diff --git a/.clang-format b/.clang-format index 395292ab2ac634..ce170c0af7179b 100644 --- a/.clang-format +++ b/.clang-format @@ -481,7 +481,6 @@ ForEachMacros: - 'genradix_for_each' - 'genradix_for_each_from' - 'genradix_for_each_reverse' - - 'guard' - 'hash_for_each' - 'hash_for_each_possible' - 'hash_for_each_possible_rcu' diff --git a/.mailmap b/.mailmap index bb8cd0c847479d..21af9983827141 100644 --- a/.mailmap +++ b/.mailmap @@ -64,6 +64,7 @@ Alex Elder Alex Elder Alex Elder Alex Elder +Alex Elder Alex Hung Alex Shi Alex Shi @@ -82,6 +83,7 @@ Amit Blay Amit Nischal Andi Kleen Andi Shyti +Andrea Cervesato Andreas Herrmann Andreas Hindborg Andrej Shadura @@ -154,6 +156,7 @@ Bart Van Assche Bart Van Assche Bartosz Golaszewski Bartosz Golaszewski +Beat M. Liechti Ben Dooks Ben Dooks Ben Gardner @@ -180,7 +183,8 @@ Boris Brezillon Boris Brezillon Boris Brezillon Boris Brezillon -Bradley Morgan +Bradley Morgan +Bradley Morgan Brendan Higgins Brendan Jackman Brian Avery @@ -356,8 +360,10 @@ Gokul Sriram Palanisamy Govindaraj Saminathan Guo Ren Guo Ren -Guodong Xu -Guodong Xu +Guodong Xu +Guodong Xu +Guodong Xu +Guodong Xu Guru Das Srinagesh Guru Das Srinagesh Guru Das Srinagesh @@ -589,6 +595,9 @@ Lorenzo Stoakes Luca Ceresoli Luca Weiss Lucas De Marchi +Luiz Capitulino +Luiz Capitulino +Luiz Capitulino Lukasz Luba Luo Jie Luo Jie @@ -658,7 +667,8 @@ Maxwell Doose Maya Erez Mayuresh Janorkar Md Sadre Alam -Miaoqing Pan +Miaoqing Pan +Miaoqing Pan Michael Buesch Michael Chan Michael Grzeschik @@ -671,6 +681,7 @@ Michel Lespinasse Michel Lespinasse Mickaël Salaün Miguel Ojeda +Mika Westerberg Mike Leach Mike Rapoport Mike Rapoport @@ -692,6 +703,7 @@ Mythri P K Nadav Amit Nadav Amit Nadia Yvette Chambers William Lee Irwin III +Naman Jain Naoya Horiguchi Naoya Horiguchi Natalie Vock @@ -810,6 +822,8 @@ Richard Genoud Richard Leitner Richard Leitner Richard Leitner +Ridong Chen +Ridong Chen Rob Clark Rob Clark Robert Foss @@ -823,11 +837,13 @@ Ronak Doshi Muchun Song Muchun Song Ross Zwisler +Ruben Wauters Rudolf Marek Rui Saraiva Sachin Mokashi Sachin P Sant Sai Prakash Ranjan +Sai Teja Aluvala Sakari Ailus Sam Protsenko Sam Protsenko @@ -1007,6 +1023,7 @@ Vlad Dogaru Vladimir Davydov Vladimir Davydov Vlastimil Babka +Wang Yibo WangYuli WangYuli Wei Wang diff --git a/CREDITS b/CREDITS index c6c7b173b06445..226a71e45edc3c 100644 --- a/CREDITS +++ b/CREDITS @@ -3939,6 +3939,12 @@ D: mandocs and mandocs_install build targets S: (Email me and ask) S: Australia +N: Lorenzo Stoakes +E: ljs@kernel.org +W: https://ljs.io +D: THP co-maintainer +S: UK + N: Henrik Storner E: storner@image.dk W: http://www.image.dk/~storner/ diff --git a/Documentation/ABI/stable/sysfs-driver-dma-idxd b/Documentation/ABI/stable/sysfs-driver-dma-idxd index 08d030159f0921..5be4e2d5775ff4 100644 --- a/Documentation/ABI/stable/sysfs-driver-dma-idxd +++ b/Documentation/ABI/stable/sysfs-driver-dma-idxd @@ -138,7 +138,7 @@ Description: The last executed device administrative command's status/error. What: /sys/bus/dsa/devices/dsa/dsacaps Date: April 5, 2026 -KernelVersion: 6.20.0 +KernelVersion: 7.0 Contact: dmaengine@vger.kernel.org Description: The DSA3 specification introduces three new capability registers: dsacap[0-2]. User components (e.g., configuration diff --git a/Documentation/ABI/stable/sysfs-nvme b/Documentation/ABI/stable/sysfs-nvme index 9291595f8102f7..1826df9161d24d 100644 --- a/Documentation/ABI/stable/sysfs-nvme +++ b/Documentation/ABI/stable/sysfs-nvme @@ -70,8 +70,7 @@ Description: fabrics controller. reconnect_delay: Shows or sets the reconnect delay in - seconds. Reading returns the delay value, or "off" if - disabled. + seconds. Reading returns the delay value. ctrl_loss_tmo: Shows or sets the controller loss timeout in seconds. Reading returns the timeout value, or "off" if diff --git a/Documentation/admin-guide/LSM/landlock.rst b/Documentation/admin-guide/LSM/landlock.rst index 946f3bf8965003..a79912e8a684c7 100644 --- a/Documentation/admin-guide/LSM/landlock.rst +++ b/Documentation/admin-guide/LSM/landlock.rst @@ -7,7 +7,7 @@ Landlock: system-wide management ================================ :Author: Mickaël Salaün -:Date: October 2026 +:Date: November 2026 Landlock can leverage the audit framework to log events. @@ -72,10 +72,13 @@ AUDIT_LANDLOCK_ACCESS :manpage:`unshare(2)`, :manpage:`clone(2)`, :manpage:`clone3(2)`, :manpage:`open_tree(2)`, or :manpage:`fsmount(2)`, or joining via :manpage:`setns(2)`); - ``namespace_type`` indicates the type (hex ``CLONE_NEW*`` bitmask), - and ``namespace_id`` identifies the target namespace (for a denied - creation, the namespace never becomes reachable so its ID is not - directly visible from user space) + ``namespace_op`` is ``create`` for construction or ``enter`` for + :manpage:`setns(2)`. These values describe semantic namespace hooks, + not exact system calls. ``namespace_type`` indicates the type (hex + ``CLONE_NEW*`` bitmask), and ``namespace_id`` identifies the namespace + object. For a denied creation, the new namespace never becomes + reachable, so its ID is not directly visible from user space. For a + denied entry, this is the exact existing target ID. **capability.*** - Capability restrictions (ABI 12+): - capability.use - Capability use was denied; @@ -86,10 +89,10 @@ AUDIT_LANDLOCK_ACCESS in a directory that lacks both ``make_reg`` and ``refer`` rights would show ``blockers=fs.make_reg,fs.refer``. - The object identification fields depend on the type of access being blocked: - ``path``, ``dev``, ``ino`` for filesystem; ``opid``, ``ocomm`` for signals; - ``namespace_type`` and ``namespace_id`` for namespace operations; - ``capability`` for capability use. + The operation and object context fields depend on the type of access being + blocked: ``path``, ``dev``, ``ino`` for filesystem; ``opid``, ``ocomm`` for + signals; ``namespace_op``, ``namespace_type``, and ``namespace_id`` for + namespace operations; ``capability`` for capability use. AUDIT_LANDLOCK_DOMAIN diff --git a/Documentation/admin-guide/kernel-parameters.txt b/Documentation/admin-guide/kernel-parameters.txt index 0b3c140babd944..dce9b8f3ae980e 100644 --- a/Documentation/admin-guide/kernel-parameters.txt +++ b/Documentation/admin-guide/kernel-parameters.txt @@ -564,6 +564,9 @@ Kernel parameters arm64.nohaft [ARM64] Unconditionally disable Hardware managed Access Flag for Table descriptors support + arm64.nols64 [ARM64] Unconditionally disable 64-byte Load/Store + instructions support + arm64.nomops [ARM64] Unconditionally disable Memory Copy and Memory Set instructions support @@ -6369,13 +6372,6 @@ Kernel parameters period to instead use normal non-expedited grace-period processing. - rcupdate.rcu_task_collapse_debug= [KNL] - Enable debugging prints that record when RCU Tasks - and RCU Tasks Trace expand to per-CPU callback - queuing and collapse back to CPU-0 queuing. - This is default-disabled due to the fact that - some workloads can make it quite noisy. - rcupdate.rcu_task_collapse_lim= [KNL] Set the maximum number of callbacks present at the beginning of a grace period that allows diff --git a/Documentation/admin-guide/mm/kho.rst b/Documentation/admin-guide/mm/kho.rst index 902d171a780afc..4281da6be5faa7 100644 --- a/Documentation/admin-guide/mm/kho.rst +++ b/Documentation/admin-guide/mm/kho.rst @@ -117,7 +117,3 @@ stabilized. kernel's state is in this file in the format of flattened device tree. This file may disappear when all consumers of it finished to interpret their metadata. - -``/sys/kernel/debug/kho/in/sub_fdts/`` - Similar to ``kho/out/sub_fdts/``, but contains sub blobs - of KHO producers passed from the old kernel. diff --git a/Documentation/arch/arm64/silicon-errata.rst b/Documentation/arch/arm64/silicon-errata.rst index dc4144ac895bf9..bffaa46c664b3a 100644 --- a/Documentation/arch/arm64/silicon-errata.rst +++ b/Documentation/arch/arm64/silicon-errata.rst @@ -209,6 +209,8 @@ stable kernels. +----------------+-----------------+-----------------+-----------------------------+ | ARM | Cortex-X3 | #4193786 | ARM64_ERRATUM_4118414 | +----------------+-----------------+-----------------+-----------------------------+ +| ARM | Cortex-X4 | #3043263 | N/A | ++----------------+-----------------+-----------------+-----------------------------+ | ARM | Cortex-X4 | #3194386 | ARM64_ERRATUM_3194386 | +----------------+-----------------+-----------------+-----------------------------+ | ARM | Cortex-X4 | #4118414 | ARM64_ERRATUM_4118414 | @@ -253,10 +255,14 @@ stable kernels. +----------------+-----------------+-----------------+-----------------------------+ | ARM | Neoverse-V2 | #4193787 | ARM64_ERRATUM_4118414 | +----------------+-----------------+-----------------+-----------------------------+ +| ARM | Neoverse-V3 | #3053180 | N/A | ++----------------+-----------------+-----------------+-----------------------------+ | ARM | Neoverse-V3 | #3312417 | ARM64_ERRATUM_3194386 | +----------------+-----------------+-----------------+-----------------------------+ | ARM | Neoverse-V3 | #4193784 | ARM64_ERRATUM_4118414 | +----------------+-----------------+-----------------+-----------------------------+ +| ARM | Neoverse-V3AE | #3053180 | N/A | ++----------------+-----------------+-----------------+-----------------------------+ | ARM | Neoverse-V3AE | #3312417 | ARM64_ERRATUM_3194386 | +----------------+-----------------+-----------------+-----------------------------+ | ARM | Neoverse-V3AE | #4193784 | ARM64_ERRATUM_4118414 | diff --git a/Documentation/block/error-injection.rst b/Documentation/block/error-injection.rst index 81f31af82e65db..3c86defddb806a 100644 --- a/Documentation/block/error-injection.rst +++ b/Documentation/block/error-injection.rst @@ -7,9 +7,9 @@ Configurable Error Injection Overview -------- -Configurable error injection allows injecting specific block layer status codes -for sector ranges of a block device. Errors can be injected unconditionally, or -with a given probability. +Configurable error injection allows injecting delays and/or specific block +layer status codes for sector ranges of a block device by adding rules. The +rules can be configured to trigger unconditionally, or with a given probability. To use configurable error injection, CONFIG_BLK_ERROR_INJECTION must be enabled. @@ -34,15 +34,36 @@ op= block layer operation this rule applies to. This uses the XYZ for each REQ_OP_XYZ operation, e.g. READ, WRITE or DISCARD. Mandatory. status= Status to return. This uses XYZ for each BLK_STS_XYZ - code, e.g. IOERR or MEDIUM. Mandatory. + code, e.g. IOERR or MEDIUM. Mandatory unless delay_us + is given. start= First block layer sector the rule applies to. Optional, defaults to 0. nr_sectors= Number of sectors this rule applies. Optional, defaults to the remainder of the device. -chance= Only return a failure with a likelihood of 1/chance. +chance= Only apply the rule with a likelihood of 1/chance. Optional, defaults to 1 (always). +delay_us= Hold the bio back for this many microseconds. Without + status the bio is then submitted to the device as + usual. With status it is failed once the delay has + expired. Bios with REQ_NOWAIT set fail with + BLK_STS_AGAIN. Optional, defaults to 0 (no delay). + Values above 600 seconds are rejected. =================== ======================================================= +Delays +------ + +A delayed bio is held above the driver, so the device never sees a slow I/O. +A delay does not reach the blk-mq timeout handler or SCSI error handling. + +A bio that matched a delay rule is not evaluated against the rules again, even +after it is split and resubmitted internally. Removing a rule does not release +bios it is already delaying. + +Holding a bio back reorders it against bios submitted later. On zoned devices +this breaks sequential write ordering and the block layer fails the +out-of-order writes, so only delay reads there. + Example ------- @@ -54,6 +75,14 @@ Return BLK_STS_MEDIUM for every write to /dev/nvme0n1: $ echo 'add,op=WRITE,start=0,status=MEDIUM' > /sys/kernel/debug/block/nvme0n1/error_injection +Delay every read of /dev/nvme0n1 by 10 milliseconds, then issue it normally: + + $ echo 'add,op=READ,delay_us=10000' > /sys/kernel/debug/block/nvme0n1/error_injection + +Fail one in 100 writes with BLK_STS_TIMEOUT, but only after 30 seconds: + + $ echo 'add,op=WRITE,status=TIMEOUT,chance=100,delay_us=30000000' > /sys/kernel/debug/block/nvme0n1/error_injection + Remove all rules for /dev/nvme0n1: $ echo 'removeall' > /sys/kernel/debug/block/nvme0n1/error_injection diff --git a/Documentation/bpf/bpf_iterators.rst b/Documentation/bpf/bpf_iterators.rst index 72435e32ffa16b..c534215f05de77 100644 --- a/Documentation/bpf/bpf_iterators.rst +++ b/Documentation/bpf/bpf_iterators.rst @@ -351,9 +351,15 @@ The following is the breakdown for each field in struct ``bpf_iter_reg``. the bpf iterator. * - feature - Specifies certain action requests in the kernel BPF iterator - infrastructure. Currently, only BPF_ITER_RESCHED is supported. This means - that the kernel function cond_resched() is called to avoid other kernel - subsystem (e.g., rcu) misbehaving. + infrastructure. + + BPF_ITER_RESCHED + the kernel function cond_resched() is called to avoid other kernel + subsystem (e.g., rcu) misbehaving + + BPF_ITER_NOSLEEP + ``seq_operations::show()`` cannot run sleepable programs + * - seq_info - Specifies the set of seq operations for the BPF iterator and helpers to initialize/free the private data for the corresponding ``seq_file``. diff --git a/Documentation/bpf/kfuncs.rst b/Documentation/bpf/kfuncs.rst index 901c3750421776..31389dd5c9f6dd 100644 --- a/Documentation/bpf/kfuncs.rst +++ b/Documentation/bpf/kfuncs.rst @@ -537,7 +537,8 @@ addresses to the BPF program, for example by reading through a pointer that the verifier does not check. Calling such a kfunc requires CAP_PERFMON, or CAP_SYS_ADMIN, in the same way that the equivalent BPF helpers are gated in bpf_base_func_proto(). A program loaded with CAP_BPF alone is rejected at load -time. +time. The flag is implied when the program gets a returned ``void *`` as a +number. 2.6 Registering the kfuncs -------------------------- diff --git a/Documentation/bpf/map_sockmap.rst b/Documentation/bpf/map_sockmap.rst index 2d630686a00baa..eb466b86df1707 100644 --- a/Documentation/bpf/map_sockmap.rst +++ b/Documentation/bpf/map_sockmap.rst @@ -33,7 +33,9 @@ of ``__SK_DROP``, ``__SK_PASS``, or ``__SK_REDIRECT``. When a socket is inserted into one of these maps, its socket callbacks are replaced and a ``struct sk_psock`` is attached to it. Additionally, this -``sk_psock`` inherits the programs that are attached to the map. +``sk_psock`` inherits the programs that are attached to the map. A TCP listener +is an exception. It gets a ``struct sk_psock``, but it keeps its callbacks and +inherits no programs. A sock object may be in multiple maps, but can only inherit a single parse or verdict program. If adding a sock object to a map would result diff --git a/Documentation/bpf/signing.rst b/Documentation/bpf/signing.rst index 27fdad3df96f1f..db48965cea642b 100644 --- a/Documentation/bpf/signing.rst +++ b/Documentation/bpf/signing.rst @@ -141,7 +141,8 @@ reuses the existing ``fd_array``: ``excl_prog_sha``) and a plain array map (``BPF_MAP_TYPE_ARRAY``); only an array map exposes its value buffer through ``map_direct_value_addr()`` as a kernel address spanning ``value_size`` bytes. A map that is not exclusive, not - frozen, or not a plain array is rejected, with a verifier log message naming + frozen, not a plain array, or that user space could map for writing + (``BPF_F_MMAPABLE``) is rejected, with a verifier log message naming the offending map. The kernel appends each map's frozen contents to the instruction buffer and verifies the PKCS#7 signature over the concatenation ``insns || metadata_0 || metadata_1 || ...`` in ``used_maps`` diff --git a/Documentation/core-api/assoc_array.rst b/Documentation/core-api/assoc_array.rst index 19d89f92bf8da8..c5ada1bff06fa2 100644 --- a/Documentation/core-api/assoc_array.rst +++ b/Documentation/core-api/assoc_array.rst @@ -123,10 +123,12 @@ This points to a number of methods, all of which need to be provided: unsigned long (*get_key_chunk)(const void *index_key, int level); - This should return a chunk of caller-supplied index key starting at the - *bit* position given by the level argument. The level argument will be a - multiple of ``ASSOC_ARRAY_KEY_CHUNK_SIZE`` and the function should return - ``ASSOC_ARRAY_KEY_CHUNK_SIZE bits``. No error is possible. + This should return the ``ASSOC_ARRAY_KEY_CHUNK_SIZE`` bits of + caller-supplied index key that contain the *bit* position given by the + level argument, starting at level rounded down to a multiple of + ``ASSOC_ARRAY_KEY_CHUNK_SIZE``. The level is often that of a node, which + is a multiple of ``ASSOC_ARRAY_LEVEL_STEP``, so the function has to do the + rounding. No error is possible. 2. Get a chunk of an object's index key:: diff --git a/Documentation/devicetree/bindings/iio/adc/aspeed,ast2600-adc.yaml b/Documentation/devicetree/bindings/iio/adc/aspeed,ast2600-adc.yaml index 249101b55cf4e7..140d7034e2196e 100644 --- a/Documentation/devicetree/bindings/iio/adc/aspeed,ast2600-adc.yaml +++ b/Documentation/devicetree/bindings/iio/adc/aspeed,ast2600-adc.yaml @@ -67,6 +67,11 @@ properties: description: Inform the driver that last channel will be used to sensor battery. + aspeed,trim-syscon: + $ref: /schemas/types.yaml#/definitions/phandle + description: + Phandle to the SCU holding the ADC's reference-voltage trimming data. + required: - compatible - reg @@ -74,6 +79,18 @@ required: - resets - "#io-channel-cells" +allOf: + - if: + properties: + compatible: + contains: + enum: + - aspeed,ast2700-adc0 + - aspeed,ast2700-adc1 + then: + required: + - aspeed,trim-syscon + additionalProperties: false examples: diff --git a/Documentation/devicetree/bindings/iio/dac/adi,ad5758.yaml b/Documentation/devicetree/bindings/iio/dac/adi,ad5758.yaml index 5121685337b5ed..a0f2649129e0f2 100644 --- a/Documentation/devicetree/bindings/iio/dac/adi,ad5758.yaml +++ b/Documentation/devicetree/bindings/iio/dac/adi,ad5758.yaml @@ -66,8 +66,8 @@ properties: - const: 0 - enum: [20000, 24000] - items: - - const: 4 - - const: 24000 + - const: 4000 + - const: 20000 - items: - const: -20000 - const: 20000 diff --git a/Documentation/devicetree/bindings/sound/airoha,an7581-pcm.yaml b/Documentation/devicetree/bindings/sound/airoha,an7581-pcm.yaml new file mode 100644 index 00000000000000..e73236453b880f --- /dev/null +++ b/Documentation/devicetree/bindings/sound/airoha,an7581-pcm.yaml @@ -0,0 +1,52 @@ +# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/sound/airoha,an7581-pcm.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Airoha PCM controller for AN7581 SoC + +maintainers: + - Christian Marangi + +properties: + compatible: + const: airoha,an7581-pcm + + reg: + maxItems: 1 + + interrupts: + maxItems: 1 + + resets: + maxItems: 1 + + reset-names: + const: pcm1 + +required: + - compatible + - reg + - interrupts + - resets + - reset-names + +additionalProperties: false + +examples: + - | + #include + #include + #include + + pcm@1fbd0000 { + compatible = "airoha,an7581-pcm"; + reg = <0x1fbd0000 0x10000>; + + interrupts = ; + resets = <&scuclk EN7581_PCM1_RST>; + reset-names = "pcm1"; + }; + +... diff --git a/Documentation/devicetree/bindings/sound/amlogic,g12a-toacodec.yaml b/Documentation/devicetree/bindings/sound/amlogic,g12a-toacodec.yaml index 23f82bb8975089..7e053aaa0f59a7 100644 --- a/Documentation/devicetree/bindings/sound/amlogic,g12a-toacodec.yaml +++ b/Documentation/devicetree/bindings/sound/amlogic,g12a-toacodec.yaml @@ -25,6 +25,7 @@ properties: - const: amlogic,g12a-toacodec - items: - enum: + - amlogic,s4-toacodec - amlogic,sm1-toacodec - const: amlogic,g12a-toacodec diff --git a/Documentation/devicetree/bindings/sound/awinic,aw8738.yaml b/Documentation/devicetree/bindings/sound/awinic,aw8738.yaml index bc6c6b17223809..5ef7b800226a37 100644 --- a/Documentation/devicetree/bindings/sound/awinic,aw8738.yaml +++ b/Documentation/devicetree/bindings/sound/awinic,aw8738.yaml @@ -14,12 +14,28 @@ description: (set using one-wire pulse control). The mode configures the speaker-guard function (primarily the power limit for the amplifier). + The Awinic AW8155 also has its mode set by one-wire pulses on its control + pin. Its modes select the amplifier class, its gain and its power limit. + allOf: - $ref: dai-common.yaml# + - if: + properties: + compatible: + contains: + const: awinic,aw8155 + then: + properties: + awinic,mode: + enum: [1, 2, 4] properties: compatible: - const: awinic,aw8738 + oneOf: + - const: awinic,aw8738 + - items: + - const: awinic,aw8155 + - const: awinic,aw8738 mode-gpios: description: diff --git a/Documentation/devicetree/bindings/sound/irondevice,ma5311.yaml b/Documentation/devicetree/bindings/sound/irondevice,ma5311.yaml new file mode 100644 index 00000000000000..d013d539e0ef53 --- /dev/null +++ b/Documentation/devicetree/bindings/sound/irondevice,ma5311.yaml @@ -0,0 +1,84 @@ +# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/sound/irondevice,ma5311.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Iron Device MA5311 Audio Codec + +maintainers: + - Hyunuk Son + +description: + The Iron Device MA5311 integrates digital speaker amplification, + analog-to-digital conversion, and audio DSP functionality. + + The device uses two I2C slave addresses. The first address + provides access to the control register bank, while the second + provides access to the ADC register bank. + + The device provides an active-low reset input and an active-low + interrupt output for fault and thermal warning notification. + +allOf: + - $ref: dai-common.yaml# + +properties: + compatible: + enum: + - irondevice,ma5311 + + reg: + items: + - description: I2C address for control registers + - description: I2C address for ADC registers + + reg-names: + items: + - const: control + - const: adc + + reset-gpios: + maxItems: 1 + description: + GPIO connected to the active-low RSTN pin. + + interrupts: + maxItems: 1 + description: + Falling-edge interrupt from the active-low INTN output. + INTN is deasserted when the fault condition clears. + + '#sound-dai-cells': + const: 1 + +required: + - compatible + - reg + - reg-names + - '#sound-dai-cells' + +unevaluatedProperties: false + +examples: + - | + #include + #include + + i2c { + #address-cells = <1>; + #size-cells = <0>; + + audio-codec@3e { + compatible = "irondevice,ma5311"; + + reg = <0x3e>, <0x3f>; + reg-names = "control", "adc"; + + reset-gpios = <&gpio 2 GPIO_ACTIVE_LOW>; + interrupt-parent = <&gpio>; + interrupts = <3 IRQ_TYPE_EDGE_FALLING>; + + #sound-dai-cells = <1>; + }; + }; diff --git a/Documentation/devicetree/bindings/sound/nvidia,tegra210-admaif.yaml b/Documentation/devicetree/bindings/sound/nvidia,tegra210-admaif.yaml index 2ce4049f94acc7..054bacf6023495 100644 --- a/Documentation/devicetree/bindings/sound/nvidia,tegra210-admaif.yaml +++ b/Documentation/devicetree/bindings/sound/nvidia,tegra210-admaif.yaml @@ -27,6 +27,7 @@ properties: - nvidia,tegra210-admaif - nvidia,tegra186-admaif - nvidia,tegra264-admaif + - nvidia,tegra268-admaif - items: - enum: - nvidia,tegra234-admaif @@ -134,6 +135,27 @@ allOf: minItems: 1 maxItems: 64 + - if: + properties: + compatible: + contains: + const: nvidia,tegra268-admaif + then: + properties: + dmas: + description: + DMA channel specifiers, equally divided for Tx and Rx. + minItems: 1 + maxItems: 10 + dma-names: + items: + pattern: "^[rt]x[1-5]$" + description: + Should be "rx1", "rx2" ... "rx5" for DMA Rx channel + Should be "tx1", "tx2" ... "tx5" for DMA Tx channel + minItems: 1 + maxItems: 10 + required: - compatible - reg diff --git a/Documentation/devicetree/bindings/sound/qcom,lpass-rx-macro.yaml b/Documentation/devicetree/bindings/sound/qcom,lpass-rx-macro.yaml index 67a4a9536d06d5..5e1940fc3e9f46 100644 --- a/Documentation/devicetree/bindings/sound/qcom,lpass-rx-macro.yaml +++ b/Documentation/devicetree/bindings/sound/qcom,lpass-rx-macro.yaml @@ -25,6 +25,7 @@ properties: - items: - enum: - qcom,eliza-lpass-rx-macro + - qcom,glymur-lpass-rx-macro - qcom,kaanapali-lpass-rx-macro - qcom,sm8650-lpass-rx-macro - qcom,sm8750-lpass-rx-macro diff --git a/Documentation/devicetree/bindings/sound/qcom,lpass-tx-macro.yaml b/Documentation/devicetree/bindings/sound/qcom,lpass-tx-macro.yaml index f9702a11ef8250..6f5648a973cd76 100644 --- a/Documentation/devicetree/bindings/sound/qcom,lpass-tx-macro.yaml +++ b/Documentation/devicetree/bindings/sound/qcom,lpass-tx-macro.yaml @@ -25,6 +25,7 @@ properties: - items: - enum: - qcom,eliza-lpass-tx-macro + - qcom,glymur-lpass-tx-macro - qcom,kaanapali-lpass-tx-macro - qcom,sm8650-lpass-tx-macro - qcom,sm8750-lpass-tx-macro diff --git a/Documentation/devicetree/bindings/sound/qcom,sm8250.yaml b/Documentation/devicetree/bindings/sound/qcom,sm8250.yaml index a890fa288a76b3..2b8ee6220d2325 100644 --- a/Documentation/devicetree/bindings/sound/qcom,sm8250.yaml +++ b/Documentation/devicetree/bindings/sound/qcom,sm8250.yaml @@ -16,6 +16,9 @@ description: properties: compatible: oneOf: + - items: + - const: arduino,monza-sndcard + - const: qcom,qcs8275-sndcard - items: - enum: - lenovo,yoga-c630-sndcard @@ -57,6 +60,9 @@ properties: - qcom,sc8280xp-sndcard - qcom,sdm660-sndcard - qcom,sdm845-sndcard + - qcom,shikra-cqm-sndcard + - qcom,shikra-cqs-sndcard + - qcom,shikra-iqs-sndcard - qcom,sm8250-sndcard - qcom,sm8450-sndcard - qcom,x1e80100-sndcard diff --git a/Documentation/devicetree/bindings/sound/ti,tas2557.yaml b/Documentation/devicetree/bindings/sound/ti,tas2557.yaml new file mode 100644 index 00000000000000..4a7f9065980a03 --- /dev/null +++ b/Documentation/devicetree/bindings/sound/ti,tas2557.yaml @@ -0,0 +1,158 @@ +# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +# Copyright (C) 2026 Gianluca Boiano +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/sound/ti,tas2557.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Texas Instruments TAS2557 Mono Smart Amplifier + +maintainers: + - Gianluca Boiano + +description: | + The TAS2557 is a mono, digital-input Class-D amplifier with an + integrated DSP for speaker protection, controlled over I2C, with + audio over I2S/TDM (ASI). The DSP runs a firmware image generated for + the speaker with the TI PurePath Console tuning tools. + + One node describes one device or a pair sharing one ASI bus, using + the reg-array convention of ti,tas2781.yaml. The device at reg index 0 + is DEV_A and the one at index 1 is DEV_B; they select the two halves + of a stereo-tuned firmware image. The firmware format defines no + other device types, so a node has at most two devices. + + Datasheet: https://www.ti.com/lit/gpn/tas2557 + +allOf: + - $ref: dai-common.yaml# + +properties: + compatible: + const: ti,tas2557 + + reg: + minItems: 1 + maxItems: 2 + description: + I2C address of each physical device sharing this node. One + entry configures a single mono TAS2557. Two entries configure a + device pair; the device at index 0 is DEV_A and the device at + index 1 is DEV_B. + + '#sound-dai-cells': + const: 0 + + reset-gpios: + minItems: 1 + maxItems: 2 + description: + GPIO connected to the active-low RESET pin of each physical + device sharing this node, one entry per reg entry. A single + entry is shared by every device in the group. + + interrupts: + minItems: 1 + maxItems: 2 + description: + Fault interrupt output (INT) of each physical device sharing + this node, one entry per reg entry. A single entry is shared + by every device in the group. + + vbat-supply: + description: Battery/boost input supply (VBAT), 2.9 V to 5.5 V. + + iovdd-supply: + description: Digital I/O supply, 1.62 V to 3.6 V. + + avdd-supply: + description: Analog supply, 1.65 V to 1.95 V. + + dvdd-supply: + description: Digital core supply, 1.65 V to 1.95 V. + + firmware-name: + maxItems: 1 + description: + Name of the DSP firmware image to load. Defaults to a name + derived from the silicon revision, which is the mono image, so a + device pair must set this property. A device pair shares one + image; each device's half of it is selected by its reg index, + not by this property. + + ti,asi-port: + $ref: /schemas/types.yaml#/definitions/uint32 + enum: [1, 2] + default: 2 + description: + Which audio serial interface (ASI1 or ASI2) of the chip is + wired to the host. Only the selected interface is configured. + +required: + - compatible + - reg + - '#sound-dai-cells' + - vbat-supply + - iovdd-supply + - avdd-supply + - dvdd-supply + +if: + properties: + reg: + minItems: 2 +then: + required: + - firmware-name + +unevaluatedProperties: false + +examples: + - | + #include + #include + + i2c { + #address-cells = <1>; + #size-cells = <0>; + + audio-codec@4c { + compatible = "ti,tas2557"; + reg = <0x4c>; + #sound-dai-cells = <0>; + reset-gpios = <&tlmm 77 GPIO_ACTIVE_LOW>; + interrupt-parent = <&tlmm>; + interrupts = <73 IRQ_TYPE_LEVEL_HIGH>; + + vbat-supply = <&vph_pwr>; + iovdd-supply = <&vreg_l6b_1p8>; + avdd-supply = <&vreg_l6b_1p8>; + dvdd-supply = <&vreg_l6b_1p8>; + }; + }; + - | + #include + #include + + i2c { + #address-cells = <1>; + #size-cells = <0>; + + audio-codec@4c { + compatible = "ti,tas2557"; + reg = <0x4c>, <0x4e>; + #sound-dai-cells = <0>; + reset-gpios = <&tlmm 77 GPIO_ACTIVE_LOW>, + <&tlmm 78 GPIO_ACTIVE_LOW>; + interrupt-parent = <&tlmm>; + interrupts = <73 IRQ_TYPE_LEVEL_HIGH>, <74 IRQ_TYPE_LEVEL_HIGH>; + + vbat-supply = <&vph_pwr>; + iovdd-supply = <&vreg_l6b_1p8>; + avdd-supply = <&vreg_l6b_1p8>; + dvdd-supply = <&vreg_l6b_1p8>; + + firmware-name = "tas2557-stereo.bin"; + }; + }; +... diff --git a/Documentation/devicetree/bindings/sound/xlnx,spdif.yaml b/Documentation/devicetree/bindings/sound/xlnx,spdif.yaml index a45d8a0755fe6e..a4abca2027d39f 100644 --- a/Documentation/devicetree/bindings/sound/xlnx,spdif.yaml +++ b/Documentation/devicetree/bindings/sound/xlnx,spdif.yaml @@ -14,6 +14,28 @@ maintainers: allOf: - $ref: dai-common.yaml# + - if: + properties: + xlnx,spdif-mode: + const: 1 + required: + - xlnx,spdif-mode + then: + properties: + clock-names: + minItems: 2 + items: + - const: aud_clk_i + - const: s_axi_aclk + - const: s_axis_aclk + else: + properties: + clock-names: + minItems: 2 + items: + - const: aud_clk_i + - const: s_axi_aclk + - const: m_axis_aclk properties: compatible: @@ -28,15 +50,15 @@ properties: - description: SPDIF audio interrupt clock-names: - items: - - const: aud_clk_i - - const: s_axi_aclk + minItems: 2 + maxItems: 3 clocks: - minItems: 1 + minItems: 2 items: - - description: input audio clock - - description: clock for the AXI data stream + - description: Audio clock input used at the SPDIF/AES3 interface + - description: AXI4-Lite clock + - description: AXI4-Stream clock xlnx,spdif-mode: $ref: /schemas/types.yaml#/definitions/uint32 @@ -49,8 +71,10 @@ properties: xlnx,aud_clk_i: $ref: /schemas/types.yaml#/definitions/uint32 + deprecated: true description: - Input audio clock frequency. It affects the sampling rate. + Frequency of the audio clock input. Superseded by the rate of the + clock named aud_clk_i. required: - compatible @@ -58,6 +82,7 @@ required: - interrupts - clock-names - clocks + - xlnx,spdif-mode additionalProperties: false @@ -66,12 +91,21 @@ examples: spdif@80010000 { compatible = "xlnx,spdif-2.0"; reg = <0x80010000 0x10000>; - clock-names = "aud_clk_i", "s_axi_aclk"; - clocks = <&misc_clk_0>, <&clk 71>; + clock-names = "aud_clk_i", "s_axi_aclk", "s_axis_aclk"; + clocks = <&misc_clk_0>, <&clk 71>, <&misc_clk_0>; interrupt-parent = <&gic>; interrupts = <0 91 4>; xlnx,spdif-mode = <1>; - xlnx,aud_clk_i = <49152913>; + }; + - | + spdif@80090000 { + compatible = "xlnx,spdif-2.0"; + reg = <0x80090000 0x10000>; + clock-names = "aud_clk_i", "s_axi_aclk", "m_axis_aclk"; + clocks = <&misc_clk_0>, <&clk 71>, <&clk 71>; + interrupt-parent = <&gic>; + interrupts = <0 90 4>; + xlnx,spdif-mode = <0>; }; ... diff --git a/Documentation/devicetree/bindings/soundwire/qcom,soundwire.yaml b/Documentation/devicetree/bindings/soundwire/qcom,soundwire.yaml index 81532cf69dd0c4..0ba3a979b68cb3 100644 --- a/Documentation/devicetree/bindings/soundwire/qcom,soundwire.yaml +++ b/Documentation/devicetree/bindings/soundwire/qcom,soundwire.yaml @@ -216,6 +216,36 @@ properties: maximum: 4 - const: 0xff + qcom,multi-master-mode: + description: + Role in v3.1.0+ multi-master mode. Both nodes set this; the + primary owns SWR_CLK, the dependent contributes DATA lanes + only. + $ref: /schemas/types.yaml#/definitions/string + enum: [ primary, dependent ] + + qcom,multi-master-peer: + description: + Peers in multi-master mode. Each entry is a + pair. Peer N's DPn slots + 1, 2, 3, ... occupy bus ports (offset+1), (offset+2), ... + $ref: /schemas/types.yaml#/definitions/phandle-array + items: + items: + - description: peer phandle + - description: bus port offset (last primary-local port) + minItems: 1 + + num-lanes: + description: + Number of DATA lanes this IP exposes locally. Required in + multi-master mode; on the primary it defines the boundary + between local bus lanes (0..num-lanes-1) and lanes contributed + by the dependent. + $ref: /schemas/types.yaml#/definitions/uint32 + minimum: 1 + maximum: 8 + label: maxItems: 1 @@ -225,21 +255,81 @@ required: - interrupts - clocks - clock-names - - '#sound-dai-cells' - '#address-cells' - '#size-cells' - - qcom,ports-offset1 - - qcom,ports-offset2 - -oneOf: - - required: - - qcom,ports-sinterval-low - - required: - - qcom,ports-sinterval allOf: - $ref: soundwire-controller.yaml# + # Single-master (no qcom,multi-master-mode): needs port config. + - if: + not: + required: + - qcom,multi-master-mode + then: + required: + - '#sound-dai-cells' + - qcom,ports-offset1 + - qcom,ports-offset2 + oneOf: + - required: + - qcom,ports-sinterval-low + - required: + - qcom,ports-sinterval + + # Multi-master primary: drives the bus, needs port config + MM props. + - if: + properties: + qcom,multi-master-mode: + const: primary + required: + - qcom,multi-master-mode + then: + properties: + compatible: + contains: + const: qcom,soundwire-v3.1.0 + required: + - '#sound-dai-cells' + - qcom,ports-offset1 + - qcom,ports-offset2 + - qcom,multi-master-peer + - num-lanes + oneOf: + - required: + - qcom,ports-sinterval-low + - required: + - qcom,ports-sinterval + + # Multi-master dependent: contributes DATA lanes only, no ports. + - if: + properties: + qcom,multi-master-mode: + const: dependent + required: + - qcom,multi-master-mode + then: + properties: + compatible: + contains: + const: qcom,soundwire-v3.1.0 + '#sound-dai-cells': false + qcom,din-ports: false + qcom,dout-ports: false + qcom,ports-word-length: false + qcom,ports-sinterval-low: false + qcom,ports-sinterval: false + qcom,ports-offset1: false + qcom,ports-offset2: false + qcom,ports-lane-control: false + qcom,ports-block-pack-mode: false + qcom,ports-hstart: false + qcom,ports-hstop: false + qcom,ports-block-group-count: false + required: + - qcom,multi-master-peer + - num-lanes + unevaluatedProperties: false examples: diff --git a/Documentation/devicetree/bindings/watchdog/arm,sp805.yaml b/Documentation/devicetree/bindings/watchdog/arm,sp805.yaml index bd7c09ed193855..690456839fccab 100644 --- a/Documentation/devicetree/bindings/watchdog/arm,sp805.yaml +++ b/Documentation/devicetree/bindings/watchdog/arm,sp805.yaml @@ -16,6 +16,7 @@ description: |+ allOf: - $ref: /schemas/watchdog/watchdog.yaml# + - $ref: /schemas/arm/primecell.yaml# # Need a custom select here or 'arm,primecell' will match on lots of nodes select: diff --git a/Documentation/driver-api/index.rst b/Documentation/driver-api/index.rst index aaf5d76ed074ed..f92448a3de0cd3 100644 --- a/Documentation/driver-api/index.rst +++ b/Documentation/driver-api/index.rst @@ -67,7 +67,6 @@ Bus-level documentation slimbus usb/index virtio/index - vme w1 xillybus diff --git a/Documentation/driver-api/soundwire/stream.rst b/Documentation/driver-api/soundwire/stream.rst index d6620129963356..58b05f2d0b0eb8 100644 --- a/Documentation/driver-api/soundwire/stream.rst +++ b/Documentation/driver-api/soundwire/stream.rst @@ -67,11 +67,11 @@ Slaves are using single port. :: | | | | | | +---------------+ - | +----------------------> | Slave | + | +------------------------+ Slave | | | Interface | | | 2 | | | | - +----------------------------> | R | + +------------------------------+ R | | (Data) | +---------------+ @@ -93,11 +93,11 @@ one or more speakers. :: | | | | | | +---------------+ - | +----------------------> | Slave | + | +------------------------+ Slave | | | Interface | | | 2 | | | | - +----------------------------> | L + R | + +------------------------------+ L + R | | (Data) | +---------------+ diff --git a/Documentation/driver-api/vme.rst b/Documentation/driver-api/vme.rst deleted file mode 100644 index 7111999abc14ce..00000000000000 --- a/Documentation/driver-api/vme.rst +++ /dev/null @@ -1,297 +0,0 @@ -VME Device Drivers -================== - -Driver registration -------------------- - -As with other subsystems within the Linux kernel, VME device drivers register -with the VME subsystem, typically called from the devices init routine. This is -achieved via a call to :c:func:`vme_register_driver`. - -A pointer to a structure of type :c:type:`struct vme_driver ` must -be provided to the registration function. Along with the maximum number of -devices your driver is able to support. - -At the minimum, the '.name', '.match' and '.probe' elements of -:c:type:`struct vme_driver ` should be correctly set. The '.name' -element is a pointer to a string holding the device driver's name. - -The '.match' function allows control over which VME devices should be registered -with the driver. The match function should return 1 if a device should be -probed and 0 otherwise. This example match function (from vme_user.c) limits -the number of devices probed to one: - -.. code-block:: c - - #define USER_BUS_MAX 1 - ... - static int vme_user_match(struct vme_dev *vdev) - { - if (vdev->id.num >= USER_BUS_MAX) - return 0; - return 1; - } - -The '.probe' element should contain a pointer to the probe routine. The -probe routine is passed a :c:type:`struct vme_dev ` pointer as an -argument. - -Here, the 'num' field refers to the sequential device ID for this specific -driver. The bridge number (or bus number) can be accessed using -dev->bridge->num. - -A function is also provided to unregister the driver from the VME core called -:c:func:`vme_unregister_driver` and should usually be called from the device -driver's exit routine. - - -Resource management -------------------- - -Once a driver has registered with the VME core the provided match routine will -be called the number of times specified during the registration. If a match -succeeds, a non-zero value should be returned. A zero return value indicates -failure. For all successful matches, the probe routine of the corresponding -driver is called. The probe routine is passed a pointer to the devices -device structure. This pointer should be saved, it will be required for -requesting VME resources. - -The driver can request ownership of one or more master windows -(:c:func:`vme_master_request`), slave windows (:c:func:`vme_slave_request`) -and/or dma channels (:c:func:`vme_dma_request`). Rather than allowing the device -driver to request a specific window or DMA channel (which may be used by a -different driver) the API allows a resource to be assigned based on the required -attributes of the driver in question. For slave windows these attributes are -split into the VME address spaces that need to be accessed in 'aspace' and VME -bus cycle types required in 'cycle'. Master windows add a further set of -attributes in 'width' specifying the required data transfer widths. These -attributes are defined as bitmasks and as such any combination of the -attributes can be requested for a single window, the core will assign a window -that meets the requirements, returning a pointer of type vme_resource that -should be used to identify the allocated resource when it is used. For DMA -controllers, the request function requires the potential direction of any -transfers to be provided in the route attributes. This is typically VME-to-MEM -and/or MEM-to-VME, though some hardware can support VME-to-VME and MEM-to-MEM -transfers as well as test pattern generation. If an unallocated window fitting -the requirements can not be found a NULL pointer will be returned. - -Functions are also provided to free window allocations once they are no longer -required. These functions (:c:func:`vme_master_free`, :c:func:`vme_slave_free` -and :c:func:`vme_dma_free`) should be passed the pointer to the resource -provided during resource allocation. - - -Master windows --------------- - -Master windows provide access from the local processor[s] out onto the VME bus. -The number of windows available and the available access modes is dependent on -the underlying chipset. A window must be configured before it can be used. - - -Master window configuration -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Once a master window has been assigned :c:func:`vme_master_set` can be used to -configure it and :c:func:`vme_master_get` to retrieve the current settings. The -address spaces, transfer widths and cycle types are the same as described -under resource management, however some of the options are mutually exclusive. -For example, only one address space may be specified. - - -Master window access -~~~~~~~~~~~~~~~~~~~~ - -The function :c:func:`vme_master_read` can be used to read from and -:c:func:`vme_master_write` used to write to configured master windows. - -In addition to simple reads and writes, :c:func:`vme_master_rmw` is provided to -do a read-modify-write transaction. Parts of a VME window can also be mapped -into user space memory using :c:func:`vme_master_mmap_prepare`. - - -Slave windows -------------- - -Slave windows provide devices on the VME bus access into mapped portions of the -local memory. The number of windows available and the access modes that can be -used is dependent on the underlying chipset. A window must be configured before -it can be used. - - -Slave window configuration -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Once a slave window has been assigned :c:func:`vme_slave_set` can be used to -configure it and :c:func:`vme_slave_get` to retrieve the current settings. - -The address spaces, transfer widths and cycle types are the same as described -under resource management, however some of the options are mutually exclusive. -For example, only one address space may be specified. - - -Slave window buffer allocation -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Functions are provided to allow the user to allocate -(:c:func:`vme_alloc_consistent`) and free (:c:func:`vme_free_consistent`) -contiguous buffers which will be accessible by the VME bridge. These functions -do not have to be used, other methods can be used to allocate a buffer, though -care must be taken to ensure that they are contiguous and accessible by the VME -bridge. - - -Slave window access -~~~~~~~~~~~~~~~~~~~ - -Slave windows map local memory onto the VME bus, the standard methods for -accessing memory should be used. - - -DMA channels ------------- - -The VME DMA transfer provides the ability to run link-list DMA transfers. The -API introduces the concept of DMA lists. Each DMA list is a link-list which can -be passed to a DMA controller. Multiple lists can be created, extended, -executed, reused and destroyed. - - -List Management -~~~~~~~~~~~~~~~ - -The function :c:func:`vme_new_dma_list` is provided to create and -:c:func:`vme_dma_list_free` to destroy DMA lists. Execution of a list will not -automatically destroy the list, thus enabling a list to be reused for repetitive -tasks. - - -List Population -~~~~~~~~~~~~~~~ - -An item can be added to a list using :c:func:`vme_dma_list_add` (the source and -destination attributes need to be created before calling this function, this is -covered under "Transfer Attributes"). - -.. note:: - - The detailed attributes of the transfers source and destination - are not checked until an entry is added to a DMA list, the request - for a DMA channel purely checks the directions in which the - controller is expected to transfer data. As a result it is - possible for this call to return an error, for example if the - source or destination is in an unsupported VME address space. - -Transfer Attributes -~~~~~~~~~~~~~~~~~~~ - -The attributes for the source and destination are handled separately from adding -an item to a list. This is due to the diverse attributes required for each type -of source and destination. There are functions to create attributes for PCI, VME -and pattern sources and destinations (where appropriate): - - - PCI source or destination: :c:func:`vme_dma_pci_attribute` - - VME source or destination: :c:func:`vme_dma_vme_attribute` - - Pattern source: :c:func:`vme_dma_pattern_attribute` - -The function :c:func:`vme_dma_free_attribute` should be used to free an -attribute. - - -List Execution -~~~~~~~~~~~~~~ - -The function :c:func:`vme_dma_list_exec` queues a list for execution and will -return once the list has been executed. - - -Interrupts ----------- - -The VME API provides functions to attach and detach callbacks to specific VME -level and status ID combinations and for the generation of VME interrupts with -specific VME level and status IDs. - - -Attaching Interrupt Handlers -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The function :c:func:`vme_irq_request` can be used to attach and -:c:func:`vme_irq_free` to free a specific VME level and status ID combination. -Any given combination can only be assigned a single callback function. A void -pointer parameter is provided, the value of which is passed to the callback -function, the use of this pointer is user undefined. The callback parameters are -as follows. Care must be taken in writing a callback function, callback -functions run in interrupt context: - -.. code-block:: c - - void callback(int level, int statid, void *priv); - - -Interrupt Generation -~~~~~~~~~~~~~~~~~~~~ - -The function :c:func:`vme_irq_generate` can be used to generate a VME interrupt -at a given VME level and VME status ID. - - -Location monitors ------------------ - -The VME API provides the following functionality to configure the location -monitor. - - -Location Monitor Management -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The function :c:func:`vme_lm_request` is provided to request the use of a block -of location monitors and :c:func:`vme_lm_free` to free them after they are no -longer required. Each block may provide a number of location monitors, -monitoring adjacent locations. The function :c:func:`vme_lm_count` can be used -to determine how many locations are provided. - - -Location Monitor Configuration -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Once a bank of location monitors has been allocated, the function -:c:func:`vme_lm_set` is provided to configure the location and mode of the -location monitor. The function :c:func:`vme_lm_get` can be used to retrieve -existing settings. - - -Location Monitor Use -~~~~~~~~~~~~~~~~~~~~ - -The function :c:func:`vme_lm_attach` enables a callback to be attached and -:c:func:`vme_lm_detach` allows on to be detached from each location monitor -location. Each location monitor can monitor a number of adjacent locations. The -callback function is declared as follows. - -.. code-block:: c - - void callback(void *data); - - -Slot Detection --------------- - -The function :c:func:`vme_slot_num` returns the slot ID of the provided bridge. - - -Bus Detection -------------- - -The function :c:func:`vme_bus_num` returns the bus ID of the provided bridge. - - -VME API -------- - -.. kernel-doc:: drivers/staging/vme_user/vme.h - :internal: - -.. kernel-doc:: drivers/staging/vme_user/vme.c - :export: diff --git a/Documentation/filesystems/ext4/allocators.rst b/Documentation/filesystems/ext4/allocators.rst index 7aa85152ace3d0..70a3930ca5480d 100644 --- a/Documentation/filesystems/ext4/allocators.rst +++ b/Documentation/filesystems/ext4/allocators.rst @@ -38,7 +38,11 @@ file's data blocks to begin I/O operations. The fourth trick is that all the inodes in a directory are placed in the same block group as the directory, when feasible. The working assumption here is that all the files in a directory might be related, therefore it -is useful to try to keep them all together. +is useful to try to keep them all together. With flex_bg, the files of a +directory are kept in the directory's flex group instead, in a block +group chosen by the directory's inode number, so that the files of +different directories in the same flex group are less likely to share +inode table blocks. The fifth trick is that the disk volume is cut up into 128MB block groups; these mini-containers are used as outlined above to try to diff --git a/Documentation/filesystems/ext4/blockgroup.rst b/Documentation/filesystems/ext4/blockgroup.rst index 7cbf0b2b778eab..d33d1c426bda1b 100644 --- a/Documentation/filesystems/ext4/blockgroup.rst +++ b/Documentation/filesystems/ext4/blockgroup.rst @@ -83,11 +83,13 @@ flex_bg is given by 2 ^ ``sb.s_log_groups_per_flex``. Meta Block Groups ~~~~~~~~~~~~~~~~~ -Without the option META_BG, for safety concerns, all block group -descriptors copies are kept in the first block group. Given the default -128MiB(2^27 bytes) block group size and 64-byte group descriptors, ext4 -can have at most 2^27/64 = 2^21 block groups. This limits the entire -filesystem size to 2^21 * 2^27 = 2^48bytes or 256TiB. +Without the option META_BG, the group descriptors for all block groups +are stored together in a single table that follows the superblock in +the first block group, with a backup copy of the whole table following +each superblock backup. Given the default 128MiB(2^27 bytes) block +group size and 64-byte group descriptors, ext4 can have at most +2^27/64 = 2^21 block groups. This limits the entire filesystem size to +2^21 * 2^27 = 2^48bytes or 256TiB. The solution to this problem is to use the metablock group feature (META_BG), which is already in ext3 for all 2.6 releases. With the @@ -104,17 +106,26 @@ to the hard limit 2^32, allowing support for a 512PiB filesystem. The change in the filesystem format replaces the current scheme where the superblock is followed by a variable-length set of block group -descriptors. Instead, the superblock and a single block group descriptor -block is placed at the beginning of the first, second, and last block -groups in a meta-block group. A meta-block group is a collection of -block groups which can be described by a single block group descriptor -block. Since the size of the block group descriptor structure is 64 -bytes, a meta-block group contains 16 block groups for filesystems with -a 1KB block size, and 64 block groups for filesystems with a 4KB -blocksize. Filesystems can either be created using this new block group -descriptor layout, or existing filesystems can be resized on-line, and -the field s_first_meta_bg in the superblock will indicate the first -block group using this new layout. +descriptors. Instead, a single block group descriptor block is placed +at the beginning of the first, second, and last block groups in a +meta-block group (immediately after the superblock, if that group has +one), regardless of the sparse_super feature. A meta-block group is a +collection of block groups which can be described by a single block +group descriptor block. Since the size of the block group descriptor +structure is 64 bytes, a meta-block group contains 16 block groups for +filesystems with a 1KB block size, and 64 block groups for filesystems +with a 4KB blocksize. Filesystems can either be created using this new +block group descriptor layout, or existing filesystems can be resized +on-line, and the field s_first_meta_bg in the superblock will indicate +the first block group using this new layout. + +Superblock backups continue to follow the ordinary sparse_super +placement rule (block group 0, 1, or a power of 3, 5, or 7) +independently of meta-block group boundaries; without sparse_super, +every block group carries one. As a result, a block group at one of the +three meta-block-group positions above will carry a superblock backup +only if its group number also satisfies that rule; otherwise it holds +only the group descriptor block. Please see an important note about ``BLOCK_UNINIT`` in the section about block and inode bitmaps. diff --git a/Documentation/filesystems/ext4/checksums.rst b/Documentation/filesystems/ext4/checksums.rst index e232749daf5f30..51a2150a1bf8dd 100644 --- a/Documentation/filesystems/ext4/checksums.rst +++ b/Documentation/filesystems/ext4/checksums.rst @@ -10,9 +10,9 @@ of October 2012 the only supported algorithm is crc32c. Some data structures did not have space to fit a full 32-bit checksum, so only the lower 16 bits are stored. Enabling the 64bit feature increases the data structure size so that full 32-bit checksums can be stored for many data -structures. However, existing 32-bit filesystems cannot be extended to -enable 64bit mode, at least not without the experimental resize2fs -patches to do so. +structures. ``resize2fs`` in ``e2fsprogs`` 1.43 or later can be used to +convert filesystems from 32-bit to 64-bit and back (using the ``-b`` +and ``-s`` options). Existing filesystems can have checksumming added by running ``tune2fs -O metadata_csum`` against the underlying device. If tune2fs diff --git a/Documentation/filesystems/ext4/directory.rst b/Documentation/filesystems/ext4/directory.rst index 9b003a4d453fe7..6d8021309ca45b 100644 --- a/Documentation/filesystems/ext4/directory.rst +++ b/Documentation/filesystems/ext4/directory.rst @@ -429,7 +429,7 @@ block (precisely the length of one dx_entry) are used to store a ``count`` entries in the dx_root/dx_node structures are adjusted as necessary to fit the dx_tail into the block. If there is no space for the dx_tail, the user is notified to run e2fsck -D to rebuild the -directory index (which will ensure that there's space for the checksum. +directory index, which will ensure that there's space for the checksum. The dx_tail structure is 8 bytes long and looks like this: .. list-table:: diff --git a/Documentation/hwmon/yogafan.rst b/Documentation/hwmon/yogafan.rst index 239c7b5761caf6..57d528cdd6f461 100644 --- a/Documentation/hwmon/yogafan.rst +++ b/Documentation/hwmon/yogafan.rst @@ -105,7 +105,8 @@ immediately to ensure the user knows the fan has stopped. 83KF | XiaoXinPro 13ARE | 0x06/0xFE | \_SB.PCI0.LPC0.EC0.FANS/FA2S | 8-bit | 100 82KU | IdeaPad 3 15ALC6 | 0x06 | \_SB.PCI0.LPC0.EC0.FAN0 | 8-bit | 100 83RU | Legion Pro 7 16 | 0x03/0x06 | \_SB.PCI0.LPC0.EC0.FANS/FA2S | 8-bit | 100 - 83KF | Yoga Pro 7 14IAH | 0x06 | \_SB.PC00.LPCB.EC0.FANS | 8-bit | 100 + 83KF | Yoga Pro 7 14IAH | 0x104 | \_SB.PC00.LPCB.EC0.FA1S (Fan1) | 8-bit | 100 + 83KF | Yoga Pro 7 14IAH | 0x137 | \_SB.PC00.LPCB.EC0.FA2S (Fan2) | 8-bit | 100 83BS | Yoga 7 16ARP8 | 0x03/0x06 | \_SB.PCI0.LPC0.EC0.FANS/FA2S | 8-bit | 100 *Legacy* | Pre-2020 Models | 0x06 | \_SB.PCI0.LPC.EC.FAN0 | 8-bit | 100 ------------------------------------------------------------------------------------------------------- diff --git a/Documentation/networking/ip-sysctl.rst b/Documentation/networking/ip-sysctl.rst index d3523c9064a22b..0c48c29fbeeb70 100644 --- a/Documentation/networking/ip-sysctl.rst +++ b/Documentation/networking/ip-sysctl.rst @@ -956,7 +956,7 @@ tcp_stdurg - BOOLEAN tcp_synack_retries - INTEGER Number of times SYNACKs for a passive TCP connection attempt will - be retransmitted. Should not be higher than 255. Default value + be retransmitted. Values above 127 are treated as 127. Default value is 5, which corresponds to 31seconds till the last retransmission with the current initial RTO of 1second. With this the final timeout for a passive TCP connection will happen after 63seconds. diff --git a/Documentation/networking/kcm.rst b/Documentation/networking/kcm.rst index 71f44d0beaa368..07778f29211c42 100644 --- a/Documentation/networking/kcm.rst +++ b/Documentation/networking/kcm.rst @@ -167,6 +167,9 @@ The kcm_attach structure contains: - fd: file descriptor for TCP socket being attached - bpf_prog_fd: file descriptor for compiled BPF program downloaded +The transport socket must be a TCP stream socket with no TCP ULP installed. +TLS cannot be enabled on a transport socket while it is attached to KCM. + Unattach transport sockets -------------------------- diff --git a/Documentation/networking/tls.rst b/Documentation/networking/tls.rst index 980c442d7161ae..e07c1a001b2177 100644 --- a/Documentation/networking/tls.rst +++ b/Documentation/networking/tls.rst @@ -215,9 +215,10 @@ To prevent attempting to decrypt incoming records using the wrong key, decryption will be paused when a KeyUpdate message is received by the kernel, until the new key has been provided using the TLS_RX socket option. Any read occurring after the KeyUpdate has been read and -before the new key is provided will fail with EKEYEXPIRED. poll() will -not report any read events from the socket until the new key is -provided. There is no pausing on the transmit side. +before the new key is provided will fail with EKEYEXPIRED. Once the +KeyUpdate has been read, poll() will not report any read events from +the socket until the new key is provided. There is no pausing on the +transmit side. Userspace should make sure that the crypto_info provided has been set properly. In particular, the kernel will not check for key/nonce diff --git a/Documentation/process/maintainer-kvm-arm64.rst b/Documentation/process/maintainer-kvm-arm64.rst new file mode 100644 index 00000000000000..ffb73cee06aef7 --- /dev/null +++ b/Documentation/process/maintainer-kvm-arm64.rst @@ -0,0 +1,181 @@ +.. SPDX-License-Identifier: GPL-2.0 + +KVM/arm64 +========= + +This document describes how KVM/arm64 (``arch/arm64/kvm/`` and the other +files listed under "KERNEL VIRTUAL MACHINE FOR ARM64 (KVM/arm64)" in +MAINTAINERS) is maintained. It supplements +Documentation/process/submitting-patches.rst. + +Overview +-------- + +The maintainers, reviewers and mailing lists for KVM/arm64 are listed in its +MAINTAINERS entry. + +Trees +~~~~~ + +The KVM/arm64 tree is:: + + git://git.kernel.org/pub/scm/linux/kernel/git/kvmarm/kvmarm.git + +This tree is used for integration only: no development happens in it, and +most patches should not be based on it (see `Base for patches`_). Its +branches are: + +``next`` + Changes queued for the next merge window. linux-next merges this branch. + +``fixes`` + Fixes for the release currently in its -rc phase. linux-next merges this + branch too. + +``master`` + Follows the -rc tags in Linus Torvalds' tree. + +Changes leave the tree as signed tags, which are pulled into the main KVM tree +(``git://git.kernel.org/pub/scm/virt/kvm/kvm.git``) and from there reach Linus +Torvalds. + +Topic branches are managed by the maintainers in their private trees, and only +the result of integrating them is pushed out. The exception is shared +branches, which are published when necessary. Where a series also touches +code maintained elsewhere, most often the arm64 architecture code, the +maintainers may set up a shared stable branch, based on an -rc tag, that both +trees merge. Say in the cover letter which parts of a series touch other +subsystems. + +Base for patches +~~~~~~~~~~~~~~~~ + +Base your patches on a tag published in Linus Torvalds' tree, preferably -rc1 +to -rc3. If you rely on something merged later, for example a fix merged in +-rc4, say why in the cover letter. Patches based on linux-next are +discouraged. + +Do not base patches on ``kvmarm/next`` either: it is rebuilt regularly, so a +commit on it is generally the wrong base. If your series conflicts with work +queued there, leave the conflict for the maintainers to see, as it is a sign +that something needs a closer look. A proposed resolution is welcome. The +exception is a series that strictly continues one that has already been +queued. + +If your series depends on something else that is not yet in mainline, such as +another series under review, say so in the cover letter and name exactly what +it applies on top of. + +Use ``git format-patch --base`` so that the base commit is recorded in the +patches. + +Submit Checklist Addendum +------------------------- + +Recipients and threading +~~~~~~~~~~~~~~~~~~~~~~~~ + +Send the whole series to all of the maintainers and reviewers listed for +KVM/arm64, not a selection of them. Post each new version as a new thread, +not as a reply to the previous version, with a cover letter for anything +longer than a single patch. + +Subject lines +~~~~~~~~~~~~~ + +Changes to KVM/arm64 use the ``KVM: arm64:`` prefix, often followed by a +sub-topic such as ``nv:`` or ``vgic:``. Selftest changes use ``KVM: arm64: +selftests:`` or ``KVM: selftests:``. +``git log --oneline`` on the files you touch shows what is in use. The text +after the prefixes starts with a capital letter, for example ``KVM: arm64: nv: +Fix life cycle of the nested_mmus array``. + +Architecture references +~~~~~~~~~~~~~~~~~~~~~~~ + +KVM/arm64 code tracks the Arm Architecture Reference Manual (the "Arm ARM", +document DDI0487) closely. Where a change depends on architected behaviour, +explain why the change is needed and cite the Arm ARM in the commit message +or in a comment. Where the rule has an identifier, such as ``R_QXXPC``, quote +that: identifiers stay the same across revisions of the document, while +section numbers do not. Otherwise give the revision along with the section, +for example ``DDI0487L.a D24.2.70``. The same applies to other architecture +documents. + +Testing +~~~~~~~ + +Say in the cover letter how the series was tested: which tests, and on which +hardware or model. The KVM selftests (``tools/testing/selftests/kvm/``) and +kvm-unit-tests are the usual test suites. Put selftest changes in patches of +their own, separate from the KVM changes and usually at the end of the series. + +KVM/arm64 can run in several modes, which are described under +``kvm-arm.mode=`` in Documentation/admin-guide/kernel-parameters.txt. Test +the modes your change can affect. + +If a patch aims to improve performance, describe exactly how you measured it, +in enough detail for others to reproduce the results. Measurements made on a +software model such as QEMU or the Arm FVP say nothing about performance on +hardware. + +New tests are encouraged, particularly for nested virtualisation, where +coverage is poor. Depending on the change, selftests may not be enough; the +maintainers may ask for testing with a VMM, for example. + +Userspace API +~~~~~~~~~~~~~ + +Document changes to the userspace API, usually in +Documentation/virt/kvm/api.rst or in the files under +Documentation/virt/kvm/devices/ and Documentation/virt/kvm/arm/. + +Fixes +~~~~~ + +Add a ``Fixes:`` tag for bug fixes. If the fix should go to stable kernels, +add ``Cc: stable@vger.kernel.org``; the maintainers may add it when applying +if the bug calls for it. + +Key Cycle Dates +--------------- + +Changes for the next merge window are queued on ``next``. New features are +usually not merged once -rc6 has been published; from then on, only fixes are +queued. This is not a hard rule, but posting a feature just before -rc6 +guarantees nothing. + +Fixes for the current release are queued on ``fixes`` and sent upstream at +intervals that depend on how severe the bugs are. There is no cut-off for +fixes, but the maintainers may defer a low-priority fix to the next merge +window. + +Review Cadence +-------------- + +Unless the maintainers ask for a new version sooner, allow at least a week +between versions of a series, and only post a new version once there has +been enough review to justify it. Posting more often delays review rather +than speeding it up. + +Pinging a series that has had no response is fine. + +Answer reviews from bots such as Sashiko as you would any other review, even +if only to say that a finding is wrong. Pre-existing problems that a bot +points out, and that are unrelated to the series, need not be fixed in its +initial posting. + +Applied patches are normally acknowledged in reply to the posting, naming the +branch (``next`` or ``fixes``) and the commits. The maintainers try not to +change the commit IDs of applied patches, but the IDs of merge commits almost +always change. + +Minor problems are often fixed up by the maintainers when applying; ask if +you are unsure whether to resend. + +Security issues +--------------- + +Bugs that let a guest attack its host, or a nested guest attack its guest +hypervisor, should be reported as described in +Documentation/process/security-bugs.rst. diff --git a/Documentation/process/maintainer-netdev.rst b/Documentation/process/maintainer-netdev.rst index f7945f30cede81..daf2bf86a357a2 100644 --- a/Documentation/process/maintainer-netdev.rst +++ b/Documentation/process/maintainer-netdev.rst @@ -328,18 +328,6 @@ the case today. Please follow the standard stable rules in :ref:`Documentation/process/stable-kernel-rules.rst `, and make sure you include appropriate Fixes tags! -Security fixes -~~~~~~~~~~~~~~ - -Do not email netdev maintainers directly if you think you discovered -a bug that might have possible security implications. -The current netdev maintainer has consistently requested that -people use the mailing lists and not reach out directly. If you aren't -OK with that, then perhaps consider mailing security@kernel.org or -reading about http://oss-security.openwall.org/wiki/mailing-lists/distros -as possible alternative mechanisms. - - Co-posting changes to user space components ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/Documentation/process/security-bugs.rst b/Documentation/process/security-bugs.rst index c7dfecc87764c0..b37d9ed94f6e7c 100644 --- a/Documentation/process/security-bugs.rst +++ b/Documentation/process/security-bugs.rst @@ -5,7 +5,59 @@ Security bugs Linux kernel developers take security very seriously. As such, we'd like to know when a security bug is found so that it can be fixed and -disclosed as quickly as possible. +disclosed as quickly as possible. If you are a maintainer and received +a report, there is a section dedicated to you below. + +What qualifies as a security bug +-------------------------------- + +It is important that most bugs are handled publicly so as to involve the widest +possible audience and find the best solution. By nature, bugs that are handled +in closed discussions between a small set of participants are less likely to +produce the best possible fix (e.g., risk of missing valid use cases, limited +testing abilities). In addition, dealing with private discussions on patches +adds much more burden to maintainers who cannot follow their usual process nor +benefit from their usual tools. For example, many subsystems have CI jobs +running on publicly posted patches and will not merge a fix before it has been +validated, and automated review tools such as Sashiko review patches posted to +the lists. Since the fix will have to be posted publicly anyway, sending it +privately first only delays it by the time needed to ask for it to be reposted +publicly, adds extra work, and loses the benefit of early reviews. + +It turns out that the majority of the bugs reported via the security team are +just regular bugs that have been improperly qualified as security bugs due to +a lack of awareness of the Linux kernel's threat model, as described in +Documentation/process/threat-model.rst, and ought to have been sent through +the normal channels described in Documentation/admin-guide/reporting-issues.rst +instead. Note that when such a bug may still have a security impact for some +users, its reproducer and any exploit must never be posted publicly; only the +fix is (see Documentation/process/threat-model.rst). + +The security list exists for urgent bugs that grant an attacker a capability +they are not supposed to have on a correctly configured production system, and +can be easily exploited, representing an imminent threat to many users. Before +reporting, consider whether the issue actually crosses a trust boundary on such +a system. + +**If you resorted to AI assistance to identify a bug, you must treat it as +public**. While you may have valid reasons to believe it is not, the security +team's experience shows that bugs discovered this way systematically surface +simultaneously across multiple researchers, often on the same day. Others are +then likely to be already working on exploiting the same bug, so keeping it +private would protect nobody, while handling it publicly lets everyone fix it +quickly without wasting time in a needless embargo. This applies even when the +bug falls within the threat model: only the fix and its description are made +public, and reporters following this procedure will never be blamed for it. In +any case, do not publicly share a reproducer, as this could cause unintended +harm; just mention that one is available and maintainers might ask for it +privately if they need it, or better, send it upfront in a separate message to +maintainers only. + +If you are unsure whether an issue qualifies, err on the side of reporting +privately: the security team would rather triage a borderline report than miss +a real vulnerability. Reporting ordinary bugs to the security list, however, +does not make them move faster and consumes triage capacity that other reports +need. Preparing your report --------------------- @@ -70,107 +122,6 @@ In addition, the following information are highly desirable: the issue appear. It is useful to share them, as they can be helpful to keep end users protected during the time it takes them to apply the fix. -What qualifies as a security bug --------------------------------- - -It is important that most bugs are handled publicly so as to involve the widest -possible audience and find the best solution. By nature, bugs that are handled -in closed discussions between a small set of participants are less likely to -produce the best possible fix (e.g., risk of missing valid use cases, limited -testing abilities). - -It turns out that the majority of the bugs reported via the security team are -just regular bugs that have been improperly qualified as security bugs due to -a lack of awareness of the Linux kernel's threat model, as described in -Documentation/process/threat-model.rst, and ought to have been sent through -the normal channels described in Documentation/admin-guide/reporting-issues.rst -instead. - -The security list exists for urgent bugs that grant an attacker a capability -they are not supposed to have on a correctly configured production system, and -can be easily exploited, representing an imminent threat to many users. Before -reporting, consider whether the issue actually crosses a trust boundary on such -a system. - -**If you resorted to AI assistance to identify a bug, you must treat it as -public**. While you may have valid reasons to believe it is not, the security -team's experience shows that bugs discovered this way systematically surface -simultaneously across multiple researchers, often on the same day. In this -case, do not publicly share a reproducer, as this could cause unintended harm; -just mention that one is available and maintainers might ask for it privately -if they need it. - -If you are unsure whether an issue qualifies, err on the side of reporting -privately: the security team would rather triage a borderline report than miss -a real vulnerability. Reporting ordinary bugs to the security list, however, -does not make them move faster and consumes triage capacity that other reports -need. - -Identifying contacts --------------------- - -The most effective way to report a security bug is to send it directly to the -affected subsystem's maintainers and Cc: the Linux kernel security team. Do -not send it to a public list at this stage, unless you have good reasons to -consider the issue as being public or trivial to discover (e.g. result of a -widely available automated vulnerability scanning tool that can be repeated by -anyone, or use of AI-based tools). - -If you're sending a report for issues affecting multiple parts in the kernel, -even if they're fairly similar issues, please send individual messages (think -that maintainers will not all work on the issues at the same time). The only -exception is when an issue concerns closely related parts maintained by the -exact same subset of maintainers, and these parts are expected to be fixed all -at once by the same commit, then it may be acceptable to report them at once. - -One difficulty for most first-time reporters is to figure the right list of -recipients to send a report to. In the Linux kernel, all official maintainers -are trusted, so the consequences of accidentally including the wrong maintainer -are essentially a bit more noise for that person, i.e. nothing dramatic. As -such, a suitable method to figure the list of maintainers (which kernel -security officers use) is to rely on the get_maintainer.pl script, tuned to -only report maintainers. This script, when passed a file name, will look for -its path in the MAINTAINERS file to figure a hierarchical list of relevant -maintainers. Calling it a first time with the finest level of filtering will -most of the time return a short list of this specific file's maintainers:: - - $ ./scripts/get_maintainer.pl --no-l --no-r --pattern-depth 1 \ - drivers/example.c - Developer One (maintainer:example driver) - Developer Two (maintainer:example driver) - -These two maintainers should then receive the message. If the command does not -return anything, it means the affected file is part of a wider subsystem, so we -should be less specific:: - - $ ./scripts/get_maintainer.pl --no-l --no-r drivers/example.c - Developer One (maintainer:example subsystem) - Developer Two (maintainer:example subsystem) - Developer Three (maintainer:example subsystem [GENERAL]) - Developer Four (maintainer:example subsystem [GENERAL]) - -Here, picking the first, most specific ones, is sufficient. When the list is -long, it is possible to produce a comma-delimited e-mail address list on a -single line suitable for use in the To: field of a mailer like this:: - - $ ./scripts/get_maintainer.pl --no-tree --no-l --no-r --no-n --m \ - --no-git-fallback --no-substatus --no-rolestats --no-multiline \ - --pattern-depth 1 drivers/example.c - dev1@example.com, dev2@example.org - -or this for the wider list:: - - $ ./scripts/get_maintainer.pl --no-tree --no-l --no-r --no-n --m \ - --no-git-fallback --no-substatus --no-rolestats --no-multiline \ - drivers/example.c - dev1@example.com, dev2@example.org, dev3@example.com, dev4@example.org - -If at this point you're still facing difficulties spotting the right -maintainers, **and only in this case**, it's possible to send your report to -the Linux kernel security team only. Your message will be triaged, and you -will receive instructions about whom to contact, if needed. Your message may -equally be forwarded as-is to the relevant maintainers. - Responsible use of AI to find bugs ---------------------------------- @@ -207,8 +158,8 @@ handle: Please always ensure your tool provides one and **test it thoroughly**. If the reproducer does not work, or if the tool cannot produce one, the validity of the report should be seriously questioned. Note that since the - report will be posted to a public list, the reproducer should only be - shared upon maintainers' request. + report will be posted to a public list, the reproducer must only be + shared privately with the maintainers. * **Propose a Fix**: Many AI tools are actually better at writing code than evaluating it. Please ask your tool to propose a fix and **test it** before @@ -224,10 +175,10 @@ ignored. Use common sense when evaluating the report. If the affected file has not been touched for more than one year and is maintained by a single individual, it is likely that usage has declined and exposed users are virtually non-existent -(e.g., drivers for very old hardware, obsolete filesystems). In such cases, -there is no need to consume a maintainer's time with an unimportant report. If -the issue is clearly trivial and publicly discoverable, you should report it -directly to the public mailing lists. +(e.g., drivers for very old hardware, obsolete filesystems). In such cases, as +well as when the issue is clearly trivial and publicly discoverable, there is +no need to consume a maintainer's time with a private security report: just +send the fix publicly like any regular bug fix, without the reproducer. At the very least, when using an AI assistant to find and report bugs, make the assistant read this file and threat-model.rst before proceeding, and have it @@ -239,7 +190,7 @@ identify the maintainers with get_maintainer.pl. On top of that procedure, the AI assistant **MUST**: 1. Prepare a plain-text report explaining the problem. It must contain the - four items listed at the top of this file as absolutely necessary: the + four items listed above as absolutely necessary: the affected version or commit ID noted while following the procedure above, the description of the problem, the reproducer or its status, and the triggering conditions. @@ -251,44 +202,139 @@ On top of that procedure, the AI assistant **MUST**: A more detailed process is covered at https://github.com/masoncl/kres.git. -Sending the report ------------------- +Identifying contacts +-------------------- -Reports are to be sent over e-mail exclusively. Please use a working e-mail -address, preferably the same that you want to appear in ``Reported-by`` tags -if any. If unsure, send your report to yourself first. +The most effective way to report a security bug is to send it directly to the +affected subsystem's maintainers, and to Cc: the Linux kernel security team +when needed (see below). Do not send it to a public list at this stage, +unless you have good reasons to consider the issue as being public or trivial +to discover (e.g. result of a widely available automated vulnerability +scanning tool that can be repeated by anyone, or use of AI-based tools). Even +in this case, never post a reproducer or an exploit to a public list; only +maintainers need it, and publishing it could put some users in trouble. -The security team and maintainers almost always require additional -information beyond what was initially provided in a report and rely on -active and efficient collaboration with the reporter to perform further -testing (e.g., verifying versions, configuration options, mitigations, or -patches). Before contacting the security team, the reporter must ensure -they are available to explain their findings, engage in discussions, and -run additional tests. Reports where the reporter does not respond promptly -or cannot effectively discuss their findings may be abandoned if the -communication does not quickly improve. +Finding the maintainers +~~~~~~~~~~~~~~~~~~~~~~~ + +One difficulty for most first-time reporters is to figure the right list of +recipients to send a report to. In the Linux kernel, all official maintainers +are trusted, so the consequences of accidentally including the wrong maintainer +are essentially a bit more noise for that person, i.e. nothing dramatic. As +such, a suitable method to figure the list of maintainers (which kernel +security officers use) is to rely on the get_maintainer.pl script, tuned to +only report maintainers. This script, when passed a file name, will look for +its path in the MAINTAINERS file to figure a hierarchical list of relevant +maintainers. Calling it a first time with the finest level of filtering will +most of the time return a short list of this specific file's maintainers:: + + $ ./scripts/get_maintainer.pl --no-l --no-r --pattern-depth 1 \ + drivers/example.c + Developer One (maintainer:example driver) + Developer Two (maintainer:example driver) + +These two maintainers should then receive the message. If the command does not +return anything, it means the affected file is part of a wider subsystem, so we +should be less specific:: + + $ ./scripts/get_maintainer.pl --no-l --no-r drivers/example.c + Developer One (maintainer:example subsystem) + Developer Two (maintainer:example subsystem) + Developer Three (maintainer:example subsystem [GENERAL]) + Developer Four (maintainer:example subsystem [GENERAL]) + +Here, picking the first, most specific ones, is sufficient. When the list is +long, it is possible to produce a comma-delimited e-mail address list on a +single line suitable for use in the To: field of a mailer like this:: + + $ ./scripts/get_maintainer.pl --no-tree --no-l --no-r --no-n --m \ + --no-git-fallback --no-substatus --no-rolestats --no-multiline \ + --pattern-depth 1 drivers/example.c + dev1@example.com, dev2@example.org + +or this for the wider list:: + + $ ./scripts/get_maintainer.pl --no-tree --no-l --no-r --no-n --m \ + --no-git-fallback --no-substatus --no-rolestats --no-multiline \ + drivers/example.c + dev1@example.com, dev2@example.org, dev3@example.com, dev4@example.org + +If at this point you're still facing difficulties spotting the right +maintainers, **and only in this case**, it's possible to send your report to +the Linux kernel security team only. Your message will be triaged, and you +will receive instructions about whom to contact, if needed. Your message may +equally be forwarded as-is to the relevant maintainers. + +Copying the security team +~~~~~~~~~~~~~~~~~~~~~~~~~ + +The report must be sent to maintainers. You must also Cc: the Linux kernel +security team in any of the following cases: + + * it is your first report: many first reports are incomplete, too long, too + strong, difficult to handle, and put a lot of pressure on maintainers. The + security team will help with the process and with the qualification of the + issue. Note that this rule also applies if you were asked to fix or adjust + a previous submission; + + * there are two or fewer maintainers among the recipients: the security + team will ensure the message is delivered to the proper people, and + will be able to assist small maintainer teams with processes they may + not be familiar with; + + * the maintainers could not be clearly identified (see above); + + * the impact of the issue is uncertain and needs to be qualified. In this + case, your must clearly state upfront that you are seeking help to qualify + this impact, and you will need to share any information you have; + + * you are seeking specific help, such as when resending a message which got + no response within a week (see "After sending the report"). + +Otherwise, when a report of clear impact is sent to a larger team of clearly +identified maintainers, it is not necessary to Cc: the security list. Never +Cc: the security list on a message sent to a public list. -The report must be sent to maintainers. If there are two or fewer -recipients in your message, you must also always Cc: the Linux kernel -security team who will ensure the message is delivered to the proper -people, and will be able to assist small maintainer teams with processes -they may not be familiar with. For larger teams, Cc: the Linux kernel -security team for your first few reports or when seeking specific help, -such as when resending a message which got no response within a week. -Once you have become comfortable with the process for a few reports, it is -no longer necessary to Cc: the security list when sending to large teams. The Linux kernel security team can be contacted by email at . This is a private list of security officers who will help verify the bug report and assist developers working on a fix. It is possible that the security team will bring in extra help from area maintainers to understand and fix the security vulnerability. +Sending the report +------------------ + +Reports are to be sent over e-mail exclusively. Please use a working e-mail +address, preferably the same that you want to appear in ``Reported-by`` tags +if any. If unsure, send your report to yourself first. + +If you're sending a report for issues affecting multiple parts in the kernel, +even if they're fairly similar issues, please send individual messages (think +that maintainers will not all work on the issues at the same time). The only +exception is when an issue concerns closely related parts maintained by the +exact same subset of maintainers, and these parts are expected to be fixed all +at once by the same commit, then it may be acceptable to report them at once. + +If this is your first report, send only one, and wait for confirmation that it +is in the expected form before sending the other ones as individual messages. +The vast majority of first reports need to be adjusted, and otherwise the same +mistakes are repeated in all of them, putting needless pressure on the +maintainers and on the security team. Violating this rule is a clear +indication that the reporter did not read this document, and such reporters +should be prepared not to receive any response at all, as maintainers and the +security team have better things to do than to repeat what is written here. + Please send **plain text** emails without attachments where possible. It is much harder to have a context-quoted discussion about a complex -issue if all the details are hidden away in attachments. Think of it like a +issue if all the details are hidden away in attachments. Archives (zip, tar, +etc.), binary files and documents (PDF, etc.) are never acceptable: when a +reproducer is too large to be placed in the message, attach its source files +as plain text, and provide scripts that generate the required files (e.g. file +system images) instead of the files themselves. Think of it like a :doc:`regular patch submission <../process/submitting-patches>` -(even if you don't have a patch yet): describe the problem and impact, list -reproduction steps, and follow it with a proposed fix, all in plain text. +(even if you don't have a patch yet): describe the problem and impact, and +list reproduction steps, all in plain text, then provide a proposed fix as +described below. Markdown, HTML and RST formatted reports are particularly frowned upon since they're quite hard to read for humans and encourage to use dedicated viewers, sometimes online, which by definition is not acceptable for a confidential @@ -296,6 +342,99 @@ security report. Note that some mailers tend to mangle formatting of plain text by default, please consult Documentation/process/email-clients.rst for more info. +Sending a fix +~~~~~~~~~~~~~ + +Most fixes sent along with reports cannot be applied as-is because they were +damaged by the mailer or lacking a commit message, forcing maintainers to ask +for a resend. A fix must be applicable using ``git am``, which is most easily +achieved by letting git produce and send the messages (see +Documentation/process/submitting-patches.rst). + +When the fix is meant to only be sent privately, the preferred method is to +send the report as a cover letter of a series, followed by the fix:: + + $ git format-patch --cover-letter -1 + (edit 0000-cover-letter.patch and replace the subject and text with the + report's subject and text) + $ git send-email --suppress-cc=all --to= 000*.patch + +The recipients are those determined above (add ``--cc=`` for the security team +when needed). The ``--suppress-cc=all`` option is important: without it, +``git send-email`` also sends the messages to addresses found in the patch's +tags (e.g. ``Cc: stable@vger.kernel.org``), which would leak the report to a +public list. + +If the report was already sent, the fix may be sent as a reply to it, to the +same recipients, for example using ``git send-email --suppress-cc=all +--in-reply-to=``. As a last resort, when none of these +methods is possible, the file produced by ``git format-patch`` may be attached +as-is to the report, but be aware that some maintainers will not look at +attachments. However, never attach more than one patch per message without +being explicitly invited to so, as this would significantly complicate reviews. + +When the fix is meant to be public (e.g. for bugs found using AI-based tools, +see above), send it using ``git send-email`` to the maintainers and lists +reported by get_maintainer.pl (i.e. without the ``--no-l`` option), with a +commit message that does not detail how to exploit the bug. Then send the +report and the reproducer privately to the maintainers (and to the security +team when needed), mentioning the patch's Message-ID or its link on +https://lore.kernel.org/ so that they can be matched. The report may also be +sent as a reply to the public message, after carefully removing all public +addresses from the To: and Cc: fields. + +After sending the report +------------------------ + +The security team and maintainers almost always require additional +information beyond what was initially provided in a report and rely on +active and efficient collaboration with the reporter to perform further +testing (e.g., verifying versions, configuration options, mitigations, or +patches). Before contacting the security team, the reporter must ensure +they are available to explain their findings, engage in discussions, and +run additional tests. Reports where the reporter does not respond promptly +or cannot effectively discuss their findings may be abandoned if the +communication does not quickly improve. + +In practice, a report for which questions or requests from the security team +or the maintainers remain unanswered for 7 days will most likely be dropped. +This matches the maximum embargo duration described below, which is how long +the security team considers it reasonable to keep an issue private. Given the +number of reports handled in parallel, the same bug may also end up being fixed +later after being reported by someone else, in which case credit can no longer +be guaranteed. + +Messages sometimes get lost, especially those containing attachments or HTML. +Since the report is private, you have no other way to know whether it was +delivered than to ask. However, some subsystems have a long report queue, some +maintainers are overloaded or only work in their spare time, so please wait for +a week without any response before resending your report with the security team +in Cc: (see above). In this case, be clear about the fact that it is a resend, +and if possible, provide a reference to the original message. Better double +check that the message is sent in plain text, and drop any attachment when +resending, to increase the chances of successful delivery. In any case, please +do not ask for proper receipt before this delay. This will not make your report +be processed faster, will add extra load on maintainers and all you risk is +your future messages being ignored. + +For maintainers receiving a report +---------------------------------- + +If you maintain some code in the kernel and received a security report, don't +panic, you're not alone! The wording of AI-generated reports these days tends +to sound scary, but just stick to technical facts and proceed like you would +with any other bug report. Feel free to share the report with other maintainers +who you think can help you, telling them upfront that the report is private. +Many other reports are being handled by other maintainers at any instant, do +not start to worry that the security of the whole kernel suddenly depends on +your ability to provide a quick fix. Do not let reporters dictate conditions +that are not compatible with what this document describes. If you have any +question or doubt, be it about the validity of the report, its impact, the +process to follow, difficult interactions with a reporter, or even if you've +mistakenly leaked part of the report to a public list (yes, this happens), just +ask the security team for help, for example by replying to the report with the +security team in Cc:, or by forwarding it to them if you're seeking advice. + Disclosure and embargoed information ------------------------------------ diff --git a/Documentation/process/submitting-patches.rst b/Documentation/process/submitting-patches.rst index f271d7413f72cf..fbd549fc6a5d67 100644 --- a/Documentation/process/submitting-patches.rst +++ b/Documentation/process/submitting-patches.rst @@ -239,9 +239,12 @@ patches as arguments to scripts/get_maintainer.pl). If you cannot find a maintainer for the subsystem you are working on, Andrew Morton (akpm@linux-foundation.org) serves as a maintainer of last resort. -linux-kernel@vger.kernel.org should be used by default for all patches, but the -volume on that list has caused a number of developers to tune it out. Please -do not spam unrelated lists and unrelated people, though. +You should also normally choose at least one mailing list to receive a copy of +your patch set. Look in the MAINTAINERS file for a subsystem-specific list; +your patch will probably get more attention there. +linux-kernel@vger.kernel.org functions as a list of last resort for patches +that do not have a subsystem-specific list. Please do not spam unrelated lists +and unrelated people, though. Many kernel-related lists are hosted at kernel.org; you can find a list of them at https://subspace.kernel.org. There are kernel-related lists @@ -253,11 +256,11 @@ He gets a lot of e-mail, and, at this point, very few patches go through Linus directly, so typically you should do your best to -avoid- sending him e-mail. -If you have a patch that fixes an exploitable security bug, send that patch -to security@kernel.org. For severe bugs, a short embargo may be considered -to allow distributors to get the patch out to users; in such cases, -obviously, the patch should not be sent to any public lists. See also -Documentation/process/security-bugs.rst. +If you have a patch that fixes a bug with possible security implications, you +need to read Documentation/process/security-bugs.rst first: it explains which +bugs need to be handled privately, and whom to send them to. Most such fixes +are posted publicly like any other fix, but their reproducers and exploits must +never be posted publicly. Patches that fix a severe bug in a released kernel should be directed toward the stable maintainers by putting a line like this:: diff --git a/Documentation/process/threat-model.rst b/Documentation/process/threat-model.rst index 04e5df6a6f78b8..a55e7c1c119680 100644 --- a/Documentation/process/threat-model.rst +++ b/Documentation/process/threat-model.rst @@ -105,7 +105,21 @@ In the Linux kernel's threat model, the following classes of problems are **NOT** considered Linux Kernel vulnerabilities. However, when it is believed that the kernel could do better, they should be reported, so that they can be reviewed and fixed where reasonably possible, but they will be handled as any -regular bug: +regular bug. + +Some of these bugs may still have a security impact for a few users, for +example when their exploitation requires a dedicated network link, a crafted +device, or a crafted file system image that only root may mount. For the vast +majority of users the impact is null, and such isolated bugs do not represent a +target worth writing an exploit for, which is why they are handled publicly +(a CVE may still be assigned later by the :doc:`CVE team `). However, +publishing a reproducer or an exploit could put the few exposed users at risk. +For such bugs, the fix is sent publicly like any regular fix, with a commit +message that does not detail how to exploit the bug, while the reproducer and +any exploit are only shared privately with the maintainers and are never posted +to public lists. + +The following classes of problems are not considered vulnerabilities: * **Configuration**: @@ -220,7 +234,12 @@ regular bug: image: mounting a block device is a privileged operation (see above), and the administrator is responsible for the media they mount. This includes issues that are resolved, mitigated, or detected by running a filesystem - consistency check (fsck) on the image prior to mounting. + consistency check (fsck) on the image prior to mounting. Automatic + mounting of unchecked file systems (e.g. removable media mounted by a + desktop environment) does not change this: an automounter is expected to + check a file system before mounting it, otherwise it is at fault, and if + the check does not detect the issue, the file system checker is at fault. + In such cases, fixes should be directed to these tools. * bugs whose reproduction requires hardware modification or emulation, including fake USB devices that pretend to be another one, or devices diff --git a/Documentation/security/landlock.rst b/Documentation/security/landlock.rst index d81f1c2cd23683..98c2e7139e8d48 100644 --- a/Documentation/security/landlock.rst +++ b/Documentation/security/landlock.rst @@ -8,7 +8,7 @@ Landlock LSM: kernel documentation ================================== :Author: Mickaël Salaün -:Date: October 2026 +:Date: November 2026 Landlock's goal is to create scoped access-control (i.e. sandboxing). To harden a whole system, this feature should be available to any process, @@ -359,9 +359,9 @@ framework in ``log.c``, compiled under ``CONFIG_SECURITY_LANDLOCK_LOG`` (automatically selected by ``CONFIG_AUDIT`` or ``CONFIG_TRACEPOINTS``). Audit records respect audit configuration, the domain's Landlock log -flags, and ``LANDLOCK_LOG_DISABLED``. Tracepoints fire unconditionally, -independent of these settings. The denial counter (``num_denials``) is -always incremented regardless of logging configuration. +flags, and ``LANDLOCK_LOG_DISABLED``. Tracepoints fire independently of +these settings. The denial counter (``num_denials``) is +incremented regardless of logging configuration. Each denial tracepoint carries a ``logged`` field reporting the audit-logging verdict: whether the denial would be written to the audit diff --git a/Documentation/sound/soc/dpcm.rst b/Documentation/sound/soc/dpcm.rst index 7b6aeab3c207a9..3b145e8ba15c8b 100644 --- a/Documentation/sound/soc/dpcm.rst +++ b/Documentation/sound/soc/dpcm.rst @@ -370,6 +370,7 @@ The machine driver sets some additional parameters to the DAI link i.e. .num_c2c_params = 1, } < ... more DAI links here ... > + }; These parameters are used to configure the DAI hw_params() when DAPM detects a valid path and then calls the PCM operations to start the link. DAPM will also diff --git a/Documentation/trace/boottime-trace.rst b/Documentation/trace/boottime-trace.rst index 2c3c1fedb92cc9..68fd6152cd0fdf 100644 --- a/Documentation/trace/boottime-trace.rst +++ b/Documentation/trace/boottime-trace.rst @@ -36,20 +36,20 @@ these options are passed as a part of kernel legacy command line. kernel.tp_printk Output trace-event data on printk buffer too. -kernel.dump_on_oops [= MODE] +kernel.ftrace_dump_on_oops [= MODE] Dump ftrace on Oops. If MODE = 1 or omitted, dump trace buffer on all CPUs. If MODE = 2, dump a buffer on a CPU which kicks Oops. kernel.traceoff_on_warning Stop tracing if WARN_ON() occurs. -kernel.fgraph_max_depth = MAX_DEPTH +kernel.ftrace_graph_max_depth = MAX_DEPTH Set MAX_DEPTH to maximum depth of fgraph tracer. -kernel.fgraph_filters = FILTER[, FILTER2...] +kernel.ftrace_graph_filter = FILTER[, FILTER2...] Add fgraph tracing function filters. -kernel.fgraph_notraces = FILTER[, FILTER2...] +kernel.ftrace_graph_notrace = FILTER[, FILTER2...] Add fgraph non-tracing function filters. diff --git a/Documentation/trace/events-landlock.rst b/Documentation/trace/events-landlock.rst index dc5f05a17c2ccd..0647a87677a132 100644 --- a/Documentation/trace/events-landlock.rst +++ b/Documentation/trace/events-landlock.rst @@ -6,7 +6,7 @@ Landlock Trace Events ===================== :Author: Mickaël Salaün -:Date: October 2026 +:Date: November 2026 Landlock emits trace events for sandbox lifecycle operations and access denials. These events can be consumed by ftrace (for human-readable @@ -186,13 +186,19 @@ known allowed and quiet member masks. Capability masks and the raw therefore appears as zero while still advancing the ruleset version, and adding a member already present still emits an event. -``landlock_deny_permission_namespace`` reports the denied raw -``CLONE_NEW*`` value. ``namespace_id`` is the exact target namespace ID. For -a denied namespace creation, the namespace never becomes reachable so its ID -is not directly visible from user space. +``landlock_deny_permission_namespace`` reports ``namespace_op`` as ``create`` +for namespace construction, for example through :manpage:`clone(2)`, +:manpage:`clone3(2)`, :manpage:`unshare(2)`, :manpage:`open_tree(2)`, or +:manpage:`fsmount(2)`, and ``enter`` for :manpage:`setns(2)`. These values +describe the semantic namespace hook, not the exact system call. +``namespace_type`` is the denied raw ``CLONE_NEW*`` value. For a denied +creation, ``namespace_id`` is allocated for the new namespace, which never +becomes reachable, so its ID is not directly visible from user space. For a +denied entry, ``namespace_id`` is the exact existing target ID. + ``landlock_deny_permission_capability`` reports the denied ``CAP_*`` number. -Like every denial event, both include the denying domain, ``same_exec``, and -``logged``. +Like every denial event, the namespace and capability events include the +denying domain, ``same_exec``, and ``logged``. Per-member quiet masks suppress audit submission but never these trace events, which report ``logged=0``. @@ -303,9 +309,9 @@ event prototypes in `Event reference`_ document their argument layouts. The arguments include both standard kernel objects and Landlock-internal objects: -- Standard kernel objects (``struct task_struct``, ``struct sock``, - ``struct path``, ``struct dentry``) can be used with existing BPF - helpers. +- Standard kernel objects (for example ``struct task_struct``, ``struct cred``, + ``struct user_namespace``, ``struct sock``, ``struct path``, and + ``struct dentry``) can be used with existing BPF helpers. - Landlock-internal objects (``struct landlock_domain``, ``struct landlock_ruleset``, ``struct landlock_rule``, ``struct landlock_hierarchy``) can be read via ``BPF_CORE_READ``. diff --git a/Documentation/userspace-api/landlock.rst b/Documentation/userspace-api/landlock.rst index 3d45b956b6407c..7cc5fde482623e 100644 --- a/Documentation/userspace-api/landlock.rst +++ b/Documentation/userspace-api/landlock.rst @@ -8,7 +8,7 @@ Landlock: unprivileged access control ===================================== :Author: Mickaël Salaün -:Date: October 2026 +:Date: November 2026 The goal of Landlock is to enable restriction of ambient rights (e.g. global filesystem or network access) for a set of processes. Because Landlock @@ -532,7 +532,7 @@ acquisition via :manpage:`open_tree(2)` / :manpage:`fsmount(2)`. Namespaces the process is already a member of when the domain is enforced are implicitly allowed (the process could not continue running otherwise); rules describe which new namespace types the process may acquire. -``LANDLOCK_PERMISSION_CAPABILITY_USE`` gates every exercise of a capability +``LANDLOCK_PERMISSION_CAPABILITY_USE`` gates the exercise of capabilities after the domain is enforced, regardless of how the capability was obtained (inherited credentials, ``CLONE_NEWUSER`` grant, ``setuid``/file-cap-bearing :manpage:`execve(2)`, etc.). Configuring @@ -641,9 +641,9 @@ after a domain is enforced through user namespace entry or :manpage:`capset(2)`; privileged sandboxes that did not set ``PR_SET_NO_NEW_PRIVS`` may also gain capabilities through :manpage:`execve(2)` of binaries with file capabilities. In all cases, :manpage:`capget(2)` will report the credential's capability sets, -but any denied capability will fail with ``EPERM`` when exercised. Do not rely +but any denied capability will fail when exercised. Do not rely on :manpage:`capget(2)` to determine whether the policy permits a given -capability; only the actual operation will return ``EPERM`` upon denial. +capability. Truncating files ---------------- @@ -780,6 +780,9 @@ in the running kernel. .. kernel-doc:: security/landlock/errata/abi-1.h :doc: erratum_4 +.. kernel-doc:: security/landlock/errata/abi-4.h + :doc: erratum_5 + How to check for errata ~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/MAINTAINERS b/MAINTAINERS index d37ed235d5141a..e7e3c31cd0cfa6 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -796,6 +796,13 @@ F: Documentation/devicetree/bindings/sound/airoha,an7581-afe.yaml F: Documentation/devicetree/bindings/sound/airoha,an7581-wm8960.yaml F: sound/soc/mediatek/an7581/* +AIROHA PCM CONTROLLER DRIVER +M: Christian Marangi +L: linux-sound@vger.kernel.org +S: Maintained +F: Documentation/devicetree/bindings/sound/airoha,an7581-pcm.yaml +F: sound/soc/airoha/* + AIROHA SPI SNFI DRIVER M: Lorenzo Bianconi M: Ray Liu @@ -1049,7 +1056,6 @@ R: Gal Pressman R: Yossi Leybovich L: linux-rdma@vger.kernel.org S: Supported -Q: https://patchwork.kernel.org/project/linux-rdma/list/ F: drivers/infiniband/hw/efa/ F: include/uapi/rdma/efa-abi.h @@ -5328,8 +5334,8 @@ F: drivers/iommu/generic_pt/fmt/*bcm2712* BROADCOM BCM281XX/BCM11XXX/BCM216XX ARM ARCHITECTURE M: Florian Fainelli -M: Ray Jui -M: Scott Branden +M: Ray Jui +M: Scott Branden R: Broadcom internal kernel review list S: Maintained T: git https://github.com/broadcom/mach-bcm @@ -5626,8 +5632,8 @@ F: drivers/net/mdio/mdio-bcm-unimac.c F: include/linux/platform_data/mdio-bcm-unimac.h BROADCOM IPROC ARM ARCHITECTURE -M: Ray Jui -M: Scott Branden +M: Ray Jui +M: Scott Branden R: Broadcom internal kernel review list L: linux-arm-kernel@lists.infradead.org (moderated for non-subscribers) S: Maintained @@ -5664,7 +5670,7 @@ F: drivers/net/ethernet/broadcom/bgmac* F: drivers/net/ethernet/broadcom/unimac.h BROADCOM KONA GPIO DRIVER -M: Ray Jui +M: Ray Jui R: Broadcom internal kernel review list S: Supported F: Documentation/devicetree/bindings/gpio/brcm,kona-gpio.yaml @@ -5992,6 +5998,7 @@ T: git git://git.kernel.org/pub/scm/linux/kernel/git/mkl/linux-can.git T: git git://git.kernel.org/pub/scm/linux/kernel/git/mkl/linux-can-next.git F: Documentation/devicetree/bindings/net/can/ F: Documentation/devicetree/bindings/phy/ti,tcan104x-can.yaml +F: Documentation/networking/device_drivers/can/ F: drivers/net/can/ F: drivers/phy/phy-can-transceiver.c F: include/linux/can/bittiming.h @@ -7585,10 +7592,9 @@ F: drivers/dma/dw-edma/ F: include/linux/dma/edma.h DESIGNWARE USB2 DRD IP DRIVER -M: Minas Harutyunyan +M: Thinh Nguyen L: linux-usb@vger.kernel.org S: Maintained -T: git git://git.kernel.org/pub/scm/linux/kernel/git/balbi/usb.git F: drivers/usb/dwc2/ DESIGNWARE USB3 DRD IP DRIVER @@ -8333,7 +8339,7 @@ F: Documentation/devicetree/bindings/display/panel/panel-edp.yaml F: drivers/gpu/drm/panel/panel-edp.c DRM DRIVER FOR GENERIC USB DISPLAY -M: Ruben Wauters +M: Ruben Wauters S: Maintained W: https://github.com/notro/gud/wiki T: git https://gitlab.freedesktop.org/drm/misc/kernel.git @@ -8885,20 +8891,17 @@ F: Documentation/devicetree/bindings/gpu/ F: Documentation/gpu/ F: drivers/gpu/drm/ F: drivers/gpu/vga/ -F: include/drm/drm +F: include/drm/drm*.h F: include/linux/vga* F: include/uapi/drm/ X: drivers/gpu/drm/amd/ -X: drivers/gpu/drm/armada/ X: drivers/gpu/drm/etnaviv/ X: drivers/gpu/drm/exynos/ X: drivers/gpu/drm/i915/ -X: drivers/gpu/drm/kmb/ X: drivers/gpu/drm/mediatek/ X: drivers/gpu/drm/msm/ X: drivers/gpu/drm/nova/ X: drivers/gpu/drm/radeon/ -X: drivers/gpu/drm/tegra/ X: drivers/gpu/drm/tyr/ X: drivers/gpu/drm/xe/ @@ -8949,11 +8952,10 @@ F: Documentation/devicetree/bindings/display/atmel/ F: drivers/gpu/drm/atmel-hlcdc/ DRM DRIVERS FOR BRIDGE CHIPS -M: Andrzej Hajda M: Neil Armstrong +M: Dmitry Baryshkov M: Robert Foss R: Laurent Pinchart -R: Jonas Karlman R: Jernej Skrabec R: Luca Ceresoli S: Maintained @@ -9081,7 +9083,6 @@ M: Mikko Perttunen L: dri-devel@lists.freedesktop.org L: linux-tegra@vger.kernel.org S: Supported -T: git https://gitlab.freedesktop.org/drm/tegra.git F: Documentation/devicetree/bindings/display/tegra/nvidia,tegra20-host1x.yaml F: Documentation/devicetree/bindings/gpu/host1x/ F: drivers/gpu/drm/tegra/ @@ -9143,6 +9144,8 @@ DRM DRIVERS FOR ROCKCHIP M: Sandy Huang M: Heiko Stübner M: Andy Yan +R: Chaoyi Chen +R: Damon Ding L: dri-devel@lists.freedesktop.org L: linux-rockchip@lists.infradead.org S: Maintained @@ -9212,7 +9215,6 @@ F: drivers/gpu/drm/v3d/ F: include/uapi/drm/v3d_drm.h DRM DRIVERS FOR VC4 -M: Maxime Ripard M: Dave Stevenson R: Maíra Canal R: Raspberry Pi Kernel Maintenance @@ -11826,6 +11828,7 @@ M: Dennis Dalessandro L: linux-rdma@vger.kernel.org S: Supported F: drivers/infiniband/hw/hfi1 +F: include/uapi/rdma/hfi HFS FILESYSTEM M: Viacheslav Dubeyko @@ -12151,6 +12154,7 @@ L: linux-rdma@vger.kernel.org S: Maintained F: Documentation/devicetree/bindings/infiniband/hisilicon,hns-roce-v1.yaml F: drivers/infiniband/hw/hns/ +F: include/uapi/rdma/hns-abi.h HISILICON SAS Controller M: Xingui Yang @@ -13117,14 +13121,14 @@ W: https://www.infineon.com/part/TLV493D-A1B6 F: Documentation/devicetree/bindings/iio/magnetometer/infineon,tlv493d-a1b6.yaml F: drivers/iio/magnetometer/tlv493d.c -INFINIBAND SUBSYSTEM +RDMA (INFINIBAND) SUBSYSTEM M: Jason Gunthorpe M: Leon Romanovsky L: linux-rdma@vger.kernel.org S: Supported W: https://github.com/linux-rdma/rdma-core Q: http://patchwork.kernel.org/project/linux-rdma/list/ -T: git git://git.kernel.org/pub/scm/linux/kernel/git/rdma/rdma.git +T: git git://git.kernel.org/pub/scm/linux/kernel/git/rdma/rdma.git for-next F: Documentation/devicetree/bindings/infiniband/ F: Documentation/infiniband/ F: drivers/infiniband/ @@ -13419,6 +13423,7 @@ F: include/linux/net/intel/ INTEL ETHERNET PROTOCOL DRIVER FOR RDMA M: Tatyana Nikolova +M: Jacob Moroni L: linux-rdma@vger.kernel.org S: Supported F: drivers/infiniband/hw/irdma/ @@ -13845,9 +13850,9 @@ F: Documentation/admin-guide/pm/intel_uncore_frequency_scaling.rst F: drivers/platform/x86/intel/uncore-frequency/ INTEL USBIO USB I/O EXPANDER DRIVERS -M: Israel Cepeda M: Hans de Goede -R: Sakari Ailus +M: Sakari Ailus +R: Antti Laakso S: Maintained F: drivers/gpio/gpio-usbio.c F: drivers/i2c/busses/i2c-usbio.c @@ -14121,9 +14126,11 @@ F: net/netfilter/ipvs/ IRON DEVICE AUDIO CODEC DRIVERS M: Kiseok Jo +M: Hyunuk Son L: linux-sound@vger.kernel.org S: Maintained F: Documentation/devicetree/bindings/sound/irondevice,* +F: sound/soc/codecs/ma5311.* F: sound/soc/codecs/sma* IRQ DOMAINS (IRQ NUMBER MAPPING LIBRARY) @@ -14208,9 +14215,6 @@ M: Sagi Grimberg M: Max Gurtovoy L: linux-rdma@vger.kernel.org S: Supported -W: http://www.openfabrics.org -W: www.open-iscsi.org -Q: http://patchwork.kernel.org/project/linux-rdma/list/ F: drivers/infiniband/ulp/iser/ ISCSI EXTENSIONS FOR RDMA (ISER) TARGET @@ -14218,7 +14222,6 @@ M: Sagi Grimberg L: linux-rdma@vger.kernel.org L: target-devel@vger.kernel.org S: Supported -T: git git://git.kernel.org/pub/scm/linux/kernel/git/nab/target-pending.git master F: drivers/infiniband/ulp/isert ISL28022 HARDWARE MONITORING DRIVER @@ -14639,7 +14642,9 @@ R: Zenghui Yu L: linux-arm-kernel@lists.infradead.org (moderated for non-subscribers) L: kvmarm@lists.linux.dev S: Maintained +P: Documentation/process/maintainer-kvm-arm64.rst T: git git://git.kernel.org/pub/scm/linux/kernel/git/kvmarm/kvmarm.git +F: Documentation/process/maintainer-kvm-arm64.rst F: Documentation/virt/kvm/arm/ F: Documentation/virt/kvm/devices/arm* F: arch/arm64/include/asm/kvm* @@ -15934,7 +15939,7 @@ F: Documentation/devicetree/bindings/i2c/i2c-mux-ltc4306.txt F: drivers/i2c/muxes/i2c-mux-ltc4306.c LTP (Linux Test Project) -M: Andrea Cervesato +M: Andrea Cervesato M: Cyril Hrubis M: Jan Stancek M: Petr Vorel @@ -16160,8 +16165,6 @@ F: drivers/tty/serial/mvebu-uart.c MARVELL ARMADA DRM SUPPORT M: Russell King S: Maintained -T: git git://git.armlinux.org.uk/~rmk/linux-arm.git drm-armada-devel -T: git git://git.armlinux.org.uk/~rmk/linux-arm.git drm-armada-fixes F: Documentation/devicetree/bindings/display/armada/ F: drivers/gpu/drm/armada/ F: include/uapi/drm/armada_drm.h @@ -16286,7 +16289,7 @@ S: Supported F: drivers/perf/marvell_pem_pmu.c MARVELL PRESTERA ETHERNET SWITCH DRIVER -M: Elad Nachman +M: Elad Nachman S: Supported W: https://github.com/Marvell-switching/switchdev-prestera F: drivers/net/ethernet/marvell/prestera/ @@ -17373,7 +17376,6 @@ M: Yishai Hadas L: linux-rdma@vger.kernel.org S: Supported W: https://www.nvidia.com/networking/ -Q: http://patchwork.kernel.org/project/linux-rdma/list/ F: drivers/infiniband/hw/mlx4/ F: include/linux/mlx4/ F: include/uapi/rdma/mlx4-abi.h @@ -17397,7 +17399,6 @@ M: Leon Romanovsky L: linux-rdma@vger.kernel.org S: Supported W: https://www.nvidia.com/networking/ -Q: http://patchwork.kernel.org/project/linux-rdma/list/ F: drivers/infiniband/hw/mlx5/ F: include/linux/mlx5/ F: include/uapi/rdma/mlx5-abi.h @@ -17505,11 +17506,9 @@ F: mm/balloon.c MEMORY MANAGEMENT - CORE M: David Hildenbrand -R: Lorenzo Stoakes R: Liam R. Howlett R: Vlastimil Babka R: Mike Rapoport -R: Suren Baghdasaryan R: Michal Hocko L: linux-mm@kvack.org S: Maintained @@ -17635,10 +17634,10 @@ K: (?i:vmemmap) MEMORY MANAGEMENT - MGLRU (MULTI-GEN LRU) M: Andrew Morton -R: Kairui Song +M: Kairui Song +R: Barry Song R: Qi Zheng R: Shakeel Butt -R: Barry Song R: Axel Rasmussen R: Yuanchu Xie R: Wei Xu @@ -17676,11 +17675,9 @@ F: mm/migrate_device.c MEMORY MANAGEMENT - MISC M: Andrew Morton M: David Hildenbrand -R: Lorenzo Stoakes R: Liam R. Howlett R: Vlastimil Babka R: Mike Rapoport -R: Suren Baghdasaryan R: Michal Hocko L: linux-mm@kvack.org S: Maintained @@ -17782,6 +17779,7 @@ F: include/linux/compaction.h F: include/linux/gfp.h F: include/linux/page-isolation.h F: include/linux/pageblock-flags.h +F: include/linux/page_ext.h F: include/trace/events/compaction.h F: include/trace/events/page_isolation.h F: include/trace/events/page_ref.h @@ -17808,11 +17806,9 @@ F: tools/mm/page_owner_sort.c MEMORY MANAGEMENT - RECLAIM M: Andrew Morton M: Johannes Weiner -R: David Hildenbrand R: Michal Hocko R: Qi Zheng R: Shakeel Butt -R: Lorenzo Stoakes L: linux-mm@kvack.org S: Maintained F: include/trace/events/vmscan.h @@ -17961,7 +17957,6 @@ F: tools/testing/selftests/mm/uffd-*.[ch] MEMORY MANAGEMENT - RUST M: Alice Ryhl -R: Lorenzo Stoakes R: Liam R. Howlett L: linux-mm@kvack.org L: rust-for-linux@vger.kernel.org @@ -17974,30 +17969,37 @@ F: rust/kernel/mm.rs F: rust/kernel/mm/ F: rust/kernel/page.rs -MEMORY MAPPING -M: Andrew Morton -M: Liam R. Howlett +MEMORY MANAGEMENT - VMA M: Lorenzo Stoakes +M: Liam R. Howlett +M: Suren Baghdasaryan R: Vlastimil Babka -R: Jann Horn +R: Shakeel Butt R: Pedro Falcato +R: David Hildenbrand +R: Jann Horn L: linux-mm@kvack.org S: Maintained -W: http://www.linux-mm.org -T: git git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm +T: git git://git.kernel.org/pub/scm/linux/kernel/git/mm/vma.git for-next F: Documentation/core-api/protection-keys.rst F: Documentation/filesystems/mmap_prepare.rst +F: Documentation/mm/process_addrs.rst F: Documentation/userspace-api/mseal.rst F: fs/proc/task_mmu.c F: fs/proc/task_nommu.c F: include/linux/mman.h +F: include/linux/mmap_lock.h F: include/linux/pkeys.h F: include/trace/events/mmap.h +F: include/trace/events/mmap_lock.h +F: include/uapi/asm-generic/mman-common.h F: include/uapi/linux/mman.h F: mm/char-mem.c +F: mm/madvise.c F: mm/mincore.c F: mm/mlock.c F: mm/mmap.c +F: mm/mmap_lock.c F: mm/mprotect.c F: mm/mremap.c F: mm/mseal.c @@ -18011,36 +18013,6 @@ F: mm/vma_internal.h F: tools/testing/selftests/mm/merge.c F: tools/testing/vma/ -MEMORY MAPPING - LOCKING -M: Andrew Morton -M: Suren Baghdasaryan -M: Liam R. Howlett -M: Lorenzo Stoakes -R: Vlastimil Babka -R: Shakeel Butt -L: linux-mm@kvack.org -S: Maintained -W: http://www.linux-mm.org -T: git git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm -F: Documentation/mm/process_addrs.rst -F: include/linux/mmap_lock.h -F: include/trace/events/mmap_lock.h -F: mm/mmap_lock.c - -MEMORY MAPPING - MADVISE (MEMORY ADVICE) -M: Andrew Morton -M: Liam R. Howlett -M: Lorenzo Stoakes -M: David Hildenbrand -R: Vlastimil Babka -R: Jann Horn -L: linux-mm@kvack.org -S: Maintained -W: http://www.linux-mm.org -T: git git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm -F: include/uapi/asm-generic/mman-common.h -F: mm/madvise.c - MEMORY TECHNOLOGY DEVICES (MTD) M: Miquel Raynal M: Richard Weinberger @@ -19547,6 +19519,7 @@ M: "David S. Miller" M: Eric Dumazet M: Jakub Kicinski M: Paolo Abeni +M: Willem de Bruijn R: Simon Horman L: netdev@vger.kernel.org S: Maintained @@ -19601,6 +19574,10 @@ F: samples/pktgen/ F: tools/net/ F: tools/testing/selftests/net/ X: Documentation/networking/batman-adv.rst +X: Documentation/networking/can.rst +X: Documentation/networking/device_drivers/can/ +X: Documentation/networking/iso15765-2.rst +X: Documentation/networking/j1939.rst X: Documentation/networking/mac80211-injection.rst X: Documentation/networking/mac80211_hwsim/ X: Documentation/networking/regulatory.rst @@ -20484,7 +20461,7 @@ F: drivers/net/dsa/ocelot/ocelot_ext.c F: include/linux/mfd/ocelot.h OCXL (Open Coherent Accelerator Processor Interface OpenCAPI) DRIVER -M: Mahesh J Salgaonkar +M: Madhavan Srinivasan R: Andrew Donnellan L: linuxppc-dev@lists.ozlabs.org S: Odd Fixes @@ -21627,7 +21604,7 @@ F: drivers/pci/endpoint/ F: tools/testing/selftests/pci_endpoint/ PCI ENHANCED ERROR HANDLING (EEH) FOR POWERPC -M: Mahesh J Salgaonkar +M: Sourabh Jain R: Oliver O'Halloran L: linuxppc-dev@lists.ozlabs.org S: Supported @@ -21775,7 +21752,7 @@ S: Odd Fixes F: drivers/pci/controller/pci-thunder-* PCIE DRIVER FOR ESWIN -M: Senchuan Zhang +M: Donghui Zhao L: linux-pci@vger.kernel.org S: Maintained F: Documentation/devicetree/bindings/pci/eswin,pcie.yaml @@ -23548,6 +23525,7 @@ M: Dennis Dalessandro L: linux-rdma@vger.kernel.org S: Supported F: drivers/infiniband/sw/rdmavt +F: include/uapi/rdma/rvt-abi.h RDS - RELIABLE DATAGRAM SOCKETS M: Allison Henderson @@ -24669,7 +24647,6 @@ K: \b(?i:rust)\b RUST [ALLOC] M: Danilo Krummrich M: Alice Ryhl -R: Lorenzo Stoakes R: Vlastimil Babka R: Liam R. Howlett R: Uladzislau Rezki @@ -25271,7 +25248,6 @@ SCSI RDMA PROTOCOL (SRP) INITIATOR M: Bart Van Assche L: linux-rdma@vger.kernel.org S: Supported -Q: http://patchwork.kernel.org/project/linux-rdma/list/ F: drivers/infiniband/ulp/srp/ F: include/scsi/srp.h @@ -25280,7 +25256,6 @@ M: Bart Van Assche L: linux-rdma@vger.kernel.org L: target-devel@vger.kernel.org S: Supported -Q: http://patchwork.kernel.org/project/linux-rdma/list/ F: drivers/infiniband/ulp/srpt/ SCSI SG DRIVER @@ -27724,6 +27699,7 @@ M: Sen Wang L: linux-sound@vger.kernel.org S: Maintained F: Documentation/devicetree/bindings/sound/ti,tas2552.yaml +F: Documentation/devicetree/bindings/sound/ti,tas2557.yaml F: Documentation/devicetree/bindings/sound/ti,tas2562.yaml F: Documentation/devicetree/bindings/sound/ti,tas2770.yaml F: Documentation/devicetree/bindings/sound/ti,tas27xx.yaml @@ -29867,6 +29843,7 @@ F: fs/vboxsf/* VIRTUAL PCM TEST DRIVER M: Ivan Orlov +R: HyeongJun An L: linux-sound@vger.kernel.org S: Maintained F: Documentation/sound/cards/pcmtest.rst @@ -29957,13 +29934,6 @@ F: mm/vmalloc.c F: mm/vmalloc.h F: scripts/gdb/linux/vmalloc.py -VME SUBSYSTEM -L: linux-kernel@vger.kernel.org -S: Orphan -T: git git://git.kernel.org/pub/scm/linux/kernel/git/gregkh/char-misc.git -F: Documentation/driver-api/vme.rst -F: drivers/staging/vme_user/ - VMWARE BALLOON DRIVER M: Jerrin Shaji George R: Broadcom internal kernel review list @@ -29985,10 +29955,10 @@ F: arch/x86/kernel/cpu/vmware.c VMWARE PVRDMA DRIVER M: Bryan Tan M: Vishnu Dasa -R: Broadcom internal kernel review list L: linux-rdma@vger.kernel.org S: Supported F: drivers/infiniband/hw/vmw_pvrdma/ +F: include/uapi/rdma/vmw_pvrdma-abi.h VMWARE PVSCSI DRIVER M: Vishal Bhakta @@ -30688,6 +30658,7 @@ F: drivers/iio/adc/xilinx-ams.c XILINX AXI ETHERNET DRIVER M: Radhey Shyam Pandey +M: Suraj Gupta S: Maintained F: Documentation/devicetree/bindings/net/xlnx,axi-ethernet.yaml F: drivers/net/ethernet/xilinx/xilinx_axienet* diff --git a/Makefile b/Makefile index 5aac6f1b011e1b..3bd24ea8ff8937 100644 --- a/Makefile +++ b/Makefile @@ -2,7 +2,7 @@ VERSION = 7 PATCHLEVEL = 4 SUBLEVEL = 0 -EXTRAVERSION = -rc3 +EXTRAVERSION = -rc5 NAME = Baby Opossum Posse # *DOCUMENTATION* @@ -622,6 +622,7 @@ KBUILD_RUSTFLAGS := $(rust_common_flags) \ -Csymbol-mangling-version=v0 \ -Crelocation-model=static \ -Zfunction-sections=n \ + -Zmerge-functions=disabled \ -Wclippy::float_arithmetic KBUILD_RUSTFLAGS_OPTION_CHKS := @@ -1136,8 +1137,7 @@ endif ifdef CONFIG_RUST # Always pass -Zsanitizer-cfi-normalize-integers as CONFIG_RUST selects # CONFIG_CFI_ICALL_NORMALIZE_INTEGERS. - # Disable function merging as LLVM incorrectly merges functions with different KCFI types. - RUSTC_FLAGS_CFI := -Zsanitizer=kcfi -Zsanitizer-cfi-normalize-integers -Zmerge-functions=disabled + RUSTC_FLAGS_CFI := -Zsanitizer=kcfi -Zsanitizer-cfi-normalize-integers KBUILD_RUSTFLAGS += $(RUSTC_FLAGS_CFI) export RUSTC_FLAGS_CFI endif diff --git a/arch/arc/include/asm/io.h b/arch/arc/include/asm/io.h index 00171a212b3cb2..b4a3393d1bdca4 100644 --- a/arch/arc/include/asm/io.h +++ b/arch/arc/include/asm/io.h @@ -133,10 +133,14 @@ static inline void __raw_writeb(u8 b, volatile void __iomem *addr) #define __raw_writew __raw_writew static inline void __raw_writew(u16 s, volatile void __iomem *addr) { + /* + * Not an "m" operand: GCC can pick a register-indexed address for it, + * which ST doesn't support (GCC PR target/127718). + */ __asm__ __volatile__( - " stw%U1 %0, %1 \n" + " stw %0, [%1] \n" : - : "r" (s), "m" (*(volatile u16 __force *)addr) + : "r" (s), "r" (addr) : "memory"); } @@ -144,10 +148,11 @@ static inline void __raw_writew(u16 s, volatile void __iomem *addr) #define __raw_writel __raw_writel static inline void __raw_writel(u32 w, volatile void __iomem *addr) { + /* See __raw_writew() above for why this doesn't use an "m" operand. */ __asm__ __volatile__( - " st%U1 %0, %1 \n" + " st %0, [%1] \n" : - : "r" (w), "m" (*(volatile u32 __force *)addr) + : "r" (w), "r" (addr) : "memory"); } diff --git a/arch/arm/boot/dts/samsung/exynos4210-trats.dts b/arch/arm/boot/dts/samsung/exynos4210-trats.dts index 20fe148387fc23..ae4327770799a3 100644 --- a/arch/arm/boot/dts/samsung/exynos4210-trats.dts +++ b/arch/arm/boot/dts/samsung/exynos4210-trats.dts @@ -469,6 +469,12 @@ &pinctrl_1 { bt_shutdown: bt-shutdown-pins { + samsung,pins = "gpl0-4"; + samsung,pin-function = ; + samsung,pin-pud = ; + }; + + bt_reset: bt-reset-pins { samsung,pins = "gpl1-0"; samsung,pin-function = ; samsung,pin-pud = ; @@ -548,9 +554,10 @@ max-speed = <3000000>; - pinctrl-0 = <&bt_shutdown &bt_device_wakeup &bt_host_wakeup>; + pinctrl-0 = <&bt_shutdown &bt_reset &bt_device_wakeup &bt_host_wakeup>; pinctrl-names = "default"; - shutdown-gpios = <&gpl1 0 GPIO_ACTIVE_HIGH>; + shutdown-gpios = <&gpl0 4 GPIO_ACTIVE_HIGH>; + reset-gpios = <&gpl1 0 GPIO_ACTIVE_LOW>; device-wakeup-gpios = <&gpx3 1 GPIO_ACTIVE_HIGH>; host-wakeup-gpios = <&gpx2 6 GPIO_ACTIVE_HIGH>; }; diff --git a/arch/arm/boot/dts/samsung/exynos4210-universal_c210.dts b/arch/arm/boot/dts/samsung/exynos4210-universal_c210.dts index 744039068e8f31..79c0c27d9377bb 100644 --- a/arch/arm/boot/dts/samsung/exynos4210-universal_c210.dts +++ b/arch/arm/boot/dts/samsung/exynos4210-universal_c210.dts @@ -537,7 +537,7 @@ &pinctrl_1 { bt_shutdown: bt-shutdown-pins { - samsung,pins = "gpe1-4"; + samsung,pins = "gpk1-1"; samsung,pin-function = ; samsung,pin-pud = ; }; @@ -572,6 +572,12 @@ samsung,pin-pud = ; samsung,pin-drv = ; }; + + bt_reset: bt-reset-pins { + samsung,pins = "gpe1-4"; + samsung,pin-function = ; + samsung,pin-pud = ; + }; }; &pwm { @@ -641,9 +647,10 @@ max-speed = <3000000>; - pinctrl-0 = <&bt_shutdown &bt_device_wakeup &bt_host_wakeup>; + pinctrl-0 = <&bt_shutdown &bt_reset &bt_device_wakeup &bt_host_wakeup>; pinctrl-names = "default"; - shutdown-gpios = <&gpe1 4 GPIO_ACTIVE_HIGH>; + shutdown-gpios = <&gpk1 1 GPIO_ACTIVE_HIGH>; + reset-gpios = <&gpe1 4 GPIO_ACTIVE_LOW>; device-wakeup-gpios = <&gpx3 1 GPIO_ACTIVE_HIGH>; host-wakeup-gpios = <&gpx2 6 GPIO_ACTIVE_HIGH>; }; diff --git a/arch/arm/boot/dts/samsung/exynos4412-p4note.dtsi b/arch/arm/boot/dts/samsung/exynos4412-p4note.dtsi index 8d52aa13b862f1..03b514a82b8a7b 100644 --- a/arch/arm/boot/dts/samsung/exynos4412-p4note.dtsi +++ b/arch/arm/boot/dts/samsung/exynos4412-p4note.dtsi @@ -1232,6 +1232,7 @@ #address-cells = <1>; #size-cells = <0>; non-removable; + cap-power-off-card; bus-width = <4>; mmc-pwrseq = <&wlan_pwrseq>; diff --git a/arch/arm/boot/dts/st/Makefile b/arch/arm/boot/dts/st/Makefile index 10c5d75f6169c9..f699d37254e24b 100644 --- a/arch/arm/boot/dts/st/Makefile +++ b/arch/arm/boot/dts/st/Makefile @@ -94,11 +94,11 @@ stm32mp15xx-dhcom-picoitx-overlay-548-200-x2-mi0700s4t-6-dtbs := \ stm32mp15xx-dhcom-picoitx-overlay-548-200-x2-mi0700s4t-6.dtbo \ stm32mp15xx-dhcom-picoitx-overlay-553-100-x2-tst043015cmhx-dtbs := \ - stm32mp157c-dhcom-pdk2.dtb \ + stm32mp157c-dhcom-picoitx.dtb \ stm32mp15xx-dhcom-picoitx-overlay-553-100-x2-tst043015cmhx.dtbo \ stm32mp15xx-dhcom-picoitx-overlay-626-100-x2-ch101olhlwh-dtbs := \ - stm32mp157c-dhcom-pdk2.dtb \ + stm32mp157c-dhcom-picoitx.dtb \ stm32mp15xx-dhcom-picoitx-overlay-626-100-x2-ch101olhlwh.dtbo \ dtb-$(CONFIG_ARCH_STM32) += \ diff --git a/arch/arm64/boot/dts/arm/corstone1000-a320.dtsi b/arch/arm64/boot/dts/arm/corstone1000-a320.dtsi index f0937914350c5d..f895a024fc9208 100644 --- a/arch/arm64/boot/dts/arm/corstone1000-a320.dtsi +++ b/arch/arm64/boot/dts/arm/corstone1000-a320.dtsi @@ -73,7 +73,7 @@ #size-cells = <1>; interrupt-controller; reg = <0x1c000000 0x10000>, - <0x1c040000 0x80000>; + <0x1c040000 0x100000>; interrupts = ; }; diff --git a/arch/arm64/boot/dts/freescale/imx8qm-ss-conn.dtsi b/arch/arm64/boot/dts/freescale/imx8qm-ss-conn.dtsi index f25f62d51f69ee..1d1cde2bd879df 100644 --- a/arch/arm64/boot/dts/freescale/imx8qm-ss-conn.dtsi +++ b/arch/arm64/boot/dts/freescale/imx8qm-ss-conn.dtsi @@ -67,7 +67,3 @@ compatible = "fsl,imx8qm-usdhc", "fsl,imx8qxp-usdhc", "fsl,imx7d-usdhc"; iommus = <&smmu 0x11 0x7f80>; }; - -&usbotg3_cdns3 { - iommus = <&smmu 0x4 0x7f80>; -}; diff --git a/arch/arm64/boot/dts/st/stm32mp231.dtsi b/arch/arm64/boot/dts/st/stm32mp231.dtsi index fefbf6f4f15377..deeda0a252ce8e 100644 --- a/arch/arm64/boot/dts/st/stm32mp231.dtsi +++ b/arch/arm64/boot/dts/st/stm32mp231.dtsi @@ -24,6 +24,19 @@ power-domains = <&cpu0_pd>; power-domain-names = "psci"; }; + + idle-states { + entry-method = "psci"; + + cpu_sleep: cpu-sleep { + compatible = "arm,idle-state"; + arm,psci-suspend-param = <0x00000002>; + local-timer-stop; + entry-latency-us = <150>; + exit-latency-us = <200>; + min-residency-us = <1000>; + }; + }; }; arm-pmu { @@ -123,6 +136,7 @@ cpu0_pd: power-domain-cpu0 { #power-domain-cells = <0>; + domain-idle-states = <&cpu_sleep>; power-domains = <&cluster_pd>; }; @@ -143,7 +157,7 @@ , , ; - always-on; + arm,no-tick-in-suspend; }; soc@0 { diff --git a/arch/arm64/boot/dts/st/stm32mp233.dtsi b/arch/arm64/boot/dts/st/stm32mp233.dtsi index 78f4059fca5db6..cebefd99906f62 100644 --- a/arch/arm64/boot/dts/st/stm32mp233.dtsi +++ b/arch/arm64/boot/dts/st/stm32mp233.dtsi @@ -26,6 +26,7 @@ psci { cpu1_pd: power-domain-cpu1 { #power-domain-cells = <0>; + domain-idle-states = <&cpu_sleep>; power-domains = <&cluster_pd>; }; }; diff --git a/arch/arm64/boot/dts/st/stm32mp23xx-dhcos-som.dtsi b/arch/arm64/boot/dts/st/stm32mp23xx-dhcos-som.dtsi index ffdcceb2fa237b..7a95f56bf857ff 100644 --- a/arch/arm64/boot/dts/st/stm32mp23xx-dhcos-som.dtsi +++ b/arch/arm64/boot/dts/st/stm32mp23xx-dhcos-som.dtsi @@ -20,11 +20,64 @@ }; }; +&gpioa { + gpio-line-names = "", "", "", "", + "", "", "", "", + "", "", "", "", + "DHCOS-C", "", "", ""; +}; + +&gpiod { + gpio-line-names = "", "DHCOS-K", "DHCOS-J", "", + "", "", "", "", + "", "", "", "", + "", "", "", ""; +}; + +&gpiof { + gpio-line-names = "", "", "", "", + "", "", "", "", + "", "", "", "DHCOS-E", + "DHCOS-N", "", "", "DHCOS_RAM-CODE_2"; +}; + +&gpiog { + gpio-line-names = "", "", "", "", + "", "", "", "DHCOS-P", + "DHCOS-O", "DHCOS_RAM-CODE_0", "DHCOS_RAM-CODE_1", "", + "", "", "DHCOS-F", "DHCOS_HW-CODE_0"; +}; + +&gpioh { + gpio-line-names = "", "", "DHCOS-I", "", + "", "DHCOS-H", "DHCOS-L", "", + "DHCOS-G", "", "", "", + "", "", "", ""; +}; + +&gpioi { + gpio-line-names = "DHCOS_HW-CODE_1", "DHCOS_HW-CODE_2", "", "", + "", "DHCOS-M", "", "", + "", "", "", "DHCOS-D", + "", "", "", ""; +}; + +&ioexp { + gpio-line-names = + "#ETH1_RST_P0_0", "#ETH0_RST_P0_1", + "BT_REG_ON_P0_2", "WL_REG_ON_P0_3", + "USB1_PWR_EN_P0_4", "USB1_PWR_STAT_P0_5", + "USB0_PWR_EN_P0_6", "USB0_PWR_STAT_P0_7", + "SDIO0_CD_P1_0", "USB0_SS_SEL_P1_1", + "#PCIe_RST_1_2", "#PCIe_Wake_P1_3", + "#QSPI_RST_P1_4", "#CSI0_PWDN_P1_5", + "#CSI0_RST_P1_6", "#PCIE_CLKREQ_GPIO_Q_P1_7"; +}; + &rv3032 { interrupts-extended = <&gpiod 10 IRQ_TYPE_EDGE_FALLING>; }; -/* Bluetooth */ &usart1 { pinctrl-names = "default", "sleep", "idle"; pinctrl-0 = <&usart1_pins_a>; @@ -32,15 +85,9 @@ pinctrl-2 = <&usart1_idle_pins_a>; uart-has-rtscts; status = "okay"; - - bluetooth { - compatible = "infineon,cyw55572-bt"; - brcm,requires-autobaud-mode; - max-speed = <3000000>; - shutdown-gpios = <&ioexp 2 GPIO_ACTIVE_HIGH>; - }; }; +/* Bluetooth */ &usart2 { pinctrl-names = "default", "sleep", "idle"; pinctrl-0 = <&usart2_pins_b>; @@ -48,4 +95,11 @@ pinctrl-2 = <&usart2_idle_pins_b>; uart-has-rtscts; status = "okay"; + + bluetooth { + compatible = "infineon,cyw55572-bt"; + brcm,requires-autobaud-mode; + max-speed = <3000000>; + shutdown-gpios = <&ioexp 2 GPIO_ACTIVE_HIGH>; + }; }; diff --git a/arch/arm64/boot/dts/st/stm32mp251.dtsi b/arch/arm64/boot/dts/st/stm32mp251.dtsi index dac3d2d23ff008..bf1542818be257 100644 --- a/arch/arm64/boot/dts/st/stm32mp251.dtsi +++ b/arch/arm64/boot/dts/st/stm32mp251.dtsi @@ -25,6 +25,19 @@ power-domains = <&CPU_PD0>; power-domain-names = "psci"; }; + + idle-states { + entry-method = "psci"; + + cpu_sleep: cpu-sleep { + compatible = "arm,idle-state"; + arm,psci-suspend-param = <0x00000002>; + local-timer-stop; + entry-latency-us = <150>; + exit-latency-us = <200>; + min-residency-us = <1000>; + }; + }; }; arm-pmu { @@ -145,6 +158,7 @@ CPU_PD0: power-domain-cpu0 { #power-domain-cells = <0>; + domain-idle-states = <&cpu_sleep>; power-domains = <&CLUSTER_PD>; }; diff --git a/arch/arm64/boot/dts/st/stm32mp253.dtsi b/arch/arm64/boot/dts/st/stm32mp253.dtsi index 7e82f01fdc10f8..19b3e55a441411 100644 --- a/arch/arm64/boot/dts/st/stm32mp253.dtsi +++ b/arch/arm64/boot/dts/st/stm32mp253.dtsi @@ -26,6 +26,7 @@ psci { CPU_PD1: power-domain-cpu1 { #power-domain-cells = <0>; + domain-idle-states = <&cpu_sleep>; power-domains = <&CLUSTER_PD>; }; }; diff --git a/arch/arm64/boot/dts/st/stm32mp257-engicam-microgea.dtsi b/arch/arm64/boot/dts/st/stm32mp257-engicam-microgea.dtsi index 5b4287e86deff9..6cd64587ecdc98 100644 --- a/arch/arm64/boot/dts/st/stm32mp257-engicam-microgea.dtsi +++ b/arch/arm64/boot/dts/st/stm32mp257-engicam-microgea.dtsi @@ -19,6 +19,18 @@ device_type = "memory"; reg = <0x0 0x80000000 0x0 0x80000000>; }; + + reserved-memory { + #address-cells = <2>; + #size-cells = <2>; + ranges; + + fw@80000000 { + compatible = "shared-dma-pool"; + reg = <0x0 0x80000000 0x0 0x4000000>; + no-map; + }; + }; }; &scmi_regu { diff --git a/arch/arm64/boot/dts/st/stm32mp25xx-dhcos-som.dtsi b/arch/arm64/boot/dts/st/stm32mp25xx-dhcos-som.dtsi index 23c25ea086445a..3f3bdef05ce4e9 100644 --- a/arch/arm64/boot/dts/st/stm32mp25xx-dhcos-som.dtsi +++ b/arch/arm64/boot/dts/st/stm32mp25xx-dhcos-som.dtsi @@ -20,6 +20,53 @@ }; }; +&gpioa { + gpio-line-names = "", "DHCOS-M", "DHCOS-K", "DHCOS-L", + "DHCOS-E", "DHCOS-J", "", "", + "DHCOS-D", "", "", "", + "", "", "", ""; +}; + +&gpiof { + gpio-line-names = "", "", "", "", + "", "", "", "", + "", "", "", "", + "", "", "", "DHCOS_RAM-CODE_2"; +}; + +&gpiog { + gpio-line-names = "", "", "", "", + "", "", "", "", + "", "DHCOS_RAM-CODE_0", "DHCOS_RAM-CODE_1", "", + "", "", "DHCOS-F", "DHCOS_HW-CODE_0"; +}; + +&gpioh { + gpio-line-names = "", "", "DHCOS-I", "DHCOS-N", + "", "", "DHCOS-O", "DHCOS-H", + "DHCOS-G", "", "", "", + "", "", "", ""; +}; + +&gpioi { + gpio-line-names = "DHCOS_HW-CODE_1", "DHCOS_HW-CODE_2", "", "", + "", "", "", "", + "", "DHCOS-C", "", "", + "", "", "", ""; +}; + +&ioexp { + gpio-line-names = + "#ETH1_RST_P0_0", "#ETH0_RST_P0_1", + "BT_REG_ON_P0_2", "WL_REG_ON_P0_3", + "USB1_PWR_EN_P0_4", "USB1_PWR_STAT_P0_5", + "USB0_PWR_EN_P0_6", "USB0_PWR_STAT_P0_7", + "SDIO0_CD_P1_0", "USB0_SS_SEL_P1_1", + "#PCIe_RST_1_2", "#PCIe_Wake_P1_3", + "#QSPI_RST_P1_4", "#CSI0_PWDN_P1_5", + "#CSI0_RST_P1_6", "#ETH3_RST_P1_7"; +}; + &rv3032 { interrupts-extended = <&gpioi 10 IRQ_TYPE_EDGE_FALLING>; }; diff --git a/arch/arm64/boot/dts/st/stm32mp2xxx-dhcos-som.dtsi b/arch/arm64/boot/dts/st/stm32mp2xxx-dhcos-som.dtsi index bcf63e2ea98985..6febdbfe83649c 100644 --- a/arch/arm64/boot/dts/st/stm32mp2xxx-dhcos-som.dtsi +++ b/arch/arm64/boot/dts/st/stm32mp2xxx-dhcos-som.dtsi @@ -218,41 +218,6 @@ status = "okay"; }; -&gpioa { - gpio-line-names = "", "DHCOS-M", "DHCOS-K", "DHCOS-L", - "DHCOS-E", "DHCOS-J", "", "", - "DHCOS-D", "", "", "", - "", "", "", ""; -}; - -&gpiof { - gpio-line-names = "", "", "", "", - "", "", "", "", - "", "", "", "", - "", "", "", "DHCOS_RAM-CODE_2"; -}; - -&gpiog { - gpio-line-names = "", "", "", "", - "", "", "", "", - "", "DHCOS_RAM-CODE_0", "DHCOS_RAM-CODE_1", "", - "", "", "DHCOS-F", "DHCOS_HW-CODE_0"; -}; - -&gpioh { - gpio-line-names = "", "", "DHCOS-I", "DHCOS-N", - "", "", "DHCOS-O", "DHCOS-H", - "DHCOS-G", "", "", "", - "", "", "", ""; -}; - -&gpioi { - gpio-line-names = "DHCOS_HW-CODE_1", "DHCOS_HW-CODE_2", "", "", - "", "", "", "", - "", "DHCOS-C", "", "", - "", "", "", ""; -}; - &gpioz { gpio-line-names = "", "", "DHCOS-A", "DHCOS-B", "", "", "", "", @@ -278,16 +243,6 @@ interrupt-controller; #interrupt-cells = <2>; wakeup-source; - - gpio-line-names = - "#ETH1_RST_P0_0", "#ETH0_RST_P0_1", - "BT_REG_ON_P0_2", "WL_REG_ON_P0_3", - "USB1_PWR_EN_P0_4", "USB1_PWR_STAT_P0_5", - "USB0_PWR_EN_P0_6", "USB0_PWR_STAT_P0_7", - "SDIO0_CD_P1_0", "USB0_SS_SEL_P1_1", - "#PCIe_RST_1_2", "#PCIe_Wake_P1_3", - "#QSPI_RST_P1_4", "#CSI0_PWDN_P1_5", - "#CSI0_RST_P1_6", "#ETH3_RST_P1_7"; }; eeprom0: eeprom@50 { diff --git a/arch/arm64/include/asm/cpufeature.h b/arch/arm64/include/asm/cpufeature.h index e3c8a1493dc8d9..7d7b8eb7f72fb1 100644 --- a/arch/arm64/include/asm/cpufeature.h +++ b/arch/arm64/include/asm/cpufeature.h @@ -872,6 +872,11 @@ static inline bool system_supports_lpa2(void) return cpus_have_final_cap(ARM64_HAS_LPA2); } +static inline bool system_supports_pie(void) +{ + return alternative_has_cap_unlikely(ARM64_HAS_S1PIE); +} + static inline bool system_supports_poe(void) { return alternative_has_cap_unlikely(ARM64_HAS_S1POE); diff --git a/arch/arm64/include/asm/cputype.h b/arch/arm64/include/asm/cputype.h index 6002d1d5f55f46..0cfa7b640b9c49 100644 --- a/arch/arm64/include/asm/cputype.h +++ b/arch/arm64/include/asm/cputype.h @@ -156,6 +156,18 @@ #define APPLE_CPU_PART_M2_AVALANCHE_PRO 0x035 #define APPLE_CPU_PART_M2_BLIZZARD_MAX 0x038 #define APPLE_CPU_PART_M2_AVALANCHE_MAX 0x039 +#define APPLE_CPU_PART_M3_SAWTOOTH 0x042 +#define APPLE_CPU_PART_M3_EVEREST 0x043 +#define APPLE_CPU_PART_M3_SAWTOOTH_PRO 0x044 +#define APPLE_CPU_PART_M3_EVEREST_PRO 0x045 +#define APPLE_CPU_PART_M3_SAWTOOTH_MAX 0x048 +#define APPLE_CPU_PART_M3_EVEREST_MAX 0x049 +#define APPLE_CPU_PART_M4_DONAN_ECORE 0x052 +#define APPLE_CPU_PART_M4_DONAN_PCORE 0x053 +#define APPLE_CPU_PART_A18_PRO_TAHITI_ECORE 0x060 +#define APPLE_CPU_PART_A18_PRO_TAHITI_PCORE 0x061 +#define APPLE_CPU_PART_M5_PRO_SOTRA_MCORE 0x064 +#define APPLE_CPU_PART_M5_PRO_SOTRA_PCORE 0x065 #define AMPERE_CPU_PART_AMPERE1 0xAC3 #define AMPERE_CPU_PART_AMPERE1A 0xAC4 @@ -252,6 +264,22 @@ #define MIDR_APPLE_M2_AVALANCHE_PRO MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M2_AVALANCHE_PRO) #define MIDR_APPLE_M2_BLIZZARD_MAX MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M2_BLIZZARD_MAX) #define MIDR_APPLE_M2_AVALANCHE_MAX MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M2_AVALANCHE_MAX) +#define MIDR_APPLE_M3_SAWTOOTH MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M3_SAWTOOTH) +#define MIDR_APPLE_M3_EVEREST MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M3_EVEREST) +#define MIDR_APPLE_M3_SAWTOOTH_PRO MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M3_SAWTOOTH_PRO) +#define MIDR_APPLE_M3_EVEREST_PRO MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M3_EVEREST_PRO) +#define MIDR_APPLE_M3_SAWTOOTH_MAX MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M3_SAWTOOTH_MAX) +#define MIDR_APPLE_M3_EVEREST_MAX MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M3_EVEREST_MAX) +#define MIDR_APPLE_M4_DONAN_ECORE MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M4_DONAN_ECORE) +#define MIDR_APPLE_M4_DONAN_PCORE MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M4_DONAN_PCORE) +#define MIDR_APPLE_A18_PRO_TAHITI_ECORE \ + MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_A18_PRO_TAHITI_ECORE) +#define MIDR_APPLE_A18_PRO_TAHITI_PCORE \ + MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_A18_PRO_TAHITI_PCORE) +#define MIDR_APPLE_M5_PRO_SOTRA_MCORE \ + MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M5_PRO_SOTRA_MCORE) +#define MIDR_APPLE_M5_PRO_SOTRA_PCORE \ + MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M5_PRO_SOTRA_PCORE) #define MIDR_AMPERE1 MIDR_CPU_MODEL(ARM_CPU_IMP_AMPERE, AMPERE_CPU_PART_AMPERE1) #define MIDR_AMPERE1A MIDR_CPU_MODEL(ARM_CPU_IMP_AMPERE, AMPERE_CPU_PART_AMPERE1A) #define MIDR_MICROSOFT_AZURE_COBALT_100 MIDR_CPU_MODEL(ARM_CPU_IMP_MICROSOFT, MICROSOFT_CPU_PART_AZURE_COBALT_100) diff --git a/arch/arm64/include/asm/kexec.h b/arch/arm64/include/asm/kexec.h index 892e5bebda957b..0be042ec22c1fc 100644 --- a/arch/arm64/include/asm/kexec.h +++ b/arch/arm64/include/asm/kexec.h @@ -100,6 +100,8 @@ void cpu_soft_restart(unsigned long el2_switch, unsigned long entry, unsigned long arg0, unsigned long arg1, unsigned long arg2); +void arm64_relocate_new_kernel(struct kimage *kimage); + int machine_kexec_post_load(struct kimage *image); #define machine_kexec_post_load machine_kexec_post_load #endif diff --git a/arch/arm64/include/asm/kvm_arm.h b/arch/arm64/include/asm/kvm_arm.h index ba0062849be908..3e1c9e31028e91 100644 --- a/arch/arm64/include/asm/kvm_arm.h +++ b/arch/arm64/include/asm/kvm_arm.h @@ -45,19 +45,6 @@ #define MPAMHCR_HOST_FLAGS 0 /* TCR_EL2 Registers bits */ -#define TCR_EL2_DS (1UL << 32) -#define TCR_EL2_RES1 ((1U << 31) | (1 << 23)) -#define TCR_EL2_HPD (1 << 24) -#define TCR_EL2_HA (1 << 21) -#define TCR_EL2_TBI (1 << 20) -#define TCR_EL2_PS_SHIFT 16 -#define TCR_EL2_PS_MASK (7 << TCR_EL2_PS_SHIFT) -#define TCR_EL2_PS_40B (2 << TCR_EL2_PS_SHIFT) -#define TCR_EL2_TG0_MASK TCR_TG0_MASK -#define TCR_EL2_SH0_MASK TCR_SH0_MASK -#define TCR_EL2_ORGN0_MASK TCR_ORGN0_MASK -#define TCR_EL2_IRGN0_MASK TCR_IRGN0_MASK -#define TCR_EL2_T0SZ_MASK 0x3f #define TCR_EL2_MASK (TCR_EL2_TG0_MASK | TCR_EL2_SH0_MASK | \ TCR_EL2_ORGN0_MASK | TCR_EL2_IRGN0_MASK) diff --git a/arch/arm64/include/asm/kvm_asm.h b/arch/arm64/include/asm/kvm_asm.h index abda476e023deb..8c585478938ee7 100644 --- a/arch/arm64/include/asm/kvm_asm.h +++ b/arch/arm64/include/asm/kvm_asm.h @@ -60,7 +60,6 @@ enum __kvm_host_smccc_func { __KVM_HOST_SMCCC_FUNC___pkvm_create_private_mapping, __KVM_HOST_SMCCC_FUNC___pkvm_cpu_set_vector, __KVM_HOST_SMCCC_FUNC___kvm_enable_ssbs, - __KVM_HOST_SMCCC_FUNC___vgic_v3_init_lrs, __KVM_HOST_SMCCC_FUNC___vgic_v3_get_gic_config, __KVM_HOST_SMCCC_FUNC___pkvm_hyp_alloc_selftest, __KVM_HOST_SMCCC_FUNC___vgic_v5_make_resident, @@ -91,6 +90,7 @@ enum __kvm_host_smccc_func { __KVM_HOST_SMCCC_FUNC___tracing_reset, __KVM_HOST_SMCCC_FUNC___tracing_enable_event, __KVM_HOST_SMCCC_FUNC___tracing_write_event, + __KVM_HOST_SMCCC_FUNC___vgic_v3_init_lrs, __KVM_HOST_SMCCC_FUNC___vgic_v3_save_aprs, __KVM_HOST_SMCCC_FUNC___vgic_v3_restore_vmcr_aprs, __KVM_HOST_SMCCC_FUNC___pkvm_hyp_topup, diff --git a/arch/arm64/include/asm/kvm_emulate.h b/arch/arm64/include/asm/kvm_emulate.h index 334211b8b2ee49..2d7c82cfb8a40d 100644 --- a/arch/arm64/include/asm/kvm_emulate.h +++ b/arch/arm64/include/asm/kvm_emulate.h @@ -740,6 +740,9 @@ static inline void vcpu_set_hcrx(struct kvm_vcpu *vcpu) if (kvm_has_feat(kvm, ID_AA64ISAR1_EL1, LS64, LS64_V)) vcpu->arch.hcrx_el2 |= HCRX_EL2_EnASR; + if (kvm_has_feat(kvm, ID_AA64ISAR1_EL1, LS64, LS64_ACCDATA)) + vcpu->arch.hcrx_el2 |= HCRX_EL2_EnAS0; + /* * NV3 is a host-specific extension, and we always use * it when present and that the guest uses NV. It may diff --git a/arch/arm64/include/asm/kvm_host.h b/arch/arm64/include/asm/kvm_host.h index 97332ffcb1300e..0614c3b3a40dfd 100644 --- a/arch/arm64/include/asm/kvm_host.h +++ b/arch/arm64/include/asm/kvm_host.h @@ -582,6 +582,9 @@ enum vcpu_sysreg { GCR_EL1, /* Tag Control Register */ TFSRE0_EL1, /* Tag Fault Status Register (EL0) */ + /* Random stuff */ + ACCDATA_EL1, /* Accelerator Data */ + POR_EL0, /* Permission Overlay Register 0 (EL0) */ /* FP/SIMD/SVE */ @@ -600,7 +603,6 @@ enum vcpu_sysreg { HACR_EL2, /* Hypervisor Auxiliary Control Register */ TTBR0_EL2, /* Translation Table Base Register 0 (EL2) */ TTBR1_EL2, /* Translation Table Base Register 1 (EL2) */ - TCR_EL2, /* Translation Control Register (EL2) */ PIRE0_EL2, /* Permission Indirection Register 0 (EL2) */ PIR_EL2, /* Permission Indirection Register 1 (EL2) */ POR_EL2, /* Permission Overlay Register 2 (EL2) */ @@ -625,6 +627,7 @@ enum vcpu_sysreg { /* Anything from this can be RES0/RES1 sanitised */ MARKER(__SANITISED_REG_START__), SCTLR_EL2, /* System Control Register (EL2) */ + TCR_EL2, /* Translation Control Register (EL2) */ TCR2_EL2, /* Extended Translation Control Register (EL2) */ SCTLR2_EL2, /* System Control Register 2 (EL2) */ MDCR_EL2, /* Monitor Debug Configuration Register (EL2) */ @@ -1376,7 +1379,7 @@ void kvm_reset_sys_regs(struct kvm_vcpu *vcpu); int __init kvm_sys_reg_table_init(void); struct sys_reg_desc; int __init populate_sysreg_config(const struct sys_reg_desc *sr, - unsigned int idx); + unsigned int idx, bool needs_nv_trap); int __init populate_nv_trap_config(void); void kvm_calculate_traps(struct kvm_vcpu *vcpu); diff --git a/arch/arm64/include/asm/kvm_nested.h b/arch/arm64/include/asm/kvm_nested.h index 0f899addafa8b4..27ec73da02c601 100644 --- a/arch/arm64/include/asm/kvm_nested.h +++ b/arch/arm64/include/asm/kvm_nested.h @@ -20,16 +20,36 @@ static inline u64 tcr_el2_ps_to_tcr_el1_ips(u64 tcr_el2) return (u64)FIELD_GET(TCR_EL2_PS_MASK, tcr_el2) << TCR_IPS_SHIFT; } -static inline u64 translate_tcr_el2_to_tcr_el1(u64 tcr) +#define __xlate_tcr_nvhe_to_vhe(nfld, vfld, nvhe, vhe) \ + FIELD_MODIFY(VHE_TCR_EL2_##vfld, vhe, FIELD_GET(TCR_EL2_##nfld, *(nvhe))) + +#define __xlate_tcr_nvhe_to_vhe_field(fld, nvhe, vhe) \ + __xlate_tcr_nvhe_to_vhe(fld, fld, nvhe, vhe) + +static inline u64 translate_tcr_el2_to_tcr_el1(u64 nvhe) { - return TCR_EPD1_MASK | /* disable TTBR1_EL1 */ - ((tcr & TCR_EL2_DS) ? TCR_DS : 0) | - ((tcr & TCR_EL2_TBI) ? TCR_TBI0 : 0) | - tcr_el2_ps_to_tcr_el1_ips(tcr) | - (tcr & TCR_EL2_TG0_MASK) | - (tcr & TCR_EL2_ORGN0_MASK) | - (tcr & TCR_EL2_IRGN0_MASK) | - (tcr & TCR_EL2_T0SZ_MASK); + u64 vhe = VHE_TCR_EL2_EPD1 | /* disable TTBR1_EL1 */ + tcr_el2_ps_to_tcr_el1_ips(nvhe); + + __xlate_tcr_nvhe_to_vhe(MTX, MTX0, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe(TCMA, TCMA0, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe(TBID, TBID0, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe(HWU62, HWU062, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe(HWU61, HWU061, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe(HWU60, HWU060, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe(HWU59, HWU059, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe(HPD, HPD0, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe(TBI, TBI0, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe_field( DS, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe_field( HA, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe_field( HD, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe_field( TG0, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe_field( SH0, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe_field( ORGN0, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe_field( IRGN0, &nvhe, &vhe); + __xlate_tcr_nvhe_to_vhe_field( T0SZ, &nvhe, &vhe); + + return vhe; } static inline u64 translate_cptr_el2_to_cpacr_el1(u64 cptr_el2) diff --git a/arch/arm64/include/asm/kvm_pgtable.h b/arch/arm64/include/asm/kvm_pgtable.h index 1c9c57cd6ae40d..6d6ed85968475b 100644 --- a/arch/arm64/include/asm/kvm_pgtable.h +++ b/arch/arm64/include/asm/kvm_pgtable.h @@ -508,7 +508,7 @@ void kvm_pgtable_hyp_destroy(struct kvm_pgtable *pgt); * If device attributes are not explicitly requested in @prot, then the * mapping will be normal, cacheable. Attempts to install a new mapping * for a virtual address that is already mapped will be rejected with an - * error and a WARN(). + * error. * * Return: 0 on success, negative error code on failure. */ diff --git a/arch/arm64/include/asm/module.h b/arch/arm64/include/asm/module.h index fb9b88eebeb15a..aff1d4ff3245f4 100644 --- a/arch/arm64/include/asm/module.h +++ b/arch/arm64/include/asm/module.h @@ -29,6 +29,9 @@ u64 module_emit_plt_entry(struct module *mod, Elf64_Shdr *sechdrs, u64 module_emit_veneer_for_adrp(struct module *mod, Elf64_Shdr *sechdrs, void *loc, u64 val); +void module_write_place(void *place, void *val, size_t len, + struct module *mod); + struct plt_entry { /* * A program that conforms to the AArch64 Procedure Call Standard diff --git a/arch/arm64/include/asm/mte.h b/arch/arm64/include/asm/mte.h index 83f3b05fc78490..ff3d78329be0c2 100644 --- a/arch/arm64/include/asm/mte.h +++ b/arch/arm64/include/asm/mte.h @@ -94,6 +94,7 @@ static inline bool try_page_mte_tagging(struct page *page) } void mte_zero_clear_page_tags(void *addr); +void mte_clear_folio_tags(struct folio *folio); void mte_sync_tags(pte_t pte, unsigned int nr_pages); void mte_copy_page_tags(void *kto, const void *kfrom); void mte_thread_init_user(void); @@ -126,6 +127,9 @@ static inline bool try_page_mte_tagging(struct page *page) static inline void mte_zero_clear_page_tags(void *addr) { } +static inline void mte_clear_folio_tags(struct folio *folio) +{ +} static inline void mte_sync_tags(pte_t pte, unsigned int nr_pages) { } @@ -222,10 +226,10 @@ static inline bool folio_try_hugetlb_mte_tagging(struct folio *folio) } #endif -static inline void mte_disable_tco_entry(struct task_struct *task) +static inline bool mte_disable_tco_entry(struct task_struct *task) { if (!system_supports_mte()) - return; + return false; /* * Re-enable tag checking (TCO set on exception entry). This is only @@ -238,8 +242,12 @@ static inline void mte_disable_tco_entry(struct task_struct *task) * expensive. */ if (kasan_hw_tags_enabled() || - (task->thread.sctlr_user & (1UL << SCTLR_EL1_TCF0_SHIFT))) + (task->thread.sctlr_user & (1UL << SCTLR_EL1_TCF0_SHIFT))) { asm volatile(SET_PSTATE_TCO(0)); + return true; + } + + return false; } #ifdef CONFIG_KASAN_HW_TAGS diff --git a/arch/arm64/include/asm/neon-intrinsics.h b/arch/arm64/include/asm/neon-intrinsics.h index 5f13505d39fc75..43cdf4d1617098 100644 --- a/arch/arm64/include/asm/neon-intrinsics.h +++ b/arch/arm64/include/asm/neon-intrinsics.h @@ -6,23 +6,13 @@ #ifndef __ASM_NEON_INTRINSICS_H #define __ASM_NEON_INTRINSICS_H -#include - /* - * In the kernel, u64/s64 are [un]signed long long, not [un]signed long. - * So by redefining these macros to the former, we can force gcc-stdint.h - * to define uint64_t / in64_t in a compatible manner. + * includes , which defines some C99 types differently + * from , so the latter must not be included into code that uses + * NEON intrinsics. The kernel's u8/u16/u32/u64 types can be used alongside the + * C99 ones, so provide those instead. */ - -#ifdef __INT64_TYPE__ -#undef __INT64_TYPE__ -#define __INT64_TYPE__ long long -#endif - -#ifdef __UINT64_TYPE__ -#undef __UINT64_TYPE__ -#define __UINT64_TYPE__ unsigned long long -#endif +#include /* * genksyms chokes on the ARM NEON instrinsics system header, but we @@ -33,8 +23,4 @@ #include #endif -#ifdef CONFIG_CC_IS_CLANG -#pragma clang diagnostic ignored "-Wincompatible-pointer-types" -#endif - #endif /* __ASM_NEON_INTRINSICS_H */ diff --git a/arch/arm64/include/asm/sysreg.h b/arch/arm64/include/asm/sysreg.h index e3b60ee0302301..7cba1216efd2e7 100644 --- a/arch/arm64/include/asm/sysreg.h +++ b/arch/arm64/include/asm/sysreg.h @@ -510,7 +510,6 @@ #define SYS_TTBR0_EL2 sys_reg(3, 4, 2, 0, 0) #define SYS_TTBR1_EL2 sys_reg(3, 4, 2, 0, 1) -#define SYS_TCR_EL2 sys_reg(3, 4, 2, 0, 2) #define SYS_VTTBR_EL2 sys_reg(3, 4, 2, 1, 0) #define SYS_HAFGRTR_EL2 sys_reg(3, 4, 3, 1, 6) diff --git a/arch/arm64/include/asm/virt.h b/arch/arm64/include/asm/virt.h index b546703c3ab9a8..a5bde8cc5df51a 100644 --- a/arch/arm64/include/asm/virt.h +++ b/arch/arm64/include/asm/virt.h @@ -83,7 +83,7 @@ extern u32 __boot_cpu_mode[2]; #define ARM64_VECTOR_TABLE_LEN SZ_2K void __hyp_set_vectors(phys_addr_t phys_vector_base); -void __hyp_reset_vectors(void); +int __hyp_reset_vectors(void); bool is_kvm_arm_initialised(void); DECLARE_STATIC_KEY_FALSE(kvm_protected_mode_initialized); diff --git a/arch/arm64/kernel/cpu_errata.c b/arch/arm64/kernel/cpu_errata.c index ca31d33152e930..0ded97d7cbecda 100644 --- a/arch/arm64/kernel/cpu_errata.c +++ b/arch/arm64/kernel/cpu_errata.c @@ -317,6 +317,18 @@ static const struct midr_range apple_cpus[] = { MIDR_ALL_VERSIONS(MIDR_APPLE_M2_AVALANCHE_PRO), MIDR_ALL_VERSIONS(MIDR_APPLE_M2_BLIZZARD_MAX), MIDR_ALL_VERSIONS(MIDR_APPLE_M2_AVALANCHE_MAX), + MIDR_ALL_VERSIONS(MIDR_APPLE_M3_SAWTOOTH), + MIDR_ALL_VERSIONS(MIDR_APPLE_M3_EVEREST), + MIDR_ALL_VERSIONS(MIDR_APPLE_M3_SAWTOOTH_PRO), + MIDR_ALL_VERSIONS(MIDR_APPLE_M3_EVEREST_PRO), + MIDR_ALL_VERSIONS(MIDR_APPLE_M3_SAWTOOTH_MAX), + MIDR_ALL_VERSIONS(MIDR_APPLE_M3_EVEREST_MAX), + MIDR_ALL_VERSIONS(MIDR_APPLE_M4_DONAN_ECORE), + MIDR_ALL_VERSIONS(MIDR_APPLE_M4_DONAN_PCORE), + MIDR_ALL_VERSIONS(MIDR_APPLE_A18_PRO_TAHITI_ECORE), + MIDR_ALL_VERSIONS(MIDR_APPLE_A18_PRO_TAHITI_PCORE), + MIDR_ALL_VERSIONS(MIDR_APPLE_M5_PRO_SOTRA_MCORE), + MIDR_ALL_VERSIONS(MIDR_APPLE_M5_PRO_SOTRA_PCORE), {}, }; diff --git a/arch/arm64/kernel/cpufeature.c b/arch/arm64/kernel/cpufeature.c index c9c9a6889455c2..866385b490eb7d 100644 --- a/arch/arm64/kernel/cpufeature.c +++ b/arch/arm64/kernel/cpufeature.c @@ -2012,9 +2012,6 @@ bool cpu_supports_bbml3(void) { /* CPUs that support BBML3 but dont advertise through ID_AA64MMFR2_EL1 */ static const struct midr_range supports_bbml3_list[] = { - MIDR_REV_RANGE(MIDR_CORTEX_X4, 0, 3, 0xf), - MIDR_REV_RANGE(MIDR_NEOVERSE_V3, 0, 2, 0xf), - MIDR_REV_RANGE(MIDR_NEOVERSE_V3AE, 0, 2, 0xf), MIDR_ALL_VERSIONS(MIDR_NVIDIA_OLYMPUS), MIDR_ALL_VERSIONS(MIDR_NVIDIA_RIGEL), MIDR_ALL_VERSIONS(MIDR_AMPERE1), @@ -2208,6 +2205,18 @@ static bool can_trap_icv_dir_el1(const struct arm64_cpu_capabilities *entry, MIDR_ALL_VERSIONS(MIDR_APPLE_M2_AVALANCHE_PRO), MIDR_ALL_VERSIONS(MIDR_APPLE_M2_BLIZZARD_MAX), MIDR_ALL_VERSIONS(MIDR_APPLE_M2_AVALANCHE_MAX), + MIDR_ALL_VERSIONS(MIDR_APPLE_M3_SAWTOOTH), + MIDR_ALL_VERSIONS(MIDR_APPLE_M3_EVEREST), + MIDR_ALL_VERSIONS(MIDR_APPLE_M3_SAWTOOTH_PRO), + MIDR_ALL_VERSIONS(MIDR_APPLE_M3_EVEREST_PRO), + MIDR_ALL_VERSIONS(MIDR_APPLE_M3_SAWTOOTH_MAX), + MIDR_ALL_VERSIONS(MIDR_APPLE_M3_EVEREST_MAX), + MIDR_ALL_VERSIONS(MIDR_APPLE_M4_DONAN_ECORE), + MIDR_ALL_VERSIONS(MIDR_APPLE_M4_DONAN_PCORE), + MIDR_ALL_VERSIONS(MIDR_APPLE_A18_PRO_TAHITI_ECORE), + MIDR_ALL_VERSIONS(MIDR_APPLE_A18_PRO_TAHITI_PCORE), + MIDR_ALL_VERSIONS(MIDR_APPLE_M5_PRO_SOTRA_MCORE), + MIDR_ALL_VERSIONS(MIDR_APPLE_M5_PRO_SOTRA_PCORE), {}, }; struct arm_smccc_res res = {}; @@ -3076,6 +3085,13 @@ static const struct arm64_cpu_capabilities arm64_features[] = { .cpu_enable = cpu_enable_ls64_v, ARM64_CPUID_FIELDS(ID_AA64ISAR1_EL1, LS64, LS64_V) }, + { + .desc = "LS64_ACCDATA", + .capability = ARM64_HAS_LS64_ACCDATA, + .type = ARM64_CPUCAP_SYSTEM_FEATURE, + .matches = has_cpuid_feature, + ARM64_CPUID_FIELDS(ID_AA64ISAR1_EL1, LS64, LS64_ACCDATA) + }, #ifdef CONFIG_ARM64_LSUI { .desc = "Unprivileged Load Store Instructions (LSUI)", diff --git a/arch/arm64/kernel/machine_kexec.c b/arch/arm64/kernel/machine_kexec.c index 48f343704cb540..24366b5b325969 100644 --- a/arch/arm64/kernel/machine_kexec.c +++ b/arch/arm64/kernel/machine_kexec.c @@ -147,9 +147,12 @@ int machine_kexec_post_load(struct kimage *kimage) kimage->arch.ttbr1 = __pa(trans_pgd); kimage->arch.zero_page = __pa_symbol(empty_zero_page); + /* Copy the whole section: a kCFI hash may precede the entry point */ reloc_size = __relocate_new_kernel_end - __relocate_new_kernel_start; memcpy(reloc_code, __relocate_new_kernel_start, reloc_size); - kimage->arch.kern_reloc = __pa(reloc_code); + kimage->arch.kern_reloc = __pa(reloc_code) + + ((unsigned long)arm64_relocate_new_kernel - + (unsigned long)__relocate_new_kernel_start); rc = trans_pgd_idmap_page(&info, &kimage->arch.ttbr0, &kimage->arch.t0sz, reloc_code); if (rc) @@ -204,7 +207,7 @@ void machine_kexec(struct kimage *kimage) restart(is_hyp_nvhe(), kimage->start, kimage->arch.dtb_mem, 0, 0); } else { - void (*kernel_reloc)(struct kimage *kimage); + typeof(arm64_relocate_new_kernel) *kernel_reloc; if (is_hyp_nvhe()) __hyp_set_vectors(kimage->arch.el2_vectors); diff --git a/arch/arm64/kernel/module-plts.c b/arch/arm64/kernel/module-plts.c index 7afd370da9f48f..758b2ec0ebc305 100644 --- a/arch/arm64/kernel/module-plts.c +++ b/arch/arm64/kernel/module-plts.c @@ -76,11 +76,20 @@ u64 module_emit_plt_entry(struct module *mod, Elf64_Shdr *sechdrs, int i = pltsec->plt_num_entries; int j = i - 1; u64 val = sym->st_value + rela->r_addend; + struct plt_entry entry; if (is_forbidden_offset_for_adrp(&plt[i].adrp)) i++; - plt[i] = get_plt_entry(val, &plt[i]); + /* + * The section has plt_max_entries + 1 slots; the last one is where a + * duplicate of the final entry is built before being discarded. + */ + if (WARN_ON_ONCE(i > pltsec->plt_max_entries)) + return 0; + + entry = get_plt_entry(val, &plt[i]); + module_write_place(&plt[i], &entry, sizeof(entry), mod); /* * Check if the entry we just created is a duplicate. Given that the @@ -107,13 +116,14 @@ u64 module_emit_veneer_for_adrp(struct module *mod, Elf64_Shdr *sechdrs, int i = pltsec->plt_num_entries++; u32 br; int rd; - - if (WARN_ON(pltsec->plt_num_entries > pltsec->plt_max_entries)) - return 0; + struct plt_entry entry; if (is_forbidden_offset_for_adrp(&plt[i].adrp)) i = pltsec->plt_num_entries++; + if (WARN_ON_ONCE(pltsec->plt_num_entries > pltsec->plt_max_entries)) + return 0; + /* get the destination register of the ADRP instruction */ rd = aarch64_insn_decode_register(AARCH64_INSN_REGTYPE_RD, le32_to_cpup((__le32 *)loc)); @@ -121,8 +131,9 @@ u64 module_emit_veneer_for_adrp(struct module *mod, Elf64_Shdr *sechdrs, br = aarch64_insn_gen_branch_imm((u64)&plt[i].br, (u64)loc + 4, AARCH64_INSN_BRANCH_NOLINK); - plt[i] = __get_adrp_add_pair(val, (u64)&plt[i], rd); - plt[i].br = cpu_to_le32(br); + entry = __get_adrp_add_pair(val, (u64)&plt[i], rd); + entry.br = cpu_to_le32(br); + module_write_place(&plt[i], &entry, sizeof(entry), mod); return (u64)&plt[i]; } diff --git a/arch/arm64/kernel/module.c b/arch/arm64/kernel/module.c index 24adb581af0eb2..9ecefc55fb48d6 100644 --- a/arch/arm64/kernel/module.c +++ b/arch/arm64/kernel/module.c @@ -18,6 +18,7 @@ #include #include #include +#include #include #include @@ -49,14 +50,20 @@ static u64 do_reloc(enum aarch64_reloc_op reloc_op, __le32 *place, u64 val) return 0; } -#define WRITE_PLACE(place, val, mod) do { \ - __typeof__(val) __val = (val); \ - \ - if (mod->state == MODULE_STATE_UNFORMED) \ - *(place) = __val; \ - else \ - aarch64_insn_copy(place, &(__val), sizeof(*place)); \ -} while (0) +/* + * Write @len bytes from @val to @place within a module. While the module is + * MODULE_STATE_UNFORMED the destination is writable and a plain copy is used; + * once the module is fully formed the region is read-only and executable, so + * the write is routed through the text-poke API. + */ +void module_write_place(void *place, void *val, size_t len, + struct module *mod) +{ + if (mod->state == MODULE_STATE_UNFORMED) + memcpy(place, val, len); + else + aarch64_insn_copy(place, val, len); +} static int reloc_data(enum aarch64_reloc_op op, void *place, u64 val, int len, struct module *me) @@ -76,8 +83,10 @@ static int reloc_data(enum aarch64_reloc_op op, void *place, u64 val, int len, */ switch (len) { - case 16: - WRITE_PLACE((s16 *)place, sval, me); + case 16: { + s16 v = sval; + + module_write_place(place, &v, sizeof(v), me); switch (op) { case RELOC_OP_ABS: if (sval < 0 || sval > U16_MAX) @@ -92,8 +101,11 @@ static int reloc_data(enum aarch64_reloc_op op, void *place, u64 val, int len, return 0; } break; - case 32: - WRITE_PLACE((s32 *)place, sval, me); + } + case 32: { + s32 v = sval; + + module_write_place(place, &v, sizeof(v), me); switch (op) { case RELOC_OP_ABS: if (sval < 0 || sval > U32_MAX) @@ -108,9 +120,13 @@ static int reloc_data(enum aarch64_reloc_op op, void *place, u64 val, int len, return 0; } break; - case 64: - WRITE_PLACE((s64 *)place, sval, me); + } + case 64: { + s64 v = sval; + + module_write_place(place, &v, sizeof(v), me); break; + } default: pr_err("Invalid length (%d) for data relocation\n", len); return 0; @@ -130,6 +146,7 @@ static int reloc_insn_movw(enum aarch64_reloc_op op, __le32 *place, u64 val, u64 imm; s64 sval; u32 insn = le32_to_cpu(*place); + __le32 v; sval = do_reloc(op, place, val); imm = sval >> lsb; @@ -157,7 +174,9 @@ static int reloc_insn_movw(enum aarch64_reloc_op op, __le32 *place, u64 val, /* Update the instruction with the new encoding. */ insn = aarch64_insn_encode_immediate(AARCH64_INSN_IMM_16, insn, imm); - WRITE_PLACE(place, cpu_to_le32(insn), me); + v = cpu_to_le32(insn); + + module_write_place(place, &v, sizeof(v), me); if (imm > U16_MAX) return -ERANGE; @@ -172,6 +191,7 @@ static int reloc_insn_imm(enum aarch64_reloc_op op, __le32 *place, u64 val, u64 imm, imm_mask; s64 sval; u32 insn = le32_to_cpu(*place); + __le32 v; /* Calculate the relocation value. */ sval = do_reloc(op, place, val); @@ -183,7 +203,9 @@ static int reloc_insn_imm(enum aarch64_reloc_op op, __le32 *place, u64 val, /* Update the instruction's immediate field. */ insn = aarch64_insn_encode_immediate(imm_type, insn, imm); - WRITE_PLACE(place, cpu_to_le32(insn), me); + v = cpu_to_le32(insn); + + module_write_place(place, &v, sizeof(v), me); /* * Extract the upper value bits (including the sign bit) and @@ -205,6 +227,7 @@ static int reloc_insn_adrp(struct module *mod, Elf64_Shdr *sechdrs, __le32 *place, u64 val, struct module *me) { u32 insn; + __le32 v; if (!is_forbidden_offset_for_adrp(place)) return reloc_insn_imm(RELOC_OP_PAGE, place, val, 12, 21, @@ -224,7 +247,9 @@ static int reloc_insn_adrp(struct module *mod, Elf64_Shdr *sechdrs, AARCH64_INSN_BRANCH_NOLINK); } - WRITE_PLACE(place, cpu_to_le32(insn), me); + v = cpu_to_le32(insn); + + module_write_place(place, &v, sizeof(v), me); return 0; } diff --git a/arch/arm64/kernel/mte.c b/arch/arm64/kernel/mte.c index 31f5c6b0510e72..850bcee21e7709 100644 --- a/arch/arm64/kernel/mte.c +++ b/arch/arm64/kernel/mte.c @@ -36,6 +36,14 @@ DEFINE_STATIC_KEY_FALSE(mte_async_or_asymm_mode); EXPORT_SYMBOL_GPL(mte_async_or_asymm_mode); #endif +void mte_clear_folio_tags(struct folio *folio) +{ + unsigned long i; + + for (i = 0; i < folio_nr_pages(folio); i++) + mte_clear_page_tags(page_address(folio_page(folio, i))); +} + void mte_sync_tags(pte_t pte, unsigned int nr_pages) { struct page *page = pte_page(pte); @@ -43,12 +51,9 @@ void mte_sync_tags(pte_t pte, unsigned int nr_pages) unsigned long i; if (folio_test_hugetlb(folio)) { - unsigned long nr = folio_nr_pages(folio); - - /* Hugetlb MTE flags are set for head page only */ + /* A hugetlb folio is marked tagged as a whole, so clear every page */ if (folio_try_hugetlb_mte_tagging(folio)) { - for (i = 0; i < nr; i++, page++) - mte_clear_page_tags(page_address(page)); + mte_clear_folio_tags(folio); folio_set_hugetlb_mte_tagged(folio); } diff --git a/arch/arm64/kernel/pi/idreg-override.c b/arch/arm64/kernel/pi/idreg-override.c index acaf56234973b9..2f132b44ef27db 100644 --- a/arch/arm64/kernel/pi/idreg-override.c +++ b/arch/arm64/kernel/pi/idreg-override.c @@ -174,6 +174,7 @@ static const struct ftr_set_desc isar1 __prel64_initconst = { .name = "id_aa64isar1", .override = &id_aa64isar1_override, .fields = { + FIELD("ls64", ID_AA64ISAR1_EL1_LS64_SHIFT, NULL), FIELD("gpi", ID_AA64ISAR1_EL1_GPI_SHIFT, NULL), FIELD("gpa", ID_AA64ISAR1_EL1_GPA_SHIFT, NULL), FIELD("api", ID_AA64ISAR1_EL1_API_SHIFT, NULL), @@ -254,6 +255,7 @@ static const struct { "id_aa64isar1.gpi=0 id_aa64isar1.gpa=0 " "id_aa64isar1.api=0 id_aa64isar1.apa=0 " "id_aa64isar2.gpa3=0 id_aa64isar2.apa3=0" }, + { "arm64.nols64", "id_aa64isar1.ls64=0" }, { "arm64.nomops", "id_aa64isar2.mops=0" }, { "arm64.nowfxt", "id_aa64isar2.wfxt=0" }, { "arm64.nomte", "id_aa64pfr1.mte=0" }, diff --git a/arch/arm64/kernel/pi/map_kernel.c b/arch/arm64/kernel/pi/map_kernel.c index fb44cbdd2f2927..f9338257adb7dc 100644 --- a/arch/arm64/kernel/pi/map_kernel.c +++ b/arch/arm64/kernel/pi/map_kernel.c @@ -211,6 +211,7 @@ static void *__init map_fdt(phys_addr_t fdt) fdt, PAGE_KERNEL, IDMAP_ROOT_LEVEL, (pte_t *)init_idmap_pg_dir, false, 0); dsb(ishst); + isb(); return (void *)fdt; } diff --git a/arch/arm64/kernel/probes/uprobes.c b/arch/arm64/kernel/probes/uprobes.c index 2a9b0bc083a3b4..1e6ac4785a5338 100644 --- a/arch/arm64/kernel/probes/uprobes.c +++ b/arch/arm64/kernel/probes/uprobes.c @@ -152,6 +152,12 @@ bool arch_uretprobe_is_alive(struct return_instance *ret, enum rp_check ctx, return regs->sp < ret->stack; } +bool arch_uprobe_regs_writable(int off, int size) +{ + /* From x0 to x30, sp, pc. */ + return off + size <= offsetof(struct pt_regs, pstate); +} + unsigned long arch_uretprobe_hijack_return_addr(unsigned long trampoline_vaddr, struct pt_regs *regs) diff --git a/arch/arm64/kernel/relocate_kernel.S b/arch/arm64/kernel/relocate_kernel.S index 6cb4209f5dab56..064db5856bba30 100644 --- a/arch/arm64/kernel/relocate_kernel.S +++ b/arch/arm64/kernel/relocate_kernel.S @@ -8,6 +8,7 @@ * Pasha Tatashin */ +#include #include #include @@ -32,11 +33,13 @@ * new image to its final location. To assure that the * arm64_relocate_new_kernel routine which does that copy is not overwritten, * all code and data needed by arm64_relocate_new_kernel must be between the - * symbols arm64_relocate_new_kernel and arm64_relocate_new_kernel_end. The - * machine_kexec() routine will copy arm64_relocate_new_kernel to the kexec + * symbols __relocate_new_kernel_start and __relocate_new_kernel_end. The + * machine_kexec_post_load() routine will copy that whole region to the kexec * safe memory that has been set up to be preserved during the copy operation. + * + * Called indirectly by machine_kexec(), this routine needs a kCFI type hash. */ -SYM_CODE_START(arm64_relocate_new_kernel) +SYM_TYPED_FUNC_START(arm64_relocate_new_kernel) /* * The kimage structure isn't allocated specially and may be clobbered * during relocation. We must load any values we need from it prior to @@ -98,4 +101,4 @@ SYM_CODE_START(arm64_relocate_new_kernel) mov x2, xzr mov x3, xzr br x28 /* Jumps from el1 */ -SYM_CODE_END(arm64_relocate_new_kernel) +SYM_FUNC_END(arm64_relocate_new_kernel) diff --git a/arch/arm64/kernel/vmlinux.lds.S b/arch/arm64/kernel/vmlinux.lds.S index 1869b44ae19095..c95243a8b24ec0 100644 --- a/arch/arm64/kernel/vmlinux.lds.S +++ b/arch/arm64/kernel/vmlinux.lds.S @@ -440,6 +440,7 @@ ASSERT(swapper_pg_dir - tramp_pg_dir == TRAMP_SWAPPER_OFFSET, ASSERT(__relocate_new_kernel_end - __relocate_new_kernel_start <= SZ_4K, "kexec relocation code is bigger than 4 KiB") ASSERT(KEXEC_CONTROL_PAGE_SIZE >= SZ_4K, "KEXEC_CONTROL_PAGE_SIZE is broken") -ASSERT(__relocate_new_kernel_start == arm64_relocate_new_kernel, - "kexec control page does not start with arm64_relocate_new_kernel") +ASSERT(arm64_relocate_new_kernel >= __relocate_new_kernel_start && + arm64_relocate_new_kernel < __relocate_new_kernel_end, + "kexec relocation code does not contain arm64_relocate_new_kernel") #endif diff --git a/arch/arm64/kvm/arm.c b/arch/arm64/kvm/arm.c index 157bf4b8120201..a148e80d0aef7c 100644 --- a/arch/arm64/kvm/arm.c +++ b/arch/arm64/kvm/arm.c @@ -128,11 +128,6 @@ bool is_kvm_arm_initialised(void) return kvm_arm_initialised; } -int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu) -{ - return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE; -} - int kvm_vm_ioctl_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) { @@ -1856,8 +1851,16 @@ static int __kvm_vcpu_set_target(struct kvm_vcpu *vcpu, bitmap_copy(kvm->arch.vcpu_features, &features, KVM_VCPU_MAX_FEATURES); ret = kvm_setup_vcpu(vcpu); - if (ret) + if (ret) { + /* Clear the bitmap and PMU if setup fails on the first vCPU to be initialized. */ + if (!test_bit(KVM_ARCH_FLAG_VCPU_FEATURES_CONFIGURED, &kvm->arch.flags)) { + bitmap_zero(kvm->arch.vcpu_features, KVM_VCPU_MAX_FEATURES); + kvm->arch.arm_pmu = NULL; + kvm->arch.nr_pmu_counters = 0; + } + goto out_unlock; + } /* Now we know what it is, we can reset it. */ kvm_reset_vcpu(vcpu); @@ -1999,7 +2002,7 @@ static int kvm_arm_vcpu_get_events(struct kvm_vcpu *vcpu, static int kvm_arm_vcpu_set_events(struct kvm_vcpu *vcpu, struct kvm_vcpu_events *events) { - int i; + int i, ret; /* check whether the reserved field is zero */ for (i = 0; i < ARRAY_SIZE(events->reserved); i++) @@ -2011,7 +2014,11 @@ static int kvm_arm_vcpu_set_events(struct kvm_vcpu *vcpu, if (events->exception.pad[i]) return -EINVAL; - return __kvm_arm_vcpu_set_events(vcpu, events); + vcpu_load(vcpu); + ret = __kvm_arm_vcpu_set_events(vcpu, events); + vcpu_put(vcpu); + + return ret; } /* @@ -2457,10 +2464,12 @@ static void cpu_init_hyp_mode(void) } } -static void cpu_hyp_reset(void) +static int cpu_hyp_reset(void) { if (!is_kernel_in_hyp_mode()) - __hyp_reset_vectors(); + return __hyp_reset_vectors() ? -EPERM : 0; + + return 0; } /* @@ -2511,32 +2520,38 @@ static void cpu_hyp_init_features(void) kvm_timer_init_vhe(); kvm_debug_init_vhe(); } - - if (vgic_present) - kvm_vgic_init_cpu_hardware(); } static void cpu_hyp_reinit(void) { - cpu_hyp_reset(); - cpu_hyp_init_context(); - cpu_hyp_init_features(); + if (!cpu_hyp_reset()) { + cpu_hyp_init_context(); + cpu_hyp_init_features(); + } else if (WARN_ON(!__this_cpu_read(kvm_hyp_initialized))) { + return; + } + + /* + * Even if the hypervisor didn't allow resetting the vectors we can + * reset the LRs. + */ + if (vgic_present) + kvm_vgic_init_cpu_hardware(); } static void cpu_hyp_init(void *discard) { - if (!__this_cpu_read(kvm_hyp_initialized)) { - cpu_hyp_reinit(); - __this_cpu_write(kvm_hyp_initialized, 1); - } + cpu_hyp_reinit(); + __this_cpu_write(kvm_hyp_initialized, 1); } static void cpu_hyp_uninit(void *discard) { - if (!is_protected_kvm_enabled() && __this_cpu_read(kvm_hyp_initialized)) { - cpu_hyp_reset(); + if (!__this_cpu_read(kvm_hyp_initialized)) + return; + + if (!cpu_hyp_reset()) __this_cpu_write(kvm_hyp_initialized, 0); - } } int kvm_arch_enable_virtualization_cpu(void) @@ -2564,8 +2579,7 @@ void kvm_arch_disable_virtualization_cpu(void) kvm_timer_cpu_down(); kvm_vgic_cpu_down(); - if (!is_protected_kvm_enabled()) - cpu_hyp_uninit(NULL); + cpu_hyp_uninit(NULL); } #ifdef CONFIG_CPU_PM @@ -2608,13 +2622,11 @@ static struct notifier_block hyp_init_cpu_pm_nb = { static void __init hyp_cpu_pm_init(void) { - if (!is_protected_kvm_enabled()) - cpu_pm_register_notifier(&hyp_init_cpu_pm_nb); + cpu_pm_register_notifier(&hyp_init_cpu_pm_nb); } static void __init hyp_cpu_pm_exit(void) { - if (!is_protected_kvm_enabled()) - cpu_pm_unregister_notifier(&hyp_init_cpu_pm_nb); + cpu_pm_unregister_notifier(&hyp_init_cpu_pm_nb); } #else static inline void __init hyp_cpu_pm_init(void) @@ -2737,8 +2749,7 @@ static int __init init_subsystems(void) if (err) hyp_cpu_pm_exit(); - if (err || !is_protected_kvm_enabled()) - on_each_cpu(cpu_hyp_uninit, NULL, 1); + on_each_cpu(cpu_hyp_uninit, NULL, 1); return err; } diff --git a/arch/arm64/kvm/config.c b/arch/arm64/kvm/config.c index adaf26ab93b857..6f668148ccc11d 100644 --- a/arch/arm64/kvm/config.c +++ b/arch/arm64/kvm/config.c @@ -219,7 +219,9 @@ struct reg_feat_map_desc { #define FEAT_CPA2 ID_AA64ISAR3_EL1, CPA, CPA2 #define FEAT_ASID2 ID_AA64MMFR4_EL1, ASID2, IMP #define FEAT_MEC ID_AA64MMFR3_EL1, MEC, IMP +#define FEAT_HAF ID_AA64MMFR1_EL1, HAFDBS, AF #define FEAT_HAFT ID_AA64MMFR1_EL1, HAFDBS, HAFT +#define FEAT_HAFDBS ID_AA64MMFR1_EL1, HAFDBS, DBM #define FEAT_HDBSS ID_AA64MMFR1_EL1, HAFDBS, HDBSS #define FEAT_HPDS ID_AA64MMFR1_EL1, HPDS, IMP #define FEAT_HPDS2 ID_AA64MMFR1_EL1, HPDS, HPDS2 @@ -232,6 +234,10 @@ struct reg_feat_map_desc { #define FEAT_MixedEndEL0 ID_AA64MMFR0_EL1, BIGENDEL0, IMP #define FEAT_MTE_ASYNC ID_AA64PFR1_EL1, MTE_frac, ASYNC #define FEAT_MTE_STORE_ONLY ID_AA64PFR2_EL1, MTESTOREONLY, IMP +#define FEAT_MTE_CANONICAL_TAGS ID_AA64PFR1_EL1, MTEX, MTE4 +#define FEAT_MTE_NO_ADDRESS_TAGS ID_AA64PFR1_EL1, MTEX, MTE4 +#define FEAT_E0PD ID_AA64MMFR2_EL1, E0PD, IMP +#define FEAT_SVE ID_AA64PFR0_EL1, SVE, IMP #define FEAT_PAN ID_AA64MMFR1_EL1, PAN, IMP #define FEAT_PAN3 ID_AA64MMFR1_EL1, PAN, PAN3 #define FEAT_SSBS ID_AA64PFR1_EL1, SSBS, IMP @@ -244,6 +250,19 @@ struct reg_feat_map_desc { #define FEAT_GCIE ID_AA64PFR2_EL1, GCIE, IMP #define FEAT_NV3 ID_AA64MMFR4_EL1, NV_frac, NV3 +static bool feat_asid16(struct kvm *kvm) +{ + return kvm_has_feat_enum(kvm, ID_AA64MMFR0_EL1, ASIDBITS, 16); +} + +static bool feat_mte_no_addr_tags_or_canonical_tags(struct kvm *kvm) +{ + bool no_addr_tags = kvm_has_feat(kvm, FEAT_MTE_NO_ADDRESS_TAGS); + bool canonical_tags = kvm_has_feat(kvm, FEAT_MTE_CANONICAL_TAGS); + + return no_addr_tags || canonical_tags; +} + static bool not_feat_aa64el3(struct kvm *kvm) { return !kvm_has_feat(kvm, FEAT_AA64EL3); @@ -256,11 +275,6 @@ static bool feat_nv2(struct kvm *kvm) kvm_has_feat(kvm, ID_AA64MMFR2_EL1, NV, NV2)); } -static bool feat_nv2_e2h0_ni(struct kvm *kvm) -{ - return feat_nv2(kvm) && !kvm_has_feat(kvm, FEAT_E2H0); -} - static bool feat_rasv1p1(struct kvm *kvm) { return (kvm_has_feat(kvm, ID_AA64PFR0_EL1, RAS, V1P1) || @@ -1034,7 +1048,7 @@ static const struct reg_bits_to_feat_map hcr_feat_map[] = { HCR_EL2_NV2 | HCR_EL2_NV, feat_nv2), - NEEDS_FEAT(HCR_EL2_NV1, feat_nv2_e2h0_ni), /* Missing from JSON */ + NEEDS_FEAT_FLAG(HCR_EL2_NV1, FORCE_RESx), /* Missing from JSON, RES0 as an IMPDEF choice */ NEEDS_FEAT(HCR_EL2_API | HCR_EL2_APK, feat_pauth), @@ -1080,6 +1094,91 @@ static const struct reg_bits_to_feat_map sctlr2_feat_map[] = { static const DECLARE_FEAT_MAP(sctlr2_desc, SCTLR2_EL1, sctlr2_feat_map, FEAT_SCTLR2); +static const struct reg_bits_to_feat_map vhe_tcr_el2_feat_map[] = { + NEEDS_FEAT(VHE_TCR_EL2_MTX1 | + VHE_TCR_EL2_MTX0, + feat_mte_no_addr_tags_or_canonical_tags), + NEEDS_FEAT(VHE_TCR_EL2_DS, feat_lpa2), + NEEDS_FEAT(VHE_TCR_EL2_TCMA1 | + VHE_TCR_EL2_TCMA0, + FEAT_MTE2), + NEEDS_FEAT(VHE_TCR_EL2_E0PD1 | + VHE_TCR_EL2_E0PD0, + FEAT_E0PD), + NEEDS_FEAT(VHE_TCR_EL2_NFD1 | + VHE_TCR_EL2_NFD0, + FEAT_SVE), + NEEDS_FEAT(VHE_TCR_EL2_TBID1 | + VHE_TCR_EL2_TBID0, + feat_pauth), + NEEDS_FEAT(VHE_TCR_EL2_HWU162 | + VHE_TCR_EL2_HWU161 | + VHE_TCR_EL2_HWU160 | + VHE_TCR_EL2_HWU159 | + VHE_TCR_EL2_HWU062 | + VHE_TCR_EL2_HWU061 | + VHE_TCR_EL2_HWU060 | + VHE_TCR_EL2_HWU059, + FEAT_HPDS2), + NEEDS_FEAT(VHE_TCR_EL2_HPD1 | + VHE_TCR_EL2_HPD0, + FEAT_HPDS), + NEEDS_FEAT(VHE_TCR_EL2_HD, FEAT_HAFDBS), + NEEDS_FEAT(VHE_TCR_EL2_HA, FEAT_HAF), + NEEDS_FEAT(VHE_TCR_EL2_AS, feat_asid16), + NEEDS_FEAT(VHE_TCR_EL2_TBI1 | + VHE_TCR_EL2_TBI0 | + VHE_TCR_EL2_IPS | + VHE_TCR_EL2_TG1 | + VHE_TCR_EL2_SH1 | + VHE_TCR_EL2_ORGN1 | + VHE_TCR_EL2_IRGN1 | + VHE_TCR_EL2_EPD1 | + VHE_TCR_EL2_A1 | + VHE_TCR_EL2_T1SZ | + VHE_TCR_EL2_TG0 | + VHE_TCR_EL2_SH0 | + VHE_TCR_EL2_ORGN0 | + VHE_TCR_EL2_IRGN0 | + VHE_TCR_EL2_EPD0 | + VHE_TCR_EL2_T0SZ, + FEAT_AA64EL2), + FORCE_RES0(VHE_TCR_EL2_RES0), + FORCE_RES1(VHE_TCR_EL2_RES1), +}; + +static const DECLARE_FEAT_MAP(vhe_tcr_el2_desc, VHE_TCR_EL2, + vhe_tcr_el2_feat_map, FEAT_AA64EL2); + +static const struct reg_bits_to_feat_map tcr_el2_feat_map[] = { + NEEDS_FEAT(TCR_EL2_MTX, + feat_mte_no_addr_tags_or_canonical_tags), + NEEDS_FEAT(TCR_EL2_DS, feat_lpa2), + NEEDS_FEAT(TCR_EL2_TCMA, FEAT_MTE2), + NEEDS_FEAT(TCR_EL2_TBID, feat_pauth), + NEEDS_FEAT(TCR_EL2_HWU62 | + TCR_EL2_HWU61 | + TCR_EL2_HWU60 | + TCR_EL2_HWU59, + FEAT_HPDS2), + NEEDS_FEAT(TCR_EL2_HPD, FEAT_HPDS), + NEEDS_FEAT(TCR_EL2_HD, FEAT_HAFDBS), + NEEDS_FEAT(TCR_EL2_HA, FEAT_HAF), + NEEDS_FEAT(TCR_EL2_TBI | + TCR_EL2_PS | + TCR_EL2_TG0 | + TCR_EL2_SH0 | + TCR_EL2_ORGN0 | + TCR_EL2_IRGN0 | + TCR_EL2_T0SZ, + FEAT_AA64EL2), + FORCE_RES0(TCR_EL2_RES0), + FORCE_RES1(TCR_EL2_RES1), +}; + +static const DECLARE_FEAT_MAP(tcr_el2_desc, TCR_EL2, + tcr_el2_feat_map, FEAT_AA64EL2); + static const struct reg_bits_to_feat_map tcr2_el2_feat_map[] = { NEEDS_FEAT_FLAG(TCR2_EL2_FNG1 | TCR2_EL2_FNG0 | @@ -1442,6 +1541,8 @@ void __init check_feature_map(void) check_reg_desc(&hcr_desc); check_reg_desc(&nvhcr_desc); check_reg_desc(&sctlr2_desc); + check_reg_desc(&vhe_tcr_el2_desc); + check_reg_desc(&tcr_el2_desc); check_reg_desc(&tcr2_el2_desc); check_reg_desc(&sctlr_el1_desc); check_reg_desc(&sctlr_el2_desc); @@ -1689,6 +1790,12 @@ struct resx get_reg_fixed_bits(struct kvm *kvm, enum vcpu_sysreg reg) case SCTLR2_EL2: resx = compute_reg_resx_bits(kvm, &sctlr2_desc, 0, 0); break; + case TCR_EL2: + if (kvm_has_feat(kvm, FEAT_E2H0)) + resx = compute_reg_resx_bits(kvm, &tcr_el2_desc, 0, 0); + else + resx = compute_reg_resx_bits(kvm, &vhe_tcr_el2_desc, 0, 0); + break; case TCR2_EL2: resx = compute_reg_resx_bits(kvm, &tcr2_el2_desc, 0, 0); break; diff --git a/arch/arm64/kvm/emulate-nested.c b/arch/arm64/kvm/emulate-nested.c index 2bec8166836148..39136a89d74bb6 100644 --- a/arch/arm64/kvm/emulate-nested.c +++ b/arch/arm64/kvm/emulate-nested.c @@ -889,6 +889,9 @@ static const struct encoding_to_trap_config encoding_to_cgt[] __initconst = { SR_TRAP(SYS_PMSCR_EL2, CGT_HCR_NV), SR_TRAP(SYS_MAIR_EL2, CGT_HCR_NV), SR_TRAP(SYS_AMAIR_EL2, CGT_HCR_NV), + SR_TRAP(SYS_PIR_EL2, CGT_HCR_NV), + SR_TRAP(SYS_PIRE0_EL2, CGT_HCR_NV), + SR_TRAP(SYS_POR_EL2, CGT_HCR_NV), SR_TRAP(SYS_MPAMHCR_EL2, CGT_HCR_NV), SR_TRAP(SYS_MPAMVPMV_EL2, CGT_HCR_NV), SR_TRAP(SYS_MPAM2_EL2, CGT_HCR_NV), @@ -939,8 +942,10 @@ static const struct encoding_to_trap_config encoding_to_cgt[] __initconst = { sys_reg(3, 5, 14, 1, 0), CGT_HCR_NV), SR_TRAP(SYS_CNTP_CTL_EL02, CGT_CNTHCTL_EL1NVPCT), SR_TRAP(SYS_CNTP_CVAL_EL02, CGT_CNTHCTL_EL1NVPCT), + SR_TRAP(SYS_CNTP_TVAL_EL02, CGT_HCR_NV), SR_TRAP(SYS_CNTV_CTL_EL02, CGT_CNTHCTL_EL1NVVCT), SR_TRAP(SYS_CNTV_CVAL_EL02, CGT_CNTHCTL_EL1NVVCT), + SR_TRAP(SYS_CNTV_TVAL_EL02, CGT_HCR_NV), SR_TRAP(OP_AT_S1E2R, CGT_HCR_NV), SR_TRAP(OP_AT_S1E2W, CGT_HCR_NV), SR_TRAP(OP_AT_S12E1R, CGT_HCR_NV), @@ -2429,7 +2434,7 @@ int __init populate_nv_trap_config(void) } int __init populate_sysreg_config(const struct sys_reg_desc *sr, - unsigned int idx) + unsigned int idx, bool needs_nv_trap) { union trap_config tc; u32 encoding; @@ -2447,6 +2452,9 @@ int __init populate_sysreg_config(const struct sys_reg_desc *sr, encoding = sys_reg(sr->Op0, sr->Op1, sr->CRn, sr->CRm, sr->Op2); tc = get_trap_config(encoding); + if (needs_nv_trap && !tc.val) + kvm_err("sysreg %s has no NV trap configuration\n", sr->name); + if (tc.sri) { kvm_err("sysreg %s (%d) duplicate entry (%d)\n", sr->name, idx - 1, tc.sri); diff --git a/arch/arm64/kvm/guest.c b/arch/arm64/kvm/guest.c index 878ea4500c5c55..ba4570c52a9162 100644 --- a/arch/arm64/kvm/guest.c +++ b/arch/arm64/kvm/guest.c @@ -1059,12 +1059,15 @@ int kvm_vm_ioctl_mte_copy_tags(struct kvm *kvm, /* * Only locking to serialise with a concurrent * __set_ptes() in the VMM but still overriding the - * tags, hence ignoring the return value. + * tags. A hugetlb folio is marked tagged as a whole, + * so its first tagging clears every page. */ - if (folio_test_hugetlb(folio)) - folio_try_hugetlb_mte_tagging(folio); - else + if (folio_test_hugetlb(folio)) { + if (folio_try_hugetlb_mte_tagging(folio)) + mte_clear_folio_tags(folio); + } else { try_page_mte_tagging(page); + } num_tags = mte_copy_tags_from_user(maddr, tags, MTE_GRANULES_PER_PAGE); diff --git a/arch/arm64/kvm/hyp/include/hyp/fault.h b/arch/arm64/kvm/hyp/include/hyp/fault.h index fc573fc767b0e7..741ea12be07df8 100644 --- a/arch/arm64/kvm/hyp/include/hyp/fault.h +++ b/arch/arm64/kvm/hyp/include/hyp/fault.h @@ -38,8 +38,9 @@ static inline bool __translate_far_to_hpfar(u64 far, u64 *hpfar) * saved the guest context yet, and we may return early... */ par = read_sysreg_par(); - ret = system_supports_poe() ? __kvm_at(OP_AT_S1E1A, far) : - __kvm_at(OP_AT_S1E1R, far); + ret = system_supports_poe() || system_supports_pie() ? + __kvm_at(OP_AT_S1E1A, far) : + __kvm_at(OP_AT_S1E1R, far); if (!ret) tmp = read_sysreg_par(); else diff --git a/arch/arm64/kvm/hyp/include/hyp/switch.h b/arch/arm64/kvm/hyp/include/hyp/switch.h index e0c55644224cb2..ec619d1049c723 100644 --- a/arch/arm64/kvm/hyp/include/hyp/switch.h +++ b/arch/arm64/kvm/hyp/include/hyp/switch.h @@ -330,7 +330,7 @@ static inline void __deactivate_traps_mpam(void) * Just like for HCR_EL2, we can't let the guest mess with some of the * basics we rely on in HCRX_EL2. However, the major difference is that * HCRX_EL2 only affects EL1, and never EL2 (sudden outburst of sanity, I - * guess). So it is always the guest inflicting it on its own guestx. + * guess). So it is always the guest inflicting it on its own guest. * * Things we don't want to let the guest control are: * @@ -339,10 +339,14 @@ static inline void __deactivate_traps_mpam(void) * - PTTWI: Similarly, it is for us to decide whether Reduced Coherency for * the PTW is a thing. It really isn't. * + * - MCE2: FEAT_MOPS generated exceptions for Option-{A,B} interoperability + * are always handled on the host and not forwarded to a guest hypervisor + * in order to give the (poor) illusion of a homogeneous system. + * * - EnIDCP128: We don't allow IMPDEF sysregs -- full stop. */ #define NV_HCRX_GUEST_EXCLUDE (HCRX_EL2_TMEA | HCRX_EL2_PTTWI | \ - HCRX_EL2_EnIDCP128) + HCRX_EL2_MCE2 | HCRX_EL2_EnIDCP128) static inline void __activate_traps_common(struct kvm_vcpu *vcpu) { @@ -843,8 +847,22 @@ static inline bool kvm_hyp_handle_cp15_32(struct kvm_vcpu *vcpu, u64 *exit_code) static inline bool kvm_hyp_handle_memory_fault(struct kvm_vcpu *vcpu, u64 *exit_code) { - if (!__populate_fault_info(vcpu)) + if (!__populate_fault_info(vcpu)) { + /* + * The AT couldn't resolve the IPA, typically because its + * stage-1 walk took a stage-2 fault, such as an Access flag + * fault on an aged page-table page. If the guest still has a + * cached translation for the VA, it won't take that fault + * itself, and would replay the same permission fault forever. + * Drop this VMID's TLB entries on this CPU, so that the replay + * walks the page tables and faults with a valid HPFAR_EL2. + */ + dsb(nsh); /* ensure that AT completed before issuing the TLBI */ + __tlbi(vmalls12e1); + dsb(nsh); + isb(); return true; + } return false; } diff --git a/arch/arm64/kvm/hyp/include/hyp/sysreg-sr.h b/arch/arm64/kvm/hyp/include/hyp/sysreg-sr.h index c382848d319479..4a008c8a696ba1 100644 --- a/arch/arm64/kvm/hyp/include/hyp/sysreg-sr.h +++ b/arch/arm64/kvm/hyp/include/hyp/sysreg-sr.h @@ -17,6 +17,7 @@ #include static inline bool ctxt_has_s1poe(struct kvm_cpu_context *ctxt); +static inline bool ctxt_has_accdata(struct kvm_cpu_context *ctxt); static inline struct kvm_vcpu *ctxt_to_vcpu(struct kvm_cpu_context *ctxt) { @@ -67,6 +68,13 @@ static inline void __sysreg_save_user_state(struct kvm_cpu_context *ctxt) { ctxt_sys_reg(ctxt, TPIDR_EL0) = read_sysreg(tpidr_el0); ctxt_sys_reg(ctxt, TPIDRRO_EL0) = read_sysreg(tpidrro_el0); + + /* + * Despite the appearances, ACCDATA_EL1 is part of the EL0 + * context, as it can only be used using ST64BV0. + */ + if (ctxt_has_accdata(ctxt)) + ctxt_sys_reg(ctxt, ACCDATA_EL1) = read_sysreg_s(SYS_ACCDATA_EL1); } static inline bool ctxt_has_mte(struct kvm_cpu_context *ctxt) @@ -131,6 +139,18 @@ static inline bool ctxt_has_sctlr2(struct kvm_cpu_context *ctxt) return kvm_has_sctlr2(kern_hyp_va(vcpu->kvm)); } +static inline bool ctxt_has_accdata(struct kvm_cpu_context *ctxt) +{ + struct kvm_vcpu *vcpu; + + /* The host never uses ACCDATA_EL1 */ + if (!cpus_have_final_cap(ARM64_HAS_LS64_ACCDATA) || !ctxt_is_guest(ctxt)) + return false; + + vcpu = ctxt_to_vcpu(ctxt); + return kvm_has_feat(kern_hyp_va(vcpu->kvm), ID_AA64ISAR1_EL1, LS64, LS64_ACCDATA); +} + static inline void __sysreg_save_el1_state(struct kvm_cpu_context *ctxt) { ctxt_sys_reg(ctxt, SCTLR_EL1) = read_sysreg_el1(SYS_SCTLR); @@ -210,6 +230,9 @@ static inline void __sysreg_restore_user_state(struct kvm_cpu_context *ctxt) { write_sysreg(ctxt_sys_reg(ctxt, TPIDR_EL0), tpidr_el0); write_sysreg(ctxt_sys_reg(ctxt, TPIDRRO_EL0), tpidrro_el0); + + if (ctxt_has_accdata(ctxt)) + write_sysreg_s(ctxt_sys_reg(ctxt, ACCDATA_EL1), SYS_ACCDATA_EL1); } static inline void __sysreg_restore_el1_state(struct kvm_cpu_context *ctxt, diff --git a/arch/arm64/kvm/hyp/include/nvhe/early_alloc.h b/arch/arm64/kvm/hyp/include/nvhe/early_alloc.h index dc61aaa56f3195..462883c4e3253d 100644 --- a/arch/arm64/kvm/hyp/include/nvhe/early_alloc.h +++ b/arch/arm64/kvm/hyp/include/nvhe/early_alloc.h @@ -7,7 +7,7 @@ void hyp_early_alloc_init(void *virt, unsigned long size); unsigned long hyp_early_alloc_nr_used_pages(void); void *hyp_early_alloc_page(void *arg); -void *hyp_early_alloc_contig(unsigned int nr_pages); +void *hyp_early_alloc_contig(unsigned long nr_pages); extern struct kvm_pgtable_mm_ops hyp_early_alloc_mm_ops; diff --git a/arch/arm64/kvm/hyp/include/nvhe/gfp.h b/arch/arm64/kvm/hyp/include/nvhe/gfp.h index 3766333bace966..3a428dc40b1490 100644 --- a/arch/arm64/kvm/hyp/include/nvhe/gfp.h +++ b/arch/arm64/kvm/hyp/include/nvhe/gfp.h @@ -29,6 +29,6 @@ void hyp_get_page(struct hyp_pool *pool, void *addr); void hyp_put_page(struct hyp_pool *pool, void *addr); /* Used pages cannot be freed */ -int hyp_pool_init(struct hyp_pool *pool, u64 pfn, unsigned int nr_pages, - unsigned int reserved_pages); +int hyp_pool_init(struct hyp_pool *pool, u64 pfn, unsigned long nr_pages, + unsigned long reserved_pages); #endif /* __KVM_HYP_GFP_H */ diff --git a/arch/arm64/kvm/hyp/nvhe/early_alloc.c b/arch/arm64/kvm/hyp/nvhe/early_alloc.c index 00de04153cc648..9fef0c7d2185e4 100644 --- a/arch/arm64/kvm/hyp/nvhe/early_alloc.c +++ b/arch/arm64/kvm/hyp/nvhe/early_alloc.c @@ -21,7 +21,7 @@ unsigned long hyp_early_alloc_nr_used_pages(void) return (cur - base) >> PAGE_SHIFT; } -void *hyp_early_alloc_contig(unsigned int nr_pages) +void *hyp_early_alloc_contig(unsigned long nr_pages) { unsigned long size = (nr_pages << PAGE_SHIFT); void *ret = (void *)cur; diff --git a/arch/arm64/kvm/hyp/nvhe/hyp-main.c b/arch/arm64/kvm/hyp/nvhe/hyp-main.c index 179d7c8277b883..0c023ee0cf42a8 100644 --- a/arch/arm64/kvm/hyp/nvhe/hyp-main.c +++ b/arch/arm64/kvm/hyp/nvhe/hyp-main.c @@ -690,6 +690,16 @@ static void sync_debug_state(struct pkvm_hyp_vcpu *hyp_vcpu) host_vcpu->arch.external_debug_state = hyp_vcpu->vcpu.arch.external_debug_state; } +#ifdef CONFIG_HW_PERF_EVENTS +static void flush_pmu_state(struct pkvm_hyp_vcpu *hyp_vcpu) +{ + if (!pkvm_hyp_vcpu_is_protected(hyp_vcpu)) + hyp_vcpu->vcpu.arch.pmu.events = hyp_vcpu->host_vcpu->arch.pmu.events; +} +#else +static void flush_pmu_state(struct pkvm_hyp_vcpu *hyp_vcpu) {} +#endif + static void flush_hyp_vcpu(struct pkvm_hyp_vcpu *hyp_vcpu) { struct kvm_vcpu *host_vcpu = hyp_vcpu->host_vcpu; @@ -699,6 +709,7 @@ static void flush_hyp_vcpu(struct pkvm_hyp_vcpu *hyp_vcpu) fpsimd_sve_flush(); flush_debug_state(hyp_vcpu); + flush_pmu_state(hyp_vcpu); /* * If we deal with a non-protected guest and the state is potentially @@ -1197,7 +1208,8 @@ DEFINE_KVM_HOST_HCALL0(u64, __vgic_v3_get_gic_config) DEFINE_KVM_HOST_HCALL0(void, __vgic_v3_init_lrs) { - __vgic_v3_init_lrs(); + if (hyp_gicv3_nr_lr) + __vgic_v3_init_lrs(); } DEFINE_KVM_HOST_HCALL(void, __vgic_v3_save_aprs, @@ -1547,7 +1559,6 @@ static const hcall_t host_hcall[] = { HANDLE_FUNC(__pkvm_create_private_mapping), HANDLE_FUNC(__pkvm_cpu_set_vector), HANDLE_FUNC(__kvm_enable_ssbs), - HANDLE_FUNC(__vgic_v3_init_lrs), HANDLE_FUNC(__vgic_v3_get_gic_config), HANDLE_FUNC(__pkvm_hyp_alloc_selftest), HANDLE_FUNC(__pkvm_prot_finalize), @@ -1569,6 +1580,7 @@ static const hcall_t host_hcall[] = { HANDLE_FUNC(__tracing_reset), HANDLE_FUNC(__tracing_enable_event), HANDLE_FUNC(__tracing_write_event), + HANDLE_FUNC(__vgic_v3_init_lrs), HANDLE_FUNC(__vgic_v3_save_aprs), HANDLE_FUNC(__vgic_v3_restore_vmcr_aprs), HANDLE_FUNC(__vgic_v5_make_resident), diff --git a/arch/arm64/kvm/hyp/nvhe/mem_protect.c b/arch/arm64/kvm/hyp/nvhe/mem_protect.c index d4c332a918035c..5cb1a1e1f2fe96 100644 --- a/arch/arm64/kvm/hyp/nvhe/mem_protect.c +++ b/arch/arm64/kvm/hyp/nvhe/mem_protect.c @@ -1210,6 +1210,14 @@ int hyp_pin_shared_mem(void *from, void *to) PAGE_HYP)); } + /* + * Only the first pin of a page maps it, and that CPU's barriers order + * only its own accesses. Order this CPU's accesses through the range + * after the mapping, whichever pin made it. + */ + dsb(ish); + isb(); + unlock: hyp_unlock_component(); host_unlock_component(); diff --git a/arch/arm64/kvm/hyp/nvhe/mm.c b/arch/arm64/kvm/hyp/nvhe/mm.c index b95d98cfe57df9..83b74c5223c385 100644 --- a/arch/arm64/kvm/hyp/nvhe/mm.c +++ b/arch/arm64/kvm/hyp/nvhe/mm.c @@ -316,6 +316,7 @@ static void *fixmap_map_slot(struct hyp_fixmap_slot *slot, phys_addr_t phys) pte |= kvm_phys_to_pte(phys) | KVM_PTE_VALID; WRITE_ONCE(*ptep, pte); dsb(ishst); + isb(); return (void *)slot->addr; } diff --git a/arch/arm64/kvm/hyp/nvhe/page_alloc.c b/arch/arm64/kvm/hyp/nvhe/page_alloc.c index 57f86aa0f82fcb..51460d420c94fa 100644 --- a/arch/arm64/kvm/hyp/nvhe/page_alloc.c +++ b/arch/arm64/kvm/hyp/nvhe/page_alloc.c @@ -229,12 +229,12 @@ void *hyp_alloc_pages(struct hyp_pool *pool, u8 order) return hyp_page_to_virt(p); } -int hyp_pool_init(struct hyp_pool *pool, u64 pfn, unsigned int nr_pages, - unsigned int reserved_pages) +int hyp_pool_init(struct hyp_pool *pool, u64 pfn, unsigned long nr_pages, + unsigned long reserved_pages) { phys_addr_t phys = hyp_pfn_to_phys(pfn); struct hyp_page *p; - int i; + unsigned long i; hyp_spin_lock_init(&pool->lock); pool->max_order = min(MAX_PAGE_ORDER, diff --git a/arch/arm64/kvm/hyp/nvhe/pkvm.c b/arch/arm64/kvm/hyp/nvhe/pkvm.c index fc0475f0877d19..6442200cd40bab 100644 --- a/arch/arm64/kvm/hyp/nvhe/pkvm.c +++ b/arch/arm64/kvm/hyp/nvhe/pkvm.c @@ -38,6 +38,9 @@ unsigned int kvm_host_sve_max_vl; */ static DEFINE_PER_CPU(struct pkvm_hyp_vcpu *, loaded_hyp_vcpu); +/* Per VM table entry, the vcpu_idx of the last vCPU of that VM loaded on this CPU. */ +static DEFINE_PER_CPU(unsigned int, last_vcpu_ran[KVM_MAX_PVMS]); + /* * The PKVM_HCR_EL2_HOST_{PVM,NPVM} bits of this value come from the host on * each entry, and a protected vCPU's TWI and TWE at vCPU load. @@ -271,6 +274,7 @@ struct pkvm_hyp_vcpu *pkvm_load_hyp_vcpu(pkvm_handle_t handle, { struct pkvm_hyp_vcpu *hyp_vcpu = NULL; struct pkvm_hyp_vm *hyp_vm; + unsigned int *last_ran; /* Cannot load a new vcpu without putting the old one first. */ if (__this_cpu_read(loaded_hyp_vcpu)) @@ -300,8 +304,18 @@ struct pkvm_hyp_vcpu *pkvm_load_hyp_vcpu(pkvm_handle_t handle, unlock: hyp_spin_unlock(&vm_table_lock); - if (hyp_vcpu) - __this_cpu_write(loaded_hyp_vcpu, hyp_vcpu); + if (!hyp_vcpu) + return NULL; + + __this_cpu_write(loaded_hyp_vcpu, hyp_vcpu); + + /* TLBs and I-cache are private to each vCPU, see vcpu_prepare_mmu(). */ + last_ran = this_cpu_ptr(&last_vcpu_ran[vm_handle_to_idx(handle)]); + if (*last_ran != vcpu_idx) { + __kvm_flush_cpu_context(hyp_vcpu->vcpu.arch.hw_mmu); + *last_ran = vcpu_idx; + } + return hyp_vcpu; } @@ -668,6 +682,7 @@ static int find_free_vm_table_entry(void) */ static int allocate_vm_table_entry(void) { + unsigned int cpu; int idx; hyp_assert_lock_held(&vm_table_lock); @@ -686,6 +701,9 @@ static int allocate_vm_table_entry(void) vm_table[idx] = RESERVED_ENTRY; + for (cpu = 0; cpu < hyp_nr_cpus; cpu++) + per_cpu(last_vcpu_ran[idx], cpu) = UINT_MAX; + return idx; } diff --git a/arch/arm64/kvm/hyp/nvhe/psci-relay.c b/arch/arm64/kvm/hyp/nvhe/psci-relay.c index e20db999e3288b..2863b4b90ea877 100644 --- a/arch/arm64/kvm/hyp/nvhe/psci-relay.c +++ b/arch/arm64/kvm/hyp/nvhe/psci-relay.c @@ -213,6 +213,10 @@ static void __noreturn __kvm_host_psci_cpu_entry(unsigned long pc, unsigned long write_sysreg_el1(INIT_SCTLR_EL1_MMU_OFF, SYS_SCTLR); write_sysreg(INIT_PSTATE_EL1, SPSR_EL2); + /* We can't trust the host to reset the LRs */ + if (hyp_gicv3_nr_lr) + __vgic_v3_init_lrs(); + trace_hyp_exit(host_ctxt, HYP_REASON_PSCI); __host_enter(host_ctxt); } diff --git a/arch/arm64/kvm/hyp/nvhe/switch.c b/arch/arm64/kvm/hyp/nvhe/switch.c index 89fb9dd351ad5d..c23fbd4ef2860c 100644 --- a/arch/arm64/kvm/hyp/nvhe/switch.c +++ b/arch/arm64/kvm/hyp/nvhe/switch.c @@ -175,6 +175,26 @@ static void __pmu_switch_to_host(struct kvm_vcpu *vcpu) #define __pmu_switch_to_host(v) do {} while (0) #endif +static u64 __pmu_stop_host_counters(struct kvm_vcpu *vcpu) +{ + u64 pmcr; + + if (!vcpu_is_protected(vcpu) || !system_supports_pmuv3()) + return 0; + + pmcr = read_sysreg(pmcr_el0); + if (pmcr & ARMV8_PMU_PMCR_E) + write_sysreg(pmcr & ~ARMV8_PMU_PMCR_E, pmcr_el0); + + return pmcr; +} + +static void __pmu_restore_host_counters(u64 pmcr) +{ + if (pmcr & ARMV8_PMU_PMCR_E) + write_sysreg(pmcr, pmcr_el0); +} + /* * Handler for protected VM MSR, MRS or System instruction execution in AArch64. * @@ -283,6 +303,7 @@ int __kvm_vcpu_run(struct kvm_vcpu *vcpu) struct kvm_s2_mmu *mmu; bool pmu_switch_needed; u64 exit_code; + u64 host_pmcr; /* * Having IRQs masked via PMR when entering the guest means the GIC @@ -300,6 +321,7 @@ int __kvm_vcpu_run(struct kvm_vcpu *vcpu) guest_ctxt = &vcpu->arch.ctxt; pmu_switch_needed = __pmu_switch_to_guest(vcpu); + host_pmcr = __pmu_stop_host_counters(vcpu); __sysreg_save_state_nvhe(host_ctxt); /* @@ -384,6 +406,8 @@ int __kvm_vcpu_run(struct kvm_vcpu *vcpu) if (pmu_switch_needed) __pmu_switch_to_host(vcpu); + __pmu_restore_host_counters(host_pmcr); + /* Returning to host will clear PSR.I, remask PMR if needed */ if (system_uses_irq_prio_masking()) gic_write_pmr(GIC_PRIO_IRQOFF); diff --git a/arch/arm64/kvm/hyp/nvhe/sys_regs.c b/arch/arm64/kvm/hyp/nvhe/sys_regs.c index 32e82653ebf7e7..e5502d5651b058 100644 --- a/arch/arm64/kvm/hyp/nvhe/sys_regs.c +++ b/arch/arm64/kvm/hyp/nvhe/sys_regs.c @@ -157,8 +157,8 @@ static const struct pvm_ftr_bits pvmid_aa64isar1[] = { MAX_FEAT(ID_AA64ISAR1_EL1, JSCVT, IMP), MAX_FEAT(ID_AA64ISAR1_EL1, FCMA, IMP), MAX_FEAT(ID_AA64ISAR1_EL1, LRCPC, LRCPC3), - MAX_FEAT(ID_AA64ISAR1_EL1, GPA, IMP), - MAX_FEAT(ID_AA64ISAR1_EL1, GPI, IMP), + MAX_FEAT_FUNC(ID_AA64ISAR1_EL1, GPA, IMP, vm_has_ptrauth), + MAX_FEAT_FUNC(ID_AA64ISAR1_EL1, GPI, IMP, vm_has_ptrauth), MAX_FEAT(ID_AA64ISAR1_EL1, FRINTTS, IMP), MAX_FEAT(ID_AA64ISAR1_EL1, SB, IMP), MAX_FEAT(ID_AA64ISAR1_EL1, SPECRES, COSP_RCTX), diff --git a/arch/arm64/kvm/hyp/pgtable.c b/arch/arm64/kvm/hyp/pgtable.c index 9c83837b184d35..94a59f29a20a21 100644 --- a/arch/arm64/kvm/hyp/pgtable.c +++ b/arch/arm64/kvm/hyp/pgtable.c @@ -414,7 +414,7 @@ static bool hyp_map_walker_try_leaf(const struct kvm_pgtable_visit_ctx *ctx, return true; if (!kvm_pte_valid(ctx->old)) ctx->mm_ops->get_page(ctx->ptep); - else if (WARN_ON((ctx->old ^ new) & ~KVM_PTE_LEAF_ATTR_HI_SW)) + else if ((ctx->old ^ new) & ~KVM_PTE_LEAF_ATTR_HI_SW) return false; smp_store_release(ctx->ptep, new); @@ -431,6 +431,14 @@ static int hyp_map_walker(const struct kvm_pgtable_visit_ctx *ctx, if (hyp_map_walker_try_leaf(ctx, data)) return 0; + /* + * A valid entry here is a leaf that conflicts with the request. + * Replacing a block with a table would need break-before-make, and + * would leave the rest of the block unmapped. + */ + if (kvm_pte_valid(ctx->old)) + return -EEXIST; + if (WARN_ON(ctx->level == KVM_PGTABLE_LAST_LEVEL)) return -EINVAL; diff --git a/arch/arm64/kvm/hyp/vhe/switch.c b/arch/arm64/kvm/hyp/vhe/switch.c index 3f2390a13173bd..5f7a46c4f516de 100644 --- a/arch/arm64/kvm/hyp/vhe/switch.c +++ b/arch/arm64/kvm/hyp/vhe/switch.c @@ -193,6 +193,13 @@ static void __deactivate_traps(struct kvm_vcpu *vcpu) if (!arm64_kernel_unmapped_at_el0()) host_vectors = __this_cpu_read(this_cpu_vector); write_sysreg(host_vectors, vbar_el1); + + /* + * We're now able to take MTE exceptions, make sure the VBAR_EL2 is + * set to the correct value. + */ + if (mte_disable_tco_entry(current)) + isb(); } NOKPROBE_SYMBOL(__deactivate_traps); diff --git a/arch/arm64/kvm/mmu.c b/arch/arm64/kvm/mmu.c index 1db10d8d6db737..86aa0b6fa8b571 100644 --- a/arch/arm64/kvm/mmu.c +++ b/arch/arm64/kvm/mmu.c @@ -176,7 +176,7 @@ static int kvm_mmu_split_huge_pages(struct kvm *kvm, phys_addr_t addr, static bool memslot_is_logging(struct kvm_memory_slot *memslot) { - return memslot->dirty_bitmap && !(memslot->flags & KVM_MEM_READONLY); + return kvm_slot_dirty_track_enabled(memslot) && !(memslot->flags & KVM_MEM_READONLY); } static int pkvm_flush_remote_tlbs(struct kvm *kvm) @@ -1617,10 +1617,9 @@ static void sanitise_mte_tags(struct kvm *kvm, kvm_pfn_t pfn, } if (folio_test_hugetlb(folio)) { - /* Hugetlb has MTE flags set on head page only */ + /* A hugetlb folio is marked tagged as a whole, so clear every page */ if (folio_try_hugetlb_mte_tagging(folio)) { - for (i = 0; i < nr_pages; i++, page++) - mte_clear_page_tags(page_address(page)); + mte_clear_folio_tags(folio); folio_set_hugetlb_mte_tagged(folio); } return; @@ -2129,7 +2128,7 @@ static int kvm_s2_fault_compute_prot(const struct kvm_s2_fault_desc *s2fd, if (s2fd->nested) *prot = adjust_nested_exec_perms(kvm, s2fd->nested, *prot); - if (!kvm_s2_fault_is_perm(s2fd) && !s2vi->map_non_cacheable && kvm_has_mte(kvm)) { + if (!s2vi->map_non_cacheable && kvm_has_mte(kvm)) { /* Check the VMM hasn't introduced a new disallowed VMA */ if (!s2vi->mte_allowed) return -EFAULT; @@ -2195,9 +2194,6 @@ static int kvm_s2_fault_map(const struct kvm_s2_fault_desc *s2fd, canonical_ipa = ALIGN_DOWN(canonical_ipa, mapping_size); } - if (!perm_fault_granule && !s2vi->map_non_cacheable && kvm_has_mte(kvm)) - sanitise_mte_tags(kvm, pfn, mapping_size); - /* * Under the premise of getting a FSC_PERM fault, we just need to relax * permissions only if mapping_size equals perm_fault_granule. Otherwise, @@ -2212,6 +2208,9 @@ static int kvm_s2_fault_map(const struct kvm_s2_fault_desc *s2fd, ret = KVM_PGT_FN(kvm_pgtable_stage2_relax_perms)(pgt, gfn_to_gpa(gfn), prot, flags); } else { + if (!s2vi->map_non_cacheable && kvm_has_mte(kvm)) + sanitise_mte_tags(kvm, pfn, mapping_size); + ret = KVM_PGT_FN(kvm_pgtable_stage2_map)(pgt, gfn_to_gpa(gfn), mapping_size, __pfn_to_phys(pfn), prot, memcache, flags); @@ -2232,11 +2231,7 @@ static int kvm_s2_fault_map(const struct kvm_s2_fault_desc *s2fd, kvm_fault_unlock(kvm); kfree(mapping); - /* - * Mark the page dirty only if the fault is handled successfully, - * making sure we adjust the canonical IPA if the mapping size has - * been updated (via a THP upgrade, for example). - */ + /* Mark the page dirty only if the fault is handled successfully. */ if (writable && !ret) mark_page_dirty_in_slot(kvm, s2fd->memslot, gpa_to_gfn(canonical_ipa)); diff --git a/arch/arm64/kvm/nested.c b/arch/arm64/kvm/nested.c index 4d83281a7a28b4..78d5b18dbd2d60 100644 --- a/arch/arm64/kvm/nested.c +++ b/arch/arm64/kvm/nested.c @@ -140,6 +140,14 @@ int kvm_vcpu_init_nested(struct kvm_vcpu *vcpu) kvm->arch.nested_mmus_size += S2_MMU_PER_VCPU; } + /* + * We can't rely on the S2 MMU staying the canonical one until + * the first run, as userspace can restore a nested context. + * Nuke the hw_mmu early to ensure that we pick the correct one + * at load time. + */ + vcpu->arch.hw_mmu = NULL; + return 0; } @@ -1875,6 +1883,17 @@ u64 limit_nv_id_reg(struct kvm *kvm, u32 reg, u64 val) /* Hide CNTPOFF if present */ val = ID_REG_LIMIT_FIELD_ENUM(val, ID_AA64MMFR0_EL1, ECV, IMP); + /* NV does not support FEAT_LPA2. */ + if (SYS_FIELD_GET(ID_AA64MMFR0_EL1, TGRAN4, val) == ID_AA64MMFR0_EL1_TGRAN4_52_BIT) { + val &= ~ID_AA64MMFR0_EL1_TGRAN4; + val |= SYS_FIELD_PREP_ENUM(ID_AA64MMFR0_EL1, TGRAN4, IMP); + } + + if (SYS_FIELD_GET(ID_AA64MMFR0_EL1, TGRAN16, val) == ID_AA64MMFR0_EL1_TGRAN16_52_BIT) { + val &= ~ID_AA64MMFR0_EL1_TGRAN16; + val |= SYS_FIELD_PREP_ENUM(ID_AA64MMFR0_EL1, TGRAN16, IMP); + } + /* Disallow unsupported S2 page sizes */ switch (PAGE_SIZE) { case SZ_64K: @@ -2090,6 +2109,10 @@ int kvm_init_nv_sysregs(struct kvm_vcpu *vcpu) resx = get_reg_fixed_bits(kvm, HFGITR2_EL2); set_sysreg_masks(kvm, HFGITR2_EL2, resx); + /* TCR_EL2 */ + resx = get_reg_fixed_bits(kvm, TCR_EL2); + set_sysreg_masks(kvm, TCR_EL2, resx); + /* TCR2_EL2 */ resx = get_reg_fixed_bits(kvm, TCR2_EL2); set_sysreg_masks(kvm, TCR2_EL2, resx); diff --git a/arch/arm64/kvm/pkvm.c b/arch/arm64/kvm/pkvm.c index 016997288fd233..fd0a0f26dffe74 100644 --- a/arch/arm64/kvm/pkvm.c +++ b/arch/arm64/kvm/pkvm.c @@ -316,6 +316,12 @@ static void __init _kvm_host_prot_finalize(void *arg) { int *err = arg; + /* + * After __pkvm_prot_finalize, access to the hypervisor copy of + * kvm_host_data is lost. Save it into the host-accessible version. + */ + *this_cpu_ptr(&kvm_host_data) = *this_cpu_ptr_nvhe_sym(kvm_host_data); + if (WARN_ON(kvm_call_hyp_nvhe(__pkvm_prot_finalize))) WRITE_ONCE(*err, -EINVAL); } diff --git a/arch/arm64/kvm/pmu-emul.c b/arch/arm64/kvm/pmu-emul.c index e2b28dbc0451b0..388a6244e7b242 100644 --- a/arch/arm64/kvm/pmu-emul.c +++ b/arch/arm64/kvm/pmu-emul.c @@ -1342,6 +1342,9 @@ void kvm_pmu_nested_transition(struct kvm_vcpu *vcpu) unsigned long mask; int i; + if (!vcpu->arch.pmu.created) + return; + mask = __vcpu_sys_reg(vcpu, PMCNTENSET_EL0); for_each_set_bit(i, &mask, 32) { struct kvm_pmc *pmc = kvm_vcpu_idx_to_pmc(vcpu, i); diff --git a/arch/arm64/kvm/sys_regs.c b/arch/arm64/kvm/sys_regs.c index c7d91138a6d49d..5555e17a771076 100644 --- a/arch/arm64/kvm/sys_regs.c +++ b/arch/arm64/kvm/sys_regs.c @@ -2914,6 +2914,15 @@ static unsigned int sve_el2_visibility(const struct kvm_vcpu *vcpu, return __el2_visibility(vcpu, rd, sve_visibility); } +static unsigned int accdata_visibility(const struct kvm_vcpu *vcpu, + const struct sys_reg_desc *rd) +{ + if (kvm_has_feat(vcpu->kvm, ID_AA64ISAR1_EL1, LS64, LS64_ACCDATA)) + return 0; + + return REG_HIDDEN; +} + static unsigned int vncr_el2_visibility(const struct kvm_vcpu *vcpu, const struct sys_reg_desc *rd) { @@ -3275,6 +3284,14 @@ static u64 reset_mdcr(struct kvm_vcpu *vcpu, const struct sys_reg_desc *r) return vcpu->kvm->arch.nr_pmu_counters; } +static u64 reset_tcr_el2(struct kvm_vcpu *vcpu, const struct sys_reg_desc *r) +{ + __vcpu_assign_sys_reg(vcpu, r->reg, + vcpu_has_feature(vcpu, KVM_ARM_VCPU_HAS_EL2_E2H0) ? + TCR_EL2_RES1 : VHE_TCR_EL2_RES1); + return __vcpu_sys_reg(vcpu, r->reg); +} + /* * Architected system registers. * Important: Must be sorted ascending by Op0, Op1, CRn, CRm, Op2 @@ -3601,7 +3618,8 @@ static const struct sys_reg_desc sys_reg_descs[] = { { SYS_DESC(SYS_CONTEXTIDR_EL1), access_vm_reg, reset_val, CONTEXTIDR_EL1, 0 }, { SYS_DESC(SYS_TPIDR_EL1), NULL, reset_unknown, TPIDR_EL1 }, - { SYS_DESC(SYS_ACCDATA_EL1), undef_access }, + { SYS_DESC(SYS_ACCDATA_EL1), undef_access, reset_val, ACCDATA_EL1, 0, + .visibility = accdata_visibility}, { SYS_DESC(SYS_SCXTNUM_EL1), undef_access }, @@ -3853,7 +3871,7 @@ static const struct sys_reg_desc sys_reg_descs[] = { EL2_REG(TTBR0_EL2, access_rw, reset_val, 0), EL2_REG(TTBR1_EL2, access_rw, reset_val, 0), - EL2_REG(TCR_EL2, access_rw, reset_val, TCR_EL2_RES1), + EL2_REG(TCR_EL2, access_rw, reset_tcr_el2, 0), EL2_REG_FILTERED(TCR2_EL2, access_rw, reset_val, TCR2_EL2_RES1, tcr2_el2_visibility), EL2_REG_VNCR(VTTBR_EL2, reset_val, 0), @@ -4098,6 +4116,17 @@ union tlbi_info { static void s2_mmu_unmap_range(struct kvm_s2_mmu *mmu, const union tlbi_info *info) { + u64 start = info->range.start; + u64 end = start + info->range.size; + + /* + * An L1 stage-2 block may be held in the shadow S2 as several smaller + * leaves, and R_TVTYQ requires the TLBI to invalidate all of them, so + * widen each end of the range to the L1 block containing it. + */ + start = ALIGN_DOWN(start, compute_tlb_inval_range(mmu, start >> 12)); + end = ALIGN(end, compute_tlb_inval_range(mmu, (end - 1) >> 12)); + /* * The unmap operation is allowed to drop the MMU lock and block, which * means that @mmu could be used for a different context than the one @@ -4121,7 +4150,7 @@ static void s2_mmu_unmap_range(struct kvm_s2_mmu *mmu, * the L1 needs to put its stage-2 in a consistent state before doing * the TLBI. */ - kvm_stage2_unmap_range(mmu, info->range.start, info->range.size, true); + kvm_stage2_unmap_range(mmu, start, end - start, true); } static bool handle_vmalls12e1is(struct kvm_vcpu *vcpu, struct sys_reg_params *p, @@ -4207,6 +4236,9 @@ static void s2_mmu_unmap_ipa(struct kvm_s2_mmu *mmu, max_size = compute_tlb_inval_range(mmu, info->ipa.addr); base_addr &= ~(max_size - 1); + if (base_addr >= kvm_phys_size(mmu)) + return; + /* * See comment in s2_mmu_unmap_range() for why this is allowed to * reschedule. @@ -5949,6 +5981,23 @@ int kvm_vcpu_finalize_sys_regs(struct kvm_vcpu *vcpu) return 0; } +/* Keep the nested virtualization traps in sync with the KVM traps. */ +static bool __init needs_nv_trap(const struct sys_reg_desc *r) +{ + /* op1 4 is the EL2 encodings, op1 5 the _EL12 and _EL02 aliases */ + if (r->Op1 != 4 && r->Op1 != 5) + return false; + + if (!r->access || + r->access == bad_vncr_trap || + r->access == trap_raz_wi || + r->access == bad_redir_trap || + r->access == undef_access) + return false; + + return true; +} + int __init kvm_sys_reg_table_init(void) { const struct sys_reg_desc *gicv3_regs, *gicv5_regs; @@ -5981,10 +6030,12 @@ int __init kvm_sys_reg_table_init(void) check_feature_map(); for (i = 0; !ret && i < ARRAY_SIZE(sys_reg_descs); i++) - ret = populate_sysreg_config(sys_reg_descs + i, i); + ret = populate_sysreg_config(sys_reg_descs + i, i, + needs_nv_trap(sys_reg_descs + i)); for (i = 0; !ret && i < ARRAY_SIZE(sys_insn_descs); i++) - ret = populate_sysreg_config(sys_insn_descs + i, i); + ret = populate_sysreg_config(sys_insn_descs + i, i, + needs_nv_trap(sys_insn_descs + i)); return ret; } diff --git a/arch/arm64/kvm/vgic/vgic-init.c b/arch/arm64/kvm/vgic/vgic-init.c index c9991e24cb6b74..7050e274b74200 100644 --- a/arch/arm64/kvm/vgic/vgic-init.c +++ b/arch/arm64/kvm/vgic/vgic-init.c @@ -519,7 +519,7 @@ int vgic_init(struct kvm *kvm) if (vgic_supports_direct_irqs(kvm)) { ret = vgic_v4_init(kvm); if (ret) - return ret; + goto out_free_spis; } } else { if (!dist->nr_spis) @@ -534,17 +534,24 @@ int vgic_init(struct kvm *kvm) kvm_vgic_vcpu_reset(vcpu); ret = kvm_vgic_setup_default_irq_routing(kvm); - if (ret) { - if (vgic_is_v5(kvm)) - vgic_v5_teardown(kvm); - - return ret; - } + if (ret) + goto out_teardown; vgic_debug_init(kvm); dist->initialized = true; return 0; + +out_teardown: + if (vgic_is_v5(kvm)) + vgic_v5_teardown(kvm); + else + vgic_v4_teardown(kvm); +out_free_spis: + kfree(dist->spis); + dist->spis = NULL; + + return ret; } static void kvm_vgic_dist_destroy(struct kvm *kvm) diff --git a/arch/arm64/kvm/vgic/vgic-its.c b/arch/arm64/kvm/vgic/vgic-its.c index 7e9b265b1f521c..5ce485485a1178 100644 --- a/arch/arm64/kvm/vgic/vgic-its.c +++ b/arch/arm64/kvm/vgic/vgic-its.c @@ -817,6 +817,38 @@ static u64 its_cmd_mask_field(u64 *its_cmd, int word, int shift, int size) #define its_cmd_get_target_addr(cmd) its_cmd_mask_field(cmd, 2, 16, 32) #define its_cmd_get_validbit(cmd) its_cmd_mask_field(cmd, 2, 63, 1) +/* + * Only an LPI on a vCPU's AP list can be in its list registers, which the + * exit path folds back, and that exit moves the LPI to its target vCPU if + * the target has changed: pause both. Clear an LPI on no AP list before + * dropping the lock, so that nothing can put it in a list register first. + * Must be called with the its_lock mutex held. + */ +static void vgic_its_clear_pending(struct vgic_irq *irq) +{ + struct kvm_vcpu *vcpu, *target; + + scoped_guard(raw_spinlock_irqsave, &irq->irq_lock) { + vcpu = irq->vcpu; + target = irq->target_vcpu; + if (!vcpu) + irq->pending_latch = false; + } + + if (vcpu) { + if (target != vcpu) + kvm_pause_vcpu(target); + kvm_pause_vcpu(vcpu); + + scoped_guard(raw_spinlock_irqsave, &irq->irq_lock) + irq->pending_latch = false; + + kvm_resume_vcpu(vcpu); + if (target != vcpu) + kvm_resume_vcpu(target); + } +} + /* * The DISCARD command frees an Interrupt Translation Table Entry (ITTE). * Must be called with the its_lock mutex held. @@ -833,36 +865,9 @@ static int vgic_its_cmd_handle_discard(struct kvm *kvm, struct vgic_its *its, struct its_device *device = find_its_device(its, device_id); int ite_esz = vgic_its_get_abi(its)->ite_esz; gpa_t gpa = device->itt_addr + ite->event_id * ite_esz; - struct vgic_irq *irq = ite->irq; - struct kvm_vcpu *vcpu, *target; vgic_its_invalidate_cache(its); - - /* - * Only an LPI on a vCPU's AP list can be in its list registers, - * which the exit path folds back, and that exit moves the LPI - * to its target vCPU if the target has changed: pause both. - */ - scoped_guard(raw_spinlock_irqsave, &irq->irq_lock) { - vcpu = irq->vcpu; - target = irq->target_vcpu; - } - - if (vcpu) { - if (target != vcpu) - kvm_pause_vcpu(target); - kvm_pause_vcpu(vcpu); - } - - scoped_guard(raw_spinlock_irqsave, &irq->irq_lock) - irq->pending_latch = false; - - if (vcpu) { - kvm_resume_vcpu(vcpu); - if (target != vcpu) - kvm_resume_vcpu(target); - } - + vgic_its_clear_pending(ite->irq); its_free_ite(kvm, ite); return vgic_its_write_entry_lock(its, gpa, 0ULL, ite); @@ -1307,10 +1312,10 @@ static int vgic_its_cmd_handle_clear(struct kvm *kvm, struct vgic_its *its, ite = find_ite(its, device_id, event_id); - if (!ite) + if (!ite || !its_is_collection_mapped(ite->collection)) return E_ITS_CLEAR_UNMAPPED_INTERRUPT; - ite->irq->pending_latch = false; + vgic_its_clear_pending(ite->irq); if (ite->irq->hw) return irq_set_irqchip_state(ite->irq->host_irq, @@ -1800,9 +1805,12 @@ static void vgic_mmio_write_its_ctlr(struct kvm *kvm, struct vgic_its *its, !(its->cbaser & GITS_CBASER_VALID))) goto out; + /* vgic_its_resolve_lpi() tests the enable bit and caches under its_lock. */ + mutex_lock(&its->its_lock); its->enabled = !!(val & GITS_CTLR_ENABLE); if (!its->enabled) vgic_its_invalidate_cache(its); + mutex_unlock(&its->its_lock); /* * Try to process any pending commands. This function bails out early diff --git a/arch/arm64/kvm/vgic/vgic-kvm-device.c b/arch/arm64/kvm/vgic/vgic-kvm-device.c index 1c205cb1361fd5..f8869dabd3657d 100644 --- a/arch/arm64/kvm/vgic/vgic-kvm-device.c +++ b/arch/arm64/kvm/vgic/vgic-kvm-device.c @@ -280,9 +280,11 @@ static int vgic_set_common_attr(struct kvm_device *dev, case KVM_DEV_ARM_VGIC_GRP_CTRL: { switch (attr->attr) { case KVM_DEV_ARM_VGIC_CTRL_INIT: + mutex_lock(&dev->kvm->lock); mutex_lock(&dev->kvm->arch.config_lock); r = vgic_init(dev->kvm); mutex_unlock(&dev->kvm->arch.config_lock); + mutex_unlock(&dev->kvm->lock); return r; case KVM_DEV_ARM_VGIC_SAVE_PENDING_TABLES: /* diff --git a/arch/arm64/kvm/vgic/vgic-mmio-v3.c b/arch/arm64/kvm/vgic/vgic-mmio-v3.c index f9ff553bbbf164..02292f8e0b4312 100644 --- a/arch/arm64/kvm/vgic/vgic-mmio-v3.c +++ b/arch/arm64/kvm/vgic/vgic-mmio-v3.c @@ -45,7 +45,7 @@ bool vgic_has_its(struct kvm *kvm) return dist->its_model && dist->its_model == dist->vgic_model; } -bool vgic_supports_direct_msis(struct kvm *kvm) +bool vgic_supports_vpes(struct kvm *kvm) { /* * Deliberately conflate vLPI and vSGI support on GICv4.1 hardware, @@ -55,7 +55,12 @@ bool vgic_supports_direct_msis(struct kvm *kvm) if (system_supports_direct_sgis() && !vgic_supports_direct_sgis(kvm)) return false; - return kvm_vgic_global_state.has_gicv4 && vgic_has_its(kvm); + return kvm_vgic_global_state.has_gicv4 && vgic_is_v3(kvm); +} + +bool vgic_supports_direct_msis(struct kvm *kvm) +{ + return vgic_supports_vpes(kvm) && vgic_has_its(kvm); } bool system_supports_direct_sgis(void) @@ -290,28 +295,31 @@ static void vgic_mmio_write_v3r_ctlr(struct kvm_vcpu *vcpu, return; if (!(val & GICR_CTLR_ENABLE_LPIS)) { - /* - * Don't disable if RWP is set, as there already an - * ongoing disable. Funky guest... - */ - ctlr = atomic_cmpxchg_acquire(&vgic_cpu->ctlr, - GICR_CTLR_ENABLE_LPIS, - GICR_CTLR_RWP); - if (ctlr != GICR_CTLR_ENABLE_LPIS) - return; - /* * Yes, disabling LPIs is painful, since it can be done from * a *remote* vcpu! So let's not take any chance, and make * sure that the target vCPU has written their LRs back to the * irq structures, and release any reference they would have. + * Pause it before its LPIs read as disabled, so that the exit's + * prune leaves them for vgic_flush_pending_lpis() to retire. * * If it hurts, don't do it. */ kvm_pause_vcpu(vcpu); - vgic_flush_pending_lpis(vcpu); - vgic_its_invalidate_all_caches(vcpu->kvm); - atomic_set_release(&vgic_cpu->ctlr, 0); + + /* + * Don't disable if RWP is set, as there already an + * ongoing disable. Funky guest... + */ + ctlr = atomic_cmpxchg_acquire(&vgic_cpu->ctlr, + GICR_CTLR_ENABLE_LPIS, + GICR_CTLR_RWP); + if (ctlr == GICR_CTLR_ENABLE_LPIS) { + vgic_flush_pending_lpis(vcpu); + vgic_its_invalidate_all_caches(vcpu->kvm); + atomic_set_release(&vgic_cpu->ctlr, 0); + } + kvm_resume_vcpu(vcpu); } else { ctlr = atomic_cmpxchg_acquire(&vgic_cpu->ctlr, 0, diff --git a/arch/arm64/kvm/vgic/vgic-mmio.c b/arch/arm64/kvm/vgic/vgic-mmio.c index fddb9da0403d55..59bdec495cd774 100644 --- a/arch/arm64/kvm/vgic/vgic-mmio.c +++ b/arch/arm64/kvm/vgic/vgic-mmio.c @@ -820,7 +820,7 @@ void vgic_write_irq_line_level_info(struct kvm_vcpu *vcpu, u32 intid, static int match_region(const void *key, const void *elt) { - const unsigned int offset = (unsigned long)key; + const u64 offset = (unsigned long)key; const struct vgic_register_region *region = elt; if (offset < region->reg_offset) @@ -834,7 +834,7 @@ static int match_region(const void *key, const void *elt) const struct vgic_register_region * vgic_find_mmio_region(const struct vgic_register_region *regions, - int nr_regions, unsigned int offset) + int nr_regions, u64 offset) { return bsearch((void *)(uintptr_t)offset, regions, nr_regions, sizeof(regions[0]), match_region); diff --git a/arch/arm64/kvm/vgic/vgic-mmio.h b/arch/arm64/kvm/vgic/vgic-mmio.h index 38ed730d68ac38..6c3c4de6883ef5 100644 --- a/arch/arm64/kvm/vgic/vgic-mmio.h +++ b/arch/arm64/kvm/vgic/vgic-mmio.h @@ -228,6 +228,6 @@ u64 vgic_sanitise_field(u64 reg, u64 field_mask, int field_shift, /* Find the proper register handler entry given a certain address offset */ const struct vgic_register_region * vgic_find_mmio_region(const struct vgic_register_region *regions, - int nr_regions, unsigned int offset); + int nr_regions, u64 offset); #endif diff --git a/arch/arm64/kvm/vgic/vgic-v3.c b/arch/arm64/kvm/vgic/vgic-v3.c index 346bacb3198f22..65b77fb35be37d 100644 --- a/arch/arm64/kvm/vgic/vgic-v3.c +++ b/arch/arm64/kvm/vgic/vgic-v3.c @@ -552,7 +552,8 @@ int vgic_v3_lpi_sync_pending_status(struct kvm *kvm, struct vgic_irq *irq) irq->pending_latch = status; vgic_queue_irq_unlock(vcpu->kvm, irq, flags); - if (status) { + /* Enabling LPIs resets the latch from the table: leave the bit for it */ + if (status && vgic_lpis_enabled(vcpu)) { /* clear consumed data */ val &= ~(1 << bit_nr); ret = vgic_write_guest_lock(kvm, ptr, &val, 1); diff --git a/arch/arm64/kvm/vgic/vgic-v4.c b/arch/arm64/kvm/vgic/vgic-v4.c index ed236f083f0d7f..1b7623f098e2f2 100644 --- a/arch/arm64/kvm/vgic/vgic-v4.c +++ b/arch/arm64/kvm/vgic/vgic-v4.c @@ -248,7 +248,7 @@ int vgic_v4_init(struct kvm *kvm) lockdep_assert_held(&kvm->arch.config_lock); - if (!kvm_vgic_global_state.has_gicv4) + if (!vgic_supports_vpes(kvm)) return 0; /* Nothing to see here... move along. */ if (dist->its_vm.vpes) @@ -333,6 +333,9 @@ void vgic_v4_teardown(struct kvm *kvm) free_irq(irq, vcpu); } + /* Make sure we free all VM-wide, per-CPU resources */ + its_vm->nr_vpes = atomic_read(&kvm->online_vcpus); + its_free_vcpu_irqs(its_vm); kfree(its_vm->vpes); its_vm->nr_vpes = 0; diff --git a/arch/arm64/kvm/vgic/vgic.c b/arch/arm64/kvm/vgic/vgic.c index bea848c93a990d..fe09ada3226253 100644 --- a/arch/arm64/kvm/vgic/vgic.c +++ b/arch/arm64/kvm/vgic/vgic.c @@ -285,14 +285,18 @@ struct kvm_vcpu *vgic_target_oracle(struct vgic_irq *irq) * If the IRQ is not active but enabled and pending, we should direct * it to its configured target VCPU. * If the distributor is disabled, pending interrupts shouldn't be - * forwarded. + * forwarded, nor should LPIs whose redistributor has them disabled. */ if (irq->enabled && irq_is_pending(irq)) { - if (unlikely(irq->target_vcpu && - !irq->target_vcpu->kvm->arch.vgic.enabled)) + struct kvm_vcpu *vcpu = irq->target_vcpu; + + if (unlikely(vcpu && !vcpu->kvm->arch.vgic.enabled)) + return NULL; + + if (unlikely(vcpu && irq_is_lpi(vcpu->kvm, irq->intid) && !vgic_lpis_enabled(vcpu))) return NULL; - return irq->target_vcpu; + return vcpu; } /* If neither active nor pending and enabled, then this IRQ should not diff --git a/arch/arm64/kvm/vgic/vgic.h b/arch/arm64/kvm/vgic/vgic.h index 97fc3bdf520e5b..71c481ddd98d61 100644 --- a/arch/arm64/kvm/vgic/vgic.h +++ b/arch/arm64/kvm/vgic/vgic.h @@ -521,6 +521,7 @@ static inline bool vgic_host_has_gicv5(void) } bool system_supports_direct_sgis(void); +bool vgic_supports_vpes(struct kvm *kvm); bool vgic_supports_direct_msis(struct kvm *kvm); bool vgic_supports_direct_sgis(struct kvm *kvm); diff --git a/arch/arm64/mm/fixmap.c b/arch/arm64/mm/fixmap.c index f66a0016dd02df..c8a0d008cf2aa1 100644 --- a/arch/arm64/mm/fixmap.c +++ b/arch/arm64/mm/fixmap.c @@ -126,11 +126,20 @@ void __set_fixmap(enum fixed_addresses idx, ptep = fixmap_pte(addr); - if (pgprot_val(flags)) { - __set_pte(ptep, pfn_pte(phys >> PAGE_SHIFT, flags)); - } else { + /* + * Break-before-make if the slot holds a valid mapping. Always + * flush on clear since another CPU may have cleared the pte + * without completing its TLBI yet. + */ + if (pte_valid(__ptep_get(ptep)) || !pgprot_val(flags)) { __pte_clear(&init_mm, addr, ptep); - flush_tlb_kernel_range(addr, addr+PAGE_SIZE); + flush_tlb_kernel_range(addr, addr + PAGE_SIZE); + } + + if (pgprot_val(flags)) { + /* The slot must be usable on return, even in lazy MMU mode. */ + __set_pte_nosync(ptep, pfn_pte(phys >> PAGE_SHIFT, flags)); + emit_pte_barriers(); } } diff --git a/arch/arm64/mm/mmu.c b/arch/arm64/mm/mmu.c index 140520b351e282..19459a4a870a2d 100644 --- a/arch/arm64/mm/mmu.c +++ b/arch/arm64/mm/mmu.c @@ -1495,8 +1495,7 @@ static void free_hotplug_page_range(struct page *page, size_t size, static void free_hotplug_pgtable_page(struct page *page) { - pagetable_dtor(page_ptdesc(page)); - free_hotplug_page_range(page, PAGE_SIZE, NULL); + pagetable_free(page_ptdesc(page)); } static bool pgtable_range_aligned(unsigned long start, unsigned long end, diff --git a/arch/arm64/mm/proc.S b/arch/arm64/mm/proc.S index 99aacf03367da3..62e790a2a779c2 100644 --- a/arch/arm64/mm/proc.S +++ b/arch/arm64/mm/proc.S @@ -290,6 +290,7 @@ SYM_FUNC_ALIAS(__pi_idmap_cpu_replace_ttbr1, idmap_cpu_replace_ttbr1) orr pte, pte, pte_flags str pte, [temp_pte, #8 * (\level + 2)] dsb nshst + isb .endm /* diff --git a/arch/arm64/net/bpf_jit_comp.c b/arch/arm64/net/bpf_jit_comp.c index 33632fb20997b7..bee2d3f6b868f6 100644 --- a/arch/arm64/net/bpf_jit_comp.c +++ b/arch/arm64/net/bpf_jit_comp.c @@ -15,6 +15,7 @@ #include #include #include +#include #include #include @@ -600,6 +601,12 @@ static int build_prologue(struct jit_ctx *ctx, bool ebpf_from_cbpf) * 12 registers are on the stack */ emit(A64_SUB_I(1, A64_SP, A64_FP, 96), ctx); + /* + * Pop the return address of bpf_throw() from the shadow call + * stack. The frames of the JIT put nothing there. + */ + if (scs_is_enabled()) + emit(A64_SUB_I(1, A64_R(18), A64_R(18), 8), ctx); /* The callback may use its own BPF stack, set up fp for it. */ ctx->fp_used = true; } diff --git a/arch/arm64/tools/cpucaps b/arch/arm64/tools/cpucaps index 3125695122a0a2..a0a0ee33fd0979 100644 --- a/arch/arm64/tools/cpucaps +++ b/arch/arm64/tools/cpucaps @@ -49,6 +49,7 @@ HAS_LPA2 HAS_LSE_ATOMICS HAS_LS64 HAS_LS64_V +HAS_LS64_ACCDATA HAS_LSUI HAS_MOPS HAS_NESTED_VIRT diff --git a/arch/arm64/tools/sysreg b/arch/arm64/tools/sysreg index 997c62ab72e686..28d319e63d8f10 100644 --- a/arch/arm64/tools/sysreg +++ b/arch/arm64/tools/sysreg @@ -5604,6 +5604,131 @@ Res0 6 Field 5:0 T0SZ EndSysreg +Sysreg TCR_EL2 3 4 2 0 2 +Prefix VHE +Res0 63:62 +Field 61 MTX1 +Field 60 MTX0 +Field 59 DS +Field 58 TCMA1 +Field 57 TCMA0 +Field 56 E0PD1 +Field 55 E0PD0 +Field 54 NFD1 +Field 53 NFD0 +Field 52 TBID1 +Field 51 TBID0 +Field 50 HWU162 +Field 49 HWU161 +Field 48 HWU160 +Field 47 HWU159 +Field 46 HWU062 +Field 45 HWU061 +Field 44 HWU060 +Field 43 HWU059 +Field 42 HPD1 +Field 41 HPD0 +Field 40 HD +Field 39 HA +Field 38 TBI1 +Field 37 TBI0 +Field 36 AS +Res0 35 +Field 34:32 IPS +Enum 31:30 TG1 + 0b01 16K + 0b10 4K + 0b11 64K +EndEnum +Enum 29:28 SH1 + 0b00 NONE + 0b10 OUTER + 0b11 INNER +EndEnum +Enum 27:26 ORGN1 + 0b00 NC + 0b01 WBWA + 0b10 WT + 0b11 WBnWA +EndEnum +Enum 25:24 IRGN1 + 0b00 NC + 0b01 WBWA + 0b10 WT + 0b11 WBnWA +EndEnum +Field 23 EPD1 +Field 22 A1 +Field 21:16 T1SZ +Enum 15:14 TG0 + 0b00 4K + 0b01 64K + 0b10 16K +EndEnum +Enum 13:12 SH0 + 0b00 NONE + 0b10 OUTER + 0b11 INNER +EndEnum +Enum 11:10 ORGN0 + 0b00 NC + 0b01 WBWA + 0b10 WT + 0b11 WBnWA +EndEnum +Enum 9:8 IRGN0 + 0b00 NC + 0b01 WBWA + 0b10 WT + 0b11 WBnWA +EndEnum +Field 7 EPD0 +Res0 6 +Field 5:0 T0SZ +EndPrefix +Res0 63:34 +Field 33 MTX +Field 32 DS +Res1 31 +Field 30 TCMA +Field 29 TBID +Field 28 HWU62 +Field 27 HWU61 +Field 26 HWU60 +Field 25 HWU59 +Field 24 HPD +Res1 23 +Field 22 HD +Field 21 HA +Field 20 TBI +Res0 19 +Field 18:16 PS +Enum 15:14 TG0 + 0b00 4K + 0b01 64K + 0b10 16K +EndEnum +Enum 13:12 SH0 + 0b00 NONE + 0b10 OUTER + 0b11 INNER +EndEnum +Enum 11:10 ORGN0 + 0b00 NC + 0b01 WBWA + 0b10 WT + 0b11 WBnWA +EndEnum +Enum 9:8 IRGN0 + 0b00 NC + 0b01 WBWA + 0b10 WT + 0b11 WBnWA +EndEnum +Res0 7:6 +Field 5:0 T0SZ +EndSysreg + Sysreg TCR_EL12 3 5 2 0 2 Mapping TCR_EL1 EndSysreg diff --git a/arch/loongarch/kvm/vcpu.c b/arch/loongarch/kvm/vcpu.c index 4026b9bf9f2d3e..76afd386abd2dd 100644 --- a/arch/loongarch/kvm/vcpu.c +++ b/arch/loongarch/kvm/vcpu.c @@ -379,11 +379,6 @@ int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu) vcpu->arch.mp_state.mp_state == KVM_MP_STATE_RUNNABLE; } -int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu) -{ - return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE; -} - bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu) { unsigned long val; diff --git a/arch/m68k/atari/atakeyb.c b/arch/m68k/atari/atakeyb.c index 49a9a459bdf4cc..b715e2b8351c8f 100644 --- a/arch/m68k/atari/atakeyb.c +++ b/arch/m68k/atari/atakeyb.c @@ -39,7 +39,7 @@ void (*atari_MIDI_interrupt_hook) (void); /* Hook for keyboard inputdev driver */ void (*atari_input_keyboard_interrupt_hook) (unsigned char, char); /* Hook for mouse inputdev driver */ -void (*atari_input_mouse_interrupt_hook) (char *); +void (*atari_input_mouse_interrupt_hook)(u8 *buf); EXPORT_SYMBOL(atari_input_keyboard_interrupt_hook); EXPORT_SYMBOL(atari_input_mouse_interrupt_hook); diff --git a/arch/m68k/include/asm/atarikb.h b/arch/m68k/include/asm/atarikb.h index 68f3622bf59193..bdf67bff147249 100644 --- a/arch/m68k/include/asm/atarikb.h +++ b/arch/m68k/include/asm/atarikb.h @@ -15,6 +15,8 @@ #ifndef _LINUX_ATARIKB_H #define _LINUX_ATARIKB_H +#include + void ikbd_write(const char *, int); void ikbd_mouse_button_action(int mode); void ikbd_mouse_rel_pos(void); @@ -37,7 +39,7 @@ extern void (*atari_MIDI_interrupt_hook) (void); /* Hook for keyboard inputdev driver */ extern void (*atari_input_keyboard_interrupt_hook) (unsigned char, char); /* Hook for mouse inputdev driver */ -extern void (*atari_input_mouse_interrupt_hook) (char *); +extern void (*atari_input_mouse_interrupt_hook)(u8 *buf); int atari_keyb_init(void); diff --git a/arch/mips/kvm/mips.c b/arch/mips/kvm/mips.c index a53abbba43ea33..273dd932d119d2 100644 --- a/arch/mips/kvm/mips.c +++ b/arch/mips/kvm/mips.c @@ -120,11 +120,6 @@ bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu) return false; } -int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu) -{ - return 1; -} - int kvm_arch_enable_virtualization_cpu(void) { return kvm_mips_callbacks->enable_virtualization_cpu(); diff --git a/arch/parisc/kernel/entry.S b/arch/parisc/kernel/entry.S index e04c5d806c1051..b0728dbee53d71 100644 --- a/arch/parisc/kernel/entry.S +++ b/arch/parisc/kernel/entry.S @@ -1949,11 +1949,7 @@ ENDPROC_CFI(mcount) #ifdef CONFIG_DYNAMIC_FTRACE -#ifdef CONFIG_64BIT #define FTRACE_FRAME_SIZE (2*FRAME_SIZE) -#else -#define FTRACE_FRAME_SIZE FRAME_SIZE -#endif ENTRY_CFI(ftrace_caller, caller,frame=FTRACE_FRAME_SIZE,CALLS,SAVE_RP,SAVE_SP) ftrace_caller: .global ftrace_caller diff --git a/arch/parisc/kernel/ftrace.c b/arch/parisc/kernel/ftrace.c index 10fd5b3e63e757..963a741faa42d9 100644 --- a/arch/parisc/kernel/ftrace.c +++ b/arch/parisc/kernel/ftrace.c @@ -146,7 +146,7 @@ int ftrace_make_call(struct dyn_ftrace *rec, unsigned long addr) #else u32 ftrace_trampoline[] = { (u32)addr, - 0x6fc10080, /* stw,ma r1,40(sp) */ + 0x6fc10100, /* stw,ma r1,80(sp) */ 0x48213fd1, /* ldw -18(r1),r1 */ 0xe820c002, /* bv,n r0(r1) */ 0xe83f1fdf, /* b,l,n .-c,r1 */ diff --git a/arch/parisc/kernel/irq.c b/arch/parisc/kernel/irq.c index dff66be65d2900..d9f6cb04e4bcf6 100644 --- a/arch/parisc/kernel/irq.c +++ b/arch/parisc/kernel/irq.c @@ -497,7 +497,7 @@ asmlinkage void do_cpu_irq_mask(struct pt_regs *regs) #endif old_regs = set_irq_regs(regs); - local_irq_disable(); + trace_hardirqs_off(); irq_enter_rcu(); eirr_val = mfctl(23) & cpu_eiem & per_cpu(local_ack_eiem, cpu); @@ -535,6 +535,8 @@ asmlinkage void do_cpu_irq_mask(struct pt_regs *regs) out: irq_exit_rcu(); set_irq_regs(old_regs); + if (!irqs_disabled_flags(regs->gr[0])) + trace_hardirqs_on(); return; set_out: diff --git a/arch/powerpc/configs/86xx-hw.config b/arch/powerpc/configs/86xx-hw.config index 07f30ab881e59d..eb3ebf90888872 100644 --- a/arch/powerpc/configs/86xx-hw.config +++ b/arch/powerpc/configs/86xx-hw.config @@ -91,8 +91,6 @@ CONFIG_USB_OHCI_HCD=y CONFIG_USB_STORAGE=y CONFIG_USB=y CONFIG_VITESSE_PHY=y -CONFIG_VME_BUS=y -CONFIG_VME_TSI148=y CONFIG_WATCHDOG=y # CONFIG_YENTA_O2 is not set # CONFIG_YENTA_RICOH is not set diff --git a/arch/powerpc/include/asm/hw_irq.h b/arch/powerpc/include/asm/hw_irq.h index b7eee6385ae5c6..ddb850e62abd69 100644 --- a/arch/powerpc/include/asm/hw_irq.h +++ b/arch/powerpc/include/asm/hw_irq.h @@ -464,7 +464,7 @@ static inline bool arch_irqs_disabled(void) return arch_irqs_disabled_flags(arch_local_save_flags()); } -#define hard_irq_disable() arch_local_irq_disable() +#define hard_irq_disable() local_irq_disable() static inline bool regs_irqs_disabled(struct pt_regs *regs) { diff --git a/arch/powerpc/include/asm/kvm_host.h b/arch/powerpc/include/asm/kvm_host.h index 708a32f8977652..de5fbf9f73371e 100644 --- a/arch/powerpc/include/asm/kvm_host.h +++ b/arch/powerpc/include/asm/kvm_host.h @@ -35,6 +35,7 @@ #define KVM_MAX_VCPUS NR_CPUS #define KVM_MAX_VCORES NR_CPUS +#define KVM_MAX_VCPU_IDS_NESTEDv2 2048 /* PAPR H_GUEST_CREATE_VCPU vcpuId */ #include @@ -745,6 +746,7 @@ struct kvm_vcpu_arch { pgd_t *pgdir; u16 io_gpr; /* GPR used as IO source/target */ + u8 mmio_len; /* kernel-private copy of mmio.len, immune to TOCTOU */ u8 mmio_host_swabbed; u8 mmio_sign_extend; /* conversion between single and double precision */ @@ -910,7 +912,6 @@ struct kvm_vcpu_arch { #define __KVM_HAVE_CREATE_DEVICE static inline void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen) {} -static inline void kvm_arch_flush_shadow_all(struct kvm *kvm) {} static inline void kvm_arch_vcpu_blocking(struct kvm_vcpu *vcpu) {} static inline void kvm_arch_vcpu_unblocking(struct kvm_vcpu *vcpu) {} diff --git a/arch/powerpc/include/asm/kvm_ppc.h b/arch/powerpc/include/asm/kvm_ppc.h index 169ea6a7fbad44..bfa2f6278fc45e 100644 --- a/arch/powerpc/include/asm/kvm_ppc.h +++ b/arch/powerpc/include/asm/kvm_ppc.h @@ -30,6 +30,17 @@ #endif #include +/* + * TODO: For unknown reasons, KVM PPC has historically ignored vcpu->mode when + * determining if kicking a vCPU needs an IPI. Either document why that + * behavior is necessary, or drop this helper and the @force param from + * __kvm_vcpu_kick(). + */ +static inline void kvmppc_vcpu_kick(struct kvm_vcpu *vcpu) +{ + __kvm_vcpu_kick(vcpu, 0, true); +} + /* * KVMPPC_INST_SW_BREAKPOINT is debug Instruction * for supporting software breakpoint. @@ -598,7 +609,7 @@ static inline void kvmppc_clear_host_ipi(int cpu) static inline void kvmppc_fast_vcpu_kick(struct kvm_vcpu *vcpu) { - kvm_vcpu_kick(vcpu); + kvmppc_vcpu_kick(vcpu); } static inline bool kvm_hv_mode_active(void) { return false; } @@ -720,7 +731,7 @@ static inline int kvmppc_xive_xics_hcall(struct kvm_vcpu *vcpu, u32 req) * new "XIVE" interrupt controller. */ extern int kvmppc_xive_set_xive(struct kvm *kvm, u32 irq, u32 server, - u32 priority); + u8 priority); extern int kvmppc_xive_get_xive(struct kvm *kvm, u32 irq, u32 *server, u32 *priority); extern int kvmppc_xive_int_on(struct kvm *kvm, u32 irq); @@ -758,7 +769,7 @@ extern bool kvmppc_xive_native_supported(void); #else static inline int kvmppc_xive_set_xive(struct kvm *kvm, u32 irq, u32 server, - u32 priority) { return -1; } + u8 priority) { return -1; } static inline int kvmppc_xive_get_xive(struct kvm *kvm, u32 irq, u32 *server, u32 *priority) { return -1; } static inline int kvmppc_xive_int_on(struct kvm *kvm, u32 irq) { return -1; } diff --git a/arch/powerpc/kernel/eeh.c b/arch/powerpc/kernel/eeh.c index bb836f02101cf1..2d7898ef6b8c93 100644 --- a/arch/powerpc/kernel/eeh.c +++ b/arch/powerpc/kernel/eeh.c @@ -1728,10 +1728,12 @@ static ssize_t eeh_force_recover_write(struct file *filp, struct pci_controller *hose; uint32_t phbid, pe_no; struct eeh_pe *pe; - char buf[20]; + char buf[20] = {}; int ret; - ret = simple_write_to_buffer(buf, sizeof(buf), ppos, user_buf, count); + ret = simple_write_to_buffer(buf, sizeof(buf) - 1, ppos, user_buf, count); + if (ret < 0) + return ret; if (!ret) return -EFAULT; diff --git a/arch/powerpc/kernel/module_32.c b/arch/powerpc/kernel/module_32.c index f930e3395a7f27..61152deffc55bf 100644 --- a/arch/powerpc/kernel/module_32.c +++ b/arch/powerpc/kernel/module_32.c @@ -41,6 +41,9 @@ static unsigned int count_relocs(const Elf32_Rela *rela, unsigned int num) #ifdef CONFIG_DYNAMIC_FTRACE _count_relocs++; /* add one for ftrace_caller */ +#ifdef CONFIG_DYNAMIC_FTRACE_WITH_REGS + _count_relocs++; /* add one for ftrace_regs_caller */ +#endif #endif return _count_relocs; } diff --git a/arch/powerpc/kernel/smp.c b/arch/powerpc/kernel/smp.c index 7a25eaa59e6260..58824f5f4c8008 100644 --- a/arch/powerpc/kernel/smp.c +++ b/arch/powerpc/kernel/smp.c @@ -824,6 +824,8 @@ static int parse_thread_groups(struct device_node *dn, int i = 0; count = of_property_count_u32_elems(dn, "ibm,thread-groups"); + if (count < 0) + return count; thread_group_array = kzalloc_objs(u32, count); if (!thread_group_array) return -ENOMEM; diff --git a/arch/powerpc/kernel/watchdog.c b/arch/powerpc/kernel/watchdog.c index 582ee3fd71c1ba..44f178e07531e6 100644 --- a/arch/powerpc/kernel/watchdog.c +++ b/arch/powerpc/kernel/watchdog.c @@ -487,6 +487,9 @@ static void start_watchdog(void *arg) if (!(watchdog_enabled & WATCHDOG_HARDLOCKUP_ENABLED)) return; + if (!watchdog_thresh) + return; + if (!cpumask_test_cpu(cpu, &watchdog_cpumask)) return; diff --git a/arch/powerpc/kvm/book3s.c b/arch/powerpc/kvm/book3s.c index 2efbe05caed760..067edb6440fe65 100644 --- a/arch/powerpc/kvm/book3s.c +++ b/arch/powerpc/kvm/book3s.c @@ -260,7 +260,7 @@ void kvmppc_core_queue_external(struct kvm_vcpu *vcpu, * external interrupts for the guest just before entering * the guest. That is OK even if userspace did do a * KVM_INTERRUPT_SET on a pseries guest vcpu, because the - * caller (kvm_vcpu_ioctl_interrupt) does a kvm_vcpu_kick() + * caller (kvm_vcpu_ioctl_interrupt) does a kvmppc_vcpu_kick() * which ends up doing a smp_send_reschedule(), which will * pull the guest all the way out to the host, meaning that * we will call kvmppc_core_prepare_to_enter() before entering @@ -401,7 +401,7 @@ int kvmppc_core_prepare_to_enter(struct kvm_vcpu *vcpu) if (vcpu->arch.pending_exceptions) printk(KERN_EMERG "KVM: Check pending: %lx\n", vcpu->arch.pending_exceptions); #endif - priority = __ffs(*pending); + priority = find_first_bit(pending, BITS_PER_BYTE * sizeof(*pending)); while (priority < BOOK3S_IRQPRIO_MAX) { if (kvmppc_book3s_irqprio_deliver(vcpu, priority) && clear_irqprio(vcpu, priority)) { @@ -827,7 +827,7 @@ int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu, void kvmppc_decrementer_func(struct kvm_vcpu *vcpu) { kvmppc_core_queue_dec(vcpu); - kvm_vcpu_kick(vcpu); + kvmppc_vcpu_kick(vcpu); } int kvmppc_core_vcpu_create(struct kvm_vcpu *vcpu) diff --git a/arch/powerpc/kvm/book3s_64_mmu_hv.c b/arch/powerpc/kvm/book3s_64_mmu_hv.c index 00b8a3f855f46e..97740173974cec 100644 --- a/arch/powerpc/kvm/book3s_64_mmu_hv.c +++ b/arch/powerpc/kvm/book3s_64_mmu_hv.c @@ -47,6 +47,9 @@ static long kvmppc_virtmode_do_h_enter(struct kvm *kvm, unsigned long flags, long pte_index, unsigned long pteh, unsigned long ptel, unsigned long *pte_idx_ret); +static void kvmppc_virtmode_do_h_remove(struct kvm *kvm, unsigned long flags, + unsigned long pte_index, unsigned long avpn, + unsigned long *hpret); struct kvm_resize_hpt { /* These fields read-only after init */ @@ -308,6 +311,22 @@ static long kvmppc_virtmode_do_h_enter(struct kvm *kvm, unsigned long flags, } +/* + * Virtual-mode H_REMOVE. kvmppc_do_h_remove() is also called from real mode, + * where preempt_disable() is not usable, so the guard stays here. The function + * spins on HPTE_V_HVLOCK and then lock_rmap() (via remove_revmap_chain()); + * preemption must be disabled across both bit-locks so that spinning callers + * holding preempt_disable() can make forward progress. + */ +static void kvmppc_virtmode_do_h_remove(struct kvm *kvm, unsigned long flags, + unsigned long pte_index, unsigned long avpn, + unsigned long *hpret) +{ + preempt_disable(); + kvmppc_do_h_remove(kvm, flags, pte_index, avpn, hpret); + preempt_enable(); +} + static struct kvmppc_slb *kvmppc_mmu_book3s_hv_find_slbe(struct kvm_vcpu *vcpu, gva_t eaddr) { @@ -810,9 +829,11 @@ static void kvm_unmap_rmapp(struct kvm *kvm, struct kvm_memory_slot *memslot, rmapp = &memslot->arch.rmap[gfn - memslot->base_gfn]; for (;;) { + preempt_disable(); lock_rmap(rmapp); if (!(*rmapp & KVMPPC_RMAP_PRESENT)) { unlock_rmap(rmapp); + preempt_enable(); break; } @@ -826,6 +847,7 @@ static void kvm_unmap_rmapp(struct kvm *kvm, struct kvm_memory_slot *memslot, if (!try_lock_hpte(hptep, HPTE_V_HVLOCK)) { /* unlock rmap before spinning on the HPTE lock */ unlock_rmap(rmapp); + preempt_enable(); while (be64_to_cpu(hptep[0]) & HPTE_V_HVLOCK) cpu_relax(); continue; @@ -834,6 +856,7 @@ static void kvm_unmap_rmapp(struct kvm *kvm, struct kvm_memory_slot *memslot, kvmppc_unmap_hpte(kvm, i, memslot, rmapp, gfn); unlock_rmap(rmapp); __unlock_hpte(hptep, be64_to_cpu(hptep[0])); + preempt_enable(); } } @@ -890,6 +913,7 @@ static bool kvm_age_rmapp(struct kvm *kvm, struct kvm_memory_slot *memslot, rmapp = &memslot->arch.rmap[gfn - memslot->base_gfn]; retry: + preempt_disable(); lock_rmap(rmapp); if (*rmapp & KVMPPC_RMAP_REFERENCED) { *rmapp &= ~KVMPPC_RMAP_REFERENCED; @@ -897,6 +921,7 @@ static bool kvm_age_rmapp(struct kvm *kvm, struct kvm_memory_slot *memslot, } if (!(*rmapp & KVMPPC_RMAP_PRESENT)) { unlock_rmap(rmapp); + preempt_enable(); return ret; } @@ -912,6 +937,7 @@ static bool kvm_age_rmapp(struct kvm *kvm, struct kvm_memory_slot *memslot, if (!try_lock_hpte(hptep, HPTE_V_HVLOCK)) { /* unlock rmap before spinning on the HPTE lock */ unlock_rmap(rmapp); + preempt_enable(); while (be64_to_cpu(hptep[0]) & HPTE_V_HVLOCK) cpu_relax(); goto retry; @@ -931,6 +957,7 @@ static bool kvm_age_rmapp(struct kvm *kvm, struct kvm_memory_slot *memslot, } while ((i = j) != head); unlock_rmap(rmapp); + preempt_enable(); return ret; } @@ -1219,6 +1246,7 @@ static unsigned long resize_hpt_rehash_hpte(struct kvm_resize_hpt *resize, if (!(vpte & HPTE_V_VALID) && !(vpte & HPTE_V_ABSENT)) return 0; /* nothing to do */ + preempt_disable(); while (!try_lock_hpte(hptep, HPTE_V_HVLOCK)) cpu_relax(); @@ -1346,6 +1374,7 @@ static unsigned long resize_hpt_rehash_hpte(struct kvm_resize_hpt *resize, out: unlock_hpte(hptep, vpte); + preempt_enable(); return ret; } @@ -1868,7 +1897,7 @@ static ssize_t kvm_htab_write(struct file *file, const char __user *buf, nb += HPTE_SIZE; if (be64_to_cpu(hptp[0]) & (HPTE_V_VALID | HPTE_V_ABSENT)) - kvmppc_do_h_remove(kvm, 0, i, 0, tmp); + kvmppc_virtmode_do_h_remove(kvm, 0, i, 0, tmp); err = -EIO; ret = kvmppc_virtmode_do_h_enter(kvm, H_EXACT, i, v, r, tmp); @@ -1897,7 +1926,7 @@ static ssize_t kvm_htab_write(struct file *file, const char __user *buf, for (j = 0; j < hdr.n_invalid; ++j) { if (be64_to_cpu(hptp[0]) & (HPTE_V_VALID | HPTE_V_ABSENT)) - kvmppc_do_h_remove(kvm, 0, i, 0, tmp); + kvmppc_virtmode_do_h_remove(kvm, 0, i, 0, tmp); ++i; hptp += 2; } diff --git a/arch/powerpc/kvm/book3s_hv.c b/arch/powerpc/kvm/book3s_hv.c index 22283d46e8fe69..89a1e0cd35afb1 100644 --- a/arch/powerpc/kvm/book3s_hv.c +++ b/arch/powerpc/kvm/book3s_hv.c @@ -1388,9 +1388,11 @@ int kvmppc_pseries_do_hcall(struct kvm_vcpu *vcpu) ret = kvmhv_copy_tofrom_guest_nested(vcpu); break; case H_PAGE_INIT: + idx = srcu_read_lock(&kvm->srcu); ret = kvmppc_h_page_init(vcpu, kvmppc_get_gpr(vcpu, 4), kvmppc_get_gpr(vcpu, 5), kvmppc_get_gpr(vcpu, 6)); + srcu_read_unlock(&kvm->srcu, idx); break; case H_SVM_PAGE_IN: ret = H_UNSUPPORTED; @@ -3090,15 +3092,20 @@ static int kvmppc_core_vcpu_create_hv(struct kvm_vcpu *vcpu) err = -ENOMEM; vcore = kvmppc_vcore_create(kvm, id & ~(kvm->arch.smt_mode - 1)); - mutex_lock(&kvm->arch.mmu_setup_lock); - kvm->arch.vcores[core] = vcore; - kvm->arch.online_vcores++; - mutex_unlock(&kvm->arch.mmu_setup_lock); + if (vcore) { + mutex_lock(&kvm->arch.mmu_setup_lock); + kvm->arch.vcores[core] = vcore; + kvm->arch.online_vcores++; + mutex_unlock(&kvm->arch.mmu_setup_lock); + } } } - if (!vcore) + if (!vcore) { + if (kvmhv_is_nestedv2()) + kvmhv_nestedv2_vcpu_free(vcpu, &vcpu->arch.nestedv2_io); return err; + } spin_lock(&vcore->lock); ++vcore->num_threads; @@ -4984,7 +4991,7 @@ int kvmhv_run_single_vcpu(struct kvm_vcpu *vcpu, u64 time_limit, if (!kvmhv_on_pseries() && (__kvmppc_get_msr_hv(vcpu) & MSR_EE)) kvmppc_inject_interrupt_hv(vcpu, BOOK3S_INTERRUPT_EXTERNAL, 0); - else + else if (!kvmppc_xive_enabled(vcpu)) lpcr |= LPCR_MER; } else { /* @@ -6743,7 +6750,7 @@ static int kvmppc_book3s_init_hv(void) r = kvmppc_uvmem_init(); if (r < 0) { pr_err("KVM-HV: kvmppc_uvmem_init failed %d\n", r); - return r; + goto err; } #if defined(CONFIG_KVM_XICS) diff --git a/arch/powerpc/kvm/book3s_hv_nested.c b/arch/powerpc/kvm/book3s_hv_nested.c index a6ff42d7666c10..e893fdd24f0a8b 100644 --- a/arch/powerpc/kvm/book3s_hv_nested.c +++ b/arch/powerpc/kvm/book3s_hv_nested.c @@ -702,20 +702,6 @@ static struct kvm_nested_guest *__find_nested(struct kvm *kvm, int lpid) return idr_find(&kvm->arch.kvm_nested_guest_idr, lpid); } -static bool __prealloc_nested(struct kvm *kvm, int lpid) -{ - if (idr_alloc(&kvm->arch.kvm_nested_guest_idr, - NULL, lpid, lpid + 1, GFP_KERNEL) != lpid) - return false; - return true; -} - -static void __add_nested(struct kvm *kvm, int lpid, struct kvm_nested_guest *gp) -{ - if (idr_replace(&kvm->arch.kvm_nested_guest_idr, gp, lpid)) - WARN_ON(1); -} - static void __remove_nested(struct kvm *kvm, int lpid) { idr_remove(&kvm->arch.kvm_nested_guest_idr, lpid); @@ -862,21 +848,21 @@ struct kvm_nested_guest *kvmhv_get_nested(struct kvm *kvm, int l1_lpid, if (!newgp) return NULL; - if (!__prealloc_nested(kvm, l1_lpid)) { - kvmhv_release_nested(newgp); - return NULL; - } - + idr_preload(GFP_KERNEL); spin_lock(&kvm->mmu_lock); gp = __find_nested(kvm, l1_lpid); if (!gp) { - __add_nested(kvm, l1_lpid, newgp); - ++newgp->refcnt; - gp = newgp; - newgp = NULL; + if (idr_alloc(&kvm->arch.kvm_nested_guest_idr, newgp, + l1_lpid, l1_lpid + 1, GFP_NOWAIT) >= 0) { + ++newgp->refcnt; + gp = newgp; + newgp = NULL; + } } - ++gp->refcnt; + if (gp) + ++gp->refcnt; spin_unlock(&kvm->mmu_lock); + idr_preload_end(); if (newgp) kvmhv_release_nested(newgp); diff --git a/arch/powerpc/kvm/book3s_hv_p9_entry.c b/arch/powerpc/kvm/book3s_hv_p9_entry.c index 34bc0a8a128856..16aa8582b88804 100644 --- a/arch/powerpc/kvm/book3s_hv_p9_entry.c +++ b/arch/powerpc/kvm/book3s_hv_p9_entry.c @@ -529,6 +529,15 @@ unsigned long kvmppc_msr_hard_disable_set_facilities(struct kvm_vcpu *vcpu, unsi } EXPORT_SYMBOL_GPL(kvmppc_msr_hard_disable_set_facilities); +/* + * EX_DSISR is a 32-bit field that shares a doubleword with EX_CCR. + * Small helper for reading it back at its natural width. + */ +static u32 exsave_dsisr(u64 *exsave) +{ + return *(u32 *)((void *)exsave + EX_DSISR); +} + int kvmhv_vcpu_entry_p9(struct kvm_vcpu *vcpu, u64 time_limit, unsigned long lpcr, u64 *tb) { struct p9_host_os_sprs host_os_sprs; @@ -770,7 +779,7 @@ int kvmhv_vcpu_entry_p9(struct kvm_vcpu *vcpu, u64 time_limit, unsigned long lpc if (unlikely(trap == BOOK3S_INTERRUPT_MACHINE_CHECK)) { vcpu->arch.fault_dar = exsave[EX_DAR/sizeof(u64)]; - vcpu->arch.fault_dsisr = exsave[EX_DSISR/sizeof(u64)]; + vcpu->arch.fault_dsisr = exsave_dsisr(exsave); kvmppc_realmode_machine_check(vcpu); } else if (unlikely(trap == BOOK3S_INTERRUPT_HMI)) { @@ -781,7 +790,7 @@ int kvmhv_vcpu_entry_p9(struct kvm_vcpu *vcpu, u64 time_limit, unsigned long lpc } else if (trap == BOOK3S_INTERRUPT_H_DATA_STORAGE) { vcpu->arch.fault_dar = exsave[EX_DAR/sizeof(u64)]; - vcpu->arch.fault_dsisr = exsave[EX_DSISR/sizeof(u64)]; + vcpu->arch.fault_dsisr = exsave_dsisr(exsave); vcpu->arch.fault_gpa = mfspr(SPRN_ASDR); } else if (trap == BOOK3S_INTERRUPT_H_INST_STORAGE) { diff --git a/arch/powerpc/kvm/book3s_pr.c b/arch/powerpc/kvm/book3s_pr.c index ecfb88bf6464d2..66a9e446ab6483 100644 --- a/arch/powerpc/kvm/book3s_pr.c +++ b/arch/powerpc/kvm/book3s_pr.c @@ -1893,7 +1893,13 @@ static int kvm_vm_ioctl_get_dirty_log_pr(struct kvm *kvm, static void kvmppc_core_flush_memslot_pr(struct kvm *kvm, struct kvm_memory_slot *memslot) { - return; + struct kvm_gfn_range range = { + .slot = memslot, + .start = memslot->base_gfn, + .end = memslot->base_gfn + memslot->npages, + }; + + kvm_unmap_gfn_range_pr(kvm, &range); } static int kvmppc_core_prepare_memory_region_pr(struct kvm *kvm, @@ -2066,7 +2072,7 @@ static struct kvmppc_ops kvm_ops_pr = { .emulate_op = kvmppc_core_emulate_op_pr, .emulate_mtspr = kvmppc_core_emulate_mtspr_pr, .emulate_mfspr = kvmppc_core_emulate_mfspr_pr, - .fast_vcpu_kick = kvm_vcpu_kick, + .fast_vcpu_kick = kvmppc_vcpu_kick, .arch_vm_ioctl = kvm_arch_vm_ioctl_pr, #ifdef CONFIG_PPC_BOOK3S_64 .hcall_implemented = kvmppc_hcall_impl_pr, diff --git a/arch/powerpc/kvm/book3s_rtas.c b/arch/powerpc/kvm/book3s_rtas.c index 0507715d0fdd02..125e06d9988410 100644 --- a/arch/powerpc/kvm/book3s_rtas.c +++ b/arch/powerpc/kvm/book3s_rtas.c @@ -18,7 +18,8 @@ #ifdef CONFIG_KVM_XICS static void kvm_rtas_set_xive(struct kvm_vcpu *vcpu, struct rtas_args *args) { - u32 irq, server, priority; + u32 irq, server; + u8 priority; int rc; if (be32_to_cpu(args->nargs) != 3 || be32_to_cpu(args->nret) != 1) { @@ -28,7 +29,7 @@ static void kvm_rtas_set_xive(struct kvm_vcpu *vcpu, struct rtas_args *args) irq = be32_to_cpu(args->args[0]); server = be32_to_cpu(args->args[1]); - priority = be32_to_cpu(args->args[2]); + priority = (u8) be32_to_cpu(args->args[2]); if (xics_on_xive()) rc = kvmppc_xive_set_xive(vcpu->kvm, irq, server, priority); diff --git a/arch/powerpc/kvm/book3s_xive.c b/arch/powerpc/kvm/book3s_xive.c index d348365df72d32..00218a7dc68833 100644 --- a/arch/powerpc/kvm/book3s_xive.c +++ b/arch/powerpc/kvm/book3s_xive.c @@ -1267,7 +1267,7 @@ static int xive_target_interrupt(struct kvm *kvm, */ int kvmppc_xive_set_xive(struct kvm *kvm, u32 irq, u32 server, - u32 priority) + u8 priority) { struct kvmppc_xive *xive = kvm->arch.xive; struct kvmppc_xive_src_block *sb; @@ -1820,7 +1820,8 @@ void kvmppc_xive_cleanup_vcpu(struct kvm_vcpu *vcpu) kvmppc_xive_disable_vcpu_interrupts(vcpu); /* Mask the VP IPI */ - xive_vm_esb_load(&xc->vp_ipi_data, XIVE_ESB_SET_PQ_01); + if (xc->vp_ipi_data.eoi_mmio) + xive_vm_esb_load(&xc->vp_ipi_data, XIVE_ESB_SET_PQ_01); /* Free escalations */ for (i = 0; i < KVMPPC_XIVE_Q_COUNT; i++) { @@ -1939,6 +1940,7 @@ int kvmppc_xive_connect_vcpu(struct kvm_device *dev, xc->vp_id = vp_id; xc->mfrr = 0xff; xc->valid = true; + vcpu->arch.irq_type = KVMPPC_IRQ_XICS; r = xive_native_get_vp_info(xc->vp_id, &xc->vp_cam, &xc->vp_chip_id); if (r) @@ -2027,7 +2029,6 @@ int kvmppc_xive_connect_vcpu(struct kvm_device *dev, return r; } - vcpu->arch.irq_type = KVMPPC_IRQ_XICS; return 0; } diff --git a/arch/powerpc/kvm/booke.c b/arch/powerpc/kvm/booke.c index 13ad4cf5fa71f8..bda86a076f7217 100644 --- a/arch/powerpc/kvm/booke.c +++ b/arch/powerpc/kvm/booke.c @@ -86,26 +86,25 @@ const struct kvm_stats_header kvm_vcpu_stats_header = { sizeof(kvm_vcpu_stats_desc), }; -/* TODO: use vcpu_printf() */ void kvmppc_dump_vcpu(struct kvm_vcpu *vcpu) { int i; - printk("pc: %08lx msr: %08llx\n", vcpu->arch.regs.nip, - vcpu->arch.shared->msr); - printk("lr: %08lx ctr: %08lx\n", vcpu->arch.regs.link, - vcpu->arch.regs.ctr); - printk("srr0: %08llx srr1: %08llx\n", vcpu->arch.shared->srr0, - vcpu->arch.shared->srr1); + vcpu_err(vcpu, "pc: %08lx msr: %08llx\n", vcpu->arch.regs.nip, + vcpu->arch.shared->msr); + vcpu_err(vcpu, "lr: %08lx ctr: %08lx\n", vcpu->arch.regs.link, + vcpu->arch.regs.ctr); + vcpu_err(vcpu, "srr0: %08llx srr1: %08llx\n", vcpu->arch.shared->srr0, + vcpu->arch.shared->srr1); - printk("exceptions: %08lx\n", vcpu->arch.pending_exceptions); + vcpu_err(vcpu, "exceptions: %08lx\n", vcpu->arch.pending_exceptions); for (i = 0; i < 32; i += 4) { - printk("gpr%02d: %08lx %08lx %08lx %08lx\n", i, - kvmppc_get_gpr(vcpu, i), - kvmppc_get_gpr(vcpu, i+1), - kvmppc_get_gpr(vcpu, i+2), - kvmppc_get_gpr(vcpu, i+3)); + vcpu_err(vcpu, "gpr%02d: %08lx %08lx %08lx %08lx\n", i, + kvmppc_get_gpr(vcpu, i), + kvmppc_get_gpr(vcpu, i+1), + kvmppc_get_gpr(vcpu, i+2), + kvmppc_get_gpr(vcpu, i+3)); } } @@ -650,7 +649,7 @@ static void kvmppc_watchdog_func(struct timer_list *t) if (new_tsr & TSR_WIS) { smp_wmb(); kvm_make_request(KVM_REQ_PENDING_TIMER, vcpu); - kvm_vcpu_kick(vcpu); + kvmppc_vcpu_kick(vcpu); } /* @@ -661,7 +660,7 @@ static void kvmppc_watchdog_func(struct timer_list *t) vcpu->arch.watchdog_enabled) { smp_wmb(); kvm_make_request(KVM_REQ_WATCHDOG, vcpu); - kvm_vcpu_kick(vcpu); + kvmppc_vcpu_kick(vcpu); } /* @@ -692,7 +691,7 @@ static void kvmppc_core_check_exceptions(struct kvm_vcpu *vcpu) unsigned long *pending = &vcpu->arch.pending_exceptions; unsigned int priority; - priority = __ffs(*pending); + priority = find_first_bit(pending, BITS_PER_BYTE * sizeof(*pending)); while (priority < BOOKE_IRQPRIO_MAX) { if (kvmppc_booke_irqprio_deliver(vcpu, priority)) break; @@ -722,7 +721,6 @@ int kvmppc_core_prepare_to_enter(struct kvm_vcpu *vcpu) if (vcpu->arch.shared->msr & MSR_WE) { local_irq_enable(); kvm_vcpu_halt(vcpu); - local_irq_disable(); hard_irq_disable(); kvmppc_set_exit_type(vcpu, EMULATED_MTMSRWE_EXITS); @@ -738,10 +736,8 @@ int kvmppc_core_check_requests(struct kvm_vcpu *vcpu) if (kvm_check_request(KVM_REQ_PENDING_TIMER, vcpu)) update_timer_ints(vcpu); -#if defined(CONFIG_KVM_E500V2) || defined(CONFIG_KVM_E500MC) if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu)) kvmppc_core_flush_tlb(vcpu); -#endif if (kvm_check_request(KVM_REQ_WATCHDOG, vcpu)) { vcpu->run->exit_reason = KVM_EXIT_WATCHDOG; @@ -1404,10 +1400,9 @@ int kvmppc_handle_exit(struct kvm_vcpu *vcpu, unsigned int exit_nr) if (s <= 0) r = (s << 2) | RESUME_HOST | (r & RESUME_FLAG_NV); else { - /* interrupts now hard-disabled */ - kvmppc_fix_ee_before_entry(); kvmppc_load_guest_fp(vcpu); kvmppc_load_guest_altivec(vcpu); + kvmppc_fix_ee_before_entry(); } } @@ -1846,6 +1841,14 @@ void kvmppc_core_commit_memory_region(struct kvm *kvm, void kvmppc_core_flush_memslot(struct kvm *kvm, struct kvm_memory_slot *memslot) { + struct kvm_gfn_range range = { + .slot = memslot, + .start = memslot->base_gfn, + .end = memslot->base_gfn + memslot->npages, + }; + + if (kvm_unmap_gfn_range(kvm, &range)) + kvm_flush_remote_tlbs(kvm); } void kvmppc_set_epcr(struct kvm_vcpu *vcpu, u32 new_epcr) @@ -1872,7 +1875,7 @@ void kvmppc_set_tsr_bits(struct kvm_vcpu *vcpu, u32 tsr_bits) set_bits(tsr_bits, &vcpu->arch.tsr); smp_wmb(); kvm_make_request(KVM_REQ_PENDING_TIMER, vcpu); - kvm_vcpu_kick(vcpu); + kvmppc_vcpu_kick(vcpu); } void kvmppc_clr_tsr_bits(struct kvm_vcpu *vcpu, u32 tsr_bits) diff --git a/arch/powerpc/kvm/e500_emulate.c b/arch/powerpc/kvm/e500_emulate.c index 051102d50c314a..10cd6b4ab45627 100644 --- a/arch/powerpc/kvm/e500_emulate.c +++ b/arch/powerpc/kvm/e500_emulate.c @@ -75,7 +75,7 @@ static int kvmppc_e500_emul_msgsnd(struct kvm_vcpu *vcpu, int rb) int cpir = cvcpu->arch.shared->pir; if ((param & PPC_DBELL_MSG_BRDCAST) || (cpir == pir)) { set_bit(prio, &cvcpu->arch.pending_exceptions); - kvm_vcpu_kick(cvcpu); + kvmppc_vcpu_kick(cvcpu); } } diff --git a/arch/powerpc/kvm/powerpc.c b/arch/powerpc/kvm/powerpc.c index 9194cf492d1ca2..f9f6ebc344a923 100644 --- a/arch/powerpc/kvm/powerpc.c +++ b/arch/powerpc/kvm/powerpc.c @@ -62,11 +62,6 @@ bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu) return false; } -int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu) -{ - return 1; -} - /* * Common checks before entering the guest world. Call with interrupts * enabled. @@ -81,12 +76,6 @@ int kvmppc_prepare_to_enter(struct kvm_vcpu *vcpu) int r; WARN_ON(irqs_disabled()); - /* - * local_irq_disable() first: on 32-bit, hard_irq_disable() alone is a - * raw MSR[EE] clear that bypasses the lockdep/irq-tracing state, and - * the xfer_to_guest_mode helpers assert IRQs are seen as disabled. - */ - local_irq_disable(); hard_irq_disable(); while (true) { @@ -101,7 +90,6 @@ int kvmppc_prepare_to_enter(struct kvm_vcpu *vcpu) */ local_irq_enable(); r = kvm_xfer_to_guest_mode_handle_work(vcpu); - local_irq_disable(); hard_irq_disable(); if (r) { /* @@ -134,7 +122,6 @@ int kvmppc_prepare_to_enter(struct kvm_vcpu *vcpu) local_irq_enable(); trace_kvm_check_requests(vcpu); r = kvmppc_core_check_requests(vcpu); - local_irq_disable(); hard_irq_disable(); if (r > 0) continue; @@ -663,12 +650,18 @@ int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext) r = min(num_present_cpus(), KVM_MAX_VCPUS); else r = min(num_online_cpus(), KVM_MAX_VCPUS); + if (kvmhv_is_nestedv2()) + r = min(r, KVM_MAX_VCPU_IDS_NESTEDv2); break; case KVM_CAP_MAX_VCPUS: r = KVM_MAX_VCPUS; + if (kvmhv_is_nestedv2()) + r = min(r, KVM_MAX_VCPU_IDS_NESTEDv2); break; case KVM_CAP_MAX_VCPU_ID: r = KVM_MAX_VCPU_IDS; + if (kvmhv_is_nestedv2()) + r = min(r, KVM_MAX_VCPU_IDS_NESTEDv2); break; #ifdef CONFIG_PPC_BOOK3S_64 case KVM_CAP_PPC_GET_SMMU_INFO: @@ -764,6 +757,17 @@ void kvm_arch_commit_memory_region(struct kvm *kvm, kvmppc_core_commit_memory_region(kvm, old, new, change); } +void kvm_arch_flush_shadow_all(struct kvm *kvm) +{ + struct kvm_memory_slot *slot; + struct kvm_memslots *slots; + int bkt; + + slots = kvm_memslots(kvm); + kvm_for_each_memslot(slot, bkt, slots) + kvmppc_core_flush_memslot(kvm, slot); +} + void kvm_arch_flush_shadow_memslot(struct kvm *kvm, struct kvm_memory_slot *slot) { @@ -772,6 +776,9 @@ void kvm_arch_flush_shadow_memslot(struct kvm *kvm, int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id) { + if (kvmhv_is_nestedv2() && id >= KVM_MAX_VCPU_IDS_NESTEDv2) + return -EINVAL; + return 0; } @@ -1156,23 +1163,29 @@ static inline u32 dp_to_sp(u64 fprd) #define dp_to_sp(x) (x) #endif /* CONFIG_PPC_FPU */ -static void kvmppc_complete_mmio_load(struct kvm_vcpu *vcpu) +static int kvmppc_complete_mmio_load(struct kvm_vcpu *vcpu) { struct kvm_run *run = vcpu->run; - u64 gpr; + u64 gpr = 0; + u8 len = vcpu->arch.mmio_len; /* use kernel-private copy, not run->mmio.len */ - if (run->mmio.len > sizeof(gpr)) - return; + /* Reject lengths that have no corresponding switch case below. */ + switch (len) { + case 1: case 2: case 4: case 8: + break; + default: + return EMULATE_FAIL; + } if (!vcpu->arch.mmio_host_swabbed) { - switch (run->mmio.len) { + switch (len) { case 8: gpr = *(u64 *)run->mmio.data; break; case 4: gpr = *(u32 *)run->mmio.data; break; case 2: gpr = *(u16 *)run->mmio.data; break; case 1: gpr = *(u8 *)run->mmio.data; break; } } else { - switch (run->mmio.len) { + switch (len) { case 8: gpr = swab64(*(u64 *)run->mmio.data); break; case 4: gpr = swab32(*(u32 *)run->mmio.data); break; case 2: gpr = swab16(*(u16 *)run->mmio.data); break; @@ -1181,11 +1194,11 @@ static void kvmppc_complete_mmio_load(struct kvm_vcpu *vcpu) } /* conversion between single and double precision */ - if ((vcpu->arch.mmio_sp64_extend) && (run->mmio.len == 4)) + if ((vcpu->arch.mmio_sp64_extend) && (len == 4)) gpr = sp_to_dp(gpr); if (vcpu->arch.mmio_sign_extend) { - switch (run->mmio.len) { + switch (len) { #ifdef CONFIG_PPC64 case 4: gpr = (s64)(s32)gpr; @@ -1264,6 +1277,7 @@ static void kvmppc_complete_mmio_load(struct kvm_vcpu *vcpu) default: BUG(); } + return EMULATE_DONE; } static int __kvmppc_handle_load(struct kvm_vcpu *vcpu, @@ -1289,6 +1303,7 @@ static int __kvmppc_handle_load(struct kvm_vcpu *vcpu, run->mmio.is_write = 0; vcpu->arch.io_gpr = rt; + vcpu->arch.mmio_len = bytes; /* kernel-private, immune to TOCTOU */ vcpu->arch.mmio_host_swabbed = host_swabbed; vcpu->mmio_needed = 1; vcpu->mmio_is_write = 0; @@ -1302,8 +1317,11 @@ static int __kvmppc_handle_load(struct kvm_vcpu *vcpu, srcu_read_unlock(&vcpu->kvm->srcu, idx); if (!ret) { - kvmppc_complete_mmio_load(vcpu); vcpu->mmio_needed = 0; + + if (kvmppc_complete_mmio_load(vcpu) != EMULATE_DONE) + return EMULATE_FAIL; + return EMULATE_DONE; } @@ -1344,7 +1362,7 @@ int kvmppc_handle_vsx_load(struct kvm_vcpu *vcpu, if (emulated != EMULATE_DONE) break; - vcpu->arch.paddr_accessed += vcpu->run->mmio.len; + vcpu->arch.paddr_accessed += vcpu->arch.mmio_len; vcpu->arch.mmio_vsx_copy_nums--; vcpu->arch.mmio_vsx_offset++; @@ -1374,6 +1392,7 @@ int kvmppc_handle_store(struct kvm_vcpu *vcpu, run->mmio.phys_addr = vcpu->arch.paddr_accessed; run->mmio.len = bytes; run->mmio.is_write = 1; + vcpu->arch.mmio_len = bytes; /* kernel-private, immune to TOCTOU */ vcpu->mmio_needed = 1; vcpu->mmio_is_write = 1; @@ -1490,7 +1509,7 @@ int kvmppc_handle_vsx_store(struct kvm_vcpu *vcpu, if (emulated != EMULATE_DONE) break; - vcpu->arch.paddr_accessed += vcpu->run->mmio.len; + vcpu->arch.paddr_accessed += vcpu->arch.mmio_len; vcpu->arch.mmio_vsx_copy_nums--; vcpu->arch.mmio_vsx_offset++; @@ -1505,14 +1524,14 @@ static int kvmppc_emulate_mmio_vsx_loadstore(struct kvm_vcpu *vcpu) enum emulation_result emulated = EMULATE_FAIL; int r; - vcpu->arch.paddr_accessed += run->mmio.len; + vcpu->arch.paddr_accessed += vcpu->arch.mmio_len; if (!vcpu->mmio_is_write) { emulated = kvmppc_handle_vsx_load(vcpu, vcpu->arch.io_gpr, - run->mmio.len, 1, vcpu->arch.mmio_sign_extend); + vcpu->arch.mmio_len, 1, vcpu->arch.mmio_sign_extend); } else { emulated = kvmppc_handle_vsx_store(vcpu, - vcpu->arch.io_gpr, run->mmio.len, 1); + vcpu->arch.io_gpr, vcpu->arch.mmio_len, 1); } switch (emulated) { @@ -1550,7 +1569,7 @@ int kvmppc_handle_vmx_load(struct kvm_vcpu *vcpu, if (emulated != EMULATE_DONE) break; - vcpu->arch.paddr_accessed += vcpu->run->mmio.len; + vcpu->arch.paddr_accessed += vcpu->arch.mmio_len; vcpu->arch.mmio_vmx_copy_nums--; vcpu->arch.mmio_vmx_offset++; } @@ -1670,7 +1689,7 @@ int kvmppc_handle_vmx_store(struct kvm_vcpu *vcpu, if (emulated != EMULATE_DONE) break; - vcpu->arch.paddr_accessed += vcpu->run->mmio.len; + vcpu->arch.paddr_accessed += vcpu->arch.mmio_len; vcpu->arch.mmio_vmx_copy_nums--; vcpu->arch.mmio_vmx_offset++; } @@ -1684,14 +1703,14 @@ static int kvmppc_emulate_mmio_vmx_loadstore(struct kvm_vcpu *vcpu) enum emulation_result emulated = EMULATE_FAIL; int r; - vcpu->arch.paddr_accessed += run->mmio.len; + vcpu->arch.paddr_accessed += vcpu->arch.mmio_len; if (!vcpu->mmio_is_write) { emulated = kvmppc_handle_vmx_load(vcpu, - vcpu->arch.io_gpr, run->mmio.len, 1); + vcpu->arch.io_gpr, vcpu->arch.mmio_len, 1); } else { emulated = kvmppc_handle_vmx_store(vcpu, - vcpu->arch.io_gpr, run->mmio.len, 1); + vcpu->arch.io_gpr, vcpu->arch.mmio_len, 1); } switch (emulated) { @@ -1819,8 +1838,16 @@ int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu) if (vcpu->mmio_needed) { vcpu->mmio_needed = 0; - if (!vcpu->mmio_is_write) - kvmppc_complete_mmio_load(vcpu); + if (!vcpu->mmio_is_write) { + if (kvmppc_complete_mmio_load(vcpu) != EMULATE_DONE) { + run->exit_reason = KVM_EXIT_INTERNAL_ERROR; + run->internal.suberror = + KVM_INTERNAL_ERROR_EMULATION; + run->internal.ndata = 0; + r = 0; + goto out; + } + } #ifdef CONFIG_VSX if (vcpu->arch.mmio_vsx_copy_nums > 0) { vcpu->arch.mmio_vsx_copy_nums--; @@ -1879,10 +1906,7 @@ int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu) kvm_sigset_deactivate(vcpu); -#ifdef CONFIG_ALTIVEC out: -#endif - /* * We're already returning to userspace, don't pass the * RESUME_HOST flags along. @@ -1903,7 +1927,7 @@ int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu, struct kvm_interrupt *irq) kvmppc_core_queue_external(vcpu, irq); - kvm_vcpu_kick(vcpu); + kvmppc_vcpu_kick(vcpu); return 0; } diff --git a/arch/powerpc/net/bpf_jit_comp.c b/arch/powerpc/net/bpf_jit_comp.c index ce2966c52ac500..c246709a15ce10 100644 --- a/arch/powerpc/net/bpf_jit_comp.c +++ b/arch/powerpc/net/bpf_jit_comp.c @@ -586,7 +586,7 @@ bool bpf_jit_supports_fsession(void) * for fsession and trampoline on ppc32. */ if (IS_ENABLED(CONFIG_PPC32)) - return -EOPNOTSUPP; + return false; return true; } diff --git a/arch/powerpc/perf/vpa-dtl.c b/arch/powerpc/perf/vpa-dtl.c index 3e3d65b6c796c6..3d34417e6aaece 100644 --- a/arch/powerpc/perf/vpa-dtl.c +++ b/arch/powerpc/perf/vpa-dtl.c @@ -338,7 +338,7 @@ static int vpa_dtl_mem_alloc(int cpu) if (!dtl_cache) return -ENOMEM; - buf = kmem_cache_alloc_node(dtl_cache, GFP_KERNEL | GFP_ATOMIC, cpu_to_node(cpu)); + buf = kmem_cache_alloc_node(dtl_cache, GFP_ATOMIC, cpu_to_node(cpu)); if (!buf) { pr_warn("buffer allocation failed for cpu %d\n", cpu); return -ENOMEM; diff --git a/arch/powerpc/platforms/pasemi/pasemi.h b/arch/powerpc/platforms/pasemi/pasemi.h index 6f6743b8e48d12..01bcfa258625b1 100644 --- a/arch/powerpc/platforms/pasemi/pasemi.h +++ b/arch/powerpc/platforms/pasemi/pasemi.h @@ -7,6 +7,12 @@ extern void pas_pci_init(void); struct pci_dev; extern void pas_pci_dma_dev_setup(struct pci_dev *dev); +#ifdef CONFIG_PPC_PASEMI_NEMO +void __init nemo_init_IRQ(void); +#else +static inline void __init nemo_init_IRQ(void) { } +#endif + void __iomem *__init pasemi_pci_getcfgaddr(struct pci_dev *dev, int offset); extern void __init pasemi_map_registers(void); diff --git a/arch/powerpc/platforms/pasemi/pci.c b/arch/powerpc/platforms/pasemi/pci.c index 2df9552746529c..fb53782da7ecda 100644 --- a/arch/powerpc/platforms/pasemi/pci.c +++ b/arch/powerpc/platforms/pasemi/pci.c @@ -265,6 +265,11 @@ static int __init pas_add_bridge(struct device_node *dev) */ isa_bridge_find_early(hose); + /* + * ISA bridge is now active, add the i8259 cascade (if needed) + */ + nemo_init_IRQ(); + return 0; } diff --git a/arch/powerpc/platforms/pasemi/setup.c b/arch/powerpc/platforms/pasemi/setup.c index 45792ecd5dfd78..7a961f2a228f8f 100644 --- a/arch/powerpc/platforms/pasemi/setup.c +++ b/arch/powerpc/platforms/pasemi/setup.c @@ -216,10 +216,12 @@ static void sb600_8259_cascade(struct irq_desc *desc) chip->irq_eoi(&desc->irq_data); } -static void __init nemo_init_IRQ(struct mpic *mpic) +void __init nemo_init_IRQ(void) { struct device_node *np; int gpio_virq; + struct mpic *mpic; + /* Connect the SB600's legacy i8259 controller */ np = of_find_node_by_path("/pxp@0,e0000000"); i8259_init(np, 0); @@ -230,14 +232,10 @@ static void __init nemo_init_IRQ(struct mpic *mpic) irq_set_chained_handler(gpio_virq, sb600_8259_cascade); mpic_unmask_irq(irq_get_irq_data(gpio_virq)); + mpic = irq_get_chip_data(gpio_virq); irq_set_default_domain(mpic->irqhost); } -#else - -static inline void nemo_init_IRQ(struct mpic *mpic) -{ -} #endif static __init void pas_init_IRQ(void) @@ -300,8 +298,6 @@ static __init void pas_init_IRQ(void) mpic_unmask_irq(irq_get_irq_data(nmi_virq)); } - nemo_init_IRQ(mpic); - of_node_put(mpic_node); of_node_put(root); } diff --git a/arch/powerpc/xmon/xmon.c b/arch/powerpc/xmon/xmon.c index cb3a3244ae6ff9..90a8d7a8f42daf 100644 --- a/arch/powerpc/xmon/xmon.c +++ b/arch/powerpc/xmon/xmon.c @@ -3240,8 +3240,9 @@ memzcan(void) printf("%.8lx\n", a - mskip); } -static void show_task(struct task_struct *volatile tsk) +static void show_task(struct task_struct *volatile vol_tsk) { + struct task_struct *tsk = vol_tsk; unsigned int p_state = READ_ONCE(tsk->__state); char state; diff --git a/arch/riscv/Kconfig b/arch/riscv/Kconfig index e7891a2a89da6a..d2db8f40c61671 100644 --- a/arch/riscv/Kconfig +++ b/arch/riscv/Kconfig @@ -602,7 +602,7 @@ config RISCV_ISA_SSQOSID config RISCV_ISA_SV48 bool "Page-Based 48-bit Virtual-Memory System" - depends on 64BIT + depends on 64BIT && MMU default y help Add support for the Page-Based 48-bit Virtual-Memory System. @@ -614,7 +614,7 @@ config RISCV_ISA_SV48 config RISCV_ISA_SV57 bool "Page-Based 57-bit Virtual-Memory System" - depends on 64BIT + depends on 64BIT && MMU default y help Add support for the Page-Based 57-bit Virtual-Memory System. diff --git a/arch/riscv/boot/dts/spacemit/k1.dtsi b/arch/riscv/boot/dts/spacemit/k1.dtsi index 542bfc0d19f55a..5d5f7f8a393d37 100644 --- a/arch/riscv/boot/dts/spacemit/k1.dtsi +++ b/arch/riscv/boot/dts/spacemit/k1.dtsi @@ -948,7 +948,7 @@ resets = <&syscon_apmu RESET_DMA>; interrupts = <72>; dma-channels = <16>; - #dma-cells= <1>; + #dma-cells = <1>; status = "disabled"; }; diff --git a/arch/riscv/configs/defconfig b/arch/riscv/configs/defconfig index 04ae305d5511bb..383fdd07a99f8e 100644 --- a/arch/riscv/configs/defconfig +++ b/arch/riscv/configs/defconfig @@ -52,6 +52,7 @@ CONFIG_JUMP_LABEL=y CONFIG_MODULES=y CONFIG_MODULE_UNLOAD=y CONFIG_BLK_DEV_THROTTLING=y +# CONFIG_COMPAT_BRK is not set CONFIG_SPARSEMEM_MANUAL=y CONFIG_NET=y CONFIG_PACKET=y @@ -222,6 +223,7 @@ CONFIG_USB_CDNS3_HOST=y CONFIG_USB_CDNS3_STARFIVE=m CONFIG_USB_MUSB_HDRC=m CONFIG_USB_MUSB_SUNXI=m +CONFIG_USB_ONBOARD_DEV=m CONFIG_NOP_USB_XCEIV=m CONFIG_USB_GADGET=y CONFIG_USB_CONFIGFS=m diff --git a/arch/riscv/include/asm/kvm_gstage.h b/arch/riscv/include/asm/kvm_gstage.h index aaf080ba1b77a2..90ec9e0b34b182 100644 --- a/arch/riscv/include/asm/kvm_gstage.h +++ b/arch/riscv/include/asm/kvm_gstage.h @@ -80,6 +80,8 @@ bool kvm_riscv_gstage_op_pte(struct kvm_gstage *gstage, gpa_t addr, bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage, gpa_t start, gpa_t size, bool may_block); +bool kvm_riscv_gstage_unmap_all(struct kvm_gstage *gstage); + bool kvm_riscv_gstage_wp_range(struct kvm_gstage *gstage, gpa_t start, gpa_t end); bool kvm_riscv_gstage_wp_pt_masked(struct kvm_gstage *gstage, gfn_t base_gfn, diff --git a/arch/riscv/include/asm/kvm_host.h b/arch/riscv/include/asm/kvm_host.h index e28f058a94d707..d705b538875d5c 100644 --- a/arch/riscv/include/asm/kvm_host.h +++ b/arch/riscv/include/asm/kvm_host.h @@ -333,5 +333,6 @@ void kvm_riscv_vcpu_record_steal_time(struct kvm_vcpu *vcpu); /* Flags representing implementation specific details */ DECLARE_STATIC_KEY_FALSE(kvm_riscv_vsstage_tlb_no_gpa); +DECLARE_STATIC_KEY_FALSE(kvm_riscv_no_xenvcfg); #endif /* __RISCV_KVM_HOST_H__ */ diff --git a/arch/riscv/include/asm/pgtable.h b/arch/riscv/include/asm/pgtable.h index 2ebd5fa5adc58e..07ccacd51ab543 100644 --- a/arch/riscv/include/asm/pgtable.h +++ b/arch/riscv/include/asm/pgtable.h @@ -189,6 +189,7 @@ extern struct pt_alloc_ops pt_ops __meminitdata; #define PAGE_KERNEL __pgprot(_PAGE_KERNEL) #define PAGE_KERNEL_READ __pgprot(_PAGE_KERNEL & ~_PAGE_WRITE) +#define PAGE_KERNEL_RO PAGE_KERNEL_READ #define PAGE_KERNEL_EXEC __pgprot(_PAGE_KERNEL | _PAGE_EXEC) #define PAGE_KERNEL_READ_EXEC __pgprot((_PAGE_KERNEL & ~_PAGE_WRITE) \ | _PAGE_EXEC) diff --git a/arch/riscv/include/asm/switch_to.h b/arch/riscv/include/asm/switch_to.h index 123c89b694e876..970f89935f0ee0 100644 --- a/arch/riscv/include/asm/switch_to.h +++ b/arch/riscv/include/asm/switch_to.h @@ -28,11 +28,13 @@ static inline void __fstate_clean(struct pt_regs *regs) static inline void fstate_off(struct task_struct *task, struct pt_regs *regs) { + preempt_disable(); regs->status = (regs->status & ~SR_FS) | SR_FS_OFF; + preempt_enable(); } -static inline void fstate_save(struct task_struct *task, - struct pt_regs *regs) +static inline void fstate_save_preempt_off(struct task_struct *task, + struct pt_regs *regs) { if ((regs->status & SR_FS) == SR_FS_DIRTY) { __fstate_save(task); @@ -40,8 +42,8 @@ static inline void fstate_save(struct task_struct *task, } } -static inline void fstate_restore(struct task_struct *task, - struct pt_regs *regs) +static inline void fstate_restore_preempt_off(struct task_struct *task, + struct pt_regs *regs) { if ((regs->status & SR_FS) != SR_FS_OFF) { __fstate_restore(task); @@ -49,14 +51,30 @@ static inline void fstate_restore(struct task_struct *task, } } +static inline void fstate_save(struct task_struct *task, + struct pt_regs *regs) +{ + preempt_disable(); + fstate_save_preempt_off(task, regs); + preempt_enable(); +} + +static inline void fstate_restore(struct task_struct *task, + struct pt_regs *regs) +{ + preempt_disable(); + fstate_restore_preempt_off(task, regs); + preempt_enable(); +} + static inline void __switch_to_fpu(struct task_struct *prev, struct task_struct *next) { struct pt_regs *regs; regs = task_pt_regs(prev); - fstate_save(prev, regs); - fstate_restore(next, task_pt_regs(next)); + fstate_save_preempt_off(prev, regs); + fstate_restore_preempt_off(next, task_pt_regs(next)); } static __always_inline bool has_fpu(void) diff --git a/arch/riscv/include/asm/vector.h b/arch/riscv/include/asm/vector.h index cd09f32e1ea3f1..3381a535abb4dc 100644 --- a/arch/riscv/include/asm/vector.h +++ b/arch/riscv/include/asm/vector.h @@ -320,6 +320,8 @@ static inline void riscv_v_vstate_save(struct __riscv_v_ext_state *vstate, static inline void riscv_v_vstate_restore(struct __riscv_v_ext_state *vstate, struct pt_regs *regs) { + WARN_ON_ONCE(preemptible()); + if (riscv_v_vstate_query(regs)) { __riscv_v_vstate_restore(vstate, vstate->datap); __riscv_v_vstate_clean(regs); diff --git a/arch/riscv/kernel/efi.c b/arch/riscv/kernel/efi.c index 2d3cc57b453525..11e85d0ebc911a 100644 --- a/arch/riscv/kernel/efi.c +++ b/arch/riscv/kernel/efi.c @@ -22,7 +22,7 @@ static __init pgprot_t efimem_to_pgprot_map(efi_memory_desc_t *md) u32 type = md->type; if (type == EFI_MEMORY_MAPPED_IO) - return PAGE_KERNEL; + return PAGE_KERNEL_IO; /* R-- */ if ((attr & (EFI_MEMORY_XP | EFI_MEMORY_RO)) == diff --git a/arch/riscv/kernel/entry.S b/arch/riscv/kernel/entry.S index 61b7a77166971d..628b85e3915a7e 100644 --- a/arch/riscv/kernel/entry.S +++ b/arch/riscv/kernel/entry.S @@ -443,15 +443,15 @@ SYM_FUNC_START(__switch_to) REG_S s10, TASK_THREAD_S10_RA(a3) REG_S s11, TASK_THREAD_S11_RA(a3) - /* save the user space access flag */ - csrr s0, CSR_STATUS + /* Save and clear the user space access flag. */ + li s1, SR_SUM + csrrc s0, CSR_STATUS, s1 REG_S s0, TASK_THREAD_SUM_RA(a3) /* Save the kernel shadow call stack pointer */ scs_save_current /* Restore context from next->thread */ REG_L s0, TASK_THREAD_SUM_RA(a4) - li s1, SR_SUM and s0, s0, s1 csrs CSR_STATUS, s0 REG_L ra, TASK_THREAD_RA_RA(a4) diff --git a/arch/riscv/kernel/kernel_mode_fpu.c b/arch/riscv/kernel/kernel_mode_fpu.c index 0ac8348876c499..03d847fbfcf68e 100644 --- a/arch/riscv/kernel/kernel_mode_fpu.c +++ b/arch/riscv/kernel/kernel_mode_fpu.c @@ -14,7 +14,7 @@ void kernel_fpu_begin(void) { preempt_disable(); - fstate_save(current, task_pt_regs(current)); + fstate_save_preempt_off(current, task_pt_regs(current)); csr_set(CSR_SSTATUS, SR_FS); } EXPORT_SYMBOL_GPL(kernel_fpu_begin); @@ -22,7 +22,7 @@ EXPORT_SYMBOL_GPL(kernel_fpu_begin); void kernel_fpu_end(void) { csr_clear(CSR_SSTATUS, SR_FS); - fstate_restore(current, task_pt_regs(current)); + fstate_restore_preempt_off(current, task_pt_regs(current)); preempt_enable(); } EXPORT_SYMBOL_GPL(kernel_fpu_end); diff --git a/arch/riscv/kernel/kgdb.c b/arch/riscv/kernel/kgdb.c index 0bf629204c76a4..b833408494f933 100644 --- a/arch/riscv/kernel/kgdb.c +++ b/arch/riscv/kernel/kgdb.c @@ -319,13 +319,28 @@ static int kgdb_riscv_kgdbbreak(unsigned long addr) return kgdb_has_hit_break(addr); } +static int kgdb_riscv_handle(struct die_args *args, unsigned long cmd, + int type) +{ + struct pt_regs *regs = args->regs; + + if (kgdb_handle_exception(type == KGDB_SW_SINGLE_STEP ? 0 : 1, + args->signr, cmd, regs)) + return NOTIFY_DONE; + + if (type == KGDB_COMPILED_BREAK) + regs->epc += 4; + + return NOTIFY_STOP; +} + static int kgdb_riscv_notify(struct notifier_block *self, unsigned long cmd, void *ptr) { struct die_args *args = (struct die_args *)ptr; struct pt_regs *regs = args->regs; unsigned long flags; - int type; + int type, ret; if (user_mode(regs)) return NOTIFY_DONE; @@ -335,17 +350,10 @@ static int kgdb_riscv_notify(struct notifier_block *self, unsigned long cmd, return NOTIFY_DONE; local_irq_save(flags); - - if (kgdb_handle_exception(type == KGDB_SW_SINGLE_STEP ? 0 : 1, - args->signr, cmd, regs)) - return NOTIFY_DONE; - - if (type == KGDB_COMPILED_BREAK) - regs->epc += 4; - + ret = kgdb_riscv_handle(args, cmd, type); local_irq_restore(flags); - return NOTIFY_STOP; + return ret; } static struct notifier_block kgdb_notifier = { diff --git a/arch/riscv/kernel/probes/uprobes.c b/arch/riscv/kernel/probes/uprobes.c index eb177d0ce8ab0e..dbb15346319729 100644 --- a/arch/riscv/kernel/probes/uprobes.c +++ b/arch/riscv/kernel/probes/uprobes.c @@ -126,6 +126,12 @@ bool arch_uretprobe_is_alive(struct return_instance *ret, enum rp_check ctx, return regs->sp < ret->stack; } +bool arch_uprobe_regs_writable(int off, int size) +{ + /* epc, from ra to t6. */ + return off + size <= offsetof(struct pt_regs, status); +} + unsigned long arch_uretprobe_hijack_return_addr(unsigned long trampoline_vaddr, struct pt_regs *regs) diff --git a/arch/riscv/kernel/signal.c b/arch/riscv/kernel/signal.c index 59784dc117e454..6f6f3315bc0952 100644 --- a/arch/riscv/kernel/signal.c +++ b/arch/riscv/kernel/signal.c @@ -123,7 +123,9 @@ static long __restore_v_state(struct pt_regs *regs, void __user *sc_vec) * to avoid getting the vstate incorrectly clobbered by the * discarded vector state. */ + preempt_disable(); riscv_v_vstate_set_restore(current, regs); + preempt_enable(); /* Copy everything of __sc_riscv_v_state except datap. */ err = __copy_from_user(¤t->thread.vstate, &state->v_state, diff --git a/arch/riscv/kernel/unaligned_access_speed.c b/arch/riscv/kernel/unaligned_access_speed.c index 67f1a03716597a..323ccfcfbbb726 100644 --- a/arch/riscv/kernel/unaligned_access_speed.c +++ b/arch/riscv/kernel/unaligned_access_speed.c @@ -322,7 +322,7 @@ static int __init set_unaligned_scalar_speed_param(char *str) else if (!strcmp(str, speed_str[RISCV_HWPROBE_MISALIGNED_SCALAR_UNSUPPORTED])) unaligned_scalar_speed_param = RISCV_HWPROBE_MISALIGNED_SCALAR_UNSUPPORTED; else - return -EINVAL; + return 0; return 1; } @@ -337,7 +337,7 @@ static int __init set_unaligned_vector_speed_param(char *str) else if (!strcmp(str, speed_str[RISCV_HWPROBE_MISALIGNED_VECTOR_UNSUPPORTED])) unaligned_vector_speed_param = RISCV_HWPROBE_MISALIGNED_VECTOR_UNSUPPORTED; else - return -EINVAL; + return 0; return 1; } diff --git a/arch/riscv/kvm/aia_device.c b/arch/riscv/kvm/aia_device.c index 97833a04268a9c..e79b92882ea800 100644 --- a/arch/riscv/kvm/aia_device.c +++ b/arch/riscv/kvm/aia_device.c @@ -10,7 +10,9 @@ #include #include #include +#include #include +#include #include static int aia_create(struct kvm_device *dev, u32 type) @@ -142,17 +144,37 @@ static int aia_config(struct kvm *kvm, unsigned long type, return 0; } +static int aia_check_addr_range(struct kvm *kvm, u64 addr, u64 alignment, + u64 size) +{ + u64 end; + + if (!IS_ALIGNED(addr, alignment)) + return -EINVAL; + + if (check_add_overflow(addr, size, &end)) + return -EINVAL; + + if (end > kvm_riscv_gstage_gpa_size(kvm->arch.pgd_levels)) + return -E2BIG; + + return 0; +} + static int aia_aplic_addr(struct kvm *kvm, u64 *addr, bool write) { struct kvm_aia *aia = &kvm->arch.aia; + int ret; if (write) { /* Writes can only be done before irqchip is initialized */ if (kvm_riscv_aia_initialized(kvm)) return -EBUSY; - if (*addr & (KVM_DEV_RISCV_APLIC_ALIGN - 1)) - return -EINVAL; + ret = aia_check_addr_range(kvm, *addr, KVM_DEV_RISCV_APLIC_ALIGN, + KVM_DEV_RISCV_APLIC_SIZE); + if (ret) + return ret; aia->aplic_addr = *addr; } else @@ -166,6 +188,7 @@ static int aia_imsic_addr(struct kvm *kvm, u64 *addr, { struct kvm_vcpu *vcpu; struct kvm_vcpu_aia *vcpu_aia; + int ret; vcpu = kvm_get_vcpu(kvm, vcpu_idx); if (!vcpu) @@ -177,8 +200,10 @@ static int aia_imsic_addr(struct kvm *kvm, u64 *addr, if (kvm_riscv_aia_initialized(kvm)) return -EBUSY; - if (*addr & (KVM_DEV_RISCV_IMSIC_ALIGN - 1)) - return -EINVAL; + ret = aia_check_addr_range(kvm, *addr, KVM_DEV_RISCV_IMSIC_ALIGN, + KVM_DEV_RISCV_IMSIC_SIZE); + if (ret) + return ret; } mutex_lock(&vcpu->mutex); @@ -248,6 +273,15 @@ static int aia_init(struct kvm *kvm) if (aia->nr_sources && aia->aplic_addr == KVM_RISCV_AIA_UNDEF_ADDR) return -EINVAL; + /* The GPA width may change after setting APLIC's address on an empty VM. */ + if (aia->nr_sources) { + ret = aia_check_addr_range(kvm, aia->aplic_addr, + KVM_DEV_RISCV_APLIC_ALIGN, + KVM_DEV_RISCV_APLIC_SIZE); + if (ret) + return ret; + } + /* Group index bits must not overlap guest and HART index bits. */ if (aia->nr_group_bits && aia->nr_group_shift < (IMSIC_MMIO_PAGE_SHIFT + @@ -269,6 +303,13 @@ static int aia_init(struct kvm *kvm) goto fail_cleanup_imsics; } + /* The GPA width may change after setting IMSIC addresses on an empty VM. */ + ret = aia_check_addr_range(kvm, vaia->imsic_addr, + KVM_DEV_RISCV_IMSIC_ALIGN, + KVM_DEV_RISCV_IMSIC_SIZE); + if (ret) + goto fail_cleanup_imsics; + /* All IMSICs should have matching base PPN */ if (base_ppn == KVM_RISCV_AIA_UNDEF_ADDR) base_ppn = aia_imsic_ppn(aia, vaia->imsic_addr); diff --git a/arch/riscv/kvm/gstage.c b/arch/riscv/kvm/gstage.c index be70607a33ea03..0aace3215d3e83 100644 --- a/arch/riscv/kvm/gstage.c +++ b/arch/riscv/kvm/gstage.c @@ -456,6 +456,28 @@ bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage, return flush; } +/* + * Clear every G-stage mapping and free all page tables below the PGD. + * kvm_riscv_gstage_unmap_range() only clears leaf PTEs and leaves the + * page tables in place, so it cannot be used to tear down a G-stage. + */ +bool kvm_riscv_gstage_unmap_all(struct kvm_gstage *gstage) +{ + u32 level = gstage->pgd_levels - 1; + pte_t *pgd = (pte_t *)gstage->pgd; + unsigned long i, page_size; + bool flush = false; + + if (gstage_level_to_page_size(gstage, level, &page_size)) + return false; + + for (i = 0; i < kvm_riscv_gstage_pgd_size / sizeof(pte_t); i++) + flush |= kvm_riscv_gstage_op_pte(gstage, i * page_size, &pgd[i], + level, GSTAGE_OP_CLEAR); + + return flush; +} + bool kvm_riscv_gstage_wp_range(struct kvm_gstage *gstage, gpa_t start, gpa_t end) { int ret; diff --git a/arch/riscv/kvm/main.c b/arch/riscv/kvm/main.c index 89568ccce01de5..0725c8e03c6ad4 100644 --- a/arch/riscv/kvm/main.c +++ b/arch/riscv/kvm/main.c @@ -15,11 +15,13 @@ #include #include #include +#include #include static DEFINE_PER_CPU(bool, kvm_riscv_virtualization_enabled); DEFINE_STATIC_KEY_FALSE(kvm_riscv_vsstage_tlb_no_gpa); +DEFINE_STATIC_KEY_FALSE(kvm_riscv_no_xenvcfg); static void kvm_riscv_setup_vendor_features(void) { @@ -29,6 +31,13 @@ static void kvm_riscv_setup_vendor_features(void) static_branch_enable(&kvm_riscv_vsstage_tlb_no_gpa); kvm_info("VS-stage TLB does not cache guest physical address and VMID\n"); } + + /* SiFive P550 (ESWIN EIC7700X): H on a 1.11 base, no henvcfg/senvcfg */ + if (riscv_cached_mvendorid(0) == SIFIVE_VENDOR_ID && + riscv_cached_marchid(0) == 0x8000000000000008ULL) { + static_branch_enable(&kvm_riscv_no_xenvcfg); + kvm_info("henvcfg and senvcfg CSRs not implemented\n"); + } } long kvm_arch_dev_ioctl(struct file *filp, diff --git a/arch/riscv/kvm/mmu.c b/arch/riscv/kvm/mmu.c index 738d9ee1eac9d6..6861c0e2728d58 100644 --- a/arch/riscv/kvm/mmu.c +++ b/arch/riscv/kvm/mmu.c @@ -591,14 +591,15 @@ static bool kvm_riscv_mmu_dirty_log_write_fault_fast(struct kvm *kvm, dirty_marked = true; } - if ((pte_val(old_pte) & (_PAGE_WRITE | _PAGE_DIRTY)) == - (_PAGE_WRITE | _PAGE_DIRTY)) { + if ((pte_val(old_pte) & + (_PAGE_WRITE | _PAGE_DIRTY | _PAGE_ACCESSED)) == + (_PAGE_WRITE | _PAGE_DIRTY | _PAGE_ACCESSED)) { new_pte = old_pte; ret = true; break; } - new_pte = pte_mkdirty(pte_mkwrite_novma(old_pte)); + new_pte = pte_mkyoung(pte_mkdirty(pte_mkwrite_novma(old_pte))); if (kvm_riscv_gstage_try_update_pte(&gstage, ptep_level, gpa, ptep, old_pte, new_pte)) { @@ -831,8 +832,7 @@ void kvm_riscv_mmu_free_pgd(struct kvm *kvm) write_lock(&kvm->mmu_lock); if (kvm->arch.pgd) { kvm_riscv_gstage_init(&gstage, kvm); - flush = kvm_riscv_gstage_unmap_range(&gstage, 0UL, - kvm_riscv_gstage_gpa_size(kvm->arch.pgd_levels), false); + flush = kvm_riscv_gstage_unmap_all(&gstage); pgd = READ_ONCE(kvm->arch.pgd); kvm->arch.pgd = NULL; kvm->arch.pgd_phys = 0; @@ -845,8 +845,6 @@ void kvm_riscv_mmu_free_pgd(struct kvm *kvm) if (pgd) free_pages((unsigned long)pgd, get_order(kvm_riscv_gstage_pgd_size)); - - kvm_mmu_free_memory_cache(&kvm->arch.pgd_split_page_cache); } void kvm_riscv_mmu_update_hgatp(struct kvm_vcpu *vcpu) diff --git a/arch/riscv/kvm/vcpu.c b/arch/riscv/kvm/vcpu.c index dd786f758eb76a..570b6864e94c0f 100644 --- a/arch/riscv/kvm/vcpu.c +++ b/arch/riscv/kvm/vcpu.c @@ -239,11 +239,6 @@ int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu) !kvm_riscv_vcpu_stopped(vcpu) && !vcpu->arch.pause); } -int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu) -{ - return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE; -} - bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu) { return (vcpu->arch.guest_context.sstatus & SR_SPP) ? true : false; @@ -775,7 +770,8 @@ static __always_inline void kvm_riscv_vcpu_swap_in_guest_state(struct kvm_vcpu * struct kvm_vcpu_csr *csr = &vcpu->arch.guest_csr; vcpu->arch.host_scounteren = csr_swap(CSR_SCOUNTEREN, csr->scounteren); - vcpu->arch.host_senvcfg = csr_swap(CSR_SENVCFG, csr->senvcfg); + if (!static_branch_unlikely(&kvm_riscv_no_xenvcfg)) + vcpu->arch.host_senvcfg = csr_swap(CSR_SENVCFG, csr->senvcfg); if (riscv_has_extension_unlikely(RISCV_ISA_EXT_SMSTATEEN)) vcpu->arch.host_sstateen0 = csr_swap(CSR_SSTATEEN0, smcsr->sstateen0); if (riscv_has_extension_unlikely(RISCV_ISA_EXT_ZICFISS)) @@ -789,7 +785,8 @@ static __always_inline void kvm_riscv_vcpu_swap_in_host_state(struct kvm_vcpu *v struct kvm_vcpu_csr *csr = &vcpu->arch.guest_csr; csr->scounteren = csr_swap(CSR_SCOUNTEREN, vcpu->arch.host_scounteren); - csr->senvcfg = csr_swap(CSR_SENVCFG, vcpu->arch.host_senvcfg); + if (!static_branch_unlikely(&kvm_riscv_no_xenvcfg)) + csr->senvcfg = csr_swap(CSR_SENVCFG, vcpu->arch.host_senvcfg); if (riscv_has_extension_unlikely(RISCV_ISA_EXT_SMSTATEEN)) smcsr->sstateen0 = csr_swap(CSR_SSTATEEN0, vcpu->arch.host_sstateen0); if (riscv_has_extension_unlikely(RISCV_ISA_EXT_ZICFISS)) diff --git a/arch/riscv/kvm/vcpu_config.c b/arch/riscv/kvm/vcpu_config.c index b68aa830aaf51c..9b8e4f1f12f43c 100644 --- a/arch/riscv/kvm/vcpu_config.c +++ b/arch/riscv/kvm/vcpu_config.c @@ -82,9 +82,11 @@ void kvm_riscv_vcpu_config_load(struct kvm_vcpu *vcpu) nsh = nacl_shmem(); nacl_csr_write(nsh, CSR_HEDELEG, cfg->hedeleg); nacl_csr_write(nsh, CSR_HIDELEG, cfg->hideleg); - nacl_csr_write(nsh, CSR_HENVCFG, cfg->henvcfg); - if (IS_ENABLED(CONFIG_32BIT)) - nacl_csr_write(nsh, CSR_HENVCFGH, cfg->henvcfg >> 32); + if (!static_branch_unlikely(&kvm_riscv_no_xenvcfg)) { + nacl_csr_write(nsh, CSR_HENVCFG, cfg->henvcfg); + if (IS_ENABLED(CONFIG_32BIT)) + nacl_csr_write(nsh, CSR_HENVCFGH, cfg->henvcfg >> 32); + } if (riscv_has_extension_unlikely(RISCV_ISA_EXT_SMSTATEEN)) { nacl_csr_write(nsh, CSR_HSTATEEN0, cfg->hstateen0); if (IS_ENABLED(CONFIG_32BIT)) @@ -93,9 +95,11 @@ void kvm_riscv_vcpu_config_load(struct kvm_vcpu *vcpu) } else { csr_write(CSR_HEDELEG, cfg->hedeleg); csr_write(CSR_HIDELEG, cfg->hideleg); - csr_write(CSR_HENVCFG, cfg->henvcfg); - if (IS_ENABLED(CONFIG_32BIT)) - csr_write(CSR_HENVCFGH, cfg->henvcfg >> 32); + if (!static_branch_unlikely(&kvm_riscv_no_xenvcfg)) { + csr_write(CSR_HENVCFG, cfg->henvcfg); + if (IS_ENABLED(CONFIG_32BIT)) + csr_write(CSR_HENVCFGH, cfg->henvcfg >> 32); + } if (riscv_has_extension_unlikely(RISCV_ISA_EXT_SMSTATEEN)) { csr_write(CSR_HSTATEEN0, cfg->hstateen0); if (IS_ENABLED(CONFIG_32BIT)) diff --git a/arch/riscv/kvm/vcpu_pmu.c b/arch/riscv/kvm/vcpu_pmu.c index e095d1ff439f19..ea788619091ad1 100644 --- a/arch/riscv/kvm/vcpu_pmu.c +++ b/arch/riscv/kvm/vcpu_pmu.c @@ -560,7 +560,7 @@ int kvm_riscv_vcpu_pmu_ctr_info(struct kvm_vcpu *vcpu, unsigned long cidx, { struct kvm_pmu *kvpmu = vcpu_to_pmu(vcpu); - if (cidx >= RISCV_KVM_MAX_COUNTERS || cidx == 1) { + if (cidx >= kvm_pmu_num_counters(kvpmu) || cidx == 1) { retdata->err_val = SBI_ERR_INVALID_PARAM; return 0; } diff --git a/arch/riscv/kvm/vcpu_sbi_fwft.c b/arch/riscv/kvm/vcpu_sbi_fwft.c index 7d0aaeff537b27..79a83f1145f6ed 100644 --- a/arch/riscv/kvm/vcpu_sbi_fwft.c +++ b/arch/riscv/kvm/vcpu_sbi_fwft.c @@ -132,6 +132,12 @@ static long kvm_sbi_fwft_envcfg_flag_get(struct kvm_vcpu *vcpu, return SBI_SUCCESS; } +/* Features implemented by setting bits in henvcfg need the CSR to exist */ +static inline bool kvm_sbi_fwft_have_henvcfg(void) +{ + return !static_branch_unlikely(&kvm_riscv_no_xenvcfg); +} + static bool kvm_sbi_fwft_misaligned_delegation_supported(struct kvm_vcpu *vcpu) { return misaligned_traps_can_delegate(); @@ -208,7 +214,8 @@ static long kvm_sbi_fwft_set_cfi(struct kvm_vcpu *vcpu, static bool kvm_sbi_fwft_landing_pad_supported(struct kvm_vcpu *vcpu) { - return riscv_isa_extension_available(vcpu->arch.isa, ZICFILP); + return kvm_sbi_fwft_have_henvcfg() && + riscv_isa_extension_available(vcpu->arch.isa, ZICFILP); } static void kvm_sbi_fwft_reset_landing_pad(struct kvm_vcpu *vcpu) @@ -236,7 +243,8 @@ static long kvm_sbi_fwft_get_landing_pad(struct kvm_vcpu *vcpu, static bool kvm_sbi_fwft_shadow_stack_supported(struct kvm_vcpu *vcpu) { - return riscv_isa_extension_available(vcpu->arch.isa, ZICFISS); + return kvm_sbi_fwft_have_henvcfg() && + riscv_isa_extension_available(vcpu->arch.isa, ZICFISS); } static void kvm_sbi_fwft_reset_shadow_stack(struct kvm_vcpu *vcpu) @@ -264,8 +272,9 @@ static long kvm_sbi_fwft_get_shadow_stack(struct kvm_vcpu *vcpu, static bool kvm_sbi_fwft_pte_ad_hw_updating_supported(struct kvm_vcpu *vcpu) { - return riscv_isa_extension_available(vcpu->arch.isa, SVADU) && - riscv_isa_extension_available(vcpu->arch.isa, SVADE); + return kvm_sbi_fwft_have_henvcfg() && + riscv_isa_extension_available(vcpu->arch.isa, SVADU) && + riscv_isa_extension_available(vcpu->arch.isa, SVADE); } static void kvm_sbi_fwft_reset_pte_ad_hw_updating(struct kvm_vcpu *vcpu) @@ -305,7 +314,8 @@ static bool try_to_set_pmm(unsigned long value) static bool kvm_sbi_fwft_pointer_masking_pmlen_supported(struct kvm_vcpu *vcpu) { - return riscv_isa_extension_available(vcpu->arch.isa, SMNPM); + return kvm_sbi_fwft_have_henvcfg() && + riscv_isa_extension_available(vcpu->arch.isa, SMNPM); } static bool kvm_sbi_fwft_pointer_masking_pmlen_init(struct kvm_vcpu *vcpu) diff --git a/arch/riscv/kvm/vm.c b/arch/riscv/kvm/vm.c index 58500a19b33bdb..cb8f604d3b54e9 100644 --- a/arch/riscv/kvm/vm.c +++ b/arch/riscv/kvm/vm.c @@ -54,6 +54,8 @@ void kvm_arch_destroy_vm(struct kvm *kvm) kvm_destroy_vcpus(kvm); kvm_riscv_aia_destroy_vm(kvm); + + kvm_mmu_free_memory_cache(&kvm->arch.pgd_split_page_cache); } int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irql, @@ -251,7 +253,8 @@ int kvm_vm_ioctl_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) mutex_lock(&kvm->lock); mutex_lock(&kvm->slots_lock); - if (kvm->created_vcpus || !kvm_are_all_memslots_empty(kvm)) + if (kvm->created_vcpus || !kvm_are_all_memslots_empty(kvm) || + kvm_riscv_aia_initialized(kvm)) r = -EBUSY; else kvm->arch.pgd_levels = new_levels; diff --git a/arch/riscv/mm/init.c b/arch/riscv/mm/init.c index 070ee69eabb381..bbc2d8cb4627ec 100644 --- a/arch/riscv/mm/init.c +++ b/arch/riscv/mm/init.c @@ -294,13 +294,6 @@ static void __init setup_bootmem(void) reserve_initrd_mem(); - /* - * No allocation should be done before reserving the memory as defined - * in the device tree, otherwise the allocation could end up in a - * reserved region. - */ - early_init_fdt_scan_reserved_mem(); - /* * If DTB is built in, no need to reserve its memblock. * Otherwise, do reserve it but avoid using @@ -309,6 +302,13 @@ static void __init setup_bootmem(void) */ if (!IS_ENABLED(CONFIG_BUILTIN_DTB)) memblock_reserve(dtb_early_pa, fdt_totalsize(dtb_early_va)); + + /* + * No allocation should be done before reserving the memory as defined + * in the device tree, otherwise the allocation could end up in a + * reserved region. + */ + early_init_fdt_scan_reserved_mem(); } #ifdef CONFIG_RELOCATABLE @@ -1501,10 +1501,17 @@ struct execmem_info __init *execmem_arch_setup(void) #endif /* CONFIG_EXECMEM */ #ifdef CONFIG_MEMORY_HOTPLUG +static void __meminit free_pgtable_page(struct page *page) +{ + if (PageReserved(page)) + free_reserved_page(page); + else + pagetable_free(page_ptdesc(page)); +} + static void __meminit free_pte_table(pte_t *pte_start, pmd_t *pmd) { struct page *page = pmd_page(*pmd); - struct ptdesc *ptdesc = page_ptdesc(page); pte_t *pte; int i; @@ -1514,18 +1521,13 @@ static void __meminit free_pte_table(pte_t *pte_start, pmd_t *pmd) return; } - pagetable_dtor(ptdesc); - if (PageReserved(page)) - free_reserved_page(page); - else - pagetable_free(ptdesc); + free_pgtable_page(page); pmd_clear(pmd); } -static void __meminit free_pmd_table(pmd_t *pmd_start, pud_t *pud, bool is_vmemmap) +static void __meminit free_pmd_table(pmd_t *pmd_start, pud_t *pud) { struct page *page = pud_page(*pud); - struct ptdesc *ptdesc = page_ptdesc(page); pmd_t *pmd; int i; @@ -1535,12 +1537,7 @@ static void __meminit free_pmd_table(pmd_t *pmd_start, pud_t *pud, bool is_vmemm return; } - if (!is_vmemmap) - pagetable_dtor(ptdesc); - if (PageReserved(page)) - free_reserved_page(page); - else - pagetable_free(ptdesc); + free_pgtable_page(page); pud_clear(pud); } @@ -1556,10 +1553,7 @@ static void __meminit free_pud_table(pud_t *pud_start, p4d_t *p4d) return; } - if (PageReserved(page)) - free_reserved_page(page); - else - __free_pages(page, 0); + free_pgtable_page(page); p4d_clear(p4d); } @@ -1660,7 +1654,7 @@ static void __meminit remove_pud_mapping(pud_t *pud_base, unsigned long addr, un remove_pmd_mapping(pmd_base, addr, next, is_vmemmap, altmap); if (pgtable_l4_enabled()) - free_pmd_table(pmd_base, pudp, is_vmemmap); + free_pmd_table(pmd_base, pudp); } } diff --git a/arch/s390/appldata/appldata_base.c b/arch/s390/appldata/appldata_base.c index 836c51da18f4b2..f10b2f040cc20d 100644 --- a/arch/s390/appldata/appldata_base.c +++ b/arch/s390/appldata/appldata_base.c @@ -360,21 +360,25 @@ appldata_generic_handler(const struct ctl_table *ctl, int write, pr_err("Starting the data collection for %s " "failed with rc=%d\n", ops->name, rc); module_put(ops->owner); + rc = -EIO; } else ops->active = 1; } else if (!active && (ops->active == 1)) { - ops->active = 0; rc = appldata_diag(ops->record_nr, APPLDATA_STOP_REC, (unsigned long) ops->data, ops->size, ops->mod_lvl); - if (rc != 0) + if (rc != 0) { pr_err("Stopping the data collection for %s " "failed with rc=%d\n", ops->name, rc); - module_put(ops->owner); + rc = -EIO; + } else { + ops->active = 0; + module_put(ops->owner); + } } mutex_unlock(&appldata_ops_mutex); module_put(ops->owner); - return 0; + return rc; } /*************************** /proc stuff *******************************/ diff --git a/arch/s390/include/asm/kvm_host_arm64.h b/arch/s390/include/asm/kvm_host_arm64.h index 82343e723ebf40..3e69724f17c907 100644 --- a/arch/s390/include/asm/kvm_host_arm64.h +++ b/arch/s390/include/asm/kvm_host_arm64.h @@ -8,6 +8,7 @@ #include #define vcpu_gp_regs(v) ((v)->arch.sae_block.gpr) +enum vcpu_sysreg; #include #include @@ -63,11 +64,10 @@ struct kvm_vcpu_arch { /* * Don't run the guest (internal implementation need). * - * Contrary to the flags above, this is set/cleared outside of - * a vcpu context, and thus cannot be mixed with the flags - * themselves (or the flag accesses need to be made atomic). + * Contrary to the flags above, this is updated outside of + * a vcpu context, and thus cannot be mixed with the flags. */ - bool pause; + atomic_t pause; /* vcpu power state */ struct kvm_mp_state mp_state; diff --git a/arch/s390/include/asm/ptrace.h b/arch/s390/include/asm/ptrace.h index 3e56ef8c268b79..d8f3a2dbe68940 100644 --- a/arch/s390/include/asm/ptrace.h +++ b/arch/s390/include/asm/ptrace.h @@ -15,14 +15,14 @@ #define PIF_SYSCALL 0 /* inside a system call */ #define PIF_PSW_ADDR_ADJUSTED 1 /* psw address has been adjusted */ -#define PIF_SYSCALL_RET_SET 2 /* return value was set via ptrace */ +#define PIF_SYSCALL_ENTRY 2 /* ptrace gpr2 access redirected to syscall nr */ #define PIF_FTRACE_FULL_REGS 3 /* all register contents valid (ftrace) */ #define PIF_WARN_TRAP_SKIPPED 4 /* __WARN_trap() was skipped */ #define PIF_PGM_CHECK 5 /* inside a program check */ #define _PIF_SYSCALL BIT(PIF_SYSCALL) #define _PIF_ADDR_PSW_ADJUSTED BIT(PIF_PSW_ADDR_ADJUSTED) -#define _PIF_SYSCALL_RET_SET BIT(PIF_SYSCALL_RET_SET) +#define _PIF_SYSCALL_ENTRY BIT(PIF_SYSCALL_ENTRY) #define _PIF_FTRACE_FULL_REGS BIT(PIF_FTRACE_FULL_REGS) #define _PIF_WARN_TRAP_SKIPPED BIT(PIF_WARN_TRAP_SKIPPED) #define _PIF_PGM_CHECK BIT(PIF_PGM_CHECK) diff --git a/arch/s390/include/asm/syscall.h b/arch/s390/include/asm/syscall.h index 5f310caad1fcec..47f66202977f7a 100644 --- a/arch/s390/include/asm/syscall.h +++ b/arch/s390/include/asm/syscall.h @@ -59,7 +59,6 @@ static inline void syscall_set_return_value(struct task_struct *task, struct pt_regs *regs, int error, long val) { - set_pt_regs_flag(regs, PIF_SYSCALL_RET_SET); regs->gprs[2] = error ? error : val; } diff --git a/arch/s390/kernel/cert_store.c b/arch/s390/kernel/cert_store.c index 998f2da5617500..6e518ff3832280 100644 --- a/arch/s390/kernel/cert_store.c +++ b/arch/s390/kernel/cert_store.c @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -45,6 +46,9 @@ static debug_info_t *cert_store_dbf; static debug_info_t *cert_store_hexdump; +/* Task currently running refresh_store(). Written under cs_refresh_lock. */ +static struct task_struct *cs_refresh_task; + #define pr_dbf_msg(fmt, ...) \ debug_sprintf_event(cert_store_dbf, 3, fmt "\n", ## __VA_ARGS__) @@ -147,12 +151,24 @@ static void cert_store_key_describe(const struct key *key, struct seq_file *m) seq_printf(m, ": %u", key->datalen); } +/* + * Only the kernel may create keys of this type. Accept the task which runs + * refresh_store(), as it cannot execute userspace during the refresh. + */ +static int cert_store_key_vet_description(const char *description) +{ + if (READ_ONCE(cs_refresh_task) != current) + return -EPERM; + return 0; +} + /* * Certificate store key type takes over properties of * user key but cannot be updated. */ static struct key_type key_type_cert_store_key = { .name = CERT_STORE_KEY_TYPE_NAME, + .vet_description = cert_store_key_vet_description, .preparse = user_preparse, .free_preparse = user_free_preparse, .instantiate = generic_key_instantiate, @@ -180,6 +196,7 @@ static void pr_dbf_vce(const struct vce *e) { unsigned char vc_name[VC_NAME_LEN_BYTES + 1]; char log_string[VC_NAME_LEN_BYTES + 40]; + u32 data_len = 0; pr_dbf_msg("VCE Header:"); pr_dbf_msg("vce_hdr.vce_length: %d", e->vce_hdr.vce_length); @@ -205,11 +222,13 @@ static void pr_dbf_vce(const struct vce *e) debug_text_event(cert_store_hexdump, 3, log_string); /* Certificate data. */ + if (e->vce_hdr.vce_length > sizeof(e->vce_hdr)) + data_len = e->vce_hdr.vce_length - sizeof(e->vce_hdr); debug_text_event(cert_store_hexdump, 3, "VCE: Certificate data start"); - debug_event(cert_store_hexdump, 3, (u8 *)e->cert_data_buf, 128); + debug_event(cert_store_hexdump, 3, (u8 *)e->cert_data_buf, min(data_len, 128U)); debug_text_event(cert_store_hexdump, 3, "VCE: Certificate data end"); - debug_event(cert_store_hexdump, 3, - (u8 *)e->cert_data_buf + e->vce_hdr.vce_length - 128, 128); + if (data_len > 128) + debug_event(cert_store_hexdump, 3, (u8 *)e + e->vce_hdr.vce_length - 128, 128); } static void pr_dbf_vcssb(const struct vcssb *s) @@ -224,7 +243,7 @@ static void pr_dbf_vcssb(const struct vcssb *s) pr_dbf_msg("total_vc_index_count: %u", s->total_vc_index_count); pr_dbf_msg("max_vc_index_count: %u", s->max_vc_index_count); pr_dbf_msg("max_vce_length: %u", s->max_vce_length); - pr_dbf_msg("max_vcxe_length: %u", s->max_vce_length); + pr_dbf_msg("max_vcxe_length: %u", s->max_vcxe_length); pr_dbf_msg("max_single_vcb_length: %u", s->max_single_vcb_length); pr_dbf_msg("total_vcb_length: %u", s->total_vcb_length); pr_dbf_msg("max_single_vcxb_length: %u", s->max_single_vcxb_length); @@ -260,13 +279,11 @@ static int diag320(unsigned long subcode, void *addr) static int check_certificate_hash(const struct vce *vce) { u8 hash[SHA256_DIGEST_SIZE]; - u16 vc_hash_length; u8 *vce_hash; vce_hash = (u8 *)vce + vce->vce_hdr.vc_hash_offset; - vc_hash_length = vce->vce_hdr.vc_hash_length; sha256((u8 *)vce + vce->vce_hdr.vc_offset, vce->vce_hdr.vc_length, hash); - if (memcmp(vce_hash, hash, vc_hash_length) == 0) + if (memcmp(vce_hash, hash, sizeof(hash)) == 0) return 0; pr_dbf_msg("SHA256 hash of received certificate does not match"); @@ -292,6 +309,10 @@ static int check_certificate_valid(const struct vce *vce) pr_dbf_msg("Hash type is not supported"); return -EINVAL; } + if (vce->vce_hdr.vc_hash_length != SHA256_DIGEST_SIZE) { + pr_dbf_msg("Hash length is not supported"); + return -EINVAL; + } return check_certificate_hash(vce); } @@ -307,7 +328,6 @@ static struct key *get_user_session_keyring(void) PTR_ERR(us_keyring_ref)); return ERR_PTR(-ENOKEY); } - key_ref_put(us_keyring_ref); return key_ref_to_ptr(us_keyring_ref); } @@ -315,34 +335,43 @@ static struct key *get_user_session_keyring(void) static int invalidate_keyring_keys(struct key *keyring) { unsigned long num_keys, key_index; - size_t keyring_payload_len; + long keyring_payload_len, rc; key_serial_t *key_array; struct key *current_key; - int rc; - keyring_payload_len = key_type_keyring.read(keyring, NULL, 0); - num_keys = keyring_payload_len / sizeof(key_serial_t); - key_array = kzalloc_objs(key_serial_t, num_keys); - if (!key_array) - return -ENOMEM; + scoped_guard(rwsem_read, &keyring->sem) { + keyring_payload_len = key_type_keyring.read(keyring, NULL, 0); + if (keyring_payload_len <= 0) + return keyring_payload_len; + + num_keys = keyring_payload_len / sizeof(key_serial_t); + key_array = kzalloc_objs(key_serial_t, num_keys); + if (!key_array) + return -ENOMEM; + + rc = key_type_keyring.read(keyring, (char *)key_array, keyring_payload_len); + } - rc = key_type_keyring.read(keyring, (char *)key_array, keyring_payload_len); if (rc != keyring_payload_len) { pr_dbf_msg("Couldn't read keyring payload"); + rc = rc < 0 ? rc : -EINVAL; goto out; } + rc = 0; for (key_index = 0; key_index < num_keys; key_index++) { current_key = key_lookup(key_array[key_index]); + if (IS_ERR(current_key)) + continue; pr_dbf_msg("Invalidating key %08x", current_key->serial); + rc = key_unlink(keyring, current_key); + if (rc) + pr_dbf_msg("Couldn't unlink key %08x: %ld", current_key->serial, rc); key_invalidate(current_key); key_put(current_key); - rc = key_unlink(keyring, current_key); - if (rc) { - pr_dbf_msg("Couldn't unlink key %08x: %d", current_key->serial, rc); + if (rc) break; - } } out: kfree(key_array); @@ -351,29 +380,25 @@ static int invalidate_keyring_keys(struct key *keyring) static struct key *find_cs_keyring(void) { + struct key *us_keyring; key_ref_t cs_keyring_ref; - struct key *cs_keyring; - cs_keyring_ref = keyring_search(make_key_ref(get_user_session_keyring(), true), - &key_type_keyring, CERT_STORE_KEYRING_NAME, - false); - if (!IS_ERR(cs_keyring_ref)) { - cs_keyring = key_ref_to_ptr(cs_keyring_ref); - key_ref_put(cs_keyring_ref); - goto found; + us_keyring = get_user_session_keyring(); + if (!IS_ERR(us_keyring)) { + cs_keyring_ref = keyring_search(make_key_ref(us_keyring, true), + &key_type_keyring, + CERT_STORE_KEYRING_NAME, + false); + key_put(us_keyring); + if (!IS_ERR(cs_keyring_ref)) + return key_ref_to_ptr(cs_keyring_ref); } - /* Search default locations: thread, process, session keyrings */ - cs_keyring = request_key(&key_type_keyring, CERT_STORE_KEYRING_NAME, NULL); - if (IS_ERR(cs_keyring)) - return NULL; - key_put(cs_keyring); -found: - return cs_keyring; + return NULL; } static void cleanup_cs_keys(void) { - struct key *cs_keyring; + struct key *cs_keyring, *us_keyring; cs_keyring = find_cs_keyring(); if (!cs_keyring) @@ -389,22 +414,39 @@ static void cleanup_cs_keys(void) keyring_clear(cs_keyring); key_invalidate(cs_keyring); + us_keyring = get_user_session_keyring(); + if (!IS_ERR(us_keyring)) { + key_unlink(us_keyring, cs_keyring); + key_put(us_keyring); + } key_put(cs_keyring); - key_unlink(get_user_session_keyring(), cs_keyring); } static struct key *create_cs_keyring(void) { - static struct key *cs_keyring; + struct key_restriction *restriction; + struct key *cs_keyring, *us_keyring; /* Cleanup previous cs_keyring and all associated keys if any. */ cleanup_cs_keys(); + us_keyring = get_user_session_keyring(); + if (IS_ERR(us_keyring)) + return NULL; + restriction = kzalloc_obj(*restriction); + if (!restriction) { + key_put(us_keyring); + return NULL; + } + /* Reject all links, the kernel bypasses the restriction. */ + restriction->check = restrict_link_reject; cs_keyring = keyring_alloc(CERT_STORE_KEYRING_NAME, GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, current_cred(), (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_VIEW | KEY_USR_READ, KEY_ALLOC_NOT_IN_QUOTA | KEY_ALLOC_SET_KEEP, - NULL, get_user_session_keyring()); + restriction, us_keyring); + key_put(us_keyring); if (IS_ERR(cs_keyring)) { + kfree(restriction); pr_dbf_msg("Can't allocate cert_store keyring"); return NULL; } @@ -467,7 +509,7 @@ static int create_key_from_vce(struct vcssb *vcssb, struct vce *vce, desc, (u8 *)vce + vce->vce_hdr.vc_offset, vce->vce_hdr.vc_length, (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_VIEW | KEY_USR_READ, - KEY_ALLOC_NOT_IN_QUOTA); + KEY_ALLOC_NOT_IN_QUOTA | KEY_ALLOC_BYPASS_RESTRICTION); rc = PTR_ERR_OR_ZERO(newkey); if (rc) { @@ -635,14 +677,6 @@ static int add_certificates_to_keyring(struct vcssb *vcssb, struct key *keyring) pr_info("Added %d of %d keys to cert_store keyring", added, count); - /* - * Do not allow to link more keys to certificate store keyring after all - * the VCEs were processed. - */ - rc = keyring_restrict(make_key_ref(keyring, true), NULL, NULL); - if (rc) - pr_dbf_msg("Failed to set restriction to cert_store keyring (%d)", rc); - return 0; } @@ -652,7 +686,7 @@ static int add_certificates_to_keyring(struct vcssb *vcssb, struct key *keyring) */ static int query_diag320_subcodes(void) { - unsigned long ism[ISM_LEN_DWORDS]; + unsigned long ism[ISM_LEN_DWORDS] = {}; int rc; rc = diag320(0, ism); @@ -710,13 +744,12 @@ static int fill_cs_keyring(void) goto cleanup_keys; rc = add_certificates_to_keyring(vcssb, cs_keyring); + key_put(cs_keyring); if (rc) - goto cleanup_cs_keyring; + goto cleanup_keys; goto out; -cleanup_cs_keyring: - key_put(cs_keyring); cleanup_keys: cleanup_cs_keys(); out: @@ -750,6 +783,7 @@ static ssize_t refresh_store(struct kobject *kobj, struct kobj_attribute *attr, if (rc) return rc; + WRITE_ONCE(cs_refresh_task, current); for (retries = 0; retries < DIAG_MAX_RETRIES; retries++) { /* Request certificates from certificate store. */ rc = fill_cs_keyring(); @@ -758,6 +792,7 @@ static ssize_t refresh_store(struct kobject *kobj, struct kobj_attribute *attr, if (rc != -EAGAIN) break; } + WRITE_ONCE(cs_refresh_task, NULL); cs_status_val = rc; mutex_unlock(&cs_refresh_lock); diff --git a/arch/s390/kernel/ptrace.c b/arch/s390/kernel/ptrace.c index 5202f9a2d9390b..577fb2c3d5a8ea 100644 --- a/arch/s390/kernel/ptrace.c +++ b/arch/s390/kernel/ptrace.c @@ -204,15 +204,24 @@ static unsigned long __peek_user(struct task_struct *child, addr_t addr) addr_t offset, tmp; if (addr < offsetof(struct user, regs.acrs)) { - /* - * psw and gprs are stored on the stack - */ - tmp = *(addr_t *)((addr_t) &task_pt_regs(child)->psw + addr); + struct pt_regs *regs = task_pt_regs(child); + + /* psw and gprs are on the stack. */ + tmp = *(addr_t *)((addr_t)®s->psw + addr); if (addr == offsetof(struct user, regs.psw.mask)) { /* Return a clean psw mask. */ tmp &= PSW_MASK_USER | PSW_MASK_RI; tmp |= PSW_USER_BITS; } + /* + * During system call entry gpr2 contains the return + * value. Redirect reads of gpr2 to int_code so that + * readers see the system call number. + */ + if (addr == offsetof(struct user, regs.gprs[2])) { + if (test_pt_regs_flag(regs, PIF_SYSCALL_ENTRY)) + tmp = syscall_get_nr(child, regs); + } } else if (addr < offsetof(struct user, regs.orig_gpr2)) { /* @@ -347,8 +356,17 @@ static int __poke_user(struct task_struct *child, addr_t addr, addr_t data) } if (addr == offsetof(struct user, regs.gprs[2])) { - if (test_pt_regs_flag(regs, PIF_SYSCALL)) + if (test_pt_regs_flag(regs, PIF_SYSCALL_ENTRY)) { + /* + * System call entry path: only change system + * call number in int_code, but leave gpr2 + * alone, which contains the return value. + */ syscall_set_nr(child, regs, data); + return 0; + } else 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/syscall.c b/arch/s390/kernel/syscall.c index bcc0b76bd868cd..a94bfcef2e8c6f 100644 --- a/arch/s390/kernel/syscall.c +++ b/arch/s390/kernel/syscall.c @@ -117,24 +117,22 @@ void noinstr __do_syscall(struct pt_regs *regs, unsigned long flags) regs->int_code &= ~0xffffUL; regs->int_code |= nr; } - regs->gprs[2] = nr; if (nr == __NR_restart_syscall && !(current->restart_block.arch_data & 1)) { regs->psw.addr = current->restart_block.arch_data; current->restart_block.arch_data = 1; } - - permit = syscall_enter_from_user_mode_work(regs, &nr); - /* - * In the s390 ptrace ABI, both the syscall number and the return value - * use gpr2. However, userspace puts the syscall number either in the - * svc instruction itself, or uses gpr1. To make at least skipping syscalls - * work, the ptrace code sets PIF_SYSCALL_RET_SET, which is checked here - * and if set, the syscall will be skipped. + * gpr2 is the return value register. Set it to -ENOSYS so that a + * skipped system call gets a defined default return value. + * Set PIF_SYSCALL_ENTRY so that ptrace reads and writes to gpr2 + * are redirected to the system call number in int_code. */ - if (unlikely(test_and_clear_pt_regs_flag(regs, PIF_SYSCALL_RET_SET) || !permit)) + syscall_set_return_value(current, regs, -ENOSYS, 0); + set_pt_regs_flag(regs, PIF_SYSCALL_ENTRY); + permit = syscall_enter_from_user_mode_work(regs, &nr); + clear_pt_regs_flag(regs, PIF_SYSCALL_ENTRY); + if (unlikely(!permit)) goto out; - regs->gprs[2] = -ENOSYS; if (likely(nr < NR_syscalls)) { nr = array_index_nospec(nr, NR_syscalls); regs->gprs[2] = sys_call_table[nr](regs); diff --git a/arch/s390/kvm/arm64/Makefile b/arch/s390/kvm/arm64/Makefile index 3f0fe5c9f0a17c..b48dc65b7aaab5 100644 --- a/arch/s390/kvm/arm64/Makefile +++ b/arch/s390/kvm/arm64/Makefile @@ -29,7 +29,7 @@ $(obj)/%-arm64.o: $(src)/%.c FORCE $(call if_changed_rule,cc_o_c) $(call cmd,force_checksrc) -# %-arm64.o stems don't match any kvm-arm64-y entry so Kbuild derives wrong +# %-arm64.o stems don't match any kvm_arm64-y entry so Kbuild derives wrong # KBUILD_MODNAME/KBUILD_MODFILE. Force include a generated header to override. KVM_ARM64_MODNAME_H := $(obj)/generated/kvm_arm64_modname.h ccflags-y += -include $(KVM_ARM64_MODNAME_H) @@ -48,7 +48,7 @@ define filechk_kvm_arm64_modname echo '#undef __KBUILD_MODNAME'; \ echo '#define __KBUILD_MODNAME $(KVM_DEV_NAME)'; \ echo '#undef KBUILD_MODFILE'; \ - echo '#define KBUILD_MODFILE "$(obj)/kvm-arm64"'; \ + echo '#define KBUILD_MODFILE "$(obj)/kvm_arm64"'; \ echo '#endif /* __KVM_ARM64_MODNAME_H */' endef @@ -60,7 +60,7 @@ $(addprefix $(obj)/,$(kvm-arm64-obj)): private part-of-builtin := y ifeq ($(CONFIG_KVM),m) -kvm-arm64-y = $(kvm-arm64-obj) +kvm_arm64-y = $(kvm-arm64-obj) else ifeq ($(CONFIG_KVM),y) @@ -86,7 +86,7 @@ $(obj)/kvm_symbol_list: $(obj)/kvm-unnamespaced.o FORCE # cmd_oc_o_o carries -DKBUILD_MODFILE so generate_builtin_ranges.awk # can attribute kvm-namespaced.o to kvm_arm64 via its .cmd file. -cmd_oc_o_o = $(cmd_objcopy) -DKBUILD_MODFILE='"$(obj)/kvm-arm64"' +cmd_oc_o_o = $(cmd_objcopy) -DKBUILD_MODFILE='"$(obj)/kvm_arm64"' define rule_oc_o_o $(call cmd,objcopy) @printf '%s\n' 'savedcmd_$@ := $(call make-cmd,oc_o_o)' > $(dot-target).cmd @@ -98,7 +98,7 @@ OBJCOPYFLAGS_kvm-namespaced.o := -O $(LD_BFD) --localize-symbols=$(obj)/kvm_symb $(obj)/kvm-namespaced.o: $(obj)/kvm-unnamespaced.o $(obj)/kvm_symbol_list FORCE $(call if_changed_rule,oc_o_o) -kvm-arm64-y = kvm-namespaced.o +kvm_arm64-y = kvm-namespaced.o targets += kvm-unnamespaced.o kvm_symbol_list kvm-namespaced.o @@ -106,5 +106,5 @@ endif clean-files += kvm-unnamespaced.o kvm_symbol_list kvm-namespaced.o -obj-$(CONFIG_KVM) += kvm-arm64.o +obj-$(CONFIG_KVM) += kvm_arm64.o diff --git a/arch/s390/kvm/arm64/copy-arm64c.awk b/arch/s390/kvm/arm64/copy-arm64c.awk index 640a7bcb7e23e2..a318be97c4191d 100644 --- a/arch/s390/kvm/arm64/copy-arm64c.awk +++ b/arch/s390/kvm/arm64/copy-arm64c.awk @@ -42,6 +42,9 @@ BEGIN { print "#endif /* __INCL_GEN_ARM_FILE */" print "#undef __INCL_GEN_ARM_FILE" print "" + print "__diag_push()" + print "__diag_ignore_all(\"-Wunused-function\", \"tolerate unused functions shared from arm64\")" + print "" file_header_done = 1 } @@ -78,5 +81,10 @@ copying { } END { - exit error || !found_marker || copying + ok = !error && found_marker && !copying + if (ok) { + print "" + print "__diag_pop()" + } + exit !ok } diff --git a/arch/s390/kvm/gmap/dat.c b/arch/s390/kvm/gmap/dat.c index ff80d02c9f5643..7a25e41a142392 100644 --- a/arch/s390/kvm/gmap/dat.c +++ b/arch/s390/kvm/gmap/dat.c @@ -159,32 +159,6 @@ bool __must_check dat_crstep_xchg_atomic(union crste *crstep, union crste old, u return cspg_crste(crstep, old, new); } -static void dat_set_storage_key_from_pgste(union pte pte, union pgste pgste) -{ - union skey nkey = { .acc = pgste.acc, .fp = pgste.fp }; - - page_set_storage_key(pte_origin(pte), nkey.skey, 0); -} - -static void dat_move_storage_key(union pte old, union pte new) -{ - page_set_storage_key(pte_origin(new), page_get_storage_key(pte_origin(old)), 1); -} - -static union pgste dat_save_storage_key_into_pgste(union pte pte, union pgste pgste) -{ - union skey skey; - - skey.skey = page_get_storage_key(pte_origin(pte)); - - pgste.acc = skey.acc; - pgste.fp = skey.fp; - pgste.gr |= skey.r; - pgste.gc |= skey.c; - - return pgste; -} - union pgste __dat_ptep_xchg(union pte *ptep, union pgste pgste, union pte new, gfn_t gfn, union asce asce, bool uses_skeys) { @@ -1084,6 +1058,7 @@ int dat_set_prefix_notif_bit(union asce asce, gfn_t gfn) * * %1 if the page state has been altered and the page is to be added to the CBRL * * %0 if the page state has been altered, but the page is not to be added to the CBRL * * %-1 if the page state has not been altered and the page is not to be added to the CBRL + * * %PGM_ADDRESSING if the guest page-table walk failed */ int dat_perform_essa(union asce asce, gfn_t gfn, int orc, union essa_state *state, bool *dirty) { @@ -1092,7 +1067,9 @@ int dat_perform_essa(union asce asce, gfn_t gfn, int orc, union essa_state *stat union pte *ptep; int res = 0; - if (dat_entry_walk(NULL, gfn, asce, 0, TABLE_TYPE_PAGE_TABLE, &crstep, &ptep)) { + if (dat_entry_walk(NULL, gfn, asce, DAT_WALK_ANY, TABLE_TYPE_PAGE_TABLE, &crstep, &ptep)) + return PGM_ADDRESSING; + if (!ptep) { *state = (union essa_state) { .exception = 1 }; return -1; } diff --git a/arch/s390/kvm/gmap/dat.h b/arch/s390/kvm/gmap/dat.h index 90389d47ba4e04..79efc56710b782 100644 --- a/arch/s390/kvm/gmap/dat.h +++ b/arch/s390/kvm/gmap/dat.h @@ -109,6 +109,8 @@ union pte { #define _REGION3_FR_MASK (_REGION3_MASK >> PAGE_SHIFT) #define _PAGES_PER_SEGMENT _PAGE_ENTRIES #define _PAGES_PER_REGION3 (_PAGES_PER_SEGMENT * _CRST_ENTRIES) +#define _UCAS_ENTRY_LENGTH 0 +#define _UCAS_ENTRY_OFFSET 3 /* Soft dirty, needed as macro for atomic operations on ptes */ #define _PAGE_SD 0x002 @@ -421,6 +423,23 @@ static inline union crste _crste_fc0(kvm_pfn_t pfn, int tt) return res; } +static inline union crste _crste_ucas(kvm_pfn_t pfn) +{ + union crste res = { .val = PFN_PHYS(pfn) }; + + res.h.i = 1; + res.h.tt = TABLE_TYPE_SEGMENT; + /* + * Segment entries do not have a TF or TL field; reuse those bits to + * indicate that this is a special mappped-but-not-allocated UCAS + * entry. Setting TL to 0 ensures that the entry will always be + * considered not present. + */ + res.h.fc0.tl = _UCAS_ENTRY_LENGTH; + res.h.fc0.tf = _UCAS_ENTRY_OFFSET; + return res; +} + /** * _crste() - Useful constructor for union crste with FC=1 * @pfn: the pfn this pte should point to. @@ -627,20 +646,22 @@ static __always_inline void idte_crste(union crste *crstep, gfn_t gfn, unsigned unsigned long table_origin = __pa(crste_table_start(crstep)); unsigned long gaddr = gfn_to_gpa(gfn) & HPAGE_MASK; + table_origin |= crstep->val & _REGION_ENTRY_TYPE_MASK; + if (__builtin_constant_p(opt) && opt == 0) { /* flush without guest asce */ asm volatile("idte %[table_origin],0,%[gaddr],%[local]" : "+m" (*crstep) : [table_origin] "a" (table_origin), [gaddr] "a" (gaddr), [local] "i" (local) - : "cc"); + : "cc", "memory"); } else { /* flush with guest asce */ asm volatile("idte %[table_origin],%[asce],%[gaddr_opt],%[local]" : "+m" (*crstep) : [table_origin] "a" (table_origin), [gaddr_opt] "a" (gaddr | opt), [asce] "a" (asce.val), [local] "i" (local) - : "cc"); + : "cc", "memory"); } } @@ -985,7 +1006,34 @@ static inline int dat_create_slot(struct kvm_s390_mmu_cache *mc, union asce asce static inline bool crste_is_ucas(union crste crste) { - return is_pmd(crste) && crste.h.i && crste.h.fc0.tl == 1 && crste.h.fc == 0; + return is_pmd(crste) && crste.h.i && !crste.h.fc && + crste.h.fc0.tl == _UCAS_ENTRY_LENGTH && crste.h.fc0.tf == _UCAS_ENTRY_OFFSET; +} + +static inline void dat_set_storage_key_from_pgste(union pte pte, union pgste pgste) +{ + union skey nkey = { .acc = pgste.acc, .fp = pgste.fp }; + + page_set_storage_key(pte_origin(pte), nkey.skey, 0); +} + +static inline void dat_move_storage_key(union pte old, union pte new) +{ + page_set_storage_key(pte_origin(new), page_get_storage_key(pte_origin(old)), 1); +} + +static inline union pgste dat_save_storage_key_into_pgste(union pte pte, union pgste pgste) +{ + union skey skey; + + skey.skey = page_get_storage_key(pte_origin(pte)); + + pgste.acc = skey.acc; + pgste.fp = skey.fp; + pgste.gr |= skey.r; + pgste.gc |= skey.c; + + return pgste; } #endif /* ARCH_KVM_GMAP_DAT_H */ diff --git a/arch/s390/kvm/gmap/gmap.c b/arch/s390/kvm/gmap/gmap.c index bf91e3d5013b57..b9d92bef5459db 100644 --- a/arch/s390/kvm/gmap/gmap.c +++ b/arch/s390/kvm/gmap/gmap.c @@ -434,17 +434,8 @@ static long _gmap_unmap_crste(union crste *crstep, gfn_t gfn, gfn_t next, struct return 0; } -/** - * gmap_unmap_gfn_range() - Unmap a range of guest addresses. - * @gmap: The gmap to act on. - * @slot: The memslot in which the range is located. - * @start: The first gfn to unmap. - * @end: The gfn after the last one to unmap. - * - * Context: Called with the kvm mmu write lock held. - * Return: false - */ -bool gmap_unmap_gfn_range(struct gmap *gmap, struct kvm_memory_slot *slot, gfn_t start, gfn_t end) +static bool gmap_unmap_gfn_range_slow(struct gmap *gmap, struct kvm_memory_slot *slot, + gfn_t start, gfn_t end) { const struct dat_walk_ops ops = { .pte_entry = _gmap_unmap_pte, @@ -462,6 +453,129 @@ bool gmap_unmap_gfn_range(struct gmap *gmap, struct kvm_memory_slot *slot, gfn_t return false; } +static long _gmap_unmap_pud_fast(union crste *crstep, gfn_t gfn, gfn_t next, struct dat_walk *w) +{ + union crste old = *crstep; + + /* We only care about large puds */ + if (!old.h.fc) + return 0; + /* + * The caller did not unmap prefixes outside the original range, which + * does not necessarily cover the whole pud. + * Since all prefixes are below 2G, the first pud covers them all; + * make sure all prefixes are unmapped whenever the first pud is being + * unmapped. + */ + if (!gfn) + gmap_unmap_prefix(w->priv, 0, next); + if (old.s.fc1.vsie_notif) + gmap_handle_vsie_unshadow_event(w->priv, gfn); + + if (machine_has_tlb_guest()) + idte_crste(crstep, gfn, IDTE_GUEST_ASCE, w->asce, 0); + else + idte_crste(crstep, gfn, 0, w->asce, 0); + *crstep = _CRSTE_EMPTY(old.h.tt); + + return 0; +} + +static long _gmap_unmap_pmd_fast(union crste *crstep, gfn_t gfn, gfn_t next, struct dat_walk *w) +{ + union crste old = *crstep; + struct page_table *pt; + gfn_t first, last; + unsigned int i; + + if (old.h.fc) { + if (old.s.fc1.vsie_notif) + gmap_handle_vsie_unshadow_event(w->priv, gfn); + + if (machine_has_tlb_guest()) + idte_crste(crstep, gfn, IDTE_GUEST_ASCE, w->asce, 0); + else + idte_crste(crstep, gfn, 0, w->asce, 0); + WRITE_ONCE(*crstep, _CRSTE_EMPTY(old.h.tt)); + + return 0; + } + + if (old.h.i) + return 0; + + pt = dereference_pmd(old.pmd); + first = max(gfn, w->start) & (PTRS_PER_PTE - 1); + last = (min(next, w->end) - 1) & (PTRS_PER_PTE - 1); + + for (i = first; i <= last; i++) + if (pte_needs_unshadow(pt->ptes[i], _PTE_EMPTY, pt->pgstes[i])) + gmap_handle_vsie_unshadow_event(w->priv, gfn + i); + + /* Detach the page table */ + if (machine_has_tlb_guest()) + idte_crste(crstep, gfn, IDTE_GUEST_ASCE, w->asce, 0); + else + idte_crste(crstep, gfn, 0, w->asce, 0); + + for (i = first; i <= last; i++) { + if (pte_hole(pt->ptes[i])) + continue; + if (!pt->ptes[i].h.i && uses_skeys(w->priv)) + pt->pgstes[i] = dat_save_storage_key_into_pgste(pt->ptes[i], pt->pgstes[i]); + pt->ptes[i] = _PTE_EMPTY; + pt->pgstes[i].vsie_notif = 0; + pt->pgstes[i].vsie_gmem = 0; + pt->pgstes[i].zero = 0; + pt->pgstes[i].prefix_notif = 0; + } + + barrier(); + /* Reattach the modified page table */ + WRITE_ONCE(*crstep, old); + + return 0; +} + +static bool gmap_unmap_gfn_range_fast(struct gmap *gmap, gfn_t start, gfn_t end) +{ + const struct dat_walk_ops ops = { + .pud_entry = _gmap_unmap_pud_fast, + .pmd_entry = _gmap_unmap_pmd_fast, + }; + gfn_t aligned_start = ALIGN_DOWN(start, _PAGE_ENTRIES); + gfn_t aligned_end = ALIGN(end, _PAGE_ENTRIES); + bool failed; + + lockdep_assert_held_write(&gmap->kvm->mmu_lock); + + /* Prefixes are below 2G; if the start is above 2G, nothing to do */ + if (aligned_start < _PAGES_PER_REGION3) + gmap_unmap_prefix(gmap, aligned_start, aligned_end); + + failed = _dat_walk_gfn_range(start, end, gmap->asce, &ops, DAT_WALK_IGN_HOLES, gmap); + KVM_BUG_ON(failed, gmap->kvm); + return false; +} + +/** + * gmap_unmap_gfn_range() - Unmap a range of guest addresses. + * @gmap: The gmap to act on. + * @slot: The memslot in which the range is located. + * @start: The first gfn to unmap. + * @end: The gfn after the last one to unmap. + * + * Context: Called with the kvm mmu write lock held. + * Return: false + */ +bool gmap_unmap_gfn_range(struct gmap *gmap, struct kvm_memory_slot *slot, gfn_t start, gfn_t end) +{ + if ((end - start <= _PAGES_PER_SEGMENT) || + test_bit(GMAP_FLAG_EXPORT_ON_UNMAP, &gmap->flags) || is_ucontrol(gmap)) + return gmap_unmap_gfn_range_slow(gmap, slot, start, end); + return gmap_unmap_gfn_range_fast(gmap, start, end); +} + static union pgste __pte_test_and_clear_softdirty(union pte *ptep, union pgste pgste, gfn_t gfn, struct gmap *gmap) { @@ -777,16 +891,14 @@ static int gmap_ucas_map_one(struct kvm_s390_mmu_cache *mc, struct gmap *gmap, if (rc) return rc; if (!ptep) { - newcrste = _crste_fc0(p_gfn, TABLE_TYPE_SEGMENT); - newcrste.h.i = 1; - newcrste.h.fc0.tl = 1; + newcrste = _crste_ucas(p_gfn); } else { pt = pte_table_start(ptep); dat_set_ptval(pt, PTVAL_VMADDR, p_gfn >> (_SEGMENT_SHIFT - PAGE_SHIFT)); newcrste = _crste_fc0(virt_to_pfn(pt), TABLE_TYPE_SEGMENT); } - rc = dat_entry_walk(mc, c_gfn, gmap->asce, DAT_WALK_ALLOC, TABLE_TYPE_SEGMENT, - &crstep, &ptep); + rc = dat_entry_walk(mc, c_gfn, gmap->asce, DAT_WALK_ALLOC | DAT_WALK_IGN_HOLES, + TABLE_TYPE_SEGMENT, &crstep, &ptep); if (rc) return rc; do { @@ -802,8 +914,9 @@ static int gmap_ucas_translate_simple(struct gmap *gmap, gpa_t *gaddr, union crs union pte *ptep; int rc; - rc = dat_entry_walk(NULL, gpa_to_gfn(*gaddr), gmap->asce, DAT_WALK_CONTINUE, - TABLE_TYPE_SEGMENT, crstepp, &ptep); + rc = dat_entry_walk(NULL, gpa_to_gfn(*gaddr), gmap->asce, + DAT_WALK_IGN_HOLES | DAT_WALK_ANY, + TABLE_TYPE_PAGE_TABLE, crstepp, &ptep); if (rc || (!ptep && !crste_is_ucas(**crstepp))) return -EREMOTE; if (!ptep) @@ -840,26 +953,24 @@ int gmap_ucas_translate(struct kvm_s390_mmu_cache *mc, struct gmap *gmap, gpa_t if (rc <= 0) return rc; } - do { - scoped_guard(write_lock, &gmap->kvm->mmu_lock) { - rc = gmap_ucas_translate_simple(gmap, gaddr, &crstep); - if (rc <= 0) - return rc; - translated_address = (*gaddr & ~_SEGMENT_MASK) | - (crstep->val & _SEGMENT_MASK); - rc = gmap_ucas_map_one(mc, gmap, gpa_to_gfn(translated_address), gfn, true); - } - if (!rc) { - *gaddr = translated_address; - return 0; - } - if (rc != -ENOMEM) - return -EREMOTE; - rc = kvm_s390_mmu_cache_topup(mc); - if (rc) + rc = kvm_s390_mmu_cache_topup(mc); + if (rc) + return rc; + + scoped_guard(write_lock, &gmap->kvm->mmu_lock) { + rc = gmap_ucas_translate_simple(gmap, gaddr, &crstep); + if (rc <= 0) return rc; - } while (1); - return 0; + translated_address = (*gaddr & ~_SEGMENT_MASK) | + (crstep->val & _SEGMENT_MASK); + rc = gmap_ucas_map_one(mc, gmap, gpa_to_gfn(translated_address), gfn, true); + } + + if (!rc) + *gaddr = translated_address; + if (!rc || rc == -ENOMEM) + return rc; + return -EREMOTE; } int gmap_ucas_map(struct gmap *gmap, gfn_t p_gfn, gfn_t c_gfn, unsigned long count) @@ -896,8 +1007,9 @@ static void gmap_ucas_unmap_one(struct gmap *gmap, gfn_t c_gfn) union pte *ptep; int rc; - rc = dat_entry_walk(NULL, c_gfn, gmap->asce, 0, TABLE_TYPE_SEGMENT, &crstep, &ptep); - if (rc) + rc = dat_entry_walk(NULL, c_gfn, gmap->asce, DAT_WALK_IGN_HOLES, + TABLE_TYPE_SEGMENT, &crstep, &ptep); + if (rc || !is_pmd(*crstep)) return; while (!dat_crstep_xchg_atomic(crstep, READ_ONCE(*crstep), _PMD_EMPTY, c_gfn, gmap->asce)) ; diff --git a/arch/s390/kvm/s390/priv.c b/arch/s390/kvm/s390/priv.c index 856939acf012fd..f22612a127c96b 100644 --- a/arch/s390/kvm/s390/priv.c +++ b/arch/s390/kvm/s390/priv.c @@ -593,7 +593,7 @@ EXPORT_SYMBOL_FOR_MODULES(kvm_s390_is_gpa_in_memslot, "vfio_ap"); */ static int handle_pqap(struct kvm_vcpu *vcpu) { - struct ap_queue_status status = {}; + union ap_queue_status_reg status = {}; crypto_hook pqap_hook; unsigned long reg0; int ret; @@ -662,8 +662,8 @@ static int handle_pqap(struct kvm_vcpu *vcpu) * No hook means no driver to enable the SIE CRYCB and no queues. * We send this response to the guest. */ - status.response_code = 0x01; - memcpy(&vcpu->run->s.regs.gprs[1], &status, sizeof(status)); + status.status.response_code = 0x01; + vcpu->run->s.regs.gprs[1] = status.value; kvm_s390_set_psw_cc(vcpu, 3); return 0; } @@ -1169,6 +1169,8 @@ static inline int __do_essa(struct kvm_vcpu *vcpu, const int orc) entries = (vcpu->arch.sie_block->cbrlo & ~PAGE_MASK) >> 3; nappended = dat_perform_essa(vcpu->arch.gmap->asce, gfn, orc, &state, &dirtied); + if (nappended == PGM_ADDRESSING) + return kvm_s390_inject_program_int(vcpu, PGM_ADDRESSING); vcpu->run->s.regs.gprs[r1] = state.val; if (nappended < 0) return 0; diff --git a/arch/s390/kvm/s390/s390.c b/arch/s390/kvm/s390/s390.c index 18fb200f854a84..9900a1a1c1487f 100644 --- a/arch/s390/kvm/s390/s390.c +++ b/arch/s390/kvm/s390/s390.c @@ -3922,13 +3922,6 @@ bool kvm_arch_no_poll(struct kvm_vcpu *vcpu) return false; } -int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu) -{ - /* kvm common code refers to this, but never calls it */ - BUG(); - return 0; -} - static int kvm_arch_vcpu_ioctl_get_one_reg(struct kvm_vcpu *vcpu, struct kvm_one_reg *reg) { diff --git a/arch/s390/kvm/s390/vsie.c b/arch/s390/kvm/s390/vsie.c index 5926689fa2267b..3ce133f20fa2cd 100644 --- a/arch/s390/kvm/s390/vsie.c +++ b/arch/s390/kvm/s390/vsie.c @@ -49,20 +49,21 @@ struct vsie_page { /* address of the last reported fault to guest2 */ unsigned long fault_addr; /* 0x0228 */ /* calculated guest addresses of satellite control blocks */ - gpa_t sca_gpa; /* 0x0230 */ - gpa_t itdba_gpa; /* 0x0238 */ - gpa_t gvrd_gpa; /* 0x0240 */ - gpa_t riccbd_gpa; /* 0x0248 */ - gpa_t sdnx_gpa; /* 0x0250 */ + struct kvm_host_map sca_map; /* 0x0230 */ + struct kvm_host_map itdba_map; /* 0x0260 */ + struct kvm_host_map gvrd_map; /* 0x0290 */ + struct kvm_host_map riccbd_map; /* 0x02c0 */ + struct kvm_host_map sdnx_map; /* 0x02f0 */ + struct kvm_host_map scb_map; /* 0x0320 */ /* * guest address of the original SCB. Remains set for free vsie * pages, so we can properly look them up in our addr_to_page * radix tree. */ - gpa_t scb_gpa; /* 0x0258 */ + gpa_t scb_gpa; /* 0x0350 */ /* the shadow gmap in use by the vsie_page */ - struct gmap_cache gmap_cache; /* 0x0260 */ - __u8 reserved[0x06f8 - 0x0278]; /* 0x0278 */ + struct gmap_cache gmap_cache; /* 0x0358 */ + __u8 reserved[0x06f8 - 0x0370]; /* 0x0370 */ struct kvm_s390_crypto_cb crycb; /* 0x06f8 */ __u8 fac[8 + S390_ARCH_FAC_LIST_SIZE_BYTE];/* 0x07f8 */ }; @@ -681,72 +682,43 @@ static int map_prefix(struct kvm_vcpu *vcpu, struct vsie_page *vsie_page, struct } /* - * Pin the guest page given by gpa and set hpa to the pinned host address. + * pin_guest_page() - Pin the given guest page and return its hpa. + * @vcpu: the vCPU + * @gpa: the gpa to pin + * @map: the map representing this pinning. + * * Will always be pinned writable. * - * Returns: - 0 on success - * - -EINVAL if the gpa is not valid guest storage + * Returns: - 0 if the gpa is not valid guest storage, + * - The host hpa of the pinned page in case of success */ -static int pin_guest_page(struct kvm *kvm, gpa_t gpa, hpa_t *hpa) -{ - struct page *page; - - page = gfn_to_page(kvm, gpa_to_gfn(gpa)); - if (!page) - return -EINVAL; - *hpa = (hpa_t)page_to_phys(page) + (gpa & ~PAGE_MASK); - return 0; -} - -/* Unpins a page previously pinned via pin_guest_page, marking it as dirty. */ -static void unpin_guest_page(struct kvm *kvm, gpa_t gpa, hpa_t hpa) +static hpa_t pin_guest_page(struct kvm_vcpu *vcpu, gpa_t gpa, struct kvm_host_map *map) { - kvm_release_page_dirty(pfn_to_page(phys_to_pfn(hpa))); - /* mark the page always as dirty for migration */ - mark_page_dirty(kvm, gpa_to_gfn(gpa)); + if (kvm_vcpu_map(vcpu, gpa_to_gfn(gpa), map)) + return 0; + return (hpa_t)PFN_PHYS(map->pfn) + (gpa & ~PAGE_MASK); } /* unpin all blocks previously pinned by pin_blocks(), marking them dirty */ static void unpin_blocks(struct kvm_vcpu *vcpu, struct vsie_page *vsie_page) { struct kvm_s390_sie_block *scb_s = &vsie_page->scb_s; - hpa_t hpa; - hpa = (u64) scb_s->scaoh << 32 | scb_s->scaol; - if (hpa) { - unpin_guest_page(vcpu->kvm, vsie_page->sca_gpa, hpa); - vsie_page->sca_gpa = 0; - scb_s->scaol = 0; - scb_s->scaoh = 0; - } + kvm_vcpu_unmap(vcpu, &vsie_page->sca_map); + scb_s->scaol = 0; + scb_s->scaoh = 0; - hpa = scb_s->itdba; - if (hpa) { - unpin_guest_page(vcpu->kvm, vsie_page->itdba_gpa, hpa); - vsie_page->itdba_gpa = 0; - scb_s->itdba = 0; - } + kvm_vcpu_unmap(vcpu, &vsie_page->itdba_map); + scb_s->itdba = 0; - hpa = scb_s->gvrd; - if (hpa) { - unpin_guest_page(vcpu->kvm, vsie_page->gvrd_gpa, hpa); - vsie_page->gvrd_gpa = 0; - scb_s->gvrd = 0; - } + kvm_vcpu_unmap(vcpu, &vsie_page->gvrd_map); + scb_s->gvrd = 0; - hpa = scb_s->riccbd; - if (hpa) { - unpin_guest_page(vcpu->kvm, vsie_page->riccbd_gpa, hpa); - vsie_page->riccbd_gpa = 0; - scb_s->riccbd = 0; - } + kvm_vcpu_unmap(vcpu, &vsie_page->riccbd_map); + scb_s->riccbd = 0; - hpa = scb_s->sdnxo; - if (hpa) { - unpin_guest_page(vcpu->kvm, vsie_page->sdnx_gpa, hpa); - vsie_page->sdnx_gpa = 0; - scb_s->sdnxo = 0; - } + kvm_vcpu_unmap(vcpu, &vsie_page->sdnx_map); + scb_s->sdnxo = 0; } /* @@ -783,13 +755,12 @@ static int pin_blocks(struct kvm_vcpu *vcpu, struct vsie_page *vsie_page) ((gpa + offsetof(struct bsca_block, cpu[0]) - 1) & PAGE_MASK)) rc = set_validity_icpt(scb_s, 0x003bU); if (!rc) { - rc = pin_guest_page(vcpu->kvm, gpa, &hpa); - if (rc) + hpa = pin_guest_page(vcpu, gpa, &vsie_page->sca_map); + if (!hpa) rc = set_validity_icpt(scb_s, 0x0034U); } if (rc) goto unpin; - vsie_page->sca_gpa = gpa; scb_s->scaoh = (u32)((u64)hpa >> 32); scb_s->scaol = (u32)(u64)hpa; } @@ -801,12 +772,11 @@ static int pin_blocks(struct kvm_vcpu *vcpu, struct vsie_page *vsie_page) goto unpin; } /* 256 bytes cannot cross page boundaries */ - rc = pin_guest_page(vcpu->kvm, gpa, &hpa); - if (rc) { + hpa = pin_guest_page(vcpu, gpa, &vsie_page->itdba_map); + if (!hpa) { rc = set_validity_icpt(scb_s, 0x0080U); goto unpin; } - vsie_page->itdba_gpa = gpa; scb_s->itdba = hpa; } @@ -820,12 +790,11 @@ static int pin_blocks(struct kvm_vcpu *vcpu, struct vsie_page *vsie_page) * 512 bytes vector registers cannot cross page boundaries * if this block gets bigger, we have to shadow it. */ - rc = pin_guest_page(vcpu->kvm, gpa, &hpa); - if (rc) { + hpa = pin_guest_page(vcpu, gpa, &vsie_page->gvrd_map); + if (!hpa) { rc = set_validity_icpt(scb_s, 0x1310U); goto unpin; } - vsie_page->gvrd_gpa = gpa; scb_s->gvrd = hpa; } @@ -836,13 +805,12 @@ static int pin_blocks(struct kvm_vcpu *vcpu, struct vsie_page *vsie_page) goto unpin; } /* 64 bytes cannot cross page boundaries */ - rc = pin_guest_page(vcpu->kvm, gpa, &hpa); - if (rc) { + hpa = pin_guest_page(vcpu, gpa, &vsie_page->riccbd_map); + if (!hpa) { rc = set_validity_icpt(scb_s, 0x0043U); goto unpin; } /* Validity 0x0044 will be checked by SIE */ - vsie_page->riccbd_gpa = gpa; scb_s->riccbd = hpa; } if (((scb_s->ecb & ECB_GS) && !(scb_s->ecd & ECD_HOSTREGMGMT)) || @@ -866,12 +834,11 @@ static int pin_blocks(struct kvm_vcpu *vcpu, struct vsie_page *vsie_page) /* Due to alignment rules (checked above) this cannot * cross page boundaries */ - rc = pin_guest_page(vcpu->kvm, gpa, &hpa); - if (rc) { + hpa = pin_guest_page(vcpu, gpa, &vsie_page->sdnx_map); + if (!hpa) { rc = set_validity_icpt(scb_s, 0x10b0U); goto unpin; } - vsie_page->sdnx_gpa = gpa; scb_s->sdnxo = hpa | sdnxc; } return 0; @@ -881,13 +848,9 @@ static int pin_blocks(struct kvm_vcpu *vcpu, struct vsie_page *vsie_page) } /* unpin the scb provided by guest 2, marking it as dirty */ -static void unpin_scb(struct kvm_vcpu *vcpu, struct vsie_page *vsie_page, - gpa_t gpa) +static void unpin_scb(struct kvm_vcpu *vcpu, struct vsie_page *vsie_page) { - hpa_t hpa = virt_to_phys(vsie_page->scb_o); - - if (hpa) - unpin_guest_page(vcpu->kvm, gpa, hpa); + kvm_vcpu_unmap(vcpu, &vsie_page->scb_map); vsie_page->scb_o = NULL; } @@ -901,12 +864,10 @@ static int pin_scb(struct kvm_vcpu *vcpu, struct vsie_page *vsie_page, gpa_t gpa) { hpa_t hpa; - int rc; - rc = pin_guest_page(vcpu->kvm, gpa, &hpa); - if (rc) { - rc = kvm_s390_inject_program_int(vcpu, PGM_ADDRESSING); - WARN_ON_ONCE(rc); + hpa = pin_guest_page(vcpu, gpa, &vsie_page->scb_map); + if (!hpa) { + WARN_ON_ONCE(kvm_s390_inject_program_int(vcpu, PGM_ADDRESSING)); return 1; } vsie_page->scb_o = phys_to_virt(hpa); @@ -1601,7 +1562,7 @@ int kvm_s390_handle_vsie(struct kvm_vcpu *vcpu) out_unshadow: unshadow_scb(vcpu, vsie_page); out_unpin_scb: - unpin_scb(vcpu, vsie_page, scb_addr); + unpin_scb(vcpu, vsie_page); out_put: put_vsie_page(vsie_page); diff --git a/arch/x86/Kconfig b/arch/x86/Kconfig index 58dce0b66179b6..3159852fd6b3ec 100644 --- a/arch/x86/Kconfig +++ b/arch/x86/Kconfig @@ -84,7 +84,7 @@ config X86 select ARCH_HAS_DMA_OPS if GART_IOMMU || XEN select ARCH_HAS_EARLY_DEBUG if KGDB select ARCH_HAS_ELF_RANDOMIZE - select ARCH_HAS_EXECMEM_ROX if X86_64 && STRICT_MODULE_RWX + select ARCH_HAS_EXECMEM_ROX if X86_64 && (STRICT_MODULE_RWX || STRICT_KERNEL_RWX) select ARCH_HAS_FAST_MULTIPLIER select ARCH_HAS_FORTIFY_SOURCE select ARCH_HAS_GCOV_PROFILE_ALL diff --git a/arch/x86/Makefile b/arch/x86/Makefile index b7e08519b8c1e2..83b07961b850ed 100644 --- a/arch/x86/Makefile +++ b/arch/x86/Makefile @@ -21,6 +21,7 @@ RETPOLINE_CFLAGS := -mretpoline-external-thunk RETPOLINE_VDSO_CFLAGS := -mretpoline endif RETPOLINE_CFLAGS += $(CONFIG_CC_OPT_INDIRECT_BRANCH_CS_PREFIX) +RETPOLINE_RUSTFLAGS += $(if $(call rustc-min-version,109100),-Zindirect-branch-cs-prefix,-Zllvm_module_flag=indirect_branch_cs_prefix:u32:1:override) ifdef CONFIG_MITIGATION_RETHUNK RETHUNK_CFLAGS := -mfunction-return=thunk-extern diff --git a/arch/x86/entry/entry_64.S b/arch/x86/entry/entry_64.S index 253f0a585927fe..7cfc617750c56b 100644 --- a/arch/x86/entry/entry_64.S +++ b/arch/x86/entry/entry_64.S @@ -937,7 +937,7 @@ SYM_CODE_START(paranoid_entry) IBRS_ENTER save_reg=%r15 UNTRAIN_RET_FROM_CALL - HANDLE_INTR_SAFERET 8(%rsp) + FIXUP_INTR_SAFERET %rsp RET SYM_CODE_END(paranoid_entry) @@ -1044,7 +1044,7 @@ SYM_CODE_START(error_entry) VALIDATE_UNRET_END - HANDLE_INTR_SAFERET 8(%rsp) + FIXUP_INTR_SAFERET %rsp cmpq $.Lgs_change, RIP+8(%rsp) jne .Lerror_entry_done_lfence @@ -1205,6 +1205,9 @@ SYM_CODE_START(asm_exc_nmi) jmp swapgs_restore_regs_and_return_to_usermode .Lnmi_from_kernel: + /* Repair the source frame before inspecting or copying it. */ + FIXUP_NMI_INTR_SAFERET %rsp + /* * Here's what our stack frame will look like: * +---------------------------------------------------------+ diff --git a/arch/x86/events/intel/core.c b/arch/x86/events/intel/core.c index 0a34d674df590c..88a60d3e4eeb41 100644 --- a/arch/x86/events/intel/core.c +++ b/arch/x86/events/intel/core.c @@ -4778,6 +4778,16 @@ static int intel_pmu_bts_config(struct perf_event *event) if (attr->precise_ip) return -EOPNOTSUPP; + /* + * BTS samples are built from the BTS buffer when it is drained, + * not from the registers of an interrupted context, and + * intel_pmu_drain_bts_buffer() does not provide the registers in + * the struct x86_perf_regs layout that extended register sampling + * relies on. + */ + if (event_has_extended_regs(event) || event_has_simd_regs(event)) + return -EOPNOTSUPP; + /* disallow bts if conflicting events are present */ if (x86_add_exclusive(x86_lbr_exclusive_lbr)) return -EBUSY; diff --git a/arch/x86/include/asm/intel-family.h b/arch/x86/include/asm/intel-family.h index 66d964afe18a45..2a5761d475b85c 100644 --- a/arch/x86/include/asm/intel-family.h +++ b/arch/x86/include/asm/intel-family.h @@ -129,6 +129,8 @@ #define INTEL_DIAMONDRAPIDS_X IFM(19, 0x01) /* Panther Cove */ +#define INTEL_CORALRAPIDS_X IFM(19, 0x08) + #define INTEL_BARTLETTLAKE IFM(6, 0xD7) /* Raptor Cove */ /* "Hybrid" Processors (P-Core/E-Core) */ @@ -159,6 +161,11 @@ #define INTEL_NOVALAKE IFM(18, 0x01) /* Coyote Cove / Arctic Wolf */ #define INTEL_NOVALAKE_L IFM(18, 0x03) /* Coyote Cove / Arctic Wolf */ +#define INTEL_RAZORLAKE IFM(18, 0x06) +#define INTEL_RAZORLAKE_L IFM(18, 0x07) +#define INTEL_RAZORLAKE_U IFM(18, 0x09) +#define INTEL_RAZORLAKE_S IFM(18, 0x0A) + /* "Small Core" Processors (Atom/E-Core) */ #define INTEL_ATOM_BONNELL IFM(6, 0x1C) /* Diamondville, Pineview */ diff --git a/arch/x86/include/asm/nospec-branch.h b/arch/x86/include/asm/nospec-branch.h index 1abeb9af000ba1..64554434320d0c 100644 --- a/arch/x86/include/asm/nospec-branch.h +++ b/arch/x86/include/asm/nospec-branch.h @@ -185,42 +185,39 @@ * * The Safe-RET sequence is: * - * CALL - * LEA 8(%RSP), %RSP - * RET + * CALL L1 + * L1: LEA 8(%RSP), %RSP + * L2: RET * - * The two CMPs below check whether RIP points to after the CALL or after the - * LEA. + * The C equivalent of the ASM sequence below is: * - * The LFENCE below is to address this particular speculation case: + * if (ptr->RIP > L2) // After RET? + * goto done; + * if (ptr->RIP < L1) // Before LEA ? + * goto done; + * if (ptr->RIP == L1) // At LEA ? + * ptr->RSP += 8; // Emulate LEA + * tmp = *ptr->RSP; // Read original return IP + * ptr->RIP = tmp; // Overwrite interrupt return IP + * ptr->RSP += 8; // Emulate RET * - * 1. Userspace runs and poisons the BTB around the safe-RET routine - * - * 2. Userspace triggers some kind of exception - * - * 3. Kernel executes error_entry() and mis-speculates the branch into thinking - * it actually came from kernel space - * - * 4. The kernel then further mis-speculates that the exception occurred due - * to an interrupted safe-RET - * - * 5. The handle_interrupted_saferet() routine speculatively executes and - * speculatively does a safe-RET. But this is unsafe since it was never - * untrained. - * - * The LFENCE fixes this by ensuring step 5 is never reached speculatively. - * Note that this LFENCE only occurs if safe-RET was actually interrupted (so - * it's outside of the normal path). + * This ensures that this interrupt returns to the original return IP without + * resuming the interrupted safe-RET sequence. */ -#define __HANDLE_INTR_SAFERET(name, pt_regs) \ - cmpq $(name), RIP+pt_regs; \ - jb 1f; \ - cmpq $(name)+5, RIP+pt_regs; \ - ja 1f; \ - lfence; \ - leaq pt_regs, %rdi; \ - call handle_interrupted_saferet; \ - 1: +#define __FIXUP_INTR_SAFERET(name, ptr, rip_offs, rsp_offs) \ + cmpq $(name)+5, rip_offs(ptr); \ + ja 2f; \ + cmpq $(name), rip_offs(ptr); \ + jb 2f; \ + jne 1f; \ + addq $8, rsp_offs(ptr); \ + 1:; \ + movq rsp_offs(ptr), %rdx; \ + movq (%rdx), %rdx; \ + movq %rdx, rip_offs(ptr); \ + addq $8, rsp_offs(ptr); \ + 2: + #ifdef __ASSEMBLER__ @@ -305,7 +302,7 @@ .macro CALL_UNTRAIN_RET #if defined(CONFIG_MITIGATION_UNRET_ENTRY) || defined(CONFIG_MITIGATION_SRSO) ALTERNATIVE_2 "", "call entry_untrain_ret", X86_FEATURE_UNRET, \ - "call srso_alias_untrain_ret", X86_FEATURE_SRSO_ALIAS + "call srso_alias_untrain_ret", X86_FEATURE_SRSO_ALIAS #endif .endm @@ -339,12 +336,25 @@ #define UNTRAIN_RET_FROM_CALL \ __UNTRAIN_RET X86_FEATURE_ENTRY_IBPB, __stringify(RESET_CALL_DEPTH_FROM_CALL) -.macro HANDLE_INTR_SAFERET pt_regs +.macro FIXUP_INTR_SAFERET pt_regs #ifdef CONFIG_MITIGATION_SRSO ALTERNATIVE_2 "", \ - __stringify(__HANDLE_INTR_SAFERET(srso_safe_ret, \pt_regs)), X86_FEATURE_SRSO, \ - __stringify(__HANDLE_INTR_SAFERET(srso_alias_safe_ret, \pt_regs)), X86_FEATURE_SRSO_ALIAS + __stringify(__FIXUP_INTR_SAFERET(srso_safe_ret, \pt_regs, RIP+8, RSP+8)), X86_FEATURE_SRSO, \ + __stringify(__FIXUP_INTR_SAFERET(srso_alias_safe_ret, \pt_regs, RIP+8, RSP+8)), X86_FEATURE_SRSO_ALIAS +#endif +.endm +/* + * Note the offsets encoding below: + * + * The IRET frame at call site in asm_exc_nmi() starts at 8(%rsp) (NMI handler + * users %rdx as a temp var so it pushes it on the stack on entry). + */ +.macro FIXUP_NMI_INTR_SAFERET fptr +#ifdef CONFIG_MITIGATION_SRSO + ALTERNATIVE_2 "", \ + __stringify(__FIXUP_INTR_SAFERET(srso_safe_ret, \fptr, RIP-RIP+8, RSP-RIP+8)), X86_FEATURE_SRSO, \ + __stringify(__FIXUP_INTR_SAFERET(srso_alias_safe_ret, \fptr, RIP-RIP+8, RSP-RIP+8)), X86_FEATURE_SRSO_ALIAS #endif .endm @@ -681,7 +691,6 @@ static __always_inline void x86_idle_clear_cpu_buffers(void) void srso_safe_ret(void); void srso_alias_safe_ret(void); -void handle_interrupted_saferet(struct pt_regs *regs); #endif /* __ASSEMBLER__ */ diff --git a/arch/x86/kernel/apic/msi.c b/arch/x86/kernel/apic/msi.c index 66bc5d3e79db3f..da5f44a80313f8 100644 --- a/arch/x86/kernel/apic/msi.c +++ b/arch/x86/kernel/apic/msi.c @@ -62,7 +62,7 @@ msi_set_affinity(struct irq_data *irqd, const struct cpumask *mask, bool force) * - The interrupt is not yet started up * - The new destination CPU is the same as the old destination CPU */ - if (!irqd_can_reserve(irqd) || + if (irqd_can_reserve(irqd) || cfg->vector == old_cfg.vector || old_cfg.vector == MANAGED_IRQ_SHUTDOWN_VECTOR || !irqd_is_started(irqd) || diff --git a/arch/x86/kernel/cpu/bugs.c b/arch/x86/kernel/cpu/bugs.c index 4ced10c6ba0db9..8c2c8310f96f61 100644 --- a/arch/x86/kernel/cpu/bugs.c +++ b/arch/x86/kernel/cpu/bugs.c @@ -3787,42 +3787,3 @@ void __warn_thunk(void) { WARN_ONCE(1, "Unpatched return thunk in use. This should not happen!\n"); } - -#ifdef CONFIG_MITIGATION_SRSO -/* - * Called during exception/interrupt entry if interrupted during the - * safe-RET sequence. The safe-RET sequence consists of 3 instructions: - * - * CALL - * LEA 8(%RSP), %RSP - * RET - * - * An interrupt after the CALL or after the LEA could potentially lead - * to branch predictor poisoning and results in the sequence not being - * able to be safely resumed. - * - * Therefore, modify the regs state as if the remaining part of the - * safe-RET sequence executed so the interrupt returns back to the - * desired return target, instead of the to the safe-RET sequence. - */ -void noinstr handle_interrupted_saferet(struct pt_regs *regs) -{ - unsigned long rip = regs->ip; - - if (rip == (unsigned long) srso_safe_ret || - rip == (unsigned long) srso_alias_safe_ret) { - /* Modify stack pointer as if LEA executed: */ - regs->sp += 8; - } - - /* - * Adjust registers as if RET executed: - * - * 1. Read the return address off the stack and into rIP: - */ - regs->ip = *(unsigned long *)(regs->sp); - - /* 2. Pop rIP off the stack: */ - regs->sp += 8; -} -#endif /* CONFIG_MITIGATION_SRSO */ diff --git a/arch/x86/kernel/cpu/hygon.c b/arch/x86/kernel/cpu/hygon.c index ec51c2b9a257cc..ea37c48de26e40 100644 --- a/arch/x86/kernel/cpu/hygon.c +++ b/arch/x86/kernel/cpu/hygon.c @@ -10,6 +10,7 @@ #include #include +#include #include #include #include @@ -170,11 +171,39 @@ static void early_init_hygon(struct cpuinfo_x86 *c) set_cpu_cap(c, X86_FEATURE_VMMCALL); } +#define X86_MATCH_HYGON_MODEL_STEP_UCODE(model, step, ucode) \ + X86_MATCH_VFM_STEPS(VFM_MAKE(X86_VENDOR_HYGON, 0x18, model), \ + step, step, ucode) + +static const struct x86_cpu_id erratum_1386_microcode[] = { + X86_MATCH_HYGON_MODEL_STEP_UCODE(0x04, 0x00, 0x9040000f), + X86_MATCH_HYGON_MODEL_STEP_UCODE(0x04, 0x01, 0x9041000f), + X86_MATCH_HYGON_MODEL_STEP_UCODE(0x06, 0x00, 0x9060000f), + X86_MATCH_HYGON_MODEL_STEP_UCODE(0x06, 0x01, 0x9061000f), + X86_MATCH_HYGON_MODEL_STEP_UCODE(0x10, 0x00, 0x91000004), + {} +}; + +static void fix_erratum_1386(struct cpuinfo_x86 *c) +{ + /* + * Work around Erratum 1386. The XSAVES instruction malfunctions in + * certain circumstances on affected Hygon processors. Clear the feature + * flag only on microcode revisions without the fix. + */ + if (x86_match_min_microcode_rev(erratum_1386_microcode)) + return; + + clear_cpu_cap(c, X86_FEATURE_XSAVES); +} + static void init_hygon(struct cpuinfo_x86 *c) { u64 vm_cr; early_init_hygon(c); + if (c->x86 == 0x18 && (c->x86_model <= 0x06 || c->x86_model == 0x10)) + fix_erratum_1386(c); set_cpu_cap(c, X86_FEATURE_REP_GOOD); @@ -228,6 +257,9 @@ static void init_hygon(struct cpuinfo_x86 *c) /* Hygon CPUs don't need fencing after x2APIC/TSC_DEADLINE MSR writes. */ clear_cpu_cap(c, X86_FEATURE_APIC_MSRS_FENCE); + + pr_notice_once("Hygon FPDSS bug detected, enabling mitigation.\n"); + msr_set_bit(MSR_AMD64_FP_CFG, MSR_AMD64_FP_CFG_ZEN1_DENORM_FIX_BIT); } static void cpu_detect_tlb_hygon(struct cpuinfo_x86 *c) diff --git a/arch/x86/kernel/cpu/mce/amd.c b/arch/x86/kernel/cpu/mce/amd.c index 1cc20b855b7e8d..255d09cd85443e 100644 --- a/arch/x86/kernel/cpu/mce/amd.c +++ b/arch/x86/kernel/cpu/mce/amd.c @@ -837,7 +837,10 @@ bool amd_mce_usable_address(struct mce *m) return false; } - if (this_cpu_ptr(smca_banks)[m->bank].paddrv) + if (m->bank >= per_cpu(mce_num_banks, m->extcpu)) + return false; + + if (per_cpu(smca_banks, m->extcpu)[m->bank].paddrv) return m->status & MCI_STATUS_PADDRV; /* Check poison bit for all other bank types. */ diff --git a/arch/x86/kernel/cpu/mce/core.c b/arch/x86/kernel/cpu/mce/core.c index 50b1614968be6a..eb0e51ac80fc25 100644 --- a/arch/x86/kernel/cpu/mce/core.c +++ b/arch/x86/kernel/cpu/mce/core.c @@ -540,21 +540,13 @@ bool mce_is_memory_error(struct mce *m) case X86_VENDOR_INTEL: case X86_VENDOR_ZHAOXIN: /* - * Intel SDM Volume 3B - 15.9.2 Compound Error Codes + * Intel SDM Volume 3B "Compound Error Codes". * - * Bit 7 of the MCACOD field of IA32_MCi_STATUS is used for - * indicating a memory error. Bit 8 is used for indicating a - * cache hierarchy error. The combination of bit 2 and bit 3 - * is used for indicating a `generic' cache hierarchy error - * But we can't just blindly check the above bits, because if - * bit 11 is set, then it is a bus/interconnect error - and - * either way the above bits just gives more detail on what - * bus/interconnect error happened. Note that bit 12 can be - * ignored, as it's the "filter" bit. + * Memory controller errors have an MCACOD of 000F 0000 1MMM CCCC: + * bit 7 set, bits 8-11 and 13-15 clear. Bit 12 is the "filter" + * bit and is ignored. */ - return (m->status & 0xef80) == BIT(7) || - (m->status & 0xef00) == BIT(8) || - (m->status & 0xeffc) == 0xc; + return (m->status & 0xef80) == BIT(7); default: return false; diff --git a/arch/x86/kernel/cpu/resctrl/monitor.c b/arch/x86/kernel/cpu/resctrl/monitor.c index a6a9090c4808ce..eee76570cf6ac9 100644 --- a/arch/x86/kernel/cpu/resctrl/monitor.c +++ b/arch/x86/kernel/cpu/resctrl/monitor.c @@ -381,6 +381,7 @@ static const struct x86_cpu_id snc_cpu_ids[] __initconst = { X86_MATCH_VFM(INTEL_GRANITERAPIDS_X, 0), X86_MATCH_VFM(INTEL_ATOM_CRESTMONT_X, 0), X86_MATCH_VFM(INTEL_ATOM_DARKMONT_X, 0), + X86_MATCH_VFM(INTEL_GRANITERAPIDS_D, 0), {} }; diff --git a/arch/x86/kernel/uprobes.c b/arch/x86/kernel/uprobes.c index 0f60c0d076b620..fc07bcd0f4627c 100644 --- a/arch/x86/kernel/uprobes.c +++ b/arch/x86/kernel/uprobes.c @@ -1888,6 +1888,21 @@ bool arch_uretprobe_is_alive(struct return_instance *ret, enum rp_check ctx, return regs->sp <= ret->stack; } +bool arch_uprobe_regs_writable(int off, int size) +{ + int end = off + size; + + /* The 32-bit pt_regs has segments in front of orig_ax. */ + if (!IS_ENABLED(CONFIG_X86_64)) + return false; + /* From r15 to di. Not orig_ax, cs, flags, ss. */ + if (end <= offsetof(struct pt_regs, orig_ax)) + return true; + if (off >= offsetof(struct pt_regs, ip) && end <= offsetofend(struct pt_regs, ip)) + return true; + return off >= offsetof(struct pt_regs, sp) && end <= offsetofend(struct pt_regs, sp); +} + /* * Heuristic-based check if uprobe is installed at the function entry. * diff --git a/arch/x86/kvm/mmu/mmu.c b/arch/x86/kvm/mmu/mmu.c index f89e9f8a6cc2f8..b122061b1fabab 100644 --- a/arch/x86/kvm/mmu/mmu.c +++ b/arch/x86/kvm/mmu/mmu.c @@ -6729,6 +6729,8 @@ int noinline kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 err emulate: if (error_code & PFERR_WRITE_MASK) emulation_type |= EMULTYPE_PF_WRITE; + if (error_code & PFERR_GUEST_PAGE_MASK) + emulation_type |= EMULTYPE_PF_GUEST_PAGE; return x86_emulate_instruction(vcpu, cr2_or_gpa, emulation_type, insn, insn_len); diff --git a/arch/x86/kvm/svm/svm.c b/arch/x86/kvm/svm/svm.c index e30ee80624b726..2dd05cd6b75714 100644 --- a/arch/x86/kvm/svm/svm.c +++ b/arch/x86/kvm/svm/svm.c @@ -2213,18 +2213,31 @@ static int shutdown_interception(struct kvm_vcpu *vcpu) /* - * VMCB is undefined after a SHUTDOWN intercept. INIT the vCPU to put - * the VMCB in a known good state. Unfortuately, KVM doesn't have - * KVM_MP_STATE_SHUTDOWN and can't add it without potentially breaking - * userspace. At a platform view, INIT is acceptable behavior as - * there exist bare metal platforms that automatically INIT the CPU - * in response to shutdown. + * The VMCB save area is undefined after a SHUTDOWN intercept, as are + * control area offsets 60h, 61h, and 68h (int_ctl[15:0] and int_state). + * INIT the vCPU to put the VMCB in a known good state. Unfortunately, + * KVM doesn't have KVM_MP_STATE_SHUTDOWN and can't add it without + * potentially breaking userspace. At a platform view, INIT is + * acceptable behavior as there exist bare metal platforms that + * automatically INIT the CPU in response to shutdown. * * The VM save area for SEV-ES guests has already been encrypted so it * cannot be reinitialized, i.e. synthesizing INIT is futile. */ if (!is_sev_es_guest(vcpu)) { - clear_page(svm->vmcb); + struct vmcb_control_area *control = &svm->vmcb->control; + + memset(&svm->vmcb->save, 0, sizeof(svm->vmcb->save)); + control->int_ctl &= ~GENMASK(15, 0); + control->int_state = 0; + + /* + * EVENTINJ is cleared on #VMEXIT, but only if VMRUN fully + * entered the guest. Manually clear the fields even though it + * should be redundant, as there is no downside to doing so. + */ + control->event_inj = 0; + control->event_inj_err = 0; #ifdef CONFIG_KVM_SMM if (is_smm(vcpu)) kvm_smm_changed(vcpu, false); @@ -3880,7 +3893,8 @@ static int pre_svm_run(struct kvm_vcpu *vcpu) /* * If the previous VMRUN of the VMCB occurred on a different physical - * cpu, then mark the VMCB dirty as hardware's clean bits are per pCPU. + * cpu, mark the VMCB dirty and reset the ASID generation, as hardware's + * clean bits and ASIDs are per pCPU. * * Reset the ASID generation in both VMCBs. This will lead to assigning * a new ASID now, and then again when switching to the other VMCB. @@ -3894,11 +3908,16 @@ static int pre_svm_run(struct kvm_vcpu *vcpu) * another vCPU/VM. */ if (unlikely(svm->current_vmcb->cpu != vcpu->cpu)) { - vmcb_mark_all_dirty(svm->vmcb); - svm->current_vmcb->cpu = vcpu->cpu; + vmcb_mark_all_dirty(svm->vmcb01.ptr); + svm->vmcb01.cpu = vcpu->cpu; svm->vmcb01.asid_generation = 0; - svm->nested.vmcb02.asid_generation = 0; - } + + if (svm->nested.initialized) { + svm->nested.vmcb02.cpu = vcpu->cpu; + svm->nested.vmcb02.asid_generation = 0; + vmcb_mark_all_dirty(svm->nested.vmcb02.ptr); + } + } if (is_sev_guest(vcpu)) return pre_sev_run(svm, vcpu->cpu); @@ -5327,19 +5346,29 @@ static int svm_check_emulate_instruction(struct kvm_vcpu *vcpu, int emul_type, } /* - * Emulate for SEV guests if the insn buffer is not empty. The buffer - * will be empty if the DecodeAssist microcode cannot fetch bytes for - * the faulting instruction because the code fetch itself faulted, e.g. - * the guest attempted to fetch from emulated MMIO or a guest page - * table used to translate CS:RIP resides in emulated MMIO. + * Under SEV, page tables are encrypted and cannot be read by the + * hypervisor, so there is no way to resolve a fault on page tables. */ + error_code = svm->vmcb->control.exit_info_1; + if (error_code & PFERR_GUEST_PAGE_MASK) + goto resume_guest; + if (likely(insn_len)) return X86EMUL_CONTINUE; /* - * Detect and workaround Errata 1096 Fam_17h_00_0Fh. + * The insn buffer was empty; the DecodeAssist microcode could not fetch + * bytes for the faulting instruction because the code fetch itself faulted, + * e.g. the guest attempted to fetch from emulated MMIO or a guest page + * table used to translate CS:RIP resides in emulated MMIO. * - * Errata: + * A data fault instead could be Errata 1096 Fam_17h_00_0Fh, so only + * retry for a fetch fault and otherwise try to workaround it. + */ + if (error_code & PFERR_FETCH_MASK) + goto resume_guest; + + /* * When CPU raises #NPF on guest data access and vCPU CR4.SMAP=1, it is * possible that CPU microcode implementing DecodeAssist will fail to * read guest memory at CS:RIP and vmcb.GuestIntrBytes will incorrectly @@ -5366,12 +5395,8 @@ static int svm_check_emulate_instruction(struct kvm_vcpu *vcpu, int emul_type, * retrieve the instruction bytes is legitimate (see abvoe). * * In addition, don't apply the erratum workaround if the #NPF occurred - * while translating guest page tables (see below). + * while translating guest page tables (see above). */ - error_code = svm->vmcb->control.exit_info_1; - if (error_code & (PFERR_GUEST_PAGE_MASK | PFERR_FETCH_MASK)) - goto resume_guest; - smep = kvm_is_cr4_bit_set(vcpu, X86_CR4_SMEP); smap = kvm_is_cr4_bit_set(vcpu, X86_CR4_SMAP); is_user = svm_get_cpl(vcpu) == 3; diff --git a/arch/x86/kvm/vmx/nested.c b/arch/x86/kvm/vmx/nested.c index 879183c1bfa5b4..cd9465f4ee343d 100644 --- a/arch/x86/kvm/vmx/nested.c +++ b/arch/x86/kvm/vmx/nested.c @@ -349,6 +349,7 @@ static void free_nested(struct kvm_vcpu *vcpu) vmx->nested.vmxon = false; vmx->nested.smm.vmxon = false; + vmx->nested.smm.guest_mode = false; vmx->nested.vmxon_ptr = INVALID_GPA; free_vpid(vmx->nested.vpid02); vmx->nested.posted_intr_nv = -1; @@ -385,8 +386,15 @@ static void free_nested(struct kvm_vcpu *vcpu) */ void nested_vmx_free_vcpu(struct kvm_vcpu *vcpu) { + struct vcpu_vmx *vmx = to_vmx(vcpu); + vcpu_load(vcpu); - vmx_leave_nested(vcpu); + if (is_guest_mode(vcpu)) { + hrtimer_cancel(&vmx->nested.preemption_timer); + leave_guest_mode(vcpu); + vmx_switch_vmcs(vcpu, &vmx->vmcs01); + } + free_nested(vcpu); vcpu_put(vcpu); } diff --git a/arch/x86/kvm/vmx/sgx.c b/arch/x86/kvm/vmx/sgx.c index 771c75a5834364..52a6d0f8bb9e9a 100644 --- a/arch/x86/kvm/vmx/sgx.c +++ b/arch/x86/kvm/vmx/sgx.c @@ -64,7 +64,7 @@ static void sgx_handle_emulation_failure(struct kvm_vcpu *vcpu, u64 addr, static int sgx_read_hva(struct kvm_vcpu *vcpu, unsigned long hva, void *data, unsigned int size) { - if (__copy_from_user(data, (void __user *)hva, size)) { + if (kvm_copy_from_user(vcpu->kvm, data, (void __user *)hva, size)) { sgx_handle_emulation_failure(vcpu, hva, size); return -EFAULT; } diff --git a/arch/x86/kvm/vmx/vmx.c b/arch/x86/kvm/vmx/vmx.c index 82eb891f684c58..af52568b551b9f 100644 --- a/arch/x86/kvm/vmx/vmx.c +++ b/arch/x86/kvm/vmx/vmx.c @@ -4021,16 +4021,16 @@ static int init_rmode_tss(struct kvm *kvm, void __user *ua) int i; for (i = 0; i < 3; i++) { - if (__copy_to_user(ua + PAGE_SIZE * i, zero_page, PAGE_SIZE)) + if (kvm_copy_to_user(kvm, ua + PAGE_SIZE * i, zero_page, PAGE_SIZE)) return -EFAULT; } data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE; - if (__copy_to_user(ua + TSS_IOPB_BASE_OFFSET, &data, sizeof(u16))) + if (kvm_copy_to_user(kvm, ua + TSS_IOPB_BASE_OFFSET, &data, sizeof(u16))) return -EFAULT; data = ~0; - if (__copy_to_user(ua + RMODE_TSS_SIZE - 1, &data, sizeof(u8))) + if (kvm_copy_to_user(kvm, ua + RMODE_TSS_SIZE - 1, &data, sizeof(u8))) return -EFAULT; return 0; @@ -4065,7 +4065,7 @@ static int init_rmode_identity_map(struct kvm *kvm) for (i = 0; i < (PAGE_SIZE / sizeof(tmp)); i++) { tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER | _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE); - if (__copy_to_user(uaddr + i * sizeof(tmp), &tmp, sizeof(tmp))) { + if (kvm_copy_to_user(kvm, uaddr + i * sizeof(tmp), &tmp, sizeof(tmp))) { r = -EFAULT; goto out; } @@ -8376,6 +8376,12 @@ int vmx_leave_smm(struct kvm_vcpu *vcpu, const union kvm_smram *smram) } if (vmx->nested.smm.guest_mode) { + /* + * Note, even if RSM ultimately fails (hits SHUTDOWN), the vCPU + * is no longer in SMM with the intent to return to L2. + */ + vmx->nested.smm.guest_mode = false; + /* Triple fault if the state is invalid. */ if (nested_vmx_check_restored_vmcs12(vcpu) < 0) return 1; @@ -8385,7 +8391,6 @@ int vmx_leave_smm(struct kvm_vcpu *vcpu, const union kvm_smram *smram) return 1; vcpu->arch.nested_run_pending = KVM_NESTED_RUN_PENDING; - vmx->nested.smm.guest_mode = false; } return 0; } diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c index 26e7beaff8a03c..0549c0b4890136 100644 --- a/arch/x86/kvm/x86.c +++ b/arch/x86/kvm/x86.c @@ -6495,8 +6495,14 @@ int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, /* Save the faulting GPA (cr2) in the address field */ ctxt->exception.address = cr2_or_gpa; - /* With shadow page tables, cr2 contains a GVA or nGPA. */ - if (vcpu->arch.mmu->root_role.direct) { + /* + * Remember the GPA if available; with shadow page tables, + * cr2 contains a GVA or nGPA, and if the fault occurred while + * walking the guest's page tables, the GPA is that of a guest + * paging structure. + */ + if (vcpu->arch.mmu->root_role.direct && + !(emulation_type & EMULTYPE_PF_GUEST_PAGE)) { ctxt->gpa_access = ACC_READ_MASK; /* * Always allow writes for guests with protected page @@ -10476,11 +10482,6 @@ unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu) return kvm_rip_read(vcpu); } -int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu) -{ - return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE; -} - static inline u32 kvm_async_pf_hash_fn(gfn_t gfn) { BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU)); diff --git a/arch/x86/kvm/x86.h b/arch/x86/kvm/x86.h index 436e2fb1396c46..cc9e28f32d1b63 100644 --- a/arch/x86/kvm/x86.h +++ b/arch/x86/kvm/x86.h @@ -410,6 +410,9 @@ int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, * * EMULTYPE_PF_WRITE - Set with EMULTYPE_PF when hardware reports a write access. * + * EMULTYPE_PF_GUEST_PAGE - Set with EMULTYPE_PF when hardware reports that the + * fault occurred while walking the guest's page tables. + * * EMULTYPE_COMPLETE_USER_EXIT - Set when the emulator should update interruptibility * state and inject single-step #DBs after skipping * an instruction (after completing userspace I/O). @@ -449,6 +452,7 @@ int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, #define EMULTYPE_WRITE_PF_TO_SP (1 << 8) #define EMULTYPE_SKIP_SOFT_INT (1 << 9) #define EMULTYPE_PF_WRITE (1 << 10) +#define EMULTYPE_PF_GUEST_PAGE (1 << 11) #define EMULTYPE_SET_SOFT_INT_VECTOR(v) ((u32)((v) & 0xff) << 16) #define EMULTYPE_GET_SOFT_INT_VECTOR(e) (((e) >> 16) & 0xff) diff --git a/arch/x86/lib/retpoline.S b/arch/x86/lib/retpoline.S index f9ca1d8eabca0d..376119f0bba791 100644 --- a/arch/x86/lib/retpoline.S +++ b/arch/x86/lib/retpoline.S @@ -210,13 +210,13 @@ SYM_CODE_START_NOALIGN(srso_alias_safe_ret) /* * Tell objtool that those are not function pointers referenced by - * __HANDLE_INTR_SAFERET(). Below too. + * FIXUP_[NMI_]INTR_SAFERET(). Below too. */ ANNOTATE_NOENDBR /* * Safe-RET sequence. If you need to change it, adjust - * handle_interrupted_saferet() too. + * FIXUP_[NMI_]INTR_SAFERET() too. */ lea 8(%_ASM_SP), %_ASM_SP UNWIND_HINT_FUNC @@ -261,7 +261,7 @@ SYM_CODE_START_LOCAL_NOALIGN(srso_untrain_ret) SYM_INNER_LABEL(srso_safe_ret, SYM_L_GLOBAL) /* * Safe-RET sequence. If you need to change it, adjust - * handle_interrupted_saferet() too. + * FIXUP_[NMI_]INTR_SAFERET() too. */ lea 8(%_ASM_SP), %_ASM_SP ret diff --git a/arch/x86/net/bpf_jit_comp.c b/arch/x86/net/bpf_jit_comp.c index 4c3e09d98131d2..a45668e971a44a 100644 --- a/arch/x86/net/bpf_jit_comp.c +++ b/arch/x86/net/bpf_jit_comp.c @@ -683,6 +683,12 @@ static void __emit_indirect_jump(u8 **pprog, int reg, bool ereg) *pprog = prog; } +/* its_static_thunk() can give the one that completes the check of a hash */ +static u8 *its_thunk(int reg) +{ + return IS_ENABLED(CONFIG_MITIGATION_ITS) ? __x86_indirect_its_thunk_array[reg] : NULL; +} + static void emit_indirect_jump(u8 **pprog, int bpf_reg, u8 *ip) { u8 *prog = *pprog; @@ -691,7 +697,7 @@ static void emit_indirect_jump(u8 **pprog, int bpf_reg, u8 *ip) if (cpu_feature_enabled(X86_FEATURE_INDIRECT_THUNK_ITS)) { OPTIMIZER_HIDE_VAR(reg); - emit_jump(&prog, its_static_thunk(reg + 8*ereg), ip); + emit_jump(&prog, its_thunk(reg + 8*ereg), ip); } else if (cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) { EMIT_LFENCE(); __emit_indirect_jump(&prog, reg, ereg); @@ -732,7 +738,7 @@ static int emit_indirect_call(u8 **pprog, int bpf_reg, u8 *ip) if (cpu_feature_enabled(X86_FEATURE_INDIRECT_THUNK_ITS)) { OPTIMIZER_HIDE_VAR(reg); - err = emit_call(&prog, its_static_thunk(reg + 8*ereg), ip); + err = emit_call(&prog, its_thunk(reg + 8*ereg), ip); } else if (cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) { EMIT_LFENCE(); __emit_indirect_call(&prog, reg, ereg); @@ -1681,6 +1687,23 @@ static int emit_atomic_rmw_index(u8 **pprog, u32 atomic_op, u32 size, return 0; } +/* + * AUX_REG = dst_reg, with the low bits of dst_reg + off in the top bits. r12 + AUX_REG + off + * is not canonical when it's not aligned: the access faults, no split lock is taken. + */ +static void emit_arena_align_check(u8 **pprog, const struct bpf_insn *insn, u32 dst_reg) +{ + int size = BPF_LDST_BYTES(insn); + u8 *prog = *pprog; + + /* lea r11, [dst_reg + off % size] */ + EMIT2(add_2mod(0x48, dst_reg, AUX_REG), 0x8D); + emit_insn_suffix(&prog, dst_reg, AUX_REG, insn->off & (size - 1)); + emit_shift_imm(&prog, BPF_LSH, AUX_REG, 64 - ilog2(size), true); + emit_alu_reg(&prog, BPF_OR, AUX_REG, dst_reg, true); + *pprog = prog; +} + static int emit_atomic_ld_st(struct bpf_verifier_env *env, u8 **pprog, struct bpf_insn *insn, u8 *ip, u32 dst_reg, u32 src_reg, bool accesses_stack_only) @@ -1765,12 +1788,14 @@ static int emit_atomic_fetch_rmw(u8 **pprog, struct bpf_insn *insn, u32 dst_reg, branch_target = prog; /* Load old value */ + if (index_reg >= 0) + emit_arena_align_check(&prog, insn, dst_reg); if (fault) fault[0] = prog; if (index_reg < 0) emit_ldx(&prog, BPF_SIZE(insn->code), BPF_REG_0, dst_reg, insn->off); else - emit_ldx_index(&prog, BPF_SIZE(insn->code), BPF_REG_0, dst_reg, + emit_ldx_index(&prog, BPF_SIZE(insn->code), BPF_REG_0, AUX_REG, index_reg, insn->off); /* @@ -2575,7 +2600,8 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int * bpf_prog_was_classic(bpf_prog), tail_call_reachable, bpf_is_subprog(bpf_prog), bpf_prog->aux->exception_cb); - bpf_prog->aux->ksym.fp_start = prog - temp; + bpf_prog->aux->ksym.fp_start = prog - temp - cfi_get_offset(); + bpf_prog->aux->ksym.fp_end = U32_MAX; /* Exception callback will clobber callee regs for its own use, and * restore the original callee regs from main prog's stack frame. @@ -3403,6 +3429,8 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int * } break; } + if (!bpf_atomic_is_load_store(insn)) + emit_arena_align_check(&prog, insn, dst_reg); start_of_ldx = prog; if (bpf_atomic_is_load_store(insn)) @@ -3411,7 +3439,7 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int * src_reg, X86_REG_R12, insn->off); else err = emit_atomic_rmw_index(&prog, insn->imm, BPF_SIZE(insn->code), - dst_reg, src_reg, X86_REG_R12, + AUX_REG, src_reg, X86_REG_R12, insn->off); if (err) return err; @@ -3801,7 +3829,7 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int * pop_r12(&prog); } EMIT1(0xC9); /* leave */ - bpf_prog->aux->ksym.fp_end = prog - temp; + bpf_prog->aux->ksym.fp_ret = proglen + (prog - temp) - cfi_get_offset(); emit_return(&prog, image + addrs[i - 1] + (prog - temp)); break; @@ -4453,8 +4481,7 @@ static int __arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *rw_im } EMIT1(0x55); /* push rbp */ EMIT3(0x48, 0x89, 0xE5); /* mov rbp, rsp */ - if (im) - im->ksym.fp_start = prog - (u8 *)rw_image; + im->ksym.fp_start = prog - (u8 *)rw_image; /* sub rsp, stack_size */ emit_sub_rsp(&prog, stack_size); @@ -4595,8 +4622,7 @@ static int __arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *rw_im emit_ldx(&prog, BPF_DW, BPF_REG_6, BPF_REG_FP, -rbx_off); EMIT1(0xC9); /* leave */ - if (im) - im->ksym.fp_end = prog - (u8 *)rw_image; + im->ksym.fp_end = prog - (u8 *)rw_image; if (flags & BPF_TRAMP_F_SKIP_FRAME) { /* skip our return address and return to parent */ @@ -4675,6 +4701,7 @@ int arch_bpf_trampoline_size(const struct btf_func_model *m, u32 flags, static int emit_bpf_dispatcher(u8 **pprog, int a, int b, s64 *progs, u8 *image, u8 *buf) { + void *nop_func = bpf_dispatcher_nop_func; u8 *jg_reloc, *prog = *pprog; int pivot, err, jg_bytes = 1; s64 jg_offset; @@ -4694,7 +4721,11 @@ static int emit_bpf_dispatcher(u8 **pprog, int a, int b, s64 *progs, u8 *image, if (err) return err; - emit_indirect_jump(&prog, BPF_REG_3 /* R3 -> rdx */, image + (prog - buf)); + /* With FineIBT there is no ENDBR at bpf_func, go through the preamble */ + OPTIMIZER_HIDE_VAR(nop_func); + err = emit_jump(&prog, nop_func, image + (prog - buf)); + if (err) + return err; *pprog = prog; return 0; diff --git a/arch/x86/platform/efi/efi.c b/arch/x86/platform/efi/efi.c index 5eb96c17883e86..f569d9a7c5ab66 100644 --- a/arch/x86/platform/efi/efi.c +++ b/arch/x86/platform/efi/efi.c @@ -432,6 +432,40 @@ static int __init efi_systab_init(unsigned long phys) return 0; } +/* + * kexec passes the firmware's config table array on to the next kernel as-is, + * but some of the tables it describes must be disregarded when booting via + * kexec, which is indicated by the presence of a SETUP_EFI setup_data entry: + * + * - The INITRD table is installed by the EFI stub to describe the initrd that + * it loaded. Both the table and the initrd are allocated from EFI loader + * data, which is released to the page allocator once the kernel is up and + * running, and so the table is stale by the time kexec boots the next kernel. + * + * - The TPM event log table is installed by the EFI stub too. It is allocated + * from EFI loader data rather than ACPI reclaim memory, as the latter would + * create an E820 entry that may move around between boots, which breaks + * resume from hibernation. It is reserved by the kernel, but the E820 map + * that kexec passes on describes it as ordinary RAM, and so it may get + * clobbered before the next kernel gets around to reserving it. + * + * - The Memory Attributes table may reside in EFI boot services data, which is + * released to the page allocator as well. Even if it is still intact, the + * sanity check in efi_memattr_init() may fail spuriously, given that only + * the runtime regions of the EFI memory map are passed on via kexec. Applying + * the permissions it describes is not critical, so just ignore it. + */ +bool __init x86_efi_config_table_is_usable(const efi_guid_t *guid, + unsigned long table) +{ + if (!efi_setup) + return true; + + return efi_guidcmp(*guid, LINUX_EFI_INITRD_MEDIA_GUID) && + efi_guidcmp(*guid, LINUX_EFI_TPM_EVENT_LOG_GUID) && + efi_guidcmp(*guid, EFI_MEMORY_ATTRIBUTES_TABLE_GUID); +} + static int __init efi_config_init(const efi_config_table_type_t *arch_tables) { void *config_tables; diff --git a/arch/x86/platform/efi/quirks.c b/arch/x86/platform/efi/quirks.c index 02c56a02eb9bc4..d6d34dfa19e60b 100644 --- a/arch/x86/platform/efi/quirks.c +++ b/arch/x86/platform/efi/quirks.c @@ -611,10 +611,6 @@ int __init efi_reuse_config(u64 tables, int nr_tables) if (!efi_guidcmp(guid, SMBIOS_TABLE_GUID)) ((efi_config_table_64_t *)p)->table = data->smbios; - /* Do not bother to play with mem attr table across kexec */ - if (!efi_guidcmp(guid, EFI_MEMORY_ATTRIBUTES_TABLE_GUID)) - ((efi_config_table_64_t *)p)->table = EFI_INVALID_TABLE_ADDR; - p += sz; } early_memunmap(tablep, nr_tables * sz); diff --git a/block/bio-integrity.c b/block/bio-integrity.c index d3df726e0f0881..aaea5802ecd5d3 100644 --- a/block/bio-integrity.c +++ b/block/bio-integrity.c @@ -394,6 +394,11 @@ int bio_integrity_map_user(struct bio *bio, struct iov_iter *iter) copy = iov_iter_alignment(iter) & blk_lim_dma_alignment_and_pad(&q->limits); + /* Reference-tag remapping must operate on a private copy of user PI. */ + if (bio_op(bio) == REQ_OP_WRITE && + (q->limits.integrity.flags & BLK_INTEGRITY_REF_TAG)) + copy = true; + if (blk_queue_pci_p2pdma(q)) extraction_flags |= ITER_ALLOW_P2PDMA; diff --git a/block/blk-core.c b/block/blk-core.c index 8836c7028568b0..2ee079c1ce150e 100644 --- a/block/blk-core.c +++ b/block/blk-core.c @@ -226,21 +226,19 @@ const char *blk_status_to_tag(blk_status_t status) return blk_errors[idx].tag; } -blk_status_t tag_to_blk_status(const char *tag) +bool tag_to_blk_status(const char *tag, blk_status_t *status) { int i; for (i = 0; i < ARRAY_SIZE(blk_errors); i++) { if (blk_errors[i].tag && - !strcmp(blk_errors[i].tag, tag)) - return (__force blk_status_t)i; + !strcmp(blk_errors[i].tag, tag)) { + *status = (__force blk_status_t)i; + return true; + } } - /* - * Return BLK_STS_OK for mismatches as this function is intended to - * parse error status values. - */ - return BLK_STS_OK; + return false; } /** diff --git a/block/blk-iocost.c b/block/blk-iocost.c index 1c1025157d8e48..0ffe34bd95b739 100644 --- a/block/blk-iocost.c +++ b/block/blk-iocost.c @@ -1853,7 +1853,8 @@ static u32 hweight_after_donation(struct ioc_gq *iocg, u32 old_hwi, u32 hwm, delta = div64_s64(WEIGHT_ONE * (now->vnow - vtime), now->vnow - ioc->period_at_vtime); target = WEIGHT_ONE * MARGIN_TARGET_PCT / 100; - new_hwi = div64_s64(WEIGHT_ONE * usage, WEIGHT_ONE - target + delta); + new_hwi = div64_s64((s64)WEIGHT_ONE * usage, + WEIGHT_ONE - target + delta); return clamp_t(s64, new_hwi, 1, hwm); } diff --git a/block/blk-lib.c b/block/blk-lib.c index 688bc67cbf733d..e98aa4837079c0 100644 --- a/block/blk-lib.c +++ b/block/blk-lib.c @@ -3,6 +3,7 @@ * Functions related to generic helpers functions */ #include +#include #include #include #include @@ -13,26 +14,25 @@ static sector_t bio_discard_limit(struct block_device *bdev, sector_t sector) { unsigned int discard_granularity = bdev_discard_granularity(bdev); - sector_t granularity_aligned_sector; + u32 unaligned_sectors; + + if (!discard_granularity) + return BIO_MAX_SECTORS; if (bdev_is_partition(bdev)) sector += bdev->bd_start_sect; - granularity_aligned_sector = - round_up(sector, discard_granularity >> SECTOR_SHIFT); - - /* - * Make sure subsequent bios start aligned to the discard granularity if - * it needs to be split. - */ - if (granularity_aligned_sector != sector) - return granularity_aligned_sector - sector; - /* - * Align the bio size to the discard granularity to make splitting the bio - * at discard granularity boundaries easier in the driver if needed. + * Align the bio size to the discard granularity to make splitting the + * bio at discard granularity boundaries easier in the driver if needed. + * + * If the current sector is not aligned, shorten the range so that the + * next one is aligned. */ - return round_down(BIO_MAX_SIZE, discard_granularity) >> SECTOR_SHIFT; + div_u64_rem(sector, discard_granularity >> SECTOR_SHIFT, + &unaligned_sectors); + return (rounddown(BIO_MAX_SIZE, discard_granularity) >> SECTOR_SHIFT) - + unaligned_sectors; } struct bio *blk_alloc_discard_bio(struct block_device *bdev, diff --git a/block/blk-mq.c b/block/blk-mq.c index 5ae22d55654044..54ccfc43c27c2e 100644 --- a/block/blk-mq.c +++ b/block/blk-mq.c @@ -4354,7 +4354,10 @@ static void blk_mq_del_queue_tag_set(struct request_queue *q) lockdep_assert_held(&set->tag_list_lock); + /* blk_mq_unquiesce_tagset() runs the hctxs, which are not RCU freed */ + spin_lock(&set->quiesce_lock); list_del_rcu(&q->tag_set_list); + spin_unlock(&set->quiesce_lock); if (list_is_singular(&set->tag_list)) { /* just transitioned to unshared */ set->flags &= ~BLK_MQ_F_TAG_QUEUE_SHARED; diff --git a/block/blk-pm.c b/block/blk-pm.c index 8d3e052f91da16..34cc7c5ca04e23 100644 --- a/block/blk-pm.c +++ b/block/blk-pm.c @@ -142,7 +142,8 @@ EXPORT_SYMBOL(blk_post_runtime_suspend); * * Description: * Update the queue's runtime status to RESUMING in preparation for the - * runtime resume of the device. + * runtime resume of the device if the queue is runtime suspended, or keep + * RPM_ACTIVE if a previous failed runtime resume already reactivated it. * * This function should be called near the start of the device's * runtime_resume callback. @@ -153,7 +154,9 @@ void blk_pre_runtime_resume(struct request_queue *q) return; spin_lock_irq(&q->queue_lock); - q->rpm_status = RPM_RESUMING; + /* Keep RPM_ACTIVE if a prior failed resume reactivated the queue. */ + if (q->rpm_status == RPM_SUSPENDED) + q->rpm_status = RPM_RESUMING; spin_unlock_irq(&q->queue_lock); } EXPORT_SYMBOL(blk_pre_runtime_resume); @@ -168,8 +171,8 @@ EXPORT_SYMBOL(blk_pre_runtime_resume); * driver or error handler will need to communicate with the device. * * This function should be called near the end of the device's - * runtime_resume callback to correct queue runtime PM status and re-enable - * peeking requests from the queue. + * runtime_resume callback to mark the queue runtime active and clear + * pm_only if the queue was resuming. */ void blk_post_runtime_resume(struct request_queue *q) { @@ -185,7 +188,7 @@ void blk_post_runtime_resume(struct request_queue *q) pm_request_autosuspend(q->dev); spin_unlock_irq(&q->queue_lock); - if (old_status != RPM_ACTIVE) + if (old_status == RPM_RESUMING) blk_clear_pm_only(q); } EXPORT_SYMBOL(blk_post_runtime_resume); diff --git a/block/blk.h b/block/blk.h index 0e38e4b88cf544..105fff157bfbd4 100644 --- a/block/blk.h +++ b/block/blk.h @@ -52,7 +52,7 @@ void blk_free_flush_queue(struct blk_flush_queue *q); const char *blk_status_to_str(blk_status_t status); const char *blk_status_to_tag(blk_status_t status); -blk_status_t tag_to_blk_status(const char *tag); +bool tag_to_blk_status(const char *tag, blk_status_t *status); enum req_op str_to_blk_op(const char *op); bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic); diff --git a/block/error-injection.c b/block/error-injection.c index e14bc4b723efb0..a6de52229ef3be 100644 --- a/block/error-injection.c +++ b/block/error-injection.c @@ -6,9 +6,17 @@ #include #include #include +#include #include "blk.h" #include "error-injection.h" +/* + * Cap the delay so that a typo can't wedge a device for good. This is still + * well beyond the default hung task timeout, which is one of the things a + * delay is useful for triggering. + */ +#define BLK_ERROR_INJECT_MAX_DELAY_US (600 * USEC_PER_SEC) + struct blk_error_inject { struct list_head entry; sector_t start; @@ -18,14 +26,97 @@ struct blk_error_inject { /* only inject every 1 / chance times */ unsigned int chance; + + /* hold the bio for this long before submitting or failing it */ + unsigned int delay_us; +}; + +/* + * A bio held by a delay rule. It does not point back at the rule, so rules + * can be removed while delayed bios are outstanding. The submitter holds the + * bdev open until the bio completes, so the disk and queue stay allocated. + * A delayed bio holds no queue usage counter reference, so it does not hold + * up a queue freeze either. + */ +struct blk_error_inject_delay { + struct delayed_work dwork; + struct bio *bio; + blk_status_t status; }; +static struct workqueue_struct *blk_error_inject_wq; + DEFINE_STATIC_KEY_FALSE(blk_error_injection_enabled); +static void blk_error_inject_fail(struct bio *bio, blk_status_t status) +{ + pr_info_ratelimited("%pg: injecting %s error for %s at sector %llu:%u\n", + bio->bi_bdev->bd_disk->part0, blk_status_to_str(status), + blk_op_str(bio_op(bio)), bio->bi_iter.bi_sector, + bio_sectors(bio)); + bio_endio_status(bio, status); +} + +static void blk_error_inject_delay_work(struct work_struct *work) +{ + struct blk_error_inject_delay *d = container_of(to_delayed_work(work), + struct blk_error_inject_delay, dwork); + struct bio *bio = d->bio; + blk_status_t status = d->status; + + kfree(d); + + if (status != BLK_STS_OK) { + blk_error_inject_fail(bio, status); + return; + } + + /* + * Resubmit. The BIO_ERROR_INJECTED flag ensures that a bio that was + * delayed once skips error injection entirely from here on, including + * any other rule that covers it. + */ + submit_bio_noacct_nocheck(bio, false); +} + +static bool blk_error_inject_delay(struct gendisk *disk, struct bio *bio, + blk_status_t status, unsigned int delay_us) +{ + struct blk_error_inject_delay *d; + + /* fail a bio that can't block, as a real queue would */ + if (bio->bi_opf & REQ_NOWAIT) { + bio_wouldblock_error(bio); + return true; + } + + d = kmalloc_obj(*d, GFP_NOIO); + if (!d) { + pr_warn_ratelimited("%pg: failed to delay %s at sector %llu:%u\n", + disk->part0, blk_op_str(bio_op(bio)), + bio->bi_iter.bi_sector, bio_sectors(bio)); + return false; + } + + pr_info_ratelimited("%pg: delaying %s at sector %llu:%u by %uus\n", + disk->part0, blk_op_str(bio_op(bio)), + bio->bi_iter.bi_sector, bio_sectors(bio), delay_us); + + d->bio = bio; + d->status = status; + INIT_DELAYED_WORK(&d->dwork, blk_error_inject_delay_work); + + queue_delayed_work(blk_error_inject_wq, &d->dwork, + usecs_to_jiffies(delay_us)); + return true; +} + bool __blk_error_inject(struct bio *bio) { struct gendisk *disk = bio->bi_bdev->bd_disk; struct blk_error_inject *inj; + blk_status_t status = BLK_STS_OK; + unsigned int delay_us = 0; rcu_read_lock(); list_for_each_entry_rcu(inj, &disk->error_injection_list, entry) { @@ -45,29 +136,34 @@ bool __blk_error_inject(struct bio *bio) if (inj->chance > 1 && (get_random_u32() % inj->chance) != 0) continue; - pr_info_ratelimited("%pg: injecting %s error for %s at sector %llu:%u\n", - disk->part0, blk_status_to_str(inj->status), - blk_op_str(inj->op), bio->bi_iter.bi_sector, - bio_sectors(bio)); - bio->bi_status = inj->status; - rcu_read_unlock(); - bio_endio(bio); - return true; + status = inj->status; + delay_us = inj->delay_us; + bio_set_flag(bio, BIO_ERROR_INJECTED); + break; } rcu_read_unlock(); - return false; + + if (delay_us && blk_error_inject_delay(disk, bio, status, delay_us)) + return true; + if (status == BLK_STS_OK) + return false; + + blk_error_inject_fail(bio, status); + return true; } static int error_inject_add(struct gendisk *disk, enum req_op op, sector_t start, u64 nr_sectors, blk_status_t status, - unsigned int chance) + unsigned int chance, unsigned int delay_us) { struct blk_error_inject *inj; int error = -EINVAL; if (op == REQ_OP_LAST) return -EINVAL; - if (status == BLK_STS_OK) + if (status == BLK_STS_OK && !delay_us) + return -EINVAL; + if (delay_us > BLK_ERROR_INJECT_MAX_DELAY_US) return -EINVAL; inj = kzalloc_obj(*inj); @@ -86,6 +182,7 @@ static int error_inject_add(struct gendisk *disk, enum req_op op, inj->start = start; inj->status = status; inj->chance = chance; + inj->delay_us = delay_us; pr_debug_ratelimited("%pg: adding %s injection for %s at sector %llu:%llu\n", disk->part0, blk_status_to_str(status), @@ -139,6 +236,7 @@ enum options { Opt_nr_sectors = (1u << 18), Opt_status = (1u << 19), Opt_chance = (1u << 20), + Opt_delay_us = (1u << 21), Opt_invalid, }; @@ -151,6 +249,7 @@ static const match_table_t opt_tokens = { { Opt_nr_sectors, "nr_sectors=%u" }, { Opt_status, "status=%s" }, { Opt_chance, "chance=%u" }, + { Opt_delay_us, "delay_us=%u" }, { Opt_invalid, NULL, }, }; @@ -171,22 +270,23 @@ static int match_op(substring_t *args, enum req_op *op) static int match_status(substring_t *args, blk_status_t *status) { const char *tag; + bool found; tag = match_strdup(args); if (!tag) return -ENOMEM; - *status = tag_to_blk_status(tag); - if (!*status) + found = tag_to_blk_status(tag, status); + if (!found) pr_warn("invalid status '%s'\n", tag); kfree(tag); - return 0; + return found ? 0 : -EINVAL; } static ssize_t blk_error_injection_parse_options(struct gendisk *disk, char *options) { enum { Unset, Add, Removeall } action = Unset; - unsigned int option_mask = 0, chance = 1; + unsigned int option_mask = 0, chance = 1, delay_us = 0; enum req_op op = REQ_OP_LAST; u64 start = 0, nr_sectors = 0; blk_status_t status = BLK_STS_OK; @@ -229,6 +329,9 @@ static ssize_t blk_error_injection_parse_options(struct gendisk *disk, if (!error && chance == 0) error = -EINVAL; break; + case Opt_delay_us: + error = match_uint(args, &delay_us); + break; default: pr_warn("unknown parameter or missing value '%s'\n", p); error = -EINVAL; @@ -240,7 +343,7 @@ static ssize_t blk_error_injection_parse_options(struct gendisk *disk, switch (action) { case Add: return error_inject_add(disk, op, start, nr_sectors, status, - chance); + chance, delay_us); case Removeall: if (option_mask & ~Opt_removeall) return -EINVAL; @@ -276,10 +379,11 @@ static int blk_error_injection_show(struct seq_file *s, void *private) rcu_read_lock(); list_for_each_entry_rcu(inj, &disk->error_injection_list, entry) { - seq_printf(s, "%llu:%llu op=%s,status=%s,chance=%u", + seq_printf(s, "%llu:%llu op=%s,status=%s,chance=%u,delay_us=%u", inj->start, inj->end, blk_op_str(inj->op), - blk_status_to_tag(inj->status), inj->chance); + blk_status_to_tag(inj->status), inj->chance, + inj->delay_us); seq_putc(s, '\n'); } rcu_read_unlock(); @@ -314,3 +418,13 @@ void blk_error_injection_exit(struct gendisk *disk) { error_inject_removeall(disk); } + +static int __init blk_error_injection_init_wq(void) +{ + blk_error_inject_wq = alloc_workqueue("blk_error_inject", + WQ_MEM_RECLAIM | WQ_UNBOUND, 0); + if (!blk_error_inject_wq) + panic("Failed to create blk_error_inject wq\n"); + return 0; +} +subsys_initcall(blk_error_injection_init_wq); diff --git a/block/error-injection.h b/block/error-injection.h index 9821d773abab87..8b3809d85e83ea 100644 --- a/block/error-injection.h +++ b/block/error-injection.h @@ -13,6 +13,7 @@ static inline bool blk_error_inject(struct bio *bio) { if (IS_ENABLED(CONFIG_BLK_ERROR_INJECTION) && static_branch_unlikely(&blk_error_injection_enabled) && + !bio_flagged(bio, BIO_ERROR_INJECTED) && test_bit(GD_ERROR_INJECT, &bio->bi_bdev->bd_disk->state)) return __blk_error_inject(bio); return false; diff --git a/block/ioctl.c b/block/ioctl.c index fb2f4b4d2505ed..96da0c87802be1 100644 --- a/block/ioctl.c +++ b/block/ioctl.c @@ -177,8 +177,7 @@ static int blk_ioctl_discard(struct block_device *bdev, blk_mode_t mode, static int blk_ioctl_secure_erase(struct block_device *bdev, blk_mode_t mode, void __user *argp) { - uint64_t start, len, end; - uint64_t range[2]; + uint64_t range[2], start, len; int err; if (!(mode & BLK_OPEN_WRITE)) @@ -190,15 +189,13 @@ static int blk_ioctl_secure_erase(struct block_device *bdev, blk_mode_t mode, start = range[0]; len = range[1]; - if ((start & 511) || (len & 511)) - return -EINVAL; - if (check_add_overflow(start, len, &end) || - end > bdev_nr_bytes(bdev)) - return -EINVAL; + err = blk_validate_byte_range(bdev, start, len); + if (err) + return err; inode_lock(bdev->bd_mapping->host); filemap_invalidate_lock(bdev->bd_mapping); - err = truncate_bdev_range(bdev, mode, start, end - 1); + err = truncate_bdev_range(bdev, mode, start, start + len - 1); if (!err) err = blkdev_issue_secure_erase(bdev, start >> 9, len >> 9, GFP_KERNEL); diff --git a/drivers/accel/ivpu/ivpu_pm.c b/drivers/accel/ivpu/ivpu_pm.c index aa813262253e4a..e4b79c946ca013 100644 --- a/drivers/accel/ivpu/ivpu_pm.c +++ b/drivers/accel/ivpu/ivpu_pm.c @@ -150,8 +150,8 @@ static void ivpu_pm_reset_complete(struct ivpu_device *vdev) up_write(&vdev->pm->reset_lock); atomic_set(&vdev->pm->reset_pending, 0); - pm_runtime_mark_last_busy(vdev->drm.dev); pm_runtime_enable(vdev->drm.dev); + pm_request_autosuspend(vdev->drm.dev); } static void ivpu_pm_recovery_work(struct work_struct *work) @@ -415,6 +415,7 @@ void ivpu_pm_init(struct ivpu_device *vdev) atomic_set(&pm->engine_reset_counter, 0); INIT_WORK(&pm->recovery_work, ivpu_pm_recovery_work); + disable_work(&pm->recovery_work); INIT_DELAYED_WORK(&pm->job_timeout_work, ivpu_job_timeout_work); if (ivpu_disable_recovery) @@ -439,6 +440,12 @@ void ivpu_pm_enable(struct ivpu_device *vdev) { struct device *dev = vdev->drm.dev; + enable_work(&vdev->pm->recovery_work); + if (atomic_read(&vdev->pm->reset_pending)) { + queue_work(system_dfl_wq, &vdev->pm->recovery_work); + flush_work(&vdev->pm->recovery_work); + } + pm_runtime_allow(dev); pm_runtime_put_autosuspend(dev); } diff --git a/drivers/accel/qaic/qaic_data.c b/drivers/accel/qaic/qaic_data.c index ee35e13091b308..be3ceb8c51a09d 100644 --- a/drivers/accel/qaic/qaic_data.c +++ b/drivers/accel/qaic/qaic_data.c @@ -1256,6 +1256,11 @@ static int send_bo_list_to_device(struct qaic_device *qdev, struct drm_file *fil goto unlock_bo; } + if (bo->dbc->id != dbc->id) { + ret = -EINVAL; + goto unlock_bo; + } + if (is_partial && pexec[i].resize > bo->base.size) { ret = -EINVAL; goto unlock_bo; @@ -1769,6 +1774,17 @@ int qaic_wait_bo_ioctl(struct drm_device *dev, void *data, struct drm_file *file } bo = to_qaic_bo(obj); + + if (!bo->sliced) { + ret = -EINVAL; + goto put_obj; + } + + if (bo->dbc->id != dbc->id) { + ret = -EINVAL; + goto put_obj; + } + timeout = args->timeout ? args->timeout : wait_exec_default_timeout_ms; timeout = msecs_to_jiffies(timeout); ret = wait_for_completion_interruptible_timeout(&bo->xfer_done, timeout); diff --git a/drivers/accel/rocket/rocket_core.c b/drivers/accel/rocket/rocket_core.c index b3b2fa9ba645a6..d4c06ad4ba9571 100644 --- a/drivers/accel/rocket/rocket_core.c +++ b/drivers/accel/rocket/rocket_core.c @@ -28,6 +28,10 @@ int rocket_core_init(struct rocket_core *core) if (err) return dev_err_probe(dev, err, "failed to get resets for core %d\n", core->index); + core->clks[ROCKET_CLK_ACLK].id = "aclk"; + core->clks[ROCKET_CLK_HCLK].id = "hclk"; + core->clks[ROCKET_CLK_NPU].id = "npu"; + core->clks[ROCKET_CLK_PCLK].id = "pclk"; err = devm_clk_bulk_get(dev, ARRAY_SIZE(core->clks), core->clks); if (err) return dev_err_probe(dev, err, "failed to get clocks for core %d\n", core->index); diff --git a/drivers/accel/rocket/rocket_core.h b/drivers/accel/rocket/rocket_core.h index f6d7382854ca9e..0b7e82ae7ef28d 100644 --- a/drivers/accel/rocket/rocket_core.h +++ b/drivers/accel/rocket/rocket_core.h @@ -27,16 +27,28 @@ #define rocket_core_writel(core, reg, value) \ writel(value, (core)->core_iomem + (REG_CORE_##reg) - REG_CORE_S_STATUS) +enum rocket_clk { + ROCKET_CLK_ACLK, + ROCKET_CLK_HCLK, + ROCKET_CLK_NPU, + ROCKET_CLK_PCLK, + ROCKET_CLK_MAX, +}; + struct rocket_core { struct device *dev; struct rocket_device *rdev; + /* + * Hardware number of the core: its position among the core nodes in + * the devicetree. + */ unsigned int index; int irq; void __iomem *pc_iomem; void __iomem *cna_iomem; void __iomem *core_iomem; - struct clk_bulk_data clks[4]; + struct clk_bulk_data clks[ROCKET_CLK_MAX]; struct reset_control_bulk_data resets[2]; struct iommu_group *iommu_group; diff --git a/drivers/accel/rocket/rocket_drv.c b/drivers/accel/rocket/rocket_drv.c index 5d7805c41dc3d1..e62a20edeca756 100644 --- a/drivers/accel/rocket/rocket_drv.c +++ b/drivers/accel/rocket/rocket_drv.c @@ -24,48 +24,57 @@ */ static struct platform_device *drm_dev; static struct rocket_device *rdev; +static void *rdev_group; static void -rocket_iommu_domain_destroy(struct kref *kref) +rocket_vm_destroy(struct kref *kref) { - struct rocket_iommu_domain *domain = container_of(kref, struct rocket_iommu_domain, kref); + struct rocket_vm *vm = container_of(kref, struct rocket_vm, kref); - iommu_domain_free(domain->domain); - domain->domain = NULL; - kfree(domain); + drm_mm_takedown(&vm->mm); + mutex_destroy(&vm->lock); + iommu_domain_free(vm->domain); + vm->domain = NULL; + kfree(vm); } -static struct rocket_iommu_domain* -rocket_iommu_domain_create(struct device *dev) +static struct rocket_vm * +rocket_vm_create(struct device *dev) { - struct rocket_iommu_domain *domain = kmalloc_obj(*domain); + struct rocket_vm *vm = kmalloc_obj(*vm); + u64 start, end; void *err; - if (!domain) + if (!vm) return ERR_PTR(-ENOMEM); - domain->domain = iommu_paging_domain_alloc(dev); - if (IS_ERR(domain->domain)) { - err = ERR_CAST(domain->domain); - kfree(domain); + vm->domain = iommu_paging_domain_alloc(dev); + if (IS_ERR(vm->domain)) { + err = ERR_CAST(vm->domain); + kfree(vm); return err; } - kref_init(&domain->kref); - return domain; + start = vm->domain->geometry.aperture_start; + end = vm->domain->geometry.aperture_end; + drm_mm_init(&vm->mm, start, end - start + 1); + mutex_init(&vm->lock); + kref_init(&vm->kref); + + return vm; } -struct rocket_iommu_domain * -rocket_iommu_domain_get(struct rocket_file_priv *rocket_priv) +struct rocket_vm * +rocket_vm_get(struct rocket_file_priv *rocket_priv) { - kref_get(&rocket_priv->domain->kref); - return rocket_priv->domain; + kref_get(&rocket_priv->vm->kref); + return rocket_priv->vm; } void -rocket_iommu_domain_put(struct rocket_iommu_domain *domain) +rocket_vm_put(struct rocket_vm *vm) { - kref_put(&domain->kref, rocket_iommu_domain_destroy); + kref_put(&vm->kref, rocket_vm_destroy); } static int @@ -73,7 +82,6 @@ rocket_open(struct drm_device *dev, struct drm_file *file) { struct rocket_device *rdev = to_rocket_device(dev); struct rocket_file_priv *rocket_priv; - u64 start, end; int ret; if (!try_module_get(THIS_MODULE)) @@ -86,29 +94,22 @@ rocket_open(struct drm_device *dev, struct drm_file *file) } rocket_priv->rdev = rdev; - rocket_priv->domain = rocket_iommu_domain_create(rdev->cores[0].dev); - if (IS_ERR(rocket_priv->domain)) { - ret = PTR_ERR(rocket_priv->domain); + rocket_priv->vm = rocket_vm_create(rdev->cores[0].dev); + if (IS_ERR(rocket_priv->vm)) { + ret = PTR_ERR(rocket_priv->vm); goto err_free; } file->driver_priv = rocket_priv; - start = rocket_priv->domain->domain->geometry.aperture_start; - end = rocket_priv->domain->domain->geometry.aperture_end; - drm_mm_init(&rocket_priv->mm, start, end - start + 1); - mutex_init(&rocket_priv->mm_lock); - ret = rocket_job_open(rocket_priv); if (ret) - goto err_mm_takedown; + goto err_vm_put; return 0; -err_mm_takedown: - mutex_destroy(&rocket_priv->mm_lock); - drm_mm_takedown(&rocket_priv->mm); - rocket_iommu_domain_put(rocket_priv->domain); +err_vm_put: + rocket_vm_put(rocket_priv->vm); err_free: kfree(rocket_priv); err_put_mod: @@ -122,9 +123,7 @@ rocket_postclose(struct drm_device *dev, struct drm_file *file) struct rocket_file_priv *rocket_priv = file->driver_priv; rocket_job_close(rocket_priv); - mutex_destroy(&rocket_priv->mm_lock); - drm_mm_takedown(&rocket_priv->mm); - rocket_iommu_domain_put(rocket_priv->domain); + rocket_vm_put(rocket_priv->vm); kfree(rocket_priv); module_put(THIS_MODULE); } @@ -157,20 +156,45 @@ static const struct drm_driver rocket_drm_driver = { .desc = "rocket DRM", }; +static int rocket_core_hw_index(struct device *dev) +{ + struct device_node *np; + int index = 0; + + for_each_matching_node(np, dev->driver->of_match_table) { + if (np == dev->of_node) { + of_node_put(np); + return index; + } + index++; + } + + return -ENODEV; +} + static int rocket_probe(struct platform_device *pdev) { + int index = rocket_core_hw_index(&pdev->dev); int ret; + if (index < 0) + return index; + if (rdev == NULL) { /* First core probing, initialize DRM device. */ + rdev_group = devres_open_group(&drm_dev->dev, NULL, GFP_KERNEL); + if (!rdev_group) + return -ENOMEM; rdev = rocket_device_init(drm_dev, &rocket_drm_driver); if (IS_ERR(rdev)) { int err = PTR_ERR(rdev); dev_err(&pdev->dev, "failed to initialize rocket device\n"); rdev = NULL; + devres_release_group(&drm_dev->dev, rdev_group); return err; } + devres_close_group(&drm_dev->dev, rdev_group); } unsigned int core = rdev->num_cores; @@ -179,7 +203,7 @@ static int rocket_probe(struct platform_device *pdev) rdev->cores[core].rdev = rdev; rdev->cores[core].dev = &pdev->dev; - rdev->cores[core].index = core; + rdev->cores[core].index = index; rdev->num_cores++; @@ -190,6 +214,7 @@ static int rocket_probe(struct platform_device *pdev) if (rdev->num_cores == 0) { rocket_device_fini(rdev); rdev = NULL; + devres_release_group(&drm_dev->dev, rdev_group); } } @@ -213,6 +238,7 @@ static void rocket_remove(struct platform_device *pdev) /* Last core removed, deinitialize DRM device. */ rocket_device_fini(rdev); rdev = NULL; + devres_release_group(&drm_dev->dev, rdev_group); } } diff --git a/drivers/accel/rocket/rocket_drv.h b/drivers/accel/rocket/rocket_drv.h index 2c673bb99ccc1d..7069ececffc434 100644 --- a/drivers/accel/rocket/rocket_drv.h +++ b/drivers/accel/rocket/rocket_drv.h @@ -11,22 +11,24 @@ extern const struct dev_pm_ops rocket_pm_ops; -struct rocket_iommu_domain { +struct rocket_vm { struct iommu_domain *domain; + struct drm_mm mm; + /* protects @mm */ + struct mutex lock; struct kref kref; }; struct rocket_file_priv { struct rocket_device *rdev; - struct rocket_iommu_domain *domain; - struct drm_mm mm; - struct mutex mm_lock; + struct rocket_vm *vm; + struct drm_gpu_scheduler **scheds; struct drm_sched_entity sched_entity; }; -struct rocket_iommu_domain *rocket_iommu_domain_get(struct rocket_file_priv *rocket_priv); -void rocket_iommu_domain_put(struct rocket_iommu_domain *domain); +struct rocket_vm *rocket_vm_get(struct rocket_file_priv *rocket_priv); +void rocket_vm_put(struct rocket_vm *vm); #endif diff --git a/drivers/accel/rocket/rocket_gem.c b/drivers/accel/rocket/rocket_gem.c index d981c6a93ff12f..8f802df3e0f143 100644 --- a/drivers/accel/rocket/rocket_gem.c +++ b/drivers/accel/rocket/rocket_gem.c @@ -14,20 +14,20 @@ static void rocket_gem_bo_free(struct drm_gem_object *obj) { struct rocket_gem_object *bo = to_rocket_bo(obj); - struct rocket_file_priv *rocket_priv = bo->driver_priv; + struct rocket_vm *vm = bo->vm; size_t unmapped; drm_WARN_ON(obj->dev, refcount_read(&bo->base.pages_use_count) > 1); - unmapped = iommu_unmap(bo->domain->domain, bo->mm.start, bo->size); + unmapped = iommu_unmap(vm->domain, bo->mm.start, bo->size); drm_WARN_ON(obj->dev, unmapped != bo->size); - mutex_lock(&rocket_priv->mm_lock); + mutex_lock(&vm->lock); drm_mm_remove_node(&bo->mm); - mutex_unlock(&rocket_priv->mm_lock); + mutex_unlock(&vm->lock); - rocket_iommu_domain_put(bo->domain); - bo->domain = NULL; + rocket_vm_put(vm); + bo->vm = NULL; drm_gem_shmem_free(&bo->base); } @@ -64,6 +64,7 @@ int rocket_ioctl_create_bo(struct drm_device *dev, void *data, struct drm_file * struct drm_gem_shmem_object *shmem_obj; struct rocket_gem_object *rkt_obj; struct drm_gem_object *gem_obj; + struct rocket_vm *vm; struct sg_table *sgt; int ret; @@ -74,8 +75,8 @@ int rocket_ioctl_create_bo(struct drm_device *dev, void *data, struct drm_file * gem_obj = &shmem_obj->base; rkt_obj = to_rocket_bo(gem_obj); - rkt_obj->driver_priv = rocket_priv; - rkt_obj->domain = rocket_iommu_domain_get(rocket_priv); + vm = rocket_vm_get(rocket_priv); + rkt_obj->vm = vm; rkt_obj->size = args->size; rkt_obj->offset = 0; @@ -85,15 +86,15 @@ int rocket_ioctl_create_bo(struct drm_device *dev, void *data, struct drm_file * goto err; } - mutex_lock(&rocket_priv->mm_lock); - ret = drm_mm_insert_node_generic(&rocket_priv->mm, &rkt_obj->mm, + mutex_lock(&vm->lock); + ret = drm_mm_insert_node_generic(&vm->mm, &rkt_obj->mm, rkt_obj->size, PAGE_SIZE, 0, 0); - mutex_unlock(&rocket_priv->mm_lock); + mutex_unlock(&vm->lock); if (ret) goto err; - ret = iommu_map_sgtable(rocket_priv->domain->domain, + ret = iommu_map_sgtable(vm->domain, rkt_obj->mm.start, shmem_obj->sgt, IOMMU_READ | IOMMU_WRITE); @@ -118,15 +119,17 @@ int rocket_ioctl_create_bo(struct drm_device *dev, void *data, struct drm_file * return 0; err_unmap: - iommu_unmap(rocket_priv->domain->domain, + iommu_unmap(vm->domain, rkt_obj->mm.start, rkt_obj->size); err_remove_node: - mutex_lock(&rocket_priv->mm_lock); + mutex_lock(&vm->lock); drm_mm_remove_node(&rkt_obj->mm); - mutex_unlock(&rocket_priv->mm_lock); + mutex_unlock(&vm->lock); err: + rocket_vm_put(rkt_obj->vm); + rkt_obj->vm = NULL; drm_gem_shmem_object_free(gem_obj); return ret; diff --git a/drivers/accel/rocket/rocket_gem.h b/drivers/accel/rocket/rocket_gem.h index 24043033450941..e1fbbd8cf71901 100644 --- a/drivers/accel/rocket/rocket_gem.h +++ b/drivers/accel/rocket/rocket_gem.h @@ -9,9 +9,7 @@ struct rocket_gem_object { struct drm_gem_shmem_object base; - struct rocket_file_priv *driver_priv; - - struct rocket_iommu_domain *domain; + struct rocket_vm *vm; struct drm_mm_node mm; size_t size; u32 offset; diff --git a/drivers/accel/rocket/rocket_job.c b/drivers/accel/rocket/rocket_job.c index c3edb94355a397..454d465a39e371 100644 --- a/drivers/accel/rocket/rocket_job.c +++ b/drivers/accel/rocket/rocket_job.c @@ -201,12 +201,13 @@ static int rocket_acquire_object_fences(struct drm_gem_object **bos, static void rocket_attach_object_fences(struct drm_gem_object **bos, int bo_count, - struct dma_fence *fence) + struct dma_fence *fence, + enum dma_resv_usage usage) { int i; for (i = 0; i < bo_count; i++) - dma_resv_add_fence(bos[i]->resv, fence, DMA_RESV_USAGE_WRITE); + dma_resv_add_fence(bos[i]->resv, fence, usage); } static int rocket_job_push(struct rocket_job *job) @@ -248,7 +249,10 @@ static int rocket_job_push(struct rocket_job *job) drm_sched_entity_push_job(&job->base); } - rocket_attach_object_fences(job->out_bos, job->out_bo_count, job->inference_done_fence); + rocket_attach_object_fences(job->in_bos, job->in_bo_count, + job->inference_done_fence, DMA_RESV_USAGE_READ); + rocket_attach_object_fences(job->out_bos, job->out_bo_count, + job->inference_done_fence, DMA_RESV_USAGE_WRITE); err_unlock: drm_gem_unlock_reservations(bos, bo_count, &acquire_ctx); @@ -264,7 +268,7 @@ static void rocket_job_cleanup(struct kref *ref) refcount); unsigned int i; - rocket_iommu_domain_put(job->domain); + rocket_vm_put(job->vm); dma_fence_put(job->done_fence); dma_fence_put(job->inference_done_fence); @@ -345,7 +349,7 @@ static struct dma_fence *rocket_job_run(struct drm_sched_job *sched_job) if (ret < 0) goto err_put_fences; - ret = iommu_attach_group(job->domain->domain, core->iommu_group); + ret = iommu_attach_group(job->vm->domain, core->iommu_group); if (ret < 0) goto err_put_pm; @@ -369,39 +373,56 @@ static void rocket_job_handle_irq(struct rocket_core *core) { pm_runtime_mark_last_busy(core->dev); - rocket_pc_writel(core, OPERATION_ENABLE, 0x0); - rocket_pc_writel(core, INTERRUPT_CLEAR, 0x1ffff); + scoped_guard(mutex, &core->job_lock) { + /* + * Stopping the block belongs under the lock. hw_submit() writes + * OPERATION_ENABLE too, and outside the lock this zero can land + * after that one and stop a task that has only just started. + */ + rocket_pc_writel(core, OPERATION_ENABLE, 0x0); + rocket_pc_writel(core, INTERRUPT_CLEAR, 0x1ffff); - scoped_guard(mutex, &core->job_lock) if (core->in_flight_job) { if (core->in_flight_job->next_task_idx < core->in_flight_job->task_count) { rocket_job_hw_submit(core, core->in_flight_job); return; } - iommu_detach_group(NULL, iommu_group_get(core->dev)); + iommu_detach_group(NULL, core->iommu_group); dma_fence_signal(core->in_flight_job->done_fence); pm_runtime_put_autosuspend(core->dev); core->in_flight_job = NULL; } + } } static void rocket_reset(struct rocket_core *core, struct drm_sched_job *bad) { + bool put_job_ref; + if (!atomic_read(&core->reset.pending)) return; drm_sched_stop(&core->sched, bad); + scoped_guard(mutex, &core->job_lock) { + if (pm_runtime_get_if_active(core->dev) > 0) { + rocket_pc_writel(core, INTERRUPT_MASK, 0x0); + rocket_pc_writel(core, INTERRUPT_CLEAR, 0x1ffff); + pm_runtime_put_autosuspend(core->dev); + } + } + + synchronize_irq(core->irq); + /* * Remaining interrupts have been handled, but we might still have * stuck jobs. Let's make sure the PM counters stay balanced by - * manually calling pm_runtime_put_noidle(). + * dropping the job's reference once the core has been reset. */ scoped_guard(mutex, &core->job_lock) { - if (core->in_flight_job) - pm_runtime_put_noidle(core->dev); + put_job_ref = core->in_flight_job; iommu_detach_group(NULL, core->iommu_group); @@ -411,6 +432,9 @@ rocket_reset(struct rocket_core *core, struct drm_sched_job *bad) /* Proceed with reset now. */ rocket_core_reset(core); + if (put_job_ref) + pm_runtime_put_autosuspend(core->dev); + /* NPU has been reset, we can clear the reset pending bit. */ atomic_set(&core->reset.pending, 0); @@ -538,6 +562,9 @@ int rocket_job_open(struct rocket_file_priv *rocket_priv) unsigned int core; int ret; + if (!scheds) + return -ENOMEM; + for (core = 0; core < rdev->num_cores; core++) scheds[core] = &rdev->cores[core].sched; @@ -545,18 +572,20 @@ int rocket_job_open(struct rocket_file_priv *rocket_priv) DRM_SCHED_PRIORITY_NORMAL, scheds, rdev->num_cores, NULL); - if (WARN_ON(ret)) - return ret; + if (ret) + kfree(scheds); + else + rocket_priv->scheds = scheds; - return 0; + return ret; } void rocket_job_close(struct rocket_file_priv *rocket_priv) { struct drm_sched_entity *entity = &rocket_priv->sched_entity; - kfree(entity->sched_list); drm_sched_entity_destroy(entity); + kfree(rocket_priv->scheds); } int rocket_job_is_idle(struct rocket_core *core) @@ -586,7 +615,7 @@ static int rocket_ioctl_submit_job(struct drm_device *dev, struct drm_file *file kref_init(&rjob->refcount); rjob->rdev = rdev; - rjob->domain = rocket_iommu_domain_get(file_priv); + rjob->vm = rocket_vm_get(file_priv); ret = drm_sched_job_init(&rjob->base, &file_priv->sched_entity, diff --git a/drivers/accel/rocket/rocket_job.h b/drivers/accel/rocket/rocket_job.h index 4ae00feec3b939..9373c3d0273b4f 100644 --- a/drivers/accel/rocket/rocket_job.h +++ b/drivers/accel/rocket/rocket_job.h @@ -36,7 +36,7 @@ struct rocket_job { /* Fence to be signaled by IRQ handler when the job is complete. */ struct dma_fence *done_fence; - struct rocket_iommu_domain *domain; + struct rocket_vm *vm; struct kref refcount; }; diff --git a/drivers/acpi/cppc_acpi.c b/drivers/acpi/cppc_acpi.c index 05a547bbe93681..b4cf93dec18b5c 100644 --- a/drivers/acpi/cppc_acpi.c +++ b/drivers/acpi/cppc_acpi.c @@ -2081,6 +2081,15 @@ int acpi_cppc_processor_probe(struct acpi_processor *pr) cpc_apply_platform_quirks(gas_t, i - 2, platform_quirks); + /* EPP interfaces require the full 0-255 preference range. */ + if (i - 2 == ENERGY_PERF && gas_t->bit_width < 8 && + !IS_NULL_REG(gas_t)) { + pr_debug("CPU%d: EPP register width %u is not supported\n", + pr->id, gas_t->bit_width); + ret = -EOPNOTSUPP; + goto out_free; + } + /* * The PCC Subspace index is encoded inside * the CPC table entries. The same PCC index @@ -2940,9 +2949,9 @@ int cppc_get_perf_caps(int cpunum, struct cppc_perf_caps *perf_caps) if (!high || !low || !nom || !ref || !min_nonlinear || high > U32_MAX || low > U32_MAX || guaranteed > U32_MAX || nom > U32_MAX || ref > U32_MAX || min_nonlinear > U32_MAX || - high < nom || nom < min_nonlinear || min_nonlinear < low || + high < min_nonlinear || min_nonlinear < low || (CPC_SUPPORTED(guaranteed_reg) && - (guaranteed < low || guaranteed > nom))) { + (guaranteed < low || guaranteed > high))) { ret = -EFAULT; goto out_err; } diff --git a/drivers/acpi/device_pm.c b/drivers/acpi/device_pm.c index 76104f715efa11..d975700936e87f 100644 --- a/drivers/acpi/device_pm.c +++ b/drivers/acpi/device_pm.c @@ -365,14 +365,25 @@ int acpi_bus_init_power(struct acpi_device *device) * fails, ACPI power management will not be used for the device going * forward. */ + if (!acpi_device_is_present(device)) { + acpi_handle_debug(device->handle, + "Device not present, ACPI PM disabled\n"); + result = -ENXIO; + goto fail; + } + 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"); + goto fail; } + return 0; + +fail: + device->flags.power_manageable = 0; + device->power.state = ACPI_D_STATE_INVALID; return result; } diff --git a/drivers/acpi/glue.c b/drivers/acpi/glue.c index 0959f58cb77c65..4e8616d2e5c8dd 100644 --- a/drivers/acpi/glue.c +++ b/drivers/acpi/glue.c @@ -108,14 +108,10 @@ static bool acpi_dev_has_children(struct acpi_device *adev) static int find_child_checks(struct acpi_device *adev, bool check_children) { - unsigned long long sta; - acpi_status status; - if (check_children && !acpi_dev_has_children(adev)) return -ENODEV; - status = acpi_evaluate_integer(adev->handle, "_STA", NULL, &sta); - if (status == AE_NOT_FOUND) { + if (!acpi_has_method(adev->handle, METHOD_NAME__STA)) { /* * Special case: backlight device objects without _STA are * preferred to other objects with the same _ADR value, because @@ -127,7 +123,7 @@ static int find_child_checks(struct acpi_device *adev, bool check_children) return FIND_CHILD_MIN_SCORE; } - if (ACPI_FAILURE(status) || !(sta & ACPI_STA_DEVICE_ENABLED)) + if (!acpi_device_is_present(adev)) return -ENODEV; /* diff --git a/drivers/android/binder/error.rs b/drivers/android/binder/error.rs index 89077c5baeaf96..acf0aa09c555e5 100644 --- a/drivers/android/binder/error.rs +++ b/drivers/android/binder/error.rs @@ -114,7 +114,6 @@ impl fmt::Debug for BinderError { BR_DEAD_REPLY => f.pad("BR_DEAD_REPLY"), BR_FROZEN_REPLY => f.pad("BR_FROZEN_REPLY"), BR_TRANSACTION_PENDING_FROZEN => f.pad("BR_TRANSACTION_PENDING_FROZEN"), - BR_TRANSACTION_COMPLETE => f.pad("BR_TRANSACTION_COMPLETE"), _ => match self.source.as_ref() { Some(source) => source.fmt(f), None => self.reply.fmt(f), diff --git a/drivers/android/binder/thread.rs b/drivers/android/binder/thread.rs index f5965e838a962a..4ce6fc53320311 100644 --- a/drivers/android/binder/thread.rs +++ b/drivers/android/binder/thread.rs @@ -1332,20 +1332,16 @@ impl Thread { self.transaction_inner(&mut info) }; - // This runs when return work is passed to the caller. This is not - // always the same as the transaction failing, as reply errors are - // delivered to the remote process. + // This runs when a transaction fails with an error returned to the caller. if let Err(err) = ret { self.push_return_work(err.reply); - if err.reply != BR_TRANSACTION_COMPLETE { - info.reply = err.reply; - info.error_line = Some(err.line); - if let Some(source) = err.source { - info.errno = Some(source); - - self.inner.lock().extended_error = - ExtendedError::new(info.debug_id as u32, err.reply, source.to_errno()); - } + info.reply = err.reply; + info.error_line = Some(err.line); + if let Some(source) = err.source { + info.errno = Some(source); + + self.inner.lock().extended_error = + ExtendedError::new(info.debug_id as u32, err.reply, source.to_errno()); } } @@ -1450,7 +1446,7 @@ impl Thread { info.to_pid = orig.from.process.task.pid(); // We need to complete the transaction even if we cannot complete building the reply. - let out = (|| -> BinderResult<_> { + if let Err(err) = (|| -> BinderResult<_> { let completion = DTRWrap::arc_try_new(DeliverCode::new( BR_TRANSACTION_COMPLETE, self.process.task.pid(), @@ -1471,11 +1467,10 @@ impl Thread { } orig.from.deliver_reply(Ok(reply), &orig, None); Ok(()) - })() - .map_err(|mut err| { + })() { // At this point we only return `BR_TRANSACTION_COMPLETE` to the caller, and we must let // the sender know that the transaction has completed (with an error in this case). - + self.push_return_work(BR_TRANSACTION_COMPLETE); let param = err.source.as_ref().map_or(0, |e| e.to_errno()); let ee = ExtendedError::new(info.debug_id as u32, err.reply, param); orig.from @@ -1483,11 +1478,9 @@ impl Thread { info.reply = BR_FAILED_REPLY; info.errno = err.source; info.error_line = Some(err.line); - err.reply = BR_TRANSACTION_COMPLETE; - err - }); + } - out + Ok(()) } fn oneway_transaction_inner(self: &Arc, info: &mut TransactionInfo) -> BinderResult { diff --git a/drivers/ata/libata-core.c b/drivers/ata/libata-core.c index 5ff45a5cbfe4a7..d234c83e046374 100644 --- a/drivers/ata/libata-core.c +++ b/drivers/ata/libata-core.c @@ -4204,6 +4204,7 @@ static const struct ata_dev_quirk_value __ata_dev_max_sec_quirks[] = { { "LITEON EP1-*", NULL, 1024 }, { "DELLBOSS VD", "MV.R00-0", 8191 }, { "INTEL SSDSC2KG480G8", "XCV10120", 8191 }, + { "INTEL SSDSCKKB240G8", "XC311102", 8191 }, { }, }; @@ -4304,6 +4305,7 @@ static const struct ata_dev_quirks_entry __ata_dev_quirks[] = { ATA_QUIRK_FIRMWARE_WARN }, /* ADATA devices with LPM issues. */ + { "ADATA SU650", "XD0R3C0F", ATA_QUIRK_NOLPM }, { "ADATA SU680", NULL, ATA_QUIRK_NOLPM }, /* Seagate disks with LPM issues */ @@ -4474,6 +4476,8 @@ static const struct ata_dev_quirks_entry __ata_dev_quirks[] = { ATA_QUIRK_MAX_SEC }, { "INTEL*SSDSC2CT*", NULL, ATA_QUIRK_ZERO_AFTER_TRIM | ATA_QUIRK_NO_FUA }, + { "INTEL SSDSCKKB240G8", "XC311102", ATA_QUIRK_ZERO_AFTER_TRIM | + ATA_QUIRK_MAX_SEC }, { "INTEL*SSD*", NULL, ATA_QUIRK_ZERO_AFTER_TRIM }, { "SSD*INTEL*", NULL, ATA_QUIRK_ZERO_AFTER_TRIM }, { "Samsung*SSD*", NULL, ATA_QUIRK_ZERO_AFTER_TRIM }, diff --git a/drivers/ata/libata-scsi.c b/drivers/ata/libata-scsi.c index 87a57495d2e4bf..c08643571ce488 100644 --- a/drivers/ata/libata-scsi.c +++ b/drivers/ata/libata-scsi.c @@ -4812,7 +4812,7 @@ static unsigned int ata_scsi_security_inout_xlat(struct ata_queued_cmd *qc) return 1; } - if (cdb[4] & 7) { /* INC_512 */ + if (cdb[4] & 0x80) { /* INC_512 */ if (len > 0xffff) { ata_scsi_set_invalid_field(qc->dev, scmd, 6, 0); return 1; @@ -4991,6 +4991,9 @@ ata_scsi_remove_element_and_truncate_xlat(struct ata_queued_cmd *qc) return 1; } + if (req_capacity > 1) + req_capacity--; + id = get_unaligned_be32(&cdb[10]); tf->protocol = ATA_PROT_NODATA; diff --git a/drivers/base/regmap/regmap-i2c.c b/drivers/base/regmap/regmap-i2c.c index a4a259232980d1..7635eca2cbee84 100644 --- a/drivers/base/regmap/regmap-i2c.c +++ b/drivers/base/regmap/regmap-i2c.c @@ -13,6 +13,43 @@ #include "internal.h" +static void regmap_i2c_init_limits(void *context, + const struct regmap_config *config, + size_t *max_raw_read, + size_t *max_raw_write) +{ + struct device *dev = context; + struct i2c_client *i2c = to_i2c_client(dev); + const struct i2c_adapter_quirks *quirks = i2c->adapter->quirks; + size_t val_bytes = BITS_TO_BYTES(config->val_bits); + size_t max_read = *max_raw_read; + size_t max_write = *max_raw_write; + + if (!quirks) + return; + + if (quirks->max_read_len && + quirks->max_read_len >= val_bytes && + (max_read == 0 || max_read > quirks->max_read_len)) + max_read = quirks->max_read_len; + + if (quirks->max_write_len) { + size_t reg_reserve_size, max_payload; + + reg_reserve_size = (config->reg_bits + config->pad_bits) / + BITS_PER_BYTE; + if (quirks->max_write_len > reg_reserve_size) { + max_payload = quirks->max_write_len - reg_reserve_size; + if (max_payload >= val_bytes && + (max_write == 0 || max_write > max_payload)) + max_write = max_payload; + } + } + + *max_raw_read = max_read; + *max_raw_write = max_write; +} + static int regmap_smbus_byte_reg_read(void *context, unsigned int reg, unsigned int *val) { @@ -47,6 +84,7 @@ static int regmap_smbus_byte_reg_write(void *context, unsigned int reg, static const struct regmap_bus regmap_smbus_byte = { .reg_write = regmap_smbus_byte_reg_write, .reg_read = regmap_smbus_byte_reg_read, + .init_limits = regmap_i2c_init_limits, }; static int regmap_smbus_word_reg_read(void *context, unsigned int reg, @@ -83,6 +121,7 @@ static int regmap_smbus_word_reg_write(void *context, unsigned int reg, static const struct regmap_bus regmap_smbus_word = { .reg_write = regmap_smbus_word_reg_write, .reg_read = regmap_smbus_word_reg_read, + .init_limits = regmap_i2c_init_limits, }; static int regmap_smbus_word_read_swapped(void *context, unsigned int reg, @@ -119,6 +158,7 @@ static int regmap_smbus_word_write_swapped(void *context, unsigned int reg, static const struct regmap_bus regmap_smbus_word_swapped = { .reg_write = regmap_smbus_word_write_swapped, .reg_read = regmap_smbus_word_read_swapped, + .init_limits = regmap_i2c_init_limits, }; static int regmap_i2c_write(void *context, const void *data, size_t count) @@ -204,6 +244,7 @@ static const struct regmap_bus regmap_i2c = { .read = regmap_i2c_read, .reg_format_endian_default = REGMAP_ENDIAN_BIG, .val_format_endian_default = REGMAP_ENDIAN_BIG, + .init_limits = regmap_i2c_init_limits, }; static int regmap_i2c_smbus_i2c_write(void *context, const void *data, @@ -245,6 +286,7 @@ static const struct regmap_bus regmap_i2c_smbus_i2c_block = { .read = regmap_i2c_smbus_i2c_read, .max_raw_read = I2C_SMBUS_BLOCK_MAX - 1, .max_raw_write = I2C_SMBUS_BLOCK_MAX - 1, + .init_limits = regmap_i2c_init_limits, }; static int regmap_i2c_smbus_i2c_write_reg16(void *context, const void *data, @@ -302,6 +344,7 @@ static const struct regmap_bus regmap_i2c_smbus_i2c_block_reg16 = { .read = regmap_i2c_smbus_i2c_read_reg16, .max_raw_read = I2C_SMBUS_BLOCK_MAX - 2, .max_raw_write = I2C_SMBUS_BLOCK_MAX - 2, + .init_limits = regmap_i2c_init_limits, }; /* @@ -346,16 +389,13 @@ static const struct regmap_bus regmap_smbus_byte_word_reg16 = { .read = regmap_i2c_smbus_i2c_read_reg16, .max_raw_read = I2C_SMBUS_BLOCK_MAX - 2, .max_raw_write = 1, + .init_limits = regmap_i2c_init_limits, }; static const struct regmap_bus *regmap_get_i2c_bus(struct i2c_client *i2c, const struct regmap_config *config) { - const struct i2c_adapter_quirks *quirks; const struct regmap_bus *bus = NULL; - struct regmap_bus *ret_bus; - size_t val_bytes; - u16 max_read, max_write; if (i2c_check_functionality(i2c->adapter, I2C_FUNC_I2C)) bus = ®map_i2c; @@ -393,43 +433,6 @@ static const struct regmap_bus *regmap_get_i2c_bus(struct i2c_client *i2c, if (!bus) return ERR_PTR(-ENOTSUPP); - max_read = bus->max_raw_read; - max_write = bus->max_raw_write; - val_bytes = BITS_TO_BYTES(config->val_bits); - - quirks = i2c->adapter->quirks; - if (quirks) { - if (quirks->max_read_len && - quirks->max_read_len >= val_bytes && - (max_read == 0 || max_read > quirks->max_read_len)) - max_read = quirks->max_read_len; - - if (quirks->max_write_len) { - size_t reg_reserve_size, max_payload; - - reg_reserve_size = (config->reg_bits + config->pad_bits) / - BITS_PER_BYTE; - if (quirks->max_write_len > reg_reserve_size) { - max_payload = quirks->max_write_len - - reg_reserve_size; - if (max_payload >= val_bytes && - (max_write == 0 || max_write > max_payload)) - max_write = max_payload; - } - } - - if (max_read != bus->max_raw_read || - max_write != bus->max_raw_write) { - ret_bus = kmemdup(bus, sizeof(*bus), GFP_KERNEL); - if (!ret_bus) - return ERR_PTR(-ENOMEM); - ret_bus->free_on_exit = true; - ret_bus->max_raw_read = max_read; - ret_bus->max_raw_write = max_write; - bus = ret_bus; - } - } - return bus; } diff --git a/drivers/base/regmap/regmap-kunit.c b/drivers/base/regmap/regmap-kunit.c index c948219f46a39d..75c251132c89c8 100644 --- a/drivers/base/regmap/regmap-kunit.c +++ b/drivers/base/regmap/regmap-kunit.c @@ -2247,6 +2247,96 @@ static void raw_ranges(struct kunit *test) } } +#define TEST_INIT_LIMITS_REGS 16 +#define TEST_INIT_LIMITS_MAX_RAW 4 + +struct test_init_limits_data { + int num_reads; + size_t read_sizes[TEST_INIT_LIMITS_REGS]; +}; + +static void test_init_limits_bus_init_limits(void *context, + const struct regmap_config *config, + size_t *max_raw_read, + size_t *max_raw_write) +{ + *max_raw_read = TEST_INIT_LIMITS_MAX_RAW; + *max_raw_write = TEST_INIT_LIMITS_MAX_RAW; +} + +static int test_init_limits_bus_read(void *context, const void *reg_buf, + size_t reg_size, void *val_buf, + size_t val_size) +{ + struct test_init_limits_data *data = context; + + if (data->num_reads < ARRAY_SIZE(data->read_sizes)) + data->read_sizes[data->num_reads] = val_size; + data->num_reads++; + + memset(val_buf, 0, val_size); + + return 0; +} + +static int test_init_limits_bus_write(void *context, const void *data, + size_t count) +{ + return 0; +} + +static const struct regmap_bus test_init_limits_bus = { + .read = test_init_limits_bus_read, + .write = test_init_limits_bus_write, + .init_limits = test_init_limits_bus_init_limits, +}; + +static const struct regmap_config test_init_limits_config = { + .reg_bits = 8, + .val_bits = 8, + .max_register = TEST_INIT_LIMITS_REGS - 1, + .cache_type = REGCACHE_FLAT, + .num_reg_defaults_raw = TEST_INIT_LIMITS_REGS, +}; + +static void test_init_limits(struct kunit *test) +{ + struct regmap_test_priv *priv = test->priv; + struct test_init_limits_data *data; + struct regmap *map; + int i, ret; + + data = kunit_kzalloc(test, sizeof(*data), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, data); + + map = regmap_init(priv->dev, &test_init_limits_bus, data, + &test_init_limits_config); + KUNIT_ASSERT_FALSE(test, IS_ERR(map)); + if (IS_ERR(map)) + return; + + ret = kunit_add_action_or_reset(test, regmap_exit_action, map); + KUNIT_ASSERT_EQ(test, 0, ret); + if (ret) + return; + + KUNIT_EXPECT_EQ(test, (size_t)TEST_INIT_LIMITS_MAX_RAW, + regmap_get_raw_read_max(map)); + KUNIT_EXPECT_EQ(test, (size_t)TEST_INIT_LIMITS_MAX_RAW, + regmap_get_raw_write_max(map)); + + /* + * regcache_hw_init() reads raw defaults during map initialization, + * so the callback must already have set the limit which chunks the + * readback. + */ + KUNIT_ASSERT_EQ(test, TEST_INIT_LIMITS_REGS / TEST_INIT_LIMITS_MAX_RAW, + data->num_reads); + for (i = 0; i < data->num_reads; i++) + KUNIT_EXPECT_EQ(test, (size_t)TEST_INIT_LIMITS_MAX_RAW, + data->read_sizes[i]); +} + static struct kunit_case regmap_test_cases[] = { KUNIT_CASE_PARAM(basic_read_write, regcache_types_gen_params), KUNIT_CASE_PARAM(read_bypassed, real_cache_types_gen_params), @@ -2290,6 +2380,7 @@ static struct kunit_case regmap_test_cases[] = { KUNIT_CASE_PARAM(raw_noinc_write, raw_test_types_gen_params), KUNIT_CASE_PARAM(raw_sync, raw_test_cache_types_gen_params), KUNIT_CASE_PARAM(raw_ranges, raw_test_cache_types_gen_params), + KUNIT_CASE(test_init_limits), {} }; diff --git a/drivers/base/regmap/regmap-mmio.c b/drivers/base/regmap/regmap-mmio.c index 6adbc950877ca3..a7eeb9498cd212 100644 --- a/drivers/base/regmap/regmap-mmio.c +++ b/drivers/base/regmap/regmap-mmio.c @@ -559,13 +559,18 @@ struct regmap *__regmap_init_mmio_clk(struct device *dev, const char *clk_id, const char *lock_name) { struct regmap_mmio_context *ctx; + struct regmap *map; ctx = regmap_mmio_gen_context(dev, clk_id, regs, config); if (IS_ERR(ctx)) return ERR_CAST(ctx); - return __regmap_init(dev, ®map_mmio, ctx, config, - lock_key, lock_name); + map = __regmap_init(dev, ®map_mmio, ctx, config, + lock_key, lock_name); + if (IS_ERR(map)) + regmap_mmio_free_context(ctx); + + return map; } EXPORT_SYMBOL_GPL(__regmap_init_mmio_clk); @@ -577,13 +582,18 @@ struct regmap *__devm_regmap_init_mmio_clk(struct device *dev, const char *lock_name) { struct regmap_mmio_context *ctx; + struct regmap *map; ctx = regmap_mmio_gen_context(dev, clk_id, regs, config); if (IS_ERR(ctx)) return ERR_CAST(ctx); - return __devm_regmap_init(dev, ®map_mmio, ctx, config, - lock_key, lock_name); + map = __devm_regmap_init(dev, ®map_mmio, ctx, config, + lock_key, lock_name); + if (IS_ERR(map)) + regmap_mmio_free_context(ctx); + + return map; } EXPORT_SYMBOL_GPL(__devm_regmap_init_mmio_clk); diff --git a/drivers/base/regmap/regmap-spi.c b/drivers/base/regmap/regmap-spi.c index b9fec387997ebe..e095e0bba10de1 100644 --- a/drivers/base/regmap/regmap-spi.c +++ b/drivers/base/regmap/regmap-spi.c @@ -98,6 +98,28 @@ static int regmap_spi_read(void *context, return spi_write_then_read(spi, reg, reg_size, val, val_size); } +static void regmap_spi_init_limits(void *context, + const struct regmap_config *config, + size_t *max_raw_read, + size_t *max_raw_write) +{ + struct device *dev = context; + struct spi_device *spi = to_spi_device(dev); + size_t max_size = spi_max_transfer_size(spi); + size_t max_msg_size, reg_reserve_size; + + if (max_size == SIZE_MAX) + return; + + max_msg_size = spi_max_message_size(spi); + reg_reserve_size = (config->reg_bits + config->pad_bits) / BITS_PER_BYTE; + if (max_size + reg_reserve_size > max_msg_size) + max_size -= reg_reserve_size; + + *max_raw_read = max_size; + *max_raw_write = max_size; +} + static const struct regmap_bus regmap_spi = { .write = regmap_spi_write, .gather_write = regmap_spi_gather_write, @@ -107,46 +129,16 @@ static const struct regmap_bus regmap_spi = { .read_flag_mask = 0x80, .reg_format_endian_default = REGMAP_ENDIAN_BIG, .val_format_endian_default = REGMAP_ENDIAN_BIG, + .init_limits = regmap_spi_init_limits, }; -static const struct regmap_bus *regmap_get_spi_bus(struct spi_device *spi, - const struct regmap_config *config) -{ - size_t max_size = spi_max_transfer_size(spi); - size_t max_msg_size, reg_reserve_size; - struct regmap_bus *bus; - - if (max_size != SIZE_MAX) { - bus = kmemdup(®map_spi, sizeof(*bus), GFP_KERNEL); - if (!bus) - return ERR_PTR(-ENOMEM); - - max_msg_size = spi_max_message_size(spi); - reg_reserve_size = (config->reg_bits + config->pad_bits) / BITS_PER_BYTE; - if (max_size + reg_reserve_size > max_msg_size) - max_size -= reg_reserve_size; - - bus->free_on_exit = true; - bus->max_raw_read = max_size; - bus->max_raw_write = max_size; - - return bus; - } - - return ®map_spi; -} - struct regmap *__regmap_init_spi(struct spi_device *spi, const struct regmap_config *config, struct lock_class_key *lock_key, const char *lock_name) { - const struct regmap_bus *bus = regmap_get_spi_bus(spi, config); - - if (IS_ERR(bus)) - return ERR_CAST(bus); - - return __regmap_init(&spi->dev, bus, &spi->dev, config, lock_key, lock_name); + return __regmap_init(&spi->dev, ®map_spi, &spi->dev, config, + lock_key, lock_name); } EXPORT_SYMBOL_GPL(__regmap_init_spi); @@ -155,12 +147,8 @@ struct regmap *__devm_regmap_init_spi(struct spi_device *spi, struct lock_class_key *lock_key, const char *lock_name) { - const struct regmap_bus *bus = regmap_get_spi_bus(spi, config); - - if (IS_ERR(bus)) - return ERR_CAST(bus); - - return __devm_regmap_init(&spi->dev, bus, &spi->dev, config, lock_key, lock_name); + return __devm_regmap_init(&spi->dev, ®map_spi, &spi->dev, config, + lock_key, lock_name); } EXPORT_SYMBOL_GPL(__devm_regmap_init_spi); diff --git a/drivers/base/regmap/regmap.c b/drivers/base/regmap/regmap.c index 910f66bcff401e..b4e07f8d6e9134 100644 --- a/drivers/base/regmap/regmap.c +++ b/drivers/base/regmap/regmap.c @@ -1037,6 +1037,22 @@ static int regmap_init_format(struct regmap *map, return 0; } +static void regmap_init_release(struct regmap *map) +{ + if (!map) + return; + + regcache_exit(map); + regmap_range_exit(map); + kfree(map->work_buf); + if (map->hwlock) + hwspin_lock_free(map->hwlock); + kfree_const(map->name); + kfree(map); +} + +DEFINE_FREE(regmap_init_release, struct regmap *, regmap_init_release(_T)); + struct regmap *__regmap_init(struct device *dev, const struct regmap_bus *bus, void *bus_context, @@ -1044,30 +1060,25 @@ struct regmap *__regmap_init(struct device *dev, struct lock_class_key *lock_key, const char *lock_name) { - struct regmap *map; bool fast_io; int ret; - if (!config) { - ret = -EINVAL; - goto err; - } + if (!config) + return ERR_PTR(-EINVAL); - map = kzalloc_obj(*map); - if (map == NULL) { - ret = -ENOMEM; - goto err; - } + struct regmap *map __free(regmap_init_release) = kzalloc_obj(*map); + if (map == NULL) + return ERR_PTR(-ENOMEM); ret = regmap_set_name(map, config); if (ret) - goto err_map; + return ERR_PTR(ret); fast_io = (bus && bus->fast_io) || config->fast_io; ret = regmap_set_lock(map, config, fast_io, lock_key, lock_name); if (ret) - goto err_name; + return ERR_PTR(ret); /* * When we write in fast-paths with regmap_bulk_write() don't allocate @@ -1119,7 +1130,6 @@ struct regmap *__regmap_init(struct device *dev, map->writeable_noinc_reg = config->writeable_noinc_reg; map->readable_noinc_reg = config->readable_noinc_reg; map->reg_default_cb = config->reg_default_cb; - map->cache_type = config->cache_type; spin_lock_init(&map->async_lock); INIT_LIST_HEAD(&map->async_list); @@ -1148,7 +1158,7 @@ struct regmap *__regmap_init(struct device *dev, REGMAP_ENDIAN_NATIVE, REGMAP_ENDIAN_NATIVE); if (ret) - goto err_hwlock; + return ERR_PTR(ret); } else if (!bus) { map->reg_read = config->reg_read; map->reg_write = config->reg_write; @@ -1172,50 +1182,39 @@ struct regmap *__regmap_init(struct device *dev, regmap_get_reg_endian(bus, config), regmap_get_val_endian(dev, bus, config)); if (ret) - goto err_hwlock; + return ERR_PTR(ret); } - ret = regmap_init_ranges(map, config); if (ret) - goto err_range; + return ERR_PTR(ret); + + if (bus && bus->init_limits) + bus->init_limits(bus_context, config, + &map->max_raw_read, &map->max_raw_write); + map->cache_type = config->cache_type; ret = regcache_init(map, config); - if (ret != 0) - goto err_range; + if (ret) { + map->cache_type = REGCACHE_NONE; + return ERR_PTR(ret); + } if (dev) { ret = regmap_attach_dev(dev, map, config); if (ret != 0) - goto err_regcache; + return ERR_PTR(ret); } else { regmap_debugfs_init(map); } - return map; - -err_regcache: - regcache_exit(map); -err_range: - regmap_range_exit(map); - kfree(map->work_buf); -err_hwlock: - if (map->hwlock) - hwspin_lock_free(map->hwlock); -err_name: - kfree_const(map->name); -err_map: - kfree(map); -err: - if (bus && bus->free_on_exit) - kfree(bus); - return ERR_PTR(ret); + return_ptr(map); } EXPORT_SYMBOL_GPL(__regmap_init); -static void devm_regmap_release(void *regmap) +static void devm_regmap_release(struct device *dev, void *res) { - regmap_exit(regmap); + regmap_exit(*(struct regmap **)res); } struct regmap *__devm_regmap_init(struct device *dev, @@ -1225,17 +1224,21 @@ struct regmap *__devm_regmap_init(struct device *dev, struct lock_class_key *lock_key, const char *lock_name) { - struct regmap *regmap; - int ret; + struct regmap **ptr, *regmap; + + ptr = devres_alloc(devm_regmap_release, sizeof(*ptr), GFP_KERNEL); + if (!ptr) + return ERR_PTR(-ENOMEM); regmap = __regmap_init(dev, bus, bus_context, config, lock_key, lock_name); - if (IS_ERR(regmap)) + if (IS_ERR(regmap)) { + devres_free(ptr); return regmap; + } - ret = devm_add_action_or_reset(dev, devm_regmap_release, regmap); - if (ret) - return ERR_PTR(ret); + *ptr = regmap; + devres_add(dev, ptr); return regmap; } @@ -1521,8 +1524,6 @@ void regmap_exit(struct regmap *map) mutex_destroy(&map->mutex); kfree_const(map->name); kfree(map->patch); - if (map->bus && map->bus->free_on_exit) - kfree(map->bus); kfree(map); } EXPORT_SYMBOL_GPL(regmap_exit); diff --git a/drivers/block/nbd.c b/drivers/block/nbd.c index ffce519bf00879..b2b27f90a7ed4d 100644 --- a/drivers/block/nbd.c +++ b/drivers/block/nbd.c @@ -1356,6 +1356,7 @@ static int nbd_genl_reconnect_sock_cb(struct nbd_device *nbd, unsigned long arg) sock = nbd_get_socket(nbd, arg, &err); if (!sock) return err; + nbd_reclassify_socket(sock); args = kzalloc_obj(*args); if (!args) { diff --git a/drivers/block/ublk_drv.c b/drivers/block/ublk_drv.c index d415be37d5ede6..0699f22714fd42 100644 --- a/drivers/block/ublk_drv.c +++ b/drivers/block/ublk_drv.c @@ -835,23 +835,27 @@ static void __ublk_release_fcmd(struct ublk_queue *ubq) WRITE_ONCE(ubq->active_fcmd, NULL); } -/* - * Nothing can move on, so clear ->active_fcmd, and the caller should stop - * dispatching - */ -static void ublk_batch_deinit_fetch_buf(struct ublk_queue *ubq, - const struct ublk_batch_io_data *data, - struct ublk_batch_fetch_cmd *fcmd, - int res) +static struct ublk_batch_fetch_cmd *__ublk_acquire_fcmd(struct ublk_queue *ubq); + +/* Remove the failed fetch and claim the next one before dropping its reference. */ +static struct ublk_batch_fetch_cmd * +ublk_batch_deinit_fetch_buf(struct ublk_queue *ubq, + const struct ublk_batch_io_data *data, + struct ublk_batch_fetch_cmd *fcmd, + int res) { + struct ublk_batch_fetch_cmd *next_fcmd; + spin_lock(&ubq->evts_lock); list_del_init(&fcmd->node); WARN_ON_ONCE(fcmd != ubq->active_fcmd); __ublk_release_fcmd(ubq); + next_fcmd = __ublk_acquire_fcmd(ubq); spin_unlock(&ubq->evts_lock); io_uring_cmd_done(fcmd->cmd, res, data->issue_flags); ublk_batch_free_fcmd(fcmd); + return next_fcmd; } static int ublk_batch_fetch_post_cqe(struct ublk_batch_fetch_cmd *fcmd, @@ -1012,10 +1016,14 @@ static int ublk_validate_params(const struct ublk_device *ub) if (ub->params.types & UBLK_PARAM_TYPE_DEVT) return -EINVAL; - if (ub->params.types & UBLK_PARAM_TYPE_ZONED) - return ublk_dev_param_zoned_validate(ub); - else if (ublk_dev_is_zoned(ub)) + if (ub->params.types & UBLK_PARAM_TYPE_ZONED) { + int ret = ublk_dev_param_zoned_validate(ub); + + if (ret) + return ret; + } else if (ublk_dev_is_zoned(ub)) { return -EINVAL; + } if (ub->params.types & UBLK_PARAM_TYPE_DMA_ALIGN) { const struct ublk_param_dma_align *p = &ub->params.dma; @@ -2041,7 +2049,10 @@ ublk_batch_dispatch(struct ublk_queue *ubq, } if (ret < 0) { - ublk_batch_deinit_fetch_buf(ubq, data, fcmd, ret); + new_fcmd = ublk_batch_deinit_fetch_buf(ubq, data, fcmd, ret); + if (new_fcmd) + io_uring_cmd_complete_in_task(new_fcmd->cmd, + ublk_batch_tw_cb); return; } diff --git a/drivers/bluetooth/btintel.c b/drivers/bluetooth/btintel.c index 929018428c1924..4cc5273fb17540 100644 --- a/drivers/bluetooth/btintel.c +++ b/drivers/bluetooth/btintel.c @@ -1511,11 +1511,8 @@ static int btintel_read_debug_features(struct hci_dev *hdev, */ skb = __hci_cmd_sync(hdev, 0xfca6, sizeof(page_no), &page_no, HCI_INIT_TIMEOUT); - if (IS_ERR(skb)) { - bt_dev_err(hdev, "Reading supported features failed (%ld)", - PTR_ERR(skb)); + if (IS_ERR(skb)) return PTR_ERR(skb); - } if (skb->len != (sizeof(features->page1) + 3)) { bt_dev_err(hdev, "Supported features event size mismatch"); @@ -1632,8 +1629,10 @@ int btintel_set_quality_report(struct hci_dev *hdev, bool enable) * supported, need to load the additional DDC config to enable. */ err = btintel_read_debug_features(hdev, &features); - if (err) + if (err) { + bt_dev_err(hdev, "Reading supported features failed (%d)", err); return err; + } /* Set or reset the debug features. */ if (enable) @@ -1684,7 +1683,7 @@ static int btintel_register_devcoredump_support(struct hci_dev *hdev) err = btintel_read_debug_features(hdev, &features); if (err) { - bt_dev_info(hdev, "Error reading debug features"); + bt_dev_dbg(hdev, "Reading supported features failed (%d)", err); return err; } diff --git a/drivers/bluetooth/btintel_pcie.c b/drivers/bluetooth/btintel_pcie.c index dd439e9b653855..3a3f14ea2a8ed4 100644 --- a/drivers/bluetooth/btintel_pcie.c +++ b/drivers/bluetooth/btintel_pcie.c @@ -732,31 +732,18 @@ static int btintel_pcie_reset_bt(struct btintel_pcie_data *data) return reg == 0 ? 0 : -ENODEV; } -static void btintel_pcie_mac_init(struct btintel_pcie_data *data) -{ - u32 reg; - - /* Set MAC_INIT bit to start primary bootloader */ - reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG); - reg &= ~(BTINTEL_PCIE_CSR_FUNC_CTRL_FUNC_INIT | - BTINTEL_PCIE_CSR_FUNC_CTRL_BUS_MASTER_DISCON | - BTINTEL_PCIE_CSR_FUNC_CTRL_SW_RESET); - reg |= (BTINTEL_PCIE_CSR_FUNC_CTRL_FUNC_ENA | - BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_INIT); - btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG, reg); -} - static int btintel_pcie_get_mac_access(struct btintel_pcie_data *data) { - u32 reg; + u32 reg, val; int retry = 15; + const u32 req = BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_INIT | + BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_ACCESS_REQ; reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG); - if (!(reg & BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_ACCESS_REQ)) { - reg |= BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_ACCESS_REQ; - btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG, reg); - } + val = reg | req; + if (val != reg) + btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG, val); do { reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG); @@ -1659,8 +1646,6 @@ static int btintel_parse_mbox_tlv(struct btintel_pcie_data *data) if (!buffer) return -ENOMEM; - btintel_pcie_mac_init(data); - err = btintel_pcie_read_device_mem(data, buffer, tbl_addr, buffer_len); if (err) @@ -2325,8 +2310,6 @@ static void btintel_pcie_read_hwexp(struct btintel_pcie_data *data) if (!buf) goto exit_on_error; - btintel_pcie_mac_init(data); - err = btintel_pcie_read_device_mem(data, buf, addr, len); if (err) goto exit_on_error; @@ -2414,8 +2397,6 @@ static int btintel_pcie_dump_fwtrigger_event(struct btintel_pcie_data *data) if (!buf) return -ENOMEM; - btintel_pcie_mac_init(data); - err = btintel_pcie_read_device_mem(data, buf, data->debug_evt_addr, len); if (err) diff --git a/drivers/bluetooth/btintel_pcie.h b/drivers/bluetooth/btintel_pcie.h index 3030b4e8b75039..5f315ebb4123cd 100644 --- a/drivers/bluetooth/btintel_pcie.h +++ b/drivers/bluetooth/btintel_pcie.h @@ -72,7 +72,7 @@ #define BTINTEL_PCIE_DBGC_CUR_DBGBUFF_STATUS (BTINTEL_PCIE_DBGC_BASE_ADDR + 0x1C) #define BTINTEL_PCIE_DBGC_DBGBUFF_WRAP_ARND (BTINTEL_PCIE_DBGC_BASE_ADDR + 0x2C) -#define BTINTEL_PCIE_DBGC_BASE_ADDR_SCP (0xf0d5d500) +#define BTINTEL_PCIE_DBGC_BASE_ADDR_SCP (0xf0d5d400) #define BTINTEL_PCIE_DBGC_CUR_DBGBUFF_STATUS_SCP (BTINTEL_PCIE_DBGC_BASE_ADDR_SCP + 0x1C) #define BTINTEL_PCIE_DBGC_DBGBUFF_WRAP_ARND_SCP (BTINTEL_PCIE_DBGC_BASE_ADDR_SCP + 0x2C) #define BTINTEL_PCIE_DBGC_ALLOCATION_OFFSET 0x100 diff --git a/drivers/bluetooth/btqca.c b/drivers/bluetooth/btqca.c index 60735b70d89ad8..9f54e33e4250fb 100644 --- a/drivers/bluetooth/btqca.c +++ b/drivers/bluetooth/btqca.c @@ -983,6 +983,7 @@ int qca_uart_setup(struct hci_dev *hdev, uint8_t baudrate, switch (soc_type) { case QCA_WCN3991: case QCA_WCN6750: + case QCA_QCA2066: case QCA_WCN6855: case QCA_WCN7850: /* get fw build info */ diff --git a/drivers/bluetooth/btrtl.c b/drivers/bluetooth/btrtl.c index d29813331603ba..35a2c9d3380c50 100644 --- a/drivers/bluetooth/btrtl.c +++ b/drivers/bluetooth/btrtl.c @@ -1073,7 +1073,6 @@ struct btrtl_device_info *btrtl_initialize(struct hci_dev *hdev, u16 hci_rev, lmp_subver; u8 hci_ver, lmp_ver, chip_type = 0; int ret; - int rc; u8 key_id; u8 reg_val[2]; @@ -1144,8 +1143,10 @@ struct btrtl_device_info *btrtl_initialize(struct hci_dev *hdev, if (btrtl_dev->drop_fw) { skb = bt_skb_alloc(sizeof(*cmd), GFP_KERNEL); - if (!skb) + if (!skb) { + ret = -ENOMEM; goto err_free; + } cmd = skb_put(skb, HCI_COMMAND_HDR_SIZE); cmd->opcode = cpu_to_le16(0xfc66); @@ -1185,8 +1186,8 @@ struct btrtl_device_info *btrtl_initialize(struct hci_dev *hdev, goto err_free; } - rc = btrtl_vendor_read_reg16(hdev, RTL_SEC_PROJ, reg_val); - if (rc < 0) + ret = btrtl_vendor_read_reg16(hdev, RTL_SEC_PROJ, reg_val); + if (ret < 0) goto err_free; key_id = reg_val[0]; diff --git a/drivers/bluetooth/hci_mrvl.c b/drivers/bluetooth/hci_mrvl.c index 57e2d80827dffa..3e542956be1ae5 100644 --- a/drivers/bluetooth/hci_mrvl.c +++ b/drivers/bluetooth/hci_mrvl.c @@ -57,7 +57,6 @@ struct hci_mrvl_pkt { static int mrvl_open(struct hci_uart *hu) { struct mrvl_data *mrvl; - int ret; BT_DBG("hu %p", hu); @@ -75,17 +74,7 @@ static int mrvl_open(struct hci_uart *hu) hu->priv = mrvl; - if (hu->serdev) { - ret = serdev_device_open(hu->serdev); - if (ret) - goto err; - } - return 0; -err: - kfree(mrvl); - - return ret; } static int mrvl_close(struct hci_uart *hu) @@ -94,9 +83,6 @@ static int mrvl_close(struct hci_uart *hu) BT_DBG("hu %p", hu); - if (hu->serdev) - serdev_device_close(hu->serdev); - skb_queue_purge(&mrvl->txq); skb_queue_purge(&mrvl->rawq); kfree_skb(mrvl->rx_skb); diff --git a/drivers/bluetooth/hci_qca.c b/drivers/bluetooth/hci_qca.c index 4cebd0a9998da9..158f294c18902a 100644 --- a/drivers/bluetooth/hci_qca.c +++ b/drivers/bluetooth/hci_qca.c @@ -1132,6 +1132,7 @@ static void qca_controller_memdump(struct work_struct *work) if (!test_bit(QCA_MEMDUMP_COLLECTION, &qca->flags)) { bt_dev_err(hu->hdev, "QCA: Discarding other packets"); kfree(qca_memdump); + qca->qca_memdump = NULL; kfree_skb(skb); mutex_unlock(&qca->hci_memdump_lock); return; @@ -1386,6 +1387,7 @@ static int qca_set_baudrate(struct hci_dev *hdev, uint8_t baudrate) case QCA_WCN3991: case QCA_WCN3998: case QCA_WCN6750: + case QCA_QCA2066: case QCA_WCN6855: case QCA_WCN7850: usleep_range(1000, 10000); @@ -1473,6 +1475,7 @@ static int qca_check_speeds(struct hci_uart *hu) case QCA_WCN3991: case QCA_WCN3998: case QCA_WCN6750: + case QCA_QCA2066: case QCA_WCN6855: case QCA_WCN7850: if (!qca_get_speed(hu, QCA_INIT_SPEED) && @@ -1516,6 +1519,7 @@ static int qca_set_speed(struct hci_uart *hu, enum qca_speed_type speed_type) case QCA_WCN3991: case QCA_WCN3998: case QCA_WCN6750: + case QCA_QCA2066: case QCA_WCN6855: case QCA_WCN7850: hci_uart_set_flow_control(hu, true); @@ -1551,6 +1555,7 @@ static int qca_set_speed(struct hci_uart *hu, enum qca_speed_type speed_type) case QCA_WCN3991: case QCA_WCN3998: case QCA_WCN6750: + case QCA_QCA2066: case QCA_WCN6855: case QCA_WCN7850: hci_uart_set_flow_control(hu, false); @@ -1750,6 +1755,27 @@ static bool qca_wakeup(struct hci_dev *hdev) return wakeup; } +static void qca_port_close(struct hci_uart *hu) +{ + /* HCI_UART_PROTO_READY tracks whether the port is open, so a port + * left closed by a failed qca_port_open() is not closed again by + * hci_uart_close() or hci_uart_unregister_device(). + */ + if (test_and_clear_bit(HCI_UART_PROTO_READY, &hu->flags)) + serdev_device_close(hu->serdev); +} + +static int qca_port_open(struct hci_uart *hu) +{ + int ret; + + ret = serdev_device_open(hu->serdev); + if (!ret) + set_bit(HCI_UART_PROTO_READY, &hu->flags); + + return ret; +} + static int qca_port_reopen(struct hci_uart *hu) { int ret; @@ -1759,8 +1785,8 @@ static int qca_port_reopen(struct hci_uart *hu) * Without this, we will have RTS and CTS synchronization * issues. */ - serdev_device_close(hu->serdev); - ret = serdev_device_open(hu->serdev); + qca_port_close(hu); + ret = qca_port_open(hu); if (ret) { bt_dev_err(hu->hdev, "failed to open port"); return ret; @@ -1784,12 +1810,12 @@ static int qca_regulator_init(struct hci_uart *hu) qcadev = serdev_device_get_drvdata(hu->serdev); if (!qcadev->bt_power->vregs_on) { - serdev_device_close(hu->serdev); + qca_port_close(hu); ret = qca_regulator_enable(qcadev); if (ret) return ret; - ret = serdev_device_open(hu->serdev); + ret = qca_port_open(hu); if (ret) { bt_dev_err(hu->hdev, "failed to open port"); return ret; @@ -1867,6 +1893,7 @@ static int qca_power_on(struct hci_dev *hdev) case QCA_WCN3991: case QCA_WCN3998: case QCA_WCN6750: + case QCA_QCA2066: case QCA_WCN6855: case QCA_WCN7850: ret = qca_regulator_init(hu); @@ -1989,6 +2016,7 @@ static int qca_setup(struct hci_uart *hu) case QCA_WCN3991: case QCA_WCN3998: case QCA_WCN6750: + case QCA_QCA2066: case QCA_WCN6855: case QCA_WCN7850: if (qcadev && qcadev->bdaddr_property_broken) @@ -2022,6 +2050,7 @@ static int qca_setup(struct hci_uart *hu) case QCA_WCN3991: case QCA_WCN3998: case QCA_WCN6750: + case QCA_QCA2066: case QCA_WCN6855: case QCA_WCN7850: break; @@ -2065,8 +2094,8 @@ static int qca_setup(struct hci_uart *hu) if (retries < MAX_INIT_RETRIES) { bt_dev_warn(hdev, "Retry BT power ON:%d", retries); if (hu->serdev) { - serdev_device_close(hu->serdev); - ret = serdev_device_open(hu->serdev); + qca_port_close(hu); + ret = qca_port_open(hu); if (ret) { bt_dev_err(hdev, "failed to open port"); return ret; @@ -2284,6 +2313,7 @@ static void qca_power_off(struct hci_uart *hu) break; case QCA_WCN6750: + case QCA_QCA2066: case QCA_WCN6855: gpiod_set_value_cansleep(qcadev->bt_en, 0); msleep(100); @@ -2438,6 +2468,7 @@ static int qca_serdev_probe(struct serdev_device *serdev) case QCA_WCN3991: case QCA_WCN3998: case QCA_WCN6750: + case QCA_QCA2066: case QCA_WCN6855: case QCA_WCN7850: qcadev->bt_power = devm_kzalloc_obj(&serdev->dev, @@ -2456,6 +2487,7 @@ static int qca_serdev_probe(struct serdev_device *serdev) case QCA_WCN3991: case QCA_WCN3998: case QCA_WCN6750: + case QCA_QCA2066: case QCA_WCN6855: case QCA_WCN7850: if (!device_property_present(&serdev->dev, "enable-gpios")) { @@ -2499,6 +2531,7 @@ static int qca_serdev_probe(struct serdev_device *serdev) if (!qcadev->bt_en && (data->soc_type == QCA_WCN6750 || + data->soc_type == QCA_QCA2066 || data->soc_type == QCA_WCN6855 || data->soc_type == QCA_WCN7850)) power_ctrl_enabled = false; @@ -2507,6 +2540,7 @@ static int qca_serdev_probe(struct serdev_device *serdev) GPIOD_IN); if (IS_ERR(qcadev->sw_ctrl) && (data->soc_type == QCA_WCN6750 || + data->soc_type == QCA_QCA2066 || data->soc_type == QCA_WCN6855 || data->soc_type == QCA_WCN7850)) { dev_err(&serdev->dev, "failed to acquire SW_CTRL gpio\n"); @@ -2591,6 +2625,7 @@ static void qca_serdev_remove(struct serdev_device *serdev) case QCA_WCN3991: case QCA_WCN3998: case QCA_WCN6750: + case QCA_QCA2066: case QCA_WCN6855: case QCA_WCN7850: if (power->vregs_on) diff --git a/drivers/bluetooth/hci_serdev.c b/drivers/bluetooth/hci_serdev.c index 48ba017e219bc3..194f11251cc5e5 100644 --- a/drivers/bluetooth/hci_serdev.c +++ b/drivers/bluetooth/hci_serdev.c @@ -97,15 +97,26 @@ static int hci_uart_flush(struct hci_dev *hdev) BT_DBG("hdev %p serdev %p", hdev, hu->serdev); + /* Stop write_work and hold SENDING so wakeups only set TX_WAKEUP. */ + disable_work_sync(&hu->write_work); + set_bit(HCI_UART_SENDING, &hu->tx_state); + if (hu->tx_skb) { kfree_skb(hu->tx_skb); hu->tx_skb = NULL; } - /* Flush any pending characters in the driver and discipline. */ - serdev_device_write_flush(hu->serdev); + if (test_bit(HCI_UART_PROTO_READY, &hu->flags)) { + /* Flush any pending characters in the driver and discipline. */ + serdev_device_write_flush(hu->serdev); - if (test_bit(HCI_UART_PROTO_READY, &hu->flags)) hu->proto->flush(hu); + } + + /* Resume TX and replay a wakeup recorded while it was stopped. */ + enable_work(&hu->write_work); + clear_bit(HCI_UART_SENDING, &hu->tx_state); + if (test_bit(HCI_UART_TX_WAKEUP, &hu->tx_state)) + hci_uart_tx_wakeup(hu); return 0; } diff --git a/drivers/bluetooth/hci_vhci.c b/drivers/bluetooth/hci_vhci.c index 8f7db0102b25fa..7fec02705e58bf 100644 --- a/drivers/bluetooth/hci_vhci.c +++ b/drivers/bluetooth/hci_vhci.c @@ -524,7 +524,9 @@ static inline ssize_t vhci_get_user(struct vhci_data *data, case HCI_ACLDATA_PKT: case HCI_SCODATA_PKT: case HCI_ISODATA_PKT: + mutex_lock(&data->open_mutex); if (!data->hdev) { + mutex_unlock(&data->open_mutex); kfree_skb(skb); return -ENODEV; } @@ -532,6 +534,7 @@ static inline ssize_t vhci_get_user(struct vhci_data *data, hci_skb_pkt_type(skb) = pkt_type; ret = hci_recv_frame(data->hdev, skb); + mutex_unlock(&data->open_mutex); break; case HCI_VENDOR_PKT: @@ -701,6 +704,8 @@ static int vhci_release(struct inode *inode, struct file *file) if (hdev) { if (!IS_ERR_OR_NULL(hdev->debugfs)) vhci_debugfs_remove(hdev); + /* Drain work queued by the last force_suspend writers. */ + flush_work(&data->suspend_work); hci_unregister_dev(hdev); hci_free_dev(hdev); } diff --git a/drivers/comedi/comedi_fops.c b/drivers/comedi/comedi_fops.c index 9a65dc5d62a475..6d71ceeff6fc49 100644 --- a/drivers/comedi/comedi_fops.c +++ b/drivers/comedi/comedi_fops.c @@ -3494,7 +3494,7 @@ void _comedi_event(struct comedi_device *dev, struct comedi_subdevice *s) void comedi_event(struct comedi_device *dev, struct comedi_subdevice *s) { if (comedi_get_is_subdevice_running(s)) { - comedi_event(dev, s); + _comedi_event(dev, s); comedi_put_is_subdevice_running(s); } } diff --git a/drivers/comedi/drivers/addi_apci_1500.c b/drivers/comedi/drivers/addi_apci_1500.c index a203e27888e2f6..3d65aef565b318 100644 --- a/drivers/comedi/drivers/addi_apci_1500.c +++ b/drivers/comedi/drivers/addi_apci_1500.c @@ -696,7 +696,7 @@ static int apci1500_timer_insn_config(struct comedi_device *dev, return -EINVAL; val = z8536_read(dev, Z8536_CT_MODE_REG(chan)); - val &= Z8536_CT_MODE_EGE; + val &= ~Z8536_CT_MODE_EGE; if (data[1] == 1) val |= Z8536_CT_MODE_EGE; else if (data[1] > 1) diff --git a/drivers/comedi/drivers/comedi_bond.c b/drivers/comedi/drivers/comedi_bond.c index a10cfbd04c7286..3764ece90f826d 100644 --- a/drivers/comedi/drivers/comedi_bond.c +++ b/drivers/comedi/drivers/comedi_bond.c @@ -184,7 +184,9 @@ static int do_dev_config(struct comedi_device *dev, struct comedi_devconfig *it) char file[sizeof("/dev/comediXXXXXX")]; int minor = it->options[i]; struct comedi_device *d; - int sdev = -1, nchans; + int sdev = -1; + int nchans; + int nope = 1; struct bonded_device *bdev; struct bonded_device **devs; @@ -223,11 +225,14 @@ static int do_dev_config(struct comedi_device *dev, struct comedi_devconfig *it) dev_err(dev->class_dev, "comedi_get_n_channels() returned %d on minor %u subdev %d!\n", nchans, minor, sdev); - return -EINVAL; + nope = -EINVAL; + break; } bdev = kmalloc_obj(*bdev); - if (!bdev) - return -ENOMEM; + if (!bdev) { + nope = -ENOMEM; + break; + } bdev->dev = d; bdev->minor = minor; @@ -248,14 +253,23 @@ static int do_dev_config(struct comedi_device *dev, struct comedi_devconfig *it) dev_err(dev->class_dev, "Could not allocate memory. Out of memory?\n"); kfree(bdev); - return -ENOMEM; + nope = -ENOMEM; + break; } devpriv->devs = devs; devpriv->devs[devpriv->ndevs++] = bdev; + nope = 0; /* keeps the device open */ /* Append dev:subdev to devpriv->name */ seq_buf_printf(&s, "%u:%u ", bdev->minor, bdev->subdev); } + + if (nope) { + /* Opened device cannot be used, so close it. */ + comedi_close_from(d, dev->minor); + if (nope < 0) + return nope; + } } if (!devpriv->nchans) { diff --git a/drivers/comedi/drivers/ni_660x.c b/drivers/comedi/drivers/ni_660x.c index 5508cdb1b0bacd..9238475dda07d2 100644 --- a/drivers/comedi/drivers/ni_660x.c +++ b/drivers/comedi/drivers/ni_660x.c @@ -459,7 +459,8 @@ static int ni_660x_input_poll(struct comedi_device *dev, /* lock to avoid race with comedi_poll */ spin_lock_irqsave(&devpriv->interrupt_lock, flags); - mite_sync_dma(counter->mite_chan, s); + if (counter->mite_chan) + mite_sync_dma(counter->mite_chan, s); spin_unlock_irqrestore(&devpriv->interrupt_lock, flags); return comedi_buf_read_n_available(s); } diff --git a/drivers/comedi/drivers/ni_tio.c b/drivers/comedi/drivers/ni_tio.c index c3a909abcfa71b..b7ab70f34275e8 100644 --- a/drivers/comedi/drivers/ni_tio.c +++ b/drivers/comedi/drivers/ni_tio.c @@ -800,7 +800,7 @@ static int ni_tio_set_clock_src(struct ni_gpct *counter, GI_PRESCALE_X2(counter_dev->variant) | GI_PRESCALE_X8(counter_dev->variant), bits); } - counter->clock_period_ps = period_ns * 1000; + counter->clock_period_ps = (u64)period_ns * 1000; ni_tio_set_sync_mode(counter); return 0; } diff --git a/drivers/comedi/drivers/vmk80xx.c b/drivers/comedi/drivers/vmk80xx.c index 84dce5184a77ae..ddb12b48c8a493 100644 --- a/drivers/comedi/drivers/vmk80xx.c +++ b/drivers/comedi/drivers/vmk80xx.c @@ -151,7 +151,7 @@ struct vmk80xx_private { enum vmk80xx_model model; }; -static void vmk80xx_do_bulk_msg(struct comedi_device *dev) +static int vmk80xx_do_bulk_msg(struct comedi_device *dev) { struct vmk80xx_private *devpriv = dev->private; struct usb_device *usb = comedi_to_usb_dev(dev); @@ -161,6 +161,7 @@ static void vmk80xx_do_bulk_msg(struct comedi_device *dev) unsigned int rx_pipe; size_t tx_size; size_t rx_size; + int ret; tx_addr = devpriv->ep_tx->bEndpointAddress; rx_addr = devpriv->ep_rx->bEndpointAddress; @@ -169,11 +170,13 @@ static void vmk80xx_do_bulk_msg(struct comedi_device *dev) tx_size = usb_endpoint_maxp(devpriv->ep_tx); rx_size = usb_endpoint_maxp(devpriv->ep_rx); - usb_bulk_msg(usb, tx_pipe, devpriv->usb_tx_buf, tx_size, NULL, - PACKET_TIMEOUT); + ret = usb_bulk_msg(usb, tx_pipe, devpriv->usb_tx_buf, tx_size, NULL, + PACKET_TIMEOUT); + if (ret) + return ret; - usb_bulk_msg(usb, rx_pipe, devpriv->usb_rx_buf, rx_size, NULL, - PACKET_TIMEOUT); + return usb_bulk_msg(usb, rx_pipe, devpriv->usb_rx_buf, rx_size, NULL, + PACKET_TIMEOUT); } static int vmk80xx_read_packet(struct comedi_device *dev) @@ -183,10 +186,8 @@ static int vmk80xx_read_packet(struct comedi_device *dev) struct usb_endpoint_descriptor *ep; unsigned int pipe; - if (devpriv->model == VMK8061_MODEL) { - vmk80xx_do_bulk_msg(dev); - return 0; - } + if (devpriv->model == VMK8061_MODEL) + return vmk80xx_do_bulk_msg(dev); ep = devpriv->ep_rx; pipe = usb_rcvintpipe(usb, ep->bEndpointAddress); @@ -204,10 +205,8 @@ static int vmk80xx_write_packet(struct comedi_device *dev, int cmd) devpriv->usb_tx_buf[0] = cmd; - if (devpriv->model == VMK8061_MODEL) { - vmk80xx_do_bulk_msg(dev); - return 0; - } + if (devpriv->model == VMK8061_MODEL) + return vmk80xx_do_bulk_msg(dev); ep = devpriv->ep_tx; pipe = usb_sndintpipe(usb, ep->bEndpointAddress); diff --git a/drivers/cpufreq/cppc_cpufreq.c b/drivers/cpufreq/cppc_cpufreq.c index 957fa7775260b5..b2af24ae500864 100644 --- a/drivers/cpufreq/cppc_cpufreq.c +++ b/drivers/cpufreq/cppc_cpufreq.c @@ -714,7 +714,17 @@ static int cppc_cpufreq_cpu_init(struct cpufreq_policy *policy) pr_debug("Unsupported CPU co-ord type: %d\n", policy->shared_type); ret = -EFAULT; - goto out; + goto out_put; + } + + /* + * Enable CPPC. The Enable register is optional - some platforms + * may not support it. + */ + ret = cppc_set_enable(cpu, true); + if (ret && ret != -EOPNOTSUPP) { + pr_err("Failed to enable CPPC for CPU%u (%d)\n", cpu, ret); + goto out_put; } policy->fast_switch_possible = cppc_allow_fast_switch(policy->cpus); @@ -742,6 +752,8 @@ static int cppc_cpufreq_cpu_init(struct cpufreq_policy *policy) return 0; out: + cppc_set_enable(cpu, false); +out_put: cppc_cpufreq_put_cpu_data(policy); return ret; } diff --git a/drivers/cpufreq/cpufreq.c b/drivers/cpufreq/cpufreq.c index 24319b214d7ba9..4332cb1140701d 100644 --- a/drivers/cpufreq/cpufreq.c +++ b/drivers/cpufreq/cpufreq.c @@ -2452,6 +2452,14 @@ int cpufreq_driver_target(struct cpufreq_policy *policy, { guard(cpufreq_policy_write)(policy); + /* + * The last CPU in the policy may have gone offline after the caller + * obtained it, in which case the policy is inactive and must not be + * used for changing the frequency. + */ + if (unlikely(policy_is_inactive(policy))) + return -EBUSY; + return __cpufreq_driver_target(policy, target_freq, relation); } EXPORT_SYMBOL_GPL(cpufreq_driver_target); diff --git a/drivers/cpufreq/intel_pstate.c b/drivers/cpufreq/intel_pstate.c index c78dcd681511cc..05c0ba06e1e311 100644 --- a/drivers/cpufreq/intel_pstate.c +++ b/drivers/cpufreq/intel_pstate.c @@ -1351,13 +1351,14 @@ static void intel_pstate_hwp_offline(struct cpudata *cpu) /* Enable bit for Dynamic Efficiency Control (DEC) */ #define POWER_CTL_DEC_ENABLE 27 +static DEFINE_MUTEX(power_ctl_update_lock); static int power_ctl_ee_state; -static void set_power_ctl_ee_state(bool input) +static void __set_power_ctl_ee_state(bool input) { u64 power_ctl; - guard(mutex)(&intel_pstate_driver_lock); + lockdep_assert_held(&power_ctl_update_lock); rdmsrq(MSR_IA32_POWER_CTL, power_ctl); if (input) { @@ -1370,6 +1371,13 @@ static void set_power_ctl_ee_state(bool input) wrmsrq(MSR_IA32_POWER_CTL, power_ctl); } +static void set_power_ctl_ee_state(bool input) +{ + guard(mutex)(&power_ctl_update_lock); + + __set_power_ctl_ee_state(input); +} + static void intel_pstate_hwp_enable(struct cpudata *cpudata); static void intel_pstate_hwp_reenable(struct cpudata *cpu) @@ -1398,11 +1406,13 @@ static int intel_pstate_resume(struct cpufreq_policy *policy) pr_debug("CPU %d resuming\n", cpu->cpu); - /* Only restore if the system default is changed */ - if (power_ctl_ee_state == POWER_CTL_EE_ENABLE) - set_power_ctl_ee_state(true); - else if (power_ctl_ee_state == POWER_CTL_EE_DISABLE) - set_power_ctl_ee_state(false); + scoped_guard(mutex, &power_ctl_update_lock) { + /* Only restore if the system default has changed */ + if (power_ctl_ee_state == POWER_CTL_EE_ENABLE) + __set_power_ctl_ee_state(true); + else if (power_ctl_ee_state == POWER_CTL_EE_DISABLE) + __set_power_ctl_ee_state(false); + } if (cpu->suspended && hwp_active) { mutex_lock(&intel_pstate_limits_lock); @@ -1426,16 +1436,24 @@ static void intel_pstate_update_policies(void) cpufreq_update_policy(cpu); } -static void __intel_pstate_update_max_freq(struct cpufreq_policy *policy, - struct cpudata *cpudata) +static void __intel_pstate_update_cpuinfo_max_freq(struct cpufreq_policy *policy, + struct cpudata *cpudata) { - guard(cpufreq_policy_write)(policy); + lockdep_assert_held_write(&policy->rwsem); if (hwp_active) intel_pstate_get_hwp_cap(cpudata); policy->cpuinfo.max_freq = READ_ONCE(global.no_turbo) ? cpudata->pstate.max_freq : cpudata->pstate.turbo_freq; +} + +static void __intel_pstate_update_max_freq(struct cpufreq_policy *policy, + struct cpudata *cpudata) +{ + guard(cpufreq_policy_write)(policy); + + __intel_pstate_update_cpuinfo_max_freq(policy, cpudata); refresh_frequency_limits(policy); } @@ -1569,6 +1587,12 @@ static ssize_t store_no_turbo(struct kobject *a, struct kobj_attribute *b, return -EINVAL; guard(mutex)(&intel_pstate_driver_lock); + /* + * intel_pstate_update_max_freq() skips offline CPUs, and a CPU coming + * online reads global.no_turbo in intel_pstate_cpu_online(). Keep CPUs + * from coming online until every online CPU has the new limit + */ + guard(cpus_read_lock)(); if (!intel_pstate_driver) return -EAGAIN; @@ -3019,6 +3043,14 @@ static int intel_pstate_cpu_online(struct cpufreq_policy *policy) hybrid_update_capacity(cpu); } + /* + * intel_pstate_update_max_freq() skips offline CPUs, so the turbo + * setting or the HWP capabilities may have changed since this CPU + * went offline. Read the HWP capabilities only once HWP is enabled + * again + */ + __intel_pstate_update_cpuinfo_max_freq(policy, cpu); + return 0; } diff --git a/drivers/cxl/core/region.c b/drivers/cxl/core/region.c index a048bd5c06cb64..f8c88113de357b 100644 --- a/drivers/cxl/core/region.c +++ b/drivers/cxl/core/region.c @@ -1764,9 +1764,6 @@ static int cxl_region_validate_position(struct cxl_region *cxlr, return -ENXIO; } - if (p->targets[pos] == cxled) - return 0; - if (p->targets[pos]) { struct cxl_endpoint_decoder *cxled_target = p->targets[pos]; struct cxl_memdev *cxlmd_target = cxled_to_memdev(cxled_target); @@ -2045,6 +2042,14 @@ static int cxl_region_sort_targets(struct cxl_region *cxlr) sort(p->targets, p->nr_targets, sizeof(p->targets[0]), cmp_interleave_pos, NULL); + /* + * Restore cxled->pos from its ->targets[] slot so that follow-on + * code paths can reliably do p->targets[cxled->pos] to + * self-reference their entry, whether or not the sort succeeded. + */ + for (i = 0; i < p->nr_targets; i++) + p->targets[i]->pos = i; + dev_dbg(&cxlr->dev, "region sort %s\n", rc ? "failed" : "successful"); return rc; } diff --git a/drivers/cxl/port.c b/drivers/cxl/port.c index c12fd0b89883a6..7b4726c7276d43 100644 --- a/drivers/cxl/port.c +++ b/drivers/cxl/port.c @@ -72,19 +72,21 @@ static int cxl_switch_port_probe(struct cxl_port *port) return 0; } -static int cxl_ras_unmask(struct cxl_port *port) +static int cxl_endpoint_ras_unmask(struct cxl_port *endpoint) { + struct cxl_memdev *cxlmd = to_cxl_memdev(endpoint->uport_dev); + struct device *parent = cxlmd->dev.parent; struct pci_dev *pdev; void __iomem *addr; u32 orig_val, val, mask; u16 cap; int rc; - if (!dev_is_pci(port->uport_dev)) + if (!dev_is_pci(parent)) return 0; - pdev = to_pci_dev(port->uport_dev); + pdev = to_pci_dev(parent); - if (!port->regs.ras) { + if (!endpoint->regs.ras) { pci_dbg(pdev, "No RAS registers.\n"); return 0; } @@ -98,7 +100,7 @@ static int cxl_ras_unmask(struct cxl_port *port) return rc; if (cap & PCI_EXP_DEVCTL_URRE) { - addr = port->regs.ras + CXL_RAS_UNCORRECTABLE_MASK_OFFSET; + addr = endpoint->regs.ras + CXL_RAS_UNCORRECTABLE_MASK_OFFSET; orig_val = readl(addr); mask = CXL_RAS_UNCORRECTABLE_MASK_MASK | @@ -110,7 +112,7 @@ static int cxl_ras_unmask(struct cxl_port *port) } if (cap & PCI_EXP_DEVCTL_CERE) { - addr = port->regs.ras + CXL_RAS_CORRECTABLE_MASK_OFFSET; + addr = endpoint->regs.ras + CXL_RAS_CORRECTABLE_MASK_OFFSET; orig_val = readl(addr); val = orig_val & ~CXL_RAS_CORRECTABLE_MASK_MASK; writel(val, addr); @@ -152,7 +154,7 @@ static int cxl_endpoint_port_probe(struct cxl_port *port) devm_cxl_dport_rch_ras_setup(dport); devm_cxl_port_ras_setup(port); - if (cxl_ras_unmask(port)) + if (cxl_endpoint_ras_unmask(port)) dev_dbg(&port->dev, "failed to unmask RAS interrupts\n"); /* diff --git a/drivers/dma/idxd/cdev.c b/drivers/dma/idxd/cdev.c index 82b07cf942ef82..f1af7f0d25d347 100644 --- a/drivers/dma/idxd/cdev.c +++ b/drivers/dma/idxd/cdev.c @@ -573,6 +573,7 @@ int idxd_wq_add_cdev(struct idxd_wq *wq) return 0; err: + ida_free(&cdev_ctx->minor_ida, minor); put_device(dev); wq->idxd_cdev = NULL; return rc; diff --git a/drivers/dma/sh/rcar-dmac.c b/drivers/dma/sh/rcar-dmac.c index dc3900d4d99c14..c303564d8f0c8b 100644 --- a/drivers/dma/sh/rcar-dmac.c +++ b/drivers/dma/sh/rcar-dmac.c @@ -844,6 +844,7 @@ static void rcar_dmac_chan_reinit(struct rcar_dmac_chan *chan) list_for_each_entry_safe(desc, _desc, &descs, node) { list_del(&desc->node); + dma_descriptor_unmap(&desc->async_tx); rcar_dmac_desc_put(chan, desc); } } @@ -1070,7 +1071,7 @@ static int rcar_dmac_alloc_chan_resources(struct dma_chan *chan) if (ret < 0) return -ENOMEM; - return pm_runtime_get_sync(chan->device->dev); + return pm_runtime_resume_and_get(chan->device->dev); } static void rcar_dmac_free_chan_resources(struct dma_chan *chan) @@ -1653,6 +1654,7 @@ static irqreturn_t rcar_dmac_isr_channel_thread(int irq, void *dev) while (!list_empty(&chan->desc.done)) { desc = list_first_entry(&chan->desc.done, struct rcar_dmac_desc, node); + dma_descriptor_unmap(&desc->async_tx); dma_cookie_complete(&desc->async_tx); list_del(&desc->node); @@ -1795,11 +1797,8 @@ static int rcar_dmac_chan_probe(struct rcar_dmac *dmac, rcar_dmac_isr_channel, rcar_dmac_isr_channel_thread, 0, irqname, rchan); - if (ret) { - dev_err(dmac->dev, "failed to request IRQ %u (%d)\n", - rchan->irq, ret); + if (ret) return ret; - } return 0; } diff --git a/drivers/dma/stm32/stm32-mdma.c b/drivers/dma/stm32/stm32-mdma.c index 4851c1c7ce0c49..0137551e6b667a 100644 --- a/drivers/dma/stm32/stm32-mdma.c +++ b/drivers/dma/stm32/stm32-mdma.c @@ -1777,6 +1777,7 @@ static int stm32_mdma_pm_suspend(struct device *dev) ccr = stm32_mdma_read(dmadev, STM32_MDMA_CCR(id)); if (ccr & STM32_MDMA_CCR_EN) { dev_warn(dev, "Suspend is prevented by Chan %i\n", id); + pm_runtime_put_sync(dev); return -EBUSY; } } diff --git a/drivers/edac/i5000_edac.c b/drivers/edac/i5000_edac.c index c0faf55f78129f..342b69909600b4 100644 --- a/drivers/edac/i5000_edac.c +++ b/drivers/edac/i5000_edac.c @@ -1253,14 +1253,12 @@ static int i5000_init_csrows(struct mem_ctl_info *mci) struct i5000_pvt *pvt; struct dimm_info *dimm; int empty; - int max_csrows; int mtr; int csrow_megs; int channel; int slot; pvt = mci->pvt_info; - max_csrows = pvt->maxdimmperch * 2; empty = 1; /* Assume NO memory */ @@ -1271,7 +1269,7 @@ static int i5000_init_csrows(struct mem_ctl_info *mci) * to map the dimms. A good cleanup would be to remove this array, * and do a loop here with branch, channel, slot */ - for (slot = 0; slot < max_csrows; slot++) { + for (slot = 0; slot < pvt->maxdimmperch; slot++) { for (channel = 0; channel < pvt->maxch; channel++) { mtr = determine_mtr(pvt, slot, channel); diff --git a/drivers/edac/versalnet_edac.c b/drivers/edac/versalnet_edac.c index d59ba3904cda65..729cf66c5c793c 100644 --- a/drivers/edac/versalnet_edac.c +++ b/drivers/edac/versalnet_edac.c @@ -70,7 +70,7 @@ #define XDDR5_BUS_WIDTH_32 1 #define XDDR5_BUS_WIDTH_16 2 -#define MC_NAME_LEN 32 +#define RPMSG_CHAN_NAME "error_ipc" /** * struct ecc_error_info - ECC error log information. @@ -715,21 +715,21 @@ static int rpmsg_cb(struct rpmsg_device *rpdev, void *data, } static struct rpmsg_device_id amd_rpmsg_id_table[] = { - { .name = "error_ipc" }, + { .name = RPMSG_CHAN_NAME }, { }, }; MODULE_DEVICE_TABLE(rpmsg, amd_rpmsg_id_table); static int rpmsg_probe(struct rpmsg_device *rpdev) { - struct rpmsg_channel_info chinfo; + struct rpmsg_channel_info chinfo = { + .src = RPMSG_ADDR_ANY, + .dst = rpdev->dst, + .name = RPMSG_CHAN_NAME, + }; struct mc_priv *pg; pg = (struct mc_priv *)amd_rpmsg_id_table[0].driver_data; - chinfo.src = RPMSG_ADDR_ANY; - chinfo.dst = rpdev->dst; - strscpy(chinfo.name, amd_rpmsg_id_table[0].name, - strlen(amd_rpmsg_id_table[0].name)); pg->ept = rpmsg_create_ept(rpdev, rpmsg_cb, NULL, chinfo); if (!pg->ept) @@ -765,11 +765,14 @@ static void versal_edac_release(struct device *dev) static void remove_one_mc(struct mc_priv *priv, int i) { struct mem_ctl_info *mci; + struct device *dev; mci = priv->mci[i]; - device_unregister(mci->pdev); - edac_mc_del_mc(mci->pdev); + dev = mci->pdev; + + edac_mc_del_mc(dev); edac_mc_free(mci); + device_unregister(dev); } static int init_one_mc(struct mc_priv *priv, struct platform_device *pdev, int i) @@ -777,7 +780,6 @@ static int init_one_mc(struct mc_priv *priv, struct platform_device *pdev, int i u32 num_chans, rank, dwidth, config; struct edac_mc_layer layers[2]; struct mem_ctl_info *mci; - char name[MC_NAME_LEN]; struct device *dev; enum dev_type dt; int rc; @@ -817,28 +819,31 @@ static int init_one_mc(struct mc_priv *priv, struct platform_device *pdev, int i if (!dev) return rc; + dev->release = versal_edac_release; + device_initialize(dev); + + rc = dev_set_name(dev, "versal-net-ddrmc5-edac-%d", i); + if (rc) + goto err_put_dev; + + rc = device_add(dev); + if (rc) + goto err_put_dev; + mci = edac_mc_alloc(i, ARRAY_SIZE(layers), layers, sizeof(struct mc_priv)); if (!mci) { edac_printk(KERN_ERR, EDAC_MC, "Failed memory allocation for MC%d\n", i); - goto err_dev_free; + rc = -ENOMEM; + goto err_dev_del; } - sprintf(name, "versal-net-ddrmc5-edac-%d", i); - - dev->init_name = name; - dev->release = versal_edac_release; - - rc = device_register(dev); - if (rc) - goto err_mc_free; - mci->pdev = dev; mc_init(mci, dev); rc = edac_mc_add_mc(mci); if (rc) { edac_printk(KERN_ERR, EDAC_MC, "Failed to register MC%d with EDAC core\n", i); - goto err_unreg; + goto err_mc_free; } priv->mci[i] = mci; @@ -848,12 +853,12 @@ static int init_one_mc(struct mc_priv *priv, struct platform_device *pdev, int i return 0; -err_unreg: - device_unregister(mci->pdev); err_mc_free: edac_mc_free(mci); -err_dev_free: - kfree(dev); +err_dev_del: + device_del(dev); +err_put_dev: + put_device(dev); return rc; } diff --git a/drivers/firmware/arm_ffa/driver.c b/drivers/firmware/arm_ffa/driver.c index 28abc808fd32d2..ae8cc3a2ba2e7a 100644 --- a/drivers/firmware/arm_ffa/driver.c +++ b/drivers/firmware/arm_ffa/driver.c @@ -1223,6 +1223,7 @@ struct notifier_cb_info { ffa_fwk_notifier_cb fwk_cb; ffa_notifier_cb cb; void *cb_data; + u16 notify_id; }; static int @@ -1302,7 +1303,8 @@ notifier_hnode_get_by_vmid(u16 notify_id, int vmid) struct notifier_cb_info *node; hash_for_each_possible(drv_info->notifier_hash, node, hnode, notify_id) - if (node->fwk_cb && vmid == node->dev->vm_id) + if (node->notify_id == notify_id && node->fwk_cb && + vmid == node->dev->vm_id) return node; return NULL; @@ -1317,7 +1319,8 @@ notifier_hnode_get_by_vmid_uuid(u16 notify_id, int vmid, const uuid_t *uuid) return notifier_hnode_get_by_vmid(notify_id, vmid); hash_for_each_possible(drv_info->notifier_hash, node, hnode, notify_id) - if (node->fwk_cb && vmid == node->dev->vm_id && + if (node->notify_id == notify_id && node->fwk_cb && + vmid == node->dev->vm_id && uuid_equal(&node->dev->uuid, uuid)) return node; @@ -1330,7 +1333,8 @@ notifier_hnode_get_by_type(u16 notify_id, enum notify_type type) struct notifier_cb_info *node; hash_for_each_possible(drv_info->notifier_hash, node, hnode, notify_id) - if (node->cb && type == ffa_notify_type_get(node->dev->vm_id)) + if (node->notify_id == notify_id && node->cb && + type == ffa_notify_type_get(node->dev->vm_id)) return node; return NULL; @@ -1422,6 +1426,7 @@ static int __ffa_notify_request(struct ffa_device *dev, bool is_per_vcpu, cb_info->dev = dev; cb_info->cb_data = cb_data; + cb_info->notify_id = notify_id; if (is_framework) cb_info->fwk_cb = cb; else diff --git a/drivers/firmware/arm_scmi/Kconfig b/drivers/firmware/arm_scmi/Kconfig index 783c24a20e2919..9f6241efd5923f 100644 --- a/drivers/firmware/arm_scmi/Kconfig +++ b/drivers/firmware/arm_scmi/Kconfig @@ -52,7 +52,7 @@ config ARM_SCMI_RAW_MODE_SUPPORT_COEX Allow SCMI Raw transmission mode to coexist with normal SCMI stack. This will allow regular SCMI drivers to register with the core and - operate normally, thing which could make an SCMI test suite using the + operate normally, things which could make an SCMI test suite using the SCMI Raw mode support unreliable. If unsure, say N. config ARM_SCMI_DEBUG_COUNTERS diff --git a/drivers/firmware/arm_scmi/bus.c b/drivers/firmware/arm_scmi/bus.c index 25197197db8e1a..7613ea2893ef92 100644 --- a/drivers/firmware/arm_scmi/bus.c +++ b/drivers/firmware/arm_scmi/bus.c @@ -36,6 +36,12 @@ struct scmi_requested_dev { /* Track globally the SCMI SystemPower protocol device. */ static struct scmi_device *scmi_syspower_registered; +static bool scmi_raw_mode_only(void) +{ + return IS_ENABLED(CONFIG_ARM_SCMI_RAW_MODE_SUPPORT) && + !IS_ENABLED(CONFIG_ARM_SCMI_RAW_MODE_SUPPORT_COEX); +} + /** * scmi_protocol_device_request - Helper to request a device * @@ -60,8 +66,7 @@ static int scmi_protocol_device_request(const struct scmi_device_id *id_table) pr_debug("Requesting SCMI device (%s) for protocol %x\n", id_table->name, id_table->protocol_id); - if (IS_ENABLED(CONFIG_ARM_SCMI_RAW_MODE_SUPPORT) && - !IS_ENABLED(CONFIG_ARM_SCMI_RAW_MODE_SUPPORT_COEX)) { + if (scmi_raw_mode_only()) { pr_warn("SCMI Raw mode active. Rejecting '%s'/0x%02X\n", id_table->name, id_table->protocol_id); return -EINVAL; @@ -181,12 +186,43 @@ static void scmi_protocol_device_unrequest(const struct scmi_device_id *id_table } } +/* Standard protocols table */ +static const struct scmi_device_id scmi_std_id_table[] = { + { SCMI_PROTOCOL_POWER, "genpd" }, + { SCMI_PROTOCOL_SYSTEM, "syspower" }, + { SCMI_PROTOCOL_PERF, "perf" }, + { SCMI_PROTOCOL_PERF, "cpufreq" }, + { SCMI_PROTOCOL_CLOCK, "clocks" }, + { SCMI_PROTOCOL_SENSOR, "hwmon" }, + { SCMI_PROTOCOL_SENSOR, "iiodev" }, + { SCMI_PROTOCOL_RESET, "reset" }, + { SCMI_PROTOCOL_VOLTAGE, "regulator" }, + { SCMI_PROTOCOL_POWERCAP, "powercap" }, + { SCMI_PROTOCOL_PINCTRL, "pinctrl" }, + { }, +}; + +static bool scmi_device_id_in_std_id_table(const struct scmi_device_id *id) +{ + for (int i = 0; scmi_std_id_table[i].name[0]; i++) { + if (scmi_std_id_table[i].protocol_id == id->protocol_id && + !strcmp(scmi_std_id_table[i].name, id->name)) + return true; + } + + return false; +} + static int scmi_protocol_table_register(const struct scmi_device_id *id_table) { const struct scmi_device_id *entry; int ret; for (entry = id_table; entry->name[0]; entry++) { + /* Skip standard devices as they are created unconditionally */ + if (scmi_device_id_in_std_id_table(entry)) + continue; + ret = scmi_protocol_device_request(entry); if (ret) goto err_unrequest; @@ -195,8 +231,11 @@ static int scmi_protocol_table_register(const struct scmi_device_id *id_table) return 0; err_unrequest: - while (entry != id_table) - scmi_protocol_device_unrequest(--entry); + while (entry != id_table) { + --entry; + if (!scmi_device_id_in_std_id_table(entry)) + scmi_protocol_device_unrequest(entry); + } return ret; } @@ -206,16 +245,23 @@ scmi_protocol_table_unregister(const struct scmi_device_id *id_table) { const struct scmi_device_id *entry; - for (entry = id_table; entry->name[0]; entry++) - scmi_protocol_device_unrequest(entry); + for (entry = id_table; entry->name[0]; entry++) { + if (!scmi_device_id_in_std_id_table(entry)) + scmi_protocol_device_unrequest(entry); + } } -static bool scmi_device_is_transport(const struct scmi_device *scmi_dev) +static bool scmi_device_name_is_transport(const char *name) { - return !strncmp(scmi_dev->name, SCMI_TRANSPORT_DEVNAME_PREFIX, + return !strncmp(name, SCMI_TRANSPORT_DEVNAME_PREFIX, strlen(SCMI_TRANSPORT_DEVNAME_PREFIX)); } +static bool scmi_device_is_transport(const struct scmi_device *scmi_dev) +{ + return scmi_device_name_is_transport(scmi_dev->name); +} + static int __scmi_dev_match_by_id_table(struct scmi_device *scmi_dev, const struct scmi_device_id *id_table, bool skip_transport) @@ -524,6 +570,11 @@ _scmi_device_create(struct fwnode_handle *fwnode, struct device *parent, { struct scmi_device *sdev; + /* The perf device is only needed when it provides power domains. */ + if (protocol == SCMI_PROTOCOL_PERF && !strcmp(name, "perf") && + !fwnode_property_present(fwnode, "#power-domain-cells")) + return NULL; + sdev = __scmi_device_create(fwnode, parent, protocol, name); if (!sdev) pr_err("(%pfwf) Failed to create device - protocol 0x%x (%s)\n", @@ -532,34 +583,6 @@ _scmi_device_create(struct fwnode_handle *fwnode, struct device *parent, return sdev; } -/* Standard protocols table */ -static const struct scmi_device_id scmi_std_id_table[] = { - { SCMI_PROTOCOL_POWER, "genpd" }, - { SCMI_PROTOCOL_SYSTEM, "syspower" }, - { SCMI_PROTOCOL_PERF, "perf" }, - { SCMI_PROTOCOL_PERF, "cpufreq" }, - { SCMI_PROTOCOL_CLOCK, "clocks" }, - { SCMI_PROTOCOL_SENSOR, "hwmon" }, - { SCMI_PROTOCOL_SENSOR, "iiodev" }, - { SCMI_PROTOCOL_RESET, "reset" }, - { SCMI_PROTOCOL_VOLTAGE, "regulator" }, - { SCMI_PROTOCOL_POWERCAP, "powercap" }, - { SCMI_PROTOCOL_PINCTRL, "pinctrl" }, - { SCMI_PROTOCOL_PINCTRL, "pinctrl-imx" }, - { }, -}; - -static bool scmi_device_id_in_std_id_table(const struct scmi_device_id *id) -{ - for (int i = 0; scmi_std_id_table[i].name[0]; i++) { - if (scmi_std_id_table[i].protocol_id == id->protocol_id && - !strcmp(scmi_std_id_table[i].name, id->name)) - return true; - } - - return false; -} - /** * scmi_device_create - A method to create one or more SCMI devices * @@ -578,10 +601,8 @@ static bool scmi_device_id_in_std_id_table(const struct scmi_device_id *id) * * Return: The created device (or one of them if @name was NOT provided and * multiple devices were created) or NULL if no device was created; - * note that NULL indicates an error ONLY in case a specific @name - * was provided: when @name param was not provided, a number of devices - * could have been potentially created for a whole protocol, unless no - * device was found to have been requested for that specific protocol. + * note that NULL can also indicate that a named device is not needed + * for this fwnode, or that no device was requested when @name is NULL. */ struct scmi_device *scmi_device_create(struct fwnode_handle *fwnode, struct device *parent, int protocol, @@ -591,6 +612,11 @@ struct scmi_device *scmi_device_create(struct fwnode_handle *fwnode, struct scmi_requested_dev *rdev; struct scmi_device *sdev, *scmi_dev = NULL; + /* Exclusive raw mode still needs transport devices for its channels. */ + if (scmi_raw_mode_only() && + (!name || !scmi_device_name_is_transport(name))) + return NULL; + if (name) return _scmi_device_create(fwnode, parent, protocol, name); @@ -619,10 +645,6 @@ struct scmi_device *scmi_device_create(struct fwnode_handle *fwnode, /* Walk the list of requested devices for protocol and create them */ list_for_each_entry(rdev, phead, node) { - /* Standard proto matches already have their dev created above */ - if (scmi_device_id_in_std_id_table(rdev->id_table)) - continue; - sdev = _scmi_device_create(fwnode, parent, rdev->id_table->protocol_id, rdev->id_table->name); diff --git a/drivers/firmware/arm_scmi/driver.c b/drivers/firmware/arm_scmi/driver.c index 05092301db29af..b753a02f1358a1 100644 --- a/drivers/firmware/arm_scmi/driver.c +++ b/drivers/firmware/arm_scmi/driver.c @@ -3107,11 +3107,7 @@ static void scmi_debugfs_common_cleanup(void *d) static const char *scmi_acpi_device_hid(struct acpi_device *adev) { -#ifdef CONFIG_ACPI return adev ? acpi_device_hid(adev) : "unknown"; -#else - return "unknown"; -#endif } static struct scmi_debug_info *scmi_debugfs_common_setup(struct scmi_info *info) diff --git a/drivers/firmware/arm_scmi/notify.c b/drivers/firmware/arm_scmi/notify.c index bc046f2f83a6f1..7be01952500d5d 100644 --- a/drivers/firmware/arm_scmi/notify.c +++ b/drivers/firmware/arm_scmi/notify.c @@ -1393,8 +1393,10 @@ static int scmi_notifier_register(const struct scmi_handle *handle, /* Enable events for not pending handlers */ if (!IS_HNDL_PENDING(hndl)) { ret = scmi_event_handler_enable_events(hndl); - if (ret) + if (ret) { + blocking_notifier_chain_unregister(&hndl->chain, nb); scmi_put_handler(ni, hndl); + } } return ret; diff --git a/drivers/firmware/arm_scmi/transports/Kconfig b/drivers/firmware/arm_scmi/transports/Kconfig index 0e34fbf2505323..6ba0dcb86204d7 100644 --- a/drivers/firmware/arm_scmi/transports/Kconfig +++ b/drivers/firmware/arm_scmi/transports/Kconfig @@ -5,7 +5,7 @@ config ARM_SCMI_HAVE_TRANSPORT bool help This declares whether at least one SCMI transport has been configured. - Used to trigger a build bug when trying to build SCMI without any + Used to trigger a runtime warning when enabling SCMI without any configured transport. config ARM_SCMI_HAVE_SHMEM diff --git a/drivers/firmware/arm_scmi/transports/mailbox.c b/drivers/firmware/arm_scmi/transports/mailbox.c index 0677005dc6d3f5..b12bd07c2867c6 100644 --- a/drivers/firmware/arm_scmi/transports/mailbox.c +++ b/drivers/firmware/arm_scmi/transports/mailbox.c @@ -206,8 +206,11 @@ static int mailbox_chan_setup(struct scmi_chan_info *cinfo, struct device *dev, smbox->shmem = core->shmem->setup_iomap(cinfo, dev, tx, NULL, &smbox->io_ops); - if (IS_ERR(smbox->shmem)) - return PTR_ERR(smbox->shmem); + if (IS_ERR(smbox->shmem)) { + ret = PTR_ERR(smbox->shmem); + devm_kfree(dev, smbox); + return ret; + } cl = &smbox->cl; cl->dev = cdev; diff --git a/drivers/firmware/arm_scmi/vendors/imx/imx-sm-misc.c b/drivers/firmware/arm_scmi/vendors/imx/imx-sm-misc.c index 2cec3dbb56ad0c..ed7499d72f198e 100644 --- a/drivers/firmware/arm_scmi/vendors/imx/imx-sm-misc.c +++ b/drivers/firmware/arm_scmi/vendors/imx/imx-sm-misc.c @@ -273,10 +273,16 @@ static int scmi_imx_misc_ctrl_get(const struct scmi_protocol_handle *ph, { struct scmi_imx_misc_ctrl_get_out *out; struct scmi_xfer *t; + u32 num_values, max_values; int ret, i; int max_msg_size = ph->hops->get_max_msg_size(ph); int max_num = (max_msg_size - sizeof(*out)) / sizeof(__le32); + if (!num || !val || !*num) + return -EINVAL; + + max_values = *num; + ret = scmi_imx_misc_ctrl_validate_id(ph, ctrl_id); if (ret) return ret; @@ -290,16 +296,18 @@ static int scmi_imx_misc_ctrl_get(const struct scmi_protocol_handle *ph, ret = ph->xops->do_xfer(ph, t); if (!ret) { out = t->rx.buf; - *num = le32_to_cpu(out->num); + num_values = le32_to_cpu(out->num); - if (*num >= max_num || - *num * sizeof(__le32) > t->rx.len - sizeof(__le32)) { + if (num_values > max_values || num_values >= max_num || + num_values * sizeof(__le32) > t->rx.len - sizeof(__le32)) { ph->xops->xfer_put(ph, t); return -EINVAL; } - for (i = 0; i < *num; i++) + for (i = 0; i < num_values; i++) val[i] = le32_to_cpu(out->val[i]); + + *num = num_values; } ph->xops->xfer_put(ph, t); @@ -438,7 +446,7 @@ static int iter_misc_syslog_update_state(struct scmi_iterator_state *st, st->num_returned = RETURNED(r->numlogflags); st->num_remaining = REMAINING(r->numlogflags); - *p->size = st->num_returned + st->num_remaining; + *p->size = st->desc_index + st->num_returned; return 0; } diff --git a/drivers/firmware/cirrus/cs_dsp.c b/drivers/firmware/cirrus/cs_dsp.c index abf9196db883c2..bb8e7c70ea4968 100644 --- a/drivers/firmware/cirrus/cs_dsp.c +++ b/drivers/firmware/cirrus/cs_dsp.c @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -824,7 +825,7 @@ int cs_dsp_coeff_write_ctrl(struct cs_dsp_coeff_ctl *ctl, if (ctl->flags & WMFW_CTL_FLAG_VOLATILE) { ret = -EPERM; - } else if (buf != ctl->cache) { + } else if (buf != &ctl->cache[0]) { if (memcmp(ctl->cache + off * sizeof(u32), buf, len)) memcpy(ctl->cache + off * sizeof(u32), buf, len); else @@ -933,7 +934,7 @@ int cs_dsp_coeff_read_ctrl(struct cs_dsp_coeff_ctl *ctl, if (!ctl->flags && ctl->enabled && ctl->dsp->running && !ctl->dsp->hibernating) ret = cs_dsp_coeff_read_ctrl_raw(ctl, 0, ctl->cache, ctl->len); - if (buf != ctl->cache) + if (buf != &ctl->cache[0]) memcpy(buf, ctl->cache + off * sizeof(u32), len); } @@ -1036,16 +1037,15 @@ static void cs_dsp_signal_event_controls(struct cs_dsp *dsp, static void cs_dsp_free_ctl_blk(struct cs_dsp_coeff_ctl *ctl) { - kvfree(ctl->cache); kfree(ctl->subname); - kfree(ctl); + kvfree(ctl); } static int cs_dsp_create_control(struct cs_dsp *dsp, const struct cs_dsp_alg_region *alg_region, unsigned int offset, unsigned int len, - const char *subname, unsigned int subname_len, - unsigned int flags, unsigned int type) + const char *subname, u16 subname_len, + u16 flags, u16 type) { struct cs_dsp_coeff_ctl *ctl; int ret; @@ -1064,7 +1064,7 @@ static int cs_dsp_create_control(struct cs_dsp *dsp, } } - ctl = kzalloc_obj(*ctl); + ctl = kvzalloc_flex(*ctl, cache, len); if (!ctl) return -ENOMEM; @@ -1086,11 +1086,6 @@ static int cs_dsp_create_control(struct cs_dsp *dsp, ctl->type = type; ctl->offset = offset; ctl->len = len; - ctl->cache = kvzalloc(ctl->len, GFP_KERNEL); - if (!ctl->cache) { - ret = -ENOMEM; - goto err_ctl_subname; - } list_add(&ctl->list, &dsp->ctl_list); @@ -1104,11 +1099,9 @@ static int cs_dsp_create_control(struct cs_dsp *dsp, err_list_del: list_del(&ctl->list); - kvfree(ctl->cache); -err_ctl_subname: kfree(ctl->subname); err_ctl: - kfree(ctl); + kvfree(ctl); return ret; } @@ -1162,9 +1155,9 @@ struct cs_dsp_coeff_parsed_coeff { int offset; int mem_type; const u8 *name; - int name_len; - unsigned int ctl_type; - int flags; + u16 name_len; + u16 ctl_type; + u16 flags; int len; }; @@ -1312,6 +1305,9 @@ static int cs_dsp_coeff_parse_coeff(struct cs_dsp *dsp, blk->offset = le16_to_cpu(raw->hdr.offset); blk->mem_type = le16_to_cpu(raw->hdr.type); + static_assert(sizeof(blk->ctl_type) >= sizeof(raw->ctl_type)); + static_assert(sizeof(blk->flags) >= sizeof(raw->flags)); + switch (dsp->wmfw_ver) { case 0: case 1: @@ -1319,7 +1315,7 @@ static int cs_dsp_coeff_parse_coeff(struct cs_dsp *dsp, return -EOVERFLOW; blk->name = raw->name; - blk->name_len = strnlen(raw->name, ARRAY_SIZE(raw->name)); + blk->name_len = (u16)strnlen(raw->name, ARRAY_SIZE(raw->name)); blk->ctl_type = le16_to_cpu(raw->ctl_type); blk->flags = le16_to_cpu(raw->flags); blk->len = le32_to_cpu(raw->len); diff --git a/drivers/firmware/cirrus/test/cs_dsp_test_bin.c b/drivers/firmware/cirrus/test/cs_dsp_test_bin.c index 63416838f8653a..2f44b7a6e63791 100644 --- a/drivers/firmware/cirrus/test/cs_dsp_test_bin.c +++ b/drivers/firmware/cirrus/test/cs_dsp_test_bin.c @@ -17,6 +17,7 @@ #include #include #include +#include #include "../cs_dsp.h" @@ -2109,6 +2110,7 @@ static void bin_patch_name_and_info(struct kunit *test) unsigned int reg_inc_per_word = cs_dsp_mock_reg_addr_inc_per_unpacked_word(priv); u32 reg_val, payload_data; char *infobuf; + struct seq_buf sb; unsigned int alg_base_words, reg_addr; struct firmware *fw; @@ -2126,8 +2128,9 @@ static void bin_patch_name_and_info(struct kunit *test) infobuf = kunit_kzalloc(test, 512, GFP_KERNEL); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, infobuf); - for (; strlcat(infobuf, "Waffle{Blah}\n", 512) < 512; ) - ; + seq_buf_init(&sb, infobuf, 512); + while (!seq_buf_has_overflowed(&sb)) + seq_buf_puts(&sb, "Waffle{Blah}\n"); cs_dsp_mock_bin_add_info(priv->local->bin_builder, infobuf); diff --git a/drivers/firmware/cirrus/test/cs_dsp_test_control_cache.c b/drivers/firmware/cirrus/test/cs_dsp_test_control_cache.c index b03cd7c37f6e40..7a9f939fcf6f56 100644 --- a/drivers/firmware/cirrus/test/cs_dsp_test_control_cache.c +++ b/drivers/firmware/cirrus/test/cs_dsp_test_control_cache.c @@ -13,6 +13,7 @@ #include #include #include +#include #include #include @@ -186,9 +187,9 @@ static void cs_dsp_ctl_v2_cache_alloc(struct kunit *test) KUNIT_EXPECT_EQ(test, list_count_nodes(&dsp->ctl_list), num_ctls); - /* Check that the block allocated for the cache is large enough */ + /* Check that the allocation holds the control and its cache */ list_for_each_entry(ctl, &dsp->ctl_list, list) - KUNIT_EXPECT_GE(test, ksize(ctl->cache), ctl->len); + KUNIT_EXPECT_GE(test, ksize(ctl), struct_size(ctl, cache, ctl->len)); } /* diff --git a/drivers/firmware/cirrus/test/cs_dsp_test_wmfw.c b/drivers/firmware/cirrus/test/cs_dsp_test_wmfw.c index 1de70e81a8687d..464a0cc79415e1 100644 --- a/drivers/firmware/cirrus/test/cs_dsp_test_wmfw.c +++ b/drivers/firmware/cirrus/test/cs_dsp_test_wmfw.c @@ -16,6 +16,7 @@ #include #include #include +#include #include #include @@ -1722,6 +1723,7 @@ static void wmfw_load_with_info(struct kunit *test) unsigned int reg_addr; u8 *payload_data, *readback; char *infobuf; + struct seq_buf sb; const unsigned int payload_size_bytes = 48; int ret; @@ -1745,8 +1747,9 @@ static void wmfw_load_with_info(struct kunit *test) infobuf = kunit_kzalloc(test, 512, GFP_KERNEL); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, infobuf); - for (; strlcat(infobuf, "Waffle{Blah}\n", 512) < 512;) - ; + seq_buf_init(&sb, infobuf, 512); + while (!seq_buf_has_overflowed(&sb)) + seq_buf_puts(&sb, "Waffle{Blah}\n"); cs_dsp_mock_wmfw_add_info(local->wmfw_builder, infobuf); cs_dsp_mock_wmfw_add_info(local->wmfw_builder, "Another block of info"); diff --git a/drivers/firmware/efi/efi-init.c b/drivers/firmware/efi/efi-init.c index 9f09b0d2daa0b9..58acb5d25adfa6 100644 --- a/drivers/firmware/efi/efi-init.c +++ b/drivers/firmware/efi/efi-init.c @@ -54,7 +54,7 @@ static phys_addr_t __init efi_to_phys(unsigned long addr) return addr; } -extern __weak const efi_config_table_type_t efi_arch_tables[]; +extern const efi_config_table_type_t efi_arch_tables[]; /* * x86 defines its own instance of sysfb_primary_display and uses @@ -123,7 +123,8 @@ static int __init uefi_init(u64 efi_system_table) goto out; } retval = efi_config_parse_tables(config_tables, systab->nr_tables, - efi_arch_tables); + IS_ENABLED(CONFIG_ARM) ? efi_arch_tables + : NULL); early_memunmap(config_tables, table_size); out: diff --git a/drivers/firmware/efi/efi-pstore.c b/drivers/firmware/efi/efi-pstore.c index a5db3534f0a632..19a7e4fe5b5248 100644 --- a/drivers/firmware/efi/efi-pstore.c +++ b/drivers/firmware/efi/efi-pstore.c @@ -19,37 +19,10 @@ MODULE_PARM_DESC(record_size, "size of each pstore UEFI var (in bytes, min/defau EFI_VARIABLE_BOOTSERVICE_ACCESS | \ EFI_VARIABLE_RUNTIME_ACCESS) -static bool pstore_disable = IS_ENABLED(CONFIG_EFI_VARS_PSTORE_DEFAULT_DISABLE); +static bool efivars_pstore_disable = + IS_ENABLED(CONFIG_EFI_VARS_PSTORE_DEFAULT_DISABLE); -static int efivars_pstore_init(void); -static void efivars_pstore_exit(void); - -static int efi_pstore_disable_set(const char *val, const struct kernel_param *kp) -{ - int err; - bool old_pstore_disable = pstore_disable; - - err = param_set_bool(val, kp); - if (err) - return err; - - if (old_pstore_disable != pstore_disable) { - if (pstore_disable) - efivars_pstore_exit(); - else - efivars_pstore_init(); - } - - return 0; -} - -static const struct kernel_param_ops pstore_disable_ops = { - .set = efi_pstore_disable_set, - .get = param_get_bool, -}; - -module_param_cb(pstore_disable, &pstore_disable_ops, &pstore_disable, 0644); -__MODULE_PARM_TYPE(pstore_disable, "bool"); +module_param_named(pstore_disable, efivars_pstore_disable, bool, 0444); static int efi_pstore_open(struct pstore_info *psi) { @@ -255,12 +228,12 @@ static struct pstore_info efi_pstore_info = { .erase = efi_pstore_erase, }; -static int efivars_pstore_init(void) +static __init int efivars_pstore_init(void) { if (!efivar_supports_writes()) return 0; - if (pstore_disable) + if (efivars_pstore_disable) return 0; /* @@ -287,7 +260,7 @@ static int efivars_pstore_init(void) return 0; } -static void efivars_pstore_exit(void) +static __exit void efivars_pstore_exit(void) { if (!efi_pstore_info.bufsize) return; diff --git a/drivers/firmware/efi/efi.c b/drivers/firmware/efi/efi.c index 9bc22de0d67ee0..355d4cb0404e69 100644 --- a/drivers/firmware/efi/efi.c +++ b/drivers/firmware/efi/efi.c @@ -157,18 +157,20 @@ static ssize_t fw_platform_size_show(struct kobject *kobj, return sysfs_emit(buf, "%d\n", efi_enabled(EFI_64BIT) ? 64 : 32); } -extern __weak const struct kobj_attribute efi_attr_fw_vendor; -extern __weak const struct kobj_attribute efi_attr_runtime; -extern __weak const struct kobj_attribute efi_attr_config_table; +extern const struct kobj_attribute efi_attr_fw_vendor; +extern const struct kobj_attribute efi_attr_runtime; +extern const struct kobj_attribute efi_attr_config_table; static const struct kobj_attribute efi_attr_fw_platform_size = __KOBJ_ATTR_RO(fw_platform_size); static const struct attribute *const efi_subsys_attrs[] = { &efi_attr_systab.attr, &efi_attr_fw_platform_size.attr, +#ifdef CONFIG_X86 &efi_attr_fw_vendor.attr, &efi_attr_runtime.attr, &efi_attr_config_table.attr, +#endif NULL, }; @@ -184,7 +186,7 @@ static const struct attribute_group efi_subsys_attr_group = { .is_visible_const = efi_attr_is_visible, }; -struct blocking_notifier_head efivar_ops_nh; +BLOCKING_NOTIFIER_HEAD(efivar_ops_nh); EXPORT_SYMBOL_GPL(efivar_ops_nh); static struct efivars generic_efivars; @@ -466,8 +468,7 @@ static int __init efisubsys_init(void) efi_kobj = kobject_create_and_add("efi", firmware_kobj); if (!efi_kobj) { pr_err("efi: Firmware registration failed.\n"); - error = -ENOMEM; - goto err_destroy_wq; + return -ENOMEM; } if (IS_ENABLED(CONFIG_PREEMPT_RT) && efi.runtime_supported_mask) { @@ -486,8 +487,6 @@ static int __init efisubsys_init(void) platform_device_register_simple("efivars", 0, NULL, 0); } - BLOCKING_INIT_NOTIFIER_HEAD(&efivar_ops_nh); - error = sysfs_create_group(efi_kobj, &efi_subsys_attr_group); if (error) { pr_err("efi: Sysfs attribute export failed with error %d.\n", @@ -525,9 +524,6 @@ static int __init efisubsys_init(void) err_put: kobject_put(efi_kobj); efi_kobj = NULL; -err_destroy_wq: - if (efi_rts_wq) - destroy_workqueue(efi_rts_wq); return error; } diff --git a/drivers/firmware/efi/libstub/Makefile b/drivers/firmware/efi/libstub/Makefile index bbab12b8eb4b23..ba6c9e7638622a 100644 --- a/drivers/firmware/efi/libstub/Makefile +++ b/drivers/firmware/efi/libstub/Makefile @@ -88,7 +88,9 @@ lib-$(CONFIG_ARM64) += kaslr.o arm64.o arm64-stub.o smbios.o lib-$(CONFIG_X86) += x86-stub.o smbios.o lib-$(CONFIG_X86_64) += x86-5lvl.o lib-$(CONFIG_RISCV) += kaslr.o riscv.o riscv-stub.o -lib-$(CONFIG_LOONGARCH) += loongarch.o loongarch-stub.o +lib-loongarch-$(CONFIG_32BIT) += lib-ashldi3.o lib-lshrdi3.o +lib-$(CONFIG_LOONGARCH) += loongarch.o loongarch-stub.o \ + $(lib-loongarch-y) CFLAGS_arm32-stub.o := -DTEXT_OFFSET=$(TEXT_OFFSET) @@ -99,8 +101,7 @@ CFLAGS_zboot-decompress-zstd.o += -I$(srctree)/lib/zstd zboot-riscv-obj-$(CONFIG_32BIT) := lib-ashldi3.o lib-lshrdi3.o zboot-obj-$(CONFIG_RISCV) += lib-clz_ctz.o $(zboot-riscv-obj-y) -zboot-loongarch-obj-$(CONFIG_32BIT) := lib-ashldi3.o lib-lshrdi3.o -zboot-obj-$(CONFIG_LOONGARCH) += lib-clz_ctz.o $(zboot-loongarch-obj-y) +zboot-obj-$(CONFIG_LOONGARCH) += lib-clz_ctz.o lib-$(CONFIG_EFI_ZBOOT) += zboot.o $(zboot-obj-y) lib-$(CONFIG_UNACCEPTED_MEMORY) += unaccepted_memory.o bitmap.o find.o diff --git a/drivers/firmware/efi/libstub/arm64.c b/drivers/firmware/efi/libstub/arm64.c index e57cd3de0a00f4..d35c6dd7660108 100644 --- a/drivers/firmware/efi/libstub/arm64.c +++ b/drivers/firmware/efi/libstub/arm64.c @@ -109,6 +109,7 @@ void efi_cache_sync_image(unsigned long image_base, } while (size >= lsize); } + dsb(ish); asm("ic ialluis"); dsb(ish); isb(); diff --git a/drivers/firmware/efi/libstub/efistub.h b/drivers/firmware/efi/libstub/efistub.h index f5eec8c12894c0..a3b589c7d81cd6 100644 --- a/drivers/firmware/efi/libstub/efistub.h +++ b/drivers/firmware/efi/libstub/efistub.h @@ -838,15 +838,17 @@ union apple_properties_protocol { unsigned long version; efi_status_t (__efiapi *get)(apple_properties_protocol_t *, struct efi_dev_path *, - efi_char16_t *, void *, u32 *); + efi_char16_t *, void *, + unsigned long *); efi_status_t (__efiapi *set)(apple_properties_protocol_t *, struct efi_dev_path *, - efi_char16_t *, void *, u32); + efi_char16_t *, void *, + unsigned long); efi_status_t (__efiapi *del)(apple_properties_protocol_t *, struct efi_dev_path *, efi_char16_t *); efi_status_t (__efiapi *get_all)(apple_properties_protocol_t *, - void *buffer, u32 *); + void *buffer, unsigned long *); }; struct { u32 version; diff --git a/drivers/firmware/efi/libstub/tpm.c b/drivers/firmware/efi/libstub/tpm.c index 73f0011147323d..b8183bfdbaa3d2 100644 --- a/drivers/firmware/efi/libstub/tpm.c +++ b/drivers/firmware/efi/libstub/tpm.c @@ -96,7 +96,7 @@ static void efi_retrieve_tcg2_eventlog(int version, efi_physical_addr_t log_loca } /* Allocate space for the logs and copy them. */ - status = efi_bs_call(allocate_pool, EFI_ACPI_RECLAIM_MEMORY, + status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, sizeof(*log_tbl) + log_size, (void **)&log_tbl); if (status != EFI_SUCCESS) { diff --git a/drivers/firmware/efi/libstub/x86-stub.c b/drivers/firmware/efi/libstub/x86-stub.c index 253dd3ba8fab24..42a0ce40260a9c 100644 --- a/drivers/firmware/efi/libstub/x86-stub.c +++ b/drivers/firmware/efi/libstub/x86-stub.c @@ -158,10 +158,10 @@ static void setup_efi_pci(struct boot_params *params) static void retrieve_apple_device_properties(struct boot_params *boot_params) { static efi_guid_t guid = APPLE_PROPERTIES_PROTOCOL_GUID; + apple_properties_protocol_t *p; struct setup_data *data, *new; + unsigned long size = 0; efi_status_t status; - u32 size = 0; - apple_properties_protocol_t *p; status = efi_bs_call(locate_protocol, &guid, NULL, (void **)&p); if (status != EFI_SUCCESS) diff --git a/drivers/firmware/efi/libstub/zboot.lds b/drivers/firmware/efi/libstub/zboot.lds index 367907eb7d8698..a785c012374970 100644 --- a/drivers/firmware/efi/libstub/zboot.lds +++ b/drivers/firmware/efi/libstub/zboot.lds @@ -45,7 +45,7 @@ SECTIONS .bss : { *(.bss* .init.bss*) - _end = ALIGN(512); + _end = ALIGN(4096); . = _end; } diff --git a/drivers/firmware/efi/vars.c b/drivers/firmware/efi/vars.c index 3700e98697676d..f9c28fbdb26dfb 100644 --- a/drivers/firmware/efi/vars.c +++ b/drivers/firmware/efi/vars.c @@ -143,7 +143,7 @@ int efivar_lock(void) { if (down_interruptible(&efivars_lock)) return -EINTR; - if (!__efivars->ops) { + if (!__efivars || !__efivars->ops) { up(&efivars_lock); return -ENODEV; } @@ -159,7 +159,7 @@ int efivar_trylock(void) { if (down_trylock(&efivars_lock)) return -EBUSY; - if (!__efivars->ops) { + if (!__efivars || !__efivars->ops) { up(&efivars_lock); return -ENODEV; } diff --git a/drivers/gpio/gpio-aspeed.c b/drivers/gpio/gpio-aspeed.c index 45e90ebaf07840..8f66be7ff9b5bc 100644 --- a/drivers/gpio/gpio-aspeed.c +++ b/drivers/gpio/gpio-aspeed.c @@ -944,10 +944,6 @@ int aspeed_gpio_copro_grab_gpio(struct gpio_desc *desc, if (!aspeed_gpio_support_copro(gpio)) return -EOPNOTSUPP; - if (!gpio->cf_copro_bankmap) - gpio->cf_copro_bankmap = kzalloc(gpio->chip.ngpio >> 3, GFP_KERNEL); - if (!gpio->cf_copro_bankmap) - return -ENOMEM; if (offset < 0 || offset > gpio->chip.ngpio) return -EINVAL; bindex = offset >> 3; @@ -1381,6 +1377,14 @@ static int aspeed_gpio_probe(struct platform_device *pdev) gpio->config->llops->reg_bank_get(gpio, (i << 5), reg_rdata); } + if (aspeed_gpio_support_copro(gpio)) { + gpio->cf_copro_bankmap = devm_kzalloc_objs(gpio->dev, + *gpio->cf_copro_bankmap, + DIV_ROUND_UP(gpio->chip.ngpio, 8)); + if (!gpio->cf_copro_bankmap) + return -ENOMEM; + } + if (gpio->config->llops->privilege_init) gpio->config->llops->privilege_init(gpio); diff --git a/drivers/gpio/gpio-davinci.c b/drivers/gpio/gpio-davinci.c index 303b5409e2844b..5f24367ad9af8a 100644 --- a/drivers/gpio/gpio-davinci.c +++ b/drivers/gpio/gpio-davinci.c @@ -43,7 +43,6 @@ typedef struct irq_chip *(*gpio_get_irq_chip_cb_t)(unsigned int irq); #define BINTEN 0x8 /* GPIO Interrupt Per-Bank Enable Register */ -static void __iomem *gpio_base; static unsigned int offset_array[5] = {0x10, 0x38, 0x60, 0x88, 0xb0}; struct davinci_gpio_irq_data { @@ -168,6 +167,7 @@ static int davinci_gpio_probe(struct platform_device *pdev) unsigned int ngpio, nbank, nirq, gpio_unbanked; struct davinci_gpio_controller *chips; struct device *dev = &pdev->dev; + void __iomem *gpio_base; /* * The gpio banks conceptually expose a segmented bitmap, @@ -550,6 +550,13 @@ static int davinci_gpio_irq_setup(struct platform_device *pdev) * Or, AINTC can handle IRQs for banks of 16 GPIO IRQs, which we * then chain through our own handler. */ + irqdata = devm_kzalloc_objs(dev, *irqdata, + DIV_ROUND_UP(ngpio, 16)); + if (!irqdata) { + irq_domain_remove(chips->irq_domain); + return -ENOMEM; + } + for (gpio = 0, bank = 0; gpio < ngpio; bank++, gpio += 16) { /* disabled by default, enabled only as needed * There are register sets for 32 GPIOs. 2 banks of 16 @@ -564,19 +571,12 @@ static int davinci_gpio_irq_setup(struct platform_device *pdev) * gpio irqs. Pass the irq bank's corresponding controller to * the chained irq handler. */ - irqdata = devm_kzalloc_obj(&pdev->dev, - struct davinci_gpio_irq_data); - if (!irqdata) { - irq_domain_remove(chips->irq_domain); - return -ENOMEM; - } - - irqdata->regs = g; - irqdata->bank_num = bank; - irqdata->chip = chips; + irqdata[bank].regs = g; + irqdata[bank].bank_num = bank; + irqdata[bank].chip = chips; irq_set_chained_handler_and_data(chips->irqs[bank], - gpio_irq_handler, irqdata); + gpio_irq_handler, &irqdata[bank]); binten |= BIT(bank); } @@ -586,7 +586,7 @@ static int davinci_gpio_irq_setup(struct platform_device *pdev) * BINTEN -- per-bank interrupt enable. genirq would also let these * bits be set/cleared dynamically. */ - writel_relaxed(binten, gpio_base + BINTEN); + writel_relaxed(binten, chips->regs[0] - offset_array[0] + BINTEN); return 0; } diff --git a/drivers/gpio/gpio-ljca.c b/drivers/gpio/gpio-ljca.c index 067e5c472abdd7..997b361a402411 100644 --- a/drivers/gpio/gpio-ljca.c +++ b/drivers/gpio/gpio-ljca.c @@ -292,9 +292,14 @@ static void ljca_gpio_event_cb(void *context, u8 cmd, const void *evt_data, return; for (i = 0; i < packet->num; i++) { - generic_handle_domain_irq(ljca_gpio->gc.irq.domain, - packet->item[i].index); - set_bit(packet->item[i].index, ljca_gpio->reenable_irqs); + u8 index = packet->item[i].index; + + /* The pin index comes from the device, do not trust it */ + if (index >= ljca_gpio->gc.ngpio) + continue; + + generic_handle_domain_irq(ljca_gpio->gc.irq.domain, index); + set_bit(index, ljca_gpio->reenable_irqs); } schedule_work(&ljca_gpio->work); diff --git a/drivers/gpio/gpio-mlxbf2.c b/drivers/gpio/gpio-mlxbf2.c index b3b107c07cbec5..ed724d544c03d5 100644 --- a/drivers/gpio/gpio-mlxbf2.c +++ b/drivers/gpio/gpio-mlxbf2.c @@ -128,12 +128,20 @@ static int mlxbf2_gpio_get_lock_res(struct platform_device *pdev) * Acquire the YU arm_gpio_lock to be able to change the direction * mode. If the lock_active bit is already set, return an error. */ -static int mlxbf2_gpio_lock_acquire(struct mlxbf2_gpio_context *gs) +static int mlxbf2_gpio_lock_acquire(struct mlxbf2_gpio_context *gs, + unsigned long *flags) { u32 arm_gpio_lock_val; mutex_lock(yu_arm_gpio_lock_param.lock); - gpio_generic_chip_lock(&gs->chip); + /* + * Disable interrupts before taking the chip lock. The GPIO irq + * callbacks take this lock while holding the irq descriptor lock, + * and the irq handler takes the descriptor lock in hardirq context. + * A plain spin_lock() here lets lockdep report an inversion, and + * can deadlock if a GPIO interrupt arrives on this CPU. + */ + gpio_generic_chip_lock_irqsave(&gs->chip, *flags); arm_gpio_lock_val = readl(yu_arm_gpio_lock_param.io); @@ -141,7 +149,7 @@ static int mlxbf2_gpio_lock_acquire(struct mlxbf2_gpio_context *gs) * When lock active bit[31] is set, ModeX is write enabled */ if (YU_LOCK_ACTIVE_BIT(arm_gpio_lock_val)) { - gpio_generic_chip_unlock(&gs->chip); + gpio_generic_chip_unlock_irqrestore(&gs->chip, *flags); mutex_unlock(yu_arm_gpio_lock_param.lock); return -EINVAL; } @@ -154,12 +162,13 @@ static int mlxbf2_gpio_lock_acquire(struct mlxbf2_gpio_context *gs) /* * Release the YU arm_gpio_lock after changing the direction mode. */ -static void mlxbf2_gpio_lock_release(struct mlxbf2_gpio_context *gs) +static void mlxbf2_gpio_lock_release(struct mlxbf2_gpio_context *gs, + unsigned long flags) __releases(&gs->chip.lock) __releases(yu_arm_gpio_lock_param.lock) { writel(YU_ARM_GPIO_LOCK_RELEASE, yu_arm_gpio_lock_param.io); - gpio_generic_chip_unlock(&gs->chip); + gpio_generic_chip_unlock_irqrestore(&gs->chip, flags); mutex_unlock(yu_arm_gpio_lock_param.lock); } @@ -185,20 +194,21 @@ static int mlxbf2_gpio_direction_input(struct gpio_chip *chip, unsigned int offset) { struct mlxbf2_gpio_context *gs = gpiochip_get_data(chip); + unsigned long flags; int ret; /* * Although the arm_gpio_lock was set in the probe function, check again * if it is still enabled to be able to write to the ModeX registers. */ - ret = mlxbf2_gpio_lock_acquire(gs); + ret = mlxbf2_gpio_lock_acquire(gs, &flags); if (ret < 0) return ret; writel(BIT(offset), gs->gpio_io + YU_GPIO_MODE0_CLEAR); writel(BIT(offset), gs->gpio_io + YU_GPIO_MODE1_CLEAR); - mlxbf2_gpio_lock_release(gs); + mlxbf2_gpio_lock_release(gs, flags); return ret; } @@ -212,6 +222,7 @@ static int mlxbf2_gpio_direction_output(struct gpio_chip *chip, int value) { struct mlxbf2_gpio_context *gs = gpiochip_get_data(chip); + unsigned long flags; int ret = 0; /* @@ -219,14 +230,14 @@ static int mlxbf2_gpio_direction_output(struct gpio_chip *chip, * check again it is still enabled to be able to write to the * ModeX registers. */ - ret = mlxbf2_gpio_lock_acquire(gs); + ret = mlxbf2_gpio_lock_acquire(gs, &flags); if (ret < 0) return ret; writel(BIT(offset), gs->gpio_io + YU_GPIO_MODE1_CLEAR); writel(BIT(offset), gs->gpio_io + YU_GPIO_MODE0_SET); - mlxbf2_gpio_lock_release(gs); + mlxbf2_gpio_lock_release(gs, flags); return ret; } diff --git a/drivers/gpio/gpio-mpsse.c b/drivers/gpio/gpio-mpsse.c index a16b6875b2e20c..393c537c1d2753 100644 --- a/drivers/gpio/gpio-mpsse.c +++ b/drivers/gpio/gpio-mpsse.c @@ -676,6 +676,10 @@ static int gpio_mpsse_probe(struct usb_interface *interface, if (err) return err; + /* Every read carries two status bytes ahead of the data */ + if (usb_endpoint_maxp(priv->bulk_in) < 3) + return -EINVAL; + priv->bulk_in_buf = devm_kmalloc(dev, usb_endpoint_maxp(priv->bulk_in), GFP_KERNEL); if (!priv->bulk_in_buf) diff --git a/drivers/gpio/gpio-mvebu.c b/drivers/gpio/gpio-mvebu.c index 2591239b1956bb..6c2bcc5d749cc7 100644 --- a/drivers/gpio/gpio-mvebu.c +++ b/drivers/gpio/gpio-mvebu.c @@ -1030,10 +1030,10 @@ static int mvebu_gpio_suspend(struct platform_device *pdev, pm_message_t state) break; case MVEBU_GPIO_SOC_VARIANT_ARMADAXP: for (i = 0; i < 4; i++) { - regmap_read(mvchip->regs, + regmap_read(mvchip->percpu_regs, GPIO_EDGE_MASK_ARMADAXP_OFF(i), &mvchip->edge_mask_regs[i]); - regmap_read(mvchip->regs, + regmap_read(mvchip->percpu_regs, GPIO_LEVEL_MASK_ARMADAXP_OFF(i), &mvchip->level_mask_regs[i]); } @@ -1103,10 +1103,10 @@ static int mvebu_gpio_resume(struct platform_device *pdev) break; case MVEBU_GPIO_SOC_VARIANT_ARMADAXP: for (i = 0; i < 4; i++) { - regmap_write(mvchip->regs, + regmap_write(mvchip->percpu_regs, GPIO_EDGE_MASK_ARMADAXP_OFF(i), mvchip->edge_mask_regs[i] & edge_cache); - regmap_write(mvchip->regs, + regmap_write(mvchip->percpu_regs, GPIO_LEVEL_MASK_ARMADAXP_OFF(i), mvchip->level_mask_regs[i] & level_cache); } @@ -1213,6 +1213,9 @@ static int mvebu_gpio_probe(struct platform_device *pdev) return -ENODEV; } + if (ngpios == 0 || ngpios > MVEBU_MAX_GPIO_PER_BANK) + return dev_err_probe(&pdev->dev, -EINVAL, "ngpios must be between 1 and 32\n"); + id = of_alias_get_id(pdev->dev.of_node, "gpio"); if (id < 0) { dev_err(&pdev->dev, "Couldn't get OF id\n"); diff --git a/drivers/gpio/gpio-omap.c b/drivers/gpio/gpio-omap.c index 585c2784bb7552..0af26c3f71978f 100644 --- a/drivers/gpio/gpio-omap.c +++ b/drivers/gpio/gpio-omap.c @@ -1449,13 +1449,11 @@ static int omap_gpio_probe(struct platform_device *pdev) } if (bank->dbck_flag) { - bank->dbck = devm_clk_get(dev, "dbclk"); + bank->dbck = devm_clk_get_prepared(dev, "dbclk"); if (IS_ERR(bank->dbck)) { dev_err(dev, - "Could not get gpio dbck. Disable debounce\n"); + "Could not get or prepare gpio dbck. Disable debounce\n"); bank->dbck_flag = false; - } else { - clk_prepare(bank->dbck); } } @@ -1465,8 +1463,6 @@ static int omap_gpio_probe(struct platform_device *pdev) ret = pm_runtime_resume_and_get(dev); if (ret < 0) { pm_runtime_disable(dev); - if (bank->dbck_flag) - clk_unprepare(bank->dbck); return ret; } @@ -1479,8 +1475,6 @@ static int omap_gpio_probe(struct platform_device *pdev) if (ret) { pm_runtime_put_sync(dev); pm_runtime_disable(dev); - if (bank->dbck_flag) - clk_unprepare(bank->dbck); return ret; } @@ -1501,8 +1495,6 @@ static void omap_gpio_remove(struct platform_device *pdev) cpu_pm_unregister_notifier(&bank->nb); gpiochip_remove(&bank->chip); pm_runtime_disable(&pdev->dev); - if (bank->dbck_flag) - clk_unprepare(bank->dbck); } static int omap_gpio_runtime_suspend(struct device *dev) diff --git a/drivers/gpio/gpio-pca953x.c b/drivers/gpio/gpio-pca953x.c index b662bcf7b9be8b..c90371eaa10c08 100644 --- a/drivers/gpio/gpio-pca953x.c +++ b/drivers/gpio/gpio-pca953x.c @@ -1337,20 +1337,23 @@ static int pca953x_regcache_sync(struct pca953x_chip *chip) u8 regaddr; /* - * The ordering between direction and output is important, - * sync these registers first and only then sync the rest. + * The ordering between output and direction is important: restore + * the output levels while the lines are still inputs, and only then + * turn them into outputs. Restoring direction first would drive + * every output at the power-on output value until the output + * registers are written. Sync these first, then the rest. */ - regaddr = chip->recalc_addr(chip, chip->regs->direction, 0); + regaddr = chip->recalc_addr(chip, chip->regs->output, 0); ret = regcache_sync_region(chip->regmap, regaddr, regaddr + NBANK(chip) - 1); if (ret) { - dev_err(dev, "Failed to sync GPIO dir registers: %d\n", ret); + dev_err(dev, "Failed to sync GPIO out registers: %d\n", ret); return ret; } - regaddr = chip->recalc_addr(chip, chip->regs->output, 0); + regaddr = chip->recalc_addr(chip, chip->regs->direction, 0); ret = regcache_sync_region(chip->regmap, regaddr, regaddr + NBANK(chip) - 1); if (ret) { - dev_err(dev, "Failed to sync GPIO out registers: %d\n", ret); + dev_err(dev, "Failed to sync GPIO dir registers: %d\n", ret); return ret; } diff --git a/drivers/gpio/gpio-shared-proxy.c b/drivers/gpio/gpio-shared-proxy.c index 80412bd4ef2502..60973acc709c0f 100644 --- a/drivers/gpio/gpio-shared-proxy.c +++ b/drivers/gpio/gpio-shared-proxy.c @@ -186,7 +186,7 @@ static int gpio_shared_proxy_set_config(struct gpio_chip *gc, } ret = gpiod_set_config(desc, cfg); - if (ret && ret != -ENOTSUPP) + if (ret) return ret; shared_desc->cfg = cfg; diff --git a/drivers/gpio/gpio-virtio.c b/drivers/gpio/gpio-virtio.c index d0ae3d57c64037..759d5cd0f62a4d 100644 --- a/drivers/gpio/gpio-virtio.c +++ b/drivers/gpio/gpio-virtio.c @@ -494,12 +494,13 @@ static const char **virtio_gpio_get_names(struct virtio_gpio *vgpio, struct device *dev = &vgpio->vdev->dev; u8 *gpio_names, *str; const char **names; - int i, ret, len; + size_t len; + int i, ret; if (!gpio_names_size) return NULL; - len = sizeof(*res) + gpio_names_size; + len = struct_size(res, value, gpio_names_size); res = devm_kzalloc(dev, len, GFP_KERNEL); if (!res) return NULL; @@ -520,13 +521,13 @@ static const char **virtio_gpio_get_names(struct virtio_gpio *vgpio, gpio_names[gpio_names_size - 1] = '\0'; for (i = 0, str = gpio_names; i < ngpio; i++) { - names[i] = str; - str += strlen(str) + 1; /* zero-length strings are allowed */ - - if (str > gpio_names + gpio_names_size) { + if (str >= gpio_names + gpio_names_size) { dev_err(dev, "gpio_names block is too short (%d)\n", i); return NULL; } + + names[i] = str; + str += strlen(str) + 1; /* zero-length strings are allowed */ } return names; diff --git a/drivers/gpio/gpiolib-cdev.c b/drivers/gpio/gpiolib-cdev.c index 3f1f8c9acfc3c1..ceecce572a520a 100644 --- a/drivers/gpio/gpiolib-cdev.c +++ b/drivers/gpio/gpiolib-cdev.c @@ -140,24 +140,25 @@ static int linehandle_validate_flags(u32 flags) return 0; } -static void linehandle_flags_to_desc_flags(u32 lflags, unsigned long *flagsp) +static void linehandle_update_desc_flags(u32 lflags, struct gpio_desc *desc) { - unsigned long flags = READ_ONCE(*flagsp); + unsigned long flags = 0, mask; - assign_bit(GPIOD_FLAG_ACTIVE_LOW, &flags, - lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW); - assign_bit(GPIOD_FLAG_OPEN_DRAIN, &flags, - lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN); - assign_bit(GPIOD_FLAG_OPEN_SOURCE, &flags, - lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE); - assign_bit(GPIOD_FLAG_PULL_UP, &flags, - lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP); - assign_bit(GPIOD_FLAG_PULL_DOWN, &flags, - lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN); - assign_bit(GPIOD_FLAG_BIAS_DISABLE, &flags, - lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE); + mask = BIT(GPIOD_FLAG_ACTIVE_LOW) | + BIT(GPIOD_FLAG_OPEN_DRAIN) | + BIT(GPIOD_FLAG_OPEN_SOURCE) | + BIT(GPIOD_FLAG_PULL_UP) | + BIT(GPIOD_FLAG_PULL_DOWN) | + BIT(GPIOD_FLAG_BIAS_DISABLE); - WRITE_ONCE(*flagsp, flags); + __assign_bit(GPIOD_FLAG_ACTIVE_LOW, &flags, lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW); + __assign_bit(GPIOD_FLAG_OPEN_DRAIN, &flags, lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN); + __assign_bit(GPIOD_FLAG_OPEN_SOURCE, &flags, lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE); + __assign_bit(GPIOD_FLAG_PULL_UP, &flags, lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP); + __assign_bit(GPIOD_FLAG_PULL_DOWN, &flags, lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN); + __assign_bit(GPIOD_FLAG_BIAS_DISABLE, &flags, lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE); + + set_mask_bits(&desc->flags, mask, flags); } static long linehandle_set_config(struct linehandle_state *lh, @@ -182,7 +183,7 @@ static long linehandle_set_config(struct linehandle_state *lh, for (i = 0; i < lh->num_descs; i++) { desc = lh->descs[i]; - linehandle_flags_to_desc_flags(lflags, &desc->flags); + linehandle_update_desc_flags(lflags, desc); if (lflags & GPIOHANDLE_REQUEST_OUTPUT) { int val = !!gcnf.default_values[i]; @@ -346,7 +347,7 @@ static int linehandle_create(struct gpio_device *gdev, void __user *ip) if (ret) return ret; lh->descs[i] = desc; - linehandle_flags_to_desc_flags(handlereq.flags, &desc->flags); + linehandle_update_desc_flags(handlereq.flags, desc); ret = gpiod_set_transitory(desc, false); if (ret < 0) @@ -399,6 +400,7 @@ static int linehandle_create(struct gpio_device *gdev, void __user *ip) * @desc: the GPIO descriptor for this line. * @req: the corresponding line request * @irq: the interrupt triggered in response to events on this GPIO + * @irq_label: the name @irq was requested with * @edflags: the edge flags, GPIO_V2_LINE_FLAG_EDGE_RISING and/or * GPIO_V2_LINE_FLAG_EDGE_FALLING, indicating the edge detection applied * @timestamp_ns: cache for the timestamp storing it between hardirq and @@ -422,6 +424,7 @@ struct line { */ struct linereq *req; unsigned int irq; + char *irq_label; /* * The flags for the active edge detector configuration. * @@ -544,17 +547,6 @@ struct linereq { GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE | \ GPIO_V2_LINE_EDGE_FLAGS) -static int linereq_unregistered_notify(struct notifier_block *nb, - unsigned long action, void *data) -{ - struct linereq *lr = container_of(nb, struct linereq, - device_unregistered_nb); - - wake_up_poll(&lr->wait, EPOLLIN | EPOLLERR); - - return NOTIFY_OK; -} - static void linereq_put_event(struct linereq *lr, struct gpio_v2_line_event *le) { @@ -609,6 +601,23 @@ static inline void free_irq_label(const char *label) kfree(label); } +/* + * gpiochip_remove() frees the interrupts still requested on the lines of the + * chip being removed, so once the chip is going away the IRQ may no longer be + * ours to free. The label is kept by the caller as free_irq() is then not the + * one returning it. + */ +static void free_line_irq(unsigned int irq, void *dev_id, char **label) +{ + const char *name = *label; + + if (irq && irq_has_action(irq)) + free_irq(irq, dev_id); + + free_irq_label(name); + *label = NULL; +} + #ifdef CONFIG_HTE static enum hte_return process_hw_ts_thread(void *p) @@ -635,6 +644,8 @@ static enum hte_return process_hw_ts_thread(void *p) level = (line->raw_level >= 0) ? line->raw_level : gpiod_get_raw_value_cansleep(line->desc); + if (level < 0) + return HTE_CB_HANDLED; if (edflags & GPIO_V2_LINE_FLAG_ACTIVE_LOW) level = !level; @@ -737,6 +748,7 @@ static irqreturn_t edge_irq_thread(int irq, void *p) struct line *line = p; struct linereq *lr = line->req; struct gpio_v2_line_event le; + int level; /* Do not leak kernel stack to userspace */ memset(&le, 0, sizeof(le)); @@ -757,7 +769,10 @@ static irqreturn_t edge_irq_thread(int irq, void *p) switch (READ_ONCE(line->edflags) & GPIO_V2_LINE_EDGE_FLAGS) { case GPIO_V2_LINE_FLAG_EDGE_BOTH: - le.id = line_event_id(gpiod_get_value_cansleep(line->desc)); + level = gpiod_get_value_cansleep(line->desc); + if (level < 0) + return IRQ_HANDLED; + le.id = line_event_id(level); break; case GPIO_V2_LINE_FLAG_EDGE_RISING: le.id = GPIO_V2_LINE_EVENT_RISING_EDGE; @@ -934,6 +949,7 @@ static int debounce_setup(struct line *line, unsigned int debounce_period_us) return ret; } line->irq = irq; + line->irq_label = label; } else { ret = hte_edge_setup(line, GPIO_V2_LINE_FLAG_EDGE_BOTH); if (ret) @@ -976,10 +992,8 @@ static u32 gpio_v2_line_config_debounce_period(struct gpio_v2_line_config *lc, static void edge_detector_stop(struct line *line) { - if (line->irq) { - free_irq_label(free_irq(line->irq, line)); - line->irq = 0; - } + free_line_irq(line->irq, line, &line->irq_label); + line->irq = 0; #ifdef CONFIG_HTE if (READ_ONCE(line->edflags) & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE) @@ -994,6 +1008,25 @@ static void edge_detector_stop(struct line *line) /* do not change line->level - see comment in debounced_value() */ } +static int linereq_unregistered_notify(struct notifier_block *nb, + unsigned long action, void *data) +{ + struct linereq *lr = container_of(nb, struct linereq, device_unregistered_nb); + + /* + * Stop edge detection now rather than when the request is released: + * by then the IRQ numbers of the removed chip may be in use again. + */ + scoped_guard(mutex, &lr->config_mutex) { + for (unsigned int i = 0; i < lr->num_lines; i++) + edge_detector_stop(&lr->lines[i]); + } + + wake_up_poll(&lr->wait, EPOLLIN | EPOLLERR); + + return NOTIFY_OK; +} + static int edge_detector_fifo_init(struct linereq *req) { if (kfifo_initialized(&req->events)) @@ -1059,6 +1092,7 @@ static int edge_detector_setup(struct line *line, } line->irq = irq; + line->irq_label = label; return 0; } @@ -1223,37 +1257,35 @@ static int gpio_v2_line_config_validate(struct gpio_v2_line_config *lc, return 0; } -static void gpio_v2_line_config_flags_to_desc_flags(u64 lflags, - unsigned long *flagsp) +static void linereq_update_desc_flags(u64 lflags, struct gpio_desc *desc) { - unsigned long flags = READ_ONCE(*flagsp); - - assign_bit(GPIOD_FLAG_ACTIVE_LOW, &flags, - lflags & GPIO_V2_LINE_FLAG_ACTIVE_LOW); + unsigned long flags = 0, mask; - assign_bit(GPIOD_FLAG_EDGE_RISING, &flags, - lflags & GPIO_V2_LINE_FLAG_EDGE_RISING); - assign_bit(GPIOD_FLAG_EDGE_FALLING, &flags, - lflags & GPIO_V2_LINE_FLAG_EDGE_FALLING); + mask = BIT(GPIOD_FLAG_ACTIVE_LOW) | + BIT(GPIOD_FLAG_EDGE_RISING) | + BIT(GPIOD_FLAG_EDGE_FALLING) | + BIT(GPIOD_FLAG_OPEN_DRAIN) | + BIT(GPIOD_FLAG_OPEN_SOURCE) | + BIT(GPIOD_FLAG_PULL_UP) | + BIT(GPIOD_FLAG_PULL_DOWN) | + BIT(GPIOD_FLAG_BIAS_DISABLE) | + BIT(GPIOD_FLAG_EVENT_CLOCK_REALTIME) | + BIT(GPIOD_FLAG_EVENT_CLOCK_HTE); - assign_bit(GPIOD_FLAG_OPEN_DRAIN, &flags, - lflags & GPIO_V2_LINE_FLAG_OPEN_DRAIN); - assign_bit(GPIOD_FLAG_OPEN_SOURCE, &flags, - lflags & GPIO_V2_LINE_FLAG_OPEN_SOURCE); + __assign_bit(GPIOD_FLAG_ACTIVE_LOW, &flags, lflags & GPIO_V2_LINE_FLAG_ACTIVE_LOW); + __assign_bit(GPIOD_FLAG_EDGE_RISING, &flags, lflags & GPIO_V2_LINE_FLAG_EDGE_RISING); + __assign_bit(GPIOD_FLAG_EDGE_FALLING, &flags, lflags & GPIO_V2_LINE_FLAG_EDGE_FALLING); + __assign_bit(GPIOD_FLAG_OPEN_DRAIN, &flags, lflags & GPIO_V2_LINE_FLAG_OPEN_DRAIN); + __assign_bit(GPIOD_FLAG_OPEN_SOURCE, &flags, lflags & GPIO_V2_LINE_FLAG_OPEN_SOURCE); + __assign_bit(GPIOD_FLAG_PULL_UP, &flags, lflags & GPIO_V2_LINE_FLAG_BIAS_PULL_UP); + __assign_bit(GPIOD_FLAG_PULL_DOWN, &flags, lflags & GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN); + __assign_bit(GPIOD_FLAG_BIAS_DISABLE, &flags, lflags & GPIO_V2_LINE_FLAG_BIAS_DISABLED); + __assign_bit(GPIOD_FLAG_EVENT_CLOCK_REALTIME, &flags, + lflags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_REALTIME); + __assign_bit(GPIOD_FLAG_EVENT_CLOCK_HTE, &flags, + lflags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE); - assign_bit(GPIOD_FLAG_PULL_UP, &flags, - lflags & GPIO_V2_LINE_FLAG_BIAS_PULL_UP); - assign_bit(GPIOD_FLAG_PULL_DOWN, &flags, - lflags & GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN); - assign_bit(GPIOD_FLAG_BIAS_DISABLE, &flags, - lflags & GPIO_V2_LINE_FLAG_BIAS_DISABLED); - - assign_bit(GPIOD_FLAG_EVENT_CLOCK_REALTIME, &flags, - lflags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_REALTIME); - assign_bit(GPIOD_FLAG_EVENT_CLOCK_HTE, &flags, - lflags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE); - - WRITE_ONCE(*flagsp, flags); + set_mask_bits(&desc->flags, mask, flags); } static long linereq_get_values(struct linereq *lr, void __user *ip) @@ -1411,7 +1443,7 @@ static long linereq_set_config(struct linereq *lr, void __user *ip) */ if (!(flags & GPIO_V2_LINE_DIRECTION_FLAGS)) continue; - gpio_v2_line_config_flags_to_desc_flags(flags, &desc->flags); + linereq_update_desc_flags(flags, desc); edflags = flags & GPIO_V2_LINE_EDGE_DETECTOR_FLAGS; if (flags & GPIO_V2_LINE_FLAG_OUTPUT) { int val = gpio_v2_line_config_output_value(&lc, i); @@ -1488,6 +1520,20 @@ static __poll_t linereq_poll(struct file *file, return events; } +/* + * For the read() paths, which must not stay in the SRCU read section while + * sleeping: that would stall gpiochip_remove() until an event arrives. + */ +static int gpiodev_check_chip(struct gpio_device *gdev) +{ + guard(srcu)(&gdev->srcu); + + if (!rcu_access_pointer(gdev->chip)) + return -ENODEV; + + return 0; +} + static ssize_t linereq_read(struct file *file, char __user *buf, size_t count, loff_t *f_ps) { @@ -1496,10 +1542,9 @@ static ssize_t linereq_read(struct file *file, char __user *buf, ssize_t bytes_read = 0; int ret; - guard(srcu)(&lr->gdev->srcu); - - if (!rcu_access_pointer(lr->gdev->chip)) - return -ENODEV; + ret = gpiodev_check_chip(lr->gdev); + if (ret) + return ret; if (count < sizeof(le)) return -EINVAL; @@ -1514,9 +1559,12 @@ static ssize_t linereq_read(struct file *file, char __user *buf, return -EAGAIN; ret = wait_event_interruptible_locked(lr->wait, - !kfifo_is_empty(&lr->events)); + !kfifo_is_empty(&lr->events) || + !rcu_access_pointer(lr->gdev->chip)); if (ret) return ret; + if (kfifo_is_empty(&lr->events)) + return -ENODEV; } if (kfifo_out(&lr->events, &le, 1) != 1) { @@ -1542,19 +1590,25 @@ static void linereq_free(struct linereq *lr) { unsigned int i; + /* + * Stop edge detection while still registered for the notification, so + * that gpiochip_remove() does not get past it until the IRQs are freed. + */ + scoped_guard(mutex, &lr->config_mutex) { + for (i = 0; i < lr->num_lines; i++) + edge_detector_stop(&lr->lines[i]); + } + if (lr->device_unregistered_nb.notifier_call) blocking_notifier_chain_unregister(&lr->gdev->device_notifier, &lr->device_unregistered_nb); - for (i = 0; i < lr->num_lines; i++) { - if (lr->lines[i].desc) { - edge_detector_stop(&lr->lines[i]); - gpiod_free(lr->lines[i].desc); - } - } + for (i = 0; i < lr->num_lines; i++) + gpiod_free(lr->lines[i].desc); kfifo_free(&lr->events); kfree(lr->label); gpio_device_put(lr->gdev); + mutex_destroy(&lr->config_mutex); kvfree(lr); } @@ -1625,6 +1679,7 @@ static int linereq_create(struct gpio_device *gdev, void __user *ip) if (!lr) return -ENOMEM; lr->num_lines = ulr.num_lines; + mutex_init(&lr->config_mutex); lr->gdev = gpio_device_get(gdev); @@ -1642,7 +1697,6 @@ static int linereq_create(struct gpio_device *gdev, void __user *ip) return -ENOMEM; } - mutex_init(&lr->config_mutex); init_waitqueue_head(&lr->wait); INIT_KFIFO(lr->events); lr->event_buffer_size = ulr.event_buffer_size; @@ -1667,7 +1721,7 @@ static int linereq_create(struct gpio_device *gdev, void __user *ip) lr->lines[i].desc = desc; flags = gpio_v2_line_config_flags(lc, i); - gpio_v2_line_config_flags_to_desc_flags(flags, &desc->flags); + linereq_update_desc_flags(flags, desc); ret = gpiod_set_transitory(desc, false); if (ret < 0) @@ -1741,6 +1795,8 @@ static int linereq_create(struct gpio_device *gdev, void __user *ip) * @desc: the GPIO descriptor held by this event * @eflags: the event flags this line was requested with * @irq: the interrupt that trigger in response to events on this GPIO + * @irq_label: the name @irq was requested with + * @irq_lock: serializes freeing @irq on release and on chip removal * @wait: wait queue that handles blocking reads of events * @device_unregistered_nb: notifier block for receiving gdev unregister events * @events: KFIFO for the GPIO events @@ -1754,6 +1810,9 @@ struct lineevent_state { struct gpio_desc *desc; u32 eflags; int irq; + char *irq_label; + /* release vs. chip removal notifier */ + struct mutex irq_lock; wait_queue_head_t wait; struct notifier_block device_unregistered_nb; DECLARE_KFIFO(events, struct gpioevent_data, 16); @@ -1789,6 +1848,11 @@ static int lineevent_unregistered_notify(struct notifier_block *nb, struct lineevent_state *le = container_of(nb, struct lineevent_state, device_unregistered_nb); + scoped_guard(mutex, &le->irq_lock) { + free_line_irq(le->irq, le, &le->irq_label); + le->irq = 0; + } + wake_up_poll(&le->wait, EPOLLIN | EPOLLERR); return NOTIFY_OK; @@ -1808,10 +1872,9 @@ static ssize_t lineevent_read(struct file *file, char __user *buf, ssize_t ge_size; int ret; - guard(srcu)(&le->gdev->srcu); - - if (!rcu_access_pointer(le->gdev->chip)) - return -ENODEV; + ret = gpiodev_check_chip(le->gdev); + if (ret) + return ret; /* * When compatible system call is being used the struct gpioevent_data, @@ -1839,9 +1902,12 @@ static ssize_t lineevent_read(struct file *file, char __user *buf, return -EAGAIN; ret = wait_event_interruptible_locked(le->wait, - !kfifo_is_empty(&le->events)); + !kfifo_is_empty(&le->events) || + !rcu_access_pointer(le->gdev->chip)); if (ret) return ret; + if (kfifo_is_empty(&le->events)) + return -ENODEV; } if (kfifo_out(&le->events, &ge, 1) != 1) { @@ -1865,15 +1931,18 @@ static ssize_t lineevent_read(struct file *file, char __user *buf, static void lineevent_free(struct lineevent_state *le) { + scoped_guard(mutex, &le->irq_lock) { + free_line_irq(le->irq, le, &le->irq_label); + le->irq = 0; + } if (le->device_unregistered_nb.notifier_call) blocking_notifier_chain_unregister(&le->gdev->device_notifier, &le->device_unregistered_nb); - if (le->irq) - free_irq_label(free_irq(le->irq, le)); if (le->desc) gpiod_free(le->desc); kfree(le->label); gpio_device_put(le->gdev); + mutex_destroy(&le->irq_lock); kfree(le); } @@ -1959,6 +2028,8 @@ static irqreturn_t lineevent_irq_thread(int irq, void *p) && le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) { int level = gpiod_get_value_cansleep(le->desc); + if (level < 0) + return IRQ_HANDLED; if (level) /* Emit low-to-high event */ ge.id = GPIOEVENT_EVENT_RISING_EDGE; @@ -2045,6 +2116,7 @@ static int lineevent_create(struct gpio_device *gdev, void __user *ip) le = kzalloc_obj(*le); if (!le) return -ENOMEM; + mutex_init(&le->irq_lock); le->gdev = gpio_device_get(gdev); if (eventreq.consumer_label[0] != '\0') { @@ -2062,7 +2134,7 @@ static int lineevent_create(struct gpio_device *gdev, void __user *ip) le->desc = desc; le->eflags = eflags; - linehandle_flags_to_desc_flags(lflags, &desc->flags); + linehandle_update_desc_flags(lflags, desc); ret = gpiod_direction_input(desc); if (ret) @@ -2108,6 +2180,7 @@ static int lineevent_create(struct gpio_device *gdev, void __user *ip) } le->irq = irq; + le->irq_label = label; FD_PREPARE(fdf, O_RDONLY | O_CLOEXEC, anon_inode_getfile("gpio-event", &lineevent_fileops, le, @@ -2586,10 +2659,9 @@ static ssize_t lineinfo_watch_read(struct file *file, char __user *buf, int ret; size_t event_size; - guard(srcu)(&cdev->gdev->srcu); - - if (!rcu_access_pointer(cdev->gdev->chip)) - return -ENODEV; + ret = gpiodev_check_chip(cdev->gdev); + if (ret) + return ret; #ifndef CONFIG_GPIO_CDEV_V1 event_size = sizeof(struct gpio_v2_line_info_changed); @@ -2607,9 +2679,12 @@ static ssize_t lineinfo_watch_read(struct file *file, char __user *buf, return -EAGAIN; ret = wait_event_interruptible_locked(cdev->wait, - !kfifo_is_empty(&cdev->events)); + !kfifo_is_empty(&cdev->events) || + !rcu_access_pointer(cdev->gdev->chip)); if (ret) return ret; + if (kfifo_is_empty(&cdev->events)) + return -ENODEV; } #ifdef CONFIG_GPIO_CDEV_V1 /* must be after kfifo check so watch_abi_version is set */ @@ -2765,6 +2840,7 @@ int gpiolib_cdev_register(struct gpio_chip *gc, dev_t devt) ret = cdev_device_add(&gdev->chrdev, &gdev->dev); if (ret) { destroy_workqueue(gdev->line_state_wq); + gdev->line_state_wq = NULL; return ret; } @@ -2775,7 +2851,5 @@ int gpiolib_cdev_register(struct gpio_chip *gc, dev_t devt) void gpiolib_cdev_unregister(struct gpio_device *gdev) { - destroy_workqueue(gdev->line_state_wq); cdev_device_del(&gdev->chrdev, &gdev->dev); - blocking_notifier_call_chain(&gdev->device_notifier, 0, NULL); } diff --git a/drivers/gpio/gpiolib-of.c b/drivers/gpio/gpiolib-of.c index 8f8454d5960469..ea1dfc3a313112 100644 --- a/drivers/gpio/gpiolib-of.c +++ b/drivers/gpio/gpiolib-of.c @@ -721,9 +721,9 @@ struct gpio_desc *of_find_gpio(struct device_node *np, const char *con_id, return desc; } -int of_gpiochip_get_lflags(struct gpio_chip *chip, - struct fwnode_reference_args *gpiospec, - unsigned long *lflags) +struct gpio_desc *of_gpiochip_get_hog_desc(struct gpio_chip *chip, + struct fwnode_reference_args *gpiospec, + unsigned long *lflags) { enum of_gpio_flags xlate_flags = 0; struct of_phandle_args args; @@ -737,11 +737,11 @@ int of_gpiochip_get_lflags(struct gpio_chip *chip, desc = of_xlate_and_get_gpiod_flags(chip, &args, &xlate_flags); if (IS_ERR(desc)) - return PTR_ERR(desc); + return desc; *lflags = of_convert_gpio_flags(xlate_flags); - return 0; + return desc; } #ifdef CONFIG_OF_DYNAMIC diff --git a/drivers/gpio/gpiolib-of.h b/drivers/gpio/gpiolib-of.h index 9ca540d93f93be..347b82f9e3ff4d 100644 --- a/drivers/gpio/gpiolib-of.h +++ b/drivers/gpio/gpiolib-of.h @@ -25,9 +25,9 @@ int of_gpiochip_add(struct gpio_chip *gc); void of_gpiochip_remove(struct gpio_chip *gc); bool of_gpiochip_instance_match(struct gpio_chip *gc, unsigned int index); int of_gpio_count(const struct fwnode_handle *fwnode, const char *con_id); -int of_gpiochip_get_lflags(struct gpio_chip *chip, - struct fwnode_reference_args *gpiospec, - unsigned long *lflags); +struct gpio_desc *of_gpiochip_get_hog_desc(struct gpio_chip *chip, + struct fwnode_reference_args *gpiospec, + unsigned long *lflags); #else static inline struct gpio_desc *of_find_gpio(struct device_node *np, const char *con_id, @@ -48,11 +48,12 @@ static inline int of_gpio_count(const struct fwnode_handle *fwnode, { return -ENOENT; } -static inline int of_gpiochip_get_lflags(struct gpio_chip *chip, - struct fwnode_reference_args *gpiospec, - unsigned long *lflags) +static inline struct gpio_desc * +of_gpiochip_get_hog_desc(struct gpio_chip *chip, + struct fwnode_reference_args *gpiospec, + unsigned long *lflags) { - return -ENOENT; + return ERR_PTR(-ENOENT); } #endif /* CONFIG_OF_GPIO */ diff --git a/drivers/gpio/gpiolib-shared.c b/drivers/gpio/gpiolib-shared.c index edb04a5bb987e1..f34315a2059a2b 100644 --- a/drivers/gpio/gpiolib-shared.c +++ b/drivers/gpio/gpiolib-shared.c @@ -532,8 +532,7 @@ int gpiochip_setup_shared(struct gpio_chip *gc) * This is a shared GPIO proxy. Mark its * descriptor as such and return here. */ - __set_bit(GPIOD_FLAG_SHARED_PROXY, - &gdev->descs[0].flags); + set_bit(GPIOD_FLAG_SHARED_PROXY, &gdev->descs[0].flags); return 0; } } @@ -573,7 +572,7 @@ int gpiochip_setup_shared(struct gpio_chip *gc) desc = &gdev->descs[entry->offset]; - __set_bit(GPIOD_FLAG_SHARED, &desc->flags); + set_bit(GPIOD_FLAG_SHARED, &desc->flags); /* * Shared GPIOs are not requested via the normal path. Make * them inaccessible to anyone even before we register the diff --git a/drivers/gpio/gpiolib.c b/drivers/gpio/gpiolib.c index 033c6fce4fc8da..46a68a6b739f70 100644 --- a/drivers/gpio/gpiolib.c +++ b/drivers/gpio/gpiolib.c @@ -28,6 +28,7 @@ #include #include #include +#include #include #include @@ -489,8 +490,7 @@ int gpiod_get_direction(struct gpio_desc *desc) if (ret > 0) ret = 1; - assign_bit(GPIOD_FLAG_IS_OUT, &flags, !ret); - WRITE_ONCE(desc->flags, flags); + assign_bit(GPIOD_FLAG_IS_OUT, &desc->flags, !ret); return ret; } @@ -854,11 +854,22 @@ bool gpiochip_line_is_valid(const struct gpio_chip *gc, } EXPORT_SYMBOL_GPL(gpiochip_line_is_valid); -static void gpiod_free_irqs(struct gpio_desc *desc) +static void gpiod_free_irqs(struct gpio_chip *gc, struct gpio_desc *desc) { - int irq = gpiod_to_irq(desc); - struct irq_desc *irqd = irq_to_desc(irq); + struct irq_desc *irqd; void *cookie; + int irq; + + /* Called with gdev->chip already NULL, so gpiod_to_irq() can't be used. */ + if (!gc->to_irq) + return; + irq = gc->to_irq(gc, gpiod_hwgpio(desc)); + if (irq <= 0) + return; + + irqd = irq_to_desc(irq); + if (!irqd) + return; for (;;) { /* @@ -890,7 +901,7 @@ static void gpiochip_free_remaining_irqs(struct gpio_chip *gc) struct gpio_desc *desc; for_each_gpio_desc_with_flag(gc, desc, GPIOD_FLAG_USED_AS_IRQ) - gpiod_free_irqs(desc); + gpiod_free_irqs(gc, desc); } static void gpiodev_release(struct device *dev) @@ -898,9 +909,12 @@ static void gpiodev_release(struct device *dev) struct gpio_device *gdev = to_gpio_device(dev); /* Call pending kfree()s for descriptor labels. */ - synchronize_srcu(&gdev->desc_srcu); + srcu_barrier(&gdev->desc_srcu); cleanup_srcu_struct(&gdev->desc_srcu); + if (gdev->line_state_wq) + destroy_workqueue(gdev->line_state_wq); + ida_free(&gpio_ida, gdev->id); kfree_const(gdev->label); kfree(gdev->descs); @@ -1033,9 +1047,9 @@ int gpiochip_add_hog(struct gpio_chip *gc, struct fwnode_handle *fwnode) for (unsigned int j = 0; j < cells; j++) gpiospec.args[j] = gpios[i * cells + j]; - ret = of_gpiochip_get_lflags(gc, &gpiospec, &lflags); - if (ret) - return ret; + desc = of_gpiochip_get_hog_desc(gc, &gpiospec, &lflags); + if (IS_ERR(desc)) + return PTR_ERR(desc); /* * If no line-name property is present, fall back to the OF @@ -1051,11 +1065,11 @@ int gpiochip_add_hog(struct gpio_chip *gc, struct fwnode_handle *fwnode) */ if (cells > 1 && gpios[i * cells + 1]) lflags |= GPIO_ACTIVE_LOW; - } - desc = gpiochip_get_desc(gc, gpios[i * cells]); - if (IS_ERR(desc)) - return PTR_ERR(desc); + desc = gpiochip_get_desc(gc, gpios[i * cells]); + if (IS_ERR(desc)) + return PTR_ERR(desc); + } ret = gpiod_hog(desc, name, lflags, dflags); if (ret) @@ -1436,7 +1450,6 @@ void gpiochip_remove(struct gpio_chip *gc) /* FIXME: should the legacy sysfs handling be moved to gpio_device? */ gpiochip_sysfs_unregister(gc); gpiochip_free_hogs(gc); - gpiochip_free_remaining_irqs(gc); scoped_guard(mutex, &gpio_devices_lock) list_del_rcu(&gdev->list); @@ -1445,7 +1458,15 @@ void gpiochip_remove(struct gpio_chip *gc) /* Numb the device, cancelling all outstanding operations */ rcu_assign_pointer(gdev->chip, NULL); synchronize_srcu(&gdev->srcu); + + /* + * No new interrupts can be requested through the character device now. + * Have it free the ones it holds, also on the shared proxies, before + * forcibly freeing the rest and removing the irqchip. + */ + blocking_notifier_call_chain(&gdev->device_notifier, 0, NULL); gpio_device_teardown_shared(gdev); + gpiochip_free_remaining_irqs(gc); gpiochip_irqchip_remove(gc); acpi_gpiochip_remove(gc); of_gpiochip_remove(gc); @@ -2704,30 +2725,34 @@ void gpiod_free_commit(struct gpio_desc *desc) flags = READ_ONCE(desc->flags); - if (guard.gc && test_bit(GPIOD_FLAG_REQUESTED, &flags)) { + if (guard.gc && !test_bit(GPIOD_FLAG_REQUESTED, &flags)) + return; + + desc_set_label(desc, NULL); + + if (guard.gc) { if (guard.gc->free) guard.gc->free(guard.gc, gpiod_hwgpio(desc)); - clear_bit(GPIOD_FLAG_ACTIVE_LOW, &flags); - clear_bit(GPIOD_FLAG_REQUESTED, &flags); - clear_bit(GPIOD_FLAG_OPEN_DRAIN, &flags); - clear_bit(GPIOD_FLAG_OPEN_SOURCE, &flags); - clear_bit(GPIOD_FLAG_PULL_UP, &flags); - clear_bit(GPIOD_FLAG_PULL_DOWN, &flags); - 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); -#endif - desc_set_label(desc, NULL); - WRITE_ONCE(desc->flags, flags); #ifdef CONFIG_GPIO_CDEV WRITE_ONCE(desc->debounce_period_us, 0); #endif +#ifdef CONFIG_OF_DYNAMIC + WRITE_ONCE(desc->hog, NULL); +#endif + set_mask_bits(&desc->flags, + BIT(GPIOD_FLAG_ACTIVE_LOW) | + BIT(GPIOD_FLAG_REQUESTED) | + BIT(GPIOD_FLAG_OPEN_DRAIN) | + BIT(GPIOD_FLAG_OPEN_SOURCE) | + BIT(GPIOD_FLAG_PULL_UP) | + BIT(GPIOD_FLAG_PULL_DOWN) | + BIT(GPIOD_FLAG_BIAS_DISABLE) | + BIT(GPIOD_FLAG_EDGE_RISING) | + BIT(GPIOD_FLAG_EDGE_FALLING) | + BIT(GPIOD_FLAG_EVENT_CLOCK_REALTIME) | + BIT(GPIOD_FLAG_EVENT_CLOCK_HTE) | + BIT(GPIOD_FLAG_IS_HOGGED), 0); gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_RELEASED); } } @@ -3644,10 +3669,10 @@ int gpiod_get_array_value_complex(bool raw, bool can_sleep, int hwgpio = gpiod_hwgpio(desc); int value = test_bit(hwgpio, bits); + trace_gpio_value(desc_to_gpio(desc), 1, value); if (!raw && test_bit(GPIOD_FLAG_ACTIVE_LOW, &desc->flags)) value = !value; __assign_bit(j, value_bitmap, value); - trace_gpio_value(desc_to_gpio(desc), 1, value); j++; if (array_info) diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu.h b/drivers/gpu/drm/amd/amdgpu/amdgpu.h index c7577b608f3e41..32e4779ea9acbd 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu.h +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu.h @@ -1050,6 +1050,8 @@ int amdgpu_do_asic_reset(struct list_head *device_list_handle, int amdgpu_device_reinit_after_reset(struct amdgpu_reset_context *reset_context); +bool amdgpu_device_is_removable(struct amdgpu_device *adev); + int emu_soc_asic_init(struct amdgpu_device *adev); /* diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c index 1b79c9f182b1db..b5e96479118271 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c @@ -3009,7 +3009,8 @@ int amdgpu_amdkfd_gpuvm_restore_process_bos(void *info, struct dma_fence __rcu * struct drm_gem_object *gobj; gobj = &mem->bo->tbo.base; - ret = drm_exec_prepare_obj(&exec, gobj, 1); + ret = drm_exec_prepare_obj(&exec, gobj, + TTM_NUM_MOVE_FENCES + 1); drm_exec_retry_on_contention(&exec); if (unlikely(ret)) { pr_err("drm_exec_prepare_obj failed, ret: %d\n", ret); diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_atpx_handler.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_atpx_handler.c index e2a4644896ca8b..f9467786aab960 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_atpx_handler.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_atpx_handler.c @@ -45,6 +45,7 @@ struct amdgpu_atpx { static struct amdgpu_atpx_priv { bool atpx_detected; bool bridge_pm_usable; + bool handler_registered; unsigned int quirks; /* handle for device - and atpx */ acpi_handle dhandle; @@ -663,7 +664,8 @@ void amdgpu_register_atpx_handler(void) if (!r) return; - vga_switcheroo_register_handler(&amdgpu_atpx_handler, handler_flags); + if (!vga_switcheroo_register_handler(&amdgpu_atpx_handler, handler_flags)) + amdgpu_atpx_priv.handler_registered = true; } /** @@ -673,5 +675,14 @@ void amdgpu_register_atpx_handler(void) */ void amdgpu_unregister_atpx_handler(void) { + /* + * vga_switcheroo has a single handler slot and unregistering clears it + * no matter who set it, so leave a handler registered by another + * driver, such as apple-gmux, in place. + */ + if (!amdgpu_atpx_priv.handler_registered) + return; + vga_switcheroo_unregister_handler(); + amdgpu_atpx_priv.handler_registered = false; } diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_bios.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_bios.c index f9315e0472fe95..2603ca60996ad9 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_bios.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_bios.c @@ -369,7 +369,7 @@ static bool amdgpu_atrm_get_bios(struct amdgpu_device *adev) bool found = false; /* ATRM is for on-platform devices only */ - if (dev_is_removable(&adev->pdev->dev)) + if (amdgpu_device_is_removable(adev)) return false; while ((pdev = pci_get_base_class(PCI_BASE_CLASS_DISPLAY, pdev))) { @@ -436,35 +436,23 @@ static bool amdgpu_read_disabled_bios(struct amdgpu_device *adev) * VFCT entries contain the PCI bus number as recorded during BIOS POST. * On systems where the kernel renumbers PCI buses (e.g. pci=realloc or * resource conflicts), the runtime bus number may differ from the POST - * value. Match by device identity (vendor + device + function) and use - * the bus number as a preference: exact bus match is preferred, but when - * the bus numbers disagree we accept the entry if the device identity - * matches. + * value. Match against the secondary bus number of the upstream bridge + * at FW/OS handoff, which the PCI core caches before any renumbering. * - * Returns: 0 on match, -ENODEV on no match + * Returns: true if @vhdr describes this device, false otherwise */ -static int amdgpu_acpi_vfct_match(struct amdgpu_device *adev, - VFCT_IMAGE_HEADER *vhdr) +static bool amdgpu_acpi_vfct_match(struct amdgpu_device *adev, + VFCT_IMAGE_HEADER *vhdr) { - /* Vendor and device IDs must always match */ - if (vhdr->VendorID != adev->pdev->vendor || - vhdr->DeviceID != adev->pdev->device) - return -ENODEV; - - if (vhdr->PCIDevice != PCI_SLOT(adev->pdev->devfn) || - vhdr->PCIFunction != PCI_FUNC(adev->pdev->devfn)) - return -ENODEV; - - /* Exact bus number match - preferred */ - if (vhdr->PCIBus == adev->pdev->bus->number) - return 0; - - /* Bus mismatch but device identity matches (PCI renumbering case) */ - dev_notice(adev->dev, - "VFCT bus number mismatch: table %u != runtime %u, matching by device identity (vendor 0x%04x device 0x%04x)\n", - vhdr->PCIBus, adev->pdev->bus->number, - adev->pdev->vendor, adev->pdev->device); - return 0; + struct pci_dev *pdev = adev->pdev; + struct pci_dev *bridge = pci_upstream_bridge(pdev); + u8 bus = bridge ? bridge->fw_sec_busnr : pdev->bus->number; + + return vhdr->VendorID == pdev->vendor && + vhdr->DeviceID == pdev->device && + vhdr->PCIBus == bus && + vhdr->PCIDevice == PCI_SLOT(pdev->devfn) && + vhdr->PCIFunction == PCI_FUNC(pdev->devfn); } static bool amdgpu_acpi_vfct_bios(struct amdgpu_device *adev) @@ -503,7 +491,7 @@ static bool amdgpu_acpi_vfct_bios(struct amdgpu_device *adev) } if (vhdr->ImageLength && - !amdgpu_acpi_vfct_match(adev, vhdr)) { + amdgpu_acpi_vfct_match(adev, vhdr)) { adev->bios = kmemdup(&vbios->VbiosContent, vhdr->ImageLength, GFP_KERNEL); diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_device.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_device.c index 19a566187dfb56..ad4b6260bc6aa8 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_device.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_device.c @@ -617,8 +617,7 @@ void amdgpu_device_detect_runtime_pm_mode(struct amdgpu_device *adev) int bamaco_support; adev->pm.rpm_mode = AMDGPU_RUNPM_NONE; - if (pci_is_thunderbolt_attached(adev->pdev) || - dev_is_removable(&adev->pdev->dev)) { + if (amdgpu_device_is_removable(adev)) { dev_info(adev->dev, "Runtime PM disabled for externally attached device\n"); return; @@ -1286,6 +1285,16 @@ bool amdgpu_device_seamless_boot_supported(struct amdgpu_device *adev) return amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0); } +bool amdgpu_device_is_removable(struct amdgpu_device *adev) +{ + /* older TB systems don't set dev_is_removable so check both here */ + if (dev_is_removable(adev->dev) || + pci_is_thunderbolt_attached(adev->pdev)) + return true; + + return false; +} + #if IS_ENABLED(CONFIG_X86) static const struct x86_cpu_id amdgpu_pcie_dynamic_switching_quirks[] = { /* @@ -1308,8 +1317,8 @@ static const struct x86_cpu_id amdgpu_pcie_dynamic_switching_quirks[] = { static bool amdgpu_device_pcie_dynamic_switching_supported(struct amdgpu_device *adev) { - /* eGPU change speeds based on USB4 fabric conditions */ - if (dev_is_removable(adev->dev)) + /* eGPU change speeds based on USB4/TB fabric conditions */ + if (amdgpu_device_is_removable(adev)) return true; /* Hosts have problems with dynamic speed switching */ @@ -2075,7 +2084,7 @@ static int amdgpu_device_ip_early_init(struct amdgpu_device *adev) (amdgpu_is_atpx_hybrid() || amdgpu_has_atpx_dgpu_power_cntl()) && ((adev->flags & AMD_IS_APU) == 0) && - !dev_is_removable(&adev->pdev->dev)) + !amdgpu_device_is_removable(adev)) adev->flags |= AMD_IS_PX; if (!(adev->flags & AMD_IS_APU)) { @@ -2101,6 +2110,10 @@ static int amdgpu_device_ip_early_init(struct amdgpu_device *adev) amdgpu_ip_version((adev), GC_HWIP, 0) == IP_VERSION(9, 4, 4); } + /* Needs the register bases, and must be known before requesting firmware */ + if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) + amdgpu_psp_init_fw_variant(adev); + total = true; for (i = 0; i < adev->num_ip_blocks; i++) { ip_block = &adev->ip_blocks[i]; @@ -2781,9 +2794,9 @@ static int amdgpu_device_ip_late_init(struct amdgpu_device *adev) amdgpu_device_set_cg_state(adev, AMD_CG_STATE_GATE); amdgpu_device_set_pg_state(adev, AMD_PG_STATE_GATE); - r = amdgpu_dpm_reapply_umd_profile(adev); + r = amdgpu_dpm_reapply_performance_level(adev); if (r) { - dev_err(adev->dev, "Failed to restore UMD profile state: %d\n", r); + dev_err(adev->dev, "Failed to restore performance level: %d\n", r); return r; } @@ -3764,9 +3777,8 @@ static void amdgpu_device_sys_interface_fini(struct amdgpu_device *adev) static bool amdgpu_device_should_register_switcheroo(struct amdgpu_device *adev, bool px) { - return !pci_is_thunderbolt_attached(adev->pdev) && - (px || (!dev_is_removable(&adev->pdev->dev) && - apple_gmux_detect(NULL, NULL))); + return !amdgpu_device_is_removable(adev) && + (px || apple_gmux_detect(NULL, NULL)); } /** @@ -4072,6 +4084,9 @@ int amdgpu_device_init(struct amdgpu_device *adev, amdgpu_reset_method = AMD_RESET_METHOD_NONE; r = amdgpu_asic_reset(adev); amdgpu_reset_method = tmp; + /* Post again so that the PSP is ready before it is used */ + if (!r) + adev->has_hw_reset = true; } if (r) { diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_drv.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_drv.c index 3e5634de077f1a..e3b3a2eebd9547 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_drv.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_drv.c @@ -3221,7 +3221,7 @@ static int __init amdgpu_init(void) /* Ignore KFD init failures when CONFIG_HSA_AMD is not set. */ r = amdgpu_amdkfd_init(); if (r && r != -ENOENT) - goto error_fini_sync; + goto error_release_acpi; if (amdgpu_pp_feature_mask & PP_OVERDRIVE_MASK) { add_taint(TAINT_CPU_OUT_OF_SPEC, LOCKDEP_STILL_OK); @@ -3230,9 +3230,17 @@ static int __init amdgpu_init(void) } /* let modprobe override vga console setting */ - return pci_register_driver(&amdgpu_kms_pci_driver); + r = pci_register_driver(&amdgpu_kms_pci_driver); + if (r) + goto error_fini_kfd; + + return 0; -error_fini_sync: +error_fini_kfd: + amdgpu_amdkfd_fini(); +error_release_acpi: + amdgpu_acpi_release(); + amdgpu_unregister_atpx_handler(); amdgpu_sync_fini(); return r; } diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_fence.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_fence.c index bff2d38f3571ab..18e333e7ffd321 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_fence.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_fence.c @@ -745,7 +745,8 @@ void amdgpu_ring_set_fence_errors_and_reemit(struct amdgpu_ring *ring, return; } ring->reemit = true; - amdgpu_ring_alloc(ring, ring->ring_backup_entries_to_copy); + amdgpu_ring_alloc(ring, ring->ring_backup_entries_to_copy + + (seq - last_seq) * ring->funcs->align_mask); spin_lock_irqsave(&ring->fence_drv.lock, flags); do { last_seq++; @@ -778,6 +779,10 @@ void amdgpu_ring_set_fence_errors_and_reemit(struct amdgpu_ring *ring, amdgpu_ring_write(ring, ring->ring_backup[fence->backup_idx + i]); } + + /* A job fence ends a submission, pad it like commit did */ + if (fence->skip_ib_dw_end_offset) + amdgpu_ring_pad_to_align(ring); } rcu_read_unlock(); } while (last_seq != seq); diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_gem.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_gem.c index b190b6c9adf299..5c88544cd12007 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_gem.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_gem.c @@ -340,7 +340,7 @@ static void amdgpu_gem_object_close(struct drm_gem_object *obj, drm_exec_init(&exec, DRM_EXEC_IGNORE_DUPLICATES, 0); drm_exec_until_all_locked(&exec) { - r = drm_exec_prepare_obj(&exec, &bo->tbo.base, 1); + r = drm_exec_prepare_obj(&exec, &bo->tbo.base, 2); /* clear_freed + last_tlb_inv */ drm_exec_retry_on_contention(&exec); if (unlikely(r)) goto out_unlock; @@ -371,11 +371,14 @@ static void amdgpu_gem_object_close(struct drm_gem_object *obj, dev_err(adev->dev, "failed to clear page " "tables on GEM object close (%ld)\n", r); if (r || !fence) - goto out_unlock; + goto out_tlb; - amdgpu_bo_fence(bo, fence, true); + dma_resv_add_fence(bo->tbo.base.resv, fence, DMA_RESV_USAGE_BOOKKEEP); dma_fence_put(fence); +out_tlb: + dma_resv_add_fence(bo->tbo.base.resv, vm->last_tlb_inv, DMA_RESV_USAGE_BOOKKEEP); + out_unlock: if (r && !drm_dev_is_unplugged(adev_to_drm(adev))) dev_err(adev->dev, "leaking bo va (%ld)\n", r); @@ -501,6 +504,14 @@ int amdgpu_gem_create_ioctl(struct drm_device *dev, void *data, if (r) return r; + /* ttm_bo_init_reserved() + clear fence */ + r = dma_resv_reserve_fences(vm->root.bo->tbo.base.resv, + TTM_NUM_MOVE_FENCES + 1); + if (r) { + amdgpu_bo_unreserve(vm->root.bo); + return r; + } + resv = vm->root.bo->tbo.base.resv; } diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_gmc.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_gmc.c index efa0bc1e432abd..2172fe0ea8cf23 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_gmc.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_gmc.c @@ -1127,6 +1127,13 @@ void amdgpu_gmc_noretry_set(struct amdgpu_device *adev) gmc->noretry = 1; else gmc->noretry = (amdgpu_noretry == -1) ? noretry_default : amdgpu_noretry; + + /* XNACK cannot be enabled on GFX12.1, so keep noretry=1 */ + if (gc_ver == IP_VERSION(12, 1, 0)) { + if (amdgpu_noretry == 0) + dev_warn(adev->dev, "Unable to set noretry = 0 on GFX12.1. Keeping noretry = 1"); + gmc->noretry = 1; + } } void amdgpu_gmc_set_vm_fault_masks(struct amdgpu_device *adev, int hub_type, diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_kms.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_kms.c index 335c523592bfa3..d442a2d9639455 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_kms.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_kms.c @@ -474,7 +474,7 @@ static int amdgpu_hw_ip_info(struct amdgpu_device *adev, !adev->gfx.compute_ring[i].no_user_submission) ++num_rings; - if (!adev->sdma.disable_uq) { + if (!adev->gfx.disable_uq) { for (i = 0; i < AMDGPU_MES_MAX_COMPUTE_PIPES; i++) num_slots += hweight32(adev->mes.compute_hqd_mask[i]); } @@ -489,7 +489,7 @@ static int amdgpu_hw_ip_info(struct amdgpu_device *adev, !adev->sdma.instance[i].ring.no_user_submission) ++num_rings; - if (!adev->gfx.disable_uq) { + if (!adev->sdma.disable_uq) { for (i = 0; i < AMDGPU_MES_MAX_SDMA_PIPES; i++) num_slots += hweight32(adev->mes.sdma_hqd_mask[i]); } @@ -1688,6 +1688,7 @@ u32 amdgpu_get_vblank_counter_kms(struct drm_crtc *crtc) struct drm_device *dev = crtc->dev; unsigned int pipe = crtc->index; struct amdgpu_device *adev = drm_to_adev(dev); + bool locked = false; int vpos, hpos, stat; u32 count; @@ -1695,9 +1696,26 @@ u32 amdgpu_get_vblank_counter_kms(struct drm_crtc *crtc) DRM_ERROR("Invalid crtc %u\n", pipe); return -EINVAL; } - if (!down_read_trylock(&adev->reset_domain->sem)) - return drm_crtc_vblank_count(crtc); + /* + * A GPU reset is in progress and the display hardware cannot be read + * safely. Return the hardware counter value DRM already cached rather + * than the software vblank count: the core feeds this callback's + * result back into vblank->last, and a software count lives in a + * different numeric domain, which later trips + * drm_WARN_ON_ONCE(cur_vblank != vblank->last) in + * drm_update_vblank_count(). + * + * Only task context has to back off. Vblank interrupts only arrive + * while a CRTC is scanning out, so the interrupt path can read the + * hardware, and it has to keep counting: vblank waits that already + * sleep when a reset takes the semaphore never complete otherwise. + */ + if (in_task()) { + if (!down_read_trylock(&adev->reset_domain->sem)) + return drm_crtc_vblank_crtc(crtc)->last; + locked = true; + } /* The hw increments its frame counter at start of vsync, not at start * of vblank, as is required by DRM core vblank counter handling. @@ -1743,7 +1761,8 @@ u32 amdgpu_get_vblank_counter_kms(struct drm_crtc *crtc) DRM_DEBUG_VBL("NULL mode info! Returned count may be wrong.\n"); } - up_read(&adev->reset_domain->sem); + if (locked) + up_read(&adev->reset_domain->sem); return count; } diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_mes.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_mes.c index 384510c343cd13..db70bdd79a80ea 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_mes.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_mes.c @@ -997,6 +997,10 @@ int amdgpu_mes_rs64mem_setup_bitmaps(struct amdgpu_mes *mes) if (!mes->use_rs64mem || !mes->ctx_array_size_cpu_ptr) return 0; + /* Keep the slots live processes and queues hold across MES re-init. */ + if (mes->proc_ctx_bitmap && mes->gang_ctx_bitmap) + return 0; + /* * MES FW wrote the sizes to the GPU buffer: * ctx_array_size_cpu_ptr[0] = proc_ctx_array_size (N) diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_psp.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_psp.c index 82a2684dbd2e19..0ce1ff2b775070 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_psp.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_psp.c @@ -403,6 +403,26 @@ static uint64_t psp_get_runtime_db_header_pos(struct amdgpu_device *adev) return pos; } +/* + * Which firmware the platform needs, as reported by the PSP in C2PMSG_63: the + * signing scheme and whether this is a preproduction part. The defaults are kept if + * the ASIC doesn't report it or it can't be read. + */ +void amdgpu_psp_init_fw_variant(struct amdgpu_device *adev) +{ + if (amdgpu_sriov_vf(adev)) + return; + + switch (amdgpu_ip_version(adev, MP0_HWIP, 0)) { + case IP_VERSION(15, 0, 0): + case IP_VERSION(15, 0, 9): + psp_v15_0_0_get_fw_variant(adev); + break; + default: + break; + } +} + /* * Helper funciton to query psp runtime database entry * @@ -3934,6 +3954,16 @@ static int psp_load_smu_fw(struct psp_context *psp) static bool fw_load_skip_check(struct psp_context *psp, struct amdgpu_firmware_info *ucode) { + struct amdgpu_device *adev = psp->adev; + /* Keep IMU firmware loading enabled for APUs with GC IP 11.0.0-11.7.1. */ + if ((adev->flags & AMD_IS_APU) && + (amdgpu_ip_version(adev, GC_HWIP, 0) >= IP_VERSION(11, 0, 0) + && amdgpu_ip_version(adev, GC_HWIP, 0) <= IP_VERSION(11, 7, 1))) { + if (!ucode->fw && (ucode->ucode_id == AMDGPU_UCODE_ID_IMU_I || + ucode->ucode_id == AMDGPU_UCODE_ID_IMU_D)) + return false; + } + if (!ucode->fw || !ucode->ucode_size) return true; diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_psp.h b/drivers/gpu/drm/amd/amdgpu/amdgpu_psp.h index a4ec60f6c31702..7d8fc8eb2b125d 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_psp.h +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_psp.h @@ -631,6 +631,7 @@ int psp_ta_invoke(struct psp_context *psp, int psp_xgmi_initialize(struct psp_context *psp, bool set_extended_data, bool load_ta); bool psp_is_xgmi_ta_supported(struct psp_context *psp); +void amdgpu_psp_init_fw_variant(struct amdgpu_device *adev); int psp_xgmi_terminate(struct psp_context *psp); int psp_xgmi_invoke(struct psp_context *psp, uint32_t ta_cmd_id); int psp_xgmi_get_hive_id(struct psp_context *psp, uint64_t *hive_id); diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_ring.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_ring.c index 22773454131650..e64ee4eb11f6d2 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_ring.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_ring.c @@ -142,6 +142,22 @@ void amdgpu_ring_generic_pad_ib(struct amdgpu_ring *ring, struct amdgpu_ib *ib) } } +/** + * amdgpu_ring_pad_to_align - pad the ring to the fetch alignment + * @ring: amdgpu_ring structure holding ring information + */ +void amdgpu_ring_pad_to_align(struct amdgpu_ring *ring) +{ + u32 count; + + count = ring->funcs->align_mask + 1 - + (ring->wptr & ring->funcs->align_mask); + count &= ring->funcs->align_mask; + + if (count != 0) + ring->funcs->insert_nop(ring, count); +} + /** * amdgpu_ring_commit - tell the GPU to execute the new * commands on the ring buffer @@ -153,18 +169,11 @@ void amdgpu_ring_generic_pad_ib(struct amdgpu_ring *ring, struct amdgpu_ib *ib) */ void amdgpu_ring_commit(struct amdgpu_ring *ring) { - uint32_t count; - if (ring->count_dw < 0) drm_err(adev_to_drm(ring->adev), "writing more dwords to the ring than expected!\n"); /* We pad to match fetch size */ - count = ring->funcs->align_mask + 1 - - (ring->wptr & ring->funcs->align_mask); - count &= ring->funcs->align_mask; - - if (count != 0) - ring->funcs->insert_nop(ring, count); + amdgpu_ring_pad_to_align(ring); mb(); amdgpu_ring_set_wptr(ring); diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_ring.h b/drivers/gpu/drm/amd/amdgpu/amdgpu_ring.h index b2040f80b7f29d..6224a9f94826ae 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_ring.h +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_ring.h @@ -464,6 +464,7 @@ void amdgpu_ring_ib_on_emit_de(struct amdgpu_ring *ring); void amdgpu_ring_insert_nop(struct amdgpu_ring *ring, uint32_t count); void amdgpu_ring_generic_pad_ib(struct amdgpu_ring *ring, struct amdgpu_ib *ib); +void amdgpu_ring_pad_to_align(struct amdgpu_ring *ring); void amdgpu_ring_commit(struct amdgpu_ring *ring); void amdgpu_ring_undo(struct amdgpu_ring *ring); int amdgpu_ring_init(struct amdgpu_device *adev, struct amdgpu_ring *ring, diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_ttm.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_ttm.c index 0f86777250fc00..326abc9b7f6908 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_ttm.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_ttm.c @@ -2410,6 +2410,13 @@ void amdgpu_ttm_enable_buffer_funcs(struct amdgpu_device *adev) sdma_ip_version = amdgpu_ip_version(adev, SDMA0_HWIP, 0); if (sdma_ip_version == IP_VERSION(7, 0, 0) || sdma_ip_version == IP_VERSION(7, 0, 1)) num_move_entities = 1; + if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(9, 4, 1) || + amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(9, 4, 2) || + amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(9, 4, 3) || + amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(9, 4, 4) || + amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(9, 5, 0) || + amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(12, 1, 0)) + num_clear_entities = 1; adev->mman.clear_entities = kzalloc_objs(struct amdgpu_ttm_buffer_entity, num_clear_entities); @@ -2711,6 +2718,8 @@ int amdgpu_ttm_clear_buffer(struct amdgpu_ttm_buffer_entity *entity, amdgpu_res_next(&dst, cur_size); } + r = 0; + error: mutex_unlock(&entity->lock); *out_fence = fence; diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_ucode.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_ucode.c index d2ce526dd95cc0..1632eda91acd91 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_ucode.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_ucode.c @@ -1527,6 +1527,37 @@ void amdgpu_ucode_ip_version_decode(struct amdgpu_device *adev, int block_type, snprintf(ucode_prefix, len, "%s_%d_%d_%d", ip_name, maj, min, rev); } +/* Add the suffix of the firmware variant before the extension: foo.bin -> foo_l.bin */ +static int amdgpu_ucode_set_suffix(struct amdgpu_device *adev, char *fname) +{ + const char *suffix; + size_t base; + + switch (adev->firmware.sign_type) { + case AMDGPU_FW_SIGN_PREPROD: + suffix = "_p.bin"; + break; + case AMDGPU_FW_SIGN_ALT: + suffix = "_l.bin"; + break; + case AMDGPU_FW_SIGN_UNKNOWN: + drm_warn(adev_to_drm(adev), "Unknown firmware signing\n"); + return -EINVAL; + default: + /* Default variant: the name is unchanged */ + return 0; + } + + if (!strends(fname, ".bin")) + return -EINVAL; + + base = strlen(fname) - strlen(".bin"); + if (strscpy(fname + base, suffix, AMDGPU_UCODE_NAME_MAX - base) < 0) + return -EOVERFLOW; + + return 0; +} + /* * amdgpu_ucode_request - Fetch and validate amdgpu microcode * @@ -1555,6 +1586,10 @@ int amdgpu_ucode_request(struct amdgpu_device *adev, const struct firmware **fw, return -EOVERFLOW; } + r = amdgpu_ucode_set_suffix(adev, fname); + if (r) + return r; + if (required == AMDGPU_UCODE_REQUIRED) r = request_firmware(fw, fname, adev->dev); else { diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_ucode.h b/drivers/gpu/drm/amd/amdgpu/amdgpu_ucode.h index 35277b240f25a9..0b2d1bccb999c8 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_ucode.h +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_ucode.h @@ -571,6 +571,14 @@ enum amdgpu_firmware_load_type { AMDGPU_FW_LOAD_RLC_BACKDOOR_AUTO, }; +enum amdgpu_firmware_sign_type { + AMDGPU_FW_SIGN_DEFAULT = 0, + AMDGPU_FW_SIGN_ALT, + AMDGPU_FW_SIGN_PREPROD, + /* Unexpected combination of signing bits, default firmware may not work */ + AMDGPU_FW_SIGN_UNKNOWN, +}; + enum amdgpu_ucode_required { AMDGPU_UCODE_OPTIONAL, AMDGPU_UCODE_REQUIRED, @@ -606,6 +614,7 @@ struct amdgpu_firmware_info { struct amdgpu_firmware { struct amdgpu_firmware_info ucode[AMDGPU_UCODE_ID_MAXIMUM]; enum amdgpu_firmware_load_type load_type; + enum amdgpu_firmware_sign_type sign_type; struct amdgpu_bo *fw_buf; unsigned int fw_size; unsigned int max_ucodes; diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_vcn.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_vcn.c index 6c12d8aa3c7696..1df2725d31e0c9 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_vcn.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_vcn.c @@ -66,6 +66,8 @@ #define FIRMWARE_VCN5_0_1 "amdgpu/vcn_5_0_1.bin" #define FIRMWARE_VCN5_0_2 "amdgpu/vcn_5_0_2.bin" #define FIRMWARE_VCN5_3_0 "amdgpu/vcn_5_3_0.bin" +#define FIRMWARE_VCN5_3_0_ALT "amdgpu/vcn_5_3_0_l.bin" +#define FIRMWARE_VCN5_3_0_PREPROD "amdgpu/vcn_5_3_0_p.bin" MODULE_FIRMWARE(FIRMWARE_RAVEN); MODULE_FIRMWARE(FIRMWARE_PICASSO); @@ -95,6 +97,8 @@ MODULE_FIRMWARE(FIRMWARE_VCN5_0_0); MODULE_FIRMWARE(FIRMWARE_VCN5_0_1); MODULE_FIRMWARE(FIRMWARE_VCN5_0_2); MODULE_FIRMWARE(FIRMWARE_VCN5_3_0); +MODULE_FIRMWARE(FIRMWARE_VCN5_3_0_ALT); +MODULE_FIRMWARE(FIRMWARE_VCN5_3_0_PREPROD); static void amdgpu_vcn_idle_work_handler(struct work_struct *work); static void amdgpu_vcn_reg_dump_fini(struct amdgpu_device *adev); diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c index 82b9b2d5d0cf5e..45f0f6aca754c4 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c @@ -462,9 +462,13 @@ void amdgpu_vm_bo_base_init(struct amdgpu_vm_bo_base *base, int amdgpu_vm_lock_pd(struct amdgpu_vm *vm, struct drm_exec *exec, unsigned int num_fences) { - /* We need at least two fences for the VM PD/PT updates */ + /* + * One fence slot for clearing newly allocated PDs/PTs and PDE/PTE updates, + * another fence slots for TLB invalidation fences, TTM_NUM_MOVE_FENCES + * for validating PDs/PTs after eviction plus anything the caller requested. + */ return drm_exec_prepare_obj(exec, &vm->root.bo->tbo.base, - 2 + num_fences); + 2 + TTM_NUM_MOVE_FENCES + num_fences); } /** @@ -1323,6 +1327,7 @@ int amdgpu_vm_bo_update(struct amdgpu_device *adev, struct amdgpu_bo_va *bo_va, } } else if (!bo) { mem = NULL; + r = 0; /* PRT map operations don't need to sync to anything. */ @@ -2108,12 +2113,6 @@ int amdgpu_vm_bo_clear_mappings(struct amdgpu_device *adev, list_for_each_entry_safe(tmp, next, &removed, list) { amdgpu_vm_it_remove(tmp, &vm->va); list_del(&tmp->list); - - if (tmp->start < saddr) - tmp->start = saddr; - if (tmp->last > eaddr) - tmp->last = eaddr; - tmp->bo_va = NULL; list_add(&tmp->list, &vm->freed); trace_amdgpu_vm_bo_unmap(NULL, tmp); @@ -2695,7 +2694,7 @@ int amdgpu_vm_init(struct amdgpu_device *adev, struct amdgpu_vm *vm, error_free_root: amdgpu_vm_pt_free_root(adev, vm); - amdgpu_bo_unreserve(vm->root.bo); + amdgpu_bo_unreserve(root_bo); amdgpu_bo_unref(&root_bo); error_free_delayed: @@ -3103,7 +3102,7 @@ bool amdgpu_vm_handle_fault(struct amdgpu_device *adev, u32 pasid, drm_exec_fini(&exec); if (!svm_range_restore_pages(adev, pasid, vmid, - node_id, addr >> PAGE_SHIFT, ts, write_fault)) + node_id, addr, ts, write_fault)) return true; /* Re-acquire the VM lock, could be that the VM was freed in between. */ diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_vm_pt.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_vm_pt.c index c73eb416c0e26b..a6d389c08524fa 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_vm_pt.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_vm_pt.c @@ -346,6 +346,33 @@ static void amdgpu_vm_pt_next_dfs(struct amdgpu_device *adev, amdgpu_vm_pt_continue_dfs((start), (entry)); \ (entry) = (cursor).entry, amdgpu_vm_pt_next_dfs((adev), &(cursor))) +/* Return the flags used for cleared PDEs/PTES */ +static uint64_t amdgpu_vm_pt_clear_flags(struct amdgpu_device *adev, + struct amdgpu_vm *vm, + unsigned int level) +{ + uint64_t flags; + + if (adev->asic_type < CHIP_VEGA10) + return 0; + + if (level != AMDGPU_VM_PTB) { + uint64_t value = 0; + + flags = AMDGPU_PDE_PTE_FLAG(adev); + if (vm->is_npa) + flags |= adev->gmc.noretry_flags; + amdgpu_gmc_get_vm_pde(adev, level, &value, &flags); + } else if (vm->is_npa) { + flags = adev->gmc.noretry_flags; + } else { + /* Workaround for fault priority problem on GMC9 */ + flags = AMDGPU_PTE_EXECUTABLE | adev->gmc.init_pte_flags; + } + + return flags; +} + /** * amdgpu_vm_pt_clear - initially clear the PDs/PTs * @@ -366,10 +393,9 @@ int amdgpu_vm_pt_clear(struct amdgpu_device *adev, struct amdgpu_vm *vm, struct ttm_operation_ctx ctx = { true, false }; struct amdgpu_vm_update_params params; struct amdgpu_bo *ancestor = &vmbo->bo; - unsigned int entries; struct amdgpu_bo *bo = &vmbo->bo; - uint64_t value = 0, flags = 0; - uint64_t addr; + unsigned int entries; + uint64_t flags; int r, idx; /* Figure out our place in the hierarchy */ @@ -404,26 +430,8 @@ int amdgpu_vm_pt_clear(struct amdgpu_device *adev, struct amdgpu_vm *vm, if (r) goto exit; - addr = 0; - - if (adev->asic_type >= CHIP_VEGA10) { - if (level != AMDGPU_VM_PTB) { - if (vm->is_npa) - flags = adev->gmc.noretry_flags; - /* Handle leaf PDEs as PTEs */ - flags |= AMDGPU_PDE_PTE_FLAG(adev); - amdgpu_gmc_get_vm_pde(adev, level, - &value, &flags); - } else if (vm->is_npa) { - flags = adev->gmc.noretry_flags; - } else { - /* Workaround for fault priority problem on GMC9 */ - flags = AMDGPU_PTE_EXECUTABLE | adev->gmc.init_pte_flags; - } - } - - r = vm->update_funcs->update(¶ms, vmbo, addr, 0, entries, - value, flags); + flags = amdgpu_vm_pt_clear_flags(adev, vm, level); + r = vm->update_funcs->update(¶ms, vmbo, 0, 0, entries, 0, flags); if (r) goto exit; @@ -714,15 +722,9 @@ static void amdgpu_vm_pte_update_flags(struct amdgpu_vm_update_params *params, flags |= AMDGPU_PDE_PTE_FLAG(params->adev); amdgpu_gmc_get_vm_pde(adev, level, &addr, &flags); - } else if (adev->asic_type >= CHIP_VEGA10 && - !(flags & AMDGPU_PTE_VALID) && + } else if (!(flags & AMDGPU_PTE_VALID) && !(flags & AMDGPU_PTE_PRT_FLAG(params->adev))) { - - /* Workaround for fault priority problem on GMC9 and GFX12, - * EXECUTABLE for GMC9 fault priority and init_pte_flags - * (e.g. AMDGPU_PTE_IS_PTE on GFX12) - */ - flags |= AMDGPU_PTE_EXECUTABLE | adev->gmc.init_pte_flags; + flags |= amdgpu_vm_pt_clear_flags(adev, params->vm, level); } /* diff --git a/drivers/gpu/drm/amd/amdgpu/gfx_v11_0.c b/drivers/gpu/drm/amd/amdgpu/gfx_v11_0.c index 11388b6660379a..da4e1cf9ed630e 100644 --- a/drivers/gpu/drm/amd/amdgpu/gfx_v11_0.c +++ b/drivers/gpu/drm/amd/amdgpu/gfx_v11_0.c @@ -134,13 +134,29 @@ MODULE_FIRMWARE("amdgpu/gc_11_5_6_me.bin"); MODULE_FIRMWARE("amdgpu/gc_11_5_6_mec.bin"); MODULE_FIRMWARE("amdgpu/gc_11_5_6_rlc.bin"); MODULE_FIRMWARE("amdgpu/gc_11_7_0_pfp.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_0_pfp_l.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_0_pfp_p.bin"); MODULE_FIRMWARE("amdgpu/gc_11_7_0_me.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_0_me_l.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_0_me_p.bin"); MODULE_FIRMWARE("amdgpu/gc_11_7_0_mec.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_0_mec_l.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_0_mec_p.bin"); MODULE_FIRMWARE("amdgpu/gc_11_7_0_rlc.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_0_rlc_l.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_0_rlc_p.bin"); MODULE_FIRMWARE("amdgpu/gc_11_7_1_pfp.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_1_pfp_l.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_1_pfp_p.bin"); MODULE_FIRMWARE("amdgpu/gc_11_7_1_me.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_1_me_l.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_1_me_p.bin"); MODULE_FIRMWARE("amdgpu/gc_11_7_1_mec.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_1_mec_l.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_1_mec_p.bin"); MODULE_FIRMWARE("amdgpu/gc_11_7_1_rlc.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_1_rlc_l.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_1_rlc_p.bin"); static const struct amdgpu_hwip_reg_entry gc_reg_list_11_0[] = { SOC15_REG_ENTRY_STR(GC, 0, regGRBM_STATUS), diff --git a/drivers/gpu/drm/amd/amdgpu/gfx_v12_1.c b/drivers/gpu/drm/amd/amdgpu/gfx_v12_1.c index 58f5ff506dc4ec..16518b0abfe91a 100644 --- a/drivers/gpu/drm/amd/amdgpu/gfx_v12_1.c +++ b/drivers/gpu/drm/amd/amdgpu/gfx_v12_1.c @@ -1514,9 +1514,8 @@ static u32 gfx_v12_1_get_sh_mem_config(struct amdgpu_device *adev) { u32 sh_mem_config = DEFAULT_SH_MEM_CONFIG; - /* GC 12.1.0 A0 requires RETRY_DISABLE in SH_MEM_CONFIG. */ - if (SOC_V1_0_DIE_REV_XCD(adev->rev_id) == 0) - sh_mem_config |= 1 << SH_MEM_CONFIG__RETRY_DISABLE__SHIFT; + /* XNACK cannot be enabled for GFX12.1 */ + sh_mem_config |= 1 << SH_MEM_CONFIG__RETRY_DISABLE__SHIFT; return sh_mem_config; } @@ -1563,14 +1562,12 @@ static void gfx_v12_1_xcc_init_compute_vmid(struct amdgpu_device *adev, static void gfx_v12_1_xcc_xnack_set_chicken_bits(struct amdgpu_device *adev, int xcc_id) { - /* NOTE: COMPRESSION_ENABLE is used a chicken bit to enable/disable xcc xnack */ + /* NOTE: COMPRESSION_ENABLE is used as a chicken bit to enable/disable xcc xnack + * Since xnack retry is disabled for GFX12.1, set it to 0 unconditionally + */ mutex_lock(&adev->srbm_mutex); - if (!adev->gmc.noretry) { - WREG32_FIELD15_PREREG(GC, GET_INST(GC, xcc_id), - TCP_PERFCOUNTER_FILTER, COMPRESSION_ENABLE, 0x1); - } else - WREG32_FIELD15_PREREG(GC, GET_INST(GC, xcc_id), - TCP_PERFCOUNTER_FILTER, COMPRESSION_ENABLE, 0x0); + WREG32_FIELD15_PREREG(GC, GET_INST(GC, xcc_id), + TCP_PERFCOUNTER_FILTER, COMPRESSION_ENABLE, 0x0); mutex_unlock(&adev->srbm_mutex); } diff --git a/drivers/gpu/drm/amd/amdgpu/gfx_v9_0.c b/drivers/gpu/drm/amd/amdgpu/gfx_v9_0.c index 1678015ce5a970..67199f18ee4857 100644 --- a/drivers/gpu/drm/amd/amdgpu/gfx_v9_0.c +++ b/drivers/gpu/drm/amd/amdgpu/gfx_v9_0.c @@ -1369,6 +1369,9 @@ struct amdgpu_gfxoff_quirk { u8 revision; }; +/* Match any chip revision in amdgpu_gfxoff_quirk.revision */ +#define AMDGPU_GFXOFF_QUIRK_ANY_REV 0xff + static const struct amdgpu_gfxoff_quirk amdgpu_gfxoff_quirk_list[] = { /* https://bugzilla.kernel.org/show_bug.cgi?id=204689 */ { 0x1002, 0x15dd, 0x1002, 0x15dd, 0xc8 }, @@ -1378,6 +1381,7 @@ static const struct amdgpu_gfxoff_quirk amdgpu_gfxoff_quirk_list[] = { { 0x1002, 0x15dd, 0x1002, 0x15dd, 0xc6 }, /* Apple MacBook Pro (15-inch, 2019) Radeon Pro Vega 20 4 GB */ { 0x1002, 0x69af, 0x106b, 0x019a, 0xc0 }, + { 0x1002, 0x15d8, 0x17aa, 0x318f, AMDGPU_GFXOFF_QUIRK_ANY_REV }, /* https://bbs.openkylin.top/t/topic/171497 */ { 0x1002, 0x15d8, 0x19e5, 0x3e14, 0xc2 }, /* HP 705G4 DM with R5 2400G */ @@ -1394,7 +1398,8 @@ static bool gfx_v9_0_should_disable_gfxoff(struct pci_dev *pdev) pdev->device == p->chip_device && pdev->subsystem_vendor == p->subsys_vendor && pdev->subsystem_device == p->subsys_device && - pdev->revision == p->revision) { + (p->revision == AMDGPU_GFXOFF_QUIRK_ANY_REV || + pdev->revision == p->revision)) { return true; } ++p; @@ -4076,39 +4081,79 @@ static int gfx_v9_0_hw_init(struct amdgpu_ip_block *ip_block) return r; } -static void gfx_v9_0_deactivate_kcq_hqd(struct amdgpu_device *adev) +/* caller must hold srbm_mutex and have selected me/pipe/queue */ +static bool gfx_v9_0_deactivate_hqd(struct amdgpu_device *adev, + u32 me, u32 pipe, u32 queue) { - amdgpu_gfx_rlc_enter_safe_mode(adev, 0); - for (int i = 0; i < adev->gfx.num_compute_rings; i++) { - u32 tmp; - struct amdgpu_ring *ring = &adev->gfx.compute_ring[i]; + int j; - mutex_lock(&adev->srbm_mutex); - soc15_grbm_select(adev, ring->me, ring->pipe, ring->queue, 0, 0); - tmp = RREG32_SOC15(GC, 0, mmCP_HQD_ACTIVE); - /* disable the queue if it's active */ - if (tmp & CP_HQD_ACTIVE__ACTIVE_MASK) { - int j; - - WREG32_SOC15(GC, 0, mmCP_HQD_DEQUEUE_REQUEST, 1); - for (j = 0; j < adev->usec_timeout; j++) { - tmp = RREG32_SOC15(GC, 0, mmCP_HQD_ACTIVE); - if (!(tmp & CP_HQD_ACTIVE__ACTIVE_MASK)) - break; - udelay(1); - } - if (j == AMDGPU_MAX_USEC_TIMEOUT) { - DRM_DEBUG("comp_%u_%u_%u dequeue request failed.\n", - ring->me, ring->pipe, ring->queue); - /* Manual disable if dequeue request times out */ - WREG32_SOC15(GC, 0, mmCP_HQD_ACTIVE, 0); + /* disable the queue if it's active */ + if (!(RREG32_SOC15(GC, 0, mmCP_HQD_ACTIVE) & CP_HQD_ACTIVE__ACTIVE_MASK)) + return false; + + WREG32_SOC15(GC, 0, mmCP_HQD_DEQUEUE_REQUEST, 1); + for (j = 0; j < adev->usec_timeout; j++) { + if (!(RREG32_SOC15(GC, 0, mmCP_HQD_ACTIVE) & + CP_HQD_ACTIVE__ACTIVE_MASK)) + break; + udelay(1); + } + if (j == adev->usec_timeout) { + dev_dbg(adev->dev, "comp_%u_%u_%u dequeue request failed.\n", + me, pipe, queue); + /* Manual disable if dequeue request times out */ + WREG32_SOC15(GC, 0, mmCP_HQD_ACTIVE, 0); + } + WREG32_SOC15(GC, 0, mmCP_HQD_DEQUEUE_REQUEST, 0); + + return true; +} + +/* + * MODE2 does not reset the CP HQD registers on gfx9 APUs. Besides the KCQs, + * the HQDs owned by KFD (HIQ and the user queues mapped by the HWS) also stay + * active, because KFD cannot unmap/destroy them while the reset domain is + * locked. After MODE2 the MEC then resumes with stale HQDs and the HWS no + * longer answers (qcm fence timeout on the next KFD queue). Deactivate every + * active HQD of all MECs except the KIQ, which is reprogrammed on resume. + */ +static void gfx_v9_0_deactivate_all_hqd(struct amdgpu_device *adev) +{ + struct amdgpu_ring *kiq_ring = &adev->gfx.kiq[0].ring; + u64 kiq_mqd_addr = kiq_ring->mqd_gpu_addr & ~0x3ULL; + u32 me, pipe, queue, n = 0; + u64 mqd_addr; + + amdgpu_gfx_rlc_enter_safe_mode(adev, 0); + mutex_lock(&adev->srbm_mutex); + for (me = 1; me <= adev->gfx.mec.num_mec; me++) { + for (pipe = 0; pipe < adev->gfx.mec.num_pipe_per_mec; pipe++) { + for (queue = 0; queue < adev->gfx.mec.num_queue_per_pipe; + queue++) { + if (me == kiq_ring->me && pipe == kiq_ring->pipe && + queue == kiq_ring->queue) + continue; + soc15_grbm_select(adev, me, pipe, queue, 0, 0); + /* + * At least on Renoir the HQD registers of MEC2 + * pipes 2/3 read back as those of pipes 0/1, so + * the KIQ shows up a second time. Skip it by its + * MQD address instead of sending it a dequeue. + */ + mqd_addr = ((u64)RREG32_SOC15(GC, 0, mmCP_MQD_BASE_ADDR_HI) << 32) | + RREG32_SOC15(GC, 0, mmCP_MQD_BASE_ADDR); + if (mqd_addr == kiq_mqd_addr) + continue; + if (gfx_v9_0_deactivate_hqd(adev, me, pipe, queue)) + n++; } - WREG32_SOC15(GC, 0, mmCP_HQD_DEQUEUE_REQUEST, 0); } - soc15_grbm_select(adev, 0, 0, 0, 0, 0); - mutex_unlock(&adev->srbm_mutex); } + soc15_grbm_select(adev, 0, 0, 0, 0, 0); + mutex_unlock(&adev->srbm_mutex); amdgpu_gfx_rlc_exit_safe_mode(adev, 0); + + dev_dbg(adev->dev, "deactivated %u active compute HQDs before MODE2\n", n); } static int gfx_v9_0_hw_fini(struct amdgpu_ip_block *ip_block) @@ -4136,8 +4181,8 @@ static int gfx_v9_0_hw_fini(struct amdgpu_ip_block *ip_block) } if ((adev->flags & AMD_IS_APU) && amdgpu_in_reset(adev) && - amdgpu_asic_reset_method(adev) == AMD_RESET_METHOD_MODE2) - gfx_v9_0_deactivate_kcq_hqd(adev); + amdgpu_asic_reset_method(adev) == AMD_RESET_METHOD_MODE2) + gfx_v9_0_deactivate_all_hqd(adev); /* Use deinitialize sequence from CAIL when unbinding device from driver, * otherwise KIQ is hanging when binding back diff --git a/drivers/gpu/drm/amd/amdgpu/gfx_v9_4_2.c b/drivers/gpu/drm/amd/amdgpu/gfx_v9_4_2.c index 54bcb5fdca2421..66a389121ad41f 100644 --- a/drivers/gpu/drm/amd/amdgpu/gfx_v9_4_2.c +++ b/drivers/gpu/drm/amd/amdgpu/gfx_v9_4_2.c @@ -23,12 +23,14 @@ #include "amdgpu.h" #include "soc15.h" #include "soc15d.h" +#include "soc15_common.h" #include "gc/gc_9_4_2_offset.h" #include "gc/gc_9_4_2_sh_mask.h" #include "gfx_v9_0.h" #include "gfx_v9_4_2.h" +#include "gfx_v9_4_3.h" #include "amdgpu_ras.h" #include "amdgpu_gfx.h" @@ -716,56 +718,88 @@ static int gfx_v9_4_2_do_vgprs_init(struct amdgpu_device *adev) static int gfx_v9_clean_shaders(struct amdgpu_device *adev) { - int r; + int r = 0; /* CU_ID: 0~15, SIMD_ID: 0~3, WAVE_ID: 0 ~ 9 */ int wb_size = adev->gfx.config.max_shader_engines * CU_ID_MAX * SIMD_ID_MAX * WAVE_ID_MAX; struct amdgpu_ib wb_ib; + struct amdgpu_ring *ring; struct dma_fence *fence = NULL; + const struct soc15_reg_entry *init_regs; + u32 init_regs_size; u32 pattern = 0xa; + int xcc_id; - /* bail if the compute ring is not ready */ - if (!adev->gfx.compute_ring[0].sched.ready) + if (adev->gfx.disable_kq) { + dev_warn(adev->dev, "Cannot run shader cleaner with kernel queues disabled"); return 0; + } - /* allocate the write-back buffer from IB */ - memset(&wb_ib, 0, sizeof(wb_ib)); - r = amdgpu_ib_get(adev, NULL, (1 + wb_size) * sizeof(uint32_t), - AMDGPU_IB_POOL_DIRECT, &wb_ib); - if (r) { - dev_err(adev->dev, "failed to get ib (%d) for wb.\n", r); - return r; + /* gfx943+ has different register layout compared to gfx942.*/ + switch (amdgpu_ip_version(adev, GC_HWIP, 0)) { + case IP_VERSION(9, 4, 3): + case IP_VERSION(9, 4, 4): + case IP_VERSION(9, 5, 0): + init_regs = gfx_v9_4_3_fault_cleaner_init_regs; + init_regs_size = gfx_v9_4_3_fault_cleaner_init_regs_size; + break; + default: + init_regs = fault_cleaner_init_regs_aldebaran; + init_regs_size = ARRAY_SIZE(fault_cleaner_init_regs_aldebaran); + break; } - memset(wb_ib.ptr, 0, (1 + wb_size) * sizeof(uint32_t)); - r = gfx_v9_4_2_run_shader(adev, - &adev->gfx.compute_ring[0], - fault_cleaner_compute_shader_aldebaran, - sizeof(fault_cleaner_compute_shader_aldebaran), - fault_cleaner_init_regs_aldebaran, - ARRAY_SIZE(fault_cleaner_init_regs_aldebaran), - adev->gfx.cu_info.number * 32, - wb_ib.gpu_addr, pattern, &fence); + for_each_inst(xcc_id, adev->gfx.xcc_mask) { + ring = &adev->gfx.compute_ring[xcc_id * adev->gfx.num_compute_rings]; - if (r) { - dev_err(adev->dev, "failed to clear MI200\n"); - goto pro_end; - } + /* bail if the compute ring is not ready */ + if (!ring->sched.ready) + continue; - /* wait for the GPU to finish processing the IB */ - r = dma_fence_wait(fence, false); - if (r) - dev_err(adev->dev, "timeout to clear MI200\n"); + /* allocate the write-back buffer from IB */ + memset(&wb_ib, 0, sizeof(wb_ib)); + r = amdgpu_ib_get(adev, NULL, (1 + wb_size) * sizeof(uint32_t), + AMDGPU_IB_POOL_DIRECT, &wb_ib); + if (r) { + dev_err(adev->dev, "failed to get ib (%d) for wb.\n", r); + return r; + } + memset(wb_ib.ptr, 0, (1 + wb_size) * sizeof(uint32_t)); + + r = gfx_v9_4_2_run_shader(adev, + ring, + fault_cleaner_compute_shader_aldebaran, + sizeof(fault_cleaner_compute_shader_aldebaran), + init_regs, + init_regs_size, + adev->gfx.cu_info.number * SIMD_ID_MAX * WAVE_ID_MAX, + wb_ib.gpu_addr, pattern, &fence); + + if (r) { + dev_err(adev->dev, "failed to clear GPR on xcc %d\n", xcc_id); + goto pro_end; + } + + /* wait for the GPU to finish processing the IB */ + r = dma_fence_wait(fence, false); + if (r) + dev_err(adev->dev, "timeout to clear GPR on xcc %d\n", xcc_id); pro_end: - if (fence) - dma_fence_put(fence); - amdgpu_ib_free(&wb_ib, NULL); + if (fence) { + dma_fence_put(fence); + fence = NULL; + } + amdgpu_ib_free(&wb_ib, NULL); + + if (r) + break; + } if (r) - dev_dbg(adev->dev, "Clean GPR Failed\n"); + dev_dbg(adev->dev, "Clearing fault state failed\n"); else - dev_dbg(adev->dev, "Clean GPR Successfully\n"); + dev_dbg(adev->dev, "Fault state cleared Successfully\n"); return r; } diff --git a/drivers/gpu/drm/amd/amdgpu/gfx_v9_4_3.c b/drivers/gpu/drm/amd/amdgpu/gfx_v9_4_3.c index 01ed1701c781ac..968bf911542d63 100644 --- a/drivers/gpu/drm/amd/amdgpu/gfx_v9_4_3.c +++ b/drivers/gpu/drm/amd/amdgpu/gfx_v9_4_3.c @@ -163,6 +163,22 @@ static const struct amdgpu_hwip_reg_entry gc_cp_reg_list_9_4_3[] = { struct amdgpu_gfx_ras gfx_v9_4_3_ras; +const struct soc15_reg_entry gfx_v9_4_3_fault_cleaner_init_regs[] = { + { SOC15_REG_ENTRY(GC, 0, regCOMPUTE_RESOURCE_LIMITS), 0x000000000 }, + { SOC15_REG_ENTRY(GC, 0, regCOMPUTE_NUM_THREAD_X), 0x40 }, + { SOC15_REG_ENTRY(GC, 0, regCOMPUTE_NUM_THREAD_Y), 1 }, + { SOC15_REG_ENTRY(GC, 0, regCOMPUTE_NUM_THREAD_Z), 1 }, + { SOC15_REG_ENTRY(GC, 0, regCOMPUTE_PGM_RSRC1), 0x00af0000 }, + { SOC15_REG_ENTRY(GC, 0, regCOMPUTE_PGM_RSRC2), 0x000000c0 }, + { SOC15_REG_ENTRY(GC, 0, regCOMPUTE_PGM_RSRC3), 0x00000000 }, + { SOC15_REG_ENTRY(GC, 0, regCOMPUTE_STATIC_THREAD_MGMT_SE0), 0xffffffff }, + { SOC15_REG_ENTRY(GC, 0, regCOMPUTE_STATIC_THREAD_MGMT_SE1), 0xffffffff }, + { SOC15_REG_ENTRY(GC, 0, regCOMPUTE_STATIC_THREAD_MGMT_SE2), 0xffffffff }, + { SOC15_REG_ENTRY(GC, 0, regCOMPUTE_STATIC_THREAD_MGMT_SE3), 0xffffffff }, +}; + +const size_t gfx_v9_4_3_fault_cleaner_init_regs_size = ARRAY_SIZE(gfx_v9_4_3_fault_cleaner_init_regs); + static void gfx_v9_4_3_set_ring_funcs(struct amdgpu_device *adev); static void gfx_v9_4_3_set_irq_funcs(struct amdgpu_device *adev); static void gfx_v9_4_3_set_gds_init(struct amdgpu_device *adev); diff --git a/drivers/gpu/drm/amd/amdgpu/gfx_v9_4_3.h b/drivers/gpu/drm/amd/amdgpu/gfx_v9_4_3.h index 42d67ee0e7ef64..81f8805a1fbce2 100644 --- a/drivers/gpu/drm/amd/amdgpu/gfx_v9_4_3.h +++ b/drivers/gpu/drm/amd/amdgpu/gfx_v9_4_3.h @@ -28,4 +28,7 @@ extern const struct amdgpu_ip_block_version gfx_v9_4_3_ip_block; extern struct amdgpu_xcp_ip_funcs gfx_v9_4_3_xcp_funcs; +extern const struct soc15_reg_entry gfx_v9_4_3_fault_cleaner_init_regs[]; +extern const size_t gfx_v9_4_3_fault_cleaner_init_regs_size; + #endif /* __GFX_V9_4_3_H__ */ diff --git a/drivers/gpu/drm/amd/amdgpu/imu_v11_0.c b/drivers/gpu/drm/amd/amdgpu/imu_v11_0.c index 09dc01a425d131..3aef68c9891a9b 100644 --- a/drivers/gpu/drm/amd/amdgpu/imu_v11_0.c +++ b/drivers/gpu/drm/amd/amdgpu/imu_v11_0.c @@ -31,6 +31,8 @@ #include "gc/gc_11_0_0_offset.h" #include "gc/gc_11_0_0_sh_mask.h" +#define IMU_DATA_SIZE_BYTES 66304 + MODULE_FIRMWARE("amdgpu/gc_11_0_0_imu.bin"); MODULE_FIRMWARE("amdgpu/gc_11_0_0_imu_kicker.bin"); MODULE_FIRMWARE("amdgpu/gc_11_0_1_imu.bin"); @@ -44,7 +46,11 @@ MODULE_FIRMWARE("amdgpu/gc_11_5_3_imu.bin"); MODULE_FIRMWARE("amdgpu/gc_11_5_4_imu.bin"); MODULE_FIRMWARE("amdgpu/gc_11_5_6_imu.bin"); MODULE_FIRMWARE("amdgpu/gc_11_7_0_imu.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_0_imu_l.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_0_imu_p.bin"); MODULE_FIRMWARE("amdgpu/gc_11_7_1_imu.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_1_imu_l.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_1_imu_p.bin"); static int imu_v11_0_init_microcode(struct amdgpu_device *adev) { @@ -52,16 +58,35 @@ static int imu_v11_0_init_microcode(struct amdgpu_device *adev) int err; const struct imu_firmware_header_v1_0 *imu_hdr; struct amdgpu_firmware_info *info = NULL; + bool imu_in_ifwi; + enum amdgpu_ucode_required required; DRM_DEBUG("\n"); + /* On GFX 11 APUs, ASP loads the IFWI IMU ucode by default. */ + imu_in_ifwi = adev->firmware.load_type == AMDGPU_FW_LOAD_PSP && + (adev->flags & AMD_IS_APU); + required = imu_in_ifwi ? AMDGPU_UCODE_OPTIONAL : AMDGPU_UCODE_REQUIRED; + amdgpu_ucode_ip_version_decode(adev, GC_HWIP, ucode_prefix, sizeof(ucode_prefix)); if (amdgpu_is_kicker_fw(adev)) - err = amdgpu_ucode_request(adev, &adev->gfx.imu_fw, AMDGPU_UCODE_REQUIRED, + err = amdgpu_ucode_request(adev, &adev->gfx.imu_fw, required, "amdgpu/%s_imu_kicker.bin", ucode_prefix); else - err = amdgpu_ucode_request(adev, &adev->gfx.imu_fw, AMDGPU_UCODE_REQUIRED, + err = amdgpu_ucode_request(adev, &adev->gfx.imu_fw, required, "amdgpu/%s_imu.bin", ucode_prefix); + if (err == -ENODEV && imu_in_ifwi) { + info = &adev->firmware.ucode[AMDGPU_UCODE_ID_IMU_I]; + info->ucode_id = AMDGPU_UCODE_ID_IMU_I; + info->fw = adev->gfx.imu_fw; + info->ucode_size = IMU_DATA_SIZE_BYTES; + + info = &adev->firmware.ucode[AMDGPU_UCODE_ID_IMU_D]; + info->ucode_id = AMDGPU_UCODE_ID_IMU_D; + info->fw = adev->gfx.imu_fw; + info->ucode_size = IMU_DATA_SIZE_BYTES; + return 0; + } if (err) goto out; diff --git a/drivers/gpu/drm/amd/amdgpu/mes_v11_0.c b/drivers/gpu/drm/amd/amdgpu/mes_v11_0.c index 0895c29899d2be..c76a6c4e69992a 100644 --- a/drivers/gpu/drm/amd/amdgpu/mes_v11_0.c +++ b/drivers/gpu/drm/amd/amdgpu/mes_v11_0.c @@ -61,9 +61,17 @@ MODULE_FIRMWARE("amdgpu/gc_11_5_4_mes1.bin"); MODULE_FIRMWARE("amdgpu/gc_11_5_6_mes_2.bin"); MODULE_FIRMWARE("amdgpu/gc_11_5_6_mes1.bin"); MODULE_FIRMWARE("amdgpu/gc_11_7_0_mes_2.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_0_mes_2_l.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_0_mes_2_p.bin"); MODULE_FIRMWARE("amdgpu/gc_11_7_0_mes1.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_0_mes1_l.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_0_mes1_p.bin"); MODULE_FIRMWARE("amdgpu/gc_11_7_1_mes_2.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_1_mes_2_l.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_1_mes_2_p.bin"); MODULE_FIRMWARE("amdgpu/gc_11_7_1_mes1.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_1_mes1_l.bin"); +MODULE_FIRMWARE("amdgpu/gc_11_7_1_mes1_p.bin"); static int mes_v11_0_hw_init(struct amdgpu_ip_block *ip_block); static int mes_v11_0_hw_fini(struct amdgpu_ip_block *ip_block); diff --git a/drivers/gpu/drm/amd/amdgpu/nbio_v2_3.c b/drivers/gpu/drm/amd/amdgpu/nbio_v2_3.c index 04041b398781b4..3da92fb09495db 100644 --- a/drivers/gpu/drm/amd/amdgpu/nbio_v2_3.c +++ b/drivers/gpu/drm/amd/amdgpu/nbio_v2_3.c @@ -357,7 +357,7 @@ static void nbio_v2_3_enable_aspm(struct amdgpu_device *adev, data |= NAVI10_PCIE__LC_L0S_INACTIVITY_DEFAULT << PCIE_LC_CNTL__LC_L0S_INACTIVITY__SHIFT; - if (dev_is_removable(&adev->pdev->dev)) + if (amdgpu_device_is_removable(adev)) data |= NAVI10_PCIE__LC_L1_INACTIVITY_TBT_DEFAULT << PCIE_LC_CNTL__LC_L1_INACTIVITY__SHIFT; else data |= NAVI10_PCIE__LC_L1_INACTIVITY_DEFAULT << PCIE_LC_CNTL__LC_L1_INACTIVITY__SHIFT; @@ -476,7 +476,7 @@ static void nbio_v2_3_program_aspm(struct amdgpu_device *adev) def = data = RREG32_PCIE(smnPCIE_LC_CNTL); data |= NAVI10_PCIE__LC_L0S_INACTIVITY_DEFAULT << PCIE_LC_CNTL__LC_L0S_INACTIVITY__SHIFT; - if (dev_is_removable(&adev->pdev->dev)) + if (amdgpu_device_is_removable(adev)) data |= NAVI10_PCIE__LC_L1_INACTIVITY_TBT_DEFAULT << PCIE_LC_CNTL__LC_L1_INACTIVITY__SHIFT; else data |= NAVI10_PCIE__LC_L1_INACTIVITY_DEFAULT << PCIE_LC_CNTL__LC_L1_INACTIVITY__SHIFT; diff --git a/drivers/gpu/drm/amd/amdgpu/psp_v15_0.c b/drivers/gpu/drm/amd/amdgpu/psp_v15_0.c index abaa40b6def90d..94b3fce1bc70af 100644 --- a/drivers/gpu/drm/amd/amdgpu/psp_v15_0.c +++ b/drivers/gpu/drm/amd/amdgpu/psp_v15_0.c @@ -32,11 +32,19 @@ #include "mp/mp_15_0_0_sh_mask.h" MODULE_FIRMWARE("amdgpu/psp_15_0_0_toc.bin"); +MODULE_FIRMWARE("amdgpu/psp_15_0_0_toc_l.bin"); +MODULE_FIRMWARE("amdgpu/psp_15_0_0_toc_p.bin"); MODULE_FIRMWARE("amdgpu/psp_15_0_0_ta.bin"); +MODULE_FIRMWARE("amdgpu/psp_15_0_0_ta_l.bin"); +MODULE_FIRMWARE("amdgpu/psp_15_0_0_ta_p.bin"); MODULE_FIRMWARE("amdgpu/psp_15_0_5_toc.bin"); MODULE_FIRMWARE("amdgpu/psp_15_0_5_ta.bin"); MODULE_FIRMWARE("amdgpu/psp_15_0_9_toc.bin"); +MODULE_FIRMWARE("amdgpu/psp_15_0_9_toc_l.bin"); +MODULE_FIRMWARE("amdgpu/psp_15_0_9_toc_p.bin"); MODULE_FIRMWARE("amdgpu/psp_15_0_9_ta.bin"); +MODULE_FIRMWARE("amdgpu/psp_15_0_9_ta_l.bin"); +MODULE_FIRMWARE("amdgpu/psp_15_0_9_ta_p.bin"); #define regMPASP_PCRU0_MPASP_C2PMSG_64 0x4280 #define regMPASP_PCRU0_MPASP_C2PMSG_64_BASE_IDX 2 @@ -108,6 +116,45 @@ static int psp_v15_0_0_ring_stop(struct psp_context *psp, return ret; } +/* + * C2PMSG_63 bit 6: 0 = default firmware signing, 1 = alternative + * C2PMSG_63 bit 28: 0 = production part, 1 = preproduction part + */ +#define PSP_V15_0_0_FW_SIGN_ALT BIT(6) +#define PSP_V15_0_0_FW_PREPROD BIT(28) + +void psp_v15_0_0_get_fw_variant(struct amdgpu_device *adev) +{ + bool alt, preprod; + u32 val; + + if (!adev->reg_offset[MP0_HWIP][0]) + return; + + val = RREG32_SOC15(MP0, 0, regMPASP_SMN_C2PMSG_63); + if (val == 0xffffffff) { + drm_warn(adev_to_drm(adev), "Unable to access regMPASP_SMN_C2PMSG_63\n"); + return; + } + + alt = val & PSP_V15_0_0_FW_SIGN_ALT; + preprod = val & PSP_V15_0_0_FW_PREPROD; + + if (alt && preprod) { + adev->firmware.sign_type = AMDGPU_FW_SIGN_UNKNOWN; + return; + } + + if (preprod) + adev->firmware.sign_type = AMDGPU_FW_SIGN_PREPROD; + else if (alt) + adev->firmware.sign_type = AMDGPU_FW_SIGN_ALT; + + dev_info(adev->dev, "PSP firmware: %s signing, %s part (C2PMSG_63=0x%08x)\n", + alt ? "alternative" : "default", + preprod ? "preproduction" : "production", val); +} + static int psp_v15_0_0_ring_create(struct psp_context *psp, enum psp_ring_type ring_type) { diff --git a/drivers/gpu/drm/amd/amdgpu/psp_v15_0.h b/drivers/gpu/drm/amd/amdgpu/psp_v15_0.h index ebd612103526fc..081be8e8268bc1 100644 --- a/drivers/gpu/drm/amd/amdgpu/psp_v15_0.h +++ b/drivers/gpu/drm/amd/amdgpu/psp_v15_0.h @@ -26,5 +26,6 @@ #include "amdgpu_psp.h" void psp_v15_0_0_set_psp_funcs(struct psp_context *psp); +void psp_v15_0_0_get_fw_variant(struct amdgpu_device *adev); #endif diff --git a/drivers/gpu/drm/amd/amdgpu/sdma_v6_0.c b/drivers/gpu/drm/amd/amdgpu/sdma_v6_0.c index 4845588c4c2471..2586d49f1e940f 100644 --- a/drivers/gpu/drm/amd/amdgpu/sdma_v6_0.c +++ b/drivers/gpu/drm/amd/amdgpu/sdma_v6_0.c @@ -56,6 +56,8 @@ MODULE_FIRMWARE("amdgpu/sdma_6_1_1.bin"); MODULE_FIRMWARE("amdgpu/sdma_6_1_2.bin"); MODULE_FIRMWARE("amdgpu/sdma_6_1_3.bin"); MODULE_FIRMWARE("amdgpu/sdma_6_1_4.bin"); +MODULE_FIRMWARE("amdgpu/sdma_6_1_4_l.bin"); +MODULE_FIRMWARE("amdgpu/sdma_6_1_4_p.bin"); MODULE_FIRMWARE("amdgpu/sdma_6_4_0.bin"); #define SDMA1_REG_OFFSET 0x600 diff --git a/drivers/gpu/drm/amd/amdgpu/vpe_v2_0.c b/drivers/gpu/drm/amd/amdgpu/vpe_v2_0.c index c92c5fc59aeb96..9367ffe0c7ad0d 100644 --- a/drivers/gpu/drm/amd/amdgpu/vpe_v2_0.c +++ b/drivers/gpu/drm/amd/amdgpu/vpe_v2_0.c @@ -31,9 +31,12 @@ #include "vpe/vpe_2_0_0_sh_mask.h" MODULE_FIRMWARE("amdgpu/vpe_2_0_0.bin"); +MODULE_FIRMWARE("amdgpu/vpe_2_0_0_l.bin"); +MODULE_FIRMWARE("amdgpu/vpe_2_0_0_p.bin"); MODULE_FIRMWARE("amdgpu/vpe_2_2_0.bin"); #define VPE_THREAD1_UCODE_OFFSET 0x8000 +#define regVPEC_F32_CNTL_DEFAULT 0x08084001 static uint32_t vpe_v2_0_get_reg_offset(struct amdgpu_vpe *vpe, uint32_t inst, uint32_t offset) { @@ -80,7 +83,7 @@ static int vpe_v2_0_load_microcode(struct amdgpu_vpe *vpe) if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) { f32_offset = vpe_get_reg_offset(vpe, 0, regVPEC_F32_CNTL); - f32_cntl = RREG32(f32_offset); + f32_cntl = regVPEC_F32_CNTL_DEFAULT; f32_cntl = REG_SET_FIELD(f32_cntl, VPEC_F32_CNTL, HALT, 0); f32_cntl = REG_SET_FIELD(f32_cntl, VPEC_F32_CNTL, TH1_RESET, 0); diff --git a/drivers/gpu/drm/amd/amdgpu/vpe_v3_0.c b/drivers/gpu/drm/amd/amdgpu/vpe_v3_0.c index 9077ae138d2a36..ca3b27e762517a 100644 --- a/drivers/gpu/drm/amd/amdgpu/vpe_v3_0.c +++ b/drivers/gpu/drm/amd/amdgpu/vpe_v3_0.c @@ -34,6 +34,7 @@ MODULE_FIRMWARE("amdgpu/vpe_3_0_0.bin"); MODULE_FIRMWARE("amdgpu/vpe_3_0_1.bin"); #define VPE_THREAD1_UCODE_OFFSET 0x8000 +#define regVPEC_F32_CNTL_DEFAULT 0x08084001 static uint32_t vpe_v3_0_get_reg_offset(struct amdgpu_vpe *vpe, uint32_t inst, uint32_t offset) { @@ -80,7 +81,7 @@ static int vpe_v3_0_load_microcode(struct amdgpu_vpe *vpe) if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) { f32_offset = vpe_get_reg_offset(vpe, 0, regVPEC_F32_CNTL); - f32_cntl = RREG32(f32_offset); + f32_cntl = regVPEC_F32_CNTL_DEFAULT; f32_cntl = REG_SET_FIELD(f32_cntl, VPEC_F32_CNTL, HALT, 0); f32_cntl = REG_SET_FIELD(f32_cntl, VPEC_F32_CNTL, TH1_RESET, 0); diff --git a/drivers/gpu/drm/amd/amdgpu/vpe_v6_1.c b/drivers/gpu/drm/amd/amdgpu/vpe_v6_1.c index 45876883bbf373..c758f7385fac61 100644 --- a/drivers/gpu/drm/amd/amdgpu/vpe_v6_1.c +++ b/drivers/gpu/drm/amd/amdgpu/vpe_v6_1.c @@ -61,6 +61,8 @@ MODULE_FIRMWARE("amdgpu/vpe_6_1_3.bin"); #define regVPEC_PUB_DUMMY2_6_1_1 0x004c #define regVPEC_PUB_DUMMY2_6_1_1_BASE_IDX 0 +#define regVPEC_F32_CNTL_DEFAULT 0x08084001 + static uint32_t vpe_v6_1_get_reg_offset(struct amdgpu_vpe *vpe, uint32_t inst, uint32_t offset) { uint32_t base; @@ -159,7 +161,7 @@ static int vpe_v6_1_load_microcode(struct amdgpu_vpe *vpe) uint32_t f32_offset, f32_cntl; f32_offset = vpe_get_reg_offset(vpe, 0, regVPEC_F32_CNTL); - f32_cntl = RREG32(f32_offset); + f32_cntl = regVPEC_F32_CNTL_DEFAULT; f32_cntl = REG_SET_FIELD(f32_cntl, VPEC_F32_CNTL, HALT, 0); f32_cntl = REG_SET_FIELD(f32_cntl, VPEC_F32_CNTL, TH1_RESET, 0); diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_debug.c b/drivers/gpu/drm/amd/amdkfd/kfd_debug.c index 0dd1fd448059bb..2296ad1a532ee5 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_debug.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_debug.c @@ -143,7 +143,9 @@ bool kfd_dbg_ev_raise(uint64_t event_mask, exception_data, exception_data_size, GFP_KERNEL); - if (!pdd->vm_fault_exc_data) + if (pdd->vm_fault_exc_data) + pdd->vm_fault_exc_data_size = exception_data_size; + else pr_debug("Failed to allocate exception data memory"); } else { pr_debug("Debugger exception data not saved\n"); diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c b/drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c index 61480e9119b8fa..4881684ed88fd1 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c @@ -1534,9 +1534,12 @@ static int clean_process_queues_cpsch(struct device_queue_manager *dqm, int retval = 0; dqm_lock(dqm); - if (qpd->evicted++ > 0) /* already evicted, do nothing */ + if (qpd->fault_cleaned) goto out; + qpd->evicted++; + qpd->fault_cleaned = true; + pdd = qpd_to_pdd(qpd); /* The debugger creates processes that temporarily have not acquired diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager_v12_1.c b/drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager_v12_1.c index 52598937137823..63ba13a60b9823 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager_v12_1.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager_v12_1.c @@ -54,7 +54,6 @@ static int update_qpd_v12_1(struct device_queue_manager *dqm, struct kfd_process_device *pdd; struct amdgpu_device *adev = dqm->dev->adev; struct amdgpu_vmhub *hub = &adev->vmhub[AMDGPU_GFXHUB(0)]; - bool xnack_enabled; pdd = qpd_to_pdd(qpd); qpd->vm_cntx_cntl = hub->vm_cntx_cntl; @@ -72,19 +71,10 @@ static int update_qpd_v12_1(struct device_queue_manager *dqm, qpd->sh_mem_ape1_base = 0; } - xnack_enabled = KFD_SUPPORT_XNACK_PER_PROCESS(dqm->dev) ? - pdd->process->xnack_enabled : - !pdd->dev->kfd->noretry; - - if (!xnack_enabled) { - qpd->sh_mem_config |= 1 << SH_MEM_CONFIG__RETRY_DISABLE__SHIFT; - qpd->vm_cntx_cntl &= - ~(1 << GCVM_CONTEXT0_CNTL__RETRY_PERMISSION_OR_INVALID_PAGE_FAULT__SHIFT); - } else { - qpd->sh_mem_config &= ~(1 << SH_MEM_CONFIG__RETRY_DISABLE__SHIFT); - qpd->vm_cntx_cntl |= - (1 << GCVM_CONTEXT0_CNTL__RETRY_PERMISSION_OR_INVALID_PAGE_FAULT__SHIFT); - } + /* XNACK cannot be enabled for gfx12.1 */ + qpd->sh_mem_config |= 1 << SH_MEM_CONFIG__RETRY_DISABLE__SHIFT; + qpd->vm_cntx_cntl &= + ~(1 << GCVM_CONTEXT0_CNTL__RETRY_PERMISSION_OR_INVALID_PAGE_FAULT__SHIFT); qpd->sh_mem_bases = compute_sh_mem_bases_64bit(pdd); diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_int_process_v9.c b/drivers/gpu/drm/amd/amdkfd/kfd_int_process_v9.c index 2ae1129fea55e7..1b597fab53957c 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_int_process_v9.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_int_process_v9.c @@ -370,7 +370,7 @@ static void gfx_9_clean_fault(uint16_t pasid) if (!pdd) return; - /* To Clean the GFX on the faulting device */ + /* To clean the GFX fault state on the faulting device */ dqm = pdd->dev->dqm; dqm->ops.clean_process_queues_cpsch(dqm, &pdd->qpd); diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_migrate.c b/drivers/gpu/drm/amd/amdkfd/kfd_migrate.c index 1eb92ac6eb058c..18652ecc0eb9fa 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_migrate.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_migrate.c @@ -504,14 +504,13 @@ svm_migrate_vma_to_vram(struct kfd_node *node, struct svm_range *prange, migrate_vma_pages(&migrate); svm_migrate_copy_done(adev, mfence); + svm_range_dma_unmap_dev(adev->dev, scratch, 0, npages); migrate_vma_finalize(&migrate); mpages = svm_migrate_successful_pages(&migrate); pr_debug("migrated/collected/requested 0x%lx/0x%lx/0x%lx\n", mpages, cpages, migrate.npages); - svm_range_dma_unmap_dev(adev->dev, scratch, 0, npages); - out_free: kvfree(buf); kfd_smi_event_migration_end(node, p->lead_thread, @@ -726,6 +725,17 @@ svm_migrate_copy_to_ram(struct amdgpu_device *adev, struct svm_range *prange, put_page(dpage); } + /* + * Copies queued before the failure may still be writing into + * the destination pages. Wait for the last SDMA fence (copies + * on the entity complete in order), then remove the device DMA + * mappings, before the pages go back to the allocator. + */ + if (*mfence) { + dma_fence_wait(*mfence, false); + dma_fence_put(*mfence); + } + /* release previous allocated sys pages and unmap dma address */ while (i--) { @@ -835,11 +845,12 @@ svm_migrate_vma_to_ram(struct kfd_node *node, struct svm_range *prange, pr_debug("migrated/collected/requested 0x%lx/0x%lx/0x%lx\n", mpages, cpages, migrate.npages); - svm_migrate_copy_done(adev, mfence); + if (!r) { + svm_migrate_copy_done(adev, mfence); + svm_range_dma_unmap_dev(adev->dev, scratch, 0, npages); + } migrate_vma_finalize(&migrate); - svm_range_dma_unmap_dev(adev->dev, scratch, 0, npages); - out_free: kvfree(buf); kfd_smi_event_migration_end(node, p->lead_thread, diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_priv.h b/drivers/gpu/drm/amd/amdkfd/kfd_priv.h index 436160549386d6..70d67f9d8cd757 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_priv.h +++ b/drivers/gpu/drm/amd/amdkfd/kfd_priv.h @@ -695,6 +695,11 @@ struct qcm_process_device { bool is_debug; unsigned int evicted; /* eviction counter, 0=active */ + /* Set after fault clean runs; never cleared. + * Prevents redundant cleaning from pipelined interrupt workers. + */ + bool fault_cleaned; + /* This flag tells if we should reset all wavefronts on * process termination */ @@ -906,6 +911,8 @@ struct svm_range_list { struct list_head deferred_range_list; struct list_head criu_svm_metadata_list; spinlock_t deferred_list_lock; + /* serializes XNACK-off evictions with the queue quiesce */ + struct mutex evict_lock; atomic_t evicted_ranges; atomic_t drain_pagefaults; struct delayed_work restore_work; @@ -1077,7 +1084,7 @@ struct kfd_process { #define KFD_PROCESS_TABLE_SIZE 8 /* bits: 256 entries */ #define KFD_CONTEXT_ID_PRIMARY 0xFFFF -#define KFD_CONTEXT_ID_MIN 0 +#define KFD_CONTEXT_ID_MIN 1 extern DECLARE_HASHTABLE(kfd_processes_table, KFD_PROCESS_TABLE_SIZE); extern struct srcu_struct kfd_processes_srcu; diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_process.c b/drivers/gpu/drm/amd/amdkfd/kfd_process.c index 6663718fb83ce3..336c66d9c5a730 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_process.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_process.c @@ -950,7 +950,8 @@ static void kfd_process_free_id(struct kfd_process *process) { struct kfd_process *primary_process; - if (process->context_id == KFD_CONTEXT_ID_PRIMARY) + if (process->context_id == KFD_CONTEXT_ID_PRIMARY || + process->context_id < KFD_CONTEXT_ID_MIN) return; primary_process = kfd_lookup_process_by_mm(process->lead_thread->mm); @@ -1235,6 +1236,7 @@ static void kfd_process_destroy_pdds(struct kfd_process *p) atomic_dec(&pdd->dev->kfd->kfd_processes_count); mutex_destroy(&pdd->doorbell_mutex); + kfree(pdd->vm_fault_exc_data); kfree(pdd); p->pdds[i] = NULL; } @@ -1536,7 +1538,12 @@ static int kfd_process_device_init_cwsr_dgpu(struct kfd_process_device *pdd) if (!dev->kfd->cwsr_enabled || !iosys_map_is_null(&qpd->cwsr_map) || !qpd->cwsr_base) return 0; - if (KFD_GC_VERSION(dev) >= IP_VERSION(9, 4, 2) && !dev->adev->apu_prefer_gtt) + if ((KFD_GC_VERSION(dev) == IP_VERSION(9, 4, 2) || + KFD_GC_VERSION(dev) == IP_VERSION(9, 4, 3) || + KFD_GC_VERSION(dev) == IP_VERSION(9, 4, 4) || + KFD_GC_VERSION(dev) == IP_VERSION(9, 5, 0) || + KFD_GC_VERSION(dev) == IP_VERSION(12, 1, 0)) && + !dev->adev->apu_prefer_gtt) flags |= KFD_IOC_ALLOC_MEM_FLAGS_VRAM; else flags |= KFD_IOC_ALLOC_MEM_FLAGS_GTT; @@ -1687,6 +1694,11 @@ struct kfd_process *create_process(const struct task_struct *thread, bool primar mutex_init(&process->mutex); process->mm = thread->mm; process->lead_thread = thread->group_leader; + /* + * Take the reference on the lead thread before the process can be + * released through kfd_process_wq_release(), which drops it again. + */ + get_task_struct(process->lead_thread); process->n_pdds = 0; process->queues_paused = false; @@ -1736,13 +1748,17 @@ struct kfd_process *create_process(const struct task_struct *thread, bool primar */ if (primary) { process->context_id = KFD_CONTEXT_ID_PRIMARY; + /* + * Must be initialized before the process can be given to + * kfd_process_wq_release(), which destroys it. + */ + ida_init(&process->id_table); mn = mmu_notifier_get(&kfd_process_mmu_notifier_ops, process->mm); if (IS_ERR(mn)) { err = PTR_ERR(mn); goto err_register_notifier; } BUG_ON(mn != &process->mmu_notifier); - ida_init(&process->id_table); } err = kfd_process_alloc_id(process); @@ -1752,17 +1768,46 @@ struct kfd_process *create_process(const struct task_struct *thread, bool primar } kfd_unref_process(process); - get_task_struct(process->lead_thread); INIT_WORK(&process->debug_event_workarea, debug_event_write_work_handler); return process; err_alloc_id: - kfd_process_free_id(process); err_register_notifier: + /* + * The process is already in kfd_processes_table, so find_process() + * may have handed it out with a reference taken on it. Unlink it + * and wait for the readers that are still walking the table before + * dropping the references held here: afterwards no new reference + * can be taken and the ones already taken keep the process alive. + * The memory is then freed by kfd_process_wq_release() when the + * last reference is dropped. + */ hash_del_rcu(&process->kfd_processes); - svm_range_list_fini(process); + synchronize_srcu(&kfd_processes_srcu); + + /* + * kfd_process_wq_release() frees the memory, but it does not + * destroy the queue manager: on the normal path that is done by + * kfd_process_notifier_release_internal(), which neither of these + * two error paths can reach, because no mmu notifier was + * registered for the process. The process is unlinked and no + * reader can reach the pqm any more, so destroy it here, before + * the references are dropped. + */ + pqm_uninit(&process->pqm); + + /* + * Drop the reference that keeps a failing free_notifier() from + * starting kfd_process_wq_release() and the one taken by + * kref_init(). + */ + kfd_unref_process(process); + kfd_unref_process(process); + + return ERR_PTR(err); + err_init_svm_range_list: kfd_process_free_outstanding_kfd_bos(process); kfd_process_destroy_pdds(process); @@ -1772,6 +1817,7 @@ struct kfd_process *create_process(const struct task_struct *thread, bool primar kfd_event_free_process(process); err_event_init: mutex_destroy(&process->mutex); + put_task_struct(process->lead_thread); kfree(process); err_alloc_process: return ERR_PTR(err); diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c b/drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c index b68e884b1c37a0..2b86d359c40653 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c @@ -1041,7 +1041,8 @@ int kfd_criu_restore_queue(struct kfd_process *p, goto exit; } - if (q_data->mqd_size != mqd_size_from_queue_type(pdd->dev->dqm, q_data->type)) { + if (q_data->mqd_size != mqd_size_from_queue_type(pdd->dev->dqm, q_data->type) * + NUM_XCC(pdd->dev->xcc_mask)) { ret = -EINVAL; goto exit; } diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_svm.c b/drivers/gpu/drm/amd/amdkfd/kfd_svm.c index 7fd331612f08cd..4df16176e2c342 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_svm.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_svm.c @@ -1008,7 +1008,7 @@ svm_range_split_array(void *ppnew, void *ppold, size_t size, kvfree(new); return -ENOMEM; } - kvfree(pold); + /* The caller frees pold once all arrays of the range are split */ *(void **)ppold = old; *(void **)ppnew = new; @@ -1019,19 +1019,36 @@ static int svm_range_split_pages(struct svm_range *new, struct svm_range *old, uint64_t start, uint64_t last) { + dma_addr_t *old_dma[MAX_GPU_INSTANCE]; uint64_t npages = last - start + 1; bool has_dma_addr = false; int i, r; + /* + * Split the arrays of all GPUs before replacing any of them, the old + * range must stay intact if one fails. + */ for (i = 0; i < MAX_GPU_INSTANCE; i++) { + old_dma[i] = old->dma_addr[i]; if (old->dma_addr[i]) has_dma_addr = true; - r = svm_range_split_array(&new->dma_addr[i], &old->dma_addr[i], + r = svm_range_split_array(&new->dma_addr[i], &old_dma[i], sizeof(*old->dma_addr[i]), old->start, npages, new->start, new->npages, old->actual_loc ? &new->vram_pages : NULL); - if (r) + if (r) { + /* new->dma_addr[] goes with the new range */ + while (i--) + if (old_dma[i] != old->dma_addr[i]) + kvfree(old_dma[i]); return r; + } + } + for (i = 0; i < MAX_GPU_INSTANCE; i++) { + if (old_dma[i] == old->dma_addr[i]) + continue; + kvfree(old->dma_addr[i]); + old->dma_addr[i] = old_dma[i]; } if (old->actual_loc) { /* @@ -1854,8 +1871,8 @@ static int svm_range_validate_and_map(struct mm_struct *mm, svm_range_lock(prange); if (vma->vm_flags & VM_WRITE) pr_debug("VM_WRITE without VM_READ is not supported"); - s = max(start, prange->start); - e = min(end, prange->last); + s = max(addr >> PAGE_SHIFT, prange->start); + e = min((next >> PAGE_SHIFT) - 1, prange->last); if (e >= s) r = svm_range_unmap_from_gpus(prange, s, e, prange->bitmap_mapped, @@ -1892,11 +1909,12 @@ static int svm_range_validate_and_map(struct mm_struct *mm, svm_range_lock(prange); - /* Free backing memory of hmm_range if it was initialized - * Override return value to TRY AGAIN only if prior returns - * were successful + /* + * Retry if the pages were invalidated after they were taken. + * Only check that when taking them succeeded: a range can exist + * without a notifier, e.g. when allocating its PFN array failed. */ - if (range && !amdgpu_hmm_range_valid(range) && !r) { + if (!r && !amdgpu_hmm_range_valid(range)) { pr_debug("hmm update the range, need validate again\n"); r = -EAGAIN; } @@ -2116,21 +2134,30 @@ svm_range_evict(struct svm_range *prange, struct mm_struct *mm, if (prange->start <= last && prange->last >= start) atomic_inc(&prange->invalid); + /* The MMU notifier must not return before the GPU has stopped + * accessing the invalidated pages. Only the first eviction stops + * the queues, which takes milliseconds (HWS preemption on every + * GPU of the process). Serialize all evictions of this process so + * that a concurrent invalidation of another range waits until + * that quiesce has completed instead of returning while queues + * still run on stale PTEs. + */ + mutex_lock(&svms->evict_lock); evicted_ranges = atomic_inc_return(&svms->evicted_ranges); - if (evicted_ranges != 1) - return r; - - pr_debug("evicting svms 0x%p range [0x%lx 0x%lx]\n", - prange->svms, prange->start, prange->last); + if (evicted_ranges == 1) { + pr_debug("evicting svms 0x%p range [0x%lx 0x%lx]\n", + prange->svms, prange->start, prange->last); - /* First eviction, stop the queues */ - r = kgd2kfd_quiesce_mm(mm, KFD_QUEUE_EVICTION_TRIGGER_SVM); - if (r) - pr_debug("failed to quiesce KFD\n"); + /* First eviction, stop the queues */ + r = kgd2kfd_quiesce_mm(mm, KFD_QUEUE_EVICTION_TRIGGER_SVM); + if (r) + pr_debug("failed to quiesce KFD\n"); - pr_debug("schedule to restore svm %p ranges\n", svms); - queue_delayed_work(system_freezable_wq, &svms->restore_work, - msecs_to_jiffies(AMDGPU_SVM_RANGE_RESTORE_DELAY_MS)); + pr_debug("schedule to restore svm %p ranges\n", svms); + queue_delayed_work(system_freezable_wq, &svms->restore_work, + msecs_to_jiffies(AMDGPU_SVM_RANGE_RESTORE_DELAY_MS)); + } + mutex_unlock(&svms->evict_lock); } else { unsigned long s, l; uint32_t trigger; @@ -3098,8 +3125,9 @@ svm_fault_allowed(struct vm_area_struct *vma, bool write_fault) int svm_range_restore_pages(struct amdgpu_device *adev, unsigned int pasid, uint32_t vmid, uint32_t node_id, - uint64_t addr, uint64_t ts, bool write_fault) + uint64_t fault_addr, uint64_t ts, bool write_fault) { + uint64_t addr = fault_addr >> PAGE_SHIFT; unsigned long start, last, size; struct mm_struct *mm = NULL; struct svm_range_list *svms; @@ -3217,7 +3245,7 @@ svm_range_restore_pages(struct amdgpu_device *adev, unsigned int pasid, mutex_lock(&prange->migrate_mutex); if (svm_range_skip_recover(prange)) { - amdgpu_gmc_filter_faults_remove(node->adev, addr, pasid); + amdgpu_gmc_filter_faults_remove(node->adev, fault_addr, pasid); r = 0; goto out_unlock_range; } @@ -3321,7 +3349,7 @@ svm_range_restore_pages(struct amdgpu_device *adev, unsigned int pasid, if (r == -EAGAIN) { pr_debug("recover vm fault later\n"); - amdgpu_gmc_filter_faults_remove(node->adev, addr, pasid); + amdgpu_gmc_filter_faults_remove(node->adev, fault_addr, pasid); r = 0; } return r; @@ -3412,6 +3440,7 @@ void svm_range_list_fini(struct kfd_process *p) svm_range_free(prange, true); } + mutex_destroy(&p->svms.evict_lock); mutex_destroy(&p->svms.lock); pr_debug("process pid %d svms 0x%p done\n", @@ -3425,6 +3454,7 @@ int svm_range_list_init(struct kfd_process *p) svms->objects = RB_ROOT_CACHED; mutex_init(&svms->lock); + mutex_init(&svms->evict_lock); INIT_LIST_HEAD(&svms->list); atomic_set(&svms->evicted_ranges, 0); atomic_set(&svms->drain_pagefaults, 0); @@ -4254,9 +4284,8 @@ int kfd_criu_restore_svm(struct kfd_process *p, return -ENOMEM; } - ret = copy_from_user(&criu_svm_md->data, user_priv_ptr + *priv_data_offset, - svm_priv_data_size); - if (ret) { + if (copy_from_user(&criu_svm_md->data, user_priv_ptr + *priv_data_offset, + svm_priv_data_size)) { ret = -EFAULT; goto exit; } diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_svm.h b/drivers/gpu/drm/amd/amdkfd/kfd_svm.h index c7d7adae4476bf..38744e716f74da 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_svm.h +++ b/drivers/gpu/drm/amd/amdkfd/kfd_svm.h @@ -178,7 +178,7 @@ int svm_range_vram_node_new(struct kfd_node *node, struct svm_range *prange, bool clear); void svm_range_vram_node_free(struct svm_range *prange); int svm_range_restore_pages(struct amdgpu_device *adev, unsigned int pasid, - uint32_t vmid, uint32_t node_id, uint64_t addr, uint64_t ts, + uint32_t vmid, uint32_t node_id, uint64_t fault_addr, uint64_t ts, bool write_fault); int svm_range_evict_svm_bo(struct amdgpu_bo *bo); @@ -230,7 +230,7 @@ static inline void svm_range_list_fini(struct kfd_process *p) static inline int svm_range_restore_pages(struct amdgpu_device *adev, unsigned int pasid, uint32_t client_id, uint32_t node_id, - uint64_t addr, uint64_t ts, bool write_fault) + uint64_t fault_addr, uint64_t ts, bool write_fault) { return -EFAULT; } 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 0ea45ab12119c5..67bbf95a8c7ab7 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c @@ -886,6 +886,13 @@ static void amdgpu_dm_fini(struct amdgpu_device *adev) adev->dm.vblank_control_workqueue = NULL; } + /* The poll re-queues itself, so stop it before the wq and dc go away. */ + if (adev->dm.hdmi_frl_status_polling_wq) { + cancel_delayed_work_sync(&adev->dm.hdmi_frl_status_polling_work); + destroy_workqueue(adev->dm.hdmi_frl_status_polling_wq); + adev->dm.hdmi_frl_status_polling_wq = NULL; + } + if (adev->dm.idle_workqueue) { if (adev->dm.idle_workqueue->running) { adev->dm.idle_workqueue->enable = false; @@ -3011,6 +3018,9 @@ fill_dc_plane_info_and_addr(struct amdgpu_device *adev, case DRM_FORMAT_ARGB8888: plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888; break; + case DRM_FORMAT_RGBA8888: + plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_RGBA8888; + break; case DRM_FORMAT_XRGB2101010: case DRM_FORMAT_ARGB2101010: plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010; @@ -3851,6 +3861,25 @@ STATIC_IFN_KUNIT void dm_arm_vblank_event_pre_programming(struct amdgpu_crtc *ac } EXPORT_IF_KUNIT(dm_arm_vblank_event_pre_programming); +/* + * FreeSync times each frame from the plane's previous flip, and a plane + * reset gives the new DC plane zeroed flip timing, so copy it over. Do + * this at commit time, not in atomic check: by then the previous commit + * has finished writing it. + */ +static void +dm_plane_inherit_flip_time(struct dc_plane_state *dc_plane_state, + struct drm_plane_state *old_plane_state, + struct drm_plane_state *new_plane_state) +{ + struct dc_plane_state *old_dc_plane_state = + to_dm_plane_state(old_plane_state)->dc_state; + + if (old_dc_plane_state && old_dc_plane_state != dc_plane_state && + old_plane_state->crtc == new_plane_state->crtc) + dc_plane_state->time = old_dc_plane_state->time; +} + static void amdgpu_dm_commit_planes(struct drm_atomic_commit *state, struct drm_device *dev, struct amdgpu_display_manager *dm, @@ -3955,6 +3984,9 @@ static void amdgpu_dm_commit_planes(struct drm_atomic_commit *state, if (!dc_plane) continue; + dm_plane_inherit_flip_time(dc_plane, old_plane_state, + new_plane_state); + bundle->surface_updates[planes_count].surface = dc_plane; if (new_pcrtc_state->color_mgmt_changed || new_plane_state->color_mgmt_changed) { bundle->surface_updates[planes_count].gamma = &dc_plane->gamma_correction; @@ -4455,6 +4487,105 @@ STATIC_IFN_KUNIT void dm_clear_writeback(struct amdgpu_display_manager *dm, } EXPORT_IF_KUNIT(dm_clear_writeback); +static bool amdgpu_dm_self_refresh_pause_needed(struct drm_atomic_commit *state) +{ + struct drm_crtc_state *old_crtc_state, *new_crtc_state; + struct drm_crtc *crtc; + int i; + + for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) + if (drm_atomic_crtc_needs_modeset(new_crtc_state) && + (old_crtc_state->active || new_crtc_state->active)) + return true; + + return false; +} + +static bool amdgpu_dm_is_new_modeset_stream(struct drm_atomic_commit *state, + const struct dc_stream_state *stream) +{ + struct drm_crtc_state *new_crtc_state; + struct drm_crtc *crtc; + int i; + + for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) + if (drm_atomic_crtc_needs_modeset(new_crtc_state) && + to_dm_crtc_state(new_crtc_state)->stream == stream) + return true; + + return false; +} + +/* + * A modeset CRTC may have no PSR or Replay, such as an HDMI output being + * turned off, while an eDP on another CRTC is still in self-refresh. Pause + * self-refresh on every stream mod_power tracks before + * amdgpu_dm_mod_power_update_streams() changes the set: the old streams of + * the CRTCs in the commit and the unchanged streams of the new state. + * Unlike hw_programming, which a fast update on another CRTC clears, the + * pause holds until amdgpu_dm_resume_self_refresh() + */ +static void amdgpu_dm_pause_self_refresh(struct drm_atomic_commit *state, + struct amdgpu_display_manager *dm, + struct dc_state *dc_state) +{ + struct drm_crtc_state *old_crtc_state; + struct dc_stream_state *stream; + struct drm_crtc *crtc; + int i; + + if (!amdgpu_dm_self_refresh_pause_needed(state)) + return; + + guard(mutex)(&dm->dc_lock); + dc_exit_ips_for_hw_access(dm->dc); + + for_each_old_crtc_in_state(state, crtc, old_crtc_state, i) { + stream = to_dm_crtc_state(old_crtc_state)->stream; + if (!old_crtc_state->active || !stream) + continue; + + amdgpu_dm_psr_set_event(dm, stream, true, psr_event_pause, true); + amdgpu_dm_replay_set_event(dm, stream, true, replay_event_pause, true); + } + + for (i = 0; i < dc_state->stream_count; i++) { + stream = dc_state->streams[i]; + if (amdgpu_dm_is_new_modeset_stream(state, stream)) + continue; + + amdgpu_dm_psr_set_event(dm, stream, true, psr_event_pause, true); + amdgpu_dm_replay_set_event(dm, stream, true, replay_event_pause, true); + } +} + +/* + * Ends amdgpu_dm_pause_self_refresh() on the streams of the commit, which + * mod_power tracks from amdgpu_dm_mod_power_update_streams() on, even if + * dc_commit_streams() failed. mod_power keeps events across + * mod_power_replace_stream(), so the replaced streams carry the pause too. + * Runs after amdgpu_dm_mod_power_setup_streams(), since enabling a stream + * clears psr_feature_enabled and replay_feature_enabled on its link until + * then, and the set_event helpers skip a link without them + */ +static void amdgpu_dm_resume_self_refresh(struct drm_atomic_commit *state, + struct amdgpu_display_manager *dm, + struct dc_state *dc_state) +{ + int i; + + if (!dc_state || !amdgpu_dm_self_refresh_pause_needed(state)) + return; + + guard(mutex)(&dm->dc_lock); + for (i = 0; i < dc_state->stream_count; i++) { + amdgpu_dm_psr_set_event(dm, dc_state->streams[i], false, + psr_event_pause, false); + amdgpu_dm_replay_set_event(dm, dc_state->streams[i], false, + replay_event_pause, false); + } +} + /** * amdgpu_dm_mod_power_update_streams - update mod_power stream state on modeset * @state: the drm atomic state @@ -4611,6 +4742,7 @@ static void amdgpu_dm_commit_streams(struct drm_atomic_commit *state, acrtc->wb_enabled = false; } + amdgpu_dm_pause_self_refresh(state, dm, dc_state); amdgpu_dm_mod_power_update_streams(state, dm); for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, @@ -4733,6 +4865,11 @@ static void amdgpu_dm_commit_streams(struct drm_atomic_commit *state, dc_exit_ips_for_hw_access(dm->dc); WARN_ON(!dc_commit_streams(dm->dc, ¶ms)); + /* Allow idle optimization when vblank count is 0 for display off */ + if (dm->active_vblank_irq_count == 0 && amdgpu_dm_is_headless(dm->adev)) + dc_allow_idle_optimizations(dm->dc, true); + mutex_unlock(&dm->dc_lock); + bool frl_stream_found = false; for (i = 0; i < params.stream_count; i++) { @@ -4743,6 +4880,7 @@ static void amdgpu_dm_commit_streams(struct drm_atomic_commit *state, break; } } + if (frl_stream_found) { if (queue_delayed_work(dm->hdmi_frl_status_polling_wq, &dm->hdmi_frl_status_polling_work, @@ -4752,10 +4890,6 @@ static void amdgpu_dm_commit_streams(struct drm_atomic_commit *state, if (cancel_delayed_work_sync(&dm->hdmi_frl_status_polling_work)) drm_dbg_kms(dev, "200ms frl status polling stops ...\n"); } - /* Allow idle optimization when vblank count is 0 for display off */ - if ((dm->active_vblank_irq_count == 0) && amdgpu_dm_is_headless(dm->adev)) - dc_allow_idle_optimizations(dm->dc, true); - mutex_unlock(&dm->dc_lock); for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) { struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc); @@ -5200,9 +5334,11 @@ static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_commit *state) scaling_changed = is_scaling_state_different(dm_new_con_state, dm_old_con_state); - if ((new_con_state->hdmi.broadcast_rgb != old_con_state->hdmi.broadcast_rgb) && - (dm_old_crtc_state->stream->output_color_space != - amdgpu_dm_get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state))) + if (new_con_state->hdmi.broadcast_rgb != old_con_state->hdmi.broadcast_rgb && + dm_old_crtc_state->stream->output_color_space != + amdgpu_dm_get_output_color_space(&dm_new_crtc_state->stream->timing, + new_con_state, + dm_new_crtc_state->stream->signal)) output_color_space_changed = true; abm_changed = dm_new_crtc_state->abm_level != @@ -5224,8 +5360,10 @@ static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_commit *state) } if (output_color_space_changed) { - dm_new_crtc_state->stream->output_color_space - = amdgpu_dm_get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state); + dm_new_crtc_state->stream->output_color_space = + amdgpu_dm_get_output_color_space(&dm_new_crtc_state->stream->timing, + new_con_state, + dm_new_crtc_state->stream->signal); stream_update.output_color_space = &dm_new_crtc_state->stream->output_color_space; } @@ -5356,6 +5494,7 @@ static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_commit *state) } amdgpu_dm_mod_power_setup_streams(state, dm); + amdgpu_dm_resume_self_refresh(state, dm, dc_state); for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) if (new_crtc_state->async_flip) diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_backlight.c b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_backlight.c index cb74b00723fdab..8d27c2712c516a 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_backlight.c +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_backlight.c @@ -122,10 +122,10 @@ static inline u32 scale_input_to_fw(int max, u64 input) return DIV_ROUND_CLOSEST_ULL(input * AMDGPU_MAX_BL_LEVEL, max); } -/* Rescale from [0..AMDGPU_MAX_BL_LEVEL] to [min..max] */ -static inline u32 scale_fw_to_input(int min, int max, u64 input) +/* Rescale from [0..AMDGPU_MAX_BL_LEVEL] to [0..max] */ +static inline u32 scale_fw_to_input(int max, u64 input) { - return min + DIV_ROUND_CLOSEST_ULL(input * (max - min), AMDGPU_MAX_BL_LEVEL); + return DIV_ROUND_CLOSEST_ULL(input * max, AMDGPU_MAX_BL_LEVEL); } static u32 backlight_signal_to_luminance(const struct amdgpu_dm_backlight_caps *caps, @@ -251,8 +251,7 @@ void convert_custom_brightness(const struct amdgpu_dm_backlight_caps *caps, (brightness - lower_signal), upper_signal - lower_signal); scale: - *user_brightness = scale_fw_to_input(min, max, - DIV_ROUND_CLOSEST(lum * brightness, 101)); + *user_brightness = scale_fw_to_input(max, DIV_ROUND_CLOSEST(lum * brightness, 101)); } EXPORT_IF_KUNIT(convert_custom_brightness); 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 b498fc5fbb140e..8a039ef6e4b766 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 @@ -737,7 +737,8 @@ EXPORT_IF_KUNIT(get_aspect_ratio); * With Broadcast RGB left at Automatic follow that default, as i915 does. */ static bool rgb_output_is_limited_range(const struct dc_crtc_timing *dc_crtc_timing, - const struct drm_connector_state *connector_state) + const struct drm_connector_state *connector_state, + enum signal_type signal) { switch (connector_state->hdmi.broadcast_rgb) { case DRM_HDMI_BROADCAST_RGB_FULL: @@ -745,14 +746,16 @@ static bool rgb_output_is_limited_range(const struct dc_crtc_timing *dc_crtc_tim case DRM_HDMI_BROADCAST_RGB_LIMITED: return true; default: - return connector_state->connector->display_info.is_hdmi && + return dc_is_hdmi_signal(signal) && + connector_state->connector->display_info.is_hdmi && dc_crtc_timing->vic > 1; } } enum dc_color_space amdgpu_dm_get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing, - const struct drm_connector_state *connector_state) + const struct drm_connector_state *connector_state, + enum signal_type signal) { enum dc_color_space color_space = COLOR_SPACE_SRGB; @@ -775,7 +778,7 @@ amdgpu_dm_get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing, case DRM_MODE_COLORIMETRY_BT2020_RGB: case DRM_MODE_COLORIMETRY_BT2020_YCC: if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB) { - if (rgb_output_is_limited_range(dc_crtc_timing, connector_state)) + if (rgb_output_is_limited_range(dc_crtc_timing, connector_state, signal)) color_space = COLOR_SPACE_2020_RGB_LIMITEDRANGE; else color_space = COLOR_SPACE_2020_RGB_FULLRANGE; @@ -787,7 +790,7 @@ amdgpu_dm_get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing, default: if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB) { color_space = COLOR_SPACE_SRGB; - if (rgb_output_is_limited_range(dc_crtc_timing, connector_state)) + if (rgb_output_is_limited_range(dc_crtc_timing, connector_state, signal)) color_space = COLOR_SPACE_SRGB_LIMITED; /* * 27030khz is the separation point between HDTV and SDTV @@ -939,7 +942,8 @@ STATIC_IFN_KUNIT void fill_stream_properties_from_drm_display_mode( err = drm_hdmi_vendor_infoframe_from_display_mode(&hv_frame, (struct drm_connector *)connector, mode_in); - if (err < 0) + /* Sinks without HDMI infoframe support make it fail with -EINVAL. */ + if (err < 0 && info->has_hdmi_infoframe) drm_warn_once(connector->dev, "Failed to setup vendor infoframe on connector %s: %zd\n", connector->name, err); timing_out->hdmi_vic = hv_frame.vic; @@ -981,7 +985,8 @@ STATIC_IFN_KUNIT void fill_stream_properties_from_drm_display_mode( if (is_hdmi_ep) adjust_colour_depth_from_display_info(timing_out, info); - stream->output_color_space = amdgpu_dm_get_output_color_space(timing_out, connector_state); + stream->output_color_space = amdgpu_dm_get_output_color_space(timing_out, connector_state, + stream->signal); stream->content_type = get_output_content_type(connector_state); } EXPORT_IF_KUNIT(fill_stream_properties_from_drm_display_mode); diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_connector.h b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_connector.h index 79698deacf616d..1528315d79e435 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_connector.h +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_connector.h @@ -129,7 +129,8 @@ int amdgpu_dm_fill_hdr_info_packet(const struct drm_connector_state *state, enum dc_color_space amdgpu_dm_get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing, - const struct drm_connector_state *connector_state); + const struct drm_connector_state *connector_state, + enum signal_type signal); struct drm_display_mode * amdgpu_dm_get_highest_refresh_rate_mode(struct amdgpu_dm_connector *aconnector, 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 383c53afd1f676..7cd08a9a957d64 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 @@ -62,6 +62,8 @@ MODULE_FIRMWARE(FIRMWARE_DCN_351_DMUB); MODULE_FIRMWARE(FIRMWARE_DCN_36_DMUB); MODULE_FIRMWARE(FIRMWARE_DCN_401_DMUB); MODULE_FIRMWARE(FIRMWARE_DCN_42_DMUB); +MODULE_FIRMWARE(FIRMWARE_DCN_42_DMUB_ALT); +MODULE_FIRMWARE(FIRMWARE_DCN_42_DMUB_PREPROD); MODULE_FIRMWARE(FIRMWARE_DCN_42B_DMUB); MODULE_FIRMWARE(FIRMWARE_DCN_60_DMUB); diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_dmub.h b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_dmub.h index df3e776c1ad14d..219e9c0427441f 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_dmub.h +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_dmub.h @@ -61,6 +61,8 @@ int dm_init_microcode(struct amdgpu_device *adev); #define FIRMWARE_DCN_36_DMUB "amdgpu/dcn_3_6_dmcub.bin" #define FIRMWARE_DCN_401_DMUB "amdgpu/dcn_4_0_1_dmcub.bin" #define FIRMWARE_DCN_42_DMUB "amdgpu/dcn_4_2_dmcub.bin" +#define FIRMWARE_DCN_42_DMUB_ALT "amdgpu/dcn_4_2_dmcub_l.bin" +#define FIRMWARE_DCN_42_DMUB_PREPROD "amdgpu/dcn_4_2_dmcub_p.bin" #define FIRMWARE_DCN_42B_DMUB "amdgpu/dcn_4_2_1_dmcub.bin" #define FIRMWARE_DCN_60_DMUB "amdgpu/dcn_6_0_0_dmcub.bin" #define FIRMWARE_RAVEN_DMCU "amdgpu/raven_dmcu.bin" diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_freesync.c b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_freesync.c index 0be4506e9ae5b3..f2539bcf824fc6 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_freesync.c +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_freesync.c @@ -251,6 +251,13 @@ void amdgpu_dm_update_freesync_state_on_stream( mod_build_adaptive_sync_infopacket(new_stream, aconn->as_type, NULL, &new_stream->adaptive_sync_infopacket); + } else if (aconn && aconn->vsdb_info.amd_vsdb_version == 3 && + aconn->max_vfreq > 255) { + /* + * v1 saturates at 255 Hz. Keyed on the sink's max, not the mode's + * rate, so the packet version stays fixed per sink. + */ + packet_type = PACKET_TYPE_FS_V3; } app_tf = dm_dp_in_hdr_mode(new_stream) ? @@ -400,8 +407,16 @@ void amdgpu_dm_handle_vrr_transition(struct amdgpu_display_manager *dm, struct dm_crtc_state *new_state) { struct amdgpu_device *adev = dm->adev; - bool old_vrr_active = amdgpu_dm_crtc_vrr_active(old_state); - bool new_vrr_active = amdgpu_dm_crtc_vrr_active(new_state); + /* + * A disabled CRTC keeps its freesync state, but drm_crtc_vblank_get() + * fails there because vblank is off. Hold the reference only while + * the CRTC is active as well, which also covers resume, where the + * reset state lost track of the reference taken before suspend + */ + bool old_vrr_active = old_state->base.active && + amdgpu_dm_crtc_vrr_active(old_state); + bool new_vrr_active = new_state->base.active && + amdgpu_dm_crtc_vrr_active(new_state); /* Only DCE gates vupdate on VRR, keep it enabled for DCN */ bool vrr_gates_vupdate = amdgpu_ip_version(adev, DCE_HWIP, 0) == 0; diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_backlight_test.c b/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_backlight_test.c index 5221050dec2f15..e500c55a067214 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_backlight_test.c +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_backlight_test.c @@ -1125,10 +1125,10 @@ static void dm_test_custom_brightness_exact_match(struct kunit *test) /* * Exact match: lum=50, brightness_scaled=128 - * result = scale_fw_to_input(min, max, DIV_ROUND_CLOSEST(50*128, 101)) - * = scale_fw_to_input(0, 65535, DIV_ROUND_CLOSEST(6400, 101)) - * = scale_fw_to_input(0, 65535, 63) - * = 0 + DIV_ROUND_CLOSEST(63 * 65535, 255) = 16191 (approx) + * result = scale_fw_to_input(max, DIV_ROUND_CLOSEST(50*128, 101)) + * = scale_fw_to_input(65535, DIV_ROUND_CLOSEST(6400, 101)) + * = scale_fw_to_input(65535, 63) + * = DIV_ROUND_CLOSEST(63 * 65535, 255) = 16191 (approx) */ KUNIT_EXPECT_TRUE(test, brightness != 32896); KUNIT_EXPECT_TRUE(test, brightness < 32896); @@ -1171,9 +1171,9 @@ static void dm_test_custom_brightness_below_first(struct kunit *test) /* * Below first data point: lum = DIV_ROUND_CLOSEST(40 * 50, 100) = 20 - * Then: scale_fw_to_input(0, 65535, DIV_ROUND_CLOSEST(20 * 50, 101)) - * = scale_fw_to_input(0, 65535, DIV_ROUND_CLOSEST(1000, 101)) - * = scale_fw_to_input(0, 65535, 10) + * Then: scale_fw_to_input(65535, DIV_ROUND_CLOSEST(20 * 50, 101)) + * = scale_fw_to_input(65535, DIV_ROUND_CLOSEST(1000, 101)) + * = scale_fw_to_input(65535, 10) * The output should be significantly less than input. */ KUNIT_EXPECT_TRUE(test, brightness < 12850); diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_connector_test.c b/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_connector_test.c index f09e2a72c53465..5988f62f470961 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_connector_test.c +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_connector_test.c @@ -422,7 +422,8 @@ static void dm_test_output_color_space_default_rgb_full(struct kunit *test) state.colorspace = DRM_MODE_COLORIMETRY_DEFAULT; state.hdmi.broadcast_rgb = DRM_HDMI_BROADCAST_RGB_AUTO; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_SRGB); } @@ -439,7 +440,8 @@ static void dm_test_output_color_space_default_rgb_limited(struct kunit *test) state.colorspace = DRM_MODE_COLORIMETRY_DEFAULT; state.hdmi.broadcast_rgb = DRM_HDMI_BROADCAST_RGB_LIMITED; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_SRGB_LIMITED); } @@ -457,7 +459,8 @@ static void dm_test_output_color_space_default_ycbcr709(struct kunit *test) timing.flags.Y_ONLY = 0; state.colorspace = DRM_MODE_COLORIMETRY_DEFAULT; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_YCBCR709); } @@ -476,7 +479,8 @@ static void dm_test_output_color_space_default_ycbcr601_limited(struct kunit *te timing.flags.Y_ONLY = 1; state.colorspace = DRM_MODE_COLORIMETRY_DEFAULT; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_YCBCR601_LIMITED); } @@ -492,7 +496,8 @@ static void dm_test_output_color_space_bt601_y_only(struct kunit *test) timing.flags.Y_ONLY = 1; state.colorspace = DRM_MODE_COLORIMETRY_BT601_YCC; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_YCBCR601_LIMITED); } @@ -508,7 +513,8 @@ static void dm_test_output_color_space_bt601(struct kunit *test) timing.flags.Y_ONLY = 0; state.colorspace = DRM_MODE_COLORIMETRY_BT601_YCC; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_YCBCR601); } @@ -524,7 +530,8 @@ static void dm_test_output_color_space_bt709(struct kunit *test) timing.flags.Y_ONLY = 0; state.colorspace = DRM_MODE_COLORIMETRY_BT709_YCC; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_YCBCR709); } @@ -540,7 +547,8 @@ static void dm_test_output_color_space_bt709_y_only(struct kunit *test) timing.flags.Y_ONLY = 1; state.colorspace = DRM_MODE_COLORIMETRY_BT709_YCC; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_YCBCR709_LIMITED); } @@ -555,7 +563,8 @@ static void dm_test_output_color_space_oprgb(struct kunit *test) state.colorspace = DRM_MODE_COLORIMETRY_OPRGB; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_ADOBERGB); } @@ -573,7 +582,8 @@ static void dm_test_output_color_space_bt2020_rgb(struct kunit *test) timing.pixel_encoding = PIXEL_ENCODING_RGB; state.colorspace = DRM_MODE_COLORIMETRY_BT2020_RGB; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_2020_RGB_FULLRANGE); } @@ -590,7 +600,8 @@ static void dm_test_output_color_space_bt2020_rgb_limited(struct kunit *test) state.colorspace = DRM_MODE_COLORIMETRY_BT2020_RGB; state.hdmi.broadcast_rgb = DRM_HDMI_BROADCAST_RGB_LIMITED; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_2020_RGB_LIMITEDRANGE); } @@ -611,7 +622,8 @@ static void dm_test_output_color_space_default_rgb_auto_hdmi_cta(struct kunit *t state.colorspace = DRM_MODE_COLORIMETRY_DEFAULT; state.hdmi.broadcast_rgb = DRM_HDMI_BROADCAST_RGB_AUTO; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_SRGB_LIMITED); } @@ -632,7 +644,8 @@ static void dm_test_output_color_space_default_rgb_auto_hdmi_vga(struct kunit *t state.colorspace = DRM_MODE_COLORIMETRY_DEFAULT; state.hdmi.broadcast_rgb = DRM_HDMI_BROADCAST_RGB_AUTO; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_SRGB); } @@ -652,7 +665,31 @@ static void dm_test_output_color_space_default_rgb_auto_dp_cta(struct kunit *tes state.colorspace = DRM_MODE_COLORIMETRY_DEFAULT; state.hdmi.broadcast_rgb = DRM_HDMI_BROADCAST_RGB_AUTO; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_DISPLAY_PORT), + (int)COLOR_SPACE_SRGB); +} + +/** + * dm_test_output_color_space_default_rgb_auto_dp_hdmi_vsdb - Automatic on DP stays full range + * even when the EDID has an HDMI VSDB + * @test: The KUnit test context + */ +static void dm_test_output_color_space_default_rgb_auto_dp_hdmi_vsdb(struct kunit *test) +{ + struct dc_crtc_timing timing = {}; + struct drm_connector_state state = {}; + struct drm_connector *connector = kunit_kzalloc(test, sizeof(*connector), GFP_KERNEL); + + connector->display_info.is_hdmi = true; + timing.pixel_encoding = PIXEL_ENCODING_RGB; + timing.vic = 118; + state.connector = connector; + state.colorspace = DRM_MODE_COLORIMETRY_DEFAULT; + state.hdmi.broadcast_rgb = DRM_HDMI_BROADCAST_RGB_AUTO; + + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_DISPLAY_PORT), (int)COLOR_SPACE_SRGB); } @@ -673,7 +710,8 @@ static void dm_test_output_color_space_default_rgb_full_hdmi_cta(struct kunit *t state.colorspace = DRM_MODE_COLORIMETRY_DEFAULT; state.hdmi.broadcast_rgb = DRM_HDMI_BROADCAST_RGB_FULL; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_SRGB); } @@ -694,7 +732,8 @@ static void dm_test_output_color_space_bt2020_rgb_auto_hdmi_cta(struct kunit *te state.colorspace = DRM_MODE_COLORIMETRY_BT2020_RGB; state.hdmi.broadcast_rgb = DRM_HDMI_BROADCAST_RGB_AUTO; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_2020_RGB_LIMITEDRANGE); } @@ -710,7 +749,8 @@ static void dm_test_output_color_space_bt2020_ycc(struct kunit *test) timing.pixel_encoding = PIXEL_ENCODING_YCBCR422; state.colorspace = DRM_MODE_COLORIMETRY_BT2020_YCC; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_2020_YCBCR_LIMITED); } @@ -729,7 +769,8 @@ static void dm_test_output_color_space_default_ycbcr709_y_only(struct kunit *tes timing.flags.Y_ONLY = 1; state.colorspace = DRM_MODE_COLORIMETRY_DEFAULT; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_YCBCR709_LIMITED); } @@ -748,7 +789,8 @@ static void dm_test_output_color_space_default_ycbcr601(struct kunit *test) timing.flags.Y_ONLY = 0; state.colorspace = DRM_MODE_COLORIMETRY_DEFAULT; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_YCBCR601); } @@ -767,7 +809,8 @@ static void dm_test_output_color_space_bt2020_ycc_rgb_encoding(struct kunit *tes timing.pixel_encoding = PIXEL_ENCODING_RGB; state.colorspace = DRM_MODE_COLORIMETRY_BT2020_YCC; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_2020_RGB_FULLRANGE); } @@ -785,7 +828,8 @@ static void dm_test_output_color_space_bt2020_ycc_rgb_encoding_limited(struct ku state.colorspace = DRM_MODE_COLORIMETRY_BT2020_YCC; state.hdmi.broadcast_rgb = DRM_HDMI_BROADCAST_RGB_LIMITED; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_2020_RGB_LIMITEDRANGE); } @@ -802,7 +846,8 @@ static void dm_test_output_color_space_bt2020_rgb_ycc_encoding(struct kunit *tes timing.pixel_encoding = PIXEL_ENCODING_YCBCR444; state.colorspace = DRM_MODE_COLORIMETRY_BT2020_RGB; - KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state), + KUNIT_EXPECT_EQ(test, (int)amdgpu_dm_get_output_color_space(&timing, &state, + SIGNAL_TYPE_HDMI_TYPE_A), (int)COLOR_SPACE_2020_YCBCR_LIMITED); } @@ -10010,6 +10055,7 @@ static struct kunit_case amdgpu_dm_connector_tests[] = { KUNIT_CASE(dm_test_output_color_space_default_rgb_auto_hdmi_cta), KUNIT_CASE(dm_test_output_color_space_default_rgb_auto_hdmi_vga), KUNIT_CASE(dm_test_output_color_space_default_rgb_auto_dp_cta), + KUNIT_CASE(dm_test_output_color_space_default_rgb_auto_dp_hdmi_vsdb), KUNIT_CASE(dm_test_output_color_space_default_rgb_full_hdmi_cta), KUNIT_CASE(dm_test_output_color_space_bt2020_rgb_auto_hdmi_cta), KUNIT_CASE(dm_test_output_color_space_bt2020_ycc), diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_freesync_test.c b/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_freesync_test.c index 5ad50bc3161375..8f219f08cd55b6 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_freesync_test.c +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_freesync_test.c @@ -622,6 +622,117 @@ static void dm_test_update_freesync_state_pcon_default(struct kunit *test) dm_test_update_freesync_state_pcon_version(test, 0); } +/* + * Build the VRR infopacket for a non-PCON, non-Replay sink with VRR inactive + * over 48Hz to @mode_hz, the max that mod_freesync_build_vrr_params() clamps + * to the mode's rate. + */ +static struct dc_info_packet +dm_test_freesync_packet(struct kunit *test, enum signal_type signal, + u8 vsdb_version, int sink_max_hz, int mode_hz) +{ + struct amdgpu_device *adev = dm_kunit_alloc_adev(test); + struct dc_link *link = dm_kunit_alloc_link(test); + struct dc_stream_state *stream = dm_kunit_alloc_stream(test, link); + struct amdgpu_dm_connector *aconnector; + struct mod_vrr_params *vrr; + struct amdgpu_crtc *acrtc; + struct dm_crtc_state crtc_state = { 0 }; + + acrtc = kunit_kzalloc(test, sizeof(*acrtc), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, acrtc); + aconnector = kunit_kzalloc(test, sizeof(*aconnector), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, aconnector); + crtc_state.base.crtc = &acrtc->base; + stream->timing.h_total = 2200; + stream->timing.v_total = 1125; + stream->signal = signal; + stream->dm_stream_context = aconnector; + aconnector->vsdb_info.amd_vsdb_version = vsdb_version; + aconnector->max_vfreq = sink_max_hz; + vrr = &acrtc->dm_irq_params.vrr_params; + vrr->send_info_frame = true; + vrr->state = VRR_STATE_INACTIVE; + vrr->min_refresh_in_uhz = 48000000; + vrr->max_refresh_in_uhz = mode_hz * 1000000; + adev->dm.adev = adev; + + amdgpu_dm_update_freesync_state_on_stream(&adev->dm, &crtc_state, stream, NULL, 0); + + return crtc_state.vrr_infopacket; +} + +/** + * dm_test_update_freesync_state_dp_v2_saturates - Test v1 saturates above 255Hz + * @test: The KUnit test context + * + * A VSDB v2 sink keeps the v1 packet, which cannot carry 320Hz. + */ +static void dm_test_update_freesync_state_dp_v2_saturates(struct kunit *test) +{ + struct dc_info_packet p = + dm_test_freesync_packet(test, SIGNAL_TYPE_DISPLAY_PORT, 2, 320, 320); + + KUNIT_EXPECT_EQ(test, p.hb3, 0x04); + KUNIT_EXPECT_EQ(test, p.sb[7], 255); + KUNIT_EXPECT_EQ(test, p.sb[8], 255); +} + +/** + * dm_test_update_freesync_state_dp_v3_above_255 - Test v3 for a VSDB v3 sink above 255Hz + * @test: The KUnit test context + */ +static void dm_test_update_freesync_state_dp_v3_above_255(struct kunit *test) +{ + struct dc_info_packet p = + dm_test_freesync_packet(test, SIGNAL_TYPE_DISPLAY_PORT, 3, 320, 320); + + KUNIT_EXPECT_EQ(test, p.hb3, 3 << 2); + KUNIT_EXPECT_EQ(test, p.sb[8], 320 & 0xff); + KUNIT_EXPECT_EQ(test, p.sb[12], 320 >> 8); +} + +/** + * dm_test_update_freesync_state_dp_v3_mode_240 - Test v3 follows the sink max, not the mode + * @test: The KUnit test context + */ +static void dm_test_update_freesync_state_dp_v3_mode_240(struct kunit *test) +{ + struct dc_info_packet p = + dm_test_freesync_packet(test, SIGNAL_TYPE_DISPLAY_PORT, 3, 320, 240); + + KUNIT_EXPECT_EQ(test, p.hb3, 3 << 2); + KUNIT_EXPECT_EQ(test, p.sb[8], 240); + KUNIT_EXPECT_EQ(test, p.sb[12], 0); +} + +/** + * dm_test_update_freesync_state_dp_v3_at_255 - Test a VSDB v3 sink at 255Hz keeps v1 + * @test: The KUnit test context + */ +static void dm_test_update_freesync_state_dp_v3_at_255(struct kunit *test) +{ + struct dc_info_packet p = + dm_test_freesync_packet(test, SIGNAL_TYPE_DISPLAY_PORT, 3, 255, 255); + + KUNIT_EXPECT_EQ(test, p.hb3, 0x04); + KUNIT_EXPECT_EQ(test, p.sb[8], 255); +} + +/** + * dm_test_update_freesync_state_hdmi_v3_above_255 - Test v3 for a VSDB v3 HDMI sink + * @test: The KUnit test context + */ +static void dm_test_update_freesync_state_hdmi_v3_above_255(struct kunit *test) +{ + struct dc_info_packet p = + dm_test_freesync_packet(test, SIGNAL_TYPE_HDMI_TYPE_A, 3, 320, 320); + + KUNIT_EXPECT_EQ(test, p.hb1, 3); + KUNIT_EXPECT_EQ(test, p.sb[8], 320 & 0xff); + KUNIT_EXPECT_EQ(test, p.sb[12], 320 >> 8); +} + /* Tests for amdgpu_dm_update_stream_irq_parameters() */ /** @@ -813,8 +924,10 @@ static void dm_test_handle_vrr_transition_round_trip(struct kunit *test) mutex_init(&adev->dm.dc_lock); old_state.base.crtc = &acrtc->base; + old_state.base.active = true; old_state.stream = stream; new_state.base.crtc = &acrtc->base; + new_state.base.active = true; new_state.stream = stream; new_state.freesync_config.state = VRR_STATE_ACTIVE_VARIABLE; @@ -825,6 +938,99 @@ static void dm_test_handle_vrr_transition_round_trip(struct kunit *test) KUNIT_EXPECT_EQ(test, atomic_read(&vblank->refcount), 0); } +/* + * Runs a transition on a CRTC whose vblank is on with two references held, + * so a get or put never has to enable or disable it, and returns the + * refcount afterwards + */ +static int dm_test_vrr_transition_refcount(struct kunit *test, + bool old_active, enum mod_vrr_state old_vrr, + bool new_active, enum mod_vrr_state new_vrr) +{ + struct amdgpu_device *adev = dm_kunit_alloc_adev(test); + struct amdgpu_display_manager *dm = dm_kunit_alloc_dm(test); + struct dm_crtc_state *old_state, *new_state; + struct drm_crtc *crtc; + int refcount; + + KUNIT_ASSERT_EQ(test, drm_vblank_init(&adev->ddev, 1), 0); + adev->ip_versions[DCE_HWIP][0] = IP_VERSION(2, 1, 0); + dm->adev = adev; + mutex_init(&dm->dc_lock); + + crtc = kunit_kzalloc(test, sizeof(*crtc), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, crtc); + crtc->dev = &adev->ddev; + + old_state = kunit_kzalloc(test, sizeof(*old_state), GFP_KERNEL); + new_state = kunit_kzalloc(test, sizeof(*new_state), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, old_state); + KUNIT_ASSERT_NOT_NULL(test, new_state); + old_state->base.crtc = crtc; + old_state->base.active = old_active; + old_state->freesync_config.state = old_vrr; + new_state->base.crtc = crtc; + new_state->base.active = new_active; + new_state->freesync_config.state = new_vrr; + + adev->ddev.vblank[0].enabled = true; + atomic_set(&adev->ddev.vblank[0].refcount, 2); + + amdgpu_dm_handle_vrr_transition(dm, old_state, new_state); + refcount = atomic_read(&adev->ddev.vblank[0].refcount); + + /* drm_vblank_init_release() warns if vblank is still enabled */ + adev->ddev.vblank[0].enabled = false; + atomic_set(&adev->ddev.vblank[0].refcount, 0); + + return refcount; +} + +/** + * dm_test_vrr_transition_crtc_off_drops_ref - Test disabling the CRTC drops the ref + * @test: The KUnit test context + * + * Disabling the CRTC keeps the freesync state, as on suspend or DPMS off. + * The reference must still be dropped, since resume restores the state from + * a reset one and takes a new reference + */ +static void dm_test_vrr_transition_crtc_off_drops_ref(struct kunit *test) +{ + KUNIT_EXPECT_EQ(test, + dm_test_vrr_transition_refcount(test, true, VRR_STATE_ACTIVE_VARIABLE, + false, VRR_STATE_ACTIVE_VARIABLE), + 1); +} + +/** + * dm_test_vrr_transition_crtc_on_takes_ref - Test enabling the CRTC takes the ref + * @test: The KUnit test context + * + * Covers resume, where the old state is a reset one, and DPMS on + */ +static void dm_test_vrr_transition_crtc_on_takes_ref(struct kunit *test) +{ + KUNIT_EXPECT_EQ(test, + dm_test_vrr_transition_refcount(test, false, VRR_STATE_UNSUPPORTED, + true, VRR_STATE_ACTIVE_VARIABLE), + 3); +} + +/** + * dm_test_vrr_transition_crtc_off_keeps_ref - Test no ref change while off + * @test: The KUnit test context + * + * A disabled CRTC has vblank off, so a VRR change there must neither take + * nor drop a reference + */ +static void dm_test_vrr_transition_crtc_off_keeps_ref(struct kunit *test) +{ + KUNIT_EXPECT_EQ(test, + dm_test_vrr_transition_refcount(test, false, VRR_STATE_UNSUPPORTED, + false, VRR_STATE_ACTIVE_VARIABLE), + 2); +} + static struct kunit_case amdgpu_dm_freesync_tests[] = { /* amdgpu_dm_is_timing_unchanged_for_freesync */ KUNIT_CASE(dm_test_timing_unchanged_null_args), @@ -857,6 +1063,11 @@ static struct kunit_case amdgpu_dm_freesync_tests[] = { KUNIT_CASE(dm_test_update_freesync_state_pcon_v2), KUNIT_CASE(dm_test_update_freesync_state_pcon_v3), KUNIT_CASE(dm_test_update_freesync_state_pcon_default), + KUNIT_CASE(dm_test_update_freesync_state_dp_v2_saturates), + KUNIT_CASE(dm_test_update_freesync_state_dp_v3_above_255), + KUNIT_CASE(dm_test_update_freesync_state_dp_v3_mode_240), + KUNIT_CASE(dm_test_update_freesync_state_dp_v3_at_255), + KUNIT_CASE(dm_test_update_freesync_state_hdmi_v3_above_255), /* amdgpu_dm_update_stream_irq_parameters */ KUNIT_CASE(dm_test_update_stream_irq_parameters_no_stream), KUNIT_CASE(dm_test_update_stream_irq_parameters_invalid_timing), @@ -867,6 +1078,9 @@ static struct kunit_case amdgpu_dm_freesync_tests[] = { /* amdgpu_dm_handle_vrr_transition */ KUNIT_CASE(dm_test_handle_vrr_transition_inactive), KUNIT_CASE(dm_test_handle_vrr_transition_round_trip), + KUNIT_CASE(dm_test_vrr_transition_crtc_off_drops_ref), + KUNIT_CASE(dm_test_vrr_transition_crtc_on_takes_ref), + KUNIT_CASE(dm_test_vrr_transition_crtc_off_keeps_ref), {} }; diff --git a/drivers/gpu/drm/amd/display/dc/basics/dce_calcs.c b/drivers/gpu/drm/amd/display/dc/basics/dce_calcs.c index 1b8e843020d6c5..1ff1a6c23c65c6 100644 --- a/drivers/gpu/drm/amd/display/dc/basics/dce_calcs.c +++ b/drivers/gpu/drm/amd/display/dc/basics/dce_calcs.c @@ -2853,6 +2853,7 @@ static void populate_initial_data( break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB8888: case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010_XR_BIAS: @@ -2957,6 +2958,7 @@ static void populate_initial_data( break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB8888: case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010_XR_BIAS: diff --git a/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn42/dcn42_clk_mgr.c b/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn42/dcn42_clk_mgr.c index 405145889ba27b..ae3d762955a9b8 100644 --- a/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn42/dcn42_clk_mgr.c +++ b/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn42/dcn42_clk_mgr.c @@ -643,6 +643,9 @@ DC_LOGGER_INIT(clk_mgr_base->ctx->logger); DC_LOG_SMU("dp_dto_source_clock %d, dprefclk %d\n", clk_mgr_base->dp_dto_source_clock_in_khz, clk_mgr_base->dprefclk_khz); dcn42_dump_clk_registers(&clk_mgr_base->boot_snapshot, clk_mgr); + /* Snapshot is in 10kHz units; seed clks so update_clocks() does not lower the pre-OS clocks */ + clk_mgr_base->clks.dispclk_khz = clk_mgr_base->boot_snapshot.dispclk * 10; + clk_mgr_base->clks.dppclk_khz = clk_mgr_base->boot_snapshot.dppclk * 10; clk_mgr_base->clks.ref_dtbclk_khz = clk_mgr_base->boot_snapshot.dtbclk * 10; clk_mgr_base->clks.dtbclk_en = clk_mgr_base->boot_snapshot.dtbclk > 59000; } diff --git a/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn42b/dcn42b_clk_mgr.c b/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn42b/dcn42b_clk_mgr.c index d500a3210eed78..6aacc4f77ae789 100644 --- a/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn42b/dcn42b_clk_mgr.c +++ b/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn42b/dcn42b_clk_mgr.c @@ -242,6 +242,10 @@ DC_LOGGER_INIT(clk_mgr_base->ctx->logger); DC_LOG_SMU("dp_dto_source_clock %d, dprefclk %d\n", clk_mgr_base->dp_dto_source_clock_in_khz, clk_mgr_base->dprefclk_khz); dcn42b_dump_clk_registers(&clk_mgr_base->boot_snapshot, clk_mgr); + + /* Snapshot is in 10kHz units; seed clks so update_clocks() does not lower the pre-OS clocks */ + clk_mgr_base->clks.dispclk_khz = clk_mgr_base->boot_snapshot.dispclk * 10; + clk_mgr_base->clks.dppclk_khz = clk_mgr_base->boot_snapshot.dppclk * 10; } static struct clk_bw_params dcn42b_bw_params = { diff --git a/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn60/dalsmc.h b/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn60/dalsmc.h index 234777bdd1831a..ea3927223117e3 100644 --- a/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn60/dalsmc.h +++ b/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn60/dalsmc.h @@ -77,7 +77,8 @@ typedef struct { typedef struct { uint32_t NumUmcChannels; - uint32_t Reserved[3]; + uint32_t DramChannelWidthBytes; + uint32_t Reserved[2]; } MemoryConfig_t; /** diff --git a/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn60/dcn60_clk_mgr.c b/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn60/dcn60_clk_mgr.c index d8a0a482d98429..e33140d45867f3 100644 --- a/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn60/dcn60_clk_mgr.c +++ b/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn60/dcn60_clk_mgr.c @@ -815,8 +815,7 @@ static bool dcn60_fetch_dal_init_table(struct clk_mgr_internal *clk_mgr) //dcn60_populate_dc_mode_limit(&bw_params->dc_mode_limit, init_table); bw_params->num_channels = init_table->MemoryConfig.NumUmcChannels; - bw_params->dram_channel_width_bytes = - clk_mgr->base.ctx->dc_bios->vram_info.dram_channel_width_bytes; + bw_params->dram_channel_width_bytes = init_table->MemoryConfig.DramChannelWidthBytes; dcn60_populate_utm_qos_model(clk_mgr, &bw_params->utm_qos_model, init_table); diff --git a/drivers/gpu/drm/amd/display/dc/core/dc.c b/drivers/gpu/drm/amd/display/dc/core/dc.c index 348e8991f8701a..98e5aa160b7493 100644 --- a/drivers/gpu/drm/amd/display/dc/core/dc.c +++ b/drivers/gpu/drm/amd/display/dc/core/dc.c @@ -1022,6 +1022,8 @@ static bool dc_construct_ctx(struct dc *dc, dc_ctx->perf_trace = dc_perf_trace_create(); if (!dc_ctx->perf_trace) { + kfree(dc_ctx->logger); + dc->dml.logger = NULL; kfree(dc_ctx); ASSERT_CRITICAL(false); return false; @@ -1663,12 +1665,25 @@ static void detect_edp_presence(struct dc *dc) } } +static void sync_current_state_clocks_from_clk_mgr(struct dc *dc) +{ + if (!dc->current_state || !dc->clk_mgr) + return; + + if (!(dc->ctx->dce_version == DCN_VERSION_4_2 || dc->ctx->dce_version == DCN_VERSION_4_2B)) + return; + + dc->current_state->bw_ctx.bw.dcn.clk = dc->clk_mgr->clks; +} + void legacy_hardware_init(struct dc *dc) { detect_edp_presence(dc); - if (dc->ctx->dce_environment != DCE_ENV_VIRTUAL_HW) + if (dc->ctx->dce_environment != DCE_ENV_VIRTUAL_HW) { dc->hwss.init_hw(dc); + sync_current_state_clocks_from_clk_mgr(dc); + } dc_dmub_srv_notify_fw_dc_power_state(dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0); } @@ -6312,6 +6327,7 @@ void dc_set_power_state(struct dc *dc, enum dc_acpi_cm_power_state power_state) dc_dmub_srv_notify_fw_dc_power_state(dc->ctx->dmub_srv, power_state); dc->hwss.init_hw(dc); + sync_current_state_clocks_from_clk_mgr(dc); if (dc->hwss.init_sys_ctx != NULL && dc->vm_pa_config.valid) { 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 187486d978da65..225dfada44a5a2 100644 --- a/drivers/gpu/drm/amd/display/dc/core/dc_resource.c +++ b/drivers/gpu/drm/amd/display/dc/core/dc_resource.c @@ -808,6 +808,9 @@ static enum dc_pixel_format convert_pixel_format_to_dalsurface( case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: dal_pixel_format = PIXEL_FORMAT_ARGB8888; break; + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: + dal_pixel_format = PIXEL_FORMAT_ARGB8888; + break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: dal_pixel_format = PIXEL_FORMAT_ARGB2101010; break; @@ -5831,6 +5834,7 @@ unsigned int resource_pixel_format_to_bpp(enum surface_pixel_format format) return 16; case SURFACE_PIXEL_FORMAT_GRPH_ARGB8888: case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010_XR_BIAS: diff --git a/drivers/gpu/drm/amd/display/dc/dc_hw_types.h b/drivers/gpu/drm/amd/display/dc/dc_hw_types.h index baf6091bb52d05..25e538db02937d 100644 --- a/drivers/gpu/drm/amd/display/dc/dc_hw_types.h +++ b/drivers/gpu/drm/amd/display/dc/dc_hw_types.h @@ -176,6 +176,8 @@ enum surface_pixel_format { SURFACE_PIXEL_FORMAT_GRPH_ARGB8888, /*32 bpp swaped*/ SURFACE_PIXEL_FORMAT_GRPH_ABGR8888, + /*32 bpp, alpha in LSB*/ + SURFACE_PIXEL_FORMAT_GRPH_RGBA8888, SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010, /*swaped*/ diff --git a/drivers/gpu/drm/amd/display/dc/dce/dce_link_encoder.c b/drivers/gpu/drm/amd/display/dc/dce/dce_link_encoder.c index c6a20378121b3f..0c1fcfd088bacb 100644 --- a/drivers/gpu/drm/amd/display/dc/dce/dce_link_encoder.c +++ b/drivers/gpu/drm/amd/display/dc/dce/dce_link_encoder.c @@ -1841,8 +1841,11 @@ bool dce110_get_hpd_state(struct link_encoder *enc) bool dce110_program_hpd_filter(struct link_encoder *enc, int delay_on_connect_in_ms, int delay_on_disconnect_in_ms) { + if (!enc->hpd_gpio) + return false; + /* Setup HPD filtering */ - if (enc->hpd_gpio && dal_gpio_lock_pin(enc->hpd_gpio) == GPIO_RESULT_OK) { + if (dal_gpio_lock_pin(enc->hpd_gpio) == GPIO_RESULT_OK) { struct gpio_hpd_config config; config.delay_on_connect = delay_on_connect_in_ms; diff --git a/drivers/gpu/drm/amd/display/dc/dce/dce_mem_input.c b/drivers/gpu/drm/amd/display/dc/dce/dce_mem_input.c index 168c2d0a5eaa75..4f1b8b2750d977 100644 --- a/drivers/gpu/drm/amd/display/dc/dce/dce_mem_input.c +++ b/drivers/gpu/drm/amd/display/dc/dce/dce_mem_input.c @@ -558,25 +558,40 @@ static void program_grph_pixel_format( struct dce_mem_input *dce_mi, enum surface_pixel_format format) { - uint32_t red_xbar = 0, blue_xbar = 0; /* no swap */ + /* Crossbar per output channel: 0 R, 1 G, 2 B, 3 A source (see + * DCP_GRPH_*_CROSSBAR in the enum headers). DCE unpacks all 32bpp + * as ARGB, so alpha-in-LSB layouts are reordered via the crossbar. + */ + uint32_t red_xbar = 0, green_xbar = 0, blue_xbar = 0, alpha_xbar = 0; uint32_t grph_depth = 0, grph_format = 0; uint32_t sign = 0, floating = 0; - if (format == SURFACE_PIXEL_FORMAT_GRPH_ABGR8888 || - /*todo: doesn't look like we handle BGRA here, - * should problem swap endian*/ - format == SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010 || - format == SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010_XR_BIAS || - format == SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616 || - format == SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616F) { - /* ABGR formats */ - red_xbar = 2; - blue_xbar = 2; + switch (format) { + case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: + case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: + case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010_XR_BIAS: + case SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616: + case SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616F: + /* ABGR: swap R and B */ + red_xbar = 2; /* R from B */ + blue_xbar = 2; /* B from R */ + break; + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: + /* rotate ARGB -> RGBA */ + red_xbar = 3; /* R from A */ + green_xbar = 3; /* G from R */ + blue_xbar = 3; /* B from G */ + alpha_xbar = 3; /* A from B */ + break; + default: + break; } - REG_SET_2(GRPH_SWAP_CNTL, 0, + REG_SET_4(GRPH_SWAP_CNTL, 0, GRPH_RED_CROSSBAR, red_xbar, - GRPH_BLUE_CROSSBAR, blue_xbar); + GRPH_GREEN_CROSSBAR, green_xbar, + GRPH_BLUE_CROSSBAR, blue_xbar, + GRPH_ALPHA_CROSSBAR, alpha_xbar); switch (format) { case SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS: @@ -593,6 +608,7 @@ static void program_grph_pixel_format( break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB8888: case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: grph_depth = 2; grph_format = 0; break; diff --git a/drivers/gpu/drm/amd/display/dc/dce/dce_mem_input.h b/drivers/gpu/drm/amd/display/dc/dce/dce_mem_input.h index e34e445a40132d..a593842ee87960 100644 --- a/drivers/gpu/drm/amd/display/dc/dce/dce_mem_input.h +++ b/drivers/gpu/drm/amd/display/dc/dce/dce_mem_input.h @@ -189,7 +189,9 @@ struct dce_mem_input_registers { SFB(blk, GRPH_PITCH, GRPH_PITCH, mask_sh),\ SFB(blk, HW_ROTATION, GRPH_ROTATION_ANGLE, mask_sh),\ SFB(blk, GRPH_SWAP_CNTL, GRPH_RED_CROSSBAR, mask_sh),\ + SFB(blk, GRPH_SWAP_CNTL, GRPH_GREEN_CROSSBAR, mask_sh),\ SFB(blk, GRPH_SWAP_CNTL, GRPH_BLUE_CROSSBAR, mask_sh),\ + SFB(blk, GRPH_SWAP_CNTL, GRPH_ALPHA_CROSSBAR, mask_sh),\ SFB(blk, PRESCALE_GRPH_CONTROL, GRPH_PRESCALE_SELECT, mask_sh),\ SFB(blk, PRESCALE_GRPH_CONTROL, GRPH_PRESCALE_R_SIGN, mask_sh),\ SFB(blk, PRESCALE_GRPH_CONTROL, GRPH_PRESCALE_G_SIGN, mask_sh),\ @@ -213,7 +215,9 @@ struct dce_mem_input_registers { SFB(blk, GRPH_Y_END, GRPH_Y_END, mask_sh),\ SFB(blk, GRPH_PITCH, GRPH_PITCH, mask_sh),\ SFB(blk, GRPH_SWAP_CNTL, GRPH_RED_CROSSBAR, mask_sh),\ + SFB(blk, GRPH_SWAP_CNTL, GRPH_GREEN_CROSSBAR, mask_sh),\ SFB(blk, GRPH_SWAP_CNTL, GRPH_BLUE_CROSSBAR, mask_sh),\ + SFB(blk, GRPH_SWAP_CNTL, GRPH_ALPHA_CROSSBAR, mask_sh),\ SFB(blk, PRESCALE_GRPH_CONTROL, GRPH_PRESCALE_SELECT, mask_sh),\ SFB(blk, PRESCALE_GRPH_CONTROL, GRPH_PRESCALE_R_SIGN, mask_sh),\ SFB(blk, PRESCALE_GRPH_CONTROL, GRPH_PRESCALE_G_SIGN, mask_sh),\ @@ -344,7 +348,9 @@ struct dce_mem_input_registers { type GRPH_PITCH; \ type GRPH_ROTATION_ANGLE; \ type GRPH_RED_CROSSBAR; \ + type GRPH_GREEN_CROSSBAR; \ type GRPH_BLUE_CROSSBAR; \ + type GRPH_ALPHA_CROSSBAR; \ type GRPH_PRESCALE_SELECT; \ type GRPH_PRESCALE_R_SIGN; \ type GRPH_PRESCALE_G_SIGN; \ diff --git a/drivers/gpu/drm/amd/display/dc/dce110/dce110_mem_input_v.c b/drivers/gpu/drm/amd/display/dc/dce110/dce110_mem_input_v.c index 095869912c091f..9d781d12d66959 100644 --- a/drivers/gpu/drm/amd/display/dc/dce110/dce110_mem_input_v.c +++ b/drivers/gpu/drm/amd/display/dc/dce110/dce110_mem_input_v.c @@ -381,6 +381,7 @@ static void program_pixel_format( break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB8888: case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: grph_depth = 2; grph_format = 0; break; diff --git a/drivers/gpu/drm/amd/display/dc/dio/dcn10/dcn10_link_encoder.c b/drivers/gpu/drm/amd/display/dc/dio/dcn10/dcn10_link_encoder.c index 32e12d894e31f6..ddb40e6507b59b 100644 --- a/drivers/gpu/drm/amd/display/dc/dio/dcn10/dcn10_link_encoder.c +++ b/drivers/gpu/drm/amd/display/dc/dio/dcn10/dcn10_link_encoder.c @@ -1506,8 +1506,11 @@ bool dcn10_get_hpd_state(struct link_encoder *enc) bool dcn10_program_hpd_filter(struct link_encoder *enc, int delay_on_connect_in_ms, int delay_on_disconnect_in_ms) { + if (!enc->hpd_gpio) + return false; + /* Setup HPD filtering */ - if (enc->hpd_gpio && dal_gpio_lock_pin(enc->hpd_gpio) == GPIO_RESULT_OK) { + if (dal_gpio_lock_pin(enc->hpd_gpio) == GPIO_RESULT_OK) { struct gpio_hpd_config config; config.delay_on_connect = delay_on_connect_in_ms; diff --git a/drivers/gpu/drm/amd/display/dc/dml/calcs/dcn_calcs.c b/drivers/gpu/drm/amd/display/dc/dml/calcs/dcn_calcs.c index 2ad4a263568326..ec25a76dc3f11d 100644 --- a/drivers/gpu/drm/amd/display/dc/dml/calcs/dcn_calcs.c +++ b/drivers/gpu/drm/amd/display/dc/dml/calcs/dcn_calcs.c @@ -231,6 +231,7 @@ static enum dcn_bw_defs tl_pixel_format_to_bw_defs(enum surface_pixel_format for return dcn_bw_rgb_sub_16; case SURFACE_PIXEL_FORMAT_GRPH_ARGB8888: case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010_XR_BIAS: diff --git a/drivers/gpu/drm/amd/display/dc/dml2_0/dml21/inc/bounding_boxes/dcn42b_soc_bb.h b/drivers/gpu/drm/amd/display/dc/dml2_0/dml21/inc/bounding_boxes/dcn42b_soc_bb.h index e83a9ac018db2c..07f1bffc75ca85 100644 --- a/drivers/gpu/drm/amd/display/dc/dml2_0/dml21/inc/bounding_boxes/dcn42b_soc_bb.h +++ b/drivers/gpu/drm/amd/display/dc/dml2_0/dml21/inc/bounding_boxes/dcn42b_soc_bb.h @@ -188,8 +188,8 @@ static const struct dml2_soc_bb dml2_socbb_dcn42b = { .dram_clk_change_blackout_us = 36, .fclk_change_blackout_us = 0, .g7_ppt_blackout_us = 0, - .stutter_enter_plus_exit_latency_us = 14, - .stutter_exit_latency_us = 12, + .stutter_enter_plus_exit_latency_us = 15.5, + .stutter_exit_latency_us = 13.5, .z8_stutter_enter_plus_exit_latency_us = 300, .z8_stutter_exit_latency_us = 200, }, diff --git a/drivers/gpu/drm/amd/display/dc/dml2_0/dml21/src/dml2_core/dml2_core_dcn5_calcs_dchub.c b/drivers/gpu/drm/amd/display/dc/dml2_0/dml21/src/dml2_core/dml2_core_dcn5_calcs_dchub.c index f407afefb37fe0..82dbf81defbbcb 100644 --- a/drivers/gpu/drm/amd/display/dc/dml2_0/dml21/src/dml2_core/dml2_core_dcn5_calcs_dchub.c +++ b/drivers/gpu/drm/amd/display/dc/dml2_0/dml21/src/dml2_core/dml2_core_dcn5_calcs_dchub.c @@ -836,7 +836,7 @@ void dcn5_calculate_swath_and_det_configuration(struct dml2_core_internal_scratc p->SwathHeightC[k] = MaximumSwathHeightC[k]; RoundedUpSwathSizeBytesY[k] = p->full_swath_bytes_l[k] / 2; RoundedUpSwathSizeBytesC[k] = p->full_swath_bytes_c[k]; - p->request_size_bytes_luma[k] = dml2_core_utils_get_segment_horizontal_contiguous(p->BytePerPixY[k], p->display_cfg->plane_descriptors[k].surface.tiling) + p->request_size_bytes_luma[k] = dml2_core_utils_get_segment_horizontal_contiguous(p->display_cfg->plane_descriptors[k].surface.tiling, p->BytePerPixY[k]) == dml2_core_utils_is_vertical_rotation(p->display_cfg->plane_descriptors[k].composition.rotation_angle) ? 64 : 128; p->request_size_bytes_chroma[k] = 256; @@ -846,7 +846,7 @@ void dcn5_calculate_swath_and_det_configuration(struct dml2_core_internal_scratc RoundedUpSwathSizeBytesY[k] = p->full_swath_bytes_l[k]; RoundedUpSwathSizeBytesC[k] = p->full_swath_bytes_c[k] / 2; p->request_size_bytes_luma[k] = 256; - p->request_size_bytes_chroma[k] = dml2_core_utils_get_segment_horizontal_contiguous(p->BytePerPixC[k], p->display_cfg->plane_descriptors[k].surface.tiling) + p->request_size_bytes_chroma[k] = dml2_core_utils_get_segment_horizontal_contiguous(p->display_cfg->plane_descriptors[k].surface.tiling, p->BytePerPixC[k]) == dml2_core_utils_is_vertical_rotation(p->display_cfg->plane_descriptors[k].composition.rotation_angle) ? 64 : 128; } else { @@ -854,9 +854,9 @@ void dcn5_calculate_swath_and_det_configuration(struct dml2_core_internal_scratc p->SwathHeightC[k] = MaximumSwathHeightC[k] / 2; RoundedUpSwathSizeBytesY[k] = p->full_swath_bytes_l[k] / 2; RoundedUpSwathSizeBytesC[k] = p->full_swath_bytes_c[k] / 2; - p->request_size_bytes_luma[k] = dml2_core_utils_get_segment_horizontal_contiguous(p->BytePerPixY[k], p->display_cfg->plane_descriptors[k].surface.tiling) + p->request_size_bytes_luma[k] = dml2_core_utils_get_segment_horizontal_contiguous(p->display_cfg->plane_descriptors[k].surface.tiling, p->BytePerPixY[k]) == dml2_core_utils_is_vertical_rotation(p->display_cfg->plane_descriptors[k].composition.rotation_angle) ? 64 : 128; - p->request_size_bytes_chroma[k] = dml2_core_utils_get_segment_horizontal_contiguous(p->BytePerPixC[k], p->display_cfg->plane_descriptors[k].surface.tiling) + p->request_size_bytes_chroma[k] = dml2_core_utils_get_segment_horizontal_contiguous(p->display_cfg->plane_descriptors[k].surface.tiling, p->BytePerPixC[k]) == dml2_core_utils_is_vertical_rotation(p->display_cfg->plane_descriptors[k].composition.rotation_angle) ? 64 : 128; } diff --git a/drivers/gpu/drm/amd/display/dc/dpp/dcn10/dcn10_dpp.c b/drivers/gpu/drm/amd/display/dc/dpp/dcn10/dcn10_dpp.c index ef605e0a75e389..ef9f0bcdd22b19 100644 --- a/drivers/gpu/drm/amd/display/dc/dpp/dcn10/dcn10_dpp.c +++ b/drivers/gpu/drm/amd/display/dc/dpp/dcn10/dcn10_dpp.c @@ -342,6 +342,9 @@ void dpp1_cnv_setup ( case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: pixel_format = 8; break; + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: + pixel_format = 9; + break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: pixel_format = 10; diff --git a/drivers/gpu/drm/amd/display/dc/dpp/dcn20/dcn20_dpp.c b/drivers/gpu/drm/amd/display/dc/dpp/dcn20/dcn20_dpp.c index 8d50007909040b..dde02ea4016ddf 100644 --- a/drivers/gpu/drm/amd/display/dc/dpp/dcn20/dcn20_dpp.c +++ b/drivers/gpu/drm/amd/display/dc/dpp/dcn20/dcn20_dpp.c @@ -141,6 +141,9 @@ static void dpp2_cnv_setup ( case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: pixel_format = 8; break; + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: + pixel_format = 9; + break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: pixel_format = 10; diff --git a/drivers/gpu/drm/amd/display/dc/dpp/dcn201/dcn201_dpp.c b/drivers/gpu/drm/amd/display/dc/dpp/dcn201/dcn201_dpp.c index d78ab3ffd95dbc..e120e6f10c85da 100644 --- a/drivers/gpu/drm/amd/display/dc/dpp/dcn201/dcn201_dpp.c +++ b/drivers/gpu/drm/amd/display/dc/dpp/dcn201/dcn201_dpp.c @@ -85,6 +85,9 @@ static void dpp201_cnv_setup( case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: pixel_format = 8; break; + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: + pixel_format = 9; + break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: pixel_format = 10; diff --git a/drivers/gpu/drm/amd/display/dc/dpp/dcn30/dcn30_dpp.c b/drivers/gpu/drm/amd/display/dc/dpp/dcn30/dcn30_dpp.c index 2ebc738c37f286..6e8744e7d26059 100644 --- a/drivers/gpu/drm/amd/display/dc/dpp/dcn30/dcn30_dpp.c +++ b/drivers/gpu/drm/amd/display/dc/dpp/dcn30/dcn30_dpp.c @@ -263,6 +263,9 @@ void dpp3_cnv_setup ( case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: pixel_format = 8; break; + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: + pixel_format = 9; + break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: pixel_format = 10; diff --git a/drivers/gpu/drm/amd/display/dc/dpp/dcn401/dcn401_dpp.c b/drivers/gpu/drm/amd/display/dc/dpp/dcn401/dcn401_dpp.c index 8e0fa7be34ee73..c24c457f29354c 100644 --- a/drivers/gpu/drm/amd/display/dc/dpp/dcn401/dcn401_dpp.c +++ b/drivers/gpu/drm/amd/display/dc/dpp/dcn401/dcn401_dpp.c @@ -97,6 +97,9 @@ void dpp401_dpp_setup( case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: pixel_format = 8; break; + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: + pixel_format = 9; + break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: pixel_format = 10; diff --git a/drivers/gpu/drm/amd/display/dc/dpp/dcn42/dcn42_dpp.c b/drivers/gpu/drm/amd/display/dc/dpp/dcn42/dcn42_dpp.c index eed86f5ae731bf..084b659958f737 100644 --- a/drivers/gpu/drm/amd/display/dc/dpp/dcn42/dcn42_dpp.c +++ b/drivers/gpu/drm/amd/display/dc/dpp/dcn42/dcn42_dpp.c @@ -157,6 +157,9 @@ static void dpp42_dpp_setup( case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: pixel_format = 8; break; + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: + pixel_format = 9; + break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: pixel_format = 10; diff --git a/drivers/gpu/drm/amd/display/dc/dpp/dcn50/dcn50_dpp.c b/drivers/gpu/drm/amd/display/dc/dpp/dcn50/dcn50_dpp.c index 38739ed048fae8..865305995ebc71 100644 --- a/drivers/gpu/drm/amd/display/dc/dpp/dcn50/dcn50_dpp.c +++ b/drivers/gpu/drm/amd/display/dc/dpp/dcn50/dcn50_dpp.c @@ -129,6 +129,9 @@ void dpp50_dpp_setup( case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: pixel_format = 8; break; + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: + pixel_format = 9; + break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: pixel_format = 10; diff --git a/drivers/gpu/drm/amd/display/dc/dpp/dcn60/dcn60_dpp.c b/drivers/gpu/drm/amd/display/dc/dpp/dcn60/dcn60_dpp.c index be2effb14fc3fe..aa59fe2c6954b5 100644 --- a/drivers/gpu/drm/amd/display/dc/dpp/dcn60/dcn60_dpp.c +++ b/drivers/gpu/drm/amd/display/dc/dpp/dcn60/dcn60_dpp.c @@ -62,6 +62,9 @@ void dpp60_dpp_setup( case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: pixel_format = 8; break; + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: + pixel_format = 9; + break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: pixel_format = 10; diff --git a/drivers/gpu/drm/amd/display/dc/hubbub/dcn10/dcn10_hubbub.c b/drivers/gpu/drm/amd/display/dc/hubbub/dcn10/dcn10_hubbub.c index 4e33648f74bbef..507b8e8a7077ee 100644 --- a/drivers/gpu/drm/amd/display/dc/hubbub/dcn10/dcn10_hubbub.c +++ b/drivers/gpu/drm/amd/display/dc/hubbub/dcn10/dcn10_hubbub.c @@ -760,6 +760,7 @@ static bool hubbub1_dcc_support_pixel_format( return true; case SURFACE_PIXEL_FORMAT_GRPH_ARGB8888: case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: *bytes_per_element = 4; diff --git a/drivers/gpu/drm/amd/display/dc/hubbub/dcn20/dcn20_hubbub.c b/drivers/gpu/drm/amd/display/dc/hubbub/dcn20/dcn20_hubbub.c index e5b55fe502ca6b..94c60c6287ce49 100644 --- a/drivers/gpu/drm/amd/display/dc/hubbub/dcn20/dcn20_hubbub.c +++ b/drivers/gpu/drm/amd/display/dc/hubbub/dcn20/dcn20_hubbub.c @@ -147,6 +147,7 @@ bool hubbub2_dcc_support_pixel_format( return true; case SURFACE_PIXEL_FORMAT_GRPH_ARGB8888: case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: case SURFACE_PIXEL_FORMAT_GRPH_RGB111110_FIX: diff --git a/drivers/gpu/drm/amd/display/dc/hubbub/dcn401/dcn401_hubbub.c b/drivers/gpu/drm/amd/display/dc/hubbub/dcn401/dcn401_hubbub.c index 957e8f5a647532..7fae4df3252a94 100644 --- a/drivers/gpu/drm/amd/display/dc/hubbub/dcn401/dcn401_hubbub.c +++ b/drivers/gpu/drm/amd/display/dc/hubbub/dcn401/dcn401_hubbub.c @@ -671,6 +671,7 @@ bool hubbub401_dcc_support_pixel_format( return true; case SURFACE_PIXEL_FORMAT_GRPH_ARGB8888: case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010_XR_BIAS: diff --git a/drivers/gpu/drm/amd/display/dc/hubp/dcn10/dcn10_hubp.c b/drivers/gpu/drm/amd/display/dc/hubp/dcn10/dcn10_hubp.c index 2a4be0c7a724b5..4723a390297ceb 100644 --- a/drivers/gpu/drm/amd/display/dc/hubp/dcn10/dcn10_hubp.c +++ b/drivers/gpu/drm/amd/display/dc/hubp/dcn10/dcn10_hubp.c @@ -272,6 +272,10 @@ void hubp1_program_pixel_format( REG_UPDATE(DCSURF_SURFACE_CONFIG, SURFACE_PIXEL_FORMAT, 8); break; + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: + REG_UPDATE(DCSURF_SURFACE_CONFIG, + SURFACE_PIXEL_FORMAT, 9); + break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010_XR_BIAS: diff --git a/drivers/gpu/drm/amd/display/dc/hubp/dcn20/dcn20_hubp.c b/drivers/gpu/drm/amd/display/dc/hubp/dcn20/dcn20_hubp.c index 79a42981406179..e82bb43be00118 100644 --- a/drivers/gpu/drm/amd/display/dc/hubp/dcn20/dcn20_hubp.c +++ b/drivers/gpu/drm/amd/display/dc/hubp/dcn20/dcn20_hubp.c @@ -473,6 +473,10 @@ void hubp2_program_pixel_format( REG_UPDATE(DCSURF_SURFACE_CONFIG, SURFACE_PIXEL_FORMAT, 8); break; + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: + REG_UPDATE(DCSURF_SURFACE_CONFIG, + SURFACE_PIXEL_FORMAT, 9); + break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010_XR_BIAS: diff --git a/drivers/gpu/drm/amd/display/dc/hubp/dcn35/dcn35_hubp.c b/drivers/gpu/drm/amd/display/dc/hubp/dcn35/dcn35_hubp.c index c879f4901c7df8..69b5d41c959e74 100644 --- a/drivers/gpu/drm/amd/display/dc/hubp/dcn35/dcn35_hubp.c +++ b/drivers/gpu/drm/amd/display/dc/hubp/dcn35/dcn35_hubp.c @@ -94,6 +94,10 @@ void hubp35_program_pixel_format( REG_UPDATE(DCSURF_SURFACE_CONFIG, SURFACE_PIXEL_FORMAT, 8); break; + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: + REG_UPDATE(DCSURF_SURFACE_CONFIG, + SURFACE_PIXEL_FORMAT, 9); + break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010_XR_BIAS: diff --git a/drivers/gpu/drm/amd/display/dc/hubp/dcn42/dcn42_hubp.c b/drivers/gpu/drm/amd/display/dc/hubp/dcn42/dcn42_hubp.c index 0c8a23cef1e0bd..b70fc7c1c80d7d 100644 --- a/drivers/gpu/drm/amd/display/dc/hubp/dcn42/dcn42_hubp.c +++ b/drivers/gpu/drm/amd/display/dc/hubp/dcn42/dcn42_hubp.c @@ -78,6 +78,10 @@ static void hubp42_program_pixel_format( REG_UPDATE(DCSURF_SURFACE_CONFIG, SURFACE_PIXEL_FORMAT, 8); break; + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: + REG_UPDATE(DCSURF_SURFACE_CONFIG, + SURFACE_PIXEL_FORMAT, 9); + break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010_XR_BIAS: diff --git a/drivers/gpu/drm/amd/display/dc/hubp/dcn50/dcn50_hubp.c b/drivers/gpu/drm/amd/display/dc/hubp/dcn50/dcn50_hubp.c index ba86e30b118040..af3ffb31daf221 100644 --- a/drivers/gpu/drm/amd/display/dc/hubp/dcn50/dcn50_hubp.c +++ b/drivers/gpu/drm/amd/display/dc/hubp/dcn50/dcn50_hubp.c @@ -306,6 +306,10 @@ static void hubp50_program_pixel_format( REG_UPDATE(DCSURF_SURFACE_CONFIG, SURFACE_PIXEL_FORMAT, 8); break; + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: + REG_UPDATE(DCSURF_SURFACE_CONFIG, + SURFACE_PIXEL_FORMAT, 9); + break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010: case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010_XR_BIAS: diff --git a/drivers/gpu/drm/amd/display/dc/hwss/dce/dce_hwseq.c b/drivers/gpu/drm/amd/display/dc/hwss/dce/dce_hwseq.c index 0f44577572fbef..9b8d4d1a2cbe28 100644 --- a/drivers/gpu/drm/amd/display/dc/hwss/dce/dce_hwseq.c +++ b/drivers/gpu/drm/amd/display/dc/hwss/dce/dce_hwseq.c @@ -228,6 +228,7 @@ bool dce_use_lut(enum surface_pixel_format format) switch (format) { case SURFACE_PIXEL_FORMAT_GRPH_ARGB8888: case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: return true; default: return false; 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 7b3aa02dda63b9..8667252fd2b0fb 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 @@ -265,6 +265,7 @@ static void dce110_prescale_params(struct ipp_prescale_params *prescale_params, break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB8888: case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888: + case SURFACE_PIXEL_FORMAT_GRPH_RGBA8888: prescale_params->scale = 0x2020; break; case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010: diff --git a/drivers/gpu/drm/amd/display/dc/link/link_detection.c b/drivers/gpu/drm/amd/display/dc/link/link_detection.c index b4546f93af0cc1..386bdb0f2b5d6f 100644 --- a/drivers/gpu/drm/amd/display/dc/link/link_detection.c +++ b/drivers/gpu/drm/amd/display/dc/link/link_detection.c @@ -1127,11 +1127,16 @@ static bool detect_link_and_local_sink(struct dc_link *link, (!link->dc->config.allow_edp_hotplug_detection)) && link->local_sink) { // need to re-write OUI and brightness in resume case - if (link->connector_signal == SIGNAL_TYPE_EDP && - (link->dpcd_sink_ext_caps.bits.oled == 1)) { - dpcd_set_source_specific_data(link); - msleep(post_oui_delay); - set_default_brightness_aux(link); + if (link->connector_signal == SIGNAL_TYPE_EDP) { + if (!link->dc->config.edp_no_power_sequencing) + link->dc->hwss.edp_power_control(link, true); + link->dc->hwss.edp_wait_for_hpd_ready(link, true); + + if (link->dpcd_sink_ext_caps.bits.oled == 1) { + dpcd_set_source_specific_data(link); + msleep(post_oui_delay); + set_default_brightness_aux(link); + } } return true; diff --git a/drivers/gpu/drm/amd/display/dc/link/link_dpms.c b/drivers/gpu/drm/amd/display/dc/link/link_dpms.c index 382ad9bd4e57c1..1a5dca9d03ce03 100644 --- a/drivers/gpu/drm/amd/display/dc/link/link_dpms.c +++ b/drivers/gpu/drm/amd/display/dc/link/link_dpms.c @@ -2815,11 +2815,11 @@ enum dc_status link_set_dpms_on( switch (step_result) { case DC_DPMS_SUCCESS: - case DC_DPMS_FAILED_HANDSHAKE: // Enum is ordered from "best" to "worst" results result = max(result, step_result); break; + case DC_DPMS_FAILED_HANDSHAKE: case DC_DPMS_SKIPPED_HANDSHAKE: return step_result; diff --git a/drivers/gpu/drm/amd/display/dc/link/protocols/link_hdmi_frl.c b/drivers/gpu/drm/amd/display/dc/link/protocols/link_hdmi_frl.c index 960f18fe275b23..27d413c2bdd6fc 100644 --- a/drivers/gpu/drm/amd/display/dc/link/protocols/link_hdmi_frl.c +++ b/drivers/gpu/drm/amd/display/dc/link/protocols/link_hdmi_frl.c @@ -1159,6 +1159,10 @@ static void update_borrow_mode_from_dsc_padding(struct dsc_padding_params *dsc_p uint32_t h_blank = timing->h_total - h_active; struct frl_borrow_params *borrow_params = &frl_link_settings->borrow_params; + if (dsc_padding_params->dsc_hactive_padding == 0 && + dsc_padding_params->dsc_htotal_padding == 0) + return; + borrow_params->borrow_mode = frl_modify_borrow_mode_for_dsc_padding(timing->pix_clk_100hz, h_active, h_active + dsc_padding_params->dsc_hactive_padding, diff --git a/drivers/gpu/drm/amd/display/dc/optc/dcn31/dcn31_optc.c b/drivers/gpu/drm/amd/display/dc/optc/dcn31/dcn31_optc.c index ce9cd32b807aca..7706f5f16a686b 100644 --- a/drivers/gpu/drm/amd/display/dc/optc/dcn31/dcn31_optc.c +++ b/drivers/gpu/drm/amd/display/dc/optc/dcn31/dcn31_optc.c @@ -143,6 +143,10 @@ static bool optc31_disable_crtc(struct timing_generator *optc) 1, 100000); optc1_clear_optc_underflow(optc); + /* a stale frame-lock force-vsync would cut every DRR-triggered frame short on reuse */ + REG_UPDATE(OTG_VERT_SYNC_CONTROL, + OTG_AUTO_FORCE_VSYNC_MODE, 0); + return true; } /* diff --git a/drivers/gpu/drm/amd/display/dc/optc/dcn314/dcn314_optc.c b/drivers/gpu/drm/amd/display/dc/optc/dcn314/dcn314_optc.c index f5faa49680ef8d..5ec70e849cce89 100644 --- a/drivers/gpu/drm/amd/display/dc/optc/dcn314/dcn314_optc.c +++ b/drivers/gpu/drm/amd/display/dc/optc/dcn314/dcn314_optc.c @@ -142,6 +142,10 @@ static bool optc314_disable_crtc(struct timing_generator *optc) OTG_BUSY, 0, 1, 100000); + /* a stale frame-lock force-vsync would cut every DRR-triggered frame short on reuse */ + REG_UPDATE(OTG_VERT_SYNC_CONTROL, + OTG_AUTO_FORCE_VSYNC_MODE, 0); + return true; } diff --git a/drivers/gpu/drm/amd/display/dc/optc/dcn35/dcn35_optc.c b/drivers/gpu/drm/amd/display/dc/optc/dcn35/dcn35_optc.c index 406446e5eae548..b4b4792167dddf 100644 --- a/drivers/gpu/drm/amd/display/dc/optc/dcn35/dcn35_optc.c +++ b/drivers/gpu/drm/amd/display/dc/optc/dcn35/dcn35_optc.c @@ -162,6 +162,10 @@ static bool optc35_disable_crtc(struct timing_generator *optc) optc1_clear_optc_underflow(optc); + /* a stale frame-lock force-vsync would cut every DRR-triggered frame short on reuse */ + REG_UPDATE(OTG_VERT_SYNC_CONTROL, + OTG_AUTO_FORCE_VSYNC_MODE, 0); + return true; } diff --git a/drivers/gpu/drm/amd/display/dmub/dmub_srv.h b/drivers/gpu/drm/amd/display/dmub/dmub_srv.h index 17579ff2e1bf7e..84f825c924bc1f 100644 --- a/drivers/gpu/drm/amd/display/dmub/dmub_srv.h +++ b/drivers/gpu/drm/amd/display/dmub/dmub_srv.h @@ -76,6 +76,8 @@ #define PSP_HEADER_BYTES_256 0x100 // 256 bytes #define PSP_FOOTER_BYTES_256 0x100 // 256 bytes +#define PSP_FOOTER_BYTES_512 0x200 // 512 bytes +#define PSP_FOOTER_BYTES_1932 0x78C // 1932 bytes /* Forward declarations */ struct dmub_srv; diff --git a/drivers/gpu/drm/amd/display/dmub/src/dmub_srv.c b/drivers/gpu/drm/amd/display/dmub/src/dmub_srv.c index 41b14b137643d5..72fc28feefb26f 100644 --- a/drivers/gpu/drm/amd/display/dmub/src/dmub_srv.c +++ b/drivers/gpu/drm/amd/display/dmub/src/dmub_srv.c @@ -173,30 +173,43 @@ dmub_srv_get_fw_meta_info_from_raw_fw(struct dmub_srv_fw_meta_info_params *param uint32_t inst_const_size_temp = params->inst_const_size; /* First try custom psp footer size, if present */ - if (params->custom_psp_footer_size) { - params->inst_const_size -= params->custom_psp_footer_size; + if (params->custom_psp_footer_size && inst_const_size_temp > params->custom_psp_footer_size) { + params->inst_const_size = inst_const_size_temp - params->custom_psp_footer_size; fw_info = dmub_get_fw_meta_info(params); if (fw_info) { memcpy(fw_info_out, fw_info, sizeof(*fw_info)); return DMUB_STATUS_OK; } - params->inst_const_size = inst_const_size_temp; } /* Try 256-byte psp footer size */ - params->inst_const_size -= PSP_FOOTER_BYTES_256; - fw_info = dmub_get_fw_meta_info(params); - if (fw_info) { - memcpy(fw_info_out, fw_info, sizeof(*fw_info)); - return DMUB_STATUS_OK; + if (inst_const_size_temp > PSP_FOOTER_BYTES_256) { + params->inst_const_size = inst_const_size_temp - PSP_FOOTER_BYTES_256; + fw_info = dmub_get_fw_meta_info(params); + if (fw_info) { + memcpy(fw_info_out, fw_info, sizeof(*fw_info)); + return DMUB_STATUS_OK; + } } - /* Try 512-byte psp footer size - final attempt */ - params->inst_const_size -= PSP_FOOTER_BYTES_256; // 256 bytes already subtracted, subtract 256 again - fw_info = dmub_get_fw_meta_info(params); - if (fw_info) { - memcpy(fw_info_out, fw_info, sizeof(*fw_info)); - return DMUB_STATUS_OK; + /* Try 512-byte psp footer size */ + if (inst_const_size_temp > PSP_FOOTER_BYTES_512) { + params->inst_const_size = inst_const_size_temp - PSP_FOOTER_BYTES_512; + fw_info = dmub_get_fw_meta_info(params); + if (fw_info) { + memcpy(fw_info_out, fw_info, sizeof(*fw_info)); + return DMUB_STATUS_OK; + } + } + + /* Try 1932-byte psp footer size */ + if (inst_const_size_temp > PSP_FOOTER_BYTES_1932) { + params->inst_const_size = inst_const_size_temp - PSP_FOOTER_BYTES_1932; + fw_info = dmub_get_fw_meta_info(params); + if (fw_info) { + memcpy(fw_info_out, fw_info, sizeof(*fw_info)); + return DMUB_STATUS_OK; + } } /* Restore original inst_const_size and subtract default PSP footer size - default behaviour */ diff --git a/drivers/gpu/drm/amd/display/modules/freesync/freesync.c b/drivers/gpu/drm/amd/display/modules/freesync/freesync.c index f154a619b53390..21165855cb9276 100644 --- a/drivers/gpu/drm/amd/display/modules/freesync/freesync.c +++ b/drivers/gpu/drm/amd/display/modules/freesync/freesync.c @@ -571,6 +571,12 @@ static bool vrr_settings_require_update(struct core_freesync *core_freesync, return false; } +/* v1/v2 packets hold each rate in one byte; saturate instead of wrapping. */ +static unsigned char vrr_refresh_hz_u8(unsigned int refresh_in_uhz) +{ + return min((refresh_in_uhz + 500000) / 1000000, 255U); +} + static void build_vrr_infopacket_data_v1(const struct mod_vrr_params *vrr, struct dc_info_packet *infopacket, bool freesync_on_desktop) @@ -614,15 +620,15 @@ static void build_vrr_infopacket_data_v1(const struct mod_vrr_params *vrr, /* PB7 = FreeSync Minimum refresh rate (Hz) */ if (vrr->state == VRR_STATE_ACTIVE_VARIABLE || vrr->state == VRR_STATE_ACTIVE_FIXED) { - infopacket->sb[7] = (unsigned char)((vrr->min_refresh_in_uhz + 500000) / 1000000); + infopacket->sb[7] = vrr_refresh_hz_u8(vrr->min_refresh_in_uhz); } else { - infopacket->sb[7] = (unsigned char)((vrr->max_refresh_in_uhz + 500000) / 1000000); + infopacket->sb[7] = vrr_refresh_hz_u8(vrr->max_refresh_in_uhz); } /* PB8 = FreeSync Maximum refresh rate (Hz) * Note: We should never go above the field rate of the mode timing set. */ - infopacket->sb[8] = (unsigned char)((vrr->max_refresh_in_uhz + 500000) / 1000000); + infopacket->sb[8] = vrr_refresh_hz_u8(vrr->max_refresh_in_uhz); } static void build_vrr_infopacket_data_v3(const struct mod_vrr_params *vrr, diff --git a/drivers/gpu/drm/amd/display/modules/power/power_psr.c b/drivers/gpu/drm/amd/display/modules/power/power_psr.c index 96bb77fff05b86..7139395b5c0066 100644 --- a/drivers/gpu/drm/amd/display/modules/power/power_psr.c +++ b/drivers/gpu/drm/amd/display/modules/power/power_psr.c @@ -94,9 +94,12 @@ bool mod_power_psr_notify_mode_change(struct mod_power *mod_power, * The value of DSC slice height is determined in DSC Driver but it does not * propagated out here, so we need to calculate it as below 'slice_height'. */ - psr_su_set_dsc_slice_height(dc, link, - (struct dc_stream_state *) stream, - &psr_config); + if (link->psr_settings.psr_version == DC_PSR_VERSION_SU_1) { + if (!psr_su_set_dsc_slice_height(dc, link, + (struct dc_stream_state *)stream, + &psr_config)) + return false; + } dc_link_setup_psr(link, stream, &psr_config, &psr_context); diff --git a/drivers/gpu/drm/amd/display/modules/power/power_replay.c b/drivers/gpu/drm/amd/display/modules/power/power_replay.c index 666585b7e00c38..8e2fab1db13ca8 100644 --- a/drivers/gpu/drm/amd/display/modules/power/power_replay.c +++ b/drivers/gpu/drm/amd/display/modules/power/power_replay.c @@ -232,6 +232,7 @@ static bool mod_power_update_replay_active_status(unsigned int active_replay_eve replay_event_sleep_resume | replay_event_disable_in_AC | replay_event_disable_replay_while_detect_display | + replay_event_waiting_stream_regen | replay_event_infopacket | replay_event_crc_window_active)) return false; diff --git a/drivers/gpu/drm/amd/pm/amdgpu_dpm.c b/drivers/gpu/drm/amd/pm/amdgpu_dpm.c index 75d8bb4868e89e..ea698fe48e0782 100644 --- a/drivers/gpu/drm/amd/pm/amdgpu_dpm.c +++ b/drivers/gpu/drm/amd/pm/amdgpu_dpm.c @@ -1083,14 +1083,16 @@ static void amdgpu_dpm_exit_umd_state(struct amdgpu_device *adev) } /** - * amdgpu_dpm_reapply_umd_profile - Restore the active UMD profile + * amdgpu_dpm_reapply_performance_level - Restore the retained DPM level * @adev: amdgpu device * * Resume and reset retain the selected DPM level in software, but the - * underlying GFX and PMFW state is lost. Reapply a retained UMD profile - * after the common resume path has restored its default CG and PG state. + * underlying GFX and PMFW state is lost. Reapply the retained level after + * the common resume path has restored its default CG and PG state. UMD + * profile levels also restore their GFX state, other levels only replay + * the level itself. */ -int amdgpu_dpm_reapply_umd_profile(struct amdgpu_device *adev) +int amdgpu_dpm_reapply_performance_level(struct amdgpu_device *adev) { const struct amd_pm_funcs *pp_funcs = adev->powerplay.pp_funcs; enum amd_dpm_forced_level level; @@ -1120,7 +1122,18 @@ int amdgpu_dpm_reapply_umd_profile(struct amdgpu_device *adev) case AMD_DPM_FORCED_LEVEL_PROFILE_MIN_MCLK: case AMD_DPM_FORCED_LEVEL_PROFILE_PEAK: break; + case AMD_DPM_FORCED_LEVEL_AUTO: + /* PMFW comes back in auto, as it does at probe. */ + ret = 0; + goto unlock; default: + /* No UMD pstate state to restore, only the level itself. */ + ret = pp_funcs->reapply_performance_level(adev->powerplay.pp_handle, + level); + if (ret) + dev_warn(adev->dev, + "Failed to restore performance level %d: %d\n", + level, ret); ret = 0; goto unlock; } diff --git a/drivers/gpu/drm/amd/pm/inc/amdgpu_dpm.h b/drivers/gpu/drm/amd/pm/inc/amdgpu_dpm.h index ba8624d28f28b4..8ae3fcc016f80a 100644 --- a/drivers/gpu/drm/amd/pm/inc/amdgpu_dpm.h +++ b/drivers/gpu/drm/amd/pm/inc/amdgpu_dpm.h @@ -484,7 +484,7 @@ void amdgpu_dpm_set_power_state(struct amdgpu_device *adev, enum amd_dpm_forced_level amdgpu_dpm_get_performance_level(struct amdgpu_device *adev); int amdgpu_dpm_force_performance_level(struct amdgpu_device *adev, enum amd_dpm_forced_level level); -int amdgpu_dpm_reapply_umd_profile(struct amdgpu_device *adev); +int amdgpu_dpm_reapply_performance_level(struct amdgpu_device *adev); int amdgpu_dpm_get_pp_num_states(struct amdgpu_device *adev, struct pp_states_info *states); int amdgpu_dpm_dispatch_task(struct amdgpu_device *adev, diff --git a/drivers/gpu/drm/amd/pm/powerplay/hwmgr/smu8_hwmgr.c b/drivers/gpu/drm/amd/pm/powerplay/hwmgr/smu8_hwmgr.c index 8f82d7c07e8c82..5a3f697a37a254 100644 --- a/drivers/gpu/drm/amd/pm/powerplay/hwmgr/smu8_hwmgr.c +++ b/drivers/gpu/drm/amd/pm/powerplay/hwmgr/smu8_hwmgr.c @@ -1483,15 +1483,25 @@ static int smu8_store_cc6_data(struct pp_hwmgr *hwmgr, uint32_t separation_time, static int smu8_force_clock_level(struct pp_hwmgr *hwmgr, enum pp_clock_type type, uint32_t mask) { + struct phm_clock_voltage_dependency_table *table = + hwmgr->dyn_state.vddc_dependency_on_sclk; + uint32_t low, high; + switch (type) { case PP_SCLK: + /* the SMU takes level indices, not a mask of levels */ + low = mask ? (ffs(mask) - 1) : 0; + high = mask ? (fls(mask) - 1) : 0; + if (high >= min(table->count, smu8_get_max_sclk_level(hwmgr))) + return -EINVAL; + smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_SetSclkSoftMin, - mask, + low, NULL); smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_SetSclkSoftMax, - mask, + high, NULL); break; default: diff --git a/drivers/gpu/drm/amd/pm/swsmu/amdgpu_smu.c b/drivers/gpu/drm/amd/pm/swsmu/amdgpu_smu.c index c9fe323fa6244e..76d45549ae2ee5 100644 --- a/drivers/gpu/drm/amd/pm/swsmu/amdgpu_smu.c +++ b/drivers/gpu/drm/amd/pm/swsmu/amdgpu_smu.c @@ -2505,33 +2505,7 @@ static int smu_reapply_power_state_dynamic(struct smu_context *smu, enum amd_dpm_forced_level level) { - struct smu_dpm_context *smu_dpm_ctx = &smu->smu_dpm; - int ret; - - ret = smu_apply_clocks_adjust_rules(smu); - if (ret) { - dev_err(smu->adev->dev, "Failed to apply clocks adjust rules!"); - return ret; - } - - ret = smu_asic_set_performance_level(smu, level); - if (ret) { - if (ret == -EOPNOTSUPP) - dev_info(smu->adev->dev, "set performance level %d not supported", - level); - else - dev_err(smu->adev->dev, "Failed to set performance level %d", - level); - return ret; - } - - smu_dpm_ctx->dpm_level = level; - - if (smu_dpm_ctx->dpm_level == AMD_DPM_FORCED_LEVEL_MANUAL || - smu_dpm_ctx->dpm_level == AMD_DPM_FORCED_LEVEL_PERF_DETERMINISM) - return 0; - - return smu_bump_power_profile_mode(smu, NULL, 0); + return smu_adjust_power_state_dynamic(smu, level, true, true); } static int smu_handle_task(struct smu_context *smu, @@ -2696,21 +2670,20 @@ smu_reapply_performance_level(void *handle, if (!smu->is_apu && !smu_dpm_ctx->dpm_context) return -EINVAL; + if (smu_dpm_ctx->dpm_level != level) + return -EINVAL; + switch (level) { case AMD_DPM_FORCED_LEVEL_PROFILE_STANDARD: case AMD_DPM_FORCED_LEVEL_PROFILE_MIN_SCLK: case AMD_DPM_FORCED_LEVEL_PROFILE_MIN_MCLK: case AMD_DPM_FORCED_LEVEL_PROFILE_PEAK: + smu_enter_umd_pstate(smu); break; default: - return -EINVAL; + break; } - if (smu_dpm_ctx->dpm_level != level) - return -EINVAL; - - smu_enter_umd_pstate(smu); - return smu_reapply_power_state_dynamic(smu, level); } diff --git a/drivers/gpu/drm/ast/Kconfig b/drivers/gpu/drm/ast/Kconfig index 242fbccdf84432..f2c99e99b5b44d 100644 --- a/drivers/gpu/drm/ast/Kconfig +++ b/drivers/gpu/drm/ast/Kconfig @@ -14,3 +14,12 @@ config DRM_AST is bound to the driver. These GPUs are commonly found in server chipsets. +config DRM_AST_DISABLE_WRITECOMBINE + bool "Disable Write Combine mapping of VRAM" + depends on DRM_AST && (PREEMPT_RT || COMPILE_TEST) + help + The VRAM of AST GPUs is mapped with Write-Combine to improve + performances. This can interfere with real-time tasks; even if they + are running on other CPU cores than the graphics output. + Enable this option only if you run real-time tasks on a server with + Aspeed graphics. diff --git a/drivers/gpu/drm/ast/ast_mm.c b/drivers/gpu/drm/ast/ast_mm.c index 0bc14031946491..cc882d2c172d04 100644 --- a/drivers/gpu/drm/ast/ast_mm.c +++ b/drivers/gpu/drm/ast/ast_mm.c @@ -74,6 +74,18 @@ int ast_mm_init(struct ast_device *ast) { struct drm_device *dev = &ast->base; struct pci_dev *pdev = to_pci_dev(dev->dev); +#if defined(CONFIG_DRM_AST_DISABLE_WRITECOMBINE) + resource_size_t base; + u32 vram_size; + + base = pci_resource_start(pdev, 0); + + vram_size = ast_get_vram_size(ast); + + ast->vram = devm_ioremap(dev->dev, base, vram_size); + if (!ast->vram) + return -ENOMEM; +#else resource_size_t base, size; u32 vram_size; @@ -89,6 +101,7 @@ int ast_mm_init(struct ast_device *ast) ast->vram = devm_ioremap_wc(dev->dev, base, vram_size); if (!ast->vram) return -ENOMEM; +#endif ast->vram_base = base; ast->vram_size = vram_size; diff --git a/drivers/gpu/drm/drm_panic_helper.c b/drivers/gpu/drm/drm_panic_helper.c index 8913c3d22e8d31..385a07ed314bc2 100644 --- a/drivers/gpu/drm/drm_panic_helper.c +++ b/drivers/gpu/drm/drm_panic_helper.c @@ -513,7 +513,8 @@ VISIBLE_IF_KUNIT int drm_panic_helper_draw_screen_kmsg(struct drm_scanout_buffer const struct font_desc *font = get_default_font(sb->width, sb->height, NULL, NULL); struct drm_rect r_screen = DRM_RECT_INIT(0, 0, sb->width, sb->height); struct kmsg_dump_iter iter; - char kmsg_buf[512]; + /* the size printk formats one record into, too big for the stack */ + static char kmsg_buf[2048]; size_t kmsg_len; struct drm_panic_line line; int yoffset; @@ -530,10 +531,15 @@ VISIBLE_IF_KUNIT int drm_panic_helper_draw_screen_kmsg(struct drm_scanout_buffer drm_panic_helper_fill(sb, &r_screen, bg_color); kmsg_dump_rewind(&iter); - while (kmsg_dump_get_buffer(&iter, false, kmsg_buf, sizeof(kmsg_buf), &kmsg_len)) { + while (yoffset >= 0 && kmsg_dump_get_buffer(&iter, false, kmsg_buf, + sizeof(kmsg_buf), &kmsg_len)) { char *start; char *end; + /* a record that does not fit comes back empty, every time */ + if (!kmsg_len) + break; + /* ignore terminating NUL and newline */ start = kmsg_buf + kmsg_len - 2; end = kmsg_buf + kmsg_len - 1; diff --git a/drivers/gpu/drm/drm_syncobj.c b/drivers/gpu/drm/drm_syncobj.c index 137397972a98a0..6cc65464118315 100644 --- a/drivers/gpu/drm/drm_syncobj.c +++ b/drivers/gpu/drm/drm_syncobj.c @@ -199,6 +199,7 @@ #include #include #include +#include #include #include @@ -220,6 +221,16 @@ struct syncobj_wait_entry { u64 point; }; +/* + * Upper limit for the number of handles passed to a single ioctl. This is a + * fixed number so that the limit is the same on all architectures. The + * largest per-handle allocation is the wait entry array, which must stay + * below the INT_MAX size limit of kvmalloc(). + */ +#define DRM_SYNCOBJ_MAX_HANDLES SZ_1M +static_assert(DRM_SYNCOBJ_MAX_HANDLES <= + INT_MAX / sizeof(struct syncobj_wait_entry)); + static void syncobj_wait_syncobj_func(struct drm_syncobj *syncobj, struct syncobj_wait_entry *wait); @@ -1051,7 +1062,7 @@ static signed long drm_syncobj_array_wait_timeout(struct drm_syncobj **syncobjs, lockdep_assert_none_held_once(); } - points = kmalloc_objs(*points, count); + points = kvmalloc_objs(*points, count); if (points == NULL) return -ENOMEM; @@ -1064,7 +1075,7 @@ static signed long drm_syncobj_array_wait_timeout(struct drm_syncobj **syncobjs, goto err_free_points; } - entries = kzalloc_objs(*entries, count); + entries = kvzalloc_objs(*entries, count); if (!entries) { timeout = -ENOMEM; goto err_free_points; @@ -1185,10 +1196,10 @@ static signed long drm_syncobj_array_wait_timeout(struct drm_syncobj **syncobjs, &entries[i].fence_cb); dma_fence_put(entries[i].fence); } - kfree(entries); + kvfree(entries); err_free_points: - kfree(points); + kvfree(points); return timeout; } @@ -1238,7 +1249,10 @@ static int drm_syncobj_array_find(struct drm_file *file_private, struct drm_syncobj **syncobjs; int ret; - handles = kmalloc_objs(*handles, count_handles); + if (count_handles > DRM_SYNCOBJ_MAX_HANDLES) + return -EINVAL; + + handles = kvmalloc_objs(*handles, count_handles); if (handles == NULL) return -ENOMEM; @@ -1248,7 +1262,7 @@ static int drm_syncobj_array_find(struct drm_file *file_private, goto err_free_handles; } - syncobjs = kmalloc_objs(*syncobjs, count_handles); + syncobjs = kvmalloc_objs(*syncobjs, count_handles); if (syncobjs == NULL) { ret = -ENOMEM; goto err_free_handles; @@ -1262,16 +1276,16 @@ static int drm_syncobj_array_find(struct drm_file *file_private, } } - kfree(handles); + kvfree(handles); *syncobjs_out = syncobjs; return 0; err_put_syncobjs: while (i-- > 0) drm_syncobj_put(syncobjs[i]); - kfree(syncobjs); + kvfree(syncobjs); err_free_handles: - kfree(handles); + kvfree(handles); return ret; } @@ -1283,7 +1297,7 @@ static void drm_syncobj_array_free(struct drm_syncobj **syncobjs, for (i = 0; i < count; i++) drm_syncobj_put(syncobjs[i]); - kfree(syncobjs); + kvfree(syncobjs); } int @@ -1572,7 +1586,7 @@ drm_syncobj_timeline_signal_ioctl(struct drm_device *dev, void *data, if (ret < 0) return ret; - points = kmalloc_objs(*points, args->count_handles); + points = kvmalloc_objs(*points, args->count_handles); if (!points) { ret = -ENOMEM; goto out; @@ -1585,7 +1599,7 @@ drm_syncobj_timeline_signal_ioctl(struct drm_device *dev, void *data, goto err_points; } - chains = kmalloc_objs(*chains, args->count_handles); + chains = kvmalloc_objs(*chains, args->count_handles); if (!chains) { ret = -ENOMEM; goto err_points; @@ -1608,9 +1622,9 @@ drm_syncobj_timeline_signal_ioctl(struct drm_device *dev, void *data, dma_fence_put(fence); } err_chains: - kfree(chains); + kvfree(chains); err_points: - kfree(points); + kvfree(points); out: drm_syncobj_array_free(syncobjs, args->count_handles); diff --git a/drivers/gpu/drm/drm_vblank.c b/drivers/gpu/drm/drm_vblank.c index f90fb2d13e423d..c26464ca4a12ca 100644 --- a/drivers/gpu/drm/drm_vblank.c +++ b/drivers/gpu/drm/drm_vblank.c @@ -1403,6 +1403,9 @@ void drm_crtc_vblank_off(struct drm_crtc *crtc) spin_unlock_irq(&dev->event_lock); + if (crtc->funcs->sync_vblank) + crtc->funcs->sync_vblank(crtc); + /* Will be reset by the modeset helpers when re-enabling the crtc by * calling drm_calc_timestamping_constants(). */ vblank->hwmode.crtc_clock = 0; @@ -2179,19 +2182,18 @@ static enum hrtimer_restart drm_vblank_timer_function(struct hrtimer *timer) struct drm_crtc *crtc = vtimer->crtc; const struct drm_crtc_helper_funcs *crtc_funcs = crtc->helper_private; struct drm_device *dev = crtc->dev; - unsigned long flags; - ktime_t interval; - u64 ret_overrun; + u64 ret_overrun = 1; bool succ; - spin_lock_irqsave(&vtimer->interval_lock, flags); - interval = vtimer->interval; - spin_unlock_irqrestore(&vtimer->interval_lock, flags); + scoped_guard(spinlock_irqsave, &vtimer->interval_lock) { + ktime_t interval = vtimer->interval; - if (!interval) - return HRTIMER_NORESTART; + if (!interval || hrtimer_is_queued(timer)) + return HRTIMER_NORESTART; + + ret_overrun = hrtimer_forward_now(timer, interval); + } - ret_overrun = hrtimer_forward_now(&vtimer->timer, interval); if (ret_overrun != 1) drm_dbg_vbl(dev, "vblank timer overrun\n"); @@ -2220,7 +2222,6 @@ int drm_crtc_vblank_start_timer(struct drm_crtc *crtc) { struct drm_vblank_crtc *vblank = drm_crtc_vblank_crtc(crtc); struct drm_vblank_crtc_timer *vtimer = &vblank->vblank_timer; - unsigned long flags; if (!vtimer->crtc) { /* @@ -2230,22 +2231,14 @@ int drm_crtc_vblank_start_timer(struct drm_crtc *crtc) spin_lock_init(&vtimer->interval_lock); hrtimer_setup(&vtimer->timer, drm_vblank_timer_function, CLOCK_MONOTONIC, HRTIMER_MODE_REL); - } else { - /* - * Timer should not be active. If it is, wait for the - * previous cancel operations to finish. - */ - while (hrtimer_active(&vtimer->timer)) - hrtimer_try_to_cancel(&vtimer->timer); } drm_calc_timestamping_constants(crtc, &crtc->mode); - spin_lock_irqsave(&vtimer->interval_lock, flags); - vtimer->interval = ns_to_ktime(vblank->framedur_ns); - spin_unlock_irqrestore(&vtimer->interval_lock, flags); - - hrtimer_start(&vtimer->timer, vtimer->interval, HRTIMER_MODE_REL); + scoped_guard(spinlock_irqsave, &vtimer->interval_lock) { + vtimer->interval = ns_to_ktime(vblank->framedur_ns); + hrtimer_start(&vtimer->timer, vtimer->interval, HRTIMER_MODE_REL); + } return 0; } @@ -2256,28 +2249,61 @@ EXPORT_SYMBOL(drm_crtc_vblank_start_timer); * @crtc: the CRTC * * Drivers should call this function from their CRTC's disable_vblank - * function to stop a vblank timer. + * function to stop a vblank timer. Only signals the timer to stop at + * the next invocation. Non-blocking. To fully stop the vblank timer, + * drivers should invoke drm_crtc_vblank_stop_timer(). */ void drm_crtc_vblank_cancel_timer(struct drm_crtc *crtc) { struct drm_vblank_crtc *vblank = drm_crtc_vblank_crtc(crtc); struct drm_vblank_crtc_timer *vtimer = &vblank->vblank_timer; - unsigned long flags; + + if (!vtimer->crtc) + return; /* - * Calling hrtimer_cancel() can result in a deadlock with DRM's - * vblank_time_lime_lock and hrtimers' softirq_expiry_lock. So + * Calling hrtimer_cancel() here can result in a deadlock between + * DRM's vblank_time_lock and hrtimers' softirq_expiry_lock. So * clear interval and indicate cancellation. The timer function - * will cancel itself on the next invocation. + * will cancel itself on the next invocation. Otherwise cancel it + * in drm_crtc_vblank_stop_canceled_timer(). */ + scoped_guard(spinlock_irqsave, &vtimer->interval_lock) + vtimer->interval = 0; +} +EXPORT_SYMBOL(drm_crtc_vblank_cancel_timer); - spin_lock_irqsave(&vtimer->interval_lock, flags); - vtimer->interval = 0; - spin_unlock_irqrestore(&vtimer->interval_lock, flags); +/** + * drm_crtc_vblank_stop_canceled_timer - Stops a CRTC's previously canceled vblank timer + * @crtc: the CRTC + * + * Drivers should call this function from their CRTC's sync_vblank + * function to fully stop a vblank timer. The timer must have been + * canceled before. Use drm_crtc_vblank_stop_timer() to stop a vblank + * timer unconditionally. + * + * The function blocks until a running timer function has returned. + */ +void drm_crtc_vblank_stop_canceled_timer(struct drm_crtc *crtc) +{ + struct drm_vblank_crtc *vblank = drm_crtc_vblank_crtc(crtc); + struct drm_vblank_crtc_timer *vtimer = &vblank->vblank_timer; + ktime_t interval; + + if (!vtimer->crtc) + return; + + /* + * The vblank timer is off if it has an interval of zero. Cancel + * it before drm_crtc_vblank_start_timer() reprograms it. + */ + scoped_guard(spinlock_irqsave, &vtimer->interval_lock) + interval = vtimer->interval; - hrtimer_try_to_cancel(&vtimer->timer); + if (!interval) + hrtimer_cancel(&vtimer->timer); } -EXPORT_SYMBOL(drm_crtc_vblank_cancel_timer); +EXPORT_SYMBOL(drm_crtc_vblank_stop_canceled_timer); /** * drm_crtc_vblank_get_vblank_timeout - Returns the vblank timeout diff --git a/drivers/gpu/drm/drm_vblank_helper.c b/drivers/gpu/drm/drm_vblank_helper.c index d3f8147ecdc126..7465d74ce29e41 100644 --- a/drivers/gpu/drm/drm_vblank_helper.c +++ b/drivers/gpu/drm/drm_vblank_helper.c @@ -146,6 +146,22 @@ void drm_crtc_vblank_helper_disable_vblank_timer(struct drm_crtc *crtc) } EXPORT_SYMBOL(drm_crtc_vblank_helper_disable_vblank_timer); +/** + * drm_crtc_vblank_helper_sync_vblank_timer - Implements struct &drm_crtc_funcs.sync_vblank + * @crtc: The CRTC + * + * The helper drm_crtc_vblank_helper_sync_vblank_timer() implements + * sync_vblank of struct drm_crtc_funcs for CRTCs that require a + * VBLANK timer. + * + * See also struct &drm_crtc_funcs.sync_vblank. + */ +void drm_crtc_vblank_helper_sync_vblank_timer(struct drm_crtc *crtc) +{ + drm_crtc_vblank_stop_canceled_timer(crtc); +} +EXPORT_SYMBOL(drm_crtc_vblank_helper_sync_vblank_timer); + /** * drm_crtc_vblank_helper_get_vblank_timestamp_from_timer - * Implements struct &drm_crtc_funcs.get_vblank_timestamp diff --git a/drivers/gpu/drm/gud/gud_drv.c b/drivers/gpu/drm/gud/gud_drv.c index 55510bf62009c5..8d7843c2b60cba 100644 --- a/drivers/gpu/drm/gud/gud_drv.c +++ b/drivers/gpu/drm/gud/gud_drv.c @@ -329,7 +329,7 @@ static int gud_stats_debugfs(struct seq_file *m, void *data) seq_puts(m, "\n"); if (gdrm->compression) { - u64 actual_length = gdrm->stats_actual_length; + u64 actual_length = READ_ONCE(gdrm->stats_actual_length); u64 remainder; u64 ratio, ratio_frac; diff --git a/drivers/gpu/drm/i915/display/intel_alpm.c b/drivers/gpu/drm/i915/display/intel_alpm.c index f54b29e193ee93..105006ca6be7f3 100644 --- a/drivers/gpu/drm/i915/display/intel_alpm.c +++ b/drivers/gpu/drm/i915/display/intel_alpm.c @@ -46,6 +46,7 @@ bool intel_alpm_is_alpm_aux_less(struct intel_dp *intel_dp, void intel_alpm_init(struct intel_dp *intel_dp) { mutex_init(&intel_dp->alpm.lock); + intel_dp->alpm.transcoder = INVALID_TRANSCODER; } static int get_silence_period_symbols(const struct intel_crtc_state *crtc_state) @@ -549,6 +550,7 @@ static void lnl_alpm_configure(struct intel_dp *intel_dp, alpm_ctl |= ALPM_CTL_ALPM_ENTRY_CHECK(crtc_state->alpm_state.check_entry_lines); intel_de_write(display, ALPM_CTL(display, cpu_transcoder), alpm_ctl); + intel_dp->alpm.transcoder = cpu_transcoder; mutex_unlock(&intel_dp->alpm.lock); } @@ -556,7 +558,6 @@ void intel_alpm_configure(struct intel_dp *intel_dp, const struct intel_crtc_state *crtc_state) { lnl_alpm_configure(intel_dp, crtc_state); - intel_dp->alpm.transcoder = crtc_state->cpu_transcoder; } void intel_alpm_port_configure(struct intel_dp *intel_dp, @@ -733,17 +734,23 @@ void intel_alpm_lobf_debugfs_add(struct intel_connector *connector) void intel_alpm_disable(struct intel_dp *intel_dp) { struct intel_display *display = to_intel_display(intel_dp); - enum transcoder cpu_transcoder = intel_dp->alpm.transcoder; + enum transcoder cpu_transcoder; if (DISPLAY_VER(display) < 20 || !intel_dp->alpm_dpcd) return; mutex_lock(&intel_dp->alpm.lock); + cpu_transcoder = intel_dp->alpm.transcoder; + if (cpu_transcoder == INVALID_TRANSCODER) + goto unlock; + intel_de_rmw(display, ALPM_CTL(display, cpu_transcoder), ALPM_CTL_ALPM_ENABLE | ALPM_CTL_LOBF_ENABLE, 0); + intel_dp->alpm.transcoder = INVALID_TRANSCODER; drm_dbg_kms(display->drm, "Disabling ALPM\n"); +unlock: mutex_unlock(&intel_dp->alpm.lock); } diff --git a/drivers/gpu/drm/i915/display/intel_bios.c b/drivers/gpu/drm/i915/display/intel_bios.c index 7b6a6f8c3cf196..b77d1599482a76 100644 --- a/drivers/gpu/drm/i915/display/intel_bios.c +++ b/drivers/gpu/drm/i915/display/intel_bios.c @@ -41,6 +41,7 @@ #include "intel_display_types.h" #include "intel_display_utils.h" #include "intel_gmbus.h" +#include "intel_quirks.h" #include "intel_rom.h" #include "intel_vdsc.h" @@ -1575,6 +1576,10 @@ parse_edp(struct intel_display *display, if (display->vbt.version >= 261) panel->vbt.edp.pipe_joiner_enable = panel_bool(edp->pipe_joiner_enable, panel_type); + + /* Some machines need the joiner regardless of what VBT says */ + if (intel_has_quirk(display, QUIRK_ALLOW_EDP_JOINER)) + panel->vbt.edp.pipe_joiner_enable = true; } static void diff --git a/drivers/gpu/drm/i915/display/intel_cdclk.c b/drivers/gpu/drm/i915/display/intel_cdclk.c index 92e6fca861f64a..0f2f693c78d48d 100644 --- a/drivers/gpu/drm/i915/display/intel_cdclk.c +++ b/drivers/gpu/drm/i915/display/intel_cdclk.c @@ -1269,18 +1269,7 @@ static void skl_set_cdclk(struct intel_display *display, static void skl_sanitize_cdclk(struct intel_display *display) { - u32 cdctl, expected, swf18; - - /* - * check if the pre-os initialized the display - * There is SWF18 scratchpad register defined which is set by the - * pre-os which can be used by the OS drivers to check the status - */ - swf18 = intel_de_read(display, SWF_ILK(0x18)); - if ((swf18 & 0x00FFFFFF) == 0) { - drm_dbg_kms(display->drm, "Sanitizing CDCLK due to SWF18 0x%x\n", swf18); - goto sanitize; - } + u32 cdctl, expected; intel_update_cdclk(display); intel_cdclk_dump_config(display, &display->cdclk.hw, "Current CDCLK"); diff --git a/drivers/gpu/drm/i915/display/intel_dsb.c b/drivers/gpu/drm/i915/display/intel_dsb.c index d9a270362a82c2..07d864039e82cd 100644 --- a/drivers/gpu/drm/i915/display/intel_dsb.c +++ b/drivers/gpu/drm/i915/display/intel_dsb.c @@ -589,10 +589,10 @@ static void intel_dsb_align_tail(struct intel_dsb *dsb) tail = dsb->free_pos * 4; aligned_tail = ALIGN(tail, CACHELINE_BYTES); - if (aligned_tail > tail) + if (aligned_tail > tail) { dsb_buffer_fill(dsb, dsb->free_pos, 0, aligned_tail - tail); - - dsb->free_pos = aligned_tail / 4; + dsb->free_pos = aligned_tail / 4; + } } static void intel_dsb_gosub_align(struct intel_dsb *dsb) @@ -607,11 +607,15 @@ static void intel_dsb_gosub_align(struct intel_dsb *dsb) /* * Wa_16024917128 * "Ensure GOSUB is not placed in cacheline QW slot 6 or 7 (numbered 0-7)" + * + * Move to the next cacheline only for those two slots. The skipped + * bytes stay in the programmed range, so fill them with NOPs. Any + * other slot can take the GOSUB directly. */ - if (aligned_tail - tail <= 2 * 8) + if (aligned_tail - tail <= 2 * 8) { dsb_buffer_fill(dsb, dsb->free_pos, 0, aligned_tail - tail); - - dsb->free_pos = aligned_tail / 4; + dsb->free_pos = aligned_tail / 4; + } } void intel_dsb_gosub(struct intel_dsb *dsb, diff --git a/drivers/gpu/drm/i915/display/intel_hdmi.c b/drivers/gpu/drm/i915/display/intel_hdmi.c index b6fa1a1558b82f..a095f5f273bb6c 100644 --- a/drivers/gpu/drm/i915/display/intel_hdmi.c +++ b/drivers/gpu/drm/i915/display/intel_hdmi.c @@ -535,18 +535,27 @@ void hsw_write_infoframe(struct intel_encoder *encoder, val &= ~hsw_infoframe_enable(type); intel_de_write(display, ctl_reg, val); - for (i = 0; i < len; i += 4) { + /* Program the payload first, the header (dword 0) is written last. */ + for (i = 4; i < len; i += 4) intel_de_write(display, hsw_dip_data_reg(display, cpu_transcoder, type, i >> 2), - *data); - data++; - } + data[i >> 2]); /* Write every possible data byte to force correct ECC calculation. */ for (; i < data_size; i += 4) intel_de_write(display, hsw_dip_data_reg(display, cpu_transcoder, type, i >> 2), 0); + /* + * Packets double buffered in the transcoder clock domain are clock + * crossed on the write of the header, so it has to come after the + * payload. Packets double buffered in the core display clock domain + * have no ordering requirement, so use the same order for all of them. + */ + intel_de_write(display, + hsw_dip_data_reg(display, cpu_transcoder, type, 0), + data[0]); + /* Wa_14013475917 */ if (!(IS_DISPLAY_VER(display, 13, 14) && crtc_state->has_psr && !crtc_state->has_panel_replay && type == DP_SDP_VSC)) diff --git a/drivers/gpu/drm/i915/display/intel_quirks.c b/drivers/gpu/drm/i915/display/intel_quirks.c index 96eb9a40df9b95..ec3a79c87e73d1 100644 --- a/drivers/gpu/drm/i915/display/intel_quirks.c +++ b/drivers/gpu/drm/i915/display/intel_quirks.c @@ -108,6 +108,16 @@ static void quirk_enable_dpcd_backlight(struct intel_dp *intel_dp) drm_info(display->drm, "Applying Enable DPCD Backlight quirk\n"); } +/* + * VBT on some machines defaults the eDP pipe joiner to disabled even though + * the panel requires it to achieve its native mode, so allow it regardless. + */ +static void quirk_allow_edp_joiner(struct intel_display *display) +{ + intel_set_quirk(display, QUIRK_ALLOW_EDP_JOINER); + drm_info(display->drm, "Applying allow eDP joiner quirk\n"); +} + struct intel_quirk { int device; int subsystem_vendor; @@ -270,6 +280,10 @@ static struct intel_quirk intel_quirks[] = { /* Xiaomi Book Pro 14 2026 */ { 0xb081, 0x1d72, 0x2424, quirk_disable_psr2 }, + { 0xb080, 0x1d72, 0x2424, quirk_disable_psr2 }, + + /* ASUS ROG Strix SCAR 18 G835LXG */ + { 0x7d67, 0x1043, 0x3b29, quirk_allow_edp_joiner }, }; static const struct intel_dpcd_quirk intel_dpcd_quirks[] = { diff --git a/drivers/gpu/drm/i915/display/intel_quirks.h b/drivers/gpu/drm/i915/display/intel_quirks.h index 4996419ae76bd7..c64d0fc39905ed 100644 --- a/drivers/gpu/drm/i915/display/intel_quirks.h +++ b/drivers/gpu/drm/i915/display/intel_quirks.h @@ -24,6 +24,7 @@ enum intel_quirk_id { QUIRK_DISABLE_EDP_PANEL_REPLAY, QUIRK_DISABLE_PSR2, QUIRK_ENABLE_DPCD_BACKLIGHT, + QUIRK_ALLOW_EDP_JOINER, }; void intel_init_quirks(struct intel_display *display); diff --git a/drivers/gpu/drm/i915/display/intel_vdsc.c b/drivers/gpu/drm/i915/display/intel_vdsc.c index 8f06c3a4d56dfd..7a6452557a0caf 100644 --- a/drivers/gpu/drm/i915/display/intel_vdsc.c +++ b/drivers/gpu/drm/i915/display/intel_vdsc.c @@ -122,7 +122,7 @@ static int get_range_bpg_offset(int bpp_low, int offset_low, int bpp_high, int offset_high, int bpp) { return offset_low + DIV_ROUND_UP((offset_high - offset_low) * (bpp - bpp_low), - (bpp_low - bpp_high)); + (bpp_high - bpp_low)); } /* @@ -211,7 +211,7 @@ calculate_rc_params(struct drm_dsc_config *vdsc_cfg) * For 420 format since bits_per_pixel (bpp) is set to target bpp * 2, * QP table values for target bpp 4.0 to 4.4375 (rounded to 4.0) are * actually for bpp 8 to 8.875 (rounded to 4.0 * 2 i.e 8). - * Similarly values for target bpp 4.5 to 4.8375 (rounded to 4.5) + * Similarly values for target bpp 4.5 to 4.9375 (rounded to 4.5) * are for bpp 9 to 9.875 (rounded to 4.5 * 2 i.e 9), and so on. */ bpp_i = bpp - 8; @@ -239,7 +239,7 @@ calculate_rc_params(struct drm_dsc_config *vdsc_cfg) range_bpg_offset & DSC_RANGE_BPG_OFFSET_MASK; } } else { - /* fractional bpp part * 10000 (for precision up to 4 decimal places) */ + /* fractional bpp part, in Q4 format */ int fractional_bits = fxp_q4_to_frac(vdsc_cfg->bits_per_pixel); static const s8 ofs_und6[] = { @@ -259,9 +259,9 @@ calculate_rc_params(struct drm_dsc_config *vdsc_cfg) * QP table rows have values in increment of 0.5. * So 6.0 bpp to 6.4375 will have index 0, 6.5 to 6.9375 will have index 1, * and so on. - * 0.5 fractional part with 4 decimal precision becomes 5000 + * 0.5 in Q4 fractional format is 8 (i.e. 8/16) */ - bpp_i = ((bpp - 6) + (fractional_bits < 5000 ? 0 : 1)); + bpp_i = (2 * (bpp - 6) + (fractional_bits < 8 ? 0 : 1)); for (buf_i = 0; buf_i < DSC_NUM_BUF_RANGES; buf_i++) { u8 range_bpg_offset; diff --git a/drivers/gpu/drm/imagination/pvr_power.c b/drivers/gpu/drm/imagination/pvr_power.c index eb4b6ecdf4f4d0..c7c160913d7cc6 100644 --- a/drivers/gpu/drm/imagination/pvr_power.c +++ b/drivers/gpu/drm/imagination/pvr_power.c @@ -59,7 +59,8 @@ pvr_power_send_command(struct pvr_device *pvr_dev, struct rogue_fwif_kccb_cmd *p return err; /* Wait for FW to acknowledge. */ - return readl_poll_timeout(pvr_dev->fw_dev.power_sync, value, value != 0, 100, + return readx_poll_timeout(READ_ONCE, + *pvr_dev->fw_dev.power_sync, value, value != 0, 100, POWER_SYNC_TIMEOUT_US); } diff --git a/drivers/gpu/drm/imagination/pvr_rogue_fwif_client.h b/drivers/gpu/drm/imagination/pvr_rogue_fwif_client.h index 6e224400083a2c..967e903bdca67d 100644 --- a/drivers/gpu/drm/imagination/pvr_rogue_fwif_client.h +++ b/drivers/gpu/drm/imagination/pvr_rogue_fwif_client.h @@ -74,7 +74,7 @@ * Flags supported by the compute DM command i.e. &struct rogue_fwif_cmd_compute. */ -#define ROGUE_COMPUTE_FLAG_PREVENT_ALL_OVERLAP BIT_MASK(2) +#define ROGUE_COMPUTE_FLAG_PREVENT_ALL_OVERLAP BIT_MASK(1) /*!< Use single core in a multi core setup. */ #define ROGUE_COMPUTE_FLAG_SINGLE_CORE BIT_MASK(5) diff --git a/drivers/gpu/drm/msm/adreno/a6xx_gmu.c b/drivers/gpu/drm/msm/adreno/a6xx_gmu.c index 662f09bec9d523..a1561ca41a5b39 100644 --- a/drivers/gpu/drm/msm/adreno/a6xx_gmu.c +++ b/drivers/gpu/drm/msm/adreno/a6xx_gmu.c @@ -76,6 +76,13 @@ static irqreturn_t a6xx_hfi_irq(int irq, void *data) return IRQ_HANDLED; } +bool a6xx_gmu_scales_bw(struct a6xx_gmu *gmu) +{ + struct a6xx_gpu *a6xx_gpu = container_of(gmu, struct a6xx_gpu, gmu); + + return a6xx_gpu->base.info->a6xx->bcms && gmu->nr_gpu_bws > 1; +} + bool a6xx_gmu_sptprac_is_on(struct a6xx_gmu *gmu) { u32 val; @@ -169,7 +176,6 @@ void a6xx_gmu_set_freq(struct msm_gpu *gpu, struct dev_pm_opp *opp, bool suspended) { struct adreno_gpu *adreno_gpu = to_adreno_gpu(gpu); - const struct a6xx_info *info = adreno_gpu->info->a6xx; struct a6xx_gpu *a6xx_gpu = to_a6xx_gpu(adreno_gpu); struct a6xx_gmu *gmu = &a6xx_gpu->gmu; u32 perf_index; @@ -187,7 +193,7 @@ void a6xx_gmu_set_freq(struct msm_gpu *gpu, struct dev_pm_opp *opp, break; /* If enabled, find the corresponding DDR bandwidth index */ - if (info->bcms && gmu->nr_gpu_bws > 1) { + if (a6xx_gmu_scales_bw(gmu)) { unsigned int bw = dev_pm_opp_get_bw(opp, true, 0); for (bw_index = 0; bw_index < gmu->nr_gpu_bws - 1; bw_index++) { @@ -1241,8 +1247,12 @@ static int a6xx_gmu_secure_init(struct a6xx_gpu *a6xx_gpu) goto done; } - ret = qcom_scm_gpu_init_regs(QCOM_SCM_GPU_ALWAYS_EN_REQ | - QCOM_SCM_GPU_TSENSE_EN_REQ); + u32 gpu_req = QCOM_SCM_GPU_ALWAYS_EN_REQ | QCOM_SCM_GPU_TSENSE_EN_REQ; + + if (adreno_gpu->info->a6xx->clx_tbl) + gpu_req |= QCOM_SCM_GPU_CLX_EN_REQ; + + ret = qcom_scm_gpu_init_regs(gpu_req); if (ret) { dev_warn_once(gpu->dev->dev, "SCM call failed\n"); @@ -1393,6 +1403,10 @@ int a6xx_gmu_resume(struct a6xx_gpu *a6xx_gpu) /* Set the GPU to the current freq */ a6xx_gmu_set_initial_freq(gpu, gmu); + /* Clear the boot bus quota to allow GMU-driven BW scaling */ + if (a6xx_gmu_scales_bw(gmu)) + dev_pm_opp_set_opp(&gpu->pdev->dev, NULL); + return 0; disable_irq: @@ -1461,8 +1475,8 @@ static void a6xx_gmu_shutdown(struct a6xx_gmu *gmu) ret = gmu_poll_timeout(gmu, REG_A6XX_GPU_GMU_AO_GPU_CX_BUSY_STATUS, val, - !(val & A6XX_GPU_GMU_AO_GPU_CX_BUSY_STATUS_GPUBUSYIGNAHB), - 100, 10000); + !(val & A6XX_GPU_GMU_AO_GPU_CX_BUSY_STATUS_CXGXCPUBUSYIGNAHB), + 100, 100000); /* * Let the user know we failed to slumber but don't worry too @@ -1867,6 +1881,9 @@ static int a6xx_gmu_rpmh_dep_votes_init(struct device *dev, u32 *votes, * back to the highest BX corner if none is high enough. */ bx = a6xx_gmu_rpmh_arc_index(dev, gbx, gbx_count, gx[index], true); + if (bx < 0) + return bx; + FIELD_MODIFY(GMU_BX_MASK, &votes[i], bx); } @@ -1910,7 +1927,7 @@ static int a6xx_gmu_rpmh_votes_init(struct a6xx_gmu *gmu) gmu->gmu_freqs, gmu->nr_gmu_freqs, "cx.lvl", "mx.lvl"); /* Build the interconnect votes */ - if (info->bcms && gmu->nr_gpu_bws > 1) + if (a6xx_gmu_scales_bw(gmu)) ret |= a6xx_gmu_rpmh_bw_votes_init(adreno_gpu, info, gmu); return ret; diff --git a/drivers/gpu/drm/msm/adreno/a6xx_gmu.h b/drivers/gpu/drm/msm/adreno/a6xx_gmu.h index d3f6cd8b97413d..b9e966e602e236 100644 --- a/drivers/gpu/drm/msm/adreno/a6xx_gmu.h +++ b/drivers/gpu/drm/msm/adreno/a6xx_gmu.h @@ -239,6 +239,7 @@ bool a6xx_gmu_gx_is_on(struct adreno_gpu *adreno_gpu); bool a7xx_gmu_gx_is_on(struct adreno_gpu *adreno_gpu); bool a8xx_gmu_gx_is_on(struct adreno_gpu *adreno_gpu); bool a6xx_gmu_sptprac_is_on(struct a6xx_gmu *gmu); +bool a6xx_gmu_scales_bw(struct a6xx_gmu *gmu); void a6xx_sptprac_disable(struct a6xx_gmu *gmu); int a6xx_sptprac_enable(struct a6xx_gmu *gmu); diff --git a/drivers/gpu/drm/msm/adreno/a6xx_gpu.c b/drivers/gpu/drm/msm/adreno/a6xx_gpu.c index 92e8c8abb86da5..3e4afaa5345fda 100644 --- a/drivers/gpu/drm/msm/adreno/a6xx_gpu.c +++ b/drivers/gpu/drm/msm/adreno/a6xx_gpu.c @@ -2248,6 +2248,7 @@ static int a6xx_gmu_pm_suspend(struct msm_gpu *gpu) for (i = 0; i < gpu->nr_rings; i++) a6xx_gpu->shadow[i] = 0; + a6xx_preempt_record_reset(gpu); gpu->suspend_count++; return 0; @@ -2287,6 +2288,7 @@ static int a6xx_pm_suspend(struct msm_gpu *gpu) for (i = 0; i < gpu->nr_rings; i++) a6xx_gpu->shadow[i] = 0; + a6xx_preempt_record_reset(gpu); gpu->suspend_count++; return 0; diff --git a/drivers/gpu/drm/msm/adreno/a6xx_gpu.h b/drivers/gpu/drm/msm/adreno/a6xx_gpu.h index 79912a33e17cf2..62a19e22e23003 100644 --- a/drivers/gpu/drm/msm/adreno/a6xx_gpu.h +++ b/drivers/gpu/drm/msm/adreno/a6xx_gpu.h @@ -305,6 +305,7 @@ void a6xx_preempt_hw_init(struct msm_gpu *gpu); void a6xx_preempt_trigger(struct msm_gpu *gpu); void a6xx_preempt_irq(struct msm_gpu *gpu); void a6xx_preempt_fini(struct msm_gpu *gpu); +void a6xx_preempt_record_reset(struct msm_gpu *gpu); void a6xx_emit_set_pseudo_reg(struct msm_ringbuffer *ring, struct a6xx_gpu *a6xx_gpu, struct msm_gpu_submitqueue *queue); int a6xx_preempt_submitqueue_setup(struct msm_gpu *gpu, diff --git a/drivers/gpu/drm/msm/adreno/a6xx_hfi.c b/drivers/gpu/drm/msm/adreno/a6xx_hfi.c index a9f9fa2adadf51..5b4459826037f0 100644 --- a/drivers/gpu/drm/msm/adreno/a6xx_hfi.c +++ b/drivers/gpu/drm/msm/adreno/a6xx_hfi.c @@ -810,7 +810,7 @@ static int a6xx_hfi_send_bw_table(struct a6xx_gmu *gmu) if (!msg) return -ENOMEM; - if (info->bcms && gmu->nr_gpu_bws > 1) + if (a6xx_gmu_scales_bw(gmu)) a6xx_generate_bw_table(info, gmu, msg); else if (adreno_is_a618(adreno_gpu)) a618_build_bw_table(msg); diff --git a/drivers/gpu/drm/msm/adreno/a6xx_preempt.c b/drivers/gpu/drm/msm/adreno/a6xx_preempt.c index 1e599d4ddea1c8..df8d4f3e8d4c1a 100644 --- a/drivers/gpu/drm/msm/adreno/a6xx_preempt.c +++ b/drivers/gpu/drm/msm/adreno/a6xx_preempt.c @@ -140,12 +140,17 @@ void a6xx_preempt_hw_init(struct msm_gpu *gpu) for (i = 0; i < gpu->nr_rings; i++) { struct a6xx_preempt_record *record_ptr = a6xx_gpu->preempt[i]; - record_ptr->wptr = 0; - record_ptr->rptr = 0; - record_ptr->rptr_addr = shadowptr(a6xx_gpu, gpu->rb[i]); + record_ptr->magic = A6XX_PREEMPT_RECORD_MAGIC; record_ptr->info = 0; + record_ptr->errno = 0; record_ptr->data = 0; + record_ptr->cntl = MSM_GPU_RB_CNTL_DEFAULT; + record_ptr->rptr = 0; + record_ptr->wptr = 0; + record_ptr->rptr_addr = shadowptr(a6xx_gpu, gpu->rb[i]); record_ptr->rbase = gpu->rb[i]->iova; + record_ptr->counter = 0; + record_ptr->bv_rptr_addr = rbmemptr(gpu->rb[i], bv_rptr); } /* Write a 0 to signal that we aren't switching pagetables */ @@ -163,6 +168,19 @@ void a6xx_preempt_hw_init(struct msm_gpu *gpu) a6xx_gpu->cur_ring = gpu->rb[0]; } +void a6xx_preempt_record_reset(struct msm_gpu *gpu) +{ + struct adreno_gpu *adreno_gpu = to_adreno_gpu(gpu); + struct a6xx_gpu *a6xx_gpu = to_a6xx_gpu(adreno_gpu); + int i; + + if (gpu->nr_rings == 1) + return; + + for (i = 0; i < gpu->nr_rings; i++) + memset(a6xx_gpu->preempt[i], 0, a6xx_gpu->preempt_bo[i]->size); +} + void a6xx_preempt_trigger(struct msm_gpu *gpu) { struct adreno_gpu *adreno_gpu = to_adreno_gpu(gpu); @@ -302,8 +320,6 @@ static int preempt_init_ring(struct a6xx_gpu *a6xx_gpu, a6xx_gpu->preempt_iova[ring->id] = iova; a6xx_gpu->preempt[ring->id] = ptr; - struct a6xx_preempt_record *record_ptr = ptr; - ptr = msm_gem_kernel_new(gpu->dev, PREEMPT_SMMU_INFO_SIZE, MSM_BO_WC | MSM_BO_MAP_PRIV | MSM_BO_GPU_READONLY, @@ -329,17 +345,6 @@ static int preempt_init_ring(struct a6xx_gpu *a6xx_gpu, smmu_info_ptr->asid = 0xdecafbad; smmu_info_ptr->context_idr = 0; - /* Set up the defaults on the preemption record */ - record_ptr->magic = A6XX_PREEMPT_RECORD_MAGIC; - record_ptr->info = 0; - record_ptr->data = 0; - record_ptr->rptr = 0; - record_ptr->wptr = 0; - record_ptr->cntl = MSM_GPU_RB_CNTL_DEFAULT; - record_ptr->rbase = ring->iova; - record_ptr->counter = 0; - record_ptr->bv_rptr_addr = rbmemptr(ring, bv_rptr); - return 0; } diff --git a/drivers/gpu/drm/msm/adreno/a8xx_catalog.c b/drivers/gpu/drm/msm/adreno/a8xx_catalog.c index 55a805ab438cc1..eb805168e2d649 100644 --- a/drivers/gpu/drm/msm/adreno/a8xx_catalog.c +++ b/drivers/gpu/drm/msm/adreno/a8xx_catalog.c @@ -54,7 +54,7 @@ static const struct adreno_reglist_pipe a830_nonctxt_regs[] = { { REG_A6XX_TPL1_DBG_ECO_CNTL, 0x10000000, BIT(PIPE_NONE) }, /* Enable cubemap small miplevel optimization settings */ /* BIT(26): Disable final clamp for bicubic filtering */ - { REG_A6XX_TPL1_DBG_ECO_CNTL1, 0x04000724, BIT(PIPE_NONE) }, + { REG_A6XX_TPL1_DBG_ECO_CNTL1, 0x06000724, BIT(PIPE_NONE) }, /* Disable tag bank id hashing */ { REG_A6XX_UCHE_MODE_CNTL, 0x00080000, BIT(PIPE_NONE) }, { REG_A8XX_UCHE_CCHE_MODE_CNTL, 0x00001000, BIT(PIPE_NONE) }, @@ -328,7 +328,7 @@ static const struct adreno_reglist_pipe x285_nonctxt_regs[] = { { REG_A7XX_SP_READ_SEL, 0x0001ff00, BIT(PIPE_NONE) }, { REG_A6XX_TPL1_DBG_ECO_CNTL, 0x10000000, BIT(PIPE_NONE) }, /* BIT(26): Disable final clamp for bicubic filtering */ - { REG_A6XX_TPL1_DBG_ECO_CNTL1, 0x04000720, BIT(PIPE_NONE) }, + { REG_A6XX_TPL1_DBG_ECO_CNTL1, 0x06000720, BIT(PIPE_NONE) }, { REG_A6XX_UCHE_MODE_CNTL, 0x80080000, BIT(PIPE_NONE) }, { REG_A8XX_UCHE_CCHE_MODE_CNTL, 0x00001000, BIT(PIPE_NONE) }, { REG_A8XX_UCHE_CCHE_CACHE_WAYS, 0x00000800, BIT(PIPE_NONE) }, @@ -470,7 +470,7 @@ static const struct adreno_reglist_pipe a810_nonctxt_regs[] = { { REG_A6XX_SP_PERFCTR_SHADER_MASK, 0x0000003f, BIT(PIPE_NONE) }, { REG_A7XX_SP_HLSQ_TIMEOUT_THRESHOLD_DP, 0x00000080, BIT(PIPE_NONE) }, { REG_A6XX_TPL1_DBG_ECO_CNTL, 0x10100000, BIT(PIPE_NONE) }, - { REG_A6XX_TPL1_DBG_ECO_CNTL1, 0x04000724, BIT(PIPE_NONE) }, + { REG_A6XX_TPL1_DBG_ECO_CNTL1, 0x06000724, BIT(PIPE_NONE) }, { REG_A6XX_UCHE_MODE_CNTL, 0x00020000, BIT(PIPE_NONE) }, { REG_A8XX_UCHE_CCHE_MODE_CNTL, 0x00001000, BIT(PIPE_NONE) }, { REG_A8XX_UCHE_CCHE_CACHE_WAYS, 0x00000800, BIT(PIPE_NONE) }, @@ -825,7 +825,7 @@ static const struct adreno_reglist_pipe a840_nonctxt_regs[] = { { REG_A7XX_SP_READ_SEL, 0x0001ff00, BIT(PIPE_NONE) }, { REG_A6XX_TPL1_DBG_ECO_CNTL, 0x10100000, BIT(PIPE_NONE) }, /* BIT(26): Disable final clamp for bicubic filtering */ - { REG_A6XX_TPL1_DBG_ECO_CNTL1, 0x04000720, BIT(PIPE_NONE) }, + { REG_A6XX_TPL1_DBG_ECO_CNTL1, 0x06000720, BIT(PIPE_NONE) }, { REG_A6XX_UCHE_MODE_CNTL, 0x80080000, BIT(PIPE_NONE) }, { REG_A8XX_UCHE_CCHE_MODE_CNTL, 0x00001000, BIT(PIPE_NONE) }, { REG_A8XX_UCHE_CCHE_CACHE_WAYS, 0x00000800, BIT(PIPE_NONE) }, @@ -1211,7 +1211,7 @@ static const struct adreno_reglist_pipe a845_nonctxt_regs[] = { { REG_A7XX_SP_READ_SEL, 0x0001ff00, BIT(PIPE_NONE) }, { REG_A8XX_SP_L0_PERF_TUNE, 0x00000024, BIT(PIPE_NONE) }, { REG_A6XX_TPL1_DBG_ECO_CNTL, 0x10100000, BIT(PIPE_NONE) }, - { REG_A6XX_TPL1_DBG_ECO_CNTL1, 0x00000720, BIT(PIPE_NONE) }, + { REG_A6XX_TPL1_DBG_ECO_CNTL1, 0x02000720, BIT(PIPE_NONE) }, { REG_A6XX_UCHE_MODE_CNTL, 0x80080000, BIT(PIPE_NONE) }, { REG_A8XX_UCHE_CCHE_MODE_CNTL, 0x00001000, BIT(PIPE_NONE) }, { REG_A8XX_UCHE_DBG_ECO_CNTL_0, BIT(31), BIT(PIPE_NONE) }, @@ -1270,7 +1270,7 @@ static const struct adreno_reglist_pipe a850_nonctxt_regs[] = { { REG_A7XX_SP_READ_SEL, 0x0001ff00, BIT(PIPE_NONE) }, { REG_A8XX_SP_L0_PERF_TUNE, 0x00000024, BIT(PIPE_NONE) }, { REG_A6XX_TPL1_DBG_ECO_CNTL, 0x10100000, BIT(PIPE_NONE) }, - { REG_A6XX_TPL1_DBG_ECO_CNTL1, 0x00000720, BIT(PIPE_NONE) }, + { REG_A6XX_TPL1_DBG_ECO_CNTL1, 0x02000720, BIT(PIPE_NONE) }, { REG_A6XX_UCHE_MODE_CNTL, 0x80080000, BIT(PIPE_NONE) }, { REG_A8XX_UCHE_CCHE_MODE_CNTL, 0x00001000, BIT(PIPE_NONE) }, { REG_A8XX_UCHE_DBG_ECO_CNTL_0, BIT(31), BIT(PIPE_NONE) }, @@ -1582,6 +1582,7 @@ static const struct adreno_info a8xx_gpus[] = { .fw = { [ADRENO_FW_SQE] = "gen80100_sqe.fw", [ADRENO_FW_GMU] = "gen80100_gmu.bin", + [ADRENO_FW_AQE] = "gen80100_aqe.fw", }, .gmem = 21 * SZ_1M, .inactive_period = DRM_MSM_INACTIVE_PERIOD, @@ -1613,6 +1614,7 @@ static const struct adreno_info a8xx_gpus[] = { .clx_tbl = &x285_clx_tbl, .limits_tbl = &x285_limits, }, + .preempt_record_size = 23088 * SZ_1K, .speedbins = ADRENO_SPEEDBINS( { 0, 0 }, { 388, 1 }, @@ -1742,6 +1744,7 @@ static const struct adreno_info a8xx_gpus[] = { { /* sentinel */ }, }, }, + .preempt_record_size = 17712 * SZ_1K, .speedbins = ADRENO_SPEEDBINS( { 0, 0 }, { 388, 1 }, diff --git a/drivers/gpu/drm/msm/adreno/a8xx_preempt.c b/drivers/gpu/drm/msm/adreno/a8xx_preempt.c index 6cb53a0718018e..0e0503ed54a1d7 100644 --- a/drivers/gpu/drm/msm/adreno/a8xx_preempt.c +++ b/drivers/gpu/drm/msm/adreno/a8xx_preempt.c @@ -121,12 +121,17 @@ void a8xx_preempt_hw_init(struct msm_gpu *gpu) for (i = 0; i < gpu->nr_rings; i++) { struct a6xx_preempt_record *record_ptr = a6xx_gpu->preempt[i]; - record_ptr->wptr = 0; - record_ptr->rptr = 0; - record_ptr->rptr_addr = shadowptr(a6xx_gpu, gpu->rb[i]); + record_ptr->magic = A6XX_PREEMPT_RECORD_MAGIC; record_ptr->info = 0; + record_ptr->errno = 0; record_ptr->data = 0; + record_ptr->cntl = MSM_GPU_RB_CNTL_DEFAULT; + record_ptr->rptr = 0; + record_ptr->wptr = 0; + record_ptr->rptr_addr = shadowptr(a6xx_gpu, gpu->rb[i]); record_ptr->rbase = gpu->rb[i]->iova; + record_ptr->counter = 0; + record_ptr->bv_rptr_addr = rbmemptr(gpu->rb[i], bv_rptr); } /* Write a 0 to signal that we aren't switching pagetables */ diff --git a/drivers/gpu/drm/msm/adreno/adreno_gpu.c b/drivers/gpu/drm/msm/adreno/adreno_gpu.c index dadfe4c6943841..54f33747523170 100644 --- a/drivers/gpu/drm/msm/adreno/adreno_gpu.c +++ b/drivers/gpu/drm/msm/adreno/adreno_gpu.c @@ -382,7 +382,9 @@ int adreno_get_param(struct msm_gpu *gpu, struct msm_context *ctx, *value = adreno_gpu->gmem; return 0; case MSM_PARAM_GMEM_BASE: - if (adreno_gpu->info->family >= ADRENO_6XX_GEN3) + if (adreno_gpu->info->family >= ADRENO_8XX_GEN1) + *value = SZ_64M; + else if (adreno_gpu->info->family >= ADRENO_6XX_GEN3) *value = 0; else *value = 0x100000; @@ -558,7 +560,7 @@ adreno_request_fw(struct adreno_gpu *adreno_gpu, const char *fwname) adreno_gpu->fwloc = FW_LOCATION_NEW; goto out; } else if (adreno_gpu->fwloc != FW_LOCATION_UNKNOWN) { - DRM_DEV_ERROR(drm->dev, "failed to load %s: %d\n", + DRM_DEV_INFO(drm->dev, "failed to load %s: %d (will try again later)\n", newname, ret); fw = ERR_PTR(ret); goto out; @@ -578,7 +580,7 @@ adreno_request_fw(struct adreno_gpu *adreno_gpu, const char *fwname) adreno_gpu->fwloc = FW_LOCATION_LEGACY; goto out; } else if (adreno_gpu->fwloc != FW_LOCATION_UNKNOWN) { - DRM_DEV_ERROR(drm->dev, "failed to load %s: %d\n", + DRM_DEV_INFO(drm->dev, "failed to load %s: %d (will try again later)\n", fwname, ret); fw = ERR_PTR(ret); goto out; @@ -599,14 +601,14 @@ adreno_request_fw(struct adreno_gpu *adreno_gpu, const char *fwname) adreno_gpu->fwloc = FW_LOCATION_HELPER; goto out; } else if (adreno_gpu->fwloc != FW_LOCATION_UNKNOWN) { - DRM_DEV_ERROR(drm->dev, "failed to load %s: %d\n", + DRM_DEV_INFO(drm->dev, "failed to load %s: %d (will try again later)\n", newname, ret); fw = ERR_PTR(ret); goto out; } } - DRM_DEV_ERROR(drm->dev, "failed to load %s\n", fwname); + DRM_DEV_INFO(drm->dev, "failed to load %s (will try again later)\n", fwname); fw = ERR_PTR(-ENOENT); out: kfree(newname); diff --git a/drivers/gpu/drm/msm/msm_drv.c b/drivers/gpu/drm/msm/msm_drv.c index c3111deaa64680..3675df277f6a6c 100644 --- a/drivers/gpu/drm/msm/msm_drv.c +++ b/drivers/gpu/drm/msm/msm_drv.c @@ -571,13 +571,14 @@ static int msm_ioctl_gem_info_set_metadata(struct drm_gem_object *obj, krealloc(msm_obj->metadata, metadata_size, GFP_KERNEL); if (!new_metadata) { ret = -ENOMEM; - goto out; + goto unlock; } msm_obj->metadata = new_metadata; msm_obj->metadata_size = metadata_size; memcpy(msm_obj->metadata, buf, metadata_size); +unlock: msm_gem_unlock(obj); out: diff --git a/drivers/gpu/drm/msm/msm_gem_submit.c b/drivers/gpu/drm/msm/msm_gem_submit.c index 5862db05297a71..c03410c568a5a4 100644 --- a/drivers/gpu/drm/msm/msm_gem_submit.c +++ b/drivers/gpu/drm/msm/msm_gem_submit.c @@ -272,7 +272,7 @@ static int submit_lock_objects_vmbind(struct msm_gem_submit *submit) struct drm_exec *exec = &submit->exec; int ret = 0; - drm_exec_init(&submit->exec, flags, submit->nr_bos); + drm_exec_init(&submit->exec, flags, 0); submit->has_exec = true; drm_exec_until_all_locked (&submit->exec) { @@ -589,6 +589,9 @@ int msm_ioctl_gem_submit(struct drm_device *dev, void *data, return -EINVAL; } + if (msm_context_is_vmbind(ctx) && args->nr_bos) + return UERR(EINVAL, dev, "invalid nr_bos, must be zero for VM_BIND contexts"); + queue = msm_submitqueue_get(ctx, args->queueid); if (!queue) return -ENOENT; diff --git a/drivers/gpu/drm/msm/msm_gem_vma.c b/drivers/gpu/drm/msm/msm_gem_vma.c index f687a629629d34..8b702422030afe 100644 --- a/drivers/gpu/drm/msm/msm_gem_vma.c +++ b/drivers/gpu/drm/msm/msm_gem_vma.c @@ -1012,10 +1012,10 @@ lookup_op(struct msm_vm_bind_job *job, const struct drm_msm_vm_bind_op *op) if (invalid_alignment(op->iova)) ret = UERR(EINVAL, dev, "invalid address: %016llx\n", op->iova); - if (invalid_alignment(op->obj_offset)) + if (invalid_alignment(op->obj_offset) || (op->obj_offset > SIZE_MAX)) ret = UERR(EINVAL, dev, "invalid bo_offset: %016llx\n", op->obj_offset); - if (invalid_alignment(op->range)) + if (invalid_alignment(op->range) || (op->range > SIZE_MAX) || !op->range) ret = UERR(EINVAL, dev, "invalid range: %016llx\n", op->range); if (!drm_gpuvm_range_valid(job->vm, op->iova, op->range)) @@ -1088,7 +1088,6 @@ vm_bind_job_lookup_ops(struct msm_vm_bind_job *job, struct drm_msm_vm_bind *args } if (ret) { - job->nr_ops = 0; goto out; } @@ -1110,6 +1109,7 @@ vm_bind_job_lookup_ops(struct msm_vm_bind_job *job, struct drm_msm_vm_bind *args obj = idr_find(&file->object_idr, op->handle); if (!obj) { ret = UERR(EINVAL, dev, "invalid handle %u at index %u\n", op->handle, i); + i--; goto out_unlock; } @@ -1118,7 +1118,7 @@ vm_bind_job_lookup_ops(struct msm_vm_bind_job *job, struct drm_msm_vm_bind *args op->obj = obj; cnt++; - if ((op->range + op->obj_offset) > obj->size) { + if (size_add(op->range, op->obj_offset) > obj->size) { ret = UERR(EINVAL, dev, "invalid range: %016llx + %016llx > %016zx\n", op->range, op->obj_offset, obj->size); goto out_unlock; @@ -1142,6 +1142,9 @@ vm_bind_job_lookup_ops(struct msm_vm_bind_job *job, struct drm_msm_vm_bind *args } } out: + if (ret) + job->nr_ops = 0; + return ret; } diff --git a/drivers/gpu/drm/msm/msm_gpu.h b/drivers/gpu/drm/msm/msm_gpu.h index d27d54bdb7a71b..bc5b31eb1eca8e 100644 --- a/drivers/gpu/drm/msm/msm_gpu.h +++ b/drivers/gpu/drm/msm/msm_gpu.h @@ -522,17 +522,18 @@ msm_context_is_vmbind(struct msm_context *ctx) * @sched_prio: [out] the gpu scheduler priority level which the userspace * priority maps to * - * With drm/scheduler providing it's own level of prioritization, our total + * With drm/scheduler providing its own level of prioritization, our total * number of available priority levels is (nr_rings * NR_SCHED_PRIORITIES). - * Each ring is associated with it's own scheduler instance. However, our - * UABI is that lower numerical values are higher priority. So mapping the - * single userspace priority level into ring_nr and sched_prio takes some - * care. The userspace provided priority (when a submitqueue is created) - * is mapped to ring nr and scheduler priority as such: + * Each ring is associated with its own scheduler instance. Both the MSM + * UABI and drm/scheduler use lower-numeric = higher-priority, so the mapping + * from a single userspace priority level into ring_nr and sched_prio is: * * ring_nr = userspace_prio / NR_SCHED_PRIORITIES - * sched_prio = NR_SCHED_PRIORITIES - - * (userspace_prio % NR_SCHED_PRIORITIES) - 1 + * sched_prio = (userspace_prio % NR_SCHED_PRIORITIES) + DRM_SCHED_PRIORITY_HIGH + * + * The offset by DRM_SCHED_PRIORITY_HIGH keeps the range within [HIGH..LOW], + * intentionally excluding DRM_SCHED_PRIORITY_KERNEL which is reserved for + * kernel-internal submissions. * * This allows generations without preemption (nr_rings==1) to have some * amount of prioritization, and provides more priority levels for gens @@ -547,16 +548,11 @@ static inline int msm_gpu_convert_priority(struct msm_gpu *gpu, int prio, rn = div_u64_rem(prio, NR_SCHED_PRIORITIES, &sp); - /* invert sched priority to map to higher-numeric-is-higher- - * priority convention - */ - sp = NR_SCHED_PRIORITIES - sp - 1; - if (rn >= gpu->nr_rings) return -EINVAL; *ring_nr = rn; - *sched_prio = sp; + *sched_prio = sp + DRM_SCHED_PRIORITY_HIGH; return 0; } diff --git a/drivers/gpu/drm/msm/msm_gpu_devfreq.c b/drivers/gpu/drm/msm/msm_gpu_devfreq.c index 2e1d5c3432728c..f3c664b20a1bad 100644 --- a/drivers/gpu/drm/msm/msm_gpu_devfreq.c +++ b/drivers/gpu/drm/msm/msm_gpu_devfreq.c @@ -357,7 +357,6 @@ static void msm_devfreq_idle_work(struct kthread_work *work) if (priv->gpu_clamp_to_idle) msm_devfreq_target(&gpu->pdev->dev, &target_freq, 0); - df->idle_time = ktime_get(); df->idle_freq = idle_freq; mutex_unlock(&df->devfreq->lock); @@ -370,6 +369,8 @@ void msm_devfreq_idle(struct msm_gpu *gpu) if (!has_devfreq(gpu)) return; + df->idle_time = ktime_get(); + msm_hrtimer_queue_work(&df->idle_work, ms_to_ktime(1), HRTIMER_MODE_REL); } diff --git a/drivers/gpu/drm/msm/msm_submitqueue.c b/drivers/gpu/drm/msm/msm_submitqueue.c index d307cdd17d908f..8d550d281704e8 100644 --- a/drivers/gpu/drm/msm/msm_submitqueue.c +++ b/drivers/gpu/drm/msm/msm_submitqueue.c @@ -136,7 +136,7 @@ get_sched_entity(struct msm_context *ctx, struct msm_ringbuffer *ring, unsigned ring_nr, enum drm_sched_priority sched_prio) { static DEFINE_MUTEX(entity_lock); - unsigned idx = (ring_nr * NR_SCHED_PRIORITIES) + sched_prio; + unsigned idx = (ring_nr * NR_SCHED_PRIORITIES) + (sched_prio - DRM_SCHED_PRIORITY_HIGH); /* We should have already validated that the requested priority is * valid by the time we get here. diff --git a/drivers/gpu/drm/msm/registers/adreno/a6xx_gmu.xml b/drivers/gpu/drm/msm/registers/adreno/a6xx_gmu.xml index b3082738c99d30..786fd7d2f67437 100644 --- a/drivers/gpu/drm/msm/registers/adreno/a6xx_gmu.xml +++ b/drivers/gpu/drm/msm/registers/adreno/a6xx_gmu.xml @@ -224,6 +224,7 @@ xsi:schemaLocation="https://gitlab.freedesktop.org/freedreno/ rules-fd.xsd"> + diff --git a/drivers/gpu/drm/nouveau/nouveau_sched.c b/drivers/gpu/drm/nouveau/nouveau_sched.c index b3f02c490ecb67..680ddffefca1ee 100644 --- a/drivers/gpu/drm/nouveau/nouveau_sched.c +++ b/drivers/gpu/drm/nouveau/nouveau_sched.c @@ -328,7 +328,11 @@ nouveau_job_submit(struct nouveau_job *job) mutex_unlock(&sched->mutex); if (done_fence) { - dma_fence_wait(done_fence, true); + /* The job is queued and its VA space changes are applied. It + * can neither be restarted nor reported as failed, so wait + * until it has run. + */ + dma_fence_wait(done_fence, false); dma_fence_put(done_fence); } diff --git a/drivers/gpu/drm/nouveau/nvkm/subdev/bar/gf100.c b/drivers/gpu/drm/nouveau/nvkm/subdev/bar/gf100.c index a1fa1b0c895437..6950801d2e0304 100644 --- a/drivers/gpu/drm/nouveau/nvkm/subdev/bar/gf100.c +++ b/drivers/gpu/drm/nouveau/nvkm/subdev/bar/gf100.c @@ -133,6 +133,12 @@ gf100_bar_oneinit(struct nvkm_bar *base) if (ret) return ret; + if (bar->base.func->bar2.oneinit) { + ret = bar->base.func->bar2.oneinit(&bar->base); + if (ret) + return ret; + } + bar->base.subdev.oneinit = true; nvkm_bar_bar2_init(bar->base.subdev.device); } diff --git a/drivers/gpu/drm/nouveau/nvkm/subdev/bar/priv.h b/drivers/gpu/drm/nouveau/nvkm/subdev/bar/priv.h index d0168e0b78fb74..5774bfa8d96d5d 100644 --- a/drivers/gpu/drm/nouveau/nvkm/subdev/bar/priv.h +++ b/drivers/gpu/drm/nouveau/nvkm/subdev/bar/priv.h @@ -16,6 +16,7 @@ struct nvkm_bar_func { void (*init)(struct nvkm_bar *); struct { + int (*oneinit)(struct nvkm_bar *); void (*init)(struct nvkm_bar *); void (*fini)(struct nvkm_bar *); void (*wait)(struct nvkm_bar *); diff --git a/drivers/gpu/drm/nouveau/nvkm/subdev/devinit/gf100.c b/drivers/gpu/drm/nouveau/nvkm/subdev/devinit/gf100.c index 186e09ea0cb10a..b256404c2454ff 100644 --- a/drivers/gpu/drm/nouveau/nvkm/subdev/devinit/gf100.c +++ b/drivers/gpu/drm/nouveau/nvkm/subdev/devinit/gf100.c @@ -107,12 +107,12 @@ gf100_devinit_preinit(struct nvkm_devinit *base) * VBIOS multiple times may have detrimental effects. */ if (base->post) { - u64 disable = nvkm_devinit_disable(base); + nvkm_devinit_disable(base); /* magic to detect whether or not x86 vbios code has * executed the devinit scripts to initialise the * board. only works if there's a display engine. */ - if (!(disable & (1ULL << NVKM_ENGINE_DISP))) { + if (device->disp) { if (nvkm_rdvgac(device, 0, 0x00) || nvkm_rdvgac(device, 0, 0x1a)) { base->post = false; diff --git a/drivers/gpu/drm/nouveau/nvkm/subdev/gsp/rm/r535/bar.c b/drivers/gpu/drm/nouveau/nvkm/subdev/gsp/rm/r535/bar.c index fae08ac3b18c73..9b907d9e80afee 100644 --- a/drivers/gpu/drm/nouveau/nvkm/subdev/gsp/rm/r535/bar.c +++ b/drivers/gpu/drm/nouveau/nvkm/subdev/gsp/rm/r535/bar.c @@ -24,9 +24,11 @@ #include #include #include -#include +#include #include +#include + #include "nvrm/bar.h" #include "nvrm/rpcfn.h" @@ -65,6 +67,25 @@ r535_bar_bar2_update_pde(struct nvkm_gsp *gsp, u8 page_shift, u64 pdbe) return nvkm_gsp_rpc_wr(gsp, rpc, NVKM_GSP_RPC_REPLY_RECV); } +static int +r535_bar_bar2_oneinit(struct nvkm_bar *bar) +{ + struct io_mapping *iomap = nv50_instmem_bar2_iomap(bar->subdev.device->imem); + + if (!iomap) + return -ENOMEM; + + /* BAR2 writes are flushed by a read. While flushFBZero is not mapped, + * read the first page of the BAR2 io_mapping. + */ + bar->flushBAR2PhysMode = io_mapping_map_wc(iomap, 0, PAGE_SIZE); + if (!bar->flushBAR2PhysMode) + return -ENOMEM; + + bar->flushBAR2 = bar->flushBAR2PhysMode; + return 0; +} + static void r535_bar_bar2_fini(struct nvkm_bar *bar) { @@ -155,7 +176,7 @@ r535_bar_dtor(struct nvkm_bar *bar) nvkm_memory_unref(&bar->flushFBZero); if (bar->flushBAR2PhysMode) - iounmap(bar->flushBAR2PhysMode); + io_mapping_unmap(bar->flushBAR2PhysMode); kfree(bar->func); return data; @@ -178,6 +199,7 @@ r535_bar_new_(const struct nvkm_bar_func *hw, struct nvkm_device *device, rm->bar1.fini = r535_bar_bar1_fini; rm->bar1.wait = r535_bar_bar1_wait; rm->bar1.vmm = hw->bar1.vmm; + rm->bar2.oneinit = r535_bar_bar2_oneinit; rm->bar2.init = r535_bar_bar2_init; rm->bar2.fini = r535_bar_bar2_fini; rm->bar2.wait = r535_bar_bar2_wait; @@ -191,12 +213,6 @@ r535_bar_new_(const struct nvkm_bar_func *hw, struct nvkm_device *device, } *pbar = bar; - bar->flushBAR2PhysMode = ioremap(device->func->resource_addr(device, NVKM_BAR2_INST), PAGE_SIZE); - if (!bar->flushBAR2PhysMode) - return -ENOMEM; - - bar->flushBAR2 = bar->flushBAR2PhysMode; - gf100_bar(*pbar)->bar2_halve = true; return 0; } diff --git a/drivers/gpu/drm/nouveau/nvkm/subdev/instmem/nv50.c b/drivers/gpu/drm/nouveau/nvkm/subdev/instmem/nv50.c index 22b0fde6ba346d..1e7d439c2d592c 100644 --- a/drivers/gpu/drm/nouveau/nvkm/subdev/instmem/nv50.c +++ b/drivers/gpu/drm/nouveau/nvkm/subdev/instmem/nv50.c @@ -191,16 +191,17 @@ nv50_instobj_map(struct nvkm_memory *memory, u64 offset, struct nvkm_vmm *vmm, } static bool -check_io_mapping(struct nv50_instmem *imem) +check_io_mapping(struct nv50_instmem *imem, struct nvkm_vmm *vmm) { struct nvkm_device *device = imem->base.subdev.device; if (imem->iomap.size) return true; + /* Map the part of BAR2 that its address space covers. */ return io_mapping_init_wc(&imem->iomap, device->func->resource_addr(device, NVKM_BAR2_INST), - device->func->resource_size(device, NVKM_BAR2_INST)) != NULL; + vmm->limit - vmm->start) != NULL; } static void @@ -293,10 +294,10 @@ nv50_instobj_boot(struct nvkm_memory *memory, struct nvkm_vmm *vmm) } /* - * boot is only called on BAR2, if we can't remap the complete - * BAR it's unlikely things are functioning well. + * boot is only called on BAR2. If we can't map it, it's unlikely + * things are functioning well. */ - if (check_io_mapping(iobj->imem)) + if (check_io_mapping(iobj->imem, vmm)) nv50_instobj_kmap(iobj, vmm); nvkm_instmem_boot(imem); mutex_unlock(&imem->mutex); @@ -436,6 +437,14 @@ nv50_instmem_dtor(struct nvkm_instmem *base) return imem; } +struct io_mapping * +nv50_instmem_bar2_iomap(struct nvkm_instmem *base) +{ + struct nv50_instmem *imem = nv50_instmem(base); + + return imem->iomap.size ? &imem->iomap : NULL; +} + static const struct nvkm_instmem_func nv50_instmem = { .dtor = nv50_instmem_dtor, diff --git a/drivers/gpu/drm/nouveau/nvkm/subdev/instmem/priv.h b/drivers/gpu/drm/nouveau/nvkm/subdev/instmem/priv.h index b423f01f5fcd1f..88990adda76651 100644 --- a/drivers/gpu/drm/nouveau/nvkm/subdev/instmem/priv.h +++ b/drivers/gpu/drm/nouveau/nvkm/subdev/instmem/priv.h @@ -4,6 +4,8 @@ #define nvkm_instmem(p) container_of((p), struct nvkm_instmem, subdev) #include +struct io_mapping; + struct nvkm_instmem_func { void *(*dtor)(struct nvkm_instmem *); int (*oneinit)(struct nvkm_instmem *); @@ -27,6 +29,7 @@ int nv50_instobj_new(struct nvkm_instmem *, u32 size, u32 align, bool zero, int nv50_instobj_wrap(struct nvkm_instmem *, struct nvkm_memory *vram, struct nvkm_memory **bar2); void *nv50_instmem_dtor(struct nvkm_instmem *base); +struct io_mapping *nv50_instmem_bar2_iomap(struct nvkm_instmem *base); void nvkm_instmem_ctor(const struct nvkm_instmem_func *, struct nvkm_device *, enum nvkm_subdev_type, int, struct nvkm_instmem *); diff --git a/drivers/gpu/drm/omapdrm/dss/output.c b/drivers/gpu/drm/omapdrm/dss/output.c index 36d37deac80263..b5cef5093a8834 100644 --- a/drivers/gpu/drm/omapdrm/dss/output.c +++ b/drivers/gpu/drm/omapdrm/dss/output.c @@ -24,6 +24,9 @@ int omapdss_device_init_output(struct omap_dss_device *out, bridge = of_drm_get_bridge_by_endpoint(out->dev->of_node, out->of_port, 0); if (IS_ERR(bridge)) { + if (PTR_ERR(bridge) == -EPROBE_DEFER) + return PTR_ERR(bridge); + dev_dbg(out->dev, "failed to find video sink\n"); return 0; } diff --git a/drivers/gpu/drm/radeon/radeon_atombios.c b/drivers/gpu/drm/radeon/radeon_atombios.c index 3dd9724b331d6d..c4e1272cd843fb 100644 --- a/drivers/gpu/drm/radeon/radeon_atombios.c +++ b/drivers/gpu/drm/radeon/radeon_atombios.c @@ -125,6 +125,22 @@ static struct radeon_i2c_bus_rec radeon_get_bus_rec_for_i2c_gpio(ATOM_GPIO_I2C_A return i2c; } +/* + * The VBIOS table size is not checked against the image; cap the + * entry count to RADEON_MAX_I2C_BUS, the size of rdev->i2c_bus[]. + */ +static int radeon_atombios_gpio_i2c_num_entries(uint16_t size) +{ + u32 bytes; + + if (size < sizeof(ATOM_COMMON_TABLE_HEADER)) + return 0; + + bytes = size - sizeof(ATOM_COMMON_TABLE_HEADER); + return min_t(u32, bytes / sizeof(ATOM_GPIO_I2C_ASSIGMENT), + RADEON_MAX_I2C_BUS); +} + static struct radeon_i2c_bus_rec radeon_lookup_i2c_gpio(struct radeon_device *rdev, uint8_t id) { @@ -142,8 +158,7 @@ static struct radeon_i2c_bus_rec radeon_lookup_i2c_gpio(struct radeon_device *rd if (atom_parse_data_header(ctx, index, &size, NULL, NULL, &data_offset)) { i2c_info = (struct _ATOM_GPIO_I2C_INFO *)(ctx->bios + data_offset); - num_indices = (size - sizeof(ATOM_COMMON_TABLE_HEADER)) / - sizeof(ATOM_GPIO_I2C_ASSIGMENT); + num_indices = radeon_atombios_gpio_i2c_num_entries(size); gpio = &i2c_info->asGPIO_Info[0]; for (i = 0; i < num_indices; i++) { @@ -176,8 +191,7 @@ void radeon_atombios_i2c_init(struct radeon_device *rdev) if (atom_parse_data_header(ctx, index, &size, NULL, NULL, &data_offset)) { i2c_info = (struct _ATOM_GPIO_I2C_INFO *)(ctx->bios + data_offset); - num_indices = (size - sizeof(ATOM_COMMON_TABLE_HEADER)) / - sizeof(ATOM_GPIO_I2C_ASSIGMENT); + num_indices = radeon_atombios_gpio_i2c_num_entries(size); gpio = &i2c_info->asGPIO_Info[0]; for (i = 0; i < num_indices; i++) { diff --git a/drivers/gpu/drm/radeon/radeon_atpx_handler.c b/drivers/gpu/drm/radeon/radeon_atpx_handler.c index f557535c1d7b3e..9ed75c69c6151a 100644 --- a/drivers/gpu/drm/radeon/radeon_atpx_handler.c +++ b/drivers/gpu/drm/radeon/radeon_atpx_handler.c @@ -34,6 +34,7 @@ struct radeon_atpx { static struct radeon_atpx_priv { bool atpx_detected; bool bridge_pm_usable; + bool handler_registered; /* handle for device - and atpx */ acpi_handle dhandle; struct radeon_atpx atpx; @@ -605,7 +606,8 @@ void radeon_register_atpx_handler(void) if (!r) return; - vga_switcheroo_register_handler(&radeon_atpx_handler, handler_flags); + if (!vga_switcheroo_register_handler(&radeon_atpx_handler, handler_flags)) + radeon_atpx_priv.handler_registered = true; } /** @@ -615,5 +617,14 @@ void radeon_register_atpx_handler(void) */ void radeon_unregister_atpx_handler(void) { + /* + * vga_switcheroo has a single handler slot and unregistering clears it + * no matter who set it, so leave a handler registered by another + * driver, such as amdgpu or apple-gmux, in place. + */ + if (!radeon_atpx_priv.handler_registered) + return; + vga_switcheroo_unregister_handler(); + radeon_atpx_priv.handler_registered = false; } diff --git a/drivers/gpu/drm/radeon/radeon_bios.c b/drivers/gpu/drm/radeon/radeon_bios.c index 1da6bf1c17ff34..869240588eb310 100644 --- a/drivers/gpu/drm/radeon/radeon_bios.c +++ b/drivers/gpu/drm/radeon/radeon_bios.c @@ -609,35 +609,23 @@ static bool radeon_read_disabled_bios(struct radeon_device *rdev) * VFCT entries contain the PCI bus number as recorded during BIOS POST. * On systems where the kernel renumbers PCI buses (e.g. pci=realloc or * resource conflicts), the runtime bus number may differ from the POST - * value. Match by device identity (vendor + device + function) and use - * the bus number as a preference: exact bus match is preferred, but when - * the bus numbers disagree we accept the entry if the device identity - * matches. + * value. Match against the secondary bus number of the upstream bridge + * at FW/OS handoff, which the PCI core caches before any renumbering. * - * Returns: 0 on match, -ENODEV on no match + * Returns: true if @vhdr describes this device, false otherwise */ -static int radeon_acpi_vfct_match(struct radeon_device *rdev, - VFCT_IMAGE_HEADER *vhdr) +static bool radeon_acpi_vfct_match(struct radeon_device *rdev, + VFCT_IMAGE_HEADER *vhdr) { - /* Vendor and device IDs must always match */ - if (vhdr->VendorID != rdev->pdev->vendor || - vhdr->DeviceID != rdev->pdev->device) - return -ENODEV; - - if (vhdr->PCIDevice != PCI_SLOT(rdev->pdev->devfn) || - vhdr->PCIFunction != PCI_FUNC(rdev->pdev->devfn)) - return -ENODEV; - - /* Exact bus number match - preferred */ - if (vhdr->PCIBus == rdev->pdev->bus->number) - return 0; - - /* Bus mismatch but device identity matches (PCI renumbering case) */ - dev_notice(&rdev->pdev->dev, - "VFCT bus number mismatch: table %u != runtime %u, matching by device identity (vendor 0x%04x device 0x%04x)\n", - vhdr->PCIBus, rdev->pdev->bus->number, - rdev->pdev->vendor, rdev->pdev->device); - return 0; + struct pci_dev *pdev = rdev->pdev; + struct pci_dev *bridge = pci_upstream_bridge(pdev); + u8 bus = bridge ? bridge->fw_sec_busnr : pdev->bus->number; + + return vhdr->VendorID == pdev->vendor && + vhdr->DeviceID == pdev->device && + vhdr->PCIBus == bus && + vhdr->PCIDevice == PCI_SLOT(pdev->devfn) && + vhdr->PCIFunction == PCI_FUNC(pdev->devfn); } static bool radeon_acpi_vfct_bios(struct radeon_device *rdev) @@ -676,7 +664,7 @@ static bool radeon_acpi_vfct_bios(struct radeon_device *rdev) } if (vhdr->ImageLength && - !radeon_acpi_vfct_match(rdev, vhdr)) { + radeon_acpi_vfct_match(rdev, vhdr)) { rdev->bios = kmemdup(&vbios->VbiosContent, vhdr->ImageLength, GFP_KERNEL); diff --git a/drivers/gpu/drm/tilcdc/tilcdc_drv.c b/drivers/gpu/drm/tilcdc/tilcdc_drv.c index 1d6c9a423a4104..e82cb2686c5f3b 100644 --- a/drivers/gpu/drm/tilcdc/tilcdc_drv.c +++ b/drivers/gpu/drm/tilcdc/tilcdc_drv.c @@ -235,7 +235,8 @@ static const struct drm_driver tilcdc_driver = { static int tilcdc_pm_suspend(struct device *dev) { - struct drm_device *ddev = dev_get_drvdata(dev); + struct tilcdc_drm_private *priv = dev_get_drvdata(dev); + struct drm_device *ddev = &priv->ddev; int ret = 0; ret = drm_mode_config_helper_suspend(ddev); @@ -248,7 +249,8 @@ static int tilcdc_pm_suspend(struct device *dev) static int tilcdc_pm_resume(struct device *dev) { - struct drm_device *ddev = dev_get_drvdata(dev); + struct tilcdc_drm_private *priv = dev_get_drvdata(dev); + struct drm_device *ddev = &priv->ddev; /* Select default pin state */ pinctrl_pm_select_default_state(dev); diff --git a/drivers/gpu/drm/ttm/tests/ttm_pool_test.c b/drivers/gpu/drm/ttm/tests/ttm_pool_test.c index be75c8abf38833..dab03dd6c9dd75 100644 --- a/drivers/gpu/drm/ttm/tests/ttm_pool_test.c +++ b/drivers/gpu/drm/ttm/tests/ttm_pool_test.c @@ -401,8 +401,6 @@ static void ttm_pool_fini_basic(struct kunit *test) KUNIT_ASSERT_FALSE(test, !list_lru_count(&pt->pages)); ttm_pool_fini(pool); - - KUNIT_ASSERT_TRUE(test, !list_lru_count(&pt->pages)); } static struct kunit_case ttm_pool_test_cases[] = { diff --git a/drivers/gpu/drm/ttm/ttm_pool.c b/drivers/gpu/drm/ttm/ttm_pool.c index 1bf37023fed663..0076594b00683a 100644 --- a/drivers/gpu/drm/ttm/ttm_pool.c +++ b/drivers/gpu/drm/ttm/ttm_pool.c @@ -421,6 +421,7 @@ static void ttm_pool_type_fini(struct ttm_pool_type *pt) list_lru_walk(&pt->pages, pool_move_to_dispose_list, &dispose, LONG_MAX); ttm_pool_dispose_list(pt, &dispose); + list_lru_destroy(&pt->pages); } /* Return the pool_type to use for the given caching and order */ diff --git a/drivers/gpu/drm/v3d/v3d_drv.h b/drivers/gpu/drm/v3d/v3d_drv.h index 7c7bdf6e51a51e..e5c9ad86449a15 100644 --- a/drivers/gpu/drm/v3d/v3d_drv.h +++ b/drivers/gpu/drm/v3d/v3d_drv.h @@ -669,10 +669,8 @@ static __always_inline int v3d_pm_runtime_put(struct v3d_dev *v3d) } /* v3d_sched.c */ -void v3d_timestamp_query_info_free(struct v3d_timestamp_query_info *query_info, - unsigned int count); -void v3d_performance_query_info_free(struct v3d_performance_query_info *query_info, - unsigned int count); +void v3d_timestamp_query_info_free(struct v3d_timestamp_query_info *query_info); +void v3d_performance_query_info_free(struct v3d_performance_query_info *query_info); struct v3d_stats *v3d_stats_alloc(void); void v3d_stats_release(struct kref *refcount); void v3d_job_update_stats(struct v3d_job *job); diff --git a/drivers/gpu/drm/v3d/v3d_sched.c b/drivers/gpu/drm/v3d/v3d_sched.c index 1be2cd5bbf673b..cc4e6d0dddabc5 100644 --- a/drivers/gpu/drm/v3d/v3d_sched.c +++ b/drivers/gpu/drm/v3d/v3d_sched.c @@ -96,33 +96,41 @@ v3d_sched_job_free(struct drm_sched_job *sched_job) } void -v3d_timestamp_query_info_free(struct v3d_timestamp_query_info *query_info, - unsigned int count) +v3d_timestamp_query_info_free(struct v3d_timestamp_query_info *query_info) { - if (query_info->queries) { - unsigned int i; + unsigned int i; - for (i = 0; i < count; i++) - drm_syncobj_put(query_info->queries[i].syncobj); + if (!query_info->queries) + return; - kvfree(query_info->queries); + for (i = 0; i < query_info->count; i++) { + if (!query_info->queries[i].syncobj) + break; + + drm_syncobj_put(query_info->queries[i].syncobj); } + + kvfree(query_info->queries); } void -v3d_performance_query_info_free(struct v3d_performance_query_info *query_info, - unsigned int count) +v3d_performance_query_info_free(struct v3d_performance_query_info *query_info) { - if (query_info->queries) { - unsigned int i; + unsigned int i; - for (i = 0; i < count; i++) { - drm_syncobj_put(query_info->queries[i].syncobj); - kvfree(query_info->queries[i].kperfmon_ids); - } + if (!query_info->queries) + return; - kvfree(query_info->queries); + for (i = 0; i < query_info->count; i++) { + kvfree(query_info->queries[i].kperfmon_ids); + + if (!query_info->queries[i].syncobj) + break; + + drm_syncobj_put(query_info->queries[i].syncobj); } + + kvfree(query_info->queries); } static void diff --git a/drivers/gpu/drm/v3d/v3d_submit.c b/drivers/gpu/drm/v3d/v3d_submit.c index 7548faab67baad..fc85ad4defb75f 100644 --- a/drivers/gpu/drm/v3d/v3d_submit.c +++ b/drivers/gpu/drm/v3d/v3d_submit.c @@ -174,11 +174,9 @@ v3d_cpu_job_free(struct kref *ref) struct v3d_cpu_job *job = container_of(ref, struct v3d_cpu_job, base.refcount); - v3d_timestamp_query_info_free(&job->timestamp_query, - job->timestamp_query.count); + v3d_timestamp_query_info_free(&job->timestamp_query); - v3d_performance_query_info_free(&job->performance_query, - job->performance_query.count); + v3d_performance_query_info_free(&job->performance_query); if (job->indirect_csd.indirect) drm_gem_object_put(job->indirect_csd.indirect); @@ -734,7 +732,6 @@ v3d_get_cpu_timestamp_query_params(struct drm_file *file_priv, struct drm_v3d_timestamp_query timestamp; struct v3d_timestamp_query_info *query_info = &job->timestamp_query; unsigned int i; - int err; if (!v3d_validate_cpu_job(file_priv, job)) return -EINVAL; @@ -747,43 +744,34 @@ v3d_get_cpu_timestamp_query_params(struct drm_file *file_priv, job->job_type = V3D_CPU_JOB_TYPE_TIMESTAMP_QUERY; - query_info->queries = kvmalloc_objs(struct v3d_timestamp_query, + query_info->queries = kvzalloc_objs(struct v3d_timestamp_query, timestamp.count); if (!query_info->queries) return -ENOMEM; + query_info->count = timestamp.count; + offsets = u64_to_user_ptr(timestamp.offsets); syncs = u64_to_user_ptr(timestamp.syncs); - for (i = 0; i < timestamp.count; i++) { + for (i = 0; i < query_info->count; i++) { u32 offset, sync; - if (get_user(offset, offsets++)) { - err = -EFAULT; - goto error; - } + if (get_user(offset, offsets++)) + return -EFAULT; query_info->queries[i].offset = offset; - if (get_user(sync, syncs++)) { - err = -EFAULT; - goto error; - } + if (get_user(sync, syncs++)) + return -EFAULT; query_info->queries[i].syncobj = drm_syncobj_find(file_priv, sync); - if (!query_info->queries[i].syncobj) { - err = -ENOENT; - goto error; - } + if (!query_info->queries[i].syncobj) + return -ENOENT; } - query_info->count = timestamp.count; return 0; - -error: - v3d_timestamp_query_info_free(&job->timestamp_query, i); - return err; } static int @@ -795,7 +783,6 @@ v3d_get_cpu_reset_timestamp_params(struct drm_file *file_priv, struct drm_v3d_reset_timestamp_query reset; struct v3d_timestamp_query_info *query_info = &job->timestamp_query; unsigned int i; - int err; if (!v3d_validate_cpu_job(file_priv, job)) return -EINVAL; @@ -805,37 +792,30 @@ v3d_get_cpu_reset_timestamp_params(struct drm_file *file_priv, job->job_type = V3D_CPU_JOB_TYPE_RESET_TIMESTAMP_QUERY; - query_info->queries = kvmalloc_objs(struct v3d_timestamp_query, + query_info->queries = kvzalloc_objs(struct v3d_timestamp_query, reset.count); if (!query_info->queries) return -ENOMEM; + query_info->count = reset.count; + syncs = u64_to_user_ptr(reset.syncs); - for (i = 0; i < reset.count; i++) { + for (i = 0; i < query_info->count; i++) { u32 sync; query_info->queries[i].offset = reset.offset + 8 * i; - if (get_user(sync, syncs++)) { - err = -EFAULT; - goto error; - } + if (get_user(sync, syncs++)) + return -EFAULT; query_info->queries[i].syncobj = drm_syncobj_find(file_priv, sync); - if (!query_info->queries[i].syncobj) { - err = -ENOENT; - goto error; - } + if (!query_info->queries[i].syncobj) + return -ENOENT; } - query_info->count = reset.count; return 0; - -error: - v3d_timestamp_query_info_free(&job->timestamp_query, i); - return err; } /* Get data for the copy timestamp query results job submission. */ @@ -848,7 +828,6 @@ v3d_get_cpu_copy_query_results_params(struct drm_file *file_priv, struct drm_v3d_copy_timestamp_query copy; struct v3d_timestamp_query_info *query_info = &job->timestamp_query; unsigned int i; - int err; if (!v3d_validate_cpu_job(file_priv, job)) return -EINVAL; @@ -861,37 +840,32 @@ v3d_get_cpu_copy_query_results_params(struct drm_file *file_priv, job->job_type = V3D_CPU_JOB_TYPE_COPY_TIMESTAMP_QUERY; - query_info->queries = kvmalloc_objs(struct v3d_timestamp_query, + query_info->queries = kvzalloc_objs(struct v3d_timestamp_query, copy.count); if (!query_info->queries) return -ENOMEM; + query_info->count = copy.count; + offsets = u64_to_user_ptr(copy.offsets); syncs = u64_to_user_ptr(copy.syncs); - for (i = 0; i < copy.count; i++) { + for (i = 0; i < query_info->count; i++) { u32 offset, sync; - if (get_user(offset, offsets++)) { - err = -EFAULT; - goto error; - } + if (get_user(offset, offsets++)) + return -EFAULT; query_info->queries[i].offset = offset; - if (get_user(sync, syncs++)) { - err = -EFAULT; - goto error; - } + if (get_user(sync, syncs++)) + return -EFAULT; query_info->queries[i].syncobj = drm_syncobj_find(file_priv, sync); - if (!query_info->queries[i].syncobj) { - err = -ENOENT; - goto error; - } + if (!query_info->queries[i].syncobj) + return -ENOENT; } - query_info->count = copy.count; job->copy.do_64bit = copy.do_64bit; job->copy.do_partial = copy.do_partial; @@ -900,73 +874,51 @@ v3d_get_cpu_copy_query_results_params(struct drm_file *file_priv, job->copy.stride = copy.stride; return 0; - -error: - v3d_timestamp_query_info_free(&job->timestamp_query, i); - return err; } static int v3d_copy_query_info(struct v3d_performance_query_info *query_info, - unsigned int count, unsigned int nperfmons, u32 __user *syncs, u64 __user *kperfmon_ids, struct drm_file *file_priv) { unsigned int i, j; - int err; - for (i = 0; i < count; i++) { + for (i = 0; i < query_info->count; i++) { struct v3d_performance_query *query = &query_info->queries[i]; u32 __user *ids_pointer; u32 sync, id; u64 ids; - if (get_user(sync, syncs++)) { - err = -EFAULT; - goto error; - } + if (get_user(sync, syncs++)) + return -EFAULT; - if (get_user(ids, kperfmon_ids++)) { - err = -EFAULT; - goto error; - } + if (get_user(ids, kperfmon_ids++)) + return -EFAULT; query->kperfmon_ids = kvmalloc_array(nperfmons, sizeof(struct v3d_performance_query *), GFP_KERNEL); - if (!query->kperfmon_ids) { - err = -ENOMEM; - goto error; - } + if (!query->kperfmon_ids) + return -ENOMEM; ids_pointer = u64_to_user_ptr(ids); for (j = 0; j < nperfmons; j++) { - if (get_user(id, ids_pointer++)) { - kvfree(query->kperfmon_ids); - err = -EFAULT; - goto error; - } + if (get_user(id, ids_pointer++)) + return -EFAULT; query->kperfmon_ids[j] = id; } query->syncobj = drm_syncobj_find(file_priv, sync); - if (!query->syncobj) { - kvfree(query->kperfmon_ids); - err = -ENOENT; - goto error; - } + if (!query->syncobj) + return -ENOENT; } return 0; - -error: - v3d_performance_query_info_free(query_info, i); - return err; } static int @@ -987,12 +939,13 @@ v3d_get_cpu_reset_performance_params(struct drm_file *file_priv, job->job_type = V3D_CPU_JOB_TYPE_RESET_PERFORMANCE_QUERY; query_info->queries = - kvmalloc_objs(struct v3d_performance_query, reset.count); + kvzalloc_objs(struct v3d_performance_query, reset.count); if (!query_info->queries) return -ENOMEM; + query_info->count = reset.count; + err = v3d_copy_query_info(query_info, - reset.count, reset.nperfmons, u64_to_user_ptr(reset.syncs), u64_to_user_ptr(reset.kperfmon_ids), @@ -1000,7 +953,6 @@ v3d_get_cpu_reset_performance_params(struct drm_file *file_priv, if (err) return err; - query_info->count = reset.count; query_info->nperfmons = reset.nperfmons; return 0; @@ -1027,12 +979,13 @@ v3d_get_cpu_copy_performance_query_params(struct drm_file *file_priv, job->job_type = V3D_CPU_JOB_TYPE_COPY_PERFORMANCE_QUERY; query_info->queries = - kvmalloc_objs(struct v3d_performance_query, copy.count); + kvzalloc_objs(struct v3d_performance_query, copy.count); if (!query_info->queries) return -ENOMEM; + query_info->count = copy.count; + err = v3d_copy_query_info(query_info, - copy.count, copy.nperfmons, u64_to_user_ptr(copy.syncs), u64_to_user_ptr(copy.kperfmon_ids), @@ -1040,7 +993,6 @@ v3d_get_cpu_copy_performance_query_params(struct drm_file *file_priv, if (err) return err; - query_info->count = copy.count; query_info->nperfmons = copy.nperfmons; query_info->ncounters = copy.ncounters; diff --git a/drivers/gpu/drm/vc4/vc4_bo.c b/drivers/gpu/drm/vc4/vc4_bo.c index da4b11b7ce9f79..2ab7c158b7ff44 100644 --- a/drivers/gpu/drm/vc4/vc4_bo.c +++ b/drivers/gpu/drm/vc4/vc4_bo.c @@ -17,6 +17,7 @@ */ #include +#include #include #include @@ -836,6 +837,19 @@ int vc4_mmap_bo_ioctl(struct drm_device *dev, void *data, return 0; } +/* + * QPUs sharing a slice's instruction cache can livelock evicting each + * other's fills. Considering that shader BOs are page aligned, any code + * at offset 0 maps every shader to the same cache sets. This makes a + * livelock more likely to happen due to GFXH-16. + * + * Start each shader at one of four offsets, cycled per client, to spread + * them across sets. The use of four different offsets is motivated by the + * number of QPUs per slice (4 QPUs). + */ +#define VC4_SHADER_OFFSET_STEP 256 +#define VC4_SHADER_OFFSET_NUM 4 + int vc4_create_shader_bo_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) @@ -844,6 +858,7 @@ vc4_create_shader_bo_ioctl(struct drm_device *dev, void *data, struct vc4_file *vc4file = file_priv->driver_priv; struct vc4_dev *vc4 = to_vc4_dev(dev); struct vc4_bo *bo = NULL; + u32 offset, size; int ret; if (WARN_ON_ONCE(vc4->gen > VC4_GEN_4)) @@ -865,29 +880,37 @@ vc4_create_shader_bo_ioctl(struct drm_device *dev, void *data, return -EINVAL; } + offset = ((u32)atomic_inc_return(&vc4file->shader_offset_idx) % + VC4_SHADER_OFFSET_NUM) * VC4_SHADER_OFFSET_STEP; + + if (check_add_overflow(offset, args->size, &size)) + return -EINVAL; + ret = vc4_grab_bin_bo(vc4, vc4file); if (ret) return ret; - bo = vc4_bo_create(dev, args->size, true, VC4_BO_TYPE_V3D_SHADER); + bo = vc4_bo_create(dev, size, true, VC4_BO_TYPE_V3D_SHADER); if (IS_ERR(bo)) return PTR_ERR(bo); bo->madv = VC4_MADV_WILLNEED; + bo->shader_offset = offset; - if (copy_from_user(bo->base.vaddr, - (void __user *)(uintptr_t)args->data, - args->size)) { + /* Clear the memory around the code, which may come from the BO + * cache. + */ + memset(bo->base.vaddr, 0, offset); + if (copy_from_user(bo->base.vaddr + offset, + (void __user *)(uintptr_t)args->data, + args->size)) { ret = -EFAULT; goto fail; } - /* Clear the rest of the memory from allocating from the BO - * cache. - */ - memset(bo->base.vaddr + args->size, 0, - bo->base.base.size - args->size); + memset(bo->base.vaddr + offset + args->size, 0, + bo->base.base.size - offset - args->size); - bo->validated_shader = vc4_validate_shader(&bo->base); + bo->validated_shader = vc4_validate_shader(&bo->base, offset); if (!bo->validated_shader) { ret = -EINVAL; goto fail; diff --git a/drivers/gpu/drm/vc4/vc4_crtc.c b/drivers/gpu/drm/vc4/vc4_crtc.c index f42cd535323020..4b6d4a5f7bc9b7 100644 --- a/drivers/gpu/drm/vc4/vc4_crtc.c +++ b/drivers/gpu/drm/vc4/vc4_crtc.c @@ -884,17 +884,21 @@ struct vc4_async_flip_state { struct drm_framebuffer *fb; struct drm_framebuffer *old_fb; struct drm_pending_vblank_event *event; + struct dma_fence *fence; struct dma_fence_cb cb; + struct work_struct work; }; -/* Called when the V3D execution for the BO being flipped to is done, so that - * we can actually update the plane's address to point to it. +/* Executed when the V3D execution for the BO being flipped to is done, so + * that we can actually update the plane's address to point to it. */ -static void -vc4_async_page_flip_complete(struct vc4_async_flip_state *flip_state) +static void vc4_async_page_flip_work(struct work_struct *work) { + struct vc4_async_flip_state *flip_state = + container_of(work, struct vc4_async_flip_state, work); struct drm_crtc *crtc = flip_state->crtc; struct drm_device *dev = crtc->dev; + struct vc4_dev *vc4 = to_vc4_dev(dev); struct drm_plane *plane = crtc->primary; vc4_plane_async_set_fb(plane, flip_state->fb); @@ -909,82 +913,57 @@ vc4_async_page_flip_complete(struct vc4_async_flip_state *flip_state) drm_crtc_vblank_put(crtc); drm_framebuffer_put(flip_state->fb); - if (flip_state->old_fb) - drm_framebuffer_put(flip_state->old_fb); - - kfree(flip_state); -} + if (flip_state->old_fb) { + /* + * Decrement the BO usecnt in order to keep the inc/dec + * calls balanced when the planes are updated through + * the async update path. + * + * FIXME: we should move to generic async-page-flip when + * it's available, so that we can get rid of this + * hand-made cleanup_fb() logic. + */ + if (vc4->gen == VC4_GEN_4) { + struct drm_gem_dma_object *dma_bo = + drm_fb_dma_get_gem_obj(flip_state->old_fb, 0); -static void vc4_async_page_flip_complete_with_cleanup(struct dma_fence *fence, - struct dma_fence_cb *cb) -{ - struct vc4_async_flip_state *flip_state = - container_of(cb, struct vc4_async_flip_state, cb); - struct vc4_bo *bo = NULL; + vc4_bo_dec_usecnt(to_vc4_bo(&dma_bo->base)); + } - if (flip_state->old_fb) { - struct drm_gem_dma_object *dma_bo = - drm_fb_dma_get_gem_obj(flip_state->old_fb, 0); - bo = to_vc4_bo(&dma_bo->base); + drm_framebuffer_put(flip_state->old_fb); } - vc4_async_page_flip_complete(flip_state); - dma_fence_put(fence); - - /* - * Decrement the BO usecnt in order to keep the inc/dec - * calls balanced when the planes are updated through - * the async update path. - * - * FIXME: we should move to generic async-page-flip when - * it's available, so that we can get rid of this - * hand-made cleanup_fb() logic. - */ - if (bo) - vc4_bo_dec_usecnt(bo); + dma_fence_put(flip_state->fence); + kfree(flip_state); } -static void vc4_async_page_flip_fence_complete(struct dma_fence *fence, - struct dma_fence_cb *cb) +static void vc4_async_page_flip_fence_cb(struct dma_fence *fence, + struct dma_fence_cb *cb) { struct vc4_async_flip_state *flip_state = container_of(cb, struct vc4_async_flip_state, cb); + struct vc4_crtc *vc4_crtc = to_vc4_crtc(flip_state->crtc); - vc4_async_page_flip_complete(flip_state); - dma_fence_put(fence); + /* Completing the flip may sleep, so defer it to a worker. */ + queue_work(vc4_crtc->async_flip_wq, &flip_state->work); } -static int vc4_async_set_fence_cb(struct drm_device *dev, - struct vc4_async_flip_state *flip_state) +static void vc4_async_set_fence_cb(struct vc4_async_flip_state *flip_state) { - struct drm_framebuffer *fb = flip_state->fb; - struct drm_gem_dma_object *dma_bo = drm_fb_dma_get_gem_obj(fb, 0); - dma_fence_func_t async_page_flip_complete_function; - struct vc4_dev *vc4 = to_vc4_dev(dev); - struct dma_fence *fence; - int ret; + struct vc4_crtc *vc4_crtc = to_vc4_crtc(flip_state->crtc); - if (vc4->gen == VC4_GEN_4) - async_page_flip_complete_function = vc4_async_page_flip_complete_with_cleanup; - else - async_page_flip_complete_function = vc4_async_page_flip_fence_complete; - - ret = dma_resv_get_singleton(dma_bo->base.resv, DMA_RESV_USAGE_READ, &fence); - if (ret) - return ret; - - /* If there's no fence, complete the page flip immediately */ - if (!fence) { - async_page_flip_complete_function(fence, &flip_state->cb); - return 0; - } + INIT_WORK(&flip_state->work, vc4_async_page_flip_work); - /* If the fence has already been completed, complete the page flip */ - if (dma_fence_add_callback(fence, &flip_state->cb, - async_page_flip_complete_function)) - async_page_flip_complete_function(fence, &flip_state->cb); + if (flip_state->fence && + !dma_fence_add_callback(flip_state->fence, &flip_state->cb, + vc4_async_page_flip_fence_cb)) + return; - return 0; + /* No fence or the fence has already signaled. Complete the flip + * immediately, after earlier queued flips. + */ + flush_workqueue(vc4_crtc->async_flip_wq); + vc4_async_page_flip_work(&flip_state->work); } static int @@ -993,14 +972,22 @@ vc4_async_page_flip_common(struct drm_crtc *crtc, struct drm_pending_vblank_event *event, uint32_t flags) { - struct drm_device *dev = crtc->dev; + struct drm_gem_dma_object *dma_bo = drm_fb_dma_get_gem_obj(fb, 0); struct drm_plane *plane = crtc->primary; struct vc4_async_flip_state *flip_state; + int ret; flip_state = kzalloc_obj(*flip_state); if (!flip_state) return -ENOMEM; + ret = dma_resv_get_singleton(dma_bo->base.resv, DMA_RESV_USAGE_READ, + &flip_state->fence); + if (ret) { + kfree(flip_state); + return ret; + } + drm_framebuffer_get(fb); flip_state->fb = fb; flip_state->crtc = crtc; @@ -1008,7 +995,7 @@ vc4_async_page_flip_common(struct drm_crtc *crtc, /* Save the current FB before it's replaced by the new one in * drm_atomic_set_fb_for_plane(). We'll need the old FB in - * vc4_async_page_flip_complete() to decrement the BO usecnt and keep + * vc4_async_page_flip_work() to decrement the BO usecnt and keep * it consistent. * FIXME: we should move to generic async-page-flip when it's * available, so that we can get rid of this hand-made cleanup_fb() @@ -1026,7 +1013,7 @@ vc4_async_page_flip_common(struct drm_crtc *crtc, */ drm_atomic_set_fb_for_plane(plane->state, fb); - vc4_async_set_fence_cb(dev, flip_state); + vc4_async_set_fence_cb(flip_state); /* Driver takes ownership of state on successful async commit. */ return 0; @@ -1413,6 +1400,11 @@ int __vc4_crtc_init(struct drm_device *drm, drm_crtc_helper_add(crtc, crtc_helper_funcs); + vc4_crtc->async_flip_wq = drmm_alloc_ordered_workqueue(drm, "%s-async-flip", + 0, crtc->name); + if (IS_ERR(vc4_crtc->async_flip_wq)) + return PTR_ERR(vc4_crtc->async_flip_wq); + if (vc4->gen == VC4_GEN_4) { drm_mode_crtc_set_gamma_size(crtc, ARRAY_SIZE(vc4_crtc->lut_r)); drm_crtc_enable_color_mgmt(crtc, 0, false, crtc->gamma_size); diff --git a/drivers/gpu/drm/vc4/vc4_drv.h b/drivers/gpu/drm/vc4/vc4_drv.h index 09134809bf1565..dae325a3854d23 100644 --- a/drivers/gpu/drm/vc4/vc4_drv.h +++ b/drivers/gpu/drm/vc4/vc4_drv.h @@ -218,6 +218,11 @@ struct vc4_dev { struct { struct timer_list timer; struct work_struct reset_work; + + /* The instruction and uniforms caches were cleared at the + * last check that found no progress. + */ + bool caches_cleared; } hangcheck; struct drm_modeset_lock ctm_state_lock; @@ -255,6 +260,9 @@ struct vc4_bo { */ struct vc4_validated_shader_info *validated_shader; + /* Byte offset of the shader code in the BO. */ + u32 shader_offset; + /* One of enum vc4_kernel_bo_type, or VC4_BO_TYPE_COUNT + i * for user-allocated labels. */ @@ -596,6 +604,12 @@ struct vc4_crtc { * access to that value. */ unsigned int current_hvs_channel; + + /** + * @async_flip_wq: Ordered workqueue completing the CRTC's async + * page flips. + */ + struct workqueue_struct *async_flip_wq; }; #define to_vc4_crtc(_crtc) \ @@ -796,6 +810,11 @@ struct vc4_file { struct xarray perfmons; bool bin_bo_used; + + /* Counter picking the start offset of the next shader BO's code, + * see vc4_create_shader_bo_ioctl(). + */ + atomic_t shader_offset_idx; }; static inline struct vc4_exec_info * @@ -1083,7 +1102,7 @@ bool vc4_check_tex_size(struct vc4_exec_info *exec, /* vc4_validate_shader.c */ struct vc4_validated_shader_info * -vc4_validate_shader(struct drm_gem_dma_object *shader_obj); +vc4_validate_shader(struct drm_gem_dma_object *shader_obj, u32 offset); /* vc4_perfmon.c */ void vc4_perfmon_get(struct vc4_perfmon *perfmon); diff --git a/drivers/gpu/drm/vc4/vc4_dsi.c b/drivers/gpu/drm/vc4/vc4_dsi.c index 0148f2befed14a..762929ec471f84 100644 --- a/drivers/gpu/drm/vc4/vc4_dsi.c +++ b/drivers/gpu/drm/vc4/vc4_dsi.c @@ -1527,8 +1527,8 @@ static irqreturn_t vc4_dsi_irq_handler(int irq, void *data) complete(&dsi->xfer_completion); ret = IRQ_HANDLED; } else if (stat & DSI_PORT_BIT(INT_HSTX_TO)) { - complete(&dsi->xfer_completion); dsi->xfer_result = -ETIMEDOUT; + complete(&dsi->xfer_completion); ret = IRQ_HANDLED; } @@ -1599,9 +1599,8 @@ vc4_dsi_init_phy_clocks(struct vc4_dsi *dsi) dsi->clk_onecell->hws[i] = &fix->hw; } - return of_clk_add_hw_provider(dev->of_node, - of_clk_hw_onecell_get, - dsi->clk_onecell); + return devm_of_clk_add_hw_provider(dev, of_clk_hw_onecell_get, + dsi->clk_onecell); } static void vc4_dsi_dma_mem_release(void *ptr) diff --git a/drivers/gpu/drm/vc4/vc4_gem.c b/drivers/gpu/drm/vc4/vc4_gem.c index 956be198f8a7c8..9898eb1ef0774a 100644 --- a/drivers/gpu/drm/vc4/vc4_gem.c +++ b/drivers/gpu/drm/vc4/vc4_gem.c @@ -43,8 +43,7 @@ vc4_queue_hangcheck(struct drm_device *dev) { struct vc4_dev *vc4 = to_vc4_dev(dev); - mod_timer(&vc4->hangcheck.timer, - round_jiffies_up(jiffies + msecs_to_jiffies(100))); + mod_timer(&vc4->hangcheck.timer, jiffies + msecs_to_jiffies(100)); } struct vc4_hang_state { @@ -355,6 +354,7 @@ vc4_hangcheck_elapsed(struct timer_list *t) /* If idle, we can stop watching for hangs. */ if (!bin_exec && !render_exec) { + vc4->hangcheck.caches_cleared = false; spin_unlock_irqrestore(&vc4->job_lock, irqflags); return; } @@ -371,11 +371,27 @@ vc4_hangcheck_elapsed(struct timer_list *t) bin_exec->last_ct0ca = ct0ca; if (render_exec) render_exec->last_ct1ca = ct1ca; + + vc4->hangcheck.caches_cleared = false; + spin_unlock_irqrestore(&vc4->job_lock, irqflags); vc4_queue_hangcheck(dev); return; } + /* Clear the slice caches to workaround GFXH-16 */ + if (!vc4->hangcheck.caches_cleared) { + V3D_WRITE(V3D_SLCACTL, VC4_SET_FIELD(0xf, V3D_SLCACTL_ICC) | + VC4_SET_FIELD(0xf, V3D_SLCACTL_UCC)); + + vc4->hangcheck.caches_cleared = true; + spin_unlock_irqrestore(&vc4->job_lock, irqflags); + vc4_queue_hangcheck(dev); + return; + } + + vc4->hangcheck.caches_cleared = false; + spin_unlock_irqrestore(&vc4->job_lock, irqflags); /* We've gone too long with no progress, reset. This has to diff --git a/drivers/gpu/drm/vc4/vc4_validate.c b/drivers/gpu/drm/vc4/vc4_validate.c index 565227657b43b4..b67ac1b212652e 100644 --- a/drivers/gpu/drm/vc4/vc4_validate.c +++ b/drivers/gpu/drm/vc4/vc4_validate.c @@ -815,7 +815,7 @@ validate_gl_shader_rec(struct drm_device *dev, exec->shader_rec_size -= packet_size; for (i = 0; i < shader_reloc_count; i++) { - if (src_handles[i] > exec->bo_count) { + if (src_handles[i] >= exec->bo_count) { DRM_DEBUG("Shader handle %d too big\n", src_handles[i]); return -EINVAL; } @@ -823,6 +823,9 @@ validate_gl_shader_rec(struct drm_device *dev, bo[i] = to_drm_gem_dma_obj(exec->bo[src_handles[i]]); if (!bo[i]) return -EINVAL; + + if (!to_vc4_bo(&bo[i]->base)->validated_shader) + return -EINVAL; } for (i = shader_reloc_count; i < nr_relocs; i++) { bo[i] = vc4_use_bo(exec, src_handles[i]); @@ -843,14 +846,16 @@ validate_gl_shader_rec(struct drm_device *dev, } for (i = 0; i < shader_reloc_count; i++) { - struct vc4_validated_shader_info *validated_shader; + struct vc4_validated_shader_info *validated_shader = + to_vc4_bo(&bo[i]->base)->validated_shader; uint32_t o = shader_reloc_offsets[i]; uint32_t src_offset = *(uint32_t *)(pkt_u + o); uint32_t *texture_handles_u; void *uniform_data_u; uint32_t tex, uni; - *(uint32_t *)(pkt_v + o) = bo[i]->dma_addr + src_offset; + *(uint32_t *)(pkt_v + o) = bo[i]->dma_addr + src_offset + + to_vc4_bo(&bo[i]->base)->shader_offset; if (src_offset != 0) { DRM_DEBUG("Shaders must be at offset 0 of " @@ -858,10 +863,6 @@ validate_gl_shader_rec(struct drm_device *dev, return -EINVAL; } - validated_shader = to_vc4_bo(&bo[i]->base)->validated_shader; - if (!validated_shader) - return -EINVAL; - if (validated_shader->uniforms_src_size > exec->uniforms_size) { DRM_DEBUG("Uniforms src buffer overflow\n"); diff --git a/drivers/gpu/drm/vc4/vc4_validate_shaders.c b/drivers/gpu/drm/vc4/vc4_validate_shaders.c index db7c0dbdf60e27..09ebd8f92bf5b2 100644 --- a/drivers/gpu/drm/vc4/vc4_validate_shaders.c +++ b/drivers/gpu/drm/vc4/vc4_validate_shaders.c @@ -779,7 +779,7 @@ vc4_handle_branch_target(struct vc4_shader_validation_state *validation_state) } struct vc4_validated_shader_info * -vc4_validate_shader(struct drm_gem_dma_object *shader_obj) +vc4_validate_shader(struct drm_gem_dma_object *shader_obj, u32 offset) { struct vc4_dev *vc4 = to_vc4_dev(shader_obj->base.dev); bool found_shader_end = false; @@ -793,8 +793,9 @@ vc4_validate_shader(struct drm_gem_dma_object *shader_obj) return NULL; memset(&validation_state, 0, sizeof(validation_state)); - validation_state.shader = shader_obj->vaddr; - validation_state.max_ip = shader_obj->base.size / sizeof(uint64_t); + validation_state.shader = shader_obj->vaddr + offset; + validation_state.max_ip = (shader_obj->base.size - offset) / + sizeof(uint64_t); reset_validation_state(&validation_state); diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_bo.c b/drivers/gpu/drm/vmwgfx/vmwgfx_bo.c index 9c7a73c0b0dc39..a6d7156e428162 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_bo.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_bo.c @@ -55,6 +55,8 @@ static void vmw_bo_free(struct ttm_buffer_object *bo) /* Reserve and switch the backing mob. */ mutex_lock(&res->dev_priv->cmdbuf_mutex); (void)vmw_resource_reserve(res, false, true); + /* TTM drops the reservation before calling the destructor. */ + dma_resv_lock(bo->base.resv, NULL); vmw_resource_mob_detach(res); if (res->dirty) res->func->dirty_free(res); @@ -62,6 +64,7 @@ static void vmw_bo_free(struct ttm_buffer_object *bo) vmw_bo_dirty_release(res->guest_memory_bo); res->guest_memory_bo = NULL; res->guest_memory_offset = 0; + dma_resv_unlock(bo->base.resv); vmw_resource_unreserve(res, true, false, false, NULL, 0); mutex_unlock(&res->dev_priv->cmdbuf_mutex); diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c b/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c index 5a69606a0593bc..b678e5b68db7bb 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c @@ -89,10 +89,26 @@ vmw_cursor_plane_update_legacy(struct vmw_private *vmw, } } +static struct vmw_user_object +vmw_cursor_plane_user_object(struct drm_framebuffer *fb) +{ + struct vmw_user_object uo = { 0 }; + + if (!fb) + return uo; + + if (vmw_framebuffer_to_vfb(fb)->bo) + uo.buffer = vmw_framebuffer_to_vfbd(fb)->buffer; + else + uo = vmw_framebuffer_to_vfbs(fb)->uo; + + return uo; +} + static enum vmw_cursor_update_type -vmw_cursor_update_type(struct vmw_private *vmw, struct vmw_plane_state *vps) +vmw_cursor_update_type(struct vmw_private *vmw, struct vmw_user_object *uo) { - struct vmw_surface *surface = vmw_user_object_surface(&vps->uo); + struct vmw_surface *surface = vmw_user_object_surface(uo); if (surface && surface->snooper.image) return VMW_CURSOR_UPDATE_LEGACY; @@ -112,8 +128,7 @@ static void vmw_cursor_update_mob(struct vmw_private *vmw, { SVGAGBCursorHeader *header; SVGAGBAlphaCursorHeader *alpha_header; - struct vmw_bo *bo = vmw_user_object_buffer(&vps->uo); - u32 *image = vmw_bo_map_and_cache(bo); + u32 *image = vps->cursor.map.virtual; const u32 image_size = vps->base.crtc_w * vps->base.crtc_h * sizeof(*image); header = vmw_bo_map_and_cache(vps->cursor.mob); @@ -132,7 +147,6 @@ static void vmw_cursor_update_mob(struct vmw_private *vmw, memcpy(header + 1, image, image_size); vmw_write(vmw, SVGA_REG_CURSOR_MOBID, vmw_bo_mobid(vps->cursor.mob)); - vmw_bo_unmap(bo); vmw_bo_unmap(vps->cursor.mob); } @@ -152,10 +166,17 @@ static u32 vmw_cursor_mob_size(enum vmw_cursor_update_type update_type, static void vmw_cursor_mob_destroy(struct vmw_bo **vbo) { + int ret; + if (!(*vbo)) return; + ret = ttm_bo_reserve(&(*vbo)->tbo, false, false, NULL); + if (WARN_ON_ONCE(ret)) + return; + ttm_bo_unpin(&(*vbo)->tbo); + ttm_bo_unreserve(&(*vbo)->tbo); vmw_bo_unreference(vbo); } @@ -490,9 +511,21 @@ vmw_cursor_plane_cleanup_fb(struct drm_plane *plane, { struct vmw_cursor_plane *vcp = vmw_plane_to_vcp(plane); struct vmw_plane_state *vps = vmw_plane_state_to_vps(old_state); + struct vmw_bo *bo; + int ret; - if (!vmw_user_object_is_null(&vps->uo)) - vmw_user_object_unmap(&vps->uo); + if (vps->cursor.map.bo) { + bo = to_vmw_bo(&vps->cursor.map.bo->base); + ret = ttm_bo_reserve(&bo->tbo, false, false, NULL); + if (WARN_ON_ONCE(ret)) + return; + + ttm_bo_kunmap(&vps->cursor.map); + vps->cursor.map.bo = NULL; + ttm_bo_unpin(&bo->tbo); + ttm_bo_unreserve(&bo->tbo); + vmw_bo_unreference(&bo); + } vmw_cursor_mob_unmap(vps); vmw_cursor_mob_put(vcp, vps); @@ -625,22 +658,17 @@ int vmw_cursor_plane_prepare_fb(struct drm_plane *plane, struct vmw_surface *surface; int ret = 0; - if (!vmw_user_object_is_null(&vps->uo)) { - vmw_user_object_unmap(&vps->uo); + /* + * A duplicated state only owns the user object reference. Its mappings + * and pins belong to the old state until cleanup_fb(). + */ + if (!vmw_user_object_is_null(&vps->uo)) vmw_user_object_unref(&vps->uo); - } - if (fb) { - if (vmw_framebuffer_to_vfb(fb)->bo) { - vps->uo.buffer = vmw_framebuffer_to_vfbd(fb)->buffer; - vps->uo.surface = NULL; - } else { - memcpy(&vps->uo, &vmw_framebuffer_to_vfbs(fb)->uo, sizeof(vps->uo)); - } - vmw_user_object_ref(&vps->uo); - } + vps->uo = vmw_cursor_plane_user_object(fb); + vmw_user_object_ref(&vps->uo); - vps->cursor.update_type = vmw_cursor_update_type(vmw, vps); + vps->cursor.update_type = vmw_cursor_update_type(vmw, &vps->uo); switch (vps->cursor.update_type) { case VMW_CURSOR_UPDATE_LEGACY: surface = vmw_user_object_surface(&vps->uo); @@ -650,33 +678,39 @@ int vmw_cursor_plane_prepare_fb(struct drm_plane *plane, case VMW_CURSOR_UPDATE_GB_ONLY: case VMW_CURSOR_UPDATE_MOB: { bo = vmw_user_object_buffer(&vps->uo); + if (fb && !bo) + return -EINVAL; + if (bo) { struct ttm_operation_ctx ctx = { false, false }; + size_t size = (size_t)new_state->crtc_w * + new_state->crtc_h * sizeof(u32); ret = ttm_bo_reserve(&bo->tbo, true, false, NULL); if (ret != 0) - return -ENOMEM; + return ret; ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx); if (ret != 0) - return -ENOMEM; + goto out_unreserve; /* - * vmw_bo_pin_reserved also validates, so to skip - * the extra validation use ttm_bo_pin directly + * vmw_bo_pin_reserved() also validates, so to skip + * the extra validation use ttm_bo_pin directly. + * Every state takes its own pin, the buffer can + * still be in use by an older state whose commit + * hasn't been cleaned up yet. */ - if (!bo->tbo.pin_count) - ttm_bo_pin(&bo->tbo); - - if (vmw_framebuffer_to_vfb(fb)->bo) { - const u32 size = new_state->crtc_w * - new_state->crtc_h * - sizeof(u32); - - (void)vmw_bo_map_and_cache_size(bo, size); - } else { - vmw_bo_map_and_cache(bo); + ttm_bo_pin(&bo->tbo); + + ret = ttm_bo_kmap(&bo->tbo, 0, PFN_UP(size), + &vps->cursor.map); + if (ret) { + vps->cursor.map.bo = NULL; + ttm_bo_unpin(&bo->tbo); + goto out_unreserve; } + vmw_bo_reference(bo); ttm_bo_unreserve(&bo->tbo); } if (!vmw_user_object_is_null(&vps->uo)) { @@ -703,6 +737,10 @@ int vmw_cursor_plane_prepare_fb(struct drm_plane *plane, } return 0; + +out_unreserve: + ttm_bo_unreserve(&bo->tbo); + return ret; } /** @@ -725,7 +763,7 @@ int vmw_cursor_plane_atomic_check(struct drm_plane *plane, int ret = 0; struct drm_crtc_state *crtc_state = NULL; struct vmw_surface *surface = NULL; - struct vmw_plane_state *vps = vmw_plane_state_to_vps(new_state); + struct vmw_user_object uo; enum vmw_cursor_update_type update_type; struct drm_framebuffer *fb = new_state->fb; @@ -744,7 +782,21 @@ int vmw_cursor_plane_atomic_check(struct drm_plane *plane, if (!fb) return 0; - update_type = vmw_cursor_update_type(vmw, vps); + if (!new_state->crtc_w || !new_state->crtc_h) { + drm_dbg_kms(&vmw->drm, + "Cursor dimensions (%u, %u) must be nonzero\n", + new_state->crtc_w, new_state->crtc_h); + return -EINVAL; + } + + /* The duplicated plane state's user object still belongs to the old FB. */ + uo = vmw_cursor_plane_user_object(fb); + update_type = vmw_cursor_update_type(vmw, &uo); + if ((update_type == VMW_CURSOR_UPDATE_GB_ONLY || + update_type == VMW_CURSOR_UPDATE_MOB) && + !vmw_user_object_buffer(&uo)) + return -EINVAL; + if (update_type == VMW_CURSOR_UPDATE_LEGACY) { if (new_state->crtc_w != VMW_CURSOR_SNOOP_WIDTH || new_state->crtc_h != VMW_CURSOR_SNOOP_HEIGHT) { @@ -753,14 +805,32 @@ int vmw_cursor_plane_atomic_check(struct drm_plane *plane, new_state->crtc_w, new_state->crtc_h); return -EINVAL; } - surface = vmw_user_object_surface(&vps->uo); + surface = vmw_user_object_surface(&uo); if (!surface || !surface->snooper.image) { drm_warn(&vmw->drm, "surface not suitable for cursor\n"); return -EINVAL; } - } else if (update_type == VMW_CURSOR_UPDATE_GB_ONLY || - update_type == VMW_CURSOR_UPDATE_MOB) { + } else if (update_type == VMW_CURSOR_UPDATE_GB_ONLY) { + u64 image_size = (u64)new_state->crtc_w * + new_state->crtc_h * sizeof(u32); + u32 max_size = SVGA_MAX_CURSOR_CMD_BYTES; + + /* The command-buffer limit includes the define-cursor header. */ + if (vmw->cman) + max_size = min_t(u32, max_size, + SVGA_CB_MAX_COMMAND_SIZE - + sizeof(struct vmw_svga_fifo_cmd_define_cursor)); + + if (new_state->crtc_w > SVGA_MAX_CURSOR_CMD_DIMENSION || + new_state->crtc_h > SVGA_MAX_CURSOR_CMD_DIMENSION || + image_size > max_size) { + drm_dbg_kms(&vmw->drm, + "Cursor dimensions (%u, %u) violate command limits\n", + new_state->crtc_w, new_state->crtc_h); + return -EINVAL; + } + } else if (update_type == VMW_CURSOR_UPDATE_MOB) { u32 cursor_max_dim = vmw_read(vmw, SVGA_REG_CURSOR_MAX_DIMENSION); @@ -796,7 +866,6 @@ void vmw_cursor_plane_atomic_update(struct drm_plane *plane, struct drm_atomic_commit *state) { - struct vmw_bo *bo; struct drm_plane_state *new_state = drm_atomic_get_new_plane_state(state, plane); struct drm_plane_state *old_state = @@ -815,6 +884,10 @@ vmw_cursor_plane_atomic_update(struct drm_plane *plane, return; } + /* Include legacy Xorg cursor-bypass offsets in the image and position. */ + hotspot_x = vps->cursor.legacy.hotspot_x + new_state->hotspot_x; + hotspot_y = vps->cursor.legacy.hotspot_y + new_state->hotspot_y; + switch (vps->cursor.update_type) { case VMW_CURSOR_UPDATE_LEGACY: vmw_cursor_plane_update_legacy(dev_priv, vps); @@ -823,13 +896,11 @@ vmw_cursor_plane_atomic_update(struct drm_plane *plane, vmw_cursor_update_mob(dev_priv, vps); break; case VMW_CURSOR_UPDATE_GB_ONLY: - bo = vmw_user_object_buffer(&vps->uo); - if (bo) - vmw_send_define_cursor_cmd(dev_priv, bo->map.virtual, + if (vps->cursor.map.virtual) + vmw_send_define_cursor_cmd(dev_priv, vps->cursor.map.virtual, vps->base.crtc_w, vps->base.crtc_h, - vps->base.hotspot_x, - vps->base.hotspot_y); + hotspot_x, hotspot_y); break; case VMW_CURSOR_UPDATE_NONE: /* do nothing */ @@ -842,9 +913,6 @@ vmw_cursor_plane_atomic_update(struct drm_plane *plane, cursor_x = new_state->crtc_x + du->set_gui_x; cursor_y = new_state->crtc_y + du->set_gui_y; - hotspot_x = vps->cursor.legacy.hotspot_x + new_state->hotspot_x; - hotspot_y = vps->cursor.legacy.hotspot_y + new_state->hotspot_y; - vmw_cursor_update_position(dev_priv, true, cursor_x + hotspot_x, cursor_y + hotspot_y); } diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.h b/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.h index d32cf17d013b51..9b50f80f9635a4 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.h +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.h @@ -14,6 +14,8 @@ #include "drm/drm_fourcc.h" #include "drm/drm_plane.h" +#include + #include struct SVGA3dCmdHeader; @@ -41,6 +43,8 @@ struct vmw_cursor_plane_state { enum vmw_cursor_update_type update_type; bool changed; bool surface_changed; + /* The mapped buffer is referenced and pinned by this state. */ + struct ttm_bo_kmap_obj map; struct vmw_bo *mob; struct { s32 hotspot_x; diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_execbuf.c b/drivers/gpu/drm/vmwgfx/vmwgfx_execbuf.c index a9136a6523cbac..435425f1adfa67 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_execbuf.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_execbuf.c @@ -564,6 +564,29 @@ static int vmw_cmd_ok(struct vmw_private *dev_priv, return 0; } +/** + * vmw_cmd_body_fits - Check that a command body covers what a handler reads + * + * @header: Pointer to the command header in the command stream. + * @size: Number of body bytes that the command handler interprets. + * + * vmw_cmd_check() only verifies that @header->size fits into the submitted + * command buffer. A handler that reads past the declared body reads the next + * command, which is verified separately. A relocation recorded there would + * rewrite the already verified command after verification has finished. + * + * Return: true if the body is at least @size bytes, false otherwise. + */ +static bool vmw_cmd_body_fits(const SVGA3dCmdHeader *header, size_t size) +{ + if (likely(header->size >= size)) + return true; + + VMW_DEBUG_USER("SVGA3D command %u: body size %u is smaller than %zu.\n", + header->id, header->size, size); + return false; +} + /** * vmw_resources_reserve - Reserve all resources on the sw_context's resource * list. @@ -810,6 +833,9 @@ static int vmw_cmd_cid_check(struct vmw_private *dev_priv, VMW_DECLARE_CMD_VAR(*cmd, uint32_t) = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + return vmw_cmd_res_check(dev_priv, sw_context, vmw_res_context, VMW_RES_DIRTY_SET, user_context_converter, &cmd->body, NULL); @@ -853,6 +879,8 @@ static int vmw_cmd_set_render_target_check(struct vmw_private *dev_priv, int ret; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; if (cmd->body.type >= SVGA3D_RT_MAX) { VMW_DEBUG_USER("Illegal render target type %u.\n", @@ -898,6 +926,8 @@ static int vmw_cmd_surface_copy_check(struct vmw_private *dev_priv, int ret; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; ret = vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_NONE, user_surface_converter, @@ -918,6 +948,9 @@ static int vmw_cmd_buffer_copy_check(struct vmw_private *dev_priv, int ret; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + ret = vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_NONE, user_surface_converter, &cmd->body.src, NULL); @@ -937,6 +970,9 @@ static int vmw_cmd_pred_copy_check(struct vmw_private *dev_priv, int ret; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + ret = vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_NONE, user_surface_converter, &cmd->body.srcSid, NULL); @@ -956,6 +992,9 @@ static int vmw_cmd_stretch_blt_check(struct vmw_private *dev_priv, int ret; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + ret = vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_NONE, user_surface_converter, &cmd->body.src.sid, NULL); @@ -974,6 +1013,9 @@ static int vmw_cmd_blt_surf_screen_check(struct vmw_private *dev_priv, VMW_DECLARE_CMD_VAR(*cmd, SVGA3dCmdBlitSurfaceToScreen) = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + return vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_NONE, user_surface_converter, &cmd->body.srcImage.sid, NULL); @@ -986,6 +1028,9 @@ static int vmw_cmd_present_check(struct vmw_private *dev_priv, VMW_DECLARE_CMD_VAR(*cmd, SVGA3dCmdPresent) = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + return vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_NONE, user_surface_converter, &cmd->body.sid, NULL); @@ -1243,6 +1288,8 @@ static int vmw_cmd_dx_define_query(struct vmw_private *dev_priv, return -EINVAL; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; if (cmd->body.type < SVGA3D_QUERYTYPE_MIN || cmd->body.type >= SVGA3D_QUERYTYPE_MAX) @@ -1280,6 +1327,8 @@ static int vmw_cmd_dx_bind_query(struct vmw_private *dev_priv, return -EINVAL; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; /* * Look up the buffer pointed to by q.mobid, put it on the relocation @@ -1310,6 +1359,9 @@ static int vmw_cmd_begin_gb_query(struct vmw_private *dev_priv, VMW_DECLARE_CMD_VAR(*cmd, SVGA3dCmdBeginGBQuery) = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + return vmw_cmd_res_check(dev_priv, sw_context, vmw_res_context, VMW_RES_DIRTY_SET, user_context_converter, &cmd->body.cid, NULL); @@ -1329,6 +1381,9 @@ static int vmw_cmd_begin_query(struct vmw_private *dev_priv, VMW_DECLARE_CMD_VAR(*cmd, SVGA3dCmdBeginQuery) = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (unlikely(dev_priv->has_mob)) { VMW_DECLARE_CMD_VAR(gb_cmd, SVGA3dCmdBeginGBQuery); @@ -1364,6 +1419,9 @@ static int vmw_cmd_end_gb_query(struct vmw_private *dev_priv, int ret; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + ret = vmw_cmd_cid_check(dev_priv, sw_context, header); if (unlikely(ret != 0)) return ret; @@ -1394,6 +1452,9 @@ static int vmw_cmd_end_query(struct vmw_private *dev_priv, int ret; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (dev_priv->has_mob) { VMW_DECLARE_CMD_VAR(gb_cmd, SVGA3dCmdEndGBQuery); @@ -1440,6 +1501,9 @@ static int vmw_cmd_wait_gb_query(struct vmw_private *dev_priv, int ret; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + ret = vmw_cmd_cid_check(dev_priv, sw_context, header); if (unlikely(ret != 0)) return ret; @@ -1468,6 +1532,9 @@ static int vmw_cmd_wait_query(struct vmw_private *dev_priv, int ret; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (dev_priv->has_mob) { VMW_DECLARE_CMD_VAR(gb_cmd, SVGA3dCmdWaitForGBQuery); @@ -1637,6 +1704,15 @@ static int vmw_cmd_tex_state(struct vmw_private *dev_priv, int ret; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + + /* The loop below must not read a truncated trailing state. */ + if ((header->size - sizeof(cmd->body)) % sizeof(*cur_state)) { + VMW_DEBUG_USER("Invalid texture state size %u.\n", + header->size); + return -EINVAL; + } ret = vmw_cmd_res_check(dev_priv, sw_context, vmw_res_context, VMW_RES_DIRTY_SET, user_context_converter, @@ -1718,6 +1794,7 @@ static int vmw_cmd_res_switch_backup(struct vmw_private *dev_priv, { struct vmw_bo *vbo; void *info; + u64 end; int ret; info = vmw_execbuf_info_from_res(sw_context, res); @@ -1728,6 +1805,13 @@ static int vmw_cmd_res_switch_backup(struct vmw_private *dev_priv, if (ret) return ret; + if (check_add_overflow((u64)backup_offset, + (u64)res->guest_memory_size, &end) || + end > vbo->tbo.base.size) { + VMW_DEBUG_USER("Backup buffer too small for resource.\n"); + return -EINVAL; + } + vmw_validation_res_switch_backup(sw_context->ctx, info, vbo, backup_offset); return 0; @@ -1782,6 +1866,9 @@ static int vmw_cmd_bind_gb_surface(struct vmw_private *dev_priv, VMW_DECLARE_CMD_VAR(*cmd, SVGA3dCmdBindGBSurface) = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + return vmw_cmd_switch_backup(dev_priv, sw_context, vmw_res_surface, user_surface_converter, &cmd->body.sid, &cmd->body.mobid, 0); @@ -1801,6 +1888,9 @@ static int vmw_cmd_update_gb_image(struct vmw_private *dev_priv, VMW_DECLARE_CMD_VAR(*cmd, SVGA3dCmdUpdateGBImage) = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + return vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_NONE, user_surface_converter, &cmd->body.image.sid, NULL); @@ -1820,6 +1910,9 @@ static int vmw_cmd_update_gb_surface(struct vmw_private *dev_priv, VMW_DECLARE_CMD_VAR(*cmd, SVGA3dCmdUpdateGBSurface) = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + return vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_CLEAR, user_surface_converter, &cmd->body.sid, NULL); @@ -1839,6 +1932,9 @@ static int vmw_cmd_readback_gb_image(struct vmw_private *dev_priv, VMW_DECLARE_CMD_VAR(*cmd, SVGA3dCmdReadbackGBImage) = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + return vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_NONE, user_surface_converter, &cmd->body.image.sid, NULL); @@ -1859,6 +1955,9 @@ static int vmw_cmd_readback_gb_surface(struct vmw_private *dev_priv, VMW_DECLARE_CMD_VAR(*cmd, SVGA3dCmdReadbackGBSurface) = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + return vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_CLEAR, user_surface_converter, &cmd->body.sid, NULL); @@ -1879,6 +1978,9 @@ static int vmw_cmd_invalidate_gb_image(struct vmw_private *dev_priv, VMW_DECLARE_CMD_VAR(*cmd, SVGA3dCmdInvalidateGBImage) = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + return vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_NONE, user_surface_converter, &cmd->body.image.sid, NULL); @@ -1899,6 +2001,9 @@ static int vmw_cmd_invalidate_gb_surface(struct vmw_private *dev_priv, VMW_DECLARE_CMD_VAR(*cmd, SVGA3dCmdInvalidateGBSurface) = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + return vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_CLEAR, user_surface_converter, &cmd->body.sid, NULL); @@ -1921,6 +2026,8 @@ static int vmw_cmd_shader_define(struct vmw_private *dev_priv, struct vmw_resource *ctx; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; ret = vmw_cmd_res_check(dev_priv, sw_context, vmw_res_context, VMW_RES_DIRTY_SET, user_context_converter, @@ -1960,6 +2067,8 @@ static int vmw_cmd_shader_destroy(struct vmw_private *dev_priv, struct vmw_resource *ctx; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; ret = vmw_cmd_res_check(dev_priv, sw_context, vmw_res_context, VMW_RES_DIRTY_SET, user_context_converter, @@ -1999,6 +2108,8 @@ static int vmw_cmd_set_shader(struct vmw_private *dev_priv, int ret; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; if (!vmw_shadertype_is_valid(VMW_SM_LEGACY, cmd->body.type)) { VMW_DEBUG_USER("Illegal shader type %u.\n", @@ -2077,6 +2188,8 @@ static int vmw_cmd_set_shader_const(struct vmw_private *dev_priv, int ret; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; ret = vmw_cmd_res_check(dev_priv, sw_context, vmw_res_context, VMW_RES_DIRTY_SET, user_context_converter, @@ -2104,6 +2217,9 @@ static int vmw_cmd_bind_gb_shader(struct vmw_private *dev_priv, VMW_DECLARE_CMD_VAR(*cmd, SVGA3dCmdBindGBShader) = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + return vmw_cmd_switch_backup(dev_priv, sw_context, vmw_res_shader, user_shader_converter, &cmd->body.shid, &cmd->body.mobid, cmd->body.offsetInBytes); @@ -2133,6 +2249,9 @@ vmw_cmd_dx_set_single_constant_buffer(struct vmw_private *dev_priv, return -EINVAL; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + ret = vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_NONE, user_surface_converter, &cmd->body.sid, &res); @@ -2186,6 +2305,9 @@ vmw_cmd_dx_set_constant_buffer_offset(struct vmw_private *dev_priv, return -EINVAL; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (cmd->body.slot >= SVGA3D_DX_MAX_CONSTBUFFERS) { VMW_DEBUG_USER("Illegal const buffer slot %u.\n", (unsigned int) cmd->body.slot); @@ -2217,6 +2339,9 @@ static int vmw_cmd_dx_set_shader_res(struct vmw_private *dev_priv, u32 num_sr_view = (cmd->header.size - sizeof(cmd->body)) / sizeof(SVGA3dShaderResourceViewId); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if ((u64) cmd->body.startView + (u64) num_sr_view > (u64) SVGA3D_DX_MAX_SRVIEWS || !vmw_shadertype_is_valid(dev_priv->sm_type, cmd->body.type)) { @@ -2252,6 +2377,8 @@ static int vmw_cmd_dx_set_shader(struct vmw_private *dev_priv, return -EINVAL; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; if (!vmw_shadertype_is_valid(dev_priv->sm_type, cmd->body.type)) { VMW_DEBUG_USER("Illegal shader type %u.\n", @@ -2309,6 +2436,9 @@ static int vmw_cmd_dx_set_vertex_buffers(struct vmw_private *dev_priv, return -EINVAL; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + num = (cmd->header.size - sizeof(cmd->body)) / sizeof(SVGA3dVertexBuffer); if ((u64)num + (u64)cmd->body.startBuffer > @@ -2360,6 +2490,9 @@ static int vmw_cmd_dx_set_index_buffer(struct vmw_private *dev_priv, return -EINVAL; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + ret = vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_NONE, user_surface_converter, &cmd->body.sid, &res); @@ -2395,6 +2528,9 @@ static int vmw_cmd_dx_set_rendertargets(struct vmw_private *dev_priv, sizeof(SVGA3dRenderTargetViewId); int ret; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (num_rt_view > SVGA3D_DX_MAX_RENDER_TARGETS) { VMW_DEBUG_USER("Invalid DX Rendertarget binding.\n"); return -EINVAL; @@ -2426,6 +2562,9 @@ static int vmw_cmd_dx_clear_rendertarget_view(struct vmw_private *dev_priv, container_of(header, typeof(*cmd), header); struct vmw_resource *ret; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + ret = vmw_view_id_val_add(sw_context, vmw_view_rt, cmd->body.renderTargetViewId); @@ -2448,6 +2587,9 @@ static int vmw_cmd_dx_clear_depthstencil_view(struct vmw_private *dev_priv, container_of(header, typeof(*cmd), header); struct vmw_resource *ret; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + ret = vmw_view_id_val_add(sw_context, vmw_view_ds, cmd->body.depthStencilViewId); @@ -2481,6 +2623,9 @@ static int vmw_cmd_dx_view_define(struct vmw_private *dev_priv, return -EINVAL; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(*cmd) - sizeof(*header))) + return -EINVAL; + if (unlikely(cmd->sid == SVGA3D_INVALID_ID)) { VMW_DEBUG_USER("Invalid surface id.\n"); return -EINVAL; @@ -2529,6 +2674,9 @@ static int vmw_cmd_dx_set_so_targets(struct vmw_private *dev_priv, return -EINVAL; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + num = (cmd->header.size - sizeof(cmd->body)) / sizeof(SVGA3dSoTarget); if (num > SVGA3D_DX_MAX_SOTARGETS) { @@ -2582,6 +2730,9 @@ static int vmw_cmd_dx_so_define(struct vmw_private *dev_priv, if (IS_ERR_OR_NULL(res)) return res ? PTR_ERR(res) : -EINVAL; cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(*cmd) - sizeof(*header))) + return -EINVAL; + ret = vmw_cotable_notify(res, cmd->defined_id); return ret; @@ -2617,6 +2768,9 @@ static int vmw_cmd_dx_check_subresource(struct vmw_private *dev_priv, offsetof(typeof(*cmd), sid)); cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->sid))) + return -EINVAL; + return vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_NONE, user_surface_converter, &cmd->sid, NULL); @@ -2658,6 +2812,9 @@ static int vmw_cmd_dx_view_remove(struct vmw_private *dev_priv, struct vmw_resource *view; int ret; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (!ctx_node) return -EINVAL; @@ -2695,6 +2852,9 @@ static int vmw_cmd_dx_define_shader(struct vmw_private *dev_priv, container_of(header, typeof(*cmd), header); int ret; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (!ctx_node) return -EINVAL; @@ -2726,6 +2886,9 @@ static int vmw_cmd_dx_destroy_shader(struct vmw_private *dev_priv, container_of(header, typeof(*cmd), header); int ret; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (!ctx_node) return -EINVAL; @@ -2752,6 +2915,9 @@ static int vmw_cmd_dx_bind_shader(struct vmw_private *dev_priv, container_of(header, typeof(*cmd), header); int ret; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (cmd->body.cid != SVGA3D_INVALID_ID) { ret = vmw_cmd_res_check(dev_priv, sw_context, vmw_res_context, VMW_RES_DIRTY_SET, @@ -2803,6 +2969,9 @@ static int vmw_cmd_dx_genmips(struct vmw_private *dev_priv, struct vmw_resource *view; struct vmw_res_cache_entry *rcache; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + view = vmw_view_id_val_add(sw_context, vmw_view_sr, cmd->body.shaderResourceViewId); if (IS_ERR(view)) @@ -2836,6 +3005,9 @@ static int vmw_cmd_dx_transfer_from_buffer(struct vmw_private *dev_priv, container_of(header, typeof(*cmd), header); int ret; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + ret = vmw_cmd_res_check(dev_priv, sw_context, vmw_res_surface, VMW_RES_DIRTY_NONE, user_surface_converter, &cmd->body.srcSid, NULL); @@ -2861,6 +3033,9 @@ static int vmw_cmd_intra_surface_copy(struct vmw_private *dev_priv, VMW_DECLARE_CMD_VAR(*cmd, SVGA3dCmdIntraSurfaceCopy) = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (!(dev_priv->capabilities2 & SVGA_CAP2_INTRA_SURFACE_COPY)) return -EINVAL; @@ -2909,6 +3084,9 @@ static int vmw_cmd_clear_uav_uint(struct vmw_private *dev_priv, } *cmd = container_of(header, typeof(*cmd), header); struct vmw_resource *ret; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (!has_sm5_context(dev_priv)) return -EINVAL; @@ -2928,6 +3106,9 @@ static int vmw_cmd_clear_uav_float(struct vmw_private *dev_priv, } *cmd = container_of(header, typeof(*cmd), header); struct vmw_resource *ret; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (!has_sm5_context(dev_priv)) return -EINVAL; @@ -2949,6 +3130,9 @@ static int vmw_cmd_set_uav(struct vmw_private *dev_priv, sizeof(SVGA3dUAViewId); int ret; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (!has_sm5_context(dev_priv)) return -EINVAL; @@ -2981,6 +3165,9 @@ static int vmw_cmd_set_cs_uav(struct vmw_private *dev_priv, sizeof(SVGA3dUAViewId); int ret; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (!has_sm5_context(dev_priv)) return -EINVAL; @@ -3013,6 +3200,9 @@ static int vmw_cmd_dx_define_streamoutput(struct vmw_private *dev_priv, } *cmd = container_of(header, typeof(*cmd), header); int ret; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (!has_sm5_context(dev_priv)) return -EINVAL; @@ -3044,6 +3234,9 @@ static int vmw_cmd_dx_destroy_streamoutput(struct vmw_private *dev_priv, SVGA3dCmdDXDestroyStreamOutput body; } *cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (!ctx_node) { DRM_ERROR("DX Context not set.\n"); return -EINVAL; @@ -3081,6 +3274,9 @@ static int vmw_cmd_dx_bind_streamoutput(struct vmw_private *dev_priv, } *cmd = container_of(header, typeof(*cmd), header); int ret; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (!has_sm5_context(dev_priv)) return -EINVAL; @@ -3123,6 +3319,9 @@ static int vmw_cmd_dx_set_streamoutput(struct vmw_private *dev_priv, } *cmd = container_of(header, typeof(*cmd), header); int ret; + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (!ctx_node) { DRM_ERROR("DX Context not set.\n"); return -EINVAL; @@ -3175,6 +3374,9 @@ static int vmw_cmd_indexed_instanced_indirect(struct vmw_private *dev_priv, SVGA3dCmdDXDrawIndexedInstancedIndirect body; } *cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (!has_sm5_context(dev_priv)) return -EINVAL; @@ -3192,6 +3394,9 @@ static int vmw_cmd_instanced_indirect(struct vmw_private *dev_priv, SVGA3dCmdDXDrawInstancedIndirect body; } *cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (!has_sm5_context(dev_priv)) return -EINVAL; @@ -3209,6 +3414,9 @@ static int vmw_cmd_dispatch_indirect(struct vmw_private *dev_priv, SVGA3dCmdDXDispatchIndirect body; } *cmd = container_of(header, typeof(*cmd), header); + if (!vmw_cmd_body_fits(header, sizeof(cmd->body))) + return -EINVAL; + if (!has_sm5_context(dev_priv)) return -EINVAL; diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_gem.c b/drivers/gpu/drm/vmwgfx/vmwgfx_gem.c index 39f8c46550c27e..2969b74fff17a0 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_gem.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_gem.c @@ -73,10 +73,13 @@ static struct sg_table *vmw_gem_object_get_sg_table(struct drm_gem_object *obj) struct vmw_ttm_tt *vmw_tt = container_of(bo->ttm, struct vmw_ttm_tt, dma_ttm); - if (vmw_tt->vsgt.sgt) - return vmw_tt->vsgt.sgt; - - return drm_prime_pages_to_sg(obj->dev, vmw_tt->dma_ttm.pages, vmw_tt->dma_ttm.num_pages); + /* + * Do not return &vmw_tt->sgt: the core owns what this returns and + * drm_gem_unmap_dma_buf() sg_free_table()s and kfree()s it, but that + * sg_table is embedded in the vmw_ttm_tt allocation. + */ + return drm_prime_pages_to_sg(obj->dev, vmw_tt->dma_ttm.pages, + vmw_tt->dma_ttm.num_pages); } static int vmw_gem_vmap(struct drm_gem_object *obj, struct iosys_map *map) @@ -184,7 +187,7 @@ struct drm_gem_object *vmw_prime_import_sg_table(struct drm_device *dev, { int ret; struct vmw_private *dev_priv = vmw_priv(dev); - struct drm_gem_object *gem = NULL; + struct drm_gem_object *gem; struct vmw_bo *vbo; struct vmw_bo_params params = { .domain = (dev_priv->has_mob) ? VMW_BO_DOMAIN_SYS : VMW_BO_DOMAIN_VRAM, @@ -201,8 +204,10 @@ struct drm_gem_object *vmw_prime_import_sg_table(struct drm_device *dev, dma_resv_lock(params.resv, NULL); ret = vmw_bo_create(dev_priv, ¶ms, &vbo); - if (ret != 0) + if (ret != 0) { + gem = ERR_PTR(ret); goto out_no_bo; + } vbo->tbo.base.funcs = &vmw_gem_object_funcs; diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_gmrid_manager.c b/drivers/gpu/drm/vmwgfx/vmwgfx_gmrid_manager.c index d607452dff6a8e..cc580ce5779782 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_gmrid_manager.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_gmrid_manager.c @@ -54,8 +54,11 @@ static int vmw_gmrid_man_get_node(struct ttm_resource_manager *man, const struct ttm_place *place, struct ttm_resource **res) { + struct vmw_private *vmw = vmw_priv_from_ttm(bo->bdev); struct vmwgfx_gmrid_man *gman = to_gmrid_manager(man); - int id; + u32 max_gmr_pages = 0; + bool mob_overflow = false; + int id, ret = 0; *res = kmalloc_obj(**res); if (!*res) @@ -85,43 +88,53 @@ static int vmw_gmrid_man_get_node(struct ttm_resource_manager *man, const unsigned long max_graphics_pages = totalram_pages() / 2; uint32_t new_max_pages = 0; - DRM_WARN("vmwgfx: mob memory overflow. Consider increasing guest RAM and graphicsMemory.\n"); - vmw_host_printf("vmwgfx, warning: mob memory overflow. Consider increasing guest RAM and graphicsMemory.\n"); + mob_overflow = true; + drm_warn(&vmw->drm, + "vmwgfx: mob memory overflow. Consider increasing guest RAM and graphicsMemory.\n"); if (gman->max_gmr_pages > (max_graphics_pages / 2)) { - DRM_WARN("vmwgfx: guest requires more than half of RAM for graphics.\n"); + drm_warn(&vmw->drm, + "vmwgfx: guest requires more than half of RAM for graphics.\n"); new_max_pages = max_graphics_pages; } else new_max_pages = gman->max_gmr_pages * 2; if (new_max_pages > gman->max_gmr_pages && new_max_pages >= gman->used_gmr_pages) { - DRM_WARN("vmwgfx: increasing guest mob limits to %u KiB.\n", - ((new_max_pages) << (PAGE_SHIFT - 10))); + drm_warn(&vmw->drm, + "vmwgfx: increasing guest mob limits to %u KiB.\n", + new_max_pages << (PAGE_SHIFT - 10)); gman->max_gmr_pages = new_max_pages; } else { - char buf[256]; - snprintf(buf, sizeof(buf), - "vmwgfx, error: guest graphics is out of memory (mob limit at: %u KiB).\n", - ((gman->max_gmr_pages) << (PAGE_SHIFT - 10))); - vmw_host_printf(buf); - DRM_WARN("%s", buf); - goto nospace; + max_gmr_pages = gman->max_gmr_pages; + gman->used_gmr_pages -= PFN_UP((*res)->size); + ret = -ENOSPC; + goto out_unlock; } } } (*res)->start = id; +out_unlock: spin_unlock(&gman->lock); - return 0; -nospace: - gman->used_gmr_pages -= PFN_UP((*res)->size); - spin_unlock(&gman->lock); - ida_free(&gman->gmr_ida, id); - ttm_resource_fini(man, *res); - kfree(*res); - return -ENOSPC; + /* Host logging allocates with GFP_KERNEL and must run unlocked. */ + if (mob_overflow) + vmw_host_printf("%s", + "vmwgfx, warning: mob memory overflow. Consider increasing guest RAM and graphicsMemory.\n"); + if (ret) { + char buf[256]; + + snprintf(buf, sizeof(buf), + "vmwgfx, error: guest graphics is out of memory (mob limit at: %u KiB).\n", + max_gmr_pages << (PAGE_SHIFT - 10)); + vmw_host_printf("%s", buf); + drm_warn(&vmw->drm, "%s", buf); + ida_free(&gman->gmr_ida, id); + ttm_resource_fini(man, *res); + kfree(*res); + } + return ret; } static void vmw_gmrid_man_put_node(struct ttm_resource_manager *man, diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_kms.c b/drivers/gpu/drm/vmwgfx/vmwgfx_kms.c index a6c3304e1a67d8..fed844ccd7893f 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_kms.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_kms.c @@ -155,9 +155,8 @@ int vmw_du_crtc_atomic_check(struct drm_crtc *crtc, * some actual rendering so give a clue as why it's blank. */ if (new_state->enable && !has_primary) - drm_dbg_driver(&vmw->drm, - "CRTC without a primary plane will be blank.\n"); - + drm_info_once(&vmw->drm, + "CRTC without a primary plane will be blank.\n"); if (new_state->connector_mask != connector_mask && new_state->connector_mask != 0) { @@ -275,6 +274,7 @@ vmw_du_plane_duplicate_state(struct drm_plane *plane) vps->cpp = 0; vps->cursor.mob = NULL; + memset(&vps->cursor.map, 0, sizeof(vps->cursor.map)); /* Each ref counted resource needs to be acquired again */ vmw_user_object_ref(&vps->uo); diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_ldu.c b/drivers/gpu/drm/vmwgfx/vmwgfx_ldu.c index b147f5db9df549..a7828b8ed68ee0 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_ldu.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_ldu.c @@ -33,7 +33,7 @@ #include #include #include - +#include #define vmw_crtc_to_ldu(x) \ container_of(x, struct vmw_legacy_display_unit, base.crtc) @@ -256,6 +256,7 @@ static const struct drm_crtc_funcs vmw_legacy_crtc_funcs = { .page_flip = drm_atomic_helper_page_flip, .enable_vblank = vmw_vkms_enable_vblank, .disable_vblank = vmw_vkms_disable_vblank, + .sync_vblank = drm_crtc_vblank_helper_sync_vblank_timer, .get_vblank_timestamp = vmw_vkms_get_vblank_timestamp, }; diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_msg.c b/drivers/gpu/drm/vmwgfx/vmwgfx_msg.c index fd77ab6568cbbc..58da332486bd2c 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_msg.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_msg.c @@ -431,7 +431,7 @@ int vmw_host_get_guestinfo(const char *guest_info_param, /* Remove reply code, which are the first 2 characters of * the reply */ - reply_len = max(reply_len - 2, (size_t) 0); + reply_len = reply_len > 2 ? reply_len - 2 : 0; reply_len = min(reply_len, *length); if (reply_len > 0) @@ -939,9 +939,12 @@ int vmw_mksstat_add_ioctl(struct drm_device *dev, void *data, struct vmw_private *const dev_priv = vmw_priv(dev); - const size_t num_pages_stat = PFN_UP(arg->stat_len); - const size_t num_pages_info = PFN_UP(arg->info_len); - const size_t num_pages_strs = PFN_UP(arg->strs_len); + const u64 max_stat_len = (u64)MKS_GUEST_STAT_INSTANCE_MAX_STAT_PPNS * PAGE_SIZE; + const u64 max_info_len = (u64)MKS_GUEST_STAT_INSTANCE_MAX_INFO_PPNS * PAGE_SIZE; + const u64 max_strs_len = (u64)MKS_GUEST_STAT_INSTANCE_MAX_STRS_PPNS * PAGE_SIZE; + size_t num_pages_stat; + size_t num_pages_info; + size_t num_pages_strs; long desc_len; long nr_pinned_stat; long nr_pinned_info; @@ -965,11 +968,15 @@ int vmw_mksstat_add_ioctl(struct drm_device *dev, void *data, if (!arg->description) return -EINVAL; - if (num_pages_stat > ARRAY_SIZE(pdesc->statPPNs) || - num_pages_info > ARRAY_SIZE(pdesc->infoPPNs) || - num_pages_strs > ARRAY_SIZE(pdesc->strsPPNs)) + if (arg->stat_len > max_stat_len || + arg->info_len > max_info_len || + arg->strs_len > max_strs_len) return -EINVAL; + num_pages_stat = PFN_UP(arg->stat_len); + num_pages_info = PFN_UP(arg->info_len); + num_pages_strs = PFN_UP(arg->strs_len); + /* Find an available slot in the mksGuestStats user array and reserve it */ for (slot = 0; slot < ARRAY_SIZE(dev_priv->mksstat_user_pids); ++slot) if (!atomic_cmpxchg(&dev_priv->mksstat_user_pids[slot], 0, MKSSTAT_PID_RESERVED)) diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_resource.c b/drivers/gpu/drm/vmwgfx/vmwgfx_resource.c index e3a187a2c7a1cc..ad13688bd7da7a 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_resource.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_resource.c @@ -138,6 +138,7 @@ static void vmw_resource_release(struct kref *kref) } res->guest_memory_dirty = false; vmw_resource_mob_detach(res); + vmw_bo_del_detached_resource(res->guest_memory_bo, res); if (res->dirty) res->func->dirty_free(res); if (res->coherent) diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_scrn.c b/drivers/gpu/drm/vmwgfx/vmwgfx_scrn.c index 89714d5c235b6d..bc6c200f51293a 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_scrn.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_scrn.c @@ -35,6 +35,7 @@ #include #include #include +#include #define vmw_crtc_to_sou(x) \ container_of(x, struct vmw_screen_object_unit, base.crtc) @@ -312,6 +313,7 @@ static const struct drm_crtc_funcs vmw_screen_object_crtc_funcs = { .page_flip = drm_atomic_helper_page_flip, .enable_vblank = vmw_vkms_enable_vblank, .disable_vblank = vmw_vkms_disable_vblank, + .sync_vblank = drm_crtc_vblank_helper_sync_vblank_timer, .get_vblank_timestamp = vmw_vkms_get_vblank_timestamp, }; diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_shader.c b/drivers/gpu/drm/vmwgfx/vmwgfx_shader.c index 39811cf19db154..033157efb1fc0a 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_shader.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_shader.c @@ -597,7 +597,7 @@ int vmw_dx_shader_add(struct vmw_cmdbuf_res_manager *man, if (!vmw_shader_id_ok(user_key, shader_type)) return -EINVAL; - shader = kmalloc_obj(*shader); + shader = kzalloc_obj(*shader); if (!shader) { return -ENOMEM; } diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_stdu.c b/drivers/gpu/drm/vmwgfx/vmwgfx_stdu.c index cbf55084110adb..08b32babc1cda2 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_stdu.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_stdu.c @@ -37,6 +37,7 @@ #include #include #include +#include #define vmw_crtc_to_stdu(x) \ container_of(x, struct vmw_screen_target_display_unit, base.crtc) @@ -44,6 +45,8 @@ container_of(x, struct vmw_screen_target_display_unit, base.encoder) #define vmw_connector_to_stdu(x) \ container_of(x, struct vmw_screen_target_display_unit, base.connector) +#define vmw_primary_to_stdu(x) \ + container_of(x, struct vmw_screen_target_display_unit, base.primary) /* * Some renderers such as llvmpipe will align the width and height of their @@ -448,6 +451,13 @@ static void vmw_stdu_crtc_atomic_disable(struct drm_crtc *crtc, !new_crtc_state->mode_changed) return; + /* Never destroy DU 0's ST so that the VM client always has a + * window to accept input from. Otherwise we may never receive + * input to wake the VM when the CRTC is disabled during idle. + */ + if (stdu->base.unit == 0) + return; + ret = vmw_stdu_destroy_st(dev_priv, stdu); if (ret) DRM_ERROR("Failed to destroy Screen Target\n"); @@ -785,6 +795,7 @@ static const struct drm_crtc_funcs vmw_stdu_crtc_funcs = { .page_flip = drm_atomic_helper_page_flip, .enable_vblank = vmw_vkms_enable_vblank, .disable_vblank = vmw_vkms_disable_vblank, + .sync_vblank = drm_crtc_vblank_helper_sync_vblank_timer, .get_vblank_timestamp = vmw_vkms_get_vblank_timestamp, .get_crc_sources = vmw_vkms_get_crc_sources, .set_crc_source = vmw_vkms_set_crc_source, @@ -1411,7 +1422,8 @@ vmw_stdu_primary_plane_atomic_update(struct drm_plane *plane, int ret; /* If case of device error, maintain consistent atomic state */ - if (crtc && new_state->fb) { + if (crtc && new_state->fb && + drm_atomic_get_new_crtc_state(state, crtc)->active) { struct vmw_framebuffer *vfb = vmw_framebuffer_to_vfb(new_state->fb); stdu = vmw_crtc_to_stdu(crtc); @@ -1435,9 +1447,8 @@ vmw_stdu_primary_plane_atomic_update(struct drm_plane *plane, if (ret) DRM_ERROR("Failed to update STDU.\n"); } else { - crtc = old_state->crtc; - stdu = vmw_crtc_to_stdu(crtc); - dev_priv = vmw_priv(crtc->dev); + stdu = vmw_primary_to_stdu(plane); + dev_priv = vmw_priv(plane->dev); /* Blank STDU when fb and crtc are NULL */ if (!stdu->defined) diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_streamoutput.c b/drivers/gpu/drm/vmwgfx/vmwgfx_streamoutput.c index 52c6cfa163dacb..34d5b71fa42fe4 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_streamoutput.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_streamoutput.c @@ -284,7 +284,7 @@ int vmw_dx_streamoutput_add(struct vmw_cmdbuf_res_manager *man, struct vmw_private *dev_priv = ctx->dev_priv; int ret; - so = kmalloc_obj(*so); + so = kzalloc_obj(*so); if (!so) { return -ENOMEM; } diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_surface.c b/drivers/gpu/drm/vmwgfx/vmwgfx_surface.c index bd0563741e89d9..3064a2a960e1f8 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_surface.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_surface.c @@ -1718,22 +1718,32 @@ vmw_gb_surface_reference_internal(struct drm_device *dev, user_srf = container_of(base, struct vmw_user_surface, prime.base); srf = &user_srf->srf; + metadata = &srf->metadata; + + mutex_lock(&dev_priv->cmdbuf_mutex); + if (!srf->res.guest_memory_bo) { + mutex_unlock(&dev_priv->cmdbuf_mutex); DRM_ERROR("Shared GB surface is missing a backup buffer.\n"); + ret = -EINVAL; goto out_bad_resource; } - metadata = &srf->metadata; - mutex_lock(&dev_priv->cmdbuf_mutex); /* Protect res->backup */ ret = drm_gem_handle_create(file_priv, &srf->res.guest_memory_bo->tbo.base, &backup_handle); - mutex_unlock(&dev_priv->cmdbuf_mutex); if (ret != 0) { + mutex_unlock(&dev_priv->cmdbuf_mutex); drm_err(dev, "Wasn't able to create a backing handle for surface sid = %u.\n", req->sid); goto out_bad_resource; } + rep->crep.buffer_map_handle = + drm_vma_node_offset_addr(&srf->res.guest_memory_bo->tbo.base.vma_node); + rep->crep.buffer_size = srf->res.guest_memory_bo->tbo.base.size; + + mutex_unlock(&dev_priv->cmdbuf_mutex); + rep->creq.base.svga3d_flags = SVGA3D_FLAGS_LOWER_32(metadata->flags); rep->creq.base.format = metadata->format; rep->creq.base.mip_levels = metadata->mip_levels[0]; @@ -1746,9 +1756,6 @@ vmw_gb_surface_reference_internal(struct drm_device *dev, rep->crep.handle = user_srf->prime.base.handle; rep->crep.backup_size = srf->res.guest_memory_size; rep->crep.buffer_handle = backup_handle; - rep->crep.buffer_map_handle = - drm_vma_node_offset_addr(&srf->res.guest_memory_bo->tbo.base.vma_node); - rep->crep.buffer_size = srf->res.guest_memory_bo->tbo.base.size; rep->creq.version = drm_vmw_gb_surface_v1; rep->creq.svga3d_flags_upper_32_bits = @@ -1758,6 +1765,9 @@ vmw_gb_surface_reference_internal(struct drm_device *dev, rep->creq.must_be_zero = 0; out_bad_resource: + if (ret) + ttm_ref_object_base_unref(vmw_fpriv(file_priv)->tfile, + base->handle); ttm_base_object_unref(&base); return ret; diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_validation.h b/drivers/gpu/drm/vmwgfx/vmwgfx_validation.h index 353d837907d84a..fc04555ca50525 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_validation.h +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_validation.h @@ -127,16 +127,23 @@ vmw_validation_bo_reserve(struct vmw_validation_context *ctx, * vmw_validation_bo_fence - Unreserve and fence buffer objects registered * with a validation context * @ctx: The validation context + * @fence: Fence with which to fence all buffer objects taking part in the + * command submission. * * This function unreserves the buffer objects previously reserved using - * vmw_validation_bo_reserve, and fences them with a fence object. + * vmw_validation_bo_reserve, and fences them with a fence object if the + * given fence object is not NULL. */ static inline void vmw_validation_bo_fence(struct vmw_validation_context *ctx, struct vmw_fence_obj *fence) { - ttm_eu_fence_buffer_objects(&ctx->ticket, &ctx->bo_list, - (void *) fence); + /* fence is able to be NULL if vmw_execbuf_fence_commands() fails */ + if (fence) + ttm_eu_fence_buffer_objects(&ctx->ticket, &ctx->bo_list, + (void *)fence); + else + ttm_eu_backoff_reservation(&ctx->ticket, &ctx->bo_list); } /** diff --git a/drivers/gpu/drm/vmwgfx/vmwgfx_vkms.c b/drivers/gpu/drm/vmwgfx/vmwgfx_vkms.c index 3d0d5dfa869f9a..8ce10cf9c19eec 100644 --- a/drivers/gpu/drm/vmwgfx/vmwgfx_vkms.c +++ b/drivers/gpu/drm/vmwgfx/vmwgfx_vkms.c @@ -299,7 +299,7 @@ vmw_vkms_crtc_cleanup(struct drm_crtc *crtc) struct vmw_display_unit *du = vmw_crtc_to_du(crtc); if (vmw->vkms_enabled) - drm_crtc_vblank_cancel_timer(crtc); + drm_crtc_vblank_stop_timer(crtc); if (du->vkms.surface) vmw_surface_unreference(&du->vkms.surface); diff --git a/drivers/gpu/drm/xe/abi/xe_log_abi.h b/drivers/gpu/drm/xe/abi/xe_log_abi.h index 526aadf85fe938..d7bd85ea96736f 100644 --- a/drivers/gpu/drm/xe/abi/xe_log_abi.h +++ b/drivers/gpu/drm/xe/abi/xe_log_abi.h @@ -151,6 +151,9 @@ enum xe_log_location_bits { define(DRIVER_HARDWARE, 3, GT, GT_TDR, "Graphics Technology") \ define(DRIVER_HARDWARE, 4, LMTT, IO_BUS, "LMEM Translation Table") \ define(DRIVER_HARDWARE, 5, MEMIRQ, IO_BUS, "Memory Based IRQ") \ + define(DRIVER_HARDWARE, 6, VRAM, IO_BUS, "Video Memory/Local Memory") \ + define(DRIVER_HARDWARE, 7, PAT, IO_BUS, "Page Attribute Table") \ + define(DRIVER_HARDWARE, 8, HWMON, IO_BUS, "Hardware Monitoring") \ /* */ \ define(DRIVER_FEATURE, 1, PF, SW, "SR-IOV Physical Function") \ define(DRIVER_FEATURE, 2, VF, SW, "SR-IOV Virtual Function") \ diff --git a/drivers/gpu/drm/xe/xe_device.c b/drivers/gpu/drm/xe/xe_device.c index c41533644c928a..570bc944d78873 100644 --- a/drivers/gpu/drm/xe/xe_device.c +++ b/drivers/gpu/drm/xe/xe_device.c @@ -1091,7 +1091,7 @@ int xe_device_probe(struct xe_device *xe) err = xe_i2c_probe(xe); if (err) - goto err_unregister_display; + goto err_unregister_hwmon; for_each_gt(gt, xe, id) xe_gt_sanitize_freq(gt); @@ -1100,7 +1100,7 @@ int xe_device_probe(struct xe_device *xe) err = xe_sriov_init_late(xe); if (err) - goto err_unregister_display; + goto err_unregister_hwmon; detect_preproduction_hw(xe); @@ -1113,10 +1113,12 @@ int xe_device_probe(struct xe_device *xe) err = devm_add_action_or_reset(xe->drm.dev, xe_device_sanitize, xe); if (err) - goto err_unregister_display; + goto err_unregister_hwmon; return 0; +err_unregister_hwmon: + xe_hwmon_unregister(xe); err_unregister_display: xe_display_unregister(xe); drm_dev_unregister(&xe->drm); @@ -1126,6 +1128,7 @@ int xe_device_probe(struct xe_device *xe) void xe_device_remove(struct xe_device *xe) { + xe_hwmon_unregister(xe); xe_display_unregister(xe); drm_dev_unplug(&xe->drm); diff --git a/drivers/gpu/drm/xe/xe_dma_buf.c b/drivers/gpu/drm/xe/xe_dma_buf.c index 6a85b292dee7b8..97299ca8f83165 100644 --- a/drivers/gpu/drm/xe/xe_dma_buf.c +++ b/drivers/gpu/drm/xe/xe_dma_buf.c @@ -242,60 +242,62 @@ static const struct dma_buf_ops xe_dmabuf_ops = { struct dma_buf *xe_gem_prime_export(struct drm_gem_object *obj, int flags) { struct xe_bo *bo = gem_to_xe_bo(obj); + struct xe_validation_ctx ctx; + struct drm_exec exec; struct dma_buf *buf; - struct ttm_operation_ctx ctx = { - .interruptible = true, - .no_wait_gpu = true, - /* We opt to avoid OOM on system pages allocations */ - .gfp_retry_mayfail = true, - .allow_res_evict = false, - }; - int ret; + int ret = 0; if (bo->vm) return ERR_PTR(-EPERM); - /* - * Reject exporting purgeable BOs. DONTNEED BOs can be purged - * at any time, making the exported dma-buf unusable. Purged BOs - * have no backing store and are permanently invalid. - */ - ret = xe_bo_lock(bo, true); - if (ret) - return ERR_PTR(ret); + xe_validation_guard(&ctx, &xe_bo_device(bo)->val, &exec, + (struct xe_val_flags) {.interruptible = true}, ret) { + ret = drm_exec_lock_obj(&exec, &bo->ttm.base); + drm_exec_retry_on_contention(&exec); + if (ret) + break; - if (xe_bo_madv_is_dontneed(bo)) { - ret = -EBUSY; - goto out_unlock; - } + /* + * Reject exporting purgeable BOs. DONTNEED BOs can be purged + * at any time, making the exported dma-buf unusable. Purged BOs + * have no backing store and are permanently invalid. + */ + if (xe_bo_madv_is_dontneed(bo)) { + ret = -EBUSY; + break; + } - if (xe_bo_is_purged(bo)) { - ret = -EINVAL; - goto out_unlock; - } + if (xe_bo_is_purged(bo)) { + ret = -EINVAL; + break; + } - xe_bo_willneed_get_locked(bo); - xe_bo_unlock(bo); + /* + * Make sure the BO is backed in its preferred placement so that + * the exporter, rather than the importer, is charged for the + * memory allocation. + */ + ret = xe_bo_validate(bo, NULL, false, &exec); + drm_exec_retry_on_contention(&exec); + xe_validation_retry_on_oom(&ctx, &ret); + if (ret) + break; - ret = ttm_bo_setup_export(&bo->ttm, &ctx); + xe_bo_willneed_get_locked(bo); + } if (ret) - goto out_put; + return ERR_PTR(ret); buf = drm_gem_prime_export(obj, flags); if (IS_ERR(buf)) { - ret = PTR_ERR(buf); - goto out_put; + xe_bo_lock(bo, false); + xe_bo_willneed_put_locked(bo); + xe_bo_unlock(bo); + return buf; } buf->ops = &xe_dmabuf_ops; return buf; - -out_put: - xe_bo_lock(bo, false); - xe_bo_willneed_put_locked(bo); -out_unlock: - xe_bo_unlock(bo); - return ERR_PTR(ret); } static struct drm_gem_object * diff --git a/drivers/gpu/drm/xe/xe_guc_submit.c b/drivers/gpu/drm/xe/xe_guc_submit.c index 01f79f8883ba68..dd970e6b1b9dcb 100644 --- a/drivers/gpu/drm/xe/xe_guc_submit.c +++ b/drivers/gpu/drm/xe/xe_guc_submit.c @@ -47,6 +47,7 @@ #include "xe_ring_ops_types.h" #include "xe_sched_job.h" #include "xe_sleep.h" +#include "xe_tlb_inval.h" #include "xe_trace.h" #include "xe_uc_fw.h" #include "xe_vm.h" @@ -264,6 +265,7 @@ static void guc_submit_fini(void *arg) /* Forcefully kill any remaining exec queues */ xe_guc_ct_stop(&guc->ct); + xe_tlb_inval_reset(&guc_to_gt(guc)->tlb_inval); guc_submit_reset_prepare(guc); xe_guc_softreset(guc); xe_guc_submit_stop(guc); diff --git a/drivers/gpu/drm/xe/xe_guc_tlb_inval.c b/drivers/gpu/drm/xe/xe_guc_tlb_inval.c index 111fef781b2abb..0945d9711e1734 100644 --- a/drivers/gpu/drm/xe/xe_guc_tlb_inval.c +++ b/drivers/gpu/drm/xe/xe_guc_tlb_inval.c @@ -31,12 +31,22 @@ static int send_tlb_inval(struct xe_guc *guc, const u32 *action, int len) { struct xe_gt *gt = guc_to_gt(guc); + int ret; xe_gt_assert(gt, action[1]); /* Seqno */ xe_gt_stats_incr(gt, XE_GT_STATS_ID_TLB_INVAL, 1); - return xe_guc_ct_send(&guc->ct, action, len, - G2H_LEN_DW_TLB_INVALIDATE, 1); + ret = xe_guc_ct_send(&guc->ct, action, len, G2H_LEN_DW_TLB_INVALIDATE, 1); + + /* + * A disabled CT can't deliver the request, and the GuC is reloaded + * with all TLBs invalid before the CT is enabled again, so there is + * nothing left to invalidate. Report it as cancelled, like a stopped CT. + */ + if (ret == -ENODEV) + return -ECANCELED; + + return ret; } #define MAKE_INVAL_OP_FLUSH(type, flush_cache) ((type << XE_GUC_TLB_INVAL_TYPE_SHIFT) | \ diff --git a/drivers/gpu/drm/xe/xe_hwmon.c b/drivers/gpu/drm/xe/xe_hwmon.c index 20c1cfffc5a03c..d81b90c9cb99a5 100644 --- a/drivers/gpu/drm/xe/xe_hwmon.c +++ b/drivers/gpu/drm/xe/xe_hwmon.c @@ -15,6 +15,7 @@ #include "regs/xe_pcode_regs.h" #include "xe_device.h" #include "xe_hwmon.h" +#include "xe_log.h" #include "xe_mmio.h" #include "xe_pcode.h" #include "xe_pcode_api.h" @@ -375,17 +376,20 @@ static struct xe_reg xe_hwmon_get_reg(struct xe_hwmon *hwmon, enum xe_hwmon_reg * same pattern for sysfs, allow arbitrary PL1 limits to be set but display * clamped values when read. */ -static void xe_hwmon_power_max_read(struct xe_hwmon *hwmon, u32 attr, int channel, long *value) +static int xe_hwmon_power_max_read(struct xe_hwmon *hwmon, u32 attr, int channel, long *value) { u32 reg_val = 0; struct xe_device *xe = hwmon->xe; struct xe_reg rapl_limit, pkg_power_sku; struct xe_mmio *mmio = xe_root_tile_mmio(xe); + int ret = 0; mutex_lock(&hwmon->hwmon_lock); if (hwmon->xe->info.has_mbx_power_limits) { - xe_hwmon_pcode_read_power_limit(hwmon, attr, channel, ®_val); + ret = xe_hwmon_pcode_read_power_limit(hwmon, attr, channel, ®_val); + if (ret) + goto unlock; } else { rapl_limit = xe_hwmon_get_reg(hwmon, REG_PKG_RAPL_LIMIT, channel); pkg_power_sku = xe_hwmon_get_reg(hwmon, REG_PKG_POWER_SKU, channel); @@ -417,6 +421,7 @@ static void xe_hwmon_power_max_read(struct xe_hwmon *hwmon, u32 attr, int channe } unlock: mutex_unlock(&hwmon->hwmon_lock); + return ret; } static int xe_hwmon_power_max_write(struct xe_hwmon *hwmon, u32 attr, int channel, long value) @@ -439,7 +444,9 @@ static int xe_hwmon_power_max_write(struct xe_hwmon *hwmon, u32 attr, int channe ret = xe_hwmon_pcode_rmw_power_limit(hwmon, attr, channel, PWR_LIM_EN, 0); if (ret) goto unlock; - xe_hwmon_pcode_read_power_limit(hwmon, attr, channel, ®_val); + ret = xe_hwmon_pcode_read_power_limit(hwmon, attr, channel, ®_val); + if (ret) + goto unlock; } else { reg_val = xe_mmio_rmw32(mmio, rapl_limit, PWR_LIM_EN, 0); reg_val = xe_mmio_read32(mmio, rapl_limit); @@ -496,15 +503,18 @@ static int xe_hwmon_power_max_write(struct xe_hwmon *hwmon, u32 attr, int channe return ret; } -static void xe_hwmon_power_rated_max_read(struct xe_hwmon *hwmon, u32 attr, int channel, - long *value) +static int xe_hwmon_power_rated_max_read(struct xe_hwmon *hwmon, u32 attr, int channel, + long *value) { struct xe_mmio *mmio = xe_root_tile_mmio(hwmon->xe); u32 reg_val; + int ret = 0; if (hwmon->xe->info.has_mbx_power_limits) { /* PL1 is rated max if supported. */ - xe_hwmon_pcode_read_power_limit(hwmon, PL1_HWMON_ATTR, channel, ®_val); + ret = xe_hwmon_pcode_read_power_limit(hwmon, PL1_HWMON_ATTR, channel, ®_val); + if (ret) + return ret; } else { /* * This sysfs file won't be visible if REG_PKG_POWER_SKU is invalid, so valid check @@ -518,6 +528,7 @@ static void xe_hwmon_power_rated_max_read(struct xe_hwmon *hwmon, u32 attr, int reg_val = REG_FIELD_GET(PKG_TDP, reg_val); *value = mul_u64_u32_shr(reg_val, SF_POWER, hwmon->scl_shift_power); + return ret; } /* @@ -540,7 +551,7 @@ static void xe_hwmon_power_rated_max_read(struct xe_hwmon *hwmon, u32 attr, int * hwmon->scl_shift_energy of 14 bits we have 57 (63 - 20 + 14) bits before * energyN_input overflows. This at 1000 W is an overflow duration of 278 years. */ -static void +static int xe_hwmon_energy_get(struct xe_hwmon *hwmon, int channel, long *energy) { struct xe_mmio *mmio = xe_root_tile_mmio(hwmon->xe); @@ -551,7 +562,7 @@ xe_hwmon_energy_get(struct xe_hwmon *hwmon, int channel, long *energy) /* Energy is supported only for card and pkg */ if (channel > CHANNEL_PKG) { *energy = 0; - return; + return 0; } if (hwmon->xe->info.platform == XE_BATTLEMAGE) { @@ -563,7 +574,7 @@ xe_hwmon_energy_get(struct xe_hwmon *hwmon, int channel, long *energy) if (ret != sizeof(pmt_val)) { drm_warn(&hwmon->xe->drm, "energy read from pmt failed, ret %d\n", ret); *energy = 0; - return; + return ret < 0 ? ret : -EIO; } if (channel == CHANNEL_PKG) @@ -580,6 +591,7 @@ xe_hwmon_energy_get(struct xe_hwmon *hwmon, int channel, long *energy) *energy = mul_u64_u32_shr(ei->accum_energy, SF_ENERGY, hwmon->scl_shift_energy); + return 0; } static ssize_t @@ -602,10 +614,11 @@ xe_hwmon_power_max_interval_show(struct device *dev, struct device_attribute *at if (hwmon->xe->info.has_mbx_power_limits) { ret = xe_hwmon_pcode_read_power_limit(hwmon, power_attr, channel, ®_val); if (ret) { - drm_err(&hwmon->xe->drm, - "power interval read fail, ch %d, attr %d, val 0x%08x, ret %d\n", - channel, power_attr, reg_val, ret); - reg_val = 0; + xe_log_err(hwmon->xe, HWMON, ret, + "Power interval read fail, ch %d, attr %d, val 0x%08x\n", + channel, power_attr, reg_val); + mutex_unlock(&hwmon->hwmon_lock); + return ret; } } else { reg_val = xe_mmio_read32(mmio, xe_hwmon_get_reg(hwmon, REG_PKG_RAPL_LIMIT, @@ -1229,7 +1242,8 @@ xe_hwmon_power_is_visible(struct xe_hwmon *hwmon, u32 attr, int channel) } case hwmon_power_crit: if (channel == CHANNEL_CARD) { - xe_hwmon_pcode_read_i1(hwmon, &uval); + if (xe_hwmon_pcode_read_i1(hwmon, &uval)) + return 0; return (uval & POWER_SETUP_I1_WATTS) ? 0644 : 0; } break; @@ -1248,7 +1262,8 @@ xe_hwmon_power_is_visible(struct xe_hwmon *hwmon, u32 attr, int channel) } } if ((!(uval & PWR_LIM_EN)) && channel == CHANNEL_CARD) { - xe_hwmon_pcode_read_i1(hwmon, &uval); + if (xe_hwmon_pcode_read_i1(hwmon, &uval)) + return 0; return (uval & POWER_SETUP_I1_WATTS) ? 0444 : 0; } return (uval) ? 0444 : 0; @@ -1264,11 +1279,9 @@ xe_hwmon_power_read(struct xe_hwmon *hwmon, u32 attr, int channel, long *val) switch (attr) { case hwmon_power_max: case hwmon_power_cap: - xe_hwmon_power_max_read(hwmon, attr, channel, val); - return 0; + return xe_hwmon_power_max_read(hwmon, attr, channel, val); case hwmon_power_rated_max: - xe_hwmon_power_rated_max_read(hwmon, attr, channel, val); - return 0; + return xe_hwmon_power_rated_max_read(hwmon, attr, channel, val); case hwmon_power_crit: return xe_hwmon_power_curr_crit_read(hwmon, channel, val, SF_POWER); default: @@ -1385,8 +1398,7 @@ xe_hwmon_energy_read(struct xe_hwmon *hwmon, u32 attr, int channel, long *val) { switch (attr) { case hwmon_energy_input: - xe_hwmon_energy_get(hwmon, channel, val); - return 0; + return xe_hwmon_energy_get(hwmon, channel, val); default: return -EOPNOTSUPP; } @@ -1649,7 +1661,7 @@ int xe_hwmon_register(struct xe_device *xe) { struct device *dev = xe->drm.dev; struct xe_hwmon *hwmon; - int ret; + int ret, err; /* hwmon is available only for dGfx */ if (!IS_DGFX(xe)) @@ -1676,15 +1688,33 @@ int xe_hwmon_register(struct xe_device *xe) drm_dbg(&xe->drm, "Register xe hwmon interface\n"); /* hwmon_dev points to device hwmon */ - hwmon->hwmon_dev = devm_hwmon_device_register_with_info(dev, "xe", hwmon, - &hwmon_chip_info, - hwmon_groups); + hwmon->hwmon_dev = hwmon_device_register_with_info(dev, "xe", hwmon, + &hwmon_chip_info, + hwmon_groups); if (IS_ERR(hwmon->hwmon_dev)) { - drm_err(&xe->drm, "Failed to register xe hwmon (%pe)\n", hwmon->hwmon_dev); + err = PTR_ERR(hwmon->hwmon_dev); + xe_log_err(xe, HWMON, err, + "Failed to register xe hwmon\n"); xe->hwmon = NULL; - return PTR_ERR(hwmon->hwmon_dev); + return err; } return 0; } + +/** + * xe_hwmon_unregister - Remove the hwmon interface + * @xe: xe device + * + * Called before the device is unplugged, so that no hwmon attribute can + * be accessed afterwards. + */ +void xe_hwmon_unregister(struct xe_device *xe) +{ + if (!xe->hwmon) + return; + + hwmon_device_unregister(xe->hwmon->hwmon_dev); + xe->hwmon = NULL; +} MODULE_IMPORT_NS("INTEL_PMT_TELEMETRY"); diff --git a/drivers/gpu/drm/xe/xe_hwmon.h b/drivers/gpu/drm/xe/xe_hwmon.h index d02c1bfe8c0a05..e67e0134f02a50 100644 --- a/drivers/gpu/drm/xe/xe_hwmon.h +++ b/drivers/gpu/drm/xe/xe_hwmon.h @@ -12,8 +12,10 @@ struct xe_device; #if IS_REACHABLE(CONFIG_HWMON) int xe_hwmon_register(struct xe_device *xe); +void xe_hwmon_unregister(struct xe_device *xe); #else static inline int xe_hwmon_register(struct xe_device *xe) { return 0; }; +static inline void xe_hwmon_unregister(struct xe_device *xe) { } #endif #endif /* _XE_HWMON_H_ */ diff --git a/drivers/gpu/drm/xe/xe_irq.c b/drivers/gpu/drm/xe/xe_irq.c index b394c8edf89c91..f3964c6eca17c9 100644 --- a/drivers/gpu/drm/xe/xe_irq.c +++ b/drivers/gpu/drm/xe/xe_irq.c @@ -786,10 +786,8 @@ static void irq_uninstall(void *arg) { struct xe_device *xe = arg; - if (!atomic_xchg(&xe->irq.enabled, 0)) - return; - - xe_irq_reset(xe); + if (atomic_xchg(&xe->irq.enabled, 0)) + xe_irq_reset(xe); if (xe_device_has_msix(xe)) xe_irq_msix_free(xe); diff --git a/drivers/gpu/drm/xe/xe_migrate.c b/drivers/gpu/drm/xe/xe_migrate.c index fffb3eb6c76ebe..786bff07b93701 100644 --- a/drivers/gpu/drm/xe/xe_migrate.c +++ b/drivers/gpu/drm/xe/xe_migrate.c @@ -187,6 +187,18 @@ * The PM reference is then dropped. If the queue was not idle, the worker * simply re-arms itself. * + * The worker waits for the "last" job to retire before dropping + * @xe_migrate.job_mutex, so a subsequent enter is serialized behind it. A + * "first" job is not chained, so it publishes its own ring tail with + * xe_lrc_set_ring_tail(), which updates the saved tail in the context image + * only. That is enough for a context which is off the hardware, since a + * context restore loads RING_TAIL from there, but the context is only off the + * hardware once the "last" job has retired. Submitted before then, the write + * races the postamble of the job preceding the "last" one, which puts that + * same saved tail - and RING_TAIL - at the end of the "last" job. The + * postamble landing second rewinds the tail behind the "first" job, which the + * command streamer then never executes. + * * Job state * --------- * @@ -761,6 +773,9 @@ static void xe_migrate_ulls_exit(struct work_struct *work) scoped_guard(mutex, &m->job_mutex) { if (xe_exec_queue_is_idle(m->q, 1)) { fence = __xe_migrate_job_push(m, job, ULLS_EXIT); + + /* Keep enter out until the context is off the HW */ + dma_fence_wait(fence, false); dma_fence_put(fence); xe_pm_runtime_put(xe); /* Pairs with PM get in enter */ diff --git a/drivers/gpu/drm/xe/xe_query.c b/drivers/gpu/drm/xe/xe_query.c index dc975f5953683a..9cc35fc83954ff 100644 --- a/drivers/gpu/drm/xe/xe_query.c +++ b/drivers/gpu/drm/xe/xe_query.c @@ -6,7 +6,6 @@ #include "xe_query.h" #include -#include #include #include @@ -97,13 +96,14 @@ hwe_read_timestamp(struct xe_hw_engine *hwe, u64 *engine_ts, u64 *cpu_ts, u32 upper, lower, old_upper, loop = 0; struct xe_reg upper_reg = RING_TIMESTAMP_UDW(hwe->mmio_base), lower_reg = RING_TIMESTAMP(hwe->mmio_base); + u64 delta_start; upper = xe_mmio_read32(mmio, upper_reg); do { - *cpu_delta = local_clock(); + delta_start = ktime_get_raw_ns(); *cpu_ts = cpu_clock(); lower = xe_mmio_read32(mmio, lower_reg); - *cpu_delta = local_clock() - *cpu_delta; + *cpu_delta = ktime_get_raw_ns() - delta_start; old_upper = upper; upper = xe_mmio_read32(mmio, upper_reg); } while (upper != old_upper && loop++ < 2); diff --git a/drivers/gpu/drm/xe/xe_ras.c b/drivers/gpu/drm/xe/xe_ras.c index fe16a41060607c..53cfbb9a3bac51 100644 --- a/drivers/gpu/drm/xe/xe_ras.c +++ b/drivers/gpu/drm/xe/xe_ras.c @@ -496,7 +496,7 @@ enum xe_ras_recovery_action xe_ras_process_errors(struct xe_device *xe) } if (!xe->info.has_sysctrl) - return XE_RAS_RECOVERY_ACTION_RESET; + return XE_RAS_RECOVERY_ACTION_RECOVERED; BUILD_BUG_ON(BITS_PER_TYPE(sent) < XE_RAS_COMP_MAX); /* Default action */ diff --git a/drivers/hid/hid-apple.c b/drivers/hid/hid-apple.c index 82d085f63030eb..a1e4372d904df0 100644 --- a/drivers/hid/hid-apple.c +++ b/drivers/hid/hid-apple.c @@ -357,6 +357,7 @@ static const struct apple_key_translation swapped_fn_leftctrl_keys[] = { }; static const struct apple_non_apple_keyboard non_apple_keyboards[] = { + { "F108Pro Dongle" }, /* AULA F108 Pro 2.4G dongle */ { "SONiX KN85 Keyboard" }, { "SONiX USB DEVICE" }, { "SONiX AK870 PRO" }, diff --git a/drivers/hid/hid-asus.c b/drivers/hid/hid-asus.c index d7b044b3a831c6..4f5749c9b2dbba 100644 --- a/drivers/hid/hid-asus.c +++ b/drivers/hid/hid-asus.c @@ -584,16 +584,24 @@ static int asus_raw_event(struct hid_device *hdev, static int asus_kbd_set_report(struct hid_device *hdev, const u8 *buf, size_t buf_size) { + int ret; u8 *dmabuf __free(kfree) = kmemdup(buf, buf_size, GFP_KERNEL); if (!dmabuf) return -ENOMEM; + /* The device may be runtime suspended, e.g. for a deferred backlight change */ + ret = hid_hw_power(hdev, PM_HINT_FULLON); + if (ret < 0) + return ret; + /* * The report ID should be set from the incoming buffer due to LED and key * interfaces having different pages */ - return hid_hw_raw_request(hdev, buf[0], dmabuf, buf_size, HID_FEATURE_REPORT, - HID_REQ_SET_REPORT); + ret = hid_hw_raw_request(hdev, buf[0], dmabuf, buf_size, HID_FEATURE_REPORT, + HID_REQ_SET_REPORT); + hid_hw_power(hdev, PM_HINT_NORMAL); + return ret; } static int asus_kbd_init(struct hid_device *hdev, u8 report_id) @@ -1363,6 +1371,8 @@ static int asus_input_mapping(struct hid_device *hdev, case 0xe2: /* Mute */ case 0xe9: /* Volume up */ case 0xea: /* Volume down */ + case 0x6f: /* Display brightness increment */ + case 0x70: /* Display brightness decrement */ return 0; default: /* Ignore dummy Consumer usages which make the diff --git a/drivers/hid/hid-betopff.c b/drivers/hid/hid-betopff.c index f802046a688a72..28ab0acce6ad78 100644 --- a/drivers/hid/hid-betopff.c +++ b/drivers/hid/hid-betopff.c @@ -16,6 +16,9 @@ * * 0x20bc:0x5500 "BTP2185 V2 BFM mode Joystick" * - tested with BTP2171s. + * + * 0x11c0:0x9105 "SPEEDLINK TORID" + * - tested with Speedlink TORID wireless gamepad. * Copyright (c) 2014 Huang Bo */ @@ -137,6 +140,7 @@ static int betop_probe(struct hid_device *hdev, const struct hid_device_id *id) static const struct hid_device_id betop_devices[] = { { HID_USB_DEVICE(USB_VENDOR_ID_BETOP_2185BFM, 0x2208) }, { HID_USB_DEVICE(USB_VENDOR_ID_BETOP_2185PC, 0x5506) }, + { HID_USB_DEVICE(USB_VENDOR_ID_BETOP_2185PC, 0x9105) }, { HID_USB_DEVICE(USB_VENDOR_ID_BETOP_2185V2PC, 0x1850) }, { HID_USB_DEVICE(USB_VENDOR_ID_BETOP_2185V2BFM, 0x5500) }, { } diff --git a/drivers/hid/hid-core.c b/drivers/hid/hid-core.c index b4fd482d39d2fb..4a47deb9d833fc 100644 --- a/drivers/hid/hid-core.c +++ b/drivers/hid/hid-core.c @@ -2270,6 +2270,8 @@ report_descriptor_read(struct file *filp, struct kobject *kobj, struct device *dev = kobj_to_dev(kobj); struct hid_device *hdev = to_hid_device(dev); + guard(device)(dev); + if (off >= hdev->rsize) return 0; diff --git a/drivers/hid/hid-corsair.c b/drivers/hid/hid-corsair.c index 3e80f22c6cc892..3cb1fe3cb04ea6 100644 --- a/drivers/hid/hid-corsair.c +++ b/drivers/hid/hid-corsair.c @@ -507,8 +507,8 @@ static int k90_init_macro_functions(struct hid_device *dev) fail_sysfs: k90->record_led.removed = true; + disable_work_sync(&k90->record_led.work); led_classdev_unregister(&k90->record_led.cdev); - cancel_work_sync(&k90->record_led.work); fail_record_led: kfree(k90->record_led.cdev.name); fail_record_led_alloc: @@ -524,8 +524,10 @@ static void k90_cleanup_backlight(struct hid_device *dev) if (drvdata->backlight) { drvdata->backlight->removed = true; - cancel_work_sync(&drvdata->backlight->work); + disable_work_sync(&drvdata->backlight->work); led_classdev_unregister(&drvdata->backlight->cdev); + /* unregister turns the LED off, which re-queues the work */ + cancel_work_sync(&drvdata->backlight->work); kfree(drvdata->backlight->cdev.name); kfree(drvdata->backlight); } @@ -540,8 +542,10 @@ static void k90_cleanup_macro_functions(struct hid_device *dev) sysfs_remove_group(&dev->dev.kobj, &k90_attr_group); k90->record_led.removed = true; - cancel_work_sync(&k90->record_led.work); + disable_work_sync(&k90->record_led.work); led_classdev_unregister(&k90->record_led.cdev); + /* unregister turns the LED off, which re-queues the work */ + cancel_work_sync(&k90->record_led.work); kfree(k90->record_led.cdev.name); kfree(k90); diff --git a/drivers/hid/hid-ids.h b/drivers/hid/hid-ids.h index 91319aa6516dae..85902527f3cdeb 100644 --- a/drivers/hid/hid-ids.h +++ b/drivers/hid/hid-ids.h @@ -236,6 +236,7 @@ #define USB_DEVICE_ID_ASUSTEK_FX503VD_KEYBOARD 0x1869 #define USB_DEVICE_ID_ASUSTEK_XGM_2022 0x1970 #define USB_DEVICE_ID_ASUSTEK_XGM_2023 0x1a9a +#define USB_DEVICE_ID_ASUSTEK_MD301_DONGLE 0x1cd3 #define USB_VENDOR_ID_ATEN 0x0557 #define USB_DEVICE_ID_ATEN_UC100KM 0x2004 @@ -470,6 +471,7 @@ #define USB_DEVICE_ID_EDIFIER_QR30 0xa101 /* EDIFIER Hal0 2.0 SE */ #define USB_VENDOR_ID_ELAN 0x04f3 +#define I2C_DEVICE_ID_ELAN_LENOVO_T14S_KEYBOARD 0x000d #define USB_DEVICE_ID_SB974D 0x0400 #define USB_DEVICE_ID_TOSHIBA_CLICK_L9W 0x0401 #define USB_DEVICE_ID_HP_X2 0x074d @@ -802,6 +804,9 @@ #define USB_VENDOR_ID_KENSINGTON 0x047d #define USB_DEVICE_ID_KS_SLIMBLADE 0x2041 +#define USB_VENDOR_ID_KEYCHRON 0x3434 +#define USB_DEVICE_ID_KEYCHRON_LINK 0xd030 + #define USB_VENDOR_ID_KWORLD 0x1b80 #define USB_DEVICE_ID_KWORLD_RADIO_FM700 0xd700 @@ -986,6 +991,7 @@ #define USB_DEVICE_ID_LOGITECH_NANO_RECEIVER_LIGHTSPEED_1_3 0xc547 #define USB_DEVICE_ID_LOGITECH_NANO_RECEIVER_LIGHTSPEED_1_4 0xc54d #define USB_DEVICE_ID_LOGITECH_NANO_RECEIVER_LIGHTSPEED_1_5 0xc545 +#define USB_DEVICE_ID_LOGITECH_NANO_RECEIVER_LIGHTSPEED_1_6 0xc541 #define USB_DEVICE_ID_LOGITECH_NANO_RECEIVER_POWERPLAY 0xc53a #define USB_DEVICE_ID_LOGITECH_BOLT_RECEIVER 0xc548 #define USB_DEVICE_ID_SPACETRAVELLER 0xc623 diff --git a/drivers/hid/hid-lenovo.c b/drivers/hid/hid-lenovo.c index 30bd3f794243be..e997d0cf267261 100644 --- a/drivers/hid/hid-lenovo.c +++ b/drivers/hid/hid-lenovo.c @@ -812,6 +812,22 @@ static int lenovo_raw_event(struct hid_device *hdev, size >= 4 && report->id == 0x03)) return lenovo_raw_event_TP_X12_tab(hdev, get_unaligned_le32(data)); + /* + * Lenovo ThinkPad T14s gen6/7 snapdragon version filter out spurious + * F23 events when Fn key is pressed. F23 cannot be unmapped because of + * the copilot key sending left-meta + left-shift + F23. Filter report 8 + * (keyboard) scancode 0x72 (F23) when the modifier byte is not 0x0a. + */ + if (unlikely(hdev->product == I2C_DEVICE_ID_ELAN_LENOVO_T14S_KEYBOARD && + size == 9 && data[0] == 8 && data[1] != 0x0a)) { + for (int i = 3; i < 9; i++) + if (data[i] == 0x72) { + memmove(&data[i], &data[i + 1], 8 - i); + data[8] = 0; + break; + } + } + return 0; } @@ -1393,6 +1409,10 @@ static int lenovo_probe(struct hid_device *hdev, { int ret; + /* Make the T14s keyboard trackpoint a separate input-device */ + if (hdev->product == I2C_DEVICE_ID_ELAN_LENOVO_T14S_KEYBOARD) + hdev->quirks |= HID_QUIRK_INPUT_PER_APP; + ret = hid_parse(hdev); if (ret) { hid_err(hdev, "hid_parse failed\n"); @@ -1558,6 +1578,7 @@ static const struct hid_device_id lenovo_devices[] = { { HID_USB_DEVICE(USB_VENDOR_ID_IBM, USB_DEVICE_ID_IBM_SCROLLPOINT_800DPI_OPTICAL_PRO) }, { HID_USB_DEVICE(USB_VENDOR_ID_LENOVO, USB_DEVICE_ID_LENOVO_SCROLLPOINT_OPTICAL) }, { HID_USB_DEVICE(USB_VENDOR_ID_LENOVO, USB_DEVICE_ID_LENOVO_TP10UBKBD) }, + { HID_I2C_DEVICE(USB_VENDOR_ID_ELAN, I2C_DEVICE_ID_ELAN_LENOVO_T14S_KEYBOARD) }, /* * Note bind to the HID_GROUP_GENERIC group, so that we only bind to the keyboard * part, while letting hid-multitouch.c handle the touchpad and trackpoint. diff --git a/drivers/hid/hid-letsketch.c b/drivers/hid/hid-letsketch.c index 51f43324ddb8d0..a1eb4137b9f3a9 100644 --- a/drivers/hid/hid-letsketch.c +++ b/drivers/hid/hid-letsketch.c @@ -213,6 +213,12 @@ static int letsketch_raw_event(struct hid_device *hdev, * string descriptors. But the firmware is buggy and does not like it if * we do this too fast. Even if we go slow sometimes the usb_string() call * fails. Ignore errors and retry it a couple of times if necessary. + * + * Some firmware revisions (e.g. "Vision_V201_180530", sold as the Starcom + * GC-422) do not implement every string descriptor index the handshake + * reads. For those indices usb_string() keeps returning an empty string or + * -EPIPE (STALL). Report such an index as missing with -ENOENT once the + * retries are used up, so that the caller can skip it. */ static int letsketch_get_string(struct usb_device *udev, int index, char *buf, int size) { @@ -225,9 +231,14 @@ static int letsketch_get_string(struct usb_device *udev, int index, char *buf, i return 0; } + if (ret == 0 || ret == -EPIPE) { + dev_dbg(&udev->dev, "String descriptor %d not implemented\n", index); + return -ENOENT; + } + dev_err(&udev->dev, "Max retries (%d) exceeded reading string descriptor %d\n", LETSKETCH_GET_STRING_RETRIES, index); - return ret ? ret : -EIO; + return ret; } static int letsketch_probe(struct hid_device *hdev, const struct hid_device_id *id) @@ -256,6 +267,8 @@ static int letsketch_probe(struct hid_device *hdev, const struct hid_device_id * */ for (i = LETSKETCH_INFO_STR_IDX_BEGIN; i <= LETSKETCH_INFO_STR_IDX_END; i++) { ret = letsketch_get_string(udev, i, buf, sizeof(buf)); + if (ret == -ENOENT) + continue; if (ret) return ret; @@ -264,16 +277,16 @@ static int letsketch_probe(struct hid_device *hdev, const struct hid_device_id * for (i = 1; i <= 250; i++) { ret = letsketch_get_string(udev, i, buf, sizeof(buf)); - if (ret) + if (ret && ret != -ENOENT) return ret; } ret = letsketch_get_string(udev, 0x64, buf, sizeof(buf)); - if (ret) + if (ret && ret != -ENOENT) return ret; ret = letsketch_get_string(udev, LETSKETCH_INFO_STR_IDX_BEGIN, buf, sizeof(buf)); - if (ret) + if (ret && ret != -ENOENT) return ret; /* diff --git a/drivers/hid/hid-logitech-dj.c b/drivers/hid/hid-logitech-dj.c index 6e8db01d27ec0e..230abff5fcd5ee 100644 --- a/drivers/hid/hid-logitech-dj.c +++ b/drivers/hid/hid-logitech-dj.c @@ -2114,6 +2114,10 @@ static const struct hid_device_id logi_dj_receivers[] = { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_NANO_RECEIVER_LIGHTSPEED_1_5), .driver_data = recvr_type_gaming_hidpp_ls_1_3}, + { /* Logitech lightspeed receiver (0xc541) */ + HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, + USB_DEVICE_ID_LOGITECH_NANO_RECEIVER_LIGHTSPEED_1_6), + .driver_data = recvr_type_gaming_hidpp_ls_1_3}, { /* Logitech 27 MHz HID++ 1.0 receiver (0xc513) */ HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_MX3000_RECEIVER), diff --git a/drivers/hid/hid-magicmouse.c b/drivers/hid/hid-magicmouse.c index a01e84a18dedeb..525ffc64a2f02a 100644 --- a/drivers/hid/hid-magicmouse.c +++ b/drivers/hid/hid-magicmouse.c @@ -1032,7 +1032,7 @@ static void magicmouse_remove(struct hid_device *hdev) struct magicmouse_sc *msc = hid_get_drvdata(hdev); if (msc) { - cancel_delayed_work_sync(&msc->work); + disable_delayed_work_sync(&msc->work); if (is_usb_magicmouse2(hdev->vendor, hdev->product) || is_usb_magictrackpad2(hdev->vendor, hdev->product)) timer_delete_sync(&msc->battery_timer); diff --git a/drivers/hid/hid-multitouch.c b/drivers/hid/hid-multitouch.c index 3afca07025ea75..f63d6f6550bd82 100644 --- a/drivers/hid/hid-multitouch.c +++ b/drivers/hid/hid-multitouch.c @@ -2154,7 +2154,7 @@ static int mt_probe(struct hid_device *hdev, const struct hid_device_id *id) if (hdev->quirks & (HID_QUIRK_X_INVERT | HID_QUIRK_Y_INVERT) && !((hdev->quirks & HID_QUIRK_X_INVERT) && (hdev->quirks & HID_QUIRK_Y_INVERT))) - td->mtclass.quirks = MT_QUIRK_ORIENTATION_INVERT; + td->mtclass.quirks |= MT_QUIRK_ORIENTATION_INVERT; /* This allows the driver to correctly support devices * that emit events over several HID messages. diff --git a/drivers/hid/hid-nintendo-switch2-usb.c b/drivers/hid/hid-nintendo-switch2-usb.c index 623473f3d21612..d7c36120db969f 100644 --- a/drivers/hid/hid-nintendo-switch2-usb.c +++ b/drivers/hid/hid-nintendo-switch2-usb.c @@ -52,12 +52,10 @@ static void switch2_bulk_in(struct urb *urb) { struct switch2_usb *ns2_usb = urb->context; int i; - bool schedule = false; unsigned long flags; switch (urb->status) { case 0: - schedule = true; break; case -ECONNRESET: case -ENOENT: @@ -71,16 +69,14 @@ static void switch2_bulk_in(struct urb *urb) } spin_lock_irqsave(&ns2_usb->bulk_in_lock, flags); - if (ns2_usb->shutdown) - schedule = false; - for (i = 0; i < NS2_IN_URBS; i++) { int err; struct switch2_urb *ns2_urb; if (ns2_usb->bulk_in[i].urb == urb) { - if (schedule) { + if (urb->status == 0 && !ns2_usb->shutdown) { ns2_usb->bulk_in[i].state = NS2_URB_IN; + schedule_work(&ns2_usb->message_in_work); continue; } else { ns2_usb->bulk_in[i].state = NS2_URB_FREE; @@ -115,9 +111,6 @@ static void switch2_bulk_in(struct urb *urb) } } spin_unlock_irqrestore(&ns2_usb->bulk_in_lock, flags); - - if (schedule) - schedule_work(&ns2_usb->message_in_work); } static void switch2_bulk_out(struct urb *urb) @@ -295,6 +288,9 @@ static void switch2_usb_message_in_work(struct work_struct *work) spin_lock_irqsave(&ns2_usb->bulk_in_lock, flags); for (i = 0; i < NS2_IN_URBS; i++) { + if (ns2_usb->shutdown) + break; + urb = &ns2_usb->bulk_in[i]; if (urb->state != NS2_URB_IN) continue; @@ -311,7 +307,7 @@ static void switch2_usb_message_in_work(struct work_struct *work) } spin_lock_irqsave(&ns2_usb->bulk_in_lock, flags); - if (!urb->urb) + if (ns2_usb->shutdown || !urb->urb) /* We're shutting down and this URB was freed */ break; @@ -431,6 +427,8 @@ static int switch2_usb_probe(struct usb_interface *intf, const struct usb_device ns2_usb->bulk_in[0].state = NS2_URB_OUT; usb_anchor_urb(ns2_usb->bulk_in[0].urb, &ns2_usb->bulk_in_anchor); ret = usb_submit_urb(ns2_usb->bulk_in[0].urb, GFP_ATOMIC); + if (ret < 0) + usb_unanchor_urb(ns2_usb->bulk_in[0].urb); spin_unlock_irqrestore(&ns2_usb->bulk_in_lock, flags); if (ret < 0) diff --git a/drivers/hid/hid-nintendo.c b/drivers/hid/hid-nintendo.c index eb3274db8ccbac..532ea1e193d625 100644 --- a/drivers/hid/hid-nintendo.c +++ b/drivers/hid/hid-nintendo.c @@ -2272,10 +2272,9 @@ static int joycon_player_led_brightness_set(struct led_classdev *led, return -ENODEV; } + mutex_lock(&ctlr->output_mutex); for (i = 0; i < JC_NUM_LEDS; i++) val |= ctlr->leds[i].brightness << i; - - mutex_lock(&ctlr->output_mutex); ret = joycon_set_player_leds(ctlr, 0, val); mutex_unlock(&ctlr->output_mutex); @@ -2792,7 +2791,7 @@ static int joycon_probe(struct hid_device *hdev, ret = joycon_leds_create(ctlr); if (ret) { hid_err(hdev, "Failed to create leds; ret=%d\n", ret); - goto err_io_stop; + goto err_ida; } /* Initialize the battery power supply */ @@ -4292,6 +4291,7 @@ int switch2_controller_attach_cfg(const char *phys, struct switch2_cfg_intf *cfg mutex_lock(&ns2->lock); if (ns2->cfg) { ret = -EBUSY; + mutex_unlock(&ns2->lock); goto out; } cfg->parent = ns2; @@ -4301,15 +4301,16 @@ int switch2_controller_attach_cfg(const char *phys, struct switch2_cfg_intf *cfg ret = switch2_init_controller(ns2); if (ret < 0) { + ns2->cfg = NULL; + mutex_unlock(&ns2->lock); if (cfg->shutdown) cfg->shutdown(cfg); cfg->parent = NULL; - ns2->cfg = NULL; + } else { + mutex_unlock(&ns2->lock); } out: - mutex_unlock(&ns2->lock); - if (ret < 0) kref_put(&ns2->refcount, switch2_kref_put); return ret; diff --git a/drivers/hid/hid-picolcd.h b/drivers/hid/hid-picolcd.h index 57c9d0a6757c1b..846a8ceb95acc2 100644 --- a/drivers/hid/hid-picolcd.h +++ b/drivers/hid/hid-picolcd.h @@ -102,6 +102,8 @@ struct picolcd_data { /* Housekeeping stuff */ spinlock_t lock; struct mutex mutex; + /* Serialize updates to output reports and their HID requests. */ + struct mutex report_mutex; struct picolcd_pending *pending; int status; #define PICOLCD_BOOTLOADER 1 diff --git a/drivers/hid/hid-quirks.c b/drivers/hid/hid-quirks.c index 793db001a62b7b..dbc40bb9c3adf8 100644 --- a/drivers/hid/hid-quirks.c +++ b/drivers/hid/hid-quirks.c @@ -37,6 +37,7 @@ static const struct hid_device_id hid_quirks[] = { { HID_USB_DEVICE(USB_VENDOR_ID_ALPS, USB_DEVICE_ID_IBM_GAMEPAD), HID_QUIRK_BADPAD }, { HID_USB_DEVICE(USB_VENDOR_ID_AMI, USB_DEVICE_ID_AMI_VIRT_KEYBOARD_AND_MOUSE), HID_QUIRK_ALWAYS_POLL }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_REVB_ANSI), HID_QUIRK_ALWAYS_POLL }, + { HID_USB_DEVICE(USB_VENDOR_ID_ASUSTEK, USB_DEVICE_ID_ASUSTEK_MD301_DONGLE), HID_QUIRK_ALWAYS_POLL }, { HID_USB_DEVICE(USB_VENDOR_ID_ATEN, USB_DEVICE_ID_ATEN_2PORTKVM), HID_QUIRK_NOGET }, { HID_USB_DEVICE(USB_VENDOR_ID_ATEN, USB_DEVICE_ID_ATEN_4PORTKVMC), HID_QUIRK_NOGET }, { HID_USB_DEVICE(USB_VENDOR_ID_ATEN, USB_DEVICE_ID_ATEN_4PORTKVM), HID_QUIRK_NOGET }, @@ -116,6 +117,8 @@ static const struct hid_device_id hid_quirks[] = { { HID_USB_DEVICE(USB_VENDOR_ID_INNOMEDIA, USB_DEVICE_ID_INNEX_GENESIS_ATARI), HID_QUIRK_MULTI_INPUT }, { HID_USB_DEVICE(USB_VENDOR_ID_JESS, USB_DEVICE_ID_AULA_MINI_60_HE_PRO), HID_QUIRK_ALWAYS_POLL }, + { HID_USB_DEVICE(USB_VENDOR_ID_KEYCHRON, USB_DEVICE_ID_KEYCHRON_LINK), + HID_QUIRK_ALWAYS_POLL }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_PIXART_USB_OPTICAL_MOUSE_ID2), HID_QUIRK_ALWAYS_POLL }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_KYE_EASYPEN_M406), HID_QUIRK_MULTI_INPUT }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_KYE_EASYPEN_M506), HID_QUIRK_MULTI_INPUT }, diff --git a/drivers/hid/hid-roccat.c b/drivers/hid/hid-roccat.c index b3e69c79c4b438..4ed8822fec20c0 100644 --- a/drivers/hid/hid-roccat.c +++ b/drivers/hid/hid-roccat.c @@ -40,7 +40,8 @@ struct roccat_device { unsigned int minor; int report_size; int open; - int exist; + struct kref ref; + atomic_t exist; wait_queue_head_t wait; struct device *dev; struct hid_device *hid; @@ -70,12 +71,25 @@ static struct roccat_device *devices[ROCCAT_MAX_DEVICES]; /* protects modifications of devices array */ static DEFINE_MUTEX(devices_lock); -static void roccat_free_device(struct roccat_device *device) +static bool roccat_device_available(struct roccat_device *device) { + return atomic_read(&device->exist); +} + +static void roccat_free_device(struct kref *ref) +{ + struct roccat_device *device; int i; + WARN_ON(!mutex_is_locked(&devices_lock)); + + device = container_of(ref, struct roccat_device, ref); for (i = 0; i < ROCCAT_CBUF_SIZE; i++) kfree(device->cbuf[i].value); + + devices[device->minor] = NULL; + mutex_destroy(&device->readers_lock); + mutex_destroy(&device->cbuf_lock); kfree(device); } @@ -105,7 +119,7 @@ static ssize_t roccat_read(struct file *file, char __user *buffer, retval = -ERESTARTSYS; break; } - if (!device->exist) { + if (!roccat_device_available(device)) { retval = -EIO; break; } @@ -146,12 +160,18 @@ static ssize_t roccat_read(struct file *file, char __user *buffer, static __poll_t roccat_poll(struct file *file, poll_table *wait) { struct roccat_reader *reader = file->private_data; + bool avail; + poll_wait(file, &reader->device->wait, wait); - if (reader->cbuf_start != reader->device->cbuf_end) - return EPOLLIN | EPOLLRDNORM; - if (!reader->device->exist) + + if (!roccat_device_available(reader->device)) return EPOLLERR | EPOLLHUP; - return 0; + + mutex_lock(&reader->device->cbuf_lock); + avail = (reader->cbuf_start != reader->device->cbuf_end); + mutex_unlock(&reader->device->cbuf_lock); + + return avail ? EPOLLIN | EPOLLRDNORM : 0; } static int roccat_open(struct inode *inode, struct file *file) @@ -169,7 +189,7 @@ static int roccat_open(struct inode *inode, struct file *file) device = devices[minor]; - if (!device) { + if (!device || !roccat_device_available(device)) { pr_emerg("roccat device with minor %d doesn't exist\n", minor); error = -ENODEV; goto exit_err_devices; @@ -191,6 +211,7 @@ static int roccat_open(struct inode *inode, struct file *file) --device->open; goto exit_err_readers; } + kref_get(&device->ref); } reader->device = device; @@ -226,12 +247,11 @@ static int roccat_release(struct inode *inode, struct file *file) if (!--device->open) { /* removing last reader */ - if (device->exist) { + if (roccat_device_available(device)) { hid_hw_power(device->hid, PM_HINT_NORMAL); hid_hw_close(device->hid); - } else { - roccat_free_device(device); } + kref_put(&device->ref, roccat_free_device); } mutex_unlock(&devices_lock); @@ -343,9 +363,10 @@ int roccat_connect(const struct class *klass, struct hid_device *hid, int report INIT_LIST_HEAD(&device->readers); mutex_init(&device->readers_lock); mutex_init(&device->cbuf_lock); + kref_init(&device->ref); device->minor = minor; device->hid = hid; - device->exist = 1; + atomic_set(&device->exist, 1); device->cbuf_end = 0; device->report_size = report_size; @@ -364,19 +385,19 @@ void roccat_disconnect(int minor) mutex_lock(&devices_lock); device = devices[minor]; - device->exist = 0; /* TODO exist maybe not needed */ - - device_destroy(device->dev->class, MKDEV(roccat_major, minor)); + if (WARN_ON(!device)) + goto out; - devices[minor] = NULL; + if (!WARN_ON(!atomic_cmpxchg(&device->exist, 1, 0))) + device_destroy(device->dev->class, MKDEV(roccat_major, minor)); if (device->open) { hid_hw_close(device->hid); wake_up_interruptible(&device->wait); - } else { - roccat_free_device(device); } + kref_put(&device->ref, roccat_free_device); +out: mutex_unlock(&devices_lock); } EXPORT_SYMBOL_GPL(roccat_disconnect); @@ -391,7 +412,7 @@ static long roccat_ioctl(struct file *file, unsigned int cmd, unsigned long arg) mutex_lock(&devices_lock); device = devices[minor]; - if (!device) { + if (!device || !roccat_device_available(device)) { retval = -ENODEV; goto out; } diff --git a/drivers/hid/hid-saitek.c b/drivers/hid/hid-saitek.c index 71f23dbf290ebb..f374c80c055478 100644 --- a/drivers/hid/hid-saitek.c +++ b/drivers/hid/hid-saitek.c @@ -151,7 +151,12 @@ static int saitek_event(struct hid_device *hdev, struct hid_field *field, struct hid_usage *usage, __s32 value) { struct saitek_sc *ssc = hid_get_drvdata(hdev); - struct input_dev *input = field->hidinput->input; + struct input_dev *input; + + if (!(hdev->claimed & HID_CLAIMED_INPUT) || !field->hidinput) + return 0; + + input = field->hidinput->input; if (usage->type == EV_KEY && value && (((ssc->quirks & SAITEK_RELEASE_MODE_RAT7) && diff --git a/drivers/hid/hid-sensor-custom.c b/drivers/hid/hid-sensor-custom.c index c12272479d82df..8a71e86d247b11 100644 --- a/drivers/hid/hid-sensor-custom.c +++ b/drivers/hid/hid-sensor-custom.c @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -37,6 +38,9 @@ struct hid_sensor_custom_field { struct hid_sensor_custom { struct mutex mutex; + struct mutex read_mutex; + struct kref ref; + bool removed; struct platform_device *pdev; struct hid_sensor_hub_device *hsdev; struct hid_sensor_hub_callbacks callbacks; @@ -643,6 +647,15 @@ static void hid_sensor_custom_remove_attributes(struct hid_sensor_custom * kfree(sensor_inst->fields); } +static void hid_sensor_custom_free(struct kref *ref) +{ + struct hid_sensor_custom *sensor_inst = + container_of(ref, struct hid_sensor_custom, ref); + + kfifo_free(&sensor_inst->data_fifo); + kfree(sensor_inst); +} + static ssize_t hid_sensor_custom_read(struct file *file, char __user *buf, size_t count, loff_t *f_ps) { @@ -656,22 +669,41 @@ static ssize_t hid_sensor_custom_read(struct file *file, char __user *buf, if (count < sizeof(struct hid_sensor_sample)) return -EINVAL; - do { - if (kfifo_is_empty(&sensor_inst->data_fifo)) { - if (file->f_flags & O_NONBLOCK) - return -EAGAIN; + if (file->f_flags & O_NONBLOCK) { + if (!mutex_trylock(&sensor_inst->read_mutex)) + return -EAGAIN; + } else { + ret = mutex_lock_interruptible(&sensor_inst->read_mutex); + if (ret) + return ret; + } - ret = wait_event_interruptible(sensor_inst->wait, - !kfifo_is_empty(&sensor_inst->data_fifo)); - if (ret) - return ret; + for (;;) { + if (READ_ONCE(sensor_inst->removed)) { + ret = -ENODEV; + break; } + ret = kfifo_to_user(&sensor_inst->data_fifo, buf, count, &copied); + if (ret || copied) + break; + + if (file->f_flags & O_NONBLOCK) { + ret = -EAGAIN; + break; + } + + ret = wait_event_interruptible(sensor_inst->wait, + READ_ONCE(sensor_inst->removed) || + !kfifo_is_empty(&sensor_inst->data_fifo)); if (ret) - return ret; + break; + } - } while (copied == 0); + mutex_unlock(&sensor_inst->read_mutex); + if (ret) + return ret; return copied; } @@ -684,6 +716,7 @@ static int hid_sensor_custom_release(struct inode *inode, struct file *file) struct hid_sensor_custom, custom_dev); clear_bit(0, &sensor_inst->misc_opened); + kref_put(&sensor_inst->ref, hid_sensor_custom_free); return 0; } @@ -691,14 +724,25 @@ static int hid_sensor_custom_release(struct inode *inode, struct file *file) static int hid_sensor_custom_open(struct inode *inode, struct file *file) { struct hid_sensor_custom *sensor_inst; + int ret; sensor_inst = container_of(file->private_data, struct hid_sensor_custom, custom_dev); + if (READ_ONCE(sensor_inst->removed)) + return -ENODEV; + /* We essentially have single reader and writer */ if (test_and_set_bit(0, &sensor_inst->misc_opened)) return -EBUSY; - return stream_open(inode, file); + kref_get(&sensor_inst->ref); + ret = stream_open(inode, file); + if (ret) { + clear_bit(0, &sensor_inst->misc_opened); + kref_put(&sensor_inst->ref, hid_sensor_custom_free); + } + + return ret; } static __poll_t hid_sensor_custom_poll(struct file *file, @@ -712,6 +756,9 @@ static __poll_t hid_sensor_custom_poll(struct file *file, poll_wait(file, &sensor_inst->wait, wait); + if (READ_ONCE(sensor_inst->removed)) + return EPOLLHUP | EPOLLERR; + if (!kfifo_is_empty(&sensor_inst->data_fifo)) mask = EPOLLIN | EPOLLRDNORM; @@ -719,6 +766,7 @@ static __poll_t hid_sensor_custom_poll(struct file *file, } static const struct file_operations hid_sensor_custom_fops = { + .owner = THIS_MODULE, .open = hid_sensor_custom_open, .read = hid_sensor_custom_read, .release = hid_sensor_custom_release, @@ -740,21 +788,15 @@ static int hid_sensor_custom_dev_if_add(struct hid_sensor_custom *sensor_inst) sensor_inst->custom_dev.minor = MISC_DYNAMIC_MINOR; sensor_inst->custom_dev.name = dev_name(&sensor_inst->pdev->dev); sensor_inst->custom_dev.fops = &hid_sensor_custom_fops; - ret = misc_register(&sensor_inst->custom_dev); - if (ret) { - kfifo_free(&sensor_inst->data_fifo); - return ret; - } - return 0; + return misc_register(&sensor_inst->custom_dev); } static void hid_sensor_custom_dev_if_remove(struct hid_sensor_custom *sensor_inst) { - wake_up(&sensor_inst->wait); + WRITE_ONCE(sensor_inst->removed, true); + wake_up_interruptible_all(&sensor_inst->wait); misc_deregister(&sensor_inst->custom_dev); - kfifo_free(&sensor_inst->data_fifo); - } /* @@ -977,7 +1019,7 @@ static int hid_sensor_custom_probe(struct platform_device *pdev) int ret; const struct hid_sensor_custom_match *match; - sensor_inst = devm_kzalloc_obj(&pdev->dev, *sensor_inst); + sensor_inst = kzalloc_obj(*sensor_inst); if (!sensor_inst) return -ENOMEM; @@ -987,6 +1029,8 @@ static int hid_sensor_custom_probe(struct platform_device *pdev) sensor_inst->hsdev = hsdev; sensor_inst->pdev = pdev; mutex_init(&sensor_inst->mutex); + mutex_init(&sensor_inst->read_mutex); + kref_init(&sensor_inst->ref); platform_set_drvdata(pdev, sensor_inst); ret = hid_sensor_custom_get_known(hsdev, &match); @@ -998,7 +1042,7 @@ static int hid_sensor_custom_probe(struct platform_device *pdev) if (ret) { dev_err(&pdev->dev, "register_platform_device failed\n"); - return ret; + goto err_put; } return 0; @@ -1008,31 +1052,32 @@ static int hid_sensor_custom_probe(struct platform_device *pdev) &sensor_inst->callbacks); if (ret < 0) { dev_err(&pdev->dev, "callback reg failed\n"); - return ret; + goto err_put; } ret = hid_sensor_custom_add_attributes(sensor_inst); if (ret) goto err_remove_callback; - ret = sysfs_create_group(&sensor_inst->pdev->dev.kobj, - &enable_sensor_attr_group); + ret = hid_sensor_custom_dev_if_add(sensor_inst); if (ret) goto err_remove_attributes; - ret = hid_sensor_custom_dev_if_add(sensor_inst); + ret = sysfs_create_group(&sensor_inst->pdev->dev.kobj, + &enable_sensor_attr_group); if (ret) - goto err_remove_group; + goto err_remove_dev_if; return 0; -err_remove_group: - sysfs_remove_group(&sensor_inst->pdev->dev.kobj, - &enable_sensor_attr_group); +err_remove_dev_if: + hid_sensor_custom_dev_if_remove(sensor_inst); err_remove_attributes: hid_sensor_custom_remove_attributes(sensor_inst); err_remove_callback: sensor_hub_remove_callback(hsdev, hsdev->usage); +err_put: + kref_put(&sensor_inst->ref, hid_sensor_custom_free); return ret; } @@ -1044,15 +1089,24 @@ static void hid_sensor_custom_remove(struct platform_device *pdev) if (sensor_inst->custom_pdev) { platform_device_unregister(sensor_inst->custom_pdev); - return; + goto out; } + sensor_hub_remove_callback(hsdev, hsdev->usage); hid_sensor_custom_dev_if_remove(sensor_inst); /* Remove enable_sensor first as it uses fields via power_state/report_state. */ sysfs_remove_group(&sensor_inst->pdev->dev.kobj, &enable_sensor_attr_group); + mutex_lock(&sensor_inst->mutex); + if (sensor_inst->enable) { + set_power_report_state(sensor_inst, false); + sensor_hub_device_close(hsdev); + sensor_inst->enable = false; + } + mutex_unlock(&sensor_inst->mutex); hid_sensor_custom_remove_attributes(sensor_inst); - sensor_hub_remove_callback(hsdev, hsdev->usage); +out: + kref_put(&sensor_inst->ref, hid_sensor_custom_free); } static const struct platform_device_id hid_sensor_custom_ids[] = { diff --git a/drivers/hid/hid-sensor-hub.c b/drivers/hid/hid-sensor-hub.c index 81c8e723f9bacf..2a7f2475171fc0 100644 --- a/drivers/hid/hid-sensor-hub.c +++ b/drivers/hid/hid-sensor-hub.c @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include "hid-ids.h" @@ -173,7 +174,9 @@ int sensor_hub_remove_callback(struct hid_sensor_hub_device *hsdev, struct sensor_hub_data *pdata = hid_get_drvdata(hsdev->hdev); unsigned long flags; - spin_lock_irqsave(&pdata->dyn_callback_lock, flags); + /* Serialize callback removal with raw-event callback execution. */ + spin_lock_irqsave(&pdata->lock, flags); + spin_lock(&pdata->dyn_callback_lock); list_for_each_entry(callback, &pdata->dyn_callback_list, list) if (callback->usage_id == usage_id && callback->hsdev == hsdev) { @@ -181,7 +184,8 @@ int sensor_hub_remove_callback(struct hid_sensor_hub_device *hsdev, kfree(callback); break; } - spin_unlock_irqrestore(&pdata->dyn_callback_lock, flags); + spin_unlock(&pdata->dyn_callback_lock); + spin_unlock_irqrestore(&pdata->lock, flags); return 0; } @@ -800,7 +804,14 @@ static int sensor_hub_probe(struct hid_device *hdev, static int sensor_hub_finalize_pending_fn(struct device *dev, void *data) { - struct hid_sensor_hub_device *hsdev = dev->platform_data; + struct hid_sensor_hub_device *hsdev; + + if (!dev_is_platform(dev)) + return 0; + + hsdev = to_platform_device(dev)->dev.platform_data; + if (!hsdev) + return 0; if (hsdev->pending.status) complete(&hsdev->pending.ready); @@ -814,8 +825,6 @@ static void sensor_hub_remove(struct hid_device *hdev) unsigned long flags; hid_dbg(hdev, " hardware removed\n"); - hid_hw_close(hdev); - hid_hw_stop(hdev); spin_lock_irqsave(&data->lock, flags); device_for_each_child(&hdev->dev, NULL, @@ -823,6 +832,14 @@ static void sensor_hub_remove(struct hid_device *hdev) spin_unlock_irqrestore(&data->lock, flags); mfd_remove_devices(&hdev->dev); + /* Clients share one HID open; release it if references remain. */ + mutex_lock(&data->mutex); + if (data->ref_cnt) { + data->ref_cnt = 0; + hid_hw_close(hdev); + } + mutex_unlock(&data->mutex); + hid_hw_stop(hdev); mutex_destroy(&data->mutex); } diff --git a/drivers/hid/hid-sony.c b/drivers/hid/hid-sony.c index 228e7481903726..ac3040267b4b0a 100644 --- a/drivers/hid/hid-sony.c +++ b/drivers/hid/hid-sony.c @@ -630,7 +630,7 @@ static int ghl_init_urb(struct sony_sc *sc, struct usb_device *usbdev, * Sending HID_REQ_SET_REPORT enables the full report. Without this * Rock Band 3 Pro instruments only report navigation events */ -static int rb3_pro_instrument_enable_full_report(struct sony_sc *sc) +static void rb3_pro_instrument_enable_full_report(struct sony_sc *sc) { struct hid_device *hdev = sc->hdev; static const u8 report[] = { 0x00, 0xE9, 0x00, 0x89, 0x1B, @@ -647,14 +647,14 @@ static int rb3_pro_instrument_enable_full_report(struct sony_sc *sc) buf = kmemdup(report, sizeof(report), GFP_KERNEL); if (!buf) - return -ENOMEM; + return; ret = hid_hw_raw_request(hdev, buf[0], buf, sizeof(report), HID_FEATURE_REPORT, HID_REQ_SET_REPORT); + if (ret < 0) + hid_dbg(hdev, "failed to enable full report: %d\n", ret); kfree(buf); - - return ret; } static int djh_turntable_mapping(struct hid_device *hdev, struct hid_input *hi, @@ -1098,10 +1098,10 @@ static int rb3_pro_instrument_raw_event(struct sony_sc *sc, u8 *rd, int size) if (size < 25 || rd[24] != 0x02) return 0; - /* Only attempt to enable full report every 8 seconds */ + /* Only attempt to enable full report every 8 seconds, from the worker */ if (time_after(jiffies, sc->rb3_pro_poke_jiffies)) { sc->rb3_pro_poke_jiffies = jiffies + secs_to_jiffies(8); - rb3_pro_instrument_enable_full_report(sc); + sony_schedule_work(sc); } return 0; @@ -2217,6 +2217,7 @@ static int sony_input_configured(struct hid_device *hdev, hdev->quirks |= HID_QUIRK_SKIP_OUTPUT_REPORT_ID; sony_init_raw_event_handler(sc, rb3_pro_instrument_raw_event); + sony_init_output_report(sc, rb3_pro_instrument_enable_full_report); } else if (sc->quirks & SIXAXIS_CONTROLLER_USB) { /* * The Sony Sixaxis does not handle HID Output Reports on the diff --git a/drivers/hid/hid-steelseries.c b/drivers/hid/hid-steelseries.c index 0170276091b9f1..3ab99ca6bc3279 100644 --- a/drivers/hid/hid-steelseries.c +++ b/drivers/hid/hid-steelseries.c @@ -356,6 +356,13 @@ static const struct dmi_system_id steelseries_msi_rgb_dmi_table[] = { DMI_MATCH(DMI_BOARD_NAME, "MS-182L"), }, }, + { + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "Micro-Star International Co., Ltd."), + DMI_MATCH(DMI_PRODUCT_NAME, "Raider A18 HX A7VHG"), + DMI_MATCH(DMI_BOARD_NAME, "MS-182K"), + }, + }, { } }; diff --git a/drivers/hid/hid-vivaldi-common.c b/drivers/hid/hid-vivaldi-common.c index b12bb5cc091aa3..973393d0935615 100644 --- a/drivers/hid/hid-vivaldi-common.c +++ b/drivers/hid/hid-vivaldi-common.c @@ -5,11 +5,13 @@ * Copyright (C) 2022 Google, Inc */ +#include #include #include #include #include #include +#include #include #include "hid-vivaldi-common.h" @@ -33,70 +35,55 @@ void vivaldi_feature_mapping(struct hid_device *hdev, { struct vivaldi_data *data = hid_get_drvdata(hdev); struct hid_report *report = field->report; - u8 *report_data, *buf; - u32 report_len; unsigned int fn_key; + unsigned int offset; + u32 report_len; int ret; + int i; - if (field->logical != HID_USAGE_FN_ROW_PHYSMAP || - (usage->hid & HID_USAGE_PAGE) != HID_UP_ORDINAL) + if (field->logical != HID_USAGE_FN_ROW_PHYSMAP || usage->usage_index) return; - fn_key = usage->hid & HID_USAGE; - if (fn_key < MIN_FN_ROW_KEY || fn_key > MAX_FN_ROW_KEY) + u8 *buf __free(kfree) = hid_alloc_report_buf(report, GFP_KERNEL); + if (!buf) return; - if (fn_key > data->num_function_row_keys) - data->num_function_row_keys = fn_key; - - report_data = buf = hid_alloc_report_buf(report, GFP_KERNEL); - if (!report_data) + /* + * hid_hw_raw_request() will stuff report ID (which will be 0) + * into the first byte of the buffer even for unnumbered + * reports, so we need to account for this to avoid getting + * -EOVERFLOW in return. + * Note that hid_alloc_report_buf() adds 7 bytes to the size + * so we can safely say that we have space for an extra byte. + */ + report_len = hid_report_len(report) + !report->id; + + ret = hid_hw_raw_request(hdev, report->id, buf, report_len, + HID_FEATURE_REPORT, HID_REQ_GET_REPORT); + if (ret != report_len) { + dev_warn(&hdev->dev, "failed to fetch feature %d: %d\n", + report->id, ret); return; - - report_len = hid_report_len(report); - if (!report->id) { - /* - * hid_hw_raw_request() will stuff report ID (which will be 0) - * into the first byte of the buffer even for unnumbered - * reports, so we need to account for this to avoid getting - * -EOVERFLOW in return. - * Note that hid_alloc_report_buf() adds 7 bytes to the size - * so we can safely say that we have space for an extra byte. - */ - report_len++; } - ret = hid_hw_raw_request(hdev, report->id, report_data, - report_len, HID_FEATURE_REPORT, - HID_REQ_GET_REPORT); - if (ret < 0) { - dev_warn(&hdev->dev, "failed to fetch feature %d\n", - field->report->id); - goto out; - } + for (i = 0; i < field->maxusage && i < field->report_count; i++) { + usage = &field->usage[i]; - if (!report->id) { - /* - * Undo the damage from hid_hw_raw_request() for unnumbered - * reports. - */ - report_data++; - report_len--; - } + if ((usage->hid & HID_USAGE_PAGE) != HID_UP_ORDINAL) + continue; - ret = hid_report_raw_event(hdev, HID_FEATURE_REPORT, report_data, - report_len, report_len, 0); - if (ret) { - dev_warn(&hdev->dev, "failed to report feature %d\n", - field->report->id); - goto out; - } + fn_key = usage->hid & HID_USAGE; + if (fn_key < MIN_FN_ROW_KEY || fn_key > MAX_FN_ROW_KEY) + continue; - data->function_row_physmap[fn_key - MIN_FN_ROW_KEY] = - field->value[usage->usage_index]; + if (fn_key > data->num_function_row_keys) + data->num_function_row_keys = fn_key; -out: - kfree(buf); + offset = field->report_offset + i * field->report_size; + data->function_row_physmap[fn_key - MIN_FN_ROW_KEY] = + hid_field_extract(hdev, buf + 1, offset, + field->report_size); + } } EXPORT_SYMBOL_GPL(vivaldi_feature_mapping); diff --git a/drivers/hid/hid-wiimote-core.c b/drivers/hid/hid-wiimote-core.c index 9168b85029183e..06759247fb37e0 100644 --- a/drivers/hid/hid-wiimote-core.c +++ b/drivers/hid/hid-wiimote-core.c @@ -1741,6 +1741,7 @@ static struct wiimote_data *wiimote_create(struct hid_device *hdev) wdata->player_id = 0; // min 1, u8 0 is unassigned id INIT_WORK(&wdata->init_worker, wiimote_init_worker); + INIT_WORK(&wdata->rumble_worker, wiimod_rumble_worker); timer_setup(&wdata->timer, wiimote_init_timeout, 0); return wdata; diff --git a/drivers/hid/hid-wiimote-modules.c b/drivers/hid/hid-wiimote-modules.c index 199589cbf2b856..16f3e6ca3b0368 100644 --- a/drivers/hid/hid-wiimote-modules.c +++ b/drivers/hid/hid-wiimote-modules.c @@ -118,7 +118,7 @@ static const struct wiimod_ops wiimod_keys = { */ /* used by wiimod_rumble and wiipro_rumble */ -static void wiimod_rumble_worker(struct work_struct *work) +void wiimod_rumble_worker(struct work_struct *work) { struct wiimote_data *wdata = container_of(work, struct wiimote_data, rumble_worker); @@ -156,8 +156,6 @@ static int wiimod_rumble_play(struct input_dev *dev, void *data, static int wiimod_rumble_probe(const struct wiimod_ops *ops, struct wiimote_data *wdata) { - INIT_WORK(&wdata->rumble_worker, wiimod_rumble_worker); - set_bit(FF_RUMBLE, wdata->input->ffbit); if (input_ff_create_memless(wdata->input, NULL, wiimod_rumble_play)) return -ENOMEM; @@ -1857,7 +1855,6 @@ static int wiimod_pro_probe(const struct wiimod_ops *ops, int ret, i; unsigned long flags; - INIT_WORK(&wdata->rumble_worker, wiimod_rumble_worker); wdata->state.calib_pro_sticks[0] = 0; wdata->state.calib_pro_sticks[1] = 0; wdata->state.calib_pro_sticks[2] = 0; diff --git a/drivers/hid/hid-wiimote.h b/drivers/hid/hid-wiimote.h index 8e5002f515e24f..9738da167a009a 100644 --- a/drivers/hid/hid-wiimote.h +++ b/drivers/hid/hid-wiimote.h @@ -263,6 +263,7 @@ enum wiiproto_reqs { #define dev_to_wii(pdev) hid_get_drvdata(to_hid_device(pdev)) void __wiimote_schedule(struct wiimote_data *wdata); +void wiimod_rumble_worker(struct work_struct *work); extern void wiiproto_req_drm(struct wiimote_data *wdata, __u8 drm); extern void wiiproto_req_rumble(struct wiimote_data *wdata, __u8 rumble); diff --git a/drivers/hid/i2c-hid/i2c-hid-acpi.c b/drivers/hid/i2c-hid/i2c-hid-acpi.c index 4362c85dfa7eac..4498c57ad07b06 100644 --- a/drivers/hid/i2c-hid/i2c-hid-acpi.c +++ b/drivers/hid/i2c-hid/i2c-hid-acpi.c @@ -21,6 +21,7 @@ #include #include +#include #include #include #include @@ -55,6 +56,67 @@ static void i2c_hid_acpi_restore_sequence(struct i2chid_ops *ops) i2c_hid_acpi_get_descriptor(ihid_acpi->adev); } +/* + * HP OmniBook X Flip 14 (board 8D9F), OmniBook 7 Flip 16 (8DA0) and + * OmniBook X Flip 16 (8DA1): the touchscreen power resource + * \_SB.PC00.I2C4.PTPL._ON writes the wrong value to the GPIROUTIOXAPIC bit + * of the touchscreen interrupt pad, disconnecting it from the IO-APIC. The + * level-triggered interrupt then never deasserts, the controller is read + * continuously (~630 reads/s while idle) and it cannot deliver pen reports + * at its native rate. Windows does not run _ON while the resource already + * reports on, so it is not affected. Linux runs _ON at probe and on every + * resume, so re-enable the routing with the firmware's own helper before + * the HID reset. + */ +static const struct dmi_system_id i2c_hid_acpi_irq_route_dmi[] = { + { + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "HP"), + DMI_EXACT_MATCH(DMI_BOARD_NAME, "8D9F"), + }, + }, + { + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "HP"), + DMI_EXACT_MATCH(DMI_BOARD_NAME, "8DA0"), + }, + }, + { + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "HP"), + DMI_EXACT_MATCH(DMI_BOARD_NAME, "8DA1"), + }, + }, + { } +}; + +static int i2c_hid_acpi_restore_irq_route(struct i2chid_ops *ops) +{ + struct i2c_hid_acpi *ihid_acpi = container_of(ops, struct i2c_hid_acpi, ops); + union acpi_object args[2]; + struct acpi_object_list arg_list = { ARRAY_SIZE(args), args }; + unsigned long long pad; + acpi_status status; + + status = acpi_evaluate_integer(NULL, "\\GPLI", NULL, &pad); + if (ACPI_FAILURE(status)) + return 0; + + args[0].type = ACPI_TYPE_INTEGER; + args[0].integer.value = pad; + args[1].type = ACPI_TYPE_INTEGER; + args[1].integer.value = 1; + + status = acpi_evaluate_object(NULL, "\\_SB.SGRA", &arg_list, NULL); + if (ACPI_FAILURE(status)) + acpi_handle_warn(acpi_device_handle(ihid_acpi->adev), + "failed to restore interrupt routing: %s\n", + acpi_format_exception(status)); + + /* Never fail probe or resume because of this workaround */ + return 0; +} + static void i2c_hid_acpi_shutdown_tail(struct i2chid_ops *ops) { struct i2c_hid_acpi *ihid_acpi = container_of(ops, struct i2c_hid_acpi, ops); @@ -85,6 +147,9 @@ static int i2c_hid_acpi_probe(struct i2c_client *client) ihid_acpi->adev = adev; ihid_acpi->ops.shutdown_tail = i2c_hid_acpi_shutdown_tail; ihid_acpi->ops.restore_sequence = i2c_hid_acpi_restore_sequence; + if (acpi_dev_hid_uid_match(ihid_acpi->adev, "ELAN2514", NULL) && + dmi_check_system(i2c_hid_acpi_irq_route_dmi)) + ihid_acpi->ops.power_up = i2c_hid_acpi_restore_irq_route; acpi_device_fix_up_power(adev); diff --git a/drivers/hid/intel-thc-hid/Kconfig b/drivers/hid/intel-thc-hid/Kconfig index 9d74e53b8c62b3..57a1e51cb512ef 100644 --- a/drivers/hid/intel-thc-hid/Kconfig +++ b/drivers/hid/intel-thc-hid/Kconfig @@ -8,6 +8,7 @@ config INTEL_THC_HID tristate "Intel Touch Host Controller" depends on ACPI select SGL_ALLOC + select REGMAP help THC (Touch Host Controller) is the name of the IP block in PCH that interfaces with Touch Devices (ex: touchscreen, touchpad etc.). It 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 bf49d8ce5f07be..ec974d549a92f9 100644 --- a/drivers/hid/intel-thc-hid/intel-quickspi/pci-quickspi.c +++ b/drivers/hid/intel-thc-hid/intel-quickspi/pci-quickspi.c @@ -562,17 +562,17 @@ static int quickspi_alloc_report_buf(struct quickspi_device *qsdev) max_report_len = max(le16_to_cpu(qsdev->dev_desc.max_output_len), le16_to_cpu(qsdev->dev_desc.max_input_len)); - /* - * write_cmd_to_txdma() writes the output report header ahead of the - * content in this buffer, so it has to hold both. - */ - qsdev->report_buf_size = HIDSPI_OUTPUT_REPORT_SIZE(max_report_len); - - qsdev->report_buf = devm_kzalloc(qsdev->dev, qsdev->report_buf_size, - GFP_KERNEL); + qsdev->report_buf = devm_kzalloc(qsdev->dev, + HIDSPI_OUTPUT_REPORT_SIZE(max_report_len), GFP_KERNEL); if (!qsdev->report_buf) return -ENOMEM; + /* + * Store the max data length of this report buffer, then compare it with output/input + * packet content when write or read into this report buffer to avoid buffer overflow. + */ + qsdev->report_buf_size = max_report_len; + return 0; } 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 fe51ff51d8c0e9..4362ac568bdaa9 100644 --- a/drivers/hid/intel-thc-hid/intel-quickspi/quickspi-dev.h +++ b/drivers/hid/intel-thc-hid/intel-quickspi/quickspi-dev.h @@ -115,6 +115,7 @@ struct acpi_device; * @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_buf_size: the data size of input/output buffer * @report_len: the length of input/output report packet * @reset_ack_wq: workqueue for waiting reset response from device * @reset_ack: indicate reset response received or not 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 0df33c44fbffe5..f8b455fd393995 100644 --- a/drivers/hid/intel-thc-hid/intel-quickspi/quickspi-protocol.c +++ b/drivers/hid/intel-thc-hid/intel-quickspi/quickspi-protocol.c @@ -30,7 +30,7 @@ static int write_cmd_to_txdma(struct quickspi_device *qsdev, write_buf = (struct output_report *)qsdev->report_buf; - if (HIDSPI_OUTPUT_REPORT_SIZE(report_buf_len) > qsdev->report_buf_size) + if (report_buf_len > qsdev->report_buf_size) return -EINVAL; write_buf->output_hdr.report_type = report_type; @@ -161,6 +161,7 @@ void quickspi_handle_input_data(struct quickspi_device *qsdev, u32 buf_len) struct input_report_body *input_body; u8 *input_report; u32 input_len; + u32 report_len; int ret = 0; input_body = (struct input_report_body *)qsdev->input_buf; @@ -210,7 +211,14 @@ void quickspi_handle_input_data(struct quickspi_device *qsdev, u32 buf_len) case GET_FEATURE_RESPONSE: case GET_INPUT_REPORT_RESPONSE: - qsdev->report_len = sizeof(body_hdr->content_id) + input_len; + report_len = sizeof(body_hdr->content_id) + input_len; + if (input_len > qsdev->report_buf_size) { + dev_err_once(qsdev->dev, "Get report response too big: %u\n", + input_len); + return; + } + + qsdev->report_len = report_len; input_report = input_body->content - sizeof(body_hdr->content_id); memcpy(qsdev->report_buf, input_report, qsdev->report_len); diff --git a/drivers/hid/wacom_sys.c b/drivers/hid/wacom_sys.c index 2d2a4d56a8da74..deed513bf5c0f9 100644 --- a/drivers/hid/wacom_sys.c +++ b/drivers/hid/wacom_sys.c @@ -2617,7 +2617,7 @@ static void wacom_wireless_work(struct work_struct *work) wacom_destroy_battery(wacom); - if (!usbdev) + if (!usbdev || usbdev->config->desc.bNumInterfaces < 3) return; /* Stylus interface */ diff --git a/drivers/hid/wacom_wac.c b/drivers/hid/wacom_wac.c index 361738bb872533..ab89a11d674039 100644 --- a/drivers/hid/wacom_wac.c +++ b/drivers/hid/wacom_wac.c @@ -1960,6 +1960,16 @@ static void wacom_wac_battery_usage_mapping(struct hid_device *hdev, return; } +static __s32 wacom_wac_battery_percentage(struct hid_field *field, __s32 value) +{ + __s32 range = field->logical_maximum - field->logical_minimum; + + if (range <= 0) + return 0; + + return clamp_val((value - field->logical_minimum) * 100 / range, 0, 100); +} + static void wacom_wac_battery_event(struct hid_device *hdev, struct hid_field *field, struct hid_usage *usage, __s32 value) { @@ -1973,7 +1983,7 @@ static void wacom_wac_battery_event(struct hid_device *hdev, struct hid_field *f wacom_wac->hid_data.bat_status = POWER_SUPPLY_STATUS_UNKNOWN; } else { - value = value * 100 / (field->logical_maximum - field->logical_minimum); + value = wacom_wac_battery_percentage(field, value); wacom_wac->hid_data.battery_capacity = value; wacom_wac->hid_data.bat_connected = 1; wacom_wac->hid_data.bat_status = WACOM_POWER_SUPPLY_STATUS_AUTO; @@ -1981,7 +1991,7 @@ static void wacom_wac_battery_event(struct hid_device *hdev, struct hid_field *f wacom_wac->features.quirks |= WACOM_QUIRK_BATTERY; break; case WACOM_HID_WD_BATTERY_LEVEL: - value = value * 100 / (field->logical_maximum - field->logical_minimum); + value = wacom_wac_battery_percentage(field, value); wacom_wac->hid_data.battery_capacity = value; wacom_wac->hid_data.bat_connected = 1; wacom_wac->hid_data.bat_status = WACOM_POWER_SUPPLY_STATUS_AUTO; @@ -2426,6 +2436,13 @@ static void wacom_wac_pen_usage_mapping(struct hid_device *hdev, } } +static int wacom_hid_wrapped_dist(int after, int before, int min, int max) +{ + if (after >= before) + return after - before; + return (max - before) + (after - min) + 1; +} + static void wacom_wac_pen_event(struct hid_device *hdev, struct hid_field *field, struct hid_usage *usage, __s32 value) { @@ -2551,8 +2568,11 @@ static void wacom_wac_pen_event(struct hid_device *hdev, struct hid_field *field case WACOM_HID_WD_SEQUENCENUMBER: if (wacom_wac->hid_data.sequence_number != value && wacom_wac->hid_data.sequence_number >= 0) { - int sequence_size = field->logical_maximum - field->logical_minimum + 1; - int drop_count = (value - wacom_wac->hid_data.sequence_number) % sequence_size; + int drop_count = wacom_hid_wrapped_dist( + value, + wacom_wac->hid_data.sequence_number, + field->logical_minimum, + field->logical_maximum); hid_warn(hdev, "Dropped %d packets", drop_count); } wacom_wac->hid_data.sequence_number = value + 1; @@ -4414,7 +4434,7 @@ int wacom_setup_pad_input_capabilities(struct input_dev *input_dev, break; case HID_GENERIC: - if (wacom_wac->shared) { + if (wacom_wac->shared && wacom_wac->has_mute_touch_switch) { /* * The setup of touch switch capability can only be done * here for those devices, such as Cintiq Pro 13 and 16, @@ -4425,11 +4445,12 @@ int wacom_setup_pad_input_capabilities(struct input_dev *input_dev, * stylus first or touch first. This path covers the touch * input first case. */ - if (wacom_wac->has_mute_touch_switch && - wacom_wac->shared->touch_input) { - input_set_capability(wacom_wac->shared->touch_input, - EV_SW, SW_MUTE_DEVICE); - } + struct input_dev *touch_input; + + guard(rcu)(); + touch_input = rcu_dereference(wacom_wac->shared->touch_input); + if (touch_input) + input_set_capability(touch_input, EV_SW, SW_MUTE_DEVICE); } break; diff --git a/drivers/hwmon/ads7871.c b/drivers/hwmon/ads7871.c index 36297bc6d047eb..a1ffc35d9272f9 100644 --- a/drivers/hwmon/ads7871.c +++ b/drivers/hwmon/ads7871.c @@ -187,7 +187,9 @@ static int ads7871_probe(struct spi_device *spi) /* Configure the SPI bus */ spi->mode = (SPI_MODE_0); spi->bits_per_word = 8; - spi_setup(spi); + ret = spi_setup(spi); + if (ret) + return ret; pdata = devm_kzalloc_obj(dev, *pdata); if (!pdata) diff --git a/drivers/hwmon/aquacomputer_d5next.c b/drivers/hwmon/aquacomputer_d5next.c index f521a6142a1326..884b5cf80fde6e 100644 --- a/drivers/hwmon/aquacomputer_d5next.c +++ b/drivers/hwmon/aquacomputer_d5next.c @@ -1575,9 +1575,10 @@ static int aqc_probe(struct hid_device *hdev, const struct hid_device_id *id) * * The difference between "aquaero Device" and the other two is in the collections * they present. The two other devices have the type of the second element in - * their respective collections set to 1, while the real device has it set to 0. + * their respective collections set to 1, while the real device either presents + * a single collection or has the type of the second element set to 0. */ - if (hdev->maxcollection < 2 || hdev->collection[1].type != 0) { + if (hdev->maxcollection > 1 && hdev->collection[1].type != 0) { ret = -ENODEV; goto fail_and_close; } diff --git a/drivers/hwmon/cgbc-hwmon.c b/drivers/hwmon/cgbc-hwmon.c index ba21ed8f0ceaf3..d1f20db4b28924 100644 --- a/drivers/hwmon/cgbc-hwmon.c +++ b/drivers/hwmon/cgbc-hwmon.c @@ -336,3 +336,4 @@ module_platform_driver(cgbc_hwmon_driver); MODULE_AUTHOR("Thomas Richard "); MODULE_DESCRIPTION("Congatec Board Controller Hardware Monitoring Driver"); MODULE_LICENSE("GPL"); +MODULE_ALIAS("platform:cgbc-hwmon"); diff --git a/drivers/hwmon/dell-smm-hwmon.c b/drivers/hwmon/dell-smm-hwmon.c index 5ec487843faaa8..5963f908972fb1 100644 --- a/drivers/hwmon/dell-smm-hwmon.c +++ b/drivers/hwmon/dell-smm-hwmon.c @@ -1030,6 +1030,9 @@ static int dell_smm_write(struct device *dev, enum hwmon_sensor_types type, u32 case hwmon_pwm: switch (attr) { case hwmon_pwm_input: + if (val < 0 || val > 255) + return -EINVAL; + pwm = clamp_val(DIV_ROUND_CLOSEST(val, data->i8k_pwm_mult), 0, data->i8k_fan_max); @@ -1248,6 +1251,12 @@ static int dell_smm_init_data(struct device *dev, const struct dell_smm_ops *ops return -EINVAL; } data->i8k_fan_max = fan_max ? : I8K_FAN_HIGH; + /* The BIOS takes the fan state in a single byte */ + if (data->i8k_fan_max > U8_MAX) { + dev_err(dev, "maximum fan state %u is too large (max %u)\n", + data->i8k_fan_max, U8_MAX); + return -EINVAL; + } data->i8k_pwm_mult = DIV_ROUND_UP(255, data->i8k_fan_max); return 0; diff --git a/drivers/hwmon/hwmon.c b/drivers/hwmon/hwmon.c index 73a818806d3d2c..6cfcdb9f60b779 100644 --- a/drivers/hwmon/hwmon.c +++ b/drivers/hwmon/hwmon.c @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -37,6 +38,7 @@ struct hwmon_device { const char *label; struct device dev; const struct hwmon_chip_info *chip; + struct lock_class_key lock_key; struct mutex lock; struct list_head tzdata; struct attribute_group group; @@ -136,6 +138,8 @@ static void hwmon_dev_release(struct device *dev) hwmon_free_attrs(hwdev->group.attrs_const); kfree(hwdev->groups); kfree(hwdev->label); + mutex_destroy(&hwdev->lock); + lockdep_unregister_key(&hwdev->lock_key); kfree(hwdev); } @@ -939,6 +943,8 @@ __hwmon_device_register(struct device *dev, const char *name, void *drvdata, } hdev = &hwdev->dev; + lockdep_register_key(&hwdev->lock_key); + mutex_init_with_key(&hwdev->lock, &hwdev->lock_key); if (chip) { const struct attribute **attrs; @@ -993,7 +999,6 @@ __hwmon_device_register(struct device *dev, const char *name, void *drvdata, tdev = tdev->parent; hdev->of_node = tdev ? tdev->of_node : NULL; hwdev->chip = chip; - mutex_init(&hwdev->lock); dev_set_drvdata(hdev, drvdata); dev_set_name(hdev, HWMON_ID_FORMAT, id); err = device_register(hdev); diff --git a/drivers/hwmon/nct6775-core.c b/drivers/hwmon/nct6775-core.c index 3515a962adac85..6e00318c47fdb8 100644 --- a/drivers/hwmon/nct6775-core.c +++ b/drivers/hwmon/nct6775-core.c @@ -1455,10 +1455,10 @@ static int nct6775_update_pwm(struct device *dev) if (!data->temp_tolerance[0][i] || data->pwm_enable[i] != speed_cruise) - data->temp_tolerance[0][i] = fanmodecfg & 0x0f; + data->temp_tolerance[0][i] = fanmodecfg & data->tolerance_mask; if (!data->target_speed_tolerance[i] || data->pwm_enable[i] == speed_cruise) { - u8 t = fanmodecfg & 0x0f; + u8 t = fanmodecfg & data->tolerance_mask; if (data->REG_TOLERANCE_H) { err = nct6775_read_value(data, data->REG_TOLERANCE_H[i], ®); @@ -1857,7 +1857,7 @@ EXPORT_SYMBOL_GPL(nct6775_show_beep); ssize_t nct6775_store_beep(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { - struct sensor_device_attribute_2 *sattr = to_sensor_dev_attr_2(attr); + struct sensor_device_attribute *sattr = to_sensor_dev_attr(attr); struct nct6775_data *data = dev_get_drvdata(dev); int nr = data->BEEP_BITS[sattr->index]; int regindex = nr >> 3; @@ -1911,7 +1911,7 @@ static ssize_t store_temp_beep(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { - struct sensor_device_attribute_2 *sattr = to_sensor_dev_attr_2(attr); + struct sensor_device_attribute *sattr = to_sensor_dev_attr(attr); struct nct6775_data *data = dev_get_drvdata(dev); int nr, bit, regindex; unsigned long val; @@ -2997,7 +2997,7 @@ store_temp_tolerance(struct device *dev, struct device_attribute *attr, mutex_lock(&data->update_lock); data->temp_tolerance[index][nr] = val; - if (index) + if (!index) err = pwm_update_registers(data, nr); else err = nct6775_write_value(data, data->REG_CRITICAL_TEMP_TOLERANCE[nr], val); @@ -3572,6 +3572,9 @@ int nct6775_probe(struct device *dev, struct nct6775_data *data, data->fan_from_reg = fan_from_reg13; data->fan_from_reg_min = fan_from_reg13; + data->target_temp_mask = 0xff; + data->tolerance_mask = 0x07; + data->speed_tolerance_limit = 63; data->temp_label = nct6776_temp_label; data->temp_mask = NCT6776_TEMP_MASK; @@ -3648,6 +3651,9 @@ int nct6775_probe(struct device *dev, struct nct6775_data *data, data->fan_from_reg = fan_from_reg13; data->fan_from_reg_min = fan_from_reg13; + data->target_temp_mask = 0xff; + data->tolerance_mask = 0x07; + data->speed_tolerance_limit = 63; data->temp_label = nct6776_temp_label; data->temp_mask = NCT6776_TEMP_MASK; @@ -3725,6 +3731,9 @@ int nct6775_probe(struct device *dev, struct nct6775_data *data, data->fan_from_reg = fan_from_reg13; data->fan_from_reg_min = fan_from_reg13; + data->target_temp_mask = 0xff; + data->tolerance_mask = 0x07; + data->speed_tolerance_limit = 63; data->temp_label = nct6776_temp_label; data->temp_mask = NCT6776_TEMP_MASK; diff --git a/drivers/hwmon/pmbus/ltc2978.c b/drivers/hwmon/pmbus/ltc2978.c index 58c83d4f398daf..bd58f786693bf6 100644 --- a/drivers/hwmon/pmbus/ltc2978.c +++ b/drivers/hwmon/pmbus/ltc2978.c @@ -136,9 +136,11 @@ struct ltc2978_data { #define FEAT_CLEAR_PEAKS BIT(0) #define FEAT_NEEDS_POLLING BIT(1) +#define FEAT_IEEE754 BIT(2) #define has_clear_peaks(d) ((d)->features & FEAT_CLEAR_PEAKS) #define needs_polling(d) ((d)->features & FEAT_NEEDS_POLLING) +#define has_ieee754(d) ((d)->features & FEAT_IEEE754) static int ltc_wait_ready(struct i2c_client *client) { @@ -236,6 +238,30 @@ static inline int lin11_to_val(int data) return (e < 0 ? m >> -e : m << e); } +static inline int ieee754_sort_key(u16 h) +{ + int mag = h & 0x7fff; + + return (h & 0x8000) ? -mag : mag; +} + +static bool ltc_peak_gt(struct ltc2978_data *data, u16 a, u16 b) +{ + if (has_ieee754(data)) + return ieee754_sort_key(a) > ieee754_sort_key(b); + return lin11_to_val(a) > lin11_to_val(b); +} + +static u16 ltc_peak_max_init(struct ltc2978_data *data) +{ + return has_ieee754(data) ? 0xfc00 : 0x7c00; +} + +static u16 ltc_peak_min_init(struct ltc2978_data *data) +{ + return has_ieee754(data) ? 0x7c00 : 0x7bff; +} + static int ltc_get_max(struct ltc2978_data *data, struct i2c_client *client, int page, int reg, u16 *pmax) { @@ -243,7 +269,7 @@ static int ltc_get_max(struct ltc2978_data *data, struct i2c_client *client, ret = ltc_read_word_data(client, page, 0xff, reg); if (ret >= 0) { - if (lin11_to_val(ret) > lin11_to_val(*pmax)) + if (ltc_peak_gt(data, ret, *pmax)) *pmax = ret; ret = *pmax; } @@ -257,7 +283,7 @@ static int ltc_get_min(struct ltc2978_data *data, struct i2c_client *client, ret = ltc_read_word_data(client, page, 0xff, reg); if (ret >= 0) { - if (lin11_to_val(ret) < lin11_to_val(*pmin)) + if (ltc_peak_gt(data, *pmin, ret)) *pmin = ret; ret = *pmin; } @@ -494,22 +520,22 @@ static int ltc2978_write_word_data(struct i2c_client *client, int page, switch (reg) { case PMBUS_VIRT_RESET_IIN_HISTORY: - data->iin_max = 0x7c00; - data->iin_min = 0x7bff; + data->iin_max = ltc_peak_max_init(data); + data->iin_min = ltc_peak_min_init(data); ret = ltc2978_clear_peaks(data, client, 0); break; case PMBUS_VIRT_RESET_PIN_HISTORY: - data->pin_max = 0x7c00; - data->pin_min = 0x7bff; + data->pin_max = ltc_peak_max_init(data); + data->pin_min = ltc_peak_min_init(data); ret = ltc2978_clear_peaks(data, client, 0); break; case PMBUS_VIRT_RESET_IOUT_HISTORY: - data->iout_max[page] = 0x7c00; - data->iout_min[page] = 0xfbff; + data->iout_max[page] = ltc_peak_max_init(data); + data->iout_min[page] = has_ieee754(data) ? 0x7c00 : 0xfbff; ret = ltc2978_clear_peaks(data, client, page); break; case PMBUS_VIRT_RESET_TEMP2_HISTORY: - data->temp2_max = 0x7c00; + data->temp2_max = ltc_peak_max_init(data); ret = ltc2978_clear_peaks(data, client, page); break; case PMBUS_VIRT_RESET_VOUT_HISTORY: @@ -518,13 +544,13 @@ static int ltc2978_write_word_data(struct i2c_client *client, int page, ret = ltc2978_clear_peaks(data, client, page); break; case PMBUS_VIRT_RESET_VIN_HISTORY: - data->vin_min = 0x7bff; - data->vin_max = 0x7c00; + data->vin_min = ltc_peak_min_init(data); + data->vin_max = ltc_peak_max_init(data); ret = ltc2978_clear_peaks(data, client, page); break; case PMBUS_VIRT_RESET_TEMP_HISTORY: - data->temp_min[page] = 0x7bff; - data->temp_max[page] = 0x7c00; + data->temp_min[page] = ltc_peak_min_init(data); + data->temp_max[page] = ltc_peak_max_init(data); ret = ltc2978_clear_peaks(data, client, page); break; default: @@ -761,7 +787,19 @@ static int ltc2978_probe(struct i2c_client *client) switch (data->id) { case lt7170: case lt7171: - data->features |= FEAT_CLEAR_PEAKS | FEAT_NEEDS_POLLING; + data->features |= FEAT_CLEAR_PEAKS | FEAT_NEEDS_POLLING | + FEAT_IEEE754; + data->vin_max = ltc_peak_max_init(data); + for (i = 0; i < ARRAY_SIZE(data->iout_max); i++) + data->iout_max[i] = ltc_peak_max_init(data); + for (i = 0; i < ARRAY_SIZE(data->temp_max); i++) + data->temp_max[i] = ltc_peak_max_init(data); + data->temp2_max = ltc_peak_max_init(data); + data->vin_min = ltc_peak_min_init(data); + for (i = 0; i < ARRAY_SIZE(data->iout_min); i++) + data->iout_min[i] = 0x7c00; + for (i = 0; i < ARRAY_SIZE(data->temp_min); i++) + data->temp_min[i] = ltc_peak_min_init(data); info->read_word_data = ltc3883_read_word_data; info->pages = LTC3883_NUM_PAGES; info->format[PSC_VOLTAGE_IN] = ieee754; diff --git a/drivers/hwmon/sht3x.c b/drivers/hwmon/sht3x.c index c217a4d0c9f18d..697b54e0ad9469 100644 --- a/drivers/hwmon/sht3x.c +++ b/drivers/hwmon/sht3x.c @@ -387,8 +387,8 @@ static size_t limit_write(struct device *dev, * adapted for fixed point arithmetic and packed the same as * in limit_read() */ - raw = ((u32)(temperature + 45000) * 24543) >> (16 + 7); - raw |= ((humidity * 42950) >> 16) & 0xfe00; + raw = min(((u64)(temperature + 45000) * 24543) >> (16 + 7), 0x1ff); + raw |= min(((u64)humidity * 42950) >> 16, 0xffff) & 0xfe00; put_unaligned_be16(raw, position); position += SHT3X_WORD_LEN; diff --git a/drivers/hwmon/w83791d.c b/drivers/hwmon/w83791d.c index 8bb457326c0bce..530935a6df7fc2 100644 --- a/drivers/hwmon/w83791d.c +++ b/drivers/hwmon/w83791d.c @@ -924,7 +924,7 @@ static struct sensor_device_attribute sda_temp_tolerance[] = { static ssize_t show_temp1(struct device *dev, struct device_attribute *devattr, char *buf) { - struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr); + struct sensor_device_attribute_2 *attr = to_sensor_dev_attr_2(devattr); struct w83791d_data *data = w83791d_update_device(dev); return sprintf(buf, "%d\n", TEMP1_FROM_REG(data->temp1[attr->index])); } @@ -932,7 +932,7 @@ static ssize_t show_temp1(struct device *dev, struct device_attribute *devattr, static ssize_t store_temp1(struct device *dev, struct device_attribute *devattr, const char *buf, size_t count) { - struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr); + struct sensor_device_attribute_2 *attr = to_sensor_dev_attr_2(devattr); struct i2c_client *client = to_i2c_client(dev); struct w83791d_data *data = i2c_get_clientdata(client); int nr = attr->index; diff --git a/drivers/hwmon/w83792d.c b/drivers/hwmon/w83792d.c index 2de6d7b685836b..cba9077134b67e 100644 --- a/drivers/hwmon/w83792d.c +++ b/drivers/hwmon/w83792d.c @@ -487,7 +487,7 @@ store_fan_div(struct device *dev, struct device_attribute *attr, static ssize_t show_temp1(struct device *dev, struct device_attribute *attr, char *buf) { - struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr); + struct sensor_device_attribute_2 *sensor_attr = to_sensor_dev_attr_2(attr); int nr = sensor_attr->index; struct w83792d_data *data = w83792d_update_device(dev); return sprintf(buf, "%d\n", TEMP1_FROM_REG(data->temp1[nr])); @@ -496,7 +496,7 @@ static ssize_t show_temp1(struct device *dev, struct device_attribute *attr, static ssize_t store_temp1(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { - struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr); + struct sensor_device_attribute_2 *sensor_attr = to_sensor_dev_attr_2(attr); int nr = sensor_attr->index; struct i2c_client *client = to_i2c_client(dev); struct w83792d_data *data = i2c_get_clientdata(client); diff --git a/drivers/hwmon/yogafan.c b/drivers/hwmon/yogafan.c index 6d1284c090487d..285bc71843525b 100644 --- a/drivers/hwmon/yogafan.c +++ b/drivers/hwmon/yogafan.c @@ -89,12 +89,6 @@ static const struct yogafan_config xiaoxin_8bit_dual_cfg = { .paths = { "\\_SB.PCI0.LPC0.EC0.FANS", "\\_SB.PCI0.LPC0.EC0.FA2S" } }; -static const struct yogafan_config yoga_pro_7_14iah10_cfg = { - .multiplier = 100, - .fan_count = 1, - .paths = { "\\_SB.PC00.LPCB.EC0.FANS", NULL } -}; - /* * Lenovo Yoga Pro 9 16IMH9 (83DN) uses the PC00 namespace and has two * 8-bit fan tachometer fields. @@ -267,7 +261,7 @@ static const struct dmi_system_id yogafan_quirks[] = { DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"), DMI_MATCH(DMI_PRODUCT_FAMILY, "Yoga Pro 7 14IAH10"), }, - .driver_data = (void *)&yoga_pro_7_14iah10_cfg, + .driver_data = (void *)&loq_15iax9_8bit_dual_cfg, }, { .ident = "Lenovo Yoga 7 16ARP8", diff --git a/drivers/iio/accel/Kconfig b/drivers/iio/accel/Kconfig index 141ac984247cdd..c6fce69ac4703c 100644 --- a/drivers/iio/accel/Kconfig +++ b/drivers/iio/accel/Kconfig @@ -33,6 +33,8 @@ config ADIS16209 config ADXL313 tristate + select IIO_BUFFER + select IIO_KFIFO_BUF config ADXL313_I2C tristate "Analog Devices ADXL313 3-Axis Digital Accelerometer I2C Driver" @@ -62,6 +64,8 @@ config ADXL313_SPI config ADXL345 tristate + select IIO_BUFFER + select IIO_KFIFO_BUF config ADXL345_I2C tristate "Analog Devices ADXL345 3-Axis Digital Accelerometer I2C Driver" diff --git a/drivers/iio/accel/adxl380.c b/drivers/iio/accel/adxl380.c index 8518ee23e11490..03b140303520d7 100644 --- a/drivers/iio/accel/adxl380.c +++ b/drivers/iio/accel/adxl380.c @@ -334,8 +334,11 @@ static int adxl380_set_act_inact_threshold(struct iio_dev *indio_dev, return ret; ret = adxl380_write_act_inact_threshold(st, act, th); - if (ret) + if (ret) { + /* Leave standby also if the value was refused */ + adxl380_set_measure_en(st, true); return ret; + } return adxl380_set_measure_en(st, true); } @@ -698,6 +701,12 @@ static int adxl380_set_range(struct adxl380_state *st, u8 range) guard(mutex)(&st->lock); + /* The thresholds are rescaled: see that they fit before any change */ + if (mult_frac(max(st->act_threshold, st->inact_threshold), + adxl380_range_scale_factor_tbl[st->range], + adxl380_range_scale_factor_tbl[range]) > ADXL380_THRESH_MAX) + return -EINVAL; + ret = adxl380_set_measure_en(st, false); if (ret) return ret; diff --git a/drivers/iio/accel/kxsd9.c b/drivers/iio/accel/kxsd9.c index 7ac885d94d7f45..27adcdd312014e 100644 --- a/drivers/iio/accel/kxsd9.c +++ b/drivers/iio/accel/kxsd9.c @@ -478,8 +478,8 @@ void kxsd9_common_remove(struct device *dev) struct iio_dev *indio_dev = dev_get_drvdata(dev); struct kxsd9_state *st = iio_priv(indio_dev); - iio_triggered_buffer_cleanup(indio_dev); iio_device_unregister(indio_dev); + iio_triggered_buffer_cleanup(indio_dev); pm_runtime_get_sync(dev); pm_runtime_put_noidle(dev); pm_runtime_disable(dev); diff --git a/drivers/iio/adc/ad7780.c b/drivers/iio/adc/ad7780.c index 1cfad70320feb5..c1428f30241c8f 100644 --- a/drivers/iio/adc/ad7780.c +++ b/drivers/iio/adc/ad7780.c @@ -311,7 +311,9 @@ static int ad7780_probe(struct spi_device *spi) st = iio_priv(indio_dev); st->gain = 1; - ad_sd_init(&st->sd, indio_dev, spi, &ad7780_sigma_delta_info); + ret = ad_sd_init(&st->sd, indio_dev, spi, &ad7780_sigma_delta_info); + if (ret) + return ret; st->chip_info = &ad7780_chip_info_tbl[spi_get_device_id(spi)->driver_data]; diff --git a/drivers/iio/adc/ad7791.c b/drivers/iio/adc/ad7791.c index c2688307bbba18..10aa40ca35e7b2 100644 --- a/drivers/iio/adc/ad7791.c +++ b/drivers/iio/adc/ad7791.c @@ -435,7 +435,9 @@ static int ad7791_probe(struct spi_device *spi) return ret; st->info = &ad7791_chip_infos[spi_get_device_id(spi)->driver_data]; - ad_sd_init(&st->sd, indio_dev, spi, &ad7791_sigma_delta_info); + ret = ad_sd_init(&st->sd, indio_dev, spi, &ad7791_sigma_delta_info); + if (ret) + return ret; indio_dev->name = spi_get_device_id(spi)->name; indio_dev->modes = INDIO_DIRECT_MODE; diff --git a/drivers/iio/adc/ad7793.c b/drivers/iio/adc/ad7793.c index b0f44c144f20e7..937c8b09ad4534 100644 --- a/drivers/iio/adc/ad7793.c +++ b/drivers/iio/adc/ad7793.c @@ -796,7 +796,9 @@ static int ad7793_probe(struct spi_device *spi) st = iio_priv(indio_dev); - ad_sd_init(&st->sd, indio_dev, spi, &ad7793_sigma_delta_info); + ret = ad_sd_init(&st->sd, indio_dev, spi, &ad7793_sigma_delta_info); + if (ret) + return ret; if (pdata->refsel != AD7793_REFSEL_INTERNAL) { ret = devm_regulator_get_enable_read_voltage(dev, "refin"); diff --git a/drivers/iio/adc/ad7923.c b/drivers/iio/adc/ad7923.c index 44e014da97222b..69fafb4aa4ea06 100644 --- a/drivers/iio/adc/ad7923.c +++ b/drivers/iio/adc/ad7923.c @@ -366,6 +366,7 @@ static const struct spi_device_id ad7923_id[] = { { .name = "ad7924", .driver_data = AD7924 }, { .name = "ad7908", .driver_data = AD7908 }, { .name = "ad7918", .driver_data = AD7918 }, + { .name = "ad7927", .driver_data = AD7928 }, { .name = "ad7928", .driver_data = AD7928 }, { } }; diff --git a/drivers/iio/adc/aspeed_adc.c b/drivers/iio/adc/aspeed_adc.c index 452c30cf04f284..085fdaffb9cd0c 100644 --- a/drivers/iio/adc/aspeed_adc.c +++ b/drivers/iio/adc/aspeed_adc.c @@ -201,18 +201,29 @@ static const struct iio_chan_spec aspeed_adc_iio_bat_channels[] = { static int aspeed_adc_set_trim_data(struct iio_dev *indio_dev) { - struct device_node *syscon; + struct device_node *np, *syscon; struct regmap *scu; u32 scu_otp, trimming_val; struct aspeed_adc_data *data = iio_priv(indio_dev); + const char *propname = "aspeed,trim-syscon"; - syscon = of_find_node_by_name(NULL, "syscon"); - if (syscon == NULL) { - dev_warn(data->dev, "Couldn't find syscon node\n"); - return -EOPNOTSUPP; + np = dev_of_node(data->dev); + if (of_property_present(np, propname)) { + scu = syscon_regmap_lookup_by_phandle(np, propname); + } else { + /* + * No "aspeed,trim-syscon" phandle: either a single-SCU SoC, + * or a DTB predating the property. Fall back to the old + * global by-name lookup for backward compatibility. + */ + syscon = of_find_node_by_name(NULL, "syscon"); + if (!syscon) { + dev_warn(data->dev, "Couldn't find syscon node\n"); + return -EOPNOTSUPP; + } + scu = syscon_node_to_regmap(syscon); + of_node_put(syscon); } - scu = syscon_node_to_regmap(syscon); - of_node_put(syscon); if (IS_ERR(scu)) { dev_warn(data->dev, "Failed to get syscon regmap\n"); return -EOPNOTSUPP; diff --git a/drivers/iio/adc/max11205.c b/drivers/iio/adc/max11205.c index 53ac2f4f383e92..e46e90400bdcb4 100644 --- a/drivers/iio/adc/max11205.c +++ b/drivers/iio/adc/max11205.c @@ -114,7 +114,9 @@ static int max11205_probe(struct spi_device *spi) st = iio_priv(indio_dev); - ad_sd_init(&st->sd, indio_dev, spi, &max11205_sigma_delta_info); + ret = ad_sd_init(&st->sd, indio_dev, spi, &max11205_sigma_delta_info); + if (ret) + return ret; st->chip_info = spi_get_device_match_data(spi); if (!st->chip_info) diff --git a/drivers/iio/adc/mcp3564.c b/drivers/iio/adc/mcp3564.c index 6d60952dd33ffb..494b5d1c13a2d3 100644 --- a/drivers/iio/adc/mcp3564.c +++ b/drivers/iio/adc/mcp3564.c @@ -1204,6 +1204,9 @@ static int mcp3564_config(struct iio_dev *indio_dev, bool *use_internal_vref_att * try using fallback compatible in device tree to deal with some newer part number. */ adc->chip_info = spi_get_device_match_data(adc->spi); + if (!adc->chip_info) + return -ENODATA; + adc->have_vref = adc->chip_info->have_vref; } else { adc->chip_info = &mcp3564_chip_infos_tbl[ids]; diff --git a/drivers/iio/adc/qcom-spmi-adc5-gen3.c b/drivers/iio/adc/qcom-spmi-adc5-gen3.c index be12bb6781cb3b..308d431e62179e 100644 --- a/drivers/iio/adc/qcom-spmi-adc5-gen3.c +++ b/drivers/iio/adc/qcom-spmi-adc5-gen3.c @@ -609,7 +609,7 @@ static void adc5_gen3_delete_aux(void *data) static void adc5_gen3_aux_device_release(struct device *dev) {} -static int adc5_gen3_add_aux_tm_device(struct adc5_chip *adc) +static int adc5_gen3_add_aux_tm_device(struct adc5_chip *adc, int id) { struct tm5_aux_dev_wrapper *aux_device; int i, ret, i_tm = 0; @@ -619,6 +619,7 @@ static int adc5_gen3_add_aux_tm_device(struct adc5_chip *adc) return -ENOMEM; aux_device->aux_dev.name = "adc5_tm_gen3"; + aux_device->aux_dev.id = id; aux_device->aux_dev.dev.parent = adc->dev; aux_device->aux_dev.dev.release = adc5_gen3_aux_device_release; @@ -796,7 +797,7 @@ static int adc5_gen3_probe(struct platform_device *pdev) return ret; if (adc->n_tm_channels > 0) { - ret = adc5_gen3_add_aux_tm_device(adc); + ret = adc5_gen3_add_aux_tm_device(adc, iio_device_id(indio_dev)); if (ret) dev_err_probe(dev, ret, "Failed to add auxiliary TM device\n"); diff --git a/drivers/iio/addac/ad74413r.c b/drivers/iio/addac/ad74413r.c index 76bad554f028a3..4120adc12e89ff 100644 --- a/drivers/iio/addac/ad74413r.c +++ b/drivers/iio/addac/ad74413r.c @@ -312,7 +312,7 @@ static int ad74413r_gpio_set_multiple(struct gpio_chip *chip, return ret; real_mask |= BIT(real_offset); - if (*bits & offset) + if (test_bit(offset, bits)) real_bits |= BIT(real_offset); } diff --git a/drivers/iio/afe/iio-rescale.c b/drivers/iio/afe/iio-rescale.c index 3a6a09ffa5267d..c01292a15a29d0 100644 --- a/drivers/iio/afe/iio-rescale.c +++ b/drivers/iio/afe/iio-rescale.c @@ -303,7 +303,8 @@ static int rescale_configure_channel(struct device *dev, chan->info_mask_separate = BIT(IIO_CHAN_INFO_RAW) | BIT(IIO_CHAN_INFO_SCALE); - if (rescale->offset) + if (rescale->offset || + iio_channel_has_info(schan, IIO_CHAN_INFO_OFFSET)) chan->info_mask_separate |= BIT(IIO_CHAN_INFO_OFFSET); /* diff --git a/drivers/iio/chemical/atlas-ezo-sensor.c b/drivers/iio/chemical/atlas-ezo-sensor.c index 298b2fe48a19c5..abe26ba212f598 100644 --- a/drivers/iio/chemical/atlas-ezo-sensor.c +++ b/drivers/iio/chemical/atlas-ezo-sensor.c @@ -116,9 +116,6 @@ static int atlas_ezo_read_raw(struct iio_dev *indio_dev, struct atlas_ezo_data *data = iio_priv(indio_dev); struct i2c_client *client = data->client; - if (chan->type != IIO_CONCENTRATION) - return -EINVAL; - switch (mask) { case IIO_CHAN_INFO_RAW: { int ret; diff --git a/drivers/iio/common/cros_ec_sensors/cros_ec_sensors.c b/drivers/iio/common/cros_ec_sensors/cros_ec_sensors.c index 551b86236abcca..2839714f5bc8e5 100644 --- a/drivers/iio/common/cros_ec_sensors/cros_ec_sensors.c +++ b/drivers/iio/common/cros_ec_sensors/cros_ec_sensors.c @@ -70,7 +70,7 @@ static int cros_ec_sensors_read(struct iio_dev *indio_dev, break; case IIO_CHAN_INFO_CALIBSCALE: st->core.param.cmd = MOTIONSENSE_CMD_SENSOR_SCALE; - st->core.param.sensor_offset.flags = 0; + st->core.param.sensor_scale.flags = 0; ret = cros_ec_motion_send_host_cmd(&st->core, 0); if (ret == -EPROTO || ret == -EOPNOTSUPP) { @@ -178,8 +178,7 @@ static int cros_ec_sensors_write(struct iio_dev *indio_dev, /* Send to EC for each axis, even if not complete */ st->core.param.cmd = MOTIONSENSE_CMD_SENSOR_SCALE; - st->core.param.sensor_offset.flags = - MOTION_SENSE_SET_OFFSET; + st->core.param.sensor_scale.flags = MOTION_SENSE_SET_OFFSET; for (i = CROS_EC_SENSOR_X; i < CROS_EC_SENSOR_MAX_AXIS; i++) st->core.param.sensor_scale.scale[i] = st->core.calib[i].scale; diff --git a/drivers/iio/common/hid-sensors/hid-sensor-attributes.c b/drivers/iio/common/hid-sensors/hid-sensor-attributes.c index 9e7c26e37880aa..cb7713646e2152 100644 --- a/drivers/iio/common/hid-sensors/hid-sensor-attributes.c +++ b/drivers/iio/common/hid-sensors/hid-sensor-attributes.c @@ -38,6 +38,8 @@ static const struct { {HID_USAGE_SENSOR_COMPASS_3D, 0, 0, 1000000}, {HID_USAGE_SENSOR_COMPASS_3D, HID_USAGE_SENSOR_UNITS_GAUSS, 1, 0}, + {HID_USAGE_SENSOR_ORIENT_COMP_MAGN_NORTH, 0, 1, 0}, + {HID_USAGE_SENSOR_INCLINOMETER_3D, 0, 0, 17453293}, {HID_USAGE_SENSOR_INCLINOMETER_3D, HID_USAGE_SENSOR_UNITS_DEGREES, 0, 17453293}, @@ -96,9 +98,14 @@ static void simple_div(int dividend, int divisor, int *whole, int *micro_frac) static void split_micro_fraction(unsigned int no, int exp, int *val1, int *val2) { int divisor = int_pow(10, exp); + unsigned int rem; *val1 = no / divisor; - *val2 = no % divisor * int_pow(10, 6 - exp); + rem = no % divisor; + if (exp > 6) + *val2 = rem / (unsigned int)int_pow(10, exp - 6); + else + *val2 = rem * int_pow(10, 6 - exp); } /* @@ -140,7 +147,10 @@ static u32 convert_to_vtf_format(int size, int exp, int val1, int val2) if (val1 < 0 || val2 < 0) sign = -1; exp = hid_sensor_convert_exponent(exp); - if (exp < 0) { + if (exp < -6) { + value = abs(val1) * int_pow(10, -exp); + value += abs(val2) * int_pow(10, -exp - 6); + } else if (exp < 0) { divisor = int_pow(10, 6 + exp); value = abs(val1) * int_pow(10, -exp); value += abs(val2) / divisor; diff --git a/drivers/iio/common/inv_sensors/inv_sensors_timestamp.c b/drivers/iio/common/inv_sensors/inv_sensors_timestamp.c index 8c9e81a77e6887..b3a784d3e67d74 100644 --- a/drivers/iio/common/inv_sensors/inv_sensors_timestamp.c +++ b/drivers/iio/common/inv_sensors/inv_sensors_timestamp.c @@ -133,15 +133,26 @@ void inv_sensors_timestamp_interrupt(struct inv_sensors_timestamp *ts, return; /* no previous data, compute theoretical value from interrupt */ - if (ts->timestamp == 0) { + if (!ts->init) { /* elapsed time: sensor period * sensor samples number */ interval = (s64)ts->period * (s64)sample_nb; - ts->timestamp = timestamp - interval; + delta = timestamp - interval; + /* prevent next timestamp to be lower than the last one */ + if ((delta + ts->period) > ts->timestamp) + ts->timestamp = delta; + ts->init = true; + } /* update delta timestamps and estimated period */ it = &ts->delta; ts->delta_counter += sample_nb; + /* reset in case of odr change */ + if (ts->new_mult) { + it->lo = 0; + it->up = 0; + ts->delta_counter = 0; + } delta = timestamp - it->up; delta_threshold = INV_SENSORS_TIMESTAMP_MIN(INV_SENSORS_MIN_IT_DELTA, ts->chip.jitter); if (delta >= delta_threshold) { @@ -161,7 +172,7 @@ void inv_sensors_timestamp_interrupt(struct inv_sensors_timestamp *ts, it->lo = it->up; it->up = timestamp; delta = it->up - it->lo; - if (it->lo != 0) { + if (it->lo != 0 && !ts->new_mult) { /* compute period and check validity */ period = div_s64(delta, sample_nb); valid = inv_validate_period(ts, period); @@ -184,7 +195,7 @@ void inv_sensors_timestamp_apply_odr(struct inv_sensors_timestamp *ts, u32 fifo_period, size_t fifo_nb, unsigned int fifo_no) { - s64 interval; + s64 interval, timestamp; u32 fifo_mult; if (ts->new_mult == 0) @@ -207,7 +218,10 @@ void inv_sensors_timestamp_apply_odr(struct inv_sensors_timestamp *ts, fifo_period = fifo_mult * ts->chip_period.val; /* computes time interval between interrupt and this sample */ interval = (s64)(fifo_nb - fifo_no) * (s64)fifo_period; - ts->timestamp = ts->it.up - interval; + timestamp = ts->it.up - interval; + /* prevent next timestamp to be lower than current one */ + if ((timestamp + ts->period) > ts->timestamp) + ts->timestamp = timestamp; } } EXPORT_SYMBOL_NS_GPL(inv_sensors_timestamp_apply_odr, "IIO_INV_SENSORS_TIMESTAMP"); diff --git a/drivers/iio/common/scmi_sensors/scmi_iio.c b/drivers/iio/common/scmi_sensors/scmi_iio.c index 5222c2dce7d5a3..eac8a613dd534d 100644 --- a/drivers/iio/common/scmi_sensors/scmi_iio.c +++ b/drivers/iio/common/scmi_sensors/scmi_iio.c @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -70,8 +71,7 @@ static int scmi_iio_sensor_update_cb(struct notifier_block *nb, */ tstamp_scale = sensor->sensor_info->tstamp_scale + 9; if (tstamp_scale < 0) { - do_div(time, int_pow(10, abs(tstamp_scale))); - time_ns = time; + time_ns = div64_u64(time, int_pow(10, abs(tstamp_scale))); } else { time_ns = time * int_pow(10, tstamp_scale); } @@ -162,7 +162,7 @@ static int scmi_iio_set_odr_val(struct iio_dev *iio_dev, int val, int val2) mult = scnprintf(buf, sizeof(buf), "%llu", sf) - 1; sec = int_pow(10, mult) * MICROHZ_PER_HZ; - do_div(sec, uHz); + sec = div64_u64(sec, uHz); if (sec == 0) { dev_err(&iio_dev->dev, "Trying to set invalid sensor update value for sensor %s", @@ -237,13 +237,10 @@ static int scmi_iio_read_avail(struct iio_dev *iio_dev, static void convert_ns_to_freq(u64 interval_ns, u64 *hz, u64 *uhz) { - u64 rem, freq; + u64 rem; - freq = NSEC_PER_SEC; - rem = do_div(freq, interval_ns); - *hz = freq; - *uhz = rem * 1000000UL; - do_div(*uhz, interval_ns); + *hz = div64_u64_rem(HZ_PER_GHZ, interval_ns, &rem); + *uhz = div64_u64(rem * MICROHZ_PER_HZ, interval_ns); } static int scmi_iio_get_odr_val(struct iio_dev *iio_dev, int *val, int *val2) @@ -269,7 +266,8 @@ static int scmi_iio_get_odr_val(struct iio_dev *iio_dev, int *val, int *val2) mult = SCMI_SENS_CFG_GET_UPDATE_EXP(sensor_config); if (mult < 0) { sensor_interval_mult = int_pow(10, abs(mult)); - do_div(sensor_update_interval, sensor_interval_mult); + sensor_update_interval = div64_u64(sensor_update_interval, + sensor_interval_mult); } else { sensor_interval_mult = int_pow(10, mult); sensor_update_interval = @@ -395,9 +393,9 @@ static ssize_t scmi_iio_get_raw_available(struct iio_dev *iio_dev, */ exponent = exponent - scale; if (exponent < 0) { - rem = do_div(resolution, - int_pow(10, abs(exponent)) - ); + resolution = div64_u64_rem(resolution, + int_pow(10, abs(exponent)), + &rem); len = sysfs_emit(buf, "[%lld %llu.%llu %lld]\n", min_range, resolution, rem, max_range); @@ -491,7 +489,8 @@ static u64 scmi_iio_convert_interval_to_ns(u32 val) mult = SCMI_SENS_INTVL_GET_EXP(val); if (mult < 0) { sensor_interval_mult = int_pow(10, abs(mult)); - do_div(sensor_update_interval, sensor_interval_mult); + sensor_update_interval = div64_u64(sensor_update_interval, + sensor_interval_mult); } else { sensor_interval_mult = int_pow(10, mult); sensor_update_interval = diff --git a/drivers/iio/dac/ad5758.c b/drivers/iio/dac/ad5758.c index 1e21ad2a050dbe..4c15447ccb6bfb 100644 --- a/drivers/iio/dac/ad5758.c +++ b/drivers/iio/dac/ad5758.c @@ -141,7 +141,7 @@ enum ad5758_output_range { AD5758_RANGE_PLUSMINUS_10V, AD5758_RANGE_0mA_20mA = 8, AD5758_RANGE_0mA_24mA, - AD5758_RANGE_4mA_24mA, + AD5758_RANGE_4mA_20mA, AD5758_RANGE_PLUSMINUS_20mA, AD5758_RANGE_PLUSMINUS_24mA, AD5758_RANGE_MINUS_1mA_PLUS_22mA, @@ -164,7 +164,7 @@ static const struct ad5758_range ad5758_voltage_range[] = { static const struct ad5758_range ad5758_current_range[] = { { AD5758_RANGE_0mA_20mA, 0, 20000}, { AD5758_RANGE_0mA_24mA, 0, 24000 }, - { AD5758_RANGE_4mA_24mA, 4, 24000 }, + { AD5758_RANGE_4mA_20mA, 4000, 20000 }, { AD5758_RANGE_PLUSMINUS_20mA, -20000, 20000 }, { AD5758_RANGE_PLUSMINUS_24mA, -24000, 24000 }, { AD5758_RANGE_MINUS_1mA_PLUS_22mA, -1000, 22000 }, diff --git a/drivers/iio/dac/mcp4725.c b/drivers/iio/dac/mcp4725.c index 3fa7acc69aeb6b..94d51af83042ff 100644 --- a/drivers/iio/dac/mcp4725.c +++ b/drivers/iio/dac/mcp4725.c @@ -356,6 +356,8 @@ static int mcp4725_write_raw(struct iio_dev *indio_dev, switch (mask) { case IIO_CHAN_INFO_RAW: ret = mcp4725_set_value(indio_dev, val); + if (ret) + return ret; data->dac_value = val; break; default: diff --git a/drivers/iio/dac/mcp47feb02-core.c b/drivers/iio/dac/mcp47feb02-core.c index c5392df029c346..30c23df6294e23 100644 --- a/drivers/iio/dac/mcp47feb02-core.c +++ b/drivers/iio/dac/mcp47feb02-core.c @@ -696,6 +696,9 @@ static int mcp47feb02_write_raw(struct iio_dev *indio_dev, struct iio_chan_spec switch (mask) { case IIO_CHAN_INFO_RAW: + if (val < 0 || val > GENMASK(data->chip_features->resolution - 1, 0)) + return -EINVAL; + ret = regmap_write(data->regmap, REG_ADDR(ch->address), val); if (ret) return ret; diff --git a/drivers/iio/gyro/bmg160_core.c b/drivers/iio/gyro/bmg160_core.c index b007f46d3fd624..0958b7d31a9281 100644 --- a/drivers/iio/gyro/bmg160_core.c +++ b/drivers/iio/gyro/bmg160_core.c @@ -761,7 +761,7 @@ static int bmg160_write_event_config(struct iio_dev *indio_dev, struct bmg160_data *data = iio_priv(indio_dev); int ret; - if (state && data->ev_enable_state) + if (state == data->ev_enable_state) return 0; mutex_lock(&data->mutex); diff --git a/drivers/iio/humidity/am2315.c b/drivers/iio/humidity/am2315.c index 5c7582f3a4f94f..8cf7e4e176a971 100644 --- a/drivers/iio/humidity/am2315.c +++ b/drivers/iio/humidity/am2315.c @@ -123,6 +123,7 @@ static int am2315_read_data(struct am2315_data *data, */ u8 rx_buf[8]; u16 crc; + u16 temp_raw; /* First wake up the device. */ am2315_ping(data->client); @@ -154,8 +155,15 @@ static int am2315_read_data(struct am2315_data *data, sensor_data->hum_data = (rx_buf[AM2315_HUM_OFFSET] << 8) | rx_buf[AM2315_HUM_OFFSET + 1]; - sensor_data->temp_data = (rx_buf[AM2315_TEMP_OFFSET] << 8) | - rx_buf[AM2315_TEMP_OFFSET + 1]; + + /* + * Temperature is sign-magnitude, not two's complement: + * bit 15 is the sign, bits 14-0 are the magnitude (x0.1 degC). + */ + temp_raw = (rx_buf[AM2315_TEMP_OFFSET] << 8) | + rx_buf[AM2315_TEMP_OFFSET + 1]; + sensor_data->temp_data = (temp_raw & 0x8000) ? + -(temp_raw & 0x7fff) : temp_raw; return ret; diff --git a/drivers/iio/humidity/hid-sensor-humidity.c b/drivers/iio/humidity/hid-sensor-humidity.c index 7cec81ff56856f..aa7d4f25c3937d 100644 --- a/drivers/iio/humidity/hid-sensor-humidity.c +++ b/drivers/iio/humidity/hid-sensor-humidity.c @@ -15,6 +15,7 @@ struct hid_humidity_state { struct hid_sensor_common common_attributes; struct hid_sensor_hub_attribute_info humidity_attr; + struct hid_sensor_hub_callbacks callbacks; struct { s32 humidity_data; aligned_s64 timestamp; @@ -184,11 +185,6 @@ static int humidity_parse_report(struct platform_device *pdev, return ret; } -static struct hid_sensor_hub_callbacks humidity_callbacks = { - .send_event = &humidity_proc_event, - .capture_sample = &humidity_capture_sample, -}; - /* Function to initialize the processing for usage id */ static int hid_humidity_probe(struct platform_device *pdev) { @@ -240,9 +236,13 @@ static int hid_humidity_probe(struct platform_device *pdev) platform_set_drvdata(pdev, indio_dev); - humidity_callbacks.pdev = pdev; + humid_st->callbacks = (struct hid_sensor_hub_callbacks) { + .send_event = humidity_proc_event, + .capture_sample = humidity_capture_sample, + .pdev = pdev, + }; ret = sensor_hub_register_callback(hsdev, HID_USAGE_SENSOR_HUMIDITY, - &humidity_callbacks); + &humid_st->callbacks); if (ret) goto error_remove_trigger; diff --git a/drivers/iio/imu/inv_icm42600/inv_icm42600_buffer.c b/drivers/iio/imu/inv_icm42600/inv_icm42600_buffer.c index 2bf9fc29d7d296..5bff2a3a44bcf5 100644 --- a/drivers/iio/imu/inv_icm42600/inv_icm42600_buffer.c +++ b/drivers/iio/imu/inv_icm42600/inv_icm42600_buffer.c @@ -532,22 +532,20 @@ int inv_icm42600_buffer_fifo_parse(struct inv_icm42600_state *st) ts = &gyro_st->ts; inv_sensors_timestamp_interrupt(ts, st->fifo.watermark.eff_gyro, st->timestamp.gyro); - ret = inv_icm42600_gyro_parse_fifo(st->indio_gyro); - if (ret) - return ret; } + ret = inv_icm42600_gyro_parse_fifo(st->indio_gyro); + if (ret) + return ret; + /* handle accelerometer timestamp and FIFO data parsing */ if (st->fifo.nb.accel > 0) { ts = &accel_st->ts; inv_sensors_timestamp_interrupt(ts, st->fifo.watermark.eff_accel, st->timestamp.accel); - ret = inv_icm42600_accel_parse_fifo(st->indio_accel); - if (ret) - return ret; } - return 0; + return inv_icm42600_accel_parse_fifo(st->indio_accel); } int inv_icm42600_buffer_hwfifo_flush(struct inv_icm42600_state *st, @@ -572,20 +570,18 @@ int inv_icm42600_buffer_hwfifo_flush(struct inv_icm42600_state *st, if (st->fifo.nb.gyro > 0) { ts = &gyro_st->ts; inv_sensors_timestamp_interrupt(ts, st->fifo.nb.gyro, gyro_ts); - ret = inv_icm42600_gyro_parse_fifo(st->indio_gyro); - if (ret) - return ret; } + ret = inv_icm42600_gyro_parse_fifo(st->indio_gyro); + if (ret) + return ret; + if (st->fifo.nb.accel > 0) { ts = &accel_st->ts; inv_sensors_timestamp_interrupt(ts, st->fifo.nb.accel, accel_ts); - ret = inv_icm42600_accel_parse_fifo(st->indio_accel); - if (ret) - return ret; } - return 0; + return inv_icm42600_accel_parse_fifo(st->indio_accel); } int inv_icm42600_buffer_init(struct inv_icm42600_state *st) diff --git a/drivers/iio/imu/inv_mpu6050/inv_mpu_core.c b/drivers/iio/imu/inv_mpu6050/inv_mpu_core.c index 38c3f3b398d4f8..7265a3c3de0582 100644 --- a/drivers/iio/imu/inv_mpu6050/inv_mpu_core.c +++ b/drivers/iio/imu/inv_mpu6050/inv_mpu_core.c @@ -150,7 +150,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6050, .fifo_size = 1024, .temp = {INV_MPU6050_TEMP_OFFSET, INV_MPU6050_TEMP_SCALE}, - .startup_time = {INV_MPU6050_GYRO_STARTUP_TIME, INV_MPU6050_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6050_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6050_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_MPU6500_WHOAMI_VALUE, @@ -159,7 +162,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_MPU6500_TEMP_OFFSET, INV_MPU6500_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_MPU6515_WHOAMI_VALUE, @@ -168,7 +174,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_MPU6500_TEMP_OFFSET, INV_MPU6500_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_MPU6880_WHOAMI_VALUE, @@ -177,7 +186,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 4096, .temp = {INV_MPU6500_TEMP_OFFSET, INV_MPU6500_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_MPU6000_WHOAMI_VALUE, @@ -186,7 +198,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6050, .fifo_size = 1024, .temp = {INV_MPU6050_TEMP_OFFSET, INV_MPU6050_TEMP_SCALE}, - .startup_time = {INV_MPU6050_GYRO_STARTUP_TIME, INV_MPU6050_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6050_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6050_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_MPU9150_WHOAMI_VALUE, @@ -195,7 +210,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6050, .fifo_size = 1024, .temp = {INV_MPU6050_TEMP_OFFSET, INV_MPU6050_TEMP_SCALE}, - .startup_time = {INV_MPU6050_GYRO_STARTUP_TIME, INV_MPU6050_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6050_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6050_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_MPU9250_WHOAMI_VALUE, @@ -204,7 +222,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_MPU6500_TEMP_OFFSET, INV_MPU6500_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_MPU9255_WHOAMI_VALUE, @@ -213,7 +234,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_MPU6500_TEMP_OFFSET, INV_MPU6500_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_ICM20608_WHOAMI_VALUE, @@ -222,7 +246,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_ICM20608D_WHOAMI_VALUE, @@ -231,7 +258,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_ICM20609_WHOAMI_VALUE, @@ -240,7 +270,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 4 * 1024, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_ICM20689_WHOAMI_VALUE, @@ -249,7 +282,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 4 * 1024, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_ICM20600_WHOAMI_VALUE, @@ -258,7 +294,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 1008, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_ICM20602_GYRO_STARTUP_TIME, INV_ICM20602_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_ICM20602_ACCEL_STARTUP_TIME, + .gyro = INV_ICM20602_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_ICM20602_WHOAMI_VALUE, @@ -267,7 +306,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 1008, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_ICM20602_GYRO_STARTUP_TIME, INV_ICM20602_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_ICM20602_ACCEL_STARTUP_TIME, + .gyro = INV_ICM20602_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_ICM20690_WHOAMI_VALUE, @@ -276,7 +318,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 1024, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_ICM20690_GYRO_STARTUP_TIME, INV_ICM20690_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_ICM20690_ACCEL_STARTUP_TIME, + .gyro = INV_ICM20690_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_IAM20380_WHOAMI_VALUE, .name = "IAM20380", @@ -284,7 +329,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_IAM20680_WHOAMI_VALUE, @@ -293,7 +341,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_IAM20680HP_WHOAMI_VALUE, @@ -302,7 +353,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 4 * 1024, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_IAM20680HT_WHOAMI_VALUE, @@ -311,7 +365,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 4 * 1024, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, }; @@ -1576,6 +1633,8 @@ static const unsigned long inv_mpu_scan_masks[] = { .type = IIO_MAGN, \ .modified = 1, \ .channel2 = _chan2, \ + /* index of the axis in magn_raw_to_gauss[] */ \ + .address = (_chan2) - IIO_MOD_X, \ .info_mask_separate = BIT(IIO_CHAN_INFO_SCALE) | \ BIT(IIO_CHAN_INFO_RAW), \ .scan_index = _index, \ diff --git a/drivers/iio/imu/kmx61.c b/drivers/iio/imu/kmx61.c index 8ef48daf182211..8d2e65e32ef909 100644 --- a/drivers/iio/imu/kmx61.c +++ b/drivers/iio/imu/kmx61.c @@ -939,7 +939,7 @@ static int kmx61_write_event_config(struct iio_dev *indio_dev, struct kmx61_data *data = kmx61_get_data(indio_dev); int ret = 0; - if (state && data->ev_enable_state) + if (state == data->ev_enable_state) return 0; guard(mutex)(&data->lock); diff --git a/drivers/iio/industrialio-acpi.c b/drivers/iio/industrialio-acpi.c index d67a4384379988..c77926f6db6215 100644 --- a/drivers/iio/industrialio-acpi.c +++ b/drivers/iio/industrialio-acpi.c @@ -6,6 +6,7 @@ #include #include #include +#include /** * iio_read_acpi_mount_matrix() - Read accelerometer mount matrix info from ACPI @@ -63,6 +64,14 @@ bool iio_read_acpi_mount_matrix(struct device *dev, } str = elements[i].string.pointer; + /* + * Microsoft's example separates the values with spaces, "0 1 0". + * Some BIOSes use commas instead, with or without spaces around + * them: "0, 1, 0", "0, -1 , 0", "1, 0,0". The string lives in + * the buffer allocated for us above, so turn the commas into + * spaces in place before parsing. + */ + strreplace(str, ',', ' '); if (sscanf(str, "%d %d %d", &val[0], &val[1], &val[2]) != 3) { dev_err(dev, "Incorrect ACPI mount matrix string format\n"); goto out_free_buffer; diff --git a/drivers/iio/industrialio-trigger.c b/drivers/iio/industrialio-trigger.c index 76926fee0f84d9..1078ffa8e06a97 100644 --- a/drivers/iio/industrialio-trigger.c +++ b/drivers/iio/industrialio-trigger.c @@ -105,9 +105,8 @@ void iio_trigger_unregister(struct iio_trigger *trig_info) scoped_guard(mutex, &iio_trigger_list_lock) list_del(&trig_info->list); - ida_free(&iio_trigger_ida, trig_info->id); - /* Possible issue in here */ device_del(&trig_info->dev); + ida_free(&iio_trigger_ida, trig_info->id); } EXPORT_SYMBOL(iio_trigger_unregister); @@ -293,6 +292,7 @@ int iio_trigger_attach_poll_func(struct iio_trigger *trig, if (pf->irq < 0) { pr_err("Could not find an available irq for trigger %s, CONFIG_IIO_CONSUMERS_PER_TRIGGER=%d limit might be exceeded\n", trig->name, CONFIG_IIO_CONSUMERS_PER_TRIGGER); + ret = pf->irq; goto out_put_module; } diff --git a/drivers/iio/light/hid-sensor-als.c b/drivers/iio/light/hid-sensor-als.c index 929343e42d8345..00dfc2037c1975 100644 --- a/drivers/iio/light/hid-sensor-als.c +++ b/drivers/iio/light/hid-sensor-als.c @@ -267,7 +267,21 @@ static int als_capture_sample(struct hid_sensor_hub_device *hsdev, struct iio_dev *indio_dev = platform_get_drvdata(priv); struct als_state *als_state = iio_priv(indio_dev); int ret = -EINVAL; - u32 sample_data = *(u32 *)raw_data; + u32 sample_data; + + switch (raw_len) { + case 1: + sample_data = *(u8 *)raw_data; + break; + case 2: + sample_data = *(u16 *)raw_data; + break; + default: + if (raw_len < sizeof(u32)) + return -EINVAL; + sample_data = *(u32 *)raw_data; + break; + } switch (usage_id) { case HID_USAGE_SENSOR_LIGHT_ILLUM: diff --git a/drivers/iio/light/tsl2591.c b/drivers/iio/light/tsl2591.c index ef3ed9635a1ef8..f56d31404c253f 100644 --- a/drivers/iio/light/tsl2591.c +++ b/drivers/iio/light/tsl2591.c @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -362,6 +363,10 @@ static int tsl2591_wait_adc_complete(struct tsl2591_chip *chip) * Scale values to get more representative value of lux i.e. * lux = ((C0DATA - C1DATA) * (1000 - ((C1DATA * 1000) / C0DATA))) / CPL * + * CPL is not computed on its own: at 1x gain it is below 1 for integration + * times under 500 ms, so the division by LUX DF is folded into the final + * division instead. + * * Channel 0 = IR + Visible * Channel 1 = IR only */ @@ -373,8 +378,10 @@ static int tsl2591_read_channel_data(struct iio_dev *indio_dev, struct tsl2591_als_settings *settings = &chip->als_settings; struct i2c_client *client = chip->client; u8 als_data[TSL2591_NUM_DATA_REGISTERS]; - int counts_per_lux, int_time_fval, gain_multi, lux; + int int_time_fval, gain_multi; u16 als_ch0, als_ch1; + u64 lux; + u32 rem; int ret; ret = tsl2591_wait_adc_complete(chip); @@ -410,23 +417,28 @@ static int tsl2591_read_channel_data(struct iio_dev *indio_dev, return gain_multi; } - int_time_fval = TSL2591_FVAL_TO_MSEC(settings->als_int_time); - /* Calculate counts per lux value */ - counts_per_lux = (int_time_fval * gain_multi) / TSL2591_LUX_COEFFICIENT; + /* No visible light, this also catches C0DATA == 0 */ + if (als_ch0 <= als_ch1) { + *val = 0; + *val2 = 0; + break; + } - dev_dbg(&client->dev, "Counts Per Lux: %d\n", counts_per_lux); + int_time_fval = TSL2591_FVAL_TO_MSEC(settings->als_int_time); /* Calculate lux value */ - lux = ((als_ch0 - als_ch1) * - (1000 - ((als_ch1 * 1000) / als_ch0))) / counts_per_lux; + lux = (u64)(als_ch0 - als_ch1) * + (1000 - ((als_ch1 * 1000) / als_ch0)) * + TSL2591_LUX_COEFFICIENT; + lux = div_u64(lux, int_time_fval * gain_multi); - dev_dbg(&client->dev, "Raw lux calculation: %d\n", lux); + dev_dbg(&client->dev, "Raw lux calculation: %llu\n", lux); /* Divide by 1000 to get real lux value before scaling */ - *val = lux / 1000; + *val = div_u64_rem(lux, 1000, &rem); /* Get the decimal part of lux reading */ - *val2 = (lux - (*val * 1000)) * 1000; + *val2 = rem * 1000; break; default: diff --git a/drivers/iio/light/vcnl4035.c b/drivers/iio/light/vcnl4035.c index ce1bd42b0c7ca7..f1cc75245001c7 100644 --- a/drivers/iio/light/vcnl4035.c +++ b/drivers/iio/light/vcnl4035.c @@ -44,8 +44,8 @@ #define VCNL4035_DEV_ID_MASK GENMASK(7, 0) /* Default values */ -#define VCNL4035_MODE_ALS_ENABLE BIT(0) -#define VCNL4035_MODE_ALS_DISABLE 0x00 +#define VCNL4035_MODE_ALS_ENABLE 0x00 +#define VCNL4035_MODE_ALS_DISABLE BIT(0) #define VCNL4035_MODE_ALS_INT_ENABLE BIT(1) #define VCNL4035_MODE_ALS_INT_DISABLE 0 #define VCNL4035_DEV_ID_VAL 0x80 diff --git a/drivers/iio/magnetometer/mmc35240.c b/drivers/iio/magnetometer/mmc35240.c index 6f40cba4b1ba74..7f028d7f1f1e3d 100644 --- a/drivers/iio/magnetometer/mmc35240.c +++ b/drivers/iio/magnetometer/mmc35240.c @@ -532,14 +532,13 @@ static int mmc35240_resume(struct device *dev) struct mmc35240_data *data = iio_priv(indio_dev); int ret; + regcache_cache_only(data->regmap, false); regcache_mark_dirty(data->regmap); ret = regcache_sync_region(data->regmap, MMC35240_REG_CTRL0, MMC35240_REG_CTRL1); if (ret < 0) dev_err(dev, "Failed to restore control registers\n"); - regcache_cache_only(data->regmap, false); - return 0; } diff --git a/drivers/iio/magnetometer/mmc5633.c b/drivers/iio/magnetometer/mmc5633.c index f4dae7ba1335b2..b651f01e1b5d98 100644 --- a/drivers/iio/magnetometer/mmc5633.c +++ b/drivers/iio/magnetometer/mmc5633.c @@ -499,13 +499,12 @@ static int mmc5633_resume(struct device *dev) struct regmap *regmap = dev_get_regmap(dev, NULL); int ret; + regcache_cache_only(regmap, false); regcache_mark_dirty(regmap); ret = regcache_sync_region(regmap, MMC5633_REG_CTRL0, MMC5633_REG_CTRL1); if (ret) dev_err(dev, "Failed to restore control registers\n"); - regcache_cache_only(regmap, false); - return 0; } diff --git a/drivers/iio/magnetometer/tlv493d.c b/drivers/iio/magnetometer/tlv493d.c index 03415cc2c9b3ee..234e3ce63ff784 100644 --- a/drivers/iio/magnetometer/tlv493d.c +++ b/drivers/iio/magnetometer/tlv493d.c @@ -299,11 +299,11 @@ static int tlv493d_read_raw(struct iio_dev *indio_dev, switch (chan->type) { case IIO_MAGN: /* - * Magnetic field scale: 0.0098 mTesla (i.e. 9.8 µT) - * Magnetic field in Gauss: mT * 10 = 0.098. + * Magnetic field scale: 0.098 mTesla (i.e. 98 µT) per LSB. + * In Gauss (1 mT = 10 G): 0.98 G per LSB. */ *val = 98; - *val2 = 1000; + *val2 = 100; return IIO_VAL_FRACTIONAL; case IIO_TEMP: /* diff --git a/drivers/iio/proximity/hx9023s.c b/drivers/iio/proximity/hx9023s.c index 0199a6351a4674..2a6da557f22ed0 100644 --- a/drivers/iio/proximity/hx9023s.c +++ b/drivers/iio/proximity/hx9023s.c @@ -1133,14 +1133,6 @@ static int hx9023s_probe(struct i2c_client *client) return dev_err_probe(dev, ret, "reg config failed\n"); if (client->irq) { - ret = devm_request_threaded_irq(dev, client->irq, - hx9023s_irq_handler, - hx9023s_irq_thread_handler, - IRQF_ONESHOT, - "hx9023s_event", indio_dev); - if (ret) - return ret; - data->trig = devm_iio_trigger_alloc(dev, "%s-dev%d", indio_dev->name, iio_device_id(indio_dev)); @@ -1150,6 +1142,14 @@ static int hx9023s_probe(struct i2c_client *client) data->trig->ops = &hx9023s_trigger_ops; iio_trigger_set_drvdata(data->trig, indio_dev); + ret = devm_request_threaded_irq(dev, client->irq, + hx9023s_irq_handler, + hx9023s_irq_thread_handler, + IRQF_ONESHOT, + "hx9023s_event", indio_dev); + if (ret) + return ret; + ret = devm_iio_trigger_register(dev, data->trig); if (ret) return dev_err_probe(dev, ret, diff --git a/drivers/iio/proximity/sx9310.c b/drivers/iio/proximity/sx9310.c index 79ba46d8a0aaeb..2585b9c6fb6938 100644 --- a/drivers/iio/proximity/sx9310.c +++ b/drivers/iio/proximity/sx9310.c @@ -891,7 +891,7 @@ static int sx9310_check_whoami(struct device *dev, if (ret) return ret; - ddata = device_get_match_data(dev); + ddata = i2c_get_match_data(data->client); if (ddata->whoami != whoami) return -ENODEV; diff --git a/drivers/iio/proximity/sx9324.c b/drivers/iio/proximity/sx9324.c index 255a36976ac41f..1c8ba28c030acc 100644 --- a/drivers/iio/proximity/sx9324.c +++ b/drivers/iio/proximity/sx9324.c @@ -279,11 +279,20 @@ static const struct { { 0, 250000 }, /* 11111: 4 s */ }; +/* + * The scan period of the SX9324 is selected by the 5-bit wide + * SX9324_REG_GNRL_CTRL0_SCANPERIOD field. The values below are the scan + * periods in ms of the corresponding sx9324_samp_freq_table[] entries. + */ static const unsigned int sx9324_scan_period_table[] = { - 2, 15, 30, 45, 60, 90, 120, 200, - 400, 600, 800, 1000, 2000, 3000, 4000, 5000, + 1, 2, 4, 6, 8, 10, 14, 18, /* 0x00 - 0x07 */ + 22, 26, 30, 34, 38, 42, 46, 50, /* 0x08 - 0x0f */ + 56, 62, 68, 74, 80, 90, 100, 200, /* 0x10 - 0x17 */ + 300, 400, 600, 800, 1000, 2000, 3000, 4000, /* 0x18 - 0x1f */ }; +static_assert(ARRAY_SIZE(sx9324_scan_period_table) == ARRAY_SIZE(sx9324_samp_freq_table)); + static const struct regmap_range sx9324_writable_reg_ranges[] = { /* * To set COMPSTAT for compensation, even if datasheet says register is diff --git a/drivers/iio/proximity/sx9360.c b/drivers/iio/proximity/sx9360.c index ed83d809ecf5ec..2a9b37df8f6228 100644 --- a/drivers/iio/proximity/sx9360.c +++ b/drivers/iio/proximity/sx9360.c @@ -14,10 +14,12 @@ #include #include #include +#include #include #include #include #include +#include #include @@ -43,6 +45,7 @@ #define SX9360_REG_GNRL_CTRL1_SCANPERIOD_MASK GENMASK(2, 0) #define SX9360_REG_GNRL_CTRL2 0x12 #define SX9360_REG_GNRL_CTRL2_PERIOD_102MS 0x32 +#define SX9360_REG_GNRL_SCANPERIOD_MAX GENMASK(10, 0) #define SX9360_REG_GNRL_REG_2_PERIOD_MS(_r) \ (((_r) * 8192) / (SX9360_FOSC_HZ / 1000)) #define SX9360_REG_GNRL_FREQ_2_REG(_f) (((_f) * 8192) / SX9360_FOSC_HZ) @@ -182,9 +185,9 @@ static const struct { int val; int val2; } sx9360_samp_freq_interval[] = { - { 0, 281250 }, /* 4MHz / (8192 * 2047) */ - { 0, 281250 }, - { 448, 281250 }, /* 4MHz / 8192 */ + { 0, 238535 }, /* 4MHz / (8192 * 2047) */ + { 0, 238419 }, + { 488, 281250 }, /* 4MHz / 8192 */ }; static const struct regmap_range sx9360_writable_reg_ranges[] = { @@ -383,11 +386,25 @@ static int sx9360_read_avail(struct iio_dev *indio_dev, static int sx9360_set_samp_freq(struct sx_common_data *data, int val, int val2) { - int reg; + unsigned int period_ticks; + u64 freq_uHz; __be16 buf; - reg = val * 8192 / SX9360_FOSC_HZ + val2 * 8192 / (SX9360_FOSC_MHZ); - buf = cpu_to_be16(reg); + if (val < 0 || val2 < 0) + return -EINVAL; + + freq_uHz = (u64)val * MICROHZ_PER_HZ + val2; + if (!freq_uHz) + return -EINVAL; + + /* The register holds the scan period in ticks of 8192 FOSC cycles. */ + period_ticks = DIV64_U64_ROUND_CLOSEST((u64)SX9360_FOSC_HZ * MICROHZ_PER_HZ, + freq_uHz * 8192); + if (!period_ticks || period_ticks > SX9360_REG_GNRL_SCANPERIOD_MAX) + return -EINVAL; + + buf = cpu_to_be16(period_ticks); + guard(mutex)(&data->mutex); return regmap_bulk_write(data->regmap, SX9360_REG_GNRL_CTRL1, &buf, diff --git a/drivers/iio/proximity/sx9500.c b/drivers/iio/proximity/sx9500.c index dadce9b442271f..26522b6c5a2d6e 100644 --- a/drivers/iio/proximity/sx9500.c +++ b/drivers/iio/proximity/sx9500.c @@ -548,6 +548,12 @@ static int sx9500_write_event_config(struct iio_dev *indio_dev, mutex_lock(&data->mutex); + /* The user counts must only change when the state does. */ + if (data->event_enabled[chan->channel] == state) { + ret = 0; + goto out_unlock; + } + if (state) { ret = sx9500_inc_chan_users(data, chan->channel); if (ret < 0) diff --git a/drivers/iio/temperature/hid-sensor-temperature.c b/drivers/iio/temperature/hid-sensor-temperature.c index 5e3262e461f463..ae67daff6df5a2 100644 --- a/drivers/iio/temperature/hid-sensor-temperature.c +++ b/drivers/iio/temperature/hid-sensor-temperature.c @@ -15,6 +15,7 @@ struct temperature_state { struct hid_sensor_common common_attributes; struct hid_sensor_hub_attribute_info temperature_attr; + struct hid_sensor_hub_callbacks callbacks; struct { s32 temperature_data; aligned_s64 timestamp; @@ -181,11 +182,6 @@ static int temperature_parse_report(struct platform_device *pdev, return ret; } -static struct hid_sensor_hub_callbacks temperature_callbacks = { - .send_event = &temperature_proc_event, - .capture_sample = &temperature_capture_sample, -}; - /* Function to initialize the processing for usage id */ static int hid_temperature_probe(struct platform_device *pdev) { @@ -237,9 +233,13 @@ static int hid_temperature_probe(struct platform_device *pdev) platform_set_drvdata(pdev, indio_dev); - temperature_callbacks.pdev = pdev; + temp_st->callbacks = (struct hid_sensor_hub_callbacks) { + .send_event = temperature_proc_event, + .capture_sample = temperature_capture_sample, + .pdev = pdev, + }; ret = sensor_hub_register_callback(hsdev, HID_USAGE_SENSOR_TEMPERATURE, - &temperature_callbacks); + &temp_st->callbacks); if (ret) goto error_remove_trigger; diff --git a/drivers/iio/temperature/mlx90614.c b/drivers/iio/temperature/mlx90614.c index 27d6ab5f5d7a46..4f79da1f905ed4 100644 --- a/drivers/iio/temperature/mlx90614.c +++ b/drivers/iio/temperature/mlx90614.c @@ -565,7 +565,7 @@ static int mlx90614_probe_num_ir_sensors(struct i2c_client *client) const struct mlx_chip_info *chip_info = data->chip_info; s32 ret; - if (chip_info->dual_channel) + if (!chip_info->dual_channel) return 0; ret = i2c_smbus_read_word_data(client, chip_info->op_eeprom_config1); diff --git a/drivers/infiniband/core/nldev.c b/drivers/infiniband/core/nldev.c index 849a5db54e1cb0..953406531cd54e 100644 --- a/drivers/infiniband/core/nldev.c +++ b/drivers/infiniband/core/nldev.c @@ -1304,7 +1304,8 @@ static int nldev_port_get_doit(struct sk_buff *skb, struct nlmsghdr *nlh, } nlh = nlmsg_put(msg, NETLINK_CB(skb).portid, nlh->nlmsg_seq, - RDMA_NL_GET_TYPE(RDMA_NL_NLDEV, RDMA_NLDEV_CMD_GET), + RDMA_NL_GET_TYPE(RDMA_NL_NLDEV, + RDMA_NLDEV_CMD_PORT_GET), 0, 0); if (!nlh) { err = -EMSGSIZE; @@ -2315,7 +2316,7 @@ static int nldev_stat_del_doit(struct sk_buff *skb, struct nlmsghdr *nlh, } nlh = nlmsg_put(msg, NETLINK_CB(skb).portid, nlh->nlmsg_seq, RDMA_NL_GET_TYPE(RDMA_NL_NLDEV, - RDMA_NLDEV_CMD_STAT_SET), + RDMA_NLDEV_CMD_STAT_DEL), 0, 0); if (!nlh) { ret = -EMSGSIZE; diff --git a/drivers/infiniband/core/uverbs_cmd.c b/drivers/infiniband/core/uverbs_cmd.c index cb8532225322c9..65af0aabb1fe71 100644 --- a/drivers/infiniband/core/uverbs_cmd.c +++ b/drivers/infiniband/core/uverbs_cmd.c @@ -1668,8 +1668,8 @@ static int ib_uverbs_query_qp(struct uverbs_attr_bundle *attrs) if (ret) return ret; - attr = kmalloc_obj(*attr); - init_attr = kmalloc_obj(*init_attr); + attr = kzalloc_obj(*attr); + init_attr = kzalloc_obj(*init_attr); if (!attr || !init_attr) { ret = -ENOMEM; goto out; diff --git a/drivers/infiniband/hw/bnxt_re/ib_verbs.c b/drivers/infiniband/hw/bnxt_re/ib_verbs.c index ac15372376a236..811f59f02f7584 100644 --- a/drivers/infiniband/hw/bnxt_re/ib_verbs.c +++ b/drivers/infiniband/hw/bnxt_re/ib_verbs.c @@ -4328,8 +4328,8 @@ int bnxt_re_poll_cq(struct ib_cq *ib_cq, int num_entries, struct ib_wc *wc) ibdev_err(&cq->rdev->ibdev, "POLL CQ : no CQL to use"); goto exit; } - cqe = &cq->cql[0]; while (budget) { + cqe = &cq->cql[0]; lib_qp = NULL; ncqe = bnxt_qplib_poll_cq(&cq->qplib_cq, cqe, budget, &lib_qp); if (lib_qp) { @@ -4555,7 +4555,7 @@ static int bnxt_re_set_page(struct ib_mr *ib_mr, u64 addr) { struct bnxt_re_mr *mr = container_of(ib_mr, struct bnxt_re_mr, ib_mr); - if (unlikely(mr->npages == mr->qplib_frpl.max_pg_ptrs)) + if (unlikely(mr->npages == mr->max_pages)) return -ENOMEM; mr->pages[mr->npages++] = addr; @@ -4584,7 +4584,7 @@ struct ib_mr *bnxt_re_alloc_mr(struct ib_pd *ib_pd, enum ib_mr_type type, ibdev_dbg(&rdev->ibdev, "MR type 0x%x not supported", type); return ERR_PTR(-EINVAL); } - if (max_num_sg > MAX_PBL_LVL_1_PGS) + if (!max_num_sg || max_num_sg > MAX_PBL_LVL_1_PGS) return ERR_PTR(-EINVAL); mr = kzalloc_obj(*mr); @@ -4603,6 +4603,7 @@ struct ib_mr *bnxt_re_alloc_mr(struct ib_pd *ib_pd, enum ib_mr_type type, mr->ib_mr.lkey = mr->qplib_mr.lkey; mr->ib_mr.rkey = mr->ib_mr.lkey; + mr->max_pages = max_num_sg; mr->pages = kzalloc_objs(u64, max_num_sg); if (!mr->pages) { rc = -ENOMEM; @@ -4909,6 +4910,8 @@ int bnxt_re_alloc_ucontext(struct ib_ucontext *ctx, struct ib_udata *udata) return 0; cfail: + rdma_user_mmap_entry_remove(uctx->shpage_mmap); + uctx->shpage_mmap = NULL; free_page((unsigned long)uctx->shpg); uctx->shpg = NULL; fail: diff --git a/drivers/infiniband/hw/bnxt_re/ib_verbs.h b/drivers/infiniband/hw/bnxt_re/ib_verbs.h index b7b33f6acf9109..d12cadaef10c56 100644 --- a/drivers/infiniband/hw/bnxt_re/ib_verbs.h +++ b/drivers/infiniband/hw/bnxt_re/ib_verbs.h @@ -124,6 +124,7 @@ struct bnxt_re_mr { struct ib_umem *ib_umem; struct bnxt_qplib_mrw qplib_mr; u32 npages; + u32 max_pages; u64 *pages; struct bnxt_qplib_frpl qplib_frpl; }; diff --git a/drivers/infiniband/hw/bnxt_re/qplib_rcfw.c b/drivers/infiniband/hw/bnxt_re/qplib_rcfw.c index 34d8aa12265de2..7278e85a8a409d 100644 --- a/drivers/infiniband/hw/bnxt_re/qplib_rcfw.c +++ b/drivers/infiniband/hw/bnxt_re/qplib_rcfw.c @@ -223,7 +223,7 @@ static int __block_for_resp(struct bnxt_qplib_rcfw *rcfw, u16 cookie) * Current design of this function is - * user must hold the completion queue hwq->lock. * user must have used existing completion and free the resources. - * this function will not check queue full condition. + * the command is dropped if the cookie slot is in use or the queue is full. * this function will explicitly set is_waiter_alive=false. * current use case is - send destroy_ah if create_ah is return * after waiter of create_ah is lost. It can be extended for other @@ -245,9 +245,17 @@ static void __send_message_no_waiter(struct bnxt_qplib_rcfw *rcfw, u8 *preq; cookie = cmdq->seq_num & RCFW_MAX_COOKIE_VALUE; - __set_cmdq_base_cookie(msg->req, msg->req_sz, cpu_to_le16(cookie)); crsqe = &rcfw->crsqe_tbl[cookie]; + if (crsqe->is_in_used || + bnxt_qplib_get_cmd_slots(msg->req) >= HWQ_FREE_SLOTS(hwq)) { + dev_warn_ratelimited(&rcfw->pdev->dev, + "CMDQ cookie %#x busy or CMDQ full, dropping internal command\n", + cookie); + return; + } + __set_cmdq_base_cookie(msg->req, msg->req_sz, cpu_to_le16(cookie)); + /* Set cmd_size in terms of 16B slots in req. */ bsize = bnxt_qplib_set_cmd_slots(msg->req); /* GET_CMD_SIZE would return number of slots in either case of tlv @@ -255,6 +263,7 @@ static void __send_message_no_waiter(struct bnxt_qplib_rcfw *rcfw, */ crsqe->is_internal_cmd = true; crsqe->is_waiter_alive = false; + crsqe->resp = NULL; crsqe->is_in_used = true; crsqe->req_size = __get_cmdq_base_cmd_size(msg->req, msg->req_sz); @@ -313,6 +322,12 @@ static int __send_message(struct bnxt_qplib_rcfw *rcfw, spin_unlock_bh(&hwq->lock); return -EAGAIN; } + if (crsqe->is_in_used) { + dev_info_ratelimited(&pdev->dev, + "CMDQ cookie %#x still in use\n", cookie); + spin_unlock_bh(&hwq->lock); + return -EAGAIN; + } if (msg->block) cookie |= RCFW_CMD_IS_BLOCKING; __set_cmdq_base_cookie(msg->req, msg->req_sz, cpu_to_le16(cookie)); @@ -487,6 +502,7 @@ static int __bnxt_qplib_rcfw_send_message(struct bnxt_qplib_rcfw *rcfw, { struct creq_qp_event *evnt = (struct creq_qp_event *)msg->resp; struct bnxt_qplib_crsqe *crsqe; + bool pending; u16 cookie; int rc; u8 opcode; @@ -511,15 +527,26 @@ static int __bnxt_qplib_rcfw_send_message(struct bnxt_qplib_rcfw *rcfw, else rc = __poll_for_resp(rcfw, cookie); - if (rc) { - spin_lock_bh(&rcfw->cmdq.hwq.lock); - crsqe = &rcfw->crsqe_tbl[cookie]; + spin_lock_bh(&rcfw->cmdq.hwq.lock); + crsqe = &rcfw->crsqe_tbl[cookie]; + pending = false; + if (crsqe->resp == evnt) { + pending = true; crsqe->is_waiter_alive = false; - if (rc == -ENODEV) - set_bit(FIRMWARE_STALL_DETECTED, &rcfw->cmdq.flags); - spin_unlock_bh(&rcfw->cmdq.hwq.lock); - return -ETIMEDOUT; + crsqe->resp = NULL; + } else if (rc) { + /* The completion was processed after the wait gave up but + * before the lock was taken. The response is valid. + */ + rc = 0; } + if (rc == -ENODEV) + set_bit(FIRMWARE_STALL_DETECTED, &rcfw->cmdq.flags); + spin_unlock_bh(&rcfw->cmdq.hwq.lock); + if (rc) + return -ETIMEDOUT; + if (pending) + return 0; if (evnt->status) { /* failed with status */ @@ -620,6 +647,7 @@ static int bnxt_qplib_process_qp_event(struct bnxt_qplib_rcfw *rcfw, struct creq_qp_event *qp_event, u32 *num_wait) { + struct creq_cq_error_notification *cq_err_event; struct creq_qp_error_notification *err_event; struct bnxt_qplib_hwq *hwq = &rcfw->cmdq.hwq; struct bnxt_qplib_crsqe *crsqe; @@ -634,6 +662,13 @@ static int bnxt_qplib_process_qp_event(struct bnxt_qplib_rcfw *rcfw, pdev = rcfw->pdev; print_hex_dump_bytes("event: ", DUMP_PREFIX_OFFSET, qp_event, sizeof(*qp_event)); switch (qp_event->event) { + case CREQ_QP_EVENT_EVENT_CQ_ERROR_NOTIFICATION: + cq_err_event = (struct creq_cq_error_notification *)qp_event; + dev_dbg(&pdev->dev, + "Received CQ error notification cqid 0x%x, reason 0x%x\n", + le32_to_cpu(cq_err_event->xid), + cq_err_event->cq_err_reason); + break; case CREQ_QP_EVENT_EVENT_QP_ERROR_NOTIFICATION: err_event = (struct creq_qp_error_notification *)qp_event; qp_id = le32_to_cpu(err_event->xid); @@ -683,6 +718,14 @@ static int bnxt_qplib_process_qp_event(struct bnxt_qplib_rcfw *rcfw, return rc; } + if (!crsqe->is_in_used) { + dev_warn_ratelimited(&pdev->dev, + "event %#x for cookie %#x with no outstanding command\n", + qp_event->event, cookie); + spin_unlock(&hwq->lock); + return rc; + } + if (crsqe->is_internal_cmd && !qp_event->status) atomic_dec(&rcfw->timeout_send); @@ -703,8 +746,8 @@ static int bnxt_qplib_process_qp_event(struct bnxt_qplib_rcfw *rcfw, is_waiter_alive = crsqe->is_waiter_alive; crsqe->req_size = 0; - if (!is_waiter_alive) - crsqe->resp = NULL; + crsqe->resp = NULL; + crsqe->is_waiter_alive = false; crsqe->is_in_used = false; @@ -718,9 +761,11 @@ static int bnxt_qplib_process_qp_event(struct bnxt_qplib_rcfw *rcfw, * so let's destroy the same address vector since it is * no more used in stack. We don't care about completion * in __send_message_no_waiter. - * If destroy_ah is failued by firmware, there will be AH - * resource leak and relatively not critical + unlikely - * scenario. Current design is not to handle such case. + * If destroy_ah is failed by firmware, or is dropped locally + * because the cookie slot is in use or the CMDQ is full, + * there will be AH resource leak and relatively not + * critical + unlikely scenario. Current design is not to + * handle such case. */ if (!is_waiter_alive && !qp_event->status && qp_event->event == CREQ_QP_EVENT_EVENT_CREATE_AH) diff --git a/drivers/infiniband/hw/ionic/ionic_lif_cfg.c b/drivers/infiniband/hw/ionic/ionic_lif_cfg.c index 66cee57442e7a3..a3ee86b560379f 100644 --- a/drivers/infiniband/hw/ionic/ionic_lif_cfg.c +++ b/drivers/infiniband/hw/ionic/ionic_lif_cfg.c @@ -84,7 +84,7 @@ void ionic_fill_lif_cfg(struct ionic_lif *lif, struct ionic_lif_cfg *cfg) cfg->cq_qtype = ident->rdma.cq_qtype.qtype; cfg->eq_qtype = ident->rdma.eq_qtype.qtype; cfg->udma_qgrp_shift = ident->rdma.udma_shift; - cfg->udma_count = 2; + cfg->udma_count = cfg->udma_qgrp_shift ? 2 : 1; cfg->max_stride = ident->rdma.max_stride; cfg->rcq_sign_bit = ident->rdma.rcq_sign_bit; diff --git a/drivers/infiniband/hw/ionic/ionic_res.h b/drivers/infiniband/hw/ionic/ionic_res.h index 46c8c584bd9a1c..c480865dced526 100644 --- a/drivers/infiniband/hw/ionic/ionic_res.h +++ b/drivers/infiniband/hw/ionic/ionic_res.h @@ -125,10 +125,14 @@ static inline void ionic_resid_put(struct ionic_resid_bits *resid, int id) static inline u32 ionic_bitid_to_qid(u32 bitid, u8 qgrp_shift, u8 half_qid_shift) { - u32 udma_bit = - (bitid & BIT(half_qid_shift)) >> (half_qid_shift - qgrp_shift); - u32 grp_bits = (bitid & GENMASK(half_qid_shift - 1, qgrp_shift)) << 1; - u32 idx_bits = bitid & (BIT(qgrp_shift) - 1); + u32 udma_bit, grp_bits, idx_bits; + + if (!qgrp_shift) + return bitid; + + udma_bit = (bitid & BIT(half_qid_shift)) >> (half_qid_shift - qgrp_shift); + grp_bits = (bitid & GENMASK(half_qid_shift - 1, qgrp_shift)) << 1; + idx_bits = bitid & (BIT(qgrp_shift) - 1); return grp_bits | udma_bit | idx_bits; } @@ -145,9 +149,14 @@ static inline u32 ionic_bitid_to_qid(u32 bitid, u8 qgrp_shift, */ static inline u32 ionic_qid_to_bitid(u32 qid, u8 qgrp_shift, u8 half_qid_shift) { - u32 udma_bit = (qid & BIT(qgrp_shift)) << (half_qid_shift - qgrp_shift); - u32 grp_bits = (qid & GENMASK(half_qid_shift, qgrp_shift + 1)) >> 1; - u32 idx_bits = qid & (BIT(qgrp_shift) - 1); + u32 udma_bit, grp_bits, idx_bits; + + if (!qgrp_shift) + return qid; + + udma_bit = (qid & BIT(qgrp_shift)) << (half_qid_shift - qgrp_shift); + grp_bits = (qid & GENMASK(half_qid_shift, qgrp_shift + 1)) >> 1; + idx_bits = qid & (BIT(qgrp_shift) - 1); return udma_bit | grp_bits | idx_bits; } diff --git a/drivers/infiniband/hw/irdma/ctrl.c b/drivers/infiniband/hw/irdma/ctrl.c index 1c2ad5773b9f7d..ef8627f070ce76 100644 --- a/drivers/infiniband/hw/irdma/ctrl.c +++ b/drivers/infiniband/hw/irdma/ctrl.c @@ -1703,8 +1703,10 @@ int irdma_sc_mr_fast_register(struct irdma_sc_qp *qp, page_size = IRDMA_PAGE_SIZE_1G; else if (info->page_size == 0x200000) page_size = IRDMA_PAGE_SIZE_2M; - else + else if (info->page_size == 0x1000) page_size = IRDMA_PAGE_SIZE_4K; + else + return -EINVAL; sq_info.wr_id = info->wr_id; sq_info.signaled = info->signaled; diff --git a/drivers/infiniband/hw/irdma/defs.h b/drivers/infiniband/hw/irdma/defs.h index d6a3152959dde6..eb91796648842e 100644 --- a/drivers/infiniband/hw/irdma/defs.h +++ b/drivers/infiniband/hw/irdma/defs.h @@ -159,6 +159,7 @@ enum irdma_protocol_used { #define IRDMA_HW_PAGE_SIZE 4096 #define IRDMA_HW_PAGE_SHIFT 12 +#define IRDMA_HW_PAGES_PER_PAGE (PAGE_SIZE >> IRDMA_HW_PAGE_SHIFT) #define IRDMA_CQE_QTYPE_RQ 0 #define IRDMA_CQE_QTYPE_SQ 1 diff --git a/drivers/infiniband/hw/irdma/hw.c b/drivers/infiniband/hw/irdma/hw.c index fbb8fb47d0d167..1d57b3c9f4906b 100644 --- a/drivers/infiniband/hw/irdma/hw.c +++ b/drivers/infiniband/hw/irdma/hw.c @@ -700,7 +700,7 @@ static void irdma_destroy_cqp(struct irdma_pci_f *rf) static void irdma_destroy_virt_aeq(struct irdma_pci_f *rf) { struct irdma_aeq *aeq = &rf->aeq; - u32 pg_cnt = DIV_ROUND_UP(aeq->mem.size, PAGE_SIZE); + u32 pg_cnt = DIV_ROUND_UP(aeq->mem.size, IRDMA_HW_PAGE_SIZE); dma_addr_t *pg_arr = (dma_addr_t *)aeq->palloc.level1.addr; irdma_unmap_vm_page_list(&rf->hw, pg_arr, pg_cnt); @@ -1479,7 +1479,7 @@ static int irdma_create_virt_aeq(struct irdma_pci_f *rf, u32 size) if (!aeq->mem.va) return -ENOMEM; - pg_cnt = DIV_ROUND_UP(aeq->mem.size, PAGE_SIZE); + pg_cnt = DIV_ROUND_UP(aeq->mem.size, IRDMA_HW_PAGE_SIZE); status = irdma_get_pble(rf->pble_rsrc, &aeq->palloc, pg_cnt, true); if (status) { vfree(aeq->mem.va); diff --git a/drivers/infiniband/hw/irdma/utils.c b/drivers/infiniband/hw/irdma/utils.c index 290ad02ed65754..3efc4125bb59cc 100644 --- a/drivers/infiniband/hw/irdma/utils.c +++ b/drivers/infiniband/hw/irdma/utils.c @@ -2199,20 +2199,24 @@ int irdma_map_vm_page_list(struct irdma_hw *hw, void *va, dma_addr_t *pg_dma, u32 pg_cnt) { struct page *vm_page; - int i; + dma_addr_t dma; + u32 i, j; u8 *addr; addr = (u8 *)(uintptr_t)va; - for (i = 0; i < pg_cnt; i++) { + for (i = 0; i < pg_cnt; i += IRDMA_HW_PAGES_PER_PAGE) { vm_page = vmalloc_to_page(addr); if (!vm_page) goto err; - pg_dma[i] = dma_map_page(hw->device, vm_page, 0, PAGE_SIZE, - DMA_BIDIRECTIONAL); - if (dma_mapping_error(hw->device, pg_dma[i])) + dma = dma_map_page(hw->device, vm_page, 0, PAGE_SIZE, + DMA_BIDIRECTIONAL); + if (dma_mapping_error(hw->device, dma)) goto err; + for (j = 0; j < IRDMA_HW_PAGES_PER_PAGE && i + j < pg_cnt; j++) + pg_dma[i + j] = dma + j * IRDMA_HW_PAGE_SIZE; + addr += PAGE_SIZE; } @@ -2225,9 +2229,9 @@ int irdma_map_vm_page_list(struct irdma_hw *hw, void *va, dma_addr_t *pg_dma, void irdma_unmap_vm_page_list(struct irdma_hw *hw, dma_addr_t *pg_dma, u32 pg_cnt) { - int i; + u32 i; - for (i = 0; i < pg_cnt; i++) + for (i = 0; i < pg_cnt; i += IRDMA_HW_PAGES_PER_PAGE) dma_unmap_page(hw->device, pg_dma[i], PAGE_SIZE, DMA_BIDIRECTIONAL); } @@ -2254,7 +2258,7 @@ void irdma_pble_free_paged_mem(struct irdma_chunk *chunk) /** * irdma_pble_get_paged_mem -allocate paged memory for pbles * @chunk: chunk to add for paged memory - * @pg_cnt: number of pages needed + * @pg_cnt: number of HW (4K) pages needed */ int irdma_pble_get_paged_mem(struct irdma_chunk *chunk, u32 pg_cnt) { @@ -2265,7 +2269,7 @@ int irdma_pble_get_paged_mem(struct irdma_chunk *chunk, u32 pg_cnt) if (!chunk->dmainfo.dmaaddrs) return -ENOMEM; - size = PAGE_SIZE * pg_cnt; + size = pg_cnt * IRDMA_HW_PAGE_SIZE; va = vmalloc(size); if (!va) goto err; diff --git a/drivers/infiniband/hw/irdma/verbs.c b/drivers/infiniband/hw/irdma/verbs.c index c91c55917de919..9cc1b65eea2672 100644 --- a/drivers/infiniband/hw/irdma/verbs.c +++ b/drivers/infiniband/hw/irdma/verbs.c @@ -2,6 +2,21 @@ /* Copyright (c) 2015 - 2021 Intel Corporation */ #include "main.h" +/** + * irdma_fmr_pages_per_page() - HW pages needed per PAGE_SIZE page in an FRWR. + * @dev: sc device + * + * If PAGE_SIZE is one of the HW supported page sizes, then it can be directly + * used. Otherwise, we need to break PAGE_SIZE into multiple HW (4K) pages. + */ +static u32 irdma_fmr_pages_per_page(struct irdma_sc_dev *dev) +{ + if (PAGE_SIZE & dev->hw_attrs.page_size_cap) + return 1; + + return IRDMA_HW_PAGES_PER_PAGE; +} + /** * irdma_query_device - get device attributes * @ibdev: device pointer from stack @@ -58,7 +73,8 @@ static int irdma_query_device(struct ib_device *ibdev, props->max_mcast_grp = rf->max_mcg; props->max_mcast_qp_attach = IRDMA_MAX_MGS_PER_CTX; props->max_total_mcast_qp_attach = rf->max_qp * IRDMA_MAX_MGS_PER_CTX; - props->max_fast_reg_page_list_len = IRDMA_MAX_PAGES_PER_FMR; + props->max_fast_reg_page_list_len = + IRDMA_MAX_PAGES_PER_FMR / irdma_fmr_pages_per_page(&rf->sc_dev); props->max_srq = rf->max_srq - rf->used_srqs; props->max_srq_wr = IRDMA_MAX_SRQ_WRS; props->max_srq_sge = hw_attrs->uk_attrs.max_hw_wq_frags; @@ -3208,12 +3224,16 @@ static struct ib_mr *irdma_alloc_mr(struct ib_pd *pd, enum ib_mr_type mr_type, u32 max_num_sg) { struct irdma_device *iwdev = to_iwdev(pd->device); + u32 pages_per_page = irdma_fmr_pages_per_page(&iwdev->rf->sc_dev); struct irdma_pble_alloc *palloc; struct irdma_pbl *iwpbl; struct irdma_mr *iwmr; u32 stag; int err_code; + if (max_num_sg > IRDMA_MAX_PAGES_PER_FMR / pages_per_page) + return ERR_PTR(-EINVAL); + iwmr = kzalloc_obj(*iwmr); if (!iwmr) return ERR_PTR(-ENOMEM); @@ -3233,7 +3253,12 @@ static struct ib_mr *irdma_alloc_mr(struct ib_pd *pd, enum ib_mr_type mr_type, iwpbl->iwmr = iwmr; iwmr->type = IRDMA_MEMREG_TYPE_MEM; palloc = &iwpbl->pble_alloc; - iwmr->page_cnt = max_num_sg; + /* Some ULPs pass PAGE_SIZE to ib_map_mr_sg() but PAGE_SIZE can be some + * multiple of 4K that the HW does not natively support. We can work + * around this by cracking the larger page into multiple 4K pages, but + * page_cnt needs to be scaled. + */ + iwmr->page_cnt = max_num_sg * pages_per_page; /* Use system PAGE_SIZE as the sg page sizes are unknown at this point */ iwmr->len = max_num_sg * PAGE_SIZE; err_code = irdma_get_pble(iwdev->rf->pble_rsrc, palloc, iwmr->page_cnt, @@ -3297,8 +3322,15 @@ static int irdma_set_page(struct ib_mr *ibmr, u64 addr) static int irdma_map_mr_sg(struct ib_mr *ibmr, struct scatterlist *sg, int sg_nents, unsigned int *sg_offset) { + struct irdma_device *iwdev = to_iwdev(ibmr->device); struct irdma_mr *iwmr = to_iwmr(ibmr); + /* HW only supports 4K, 2M and 1G pages, but some ULPs pass PAGE_SIZE + * which can be some multiple of 4K that we do not support, so force 4K. + */ + if (!(ibmr->page_size & iwdev->rf->sc_dev.hw_attrs.page_size_cap)) + ibmr->page_size = SZ_4K; + iwmr->npages = 0; return ib_sg_to_pages(ibmr, sg, sg_nents, sg_offset, irdma_set_page); @@ -3308,14 +3340,14 @@ static int irdma_map_mr_sg(struct ib_mr *ibmr, struct scatterlist *sg, * irdma_hwreg_mr - send cqp command for memory registration * @iwdev: irdma device * @iwmr: irdma mr pointer + * @pd: protection domain to register the MR with * @access: access for MR */ static int irdma_hwreg_mr(struct irdma_device *iwdev, struct irdma_mr *iwmr, - u16 access) + struct ib_pd *pd, u16 access) { struct irdma_pbl *iwpbl = &iwmr->iwpbl; struct irdma_reg_ns_stag_info *stag_info; - struct ib_pd *pd = iwmr->ibmr.pd; struct irdma_pd *iwpd = to_iwpd(pd); struct irdma_pble_alloc *palloc = &iwpbl->pble_alloc; struct irdma_cqp_request *cqp_request; @@ -3369,8 +3401,8 @@ static int irdma_hwreg_mr(struct irdma_device *iwdev, struct irdma_mr *iwmr, return ret; } -static int irdma_reg_user_mr_type_mem(struct irdma_mr *iwmr, int access, - bool create_stag) +static int irdma_reg_user_mr_type_mem(struct irdma_mr *iwmr, struct ib_pd *pd, + int access, bool create_stag) { struct irdma_device *iwdev = to_iwdev(iwmr->ibmr.device); struct irdma_pbl *iwpbl = &iwmr->iwpbl; @@ -3415,7 +3447,7 @@ static int irdma_reg_user_mr_type_mem(struct irdma_mr *iwmr, int access, iwmr->ibmr.lkey = stag; } - err = irdma_hwreg_mr(iwdev, iwmr, access); + err = irdma_hwreg_mr(iwdev, iwmr, pd, access); if (err) goto err_hwreg; @@ -3646,7 +3678,7 @@ static struct ib_mr *irdma_reg_user_mr(struct ib_pd *pd, u64 start, u64 len, goto error; break; case IRDMA_MEMREG_TYPE_MEM: - err = irdma_reg_user_mr_type_mem(iwmr, access, true); + err = irdma_reg_user_mr_type_mem(iwmr, pd, access, true); if (err) goto error; @@ -3726,7 +3758,7 @@ static struct ib_mr *irdma_reg_user_mr_dmabuf(struct ib_pd *pd, u64 start, goto err_release; } - err = irdma_reg_user_mr_type_mem(iwmr, access, true); + err = irdma_reg_user_mr_type_mem(iwmr, pd, access, true); if (err) goto err_iwmr; @@ -3794,6 +3826,7 @@ static int irdma_hwdereg_mr(struct ib_mr *ib_mr) /* * irdma_rereg_mr_trans - Re-register a user MR for a change translation. * @iwmr: ptr of iwmr + * @pd: protection domain to register the MR with * @start: virtual start address * @len: length of mr * @virt: virtual address @@ -3801,11 +3834,10 @@ static int irdma_hwdereg_mr(struct ib_mr *ib_mr) * Re-register a user memory region when a change translation is requested. * Re-register a new region while reusing the stag from the original registration. */ -static int irdma_rereg_mr_trans(struct irdma_mr *iwmr, u64 start, u64 len, - u64 virt) +static int irdma_rereg_mr_trans(struct irdma_mr *iwmr, struct ib_pd *pd, + u64 start, u64 len, u64 virt) { struct irdma_pbl *iwpbl = &iwmr->iwpbl; - struct ib_pd *pd = iwmr->ibmr.pd; struct ib_umem *region; int err; @@ -3815,11 +3847,10 @@ static int irdma_rereg_mr_trans(struct irdma_mr *iwmr, u64 start, u64 len, iwmr->region = region; iwmr->ibmr.iova = virt; - iwmr->ibmr.pd = pd; iwmr->len = region->length; iwpbl->user_base = virt; - err = irdma_reg_user_mr_type_mem(iwmr, iwmr->access, false); + err = irdma_reg_user_mr_type_mem(iwmr, pd, iwmr->access, false); if (err) goto err; @@ -3873,6 +3904,9 @@ static struct ib_mr *irdma_rereg_user_mr(struct ib_mr *ib_mr, int flags, if (ret) return ERR_PTR(ret); + if (!iwmr->is_hwreg) + return ERR_PTR(-EINVAL); + ret = irdma_hwdereg_mr(ib_mr); if (ret) return ERR_PTR(ret); @@ -3880,11 +3914,6 @@ static struct ib_mr *irdma_rereg_user_mr(struct ib_mr *ib_mr, int flags, if (flags & IB_MR_REREG_ACCESS) iwmr->access = new_access; - if (flags & IB_MR_REREG_PD) { - iwmr->ibmr.pd = new_pd; - iwmr->ibmr.device = new_pd->device; - } - if (flags & IB_MR_REREG_TRANS) { if (iwpbl->pbl_allocated) { irdma_free_pble(iwdev->rf->pble_rsrc, @@ -3897,9 +3926,9 @@ static struct ib_mr *irdma_rereg_user_mr(struct ib_mr *ib_mr, int flags, iwmr->region = NULL; } - ret = irdma_rereg_mr_trans(iwmr, start, len, virt); + ret = irdma_rereg_mr_trans(iwmr, new_pd, start, len, virt); } else { - ret = irdma_hwreg_mr(iwdev, iwmr, iwmr->access); + ret = irdma_hwreg_mr(iwdev, iwmr, new_pd, iwmr->access); } return ret ? ERR_PTR(ret) : NULL; @@ -3948,7 +3977,7 @@ struct ib_mr *irdma_reg_phys_mr(struct ib_pd *pd, u64 addr, u64 size, int access iwmr->pgaddrmem[0] = addr; iwmr->len = size; iwmr->page_size = SZ_4K; - ret = irdma_hwreg_mr(iwdev, iwmr, access); + ret = irdma_hwreg_mr(iwdev, iwmr, pd, access); if (ret) { irdma_free_stag(iwdev, stag); goto err; diff --git a/drivers/infiniband/hw/mlx4/mr.c b/drivers/infiniband/hw/mlx4/mr.c index a6b4abce1bfef0..e7f524c28f1e07 100644 --- a/drivers/infiniband/hw/mlx4/mr.c +++ b/drivers/infiniband/hw/mlx4/mr.c @@ -268,6 +268,8 @@ struct ib_mr *mlx4_ib_rereg_user_mr(struct ib_mr *mr, int flags, u64 start, *pmpt_entry); if (err) { ib_umem_release(mmr->umem); + mmr->mmr.mtt.order = -1; + mmr->umem = NULL; goto release_mpt_entry; } mmr->mmr.iova = virt_addr; @@ -277,6 +279,7 @@ struct ib_mr *mlx4_ib_rereg_user_mr(struct ib_mr *mr, int flags, u64 start, if (err) { mlx4_mr_rereg_mem_cleanup(dev->dev, &mmr->mmr); ib_umem_release(mmr->umem); + mmr->umem = NULL; goto release_mpt_entry; } } diff --git a/drivers/infiniband/hw/mlx5/devx.c b/drivers/infiniband/hw/mlx5/devx.c index fc6f793dcc6584..2277160d9a33be 100644 --- a/drivers/infiniband/hw/mlx5/devx.c +++ b/drivers/infiniband/hw/mlx5/devx.c @@ -2294,8 +2294,8 @@ static int devx_umem_get(struct mlx5_ib_dev *dev, struct ib_ucontext *ucontext, return 0; } -static unsigned int devx_umem_find_best_pgsize(struct ib_umem *umem, - unsigned long pgsz_bitmap) +static unsigned long devx_umem_find_best_pgsize(struct ib_umem *umem, + unsigned long pgsz_bitmap) { unsigned long page_size; @@ -2333,7 +2333,7 @@ static int devx_umem_reg_cmd_alloc(struct mlx5_ib_dev *dev, int access) { unsigned long pgsz_bitmap; - unsigned int page_size; + unsigned long page_size; __be64 *mtt; void *umem; int ret; diff --git a/drivers/infiniband/hw/mlx5/ib_rep.c b/drivers/infiniband/hw/mlx5/ib_rep.c index 65d8767d1830c6..c460018d04754c 100644 --- a/drivers/infiniband/hw/mlx5/ib_rep.c +++ b/drivers/infiniband/hw/mlx5/ib_rep.c @@ -22,21 +22,30 @@ mlx5_ib_set_vport_rep(struct mlx5_core_dev *dev, if (!ibdev) return -EINVAL; + /* Only Vports that are not native to the LAG master eswitch need to add + * demux rule. + */ + if (mlx5_eswitch_get_total_vports(dev) <= vport_index) { + ret = mlx5_lag_demux_rule_add(rep_dev, rep->vport, vport_index); + if (ret) + return ret; + } + ibdev->port[vport_index].rep = rep; rep->rep_data[REP_IB].priv = ibdev; ndev = mlx5_ib_get_rep_netdev(rep->esw, rep->vport); ret = ib_device_set_netdev(&ibdev->ib_dev, ndev, vport_index + 1); if (ret) - return ret; + goto err_set_netdev; - /* Only Vports that are not native to the LAG master eswitch need to add - * demux rule. - */ - if (mlx5_eswitch_get_total_vports(dev) > vport_index) - return 0; + return 0; - return mlx5_lag_demux_rule_add(rep_dev, rep->vport, vport_index); +err_set_netdev: + rep->rep_data[REP_IB].priv = NULL; + ibdev->port[vport_index].rep = NULL; + mlx5_lag_demux_rule_del(rep_dev, vport_index); + return ret; } static void mlx5_ib_register_peer_vport_reps(struct mlx5_core_dev *mdev); diff --git a/drivers/infiniband/hw/mlx5/main.c b/drivers/infiniband/hw/mlx5/main.c index 65455aedd559b6..2ab38068db8388 100644 --- a/drivers/infiniband/hw/mlx5/main.c +++ b/drivers/infiniband/hw/mlx5/main.c @@ -3536,7 +3536,8 @@ static int mlx5_port_immutable(struct ib_device *ibdev, u32 port_num, if (err) return err; - if (ll == IB_LINK_LAYER_INFINIBAND) { + if (ll == IB_LINK_LAYER_INFINIBAND && + MLX5_CAP_GEN(dev->mdev, ib_virt)) { if (ibdev->type == RDMA_DEVICE_TYPE_SMI) port_num = smi_to_native_portnum(dev, port_num); diff --git a/drivers/infiniband/hw/mthca/mthca_memfree.c b/drivers/infiniband/hw/mthca/mthca_memfree.c index 9c5eb03f354ded..39d82dc73807e4 100644 --- a/drivers/infiniband/hw/mthca/mthca_memfree.c +++ b/drivers/infiniband/hw/mthca/mthca_memfree.c @@ -453,7 +453,7 @@ int mthca_map_user_db(struct mthca_dev *dev, struct mthca_uar *uar, if (!mthca_is_memfree(dev)) return 0; - if (index < 0 || index > dev->uar_table.uarc_size / 8) + if (index < 0 || index >= dev->uar_table.uarc_size / 8) return -EINVAL; mutex_lock(&db_tab->mutex); diff --git a/drivers/infiniband/hw/usnic/usnic_ib_qp_grp.c b/drivers/infiniband/hw/usnic/usnic_ib_qp_grp.c index a7327c7a746577..6f6aaea06edead 100644 --- a/drivers/infiniband/hw/usnic/usnic_ib_qp_grp.c +++ b/drivers/infiniband/hw/usnic/usnic_ib_qp_grp.c @@ -78,8 +78,17 @@ int usnic_ib_qp_grp_dump_rows(void *obj, char *buf, int buf_sz) struct usnic_ib_qp_grp *qp_grp = obj; struct usnic_ib_qp_grp_flow *default_flow; if (obj) { - default_flow = list_first_entry(&qp_grp->flows_lst, - struct usnic_ib_qp_grp_flow, link); + default_flow = list_first_entry_or_null(&qp_grp->flows_lst, + struct usnic_ib_qp_grp_flow, + link); + if (!default_flow) + return scnprintf(buf, buf_sz, + "|%d\t|%s\t|%d\t|%hu\t|N/A", + qp_grp->ibqp.qp_num, + usnic_ib_qp_grp_state_to_string( + qp_grp->state), + qp_grp->owner_pid, + usnic_vnic_get_index(qp_grp->vf->vnic)); return scnprintf(buf, buf_sz, "|%d\t|%s\t|%d\t|%hu\t|%d", qp_grp->ibqp.qp_num, usnic_ib_qp_grp_state_to_string( diff --git a/drivers/infiniband/sw/siw/siw.h b/drivers/infiniband/sw/siw/siw.h index dbc998248b1e9f..4ec9c2ac75e7b4 100644 --- a/drivers/infiniband/sw/siw/siw.h +++ b/drivers/infiniband/sw/siw/siw.h @@ -157,6 +157,7 @@ struct siw_mem { void *mem_obj; }; struct ib_pd *pd; + struct rcu_head rcu; }; struct siw_mr { diff --git a/drivers/infiniband/sw/siw/siw_mem.c b/drivers/infiniband/sw/siw/siw_mem.c index 2a08817d3cce08..be70dc9c8f813d 100644 --- a/drivers/infiniband/sw/siw/siw_mem.c +++ b/drivers/infiniband/sw/siw/siw_mem.c @@ -115,7 +115,7 @@ void siw_free_mem(struct kref *ref) else kfree(mem->pbl); } - kfree(mem); + kfree_rcu(mem, rcu); } /* diff --git a/drivers/infiniband/ulp/rtrs/rtrs-clt.c b/drivers/infiniband/ulp/rtrs/rtrs-clt.c index bf3a0377da3ff4..85eaa2bdb4704a 100644 --- a/drivers/infiniband/ulp/rtrs/rtrs-clt.c +++ b/drivers/infiniband/ulp/rtrs/rtrs-clt.c @@ -3191,16 +3191,16 @@ void rtrs_clt_ib_event_handler(struct ib_event_handler *handler, static int rtrs_clt_ib_dev_init(struct rtrs_ib_dev *dev) { - INIT_IB_EVENT_HANDLER(&dev->event_handler, dev->ib_dev, - rtrs_clt_ib_event_handler); - ib_register_event_handler(&dev->event_handler); - if (!(dev->ib_dev->attrs.device_cap_flags & IB_DEVICE_MEM_MGT_EXTENSIONS)) { pr_err("Memory registrations not supported.\n"); return -ENOTSUPP; } + INIT_IB_EVENT_HANDLER(&dev->event_handler, dev->ib_dev, + rtrs_clt_ib_event_handler); + ib_register_event_handler(&dev->event_handler); + return 0; } diff --git a/drivers/infiniband/ulp/srpt/ib_srpt.c b/drivers/infiniband/ulp/srpt/ib_srpt.c index 43c3ff1ad8e7ed..a2af0882eff5ad 100644 --- a/drivers/infiniband/ulp/srpt/ib_srpt.c +++ b/drivers/infiniband/ulp/srpt/ib_srpt.c @@ -959,7 +959,7 @@ static int srpt_alloc_rw_ctxs(struct srpt_send_ioctx *ioctx, struct srpt_rdma_ch *ch = ioctx->ch; struct scatterlist *prev = NULL; unsigned prev_nents; - u8 n_rdma, n_rw_ctx; + int n_rdma, n_rw_ctx; int ret, i; if (nbufs == 1) { @@ -979,6 +979,12 @@ static int srpt_alloc_rw_ctxs(struct srpt_send_ioctx *ioctx, u32 size = be32_to_cpu(db->len); u32 rkey = be32_to_cpu(db->key); + if (size == 0) { + pr_err("received SRP_CMD buffer descriptor with zero length\n"); + ret = -EINVAL; + goto unwind; + } + ret = target_alloc_sgl(&ctx->sg, &ctx->nents, size, false, i < nbufs - 1); if (ret) @@ -1117,6 +1123,7 @@ static int srpt_get_desc_tbl(struct srpt_recv_ioctx *recv_ioctx, struct srp_indirect_buf *idb = srpt_get_desc_buf(srp_cmd); int nbufs = be32_to_cpu(idb->table_desc.len) / sizeof(struct srp_direct_buf); + size_t desc_off = (uintptr_t)idb - (uintptr_t)srp_cmd; if (nbufs > (srp_cmd->data_out_desc_cnt + srp_cmd->data_in_desc_cnt)) { @@ -1128,6 +1135,18 @@ static int srpt_get_desc_tbl(struct srpt_recv_ioctx *recv_ioctx, return -EINVAL; } + if (nbufs == 0) { + pr_err("received SRP_CMD with an empty indirect descriptor table\n"); + return -EINVAL; + } + + if (desc_off + struct_size(idb, desc_list, nbufs) > + recv_ioctx->byte_len) { + pr_err("received SRP_CMD indirect table (%d descriptors) that does not fit the %d-byte IU\n", + nbufs, recv_ioctx->byte_len); + return -EINVAL; + } + *data_len = be32_to_cpu(idb->len); return srpt_alloc_rw_ctxs(ioctx, idb->desc_list, nbufs, sg, sg_cnt); diff --git a/drivers/infiniband/ulp/srpt/ib_srpt.h b/drivers/infiniband/ulp/srpt/ib_srpt.h index 506c11b843593b..d9061aa65c1a89 100644 --- a/drivers/infiniband/ulp/srpt/ib_srpt.h +++ b/drivers/infiniband/ulp/srpt/ib_srpt.h @@ -223,8 +223,8 @@ struct srpt_send_ioctx { struct ib_cqe rdma_cqe; enum srpt_command_state state; struct se_cmd cmd; - u8 n_rdma; - u8 n_rw_ctx; + int n_rdma; + int n_rw_ctx; bool queue_status_only; u8 sense_data[TRANSPORT_SENSE_BUFFER]; }; diff --git a/drivers/input/ff-core.c b/drivers/input/ff-core.c index 0e5d1d1ceb4604..133b4622dc49ad 100644 --- a/drivers/input/ff-core.c +++ b/drivers/input/ff-core.c @@ -338,7 +338,7 @@ EXPORT_SYMBOL_GPL(input_ff_create); * * This function is only needed in error path as input core will * automatically free force feedback structures when device is - * destroyed. + * unregistered or destroyed. */ void input_ff_destroy(struct input_dev *dev) { diff --git a/drivers/input/ff-memless.c b/drivers/input/ff-memless.c index d1fefd1dfc0de1..3069436148ec16 100644 --- a/drivers/input/ff-memless.c +++ b/drivers/input/ff-memless.c @@ -483,32 +483,10 @@ static void ml_ff_destroy(struct ff_device *ff) { struct ml_device *ml = ff->private; - /* - * The timer is normally shut down in ml_ff_stop() when the device - * is unregistered. However, we still shut it down here as a safety - * net and for cases where the device was never registered (e.g. - * error paths during probe). - */ timer_shutdown_sync(&ml->timer); - kfree(ml->private); } -static void ml_ff_stop(struct ff_device *ff) -{ - struct ml_device *ml = ff->private; - - /* - * Even though we stop all playing effects when tearing down an - * input device (by the way of evdev calling input_flush_device() - * that calls into input_ff_flush() that stops and erases all - * effects), we do not actually shutdown the timer, and therefore - * we should do it here to prevent it firing after the input - * device is unregistered and its associated resources are freed. - */ - timer_shutdown_sync(&ml->timer); -} - /** * input_ff_create_memless() - create memoryless force-feedback device * @dev: input device supporting force-feedback @@ -543,7 +521,6 @@ int input_ff_create_memless(struct input_dev *dev, void *data, ff->playback = ml_ff_playback; ff->set_gain = ml_ff_set_gain; ff->destroy = ml_ff_destroy; - ff->stop = ml_ff_stop; /* we can emulate periodic effects with RUMBLE */ if (test_bit(FF_RUMBLE, ff->ffbit)) { diff --git a/drivers/input/input.c b/drivers/input/input.c index 0859b60ca924f1..4e732519d05780 100644 --- a/drivers/input/input.c +++ b/drivers/input/input.c @@ -2265,10 +2265,9 @@ static void __input_unregister_device(struct input_dev *dev) input_wakeup_procfs_readers(); } - if (dev->ff && dev->ff->stop) - dev->ff->stop(dev->ff); - device_del(&dev->dev); + + input_ff_destroy(dev); } static void devm_input_device_unregister(struct device *dev, void *res) diff --git a/drivers/input/joystick/xpad.c b/drivers/input/joystick/xpad.c index d2eb48d98fead7..86f4e756a7fc42 100644 --- a/drivers/input/joystick/xpad.c +++ b/drivers/input/joystick/xpad.c @@ -255,10 +255,12 @@ static const struct xpad_device { { 0x0f0d, 0x0063, "Hori Real Arcade Pro Hayabusa (USA) Xbox One", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOXONE }, { 0x0f0d, 0x0067, "HORIPAD ONE", 0, XTYPE_XBOXONE }, { 0x0f0d, 0x0078, "Hori Real Arcade Pro V Kai Xbox One", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOXONE }, + { 0x0f0d, 0x008c, "Real Arcade Pro 4", 0, XTYPE_XBOX360 }, { 0x0f0d, 0x00c5, "Hori Fighting Commander ONE", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOXONE }, { 0x0f0d, 0x00dc, "HORIPAD FPS for Nintendo Switch", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 }, { 0x0f0d, 0x0151, "Hori Racing Wheel Overdrive for Xbox Series X", 0, XTYPE_XBOXONE }, { 0x0f0d, 0x0152, "Hori Racing Wheel Overdrive for Xbox Series X", 0, XTYPE_XBOXONE }, + { 0x0f0d, 0x01b1, "HORI Taiko Controller DX", 0, XTYPE_XBOX360 }, { 0x0f0d, 0x01b2, "HORI Taiko No Tatsujin Drum Controller", MAP_SHARE_BUTTON, XTYPE_XBOXONE }, { 0x0f30, 0x010b, "Philips Recoil", 0, XTYPE_XBOX }, { 0x0f30, 0x0202, "Joytech Advanced Controller", 0, XTYPE_XBOX }, @@ -380,6 +382,7 @@ static const struct xpad_device { { 0x294b, 0x3404, "Snakebyte GAMEPAD RGB X", 0, XTYPE_XBOXONE }, { 0x2993, 0x2001, "TECNO Pocket Go", 0, XTYPE_XBOX360 }, { 0x2dc8, 0x2000, "8BitDo Pro 2 Wired Controller fox Xbox", 0, XTYPE_XBOXONE }, + { 0x2dc8, 0x200a, "8BitDo M30 Wired Controller for Xbox", MAP_SHARE_BUTTON, XTYPE_XBOXONE }, { 0x2dc8, 0x200f, "8BitDo Ultimate 3-mode Controller for Xbox", MAP_SHARE_BUTTON, XTYPE_XBOXONE }, { 0x2dc8, 0x201e, "8BitDo Pro 2 Wired Controller for Xbox", MAP_SHARE_BUTTON, XTYPE_XBOXONE }, { 0x2dc8, 0x3106, "8BitDo Ultimate Wireless / Pro 2 Wired Controller", 0, XTYPE_XBOX360 }, @@ -389,6 +392,7 @@ static const struct xpad_device { { 0x2dc8, 0x6001, "8BitDo SN30 Pro", 0, XTYPE_XBOX360 }, { 0x2e24, 0x0423, "Hyperkin DuchesS Xbox One pad", MAP_SHARE_BUTTON, XTYPE_XBOXONE }, { 0x2e24, 0x0652, "Hyperkin Duke X-Box One pad", 0, XTYPE_XBOXONE }, + { 0x2e24, 0x072e, "Hyperkin Xenon Controller", MAP_SHARE_BUTTON, XTYPE_XBOXONE }, { 0x2e24, 0x1688, "Hyperkin X91 X-Box One pad", 0, XTYPE_XBOXONE }, { 0x2e95, 0x0504, "SCUF Gaming Controller", MAP_SHARE_BUTTON, XTYPE_XBOXONE }, { 0x31e3, 0x1100, "Wooting One", 0, XTYPE_XBOX360 }, @@ -409,6 +413,7 @@ static const struct xpad_device { { 0x3537, 0x100f, "GameSir Nova 2 Lite", 0, XTYPE_XBOX360 }, { 0x3537, 0x1010, "GameSir G7 SE", 0, XTYPE_XBOXONE }, { 0x3537, 0x1040, "GameSir Nova Lite", 0, XTYPE_XBOX360 }, + { 0x3537, 0x109c, "GameSir G7 Pro", MAP_SHARE_BUTTON, XTYPE_XBOXONE }, { 0x3651, 0x1000, "CRKD SG", 0, XTYPE_XBOX360 }, { 0x366c, 0x0005, "ByoWave Proteus Controller", MAP_SHARE_BUTTON, XTYPE_XBOXONE, FLAG_DELAY_INIT }, { 0x3767, 0x0101, "Fanatec Speedster 3 Forceshock Wheel", 0, XTYPE_XBOX }, diff --git a/drivers/input/misc/da7280.c b/drivers/input/misc/da7280.c index 995d3f7af41a15..4c60fd4fb93211 100644 --- a/drivers/input/misc/da7280.c +++ b/drivers/input/misc/da7280.c @@ -1226,7 +1226,6 @@ static int da7280_probe(struct i2c_client *client) input_set_capability(haptics->input_dev, EV_FF, FF_PERIODIC); input_set_capability(haptics->input_dev, EV_FF, FF_CUSTOM); input_set_capability(haptics->input_dev, EV_FF, FF_CONSTANT); - input_set_capability(haptics->input_dev, EV_FF, FF_GAIN); error = input_ff_create(haptics->input_dev, DA7280_FF_EFFECT_COUNT_MAX); diff --git a/drivers/input/misc/max77693-haptic.c b/drivers/input/misc/max77693-haptic.c index 96d6d4620eb4db..2bf4581b6adc40 100644 --- a/drivers/input/misc/max77693-haptic.c +++ b/drivers/input/misc/max77693-haptic.c @@ -278,6 +278,7 @@ static int max77693_haptic_open(struct input_dev *dev) if (error) { dev_err(haptic->dev, "failed to enable regulator: %d\n", error); + max77843_haptic_bias(haptic, false); return error; } diff --git a/drivers/input/mouse/atarimouse.c b/drivers/input/mouse/atarimouse.c index b1219cc4d9a2a0..c5b794262e856b 100644 --- a/drivers/input/mouse/atarimouse.c +++ b/drivers/input/mouse/atarimouse.c @@ -60,7 +60,7 @@ extern int atari_mouse_buttons; static struct input_dev *atamouse_dev; -static void atamouse_interrupt(char *buf) +static void atamouse_interrupt(u8 *buf) { int buttons, dx, dy; @@ -71,8 +71,8 @@ static void atamouse_interrupt(char *buf) #endif /* only relative events get here */ - dx = buf[1]; - dy = buf[2]; + dx = (s8)buf[1]; + dy = (s8)buf[2]; input_report_rel(atamouse_dev, REL_X, dx); input_report_rel(atamouse_dev, REL_Y, dy); diff --git a/drivers/input/mouse/cyapa.c b/drivers/input/mouse/cyapa.c index c086d28f1412a4..78819d32bd2c94 100644 --- a/drivers/input/mouse/cyapa.c +++ b/drivers/input/mouse/cyapa.c @@ -900,8 +900,10 @@ static ssize_t cyapa_update_rt_suspend_scanrate(struct device *dev, pm_runtime_get_sync(dev); error = mutex_lock_interruptible(&cyapa->state_sync_lock); - if (error) + if (error) { + pm_runtime_put_autosuspend(dev); return error; + } cyapa->runtime_suspend_sleep_time = min_t(u16, time, 1000); cyapa->runtime_suspend_power_mode = diff --git a/drivers/input/mouse/trackpoint.c b/drivers/input/mouse/trackpoint.c index 3bd8fdf56cd3d2..2dde8cc5cab155 100644 --- a/drivers/input/mouse/trackpoint.c +++ b/drivers/input/mouse/trackpoint.c @@ -25,6 +25,7 @@ static const char * const trackpoint_variants[] = { [TP_VARIANT_NXP] = "NXP", [TP_VARIANT_JYT_SYNAPTICS] = "JYT_Synaptics", [TP_VARIANT_SYNAPTICS] = "Synaptics", + [TP_VARIANT_JYT_NDT] = "JYT_NDT" }; /* @@ -285,6 +286,7 @@ static int trackpoint_start_protocol(struct psmouse *psmouse, case TP_VARIANT_ELAN: case TP_VARIANT_NXP: case TP_VARIANT_JYT_SYNAPTICS: + case TP_VARIANT_JYT_NDT: case TP_VARIANT_SYNAPTICS: if (variant_id) *variant_id = param[0]; diff --git a/drivers/input/mouse/trackpoint.h b/drivers/input/mouse/trackpoint.h index 3e03cdb3944984..2aa76311e40043 100644 --- a/drivers/input/mouse/trackpoint.h +++ b/drivers/input/mouse/trackpoint.h @@ -30,6 +30,7 @@ #define TP_VARIANT_NXP 0x04 #define TP_VARIANT_JYT_SYNAPTICS 0x05 #define TP_VARIANT_SYNAPTICS 0x06 +#define TP_VARIANT_JYT_NDT 0x07 /* * Commands diff --git a/drivers/input/touchscreen/goodix_fwupload.c b/drivers/input/touchscreen/goodix_fwupload.c index 5ae9a109ba0d17..888da7538c065b 100644 --- a/drivers/input/touchscreen/goodix_fwupload.c +++ b/drivers/input/touchscreen/goodix_fwupload.c @@ -281,6 +281,8 @@ static int goodix_prepare_bak_ref(struct goodix_ts_data *ts) driver_num, sensor_num, have_key); ts->bak_ref_len = (driver_num * (sensor_num - 2) + 2) * 2; + if (ts->bak_ref_len < 2) + return -EINVAL; ts->bak_ref = devm_kzalloc(&ts->client->dev, ts->bak_ref_len, GFP_KERNEL); @@ -409,7 +411,7 @@ void goodix_save_bak_ref(struct goodix_ts_data *ts) int error; u8 val; - if (!ts->firmware_name) + if (!ts->firmware_name || !ts->bak_ref) return; error = goodix_i2c_read(ts->client, GOODIX_REG_STATUS, &val, 1); diff --git a/drivers/iommu/amd/iommu.c b/drivers/iommu/amd/iommu.c index 41ee4ad1dcf826..0f04013f590d44 100644 --- a/drivers/iommu/amd/iommu.c +++ b/drivers/iommu/amd/iommu.c @@ -2792,6 +2792,15 @@ static const struct iommu_domain_ops amdv2_ops = { .enforce_cache_coherency = amd_iommu_enforce_cache_coherency, }; +/* + * Force a clflush on Cezanne (family 19h, model 50h) when the v2 + * page-table is enabled. + */ +static bool amd_iommu_force_incoherent(void) +{ + return boot_cpu_data.x86 == 0x19 && boot_cpu_data.x86_model == 0x50; +} + static struct iommu_domain *amd_iommu_domain_alloc_paging_v2(struct device *dev, u32 flags) { @@ -2810,6 +2819,13 @@ static struct iommu_domain *amd_iommu_domain_alloc_paging_v2(struct device *dev, domain->iommu.nid = dev_to_node(dev); cfg.common.features = BIT(PT_FEAT_X86_64_AMD_ENCRYPT_TABLES); + + if (amd_iommu_force_incoherent()) { + cfg.common.features |= BIT(PT_FEAT_DMA_INCOHERENT); + /* pt_iommu_init() rejects DMA_INCOHERENT without a device */ + domain->iommu.iommu_device = dev; + } + if (amd_iommu_np_cache) cfg.common.features |= BIT(PT_FEAT_FLUSH_RANGE_NO_GAPS); else diff --git a/drivers/iommu/hyperv/hv-iommu-guest.c b/drivers/iommu/hyperv/hv-iommu-guest.c index 9f4fa431509168..0110a1529a2361 100644 --- a/drivers/iommu/hyperv/hv-iommu-guest.c +++ b/drivers/iommu/hyperv/hv-iommu-guest.c @@ -107,7 +107,7 @@ static int hv_create_device_domain(struct hv_iommu_domain *hv_domain) return hv_result_to_errno(status); } -static void hv_delete_device_domain(struct hv_iommu_domain *hv_domain) +static int hv_delete_device_domain(struct hv_iommu_domain *hv_domain) { u64 status; unsigned long flags; @@ -122,11 +122,15 @@ static void hv_delete_device_domain(struct hv_iommu_domain *hv_domain) local_irq_restore(flags); - if (!hv_result_success(status)) - hv_status_err(status, "HVCALL_DELETE_DEVICE_DOMAIN failed\n"); + /* If the domain still exists, its ID cannot be reused */ + if (WARN(!hv_result_success(status), + "HVCALL_DELETE_DEVICE_DOMAIN failed: %#llx (%s)\n", + status, hv_result_to_string(status))) + return hv_result_to_errno(status); ida_free(&hv_domain->hv_iommu->domain_ids, hv_domain->device_domain.domain_id.id); + return 0; } static int @@ -466,11 +470,16 @@ static void hv_iommu_paging_domain_free(struct iommu_domain *domain) { struct hv_iommu_domain *hv_domain = to_hv_iommu_domain(domain); + /* + * If the hypervisor still has the domain, it may still use its page + * tables, so leak them. + */ + if (hv_delete_device_domain(hv_domain)) + return; + /* Free all remaining mappings */ pt_iommu_deinit(&hv_domain->pt_iommu); - hv_delete_device_domain(hv_domain); - kfree(hv_domain); } @@ -531,10 +540,23 @@ static struct iommu_domain *hv_iommu_domain_alloc_paging(struct device *dev) settings.page_table_root = pt_info.gcr3_pt; settings.flags.first_stage_paging_mode = pt_info.levels == 5; - ret = hv_create_configure_device_domain(hv_domain, &settings); + ret = hv_create_device_domain(hv_domain); if (ret) goto err_pt_deinit; + ret = hv_configure_device_domain(hv_domain, &settings); + if (ret) { + /* + * The current hypervisor does not adopt the page table root + * when the configure call fails. Still, keep the page tables + * while it has the domain, as hv_iommu_paging_domain_free() + * does. + */ + if (hv_delete_device_domain(hv_domain)) + return ERR_PTR(ret); + goto err_pt_deinit; + } + return &hv_domain->domain; err_pt_deinit: diff --git a/drivers/iommu/iommufd/pages.c b/drivers/iommu/iommufd/pages.c index 2f6153108add73..fcdbde007a9ab5 100644 --- a/drivers/iommu/iommufd/pages.c +++ b/drivers/iommu/iommufd/pages.c @@ -781,6 +781,7 @@ struct pfn_reader_user { struct file *file; struct folio **ufolios; size_t ufolios_len; + unsigned long ufolios_count; unsigned long ufolios_offset; struct folio **ufolios_next; }; @@ -800,6 +801,7 @@ static void pfn_reader_user_init(struct pfn_reader_user *user, user->file = (pages->type == IOPT_ADDRESS_FILE) ? pages->file : NULL; user->ufolios = NULL; user->ufolios_len = 0; + user->ufolios_count = 0; user->ufolios_next = NULL; user->ufolios_offset = 0; } @@ -843,6 +845,7 @@ static long pin_memfd_pages(struct pfn_reader_user *user, unsigned long start, offset >>= PAGE_SHIFT; user->ufolios_next = user->ufolios; + user->ufolios_count = nfolios; user->ufolios_offset = offset; for (i = 0; i < nfolios; i++) { @@ -859,8 +862,12 @@ static long pin_memfd_pages(struct pfn_reader_user *user, unsigned long start, } else { int rc = folio_add_pins(folio, npin - 1); - if (rc) + if (rc) { + unpin_user_pages(user->upages, + upages - user->upages); + unpin_folios(user->ufolios + i, nfolios - i); return rc; + } while (npin--) *upages++ = folio_page(folio, offset++); @@ -1251,14 +1258,14 @@ static int pfn_reader_next(struct pfn_reader *pfns) return -EINVAL; rc = pfn_reader_fill_span(pfns); + pfns->batch_end_index = pfns->batch_start_index + + pfns->batch.total_pfns; if (rc) return rc; if (WARN_ON(!pfns->batch.total_pfns)) return -EINVAL; - pfns->batch_end_index = - pfns->batch_start_index + pfns->batch.total_pfns; if (pfns->batch_end_index == pfns->span.last_used + 1) interval_tree_double_span_iter_next(&pfns->span); @@ -1320,7 +1327,7 @@ static void pfn_reader_release_pins(struct pfn_reader *pfns) if (!user->file) { unpin_user_pages(user->upages + start_index, npages); } else { - long n = user->ufolios_len / sizeof(*user->ufolios); + const unsigned long n = user->ufolios_count; unpin_folios(user->ufolios_next, user->ufolios + n - user->ufolios_next); diff --git a/drivers/iommu/vsi-iommu.c b/drivers/iommu/vsi-iommu.c index 0633fe82d44366..f0963e0406c7e2 100644 --- a/drivers/iommu/vsi-iommu.c +++ b/drivers/iommu/vsi-iommu.c @@ -196,7 +196,7 @@ static irqreturn_t vsi_iommu_irq(int irq, void *dev_id) dma_addr_t iova; u32 status; - if (pm_runtime_resume_and_get(iommu->dev) < 0) + if (pm_runtime_get_if_active(iommu->dev) <= 0) return IRQ_NONE; spin_lock_irqsave(&iommu->lock, flags); @@ -369,7 +369,8 @@ static void vsi_iommu_flush_tlb(struct iommu_domain *domain) struct vsi_iommu *iommu; list_for_each_entry(iommu, &vsi_domain->iommus, node) { - if (pm_runtime_get(iommu->dev) < 0) + /* A suspended IOMMU is flushed when it resumes */ + if (pm_runtime_get_if_active(iommu->dev) <= 0) continue; spin_lock(&iommu->lock); @@ -496,31 +497,42 @@ static void vsi_iommu_disable(struct vsi_iommu *iommu) iommu->enable = false; } +/* Take the IOMMU off the list of its paging domain, if it has one. */ +static void vsi_iommu_list_del(struct vsi_iommu *iommu) +{ + struct vsi_iommu_domain *vsi_domain; + unsigned long flags; + + if (!iommu->domain || iommu->domain == &vsi_identity_domain) + return; + + vsi_domain = to_vsi_domain(iommu->domain); + spin_lock_irqsave(&vsi_domain->lock, flags); + list_del_init(&iommu->node); + spin_unlock_irqrestore(&vsi_domain->lock, flags); +} + static int vsi_iommu_identity_attach(struct iommu_domain *domain, struct device *dev, struct iommu_domain *old) { struct vsi_iommu *iommu = dev_iommu_priv_get(dev); - struct vsi_iommu_domain *vsi_domain = to_vsi_domain(domain); unsigned long flags; int ret; + if (iommu->domain == domain) + return 0; + ret = pm_runtime_resume_and_get(iommu->dev); if (ret < 0) return ret; - spin_lock_irqsave(&vsi_domain->lock, flags); - spin_lock(&iommu->lock); - if (iommu->domain == domain) - goto unlock; + vsi_iommu_list_del(iommu); + spin_lock_irqsave(&iommu->lock, flags); vsi_iommu_disable(iommu); - list_del_init(&iommu->node); - iommu->domain = domain; + spin_unlock_irqrestore(&iommu->lock, flags); -unlock: - spin_unlock(&iommu->lock); - spin_unlock_irqrestore(&vsi_domain->lock, flags); pm_runtime_put_autosuspend(iommu->dev); return 0; } @@ -536,15 +548,18 @@ static struct iommu_domain vsi_identity_domain = { static void vsi_iommu_enable(struct vsi_iommu *iommu, struct iommu_domain *domain) { - struct vsi_iommu_domain *vsi_domain = to_vsi_domain(domain); + struct vsi_iommu_domain *vsi_domain; if (domain == &vsi_identity_domain) return; + vsi_domain = to_vsi_domain(domain); writel(vsi_domain->pta_dma, iommu->regs + VSI_MMU_AHB_TLB_ARRAY_BASE_L_BASE); writel(VSI_MMU_OUT_OF_BOUND, iommu->regs + VSI_MMU_CONFIG1_BASE); writel(VSI_MMU_BIT_ENABLE, iommu->regs + VSI_MMU_AHB_EXCEPTION_BASE); writel(VSI_MMU_BIT_ENABLE, iommu->regs + VSI_MMU_AHB_CONTROL_BASE); + writel(VSI_MMU_BIT_FLUSH, iommu->regs + VSI_MMU_FLUSH_BASE); + writel(0, iommu->regs + VSI_MMU_FLUSH_BASE); iommu->enable = true; } @@ -560,14 +575,13 @@ static int vsi_iommu_attach_device(struct iommu_domain *domain, if (ret < 0) return ret; + vsi_iommu_list_del(iommu); + spin_lock_irqsave(&vsi_domain->lock, flags); spin_lock(&iommu->lock); vsi_iommu_enable(iommu, domain); - writel(VSI_MMU_BIT_FLUSH, iommu->regs + VSI_MMU_FLUSH_BASE); - writel(0, iommu->regs + VSI_MMU_FLUSH_BASE); - list_del_init(&iommu->node); list_add_tail(&iommu->node, &vsi_domain->iommus); iommu->domain = domain; @@ -693,8 +707,10 @@ static int vsi_iommu_probe(struct platform_device *pdev) return err; iommu->irq = platform_get_irq(pdev, 0); - if (iommu->irq < 0) - return iommu->irq; + if (iommu->irq < 0) { + err = iommu->irq; + goto err_unprepare_clocks; + } err = devm_request_irq(iommu->dev, iommu->irq, vsi_iommu_irq, IRQF_SHARED, dev_name(dev), iommu); @@ -740,7 +756,7 @@ static int __maybe_unused vsi_iommu_suspend(struct device *dev) { struct vsi_iommu *iommu = dev_get_drvdata(dev); - vsi_iommu_disable(iommu); + iommu->enable = false; clk_bulk_disable(iommu->num_clocks, iommu->clocks); @@ -757,15 +773,10 @@ static int __maybe_unused vsi_iommu_resume(struct device *dev) if (ret) return ret; - if (iommu->domain) { - struct vsi_iommu_domain *vsi_domain = to_vsi_domain(iommu->domain); - - spin_lock_irqsave(&vsi_domain->lock, flags); - spin_lock(&iommu->lock); + spin_lock_irqsave(&iommu->lock, flags); + if (iommu->domain) vsi_iommu_enable(iommu, iommu->domain); - spin_unlock(&iommu->lock); - spin_unlock_irqrestore(&vsi_domain->lock, flags); - } + spin_unlock_irqrestore(&iommu->lock, flags); return 0; } @@ -780,7 +791,7 @@ static struct platform_driver rockchip_vsi_iommu_driver = { .driver = { .name = "vsi_iommu", .of_match_table = vsi_iommu_dt_ids, - .pm = pm_sleep_ptr(&vsi_iommu_pm_ops), + .pm = pm_ptr(&vsi_iommu_pm_ops), .suppress_bind_attrs = true, }, }; diff --git a/drivers/irqchip/Kconfig b/drivers/irqchip/Kconfig index 136bab41f8011f..ca915fca0ef501 100644 --- a/drivers/irqchip/Kconfig +++ b/drivers/irqchip/Kconfig @@ -37,7 +37,7 @@ config ARM_GIC_V3 bool select IRQ_DOMAIN_HIERARCHY select GENERIC_IRQ_EFFECTIVE_AFF_MASK if SMP - select HAVE_ARM_SMCCC_DISCOVERY + select HAVE_ARM_SMCCC_DISCOVERY if ARM64 select IRQ_MSI_IOMMU config ARM_GIC_ITS_PARENT diff --git a/drivers/irqchip/irq-gic-v4.c b/drivers/irqchip/irq-gic-v4.c index 8455b4a5fbb0d5..019aa0ded1bf95 100644 --- a/drivers/irqchip/irq-gic-v4.c +++ b/drivers/irqchip/irq-gic-v4.c @@ -147,16 +147,24 @@ static int its_alloc_vcpu_sgis(struct its_vpe *vpe, int idx) return 0; err: - if (vpe->sgi_domain) + if (vpe->sgi_domain) { irq_domain_remove(vpe->sgi_domain); - if (vpe->fwnode) + vpe->sgi_domain = NULL; + } + if (vpe->fwnode) { irq_domain_free_fwnode(vpe->fwnode); + vpe->fwnode = NULL; + } kfree(name); return -ENOMEM; } +static void its_free_sgi_irqs(struct its_vm *vm); + int its_alloc_vcpu_irqs(struct its_vm *vm) { + static struct lock_class_key vpe_irq_lock_class; + static struct lock_class_key vpe_irq_request_class; int vpe_base_irq, i; vm->fwnode = irq_domain_alloc_named_id_fwnode("GICv4-vpe", @@ -183,18 +191,28 @@ int its_alloc_vcpu_irqs(struct its_vm *vm) for (i = 0; i < vm->nr_vpes; i++) { int ret; vm->vpes[i]->irq = vpe_base_irq + i; + irq_set_lockdep_class(vm->vpes[i]->irq, &vpe_irq_lock_class, + &vpe_irq_request_class); + irq_set_nothread(vm->vpes[i]->irq); ret = its_alloc_vcpu_sgis(vm->vpes[i], i); if (ret) - goto err; + goto err_free_irqs; } return 0; +err_free_irqs: + its_free_sgi_irqs(vm); + irq_domain_free_irqs(vpe_base_irq, vm->nr_vpes); err: - if (vm->domain) + if (vm->domain) { irq_domain_remove(vm->domain); - if (vm->fwnode) + vm->domain = NULL; + } + if (vm->fwnode) { irq_domain_free_fwnode(vm->fwnode); + vm->fwnode = NULL; + } return -ENOMEM; } @@ -207,14 +225,21 @@ static void its_free_sgi_irqs(struct its_vm *vm) return; for (i = 0; i < vm->nr_vpes; i++) { - unsigned int irq = irq_find_mapping(vm->vpes[i]->sgi_domain, 0); + unsigned int irq; + + /* irq_find_mapping() falls back to the default domain on NULL. */ + if (!vm->vpes[i]->sgi_domain) + continue; + irq = irq_find_mapping(vm->vpes[i]->sgi_domain, 0); if (WARN_ON(!irq)) continue; irq_domain_free_irqs(irq, 16); irq_domain_remove(vm->vpes[i]->sgi_domain); irq_domain_free_fwnode(vm->vpes[i]->fwnode); + vm->vpes[i]->sgi_domain = NULL; + vm->vpes[i]->fwnode = NULL; } } @@ -224,6 +249,8 @@ void its_free_vcpu_irqs(struct its_vm *vm) irq_domain_free_irqs(vm->vpes[0]->irq, vm->nr_vpes); irq_domain_remove(vm->domain); irq_domain_free_fwnode(vm->fwnode); + vm->domain = NULL; + vm->fwnode = NULL; } static int its_send_vpe_cmd(struct its_vpe *vpe, struct its_cmd_info *info) diff --git a/drivers/memory/atmel-ebi.c b/drivers/memory/atmel-ebi.c index cf6b404afaf1fb..2ab79d9231392b 100644 --- a/drivers/memory/atmel-ebi.c +++ b/drivers/memory/atmel-ebi.c @@ -561,7 +561,7 @@ static int atmel_ebi_probe(struct platform_device *pdev) } ret = clk_prepare_enable(ebi->smc.clk); if (ret) - return ret; + goto err_put_clk; /* * The sama5d3 does not provide an EBICSA register and thus does need @@ -571,14 +571,16 @@ static int atmel_ebi_probe(struct platform_device *pdev) ebi->regmap = syscon_regmap_lookup_by_phandle(np, ebi->caps->regmap_name); - if (IS_ERR(ebi->regmap)) - return PTR_ERR(ebi->regmap); + if (IS_ERR(ebi->regmap)) { + ret = PTR_ERR(ebi->regmap); + goto err_disable_clk; + } } ret = of_property_read_u32(np, "#address-cells", &val); if (ret) { dev_err(dev, "missing #address-cells property\n"); - return ret; + goto err_disable_clk; } reg_cells = val; @@ -586,7 +588,7 @@ static int atmel_ebi_probe(struct platform_device *pdev) ret = of_property_read_u32(np, "#size-cells", &val); if (ret) { dev_err(dev, "missing #address-cells property\n"); - return ret; + goto err_disable_clk; } reg_cells += val; @@ -602,11 +604,22 @@ static int atmel_ebi_probe(struct platform_device *pdev) ret = atmel_ebi_dev_disable(ebi, child); if (ret) - return ret; + goto err_disable_clk; } } - return of_platform_populate(np, NULL, NULL, dev); + ret = of_platform_populate(np, NULL, NULL, dev); + if (ret) + goto err_disable_clk; + + return 0; + +err_disable_clk: + clk_disable_unprepare(ebi->smc.clk); +err_put_clk: + clk_put(ebi->smc.clk); + + return ret; } static __maybe_unused int atmel_ebi_resume(struct device *dev) diff --git a/drivers/memory/fsl_ifc.c b/drivers/memory/fsl_ifc.c index db2d239aeba890..ad9491c5db1c40 100644 --- a/drivers/memory/fsl_ifc.c +++ b/drivers/memory/fsl_ifc.c @@ -63,6 +63,23 @@ int fsl_ifc_find(phys_addr_t addr_base) } EXPORT_SYMBOL(fsl_ifc_find); +static u32 fsl_ifc_ctrl_in32(struct fsl_ifc_ctrl *ctrl, void __iomem *addr) +{ + if (ctrl->little_endian) + return ioread32(addr); + + return ioread32be(addr); +} + +static void fsl_ifc_ctrl_out32(struct fsl_ifc_ctrl *ctrl, u32 val, + void __iomem *addr) +{ + if (ctrl->little_endian) + iowrite32(val, addr); + else + iowrite32be(val, addr); +} + static int fsl_ifc_ctrl_init(struct fsl_ifc_ctrl *ctrl) { struct fsl_ifc_global __iomem *ifc = ctrl->gregs; @@ -70,16 +87,18 @@ static int fsl_ifc_ctrl_init(struct fsl_ifc_ctrl *ctrl) /* * Clear all the common status and event registers */ - if (ifc_in32(&ifc->cm_evter_stat) & IFC_CM_EVTER_STAT_CSER) - ifc_out32(IFC_CM_EVTER_STAT_CSER, &ifc->cm_evter_stat); + if (fsl_ifc_ctrl_in32(ctrl, &ifc->cm_evter_stat) & IFC_CM_EVTER_STAT_CSER) + fsl_ifc_ctrl_out32(ctrl, IFC_CM_EVTER_STAT_CSER, + &ifc->cm_evter_stat); /* enable all error and events */ - ifc_out32(IFC_CM_EVTER_EN_CSEREN, &ifc->cm_evter_en); + fsl_ifc_ctrl_out32(ctrl, IFC_CM_EVTER_EN_CSEREN, &ifc->cm_evter_en); /* enable all error and event interrupts */ - ifc_out32(IFC_CM_EVTER_INTR_EN_CSERIREN, &ifc->cm_evter_intr_en); - ifc_out32(0x0, &ifc->cm_erattr0); - ifc_out32(0x0, &ifc->cm_erattr1); + fsl_ifc_ctrl_out32(ctrl, IFC_CM_EVTER_INTR_EN_CSERIREN, + &ifc->cm_evter_intr_en); + fsl_ifc_ctrl_out32(ctrl, 0x0, &ifc->cm_erattr0); + fsl_ifc_ctrl_out32(ctrl, 0x0, &ifc->cm_erattr1); return 0; } @@ -89,8 +108,10 @@ static void fsl_ifc_ctrl_remove(struct platform_device *dev) struct fsl_ifc_ctrl *ctrl = dev_get_drvdata(&dev->dev); of_platform_depopulate(&dev->dev); - free_irq(ctrl->nand_irq, ctrl); + if (ctrl->nand_irq) + free_irq(ctrl->nand_irq, ctrl); free_irq(ctrl->irq, ctrl); + fsl_ifc_ctrl_dev = NULL; irq_dispose_mapping(ctrl->nand_irq); irq_dispose_mapping(ctrl->irq); @@ -204,81 +225,83 @@ static int fsl_ifc_ctrl_probe(struct platform_device *dev) int ret = 0; int version, banks; void __iomem *addr; + struct fsl_ifc_ctrl *ctrl; dev_info(&dev->dev, "Freescale Integrated Flash Controller\n"); - fsl_ifc_ctrl_dev = devm_kzalloc_obj(&dev->dev, *fsl_ifc_ctrl_dev); - if (!fsl_ifc_ctrl_dev) + ctrl = devm_kzalloc_obj(&dev->dev, *ctrl); + if (!ctrl) return -ENOMEM; - dev_set_drvdata(&dev->dev, fsl_ifc_ctrl_dev); + dev_set_drvdata(&dev->dev, ctrl); /* IOMAP the entire IFC region */ - fsl_ifc_ctrl_dev->gregs = of_iomap(dev->dev.of_node, 0); - if (!fsl_ifc_ctrl_dev->gregs) { + ctrl->gregs = of_iomap(dev->dev.of_node, 0); + if (!ctrl->gregs) { dev_err(&dev->dev, "failed to get memory region\n"); return -ENODEV; } if (of_property_read_bool(dev->dev.of_node, "little-endian")) { - fsl_ifc_ctrl_dev->little_endian = true; + ctrl->little_endian = true; dev_dbg(&dev->dev, "IFC REGISTERS are LITTLE endian\n"); } else { - fsl_ifc_ctrl_dev->little_endian = false; + ctrl->little_endian = false; dev_dbg(&dev->dev, "IFC REGISTERS are BIG endian\n"); } - version = ifc_in32(&fsl_ifc_ctrl_dev->gregs->ifc_rev) & - FSL_IFC_VERSION_MASK; + version = fsl_ifc_ctrl_in32(ctrl, &ctrl->gregs->ifc_rev) & + FSL_IFC_VERSION_MASK; banks = (version == FSL_IFC_VERSION_1_0_0) ? 4 : 8; dev_info(&dev->dev, "IFC version %d.%d, %d banks\n", version >> 24, (version >> 16) & 0xf, banks); - fsl_ifc_ctrl_dev->version = version; - fsl_ifc_ctrl_dev->banks = banks; + ctrl->version = version; + ctrl->banks = banks; - addr = fsl_ifc_ctrl_dev->gregs; + addr = ctrl->gregs; if (version >= FSL_IFC_VERSION_2_0_0) addr += PGOFFSET_64K; else addr += PGOFFSET_4K; - fsl_ifc_ctrl_dev->rregs = addr; + ctrl->rregs = addr; /* get the Controller level irq */ - fsl_ifc_ctrl_dev->irq = irq_of_parse_and_map(dev->dev.of_node, 0); - if (fsl_ifc_ctrl_dev->irq == 0) { + ctrl->irq = irq_of_parse_and_map(dev->dev.of_node, 0); + if (ctrl->irq == 0) { dev_err(&dev->dev, "failed to get irq resource for IFC\n"); ret = -ENODEV; goto err; } /* get the nand machine irq */ - fsl_ifc_ctrl_dev->nand_irq = - irq_of_parse_and_map(dev->dev.of_node, 1); + ctrl->nand_irq = irq_of_parse_and_map(dev->dev.of_node, 1); - fsl_ifc_ctrl_dev->dev = &dev->dev; + ctrl->dev = &dev->dev; - ret = fsl_ifc_ctrl_init(fsl_ifc_ctrl_dev); + ret = fsl_ifc_ctrl_init(ctrl); if (ret < 0) goto err_unmap_nandirq; - init_waitqueue_head(&fsl_ifc_ctrl_dev->nand_wait); + init_waitqueue_head(&ctrl->nand_wait); + + fsl_ifc_ctrl_dev = ctrl; - ret = request_irq(fsl_ifc_ctrl_dev->irq, fsl_ifc_ctrl_irq, IRQF_SHARED, - "fsl-ifc", fsl_ifc_ctrl_dev); + ret = request_irq(ctrl->irq, fsl_ifc_ctrl_irq, IRQF_SHARED, + "fsl-ifc", ctrl); if (ret != 0) { dev_err(&dev->dev, "failed to install irq (%d)\n", - fsl_ifc_ctrl_dev->irq); - goto err_unmap_nandirq; + ctrl->irq); + goto err_clear_global; } - if (fsl_ifc_ctrl_dev->nand_irq) { - ret = request_irq(fsl_ifc_ctrl_dev->nand_irq, fsl_ifc_nand_irq, - 0, "fsl-ifc-nand", fsl_ifc_ctrl_dev); + if (ctrl->nand_irq) { + ret = request_irq(ctrl->nand_irq, fsl_ifc_nand_irq, 0, + "fsl-ifc-nand", ctrl); if (ret != 0) { dev_err(&dev->dev, "failed to install irq (%d)\n", - fsl_ifc_ctrl_dev->nand_irq); + ctrl->nand_irq); goto err_free_irq; } } @@ -291,14 +314,17 @@ static int fsl_ifc_ctrl_probe(struct platform_device *dev) return 0; err_free_nandirq: - free_irq(fsl_ifc_ctrl_dev->nand_irq, fsl_ifc_ctrl_dev); + if (ctrl->nand_irq) + free_irq(ctrl->nand_irq, ctrl); err_free_irq: - free_irq(fsl_ifc_ctrl_dev->irq, fsl_ifc_ctrl_dev); + free_irq(ctrl->irq, ctrl); +err_clear_global: + fsl_ifc_ctrl_dev = NULL; err_unmap_nandirq: - irq_dispose_mapping(fsl_ifc_ctrl_dev->nand_irq); - irq_dispose_mapping(fsl_ifc_ctrl_dev->irq); + irq_dispose_mapping(ctrl->nand_irq); + irq_dispose_mapping(ctrl->irq); err: - iounmap(fsl_ifc_ctrl_dev->gregs); + iounmap(ctrl->gregs); return ret; } diff --git a/drivers/memory/tegra/tegra186.c b/drivers/memory/tegra/tegra186.c index 103f327b636524..f202e87dd81a41 100644 --- a/drivers/memory/tegra/tegra186.c +++ b/drivers/memory/tegra/tegra186.c @@ -146,6 +146,7 @@ static int tegra186_mc_probe_device(struct tegra_mc *mc, struct device *dev) } } + of_node_put(args.np); index++; } #endif diff --git a/drivers/memory/tegra/tegra210-emc-core.c b/drivers/memory/tegra/tegra210-emc-core.c index 2ee8249b20050d..b645191d8a0460 100644 --- a/drivers/memory/tegra/tegra210-emc-core.c +++ b/drivers/memory/tegra/tegra210-emc-core.c @@ -1946,12 +1946,6 @@ static int tegra210_emc_probe(struct platform_device *pdev) config->same_freq = true; } - err = tegra210_clk_emc_attach(emc->clk, &emc->provider); - if (err < 0) { - dev_err(&pdev->dev, "failed to attach to EMC clock: %d\n", err); - goto release; - } - emc->clkchange_delay = 100; emc->training_interval = 100; dev_set_drvdata(emc->dev, emc); @@ -1963,6 +1957,12 @@ static int tegra210_emc_probe(struct platform_device *pdev) timer_setup(&emc->training, tegra210_emc_train, 0); + err = tegra210_clk_emc_attach(emc->clk, &emc->provider); + if (err < 0) { + dev_err(&pdev->dev, "failed to attach to EMC clock: %d\n", err); + goto release; + } + tegra210_emc_debugfs_init(emc); cd = devm_thermal_of_child_cooling_device_register(emc->dev, np, "emc", emc, @@ -1978,6 +1978,8 @@ static int tegra210_emc_probe(struct platform_device *pdev) detach: debugfs_remove_recursive(emc->debugfs.root); + timer_shutdown_sync(&emc->training); + timer_shutdown_sync(&emc->refresh_timer); tegra210_clk_emc_detach(emc->clk); release: of_reserved_mem_device_release(emc->dev); @@ -1990,6 +1992,8 @@ static void tegra210_emc_remove(struct platform_device *pdev) struct tegra210_emc *emc = platform_get_drvdata(pdev); debugfs_remove_recursive(emc->debugfs.root); + timer_shutdown_sync(&emc->training); + timer_shutdown_sync(&emc->refresh_timer); tegra210_clk_emc_detach(emc->clk); of_reserved_mem_device_release(emc->dev); } diff --git a/drivers/misc/bcm-vk/bcm_vk_sg.c b/drivers/misc/bcm-vk/bcm_vk_sg.c index 8662bb8651293c..b237a5332b7f0a 100644 --- a/drivers/misc/bcm-vk/bcm_vk_sg.c +++ b/drivers/misc/bcm-vk/bcm_vk_sg.c @@ -78,7 +78,8 @@ static int bcm_vk_dma_alloc(struct device *dev, dma->nr_pages = (err >= 0) ? err : 0; dev_err(dev, "get_user_pages_fast, err=%d [%d]\n", err, dma->nr_pages); - return err < 0 ? err : -EINVAL; + err = err < 0 ? err : -EINVAL; + goto err_pages; } /* Max size of sg list is 1 per mapped page + fields at start */ @@ -90,8 +91,10 @@ static int bcm_vk_dma_alloc(struct device *dev, dma->sglen, &dma->handle, GFP_KERNEL); - if (!dma->sglist) - return -ENOMEM; + if (!dma->sglist) { + err = -ENOMEM; + goto err_pages; + } dma->sglist[SGLIST_NUM_SG] = 0; dma->sglist[SGLIST_TOTALSIZE] = vkdata->size; @@ -108,8 +111,8 @@ static int bcm_vk_dma_alloc(struct device *dev, dma->direction); transfer_size = size; if (unlikely(dma_mapping_error(dev, sg_addr))) { - __free_page(dma->pages[0]); - return -EIO; + err = -EIO; + goto err_sglist; } for (i = 1; i < dma->nr_pages; i++) { @@ -121,8 +124,8 @@ static int bcm_vk_dma_alloc(struct device *dev, size, dma->direction); if (unlikely(dma_mapping_error(dev, addr))) { - __free_page(dma->pages[i]); - return -EIO; + err = -EIO; + goto err_unmap; } /* @@ -167,6 +170,32 @@ static int bcm_vk_dma_alloc(struct device *dev, #endif return 0; + +err_unmap: + /* + * Unmap completed SG entries and the in-progress DMA range, + * which has not been written to the SG list yet. + */ + sgdata = (struct _vk_data *)&dma->sglist[SGLIST_VKDATA_START]; + for (i = 0; i < dma->sglist[SGLIST_NUM_SG]; i++) { + size = sgdata[i].size; + addr = get_unaligned(&sgdata[i].address); + dma_unmap_page(dev, addr, size, dma->direction); + } + dma_unmap_page(dev, sg_addr, transfer_size, dma->direction); + +err_sglist: + dma_free_coherent(dev, dma->sglen, dma->sglist, dma->handle); + +err_pages: + for (i = 0; i < dma->nr_pages; i++) + put_page(dma->pages[i]); + kfree(dma->pages); + dma->pages = NULL; + dma->sglist = NULL; + dma->sglen = 0; + dma->nr_pages = 0; + return err; } int bcm_vk_sg_alloc(struct device *dev, diff --git a/drivers/misc/ibmvmc.c b/drivers/misc/ibmvmc.c index 6afef0788b9095..d03aeb8dea8fd4 100644 --- a/drivers/misc/ibmvmc.c +++ b/drivers/misc/ibmvmc.c @@ -2366,14 +2366,6 @@ static int __init ibmvmc_module_init(void) ibmvmc.state = ibmvmc_state_initial; pr_info("ibmvmc: version %s\n", IBMVMC_DRIVER_VERSION); - rc = misc_register(&ibmvmc_miscdev); - if (rc) { - pr_err("ibmvmc: misc registration failed\n"); - goto misc_register_failed; - } - pr_info("ibmvmc: node %d:%d\n", MISC_MAJOR, - ibmvmc_miscdev.minor); - /* Initialize data structures */ memset(hmcs, 0, sizeof(struct ibmvmc_hmc) * MAX_HMCS); for (i = 0; i < MAX_HMCS; i++) { @@ -2383,6 +2375,14 @@ static int __init ibmvmc_module_init(void) hmcs[i].queue_outbound_msgs[j] = VMC_INVALID_BUFFER_ID; } + rc = misc_register(&ibmvmc_miscdev); + if (rc) { + pr_err("ibmvmc: misc registration failed\n"); + goto misc_register_failed; + } + pr_info("ibmvmc: node %d:%d\n", MISC_MAJOR, + ibmvmc_miscdev.minor); + /* Sanity check module parms */ ibmvmc_scrub_module_parms(); diff --git a/drivers/misc/mei/hw-me-regs.h b/drivers/misc/mei/hw-me-regs.h index b9a67629496bab..3972f9504f12f7 100644 --- a/drivers/misc/mei/hw-me-regs.h +++ b/drivers/misc/mei/hw-me-regs.h @@ -94,6 +94,7 @@ #define PCI_DEVICE_ID_INTEL_MEI_CDF 0x18D3 /* Cedar Fork */ #define PCI_DEVICE_ID_INTEL_MEI_ICP_LP 0x34E0 /* Ice Lake Point LP */ +#define PCI_DEVICE_ID_INTEL_MEI_ICP_LP_3 0x34E4 /* Ice Lake Point LP 3 (iTouch) */ #define PCI_DEVICE_ID_INTEL_MEI_ICP_N 0x38E0 /* Ice Lake Point N */ #define PCI_DEVICE_ID_INTEL_MEI_JSP_N 0x4DE0 /* Jasper Lake Point N */ diff --git a/drivers/misc/mei/mei_lb.c b/drivers/misc/mei/mei_lb.c index 9fa69acf28d5b0..ffaf5be3b6059b 100644 --- a/drivers/misc/mei/mei_lb.c +++ b/drivers/misc/mei/mei_lb.c @@ -312,16 +312,24 @@ static int mei_lb_push_payload_v2(struct device *dev, struct mei_cl_device *clde size_t chunk_size; size_t req_size; ssize_t bytes; + size_t mtu; int ret; - struct mei_lb2_req *req __free(kfree) = kzalloc(mei_cldev_mtu(cldev), GFP_KERNEL); + /* The MTU turns into 0 when a link reset disconnects the client */ + mtu = mei_cldev_mtu(cldev); + if (mtu <= sizeof(struct mei_lb2_req)) { + dev_err(dev, "MTU is too small: %zu\n", mtu); + return -EMSGSIZE; + } + + struct mei_lb2_req *req __free(kfree) = kzalloc(mtu, GFP_KERNEL); if (!req) return -ENOMEM; first_chunk = MEI_LB2_FLAG_FST_CHUNK; last_chunk = 0; do { - chunk_size = min(payload_size - sent_data, mei_cldev_mtu(cldev) - sizeof(*req)); + chunk_size = min(payload_size - sent_data, mtu - sizeof(*req)); req_size = struct_size(req, payload, chunk_size); if (sent_data + chunk_size == payload_size) diff --git a/drivers/misc/mei/pci-me.c b/drivers/misc/mei/pci-me.c index 790a4647811b70..cfdef9531ab1db 100644 --- a/drivers/misc/mei/pci-me.c +++ b/drivers/misc/mei/pci-me.c @@ -98,6 +98,7 @@ static const struct pci_device_id mei_me_pci_tbl[] = { { PCI_DEVICE_DATA(INTEL, MEI_CMP_H_3, MEI_ME_PCH8_ITOUCH_CFG) }, { PCI_DEVICE_DATA(INTEL, MEI_ICP_LP, MEI_ME_PCH12_CFG) }, + { PCI_DEVICE_DATA(INTEL, MEI_ICP_LP_3, MEI_ME_PCH12_SPS_ITOUCH_CFG) }, { PCI_DEVICE_DATA(INTEL, MEI_ICP_N, MEI_ME_PCH12_CFG) }, { PCI_DEVICE_DATA(INTEL, MEI_TGP_LP, MEI_ME_PCH15_CFG) }, diff --git a/drivers/misc/rpmb-core.c b/drivers/misc/rpmb-core.c index ecf14acf230ae0..0fda893dd74dba 100644 --- a/drivers/misc/rpmb-core.c +++ b/drivers/misc/rpmb-core.c @@ -45,6 +45,8 @@ EXPORT_SYMBOL_GPL(rpmb_dev_put); * @rsp: rpmb response frames * @rsp_len: length of rpmb response frames in bytes * + * Context: Might sleep. + * * Returns: < 0 on failure */ int rpmb_route_frames(struct rpmb_dev *rdev, u8 *req, @@ -53,6 +55,10 @@ int rpmb_route_frames(struct rpmb_dev *rdev, u8 *req, if (!req || !req_len || !rsp || !rsp_len) return -EINVAL; + guard(mutex)(&rdev->lock); + if (!rdev->descr.route_frames) + return -ENODEV; + return rdev->descr.route_frames(rdev->dev.parent, req, req_len, rsp, rsp_len); } @@ -62,6 +68,7 @@ static void rpmb_dev_release(struct device *dev) { struct rpmb_dev *rdev = to_rpmb_dev(dev); + mutex_destroy(&rdev->lock); ida_free(&rpmb_ida, rdev->id); kfree(rdev->descr.dev_id); kfree(rdev); @@ -123,8 +130,9 @@ EXPORT_SYMBOL_GPL(rpmb_interface_unregister); * rpmb_dev_unregister() - unregister RPMB partition from the RPMB subsystem * @rdev: the rpmb device to unregister * - * This function should be called from the release function of the - * underlying device used when the RPMB device was registered. + * This function should be called from the remove or unbind callback of the + * underlying device used when the RPMB device was registered, never from + * a device release callback. * * Returns: < 0 on failure */ @@ -133,6 +141,12 @@ int rpmb_dev_unregister(struct rpmb_dev *rdev) if (!rdev) return -EINVAL; + scoped_guard(mutex, &rdev->lock) { + if (!rdev->descr.route_frames) + return 0; + rdev->descr.route_frames = NULL; + } + device_del(&rdev->dev); rpmb_dev_put(rdev); @@ -164,6 +178,7 @@ struct rpmb_dev *rpmb_dev_register(struct device *dev, rdev = kzalloc_obj(*rdev); if (!rdev) return ERR_PTR(-ENOMEM); + mutex_init(&rdev->lock); rdev->descr = *descr; rdev->descr.dev_id = kmemdup(descr->dev_id, descr->dev_id_len, GFP_KERNEL); @@ -194,6 +209,7 @@ struct rpmb_dev *rpmb_dev_register(struct device *dev, err_free_dev_id: kfree(rdev->descr.dev_id); err_free_rdev: + mutex_destroy(&rdev->lock); kfree(rdev); return ERR_PTR(ret); } diff --git a/drivers/misc/vmw_vmci/vmci_event.c b/drivers/misc/vmw_vmci/vmci_event.c index c3ef3b98c432e0..57d3a63678acd9 100644 --- a/drivers/misc/vmw_vmci/vmci_event.c +++ b/drivers/misc/vmw_vmci/vmci_event.c @@ -213,7 +213,12 @@ int vmci_event_unsubscribe(u32 sub_id) if (!s) return VMCI_ERROR_NOT_FOUND; - kvfree_rcu_mightsleep(s); + /* + * Wait for event_deliver(): the caller is going to free what the + * callback works on. + */ + synchronize_rcu(); + kfree(s); return VMCI_SUCCESS; } diff --git a/drivers/net/amt.c b/drivers/net/amt.c index 8b9fc3d11eceec..b145ed3ca6ede2 100644 --- a/drivers/net/amt.c +++ b/drivers/net/amt.c @@ -35,9 +35,19 @@ static struct workqueue_struct *amt_wq; static HLIST_HEAD(source_gc_list); -/* Lock for source_gc_list */ +/* Lock for source_gc_list, group_gc_list and the counts below */ static spinlock_t source_gc_lock; static struct delayed_work source_gc_wq; +static HLIST_HEAD(group_gc_list); +static struct delayed_work group_gc_wq; +/* Nodes parked on source_gc_list and group_gc_list, and the sources among + * them, so that a drain of either list can take its nodes off the count. + * Parked nodes are not charged to max_groups or max_sources, so + * Report/Leave churn could park them faster than the AMT_GC_INTERVAL tick + * frees them: once AMT_GC_KICK are parked, the drain runs at once. + */ +static unsigned int amt_gc_queued; +static unsigned int amt_gc_sources; static char *status_str[] = { "AMT_STATUS_INIT", "AMT_STATUS_SENT_DISCOVERY", @@ -88,11 +98,15 @@ static void __amt_source_gc_work(void) spin_lock_bh(&source_gc_lock); hlist_move_list(&source_gc_list, &gc_list); + amt_gc_queued -= amt_gc_sources; + amt_gc_sources = 0; spin_unlock_bh(&source_gc_lock); - hlist_for_each_entry_safe(snode, t, &gc_list, node) { - hlist_del_rcu(&snode->node); + hlist_for_each_entry_safe(snode, t, &gc_list, gc_node) { + cancel_delayed_work_sync(&snode->source_timer); + hlist_del_init(&snode->gc_node); kfree_rcu(snode, rcu); + cond_resched(); } } @@ -106,6 +120,62 @@ static void amt_source_gc_work(struct work_struct *work) spin_unlock_bh(&source_gc_lock); } +static void __amt_group_gc_work(void) +{ + struct amt_group_node *gnode; + struct hlist_head gc_list; + struct hlist_node *t; + + spin_lock_bh(&source_gc_lock); + hlist_move_list(&group_gc_list, &gc_list); + amt_gc_queued = amt_gc_sources; + spin_unlock_bh(&source_gc_lock); + + /* Group deletion queues all of its sources first. Reclaim them now + * rather than at the next periodic run; a source callback cannot + * reach a freed group because it resolves snode->gnode under RCU and + * the pointer is cleared before the source is queued. Call the GC + * here rather than flush source_gc_wq: a flush queues the work and + * waits for it to run, which needs a free amt_wq active slot, and + * when this runs on amt_wq every slot can be held by such waiters. + * The cancel_delayed_work_sync() calls in the GC need no slot: each + * takes a pending timer work off its timer or queue, or waits for a + * running one on a barrier that max_active does not count. + */ + __amt_source_gc_work(); + + hlist_for_each_entry_safe(gnode, t, &gc_list, gc_node) { + cancel_delayed_work_sync(&gnode->group_timer); + hlist_del_init(&gnode->gc_node); + kfree_rcu(gnode, rcu); + cond_resched(); + } +} + +static void amt_group_gc_work(struct work_struct *work) +{ + __amt_group_gc_work(); + + /* Run again at once if AMT_GC_KICK nodes were parked meanwhile: a + * kick that landed during the drain must not be pushed back to the + * interval. + */ + spin_lock_bh(&source_gc_lock); + mod_delayed_work(amt_wq, &group_gc_wq, + amt_gc_queued >= AMT_GC_KICK ? 0 : + msecs_to_jiffies(AMT_GC_INTERVAL)); + spin_unlock_bh(&source_gc_lock); +} + +/* Caller holds source_gc_lock and has just parked one node. This runs + * under tunnel->lock, often in softirq; mod_delayed_work() does not sleep. + */ +static void amt_gc_parked(void) +{ + if (++amt_gc_queued == AMT_GC_KICK) + mod_delayed_work(amt_wq, &group_gc_wq, 0); +} + static bool amt_addr_equal(union amt_addr *a, union amt_addr *b) { return !memcmp(a, b, sizeof(union amt_addr)); @@ -215,8 +285,13 @@ static struct amt_group_node *amt_lookup_group(struct amt_tunnel_list *tunnel, static void amt_destroy_source(struct amt_source_node *snode) { - struct amt_group_node *gnode = snode->gnode; struct amt_tunnel_list *tunnel; + struct amt_group_node *gnode; + + if (snode->dead) + return; + snode->dead = true; + gnode = snode->gnode; tunnel = gnode->tunnel_list; @@ -238,8 +313,11 @@ static void amt_destroy_source(struct amt_source_node *snode) hlist_del_init_rcu(&snode->node); tunnel->nr_sources--; gnode->nr_sources--; + WRITE_ONCE(snode->gnode, NULL); spin_lock_bh(&source_gc_lock); - hlist_add_head_rcu(&snode->node, &source_gc_list); + hlist_add_head(&snode->gc_node, &source_gc_list); + amt_gc_sources++; + amt_gc_parked(); spin_unlock_bh(&source_gc_lock); } @@ -249,6 +327,9 @@ static void amt_del_group(struct amt_dev *amt, struct amt_group_node *gnode) struct hlist_node *t; int i; + if (gnode->dead) + return; + gnode->dead = true; if (cancel_delayed_work(&gnode->group_timer)) dev_put(amt->dev); hlist_del_rcu(&gnode->node); @@ -266,10 +347,11 @@ static void amt_del_group(struct amt_dev *amt, struct amt_group_node *gnode) hlist_for_each_entry_safe(snode, t, &gnode->sources[i], node) amt_destroy_source(snode); - /* tunnel->lock was acquired outside of amt_del_group() - * But rcu_read_lock() was acquired too so It's safe. - */ - kfree_rcu(gnode, rcu); + WRITE_ONCE(gnode->tunnel_list, NULL); + spin_lock_bh(&source_gc_lock); + hlist_add_head(&gnode->gc_node, &group_gc_list); + amt_gc_parked(); + spin_unlock_bh(&source_gc_lock); } /* If a source timer expires with a router filter-mode for the group of @@ -282,13 +364,28 @@ static void amt_source_work(struct work_struct *work) struct amt_source_node *snode = container_of(to_delayed_work(work), struct amt_source_node, source_timer); - struct amt_group_node *gnode = snode->gnode; - struct amt_dev *amt = gnode->amt; struct amt_tunnel_list *tunnel; + struct amt_group_node *gnode; + struct amt_dev *amt; - tunnel = gnode->tunnel_list; - spin_lock_bh(&tunnel->lock); rcu_read_lock(); + gnode = READ_ONCE(snode->gnode); + if (!gnode) { + rcu_read_unlock(); + return; + } + amt = gnode->amt; + tunnel = READ_ONCE(gnode->tunnel_list); + if (!tunnel) { + rcu_read_unlock(); + return; + } + spin_lock_bh(&tunnel->lock); + if (snode->dead || gnode->dead) { + spin_unlock_bh(&tunnel->lock); + rcu_read_unlock(); + return; + } if (gnode->filter_mode == MCAST_INCLUDE) { amt_destroy_source(snode); if (!gnode->nr_sources) @@ -299,8 +396,8 @@ static void amt_source_work(struct work_struct *work) */ snode->status = AMT_SOURCE_STATUS_D_FWD; } - rcu_read_unlock(); spin_unlock_bh(&tunnel->lock); + rcu_read_unlock(); } static void amt_act_src(struct amt_tunnel_list *tunnel, @@ -368,6 +465,7 @@ static struct amt_source_node *amt_alloc_snode(struct amt_group_node *gnode, snode->status = AMT_SOURCE_STATUS_NONE; snode->flags = AMT_SOURCE_NEW; INIT_HLIST_NODE(&snode->node); + INIT_HLIST_NODE(&snode->gc_node); INIT_DELAYED_WORK(&snode->source_timer, amt_source_work); return snode; @@ -403,23 +501,31 @@ static void amt_group_work(struct work_struct *work) struct amt_group_node *gnode = container_of(to_delayed_work(work), struct amt_group_node, group_timer); - struct amt_tunnel_list *tunnel = gnode->tunnel_list; - struct amt_dev *amt = gnode->amt; + struct amt_tunnel_list *tunnel; struct amt_source_node *snode; bool delete_group = true; struct hlist_node *t; + struct amt_dev *amt; int i, buckets; + rcu_read_lock(); + tunnel = READ_ONCE(gnode->tunnel_list); + amt = gnode->amt; + if (!tunnel) + goto out; buckets = amt->hash_buckets; spin_lock_bh(&tunnel->lock); + if (gnode->dead) { + spin_unlock_bh(&tunnel->lock); + goto out; + } if (gnode->filter_mode == MCAST_INCLUDE) { /* Not Used */ spin_unlock_bh(&tunnel->lock); goto out; } - rcu_read_lock(); for (i = 0; i < buckets; i++) { hlist_for_each_entry_safe(snode, t, &gnode->sources[i], node) { @@ -436,9 +542,9 @@ static void amt_group_work(struct work_struct *work) amt_del_group(amt, gnode); else gnode->filter_mode = MCAST_INCLUDE; - rcu_read_unlock(); spin_unlock_bh(&tunnel->lock); out: + rcu_read_unlock(); dev_put(amt->dev); } @@ -479,6 +585,7 @@ static struct amt_group_node *amt_add_group(struct amt_dev *amt, gnode->tunnel_list = tunnel; gnode->filter_mode = MCAST_INCLUDE; INIT_HLIST_NODE(&gnode->node); + INIT_HLIST_NODE(&gnode->gc_node); INIT_DELAYED_WORK(&gnode->group_timer, amt_group_work); for (i = 0; i < amt->hash_buckets; i++) INIT_HLIST_HEAD(&gnode->sources[i]); @@ -593,14 +700,6 @@ static void __amt_update_relay_status(struct amt_tunnel_list *tunnel, tunnel->status = status; } -static void amt_update_relay_status(struct amt_tunnel_list *tunnel, - enum amt_status status, bool validate) -{ - spin_lock_bh(&tunnel->lock); - __amt_update_relay_status(tunnel, status, validate); - spin_unlock_bh(&tunnel->lock); -} - static void amt_send_discovery(struct amt_dev *amt) { struct amt_header_discovery *amtd; @@ -628,7 +727,7 @@ static void amt_send_discovery(struct amt_dev *amt) IPPROTO_UDP, 0, amt->stream_dev->ifindex); if (IS_ERR(rt)) { - amt->dev->stats.tx_errors++; + DEV_STATS_INC(amt->dev, tx_errors); goto out; } @@ -638,7 +737,7 @@ static void amt_send_discovery(struct amt_dev *amt) skb = netdev_alloc_skb_ip_align(amt->dev, len); if (!skb) { ip_rt_put(rt); - amt->dev->stats.tx_errors++; + DEV_STATS_INC(amt->dev, tx_errors); goto out; } @@ -683,7 +782,7 @@ static void amt_send_discovery(struct amt_dev *amt) ip_send_check(iph); err = ip_local_out(amt->net, sk, skb); if (unlikely(net_xmit_eval(err))) - amt->dev->stats.tx_errors++; + DEV_STATS_INC(amt->dev, tx_errors); amt_update_gw_status(amt, AMT_STATUS_SENT_DISCOVERY, true); out: @@ -719,7 +818,7 @@ static void amt_send_request(struct amt_dev *amt, bool v6) IPPROTO_UDP, 0, amt->stream_dev->ifindex); if (IS_ERR(rt)) { - amt->dev->stats.tx_errors++; + DEV_STATS_INC(amt->dev, tx_errors); goto out; } @@ -729,7 +828,7 @@ static void amt_send_request(struct amt_dev *amt, bool v6) skb = netdev_alloc_skb_ip_align(amt->dev, len); if (!skb) { ip_rt_put(rt); - amt->dev->stats.tx_errors++; + DEV_STATS_INC(amt->dev, tx_errors); goto out; } @@ -776,7 +875,7 @@ static void amt_send_request(struct amt_dev *amt, bool v6) ip_send_check(iph); err = ip_local_out(amt->net, sk, skb); if (unlikely(net_xmit_eval(err))) - amt->dev->stats.tx_errors++; + DEV_STATS_INC(amt->dev, tx_errors); out: rcu_read_unlock(); @@ -784,11 +883,16 @@ static void amt_send_request(struct amt_dev *amt, bool v6) static bool amt_send_membership_query(struct amt_dev *amt, struct sk_buff *skb, - struct amt_tunnel_list *tunnel, + __be32 daddr, __be16 dport, + __be32 nonce, u64 mac, bool v6); -static void amt_send_igmp_gq(struct amt_dev *amt, - struct amt_tunnel_list *tunnel) +/* The destination is passed by value rather than as a tunnel: a Request is + * unauthenticated, so no tunnel state is created or changed for it - see + * amt_request_handler(). + */ +static void amt_send_igmp_gq(struct amt_dev *amt, __be32 daddr, __be16 dport, + __be32 nonce, u64 mac) { struct sk_buff *skb; @@ -797,8 +901,9 @@ static void amt_send_igmp_gq(struct amt_dev *amt, return; skb_pull(skb, sizeof(struct ethhdr)); - if (amt_send_membership_query(amt, skb, tunnel, false)) { - amt->dev->stats.tx_dropped++; + if (amt_send_membership_query(amt, skb, daddr, dport, nonce, mac, + false)) { + DEV_STATS_INC(amt->dev, tx_dropped); kfree_skb(skb); } } @@ -842,7 +947,7 @@ static struct sk_buff *amt_build_mld_gq(struct amt_dev *amt) if (ipv6_dev_get_saddr(amt->net, amt->dev, &ip6h->daddr, 0, &ip6h->saddr)) { - amt->dev->stats.tx_errors++; + DEV_STATS_INC(amt->dev, tx_errors); kfree_skb(skb); return NULL; } @@ -876,7 +981,8 @@ static struct sk_buff *amt_build_mld_gq(struct amt_dev *amt) return skb; } -static void amt_send_mld_gq(struct amt_dev *amt, struct amt_tunnel_list *tunnel) +static void amt_send_mld_gq(struct amt_dev *amt, __be32 daddr, __be16 dport, + __be32 nonce, u64 mac) { struct sk_buff *skb; @@ -885,13 +991,15 @@ static void amt_send_mld_gq(struct amt_dev *amt, struct amt_tunnel_list *tunnel) return; skb_pull(skb, sizeof(struct ethhdr)); - if (amt_send_membership_query(amt, skb, tunnel, true)) { - amt->dev->stats.tx_dropped++; + if (amt_send_membership_query(amt, skb, daddr, dport, nonce, mac, + true)) { + DEV_STATS_INC(amt->dev, tx_dropped); kfree_skb(skb); } } #else -static void amt_send_mld_gq(struct amt_dev *amt, struct amt_tunnel_list *tunnel) +static void amt_send_mld_gq(struct amt_dev *amt, __be32 daddr, __be16 dport, + __be32 nonce, u64 mac) { } #endif @@ -925,7 +1033,16 @@ static void amt_secret_work(struct work_struct *work) secret_wq); spin_lock_bh(&amt->lock); - get_random_bytes(&amt->key, sizeof(siphash_key_t)); + write_seqcount_begin(&amt->key_seq); + /* Keep three previous generations for a 180-240s MAC lifetime. + * Its 180s floor exceeds the advertised QQIC (amt->qi, 125s), + * allowing the gateway to renew its MAC with a periodic Request. + */ + amt->key[3] = amt->key[2]; + amt->key[2] = amt->key[1]; + amt->key[1] = amt->key[0]; + get_random_bytes(&amt->key[0], sizeof(siphash_key_t)); + write_seqcount_end(&amt->key_seq); spin_unlock_bh(&amt->lock); mod_delayed_work(amt_wq, &amt->secret_wq, msecs_to_jiffies(AMT_SECRET_TIMEOUT)); @@ -1125,9 +1242,16 @@ static void amt_send_multicast_data(struct amt_dev *amt, 0); } +/* Send a Membership Query in reply to an unauthenticated Request. + * + * No per-source state is read or created: the gateway echoes the nonce and + * the keyed MAC in its Membership Update, where the MAC is recomputed, so + * everything this needs is passed by value. + */ static bool amt_send_membership_query(struct amt_dev *amt, struct sk_buff *skb, - struct amt_tunnel_list *tunnel, + __be32 daddr, __be16 dport, + __be32 nonce, u64 mac, bool v6) { struct amt_header_membership_query *amtmq; @@ -1148,13 +1272,13 @@ static bool amt_send_membership_query(struct amt_dev *amt, skb_reset_inner_headers(skb); memset(&fl4, 0, sizeof(struct flowi4)); fl4.flowi4_oif = amt->stream_dev->ifindex; - fl4.daddr = tunnel->ip4; + fl4.daddr = daddr; fl4.saddr = amt->local_ip; fl4.flowi4_dscp = inet_dsfield_to_dscp(AMT_TOS); fl4.flowi4_proto = IPPROTO_UDP; rt = ip_route_output_key(amt->net, &fl4); if (IS_ERR(rt)) { - netdev_dbg(amt->dev, "no route to %pI4\n", &tunnel->ip4); + netdev_dbg(amt->dev, "no route to %pI4\n", &daddr); return true; } @@ -1164,8 +1288,8 @@ static bool amt_send_membership_query(struct amt_dev *amt, amtmq->reserved = 0; amtmq->l = 0; amtmq->g = 0; - amtmq->nonce = tunnel->nonce; - amtmq->response_mac = tunnel->mac; + amtmq->nonce = nonce; + amtmq->response_mac = mac; if (!v6) skb_set_inner_protocol(skb, htons(ETH_P_IP)); @@ -1178,11 +1302,10 @@ static bool amt_send_membership_query(struct amt_dev *amt, ip4_dst_hoplimit(&rt->dst), 0, amt->relay_port, - tunnel->source_port, + dport, false, false, 0); - amt_update_relay_status(tunnel, AMT_STATUS_SENT_QUERY, true); return false; } @@ -1246,7 +1369,7 @@ static netdev_tx_t amt_dev_xmit(struct sk_buff *skb, struct net_device *dev) group.ip6 = ipv6_hdr(skb)->daddr; #endif } else { - dev->stats.tx_errors++; + DEV_STATS_INC(dev, tx_errors); goto free; } @@ -1259,12 +1382,21 @@ static netdev_tx_t amt_dev_xmit(struct sk_buff *skb, struct net_device *dev) /* Gateway only passes IGMP/MLD packets */ if (!report) goto free; + /* A validated report can only be forwarded after the relay's + * family-specific Membership Query supplies the state echoed + * by the Membership Update. Log this readiness failure before + * the shared drop path accounts it. + */ if ((!v6 && !READ_ONCE(amt->ready4)) || - (v6 && !READ_ONCE(amt->ready6))) + (v6 && !READ_ONCE(amt->ready6))) { + netdev_dbg(dev, "drop %s report: waiting for Membership Query\n", + v6 ? "MLD" : "IGMP"); goto free; + } if (amt_send_membership_update(amt, skb, v6)) goto free; - goto unlock; + /* Sent: the tunnel consumed the skb. Not a drop. */ + return NETDEV_TX_OK; } else if (amt->mode == AMT_MODE_RELAY) { if (!data) goto free; @@ -1293,8 +1425,7 @@ static netdev_tx_t amt_dev_xmit(struct sk_buff *skb, struct net_device *dev) return NETDEV_TX_OK; free: dev_kfree_skb(skb); -unlock: - dev->stats.tx_dropped++; + DEV_STATS_INC(dev, tx_dropped); return NETDEV_TX_OK; } @@ -1342,14 +1473,46 @@ static void amt_tunnel_expire(struct work_struct *work) struct amt_tunnel_list, gc_wq); struct amt_dev *amt = tunnel->amt; + unsigned long deadline, now; spin_lock_bh(&amt->lock); + spin_lock_bh(&tunnel->lock); + /* amt_dev_stop() has taken ownership of the teardown. */ + if (READ_ONCE(tunnel->dead)) { + spin_unlock_bh(&tunnel->lock); + spin_unlock_bh(&amt->lock); + return; + } + /* A Membership Update may have refreshed the tunnel after this work + * was queued. Re-arm from last_seen rather than letting + * amt_update_handler() re-arm gc_wq: this handler is then the only + * context that frees the tunnel on the timeout path; amt_dev_stop() + * still owns teardown during device shutdown. last_seen is read and + * dead is set under tunnel->lock, which the Update path holds while + * it refreshes last_seen, so an Update either keeps the tunnel alive + * or finds it dead. + */ + now = jiffies; + deadline = tunnel->last_seen + msecs_to_jiffies(amt_gmi(amt)) * 3; + if (time_before(now, deadline)) { + mod_delayed_work(amt_wq, &tunnel->gc_wq, deadline - now); + spin_unlock_bh(&tunnel->lock); + spin_unlock_bh(&amt->lock); + return; + } + WRITE_ONCE(tunnel->dead, true); + spin_unlock_bh(&tunnel->lock); rcu_read_lock(); list_del_rcu(&tunnel->list); amt->nr_tunnels--; amt_clear_groups(tunnel); rcu_read_unlock(); spin_unlock_bh(&amt->lock); + /* Free now, rather than at the next periodic run, the nodes that + * amt_clear_groups() queued. Call the GC rather than flush + * group_gc_wq, as explained in __amt_group_gc_work(). + */ + __amt_group_gc_work(); kfree_rcu(tunnel, rcu); } @@ -2382,6 +2545,10 @@ static bool amt_membership_query_handler(struct amt_dev *amt, if (amtmq->reserved || amtmq->version) return true; + /* A deferred query may outlive a relay address change. */ + if (ip_hdr(skb)->saddr != READ_ONCE(amt->remote_ip)) + return true; + if (amtmq->nonce != amt->nonce) return true; @@ -2474,16 +2641,165 @@ static bool amt_membership_query_handler(struct amt_dev *amt, return false; } +/* The live tunnel of the gateway endpoint @saddr:@sport, or NULL. Dead + * tunnels are skipped, so the retry in amt_update_tunnel() after losing a + * race with amt_tunnel_expire() creates the replacement. + */ +static struct amt_tunnel_list *amt_tunnel_lookup(struct amt_dev *amt, + __be32 saddr, __be16 sport) +{ + struct amt_tunnel_list *tunnel; + + list_for_each_entry_rcu(tunnel, &amt->tunnel_list, list) { + if (tunnel->ip4 == saddr && tunnel->source_port == sport && + !READ_ONCE(tunnel->dead)) + return tunnel; + } + return NULL; +} + +/* Most tunnels one source address may hold: an eighth of the table, at + * least one and at most AMT_MAX_TUNNELS_PER_SRC. + */ +static u32 amt_max_tunnels_per_src(const struct amt_dev *amt) +{ + return clamp_t(u32, amt->max_tunnels / 8, 1, + AMT_MAX_TUNNELS_PER_SRC); +} + +/* Look up the tunnel for a source whose Membership Update has already been + * authenticated, creating it on first contact. + * + * This is the only place tunnel state is allocated, so amt->max_tunnels + * bounds the number of *verified* gateways rather than the number of + * unverified Requests anyone can send. A per-source cap derived from the + * table, amt_max_tunnels_per_src(), additionally limits the tunnels one + * verified source address may hold. + */ +static struct amt_tunnel_list *amt_tunnel_get_or_create(struct amt_dev *amt, + __be32 saddr, + __be16 sport) +{ + struct amt_tunnel_list *tunnel; + u32 per_src = 0; + int i; + + tunnel = amt_tunnel_lookup(amt, saddr, sport); + if (tunnel) + return tunnel; + + spin_lock_bh(&amt->lock); + + /* Re-check under the lock in case a concurrent Update won the race, and + * count how many tunnels this source already holds on the same walk. + * Skip dead tunnels, as amt_tunnel_lookup() and the Request path do, so + * a tunnel being freed neither stands in for its endpoint nor counts + * against its address. + */ + list_for_each_entry(tunnel, &amt->tunnel_list, list) { + if (tunnel->ip4 != saddr || READ_ONCE(tunnel->dead)) + continue; + if (tunnel->source_port == sport) { + spin_unlock_bh(&amt->lock); + return tunnel; + } + per_src++; + } + + if (amt->nr_tunnels >= amt->max_tunnels || + per_src >= amt_max_tunnels_per_src(amt)) { + spin_unlock_bh(&amt->lock); + return NULL; + } + + if (!netif_running(amt->dev)) { + spin_unlock_bh(&amt->lock); + return NULL; + } + + tunnel = kzalloc(sizeof(*tunnel) + + (sizeof(struct hlist_head) * amt->hash_buckets), + GFP_ATOMIC); + if (!tunnel) { + spin_unlock_bh(&amt->lock); + return NULL; + } + + tunnel->source_port = sport; + tunnel->ip4 = saddr; + tunnel->amt = amt; + spin_lock_init(&tunnel->lock); + for (i = 0; i < amt->hash_buckets; i++) + INIT_HLIST_HEAD(&tunnel->groups[i]); + + tunnel->last_seen = jiffies; + INIT_DELAYED_WORK(&tunnel->gc_wq, amt_tunnel_expire); + __amt_update_relay_status(tunnel, AMT_STATUS_RECEIVED_UPDATE, false); + + /* Publish only once the entry is fully initialised. */ + list_add_tail_rcu(&tunnel->list, &amt->tunnel_list); + amt->nr_tunnels++; + mod_delayed_work(amt_wq, &tunnel->gc_wq, + msecs_to_jiffies(amt_gmi(amt)) * 3); + spin_unlock_bh(&amt->lock); + + return tunnel; +} + +/* Apply a valid, authenticated Membership Update to the tunnel of its + * endpoint, creating the tunnel on first contact. Returns false if the + * Update is dropped. + * + * amt_tunnel_expire() reads last_seen and sets dead under tunnel->lock, so + * the refresh below either keeps the tunnel alive or finds it dead. A + * tunnel that expired between the lookup and the lock is skipped by the + * second amt_tunnel_get_or_create() call, which creates its replacement. + */ +static bool amt_update_tunnel(struct amt_dev *amt, struct sk_buff *skb, + __be32 saddr, __be16 sport, bool v6) +{ + struct amt_tunnel_list *tunnel; + int i; + + for (i = 0; i < 2; i++) { + tunnel = amt_tunnel_get_or_create(amt, saddr, sport); + if (!tunnel) + return false; + + spin_lock_bh(&tunnel->lock); + if (!READ_ONCE(tunnel->dead)) { + /* gc_wq is re-armed by amt_tunnel_expire() itself + * from last_seen, never from here, so this cannot + * re-queue the work of a tunnel that is being freed. + */ + tunnel->last_seen = jiffies; +#if IS_ENABLED(CONFIG_IPV6) + if (v6) + amt_mld_report_handler(amt, skb, tunnel); + else +#endif + amt_igmp_report_handler(amt, skb, tunnel); + spin_unlock_bh(&tunnel->lock); + return true; + } + spin_unlock_bh(&tunnel->lock); + } + return false; +} + static bool amt_update_handler(struct amt_dev *amt, struct sk_buff *skb) { struct amt_header_membership_update *amtmu; - struct amt_tunnel_list *tunnel; + bool verified = false; + siphash_key_t key[4]; + int len, hdr_size, i; struct ethhdr *eth; struct iphdr *iph; - int len, hdr_size; + unsigned int seq; u64 response_mac; __be32 saddr; __be32 nonce; + __be16 sport; saddr = ip_hdr(skb)->saddr; @@ -2497,30 +2813,45 @@ static bool amt_update_handler(struct amt_dev *amt, struct sk_buff *skb) nonce = amtmu->nonce; response_mac = amtmu->response_mac; + /* Snapshot the tunnel endpoint port before the encap is stripped. */ + sport = udp_hdr(skb)->source; + + /* Recompute the MAC handed out in the Membership Query. Four live + * secrets cover 180-240s, exceeding the advertised QQIC (amt->qi, + * 125s), so a periodic Request can renew the MAC before it expires. + * Authenticate before decapsulation or allocating tunnel state. + */ + do { + seq = read_seqcount_begin(&amt->key_seq); + for (i = 0; i < ARRAY_SIZE(key); i++) + key[i] = amt->key[i]; + } while (read_seqcount_retry(&amt->key_seq, seq)); + + for (i = 0; i < ARRAY_SIZE(key); i++) { + u64 mac = siphash_3u32((__force u32)saddr, + (__force u32)sport, + (__force u32)nonce, + &key[i]) >> 16; + + if (response_mac == mac) { + verified = true; + break; + } + } + if (!verified) { + netdev_dbg(amt->dev, "Invalid MAC\n"); + return true; + } + + /* Create or refresh a tunnel only once the encapsulated message has + * passed ip_mc_check_igmp() or ipv6_mc_check_mld(). + */ if (iptunnel_pull_header(skb, hdr_size, skb->protocol, false)) return true; skb_reset_network_header(skb); - list_for_each_entry_rcu(tunnel, &amt->tunnel_list, list) { - if (tunnel->ip4 == saddr) { - if ((nonce == tunnel->nonce && - response_mac == tunnel->mac)) { - mod_delayed_work(amt_wq, &tunnel->gc_wq, - msecs_to_jiffies(amt_gmi(amt)) - * 3); - goto report; - } else { - netdev_dbg(amt->dev, "Invalid MAC\n"); - return true; - } - } - } - - return true; - -report: if (!pskb_may_pull(skb, sizeof(*iph))) return true; @@ -2534,9 +2865,8 @@ static bool amt_update_handler(struct amt_dev *amt, struct sk_buff *skb) return true; } - spin_lock_bh(&tunnel->lock); - amt_igmp_report_handler(amt, skb, tunnel); - spin_unlock_bh(&tunnel->lock); + if (!amt_update_tunnel(amt, skb, saddr, sport, false)) + return true; skb_push(skb, sizeof(struct ethhdr)); skb_reset_mac_header(skb); @@ -2554,9 +2884,8 @@ static bool amt_update_handler(struct amt_dev *amt, struct sk_buff *skb) return true; } - spin_lock_bh(&tunnel->lock); - amt_mld_report_handler(amt, skb, tunnel); - spin_unlock_bh(&tunnel->lock); + if (!amt_update_tunnel(amt, skb, saddr, sport, true)) + return true; skb_push(skb, sizeof(struct ethhdr)); skb_reset_mac_header(skb); @@ -2575,13 +2904,10 @@ static bool amt_update_handler(struct amt_dev *amt, struct sk_buff *skb) skb->pkt_type = PACKET_MULTICAST; skb->ip_summed = CHECKSUM_NONE; len = skb->len; - if (__netif_rx(skb) == NET_RX_SUCCESS) { - amt_update_relay_status(tunnel, AMT_STATUS_RECEIVED_UPDATE, - true); + if (__netif_rx(skb) == NET_RX_SUCCESS) dev_sw_netstats_rx_add(amt->dev, len); - } else { + else amt->dev->stats.rx_dropped++; - } return false; } @@ -2614,7 +2940,7 @@ static void amt_send_advertisement(struct amt_dev *amt, __be32 nonce, IPPROTO_UDP, 0, amt->stream_dev->ifindex); if (IS_ERR(rt)) { - amt->dev->stats.tx_errors++; + DEV_STATS_INC(amt->dev, tx_errors); goto out; } @@ -2624,7 +2950,7 @@ static void amt_send_advertisement(struct amt_dev *amt, __be32 nonce, skb = netdev_alloc_skb_ip_align(amt->dev, len); if (!skb) { ip_rt_put(rt); - amt->dev->stats.tx_errors++; + DEV_STATS_INC(amt->dev, tx_errors); goto out; } @@ -2670,7 +2996,7 @@ static void amt_send_advertisement(struct amt_dev *amt, __be32 nonce, ip_send_check(iph); err = ip_local_out(amt->net, sk, skb); if (unlikely(net_xmit_eval(err))) - amt->dev->stats.tx_errors++; + DEV_STATS_INC(amt->dev, tx_errors); out: rcu_read_unlock(); @@ -2697,15 +3023,30 @@ static bool amt_discovery_handler(struct amt_dev *amt, struct sk_buff *skb) return false; } +/* Handle an AMT Request. + * + * The source of a Request is unauthenticated: it is a bare UDP datagram with a + * trivially spoofable source address. Allocating tunnel state here would let + * an attacker fill the table from spoofed addresses, or let one spoofed packet + * overwrite the nonce/MAC of an established tunnel and cut that gateway off. + * + * Nothing needs to be remembered at this point. Every input to the keyed MAC + * is carried in the packet or is device state, so the MAC is generated here, + * echoed back by the gateway in its Membership Update, and recomputed and + * verified there - see amt_update_handler(). Tunnel state is created only once + * that verification succeeds and the encapsulated message passes its IGMP or + * MLD check. + */ static bool amt_request_handler(struct amt_dev *amt, struct sk_buff *skb) { struct amt_header_request *amtrh; struct amt_tunnel_list *tunnel; - unsigned long long key; + bool full, have = false; struct udphdr *udph; struct iphdr *iph; + siphash_key_t key; + u32 per_src = 0; u64 mac; - int i; if (!pskb_may_pull(skb, sizeof(*udph) + sizeof(*amtrh))) return true; @@ -2717,59 +3058,45 @@ static bool amt_request_handler(struct amt_dev *amt, struct sk_buff *skb) if (amtrh->reserved1 || amtrh->reserved2 || amtrh->version) return true; - list_for_each_entry_rcu(tunnel, &amt->tunnel_list, list) - if (tunnel->ip4 == iph->saddr) - goto send; - - spin_lock_bh(&amt->lock); - if (amt->nr_tunnels >= amt->max_tunnels) { - spin_unlock_bh(&amt->lock); - icmp_ndo_send(skb, ICMP_DEST_UNREACH, ICMP_HOST_UNREACH, 0); - return true; - } - - tunnel = kzalloc(sizeof(*tunnel) + - (sizeof(struct hlist_head) * amt->hash_buckets), - GFP_ATOMIC); - if (!tunnel) { - spin_unlock_bh(&amt->lock); + if (!netif_running(amt->dev) || !netif_running(amt->stream_dev)) return true; - } - - tunnel->source_port = udph->source; - tunnel->ip4 = iph->saddr; - memcpy(&key, &tunnel->key, sizeof(unsigned long long)); - tunnel->amt = amt; - spin_lock_init(&tunnel->lock); - for (i = 0; i < amt->hash_buckets; i++) - INIT_HLIST_HEAD(&tunnel->groups[i]); - - INIT_DELAYED_WORK(&tunnel->gc_wq, amt_tunnel_expire); - - list_add_tail_rcu(&tunnel->list, &amt->tunnel_list); - tunnel->key = amt->key; - __amt_update_relay_status(tunnel, AMT_STATUS_RECEIVED_REQUEST, true); - amt->nr_tunnels++; - mod_delayed_work(amt_wq, &tunnel->gc_wq, - msecs_to_jiffies(amt_gmi(amt))); + /* Snapshot the secret and the table-full state under the lock and walk + * the endpoints outside it, so a Request holds amt->lock only for this + * O(1) snapshot. + */ + spin_lock_bh(&amt->lock); + key = amt->key[0]; + full = amt->nr_tunnels >= amt->max_tunnels; spin_unlock_bh(&amt->lock); -send: - tunnel->nonce = amtrh->nonce; - mac = siphash_3u32((__force u32)tunnel->ip4, - (__force u32)tunnel->source_port, - (__force u32)tunnel->nonce, - &tunnel->key); - tunnel->mac = mac >> 16; + /* Skip dead tunnels, as amt_tunnel_lookup() does: each is already + * being torn down, so it must not count against a new endpoint. + */ + rcu_read_lock(); + list_for_each_entry_rcu(tunnel, &amt->tunnel_list, list) { + if (tunnel->ip4 != iph->saddr || READ_ONCE(tunnel->dead)) + continue; + per_src++; + if (tunnel->source_port == udph->source) + have = true; + } + rcu_read_unlock(); - if (!netif_running(amt->dev) || !netif_running(amt->stream_dev)) + /* Withhold the Query when a new endpoint cannot get a tunnel. */ + if (!have && (full || per_src >= amt_max_tunnels_per_src(amt))) return true; + mac = siphash_3u32((__force u32)iph->saddr, + (__force u32)udph->source, + (__force u32)amtrh->nonce, + &key) >> 16; if (!amtrh->p) - amt_send_igmp_gq(amt, tunnel); + amt_send_igmp_gq(amt, iph->saddr, udph->source, amtrh->nonce, + mac); else - amt_send_mld_gq(amt, tunnel); + amt_send_mld_gq(amt, iph->saddr, udph->source, amtrh->nonce, + mac); return false; } @@ -2846,7 +3173,7 @@ static int amt_rcv(struct sock *sk, struct sk_buff *skb) } goto out; case AMT_MSG_MULTICAST_DATA: - if (saddr != remote_ip) { + if (!remote_ip || saddr != remote_ip) { netdev_dbg(amt->dev, "Invalid Relay IP\n"); err = true; goto drop; @@ -2857,7 +3184,7 @@ static int amt_rcv(struct sock *sk, struct sk_buff *skb) else goto out; case AMT_MSG_MEMBERSHIP_QUERY: - if (saddr != remote_ip) { + if (!remote_ip || saddr != remote_ip) { netdev_dbg(amt->dev, "Invalid Relay IP\n"); err = true; goto drop; @@ -3037,6 +3364,16 @@ static int amt_dev_open(struct net_device *dev) enable_delayed_work(&amt->discovery_wq); enable_delayed_work(&amt->req_wq); + /* Seed the keys before amt_socket_create() enables the encap receive + * path, so no Query MAC is generated, and no Update verified, with an + * all-zero (predictable) secret. + */ + spin_lock_bh(&amt->lock); + write_seqcount_begin(&amt->key_seq); + get_random_bytes(&amt->key, sizeof(amt->key)); + write_seqcount_end(&amt->key_seq); + spin_unlock_bh(&amt->lock); + err = amt_socket_create(amt); if (err) { disable_delayed_work(&amt->req_wq); @@ -3047,7 +3384,6 @@ static int amt_dev_open(struct net_device *dev) amt->req_cnt = 0; WRITE_ONCE(amt->remote_ip, 0); amt->nonce = 0; - get_random_bytes(&amt->key, sizeof(siphash_key_t)); amt->status = AMT_STATUS_INIT; if (amt->mode == AMT_MODE_GATEWAY) { @@ -3063,7 +3399,7 @@ static int amt_dev_open(struct net_device *dev) static int amt_dev_stop(struct net_device *dev) { struct amt_dev *amt = netdev_priv(dev); - struct amt_tunnel_list *tunnel, *tmp; + struct amt_tunnel_list *tunnel; struct sk_buff *skb; struct sock *sk; int i; @@ -3072,9 +3408,14 @@ static int amt_dev_stop(struct net_device *dev) disable_delayed_work_sync(&amt->discovery_wq); cancel_delayed_work_sync(&amt->secret_wq); - /* shutdown */ + /* shutdown. Detach the receive path as well, so that once the + * grace period ends no amt_rcv() can still see the device and queue + * work after the teardown below. + */ sk = rtnl_dereference(amt->sk); RCU_INIT_POINTER(amt->sk, NULL); + if (sk) + rcu_assign_sk_user_data(sk, NULL); synchronize_net(); if (sk) udp_tunnel_sock_release(sk); @@ -3092,11 +3433,37 @@ static int amt_dev_stop(struct net_device *dev) amt->req_cnt = 0; WRITE_ONCE(amt->remote_ip, 0); - list_for_each_entry_safe(tunnel, tmp, &amt->tunnel_list, list) { - list_del_rcu(&tunnel->list); - amt->nr_tunnels--; + /* Mark every tunnel dead first, so a concurrent amt_tunnel_expire() + * sees ->dead and bails instead of freeing a tunnel in parallel; this + * path is then the sole freer. + */ + spin_lock_bh(&amt->lock); + list_for_each_entry(tunnel, &amt->tunnel_list, list) { + spin_lock_bh(&tunnel->lock); + WRITE_ONCE(tunnel->dead, true); + spin_unlock_bh(&tunnel->lock); + } + spin_unlock_bh(&amt->lock); + + /* Unlink one tunnel at a time with list_del_rcu() rather than splicing + * the list onto a local head: a lockless reader walking tunnel_list + * must always terminate at &amt->tunnel_list, never at a stack head. + */ + for (;;) { + spin_lock_bh(&amt->lock); + tunnel = list_first_entry_or_null(&amt->tunnel_list, + struct amt_tunnel_list, list); + if (tunnel) { + list_del_rcu(&tunnel->list); + amt->nr_tunnels--; + } + spin_unlock_bh(&amt->lock); + if (!tunnel) + break; + cancel_delayed_work_sync(&tunnel->gc_wq); amt_clear_groups(tunnel); + __amt_group_gc_work(); kfree_rcu(tunnel, rcu); } @@ -3165,9 +3532,9 @@ static const struct nla_policy amt_policy[IFLA_AMT_MAX + 1] = { [IFLA_AMT_RELAY_PORT] = { .type = NLA_U16 }, [IFLA_AMT_GATEWAY_PORT] = { .type = NLA_U16 }, [IFLA_AMT_LINK] = { .type = NLA_U32 }, - [IFLA_AMT_LOCAL_IP] = { .len = sizeof_field(struct iphdr, daddr) }, + [IFLA_AMT_LOCAL_IP] = NLA_POLICY_EXACT_LEN(sizeof(__be32)), [IFLA_AMT_REMOTE_IP] = { .len = sizeof_field(struct iphdr, daddr) }, - [IFLA_AMT_DISCOVERY_IP] = { .len = sizeof_field(struct iphdr, daddr) }, + [IFLA_AMT_DISCOVERY_IP] = NLA_POLICY_EXACT_LEN(sizeof(__be32)), [IFLA_AMT_MAX_TUNNELS] = { .type = NLA_U32 }, }; @@ -3234,6 +3601,7 @@ static int amt_newlink(struct net_device *dev, amt->max_tunnels = AMT_MAX_TUNNELS; spin_lock_init(&amt->lock); + seqcount_spinlock_init(&amt->key_seq, &amt->lock); amt->max_groups = AMT_MAX_GROUP; amt->max_sources = AMT_MAX_SOURCE; amt->hash_buckets = AMT_HSIZE; @@ -3470,6 +3838,9 @@ static int __init amt_init(void) INIT_DELAYED_WORK(&source_gc_wq, amt_source_gc_work); mod_delayed_work(amt_wq, &source_gc_wq, msecs_to_jiffies(AMT_GC_INTERVAL)); + INIT_DELAYED_WORK(&group_gc_wq, amt_group_gc_work); + mod_delayed_work(amt_wq, &group_gc_wq, + msecs_to_jiffies(AMT_GC_INTERVAL)); spin_unlock_bh(&source_gc_lock); return 0; @@ -3490,6 +3861,8 @@ static void __exit amt_fini(void) unregister_netdevice_notifier(&amt_notifier_block); cancel_delayed_work_sync(&source_gc_wq); __amt_source_gc_work(); + cancel_delayed_work_sync(&group_gc_wq); + __amt_group_gc_work(); destroy_workqueue(amt_wq); } module_exit(amt_fini); diff --git a/drivers/net/bonding/bond_main.c b/drivers/net/bonding/bond_main.c index e9f5e753f6770b..042d7c75548fac 100644 --- a/drivers/net/bonding/bond_main.c +++ b/drivers/net/bonding/bond_main.c @@ -1894,9 +1894,12 @@ int bond_enslave(struct net_device *bond_dev, struct net_device *slave_dev, struct sockaddr_storage ss; int res = 0, i; - if (slave_dev->type == ARPHRD_CAN) { + if (slave_dev->type == ARPHRD_CAN || + slave_dev->type == ARPHRD_IEEE802154 || + slave_dev->type == ARPHRD_IEEE802154_MONITOR || + slave_dev->type == ARPHRD_6LOWPAN) { BOND_NL_ERR(bond_dev, extack, - "CAN devices cannot be enslaved"); + "CAN, IEEE 802.15.4 and 6LoWPAN devices cannot be enslaved"); return -EPERM; } diff --git a/drivers/net/can/dev/netlink.c b/drivers/net/can/dev/netlink.c index 081dfddda00088..7f597c975c6f4a 100644 --- a/drivers/net/can/dev/netlink.c +++ b/drivers/net/can/dev/netlink.c @@ -330,9 +330,17 @@ static int can_ctrlmode_changelink(struct net_device *dev, return -EOPNOTSUPP; } + /* static control modes can not be switched off */ + if (deactivated & ctrlstatic) { + NL_SET_ERR_MSG_FMT(extack, + "static control mode %s can not be switched off", + can_get_ctrlmode_str(deactivated & ctrlstatic)); + return -EOPNOTSUPP; + } + /* do not check for static fd-non-iso if 'fd' is disabled */ if (!(maskedflags & CAN_CTRLMODE_FD)) - ctrlstatic &= ~CAN_CTRLMODE_FD_NON_ISO; + ctrlstatic_missing &= ~CAN_CTRLMODE_FD_NON_ISO; if (ctrlstatic_missing) { NL_SET_ERR_MSG_FMT(extack, @@ -783,7 +791,7 @@ static size_t can_pwm_get_size(const struct can_pwm_const *pwm_const, { size_t size; - if (!pwm_const || !pwm_on) + if (!pwm_const) return 0; size = nla_total_size(0); /* nest IFLA_CAN_PWM */ @@ -795,9 +803,11 @@ static size_t can_pwm_get_size(const struct can_pwm_const *pwm_const, size += nla_total_size(sizeof(u32)); /* IFLA_CAN_PWM_PWMO_MIN */ size += nla_total_size(sizeof(u32)); /* IFLA_CAN_PWM_PWMO_MAX */ - size += nla_total_size(sizeof(u32)); /* IFLA_CAN_PWM_PWMS */ - size += nla_total_size(sizeof(u32)); /* IFLA_CAN_PWM_PWML */ - size += nla_total_size(sizeof(u32)); /* IFLA_CAN_PWM_PWMO */ + if (pwm_on) { + size += nla_total_size(sizeof(u32)); /* IFLA_CAN_PWM_PWMS */ + size += nla_total_size(sizeof(u32)); /* IFLA_CAN_PWM_PWML */ + size += nla_total_size(sizeof(u32)); /* IFLA_CAN_PWM_PWMO */ + } return size; } @@ -825,7 +835,7 @@ static size_t can_get_size(const struct net_device *dev) if (priv->bitrate_const) /* IFLA_CAN_BITRATE_CONST */ size += nla_total_size(sizeof(*priv->bitrate_const) * priv->bitrate_const_cnt); - size += sizeof(priv->bitrate_max); /* IFLA_CAN_BITRATE_MAX */ + size += nla_total_size(sizeof(priv->bitrate_max)); /* IFLA_CAN_BITRATE_MAX */ size += can_ctrlmode_ext_get_size(); /* IFLA_CAN_CTRLMODE_EXT */ size += can_data_bittiming_get_size(dev, &priv->fd, diff --git a/drivers/net/can/flexcan/flexcan-core.c b/drivers/net/can/flexcan/flexcan-core.c index 86b40abe9e767e..e9b82267821350 100644 --- a/drivers/net/can/flexcan/flexcan-core.c +++ b/drivers/net/can/flexcan/flexcan-core.c @@ -2077,10 +2077,9 @@ MODULE_DEVICE_TABLE(of, flexcan_of_match); static const struct platform_device_id flexcan_id_table[] = { { .name = "flexcan-mcf5441x", - .driver_data = (kernel_ulong_t)&fsl_mcf5441x_devtype_data, }, { /* sentinel */ - }, + } }; MODULE_DEVICE_TABLE(platform, flexcan_id_table); @@ -2148,6 +2147,15 @@ static int flexcan_probe(struct platform_device *pdev) return PTR_ERR(regs); devtype_data = device_get_match_data(&pdev->dev); + if (!devtype_data) + /* + * If the device was instantiated via the traditional platform + * mechanisms (i.e. not by device tree), device_get_match_data() + * returns NULL. The only remaining such device is mcf_flexcan0 + * (defined in arch/m68k/coldfire/device.c). Pick the right + * device type for that. + */ + devtype_data = &fsl_mcf5441x_devtype_data; if ((devtype_data->quirks & FLEXCAN_QUIRK_SUPPORT_FD) && !((devtype_data->quirks & diff --git a/drivers/net/can/usb/gs_usb.c b/drivers/net/can/usb/gs_usb.c index 3b9b2f104d868e..15f28833f2debd 100644 --- a/drivers/net/can/usb/gs_usb.c +++ b/drivers/net/can/usb/gs_usb.c @@ -861,7 +861,7 @@ static netdev_tx_t gs_can_start_xmit(struct sk_buff *skb, if (!urb) goto nomem_urb; - hf = kmalloc(dev->hf_size_tx, GFP_ATOMIC); + hf = kzalloc(dev->hf_size_tx, GFP_ATOMIC); if (!hf) goto nomem_hf; diff --git a/drivers/net/dsa/b53/b53_common.c b/drivers/net/dsa/b53/b53_common.c index b7aff5e238e857..ee2d27732c0c8c 100644 --- a/drivers/net/dsa/b53/b53_common.c +++ b/drivers/net/dsa/b53/b53_common.c @@ -1360,6 +1360,10 @@ static int b53_setup(struct dsa_switch *ds) return ret; } + ret = b53_mirror_init(ds); + if (ret) + return ret; + /* setup default vlan for filtering mode */ pvid = b53_default_pvid(dev); vl = &dev->vlans[pvid]; @@ -1427,17 +1431,19 @@ static void b53_force_port_config(struct b53_device *dev, int port, int speed, int duplex, bool tx_pause, bool rx_pause) { - u8 reg, val, off; + u8 reg, val, off, speed2000; /* Override the port settings */ if (port == dev->imp_port) { off = B53_PORT_OVERRIDE_CTRL; val = PORT_OVERRIDE_EN; + speed2000 = PORT_OVERRIDE_SPEED_2000M; } else if (is5325(dev)) { return; } else { off = B53_GMII_PORT_OVERRIDE_CTRL(port); val = GMII_PO_EN; + speed2000 = GMII_PO_SPEED_2000M; } b53_read8(dev, B53_CTRL_PAGE, off, ®); @@ -1449,11 +1455,12 @@ static void b53_force_port_config(struct b53_device *dev, int port, reg &= ~(0x3 << GMII_PO_SPEED_S); if (is5301x(dev) || is58xx(dev)) - reg &= ~PORT_OVERRIDE_SPEED_2000M; + reg &= ~speed2000; switch (speed) { case 2000: - reg |= PORT_OVERRIDE_SPEED_2000M; + if (is5301x(dev) || is58xx(dev)) + reg |= speed2000; fallthrough; case SPEED_1000: reg |= PORT_OVERRIDE_SPEED_1000M; @@ -2055,9 +2062,13 @@ static int b53_arl_op(struct b53_device *dev, int op, int port, addr, vid); return is_valid ? ret : 0; case -ENOENT: + if (!is_valid) + return 0; + /* We could not find a matching MAC, so reset to a new entry */ dev_dbg(dev->dev, "{%pM,%.4d} not found, using idx: %d\n", addr, vid, idx); + memset(&ent, 0, sizeof(ent)); break; default: dev_dbg(dev->dev, "{%pM,%.4d} found, using idx: %d\n", @@ -2597,27 +2608,128 @@ enum dsa_tag_protocol b53_get_tag_protocol(struct dsa_switch *ds, int port, } EXPORT_SYMBOL(b53_get_tag_protocol); +static u16 b53_mirror_capture_port_mask(struct b53_device *dev) +{ + if (is5325(dev) || is5365(dev)) + return CAP_PORT_MASK_25; + + return CAP_PORT_MASK; +} + +static u16 b53_mirror_port_mask(struct b53_device *dev, int port) +{ + /* These switches use a bitmap with the CPU port at bit 8. */ + if ((is5325(dev) || is5365(dev)) && port == B53_CPU_PORT_25) + port = B53_CPU_PORT; + + return BIT(port); +} + +static u16 b53_mirror_capture_port(struct b53_device *dev, int port) +{ + if (is5325(dev) || is5365(dev)) + return b53_mirror_port_mask(dev, port); + + return port; +} + +int b53_mirror_init(struct dsa_switch *ds) +{ + struct b53_device *dev = ds->priv; + u16 ingress = 0, egress = 0, cap_ctl = 0; + unsigned int port; + int ret; + + /* A switch reset may leave the previous mirror configuration intact. */ + ret = b53_write16(dev, B53_MGMT_PAGE, B53_MIR_CAP_CTL, 0); + if (ret) + return ret; + + ret = b53_write16(dev, B53_MGMT_PAGE, B53_IG_MIR_CTL, 0); + if (ret) + return ret; + + ret = b53_write16(dev, B53_MGMT_PAGE, B53_EG_MIR_CTL, 0); + if (ret) + return ret; + + /* DSA retains matchall filters across suspend and resume. */ + for (port = 0; port < dev->num_ports; port++) { + if (dev->ports[port].mirror_count[true]) + ingress |= b53_mirror_port_mask(dev, port); + if (dev->ports[port].mirror_count[false]) + egress |= b53_mirror_port_mask(dev, port); + } + + if (!(ingress | egress)) + return 0; + + cap_ctl = MIRROR_EN | b53_mirror_capture_port(dev, dev->mirror_port); + ret = b53_write16(dev, B53_MGMT_PAGE, B53_MIR_CAP_CTL, cap_ctl); + if (ret) + return ret; + + ret = b53_write16(dev, B53_MGMT_PAGE, B53_IG_MIR_CTL, ingress); + if (ret) + return ret; + + return b53_write16(dev, B53_MGMT_PAGE, B53_EG_MIR_CTL, egress); +} +EXPORT_SYMBOL(b53_mirror_init); + int b53_mirror_add(struct dsa_switch *ds, int port, struct dsa_mall_mirror_tc_entry *mirror, bool ingress, struct netlink_ext_ack *extack) { struct b53_device *dev = ds->priv; - u16 reg, loc; + unsigned int *mirror_count = &dev->ports[port].mirror_count[ingress]; + u16 reg, other_reg, loc, other_loc, cap_ctl; + u16 cap_mask = b53_mirror_capture_port_mask(dev); + u16 cap_port = b53_mirror_capture_port(dev, mirror->to_local_port); + int ret; - if (ingress) - loc = B53_IG_MIR_CTL; - else - loc = B53_EG_MIR_CTL; + loc = ingress ? B53_IG_MIR_CTL : B53_EG_MIR_CTL; + other_loc = ingress ? B53_EG_MIR_CTL : B53_IG_MIR_CTL; - b53_read16(dev, B53_MGMT_PAGE, loc, ®); - reg |= BIT(port); - b53_write16(dev, B53_MGMT_PAGE, loc, reg); + ret = b53_read16(dev, B53_MGMT_PAGE, loc, ®); + if (ret) + return ret; - b53_read16(dev, B53_MGMT_PAGE, B53_MIR_CAP_CTL, ®); - reg &= ~CAP_PORT_MASK; - reg |= mirror->to_local_port; - reg |= MIRROR_EN; - b53_write16(dev, B53_MGMT_PAGE, B53_MIR_CAP_CTL, reg); + ret = b53_read16(dev, B53_MGMT_PAGE, other_loc, &other_reg); + if (ret) + return ret; + + ret = b53_read16(dev, B53_MGMT_PAGE, B53_MIR_CAP_CTL, &cap_ctl); + if (ret) + return ret; + + if (((reg | other_reg) & MIRROR_MASK) && + (cap_ctl & cap_mask) != cap_port) { + NL_SET_ERR_MSG_MOD(extack, + "Only one mirroring destination is supported"); + return -EOPNOTSUPP; + } + + if (*mirror_count) { + (*mirror_count)++; + return 0; + } + + /* Select the destination before enabling the new source. */ + cap_ctl &= ~cap_mask; + cap_ctl |= cap_port; + cap_ctl |= MIRROR_EN; + ret = b53_write16(dev, B53_MGMT_PAGE, B53_MIR_CAP_CTL, cap_ctl); + if (ret) + return ret; + + ret = b53_write16(dev, B53_MGMT_PAGE, loc, + reg | b53_mirror_port_mask(dev, port)); + if (ret) + return ret; + + (*mirror_count)++; + dev->mirror_port = mirror->to_local_port; return 0; } @@ -2627,38 +2739,54 @@ void b53_mirror_del(struct dsa_switch *ds, int port, struct dsa_mall_mirror_tc_entry *mirror) { struct b53_device *dev = ds->priv; - bool loc_disable = false, other_loc_disable = false; - u16 reg, loc; + unsigned int *mirror_count = + &dev->ports[port].mirror_count[mirror->ingress]; + u16 reg, other_reg, loc, other_loc; + int ret; - if (mirror->ingress) - loc = B53_IG_MIR_CTL; - else - loc = B53_EG_MIR_CTL; + if (!*mirror_count) + return; + + if (--(*mirror_count)) + return; + + loc = mirror->ingress ? B53_IG_MIR_CTL : B53_EG_MIR_CTL; + other_loc = mirror->ingress ? B53_EG_MIR_CTL : B53_IG_MIR_CTL; /* Update the desired ingress/egress register */ - b53_read16(dev, B53_MGMT_PAGE, loc, ®); - reg &= ~BIT(port); - if (!(reg & MIRROR_MASK)) - loc_disable = true; - b53_write16(dev, B53_MGMT_PAGE, loc, reg); + ret = b53_read16(dev, B53_MGMT_PAGE, loc, ®); + if (ret) + goto err; + + reg &= ~b53_mirror_port_mask(dev, port); + ret = b53_write16(dev, B53_MGMT_PAGE, loc, reg); + if (ret) + goto err; /* Now look at the other one to know if we can disable mirroring * entirely */ - if (mirror->ingress) - b53_read16(dev, B53_MGMT_PAGE, B53_EG_MIR_CTL, ®); - else - b53_read16(dev, B53_MGMT_PAGE, B53_IG_MIR_CTL, ®); - if (!(reg & MIRROR_MASK)) - other_loc_disable = true; + ret = b53_read16(dev, B53_MGMT_PAGE, other_loc, &other_reg); + if (ret) + goto err; - b53_read16(dev, B53_MGMT_PAGE, B53_MIR_CAP_CTL, ®); - /* Both no longer have ports, let's disable mirroring */ - if (loc_disable && other_loc_disable) { - reg &= ~MIRROR_EN; - reg &= ~mirror->to_local_port; - } - b53_write16(dev, B53_MGMT_PAGE, B53_MIR_CAP_CTL, reg); + if ((reg | other_reg) & MIRROR_MASK) + return; + + ret = b53_read16(dev, B53_MGMT_PAGE, B53_MIR_CAP_CTL, ®); + if (ret) + goto err; + + reg &= ~(MIRROR_EN | b53_mirror_capture_port_mask(dev)); + ret = b53_write16(dev, B53_MGMT_PAGE, B53_MIR_CAP_CTL, reg); + if (ret) + goto err; + + return; + +err: + dev_err(dev->dev, "Failed to delete mirror rule for port %d: %d\n", + port, ret); } EXPORT_SYMBOL(b53_mirror_del); @@ -3172,6 +3300,7 @@ static int b53_switch_init(struct b53_device *dev) dev->vta_regs[1] = chip->vta_regs[1]; dev->vta_regs[2] = chip->vta_regs[2]; dev->jumbo_pm_reg = chip->jumbo_pm_reg; + dev->jumbo_size_reg = chip->jumbo_size_reg; dev->imp_port = chip->imp_port; dev->num_vlans = chip->vlans; dev->num_arl_bins = chip->arl_bins; diff --git a/drivers/net/dsa/b53/b53_priv.h b/drivers/net/dsa/b53/b53_priv.h index c4d2a41c714f62..df00a5ae46c9d3 100644 --- a/drivers/net/dsa/b53/b53_priv.h +++ b/drivers/net/dsa/b53/b53_priv.h @@ -119,6 +119,8 @@ struct b53_pcs { #define B53_N_PCS 2 struct b53_port { + /* References to each egress/ingress mirror source mask bit. */ + unsigned int mirror_count[2]; u16 vlan_ctl_mask; u16 pvid; struct ethtool_keee eee; @@ -170,6 +172,7 @@ struct b53_device { /* run time configuration */ bool enable_jumbo; + unsigned int mirror_port; unsigned int num_vlans; struct b53_vlan *vlans; @@ -545,6 +548,7 @@ int b53_mdb_add(struct dsa_switch *ds, int port, int b53_mdb_del(struct dsa_switch *ds, int port, const struct switchdev_obj_port_mdb *mdb, struct dsa_db db); +int b53_mirror_init(struct dsa_switch *ds); int b53_mirror_add(struct dsa_switch *ds, int port, struct dsa_mall_mirror_tc_entry *mirror, bool ingress, struct netlink_ext_ack *extack); diff --git a/drivers/net/dsa/b53/b53_regs.h b/drivers/net/dsa/b53/b53_regs.h index cfdb5ed3832606..ee049927a63aee 100644 --- a/drivers/net/dsa/b53/b53_regs.h +++ b/drivers/net/dsa/b53/b53_regs.h @@ -239,6 +239,7 @@ /* Mirror capture control register (16 bit) */ #define B53_MIR_CAP_CTL 0x10 #define CAP_PORT_MASK 0xf +#define CAP_PORT_MASK_25 0x7ff #define BLK_NOT_MIR BIT(14) #define MIRROR_EN BIT(15) diff --git a/drivers/net/dsa/b53/b53_srab.c b/drivers/net/dsa/b53/b53_srab.c index e6d14fdc56fde2..7306535a892a2d 100644 --- a/drivers/net/dsa/b53/b53_srab.c +++ b/drivers/net/dsa/b53/b53_srab.c @@ -105,7 +105,7 @@ static int b53_srab_request_grant(struct b53_device *dev) break; usleep_range(10, 100); } - if (WARN_ON(i == 5)) + if (WARN_ON(i == 20)) return -EIO; return 0; diff --git a/drivers/net/dsa/bcm_sf2.c b/drivers/net/dsa/bcm_sf2.c index 1747a1f20c78e2..cbaa5de9b1072f 100644 --- a/drivers/net/dsa/bcm_sf2.c +++ b/drivers/net/dsa/bcm_sf2.c @@ -1061,6 +1061,10 @@ static int bcm_sf2_sw_setup(struct dsa_switch *ds) unsigned int port; int ret; + ret = b53_mirror_init(ds); + if (ret) + return ret; + /* Enable all valid ports and disable those unused */ for (port = 0; port < priv->hw_params.num_ports; port++) { /* IMP port receives special treatment */ diff --git a/drivers/net/dsa/mv88e6xxx/chip.c b/drivers/net/dsa/mv88e6xxx/chip.c index 425fd2d22c289e..abef896b7670ff 100644 --- a/drivers/net/dsa/mv88e6xxx/chip.c +++ b/drivers/net/dsa/mv88e6xxx/chip.c @@ -3779,7 +3779,7 @@ static int mv88e6xxx_mdio_read(struct mii_bus *bus, int phy, int reg) mv88e6xxx_reg_unlock(chip); /* Some internal PHYs don't have a model number. */ - if (reg == MII_PHYSID2 && !(val & 0x3f0) && + if (!mdio_bus->external && reg == MII_PHYSID2 && !(val & 0x3f0) && chip->info->family < ARRAY_SIZE(family_prod_id_table)) { prod_id = family_prod_id_table[chip->info->family]; if (prod_id) diff --git a/drivers/net/dsa/ocelot/felix.c b/drivers/net/dsa/ocelot/felix.c index c99fd3d23bb3f1..76aabb8e288787 100644 --- a/drivers/net/dsa/ocelot/felix.c +++ b/drivers/net/dsa/ocelot/felix.c @@ -1239,8 +1239,19 @@ static int felix_port_enable(struct dsa_switch *ds, int port, if (ocelot->npi >= 0) { struct net_device *conduit = dsa_port_to_conduit(dp); + int cpu; - if (felix_cpu_port_for_conduit(ds, conduit) != ocelot->npi) { + /* Do not use conduit->dsa_ptr for a physical conduit. It is + * NULL before DSA sets up the conduit and after it tears it + * down, and opening a user port can reach this check in both + * cases. + */ + if (netif_is_lag_master(conduit)) + cpu = felix_cpu_port_for_conduit(ds, conduit); + else + cpu = dp->cpu_dp->index; + + if (cpu != ocelot->npi) { dev_err(ds->dev, "Multiple conduits are not allowed\n"); return -EINVAL; } diff --git a/drivers/net/ethernet/amazon/ena/ena_com.c b/drivers/net/ethernet/amazon/ena/ena_com.c index 297fb36ab8c16f..9b14cddf4432ee 100644 --- a/drivers/net/ethernet/amazon/ena/ena_com.c +++ b/drivers/net/ethernet/amazon/ena/ena_com.c @@ -1992,6 +1992,7 @@ int ena_com_admin_init(struct ena_com_dev *ena_dev, admin_queue->q_depth = ENA_ADMIN_QUEUE_DEPTH; + admin_queue->ena_dev = ena_dev; admin_queue->q_dmadev = ena_dev->dmadev; admin_queue->polling = false; admin_queue->curr_cmd_id = 0; @@ -2045,7 +2046,6 @@ int ena_com_admin_init(struct ena_com_dev *ena_dev, if (ret) goto error; - admin_queue->ena_dev = ena_dev; admin_queue->running_state = true; return 0; diff --git a/drivers/net/ethernet/amazon/ena/ena_netdev.c b/drivers/net/ethernet/amazon/ena/ena_netdev.c index ecc6f1d827f9cf..560b20a5861c8a 100644 --- a/drivers/net/ethernet/amazon/ena/ena_netdev.c +++ b/drivers/net/ethernet/amazon/ena/ena_netdev.c @@ -2609,7 +2609,6 @@ static int ena_tx_map_skb(struct ena_ring *tx_ring, tx_info->skb = NULL; - tx_info->num_of_bufs += i; ena_unmap_tx_buff(tx_ring, tx_info); return -EINVAL; diff --git a/drivers/net/ethernet/broadcom/asp2/bcmasp.c b/drivers/net/ethernet/broadcom/asp2/bcmasp.c index a59a006cea3a73..af9e1421498786 100644 --- a/drivers/net/ethernet/broadcom/asp2/bcmasp.c +++ b/drivers/net/ethernet/broadcom/asp2/bcmasp.c @@ -1342,7 +1342,7 @@ static int bcmasp_probe(struct platform_device *pdev) bcmasp_init_wol(priv); - ports_node = of_find_node_by_name(dev->of_node, "ethernet-ports"); + ports_node = of_get_child_by_name(dev->of_node, "ethernet-ports"); if (!ports_node) { dev_warn(dev, "No ports found\n"); ret = -EINVAL; diff --git a/drivers/net/ethernet/broadcom/bcm4908_enet.c b/drivers/net/ethernet/broadcom/bcm4908_enet.c index fd2715f84af979..8bc620de2ef0d5 100644 --- a/drivers/net/ethernet/broadcom/bcm4908_enet.c +++ b/drivers/net/ethernet/broadcom/bcm4908_enet.c @@ -7,12 +7,14 @@ #include #include #include +#include #include #include #include #include #include #include +#include #include "bcm4908_enet.h" #include "unimac.h" @@ -289,8 +291,10 @@ static int bcm4908_enet_dma_alloc_rx_buf(struct bcm4908_enet *enet, unsigned int tmp |= DMA_CTL_STATUS_OWN; if (idx == enet->rx_ring.length - 1) tmp |= DMA_CTL_STATUS_WRAP; - buf_desc->ctl = cpu_to_le32(tmp); buf_desc->addr = cpu_to_le32(slot->dma_addr); + /* Hand the descriptor to the DMA only once it holds the new buffer */ + dma_wmb(); + buf_desc->ctl = cpu_to_le32(tmp); return 0; } @@ -312,6 +316,11 @@ static void bcm4908_enet_dma_ring_init(struct bcm4908_enet *enet, enet_write(enet, ring->st_ram_block + ENET_DMA_CH_STATE_RAM_BASE_DESC_PTR, (uint32_t)ring->dma_addr); + /* A descriptor the stopped DMA never completed still carries OWN */ + if (ring->is_tx) + memset(ring->buf_desc, 0, + ring->length * sizeof(*ring->buf_desc)); + ring->read_idx = 0; ring->write_idx = 0; } @@ -327,7 +336,8 @@ static void bcm4908_enet_dma_uninit(struct bcm4908_enet *enet) slot = &rx_ring->slots[i]; if (!slot->buf) continue; - dma_unmap_single(dev, slot->dma_addr, slot->len, DMA_FROM_DEVICE); + dma_unmap_single(dev, slot->dma_addr, ENET_RX_BUF_DMA_SIZE, + DMA_FROM_DEVICE); skb_free_frag(slot->buf); slot->buf = NULL; } @@ -361,10 +371,22 @@ static void bcm4908_enet_dma_tx_ring_enable(struct bcm4908_enet *enet, enet_write(enet, ring->cfg_block + ENET_DMA_CH_CFG, ENET_DMA_CH_CFG_ENABLE); } -static void bcm4908_enet_dma_tx_ring_disable(struct bcm4908_enet *enet, - struct bcm4908_enet_dma_ring *ring) +static int bcm4908_enet_dma_tx_ring_disable(struct bcm4908_enet *enet, + struct bcm4908_enet_dma_ring *ring) { + u32 tmp; + int err; + enet_write(enet, ring->cfg_block + ENET_DMA_CH_CFG, 0); + + /* Wait for the channel to stop, as for RX, before freeing buffers */ + err = read_poll_timeout(enet_read, tmp, !(tmp & ENET_DMA_CH_CFG_ENABLE), + 10, 2000, false, enet, + ring->cfg_block + ENET_DMA_CH_CFG); + if (err) + dev_warn(enet->dev, "Timeout waiting for DMA TX stop\n"); + + return err; } static void bcm4908_enet_dma_rx_ring_enable(struct bcm4908_enet *enet, @@ -390,7 +412,7 @@ static void bcm4908_enet_dma_rx_ring_disable(struct bcm4908_enet *enet, usleep_range(10, 30); } while (!time_after_eq(jiffies, deadline)); - dev_warn(enet->dev, "Timeout waiting for DMA TX stop\n"); + dev_warn(enet->dev, "Timeout waiting for DMA RX stop\n"); } /*** @@ -495,6 +517,25 @@ static int bcm4908_enet_open(struct net_device *netdev) return 0; } +static void bcm4908_enet_tx_ring_clean(struct bcm4908_enet *enet) +{ + struct bcm4908_enet_dma_ring *tx_ring = &enet->tx_ring; + struct device *dev = enet->dev; + int i; + + for (i = tx_ring->read_idx; i != tx_ring->write_idx; + i = i == tx_ring->length - 1 ? 0 : i + 1) { + struct bcm4908_enet_dma_ring_slot *slot = &tx_ring->slots[i]; + + dma_unmap_single(dev, slot->dma_addr, slot->len, DMA_TO_DEVICE); + dev_kfree_skb_any(slot->skb); + } + + /* Leave the ring empty, so that nothing frees these skbs again */ + tx_ring->read_idx = 0; + tx_ring->write_idx = 0; +} + static int bcm4908_enet_stop(struct net_device *netdev) { struct bcm4908_enet *enet = netdev_priv(netdev); @@ -508,8 +549,10 @@ static int bcm4908_enet_stop(struct net_device *netdev) netdev_reset_queue(netdev); bcm4908_enet_dma_rx_ring_disable(enet, &enet->rx_ring); - bcm4908_enet_dma_tx_ring_disable(enet, &enet->tx_ring); + /* Leave the TX buffers alone if the channel may still read them */ + if (!bcm4908_enet_dma_tx_ring_disable(enet, &enet->tx_ring)) + bcm4908_enet_tx_ring_clean(enet); bcm4908_enet_dma_uninit(enet); free_irq(enet->irq_tx, enet); @@ -518,62 +561,77 @@ static int bcm4908_enet_stop(struct net_device *netdev) return 0; } +/* One descriptor always stays unused, so read_idx == write_idx can only + * mean an empty ring + */ +static int bcm4908_enet_tx_free_descs(struct bcm4908_enet_dma_ring *ring) +{ + /* Pairs with smp_store_release() in bcm4908_enet_poll_tx() */ + int free = smp_load_acquire(&ring->read_idx) - + READ_ONCE(ring->write_idx) - 1; + + return free < 0 ? free + ring->length : free; +} + static netdev_tx_t bcm4908_enet_start_xmit(struct sk_buff *skb, struct net_device *netdev) { + struct netdev_queue *txq = netdev_get_tx_queue(netdev, 0); struct bcm4908_enet *enet = netdev_priv(netdev); struct bcm4908_enet_dma_ring *ring = &enet->tx_ring; struct bcm4908_enet_dma_ring_slot *slot; struct device *dev = enet->dev; struct bcm4908_enet_dma_ring_bd *buf_desc; - int free_buf_descs; + dma_addr_t dma_addr; u32 tmp; /* Free transmitted skbs */ if (enet->irq_tx < 0 && - !(le32_to_cpu(ring->buf_desc[ring->read_idx].ctl) & DMA_CTL_STATUS_OWN)) + !(le32_to_cpu(ring->buf_desc[READ_ONCE(ring->read_idx)].ctl) & + DMA_CTL_STATUS_OWN)) napi_schedule(&enet->tx_ring.napi); - /* Don't use the last empty buf descriptor */ - if (ring->read_idx <= ring->write_idx) - free_buf_descs = ring->read_idx - ring->write_idx + ring->length; - else - free_buf_descs = ring->read_idx - ring->write_idx; - if (free_buf_descs < 2) { - netif_stop_queue(netdev); + if (!netif_txq_maybe_stop(txq, bcm4908_enet_tx_free_descs(ring), 1, 1)) return NETDEV_TX_BUSY; - } - /* Hardware removes OWN bit after sending data */ - buf_desc = &ring->buf_desc[ring->write_idx]; - if (unlikely(le32_to_cpu(buf_desc->ctl) & DMA_CTL_STATUS_OWN)) { - netif_stop_queue(netdev); - return NETDEV_TX_BUSY; + dma_addr = dma_map_single(dev, skb->data, skb->len, DMA_TO_DEVICE); + if (unlikely(dma_mapping_error(dev, dma_addr))) { + dev_kfree_skb_any(skb); + netdev->stats.tx_dropped++; + return NETDEV_TX_OK; } + buf_desc = &ring->buf_desc[ring->write_idx]; slot = &ring->slots[ring->write_idx]; slot->skb = skb; slot->len = skb->len; - slot->dma_addr = dma_map_single(dev, skb->data, skb->len, DMA_TO_DEVICE); - if (unlikely(dma_mapping_error(dev, slot->dma_addr))) - return NETDEV_TX_BUSY; + slot->dma_addr = dma_addr; tmp = skb->len << DMA_CTL_LEN_DESC_BUFLENGTH_SHIFT; tmp |= DMA_CTL_STATUS_OWN; tmp |= DMA_CTL_STATUS_SOP; tmp |= DMA_CTL_STATUS_EOP; tmp |= DMA_CTL_STATUS_APPEND_CRC; - if (ring->write_idx + 1 == ring->length - 1) + if (ring->write_idx == ring->length - 1) tmp |= DMA_CTL_STATUS_WRAP; netdev_sent_queue(enet->netdev, skb->len); buf_desc->addr = cpu_to_le32((uint32_t)slot->dma_addr); + /* The DMA must not see OWN before the buffer address */ + dma_wmb(); buf_desc->ctl = cpu_to_le32(tmp); + /* Publish the slot and the descriptor before the index; pairs with + * smp_load_acquire() in bcm4908_enet_poll_tx() + */ + smp_store_release(&ring->write_idx, + ring->write_idx < ring->length - 1 ? + ring->write_idx + 1 : 0); + bcm4908_enet_dma_tx_ring_enable(enet, &enet->tx_ring); - if (++ring->write_idx == ring->length - 1) - ring->write_idx = 0; + /* poll_tx() wakes the queue once there is room again */ + netif_txq_maybe_stop(txq, bcm4908_enet_tx_free_descs(ring), 1, 1); return NETDEV_TX_OK; } @@ -597,6 +655,8 @@ static int bcm4908_enet_poll_rx(struct napi_struct *napi, int weight) ctl = le32_to_cpu(buf_desc->ctl); if (ctl & DMA_CTL_STATUS_OWN) break; + /* Read the rest only after the DMA gave the descriptor back */ + dma_rmb(); slot = enet->rx_ring.slots[enet->rx_ring.read_idx]; @@ -612,6 +672,8 @@ static int bcm4908_enet_poll_rx(struct napi_struct *napi, int weight) if (len < ETH_ZLEN || (ctl & (DMA_CTL_STATUS_SOP | DMA_CTL_STATUS_EOP)) != (DMA_CTL_STATUS_SOP | DMA_CTL_STATUS_EOP)) { + dma_unmap_single(dev, slot.dma_addr, + ENET_RX_BUF_DMA_SIZE, DMA_FROM_DEVICE); skb_free_frag(slot.buf); enet->netdev->stats.rx_dropped++; break; @@ -652,17 +714,22 @@ static int bcm4908_enet_poll_tx(struct napi_struct *napi, int weight) { struct bcm4908_enet_dma_ring *tx_ring = container_of(napi, struct bcm4908_enet_dma_ring, napi); struct bcm4908_enet *enet = container_of(tx_ring, struct bcm4908_enet, tx_ring); + struct netdev_queue *txq = netdev_get_tx_queue(enet->netdev, 0); struct bcm4908_enet_dma_ring_bd *buf_desc; struct bcm4908_enet_dma_ring_slot *slot; struct device *dev = enet->dev; + int read_idx = tx_ring->read_idx; unsigned int bytes = 0; int handled = 0; - while (handled < weight && tx_ring->read_idx != tx_ring->write_idx) { - buf_desc = &tx_ring->buf_desc[tx_ring->read_idx]; + while (handled < weight) { + /* Pairs with the release in bcm4908_enet_start_xmit() */ + if (read_idx == smp_load_acquire(&tx_ring->write_idx)) + break; + buf_desc = &tx_ring->buf_desc[read_idx]; if (le32_to_cpu(buf_desc->ctl) & DMA_CTL_STATUS_OWN) break; - slot = &tx_ring->slots[tx_ring->read_idx]; + slot = &tx_ring->slots[read_idx]; dma_unmap_single(dev, slot->dma_addr, slot->len, DMA_TO_DEVICE); dev_kfree_skb(slot->skb); @@ -670,22 +737,26 @@ static int bcm4908_enet_poll_tx(struct napi_struct *napi, int weight) handled++; bytes += slot->len; - if (++tx_ring->read_idx == tx_ring->length) - tx_ring->read_idx = 0; + if (++read_idx == tx_ring->length) + read_idx = 0; } + /* Be done with the slots before start_xmit() may reuse them; pairs + * with smp_load_acquire() in bcm4908_enet_tx_free_descs() + */ + smp_store_release(&tx_ring->read_idx, read_idx); - netdev_completed_queue(enet->netdev, handled, bytes); enet->netdev->stats.tx_packets += handled; enet->netdev->stats.tx_bytes += bytes; + /* Reports to BQL, and wakes the queue if start_xmit() stopped it */ + netif_txq_completed_wake(txq, handled, bytes, + bcm4908_enet_tx_free_descs(tx_ring), 1); + if (handled < weight) { napi_complete_done(napi, handled); bcm4908_enet_dma_ring_intrs_on(enet, tx_ring); } - if (netif_queue_stopped(enet->netdev)) - netif_wake_queue(enet->netdev); - return handled; } diff --git a/drivers/net/ethernet/broadcom/bcmsysport.c b/drivers/net/ethernet/broadcom/bcmsysport.c index bc88a27da16bee..0902dd0dd94bcb 100644 --- a/drivers/net/ethernet/broadcom/bcmsysport.c +++ b/drivers/net/ethernet/broadcom/bcmsysport.c @@ -844,8 +844,8 @@ static unsigned int bcm_sysport_desc_rx(struct bcm_sysport_priv *priv, priv->rx_read_ptr = 0; } - priv->dim.packets = processed; - priv->dim.bytes = processed_bytes; + priv->dim.packets += processed; + priv->dim.bytes += processed_bytes; return processed; } @@ -1012,18 +1012,19 @@ static int bcm_sysport_poll(struct napi_struct *napi, int budget) else rdma_writel(priv, priv->rx_c_index << 16, RDMA_CONS_INDEX); - if (work_done < budget) { - napi_complete_done(napi, work_done); - /* re-enable RX interrupts */ - intrl2_0_mask_clear(priv, INTRL2_0_RDMA_MBDONE); - } - + /* net_dim() can queue work, so run it while NAPI is still owned */ if (priv->dim.use_dim) { dim_update_sample(priv->dim.event_ctr, priv->dim.packets, priv->dim.bytes, &dim_sample); net_dim(&priv->dim.dim, &dim_sample); } + if (work_done < budget) { + napi_complete_done(napi, work_done); + /* re-enable RX interrupts */ + intrl2_0_mask_clear(priv, INTRL2_0_RDMA_MBDONE); + } + return work_done; } @@ -1452,8 +1453,11 @@ static void bcm_sysport_init_dim(struct bcm_sysport_priv *priv, { struct bcm_sysport_net_dim *dim = &priv->dim; + memset(&dim->dim, 0, sizeof(dim->dim)); INIT_WORK(&dim->dim.work, cb); dim->dim.mode = DIM_CQ_PERIOD_MODE_START_FROM_EQE; + /* Match the profile bcm_sysport_init_rx_coalesce() programs */ + dim->dim.profile_ix = NET_DIM_DEF_PROFILE_EQE; dim->event_ctr = 0; dim->packets = 0; dim->bytes = 0; diff --git a/drivers/net/ethernet/broadcom/bnxt/bnxt.c b/drivers/net/ethernet/broadcom/bnxt/bnxt.c index 6846a27bfef4c0..52606db3f7b4a8 100644 --- a/drivers/net/ethernet/broadcom/bnxt/bnxt.c +++ b/drivers/net/ethernet/broadcom/bnxt/bnxt.c @@ -8618,6 +8618,43 @@ int bnxt_hwrm_set_coal(struct bnxt *bp) return rc; } +/* Program Rx coalescing of a single ring, e.g. after its completion ring + * was re-allocated in the FW, which resets the coalescing parameters. + */ +static int bnxt_hwrm_set_rx_ring_coal(struct bnxt *bp, struct bnxt_napi *bnapi) +{ + struct hwrm_ring_cmpl_ring_cfg_aggint_params_input *req; + int rc; + + if (bp->flags & BNXT_FLAG_DIM) + return bnxt_hwrm_set_ring_coal(bp, bnapi); + + rc = hwrm_req_init(bp, req, HWRM_RING_CMPL_RING_CFG_AGGINT_PARAMS); + if (rc) + return rc; + + bnxt_hwrm_set_coal_params(bp, &bp->rx_coal, req); + return bnxt_hwrm_set_rx_coal(bp, bnapi, req); +} + +/* Program Tx coalescing of the completion ring of a single Tx ring, e.g. + * after it was re-allocated in the FW. + */ +static int bnxt_hwrm_set_tx_ring_coal(struct bnxt *bp, + struct bnxt_tx_ring_info *txr) +{ + struct hwrm_ring_cmpl_ring_cfg_aggint_params_input *req; + int rc; + + rc = hwrm_req_init(bp, req, HWRM_RING_CMPL_RING_CFG_AGGINT_PARAMS); + if (rc) + return rc; + + bnxt_hwrm_set_coal_params(bp, &bp->tx_coal, req); + req->ring_id = cpu_to_le16(bnxt_cp_ring_for_tx(bp, txr)); + return hwrm_req_send(bp, req); +} + static void bnxt_hwrm_stat_ctx_free(struct bnxt *bp) { struct hwrm_stat_ctx_clr_stats_input *req0 = NULL; @@ -11318,7 +11355,7 @@ static int bnxt_init_chip(struct bnxt *bp, bool irq_re_init) /* Filter for default vnic 0 */ rc = bnxt_hwrm_set_vnic_filter(bp, 0, 0, bp->dev->dev_addr); if (rc) { - if (BNXT_VF(bp) && rc == -ENODEV) + if (rc == -ECOMM) netdev_err(bp->dev, "Cannot configure L2 filter while PF is unavailable\n"); else netdev_err(bp->dev, "HWRM vnic filter failure rc: %x\n", rc); @@ -11838,6 +11875,11 @@ static int bnxt_tx_queue_start(struct bnxt *bp, int idx) if (rc) return rc; + rc = bnxt_hwrm_set_tx_ring_coal(bp, txr); + if (rc) + netdev_warn(bp->dev, "HWRM set coalescing failure rc: %d\n", + rc); + rc = bnxt_hwrm_tx_ring_alloc(bp, txr, false); if (rc) return rc; @@ -12476,7 +12518,7 @@ int bnxt_update_link(struct bnxt *bp, bool chng_link_state) rc = hwrm_req_send(bp, req); if (rc) { hwrm_req_drop(bp, req); - if (BNXT_VF(bp) && rc == -ENODEV) { + if (rc == -ECOMM) { netdev_warn(bp->dev, "Cannot obtain link state while PF unavailable.\n"); rc = 0; } @@ -13953,7 +13995,7 @@ static int bnxt_cfg_rx_mode(struct bnxt *bp, struct netdev_hw_addr_list *uc, for (i = 1, off = 0; i < vnic->uc_filter_count; i++, off += ETH_ALEN) { rc = bnxt_hwrm_set_vnic_filter(bp, 0, i, vnic->uc_list + off); if (rc) { - if (BNXT_VF(bp) && rc == -ENODEV) { + if (rc == -ECOMM) { netdev_warn(bp->dev, "Cannot configure L2 filters while PF is unavailable, will retry\n"); rc = -EAGAIN; } else if (rc == -EAGAIN) { @@ -16643,6 +16685,11 @@ static int bnxt_queue_start(struct net_device *dev, rc = bnxt_hwrm_cp_ring_alloc_p5(bp, rxr->rx_cpr); if (rc) goto err_reset; + + rc = bnxt_hwrm_set_rx_ring_coal(bp, bnapi); + if (rc) + netdev_warn(bp->dev, "HWRM set coalescing failure rc: %d\n", + rc); } rc = bnxt_hwrm_rx_agg_ring_alloc(bp, rxr); @@ -17003,7 +17050,7 @@ static int bnxt_set_dflt_rings(struct bnxt *bp, bool sh) } rc = __bnxt_reserve_rings(bp); - if (rc && rc != -ENODEV) + if (rc && rc != -ECOMM) netdev_warn(bp->dev, "Unable to reserve tx rings\n"); bnxt_adj_tx_rings(bp); @@ -17013,7 +17060,7 @@ static int bnxt_set_dflt_rings(struct bnxt *bp, bool sh) /* Rings may have been trimmed, re-reserve the trimmed rings. */ if (bnxt_need_reserve_rings(bp)) { rc = __bnxt_reserve_rings(bp); - if (rc && rc != -ENODEV) + if (rc && rc != -ECOMM) netdev_warn(bp->dev, "2nd rings reservation failed.\n"); bnxt_adj_tx_rings(bp); } @@ -17039,7 +17086,7 @@ static int bnxt_init_dflt_ring_mode(struct bnxt *bp) bnxt_clear_int_mode(bp); rc = bnxt_set_dflt_rings(bp, true); if (rc) { - if (BNXT_VF(bp) && rc == -ENODEV) + if (rc == -ECOMM) netdev_err(bp->dev, "Cannot configure VF rings while PF is unavailable.\n"); else netdev_err(bp->dev, "Not enough rings available.\n"); @@ -17417,7 +17464,7 @@ static int bnxt_init_one(struct pci_dev *pdev, const struct pci_device_id *ent) bnxt_aux_devices_init(bp); rc = bnxt_set_dflt_rings(bp, true); if (rc) { - if (BNXT_VF(bp) && rc == -ENODEV) { + if (rc == -ECOMM) { netdev_err(bp->dev, "Cannot configure VF rings while PF is unavailable.\n"); } else { netdev_err(bp->dev, "Not enough rings available.\n"); @@ -17573,21 +17620,50 @@ static int bnxt_suspend(struct device *device) return rc; } +#define BNXT_RESUME_MAX_RETRY 10 + static int bnxt_resume(struct device *device) { struct net_device *dev = dev_get_drvdata(device); struct bnxt *bp = netdev_priv(dev); - int rc = 0; + int i, rc; - rtnl_lock(); - netdev_lock(dev); rc = pci_enable_device(bp->pdev); if (rc) { netdev_err(dev, "Cannot re-enable PCI device during resume, err = %d\n", rc); - goto resume_exit; + return rc; } pci_set_master(bp->pdev); + if (BNXT_VF(bp)) { + for (i = 0; i < BNXT_RESUME_MAX_RETRY; i++) { + rc = bnxt_hwrm_poll(bp); + if (rc != -EAGAIN && rc != -EBUSY && rc != -ECOMM) + break; + + /* Wait briefly for -EAGAIN (FW busy), a bit longer for + * -ECOMM (PF down) to allow the PF to fully initialize. + * For -EBUSY, the message typically has timed out, so + * try again immediately. + */ + if (i < BNXT_RESUME_MAX_RETRY - 1) { + if (rc == -EAGAIN) + msleep(250); + else if (rc == -ECOMM) + msleep(750); + } + } + if (rc) { + netdev_err(dev, + "Firmware not responding during resume, rc = %d\n", + rc); + return -ENODEV; + } + } + + rtnl_lock(); + netdev_lock(dev); + if (bnxt_hwrm_ver_get(bp)) { rc = -ENODEV; goto resume_exit; diff --git a/drivers/net/ethernet/broadcom/bnxt/bnxt_hwrm.c b/drivers/net/ethernet/broadcom/bnxt/bnxt_hwrm.c index 5bfabdca7d0e2a..de02d1baa75142 100644 --- a/drivers/net/ethernet/broadcom/bnxt/bnxt_hwrm.c +++ b/drivers/net/ethernet/broadcom/bnxt/bnxt_hwrm.c @@ -360,7 +360,7 @@ static int __hwrm_to_stderr(u32 hwrm_err) case HWRM_ERR_CODE_CMD_NOT_SUPPORTED: return -EOPNOTSUPP; case HWRM_ERR_CODE_PF_UNAVAILABLE: - return -ENODEV; + return -ECOMM; default: return -EIO; } @@ -716,6 +716,8 @@ static int __hwrm_send(struct bnxt *bp, struct bnxt_hwrm_ctx *ctx) * ENOMEM: HWRM has no buffers. * EAGAIN: HWRM busy or reset in progress. * EOPNOTSUPP: Invalid request type. + * ENODEV: PCI device is disabled. + * ECOMM: The parent PF is unavailable when issued on VFs. * EIO: Any other error. * Error handling is orthogonal to request ownership. An unowned request will * still be consumed on error. If the caller owns the request, then the caller diff --git a/drivers/net/ethernet/broadcom/genet/bcmgenet.c b/drivers/net/ethernet/broadcom/genet/bcmgenet.c index 4d2be2a21ed1bc..b81408e6293c3f 100644 --- a/drivers/net/ethernet/broadcom/genet/bcmgenet.c +++ b/drivers/net/ethernet/broadcom/genet/bcmgenet.c @@ -2486,8 +2486,8 @@ static unsigned int bcmgenet_desc_rx(struct bcmgenet_rx_ring *ring, bcmgenet_rdma_ring_writel(priv, ring->index, ring->c_index, RDMA_CONS_INDEX); } - ring->dim.bytes = bytes_processed; - ring->dim.packets = rxpktprocessed; + ring->dim.bytes += bytes_processed; + ring->dim.packets += rxpktprocessed; return rxpktprocessed; } @@ -2502,15 +2502,16 @@ static int bcmgenet_rx_poll(struct napi_struct *napi, int budget) work_done = bcmgenet_desc_rx(ring, budget); - if (work_done < budget && napi_complete_done(napi, work_done)) - bcmgenet_rx_ring_int_enable(ring); - + /* net_dim() can queue work, so run it while NAPI is still owned */ if (ring->dim.use_dim) { dim_update_sample(ring->dim.event_ctr, ring->dim.packets, ring->dim.bytes, &dim_sample); net_dim(&ring->dim.dim, &dim_sample); } + if (work_done < budget && napi_complete_done(napi, work_done)) + bcmgenet_rx_ring_int_enable(ring); + return work_done; } @@ -2702,8 +2703,11 @@ static void bcmgenet_init_dim(struct bcmgenet_rx_ring *ring, { struct bcmgenet_net_dim *dim = &ring->dim; + memset(&dim->dim, 0, sizeof(dim->dim)); INIT_WORK(&dim->dim.work, cb); dim->dim.mode = DIM_CQ_PERIOD_MODE_START_FROM_EQE; + /* Match the profile bcmgenet_init_rx_coalesce() programs */ + dim->dim.profile_ix = NET_DIM_DEF_PROFILE_EQE; dim->event_ctr = 0; dim->packets = 0; dim->bytes = 0; @@ -2822,6 +2826,8 @@ static int bcmgenet_init_rx_ring(struct bcmgenet_priv *priv, ring->read_ptr = start_ptr; ring->cb_ptr = start_ptr; ring->end_ptr = end_ptr - 1; + /* Zeroing RDMA_PROD_INDEX below also clears the discard counter */ + ring->old_discards = 0; ret = bcmgenet_rx_ring_create_pool(priv, ring); if (ret) @@ -3014,7 +3020,8 @@ static void bcmgenet_disable_rx_napi(struct bcmgenet_priv *priv) for (i = 0; i <= priv->hw_params->rx_queues; ++i) { ring = &priv->rx_rings[i]; napi_disable(&ring->napi); - cancel_work_sync(&ring->dim.dim.work); + /* Cancelling would leave DIM stuck in DIM_APPLY_NEW_PROFILE */ + flush_work(&ring->dim.dim.work); } } diff --git a/drivers/net/ethernet/broadcom/tg3.c b/drivers/net/ethernet/broadcom/tg3.c index 95827df4cf6a1b..12f199355984b1 100644 --- a/drivers/net/ethernet/broadcom/tg3.c +++ b/drivers/net/ethernet/broadcom/tg3.c @@ -56,6 +56,7 @@ #include #include #include +#include #include #include @@ -3379,6 +3380,9 @@ static int tg3_nvram_write_block_unbuffered(struct tg3 *tp, u32 offset, u32 len, u32 nvram_cmd; u8 *tmp; + if (pagesize < 4 || !is_power_of_2(pagesize)) + return -EINVAL; + tmp = kmalloc(pagesize, GFP_KERNEL); if (tmp == NULL) return -ENOMEM; @@ -3399,13 +3403,14 @@ static int tg3_nvram_write_block_unbuffered(struct tg3 *tp, u32 offset, u32 len, break; page_off = offset & pagemask; - size = pagesize; + size = pagesize - page_off; if (len < size) size = len; len -= size; memcpy(tmp + page_off, buf, size); + buf += size; offset = offset + (pagesize - page_off); @@ -8867,6 +8872,13 @@ static int tg3_alloc_consistent(struct tg3 *tp) if (!tnapi->hw_status) goto err_out; + if (tg3_asic_rev(tp) == ASIC_REV_57766 && + (lower_32_bits(tnapi->status_mapping) & 0xffff0000) == + 0xffff0000) + dev_warn(&tp->pdev->dev, + "Status block at DMA address %pad may cause TX timeouts on this device\n", + &tnapi->status_mapping); + sblk = tnapi->hw_status; if (tg3_flag(tp, ENABLE_RSS)) { @@ -15990,20 +16002,26 @@ static void tg3_read_mgmtfw_ver(struct tg3 *tp) } } -static void tg3_probe_ncsi(struct tg3 *tp) +/* Returns true if valid, ready APE firmware is present, regardless of + * whether it advertises NCSI (it may be DASH or SMASH). Sets APE_HAS_NCSI + * if the NCSI feature is advertised. + */ +static bool tg3_probe_ncsi(struct tg3 *tp) { u32 apedata; apedata = tg3_ape_read32(tp, TG3_APE_SEG_SIG); if (apedata != APE_SEG_SIG_MAGIC) - return; + return false; apedata = tg3_ape_read32(tp, TG3_APE_FW_STATUS); if (!(apedata & APE_FW_STATUS_READY)) - return; + return false; if (tg3_ape_read32(tp, TG3_APE_FW_FEATURES) & TG3_APE_FW_FEATURE_NCSI) tg3_flag_set(tp, APE_HAS_NCSI); + + return true; } static void tg3_read_dash_ver(struct tg3 *tp) @@ -16082,8 +16100,7 @@ static void tg3_read_fw_ver(struct tg3 *tp) if (tg3_flag(tp, ENABLE_ASF)) { if (tg3_flag(tp, ENABLE_APE)) { - tg3_probe_ncsi(tp); - if (!vpd_vers) + if (tg3_probe_ncsi(tp) && !vpd_vers) tg3_read_dash_ver(tp); } else if (!vpd_vers) { tg3_read_mgmtfw_ver(tp); @@ -17756,6 +17773,7 @@ static int tg3_init_one(struct pci_dev *pdev, u64 dma_mask, persist_dma_mask; netdev_features_t features = 0; u8 addr[ETH_ALEN] __aligned(2); + u64 test_dma_mask = 0; err = pci_enable_device(pdev); if (err) { @@ -17895,15 +17913,22 @@ static int tg3_init_one(struct pci_dev *pdev, persist_dma_mask = dma_mask = DMA_BIT_MASK(64); if (tg3_asic_rev(tp) == ASIC_REV_57766) - persist_dma_mask = DMA_BIT_MASK(31); + test_dma_mask = DMA_BIT_MASK(31); /* Configure DMA attributes. */ if (dma_mask > DMA_BIT_MASK(32)) { err = dma_set_mask(&pdev->dev, dma_mask); if (!err) { features |= NETIF_F_HIGHDMA; - err = dma_set_coherent_mask(&pdev->dev, - persist_dma_mask); + if (!test_dma_mask || + dma_set_coherent_mask(&pdev->dev, + test_dma_mask)) { + if (test_dma_mask) + dev_warn(&pdev->dev, + "Unable to set 31 bit coherent DMA mask, workaround not applied\n"); + err = dma_set_coherent_mask(&pdev->dev, + persist_dma_mask); + } if (err < 0) { dev_err(&pdev->dev, "Unable to obtain 64 bit " "DMA for consistent allocations\n"); diff --git a/drivers/net/ethernet/chelsio/cxgb4/cxgb4_ethtool.c b/drivers/net/ethernet/chelsio/cxgb4/cxgb4_ethtool.c index 0092bc16f88709..c72c0bcd45c80a 100644 --- a/drivers/net/ethernet/chelsio/cxgb4/cxgb4_ethtool.c +++ b/drivers/net/ethernet/chelsio/cxgb4/cxgb4_ethtool.c @@ -2269,7 +2269,9 @@ int cxgb4_init_ethtool_filters(struct adapter *adap) eth_filter->nentries = nentries; for (i = 0; i < adap->params.nports; i++) { - eth_filter->port[i].loc_array = kvzalloc(nentries, GFP_KERNEL); + eth_filter->port[i].loc_array = + kvcalloc(nentries, sizeof(*eth_filter->port[i].loc_array), + GFP_KERNEL); if (!eth_filter->port[i].loc_array) { ret = -ENOMEM; goto free_eth_finfo; diff --git a/drivers/net/ethernet/freescale/dpaa2/dpaa2-eth.c b/drivers/net/ethernet/freescale/dpaa2/dpaa2-eth.c index 9003cff88024c4..bb3c55d84d89ea 100644 --- a/drivers/net/ethernet/freescale/dpaa2/dpaa2-eth.c +++ b/drivers/net/ethernet/freescale/dpaa2/dpaa2-eth.c @@ -1681,11 +1681,9 @@ static int dpaa2_eth_add_bufs(struct dpaa2_eth_priv *priv, struct device *dev = priv->net_dev->dev.parent; u64 buf_array[DPAA2_ETH_BUFS_PER_CMD]; struct dpaa2_eth_swa *swa; - struct page *page; dma_addr_t addr; int retries = 0; int i = 0, err; - u32 batch; /* Allocate buffers visible to WRIOP */ if (!ch->xsk_zc) { @@ -1695,14 +1693,16 @@ static int dpaa2_eth_add_bufs(struct dpaa2_eth_priv *priv, * the entire page except for a tailroom reserved for * skb shared info */ - page = dev_alloc_pages(0); + struct page *page = dev_alloc_pages(0); if (!page) goto err_alloc; addr = dma_map_page(dev, page, 0, priv->rx_buf_size, DMA_BIDIRECTIONAL); - if (unlikely(dma_mapping_error(dev, addr))) - goto err_map; + if (unlikely(dma_mapping_error(dev, addr))) { + __free_pages(page, 0); + goto err_alloc; + } buf_array[i] = addr; @@ -1718,8 +1718,8 @@ static int dpaa2_eth_add_bufs(struct dpaa2_eth_priv *priv, * of DPAA2_ETH_BUFS_PER_CMD. Bail out if the UMEM cannot * provide enough buffers at the moment */ - batch = xsk_buff_alloc_batch(ch->xsk_pool, xdp_buffs, - DPAA2_ETH_BUFS_PER_CMD); + u32 batch = xsk_buff_alloc_batch(ch->xsk_pool, xdp_buffs, + DPAA2_ETH_BUFS_PER_CMD); if (!batch) goto err_alloc; @@ -1729,8 +1729,11 @@ static int dpaa2_eth_add_bufs(struct dpaa2_eth_priv *priv, swa->xsk.xdp_buff = xdp_buffs[i]; addr = xsk_buff_xdp_get_frame_dma(xdp_buffs[i]); - if (unlikely(dma_mapping_error(dev, addr))) - goto err_map; + if (unlikely(dma_mapping_error(dev, addr))) { + for (int j = i; j < batch; j++) + xsk_buff_free(xdp_buffs[j]); + goto err_alloc; + } buf_array[i] = addr; @@ -1761,13 +1764,6 @@ static int dpaa2_eth_add_bufs(struct dpaa2_eth_priv *priv, return i; -err_map: - if (!ch->xsk_zc) { - __free_pages(page, 0); - } else { - for (; i < batch; i++) - xsk_buff_free(xdp_buffs[i]); - } err_alloc: /* If we managed to allocate at least some buffers, * release them to hardware diff --git a/drivers/net/ethernet/freescale/gianfar.c b/drivers/net/ethernet/freescale/gianfar.c index cf636fc5aafac2..19010e08fc55fe 100644 --- a/drivers/net/ethernet/freescale/gianfar.c +++ b/drivers/net/ethernet/freescale/gianfar.c @@ -1092,6 +1092,7 @@ static void free_skb_rx_queue(struct gfar_priv_rx_q *rx_queue) struct rxbd8 *rxbdp = rx_queue->rx_bd_base; dev_kfree_skb(rx_queue->skb); + rx_queue->skb = NULL; for (i = 0; i < rx_queue->rx_ring_size; i++) { struct gfar_rx_buff *rxb = &rx_queue->rx_buff[i]; diff --git a/drivers/net/ethernet/google/gve/gve.h b/drivers/net/ethernet/google/gve/gve.h index e509488a3d3e1a..143d8cd595aa27 100644 --- a/drivers/net/ethernet/google/gve/gve.h +++ b/drivers/net/ethernet/google/gve/gve.h @@ -119,7 +119,7 @@ struct gve_rx_slot_page_info { void *page_address; u32 page_offset; /* offset to write to in page */ unsigned int buf_size; - int pagecnt_bias; /* expected pagecnt if only the driver has a ref */ + u16 pagecnt_bias; /* expected pagecnt if only the driver has a ref */ u16 pad; /* adjustment for rx padding */ u8 can_flip; /* tracks if the networking stack is using the page */ }; diff --git a/drivers/net/ethernet/google/gve/gve_buffer_mgmt_dqo.c b/drivers/net/ethernet/google/gve/gve_buffer_mgmt_dqo.c index 6880d1531ba5ef..52223baf03036d 100644 --- a/drivers/net/ethernet/google/gve/gve_buffer_mgmt_dqo.c +++ b/drivers/net/ethernet/google/gve/gve_buffer_mgmt_dqo.c @@ -149,8 +149,8 @@ int gve_alloc_qpl_page_dqo(struct gve_rx_ring *rx, buf_state->last_single_ref_offset = 0; /* The page already has 1 ref. */ - page_ref_add(buf_state->page_info.page, INT_MAX - 1); - buf_state->page_info.pagecnt_bias = INT_MAX; + page_ref_add(buf_state->page_info.page, USHRT_MAX - 1); + buf_state->page_info.pagecnt_bias = USHRT_MAX; return 0; } diff --git a/drivers/net/ethernet/google/gve/gve_main.c b/drivers/net/ethernet/google/gve/gve_main.c index 0ee69bc11d8366..35cf0f06a0f27b 100644 --- a/drivers/net/ethernet/google/gve/gve_main.c +++ b/drivers/net/ethernet/google/gve/gve_main.c @@ -1798,6 +1798,12 @@ static int gve_verify_xdp_configuration(struct net_device *dev, struct gve_priv *priv = netdev_priv(dev); u16 max_xdp_mtu; + if (!(dev->xdp_features & NETDEV_XDP_ACT_BASIC)) { + NL_SET_ERR_MSG_MOD(extack, + "XDP is not supported on this queue format."); + return -EOPNOTSUPP; + } + if (dev->features & NETIF_F_GRO_HW) { NL_SET_ERR_MSG_MOD(extack, "XDP is not supported when HW-GRO is on."); diff --git a/drivers/net/ethernet/google/gve/gve_rx.c b/drivers/net/ethernet/google/gve/gve_rx.c index 81ea800e66e941..3bed1986637666 100644 --- a/drivers/net/ethernet/google/gve/gve_rx.c +++ b/drivers/net/ethernet/google/gve/gve_rx.c @@ -152,8 +152,8 @@ static void gve_setup_rx_buffer(struct gve_rx_ring *rx, page_info->buf_size = rx->packet_buffer_size; *slot_addr = cpu_to_be64(addr); /* The page already has 1 ref */ - page_ref_add(page, INT_MAX - 1); - page_info->pagecnt_bias = INT_MAX; + page_ref_add(page, USHRT_MAX - 1); + page_info->pagecnt_bias = USHRT_MAX; } static int gve_rx_alloc_buffer(struct gve_priv *priv, struct device *dev, @@ -230,8 +230,8 @@ static int gve_rx_prefill_pages(struct gve_rx_ring *rx, rx->qpl_copy_pool[j].buf_size = rx->packet_buffer_size; /* The page already has 1 ref. */ - page_ref_add(page, INT_MAX - 1); - rx->qpl_copy_pool[j].pagecnt_bias = INT_MAX; + page_ref_add(page, USHRT_MAX - 1); + rx->qpl_copy_pool[j].pagecnt_bias = USHRT_MAX; } } diff --git a/drivers/net/ethernet/google/gve/gve_rx_dqo.c b/drivers/net/ethernet/google/gve/gve_rx_dqo.c index 82ed5e48b00abd..b4dbfb1ba39b01 100644 --- a/drivers/net/ethernet/google/gve/gve_rx_dqo.c +++ b/drivers/net/ethernet/google/gve/gve_rx_dqo.c @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -1000,13 +1001,34 @@ static int gve_rx_dqo(struct napi_struct *napi, struct gve_rx_ring *rx, return -ENOMEM; } +/* Prepare a HW-GRO packet the way tcp4/6_gro_complete() prepare a SW-GRO + * packet, so that it can be resegmented by GSO or TSO if it is forwarded: + * seed th->check with the TCP pseudo-header checksum and set CHECKSUM_PARTIAL. + */ +static void gve_rx_fixup_gro_checksum(struct sk_buff *skb) +{ + int len = skb->len - skb_transport_offset(skb); + struct tcphdr *th = tcp_hdr(skb); + + if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) + th->check = ~tcp_v4_check(len, ip_hdr(skb)->saddr, + ip_hdr(skb)->daddr, 0); + else + th->check = ~tcp_v6_check(len, &ipv6_hdr(skb)->saddr, + &ipv6_hdr(skb)->daddr, 0); + + NAPI_GRO_CB(skb)->count = skb_shinfo(skb)->gso_segs; + tcp_gro_complete(skb); +} + static int gve_rx_complete_rsc(struct sk_buff *skb, const struct gve_rx_compl_desc_dqo *desc, struct gve_ptype ptype) { struct skb_shared_info *shinfo = skb_shinfo(skb); - int rsc_segments, rsc_seg_len, hdr_len; + int rsc_seg_len, hdr_len, nhoff, thoff, gso_type, payload; skb_frag_t *frag; + __be16 proto; void *va; /* HW-GRO only coalesces TCP. */ @@ -1017,20 +1039,11 @@ static int gve_rx_complete_rsc(struct sk_buff *skb, if (!rsc_seg_len) return 0; - switch (ptype.l3_type) { - case GVE_L3_TYPE_IPV4: - shinfo->gso_type = SKB_GSO_TCPV4; - break; - case GVE_L3_TYPE_IPV6: - shinfo->gso_type = SKB_GSO_TCPV6; - break; - default: - return -EINVAL; - } - if (skb_headlen(skb)) { - /* With header-split, payload is in the non-linear part */ - rsc_segments = DIV_ROUND_UP(skb->data_len, rsc_seg_len); + /* With header-split or copybreak, eth_type_trans() has already + * pulled the Ethernet header. + */ + nhoff = 0; } else { /* HW-GRO packets are guaranteed to have complete TCP/IP * headers in frag[0] when header-split is not enabled. @@ -1039,7 +1052,6 @@ static int gve_rx_complete_rsc(struct sk_buff *skb, va = skb_frag_address(frag); hdr_len = eth_get_headlen(skb->dev, va, skb_frag_size(frag)); - rsc_segments = DIV_ROUND_UP(skb->len - hdr_len, rsc_seg_len); skb_copy_to_linear_data(skb, va, hdr_len); skb_frag_size_sub(frag, hdr_len); /* Verify we didn't empty the fragment completely as that could @@ -1049,10 +1061,50 @@ static int gve_rx_complete_rsc(struct sk_buff *skb, skb_frag_off_add(frag, hdr_len); skb->data_len -= hdr_len; skb->tail += hdr_len; + /* napi_gro_frags() pulls the Ethernet header later. */ + nhoff = ETH_HLEN; + } + + /* The header lengths come from the packet, so make sure the headers are + * in the linear part before reading them and writing th->check. + */ + if (unlikely(skb_headlen(skb) < nhoff + sizeof(struct iphdr))) + return -EINVAL; + + skb_set_network_header(skb, nhoff); + proto = nhoff ? ((struct ethhdr *)skb->data)->h_proto : skb->protocol; + switch (proto) { + case htons(ETH_P_IP): + gso_type = SKB_GSO_TCPV4; + thoff = nhoff + ip_hdrlen(skb); + break; + case htons(ETH_P_IPV6): + gso_type = SKB_GSO_TCPV6; + thoff = nhoff + sizeof(struct ipv6hdr); + break; + default: + return -EINVAL; } + if (unlikely(skb_headlen(skb) < thoff + sizeof(struct tcphdr))) + return -EINVAL; + skb_set_transport_header(skb, thoff); + if (unlikely(skb->len < thoff + tcp_hdrlen(skb))) + return -EINVAL; + + /* With at most one segment of payload, this is not a GSO packet. */ + payload = skb->len - thoff - tcp_hdrlen(skb); + if (payload <= rsc_seg_len) + return 0; + + shinfo->gso_type = gso_type; shinfo->gso_size = rsc_seg_len; - shinfo->gso_segs = rsc_segments; + shinfo->gso_segs = DIV_ROUND_UP(payload, rsc_seg_len); + + if (!IS_ENABLED(CONFIG_INET) || + unlikely(skb->ip_summed != CHECKSUM_UNNECESSARY)) + return 0; + gve_rx_fixup_gro_checksum(skb); return 0; } diff --git a/drivers/net/ethernet/google/gve/gve_utils.c b/drivers/net/ethernet/google/gve/gve_utils.c index caed38cd5f2b3b..930555ac8fe912 100644 --- a/drivers/net/ethernet/google/gve/gve_utils.c +++ b/drivers/net/ethernet/google/gve/gve_utils.c @@ -93,15 +93,11 @@ void gve_dec_pagecnt_bias(struct gve_rx_slot_page_info *page_info) { page_info->pagecnt_bias--; if (page_info->pagecnt_bias == 0) { - int pagecount = page_count(page_info->page); - - /* If we have run out of bias - set it back up to INT_MAX - * minus the existing refs. + /* Out of bias: take another batch. USHRT_MAX keeps this rare + * while leaving page_count() far below INT_MAX. */ - page_info->pagecnt_bias = INT_MAX - pagecount; - - /* Set pagecount back up to max. */ - page_ref_add(page_info->page, INT_MAX - pagecount); + page_info->pagecnt_bias = USHRT_MAX; + page_ref_add(page_info->page, USHRT_MAX); } } diff --git a/drivers/net/ethernet/google/gve/gve_utils.h b/drivers/net/ethernet/google/gve/gve_utils.h index bf2e9a0adb36ee..c686142d37eaf5 100644 --- a/drivers/net/ethernet/google/gve/gve_utils.h +++ b/drivers/net/ethernet/google/gve/gve_utils.h @@ -25,7 +25,7 @@ struct sk_buff *gve_rx_copy_data(struct net_device *dev, struct napi_struct *nap struct sk_buff *gve_rx_copy(struct net_device *dev, struct napi_struct *napi, struct gve_rx_slot_page_info *page_info, u16 len); -/* Decrement pagecnt_bias. Set it back to INT_MAX if it reached zero. */ +/* Decrement pagecnt_bias. Top it up by USHRT_MAX if it reached zero. */ void gve_dec_pagecnt_bias(struct gve_rx_slot_page_info *page_info); void gve_add_napi(struct gve_priv *priv, int ntfy_idx, diff --git a/drivers/net/ethernet/intel/e1000/e1000_main.c b/drivers/net/ethernet/intel/e1000/e1000_main.c index d7f5c6f1614206..d7e279b739b8d4 100644 --- a/drivers/net/ethernet/intel/e1000/e1000_main.c +++ b/drivers/net/ethernet/intel/e1000/e1000_main.c @@ -1227,7 +1227,8 @@ static int e1000_probe(struct pci_dev *pdev, const struct pci_device_id *ent) kfree(adapter->rx_ring); err_dma: err_sw_init: - iounmap(hw->ce4100_gbe_mdio_base_virt); + if (hw->ce4100_gbe_mdio_base_virt) + iounmap(hw->ce4100_gbe_mdio_base_virt); iounmap(hw->hw_addr); err_ioremap: disable_dev = !test_and_set_bit(__E1000_DISABLED, &adapter->flags); diff --git a/drivers/net/ethernet/intel/i40e/i40e_ethtool.c b/drivers/net/ethernet/intel/i40e/i40e_ethtool.c index 6a992df06fa11b..58d842d6764223 100644 --- a/drivers/net/ethernet/intel/i40e/i40e_ethtool.c +++ b/drivers/net/ethernet/intel/i40e/i40e_ethtool.c @@ -2143,6 +2143,8 @@ static int i40e_set_ringparam(struct net_device *netdev, i--; if (!i40e_active_tx_ring_index(vsi, i)) continue; + /* not live yet, skip its BQL reset on free */ + tx_rings[i].netdev = NULL; i40e_free_tx_resources(&tx_rings[i]); } kfree(tx_rings); @@ -2248,8 +2250,11 @@ static int i40e_set_ringparam(struct net_device *netdev, /* error cleanup if the Rx allocations failed after getting Tx */ if (tx_rings) { for (i = 0; i < tx_alloc_queue_pairs; i++) { - if (i40e_active_tx_ring_index(vsi, i)) - i40e_free_tx_resources(vsi->tx_rings[i]); + if (i40e_active_tx_ring_index(vsi, i)) { + /* not live yet, skip its BQL reset on free */ + tx_rings[i].netdev = NULL; + i40e_free_tx_resources(&tx_rings[i]); + } } kfree(tx_rings); tx_rings = NULL; diff --git a/drivers/net/ethernet/intel/iavf/iavf_adminq.c b/drivers/net/ethernet/intel/iavf/iavf_adminq.c index 6937b7dd44cbb6..40f76f9507f4bb 100644 --- a/drivers/net/ethernet/intel/iavf/iavf_adminq.c +++ b/drivers/net/ethernet/intel/iavf/iavf_adminq.c @@ -60,6 +60,7 @@ static enum iavf_status iavf_alloc_adminq_arq_ring(struct iavf_hw *hw) **/ static void iavf_free_adminq_asq(struct iavf_hw *hw) { + iavf_free_virt_mem(hw, &hw->aq.asq.cmd_buf); iavf_free_dma_mem(hw, &hw->aq.asq.desc_buf); } diff --git a/drivers/net/ethernet/intel/iavf/iavf_main.c b/drivers/net/ethernet/intel/iavf/iavf_main.c index 2f8a80a1133626..4de3ea8525b3fa 100644 --- a/drivers/net/ethernet/intel/iavf/iavf_main.c +++ b/drivers/net/ethernet/intel/iavf/iavf_main.c @@ -5638,6 +5638,7 @@ static void iavf_remove(struct pci_dev *pdev) iounmap(hw->hw_addr); pci_release_regions(pdev); kfree(adapter->vf_res); + kfree(adapter->qos_caps); spin_lock_bh(&adapter->mac_vlan_list_lock); /* If we got removed before an up/down sequence, we've got a filter * hanging out there that we need to get rid of. diff --git a/drivers/net/ethernet/intel/iavf/iavf_ptp.c b/drivers/net/ethernet/intel/iavf/iavf_ptp.c index 87b97e09df14a9..fcb273828bc1b6 100644 --- a/drivers/net/ethernet/intel/iavf/iavf_ptp.c +++ b/drivers/net/ethernet/intel/iavf/iavf_ptp.c @@ -252,6 +252,16 @@ static int iavf_ptp_gettimex64(struct ptp_clock_info *info, return iavf_read_phc_indirect(adapter, ts, sts); } +static int iavf_ptp_adjfine(struct ptp_clock_info *info, long scaled_ppm) +{ + return -EOPNOTSUPP; +} + +static int iavf_ptp_adjtime(struct ptp_clock_info *info, s64 delta) +{ + return -EOPNOTSUPP; +} + static int iavf_ptp_settime64(struct ptp_clock_info *info, const struct timespec64 *ts) { @@ -326,6 +336,8 @@ static int iavf_ptp_register_clock(struct iavf_adapter *adapter) KBUILD_MODNAME, dev_name(dev)); ptp_info->owner = THIS_MODULE; ptp_info->gettimex64 = iavf_ptp_gettimex64; + ptp_info->adjfine = iavf_ptp_adjfine; + ptp_info->adjtime = iavf_ptp_adjtime; ptp_info->settime64 = iavf_ptp_settime64; ptp_info->do_aux_work = iavf_ptp_do_aux_work; diff --git a/drivers/net/ethernet/intel/ice/devlink/devlink.c b/drivers/net/ethernet/intel/ice/devlink/devlink.c index a87a3e0a900c32..9eafe7d5773263 100644 --- a/drivers/net/ethernet/intel/ice/devlink/devlink.c +++ b/drivers/net/ethernet/intel/ice/devlink/devlink.c @@ -1953,7 +1953,7 @@ static int ice_devlink_nvm_read(struct devlink *devlink, return -EOPNOTSUPP; } - if (offset + size >= nvm_size) { + if (offset + size > nvm_size) { NL_SET_ERR_MSG_MOD(extack, "Cannot read beyond the region size"); return -ERANGE; } diff --git a/drivers/net/ethernet/intel/ice/ice_tc_lib.c b/drivers/net/ethernet/intel/ice/ice_tc_lib.c index d20357c0412731..6f49ecb4165b24 100644 --- a/drivers/net/ethernet/intel/ice/ice_tc_lib.c +++ b/drivers/net/ethernet/intel/ice/ice_tc_lib.c @@ -1202,7 +1202,8 @@ ice_add_tc_flower_adv_fltr(struct ice_vsi *vsi, break; case ICE_FWD_TO_Q: /* HW queue number in global space */ - rule_info.sw_act.fwd_id.q_id = tc_fltr->action.fwd.q.hw_queue; + rule_info.sw_act.fwd_id.q_id = tc_fltr->action.fwd.q.hw_queue + + hw->func_caps.common_cap.rxq_first_id; rule_info.sw_act.vsi_handle = dest_vsi->idx; rule_info.priority = ICE_SWITCH_FLTR_PRIO_QUEUE; rule_info.sw_act.src = hw->pf_id; diff --git a/drivers/net/ethernet/marvell/prestera/prestera_main.c b/drivers/net/ethernet/marvell/prestera/prestera_main.c index a82e7a80298513..3173145573600d 100644 --- a/drivers/net/ethernet/marvell/prestera/prestera_main.c +++ b/drivers/net/ethernet/marvell/prestera/prestera_main.c @@ -307,13 +307,14 @@ static int prestera_pcs_config(struct phylink_pcs *pcs, unsigned int neg_mode, bool permit_pause_to_mac) { struct prestera_port *port = prestera_pcs_to_port(pcs); - struct prestera_port_mac_config cfg_mac; + struct prestera_port_mac_config cfg_mac, old; int err; err = prestera_port_cfg_mac_read(port, &cfg_mac); if (err) return err; + old = cfg_mac; cfg_mac.admin = true; cfg_mac.fec = PRESTERA_PORT_FEC_OFF; cfg_mac.inband = neg_mode == PHYLINK_PCS_NEG_INBAND_ENABLED; @@ -329,6 +330,7 @@ static int prestera_pcs_config(struct phylink_pcs *pcs, unsigned int neg_mode, cfg_mac.mode = PRESTERA_MAC_MODE_SGMII; break; case PHY_INTERFACE_MODE_SGMII: + cfg_mac.speed = SPEED_1000; cfg_mac.mode = PRESTERA_MAC_MODE_SGMII; break; case PHY_INTERFACE_MODE_1000BASEX: @@ -339,6 +341,19 @@ static int prestera_pcs_config(struct phylink_pcs *pcs, unsigned int neg_mode, break; } + /* Firmware may not report link up after the mode, speed or inband + * setting of an enabled port changes until the port is disabled and + * re-enabled. + */ + if (old.admin && (old.mode != cfg_mac.mode || + old.speed != cfg_mac.speed || + old.inband != cfg_mac.inband)) { + old.admin = false; + err = prestera_port_cfg_mac_write(port, &old); + if (err) + return err; + } + err = prestera_port_cfg_mac_write(port, &cfg_mac); if (err) return err; diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en/tc_tun_encap.c b/drivers/net/ethernet/mellanox/mlx5/core/en/tc_tun_encap.c index 5e40107efa266a..4f9f8beffbc8db 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en/tc_tun_encap.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en/tc_tun_encap.c @@ -1718,9 +1718,9 @@ static void mlx5e_tc_fib_event_work(struct work_struct *work) r->flags |= MLX5E_ROUTE_ENTRY_VALID; out: mutex_unlock(&esw->offloads.encap_tbl_lock); + mlx5e_put_flow_list(priv, &flow_list); rtnl_unlock(); - mlx5e_put_flow_list(priv, &flow_list); mlx5e_route_put(priv, event_data->r); dev_put(event_data->ul_dev); kfree(event_data); 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 5a340f1435e6be..554c225f73767f 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 @@ -219,9 +219,10 @@ static inline void mlx5e_accel_tx_finish(struct mlx5e_txqsq *sq, } static inline bool -mlx5e_accel_shampo_can_merge(struct mlx5e_rq *rq, struct mlx5_cqe64 *cqe) +mlx5e_accel_shampo_can_merge(struct sk_buff *skb, struct mlx5_cqe64 *cqe) { - return mlx5e_psp_shampo_can_merge(rq->hw_gro_data->skb, cqe); + return mlx5e_psp_shampo_can_merge(skb, cqe) && + mlx5e_ktls_shampo_can_merge(skb, cqe); } static inline int mlx5e_accel_init_rx(struct mlx5e_priv *priv) diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ktls_txrx.h b/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ktls_txrx.h index 93bd383a23d8c2..20e5dc6a718e10 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ktls_txrx.h +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ktls_txrx.h @@ -60,6 +60,21 @@ mlx5e_ktls_handle_tx_wqe(struct mlx5_wqe_ctrl_seg *cseg, { cseg->tis_tir_num = cpu_to_be32(state->tls_tisn << 8); } + +/* The first CQE of a HW-GRO session sets skb->decrypted. A resync request or + * a TLS error is handled on the first CQE only, so it starts a new session. + */ +static inline bool +mlx5e_ktls_shampo_can_merge(struct sk_buff *skb, struct mlx5_cqe64 *cqe) +{ + u8 tls_offload = get_cqe_tls_offload(cqe); + + if (unlikely(tls_offload > CQE_TLS_OFFLOAD_DECRYPTED)) + return false; + + return (tls_offload == CQE_TLS_OFFLOAD_DECRYPTED) == + skb_is_decrypted(skb); +} #else static inline bool mlx5e_ktls_tx_try_handle_resync_dump_comp(struct mlx5e_txqsq *sq, @@ -93,6 +108,12 @@ static inline void mlx5e_ktls_handle_rx_skb(struct mlx5e_rq *rq, u32 *cqe_bcnt) { } + +static inline bool +mlx5e_ktls_shampo_can_merge(struct sk_buff *skb, struct mlx5_cqe64 *cqe) +{ + return true; +} #endif /* CONFIG_MLX5_EN_TLS */ #endif /* __MLX5E_TLS_TXRX_H__ */ diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_main.c b/drivers/net/ethernet/mellanox/mlx5/core/en_main.c index d8563f86384473..227695dfa51dfa 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_main.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_main.c @@ -3421,6 +3421,23 @@ static int mlx5e_switch_priv_params(struct mlx5e_priv *priv, return 0; } +/* The old and the new channel of the same index are bound to the same + * XSK pool, which is lockless and expects a single user at a time. + * Close the old XSK queues before the new ones are activated, even + * when the closure of the rest of the old channels is deferred. + */ +static void mlx5e_close_channels_xsk(struct mlx5e_channels *chs) +{ + int i; + + for (i = 0; i < chs->num; i++) { + struct mlx5e_channel *c = chs->c[i]; + + if (test_bit(MLX5E_CHANNEL_STATE_XSK, c->state)) + mlx5e_close_xsk(c); + } +} + static int mlx5e_switch_priv_channels(struct mlx5e_priv *priv, struct mlx5e_channels *old_chs, struct mlx5e_channels *new_chs, @@ -3452,6 +3469,8 @@ static int mlx5e_switch_priv_channels(struct mlx5e_priv *priv, mlx5e_set_xdp_feature(priv); if (!MLX5_CAP_GEN(priv->mdev, tis_tir_td_order)) mlx5e_close_channels(old_chs); + else + mlx5e_close_channels_xsk(old_chs); priv->profile->update_rx(priv); mlx5e_selq_apply(&priv->selq); diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_rep.c b/drivers/net/ethernet/mellanox/mlx5/core/en_rep.c index c7b4a8a827738b..ca5da48626f64d 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_rep.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_rep.c @@ -506,10 +506,11 @@ static int mlx5e_sqs2vport_start(struct mlx5_eswitch *esw, struct mlx5_eswitch_rep *rep, u32 *sqns_array, int sqns_num) { + struct mlx5_devcom_comp_dev *devcom = esw->devcom; struct mlx5_flow_handle *flow_rule; struct mlx5e_rep_priv *rpriv; struct mlx5e_rep_sq *rep_sq; - bool devcom_locked = false; + bool peers_ready; int err; int i; @@ -518,9 +519,8 @@ static int mlx5e_sqs2vport_start(struct mlx5_eswitch *esw, rpriv = mlx5e_rep_to_rep_priv(rep); - if (mlx5_devcom_comp_is_ready(esw->devcom) && - mlx5_devcom_for_each_peer_begin(esw->devcom)) - devcom_locked = true; + mlx5_devcom_comp_read_lock(devcom); + peers_ready = mlx5_devcom_comp_is_ready(devcom); for (i = 0; i < sqns_num; i++) { rep_sq = kzalloc_obj(*rep_sq); @@ -541,7 +541,7 @@ static int mlx5e_sqs2vport_start(struct mlx5_eswitch *esw, rep_sq->sqn = sqns_array[i]; xa_init(&rep_sq->sq_peer); - if (devcom_locked) { + if (peers_ready) { err = mlx5e_sqs2vport_add_peers_rules(esw, rep, rep_sq, i); if (err) { mlx5_eswitch_del_send_to_vport_rule(rep_sq->send_to_vport_rule); @@ -554,16 +554,13 @@ static int mlx5e_sqs2vport_start(struct mlx5_eswitch *esw, list_add(&rep_sq->list, &rpriv->vport_sqs_list); } - if (devcom_locked) - mlx5_devcom_for_each_peer_end(esw->devcom); + mlx5_devcom_comp_read_unlock(devcom); return 0; out_err: mlx5e_sqs2vport_stop(esw, rep); - - if (devcom_locked) - mlx5_devcom_for_each_peer_end(esw->devcom); + mlx5_devcom_comp_read_unlock(devcom); return err; } @@ -630,8 +627,12 @@ mlx5e_remove_sqs_fwd_rules(struct mlx5e_priv *priv) struct mlx5_eswitch *esw = priv->mdev->priv.eswitch; struct mlx5e_rep_priv *rpriv = priv->ppriv; struct mlx5_eswitch_rep *rep = rpriv->rep; + struct mlx5_devcom_comp_dev *devcom; + devcom = esw->devcom; + mlx5_devcom_comp_read_lock(devcom); mlx5e_sqs2vport_stop(esw, rep); + mlx5_devcom_comp_read_unlock(devcom); } static int diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_rx.c b/drivers/net/ethernet/mellanox/mlx5/core/en_rx.c index 22fea4739a2c97..1586cb2404c01d 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_rx.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_rx.c @@ -2271,7 +2271,7 @@ 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) && - mlx5e_accel_shampo_can_merge(rq, cqe))) { + mlx5e_accel_shampo_can_merge(*skb, cqe))) { match = false; mlx5e_shampo_flush_skb(rq, cqe, match); } diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_tc.c b/drivers/net/ethernet/mellanox/mlx5/core/en_tc.c index 1d35c97aea0bc3..011741553f5b94 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_tc.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_tc.c @@ -4631,6 +4631,10 @@ static int mlx5e_tc_add_fdb_peer_flow(struct flow_cls_offload *f, else in_mdev = priv->mdev; + dup_peer_flows = xa_load(&esw->offloads.peer_flows, peer_vhca_id); + if (!dup_peer_flows) + return -ENODEV; + flow_flags |= BIT(MLX5E_TC_FLOW_FLAG_PEER); parse_attr = flow->attr->parse_attr; peer_flow = __mlx5e_add_fdb_flow(peer_priv, f, flow_flags, @@ -4644,9 +4648,6 @@ static int mlx5e_tc_add_fdb_peer_flow(struct flow_cls_offload *f, peer_flow->peer_orig = flow; list_add_tail(&peer_flow->peer_flows, &flow->peer_flows); flow_flag_set(flow, DUP); - dup_peer_flows = xa_load(&esw->offloads.peer_flows, peer_vhca_id); - if (!dup_peer_flows) - return -ENODEV; mutex_lock(&esw->offloads.peer_mutex); list_add_tail(&peer_flow->peer, dup_peer_flows); mutex_unlock(&esw->offloads.peer_mutex); diff --git a/drivers/net/ethernet/mellanox/mlx5/core/eswitch.c b/drivers/net/ethernet/mellanox/mlx5/core/eswitch.c index 76f808e06a88bf..174197f6988876 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/eswitch.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/eswitch.c @@ -758,7 +758,8 @@ static void esw_vport_change_handler(struct work_struct *work) struct mlx5_eswitch *esw = vport->dev->priv.eswitch; mutex_lock(&esw->state_lock); - esw_vport_change_handle_locked(vport); + if (vport->enabled) + esw_vport_change_handle_locked(vport); mutex_unlock(&esw->state_lock); } diff --git a/drivers/net/ethernet/mellanox/mlx5/core/lib/devcom.c b/drivers/net/ethernet/mellanox/mlx5/core/lib/devcom.c index 75855481522b11..aed9e2a74162fa 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/lib/devcom.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/lib/devcom.c @@ -456,6 +456,20 @@ void mlx5_devcom_comp_unlock(struct mlx5_devcom_comp_dev *devcom) up_write(&devcom->comp->sem); } +void mlx5_devcom_comp_read_lock(struct mlx5_devcom_comp_dev *devcom) +{ + if (!devcom) + return; + down_read(&devcom->comp->sem); +} + +void mlx5_devcom_comp_read_unlock(struct mlx5_devcom_comp_dev *devcom) +{ + if (!devcom) + return; + up_read(&devcom->comp->sem); +} + int mlx5_devcom_comp_trylock(struct mlx5_devcom_comp_dev *devcom) { if (!devcom) diff --git a/drivers/net/ethernet/mellanox/mlx5/core/lib/devcom.h b/drivers/net/ethernet/mellanox/mlx5/core/lib/devcom.h index 7a704fafdbd3a8..94b0fe20cc265f 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/lib/devcom.h +++ b/drivers/net/ethernet/mellanox/mlx5/core/lib/devcom.h @@ -79,6 +79,8 @@ void *mlx5_devcom_get_next_peer_data_rcu(struct mlx5_devcom_comp_dev *devcom, void mlx5_devcom_comp_lock(struct mlx5_devcom_comp_dev *devcom); void mlx5_devcom_comp_unlock(struct mlx5_devcom_comp_dev *devcom); +void mlx5_devcom_comp_read_lock(struct mlx5_devcom_comp_dev *devcom); +void mlx5_devcom_comp_read_unlock(struct mlx5_devcom_comp_dev *devcom); int mlx5_devcom_comp_trylock(struct mlx5_devcom_comp_dev *devcom); void mlx5_devcom_comp_assert_locked(struct mlx5_devcom_comp_dev *devcom); diff --git a/drivers/net/ethernet/mellanox/mlx5/core/lib/vxlan.c b/drivers/net/ethernet/mellanox/mlx5/core/lib/vxlan.c index c2292cab4592d3..b953bbc4925c55 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/lib/vxlan.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/lib/vxlan.c @@ -121,25 +121,29 @@ int mlx5_vxlan_add_port(struct mlx5_vxlan *vxlan, u16 port) return 0; } -int mlx5_vxlan_del_port(struct mlx5_vxlan *vxlan, u16 port) +static int __mlx5_vxlan_del_port(struct mlx5_vxlan *vxlan, u16 port) { struct mlx5_vxlan_port *vxlanp; - int ret = 0; - mutex_lock(&vxlan->sync_lock); + lockdep_assert_held(&vxlan->sync_lock); vxlanp = vxlan_lookup_port(vxlan, port); - if (WARN_ON(!vxlanp)) { - ret = -ENOENT; - goto out_unlock; - } + if (WARN_ON(!vxlanp)) + return -ENOENT; hash_del_rcu(&vxlanp->hlist); synchronize_rcu(); mlx5_vxlan_core_del_port_cmd(vxlan->mdev, port); kfree(vxlanp); + return 0; +} + +int mlx5_vxlan_del_port(struct mlx5_vxlan *vxlan, u16 port) +{ + int ret; -out_unlock: + mutex_lock(&vxlan->sync_lock); + ret = __mlx5_vxlan_del_port(vxlan, port); mutex_unlock(&vxlan->sync_lock); return ret; } @@ -185,12 +189,14 @@ void mlx5_vxlan_reset_to_default(struct mlx5_vxlan *vxlan) if (!mlx5_vxlan_allowed(vxlan)) return; + mutex_lock(&vxlan->sync_lock); hash_for_each_safe(vxlan->htable, bkt, tmp, vxlanp, hlist) { /* Don't delete default UDP port added by the HW. * Remove only user configured ports */ if (vxlanp->udp_port == IANA_VXLAN_UDP_PORT) continue; - mlx5_vxlan_del_port(vxlan, vxlanp->udp_port); + __mlx5_vxlan_del_port(vxlan, vxlanp->udp_port); } + mutex_unlock(&vxlan->sync_lock); } diff --git a/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws.c b/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws.c index cbcbc2b62809d7..de22e7279a312d 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 @@ -441,6 +441,8 @@ mlx5_fs_get_dest_action_vport(struct mlx5_fs_hws_context *fs_ctx, dest = mlx5hws_action_create_dest_vport(ctx, vport_num, vhca_id_valid, dest_attr->vport.vhca_id, flags); + if (!dest) + return NULL; err = xa_insert(dests_xa, idx, dest, GFP_KERNEL); if (err) { diff --git a/drivers/net/ethernet/mellanox/mlx5/core/steering/sws/dr_icm_pool.c b/drivers/net/ethernet/mellanox/mlx5/core/steering/sws/dr_icm_pool.c index 1b928b40686e5b..a906a72601c4fa 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/steering/sws/dr_icm_pool.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/steering/sws/dr_icm_pool.c @@ -33,6 +33,11 @@ struct mlx5dr_icm_pool { u64 hot_memory_size; /* hot memory size threshold for triggering sync */ u64 th; + /* Set when a sync to HW fails - no new chunks are served, freed + * chunks are no longer queued, and their ICM is not returned to + * the buddy allocator. + */ + bool error_state; }; struct mlx5dr_icm_dm { @@ -368,7 +373,15 @@ static int dr_icm_pool_sync_all_buddy_pools(struct mlx5dr_icm_pool *pool) err = mlx5dr_cmd_sync_steering(pool->dmn->mdev); if (err) { - mlx5dr_err(pool->dmn, "Failed to sync to HW (err: %d)\n", err); + /* The hot chunks could not be flushed. Put the pool in an + * error state so that no further chunks are queued (which + * would overflow hot_chunks_arr), and no new chunks are + * served. The sync is not retried. + */ + mlx5dr_err(pool->dmn, + "Failed to sync to HW (err: %d), disabling ICM pool\n", + err); + pool->error_state = true; return err; } @@ -443,6 +456,10 @@ mlx5dr_icm_alloc_chunk(struct mlx5dr_icm_pool *pool, return NULL; mutex_lock(&pool->mutex); + + if (pool->error_state) + goto out; + /* find mem, get back the relevant buddy pool and seg in that mem */ ret = dr_icm_handle_buddies_get_mem(pool, chunk_size, &buddy, &seg); if (ret) @@ -475,6 +492,14 @@ void mlx5dr_icm_free_chunk(struct mlx5dr_icm_chunk *chunk) /* move the chunk to the waiting chunks array, AKA "hot" memory */ mutex_lock(&pool->mutex); + /* If the pool is in an error state, the chunk must not be queued. + * ICM memory is not returned to the buddy allocator - it is + * reclaimed only when the pool is destroyed. + * Just free the chunk's bookkeeping struct. + */ + if (pool->error_state) + goto out; + pool->hot_memory_size += mlx5dr_icm_pool_get_chunk_byte_size(chunk); hot_chunk = &pool->hot_chunks_arr[pool->hot_chunks_num++]; @@ -482,12 +507,13 @@ void mlx5dr_icm_free_chunk(struct mlx5dr_icm_chunk *chunk) hot_chunk->seg = chunk->seg; hot_chunk->size = chunk->size; - kmem_cache_free(chunks_cache, chunk); - /* Check if we have chunks that are waiting for sync-ste */ if (dr_icm_pool_is_sync_required(pool)) dr_icm_pool_sync_all_buddy_pools(pool); +out: + kmem_cache_free(chunks_cache, chunk); + mutex_unlock(&pool->mutex); } diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_csr.h b/drivers/net/ethernet/meta/fbnic/fbnic_csr.h index c371ac9f78c182..dc234f4d24f663 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_csr.h +++ b/drivers/net/ethernet/meta/fbnic/fbnic_csr.h @@ -422,7 +422,8 @@ enum { #define FBNIC_TCE_TXB_NTWRK_DWRR_CTRL_EXT \ 0x0404E /* 0x10138 */ #define FBNIC_TCE_TXB_BMC_DWRR_CTRL_EXT 0x0404F /* 0x1013c */ -#define FBNIC_CSR_END_TCE 0x04050 /* CSR section delimiter */ +#define FBNIC_TCE_PTP_INFLIGHT 0x040A7 /* 0x1029c */ +#define FBNIC_CSR_END_TCE 0x040B4 /* CSR section delimiter */ /* TCE RAM registers */ #define FBNIC_CSR_START_TCE_RAM 0x04200 /* CSR section delimiter */ diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_debugfs.c b/drivers/net/ethernet/meta/fbnic/fbnic_debugfs.c index f9e879be254dac..65bea571c0cc1a 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_debugfs.c +++ b/drivers/net/ethernet/meta/fbnic/fbnic_debugfs.c @@ -3,7 +3,6 @@ #include #include -#include #include #include "fbnic.h" @@ -607,7 +606,6 @@ static int fbnic_dbg_pcie_stats_show(struct seq_file *s, void *v) { struct fbnic_dev *fbd = s->private; - rtnl_lock(); fbnic_get_hw_stats(fbd); seq_printf(s, "ob_rd_tlp: %llu\n", fbd->hw_stats.pcie.ob_rd_tlp.value); @@ -626,7 +624,6 @@ static int fbnic_dbg_pcie_stats_show(struct seq_file *s, void *v) fbd->hw_stats.pcie.ob_rd_no_cpl_cred.value); seq_printf(s, "ob_rd_no_np_cred: %llu\n", fbd->hw_stats.pcie.ob_rd_no_np_cred.value); - rtnl_unlock(); return 0; } diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_ethtool.c b/drivers/net/ethernet/meta/fbnic/fbnic_ethtool.c index e774740fcb5d81..9714a89977fa7a 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_ethtool.c +++ b/drivers/net/ethernet/meta/fbnic/fbnic_ethtool.c @@ -1740,6 +1740,9 @@ static void fbnic_get_ts_stats(struct net_device *netdev, ts_stats->lost = fbn->tx_stats.twq.ts_lost; for (i = 0; i < fbn->num_tx_queues; i++) { ring = fbn->tx[i]; + if (!ring) + continue; + do { start = u64_stats_fetch_begin(&ring->stats.syncp); ts_packets = ring->stats.twq.ts_packets; @@ -1867,12 +1870,14 @@ fbnic_get_pause_stats(struct net_device *netdev, mac_stats = &fbd->hw_stats.mac; + spin_lock(&fbd->hw_stats.lock); fbd->mac->get_pause_stats(fbd, false, &mac_stats->pause); pause_stats->tx_pause_frames = mac_stats->pause.tx_pause_frames.value; pause_stats->rx_pause_frames = mac_stats->pause.rx_pause_frames.value; tx_ps_events = mac_stats->pause.tx_pause_storm_events.value; pause_stats->tx_pause_storm_events = tx_ps_events; + spin_unlock(&fbd->hw_stats.lock); } static void @@ -1928,6 +1933,7 @@ fbnic_get_eth_mac_stats(struct net_device *netdev, mac_stats = &fbd->hw_stats.mac; mac = fbd->mac; + spin_lock(&fbd->hw_stats.lock); mac->get_eth_mac_stats(fbd, false, &mac_stats->eth_mac); fbnic_set_counter(ð_mac_stats->FramesTransmittedOK, @@ -1956,6 +1962,7 @@ fbnic_get_eth_mac_stats(struct net_device *netdev, &mac_stats->eth_mac.BroadcastFramesReceivedOK); fbnic_set_counter(ð_mac_stats->FrameTooLongErrors, &mac_stats->eth_mac.FrameTooLongErrors); + spin_unlock(&fbd->hw_stats.lock); } static void @@ -1968,12 +1975,14 @@ fbnic_get_eth_ctrl_stats(struct net_device *netdev, mac_stats = &fbd->hw_stats.mac; + spin_lock(&fbd->hw_stats.lock); fbd->mac->get_eth_ctrl_stats(fbd, false, &mac_stats->eth_ctrl); eth_ctrl_stats->MACControlFramesReceived = mac_stats->eth_ctrl.MACControlFramesReceived.value; eth_ctrl_stats->MACControlFramesTransmitted = mac_stats->eth_ctrl.MACControlFramesTransmitted.value; + spin_unlock(&fbd->hw_stats.lock); } static const struct ethtool_rmon_hist_range fbnic_rmon_ranges[] = { @@ -2003,6 +2012,7 @@ fbnic_get_rmon_stats(struct net_device *netdev, mac_stats = &fbd->hw_stats.mac; + spin_lock(&fbd->hw_stats.lock); fbd->mac->get_rmon_stats(fbd, false, &mac_stats->rmon); rmon_stats->undersize_pkts = @@ -2018,6 +2028,7 @@ fbnic_get_rmon_stats(struct net_device *netdev, rmon_stats->hist[i] = mac_stats->rmon.hist[i].value; rmon_stats->hist_tx[i] = mac_stats->rmon.hist_tx[i].value; } + spin_unlock(&fbd->hw_stats.lock); *ranges = fbnic_rmon_ranges; } diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_hw_stats.c b/drivers/net/ethernet/meta/fbnic/fbnic_hw_stats.c index 8b9b2076beecd4..076bfcac47d67c 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_hw_stats.c +++ b/drivers/net/ethernet/meta/fbnic/fbnic_hw_stats.c @@ -1,8 +1,6 @@ // SPDX-License-Identifier: GPL-2.0 /* Copyright (c) Meta Platforms, Inc. and affiliates. */ -#include - #include "fbnic.h" static void fbnic_hw_stat_rst32(struct fbnic_dev *fbd, u32 reg, @@ -541,9 +539,10 @@ static void fbnic_reset_hw_mac_stats(struct fbnic_dev *fbd, mac->get_rmon_stats(fbd, true, &mac_stats->rmon); } -void fbnic_reset_hw_stats(struct fbnic_dev *fbd) +void __fbnic_reset_hw_stats(struct fbnic_dev *fbd) { - spin_lock(&fbd->hw_stats.lock); + lockdep_assert_held(&fbd->hw_stats.lock); + fbnic_reset_phy_stats(fbd, &fbd->hw_stats.phy); fbnic_reset_tmi_stats(fbd, &fbd->hw_stats.tmi); fbnic_reset_tti_stats(fbd, &fbd->hw_stats.tti); @@ -551,19 +550,16 @@ void fbnic_reset_hw_stats(struct fbnic_dev *fbd) fbnic_reset_rxb_stats(fbd, &fbd->hw_stats.rxb); fbnic_reset_hw_rxq_stats(fbd, fbd->hw_stats.hw_q); fbnic_reset_pcie_stats_asic(fbd, &fbd->hw_stats.pcie); - spin_unlock(&fbd->hw_stats.lock); - - /* Once registered, the only other access to MAC stats is via the - * ethtool API which is protected by the rtnl_lock. The call to - * fbnic_reset_hw_stats() during PCI recovery is also protected - * by the rtnl_lock hence, we don't need the spinlock to access - * the MAC stats. - */ - if (fbd->netdev) - ASSERT_RTNL(); fbnic_reset_hw_mac_stats(fbd, &fbd->hw_stats.mac); } +void fbnic_reset_hw_stats(struct fbnic_dev *fbd) +{ + spin_lock(&fbd->hw_stats.lock); + __fbnic_reset_hw_stats(fbd); + spin_unlock(&fbd->hw_stats.lock); +} + void fbnic_init_hw_stats(struct fbnic_dev *fbd) { spin_lock_init(&fbd->hw_stats.lock); diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_hw_stats.h b/drivers/net/ethernet/meta/fbnic/fbnic_hw_stats.h index caea4be46762af..5eb1e8b29ef9d6 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_hw_stats.h +++ b/drivers/net/ethernet/meta/fbnic/fbnic_hw_stats.h @@ -154,6 +154,7 @@ struct fbnic_hw_stats { u64 fbnic_stat_rd64(struct fbnic_dev *fbd, u32 reg, u32 offset); +void __fbnic_reset_hw_stats(struct fbnic_dev *fbd); void fbnic_reset_hw_stats(struct fbnic_dev *fbd); void fbnic_init_hw_stats(struct fbnic_dev *fbd); void fbnic_get_hw_q_stats(struct fbnic_dev *fbd, diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_pci.c b/drivers/net/ethernet/meta/fbnic/fbnic_pci.c index 09ae797b1f0dc6..cb0191b6520496 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_pci.c +++ b/drivers/net/ethernet/meta/fbnic/fbnic_pci.c @@ -350,13 +350,13 @@ static int fbnic_probe(struct pci_dev *pdev, const struct pci_device_id *ent) */ fbnic_fw_log_enable(fbd, true); + /* Capture snapshot of hardware stats so netdev can calculate delta */ + fbnic_init_hw_stats(fbd); + fbnic_devlink_register(fbd); fbnic_devlink_otp_check(fbd, "error detected during probe"); fbnic_dbg_fbd_init(fbd); - /* Capture snapshot of hardware stats so netdev can calculate delta */ - fbnic_init_hw_stats(fbd); - fbnic_hwmon_register(fbd); if (!fbd->dsn) { @@ -498,10 +498,16 @@ static int __fbnic_pm_resume(struct device *dev) struct fbnic_net *fbn; int err; - /* Restore MMIO access */ + /* Restore MMIO access and rebase the HW stats in one step, so that + * no stats read can take its delta from counters the reset cleared + * against the values read before it. + */ iomap_table = pcim_iomap_table(to_pci_dev(dev)); + spin_lock(&fbd->hw_stats.lock); fbd->uc_addr0 = iomap_table[0]; fbd->uc_addr4 = iomap_table[4]; + __fbnic_reset_hw_stats(fbd); + spin_unlock(&fbd->hw_stats.lock); /* Rerequest the IRQs */ err = fbnic_alloc_irqs(fbd); @@ -582,8 +588,6 @@ static void __fbnic_pm_attach(struct device *dev) rtnl_lock(); netdev_lock(netdev); - fbnic_reset_hw_stats(fbd); - if (netif_running(netdev)) fbnic_up(fbn); diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c b/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c index 07d4b2e923627b..381831b7e1080d 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +++ b/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c @@ -1772,7 +1772,7 @@ static int fbnic_alloc_napi_vector(struct fbnic_dev *fbd, struct fbnic_net *fbn, /* Configure Tx completion queue */ db = &uc_addr[FBNIC_QUEUE(txq_idx) + FBNIC_QUEUE_TCQ_HEAD]; - fbnic_ring_init(&qt->cmpl, db, 0, 0); + fbnic_ring_init(&qt->cmpl, db, txq_idx, 0); /* Update Tx queue index */ txt_count--; @@ -2184,6 +2184,9 @@ static void fbnic_set_netif_napi(struct fbnic_napi_vector *nv) for (i = 0; i < nv->txt_count; i++) { struct fbnic_q_triad *qt = &nv->qt[i]; + if (qt->sub0.flags & FBNIC_RING_F_DISABLED) + continue; + netif_queue_set_napi(nv->napi.dev, qt->sub0.q_idx, NETDEV_QUEUE_TYPE_TX, &nv->napi); } @@ -2205,6 +2208,9 @@ static void fbnic_reset_netif_napi(struct fbnic_napi_vector *nv) for (i = 0; i < nv->txt_count; i++) { struct fbnic_q_triad *qt = &nv->qt[i]; + if (qt->sub0.flags & FBNIC_RING_F_DISABLED) + continue; + netif_queue_set_napi(nv->napi.dev, qt->sub0.q_idx, NETDEV_QUEUE_TYPE_TX, NULL); } @@ -2398,38 +2404,85 @@ static void fbnic_idle_dump(struct fbnic_dev *fbd, fbnic_rd32(fbd, regs[i].reg_base + j)); } -int fbnic_wait_all_queues_idle(struct fbnic_dev *fbd, bool may_fail) +/* The poll timeout only accounts for the delay between polls, not for + * the time spent in the poll itself, and each poll is a series of + * non-posted PCIe register reads that take on the order of a + * microsecond each. Space the polls out so that the reads stay a small + * part of each interval and the timeout stays close to wall time. + */ +#define FBNIC_IDLE_POLL_US 20 +#define FBNIC_IDLE_TIMEOUT_US 500000 + +static bool fbnic_tx_idle(struct fbnic_dev *fbd, + const struct fbnic_idle_regs *regs, + unsigned int nregs) +{ + u32 inflight; + + if (!fbnic_all_idle(fbd, regs, nregs)) + return false; + + /* The QM idle bits do not cover the TMI completion path, so a + * timestamp request can still be waiting on its completion. The + * count is bounded by the timestamp requests the Tx path can hold, + * so all ones is a failed read, as for the idle bits, not a count. + */ + inflight = fbnic_rd32(fbd, FBNIC_TCE_PTP_INFLIGHT); + + return !inflight || !~inflight; +} + +static int fbnic_wait_tx_idle(struct fbnic_dev *fbd) { static const struct fbnic_idle_regs tx[] = { { FBNIC_QM_TWQ_IDLE(0), FBNIC_QM_TWQ_IDLE_CNT, }, { FBNIC_QM_TQS_IDLE(0), FBNIC_QM_TQS_IDLE_CNT, }, { FBNIC_QM_TDE_IDLE(0), FBNIC_QM_TDE_IDLE_CNT, }, { FBNIC_QM_TCQ_IDLE(0), FBNIC_QM_TCQ_IDLE_CNT, }, - }, rx[] = { - { FBNIC_QM_HPQ_IDLE(0), FBNIC_QM_HPQ_IDLE_CNT, }, - { FBNIC_QM_PPQ_IDLE(0), FBNIC_QM_PPQ_IDLE_CNT, }, - { FBNIC_QM_RCQ_IDLE(0), FBNIC_QM_RCQ_IDLE_CNT, }, }; bool idle; int err; - err = read_poll_timeout_atomic(fbnic_all_idle, idle, idle, 2, 500000, - false, fbd, tx, ARRAY_SIZE(tx)); + err = read_poll_timeout_atomic(fbnic_tx_idle, idle, idle, + FBNIC_IDLE_POLL_US, + FBNIC_IDLE_TIMEOUT_US, false, + fbd, tx, ARRAY_SIZE(tx)); if (err == -ETIMEDOUT) { fbnic_tx_flush(fbd); - err = read_poll_timeout_atomic(fbnic_all_idle, idle, idle, - 2, 500000, false, + err = read_poll_timeout_atomic(fbnic_tx_idle, idle, idle, + FBNIC_IDLE_POLL_US, + FBNIC_IDLE_TIMEOUT_US, false, fbd, tx, ARRAY_SIZE(tx)); fbnic_tx_flush_off(fbd); } if (err) { fbnic_idle_dump(fbd, tx, ARRAY_SIZE(tx), "Tx", err); - if (may_fail) - return err; + netdev_err(fbd->netdev, "0x%04x: %08x\n", + FBNIC_TCE_PTP_INFLIGHT, + fbnic_rd32(fbd, FBNIC_TCE_PTP_INFLIGHT)); } - err = read_poll_timeout_atomic(fbnic_all_idle, idle, idle, 2, 500000, - false, fbd, rx, ARRAY_SIZE(rx)); + return err; +} + +int fbnic_wait_all_queues_idle(struct fbnic_dev *fbd, bool may_fail) +{ + static const struct fbnic_idle_regs rx[] = { + { FBNIC_QM_HPQ_IDLE(0), FBNIC_QM_HPQ_IDLE_CNT, }, + { FBNIC_QM_PPQ_IDLE(0), FBNIC_QM_PPQ_IDLE_CNT, }, + { FBNIC_QM_RCQ_IDLE(0), FBNIC_QM_RCQ_IDLE_CNT, }, + }; + bool idle; + int err; + + err = fbnic_wait_tx_idle(fbd); + if (err && may_fail) + return err; + + err = read_poll_timeout_atomic(fbnic_all_idle, idle, idle, + FBNIC_IDLE_POLL_US, + FBNIC_IDLE_TIMEOUT_US, false, + fbd, rx, ARRAY_SIZE(rx)); if (err) fbnic_idle_dump(fbd, rx, ARRAY_SIZE(rx), "Rx", err); return err; @@ -3047,8 +3100,11 @@ static void __fbnic_nv_restart(struct fbnic_net *fbn, fbnic_wr32(fbd, FBNIC_INTR_SET(nv->v_idx / 32), BIT(nv->v_idx % 32)); fbnic_wrfl(fbd); - for (i = 0; i < nv->txt_count; i++) + for (i = 0; i < nv->txt_count; i++) { + if (nv->qt[i].sub0.flags & FBNIC_RING_F_DISABLED) + continue; netif_wake_subqueue(fbn->netdev, nv->qt[i].sub0.q_idx); + } fbnic_dbg_nv_init(nv); } @@ -3089,13 +3145,16 @@ static int fbnic_queue_stop(struct net_device *dev, void *qmem, int idx) napi_disable_locked(&nv->napi); fbnic_nv_irq_disable(nv); - for (i = 0; i < nv->txt_count; i++) + for (i = 0; i < nv->txt_count; i++) { + if (nv->qt[i].sub0.flags & FBNIC_RING_F_DISABLED) + continue; netif_stop_subqueue(dev, nv->qt[i].sub0.q_idx); + } fbnic_nv_disable(fbn, nv); for (t = 0; t < nv->txt_count + nv->rxt_count; t++) { err = fbnic_wait_queue_idle(fbn, t >= nv->txt_count, - nv->qt[t].sub0.q_idx); + nv->qt[t].cmpl.q_idx); if (err) goto err_restart; } diff --git a/drivers/net/ethernet/microchip/encx24j600.c b/drivers/net/ethernet/microchip/encx24j600.c index b011bf5c2305c8..ebc067cb2c9d28 100644 --- a/drivers/net/ethernet/microchip/encx24j600.c +++ b/drivers/net/ethernet/microchip/encx24j600.c @@ -893,9 +893,10 @@ static netdev_tx_t encx24j600_tx(struct sk_buff *skb, struct net_device *dev) static void encx24j600_tx_timeout(struct net_device *dev, unsigned int txqueue) { struct encx24j600_priv *priv = netdev_priv(dev); + unsigned long j = jiffies; netif_err(priv, tx_err, dev, "TX timeout at %ld, latency %ld\n", - jiffies, jiffies - dev_trans_start(dev)); + j, j - dev_trans_start(dev)); dev->stats.tx_errors++; netif_wake_queue(dev); diff --git a/drivers/net/ethernet/microchip/sparx5/lan969x/lan969x_fdma.c b/drivers/net/ethernet/microchip/sparx5/lan969x/lan969x_fdma.c index 053d125eda6584..fd532c89f91100 100644 --- a/drivers/net/ethernet/microchip/sparx5/lan969x/lan969x_fdma.c +++ b/drivers/net/ethernet/microchip/sparx5/lan969x/lan969x_fdma.c @@ -113,8 +113,11 @@ static struct sk_buff *lan969x_fdma_rx_get_frame(struct sparx5 *sparx5, sparx5_ifh_parse(sparx5, page_address(page), &fi); port = fi.src_port < consts->n_ports ? sparx5->ports[fi.src_port] : NULL; - if (WARN_ON(!port)) + if (!port) { + dev_err_ratelimited(sparx5->dev, "Data on inactive port %d\n", + fi.src_port); goto free_page; + } skb = build_skb(page_address(page), fdma->db_size); if (unlikely(!skb)) @@ -258,10 +261,8 @@ int lan969x_fdma_napi_poll(struct napi_struct *napi, int weight) break; skb = lan969x_fdma_rx_get_frame(sparx5, rx); - if (!skb) - break; - - napi_gro_receive(&rx->napi, skb); + if (skb) + napi_gro_receive(&rx->napi, skb); fdma_db_advance(fdma); counter++; diff --git a/drivers/net/ethernet/microchip/sparx5/sparx5_fdma.c b/drivers/net/ethernet/microchip/sparx5/sparx5_fdma.c index 15ec9b053824f5..8675702bf1504e 100644 --- a/drivers/net/ethernet/microchip/sparx5/sparx5_fdma.c +++ b/drivers/net/ethernet/microchip/sparx5/sparx5_fdma.c @@ -157,9 +157,15 @@ static bool sparx5_fdma_rx_get_frame(struct sparx5 *sparx5, struct sparx5_rx *rx sparx5->ports[fi.src_port] : NULL; if (!port || !port->ndev) { - dev_err(sparx5->dev, "Data on inactive port %d\n", fi.src_port); - sparx5_xtr_flush(sparx5, XTR_QUEUE); - return false; + dev_err_ratelimited(sparx5->dev, "Data on inactive port %d\n", + fi.src_port); + + /* Drop the frame, but report the DB as consumed so the + * caller advances past it and recycles the DCB. + */ + kfree_skb(skb); + + return true; } skb->dev = port->ndev; skb_pull(skb, IFH_LEN * sizeof(u32)); diff --git a/drivers/net/ethernet/microsoft/mana/gdma_main.c b/drivers/net/ethernet/microsoft/mana/gdma_main.c index ab942d5bfe0585..10be69e97ceb9c 100644 --- a/drivers/net/ethernet/microsoft/mana/gdma_main.c +++ b/drivers/net/ethernet/microsoft/mana/gdma_main.c @@ -646,6 +646,11 @@ void mana_gd_ring_dim(struct gdma_queue *cq, u32 mod_usec, bool mod_usec_vld, struct gdma_context *gc = cq->gdma_dev->gdma_context; u32 dim_val; + mod_usec = clamp_t(u32, mod_usec, MANA_INTR_MODR_USEC_MIN, + MANA_INTR_MODR_USEC_MAX); + mod_comps = clamp_t(u32, mod_comps, MANA_INTR_MODR_COMP_MIN, + MANA_INTR_MODR_COMP_MAX); + /* Convert the DIM values to doorbell parameters */ dim_val = FIELD_PREP(MANA_INTR_MODR_USEC_MAX, mod_usec) | FIELD_PREP(MANA_INTR_MODR_COMP_MASK, mod_comps); diff --git a/drivers/net/ethernet/microsoft/mana/mana_en.c b/drivers/net/ethernet/microsoft/mana/mana_en.c index 7e9223143fc75f..95bf153c3e1a86 100644 --- a/drivers/net/ethernet/microsoft/mana/mana_en.c +++ b/drivers/net/ethernet/microsoft/mana/mana_en.c @@ -2515,9 +2515,6 @@ static void mana_rx_dim_work(struct work_struct *work) cur_moder = net_dim_get_rx_moderation(dim->mode, dim->profile_ix); cq = container_of(dim, struct mana_cq, dim); - cur_moder.usec = min_t(u16, cur_moder.usec, MANA_INTR_MODR_USEC_MAX); - cur_moder.pkts = min_t(u16, cur_moder.pkts, MANA_INTR_MODR_COMP_MAX); - mana_gd_ring_dim(cq->gdma_cq, cur_moder.usec, true, cur_moder.pkts, true); @@ -2533,9 +2530,6 @@ static void mana_tx_dim_work(struct work_struct *work) cur_moder = net_dim_get_tx_moderation(dim->mode, dim->profile_ix); cq = container_of(dim, struct mana_cq, dim); - cur_moder.usec = min_t(u16, cur_moder.usec, MANA_INTR_MODR_USEC_MAX); - cur_moder.pkts = min_t(u16, cur_moder.pkts, MANA_INTR_MODR_COMP_MAX); - mana_gd_ring_dim(cq->gdma_cq, cur_moder.usec, true, cur_moder.pkts, true); @@ -2871,10 +2865,15 @@ static int mana_create_txq(struct mana_port_context *apc, cq_spec.modr_ctx_id = 0; cq_spec.attached_eq = cq->gdma_cq->cq.parent->id; - /* DIM setting can be changed at runtime */ - cq_spec.req_cq_moderation = true; - cq_spec.cq_moderation_usec = apc->intr_modr_tx_usec; - cq_spec.cq_moderation_comp = apc->intr_modr_tx_comp; + /* Request CQ moderation only if HW supports it. + * DIM setting can be changed at runtime. + */ + if (gc->pf_cap_flags1 & + GDMA_PF_CAP_FLAG_1_DYN_INTERRUPT_MODERATION) { + cq_spec.req_cq_moderation = true; + cq_spec.cq_moderation_usec = apc->intr_modr_tx_usec; + cq_spec.cq_moderation_comp = apc->intr_modr_tx_comp; + } err = mana_create_wq_obj(apc, apc->port_handle, GDMA_SQ, &wq_spec, &cq_spec, @@ -3206,10 +3205,14 @@ static struct mana_rxq *mana_create_rxq(struct mana_port_context *apc, cq_spec.modr_ctx_id = 0; cq_spec.attached_eq = cq->gdma_cq->cq.parent->id; - /* DIM setting can be changed at runtime */ - cq_spec.req_cq_moderation = true; - cq_spec.cq_moderation_usec = apc->intr_modr_rx_usec; - cq_spec.cq_moderation_comp = apc->intr_modr_rx_comp; + /* Request CQ moderation only if HW supports it. + * DIM setting can be changed at runtime. + */ + if (gc->pf_cap_flags1 & GDMA_PF_CAP_FLAG_1_DYN_INTERRUPT_MODERATION) { + cq_spec.req_cq_moderation = true; + cq_spec.cq_moderation_usec = apc->intr_modr_rx_usec; + cq_spec.cq_moderation_comp = apc->intr_modr_rx_comp; + } err = mana_create_wq_obj(apc, apc->port_handle, GDMA_RQ, &wq_spec, &cq_spec, &rxq->rxobj); @@ -3894,6 +3897,40 @@ int mana_detach(struct net_device *ndev, bool from_close) return 0; } +/* Match the interrupt moderation settings to the PF capability, which is + * queried again when the device resumes from a reset or suspend. Must be + * called before the queues are created. + */ +static void mana_init_intr_modr(struct mana_port_context *apc) +{ + struct gdma_context *gc = apc->ac->gdma_dev->gdma_context; + + if (!(gc->pf_cap_flags1 & + GDMA_PF_CAP_FLAG_1_DYN_INTERRUPT_MODERATION)) { + apc->intr_modr_rx_usec = 0; + apc->intr_modr_rx_comp = 0; + apc->intr_modr_tx_usec = 0; + apc->intr_modr_tx_comp = 0; + apc->rx_dim_enabled = false; + apc->tx_dim_enabled = false; + return; + } + + /* Keep the current settings, unless they were never initialized + * because the port was probed without the capability. + */ + if (apc->intr_modr_rx_usec && apc->intr_modr_rx_comp && + apc->intr_modr_tx_usec && apc->intr_modr_tx_comp) + return; + + apc->intr_modr_rx_usec = MANA_INTR_MODR_USEC_DEF; + apc->intr_modr_rx_comp = MANA_INTR_MODR_COMP_DEF; + apc->intr_modr_tx_usec = MANA_INTR_MODR_USEC_DEF; + apc->intr_modr_tx_comp = MANA_INTR_MODR_COMP_DEF; + apc->rx_dim_enabled = MANA_ADAPTIVE_RX_DEF; + apc->tx_dim_enabled = MANA_ADAPTIVE_TX_DEF; +} + static int mana_probe_port(struct mana_context *ac, int port_idx, struct net_device **ndev_storage) { @@ -3924,15 +3961,7 @@ static int mana_probe_port(struct mana_context *ac, int port_idx, apc->cqe_coalescing_enable = 0; apc->cqe8_coalescing_enable = 0; - /* Initialize interrupt moderation settings if supported by HW */ - if (gc->pf_cap_flags1 & GDMA_PF_CAP_FLAG_1_DYN_INTERRUPT_MODERATION) { - apc->intr_modr_rx_usec = MANA_INTR_MODR_USEC_DEF; - apc->intr_modr_rx_comp = MANA_INTR_MODR_COMP_DEF; - apc->intr_modr_tx_usec = MANA_INTR_MODR_USEC_DEF; - apc->intr_modr_tx_comp = MANA_INTR_MODR_COMP_DEF; - apc->rx_dim_enabled = MANA_ADAPTIVE_RX_DEF; - apc->tx_dim_enabled = MANA_ADAPTIVE_TX_DEF; - } + mana_init_intr_modr(apc); mutex_init(&apc->vport_mutex); apc->vport_use_count = 0; @@ -4256,6 +4285,7 @@ int mana_probe(struct gdma_dev *gd, bool resuming) enable_work(&apc->queue_reset_work); netdev_lock(ac->ports[i]); apc->link_cfg_error = 1; + mana_init_intr_modr(apc); netdev_unlock(ac->ports[i]); err = mana_attach(ac->ports[i]); rtnl_unlock(); diff --git a/drivers/net/ethernet/microsoft/mana/mana_ethtool.c b/drivers/net/ethernet/microsoft/mana/mana_ethtool.c index 4068e08acb1667..96aabf7a8f08b0 100644 --- a/drivers/net/ethernet/microsoft/mana/mana_ethtool.c +++ b/drivers/net/ethernet/microsoft/mana/mana_ethtool.c @@ -505,9 +505,12 @@ static int mana_set_coalesce(struct net_device *ndev, bool dim_changed = false; struct gdma_context *gc; u32 max_cqe_frames; + bool modr_sup; int err; gc = apc->ac->gdma_dev->gdma_context; + modr_sup = gc->pf_cap_flags1 & + GDMA_PF_CAP_FLAG_1_DYN_INTERRUPT_MODERATION; max_cqe_frames = gc->cqe8_coalescing_sup ? MANA_CQE_COAL_PKTS_8 : MANA_RXCOMP_OOB_NUM_PPI; @@ -517,7 +520,7 @@ static int mana_set_coalesce(struct net_device *ndev, if ((ec->use_adaptive_rx_coalesce || ec->use_adaptive_tx_coalesce || ec->rx_coalesce_usecs || ec->tx_coalesce_usecs || ec->rx_max_coalesced_frames || ec->tx_max_coalesced_frames) && - !(gc->pf_cap_flags1 & GDMA_PF_CAP_FLAG_1_DYN_INTERRUPT_MODERATION)) { + !modr_sup) { NL_SET_ERR_MSG(extack, "Interrupt Moderation is not supported by HW"); return -EOPNOTSUPP; @@ -534,18 +537,27 @@ static int mana_set_coalesce(struct net_device *ndev, return -EINVAL; } - if (ec->rx_coalesce_usecs > MANA_INTR_MODR_USEC_MAX || - ec->tx_coalesce_usecs > MANA_INTR_MODR_USEC_MAX) { + /* Without the HW capability, only zero values pass the check above */ + if (modr_sup && + (ec->rx_coalesce_usecs < MANA_INTR_MODR_USEC_MIN || + ec->tx_coalesce_usecs < MANA_INTR_MODR_USEC_MIN || + ec->rx_coalesce_usecs > MANA_INTR_MODR_USEC_MAX || + ec->tx_coalesce_usecs > MANA_INTR_MODR_USEC_MAX)) { NL_SET_ERR_MSG_FMT(extack, - "coalesce usecs must be <= %lu", + "coalesce usecs must be between %d and %lu", + MANA_INTR_MODR_USEC_MIN, MANA_INTR_MODR_USEC_MAX); return -EINVAL; } - if (ec->rx_max_coalesced_frames > MANA_INTR_MODR_COMP_MAX || - ec->tx_max_coalesced_frames > MANA_INTR_MODR_COMP_MAX) { + if (modr_sup && + (ec->rx_max_coalesced_frames < MANA_INTR_MODR_COMP_MIN || + ec->tx_max_coalesced_frames < MANA_INTR_MODR_COMP_MIN || + ec->rx_max_coalesced_frames > MANA_INTR_MODR_COMP_MAX || + ec->tx_max_coalesced_frames > MANA_INTR_MODR_COMP_MAX)) { NL_SET_ERR_MSG_FMT(extack, - "coalesce frames must be <= %lu", + "coalesce frames must be between %d and %lu", + MANA_INTR_MODR_COMP_MIN, MANA_INTR_MODR_COMP_MAX); return -EINVAL; } diff --git a/drivers/net/ethernet/pensando/ionic/ionic_dev.h b/drivers/net/ethernet/pensando/ionic/ionic_dev.h index db90e39a1442d2..4b3e244e6bbb2d 100644 --- a/drivers/net/ethernet/pensando/ionic/ionic_dev.h +++ b/drivers/net/ethernet/pensando/ionic/ionic_dev.h @@ -16,7 +16,8 @@ #define IONIC_MAX_TX_DESC 8192 #define IONIC_MAX_RX_DESC 16384 -#define IONIC_MIN_TXRX_DESC 64 +#define IONIC_MIN_RX_DESC 64 +#define IONIC_MIN_TX_DESC 128 #define IONIC_DEF_TXRX_DESC 1024 #define IONIC_RX_FILL_THRESHOLD 16 #define IONIC_RX_FILL_DIV 8 diff --git a/drivers/net/ethernet/pensando/ionic/ionic_ethtool.c b/drivers/net/ethernet/pensando/ionic/ionic_ethtool.c index 119ac720c0787a..24fd34b4cfccc6 100644 --- a/drivers/net/ethernet/pensando/ionic/ionic_ethtool.c +++ b/drivers/net/ethernet/pensando/ionic/ionic_ethtool.c @@ -708,6 +708,13 @@ static int ionic_set_ringparam(struct net_device *netdev, return -EINVAL; } + if (ring->tx_pending < IONIC_MIN_TX_DESC) { + NL_SET_ERR_MSG_FMT_MOD(extack, + "Tx descriptor count must be at least %d", + IONIC_MIN_TX_DESC); + return -EINVAL; + } + /* if nothing to do return success */ if (ring->tx_pending == lif->ntxq_descs && ring->rx_pending == lif->nrxq_descs && diff --git a/drivers/net/ethernet/pensando/ionic/ionic_lif.c b/drivers/net/ethernet/pensando/ionic/ionic_lif.c index 22d1e4b6d61be8..339a3c4c5b4327 100644 --- a/drivers/net/ethernet/pensando/ionic/ionic_lif.c +++ b/drivers/net/ethernet/pensando/ionic/ionic_lif.c @@ -997,7 +997,7 @@ int ionic_lif_create_hwstamp_txq(struct ionic_lif *lif) features = IONIC_Q_F_2X_CQ_DESC | IONIC_TXQ_F_HWSTAMP; - num_desc = IONIC_MIN_TXRX_DESC; + num_desc = IONIC_MIN_TX_DESC; desc_sz = sizeof(struct ionic_txq_desc); comp_sz = 2 * sizeof(struct ionic_txq_comp); @@ -1062,7 +1062,7 @@ int ionic_lif_create_hwstamp_rxq(struct ionic_lif *lif) features = IONIC_Q_F_2X_CQ_DESC | IONIC_RXQ_F_HWSTAMP; - num_desc = IONIC_MIN_TXRX_DESC; + num_desc = IONIC_MIN_RX_DESC; desc_sz = sizeof(struct ionic_rxq_desc); comp_sz = 2 * sizeof(struct ionic_rxq_comp); sg_desc_sz = sizeof(struct ionic_rxq_sg_desc); @@ -1642,6 +1642,8 @@ static int ionic_init_nic_features(struct ionic_lif *lif) netdev->features |= netdev->hw_features; netdev->vlan_features |= netdev->features & ~NETIF_F_VLAN_FEATURES; + netif_set_tso_max_segs(netdev, IONIC_MIN_TX_DESC - 1); + netdev->priv_flags |= IFF_UNICAST_FLT | IFF_LIVE_ADDR_CHANGE; @@ -3284,8 +3286,8 @@ int ionic_lif_alloc(struct ionic *ionic) lif->index = 0; if (is_kdump_kernel()) { - lif->ntxq_descs = IONIC_MIN_TXRX_DESC; - lif->nrxq_descs = IONIC_MIN_TXRX_DESC; + lif->ntxq_descs = IONIC_MIN_TX_DESC; + lif->nrxq_descs = IONIC_MIN_RX_DESC; } else { lif->ntxq_descs = IONIC_DEF_TXRX_DESC; lif->nrxq_descs = IONIC_DEF_TXRX_DESC; diff --git a/drivers/net/ethernet/qualcomm/qca_spi.c b/drivers/net/ethernet/qualcomm/qca_spi.c index 38a779f4b866ca..249b4b549a12b4 100644 --- a/drivers/net/ethernet/qualcomm/qca_spi.c +++ b/drivers/net/ethernet/qualcomm/qca_spi.c @@ -801,8 +801,8 @@ qcaspi_netdev_tx_timeout(struct net_device *dev, unsigned int txqueue) { struct qcaspi *qca = netdev_priv(dev); - netdev_info(qca->net_dev, "Transmit timeout at %ld, latency %ld\n", - jiffies, jiffies - dev_trans_start(dev)); + netdev_info(qca->net_dev, "Transmit timeout, latency %ld\n", + jiffies - dev_trans_start(dev)); qca->net_dev->stats.tx_errors++; /* Trigger tx queue flush and QCA7000 reset */ set_bit(SPI_RESET, &qca->flags); diff --git a/drivers/net/ethernet/spacemit/k1_emac.c b/drivers/net/ethernet/spacemit/k1_emac.c index 71a80838bffd0b..d07d8a1aa5ee01 100644 --- a/drivers/net/ethernet/spacemit/k1_emac.c +++ b/drivers/net/ethernet/spacemit/k1_emac.c @@ -1732,7 +1732,6 @@ static int emac_down(struct emac_priv *priv) napi_disable(&priv->napi); timer_delete_sync(&priv->txtimer); - cancel_work_sync(&priv->tx_timeout_task); timer_delete_sync(&priv->stats_timer); @@ -2010,8 +2009,9 @@ static void emac_remove(struct platform_device *pdev) { struct emac_priv *priv = platform_get_drvdata(pdev); + disable_work_sync(&priv->tx_timeout_task); + timer_shutdown_sync(&priv->txtimer); - cancel_work_sync(&priv->tx_timeout_task); timer_shutdown_sync(&priv->stats_timer); @@ -2024,16 +2024,23 @@ static int emac_resume(struct device *dev) struct net_device *ndev = priv->ndev; int ret; + enable_work(&priv->tx_timeout_task); + ret = clk_prepare_enable(priv->bus_clk); if (ret < 0) { dev_err(dev, "Failed to enable bus clock: %d\n", ret); return ret; } + rtnl_lock(); - if (!netif_running(ndev)) + if (!netif_running(ndev)) { + rtnl_unlock(); return 0; + } ret = emac_open(ndev); + rtnl_unlock(); + if (ret) { clk_disable_unprepare(priv->bus_clk); return ret; @@ -2051,12 +2058,18 @@ static int emac_suspend(struct device *dev) struct emac_priv *priv = dev_get_drvdata(dev); struct net_device *ndev = priv->ndev; + disable_work_sync(&priv->tx_timeout_task); + + rtnl_lock(); + if (!ndev || !netif_running(ndev)) { + rtnl_unlock(); clk_disable_unprepare(priv->bus_clk); return 0; } emac_stop(ndev); + rtnl_unlock(); clk_disable_unprepare(priv->bus_clk); netif_device_detach(ndev); diff --git a/drivers/net/ethernet/stmicro/stmmac/common.h b/drivers/net/ethernet/stmicro/stmmac/common.h index c74bc7c9750e98..a972bee66504ba 100644 --- a/drivers/net/ethernet/stmicro/stmmac/common.h +++ b/drivers/net/ethernet/stmicro/stmmac/common.h @@ -382,6 +382,7 @@ enum dma_irq_dir { DMA_DIR_RX = 0x1, DMA_DIR_TX = 0x2, DMA_DIR_RXTX = 0x3, + DMA_DIR_ERR = 0x4, }; enum request_irq_err { diff --git a/drivers/net/ethernet/stmicro/stmmac/dwmac1000.h b/drivers/net/ethernet/stmicro/stmmac/dwmac1000.h index 1de1f929d61cdd..55d9c39287f1ff 100644 --- a/drivers/net/ethernet/stmicro/stmmac/dwmac1000.h +++ b/drivers/net/ethernet/stmicro/stmmac/dwmac1000.h @@ -162,7 +162,7 @@ enum rx_tx_priority_ratio { /* DMA CRS Control and Status Register Mapping */ /* DMA operation mode defines (start/stop tx/rx are placed in common header)*/ -/* Disable Drop TCP/IP csum error */ +#define DMA_CONTROL_DT 0x04000000 /* Disable Drop of TCP/IP csum errors */ #define DMA_CONTROL_RSF 0x02000000 /* Receive Store and Forward */ #define DMA_CONTROL_DFF 0x01000000 /* Disaable flushing */ /* Threshold for Activating the FC */ diff --git a/drivers/net/ethernet/stmicro/stmmac/dwmac1000_dma.c b/drivers/net/ethernet/stmicro/stmmac/dwmac1000_dma.c index 3ac7a7949529c8..31d5f79ef5602d 100644 --- a/drivers/net/ethernet/stmicro/stmmac/dwmac1000_dma.c +++ b/drivers/net/ethernet/stmicro/stmmac/dwmac1000_dma.c @@ -15,6 +15,7 @@ #include #include "dwmac1000.h" #include "dwmac_dma.h" +#include "stmmac.h" static void dwmac1000_dma_axi(void __iomem *ioaddr, struct stmmac_axi *axi) { @@ -129,6 +130,13 @@ static void dwmac1000_dma_operation_mode_rx(struct stmmac_priv *priv, { u32 csr6 = readl(ioaddr + DMA_CHAN_CONTROL(channel)); + /* Deliver checksum-error frames only with enhanced + * descriptors, because the normal descriptor parser does not + * report a checksum-only error. + */ + if (priv->plat->enh_desc) + csr6 |= DMA_CONTROL_DT; + if (mode == SF_DMA_MODE) { pr_debug("GMAC: enable RX store and forward mode\n"); csr6 |= DMA_CONTROL_RSF | DMA_CONTROL_DFF; diff --git a/drivers/net/ethernet/stmicro/stmmac/dwmac4_dma.h b/drivers/net/ethernet/stmicro/stmmac/dwmac4_dma.h index 43b036d4e95bdd..a7caac3c98e6cd 100644 --- a/drivers/net/ethernet/stmicro/stmmac/dwmac4_dma.h +++ b/drivers/net/ethernet/stmicro/stmmac/dwmac4_dma.h @@ -173,6 +173,11 @@ static inline u32 dma_chanx_base_addr(const struct dwmac4_addrs *addrs, DMA_CHAN_STATUS_TI | \ DMA_CHAN_STATUS_MSK_COMMON) +#define DMA_CHAN_STATUS_MSK_ERR (DMA_CHAN_STATUS_AIS | \ + DMA_CHAN_STATUS_FBE | \ + DMA_CHAN_STATUS_RPS | \ + DMA_CHAN_STATUS_RBU) + int dwmac4_dma_reset(void __iomem *ioaddr); void dwmac4_enable_dma_irq(struct stmmac_priv *priv, void __iomem *ioaddr, u32 chan, bool rx, bool tx); diff --git a/drivers/net/ethernet/stmicro/stmmac/dwmac4_lib.c b/drivers/net/ethernet/stmicro/stmmac/dwmac4_lib.c index a0249715fafafd..02aa1a3dd1e25c 100644 --- a/drivers/net/ethernet/stmicro/stmmac/dwmac4_lib.c +++ b/drivers/net/ethernet/stmicro/stmmac/dwmac4_lib.c @@ -150,6 +150,8 @@ int dwmac4_dma_interrupt(struct stmmac_priv *priv, void __iomem *ioaddr, intr_status &= DMA_CHAN_STATUS_MSK_RX; else if (dir == DMA_DIR_TX) intr_status &= DMA_CHAN_STATUS_MSK_TX; + else if (dir == DMA_DIR_ERR) + intr_status &= DMA_CHAN_STATUS_MSK_ERR; /* ABNORMAL interrupts */ if (unlikely(intr_status & DMA_CHAN_STATUS_AIS)) { diff --git a/drivers/net/ethernet/stmicro/stmmac/dwxgmac2_core.c b/drivers/net/ethernet/stmicro/stmmac/dwxgmac2_core.c index 1a88cbaed70ca1..6b2bfc2411098a 100644 --- a/drivers/net/ethernet/stmicro/stmmac/dwxgmac2_core.c +++ b/drivers/net/ethernet/stmicro/stmmac/dwxgmac2_core.c @@ -859,10 +859,10 @@ dwxgmac3_safety_feat_config(void __iomem *ioaddr, unsigned int asp, value |= XGMAC_TCEIE; /* TSO Memory Correctable Error */ writel(value, ioaddr + XGMAC_DMA_ECC_INT_ENABLE); - /* 0x2: Without ECC or Parity Ports on External Application Interface - * 0x4: Only ECC Protection for External Memory feature is selected + /* 0x4: Only ECC Protection for External Memory feature is + * selected, without any on-chip parity protection */ - if (asp == 0x2 || asp == 0x4) + if (asp == 0x4) return 0; /* 4. Enable Parity and Timeout for FSM */ diff --git a/drivers/net/ethernet/stmicro/stmmac/enh_desc.c b/drivers/net/ethernet/stmicro/stmmac/enh_desc.c index 7ece8d4157a869..d0622f2605aaae 100644 --- a/drivers/net/ethernet/stmicro/stmmac/enh_desc.c +++ b/drivers/net/ethernet/stmicro/stmmac/enh_desc.c @@ -216,9 +216,6 @@ static int enh_desc_get_rx_status(struct stmmac_extra_stats *x, if (unlikely(rdes0 & RDES0_OVERFLOW_ERROR)) x->rx_gmac_overflow++; - if (unlikely(rdes0 & RDES0_IPC_CSUM_ERROR)) - pr_err("\tIPC Csum Error/Giant frame\n"); - if (unlikely(rdes0 & RDES0_COLLISION)) x->rx_collision++; if (unlikely(rdes0 & RDES0_RECEIVE_WATCHDOG)) @@ -230,7 +227,10 @@ static int enh_desc_get_rx_status(struct stmmac_extra_stats *x, if (unlikely(rdes0 & RDES0_CRC_ERROR)) { x->rx_crc_errors++; } - ret = discard_frame; + if (rdes0 & (RDES0_DESCRIPTOR_ERROR | RDES0_OVERFLOW_ERROR | + RDES0_COLLISION | RDES0_RECEIVE_WATCHDOG | + RDES0_MII_ERROR | RDES0_CRC_ERROR)) + ret = discard_frame; } /* After a payload csum error, the ES bit is set. diff --git a/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c b/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c index 25894771e9e9f8..a685ce4638f61a 100644 --- a/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +++ b/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c @@ -3145,6 +3145,22 @@ static int stmmac_napi_check(struct stmmac_priv *priv, u32 chan, u32 dir) return status; } +static void stmmac_dma_err_interrupt(struct stmmac_priv *priv) +{ + u8 channels_to_check = max(priv->plat->rx_queues_to_use, + priv->plat->tx_queues_to_use); + int status; + u8 chan; + + for (chan = 0; chan < channels_to_check; chan++) { + status = stmmac_dma_interrupt_status(priv, priv->ioaddr, + &priv->xstats, chan, + DMA_DIR_ERR); + if (unlikely(status & tx_hard_error)) + stmmac_global_err(priv); + } +} + /** * stmmac_dma_interrupt - DMA ISR * @priv: driver private structure @@ -5547,7 +5563,7 @@ static struct sk_buff *stmmac_construct_skb_zc(struct stmmac_channel *ch, static void stmmac_dispatch_skb_zc(struct stmmac_priv *priv, u32 queue, struct dma_desc *p, struct dma_desc *np, - struct xdp_buff *xdp) + struct xdp_buff *xdp, int status) { struct stmmac_rxq_stats *rxq_stats = &priv->xstats.rxq_stats[queue]; struct stmmac_channel *ch = &priv->channel[queue]; @@ -5575,7 +5591,8 @@ static void stmmac_dispatch_skb_zc(struct stmmac_priv *priv, u32 queue, skb->protocol = eth_type_trans(skb, priv->dev); - if (unlikely(!coe) || !stmmac_has_ip_ethertype(skb)) + if (unlikely(!coe) || !stmmac_has_ip_ethertype(skb) || + (status & csum_none)) skb_checksum_none_assert(skb); else skb->ip_summed = CHECKSUM_UNNECESSARY; @@ -5789,7 +5806,8 @@ static int stmmac_rx_zc(struct stmmac_priv *priv, int limit, u32 queue) switch (res) { case STMMAC_XDP_PASS: - stmmac_dispatch_skb_zc(priv, queue, p, np, buf->xdp); + stmmac_dispatch_skb_zc(priv, queue, p, np, buf->xdp, + status); xsk_buff_free(buf->xdp); break; case STMMAC_XDP_CONSUMED: @@ -6029,7 +6047,7 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue) buf->page); buf->page = NULL; rx_dropped++; - count++; + error = 1; goto drain_data; } @@ -6065,7 +6083,7 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue) if (likely(status & rx_not_ls)) goto read_again; if (!skb) - continue; + goto next; /* Got entire packet into SKB. Finish it. */ @@ -6498,6 +6516,9 @@ static irqreturn_t stmmac_mac_interrupt(int irq, void *dev_id) /* To handle Common interrupts */ stmmac_common_interrupt(priv); + if (priv->plat->core_type == DWMAC_CORE_GMAC4) + stmmac_dma_err_interrupt(priv); + return IRQ_HANDLED; } @@ -6741,9 +6762,9 @@ static int stmmac_dma_cap_show(struct seq_file *seq, void *v) }; static const char * const dwxgmac_safety_feature_desc[] = { "No", - "All Safety Features with ECC and Parity", - "All Safety Features without ECC or Parity", - "All Safety Features with Parity Only", + "All Safety Features with ECC and Parity Ports on External Application Interface", + "All Safety Features without ECC or Parity Ports on External Application Interface", + "All Safety Features with Parity Ports on External Application Interface", "ECC Only", "UNDEFINED", "UNDEFINED", diff --git a/drivers/net/ethernet/stmicro/stmmac/stmmac_ptp.c b/drivers/net/ethernet/stmicro/stmmac/stmmac_ptp.c index 31a66e855d6b1a..6370bdc6c58b55 100644 --- a/drivers/net/ethernet/stmicro/stmmac/stmmac_ptp.c +++ b/drivers/net/ethernet/stmicro/stmmac/stmmac_ptp.c @@ -129,10 +129,19 @@ static int stmmac_set_time(struct ptp_clock_info *ptp, container_of(ptp, struct stmmac_priv, ptp_clock_ops); unsigned long flags; + mutex_lock(&priv->est_lock); + if (priv->est && priv->est->enable) + stmmac_est_configure(priv, priv, priv->est, + priv->plat->clk_ptp_rate, false); + write_lock_irqsave(&priv->ptp_lock, flags); stmmac_init_systime(priv, priv->ptpaddr, ts->tv_sec, ts->tv_nsec); write_unlock_irqrestore(&priv->ptp_lock, flags); + if (priv->est && priv->est->enable) + __stmmac_setup_est(priv); + mutex_unlock(&priv->est_lock); + return 0; } diff --git a/drivers/net/ethernet/via/via-rhine.c b/drivers/net/ethernet/via/via-rhine.c index e56ebbdd428d53..dbbbaf7f20ac95 100644 --- a/drivers/net/ethernet/via/via-rhine.c +++ b/drivers/net/ethernet/via/via-rhine.c @@ -2461,6 +2461,17 @@ static void rhine_remove_one_platform(struct platform_device *pdev) free_netdev(dev); } +static void rhine_shutdown_platform(struct platform_device *pdev) +{ + struct net_device *dev = platform_get_drvdata(pdev); + + rtnl_lock(); + netif_device_detach(dev); + if (netif_running(dev)) + dev_close(dev); + rtnl_unlock(); +} + static void rhine_shutdown_pci(struct pci_dev *pdev) { struct net_device *dev = pci_get_drvdata(pdev); @@ -2580,6 +2591,7 @@ static struct pci_driver rhine_driver_pci = { static struct platform_driver rhine_driver_platform = { .probe = rhine_init_one_platform, .remove = rhine_remove_one_platform, + .shutdown = rhine_shutdown_platform, .driver = { .name = DRV_NAME, .of_match_table = rhine_of_tbl, diff --git a/drivers/net/netdevsim/ethtool.c b/drivers/net/netdevsim/ethtool.c index c3d2bc783d5571..e0c4c96209c433 100644 --- a/drivers/net/netdevsim/ethtool.c +++ b/drivers/net/netdevsim/ethtool.c @@ -205,6 +205,14 @@ static int nsim_get_ts_info(struct net_device *dev, return 0; } +static void nsim_get_ts_stats(struct net_device *dev, + struct ethtool_ts_stats *ts_stats) +{ + ts_stats->pkts = 3; + ts_stats->lost = 1; + ts_stats->err = 0; +} + static u32 nsim_get_rxfh_key_size(struct net_device *dev) { return NETDEV_RSS_KEY_LEN; @@ -275,6 +283,7 @@ static const struct ethtool_ops nsim_ethtool_ops = { .set_fecparam = nsim_set_fecparam, .get_fec_stats = nsim_get_fec_stats, .get_ts_info = nsim_get_ts_info, + .get_ts_stats = nsim_get_ts_stats, }; static void nsim_ethtool_ring_init(struct netdevsim *ns) diff --git a/drivers/net/phy/realtek/realtek_main.c b/drivers/net/phy/realtek/realtek_main.c index ca2d515b77b36b..a39ad18382f254 100644 --- a/drivers/net/phy/realtek/realtek_main.c +++ b/drivers/net/phy/realtek/realtek_main.c @@ -3483,7 +3483,7 @@ static struct phy_driver realtek_drvs[] = { .write_mmd = genphy_write_mmd_unsupported, }, { PHY_ID_MATCH_EXACT(RTL_8261C_CG), - .name = "Realtek RTL8261C/D 10Gbps PHY", + .name = "Realtek RTL8261C_RTL8261D 10Gbps PHY", .probe = rtl8261x_probe, .config_init = rtl8261x_config_init, .get_features = rtl8261x_get_features, diff --git a/drivers/net/team/team_core.c b/drivers/net/team/team_core.c index cfb833c307c14f..65ac25e97ae311 100644 --- a/drivers/net/team/team_core.c +++ b/drivers/net/team/team_core.c @@ -2834,6 +2834,10 @@ int team_nl_options_set_doit(struct sk_buff *skb, struct genl_info *info) ctx.info = opt_inst_info; switch (opt_type) { case TEAM_OPTION_TYPE_U32: + if (nla_len(attr_data) != sizeof(u32)) { + err = -EINVAL; + goto team_put; + } ctx.data.u32_val = nla_get_u32(attr_data); break; case TEAM_OPTION_TYPE_STRING: @@ -2853,6 +2857,10 @@ int team_nl_options_set_doit(struct sk_buff *skb, struct genl_info *info) ctx.data.bool_val = attr_data ? true : false; break; case TEAM_OPTION_TYPE_S32: + if (nla_len(attr_data) != sizeof(s32)) { + err = -EINVAL; + goto team_put; + } ctx.data.s32_val = nla_get_s32(attr_data); break; default: diff --git a/drivers/net/tun.c b/drivers/net/tun.c index 86fd44e1075506..ae05b1e58abaa2 100644 --- a/drivers/net/tun.c +++ b/drivers/net/tun.c @@ -58,6 +58,7 @@ #include #include #include +#include #include #include #include @@ -227,6 +228,16 @@ struct veth { static void tun_flow_init(struct tun_struct *tun); static void tun_flow_uninit(struct tun_struct *tun); +/* In IFF_NAPI mode written packets wait in the tfile's sk_write_queue for the + * NAPI poll, which may run later in a kthread or ksoftirqd. Bound that queue + * like the per-CPU backlog. + */ +static bool tun_napi_queue_full(const struct sk_buff_head *queue) +{ + return skb_queue_len_lockless(queue) > + READ_ONCE(net_hotdata.max_backlog); +} + static int tun_napi_receive(struct napi_struct *napi, int budget) { struct tun_file *tfile = container_of(napi, struct tun_file, napi); @@ -237,21 +248,22 @@ static int tun_napi_receive(struct napi_struct *napi, int budget) __skb_queue_head_init(&process_queue); + /* At most budget skbs: the rest stays on the queue writers check */ spin_lock(&queue->lock); - skb_queue_splice_tail_init(queue, &process_queue); + if (skb_queue_len(queue) <= budget) { + skb_queue_splice_tail_init(queue, &process_queue); + } else { + while (skb_queue_len(&process_queue) < budget && + (skb = __skb_dequeue(queue))) + __skb_queue_tail(&process_queue, skb); + } spin_unlock(&queue->lock); - while (received < budget && (skb = __skb_dequeue(&process_queue))) { + while ((skb = __skb_dequeue(&process_queue))) { napi_gro_receive(napi, skb); ++received; } - if (!skb_queue_empty(&process_queue)) { - spin_lock(&queue->lock); - skb_queue_splice(&process_queue, queue); - spin_unlock(&queue->lock); - } - return received; } @@ -1871,8 +1883,15 @@ static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile, err = PTR_ERR_OR_ZERO(skb); if (err) goto drop; - if (!skb) + if (!skb) { + /* consumed by XDP, after copying */ + if (msg_control) { + struct ubuf_info *uarg = msg_control; + + uarg->ops->complete(NULL, uarg, false); + } return total_len; + } } else { if (!zerocopy) { copylen = len; @@ -2043,6 +2062,19 @@ static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile, struct sk_buff_head *queue = &tfile->sk.sk_write_queue; int queue_len; + /* Queue full: drop, and schedule NAPI, which a MSG_MORE sender + * may not have done yet. Lockless: concurrent writers can each + * still add one. + */ + if (unlikely(tun_napi_queue_full(queue))) { + local_bh_disable(); + napi_schedule(&tfile->napi); + local_bh_enable(); + rcu_read_unlock(); + drop_reason = SKB_DROP_REASON_FULL_RING; + goto drop; + } + spin_lock_bh(&queue->lock); if (unlikely(tfile->detached)) { @@ -2658,6 +2690,17 @@ static int tun_xdp_one(struct tun_struct *tun, if (tfile->napi_enabled) { queue = &tfile->sk.sk_write_queue; + + /* Queue full: drop, and schedule NAPI so that it drains even if + * nothing in this batch gets queued. + */ + if (unlikely(tun_napi_queue_full(queue))) { + napi_schedule(&tfile->napi); + kfree_skb_reason(skb, SKB_DROP_REASON_FULL_RING); + dev_core_stats_rx_dropped_inc(tun->dev); + return 0; + } + spin_lock(&queue->lock); if (unlikely(tfile->detached)) { @@ -3375,9 +3418,12 @@ static long __tun_chr_ioctl(struct file *file, unsigned int cmd, ret = -EBUSY; } else if ((unsigned short)arg == ARPHRD_IEEE802154 || (unsigned short)arg == ARPHRD_IEEE802154_MONITOR || - (unsigned short)arg == ARPHRD_6LOWPAN) { + (unsigned short)arg == ARPHRD_6LOWPAN || + (unsigned short)arg == ARPHRD_MCTP) { ret = -EINVAL; } else { + unsigned char addr_len = tun_get_addr_len(arg); + ret = call_netdevice_notifiers(NETDEV_PRE_TYPE_CHANGE, tun->dev); ret = notifier_to_errno(ret); @@ -3386,8 +3432,13 @@ static long __tun_chr_ioctl(struct file *file, unsigned int cmd, "Refused to change device type\n"); break; } + /* Addresses were added with the old dev->addr_len. */ + if (addr_len != tun->dev->addr_len) { + dev_uc_flush(tun->dev); + dev_mc_flush(tun->dev); + } tun->dev->type = (int) arg; - tun->dev->addr_len = tun_get_addr_len(tun->dev->type); + tun->dev->addr_len = addr_len; netif_info(tun, drv, tun->dev, "linktype set to %d\n", tun->dev->type); call_netdevice_notifiers(NETDEV_POST_TYPE_CHANGE, diff --git a/drivers/net/usb/smsc75xx.c b/drivers/net/usb/smsc75xx.c index 6f72a3f1590794..d1eca6bf7770f7 100644 --- a/drivers/net/usb/smsc75xx.c +++ b/drivers/net/usb/smsc75xx.c @@ -2217,6 +2217,14 @@ static int smsc75xx_rx_fixup(struct usbnet *dev, struct sk_buff *skb) return 0; } + if (unlikely(size < ETH_HLEN + ETH_FCS_LEN)) { + netif_dbg(dev, rx_err, dev->net, + "size err rx_cmd_a=0x%08x\n", + rx_cmd_a); + dev->net->stats.rx_length_errors++; + return 0; + } + /* last frame in this batch */ if (skb->len == size) { smsc75xx_rx_csum_offload(dev, skb, rx_cmd_a, diff --git a/drivers/net/veth.c b/drivers/net/veth.c index a61842b2585bfa..faa837acea7b7e 100644 --- a/drivers/net/veth.c +++ b/drivers/net/veth.c @@ -984,7 +984,7 @@ static int veth_poll(struct napi_struct *napi, int budget) /* NAPI functions as RCU section */ peer_dev = rcu_dereference_check(priv->peer, rcu_read_lock_bh_held()); - peer_txq = (peer_dev && queue_idx < peer_dev->real_num_tx_queues) ? + peer_txq = (peer_dev && queue_idx < peer_dev->num_tx_queues) ? netdev_get_tx_queue(peer_dev, queue_idx) : NULL; xdp_set_return_frame_no_direct(); @@ -1087,6 +1087,7 @@ static int __veth_napi_enable(struct net_device *dev) static void veth_napi_del_range(struct net_device *dev, int start, int end) { struct veth_priv *priv = netdev_priv(dev); + struct net_device *peer; int i; for (i = start; i < end; i++) { @@ -1099,11 +1100,17 @@ static void veth_napi_del_range(struct net_device *dev, int start, int end) } synchronize_net(); + peer = rtnl_dereference(priv->peer); + for (i = start; i < end; i++) { struct veth_rq *rq = &priv->rq[i]; rq->rx_notify_masked = false; ptr_ring_cleanup(&rq->xdp_ring, veth_ptr_free); + + /* veth_poll() can no longer wake a txq stopped on a full ring */ + if (peer && i < peer->num_tx_queues) + netif_wake_subqueue(peer, i); } for (i = start; i < end; i++) { diff --git a/drivers/net/virtio_net.c b/drivers/net/virtio_net.c index ed20e76fbc4c79..1cd64f9e12e745 100644 --- a/drivers/net/virtio_net.c +++ b/drivers/net/virtio_net.c @@ -792,19 +792,32 @@ static unsigned int mergeable_ctx_to_truesize(void *mrg_ctx) return (unsigned long)mrg_ctx & ((1 << MRG_CTX_HEADER_SHIFT) - 1); } -static int check_mergeable_len(struct net_device *dev, void *mrg_ctx, - unsigned int len) +/* Length of the mergeable buffer that add_recvbuf_mergeable() posted. */ +static unsigned int mergeable_ctx_to_buflen(void *mrg_ctx) { - unsigned int headroom, tailroom, room, truesize; + unsigned int headroom, tailroom, room; - truesize = mergeable_ctx_to_truesize(mrg_ctx); headroom = mergeable_ctx_to_headroom(mrg_ctx); tailroom = headroom ? sizeof(struct skb_shared_info) : 0; room = SKB_DATA_ALIGN(headroom + tailroom); - if (len > truesize - room) { - pr_debug("%s: rx error: len %u exceeds truesize %lu\n", - dev->name, len, (unsigned long)(truesize - room)); + return mergeable_ctx_to_truesize(mrg_ctx) - room; +} + +/* Length of the small buffer that add_recvbuf_small() posts. */ +static unsigned int small_buflen(const struct virtnet_info *vi) +{ + return vi->hdr_len + GOOD_PACKET_LEN; +} + +static int check_mergeable_len(struct net_device *dev, void *mrg_ctx, + unsigned int len) +{ + unsigned int buflen = mergeable_ctx_to_buflen(mrg_ctx); + + if (len > buflen) { + pr_debug("%s: rx error: len %u exceeds buffer length %u\n", + dev->name, len, buflen); DEV_STATS_INC(dev, rx_length_errors); return -1; } @@ -1797,15 +1810,15 @@ static struct page *xdp_linearize_page(struct net_device *dev, p = virt_to_head_page(buf); off = buf - page_address(p); - if (rq->use_page_pool_dma) - page_pool_dma_sync_for_cpu(rq->page_pool, p, - off, buflen); - if (check_mergeable_len(dev, ctx, buflen)) { page_pool_put_page(rq->page_pool, p, -1, true); goto err_buf; } + if (rq->use_page_pool_dma) + page_pool_dma_sync_for_cpu(rq->page_pool, p, + off, buflen); + /* guard against a misconfigured or uncooperative backend that * is sending packet larger than the MTU. */ @@ -2165,15 +2178,15 @@ static int virtnet_build_xdp_buff_mrg(struct net_device *dev, page = virt_to_head_page(buf); offset = buf - page_address(page); - if (rq->use_page_pool_dma) - page_pool_dma_sync_for_cpu(rq->page_pool, page, - offset, len); - if (check_mergeable_len(dev, ctx, len)) { page_pool_put_page(rq->page_pool, page, -1, true); goto err; } + if (rq->use_page_pool_dma) + page_pool_dma_sync_for_cpu(rq->page_pool, page, + offset, len); + truesize = mergeable_ctx_to_truesize(ctx); xdp_frags_truesz += truesize; @@ -2446,15 +2459,15 @@ static struct sk_buff *receive_mergeable(struct net_device *dev, u64_stats_add(&stats->bytes, len); page = virt_to_head_page(buf); + if (check_mergeable_len(dev, ctx, len)) + goto err_skb; + if (rq->use_page_pool_dma) { offset = buf - page_address(page); page_pool_dma_sync_for_cpu(rq->page_pool, page, offset, len); } - if (check_mergeable_len(dev, ctx, len)) - goto err_skb; - truesize = mergeable_ctx_to_truesize(ctx); curr_skb = virtnet_skb_append_frag(rq, head_skb, curr_skb, page, buf, len, truesize); @@ -2574,12 +2587,22 @@ static void receive_buf(struct virtnet_info *vi, struct receive_queue *rq, /* Sync the memory before touching anything through buf, * unless virtio core did it already. + * + * len comes from the device and is checked against the buffer + * only later, so never sync past the buffer posted to the device. + * The sync still covers the header, which receive_buf() and the + * mergeable drop path read. Big buffers never come from the page + * pool, so a buffer here is either mergeable or small. */ if (rq->use_page_pool_dma) { struct page *page = virt_to_head_page(buf); int offset = buf - page_address(page); + unsigned int buflen = vi->mergeable_rx_bufs ? + mergeable_ctx_to_buflen(ctx) : + small_buflen(vi); - page_pool_dma_sync_for_cpu(rq->page_pool, page, offset, len); + page_pool_dma_sync_for_cpu(rq->page_pool, page, offset, + min(len, buflen)); } /* About the flags below: @@ -2655,7 +2678,7 @@ static int add_recvbuf_small(struct virtnet_info *vi, struct receive_queue *rq, buf += VIRTNET_RX_PAD + xdp_headroom; ctx = mergeable_len_to_ctx(alloc_len, xdp_headroom); - err = virtnet_rq_submit(rq, buf, vi->hdr_len + GOOD_PACKET_LEN, ctx, gfp); + err = virtnet_rq_submit(rq, buf, small_buflen(vi), ctx, gfp); if (err < 0) page_pool_put_page(rq->page_pool, virt_to_head_page(buf), -1, false); @@ -6017,7 +6040,8 @@ static int virtnet_xsk_pool_disable(struct net_device *dev, u16 qid) struct send_queue *sq; int err; - if (qid >= vi->curr_queue_pairs) + /* Removing XDP can leave the pool on a queue above curr_queue_pairs */ + if (qid >= vi->max_queue_pairs) return -EINVAL; sq = &vi->sq[qid]; diff --git a/drivers/net/wireless/ath/ath10k/core.c b/drivers/net/wireless/ath/ath10k/core.c index a749ae582b0a49..7c2939cbde5f05 100644 --- a/drivers/net/wireless/ath/ath10k/core.c +++ b/drivers/net/wireless/ath/ath10k/core.c @@ -2985,7 +2985,6 @@ int ath10k_core_start(struct ath10k *ar, enum ath10k_firmware_mode mode, clear_bit(ATH10K_FLAG_CRASH_FLUSH, &ar->dev_flags); ar->running_fw = fw; - ar->thermal.broken = false; if (!test_bit(ATH10K_FW_FEATURE_NON_BMI, ar->running_fw->fw_file.fw_features)) { diff --git a/drivers/net/wireless/ath/ath10k/thermal.c b/drivers/net/wireless/ath/ath10k/thermal.c index 9ff7de0abd1297..9bb486f8e92078 100644 --- a/drivers/net/wireless/ath/ath10k/thermal.c +++ b/drivers/net/wireless/ath/ath10k/thermal.c @@ -75,12 +75,6 @@ static ssize_t ath10k_thermal_show_temp(struct device *dev, goto out; } - /* Don't stall every read on firmware that never answers */ - if (ar->thermal.broken) { - ret = -EOPNOTSUPP; - goto out; - } - reinit_completion(&ar->thermal.wmi_sync); ret = ath10k_wmi_pdev_get_temperature(ar); if (ret) { @@ -96,8 +90,7 @@ static ssize_t ath10k_thermal_show_temp(struct device *dev, time_left = wait_for_completion_timeout(&ar->thermal.wmi_sync, ATH10K_THERMAL_SYNC_TIMEOUT_HZ); if (!time_left) { - ath10k_warn(ar, "failed to synchronize thermal read, not asking again until the firmware restarts\n"); - ar->thermal.broken = true; + ath10k_warn(ar, "failed to synchronize thermal read\n"); ret = -ETIMEDOUT; goto out; } diff --git a/drivers/net/wireless/ath/ath10k/thermal.h b/drivers/net/wireless/ath/ath10k/thermal.h index d1fb5b958c37c1..1f4de9fbf2b30b 100644 --- a/drivers/net/wireless/ath/ath10k/thermal.h +++ b/drivers/net/wireless/ath/ath10k/thermal.h @@ -19,8 +19,6 @@ struct ath10k_thermal { /* protected by conf_mutex */ u32 throttle_state; u32 quiet_period; - /* the running firmware did not answer a temperature request */ - bool broken; /* temperature value in Celsius degree * protected by data_lock */ diff --git a/drivers/net/wireless/ath/ath10k/wmi.c b/drivers/net/wireless/ath/ath10k/wmi.c index e57588c19c800c..67be6e8171cd7d 100644 --- a/drivers/net/wireless/ath/ath10k/wmi.c +++ b/drivers/net/wireless/ath/ath10k/wmi.c @@ -2512,7 +2512,7 @@ int ath10k_wmi_event_mgmt_tx_bundle_compl(struct ath10k *ar, struct sk_buff *skb for (i = 0; i < num_reports; i++) { memset(¶m, 0, sizeof(struct mgmt_tx_compl_params)); param.desc_id = __le32_to_cpu(arg.desc_ids[i]); - param.status = __le32_to_cpu(arg.desc_ids[i]); + param.status = __le32_to_cpu(arg.status[i]); if (test_bit(WMI_SERVICE_TX_DATA_ACK_RSSI, ar->wmi.svc_map)) param.ack_rssi = __le32_to_cpu(arg.ack_rssi[i]); diff --git a/drivers/net/wireless/ath/ath9k/ar9003_paprd.c b/drivers/net/wireless/ath/ath9k/ar9003_paprd.c index 6170e37d020577..17e28ad216cfa6 100644 --- a/drivers/net/wireless/ath/ath9k/ar9003_paprd.c +++ b/drivers/net/wireless/ath/ath9k/ar9003_paprd.c @@ -416,7 +416,8 @@ static inline int find_proper_scale(int expn, int N) #define NUM_BIN 23 -static bool create_pa_curve(u32 *data_L, u32 *data_U, u32 *pa_table, u16 *gain) +static noinline_for_stack bool +create_pa_curve(u32 *data_L, u32 *data_U, u32 *pa_table, u16 *gain) { unsigned int thresh_accum_cnt; int x_est[NUM_BIN + 1], Y[NUM_BIN + 1], theta[NUM_BIN + 1]; @@ -817,9 +818,10 @@ void ar9003_paprd_setup_gain_table(struct ath_hw *ah, int chain) } EXPORT_SYMBOL(ar9003_paprd_setup_gain_table); -static bool ar9003_paprd_retrain_pa_in(struct ath_hw *ah, - struct ath9k_hw_cal_data *caldata, - int chain) +static noinline_for_stack bool +ar9003_paprd_retrain_pa_in(struct ath_hw *ah, + struct ath9k_hw_cal_data *caldata, + int chain) { u32 *pa_in = caldata->pa_table[chain]; int capdiv_offset, quick_drop_offset; diff --git a/drivers/net/wireless/ath/ath9k/ath9k.h b/drivers/net/wireless/ath/ath9k/ath9k.h index e8635bf81f9d09..5c15b2e3cdcfbc 100644 --- a/drivers/net/wireless/ath/ath9k/ath9k.h +++ b/drivers/net/wireless/ath/ath9k/ath9k.h @@ -691,9 +691,6 @@ void ath9k_set_txpower(struct ath_softc *sc, struct ieee80211_vif *vif); #define ATH_DEFAULT_BINTVAL 100 /* TU */ #define ATH_DEFAULT_BMISS_LIMIT 10 -#define TSF_TO_TU(_h,_l) \ - ((((u32)(_h)) << 22) | (((u32)(_l)) >> 10)) - struct ath_beacon { enum { OK, /* no change needed */ diff --git a/drivers/net/wireless/ath/ath9k/beacon.c b/drivers/net/wireless/ath/ath9k/beacon.c index 4a27e3753c0367..8a9bd23d3d931e 100644 --- a/drivers/net/wireless/ath/ath9k/beacon.c +++ b/drivers/net/wireless/ath/ath9k/beacon.c @@ -308,7 +308,7 @@ static int ath9k_beacon_choose_slot(struct ath_softc *sc) struct ath_common *common = ath9k_hw_common(sc->sc_ah); struct ath_beacon_config *cur_conf = &sc->cur_chan->beacon; u16 intval; - u32 tsftu; + u32 offset; u64 tsf; int slot; @@ -322,11 +322,11 @@ static int ath9k_beacon_choose_slot(struct ath_softc *sc) intval = cur_conf->beacon_interval ? : ATH_DEFAULT_BINTVAL; tsf = ath9k_hw_gettsf64(sc->sc_ah); tsf += TU_TO_USEC(sc->sc_ah->config.sw_beacon_response_time); - tsftu = TSF_TO_TU((tsf * ATH_BCBUF) >>32, tsf * ATH_BCBUF); - slot = (tsftu % (intval * ATH_BCBUF)) / intval; + div_u64_rem(tsf, TU_TO_USEC(intval), &offset); + slot = offset * ATH_BCBUF / TU_TO_USEC(intval); - ath_dbg(common, BEACON, "slot: %d tsf: %llu tsftu: %u\n", - slot, tsf, tsftu / ATH_BCBUF); + ath_dbg(common, BEACON, "slot: %d tsf: %llu offset: %u\n", + slot, tsf, offset); return slot; } diff --git a/drivers/net/wireless/ath/ath9k/htc.h b/drivers/net/wireless/ath/ath9k/htc.h index 4d2b75d0212efa..59e0b3cf7f0f52 100644 --- a/drivers/net/wireless/ath/ath9k/htc.h +++ b/drivers/net/wireless/ath/ath9k/htc.h @@ -39,8 +39,6 @@ #define ATH_RESTART_CALINTERVAL 1200000 /* 20 minutes */ #define ATH_DEFAULT_BMISS_LIMIT 10 -#define TSF_TO_TU(_h, _l) \ - ((((u32)(_h)) << 22) | (((u32)(_l)) >> 10)) extern struct ieee80211_ops ath9k_htc_ops; extern int htc_modparam_nohwcrypt; diff --git a/drivers/net/wireless/ath/ath9k/htc_drv_beacon.c b/drivers/net/wireless/ath/ath9k/htc_drv_beacon.c index 81fa7cbad89213..b478af1502f2e6 100644 --- a/drivers/net/wireless/ath/ath9k/htc_drv_beacon.c +++ b/drivers/net/wireless/ath/ath9k/htc_drv_beacon.c @@ -266,20 +266,20 @@ static int ath9k_htc_choose_bslot(struct ath9k_htc_priv *priv, { struct ath_common *common = ath9k_hw_common(priv->ah); u64 tsf; - u32 tsftu; + u32 offset; u16 intval; int slot; intval = priv->cur_beacon_conf.beacon_interval; tsf = be64_to_cpu(swba->tsf); - tsftu = TSF_TO_TU(tsf >> 32, tsf); - slot = ((tsftu % intval) * ATH9K_HTC_MAX_BCN_VIF) / intval; + div_u64_rem(tsf, TU_TO_USEC(intval), &offset); + slot = (offset * ATH9K_HTC_MAX_BCN_VIF) / TU_TO_USEC(intval); slot = ATH9K_HTC_MAX_BCN_VIF - slot - 1; ath_dbg(common, BEACON, - "Choose slot: %d, tsf: %llu, tsftu: %u, intval: %u\n", - slot, tsf, tsftu, intval); + "Choose slot: %d, tsf: %llu, offset: %u, intval: %u\n", + slot, tsf, offset, intval); return slot; } diff --git a/drivers/net/wireless/ath/ath9k/wmi.c b/drivers/net/wireless/ath/ath9k/wmi.c index 44e91815a15943..520bb2347dfcd0 100644 --- a/drivers/net/wireless/ath/ath9k/wmi.c +++ b/drivers/net/wireless/ath/ath9k/wmi.c @@ -118,6 +118,8 @@ void ath9k_stop_wmi(struct ath9k_htc_priv *priv) mutex_lock(&wmi->op_mutex); wmi->stopped = true; mutex_unlock(&wmi->op_mutex); + + ath9k_wmi_event_drain(priv); } void ath9k_destroy_wmi(struct ath9k_htc_priv *priv) @@ -148,7 +150,8 @@ void ath9k_wmi_event_tasklet(struct tasklet_struct *t) /* Check if ath9k_init_device() completed. */ if (!smp_load_acquire(&priv->initialized)) { - tasklet_schedule(t); + if (!READ_ONCE(wmi->stopped)) + tasklet_schedule(t); return; } diff --git a/drivers/net/wireless/intel/iwlwifi/iwl-nvm-parse.c b/drivers/net/wireless/intel/iwlwifi/iwl-nvm-parse.c index 31badfa35f976b..8c166e0479ebb8 100644 --- a/drivers/net/wireless/intel/iwlwifi/iwl-nvm-parse.c +++ b/drivers/net/wireless/intel/iwlwifi/iwl-nvm-parse.c @@ -106,8 +106,6 @@ static const u16 iwl_unii9_nvm_channels[] = { #define IWL_NVM_NUM_CHANNELS_EXT 51 #define IWL_NVM_NUM_CHANNELS_UHB 110 #define IWL_NVM_NUM_CHANNELS_UNII9 ARRAY_SIZE(iwl_unii9_nvm_channels) -#define NUM_2GHZ_CHANNELS 14 -#define NUM_5GHZ_CHANNELS 37 #define FIRST_2GHZ_HT_MINUS 5 #define LAST_2GHZ_HT_PLUS 9 #define N_HW_ADDR_MASK 0xF @@ -280,7 +278,7 @@ static inline void iwl_nvm_print_channel_flags(struct device *dev, u32 level, CHECK_AND_PRINT_I(40MHZ), CHECK_AND_PRINT_I(80MHZ), CHECK_AND_PRINT_I(160MHZ), - CHECK_AND_PRINT_I(DC_HIGH), + CHECK_AND_PRINT_I(320MHZ), CHECK_AND_PRINT_I(VLP), CHECK_AND_PRINT_I(AFC)); #undef CHECK_AND_PRINT_I @@ -1632,6 +1630,8 @@ u32 iwl_nvm_get_regdom_bw_flags(const u16 *nvm_chan, flags |= NL80211_RRF_NO_80MHZ; if (!(nvm_flags & NVM_CHANNEL_160MHZ)) flags |= NL80211_RRF_NO_160MHZ; + if (!(nvm_flags & NVM_CHANNEL_320MHZ)) + flags |= NL80211_RRF_NO_320MHZ; if (!(nvm_flags & NVM_CHANNEL_ACTIVE)) flags |= NL80211_RRF_NO_IR; diff --git a/drivers/net/wireless/intel/iwlwifi/iwl-nvm-parse.h b/drivers/net/wireless/intel/iwlwifi/iwl-nvm-parse.h index 9ebb72d3726a5d..7b11682f5d45c1 100644 --- a/drivers/net/wireless/intel/iwlwifi/iwl-nvm-parse.h +++ b/drivers/net/wireless/intel/iwlwifi/iwl-nvm-parse.h @@ -10,6 +10,9 @@ #include "iwl-nvm-utils.h" #include "mei/iwl-mei.h" +#define NUM_2GHZ_CHANNELS 14 +#define NUM_5GHZ_CHANNELS 37 + /** * enum iwl_nvm_sbands_flags - modification flags for the channel profiles * @@ -82,7 +85,7 @@ struct iwl_reg_capa { * @NVM_CHANNEL_40MHZ: 40 MHz channel okay * @NVM_CHANNEL_80MHZ: 80 MHz channel okay * @NVM_CHANNEL_160MHZ: 160 MHz channel okay - * @NVM_CHANNEL_DC_HIGH: DC HIGH required/allowed (?) + * @NVM_CHANNEL_320MHZ: 320 MHz channel okay * @NVM_CHANNEL_VLP: client support connection to UHB VLP AP * @NVM_CHANNEL_AFC: client support connection to UHB AFC AP * @NVM_CHANNEL_VLP_AP_NOT_ALLOWED: UHB VLP AP not allowed, @@ -101,7 +104,7 @@ enum iwl_nvm_channel_flags { NVM_CHANNEL_40MHZ = BIT(9), NVM_CHANNEL_80MHZ = BIT(10), NVM_CHANNEL_160MHZ = BIT(11), - NVM_CHANNEL_DC_HIGH = BIT(12), + NVM_CHANNEL_320MHZ = BIT(12), NVM_CHANNEL_VLP = BIT(13), NVM_CHANNEL_AFC = BIT(14), NVM_CHANNEL_VLP_AP_NOT_ALLOWED = BIT(15), diff --git a/drivers/net/wireless/intel/iwlwifi/iwl-trans.c b/drivers/net/wireless/intel/iwlwifi/iwl-trans.c index 6ddf4945ed1c37..70effba46c1ca0 100644 --- a/drivers/net/wireless/intel/iwlwifi/iwl-trans.c +++ b/drivers/net/wireless/intel/iwlwifi/iwl-trans.c @@ -432,7 +432,6 @@ void iwl_trans_op_mode_leave(struct iwl_trans *trans) cancel_delayed_work_sync(&trans->restart.wk); trans->op_mode = NULL; - memset(&trans->conf, 0, sizeof(trans->conf)); trans->state = IWL_TRANS_NO_FW; } diff --git a/drivers/net/wireless/intel/iwlwifi/mvm/fw.c b/drivers/net/wireless/intel/iwlwifi/mvm/fw.c index ae109e3ea141c2..6cee41bb1ffbbb 100644 --- a/drivers/net/wireless/intel/iwlwifi/mvm/fw.c +++ b/drivers/net/wireless/intel/iwlwifi/mvm/fw.c @@ -1553,6 +1553,9 @@ static void iwl_mvm_lari_cfg(struct iwl_mvm *mvm) size_t cmd_size; int ret; + if (mvm->fw->ucode_ver < 26) + return; + /* * LARI_CONFIG_CHANGE triggers a profile update, so send * LARI_CONFIG_EXTENSION first to make sure its data is applied diff --git a/drivers/net/wireless/intel/iwlwifi/mvm/ops.c b/drivers/net/wireless/intel/iwlwifi/mvm/ops.c index 1832514573612e..3d35c922706fbd 100644 --- a/drivers/net/wireless/intel/iwlwifi/mvm/ops.c +++ b/drivers/net/wireless/intel/iwlwifi/mvm/ops.c @@ -1412,15 +1412,13 @@ iwl_op_mode_mvm_start(struct iwl_trans *trans, const struct iwl_rf_cfg *cfg, sizeof(mvm->hw->wiphy->fw_version), "%.31s", fw->fw_version); - trans->conf.fw_reset_handshake = - fw_has_capa(&mvm->fw->ucode_capa, - IWL_UCODE_TLV_CAPA_FW_RESET_HANDSHAKE); - - /* Those firmware versions claim to support the fw_reset_handshake + /* Some firmware versions claim to support the fw_reset_handshake * but they are buggy. */ - if (IWL_UCODE_MAJOR(mvm->fw->ucode_ver) <= 77) - trans->conf.fw_reset_handshake = false; + trans->conf.fw_reset_handshake = + fw_has_capa(&mvm->fw->ucode_capa, + IWL_UCODE_TLV_CAPA_FW_RESET_HANDSHAKE) && + mvm->fw->ucode_ver > 77; trans->conf.queue_alloc_cmd_ver = iwl_fw_lookup_cmd_ver(mvm->fw, diff --git a/drivers/net/wireless/intel/iwlwifi/mvm/rx.c b/drivers/net/wireless/intel/iwlwifi/mvm/rx.c index 8c197a090c2b1a..0be307ae92f6ce 100644 --- a/drivers/net/wireless/intel/iwlwifi/mvm/rx.c +++ b/drivers/net/wireless/intel/iwlwifi/mvm/rx.c @@ -257,7 +257,7 @@ static void iwl_mvm_rx_handle_tcm(struct iwl_mvm *mvm, ARRAY_SIZE(thresh_tpt))) return; thr = thresh_tpt[rate_n_flags & RATE_VHT_MCS_RATE_CODE_MSK]; - thr *= 1 + FIELD_GET(RATE_MCS_NSS_MSK, rate_n_flags); + thr *= 1 + FIELD_GET(RATE_VHT_MCS_NSS_MSK, rate_n_flags); } thr <<= ((rate_n_flags & RATE_MCS_CHAN_WIDTH_MSK_V1) >> @@ -502,7 +502,7 @@ void iwl_mvm_rx_rx_mpdu(struct iwl_mvm *mvm, struct napi_struct *napi, u8 stbc = (rate_n_flags & RATE_MCS_STBC_MSK) >> RATE_MCS_STBC_POS; rx_status->nss = - FIELD_GET(RATE_MCS_NSS_MSK, rate_n_flags) + 1; + FIELD_GET(RATE_VHT_MCS_NSS_MSK, rate_n_flags) + 1; rx_status->rate_idx = rate_n_flags & RATE_VHT_MCS_RATE_CODE_MSK; rx_status->encoding = RX_ENC_VHT; rx_status->enc_flags |= stbc << RX_ENC_FLAG_STBC_SHIFT; diff --git a/drivers/net/wireless/intel/iwlwifi/tests/nvm_parse.c b/drivers/net/wireless/intel/iwlwifi/tests/nvm_parse.c index 853911900bfd2f..5a50807e31817c 100644 --- a/drivers/net/wireless/intel/iwlwifi/tests/nvm_parse.c +++ b/drivers/net/wireless/intel/iwlwifi/tests/nvm_parse.c @@ -2,7 +2,7 @@ /* * KUnit tests for NVM parse * - * Copyright (C) 2025 Intel Corporation + * Copyright (C) 2025-2026 Intel Corporation */ #include #include @@ -12,7 +12,9 @@ MODULE_IMPORT_NS("EXPORTED_FOR_KUNIT_TESTING"); static const struct nvm_flag_case { const char *desc; + int ch_idx; u16 nvm_flags; + struct iwl_reg_capa reg_capa; u32 reg_rule_flags; u32 set_reg_rule_flags; u32 clear_reg_rule_flags; @@ -36,6 +38,20 @@ static const struct nvm_flag_case { .clear_reg_rule_flags = NL80211_RRF_ALLOW_6GHZ_VLP_AP | NL80211_RRF_NO_6GHZ_VLP_CLIENT, }, + { + .desc = "Allow 320 MHz on a 6 GHz channel that reports it", + .ch_idx = NUM_2GHZ_CHANNELS + NUM_5GHZ_CHANNELS, + .nvm_flags = NVM_CHANNEL_320MHZ, + .reg_capa = { .allow_320mhz = true, }, + .clear_reg_rule_flags = NL80211_RRF_NO_320MHZ, + }, + { + .desc = "Restrict 320 MHz on a 6 GHz channel without the bit", + .ch_idx = NUM_2GHZ_CHANNELS + NUM_5GHZ_CHANNELS, + .nvm_flags = 0, + .reg_capa = { .allow_320mhz = true, }, + .set_reg_rule_flags = NL80211_RRF_NO_320MHZ, + }, }; KUNIT_ARRAY_PARAM_DESC(nvm_flag, nvm_flag_cases, desc) @@ -43,11 +59,11 @@ KUNIT_ARRAY_PARAM_DESC(nvm_flag, nvm_flag_cases, desc) static void test_nvm_flags(struct kunit *test) { const struct nvm_flag_case *params = test->param_value; - struct iwl_reg_capa reg_capa = {}; u32 flags = 0; - flags = iwl_nvm_get_regdom_bw_flags(NULL, 0, params->nvm_flags, - reg_capa); + flags = iwl_nvm_get_regdom_bw_flags(NULL, params->ch_idx, + params->nvm_flags, + params->reg_capa); if ((params->set_reg_rule_flags & flags) != params->set_reg_rule_flags) KUNIT_FAIL(test, "Expected set bits:0x%08x flags:0x%08x\n", diff --git a/drivers/net/wireless/realtek/rtw89/coex.c b/drivers/net/wireless/realtek/rtw89/coex.c index 61e8b601ca3420..411c1490b03fc3 100644 --- a/drivers/net/wireless/realtek/rtw89/coex.c +++ b/drivers/net/wireless/realtek/rtw89/coex.c @@ -6604,7 +6604,8 @@ static void _set_wl_preagc_ctrl(struct rtw89_dev *rtwdev) if (!(bt->run_patch_code && bt->enable.now)) { is_preagc = BTC_PREAGC_DISABLE; - } else if (dm->tdd_bind.rf_band == BIT(RTW89_BAND_5G)) { + } else if (dm->out_of_band || + dm->tdd_bind.rf_band == BIT(RTW89_BAND_5G)) { is_preagc = BTC_PREAGC_DISABLE; } else if (rinfo->link_mode[RTW89_MAC_0] == BTC_WLINK_NOLINK || btc->cx.bt0.link_info.link_cnt.now == 0) { diff --git a/drivers/nvdimm/namespace_devs.c b/drivers/nvdimm/namespace_devs.c index 557fe0cb43e241..3aa0a9026efa8a 100644 --- a/drivers/nvdimm/namespace_devs.c +++ b/drivers/nvdimm/namespace_devs.c @@ -2031,6 +2031,7 @@ static struct device **scan_labels(struct nd_region *nd_region) static struct device **create_namespaces(struct nd_region *nd_region) { + struct nvdimm_bus *nvdimm_bus = walk_to_nvdimm_bus(&nd_region->dev); struct nd_mapping *nd_mapping; struct device **devs; int i; @@ -2038,10 +2039,16 @@ static struct device **create_namespaces(struct nd_region *nd_region) if (nd_region->ndr_mappings == 0) return NULL; - /* lock down all mappings while we scan labels */ + /* + * Lock down all mappings while we scan labels. A region can have + * more mappings than lockdep has subclasses, so nest the mapping + * locks under the bus lock rather than giving each its own subclass. + */ + lockdep_assert_held(&nvdimm_bus->reconfig_mutex); for (i = 0; i < nd_region->ndr_mappings; i++) { nd_mapping = &nd_region->mapping[i]; - mutex_lock_nested(&nd_mapping->lock, i); + mutex_lock_nest_lock(&nd_mapping->lock, + &nvdimm_bus->reconfig_mutex); } devs = scan_labels(nd_region); diff --git a/drivers/nvme/common/auth.c b/drivers/nvme/common/auth.c index e2e0c736540afd..1fdc4e4ed0b94d 100644 --- a/drivers/nvme/common/auth.c +++ b/drivers/nvme/common/auth.c @@ -489,17 +489,19 @@ int nvme_auth_parse_key(const char *secret, struct nvme_dhchap_key **ret_key) { struct nvme_dhchap_key *key; u8 key_hash; + int offset = 0; if (!secret) { *ret_key = NULL; return 0; } - if (sscanf(secret, "DHHC-1:%hhd:%*s:", &key_hash) != 1) + if (sscanf(secret, "DHHC-1:%hhd:%n", &key_hash, &offset) != 1 || + !offset) return -EINVAL; /* Pass in the secret without the 'DHHC-1:XX:' prefix */ - key = nvme_auth_extract_key(secret + 10, key_hash); + key = nvme_auth_extract_key(secret + offset, key_hash); if (IS_ERR(key)) { *ret_key = NULL; return PTR_ERR(key); diff --git a/drivers/nvme/host/auth.c b/drivers/nvme/host/auth.c index 85f005a5efd0aa..9a3da74dec5aa8 100644 --- a/drivers/nvme/host/auth.c +++ b/drivers/nvme/host/auth.c @@ -19,7 +19,6 @@ static struct kmem_cache *nvme_chap_buf_cache; static mempool_t *nvme_chap_buf_pool; struct nvme_dhchap_queue_context { - struct list_head entry; struct work_struct auth_work; struct nvme_ctrl *ctrl; struct crypto_kpp *dh_tfm; diff --git a/drivers/nvme/host/core.c b/drivers/nvme/host/core.c index f4aa02869b7904..f43582e5f6c4a9 100644 --- a/drivers/nvme/host/core.c +++ b/drivers/nvme/host/core.c @@ -3413,7 +3413,11 @@ static int nvme_init_subsystem(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id) return 0; out_put_subsystem: + if (!found) + list_del_init(&subsys->entry); + mutex_unlock(&nvme_subsystems_lock); nvme_put_subsystem(subsys); + return ret; out_unlock: mutex_unlock(&nvme_subsystems_lock); return ret; @@ -4378,24 +4382,16 @@ static void nvme_alloc_ns(struct nvme_ctrl *ctrl, struct nvme_ns_info *info) mutex_lock(&ctrl->subsys->lock); list_del_rcu(&ns->siblings); if (list_empty(&ns->head->list)) { - list_del_init(&ns->head->entry); - /* - * If multipath is not configured, we still create a namespace - * head (nshead), but head->disk is not initialized in that - * case. As a result, only a single reference to nshead is held - * (via kref_init()) when it is created. Therefore, ensure that - * we do not release the reference to nshead twice if head->disk - * is not present. - */ - if (ns->head->disk) - last_path = true; + if (!nvme_mpath_queue_if_no_path(ns->head)) + list_del_init(&ns->head->entry); + last_path = true; } mutex_unlock(&ctrl->subsys->lock); /* guarantee not available in head->list */ synchronize_srcu(&ns->head->srcu); if (last_path) - nvme_put_ns_head(ns->head); + nvme_mpath_remove_disk(ns->head); nvme_put_ns_head(ns->head); out_cleanup_disk: put_disk(disk); @@ -4730,6 +4726,11 @@ static void nvme_scan_work(struct work_struct *work) #endif } +static void nvme_ns_remove_async(void *data, async_cookie_t cookie) +{ + nvme_ns_remove(data); +} + /* * This function iterates the namespace list unlocked to allow recovery from * controller failure. It is up to the caller to ensure the namespace list is @@ -4739,6 +4740,7 @@ void nvme_remove_namespaces(struct nvme_ctrl *ctrl) { struct nvme_ns *ns, *next; LIST_HEAD(ns_list); + ASYNC_DOMAIN(domain); /* * make sure to requeue I/O to all namespaces as these @@ -4772,8 +4774,13 @@ void nvme_remove_namespaces(struct nvme_ctrl *ctrl) list_splice_init_srcu(&ctrl->namespaces, &ns_list, &ctrl->srcu); mutex_unlock(&ctrl->namespaces_lock); + /* + * Remove the namespaces in parallel, as each removal waits for several + * RCU grace periods. + */ list_for_each_entry_safe(ns, next, &ns_list, list) - nvme_ns_remove(ns); + async_schedule_domain(nvme_ns_remove_async, ns, &domain); + async_synchronize_full_domain(&domain); } EXPORT_SYMBOL_GPL(nvme_remove_namespaces); @@ -4903,7 +4910,7 @@ static void nvme_fw_act_work(struct work_struct *work) if (ctrl->mtfa) fw_act_timeout = jiffies + msecs_to_jiffies(ctrl->mtfa * 100); else - fw_act_timeout = jiffies + secs_to_jiffies(admin_timeout); + fw_act_timeout = jiffies + NVME_ADMIN_TIMEOUT; nvme_quiesce_io_queues(ctrl); while (nvme_ctrl_pp_status(ctrl)) { @@ -5195,6 +5202,15 @@ EXPORT_SYMBOL_GPL(nvme_start_ctrl); void nvme_uninit_ctrl(struct nvme_ctrl *ctrl) { nvme_stop_keep_alive(ctrl); + + /* + * An AER completion can queue async_event_work; drain it before the + * controller's final release. Note that ana_work has additional + * producers (namespace scanning via nvme_scan_work, and the failover + * path in nvme_failover_req), which is why nvme_mpath_uninit() + * separately cancels ana_work after this point. + */ + cancel_work_sync(&ctrl->async_event_work); nvme_hwmon_exit(ctrl); nvme_fault_inject_fini(&ctrl->fault_inject); dev_pm_qos_hide_latency_tolerance(ctrl->device); diff --git a/drivers/nvme/host/fabrics.c b/drivers/nvme/host/fabrics.c index 3d7ad86c1955ff..5ed91557f07065 100644 --- a/drivers/nvme/host/fabrics.c +++ b/drivers/nvme/host/fabrics.c @@ -872,12 +872,6 @@ static int nvmf_parse_options(struct nvmf_ctrl_options *opts, opts->fast_io_fail_tmo = token; break; case NVMF_OPT_HOSTNQN: - if (opts->host) { - pr_err("hostnqn already user-assigned: %s\n", - opts->host->nqn); - ret = -EADDRINUSE; - goto out; - } p = match_strdup(args); if (!p) { ret = -ENOMEM; @@ -1032,7 +1026,7 @@ static int nvmf_parse_options(struct nvmf_ctrl_options *opts, ret = -EINVAL; goto out; } - kfree(opts->dhchap_secret); + kfree_sensitive(opts->dhchap_secret); opts->dhchap_secret = p; break; case NVMF_OPT_DHCHAP_CTRL_SECRET: @@ -1047,7 +1041,7 @@ static int nvmf_parse_options(struct nvmf_ctrl_options *opts, ret = -EINVAL; goto out; } - kfree(opts->dhchap_ctrl_secret); + kfree_sensitive(opts->dhchap_ctrl_secret); opts->dhchap_ctrl_secret = p; break; case NVMF_OPT_TLS: diff --git a/drivers/nvme/host/fc.c b/drivers/nvme/host/fc.c index 0b9ff50d26ff30..2cbd744ffd22ad 100644 --- a/drivers/nvme/host/fc.c +++ b/drivers/nvme/host/fc.c @@ -39,7 +39,6 @@ struct nvme_fc_queue { size_t cmnd_capsule_len; u32 qnum; u32 rqcnt; - u32 seqno; u64 connection_id; atomic_t csn; diff --git a/drivers/nvme/host/multipath.c b/drivers/nvme/host/multipath.c index ae8059366b57d4..27facdbb3d4c03 100644 --- a/drivers/nvme/host/multipath.c +++ b/drivers/nvme/host/multipath.c @@ -1608,6 +1608,13 @@ int nvme_mpath_init_identify(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id) void nvme_mpath_uninit(struct nvme_ctrl *ctrl) { + /* + * ANA work can be queued by nvme_handle_aen_notice, nvme_scan_work, + * and nvme_failover_req. Drain remaining work before releasing the ANA + * resources. + */ + cancel_work_sync(&ctrl->ana_work); + kvfree(ctrl->ana_log_buf); ctrl->ana_log_buf = NULL; ctrl->ana_log_size = 0; diff --git a/drivers/nvme/host/nvme.h b/drivers/nvme/host/nvme.h index 8833a463f1c846..2543e52d6358a6 100644 --- a/drivers/nvme/host/nvme.h +++ b/drivers/nvme/host/nvme.h @@ -22,11 +22,20 @@ extern const struct pr_ops nvme_pr_ops; +/* Seconds to jiffies, capped for the u32 timeouts and timer delays */ +static inline unsigned int nvme_timeout_to_jiffies(unsigned int timeout) +{ + unsigned long max_secs; + + max_secs = min_t(unsigned long, UINT_MAX, MAX_JIFFY_OFFSET) / HZ; + return min_t(unsigned long, timeout, max_secs) * HZ; +} + extern unsigned int nvme_io_timeout; -#define NVME_IO_TIMEOUT (nvme_io_timeout * HZ) +#define NVME_IO_TIMEOUT nvme_timeout_to_jiffies(nvme_io_timeout) extern unsigned int admin_timeout; -#define NVME_ADMIN_TIMEOUT (admin_timeout * HZ) +#define NVME_ADMIN_TIMEOUT nvme_timeout_to_jiffies(admin_timeout) #define NVME_DEFAULT_KATO 5 diff --git a/drivers/nvme/host/pci.c b/drivers/nvme/host/pci.c index f8088d5aa724cd..076603df01abbb 100644 --- a/drivers/nvme/host/pci.c +++ b/drivers/nvme/host/pci.c @@ -390,7 +390,6 @@ struct nvme_queue { unsigned long flags; #define NVMEQ_ENABLED 0 #define NVMEQ_SQ_CMB 1 -#define NVMEQ_DELETE_ERROR 2 #define NVMEQ_POLLED 3 __le32 *dbbuf_sq_db; __le32 *dbbuf_cq_db; @@ -2459,8 +2458,6 @@ static int nvme_create_queue(struct nvme_queue *nvmeq, int qid, bool polled) int result; u16 vector = 0; - clear_bit(NVMEQ_DELETE_ERROR, &nvmeq->flags); - /* * A queue's vector matches the queue identifier unless the controller * has only one vector available. @@ -3322,18 +3319,6 @@ static enum rq_end_io_ret nvme_del_queue_end(struct request *req, return RQ_END_IO_NONE; } -static enum rq_end_io_ret nvme_del_cq_end(struct request *req, - blk_status_t error, - const struct io_comp_batch *iob) -{ - struct nvme_queue *nvmeq = req->end_io_data; - - if (error) - set_bit(NVMEQ_DELETE_ERROR, &nvmeq->flags); - - return nvme_del_queue_end(req, error, iob); -} - static int nvme_delete_queue(struct nvme_queue *nvmeq, u8 opcode) { struct request_queue *q = nvmeq->dev->ctrl.admin_q; @@ -3348,10 +3333,7 @@ static int nvme_delete_queue(struct nvme_queue *nvmeq, u8 opcode) return PTR_ERR(req); nvme_init_request(req, &cmd); - if (opcode == nvme_admin_delete_cq) - req->end_io = nvme_del_cq_end; - else - req->end_io = nvme_del_queue_end; + req->end_io = nvme_del_queue_end; req->end_io_data = nvmeq; init_completion(&nvmeq->delete_done); @@ -4229,6 +4211,14 @@ static int nvme_suspend(struct device *dev) ret = nvme_set_host_mem(ndev, 0); if (ret < 0) goto unfreeze; + if (ret) { + /* + * The controller may still access the HMB. Shut it + * down instead, which forces a reset on resume. + */ + ret = nvme_disable_prepare_reset(ndev, true); + goto unfreeze; + } } ret = nvme_get_power_state(ctrl, &ndev->last_ps); @@ -4440,8 +4430,9 @@ static const struct pci_device_id nvme_id_table[] = { .driver_data = NVME_QUIRK_DISABLE_WRITE_ZEROES, }, { PCI_DEVICE(0x15b7, 0x2001), /* Sandisk Skyhawk */ .driver_data = NVME_QUIRK_DISABLE_WRITE_ZEROES, }, - { PCI_DEVICE(0x1d97, 0x2263), /* SPCC */ - .driver_data = NVME_QUIRK_DISABLE_WRITE_ZEROES, }, + { PCI_DEVICE(0x1d97, 0x2263), /* SPCC / Lexar NM610 */ + .driver_data = NVME_QUIRK_DISABLE_WRITE_ZEROES | + NVME_QUIRK_BOGUS_NID, }, { PCI_DEVICE(0x144d, 0xa80b), /* Samsung PM9B1 256G and 512G */ .driver_data = NVME_QUIRK_DISABLE_WRITE_ZEROES | NVME_QUIRK_BOGUS_NID, }, @@ -4501,8 +4492,6 @@ static const struct pci_device_id nvme_id_table[] = { .driver_data = NVME_QUIRK_NO_DEEPEST_PS, }, { PCI_DEVICE(0xc0a9, 0x540a), /* Crucial P2 */ .driver_data = NVME_QUIRK_BOGUS_NID, }, - { PCI_DEVICE(0x1d97, 0x2263), /* Lexar NM610 */ - .driver_data = NVME_QUIRK_BOGUS_NID, }, { PCI_DEVICE(0x1d97, 0x1d97), /* Lexar NM620 */ .driver_data = NVME_QUIRK_BOGUS_NID, }, { PCI_DEVICE(0x1d97, 0x2269), /* Lexar NM760 */ diff --git a/drivers/nvme/host/sysfs.c b/drivers/nvme/host/sysfs.c index 10018c6356b62e..35f871e3e0c0ae 100644 --- a/drivers/nvme/host/sysfs.c +++ b/drivers/nvme/host/sysfs.c @@ -618,8 +618,6 @@ static ssize_t nvme_ctrl_reconnect_delay_show(struct device *dev, { struct nvme_ctrl *ctrl = dev_get_drvdata(dev); - if (ctrl->opts->reconnect_delay == -1) - return sysfs_emit(buf, "off\n"); return sysfs_emit(buf, "%d\n", ctrl->opts->reconnect_delay); } @@ -634,6 +632,9 @@ static ssize_t nvme_ctrl_reconnect_delay_store(struct device *dev, if (err) return err; + if (!v || v > INT_MAX) + return -EINVAL; + ctrl->opts->reconnect_delay = v; return count; } @@ -849,10 +850,10 @@ static ssize_t dhchap_secret_store(struct device *dev, ret = nvme_auth_parse_key(dhchap_secret, &key); if (ret) { - kfree(dhchap_secret); + kfree_sensitive(dhchap_secret); return ret; } - kfree(opts->dhchap_secret); + kfree_sensitive(opts->dhchap_secret); opts->dhchap_secret = dhchap_secret; host_key = ctrl->host_key; mutex_lock(&ctrl->dhchap_auth_mutex); @@ -860,7 +861,7 @@ static ssize_t dhchap_secret_store(struct device *dev, mutex_unlock(&ctrl->dhchap_auth_mutex); nvme_auth_free_key(host_key); } else - kfree(dhchap_secret); + kfree_sensitive(dhchap_secret); /* Start re-authentication */ dev_info(ctrl->device, "re-authenticating controller\n"); queue_work(nvme_wq, &ctrl->dhchap_auth_work); @@ -906,10 +907,10 @@ static ssize_t dhchap_ctrl_secret_store(struct device *dev, ret = nvme_auth_parse_key(dhchap_secret, &key); if (ret) { - kfree(dhchap_secret); + kfree_sensitive(dhchap_secret); return ret; } - kfree(opts->dhchap_ctrl_secret); + kfree_sensitive(opts->dhchap_ctrl_secret); opts->dhchap_ctrl_secret = dhchap_secret; ctrl_key = ctrl->ctrl_key; mutex_lock(&ctrl->dhchap_auth_mutex); @@ -917,7 +918,7 @@ static ssize_t dhchap_ctrl_secret_store(struct device *dev, mutex_unlock(&ctrl->dhchap_auth_mutex); nvme_auth_free_key(ctrl_key); } else - kfree(dhchap_secret); + kfree_sensitive(dhchap_secret); /* Start re-authentication */ dev_info(ctrl->device, "re-authenticating controller\n"); queue_work(nvme_wq, &ctrl->dhchap_auth_work); diff --git a/drivers/nvme/host/tcp.c b/drivers/nvme/host/tcp.c index 7ecc6c007f8d4f..62a594b8ab9bfa 100644 --- a/drivers/nvme/host/tcp.c +++ b/drivers/nvme/host/tcp.c @@ -77,6 +77,12 @@ MODULE_PARM_DESC(tls_handshake_timeout, /* TLS records read while waiting for the ICResp, the ICResp included */ #define NVME_TCP_ICRESP_MAX_RECORDS 8 +/* control message buffer for the TLS record type */ +union nvme_tcp_tls_cmsg { + struct cmsghdr cmsg; + u8 buf[CMSG_SPACE(sizeof(u8))]; +}; + static int nvme_tcp_cpu_queues[NR_CPUS]; static DEFINE_SPINLOCK(nvme_tcp_cpu_queues_lock); @@ -117,6 +123,7 @@ enum nvme_tcp_queue_flags { NVME_TCP_Q_LIVE = 1, NVME_TCP_Q_POLLING = 2, NVME_TCP_Q_IO_CPU_SET = 3, + NVME_TCP_Q_TLS_RECORD = 4, }; #define NVME_TCP_OPT_NR_QUEUES(opts) ((opts)->nr_io_queues + \ @@ -847,7 +854,7 @@ static int nvme_tcp_handle_r2t(struct nvme_tcp_queue *queue, return -EPROTO; } - if (unlikely(r2t_offset < req->data_sent)) { + if (unlikely(r2t_offset != req->data_sent)) { dev_err(queue->ctrl->ctrl.device, "req %d unexpected r2t offset %u (expected %zu)\n", rq->tag, r2t_offset, req->data_sent); @@ -1444,6 +1451,8 @@ static int nvme_tcp_try_send(struct nvme_tcp_queue *queue) return ret; } +static int nvme_tcp_recv_tls_record(struct nvme_tcp_queue *queue); + static int nvme_tcp_try_recv(struct nvme_tcp_queue *queue) { struct socket *sock = queue->sock; @@ -1456,10 +1465,31 @@ static int nvme_tcp_try_recv(struct nvme_tcp_queue *queue) lock_sock(sk); queue->nr_cqe = 0; consumed = sock->ops->read_sock(sk, &rd_desc, nvme_tcp_recv_skb); + /* + * kTLS cannot pass a TLS record without application data to + * nvme_tcp_recv_skb(). It returns -EINVAL and leaves the record at + * the head of the receive queue. recvmsg() takes the socket lock, + * so read the record without it. + */ + if (unlikely(consumed == -EINVAL && nvme_tcp_queue_tls(queue) && + queue->rd_enabled)) { + /* + * On a poll queue, nvme_tcp_poll() and nvme_tcp_io_work() can + * both get here for the same record. Only one of them reads it. + */ + if (test_and_set_bit(NVME_TCP_Q_TLS_RECORD, &queue->flags)) { + consumed = 0; + } else { + release_sock(sk); + consumed = nvme_tcp_recv_tls_record(queue); + lock_sock(sk); + clear_bit(NVME_TCP_Q_TLS_RECORD, &queue->flags); + } + } /* * nvme_tcp_recv_skb() handles its own errors, so a queue that is - * still enabled failed inside read_sock(). Handle it before - * release_sock() processes the backlog. + * still enabled failed inside read_sock() or while reading a TLS + * record. Handle it before release_sock() processes the backlog. */ if (unlikely(consumed < 0 && consumed != -EAGAIN && queue->rd_enabled)) { @@ -1623,54 +1653,125 @@ static int nvme_tcp_recv_tls_alert(struct nvme_tcp_queue *queue, } /* - * Discard a TLS record that arrived in place of the ICResp. A peer may send - * a NewSessionTicket as soon as the handshake completes. + * Read the rest of a TLS record whose first part was read into @msg. * - * Returns 0 when the record was discarded and the ICResp can be read, or a - * negative errno if the connection cannot continue. + * Returns the bytes read, or a negative errno. */ -static int nvme_tcp_skip_tls_record(struct nvme_tcp_queue *queue, - struct msghdr *msg, u8 ctype, int len) +static int nvme_tcp_drain_tls_record(struct nvme_tcp_queue *queue, + struct msghdr *msg, int flags) { u8 buf[NVME_TCP_TLS_REC_CHUNK]; - int ret; + int ret, drained = 0; - switch (ctype) { - case TLS_RECORD_TYPE_HANDSHAKE: - break; - case TLS_RECORD_TYPE_ALERT: - ret = nvme_tcp_recv_tls_alert(queue, msg, len); - return ret ? : -ENOTCONN; - default: - pr_err("queue %d: unhandled TLS record %u\n", - nvme_tcp_queue_id(queue), ctype); - return -ENOTCONN; - } - - /* the ICResp is in a later record, drain this one first */ while (!(msg->msg_flags & MSG_EOR)) { struct kvec iov = { .iov_base = buf, .iov_len = sizeof(buf), }; - char cbuf[CMSG_LEN(sizeof(char))] = {}; + union nvme_tcp_tls_cmsg u = {}; /* kTLS fails a control record read without a cmsg buffer */ struct msghdr drain = { - .msg_control = cbuf, - .msg_controllen = sizeof(cbuf), + .msg_control = &u, + .msg_controllen = sizeof(u), }; ret = kernel_recvmsg(queue->sock, &drain, &iov, 1, sizeof(buf), - 0); + flags); if (ret <= 0) { pr_warn("queue %d: failed to drain TLS record: %d\n", nvme_tcp_queue_id(queue), ret); return ret ? : -ECONNRESET; } + drained += ret; msg->msg_flags = drain.msg_flags; } - return 0; + return drained; +} + +/* + * Consume a TLS record without application data. The first @len bytes of + * the record were read into @msg and @data. + * + * A KeyUpdate needs new keys that nothing here can supply. Other handshake + * messages, such as a NewSessionTicket, are discarded. + * + * Returns the bytes read after the first @len, or a negative errno if the + * connection cannot continue. + */ +static int nvme_tcp_consume_tls_record(struct nvme_tcp_queue *queue, + struct msghdr *msg, u8 ctype, + const u8 *data, int len, int flags) +{ + int ret; + + switch (ctype) { + case TLS_RECORD_TYPE_HANDSHAKE: + if (data[0] == TLS_HANDSHAKE_KEYUPDATE) { + dev_err(queue->ctrl->ctrl.device, + "queue %d: TLS KeyUpdate is not supported\n", + nvme_tcp_queue_id(queue)); + return -EKEYEXPIRED; + } + break; + case TLS_RECORD_TYPE_ALERT: + ret = nvme_tcp_recv_tls_alert(queue, msg, len); + if (ret) + return ret; + break; + default: + dev_err(queue->ctrl->ctrl.device, + "queue %d: unexpected TLS record %u\n", + nvme_tcp_queue_id(queue), ctype); + return -EPROTO; + } + + return nvme_tcp_drain_tls_record(queue, msg, flags); +} + +/* + * Read the TLS record that read_sock() could not pass to + * nvme_tcp_recv_skb(). The caller must not hold the socket lock. + * + * Returns the bytes consumed, or a negative errno if the connection cannot + * continue. + */ +static int nvme_tcp_recv_tls_record(struct nvme_tcp_queue *queue) +{ + u8 buf[NVME_TCP_TLS_REC_CHUNK]; + union nvme_tcp_tls_cmsg u = {}; + struct kvec iov = { + .iov_base = buf, + .iov_len = sizeof(buf), + }; + struct msghdr msg = { + .msg_control = &u, + .msg_controllen = sizeof(u), + }; + int len, ret; + u8 ctype; + + len = kernel_recvmsg(queue->sock, &msg, &iov, 1, sizeof(buf), + MSG_DONTWAIT); + if (len <= 0) + goto fail; + + ctype = tls_get_record_type(queue->sock->sk, &u.cmsg); + ret = nvme_tcp_consume_tls_record(queue, &msg, ctype, buf, len, + MSG_DONTWAIT); + if (ret < 0) { + len = ret; + goto fail; + } + + return len + ret; + +fail: + /* read_sock() left a whole record, so none of it can be missing */ + if (len == -EAGAIN) + return -EPROTO; + + return len ? : -ECONNRESET; } /* @@ -1682,7 +1783,7 @@ static int nvme_tcp_skip_tls_record(struct nvme_tcp_queue *queue, static int nvme_tcp_recv_icresp(struct nvme_tcp_queue *queue, struct nvme_tcp_icresp_pdu *icresp) { - char cbuf[CMSG_LEN(sizeof(char))]; + union nvme_tcp_tls_cmsg u; struct msghdr msg; struct kvec iov; u8 ctype; @@ -1690,12 +1791,12 @@ static int nvme_tcp_recv_icresp(struct nvme_tcp_queue *queue, for (i = 0; i < NVME_TCP_ICRESP_MAX_RECORDS; i++) { memset(&msg, 0, sizeof(msg)); - memset(cbuf, 0, sizeof(cbuf)); + memset(&u, 0, sizeof(u)); iov.iov_base = icresp; iov.iov_len = sizeof(*icresp); if (nvme_tcp_queue_tls(queue)) { - msg.msg_control = cbuf; - msg.msg_controllen = sizeof(cbuf); + msg.msg_control = &u; + msg.msg_controllen = sizeof(u); } msg.msg_flags = MSG_WAITALL; ret = kernel_recvmsg(queue->sock, &msg, &iov, 1, @@ -1703,12 +1804,13 @@ static int nvme_tcp_recv_icresp(struct nvme_tcp_queue *queue, if (ret <= 0 || !nvme_tcp_queue_tls(queue)) return ret; - ctype = tls_get_record_type(queue->sock->sk, - (struct cmsghdr *)cbuf); + ctype = tls_get_record_type(queue->sock->sk, &u.cmsg); if (ctype == TLS_RECORD_TYPE_DATA) return ret; - ret = nvme_tcp_skip_tls_record(queue, &msg, ctype, ret); + /* the ICResp is in a later record */ + ret = nvme_tcp_consume_tls_record(queue, &msg, ctype, + (const u8 *)icresp, ret, 0); if (ret < 0) return ret; } @@ -1992,7 +2094,8 @@ static int nvme_tcp_start_tls(struct nvme_ctrl *nctrl, dev_err(nctrl->device, "queue %d: TLS handshake failed, error %d\n", qid, ret); - tls_handshake_cancel(queue->sock->sk); + if (!tls_handshake_cancel(queue->sock->sk)) + wait_for_completion(&queue->tls_complete); } else { if (queue->tls_err) { dev_err(nctrl->device, diff --git a/drivers/nvme/target/admin-cmd.c b/drivers/nvme/target/admin-cmd.c index f12d8309864464..e0be6eb0fa0447 100644 --- a/drivers/nvme/target/admin-cmd.c +++ b/drivers/nvme/target/admin-cmd.c @@ -176,16 +176,35 @@ static void nvmet_execute_get_log_page_error(struct nvmet_req *req) { struct nvmet_ctrl *ctrl = req->sq->ctrl; unsigned long flags; - off_t offset = 0; + u32 offset = 0; + u32 len; u64 slot; u64 i; + u16 status = 0; + + status = nvmet_zero_sgl(req, 0, req->transfer_len); + if (status) { + nvmet_req_complete(req, status); + return; + } + + len = min_t(u32, req->transfer_len, + NVMET_ERROR_LOG_SLOTS * sizeof(struct nvme_error_slot)); spin_lock_irqsave(&ctrl->error_lock, flags); + + /* + * The NVMe base specification requires the most recent error to be + * the first log entry, so walk the ring backwards from the slot of + * the last error and stop at the end of the requested buffer. + */ slot = ctrl->err_counter % NVMET_ERROR_LOG_SLOTS; - for (i = 0; i < NVMET_ERROR_LOG_SLOTS; i++) { - if (nvmet_copy_to_sgl(req, offset, &ctrl->slots[slot], - sizeof(struct nvme_error_slot))) + for (i = 0; i < NVMET_ERROR_LOG_SLOTS && + offset + sizeof(struct nvme_error_slot) <= len; i++) { + status = nvmet_copy_to_sgl(req, offset, &ctrl->slots[slot], + sizeof(struct nvme_error_slot)); + if (status) break; if (slot == 0) @@ -195,7 +214,7 @@ static void nvmet_execute_get_log_page_error(struct nvmet_req *req) offset += sizeof(struct nvme_error_slot); } spin_unlock_irqrestore(&ctrl->error_lock, flags); - nvmet_req_complete(req, 0); + nvmet_req_complete(req, status); } static void nvmet_execute_get_supported_log_pages(struct nvmet_req *req) @@ -221,7 +240,9 @@ static void nvmet_execute_get_supported_log_pages(struct nvmet_req *req) logs->lids[NVME_LOG_RMI] = cpu_to_le32(NVME_LIDS_LSUPP); logs->lids[NVME_LOG_RESERVATION] = cpu_to_le32(NVME_LIDS_LSUPP); - status = nvmet_copy_to_sgl(req, 0, logs, sizeof(*logs)); + status = nvmet_zero_sgl(req, 0, req->transfer_len); + if (!status) + status = nvmet_copy_to_sgl(req, 0, logs, sizeof(*logs)); kfree(logs); out: nvmet_req_complete(req, status); @@ -303,7 +324,7 @@ static void nvmet_execute_get_log_page_rmi(struct nvmet_req *req) goto out; } - if (req->transfer_len != sizeof(*log)) { + if (req->transfer_len < sizeof(*log)) { status = NVME_SC_SGL_INVALID_DATA | NVME_STATUS_DNR; goto out; } @@ -321,7 +342,9 @@ static void nvmet_execute_get_log_page_rmi(struct nvmet_req *req) else log->numa = cpu_to_le16(1); - status = nvmet_copy_to_sgl(req, 0, log, sizeof(*log)); + status = nvmet_zero_sgl(req, 0, req->transfer_len); + if (!status) + status = nvmet_copy_to_sgl(req, 0, log, sizeof(*log)); kfree(log); out: nvmet_req_complete(req, status); @@ -436,7 +459,9 @@ static void nvmet_execute_get_log_cmd_effects_ns(struct nvmet_req *req) goto free; } - status = nvmet_copy_to_sgl(req, 0, log, sizeof(*log)); + status = nvmet_zero_sgl(req, 0, req->transfer_len); + if (!status) + status = nvmet_copy_to_sgl(req, 0, log, sizeof(*log)); free: kfree(log); out: @@ -527,7 +552,9 @@ static void nvmet_execute_get_log_page_endgrp(struct nvmet_req *req) put_unaligned_le64(host_writes, &log->hwc[0]); put_unaligned_le64(data_units_written, &log->duw[0]); copy: - status = nvmet_copy_to_sgl(req, 0, log, sizeof(*log)); + status = nvmet_zero_sgl(req, 0, req->transfer_len); + if (!status) + status = nvmet_copy_to_sgl(req, 0, log, sizeof(*log)); kfree(log); out: nvmet_req_complete(req, status); @@ -610,7 +637,9 @@ static void nvmet_execute_get_log_page_features(struct nvmet_req *req) features->fis[NVME_FEAT_RESV_MASK] = cpu_to_le32(NVME_FIS_FSUPP | NVME_FIS_NSCPE); - status = nvmet_copy_to_sgl(req, 0, features, sizeof(*features)); + status = nvmet_zero_sgl(req, 0, req->transfer_len); + if (!status) + status = nvmet_copy_to_sgl(req, 0, features, sizeof(*features)); kfree(features); out: nvmet_req_complete(req, status); @@ -1223,6 +1252,7 @@ static u16 nvmet_set_feat_write_protect(struct nvmet_req *req) status = 0; break; default: + status = NVME_SC_INVALID_FIELD | NVME_STATUS_DNR; break; } diff --git a/drivers/nvme/target/auth.c b/drivers/nvme/target/auth.c index ccba84b1344e0f..a4a2a5cfd823f9 100644 --- a/drivers/nvme/target/auth.c +++ b/drivers/nvme/target/auth.c @@ -24,20 +24,26 @@ int nvmet_auth_set_key(struct nvmet_host *host, const char *secret, { unsigned char key_hash; char *dhchap_secret; + int offset = 0; if (!strlen(secret)) { + down_write(&nvmet_config_sem); if (set_ctrl) { kfree(host->dhchap_ctrl_secret); host->dhchap_ctrl_secret = NULL; host->dhchap_ctrl_key_hash = 0; + host->dhchap_ctrl_key_offset = 0; } else { kfree(host->dhchap_secret); host->dhchap_secret = NULL; host->dhchap_key_hash = 0; + host->dhchap_key_offset = 0; } + up_write(&nvmet_config_sem); return 0; } - if (sscanf(secret, "DHHC-1:%hhd:%*s", &key_hash) != 1) + if (sscanf(secret, "DHHC-1:%hhd:%n", &key_hash, &offset) != 1 || + !offset) return -EINVAL; if (key_hash > 3) { pr_warn("Invalid DH-HMAC-CHAP hash id %d\n", @@ -52,10 +58,12 @@ int nvmet_auth_set_key(struct nvmet_host *host, const char *secret, kfree(host->dhchap_ctrl_secret); host->dhchap_ctrl_secret = strim(dhchap_secret); host->dhchap_ctrl_key_hash = key_hash; + host->dhchap_ctrl_key_offset = offset; } else { kfree(host->dhchap_secret); host->dhchap_secret = strim(dhchap_secret); host->dhchap_key_hash = key_hash; + host->dhchap_key_offset = offset; } up_write(&nvmet_config_sem); return 0; @@ -76,8 +84,11 @@ int nvmet_setup_dhgroup(struct nvmet_ctrl *ctrl, u8 dhgroup_id) return 0; } crypto_free_kpp(ctrl->dh_tfm); + kfree_sensitive(ctrl->dh_key); ctrl->dh_tfm = NULL; ctrl->dh_gid = 0; + ctrl->dh_key = NULL; + ctrl->dh_keysize = 0; } if (dhgroup_id == NVME_AUTH_DHGROUP_NULL) @@ -95,38 +106,42 @@ int nvmet_setup_dhgroup(struct nvmet_ctrl *ctrl, u8 dhgroup_id) __func__, ctrl->cntlid, dhgroup_id, PTR_ERR(ctrl->dh_tfm)); ret = PTR_ERR(ctrl->dh_tfm); - ctrl->dh_tfm = NULL; - ctrl->dh_gid = 0; - } else { - ctrl->dh_gid = dhgroup_id; - pr_debug("%s: ctrl %d setup DH group %d\n", - __func__, ctrl->cntlid, ctrl->dh_gid); - ret = nvme_auth_gen_privkey(ctrl->dh_tfm, ctrl->dh_gid); - if (ret < 0) { - pr_debug("%s: ctrl %d failed to generate private key, err %d\n", - __func__, ctrl->cntlid, ret); - kfree_sensitive(ctrl->dh_key); - ctrl->dh_key = NULL; - return ret; - } - ctrl->dh_keysize = crypto_kpp_maxsize(ctrl->dh_tfm); - kfree_sensitive(ctrl->dh_key); - ctrl->dh_key = kzalloc(ctrl->dh_keysize, GFP_KERNEL); - if (!ctrl->dh_key) { - pr_warn("ctrl %d failed to allocate public key\n", - ctrl->cntlid); - return -ENOMEM; - } - ret = nvme_auth_gen_pubkey(ctrl->dh_tfm, ctrl->dh_key, - ctrl->dh_keysize); - if (ret < 0) { - pr_warn("ctrl %d failed to generate public key\n", - ctrl->cntlid); - kfree(ctrl->dh_key); - ctrl->dh_key = NULL; - } + goto err; + } + + ctrl->dh_gid = dhgroup_id; + pr_debug("%s: ctrl %d setup DH group %d\n", + __func__, ctrl->cntlid, ctrl->dh_gid); + ret = nvme_auth_gen_privkey(ctrl->dh_tfm, ctrl->dh_gid); + if (ret < 0) { + pr_debug("%s: ctrl %d failed to generate private key, err %d\n", + __func__, ctrl->cntlid, ret); + goto err; + } + ctrl->dh_keysize = crypto_kpp_maxsize(ctrl->dh_tfm); + ctrl->dh_key = kzalloc(ctrl->dh_keysize, GFP_KERNEL); + if (!ctrl->dh_key) { + pr_warn("ctrl %d failed to allocate public key\n", + ctrl->cntlid); + ret = -ENOMEM; + goto err; + } + ret = nvme_auth_gen_pubkey(ctrl->dh_tfm, ctrl->dh_key, + ctrl->dh_keysize); + if (ret < 0) { + pr_warn("ctrl %d failed to generate public key\n", + ctrl->cntlid); + goto err; } + return 0; +err: + kfree_sensitive(ctrl->dh_key); + ctrl->dh_key = NULL; + crypto_free_kpp(ctrl->dh_tfm); + ctrl->dh_tfm = NULL; + ctrl->dh_gid = 0; + ctrl->dh_keysize = 0; return ret; } @@ -177,14 +192,16 @@ u8 nvmet_setup_auth(struct nvmet_ctrl *ctrl, struct nvmet_sq *sq, bool reset) * Skip the 'DHHC-1:XX:' prefix. Keep the old keys until the new ones * are there: a controller without a host key needs no authentication. */ - host_key = nvme_auth_extract_key(host->dhchap_secret + 10, + host_key = nvme_auth_extract_key(host->dhchap_secret + + host->dhchap_key_offset, host->dhchap_key_hash); if (IS_ERR(host_key)) { ret = NVME_AUTH_DHCHAP_FAILURE_NOT_USABLE; goto out_unlock; } if (host->dhchap_ctrl_secret) { - ctrl_key = nvme_auth_extract_key(host->dhchap_ctrl_secret + 10, + ctrl_key = nvme_auth_extract_key(host->dhchap_ctrl_secret + + host->dhchap_ctrl_key_offset, host->dhchap_ctrl_key_hash); if (IS_ERR(ctrl_key)) { nvme_auth_free_key(host_key); diff --git a/drivers/nvme/target/configfs.c b/drivers/nvme/target/configfs.c index bde94656e4b743..27c50fa533e70e 100644 --- a/drivers/nvme/target/configfs.c +++ b/drivers/nvme/target/configfs.c @@ -42,7 +42,6 @@ static struct nvmet_type_name_map nvmet_transport[] = { }; static const struct nvmet_type_name_map nvmet_addr_family[] = { - { NVMF_ADDR_FAMILY_PCI, "pcie" }, { NVMF_ADDR_FAMILY_IP4, "ipv4" }, { NVMF_ADDR_FAMILY_IP6, "ipv6" }, { NVMF_ADDR_FAMILY_IB, "ib" }, @@ -68,7 +67,7 @@ static ssize_t nvmet_addr_adrfam_show(struct config_item *item, char *page) u8 adrfam = to_nvmet_port(item)->disc_addr.adrfam; int i; - for (i = 1; i < ARRAY_SIZE(nvmet_addr_family); i++) { + for (i = 0; i < ARRAY_SIZE(nvmet_addr_family); i++) { if (nvmet_addr_family[i].type == adrfam) return snprintf(page, PAGE_SIZE, "%s\n", nvmet_addr_family[i].name); @@ -86,7 +85,7 @@ static ssize_t nvmet_addr_adrfam_store(struct config_item *item, if (nvmet_is_port_enabled(port, __func__)) return -EACCES; - for (i = 1; i < ARRAY_SIZE(nvmet_addr_family); i++) { + for (i = 0; i < ARRAY_SIZE(nvmet_addr_family); i++) { if (sysfs_streq(page, nvmet_addr_family[i].name)) goto found; } @@ -709,7 +708,7 @@ static ssize_t nvmet_ns_ana_grpid_store(struct config_item *item, down_write(&nvmet_ana_sem); oldgrpid = ns->anagrpid; - newgrpid = array_index_nospec(newgrpid, NVMET_MAX_ANAGRPS); + newgrpid = array_index_nospec(newgrpid, NVMET_MAX_ANAGRPS + 1); nvmet_ana_group_enabled[newgrpid]++; ns->anagrpid = newgrpid; nvmet_ana_group_enabled[oldgrpid]--; @@ -2086,7 +2085,7 @@ static struct config_group *nvmet_ana_groups_make_group( grp->grpid = grpid; down_write(&nvmet_ana_sem); - grpid = array_index_nospec(grpid, NVMET_MAX_ANAGRPS); + grpid = array_index_nospec(grpid, NVMET_MAX_ANAGRPS + 1); nvmet_ana_group_enabled[grpid]++; up_write(&nvmet_ana_sem); diff --git a/drivers/nvme/target/fabrics-cmd.c b/drivers/nvme/target/fabrics-cmd.c index fc626c2fd2c924..6f0fc695e64992 100644 --- a/drivers/nvme/target/fabrics-cmd.c +++ b/drivers/nvme/target/fabrics-cmd.c @@ -216,6 +216,8 @@ static u16 nvmet_install_queue(struct nvmet_ctrl *ctrl, struct nvmet_req *req) if (old) { pr_warn("queue already connected!\n"); req->error_loc = offsetof(struct nvmf_connect_command, opcode); + req->sq->ctrl = NULL; + nvmet_ctrl_put(ctrl); return NVME_SC_CONNECT_CTRL_BUSY | NVME_STATUS_DNR; } @@ -242,6 +244,7 @@ static u16 nvmet_install_queue(struct nvmet_ctrl *ctrl, struct nvmet_req *req) err: req->sq->ctrl = NULL; + nvmet_cq_destroy(req->cq); return ret; } diff --git a/drivers/nvme/target/fc.c b/drivers/nvme/target/fc.c index 2b7dc3f03912d5..5d6c1c79508af0 100644 --- a/drivers/nvme/target/fc.c +++ b/drivers/nvme/target/fc.c @@ -27,7 +27,6 @@ struct nvmet_fc_tgt_assoc; struct nvmet_fc_ls_iod { /* for an LS RQST RCV */ struct nvmefc_ls_rsp *lsrsp; - struct nvmefc_tgt_fcp_req *fcpreq; /* only if RS */ struct list_head ls_rcv_list; /* tgtport->ls_rcv_list */ @@ -129,7 +128,6 @@ struct nvmet_fc_defer_fcp_req { }; struct nvmet_fc_tgt_queue { - bool ninetypercent; u16 qid; u16 sqsize; u16 ersp_ratio; @@ -818,8 +816,17 @@ nvmet_fc_alloc_target_queue(struct nvmet_fc_tgt_assoc *assoc, if (ret) goto out_fail_iodlist; - WARN_ON(assoc->queues[qid]); - assoc->queues[qid] = queue; + /* + * Publish the queue only if the slot is still free. A Create + * Connection may arrive twice for the same queue ID, or with the + * admin queue ID that was created by Create Association; replacing + * the old pointer would leak that queue and its controller + * reference forever. + */ + if (cmpxchg(&assoc->queues[qid], NULL, queue)) { + nvmet_sq_destroy(&queue->nvme_sq); + goto out_fail_iodlist; + } return queue; @@ -2076,7 +2083,6 @@ nvmet_fc_rcv_ls_req(struct nvmet_fc_target_port *target_port, } iod->lsrsp = lsrsp; - iod->fcpreq = NULL; memcpy(iod->rqstbuf, lsreqbuf, lsreqbuf_len); iod->rqstdatalen = lsreqbuf_len; iod->hosthandle = hosthandle; diff --git a/drivers/nvme/target/fcloop.c b/drivers/nvme/target/fcloop.c index b63af3b643a648..a9cde536c33ba1 100644 --- a/drivers/nvme/target/fcloop.c +++ b/drivers/nvme/target/fcloop.c @@ -379,6 +379,8 @@ fcloop_h2t_ls_req(struct nvme_fc_local_port *localport, ret = nvmet_fc_rcv_ls_req(rport->targetport, rport, &tls_req->ls_rsp, lsreq->rqstaddr, lsreq->rqstlen); + if (ret) + kmem_cache_free(lsreq_cache, tls_req); return ret; } diff --git a/drivers/nvme/target/io-cmd-file.c b/drivers/nvme/target/io-cmd-file.c index 695963dd932ee7..3098b902f51987 100644 --- a/drivers/nvme/target/io-cmd-file.c +++ b/drivers/nvme/target/io-cmd-file.c @@ -113,10 +113,23 @@ static void nvmet_file_io_done(struct kiocb *iocb, long ret) } if (unlikely(ret != req->transfer_len)) - status = errno_to_nvme_status(req, ret); + status = errno_to_nvme_status(req, ret < 0 ? ret : -EIO); nvmet_req_complete(req, status); } +static bool nvmet_file_check_lba_range(struct nvmet_req *req, u64 slba, + u64 len, loff_t *pos) +{ + u64 pos64; + + if (check_shl_overflow(slba, req->ns->blksize_shift, &pos64) || + pos64 > req->ns->size || len > req->ns->size - pos64) + return false; + + *pos = pos64; + return true; +} + static bool nvmet_file_execute_io(struct nvmet_req *req, int ki_flags) { ssize_t nr_bvec = req->sg_cnt; @@ -131,8 +144,9 @@ static bool nvmet_file_execute_io(struct nvmet_req *req, int ki_flags) if (req->f.mpool_alloc && nr_bvec > NVMET_MAX_MPOOL_BVEC) is_sync = true; - pos = le64_to_cpu(req->cmd->rw.slba) << req->ns->blksize_shift; - if (unlikely(pos + req->transfer_len > req->ns->size)) { + if (unlikely(!nvmet_file_check_lba_range(req, + le64_to_cpu(req->cmd->rw.slba), + req->transfer_len, &pos))) { ret = -ENOSPC; goto complete; } @@ -150,8 +164,11 @@ static bool nvmet_file_execute_io(struct nvmet_req *req, int ki_flags) if (unlikely(is_sync) && (nr_bvec - 1 == 0 || bv_cnt == NVMET_MAX_MPOOL_BVEC)) { ret = nvmet_file_submit_bvec(req, pos, bv_cnt, len, 0); - if (ret < 0) + if (ret != len) { + if (ret >= 0) + ret = -EIO; goto complete; + } pos += len; bv_cnt = 0; @@ -279,19 +296,22 @@ static void nvmet_file_execute_discard(struct nvmet_req *req) int i; for (i = 0; i <= le32_to_cpu(req->cmd->dsm.nr); i++) { + u64 len64; + status = nvmet_copy_from_sgl(req, i * sizeof(range), &range, sizeof(range)); if (status) break; - offset = le64_to_cpu(range.slba) << req->ns->blksize_shift; - len = le32_to_cpu(range.nlb); - len <<= req->ns->blksize_shift; - if (offset + len > req->ns->size) { + if (check_shl_overflow((u64)le32_to_cpu(range.nlb), + req->ns->blksize_shift, &len64) || + !nvmet_file_check_lba_range(req, le64_to_cpu(range.slba), + len64, &offset)) { req->error_slba = le64_to_cpu(range.slba); status = errno_to_nvme_status(req, -ENOSPC); break; } + len = len64; ret = vfs_fallocate(req->ns->file, mode, offset, len); if (ret && ret != -EOPNOTSUPP) { @@ -336,16 +356,17 @@ static void nvmet_file_write_zeroes_work(struct work_struct *w) int mode = FALLOC_FL_ZERO_RANGE | FALLOC_FL_KEEP_SIZE; loff_t offset; loff_t len; + u64 len64; int ret; - offset = le64_to_cpu(write_zeroes->slba) << req->ns->blksize_shift; - len = (((sector_t)le16_to_cpu(write_zeroes->length) + 1) << - req->ns->blksize_shift); - - if (unlikely(offset + len > req->ns->size)) { + if (check_shl_overflow((u64)le16_to_cpu(write_zeroes->length) + 1, + req->ns->blksize_shift, &len64) || + !nvmet_file_check_lba_range(req, le64_to_cpu(write_zeroes->slba), + len64, &offset)) { nvmet_req_complete(req, errno_to_nvme_status(req, -ENOSPC)); return; } + len = len64; ret = vfs_fallocate(req->ns->file, mode, offset, len); nvmet_req_complete(req, ret < 0 ? errno_to_nvme_status(req, ret) : 0); diff --git a/drivers/nvme/target/loop.c b/drivers/nvme/target/loop.c index 80b67608eb155e..d04be1f41d5229 100644 --- a/drivers/nvme/target/loop.c +++ b/drivers/nvme/target/loop.c @@ -159,6 +159,7 @@ static blk_status_t nvme_loop_queue_rq(struct blk_mq_hw_ctx *hctx, blk_rq_nr_phys_segments(req), iod->sg_table.sgl, NVME_INLINE_SG_CNT)) { nvme_cleanup_cmd(req); + nvmet_req_uninit(&iod->req); return BLK_STS_RESOURCE; } diff --git a/drivers/nvme/target/nvmet.h b/drivers/nvme/target/nvmet.h index 2c2460ef5e2b74..e33884a81efc9f 100644 --- a/drivers/nvme/target/nvmet.h +++ b/drivers/nvme/target/nvmet.h @@ -401,6 +401,8 @@ struct nvmet_host { struct config_group group; u8 *dhchap_secret; u8 *dhchap_ctrl_secret; + int dhchap_key_offset; + int dhchap_ctrl_key_offset; u8 dhchap_key_hash; u8 dhchap_ctrl_key_hash; u8 dhchap_hash_id; diff --git a/drivers/nvme/target/passthru.c b/drivers/nvme/target/passthru.c index 6b67880c7bb2fc..32ae4b6b59bf06 100644 --- a/drivers/nvme/target/passthru.c +++ b/drivers/nvme/target/passthru.c @@ -550,7 +550,6 @@ u16 nvmet_parse_passthru_admin_cmd(struct nvmet_req *req) default: return nvmet_passthru_get_set_features(req); } - break; case nvme_admin_get_features: switch (le32_to_cpu(req->cmd->features.fid)) { case NVME_FEAT_ASYNC_EVENT: @@ -564,7 +563,6 @@ u16 nvmet_parse_passthru_admin_cmd(struct nvmet_req *req) default: return nvmet_passthru_get_set_features(req); } - break; case nvme_admin_identify: switch (req->cmd->identify.cns) { case NVME_ID_CNS_CS_CTRL: diff --git a/drivers/nvme/target/pci-epf.c b/drivers/nvme/target/pci-epf.c index 670068d1ee3e36..4199fead04ff37 100644 --- a/drivers/nvme/target/pci-epf.c +++ b/drivers/nvme/target/pci-epf.c @@ -1432,8 +1432,6 @@ static u16 nvmet_pci_epf_delete_sq(struct nvmet_ctrl *tctrl, u16 sqid) destroy_workqueue(sq->iod_wq); sq->iod_wq = NULL; - nvmet_pci_epf_drain_queue(sq); - if (sq->nvme_sq.ctrl) nvmet_sq_destroy(&sq->nvme_sq); diff --git a/drivers/nvme/target/pr.c b/drivers/nvme/target/pr.c index 14eaa99f98fa32..8c818f24815bdf 100644 --- a/drivers/nvme/target/pr.c +++ b/drivers/nvme/target/pr.c @@ -99,6 +99,12 @@ void nvmet_execute_get_log_page_resv(struct nvmet_req *req) u64 cur_count; u64 next_count; + status = nvmet_zero_sgl(req, 0, req->transfer_len); + if (status) { + nvmet_req_complete(req, status); + return; + } + mutex_lock(&log_mgr->lock); if (!kfifo_get(&log_mgr->log_queue, &log)) goto out; @@ -335,7 +341,7 @@ static u16 nvmet_pr_update_reg_attr(struct nvmet_pr *pr, return NVME_SC_SUCCESS; } - new = kmalloc_obj(*new, GFP_ATOMIC); + new = kmalloc_obj(*new, GFP_KERNEL); if (!new) return NVME_SC_INTERNAL; @@ -1040,7 +1046,7 @@ static int nvmet_pr_alloc_and_insert_pc_ref(struct nvmet_ns *ns, struct nvmet_pr_per_ctrl_ref *pc_ref; int ret; - pc_ref = kmalloc_obj(*pc_ref, GFP_ATOMIC); + pc_ref = kmalloc_obj(*pc_ref, GFP_KERNEL); if (!pc_ref) return -ENOMEM; diff --git a/drivers/nvme/target/tcp.c b/drivers/nvme/target/tcp.c index 5105317cc61e3c..8a2e0e056131b3 100644 --- a/drivers/nvme/target/tcp.c +++ b/drivers/nvme/target/tcp.c @@ -270,6 +270,30 @@ static inline bool nvmet_tcp_has_inline_data(struct nvmet_tcp_cmd *cmd) !cmd->rbytes_done; } +/* + * Check whether the SGL of @cmd carries in-capsule data that the host + * will send right after the command PDU. Only the offset form of the + * data block descriptor is in-capsule; a regular transport SGL is + * fetched through an R2T instead. + */ +static inline bool nvmet_tcp_sgl_is_inline(struct nvmet_tcp_cmd *cmd) +{ + struct nvme_sgl_desc *sgl = &cmd->req.cmd->common.dptr.sgl; + u32 len = le32_to_cpu(sgl->length); + + if (sgl->type != ((NVME_SGL_FMT_DATA_DESC << 4) | + NVME_SGL_FMT_OFFSET)) + return false; + + if (!nvme_is_write(cmd->req.cmd)) + return false; + + if (!len) + return false; + + return len <= cmd->req.port->inline_data_size; +} + static inline struct nvmet_tcp_cmd * nvmet_tcp_get_cmd(struct nvmet_tcp_queue *queue) { @@ -626,25 +650,19 @@ static void nvmet_tcp_queue_response(struct nvmet_req *req) struct nvmet_tcp_queue *queue = cmd->queue; enum nvmet_tcp_recv_state queue_state; struct nvmet_tcp_cmd *queue_cmd; - struct nvme_sgl_desc *sgl; - u32 len; /* Pairs with store_release in nvmet_prepare_receive_pdu() */ queue_state = smp_load_acquire(&queue->rcv_state); queue_cmd = READ_ONCE(queue->cmd); if (unlikely(cmd == queue_cmd)) { - sgl = &cmd->req.cmd->common.dptr.sgl; - len = le32_to_cpu(sgl->length); - /* - * Wait for inline data before processing the response. - * Avoid using helpers, this might happen before - * nvmet_req_init is completed. + * Wait for in-capsule data before processing the response. + * This can happen before nvmet_req_init() has completed, so + * only look at the SGL descriptor itself. */ if (queue_state == NVMET_TCP_RECV_PDU && - len && len <= cmd->req.port->inline_data_size && - nvme_is_write(cmd->req.cmd)) + nvmet_tcp_sgl_is_inline(cmd)) return; } @@ -982,7 +1000,6 @@ static int nvmet_tcp_handle_icreq(struct nvmet_tcp_queue *queue) static int nvmet_tcp_handle_req_failure(struct nvmet_tcp_queue *queue, struct nvmet_tcp_cmd *cmd, struct nvmet_req *req) { - size_t data_len = le32_to_cpu(req->cmd->common.dptr.sgl.length); int ret; /* @@ -992,8 +1009,7 @@ static int nvmet_tcp_handle_req_failure(struct nvmet_tcp_queue *queue, * otherwise we will need to prepare a buffer and receive the * stale data before continuing forward. */ - if (!nvme_is_write(cmd->req.cmd) || !data_len || - data_len > cmd->req.port->inline_data_size) { + if (!nvmet_tcp_sgl_is_inline(cmd)) { nvmet_prepare_receive_pdu(queue); return 0; } diff --git a/drivers/nvme/target/zns.c b/drivers/nvme/target/zns.c index 92f5c1435582ec..cea05b4bc7409c 100644 --- a/drivers/nvme/target/zns.c +++ b/drivers/nvme/target/zns.c @@ -108,7 +108,7 @@ void nvmet_execute_identify_ns_zns(struct nvmet_req *req) status = nvmet_req_find_ns(req); if (status) - goto done; + goto out; if (nvmet_ns_revalidate(req->ns)) { mutex_lock(&req->ns->subsys->lock); @@ -140,7 +140,6 @@ void nvmet_execute_identify_ns_zns(struct nvmet_req *req) mar--; id_zns->mar = cpu_to_le32(mar); -done: status = nvmet_copy_to_sgl(req, 0, id_zns, sizeof(*id_zns)); out: kfree(id_zns); diff --git a/drivers/pci/probe.c b/drivers/pci/probe.c index 9a178e0e5f7f46..89a7c52ac3e5b7 100644 --- a/drivers/pci/probe.c +++ b/drivers/pci/probe.c @@ -513,6 +513,7 @@ static void pci_read_bridge_windows(struct pci_dev *bridge) res.flags = IORESOURCE_BUS; res.start = FIELD_GET(PCI_SECONDARY_BUS_MASK, buses); res.end = FIELD_GET(PCI_SUBORDINATE_BUS_MASK, buses); + bridge->fw_sec_busnr = res.start; pci_info(bridge, "PCI bridge to %pR%s\n", &res, bridge->transparent ? " (subtractive decode)" : ""); diff --git a/drivers/pci/quirks.c b/drivers/pci/quirks.c index 7f1f47ea2ee415..4a02fc80755da8 100644 --- a/drivers/pci/quirks.c +++ b/drivers/pci/quirks.c @@ -5789,6 +5789,7 @@ static void quirk_no_imm_ready(struct pci_dev *dev) } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_SAMSUNG, 0xa80c, quirk_no_imm_ready); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_SAMSUNG, 0xa80d, quirk_no_imm_ready); +DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_SAMSUNG, 0xa80e, quirk_no_imm_ready); static void quirk_no_ext_tags(struct pci_dev *pdev) { diff --git a/drivers/perf/Kconfig b/drivers/perf/Kconfig index 245e7bb763b994..8cef4bdef76aec 100644 --- a/drivers/perf/Kconfig +++ b/drivers/perf/Kconfig @@ -117,7 +117,7 @@ config STARFIVE_STARLINK_PMU config ANDES_CUSTOM_PMU bool "Andes custom PMU support" - depends on ARCH_RENESAS && RISCV_ALTERNATIVE && RISCV_PMU_SBI + depends on ARCH_RENESAS && RISCV_PMU_SBI default y help The Andes cores implement the PMU overflow extension very diff --git a/drivers/phy/Kconfig b/drivers/phy/Kconfig index 105fbe408aa25b..d151c05297d7e5 100644 --- a/drivers/phy/Kconfig +++ b/drivers/phy/Kconfig @@ -93,6 +93,7 @@ config PHY_ECONET_PCIE config PHY_GOOGLE_USB tristate "Google Tensor SoC USB PHY driver" + depends on ARCH_GOOGLE || COMPILE_TEST select GENERIC_PHY depends on TYPEC help diff --git a/drivers/phy/broadcom/phy-bcm-ns2-usbdrd.c b/drivers/phy/broadcom/phy-bcm-ns2-usbdrd.c index bb4221fec01b59..dc3294f1f4f53c 100644 --- a/drivers/phy/broadcom/phy-bcm-ns2-usbdrd.c +++ b/drivers/phy/broadcom/phy-bcm-ns2-usbdrd.c @@ -2,6 +2,7 @@ // Copyright (C) 2017 Broadcom #include +#include #include #include #include @@ -337,7 +338,9 @@ static int ns2_drd_phy_probe(struct platform_device *pdev) if (ret < 0) driver->debounce_jiffies = msecs_to_jiffies(GPIO_DELAY); - INIT_DELAYED_WORK(&driver->wq_extcon, extcon_work); + ret = devm_delayed_work_autocancel(dev, &driver->wq_extcon, extcon_work); + if (ret) + return ret; driver->id_irq = gpiod_to_irq(driver->id_gpiod); if (driver->id_irq < 0) { diff --git a/drivers/phy/freescale/phy-fsl-imx8-mipi-dphy.c b/drivers/phy/freescale/phy-fsl-imx8-mipi-dphy.c index 24c8b077774762..2aa2898cd002cc 100644 --- a/drivers/phy/freescale/phy-fsl-imx8-mipi-dphy.c +++ b/drivers/phy/freescale/phy-fsl-imx8-mipi-dphy.c @@ -191,8 +191,7 @@ static int mixel_dphy_config_from_opts(struct phy *phy, unsigned long ref_clk = clk_get_rate(priv->phy_ref_clk); u32 lp_t, numerator, denominator; unsigned long long tmp; - u32 n; - int i; + int n, i; if (dphy_opts->hs_clk_rate > DATA_RATE_MAX_SPEED || dphy_opts->hs_clk_rate < DATA_RATE_MIN_SPEED) @@ -276,7 +275,7 @@ static int mixel_dphy_config_from_opts(struct phy *phy, cfg->mc_prg_hs_prepare = dphy_opts->clk_prepare > lp_t ? 1 : 0; /* hs_zero: formula from NXP BSP */ - n = (144 * (dphy_opts->hs_clk_rate / 1000000) - 47500) / 10000; + n = (144 * (int)(dphy_opts->hs_clk_rate / 1000000) - 47500) / 10000; cfg->m_prg_hs_zero = n < 1 ? 1 : n; /* clk_zero: formula from NXP BSP */ diff --git a/drivers/phy/freescale/phy-fsl-samsung-hdmi.c b/drivers/phy/freescale/phy-fsl-samsung-hdmi.c index aaa651abcbc614..d7418c2197c9b7 100644 --- a/drivers/phy/freescale/phy-fsl-samsung-hdmi.c +++ b/drivers/phy/freescale/phy-fsl-samsung-hdmi.c @@ -44,8 +44,6 @@ #define MHZ (1000UL * 1000UL) #endif -#define PHY_DEFAULT_RATE 74250000 - #define PHY_PLL_DIV_REGS_NUM 7 struct phy_config { @@ -491,6 +489,17 @@ static int fsl_samsung_hdmi_phy_configure(struct fsl_samsung_hdmi_phy *phy, return ret; } +static unsigned long phy_clk_recalc_rate(struct clk_hw *hw, + unsigned long parent_rate) +{ + struct fsl_samsung_hdmi_phy *phy = to_fsl_samsung_hdmi_phy(hw); + + if (!phy->cur_cfg) + return 74250000; + + return phy->cur_cfg->pixclk; +} + /* Helper function to lookup the available fractional-divider rate */ static const struct phy_config *fsl_samsung_hdmi_phy_lookup_rate(unsigned long rate) { @@ -511,14 +520,6 @@ static const struct phy_config *fsl_samsung_hdmi_phy_lookup_rate(unsigned long r &phy_pll_cfg[i] : &phy_pll_cfg[i+1]); } -static unsigned long phy_clk_recalc_rate(struct clk_hw *hw, - unsigned long parent_rate) -{ - struct fsl_samsung_hdmi_phy *phy = to_fsl_samsung_hdmi_phy(hw); - - return phy->cur_cfg->pixclk; -} - static void fsl_samsung_hdmi_calculate_phy(struct phy_config *cal_phy, unsigned long rate, u8 p, u16 m, u8 s) { @@ -639,7 +640,6 @@ static int phy_clk_register(struct fsl_samsung_hdmi_phy *phy) static int fsl_samsung_hdmi_phy_probe(struct platform_device *pdev) { - const struct phy_config *default_cfg; struct fsl_samsung_hdmi_phy *phy; int ret; @@ -664,23 +664,6 @@ static int fsl_samsung_hdmi_phy_probe(struct platform_device *pdev) return dev_err_probe(phy->dev, PTR_ERR(phy->refclk), "failed to get ref clk\n"); - /* - * Establish the rate reported by recalc_rate() before registering the - * clock. Otherwise CCF may skip the first set_rate() when it requests - * the assumed default rate, leaving the PHY unconfigured. - */ - ret = clk_prepare_enable(phy->refclk); - if (ret) - return dev_err_probe(phy->dev, ret, - "failed to enable ref clk\n"); - - default_cfg = fsl_samsung_hdmi_phy_lookup_rate(PHY_DEFAULT_RATE); - ret = fsl_samsung_hdmi_phy_configure(phy, default_cfg); - clk_disable_unprepare(phy->refclk); - if (ret) - return dev_err_probe(phy->dev, ret, - "failed to configure default rate\n"); - pm_runtime_get_noresume(phy->dev); pm_runtime_set_active(phy->dev); pm_runtime_enable(phy->dev); @@ -719,7 +702,7 @@ static int __maybe_unused fsl_samsung_hdmi_phy_suspend(struct device *dev) static int __maybe_unused fsl_samsung_hdmi_phy_resume(struct device *dev) { struct fsl_samsung_hdmi_phy *phy = dev_get_drvdata(dev); - int ret; + int ret = 0; ret = clk_prepare_enable(phy->apbclk); if (ret) { @@ -727,23 +710,11 @@ static int __maybe_unused fsl_samsung_hdmi_phy_resume(struct device *dev) return ret; } - if (!phy->cur_cfg) - return 0; - - ret = clk_prepare_enable(phy->refclk); - if (ret) { - dev_err(phy->dev, "failed to enable ref clk\n"); - goto disable_apbclk; - } - - ret = fsl_samsung_hdmi_phy_configure(phy, phy->cur_cfg); - clk_disable_unprepare(phy->refclk); - if (!ret) - return 0; + if (phy->cur_cfg) + ret = fsl_samsung_hdmi_phy_configure(phy, phy->cur_cfg); -disable_apbclk: - clk_disable_unprepare(phy->apbclk); return ret; + } static DEFINE_RUNTIME_DEV_PM_OPS(fsl_samsung_hdmi_phy_pm_ops, diff --git a/drivers/phy/ingenic/phy-ingenic-usb.c b/drivers/phy/ingenic/phy-ingenic-usb.c index f21c3727ad5951..b11dcdc7c66646 100644 --- a/drivers/phy/ingenic/phy-ingenic-usb.c +++ b/drivers/phy/ingenic/phy-ingenic-usb.c @@ -124,7 +124,6 @@ static int ingenic_usb_phy_exit(struct phy *phy) struct ingenic_usb_phy *priv = phy_get_drvdata(phy); clk_disable_unprepare(priv->clk); - regulator_disable(priv->vcc_supply); return 0; } diff --git a/drivers/phy/marvell/phy-mvebu-a3700-comphy.c b/drivers/phy/marvell/phy-mvebu-a3700-comphy.c index dfc7cf7093093c..63e46d4c72014e 100644 --- a/drivers/phy/marvell/phy-mvebu-a3700-comphy.c +++ b/drivers/phy/marvell/phy-mvebu-a3700-comphy.c @@ -1232,8 +1232,8 @@ static struct phy *mvebu_a3700_comphy_xlate(struct device *dev, return ERR_PTR(-EINVAL); } - lane->invert_tx = args->args[1] & BIT(0); - lane->invert_rx = args->args[1] & BIT(1); + lane->invert_tx = args->args_count > 1 && (args->args[1] & BIT(0)); + lane->invert_rx = args->args_count > 1 && (args->args[1] & BIT(1)); return phy; } diff --git a/drivers/phy/qualcomm/phy-qcom-qmp-pcie.c b/drivers/phy/qualcomm/phy-qcom-qmp-pcie.c index b9fe3ce942270c..85c04c50674391 100644 --- a/drivers/phy/qualcomm/phy-qcom-qmp-pcie.c +++ b/drivers/phy/qualcomm/phy-qcom-qmp-pcie.c @@ -5715,7 +5715,6 @@ static int qmp_pcie_init(struct phy *phy) struct qmp_pcie *qmp = phy_get_drvdata(phy); const struct qmp_phy_cfg *cfg = qmp->cfg; void __iomem *pcs = qmp->pcs; - bool skip_reset; int ret; /* @@ -5731,9 +5730,6 @@ static int qmp_pcie_init(struct phy *phy) qphy_checkbits(pcs, cfg->regs[QPHY_START_CTRL], SERDES_START | PCS_START) && qphy_checkbits(pcs, cfg->regs[QPHY_PCS_POWER_DOWN_CONTROL], cfg->pwrdn_ctrl); - skip_reset = qmp->skip_init && !qphy_checkbits(pcs, cfg->regs[QPHY_PCS_STATUS], - cfg->phy_status); - if (!qmp->skip_init && !cfg->tbls.serdes_num) { dev_err(qmp->dev, "Init sequence not available\n"); return -ENODATA; @@ -5757,16 +5753,14 @@ static int qmp_pcie_init(struct phy *phy) } } - if (!skip_reset) { - ret = reset_control_assert(qmp->nocsr_reset); - if (ret) { - dev_err(qmp->dev, "no-csr reset assert failed\n"); - goto err_assert_reset; - } - - usleep_range(200, 300); + ret = reset_control_assert(qmp->nocsr_reset); + if (ret) { + dev_err(qmp->dev, "no-csr reset assert failed\n"); + goto err_assert_reset; } + usleep_range(200, 300); + if (!qmp->skip_init) { ret = reset_control_bulk_deassert(cfg->num_resets, qmp->resets); if (ret) { @@ -5815,11 +5809,8 @@ static int qmp_pcie_power_on(struct phy *phy) void __iomem *pcs = qmp->pcs; void __iomem *status; unsigned int mask, val; - bool skip_reset; int ret; - skip_reset = qmp->skip_init && !qphy_checkbits(pcs, cfg->regs[QPHY_PCS_STATUS], - cfg->phy_status); /* * Write CSR register for PHY that doesn't support no_csr reset or has not * been initialized. @@ -5843,12 +5834,10 @@ static int qmp_pcie_power_on(struct phy *phy) if (ret) return ret; - if (!skip_reset) { - ret = reset_control_deassert(qmp->nocsr_reset); - if (ret) { - dev_err(qmp->dev, "no-csr reset deassert failed\n"); - goto err_disable_pipe_clk; - } + ret = reset_control_deassert(qmp->nocsr_reset); + if (ret) { + dev_err(qmp->dev, "no-csr reset deassert failed\n"); + goto err_disable_pipe_clk; } if (qmp->skip_init) diff --git a/drivers/phy/rockchip/phy-rockchip-inno-hdmi.c b/drivers/phy/rockchip/phy-rockchip-inno-hdmi.c index f5874cd674e6cc..5f055b85ad9b9a 100644 --- a/drivers/phy/rockchip/phy-rockchip-inno-hdmi.c +++ b/drivers/phy/rockchip/phy-rockchip-inno-hdmi.c @@ -1068,7 +1068,7 @@ static int inno_hdmi_phy_clk_register(struct inno_hdmi_phy *inno) return ret; } - ret = of_clk_add_provider(np, of_clk_src_simple_get, inno->phyclk); + ret = devm_of_clk_add_hw_provider(dev, of_clk_hw_simple_get, &inno->hw); if (ret) { dev_err(dev, "failed to register clock provider: %d\n", ret); return ret; @@ -1454,11 +1454,6 @@ static int inno_hdmi_phy_probe(struct platform_device *pdev) return PTR_ERR_OR_ZERO(phy_provider); } -static void inno_hdmi_phy_remove(struct platform_device *pdev) -{ - of_clk_del_provider(pdev->dev.of_node); -} - static const struct of_device_id inno_hdmi_phy_of_match[] = { { .compatible = "rockchip,rk3228-hdmi-phy", @@ -1472,7 +1467,6 @@ MODULE_DEVICE_TABLE(of, inno_hdmi_phy_of_match); static struct platform_driver inno_hdmi_phy_driver = { .probe = inno_hdmi_phy_probe, - .remove = inno_hdmi_phy_remove, .driver = { .name = "inno-hdmi-phy", .of_match_table = inno_hdmi_phy_of_match, diff --git a/drivers/phy/rockchip/phy-rockchip-naneng-combphy.c b/drivers/phy/rockchip/phy-rockchip-naneng-combphy.c index 51c7c8405244a2..01f9d8fff600bb 100644 --- a/drivers/phy/rockchip/phy-rockchip-naneng-combphy.c +++ b/drivers/phy/rockchip/phy-rockchip-naneng-combphy.c @@ -526,7 +526,8 @@ static void rk_combphy_common_cfg_ssc(struct rockchip_combphy_priv *priv, unsign val = FIELD_PREP(RK3568_PHYREG33_PLL_KVCO_MASK, RK3576_PHYREG33_PLL_KVCO_VALUE); - writel(val, priv->mmio + RK3568_PHYREG33); + rockchip_combphy_updatel(priv, RK3568_PHYREG33_PLL_KVCO_MASK, + val, RK3568_PHYREG33); } } diff --git a/drivers/phy/rockchip/phy-rockchip-snps-pcie3.c b/drivers/phy/rockchip/phy-rockchip-snps-pcie3.c index 5f517bab1aa425..0a962067376579 100644 --- a/drivers/phy/rockchip/phy-rockchip-snps-pcie3.c +++ b/drivers/phy/rockchip/phy-rockchip-snps-pcie3.c @@ -18,6 +18,9 @@ #include #include #include +#include + +#define RK_PCIE_SRAM_INIT_TIMEOUT_US (20 * USEC_PER_MSEC) /* Register for RK3568 */ #define GRF_PCIE30PHY_CON1 0x4 @@ -127,7 +130,7 @@ static int rockchip_p3phy_rk3568_init(struct rockchip_p3phy_priv *priv) ret = regmap_read_poll_timeout(priv->phy_grf, GRF_PCIE30PHY_STATUS0, reg, SRAM_INIT_DONE(reg), - 0, 500); + 1000, RK_PCIE_SRAM_INIT_TIMEOUT_US); if (ret) dev_err(&priv->phy->dev, "%s: lock failed 0x%x, check input refclk and power supply\n", __func__, reg); @@ -187,11 +190,11 @@ static int rockchip_p3phy_rk3588_init(struct rockchip_p3phy_priv *priv) ret = regmap_read_poll_timeout(priv->phy_grf, RK3588_PCIE3PHY_GRF_PHY0_STATUS1, reg, RK3588_SRAM_INIT_DONE(reg), - 0, 500); + 1000, RK_PCIE_SRAM_INIT_TIMEOUT_US); ret |= regmap_read_poll_timeout(priv->phy_grf, RK3588_PCIE3PHY_GRF_PHY1_STATUS1, reg, RK3588_SRAM_INIT_DONE(reg), - 0, 500); + 1000, RK_PCIE_SRAM_INIT_TIMEOUT_US); if (ret) dev_err(&priv->phy->dev, "lock failed 0x%x, check input refclk and power supply\n", reg); diff --git a/drivers/phy/samsung/phy-exynos5-usbdrd.c b/drivers/phy/samsung/phy-exynos5-usbdrd.c index 5a208a584b3b78..73fad570934f59 100644 --- a/drivers/phy/samsung/phy-exynos5-usbdrd.c +++ b/drivers/phy/samsung/phy-exynos5-usbdrd.c @@ -477,6 +477,7 @@ struct exynos5_usbdrd_phy_config { struct exynos5_usbdrd_phy_drvdata { const struct exynos5_usbdrd_phy_config *phy_cfg; + int n_phy_cfg; const struct exynos5_usbdrd_phy_tuning **phy_tunes; const struct phy_ops *phy_ops; const char * const *clk_names; @@ -1173,7 +1174,7 @@ static struct phy *exynos5_usbdrd_phy_xlate(struct device *dev, { struct exynos5_usbdrd_phy *phy_drd = dev_get_drvdata(dev); - if (WARN_ON(args->args[0] >= EXYNOS5_DRDPHYS_NUM)) + if (WARN_ON(args->args[0] >= phy_drd->drv_data->n_phy_cfg)) return ERR_PTR(-ENODEV); return phy_drd->phys[args->args[0]].phy; @@ -2020,6 +2021,7 @@ static const char * const exynos5_regulator_names[] = { static const struct exynos5_usbdrd_phy_drvdata exynos2200_usb32drd_phy = { .phy_cfg = phy_cfg_exynos2200, + .n_phy_cfg = ARRAY_SIZE(phy_cfg_exynos2200), .phy_ops = &exynos2200_usbdrd_phy_ops, .pmu_offset_usbdrd0_phy = EXYNOS2200_PHY_CTRL_USB20, .clk_names = exynos5_clk_names, @@ -2033,6 +2035,7 @@ static const struct exynos5_usbdrd_phy_drvdata exynos2200_usb32drd_phy = { static const struct exynos5_usbdrd_phy_drvdata exynos5420_usbdrd_phy = { .phy_cfg = phy_cfg_exynos5, + .n_phy_cfg = ARRAY_SIZE(phy_cfg_exynos5), .phy_ops = &exynos5_usbdrd_phy_ops, .pmu_offset_usbdrd0_phy = EXYNOS5_USBDRD_PHY_CONTROL, .pmu_offset_usbdrd1_phy = EXYNOS5420_USBDRD1_PHY_CONTROL, @@ -2046,6 +2049,7 @@ static const struct exynos5_usbdrd_phy_drvdata exynos5420_usbdrd_phy = { static const struct exynos5_usbdrd_phy_drvdata exynos5250_usbdrd_phy = { .phy_cfg = phy_cfg_exynos5, + .n_phy_cfg = ARRAY_SIZE(phy_cfg_exynos5), .phy_ops = &exynos5_usbdrd_phy_ops, .pmu_offset_usbdrd0_phy = EXYNOS5_USBDRD_PHY_CONTROL, .clk_names = exynos5_clk_names, @@ -2058,6 +2062,7 @@ static const struct exynos5_usbdrd_phy_drvdata exynos5250_usbdrd_phy = { static const struct exynos5_usbdrd_phy_drvdata exynos5433_usbdrd_phy = { .phy_cfg = phy_cfg_exynos5, + .n_phy_cfg = ARRAY_SIZE(phy_cfg_exynos5), .phy_ops = &exynos5_usbdrd_phy_ops, .pmu_offset_usbdrd0_phy = EXYNOS5_USBDRD_PHY_CONTROL, .pmu_offset_usbdrd1_phy = EXYNOS5433_USBHOST30_PHY_CONTROL, @@ -2071,6 +2076,7 @@ static const struct exynos5_usbdrd_phy_drvdata exynos5433_usbdrd_phy = { static const struct exynos5_usbdrd_phy_drvdata exynos7_usbdrd_phy = { .phy_cfg = phy_cfg_exynos5, + .n_phy_cfg = ARRAY_SIZE(phy_cfg_exynos5), .phy_ops = &exynos5_usbdrd_phy_ops, .pmu_offset_usbdrd0_phy = EXYNOS5_USBDRD_PHY_CONTROL, .clk_names = exynos5_clk_names, @@ -2083,6 +2089,7 @@ static const struct exynos5_usbdrd_phy_drvdata exynos7_usbdrd_phy = { static const struct exynos5_usbdrd_phy_drvdata exynos7870_usbdrd_phy = { .phy_cfg = phy_cfg_exynos7870, + .n_phy_cfg = ARRAY_SIZE(phy_cfg_exynos7870), .phy_tunes = exynos7870_tunes, .phy_ops = &exynos7870_usbdrd_phy_ops, .pmu_offset_usbdrd0_phy = EXYNOS5_USBDRD_PHY_CONTROL, @@ -2096,6 +2103,7 @@ static const struct exynos5_usbdrd_phy_drvdata exynos7870_usbdrd_phy = { static const struct exynos5_usbdrd_phy_drvdata exynos850_usbdrd_phy = { .phy_cfg = phy_cfg_exynos850, + .n_phy_cfg = ARRAY_SIZE(phy_cfg_exynos850), .phy_ops = &exynos850_usbdrd_phy_ops, .pmu_offset_usbdrd0_phy = EXYNOS5_USBDRD_PHY_CONTROL, .clk_names = exynos5_clk_names, @@ -2124,6 +2132,7 @@ static const struct exynos5_usbdrd_phy_tuning *exynos990_tunes[PTS_MAX] = { static const struct exynos5_usbdrd_phy_drvdata exynos990_usbdrd_phy = { .phy_cfg = phy_cfg_exynos850, + .n_phy_cfg = ARRAY_SIZE(phy_cfg_exynos850), .phy_ops = &exynos850_usbdrd_phy_ops, .phy_tunes = exynos990_tunes, .pmu_offset_usbdrd0_phy = EXYNOS990_PHY_CTRL_USB20, @@ -2660,6 +2669,7 @@ static const struct phy_ops exynosautov920_usb31drd_combo_ssphy_ops = { static const struct exynos5_usbdrd_phy_drvdata exynosautov920_usb31drd_combo_ssphy = { .phy_cfg = usb31drd_phy_cfg_exynosautov920, + .n_phy_cfg = ARRAY_SIZE(usb31drd_phy_cfg_exynosautov920), .phy_ops = &exynosautov920_usb31drd_combo_ssphy_ops, .pmu_offset_usbdrd0_phy = EXYNOSAUTOV920_PHY_CTRL_USB31, .clk_names = exynos5_clk_names, @@ -2690,6 +2700,7 @@ exynos5_usbdrd_phy_config usbdrd_hsphy_cfg_exynosautov920[] = { static const struct exynos5_usbdrd_phy_drvdata exynosautov920_usbdrd_combo_hsphy = { .phy_cfg = usbdrd_hsphy_cfg_exynosautov920, + .n_phy_cfg = ARRAY_SIZE(usbdrd_hsphy_cfg_exynosautov920), .phy_ops = &exynosautov920_usbdrd_combo_hsphy_ops, .pmu_offset_usbdrd0_phy = EXYNOSAUTOV920_PHY_CTRL_USB20, .clk_names = exynos5_clk_names, @@ -2718,6 +2729,7 @@ static const struct exynos5_usbdrd_phy_config phy_cfg_exynosautov920[] = { static const struct exynos5_usbdrd_phy_drvdata exynosautov920_usbdrd_phy = { .phy_cfg = phy_cfg_exynosautov920, + .n_phy_cfg = ARRAY_SIZE(phy_cfg_exynosautov920), .phy_ops = &exynosautov920_usbdrd_phy_ops, .pmu_offset_usbdrd0_phy = EXYNOSAUTOV920_PHY_CTRL_USB20, .clk_names = exynos5_clk_names, @@ -2894,6 +2906,7 @@ static const char * const gs101_regulator_names[] = { static const struct exynos5_usbdrd_phy_drvdata gs101_usbd31rd_phy = { .phy_cfg = phy_cfg_gs101, + .n_phy_cfg = ARRAY_SIZE(phy_cfg_gs101), .phy_tunes = gs101_tunes, .phy_ops = &gs101_usbdrd_phy_ops, .pmu_offset_usbdrd0_phy = GS101_PHY_CTRL_USB20, @@ -3049,7 +3062,7 @@ static int exynos5_usbdrd_phy_probe(struct platform_device *pdev) dev_vdbg(dev, "Creating usbdrd_phy phy\n"); - for (i = 0; i < EXYNOS5_DRDPHYS_NUM; i++) { + for (i = 0; i < drv_data->n_phy_cfg; i++) { struct phy *phy = devm_phy_create(dev, NULL, drv_data->phy_ops); if (IS_ERR(phy)) diff --git a/drivers/phy/ti/phy-ti-pipe3.c b/drivers/phy/ti/phy-ti-pipe3.c index c280e696fff96b..5badeebe3f0e2b 100644 --- a/drivers/phy/ti/phy-ti-pipe3.c +++ b/drivers/phy/ti/phy-ti-pipe3.c @@ -498,9 +498,12 @@ static int ti_pipe3_init(struct phy *x) { struct ti_pipe3 *phy = phy_get_drvdata(x); u32 val; - int ret = 0; + int ret; + + ret = ti_pipe3_enable_clocks(phy); + if (ret) + return ret; - ti_pipe3_enable_clocks(phy); /* * Set pcie_pcs register to 0x96 for proper functioning of phy * as recommended in AM572x TRM SPRUHZ6, section 18.5.2.2, table @@ -515,6 +518,8 @@ static int ti_pipe3_init(struct phy *x) val = 0x96 << OMAP_CTRL_PCIE_PCS_DELAY_COUNT_SHIFT; ret = regmap_update_bits(phy->pcs_syscon, phy->pcie_pcs_reg, PCIE_PCS_MASK, val); + if (ret) + ti_pipe3_disable_clocks(phy); return ret; } @@ -552,8 +557,10 @@ static int ti_pipe3_exit(struct phy *x) /* If dpll_reset_syscon is not present we wont power down SATA DPLL * due to Errata i783 */ - if (phy->mode == PIPE3_MODE_SATA && !phy->dpll_reset_syscon) + if (phy->mode == PIPE3_MODE_SATA && !phy->dpll_reset_syscon) { + ti_pipe3_disable_clocks(phy); return 0; + } /* PCIe doesn't have internal DPLL */ if (phy->mode != PIPE3_MODE_PCIE) { @@ -605,14 +612,20 @@ static int ti_pipe3_get_clk(struct ti_pipe3 *phy) struct clk *clk; struct device *dev = phy->dev; - phy->refclk = devm_clk_get(dev, "refclk"); + /* + * refclk is optional for SATA PHY to support older DTBs, but + * required for other modes. Use devm_clk_get_optional() for SATA + * which returns NULL for -ENOENT, allowing us to propagate all + * other errors including -EPROBE_DEFER. + */ + if (phy->mode == PIPE3_MODE_SATA) + phy->refclk = devm_clk_get_optional(dev, "refclk"); + else + phy->refclk = devm_clk_get(dev, "refclk"); + if (IS_ERR(phy->refclk)) { - dev_err(dev, "unable to get refclk\n"); - /* older DTBs have missing refclk in SATA PHY - * so don't bail out in case of SATA PHY. - */ - if (phy->mode != PIPE3_MODE_SATA) - return PTR_ERR(phy->refclk); + return dev_err_probe(dev, PTR_ERR(phy->refclk), + "unable to get refclk\n"); } if (phy->mode != PIPE3_MODE_SATA) { @@ -628,8 +641,8 @@ static int ti_pipe3_get_clk(struct ti_pipe3 *phy) if (phy->mode != PIPE3_MODE_PCIE || phy->phy_power_syscon) { phy->sys_clk = devm_clk_get(dev, "sysclk"); if (IS_ERR(phy->sys_clk)) { - dev_err(dev, "unable to get sysclk\n"); - return -EINVAL; + return dev_err_probe(dev, PTR_ERR(phy->sys_clk), + "unable to get sysclk\n"); } } @@ -831,21 +844,39 @@ static int ti_pipe3_probe(struct platform_device *pdev) */ if (phy->mode == PIPE3_MODE_SATA) { if (!IS_ERR(phy->refclk)) { - clk_prepare_enable(phy->refclk); + ret = clk_prepare_enable(phy->refclk); + if (ret) { + dev_err(dev, "Failed to enable refclk %d\n", ret); + goto err_pm_disable; + } phy->sata_refclk_enabled = true; } } generic_phy = devm_phy_create(dev, NULL, &ops); - if (IS_ERR(generic_phy)) - return PTR_ERR(generic_phy); + if (IS_ERR(generic_phy)) { + ret = PTR_ERR(generic_phy); + goto err_clk_disable; + } phy_set_drvdata(generic_phy, phy); ti_pipe3_power_off(generic_phy); phy_provider = devm_of_phy_provider_register(dev, of_phy_simple_xlate); - return PTR_ERR_OR_ZERO(phy_provider); + if (IS_ERR(phy_provider)) { + ret = PTR_ERR(phy_provider); + goto err_clk_disable; + } + + return 0; + +err_clk_disable: + if (phy->sata_refclk_enabled) + clk_disable_unprepare(phy->refclk); +err_pm_disable: + pm_runtime_disable(dev); + return ret; } static void ti_pipe3_remove(struct platform_device *pdev) diff --git a/drivers/pinctrl/freescale/pinctrl-imx-scmi.c b/drivers/pinctrl/freescale/pinctrl-imx-scmi.c index 2cc3521f8df475..c62c6bff82abb1 100644 --- a/drivers/pinctrl/freescale/pinctrl-imx-scmi.c +++ b/drivers/pinctrl/freescale/pinctrl-imx-scmi.c @@ -354,7 +354,7 @@ static int scmi_pinctrl_imx_probe(struct scmi_device *sdev) } static const struct scmi_device_id scmi_id_table[] = { - { SCMI_PROTOCOL_PINCTRL, "pinctrl-imx" }, + { SCMI_PROTOCOL_PINCTRL, "pinctrl" }, { } }; MODULE_DEVICE_TABLE(scmi, scmi_id_table); diff --git a/drivers/pinctrl/mediatek/pinctrl-mtk-common-v2.c b/drivers/pinctrl/mediatek/pinctrl-mtk-common-v2.c index e01a782bbc3d6a..ca8782f9358ac5 100644 --- a/drivers/pinctrl/mediatek/pinctrl-mtk-common-v2.c +++ b/drivers/pinctrl/mediatek/pinctrl-mtk-common-v2.c @@ -399,8 +399,8 @@ int mtk_build_eint(struct mtk_pinctrl *hw, struct platform_device *pdev) for (i = hw->soc->nbase_names, j = 0; i < count_reg_names; i++, j++) { hw->eint->base[j] = of_iomap(np, i); - if (IS_ERR(hw->eint->base[j])) { - ret = PTR_ERR(hw->eint->base[j]); + if (!hw->eint->base[j]) { + ret = -ENOMEM; goto err_free_eint; } } diff --git a/drivers/pinctrl/pinctrl-ocelot.c b/drivers/pinctrl/pinctrl-ocelot.c index 4cf7b36cc0e410..c71ddcb24dbd54 100644 --- a/drivers/pinctrl/pinctrl-ocelot.c +++ b/drivers/pinctrl/pinctrl-ocelot.c @@ -2367,8 +2367,9 @@ static int ocelot_gpiochip_register(struct platform_device *pdev, gc->parent = &pdev->dev; gc->base = -1; gc->label = "ocelot-gpio"; + gc->can_sleep = regmap_might_sleep(info->map); - irq = platform_get_irq_optional(pdev, 0); + irq = gc->can_sleep ? 0 : platform_get_irq_optional(pdev, 0); if (irq > 0) { girq = &gc->irq; gpio_irq_chip_set_chip(girq, &ocelot_irqchip); @@ -2438,6 +2439,7 @@ static int ocelot_pinctrl_probe(struct platform_device *pdev) .reg_bits = 32, .val_bits = 32, .reg_stride = 4, + .use_raw_spinlock = true, }; info = devm_kzalloc_obj(dev, *info); diff --git a/drivers/pinctrl/pinctrl-scmi.c b/drivers/pinctrl/pinctrl-scmi.c index 43d5f3d54a8a0a..982c79bc77cc80 100644 --- a/drivers/pinctrl/pinctrl-scmi.c +++ b/drivers/pinctrl/pinctrl-scmi.c @@ -14,6 +14,7 @@ #include #include #include +#include #include #include @@ -127,11 +128,8 @@ static int pinctrl_scmi_map_pinconf_type(enum pin_config_param param, case PIN_CONFIG_INPUT_ENABLE: *type = SCMI_PIN_INPUT_MODE; break; - case PIN_CONFIG_INPUT_SCHMITT: - *type = SCMI_PIN_INPUT_SCHMITT; - break; case PIN_CONFIG_INPUT_SCHMITT_ENABLE: - *type = SCMI_PIN_INPUT_MODE; + *type = SCMI_PIN_INPUT_SCHMITT; break; case PIN_CONFIG_MODE_LOW_POWER: *type = SCMI_PIN_LOW_POWER_MODE; @@ -155,6 +153,15 @@ static int pinctrl_scmi_map_pinconf_type(enum pin_config_param param, return 0; } +static u32 pinctrl_scmi_map_pinconf_arg_get(enum pin_config_param param, + u32 value) +{ + if (param == PIN_CONFIG_DRIVE_STRENGTH) + return value / MILLI; + + return value; +} + static int pinctrl_scmi_map_pinconf_type_get(enum pin_config_param param, enum scmi_pinctrl_conf_type *type) { @@ -166,14 +173,36 @@ static int pinctrl_scmi_map_pinconf_type_get(enum pin_config_param param, return pinctrl_scmi_map_pinconf_type(param, type); } +static bool pinctrl_scmi_pinconf_arg_ignored(enum pin_config_param param) +{ + switch (param) { + case PIN_CONFIG_BIAS_BUS_HOLD: + case PIN_CONFIG_BIAS_DISABLE: + case PIN_CONFIG_BIAS_HIGH_IMPEDANCE: + case PIN_CONFIG_DRIVE_OPEN_DRAIN: + case PIN_CONFIG_DRIVE_OPEN_SOURCE: + case PIN_CONFIG_DRIVE_PUSH_PULL: + return true; + default: + return false; + } +} + static int pinctrl_scmi_map_pinconf_type_set(enum pin_config_param param, - enum scmi_pinctrl_conf_type *type) + enum scmi_pinctrl_conf_type *type, + u32 *arg) { if (param == PIN_CONFIG_LEVEL) { *type = SCMI_PIN_OUTPUT_VALUE; return 0; } + if (pinctrl_scmi_pinconf_arg_ignored(param)) + *arg = 1; + + if (param == PIN_CONFIG_DRIVE_STRENGTH) + *arg *= MILLI; + return pinctrl_scmi_map_pinconf_type(param, type); } @@ -203,6 +232,7 @@ static int pinctrl_scmi_pinconf_get(struct pinctrl_dev *pctldev, if (ret) return ret; + config_value = pinctrl_scmi_map_pinconf_arg_get(config_type, config_value); *config = pinconf_to_config_packed(config_type, config_value); return 0; @@ -267,12 +297,13 @@ static int pinctrl_scmi_pinconf_set(struct pinctrl_dev *pctldev, param = pinconf_to_config_param(configs[i]); if (param == PIN_CONFIG_PERSIST_STATE) continue; - ret = pinctrl_scmi_map_pinconf_type_set(param, &p_config_type[cnt]); + p_config_value[cnt] = pinconf_to_config_argument(configs[i]); + ret = pinctrl_scmi_map_pinconf_type_set(param, &p_config_type[cnt], + &p_config_value[cnt]); if (ret) { dev_err(pmx->dev, "Error map pinconf_type %d\n", ret); goto free_config; } - p_config_value[cnt] = pinconf_to_config_argument(configs[i]); cnt++; } @@ -310,13 +341,13 @@ static int pinctrl_scmi_pinconf_group_set(struct pinctrl_dev *pctldev, for (i = 0; i < num_configs; i++) { param = pinconf_to_config_param(configs[i]); - ret = pinctrl_scmi_map_pinconf_type_set(param, &p_config_type[i]); + p_config_value[i] = pinconf_to_config_argument(configs[i]); + ret = pinctrl_scmi_map_pinconf_type_set(param, &p_config_type[i], + &p_config_value[i]); if (ret) { dev_err(pmx->dev, "Error map pinconf_type %d\n", ret); goto free_config; } - - p_config_value[i] = pinconf_to_config_argument(configs[i]); } ret = pinctrl_ops->settings_conf(pmx->ph, group, GROUP_TYPE, @@ -359,6 +390,7 @@ static int pinctrl_scmi_pinconf_group_get(struct pinctrl_dev *pctldev, if (ret) return ret; + config_value = pinctrl_scmi_map_pinconf_arg_get(config_type, config_value); *config = pinconf_to_config_packed(config_type, config_value); return 0; diff --git a/drivers/pinctrl/qcom/pinctrl-kaanapali.c b/drivers/pinctrl/qcom/pinctrl-kaanapali.c index e95ac064b84ce8..e9351e29d38ed9 100644 --- a/drivers/pinctrl/qcom/pinctrl-kaanapali.c +++ b/drivers/pinctrl/qcom/pinctrl-kaanapali.c @@ -37,6 +37,7 @@ .mux_bit = 2, \ .pull_bit = 0, \ .drv_bit = 6, \ + .i2c_pull_bit = 13, \ .egpio_enable = 12, \ .egpio_present = 11, \ .oe_bit = 9, \ diff --git a/drivers/pinctrl/realtek/pinctrl-rtd.c b/drivers/pinctrl/realtek/pinctrl-rtd.c index df2850d73014b5..c2cc878b075dc6 100644 --- a/drivers/pinctrl/realtek/pinctrl-rtd.c +++ b/drivers/pinctrl/realtek/pinctrl-rtd.c @@ -438,7 +438,7 @@ static int rtd_pconf_parse_conf(struct rtd_pinctrl *data, sr_off = config_desc->base_bit + config_desc->slew_rate_offset; reg_off = config_desc->reg_offset; mask = 0x3 << sr_off; - val = arg << sr_off; + val = set_val << sr_off; break; case PIN_CONFIG_INPUT_VOLTAGE_UV: diff --git a/drivers/platform/raspberrypi/vchiq-interface/vchiq_arm.c b/drivers/platform/raspberrypi/vchiq-interface/vchiq_arm.c index dae1fc0fea2925..8823d9526fbeb2 100644 --- a/drivers/platform/raspberrypi/vchiq-interface/vchiq_arm.c +++ b/drivers/platform/raspberrypi/vchiq-interface/vchiq_arm.c @@ -1462,7 +1462,7 @@ static int __init vchiq_driver_init(void) return ret; } -module_init(vchiq_driver_init); +subsys_initcall(vchiq_driver_init); static void __exit vchiq_driver_exit(void) { diff --git a/drivers/ptp/ptp_vmclock.c b/drivers/ptp/ptp_vmclock.c index 7f25fe6c2ce2a8..3e32a90306616c 100644 --- a/drivers/ptp/ptp_vmclock.c +++ b/drivers/ptp/ptp_vmclock.c @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -51,6 +52,8 @@ struct vmclock_state { enum clocksource_ids cs_id, sys_cs_id; int index; char *name; + struct kref kref; + bool removed; }; #define VMCLOCK_MAX_WAIT ms_to_ktime(100) @@ -369,6 +372,9 @@ static int vmclock_miscdev_mmap(struct file *fp, struct vm_area_struct *vma) struct vmclock_file_state *fst = fp->private_data; struct vmclock_state *st = fst->st; + if (READ_ONCE(st->removed)) + return -ENODEV; + if ((vma->vm_flags & (VM_READ|VM_WRITE)) != VM_READ) return -EROFS; @@ -398,6 +404,9 @@ static ssize_t vmclock_miscdev_read(struct file *fp, char __user *buf, uint32_t seq, old_seq; size_t max_count; + if (READ_ONCE(st->removed)) + return -ENODEV; + if (*ppos >= PAGE_SIZE) return 0; @@ -450,6 +459,10 @@ static __poll_t vmclock_miscdev_poll(struct file *fp, poll_table *wait) poll_wait(fp, &st->disrupt_wait, wait); + /* After poll_wait(), so vmclock_remove()'s wake-up is not missed */ + if (READ_ONCE(st->removed)) + return EPOLLHUP | EPOLLERR; + seq = le32_to_cpu(st->clk->seq_count); if (atomic_read(&fst->seq) != seq) return POLLIN | POLLRDNORM; @@ -466,6 +479,12 @@ static int vmclock_miscdev_open(struct inode *inode, struct file *fp) if (!fst) return -ENOMEM; + /* + * misc_open() calls this with misc_mtx held, and vmclock_remove() + * calls misc_deregister(), which takes misc_mtx, before the device's + * own reference is dropped. + */ + kref_get(&st->kref); fst->st = st; atomic_set(&fst->seq, 0); @@ -474,9 +493,22 @@ static int vmclock_miscdev_open(struct inode *inode, struct file *fp) return 0; } +static void vmclock_free(struct kref *kref) +{ + struct vmclock_state *st = + container_of(kref, struct vmclock_state, kref); + + if (st->clk) + memunmap(st->clk); + kfree(st); +} + static int vmclock_miscdev_release(struct inode *inode, struct file *fp) { - kfree(fp->private_data); + struct vmclock_file_state *fst = fp->private_data; + + kref_put(&fst->st->kref, vmclock_free); + kfree(fst); return 0; } @@ -649,9 +681,20 @@ static void vmclock_remove(void *data) if (st->miscdev.minor != MISC_DYNAMIC_MINOR) misc_deregister(&st->miscdev); + /* Files still open now fail, and a poll() in progress returns */ + WRITE_ONCE(st->removed, true); + wake_up_interruptible_all(&st->disrupt_wait); + dev->driver_data = NULL; } +static void vmclock_put(void *data) +{ + struct vmclock_state *st = data; + + kref_put(&st->kref, vmclock_free); +} + static void vmclock_put_idx(void *data) { struct vmclock_state *st = data; @@ -665,9 +708,15 @@ static int vmclock_probe(struct platform_device *pdev) struct vmclock_state *st; int ret; - st = devm_kzalloc_obj(dev, *st); + /* Open files can outlive the device, so st is not devm memory */ + st = kzalloc_obj(*st); if (!st) return -ENOMEM; + kref_init(&st->kref); + + ret = devm_add_action_or_reset(dev, vmclock_put, st); + if (ret) + return ret; #if IS_ENABLED(CONFIG_ACPI) if (has_acpi_companion(dev)) @@ -686,13 +735,11 @@ static int vmclock_probe(struct platform_device *pdev) resource_size(&st->res)); return -EINVAL; } - st->clk = devm_memremap(dev, st->res.start, resource_size(&st->res), - MEMREMAP_WB | MEMREMAP_DEC); - if (IS_ERR(st->clk)) { - ret = PTR_ERR(st->clk); + st->clk = memremap(st->res.start, resource_size(&st->res), + MEMREMAP_WB | MEMREMAP_DEC); + if (!st->clk) { dev_info(dev, "failed to map shared memory\n"); - st->clk = NULL; - return ret; + return -ENXIO; } if (le32_to_cpu(st->clk->magic) != VMCLOCK_MAGIC || diff --git a/drivers/regulator/axp20x-regulator.c b/drivers/regulator/axp20x-regulator.c index e88da44aa2a0d4..53b1e0499c00aa 100644 --- a/drivers/regulator/axp20x-regulator.c +++ b/drivers/regulator/axp20x-regulator.c @@ -744,18 +744,18 @@ static const struct linear_range axp313a_dcdc3_ranges[] = { }; static const struct regulator_desc axp313a_regulators[] = { - AXP_DESC_RANGES(AXP313A, DCDC1, "dcdc1", "vin1", + AXP_DESC_RANGES_DELAY(AXP313A, DCDC1, "dcdc1", "vin1", axp313a_dcdc1_ranges, AXP313A_DCDC1_NUM_VOLTAGES, AXP313A_DCDC1_CONTROL, AXP313A_DCDC_V_OUT_MASK, - AXP313A_OUTPUT_CONTROL, BIT(0)), - AXP_DESC_RANGES(AXP313A, DCDC2, "dcdc2", "vin2", + AXP313A_OUTPUT_CONTROL, BIT(0), 400), + AXP_DESC_RANGES_DELAY(AXP313A, DCDC2, "dcdc2", "vin2", axp313a_dcdc2_ranges, AXP313A_DCDC23_NUM_VOLTAGES, AXP313A_DCDC2_CONTROL, AXP313A_DCDC_V_OUT_MASK, - AXP313A_OUTPUT_CONTROL, BIT(1)), - AXP_DESC_RANGES(AXP313A, DCDC3, "dcdc3", "vin3", + AXP313A_OUTPUT_CONTROL, BIT(1), 400), + AXP_DESC_RANGES_DELAY(AXP313A, DCDC3, "dcdc3", "vin3", axp313a_dcdc3_ranges, AXP313A_DCDC23_NUM_VOLTAGES, AXP313A_DCDC3_CONTROL, AXP313A_DCDC_V_OUT_MASK, - AXP313A_OUTPUT_CONTROL, BIT(2)), + AXP313A_OUTPUT_CONTROL, BIT(2), 400), AXP_DESC(AXP313A, ALDO1, "aldo1", "vin1", 500, 3500, 100, AXP313A_ALDO1_CONTROL, AXP313A_LDO_V_OUT_MASK, AXP313A_OUTPUT_CONTROL, BIT(3)), diff --git a/drivers/regulator/mt6363-regulator.c b/drivers/regulator/mt6363-regulator.c index e6c4bd851fef54..b4f5f33779b574 100644 --- a/drivers/regulator/mt6363-regulator.c +++ b/drivers/regulator/mt6363-regulator.c @@ -4,6 +4,7 @@ // Copyright (c) 2025 Collabora Ltd // AngeloGioacchino Del Regno +#include #include #include #include @@ -12,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -114,6 +116,8 @@ struct mt6363_regulator_info { int virq; }; +static DEFINE_MUTEX(mt6363_buck_top_lock); + #define MT6363_BUCK(match, vreg, min, max, step, en_reg, lp_reg, \ mset_reg, ocp_intn) \ [MT6363_ID_##vreg] = { \ @@ -388,6 +392,23 @@ static int mt6363_buck_unlock(struct regmap *map, bool unlock) return regmap_bulk_write(map, MT6363_BUCK_TOP_KEY_PROT_LO, &buf, sizeof(buf)); } +static int mt6363_buck_top_update_bits(struct regmap *map, unsigned int reg, + unsigned int mask, unsigned int val) +{ + int ret; + + guard(mutex)(&mt6363_buck_top_lock); + + ret = mt6363_buck_unlock(map, true); + if (ret) + return ret; + + ret = regmap_update_bits(map, reg, mask, val); + + mt6363_buck_unlock(map, false); + return ret; +} + static int mt6363_regulator_set_mode(struct regulator_dev *rdev, unsigned int mode) { @@ -400,13 +421,9 @@ static int mt6363_regulator_set_mode(struct regulator_dev *rdev, switch (mode) { case REGULATOR_MODE_FAST: - ret = mt6363_buck_unlock(regmap, true); - if (ret) - break; - - ret = regmap_set_bits(regmap, info->modeset_reg, info->modeset_mask); - - mt6363_buck_unlock(regmap, false); + ret = mt6363_buck_top_update_bits(regmap, info->modeset_reg, + info->modeset_mask, + info->modeset_mask); break; case REGULATOR_MODE_NORMAL: cur_mode = mt6363_regulator_get_mode(rdev); @@ -416,13 +433,8 @@ static int mt6363_regulator_set_mode(struct regulator_dev *rdev, } if (cur_mode == REGULATOR_MODE_FAST) { - ret = mt6363_buck_unlock(regmap, true); - if (ret) - break; - - ret = regmap_clear_bits(regmap, info->modeset_reg, info->modeset_mask); - - mt6363_buck_unlock(regmap, false); + ret = mt6363_buck_top_update_bits(regmap, info->modeset_reg, + info->modeset_mask, 0); break; } else if (cur_mode == REGULATOR_MODE_IDLE) { ret = regmap_clear_bits(regmap, info->lp_mode_reg, info->lp_mode_mask); @@ -508,20 +520,17 @@ static int mt6363_va15_set_voltage_sel(struct regulator_dev *rdev, unsigned int struct regmap *regmap = rdev->regmap; int ret; + guard(mutex)(&mt6363_buck_top_lock); + ret = mt6363_buck_unlock(regmap, true); if (ret) return ret; ret = regulator_set_voltage_sel_pickable_regmap(rdev, sel); - if (ret) - goto va15_unlock; - - ret = regmap_update_bits(regmap, MT6363_RG_BUCK_EFUSE_RSV1, - MT6363_RG_BUCK_EFUSE_RSV1_MASK, sel); - if (ret) - goto va15_unlock; + if (!ret) + ret = regmap_update_bits(regmap, MT6363_RG_BUCK_EFUSE_RSV1, + MT6363_RG_BUCK_EFUSE_RSV1_MASK, sel); -va15_unlock: mt6363_buck_unlock(rdev->regmap, false); return ret; } diff --git a/drivers/regulator/tps65132-regulator.c b/drivers/regulator/tps65132-regulator.c index 912db82ab51d06..42388a170116c9 100644 --- a/drivers/regulator/tps65132-regulator.c +++ b/drivers/regulator/tps65132-regulator.c @@ -37,8 +37,8 @@ #define TPS65132_VOUT_VMAX 6000000 #define TPS65132_VOUT_STEP 100000 -#define TPS65132_REG_APPS_DIS_VPOS BIT(0) -#define TPS65132_REG_APPS_DIS_VNEG BIT(1) +#define TPS65132_REG_APPS_DIS_VNEG BIT(0) +#define TPS65132_REG_APPS_DIS_VPOS BIT(1) #define TPS65132_REGULATOR_ID_VPOS 0 #define TPS65132_REGULATOR_ID_VNEG 1 diff --git a/drivers/reset/core.c b/drivers/reset/core.c index 38e189d04d09b2..1ae7ca1e8552f9 100644 --- a/drivers/reset/core.c +++ b/drivers/reset/core.c @@ -160,11 +160,18 @@ int reset_controller_register(struct reset_controller_dev *rcdev) } EXPORT_SYMBOL_GPL(reset_controller_register); +static void __reset_control_release(struct kref *kref); +static void __reset_control_free(struct reset_control *rstc); + +/* + * Removes rstc from its list and drops the references on rcdev's owner module + * and device. The caller must ensure rstc->list access is serialized (e.g., + * by holding rcdev->lock or moving rstc to a private list) and that no + * operations on rcdev via rstc are in flight. + */ static void reset_controller_remove(struct reset_controller_dev *rcdev, struct reset_control *rstc) { - lockdep_assert_held(&rcdev->lock); - list_del(&rstc->list); module_put(rcdev->owner); put_device(rcdev->dev); @@ -177,6 +184,7 @@ static void reset_controller_remove(struct reset_controller_dev *rcdev, void reset_controller_unregister(struct reset_controller_dev *rcdev) { struct reset_control *rstc, *pos; + LIST_HEAD(reset_control_head); scoped_guard(mutex, &reset_list_mutex) list_del(&rcdev->list); @@ -185,14 +193,30 @@ void reset_controller_unregister(struct reset_controller_dev *rcdev) /* * Numb but don't free the remaining reset control handles that are * still held by consumers. + * + * Hold a temporary reference on rstc before clearing rstc->rcdev: + * once rstc->rcdev is NULL, a concurrent reset_control_put_internal() + * will not acquire rcdev->lock and could otherwise free rstc. */ list_for_each_entry_safe(rstc, pos, &rcdev->reset_control_head, list) { + kref_get(&rstc->refcnt); rcu_assign_pointer(rstc->rcdev, NULL); - synchronize_srcu(&rstc->srcu); - reset_controller_remove(rcdev, rstc); + list_move(&rstc->list, &reset_control_head); } } + /* + * Run synchronize_srcu() outside rcdev->lock to avoid a circular + * locking dependency with paths that acquire rcdev->lock inside + * the rstc->srcu read-side critical section. + */ + list_for_each_entry_safe(rstc, pos, &reset_control_head, list) { + synchronize_srcu(&rstc->srcu); + reset_controller_remove(rcdev, rstc); + if (kref_put(&rstc->refcnt, __reset_control_release)) + __reset_control_free(rstc); + } + mutex_destroy(&rcdev->lock); } EXPORT_SYMBOL_GPL(reset_controller_unregister); @@ -886,14 +910,16 @@ __reset_control_get_internal(struct reset_controller_dev *rcdev, return rstc; } +/* + * Detaches rstc from rcdev (if still attached) when refcnt reaches 0. + * If rstc is still attached, the caller must hold rcdev->lock. + */ static void __reset_control_release(struct kref *kref) { struct reset_control *rstc = container_of(kref, struct reset_control, refcnt); struct reset_controller_dev *rcdev; - lockdep_assert_held(&rstc->srcu); - rcdev = rcu_replace_pointer(rstc->rcdev, NULL, true); if (rcdev) { lockdep_assert_held(&rcdev->lock); @@ -903,6 +929,17 @@ static void __reset_control_release(struct kref *kref) mutex_destroy(&rstc->lock); } +/* + * Must be called outside the rstc->srcu read-side critical section after + * kref_put(..., __reset_control_release) returns true. + */ +static void __reset_control_free(struct reset_control *rstc) +{ + synchronize_srcu(&rstc->srcu); + cleanup_srcu_struct(&rstc->srcu); + kfree(rstc); +} + static void reset_control_put_internal(struct reset_control *rstc) { struct reset_controller_dev *rcdev; @@ -913,19 +950,17 @@ static void reset_control_put_internal(struct reset_control *rstc) scoped_guard(srcu, &rstc->srcu) { rcdev = srcu_dereference(rstc->rcdev, &rstc->srcu); - if (!rcdev) - /* Already released. */ - return; - - guard(mutex)(&rcdev->lock); - ret = kref_put(&rstc->refcnt, __reset_control_release); + if (rcdev) { + guard(mutex)(&rcdev->lock); + ret = kref_put(&rstc->refcnt, __reset_control_release); + } else { + /* Already detached from rcdev. */ + ret = kref_put(&rstc->refcnt, __reset_control_release); + } } - if (ret) { - synchronize_srcu(&rstc->srcu); - cleanup_srcu_struct(&rstc->srcu); - kfree(rstc); - } + if (ret) + __reset_control_free(rstc); } static void reset_gpio_aux_device_release(struct device *dev) @@ -1181,6 +1216,8 @@ __fwnode_reset_control_get(struct fwnode_handle *fwnode, const char *id, int ind ret = __reset_add_reset_gpio_device(fwnode, &args); if (ret) { fwnode_handle_put(args.fwnode); + if (ret == -ENOENT && optional) + return NULL; return ERR_PTR(ret); } } diff --git a/drivers/reset/reset-scmi.c b/drivers/reset/reset-scmi.c index 5cb925321c6c7e..1d3415b21c5789 100644 --- a/drivers/reset/reset-scmi.c +++ b/drivers/reset/reset-scmi.c @@ -107,6 +107,7 @@ static int scmi_reset_probe(struct scmi_device *sdev) data->rcdev.ops = &scmi_reset_ops; data->rcdev.owner = THIS_MODULE; + data->rcdev.dev = dev; data->rcdev.of_node = np; data->rcdev.nr_resets = reset_ops->num_domains_get(ph); data->ph = ph; diff --git a/drivers/reset/spacemit/reset-spacemit-k1.c b/drivers/reset/spacemit/reset-spacemit-k1.c index 8f3b5329ea5f62..dbd783c138b1b1 100644 --- a/drivers/reset/spacemit/reset-spacemit-k1.c +++ b/drivers/reset/spacemit/reset-spacemit-k1.c @@ -154,15 +154,15 @@ static const struct ccu_reset_controller_data k1_rcpu_reset_data = { }; static const struct ccu_reset_data k1_rcpu2_resets[] = { - [RESET_RCPU2_PWM0] = RESET_DATA(RCPU2_PWM9_CLK_RST, BIT(2), BIT(0)), - [RESET_RCPU2_PWM1] = RESET_DATA(RCPU2_PWM9_CLK_RST, BIT(2), BIT(0)), - [RESET_RCPU2_PWM2] = RESET_DATA(RCPU2_PWM9_CLK_RST, BIT(2), BIT(0)), - [RESET_RCPU2_PWM3] = RESET_DATA(RCPU2_PWM9_CLK_RST, BIT(2), BIT(0)), - [RESET_RCPU2_PWM4] = RESET_DATA(RCPU2_PWM9_CLK_RST, BIT(2), BIT(0)), - [RESET_RCPU2_PWM5] = RESET_DATA(RCPU2_PWM9_CLK_RST, BIT(2), BIT(0)), - [RESET_RCPU2_PWM6] = RESET_DATA(RCPU2_PWM9_CLK_RST, BIT(2), BIT(0)), - [RESET_RCPU2_PWM7] = RESET_DATA(RCPU2_PWM9_CLK_RST, BIT(2), BIT(0)), - [RESET_RCPU2_PWM8] = RESET_DATA(RCPU2_PWM9_CLK_RST, BIT(2), BIT(0)), + [RESET_RCPU2_PWM0] = RESET_DATA(RCPU2_PWM0_CLK_RST, BIT(2), BIT(0)), + [RESET_RCPU2_PWM1] = RESET_DATA(RCPU2_PWM1_CLK_RST, BIT(2), BIT(0)), + [RESET_RCPU2_PWM2] = RESET_DATA(RCPU2_PWM2_CLK_RST, BIT(2), BIT(0)), + [RESET_RCPU2_PWM3] = RESET_DATA(RCPU2_PWM3_CLK_RST, BIT(2), BIT(0)), + [RESET_RCPU2_PWM4] = RESET_DATA(RCPU2_PWM4_CLK_RST, BIT(2), BIT(0)), + [RESET_RCPU2_PWM5] = RESET_DATA(RCPU2_PWM5_CLK_RST, BIT(2), BIT(0)), + [RESET_RCPU2_PWM6] = RESET_DATA(RCPU2_PWM6_CLK_RST, BIT(2), BIT(0)), + [RESET_RCPU2_PWM7] = RESET_DATA(RCPU2_PWM7_CLK_RST, BIT(2), BIT(0)), + [RESET_RCPU2_PWM8] = RESET_DATA(RCPU2_PWM8_CLK_RST, BIT(2), BIT(0)), [RESET_RCPU2_PWM9] = RESET_DATA(RCPU2_PWM9_CLK_RST, BIT(2), BIT(0)), }; diff --git a/drivers/s390/block/dcssblk.c b/drivers/s390/block/dcssblk.c index e5a02c2990d017..9b6b48431fbf0b 100644 --- a/drivers/s390/block/dcssblk.c +++ b/drivers/s390/block/dcssblk.c @@ -101,7 +101,7 @@ static DEVICE_ATTR(remove, S_IWUSR, NULL, dcssblk_remove_store); static struct device *dcssblk_root_dev; static LIST_HEAD(dcssblk_devices); -static struct rw_semaphore dcssblk_devices_sem; +static DECLARE_RWSEM(dcssblk_devices_sem); /* * release function for segment device. @@ -1026,7 +1026,6 @@ dcssblk_init(void) if (rc < 0) goto out_root; dcssblk_major = rc; - init_rwsem(&dcssblk_devices_sem); dcssblk_check_params(); return 0; diff --git a/drivers/scsi/ch.c b/drivers/scsi/ch.c index b2c9fb71c9e0a7..390425671a3a7a 100644 --- a/drivers/scsi/ch.c +++ b/drivers/scsi/ch.c @@ -952,11 +952,15 @@ static void ch_remove(struct scsi_device *sd) scsi_changer *ch = dev_get_drvdata(dev); spin_lock(&ch_index_lock); - idr_remove(&ch_index_idr, ch->minor); + idr_replace(&ch_index_idr, NULL, ch->minor); dev_set_drvdata(dev, NULL); spin_unlock(&ch_index_lock); device_destroy(&ch_sysfs_class, MKDEV(SCSI_CHANGER_MAJOR, ch->minor)); + + spin_lock(&ch_index_lock); + idr_remove(&ch_index_idr, ch->minor); + spin_unlock(&ch_index_lock); scsi_device_put(ch->device); kref_put(&ch->ref, ch_destroy); } diff --git a/drivers/scsi/device_handler/scsi_dh_alua.c b/drivers/scsi/device_handler/scsi_dh_alua.c index 87ac0a6d63e54a..84ff3aed2c462f 100644 --- a/drivers/scsi/device_handler/scsi_dh_alua.c +++ b/drivers/scsi/device_handler/scsi_dh_alua.c @@ -1233,13 +1233,20 @@ static int alua_bus_attach(struct scsi_device *sdev) INIT_LIST_HEAD(&h->node); mutex_init(&h->init_mutex); + /* + * alua_rtpg_queue() only queues an RTPG when sdev->handler_data + * points at this alua_dh_data, so set it before alua_initialize() + * otherwise the initial RTPG issued from alua_check_vpd() is + * silently dropped and sdev->access_state is never populated. + */ + sdev->handler_data = h; err = alua_initialize(sdev, h); if (err != SCSI_DH_OK && err != SCSI_DH_DEV_OFFLINED) goto failed; - sdev->handler_data = h; return SCSI_DH_OK; failed: + sdev->handler_data = NULL; kfree(h); return err; } diff --git a/drivers/scsi/device_handler/scsi_dh_rdac.c b/drivers/scsi/device_handler/scsi_dh_rdac.c index 742534c9938654..0986a6e2a6aee4 100644 --- a/drivers/scsi/device_handler/scsi_dh_rdac.c +++ b/drivers/scsi/device_handler/scsi_dh_rdac.c @@ -450,14 +450,14 @@ static int initialize_controller(struct scsi_device *sdev, spin_lock(&list_lock); h->ctlr = get_controller(index, array_name, array_id, sdev); - if (!h->ctlr) + if (!h->ctlr) { err = SCSI_DH_RES_TEMP_UNAVAIL; - else { + } else { h->sdev = sdev; list_add_rcu(&h->node, &h->ctlr->dh_list); + err = SCSI_DH_OK; } spin_unlock(&list_lock); - err = SCSI_DH_OK; } return err; } diff --git a/drivers/scsi/leapraid/leapraid_os.c b/drivers/scsi/leapraid/leapraid_os.c index da597eb99377eb..749e50366dbcf0 100644 --- a/drivers/scsi/leapraid/leapraid_os.c +++ b/drivers/scsi/leapraid/leapraid_os.c @@ -935,22 +935,16 @@ static int leapraid_init_cmd_priv(struct Scsi_Host *shost, struct scsi_cmnd *scmd) { struct leapraid_adapter *adapter = shost_priv(shost); - struct leapraid_io_req_tracker *io_tracker; - io_tracker = scsi_cmd_priv(scmd); - leapraid_internal_init_cmd_priv(adapter, io_tracker); - - return 0; + return leapraid_internal_init_cmd_priv(adapter, scsi_cmd_priv(scmd)); } static int leapraid_exit_cmd_priv(struct Scsi_Host *shost, struct scsi_cmnd *scmd) { struct leapraid_adapter *adapter = shost_priv(shost); - struct leapraid_io_req_tracker *io_tracker; - io_tracker = scsi_cmd_priv(scmd); - leapraid_internal_exit_cmd_priv(adapter, io_tracker); + leapraid_internal_exit_cmd_priv(adapter, scsi_cmd_priv(scmd)); return 0; } diff --git a/drivers/scsi/libfc/fc_rport.c b/drivers/scsi/libfc/fc_rport.c index c25979d96808a9..7b093854462e44 100644 --- a/drivers/scsi/libfc/fc_rport.c +++ b/drivers/scsi/libfc/fc_rport.c @@ -550,10 +550,11 @@ static void fc_rport_enter_ready(struct fc_rport_priv *rdata) FC_RPORT_DBG(rdata, "Port is Ready\n"); - kref_get(&rdata->kref); - if (rdata->event == RPORT_EV_NONE && - !queue_work(rport_event_queue, &rdata->event_work)) - kref_put(&rdata->kref, fc_rport_destroy); + if (rdata->event == RPORT_EV_NONE) { + kref_get(&rdata->kref); + if (!queue_work(rport_event_queue, &rdata->event_work)) + kref_put(&rdata->kref, fc_rport_destroy); + } rdata->event = RPORT_EV_READY; } diff --git a/drivers/scsi/lpfc/lpfc_els.c b/drivers/scsi/lpfc/lpfc_els.c index 804aa7509b6926..8d5bf2510d7a0b 100644 --- a/drivers/scsi/lpfc/lpfc_els.c +++ b/drivers/scsi/lpfc/lpfc_els.c @@ -4477,18 +4477,35 @@ lpfc_issue_els_edc(struct lpfc_vport *vport, uint8_t retry) void lpfc_cancel_retry_delay_tmo(struct lpfc_vport *vport, struct lpfc_nodelist *nlp) { - struct lpfc_work_evt *evtp; + struct lpfc_hba *phba = vport->phba; + struct lpfc_work_evt *evtp = &nlp->els_retry_evt; + struct lpfc_nodelist *arg_ndlp = NULL; + unsigned long flags; if (!test_and_clear_bit(NLP_DELAY_TMO, &nlp->nlp_flag)) return; timer_delete_sync(&nlp->nlp_delayfunc); nlp->nlp_last_elscmd = 0; - if (!list_empty(&nlp->els_retry_evt.evt_listp)) { - list_del_init(&nlp->els_retry_evt.evt_listp); - /* Decrement nlp reference count held for the delayed retry */ - evtp = &nlp->els_retry_evt; - lpfc_nlp_put((struct lpfc_nodelist *)evtp->evt_arg1); + + /* + * If retry event is queued, remove it under lock and consume + * its payload to prevent double-put. The event holds a reference + * to the nodelist that must be released exactly once. + */ + spin_lock_irqsave(&phba->hbalock, flags); + if (!list_empty(&evtp->evt_listp)) { + list_del_init(&evtp->evt_listp); + /* Take local copy and clear to prevent reuse */ + arg_ndlp = (struct lpfc_nodelist *)evtp->evt_arg1; + evtp->evt_arg1 = NULL; + smp_wmb(); /* Ensure NULL visible before unlock */ } + spin_unlock_irqrestore(&phba->hbalock, flags); + + /* Drop the event-held reference outside the lock */ + if (arg_ndlp) + lpfc_nlp_put(arg_ndlp); + if (test_and_clear_bit(NLP_NPR_2B_DISC, &nlp->nlp_flag)) { if (vport->num_disc_nodes) { if (vport->port_state < LPFC_VPORT_READY) { diff --git a/drivers/scsi/lpfc/lpfc_hbadisc.c b/drivers/scsi/lpfc/lpfc_hbadisc.c index 57cdd669928c2d..b447b9acfe7bfc 100644 --- a/drivers/scsi/lpfc/lpfc_hbadisc.c +++ b/drivers/scsi/lpfc/lpfc_hbadisc.c @@ -840,12 +840,21 @@ lpfc_work_list_done(struct lpfc_hba *phba) while (!list_empty(&phba->work_list)) { list_remove_head((&phba->work_list), evtp, typeof(*evtp), evt_listp); + /* + * The ELS retry event can be requeued by lpfc_els_retry_delay() + * as soon as hbalock is dropped. Consume the payload within the + * hbalock to prevent reuse or double-put. + */ + if (evtp->evt == LPFC_EVT_ELS_RETRY) { + ndlp = (struct lpfc_nodelist *)(evtp->evt_arg1); + evtp->evt_arg1 = NULL; + } spin_unlock_irq(&phba->hbalock); hba_pci_err = test_bit(HBA_PCI_ERR, &phba->bit_flags); free_evt = 1; switch (evtp->evt) { case LPFC_EVT_ELS_RETRY: - ndlp = (struct lpfc_nodelist *) (evtp->evt_arg1); + /* ndlp was already captured under hbalock */ if (!hba_pci_err) { lpfc_els_retry_delay_handler(ndlp); free_evt = 0; /* evt is part of ndlp */ diff --git a/drivers/scsi/mpi3mr/mpi3mr.h b/drivers/scsi/mpi3mr/mpi3mr.h index d6e16707fd97c8..e78383df619c34 100644 --- a/drivers/scsi/mpi3mr/mpi3mr.h +++ b/drivers/scsi/mpi3mr/mpi3mr.h @@ -83,6 +83,7 @@ extern atomic64_t event_counter; #define MPI3MR_ADMIN_REPLY_Q_SIZE (8 * MPI3MR_PAGE_SIZE_4K) #define MPI3MR_ADMIN_REQ_FRAME_SZ 128 #define MPI3MR_ADMIN_REPLY_FRAME_SZ 16 +#define MPI3MR_MIN_REPLY_FRAME_SZ_DWORDS 16 /* 64 bytes */ /* Operational queue management definitions */ #define MPI3MR_OP_REQ_Q_QD 512 diff --git a/drivers/scsi/mpi3mr/mpi3mr_fw.c b/drivers/scsi/mpi3mr/mpi3mr_fw.c index f0d3cd398dd00c..60a92366e59049 100644 --- a/drivers/scsi/mpi3mr/mpi3mr_fw.c +++ b/drivers/scsi/mpi3mr/mpi3mr_fw.c @@ -3261,6 +3261,7 @@ static int mpi3mr_issue_iocfacts(struct mpi3mr_ioc *mrioc, struct mpi3_ioc_facts_data *facts_data) { struct mpi3_ioc_facts_request iocfacts_req; + u16 reply_frame_size; void *data = NULL; dma_addr_t data_dma; u32 data_len = sizeof(*facts_data); @@ -3318,6 +3319,23 @@ static int mpi3mr_issue_iocfacts(struct mpi3mr_ioc *mrioc, goto out_unlock; } memcpy(facts_data, (u8 *)data, data_len); + + reply_frame_size = le16_to_cpu(facts_data->reply_frame_size); + /* + * Validate reply_frame_size: + * - Must be at least 16 dwords (64 bytes) to accommodate fixed reply + * structures and avoid underflow/divide-by-zero in logdata sizing. + * - Must not exceed U16_MAX / 4 to prevent integer overflow. + */ + if (reply_frame_size < MPI3MR_MIN_REPLY_FRAME_SZ_DWORDS || + reply_frame_size > (U16_MAX / 4)) { + ioc_err(mrioc, "Invalid reply_frame_size %u (must be %u..%u dwords)\n", + reply_frame_size, MPI3MR_MIN_REPLY_FRAME_SZ_DWORDS, + (unsigned int)(U16_MAX / 4)); + retval = -EINVAL; + goto out_unlock; + } + mpi3mr_process_factsdata(mrioc, facts_data); out_unlock: mrioc->init_cmds.state = MPI3MR_CMD_NOTUSED; diff --git a/drivers/scsi/mpt3sas/mpt3sas_base.c b/drivers/scsi/mpt3sas/mpt3sas_base.c index 5c957044eded18..b33a3e49608ddf 100644 --- a/drivers/scsi/mpt3sas/mpt3sas_base.c +++ b/drivers/scsi/mpt3sas/mpt3sas_base.c @@ -3264,11 +3264,8 @@ _base_assign_reply_queues(struct MPT3SAS_ADAPTER *ioc) goto fall_back; } - for_each_cpu_and(cpu, mask, cpu_online_mask) { - if (cpu >= ioc->cpu_msix_table_sz) - break; + for_each_cpu(cpu, mask) ioc->cpu_msix_table[cpu] = reply_q->msix_index; - } } return; } @@ -8409,15 +8406,18 @@ int mpt3sas_base_attach(struct MPT3SAS_ADAPTER *ioc) { int r, i, rc; - int cpu_id, last_cpu_id = 0; dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__)); /* setup cpu_msix_table */ ioc->cpu_count = num_online_cpus(); - for_each_online_cpu(cpu_id) - last_cpu_id = cpu_id; - ioc->cpu_msix_table_sz = last_cpu_id + 1; + /* + * Allocate an entry for every possible CPU, because + * _base_get_msix_index() indexes the table with + * raw_smp_processor_id(), which can be a CPU brought online after + * the adapter was attached. + */ + ioc->cpu_msix_table_sz = nr_cpu_ids; ioc->cpu_msix_table = kzalloc(ioc->cpu_msix_table_sz, GFP_KERNEL); ioc->reply_queue_count = 1; if (!ioc->cpu_msix_table) { diff --git a/drivers/scsi/mpt3sas/mpt3sas_ctl.c b/drivers/scsi/mpt3sas/mpt3sas_ctl.c index 8bb947004885bf..b069dd384ed781 100644 --- a/drivers/scsi/mpt3sas/mpt3sas_ctl.c +++ b/drivers/scsi/mpt3sas/mpt3sas_ctl.c @@ -57,9 +57,13 @@ #include #include +#include + #include "mpt3sas_base.h" #include "mpt3sas_ctl.h" +/* PHY operation byte in an SMP PHY Control request */ +#define SMP_PHY_CONTROL_OP_OFFSET 10 static struct fasync_struct *async_queue; static DECLARE_WAIT_QUEUE_HEAD(ctl_poll_wait); @@ -959,13 +963,17 @@ _ctl_do_mpt_command(struct MPT3SAS_ADAPTER *ioc, struct mpt3_ioctl_command karg, Mpi2SmpPassthroughRequest_t *smp_request = (Mpi2SmpPassthroughRequest_t *)mpi_request; u8 *data; + bool immediate; if (!ioc->multipath_on_hba) { /* ioc determines which port to use */ smp_request->PhysicalPort = 0xFF; } - if (smp_request->PassthroughFlags & - MPI2_SMP_PT_REQ_PT_FLAGS_IMMEDIATE) + + immediate = smp_request->PassthroughFlags & + MPI2_SMP_PT_REQ_PT_FLAGS_IMMEDIATE; + + if (immediate) data = (u8 *)&smp_request->SGL; else { if (unlikely(data_out == NULL)) { @@ -978,7 +986,11 @@ _ctl_do_mpt_command(struct MPT3SAS_ADAPTER *ioc, struct mpt3_ioctl_command karg, data = data_out; } - if (data[1] == 0x91 && (data[10] == 1 || data[10] == 2)) { + if ((immediate || + data_out_sz >= SMP_PHY_CONTROL_OP_OFFSET + 1) && + data[1] == SMP_PHY_CONTROL && + (data[10] == PHY_FUNC_LINK_RESET || + data[10] == PHY_FUNC_HARD_RESET)) { ioc->ioc_link_reset_in_progress = 1; ioc->ignore_loginfos = 1; } diff --git a/drivers/scsi/mpt3sas/mpt3sas_scsih.c b/drivers/scsi/mpt3sas/mpt3sas_scsih.c index a77bbc3d2b6662..04255286a2a69e 100644 --- a/drivers/scsi/mpt3sas/mpt3sas_scsih.c +++ b/drivers/scsi/mpt3sas/mpt3sas_scsih.c @@ -57,6 +57,14 @@ #include "mpt3sas_base.h" +/* + * Largest NVMe transfer whose PRP list fits in one NVME_PRP_PAGE_SIZE + * buffer (last entry reserved for the chain pointer) for any buffer + * offset: (4096 / 8 - 1) * 4096 = 2 MiB - 4 KiB. + */ +#define MPT3SAS_NVME_MAX_XFER \ + ((NVME_PRP_PAGE_SIZE / NVME_PRP_SIZE - 1) * NVME_PRP_PAGE_SIZE) + #define RAID_CHANNEL 1 #define PCIE_CHANNEL 2 @@ -2741,14 +2749,22 @@ scsih_sdev_configure(struct scsi_device *sdev, struct queue_limits *lim) /* * The HBA firmware passes the NVMe drive's MDTS * (Maximum Data Transfer Size) up to the driver. However, - * the driver hardcodes a 4K buffer size for the PRP list, - * accommodating at most 512 entries. This strictly limits - * the maximum supported NVMe I/O transfer to 2 MiB. + * the driver hardcodes a 4K buffer size for the PRP list. + * base_make_prp_nvme() reserves the last slot of that page + * for a chain pointer, leaving 511 data PRP entries, and + * PRP1 in the main message frame covers the first, possibly + * partial, page. + * + * A transfer that is not page aligned spans one more page + * than its length implies, so a 2 MiB I/O starting at a + * non-zero page offset needs 512 list entries and overruns + * the PRP buffer by one. Limit transfers to 511 pages, which + * fits the PRP list for any starting offset. * * Cap max_hw_sectors to the smaller of the drive's reported - * MDTS or the 2 MiB driver limit to prevent kernel oopses. + * MDTS or the driver limit to prevent kernel oopses. */ - lim->max_hw_sectors = SZ_2M >> SECTOR_SHIFT; + lim->max_hw_sectors = MPT3SAS_NVME_MAX_XFER >> SECTOR_SHIFT; if (pcie_device->nvme_mdts) lim->max_hw_sectors = min(lim->max_hw_sectors, pcie_device->nvme_mdts >> SECTOR_SHIFT); diff --git a/drivers/scsi/pm8001/pm8001_defs.h b/drivers/scsi/pm8001/pm8001_defs.h index a9605ca317f341..9b37a76d8b7443 100644 --- a/drivers/scsi/pm8001/pm8001_defs.h +++ b/drivers/scsi/pm8001/pm8001_defs.h @@ -178,6 +178,7 @@ enum port_type { #define PM8001_MAX_INB_NUM 64 #define PM8001_MAX_OUTB_NUM 64 #define PM8001_CAN_QUEUE 508 /* SCSI Queue depth */ +#define PM8001_PRE_VECTORS 1 /* non-affinitized housekeeping vector */ /* Inbound/Outbound queue size */ #define IOMB_SIZE_SPC 64 diff --git a/drivers/scsi/pm8001/pm8001_init.c b/drivers/scsi/pm8001/pm8001_init.c index 5af81c73a8f875..b1788788b7ed9b 100644 --- a/drivers/scsi/pm8001/pm8001_init.c +++ b/drivers/scsi/pm8001/pm8001_init.c @@ -104,8 +104,9 @@ static void pm8001_map_queues(struct Scsi_Host *shost) struct pm8001_hba_info *pm8001_ha = sha->lldd_ha; struct blk_mq_queue_map *qmap = &shost->tag_set.map[HCTX_TYPE_DEFAULT]; - if (pm8001_ha->number_of_intr > 1) { - blk_mq_map_hw_queues(qmap, &pm8001_ha->pdev->dev, 1); + if (pm8001_ha->number_of_intr > PM8001_PRE_VECTORS) { + blk_mq_map_hw_queues(qmap, &pm8001_ha->pdev->dev, + PM8001_PRE_VECTORS); return; } @@ -977,10 +978,11 @@ static u32 pm8001_setup_msix(struct pm8001_hba_info *pm8001_ha) * include in the affinity spreading. */ struct irq_affinity desc = { - .pre_vectors = 1, + .pre_vectors = PM8001_PRE_VECTORS, }; rc = pci_alloc_irq_vectors_affinity( - pm8001_ha->pdev, 2, PM8001_MAX_MSIX_VEC, + pm8001_ha->pdev, PM8001_PRE_VECTORS + 1, + PM8001_MAX_MSIX_VEC, PCI_IRQ_MSIX | PCI_IRQ_AFFINITY, &desc); } @@ -1183,8 +1185,9 @@ static int pm8001_pci_probe(struct pci_dev *pdev, PM8001_CHIP_DISP->chip_post_init(pm8001_ha); - if (pm8001_ha->number_of_intr > 1) { - shost->nr_hw_queues = pm8001_ha->number_of_intr - 1; + if (pm8001_ha->number_of_intr > PM8001_PRE_VECTORS) { + shost->nr_hw_queues = pm8001_ha->number_of_intr - + PM8001_PRE_VECTORS; /* * For now, ensure we're not sent too many commands by setting * host_tagset. This is also required if we start using request diff --git a/drivers/scsi/pm8001/pm80xx_hwi.c b/drivers/scsi/pm8001/pm80xx_hwi.c index d2572dd66071f1..1d4f5ee861c1f0 100644 --- a/drivers/scsi/pm8001/pm80xx_hwi.c +++ b/drivers/scsi/pm8001/pm80xx_hwi.c @@ -4328,14 +4328,19 @@ static int check_enc_sat_cmd(struct sas_task *task) return ret; } -static u32 pm80xx_chip_get_q_index(struct sas_task *task) +static u32 pm80xx_chip_get_q_index(struct pm8001_hba_info *pm8001_ha, + struct sas_task *task) { struct request *rq = sas_task_find_rq(task); if (!rq) return 0; - return blk_mq_unique_tag_to_hwq(blk_mq_unique_tag(rq)); + if (pm8001_ha->number_of_intr > PM8001_PRE_VECTORS) + return blk_mq_unique_tag_to_hwq(blk_mq_unique_tag(rq)) + + PM8001_PRE_VECTORS; + + return 0; } /** @@ -4371,7 +4376,7 @@ static int pm80xx_chip_ssp_io_req(struct pm8001_hba_info *pm8001_ha, ssp_cmd.ssp_iu.efb_prio_attr |= (task->ssp_task.task_attr & 7); memcpy(ssp_cmd.ssp_iu.cdb, task->ssp_task.cmd->cmnd, task->ssp_task.cmd->cmd_len); - q_index = pm80xx_chip_get_q_index(task); + q_index = pm80xx_chip_get_q_index(pm8001_ha, task); /* Check if encryption is set */ if (pm8001_ha->chip->encrypt && @@ -4510,7 +4515,7 @@ static int pm80xx_chip_sata_req(struct pm8001_hba_info *pm8001_ha, u32 opc = OPC_INB_SATA_HOST_OPSTART; memset(&sata_cmd, 0, sizeof(sata_cmd)); - q_index = pm80xx_chip_get_q_index(task); + q_index = pm80xx_chip_get_q_index(pm8001_ha, task); if (task->data_dir == DMA_NONE && !task->ata_task.use_ncq) { ATAP = 0x04; /* no data*/ diff --git a/drivers/scsi/scsi_bsg.c b/drivers/scsi/scsi_bsg.c index e4a65d7a237422..3cf1caad02f70b 100644 --- a/drivers/scsi/scsi_bsg.c +++ b/drivers/scsi/scsi_bsg.c @@ -43,9 +43,17 @@ static void scsi_bsg_uring_task_cb(struct io_tw_req tw_req, io_tw_token_t tw) if (pdu->bio) ret = blk_rq_unmap_user(pdu->bio); + /* + * If the request is being canceled, e.g. because the submitting task + * has exited, this may run from a kworker or in a different task, so + * don't copy the sense data to the submitter's address. + */ + if (unlikely(tw.cancel)) + ret = -ECANCELED; + if (scsi_status_is_check_condition(scmd->result)) { driver_status = DRIVER_SENSE; - if (pdu->response_addr) + if (pdu->response_addr && !tw.cancel) sense_len_wr = min_t(unsigned int, pdu->max_response_len, scmd->sense_len); } diff --git a/drivers/scsi/scsi_ioctl.c b/drivers/scsi/scsi_ioctl.c index bf049d9cb71915..91525103d0743b 100644 --- a/drivers/scsi/scsi_ioctl.c +++ b/drivers/scsi/scsi_ioctl.c @@ -300,7 +300,6 @@ bool scsi_cmd_allowed(unsigned char *cmd, bool open_for_write) case GPCMD_VERIFY_10: case VERIFY_16: case REPORT_LUNS: - case SERVICE_ACTION_IN_16: case RECEIVE_DIAGNOSTIC: case MAINTENANCE_IN: /* also GPCMD_SEND_KEY, which is a write command */ case GPCMD_READ_BUFFER_CAPACITY: @@ -330,6 +329,21 @@ bool scsi_cmd_allowed(unsigned char *cmd, bool open_for_write) /* ZBC */ case ZBC_IN: return true; + /* + * The storage element depopulation commands share the opcode of the + * read-only SERVICE ACTION IN(16) commands, but change the capacity + * of the device and may destroy its data, so treat them as writing + * commands. + */ + case SERVICE_ACTION_IN_16: + switch (cmd[1] & 0x1f) { + case SAI_REMOVE_ELEMENT_AND_TRUNCATE: + case SAI_RESTORE_ELEMENTS_AND_REBUILD: + case SAI_REMOVE_ELEMENT_AND_MODIFY_ZONES: + return open_for_write; + default: + return true; + } /* Basic writing commands */ case WRITE_6: case WRITE_10: diff --git a/drivers/scsi/sd_zbc.c b/drivers/scsi/sd_zbc.c index 8cbf171e6fabf1..06f4e3fcda1de9 100644 --- a/drivers/scsi/sd_zbc.c +++ b/drivers/scsi/sd_zbc.c @@ -222,7 +222,7 @@ int sd_zbc_report_zones(struct gendisk *disk, sector_t sector, { struct scsi_disk *sdkp = scsi_disk(disk); sector_t lba = sectors_to_logical(sdkp->device, sector); - unsigned int nr, i; + unsigned int nr, i, max_in_buf; unsigned char *buf; u64 zone_length, start_lba; size_t offset, buflen = 0; @@ -241,13 +241,18 @@ int sd_zbc_report_zones(struct gendisk *disk, sector_t sector, if (!buf) return -ENOMEM; + max_in_buf = (buflen - ZBC_REPORT_ZONES_HEADER_SIZE) / + ZBC_ZONE_DESCRIPTOR_SIZE; + while (zone_idx < nr_zones && lba < sdkp->capacity) { ret = sd_zbc_do_report_zones(sdkp, buf, buflen, lba, true); if (ret) goto out; offset = 0; - nr = min(nr_zones, get_unaligned_be32(&buf[0]) / 64); + nr = min3(nr_zones - zone_idx, + get_unaligned_be32(&buf[0]) / ZBC_ZONE_DESCRIPTOR_SIZE, + max_in_buf); if (!nr) break; diff --git a/drivers/soc/renesas/Kconfig b/drivers/soc/renesas/Kconfig index a63df28df3b5e7..0b6876ef6dca22 100644 --- a/drivers/soc/renesas/Kconfig +++ b/drivers/soc/renesas/Kconfig @@ -461,7 +461,6 @@ config ARCH_R9A07G043 bool "RISC-V Platform support for R9A07G043F (RZ/Five)" depends on NONPORTABLE depends on !DMA_DIRECT_REMAP - depends on RISCV_ALTERNATIVE depends on !RISCV_ISA_ZICBOM depends on RISCV_SBI select ARCH_RZG2L diff --git a/drivers/soundwire/bus.c b/drivers/soundwire/bus.c index 79ae8a4babf97f..e104185c0fa3c2 100644 --- a/drivers/soundwire/bus.c +++ b/drivers/soundwire/bus.c @@ -1234,7 +1234,6 @@ int sdw_bus_exit_clk_stop(struct sdw_bus *bus) if (ret < 0) dev_warn(&slave->dev, "clock stop pre-deprepare cb failed:%d\n", ret); - /* Only de-prepare a Slave device if needed */ if (!slave->prop.simple_clk_stop_capable) { simple_clk_stop = false; @@ -1914,9 +1913,9 @@ int sdw_handle_slave_status(struct sdw_bus *bus, mutex_unlock(&bus->bus_lock); continue; } - mutex_unlock(&bus->bus_lock); slave = sdw_get_slave(bus, i); + mutex_unlock(&bus->bus_lock); if (!slave) continue; @@ -1961,9 +1960,9 @@ int sdw_handle_slave_status(struct sdw_bus *bus, mutex_unlock(&bus->bus_lock); continue; } - mutex_unlock(&bus->bus_lock); slave = sdw_get_slave(bus, i); + mutex_unlock(&bus->bus_lock); if (!slave) continue; @@ -2059,9 +2058,9 @@ void sdw_clear_slave_status(struct sdw_bus *bus, u32 request) mutex_unlock(&bus->bus_lock); continue; } - mutex_unlock(&bus->bus_lock); slave = sdw_get_slave(bus, i); + mutex_unlock(&bus->bus_lock); if (!slave) continue; diff --git a/drivers/soundwire/intel_ace2x.c b/drivers/soundwire/intel_ace2x.c index 43961c45ed2749..a39808b8c1cf76 100644 --- a/drivers/soundwire/intel_ace2x.c +++ b/drivers/soundwire/intel_ace2x.c @@ -83,16 +83,21 @@ static int intel_ace2x_bpt_open_stream(struct sdw_intel *sdw, struct sdw_slave * int len; int i; + mutex_lock(&cdns->bus.bus_lock); if (cdns->bus.bpt_stream) { + mutex_unlock(&cdns->bus.bus_lock); dev_err(cdns->dev, "%s: BPT stream already exists\n", __func__); return -EAGAIN; } stream = sdw_alloc_stream("BPT", SDW_STREAM_BPT); - if (!stream) + if (!stream) { + mutex_unlock(&cdns->bus.bus_lock); return -ENOMEM; + } cdns->bus.bpt_stream = stream; + mutex_unlock(&cdns->bus.bus_lock); ret = sdw_slave_bpt_stream_add(slave, stream); if (ret < 0) @@ -105,7 +110,7 @@ static int intel_ace2x_bpt_open_stream(struct sdw_intel *sdw, struct sdw_slave * if (!pdi0) { dev_err(cdns->dev, "%s: sdw_cdns_alloc_pdi0 failed\n", __func__); ret = -EINVAL; - goto remove_slave; + goto remove_master; } sdw_cdns_config_stream(cdns, 1, dir, pdi0); @@ -117,7 +122,7 @@ static int intel_ace2x_bpt_open_stream(struct sdw_intel *sdw, struct sdw_slave * if (!pdi1) { dev_err(cdns->dev, "%s: sdw_cdns_alloc_pdi1 failed\n", __func__); ret = -EINVAL; - goto remove_slave; + goto remove_master; } sdw_cdns_config_stream(cdns, 1, dir, pdi1); @@ -136,7 +141,7 @@ static int intel_ace2x_bpt_open_stream(struct sdw_intel *sdw, struct sdw_slave * pconfig = kzalloc_objs(*pconfig, 2); if (!pconfig) { ret = -ENOMEM; - goto remove_slave; + goto remove_master; } for (i = 0; i < 2 /* num_pdi */; i++) { @@ -149,7 +154,7 @@ static int intel_ace2x_bpt_open_stream(struct sdw_intel *sdw, struct sdw_slave * if (ret < 0) { dev_err(cdns->dev, "add master to stream failed:%d\n", ret); - goto remove_slave; + goto remove_master; } ret = sdw_prepare_stream(cdns->bus.bpt_stream); @@ -293,15 +298,16 @@ static int intel_ace2x_bpt_open_stream(struct sdw_intel *sdw, struct sdw_slave * dev_err(cdns->dev, "%s: remove master failed: %d\n", __func__, ret1); -remove_slave: ret1 = sdw_stream_remove_slave(slave, cdns->bus.bpt_stream); if (ret1 < 0) dev_err(cdns->dev, "%s: remove slave failed: %d\n", __func__, ret1); release_stream: + mutex_lock(&cdns->bus.bus_lock); sdw_release_stream(cdns->bus.bpt_stream); cdns->bus.bpt_stream = NULL; + mutex_unlock(&cdns->bus.bus_lock); return ret; } @@ -335,8 +341,10 @@ static void intel_ace2x_bpt_close_stream(struct sdw_intel *sdw, struct sdw_slave dev_err(cdns->dev, "%s: remove slave failed: %d\n", __func__, ret); + mutex_lock(&cdns->bus.bus_lock); sdw_release_stream(cdns->bus.bpt_stream); cdns->bus.bpt_stream = NULL; + mutex_unlock(&cdns->bus.bus_lock); } #define INTEL_BPT_MSG_BYTE_MIN 16 diff --git a/drivers/soundwire/mipi_disco.c b/drivers/soundwire/mipi_disco.c index 8110a5399fd943..d90595a28dfaf0 100644 --- a/drivers/soundwire/mipi_disco.c +++ b/drivers/soundwire/mipi_disco.c @@ -279,12 +279,6 @@ static int sdw_slave_read_dpn(struct sdw_slave *slave, "mipi-sdw-imp-def-dpn-interrupts-supported", &dpn[i].imp_def_interrupts); - fwnode_property_read_u32(node, "mipi-sdw-min-channel-number", - &dpn[i].min_ch); - - fwnode_property_read_u32(node, "mipi-sdw-max-channel-number", - &dpn[i].max_ch); - nval = fwnode_property_count_u32(node, "mipi-sdw-channel-number-list"); if (nval > 0) { dpn[i].num_channels = nval; @@ -301,6 +295,14 @@ static int sdw_slave_read_dpn(struct sdw_slave *slave, dpn[i].channels, dpn[i].num_channels); if (ret < 0) return ret; + } else { + fwnode_property_read_u32(node, "mipi-sdw-min-channel-number", + &dpn[i].min_ch); + + ret = fwnode_property_read_u32(node, "mipi-sdw-max-channel-number", + &dpn[i].max_ch); + if (ret) + dpn[i].max_ch = 7; } nval = fwnode_property_count_u32(node, "mipi-sdw-channel-combination-list"); diff --git a/drivers/soundwire/qcom.c b/drivers/soundwire/qcom.c index 7c080869475876..6397cc43b4c34d 100644 --- a/drivers/soundwire/qcom.c +++ b/drivers/soundwire/qcom.c @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -47,6 +48,18 @@ #define SWRM_V3_COMP_PARAMS_RD_FIFO_DEPTH GENMASK(23, 18) #define SWRM_COMP_MASTER_ID 0x104 + +#define SWRM_V3_MM_SYNC_CONFIG 0x108 +#define SWRM_V3_MM_SYNC_CONNECTED_MASTER_MASK GENMASK(15, 0) +#define SWRM_V3_MM_SYNC_IS_DEPENDENT_MASTER BIT(16) +#define SWRM_V3_MM_SYNC_MASK_CONTROL_BITS BIT(17) + +#define SWRM_V3_COMP_FEATURE_CFG 0x10 +#define SWRM_V3_COMP_FEATURE_CFG_BASE 0x00E +#define SWRM_V3_COMP_FEATURE_CFG_FORCE_MODE_EN BIT(9) +#define SWRM_V3_COMP_FEATURE_CFG_CLK_PIN_AVAIL BIT(10) +#define SWRM_V3_COMP_FEATURE_CFG_CLK_STOP_EXEC_ON_CMD_IGNORE BIT(12) + #define SWRM_V1_3_INTERRUPT_STATUS 0x200 #define SWRM_V2_0_INTERRUPT_STATUS 0x5000 #define SWRM_INTERRUPT_STATUS_RMSK GENMASK(16, 0) @@ -113,6 +126,7 @@ #define SWRM_DPn_PORT_HCTRL_BANK(offset, n, m) (offset + 0x100 * (n - 1) + 0x40 * m) #define SWRM_DPn_BLOCK_CTRL3_BANK(offset, n, m) (offset + 0x100 * (n - 1) + 0x40 * m) #define SWRM_DPn_SAMPLECTRL2_BANK(offset, n, m) (offset + 0x100 * (n - 1) + 0x40 * m) +#define SWRM_DPn_SLOT_STRIDE 0x100 #define SWR_V1_3_MSTR_MAX_REG_ADDR 0x1740 #define SWR_V2_0_MSTR_MAX_REG_ADDR 0x50ac @@ -187,6 +201,12 @@ enum { SWRM_OFFSET_DP_SAMPLECTRL2_BANK, }; +enum qcom_swrm_mm_role { + QCOM_SWRM_MM_NONE, + QCOM_SWRM_MM_PRIMARY, + QCOM_SWRM_MM_DEPENDENT, +}; + struct qcom_swrm_ctrl { struct sdw_bus bus; struct device *dev; @@ -195,6 +215,12 @@ struct qcom_swrm_ctrl { const unsigned int *reg_layout; void __iomem *mmio; struct reset_control *audio_cgcr; + u8 num_lanes; + struct qcom_swrm_ctrl *peer_ctrl; + u8 peer_first_lane; + u8 num_peer_lanes; + enum qcom_swrm_mm_role mm_role; + u32 peer_dpn_offset; #ifdef CONFIG_DEBUG_FS struct dentry *debugfs; #endif @@ -935,6 +961,43 @@ static bool swrm_wait_for_frame_gen_enabled(struct qcom_swrm_ctrl *ctrl) return false; } +static void qcom_swrm_program_mm_sync(struct qcom_swrm_ctrl *ctrl) +{ + struct qcom_swrm_ctrl *peer = ctrl->peer_ctrl; + u32 conn_mask; + + if (!peer) + return; + + if (peer->bus.controller_id < 1) { + dev_warn_once(ctrl->dev, + "multi-master peer has no qcom,controller-id; MM_SYNC skipped\n"); + return; + } + + conn_mask = BIT(peer->bus.controller_id - 1) & + SWRM_V3_MM_SYNC_CONNECTED_MASTER_MASK; + + if (ctrl->mm_role == QCOM_SWRM_MM_PRIMARY) { + ctrl->reg_write(ctrl, SWRM_V3_MM_SYNC_CONFIG, conn_mask); + ctrl->reg_write(ctrl, SWRM_V3_COMP_FEATURE_CFG, + SWRM_V3_COMP_FEATURE_CFG_BASE | + SWRM_V3_COMP_FEATURE_CFG_FORCE_MODE_EN | + SWRM_V3_COMP_FEATURE_CFG_CLK_PIN_AVAIL | + SWRM_V3_COMP_FEATURE_CFG_CLK_STOP_EXEC_ON_CMD_IGNORE); + return; + } + + ctrl->reg_write(ctrl, SWRM_V3_MM_SYNC_CONFIG, + SWRM_V3_MM_SYNC_IS_DEPENDENT_MASTER | + SWRM_V3_MM_SYNC_MASK_CONTROL_BITS | conn_mask); + + ctrl->reg_write(ctrl, SWRM_V3_COMP_FEATURE_CFG, + SWRM_V3_COMP_FEATURE_CFG_BASE | + SWRM_V3_COMP_FEATURE_CFG_FORCE_MODE_EN | + SWRM_V3_COMP_FEATURE_CFG_CLK_STOP_EXEC_ON_CMD_IGNORE); +} + static int qcom_swrm_init(struct qcom_swrm_ctrl *ctrl) { u32 val; @@ -950,7 +1013,9 @@ static int qcom_swrm_init(struct qcom_swrm_ctrl *ctrl) /* Enable Auto enumeration */ ctrl->reg_write(ctrl, SWRM_ENUMERATOR_CFG_ADDR, 1); - ctrl->intr_mask = SWRM_INTERRUPT_STATUS_RMSK; + /* dependent has no sdw_bus; keep IRQ dispatch masked */ + if (ctrl->mm_role != QCOM_SWRM_MM_DEPENDENT) + ctrl->intr_mask = SWRM_INTERRUPT_STATUS_RMSK; /* Mask soundwire interrupts */ if (ctrl->version < SWRM_VERSION_2_0_0) ctrl->reg_write(ctrl, ctrl->reg_layout[SWRM_REG_INTERRUPT_MASK_ADDR], @@ -961,6 +1026,8 @@ static int qcom_swrm_init(struct qcom_swrm_ctrl *ctrl) u32p_replace_bits(&val, SWRM_DEF_CMD_NO_PINGS, SWRM_MCP_CFG_MAX_NUM_OF_CMD_NO_PINGS_BMSK); ctrl->reg_write(ctrl, SWRM_MCP_CFG_ADDR, val); + qcom_swrm_program_mm_sync(ctrl); + if (ctrl->version == SWRM_VERSION_1_7_0) { ctrl->reg_write(ctrl, SWRM_LINK_MANAGER_EE, ctrl->ee); ctrl->reg_write(ctrl, SWRM_MCP_BUS_CTRL, @@ -994,9 +1061,11 @@ static int qcom_swrm_init(struct qcom_swrm_ctrl *ctrl) ctrl->reg_write(ctrl, ctrl->reg_layout[SWRM_REG_INTERRUPT_CLEAR], 0xFFFFFFFF); - /* enable CPU IRQs for the selected EE window */ - ctrl->reg_write(ctrl, ctrl->reg_layout[SWRM_REG_INTERRUPT_CPU_EN], - SWRM_INTERRUPT_STATUS_RMSK); + /* enable CPU IRQs for the selected EE window; dependent has no sdw_bus */ + if (ctrl->mmio && ctrl->mm_role != QCOM_SWRM_MM_DEPENDENT) { + ctrl->reg_write(ctrl, ctrl->reg_layout[SWRM_REG_INTERRUPT_CPU_EN], + SWRM_INTERRUPT_STATUS_RMSK); + } /* Set IRQ to PULSE */ ctrl->reg_write(ctrl, SWRM_COMP_CFG_ADDR, @@ -1091,9 +1160,48 @@ static int qcom_swrm_pre_bank_switch(struct sdw_bus *bus) u32p_replace_bits(&val, ctrl->cols_index, SWRM_MCP_FRAME_CTRL_BANK_COL_CTRL_BMSK); u32p_replace_bits(&val, ctrl->rows_index, SWRM_MCP_FRAME_CTRL_BANK_ROW_CTRL_BMSK); + if (ctrl->peer_ctrl) + ctrl->peer_ctrl->reg_write(ctrl->peer_ctrl, reg, val); + return ctrl->reg_write(ctrl, reg, val); } +static struct qcom_swrm_ctrl * +qcom_swrm_port_target(struct qcom_swrm_ctrl *ctrl, u8 port_num, u32 *reg) +{ + u8 lane; + + if (WARN_ON_ONCE(!port_num || port_num > ctrl->nports)) + return ctrl; + + lane = ctrl->pconfig[port_num].lane_control; + + if (ctrl->peer_ctrl && lane >= ctrl->peer_first_lane && + lane < ctrl->peer_first_lane + ctrl->num_peer_lanes) { + if (WARN_ON_ONCE(*reg < ctrl->peer_dpn_offset)) + return ctrl; + *reg -= ctrl->peer_dpn_offset; + return ctrl->peer_ctrl; + } + return ctrl; +} + +static int qcom_swrm_port_reg_write(struct qcom_swrm_ctrl *ctrl, u8 port_num, + u32 reg, u32 val) +{ + struct qcom_swrm_ctrl *tgt = qcom_swrm_port_target(ctrl, port_num, ®); + + return tgt->reg_write(tgt, reg, val); +} + +static int qcom_swrm_port_reg_read(struct qcom_swrm_ctrl *ctrl, u8 port_num, + u32 reg, u32 *val) +{ + struct qcom_swrm_ctrl *tgt = qcom_swrm_port_target(ctrl, port_num, ®); + + return tgt->reg_read(tgt, reg, val); +} + static int qcom_swrm_port_params(struct sdw_bus *bus, struct sdw_port_params *p_params, unsigned int bank) @@ -1101,8 +1209,9 @@ static int qcom_swrm_port_params(struct sdw_bus *bus, struct qcom_swrm_ctrl *ctrl = to_qcom_sdw(bus); u32 offset = ctrl->reg_layout[SWRM_OFFSET_DP_BLOCK_CTRL_1]; - return ctrl->reg_write(ctrl, SWRM_DPn_BLOCK_CTRL_1(offset, p_params->num), - p_params->bps - 1); + return qcom_swrm_port_reg_write(ctrl, p_params->num, + SWRM_DPn_BLOCK_CTRL_1(offset, p_params->num), + p_params->bps - 1); } static int qcom_swrm_transport_params(struct sdw_bus *bus, @@ -1123,7 +1232,7 @@ static int qcom_swrm_transport_params(struct sdw_bus *bus, value |= pcfg->off2 << SWRM_DP_PORT_CTRL_OFFSET2_SHFT; value |= pcfg->si & 0xff; - ret = ctrl->reg_write(ctrl, reg, value); + ret = qcom_swrm_port_reg_write(ctrl, params->port_num, reg, value); if (ret) goto err; @@ -1132,7 +1241,7 @@ static int qcom_swrm_transport_params(struct sdw_bus *bus, value = (pcfg->si >> 8) & 0xff; reg = SWRM_DPn_SAMPLECTRL2_BANK(offset, params->port_num, bank); - ret = ctrl->reg_write(ctrl, reg, value); + ret = qcom_swrm_port_reg_write(ctrl, params->port_num, reg, value); if (ret) goto err; } @@ -1142,7 +1251,10 @@ static int qcom_swrm_transport_params(struct sdw_bus *bus, reg = SWRM_DPn_PORT_CTRL_2_BANK(offset, params->port_num, bank); value = pcfg->lane_control; - ret = ctrl->reg_write(ctrl, reg, value); + if (ctrl->peer_ctrl && value >= ctrl->peer_first_lane && + value < ctrl->peer_first_lane + ctrl->num_peer_lanes) + value -= ctrl->peer_first_lane; + ret = qcom_swrm_port_reg_write(ctrl, params->port_num, reg, value); if (ret) goto err; } @@ -1153,7 +1265,7 @@ static int qcom_swrm_transport_params(struct sdw_bus *bus, reg = SWRM_DPn_BLOCK_CTRL2_BANK(offset, params->port_num, bank); value = pcfg->blk_group_count; - ret = ctrl->reg_write(ctrl, reg, value); + ret = qcom_swrm_port_reg_write(ctrl, params->port_num, reg, value); if (ret) goto err; } @@ -1163,10 +1275,10 @@ static int qcom_swrm_transport_params(struct sdw_bus *bus, if (pcfg->hstart != SWR_INVALID_PARAM && pcfg->hstop != SWR_INVALID_PARAM) { value = (pcfg->hstop << 4) | pcfg->hstart; - ret = ctrl->reg_write(ctrl, reg, value); + ret = qcom_swrm_port_reg_write(ctrl, params->port_num, reg, value); } else { value = (SWR_HSTOP_MAX_VAL << 4) | SWR_HSTART_MIN_VAL; - ret = ctrl->reg_write(ctrl, reg, value); + ret = qcom_swrm_port_reg_write(ctrl, params->port_num, reg, value); } if (ret) @@ -1175,7 +1287,8 @@ static int qcom_swrm_transport_params(struct sdw_bus *bus, if (pcfg->bp_mode != SWR_INVALID_PARAM) { offset = ctrl->reg_layout[SWRM_OFFSET_DP_BLOCK_CTRL3_BANK]; reg = SWRM_DPn_BLOCK_CTRL3_BANK(offset, params->port_num, bank); - ret = ctrl->reg_write(ctrl, reg, pcfg->bp_mode); + ret = qcom_swrm_port_reg_write(ctrl, params->port_num, reg, + pcfg->bp_mode); } err: @@ -1193,14 +1306,14 @@ static int qcom_swrm_port_enable(struct sdw_bus *bus, reg = SWRM_DPn_PORT_CTRL_BANK(offset, enable_ch->port_num, bank); - ctrl->reg_read(ctrl, reg, &val); + qcom_swrm_port_reg_read(ctrl, enable_ch->port_num, reg, &val); if (enable_ch->enable) val |= (enable_ch->ch_mask << SWRM_DP_PORT_CTRL_EN_CHAN_SHFT); else val &= ~(0xff << SWRM_DP_PORT_CTRL_EN_CHAN_SHFT); - return ctrl->reg_write(ctrl, reg, val); + return qcom_swrm_port_reg_write(ctrl, enable_ch->port_num, reg, val); } static const struct sdw_master_port_ops qcom_swrm_port_ops = { @@ -1307,7 +1420,7 @@ static int qcom_swrm_stream_alloc_ports(struct qcom_swrm_ctrl *ctrl, struct sdw_slave_runtime *s_rt; struct sdw_port_runtime *p_rt; struct sdw_slave *slave; - unsigned long *port_mask; + unsigned long *port_mask, allocated = 0; int maxport, pn, nports = 0; unsigned int m_port; struct sdw_port_config *pconfig __free(kfree) = kzalloc_objs(*pconfig, @@ -1351,11 +1464,13 @@ static int qcom_swrm_stream_alloc_ports(struct qcom_swrm_ctrl *ctrl, else pn = find_first_zero_bit(port_mask, maxport); - if (pn >= maxport) { + if (pn >= maxport || nports >= maxport) { dev_err(ctrl->dev, "All ports busy\n"); + *port_mask &= ~allocated; return -EBUSY; } - set_bit(pn, port_mask); + if (!test_and_set_bit(pn, port_mask)) + __set_bit(pn, &allocated); pconfig[nports].num = pn; pconfig[nports].ch_mask = p_rt->ch_mask; nports++; @@ -1614,6 +1729,103 @@ static int swrm_reg_show(struct seq_file *s_file, void *data) DEFINE_SHOW_ATTRIBUTE(swrm_reg); #endif +static int qcom_swrm_multi_master_setup(struct qcom_swrm_ctrl *ctrl) +{ + struct of_phandle_args args; + struct qcom_swrm_ctrl *peer; + struct platform_device *pdev; + u32 offset; + int ret; + + if (ctrl->peer_ctrl) { + dev_err(ctrl->dev, "multi-master peer already paired\n"); + return -EBUSY; + } + + ret = of_parse_phandle_with_fixed_args(ctrl->dev->of_node, + "qcom,multi-master-peer", + 1, 0, &args); + if (ret) + return -EINVAL; + + pdev = of_find_device_by_node(args.np); + of_node_put(args.np); + if (!pdev) + return -EPROBE_DEFER; + + /* + * Lock the peer device while we inspect its driver binding and + * drvdata. This prevents a concurrent sysfs unbind from dropping + * pdev->dev.driver between the check below and the drvdata read; + * it also covers the mid-probe case: if the peer has not finished + * binding yet, pdev->dev.driver is NULL and we defer so driver + * core reprobes us once it is bound. + */ + device_lock(&pdev->dev); + + if (!pdev->dev.driver) { + ret = -EPROBE_DEFER; + goto out_unlock; + } + + if (pdev->dev.driver != ctrl->dev->driver) { + ret = -EINVAL; + goto out_unlock; + } + + peer = platform_get_drvdata(pdev); + if (!peer || peer->mm_role != QCOM_SWRM_MM_DEPENDENT) { + ret = -EPROBE_DEFER; + goto out_unlock; + } + + if (peer->peer_ctrl) { + dev_err(ctrl->dev, "multi-master peer %s already claimed\n", + dev_name(&pdev->dev)); + ret = -EBUSY; + goto out_unlock; + } + + if (!ctrl->num_lanes || !peer->num_lanes || + ctrl->num_lanes + peer->num_lanes > SDW_MAX_LANES) { + ret = -EINVAL; + goto out_unlock; + } + + offset = args.args[0]; + if (offset < ctrl->num_lanes) { + dev_err(ctrl->dev, "qcom,multi-master-peer: offset %u < num-lanes %u\n", + offset, ctrl->num_lanes); + ret = -EINVAL; + goto out_unlock; + } + + /* + * The dependent's hclk is gated from its own runtime PM; keep it + * active while the primary is, and resume it now as the rest of + * probe programs the peer's registers. + */ + if (!device_link_add(ctrl->dev, &pdev->dev, + DL_FLAG_AUTOREMOVE_CONSUMER | DL_FLAG_PM_RUNTIME | + DL_FLAG_RPM_ACTIVE)) { + ret = -EINVAL; + goto out_unlock; + } + + ctrl->peer_first_lane = ctrl->num_lanes; + ctrl->num_peer_lanes = peer->num_lanes; + ctrl->peer_dpn_offset = offset * SWRM_DPn_SLOT_STRIDE; + /* publish the cross-refs last so readers never see partial state */ + ctrl->peer_ctrl = peer; + peer->peer_ctrl = ctrl; + + ret = 0; +out_unlock: + device_unlock(&pdev->dev); + put_device(&pdev->dev); + return ret; +} + static int qcom_swrm_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; @@ -1628,6 +1840,9 @@ static int qcom_swrm_probe(struct platform_device *pdev) if (!ctrl) return -ENOMEM; + if (!of_property_read_u32(dev->of_node, "num-lanes", &val)) + ctrl->num_lanes = val; + memset(ctrl->page1_cache, 0xff, sizeof(ctrl->page1_cache)); memset(ctrl->page2_cache, 0xff, sizeof(ctrl->page2_cache)); @@ -1689,9 +1904,19 @@ static int qcom_swrm_probe(struct platform_device *pdev) ctrl->bus.compute_params = &qcom_swrm_compute_params; ctrl->bus.clk_stop_timeout = 300; - ret = qcom_swrm_get_port_config(ctrl); - if (ret) - goto err_clk; + if (of_property_match_string(dev->of_node, "qcom,multi-master-mode", + "dependent") < 0) { + ret = qcom_swrm_get_port_config(ctrl); + if (ret) + goto err_clk; + } + + if (of_property_match_string(dev->of_node, "qcom,multi-master-mode", "primary") >= 0) { + ctrl->mm_role = QCOM_SWRM_MM_PRIMARY; + ret = qcom_swrm_multi_master_setup(ctrl); + if (ret) + goto err_clk; + } params = &ctrl->bus.params; params->max_dr_freq = DEFAULT_CLK_FREQ; @@ -1732,7 +1957,7 @@ static int qcom_swrm_probe(struct platform_device *pdev) "swr_wake_irq", ctrl); if (ret) { dev_err(dev, "Failed to request soundwire wake irq\n"); - goto err_init; + goto err_clk; } } @@ -1743,6 +1968,19 @@ static int qcom_swrm_probe(struct platform_device *pdev) ctrl->bus.controller_id = val; } + if (of_property_match_string(dev->of_node, "qcom,multi-master-mode", "dependent") >= 0) { + ctrl->mm_role = QCOM_SWRM_MM_DEPENDENT; + dev_dbg(dev, + "Qualcomm SoundWire multi-master dependent v%x.%x.%x registered (%u lanes)\n", + (ctrl->version >> 24) & 0xff, + (ctrl->version >> 16) & 0xff, + ctrl->version & 0xffff, ctrl->num_lanes); + /* runtime PM is driven by the primary through the device link */ + pm_runtime_set_active(dev); + pm_runtime_enable(dev); + return 0; + } + ret = sdw_bus_master_add(&ctrl->bus, dev, dev->fwnode); if (ret) { dev_err(dev, "Failed to register Soundwire controller (%d)\n", @@ -1751,6 +1989,15 @@ static int qcom_swrm_probe(struct platform_device *pdev) } qcom_swrm_init(ctrl); + + if (ctrl->mm_role == QCOM_SWRM_MM_PRIMARY && ctrl->peer_ctrl) { + ret = qcom_swrm_init(ctrl->peer_ctrl); + if (ret) { + dev_err(dev, "peer init failed: %d\n", ret); + goto err_master_add; + } + } + wait_for_completion_timeout(&ctrl->enumeration, msecs_to_jiffies(TIMEOUT_MS)); ret = qcom_swrm_register_dais(ctrl); @@ -1778,6 +2025,17 @@ static int qcom_swrm_probe(struct platform_device *pdev) err_master_add: sdw_bus_master_delete(&ctrl->bus); err_clk: + /* tear down cross-link + mask peer IRQs before devres frees us */ + if (ctrl->mm_role == QCOM_SWRM_MM_PRIMARY && ctrl->peer_ctrl) { + struct qcom_swrm_ctrl *peer = ctrl->peer_ctrl; + + peer->reg_write(peer, + peer->reg_layout[SWRM_REG_INTERRUPT_CPU_EN], 0); + /* disable peer SWRM; releases shared SWR_CLK */ + peer->reg_write(peer, SWRM_COMP_CFG_ADDR, 0); + peer->peer_ctrl = NULL; + ctrl->peer_ctrl = NULL; + } clk_disable_unprepare(ctrl->hclk); err_init: return ret; @@ -1787,7 +2045,35 @@ static void qcom_swrm_remove(struct platform_device *pdev) { struct qcom_swrm_ctrl *ctrl = dev_get_drvdata(&pdev->dev); + if (ctrl->mm_role == QCOM_SWRM_MM_DEPENDENT) { + pm_runtime_disable(&pdev->dev); + if (!pm_runtime_status_suspended(&pdev->dev)) + clk_disable_unprepare(ctrl->hclk); + return; + } + + /* delete bus before dropping peer_ctrl; in-flight ops deref it */ sdw_bus_master_delete(&ctrl->bus); + + if (ctrl->mm_role == QCOM_SWRM_MM_PRIMARY && ctrl->peer_ctrl) { + struct qcom_swrm_ctrl *peer = ctrl->peer_ctrl; + int ret; + + /* peer hclk may be gated by runtime PM */ + ret = pm_runtime_resume_and_get(peer->dev); + if (ret < 0) { + dev_err(&pdev->dev, "peer resume failed on remove: %d\n", ret); + } else { + peer->reg_write(peer, + peer->reg_layout[SWRM_REG_INTERRUPT_CPU_EN], 0); + /* disable peer SWRM; releases shared SWR_CLK */ + peer->reg_write(peer, SWRM_COMP_CFG_ADDR, 0); + pm_runtime_put(peer->dev); + } + peer->peer_ctrl = NULL; + ctrl->peer_ctrl = NULL; + } + clk_disable_unprepare(ctrl->hclk); } @@ -1796,12 +2082,17 @@ static int __maybe_unused swrm_runtime_resume(struct device *dev) struct qcom_swrm_ctrl *ctrl = dev_get_drvdata(dev); int ret; + /* no bus of its own; the primary restarts the link */ + if (ctrl->mm_role == QCOM_SWRM_MM_DEPENDENT) + return clk_prepare_enable(ctrl->hclk); + if (ctrl->wake_irq > 0) { if (!irqd_irq_disabled(irq_get_irq_data(ctrl->wake_irq))) disable_irq_nosync(ctrl->wake_irq); } clk_prepare_enable(ctrl->hclk); + enable_irq(ctrl->irq); if (ctrl->clock_stop_not_supported) { reinit_completion(&ctrl->enumeration); @@ -1822,6 +2113,11 @@ static int __maybe_unused swrm_runtime_resume(struct device *dev) } else { reset_control_reset(ctrl->audio_cgcr); + qcom_swrm_program_mm_sync(ctrl); + /* dependent was resumed first via the device link */ + if (ctrl->mm_role == QCOM_SWRM_MM_PRIMARY && ctrl->peer_ctrl) + qcom_swrm_program_mm_sync(ctrl->peer_ctrl); + if (ctrl->version == SWRM_VERSION_1_7_0) { ctrl->reg_write(ctrl, SWRM_LINK_MANAGER_EE, ctrl->ee); ctrl->reg_write(ctrl, SWRM_MCP_BUS_CTRL, @@ -1864,6 +2160,12 @@ static int __maybe_unused swrm_runtime_suspend(struct device *dev) struct qcom_swrm_ctrl *ctrl = dev_get_drvdata(dev); int ret; + /* the primary has already stopped the bus clock */ + if (ctrl->mm_role == QCOM_SWRM_MM_DEPENDENT) { + clk_disable_unprepare(ctrl->hclk); + return 0; + } + swrm_wait_for_wr_fifo_done(ctrl); if (!ctrl->clock_stop_not_supported) { /* Mask bus clash interrupt */ @@ -1888,6 +2190,7 @@ static int __maybe_unused swrm_runtime_suspend(struct device *dev) } } + disable_irq(ctrl->irq); clk_disable_unprepare(ctrl->hclk); usleep_range(300, 305); diff --git a/drivers/soundwire/stream.c b/drivers/soundwire/stream.c index 06a0d89a944378..9a8a6571434e77 100644 --- a/drivers/soundwire/stream.c +++ b/drivers/soundwire/stream.c @@ -1034,14 +1034,18 @@ static int sdw_slave_port_alloc(struct sdw_slave *slave, struct sdw_slave_runtime *s_rt, unsigned int num_config) { - struct sdw_port_runtime *p_rt; + struct sdw_port_runtime *p_rt, *_p_rt; int i; /* Iterate for number of ports to perform initialization */ for (i = 0; i < num_config; i++) { p_rt = sdw_port_alloc(&s_rt->port_list); - if (!p_rt) + if (!p_rt) { + list_for_each_entry_safe(p_rt, _p_rt, + &s_rt->port_list, port_node) + sdw_port_free(p_rt); return -ENOMEM; + } } return 0; @@ -1057,16 +1061,16 @@ static int sdw_slave_port_is_valid_range(struct device *dev, int num) return 0; } -static int sdw_slave_port_config(struct sdw_slave *slave, - struct sdw_slave_runtime *s_rt, - const struct sdw_port_config *port_config, - bool is_bpt_stream) +static int sdw_slave_port_config_valid(struct sdw_slave *slave, + struct sdw_slave_runtime *s_rt, + const struct sdw_stream_config *stream_config, + const struct sdw_port_config *port_config) { + bool is_bpt_stream = stream_config->type == SDW_STREAM_BPT; struct sdw_port_runtime *p_rt; int ret; - int i; + int i = 0; - i = 0; list_for_each_entry(p_rt, &s_rt->port_list, port_node) { if (!is_bpt_stream) { ret = sdw_slave_port_is_valid_range(&slave->dev, port_config[i].num); @@ -1077,18 +1081,32 @@ static int sdw_slave_port_config(struct sdw_slave *slave, * A port in the generic valid range may still be unsupported by * the Slave or unavailable for the requested stream direction. */ - if (!sdw_get_slave_dpn_prop(slave, s_rt->direction, + if (!sdw_get_slave_dpn_prop(slave, stream_config->direction, port_config[i].num)) { dev_err(&slave->dev, "port %u not supported for %s\n", port_config[i].num, - s_rt->direction == SDW_DATA_DIR_TX ? "TX" : "RX"); + stream_config->direction == SDW_DATA_DIR_TX ? + "TX" : "RX"); return -EINVAL; } } else if (port_config[i].num) { return -EINVAL; } + i++; + } + return 0; +} + +static int sdw_slave_port_config(struct sdw_slave_runtime *s_rt, + const struct sdw_port_config *port_config) +{ + struct sdw_port_runtime *p_rt; + int ret; + int i = 0; + + list_for_each_entry(p_rt, &s_rt->port_list, port_node) { ret = sdw_port_config(p_rt, port_config, i); if (ret < 0) return ret; @@ -1122,8 +1140,10 @@ static int sdw_master_port_alloc(struct sdw_master_runtime *m_rt, /* Iterate for number of ports to perform initialization */ for (i = 0; i < num_ports; i++) { p_rt = sdw_port_alloc(&m_rt->port_list); - if (!p_rt) + if (!p_rt) { + sdw_master_port_free(m_rt); return -ENOMEM; + } } return 0; @@ -2037,6 +2057,7 @@ int sdw_stream_add_master(struct sdw_bus *bus, struct sdw_stream_runtime *stream) { struct sdw_master_runtime *m_rt; + bool alloc_master_port = false; bool alloc_master_rt = false; int ret; @@ -2082,18 +2103,23 @@ int sdw_stream_add_master(struct sdw_bus *bus, if (ret) goto alloc_error; - stream->m_rt_count++; + if (sdw_master_port_allocated(m_rt)) { + alloc_master_port = true; + stream->m_rt_count++; + } } - ret = sdw_master_rt_config(m_rt, stream_config); - if (ret < 0) - goto unlock; - ret = sdw_config_stream(bus->dev, stream, stream_config, false); if (ret) - goto unlock; + goto alloc_error; + + ret = sdw_master_rt_config(m_rt, stream_config); + if (ret < 0) + goto alloc_error; ret = sdw_master_port_config(m_rt, port_config); + if (ret) + goto alloc_error; goto unlock; @@ -2101,6 +2127,10 @@ int sdw_stream_add_master(struct sdw_bus *bus, /* * we only cleanup what was allocated in this routine */ + if (alloc_master_port) { + sdw_master_port_free(m_rt); + stream->m_rt_count--; + } if (alloc_master_rt) sdw_master_rt_free(m_rt, stream); unlock: @@ -2129,9 +2159,10 @@ int sdw_stream_remove_master(struct sdw_bus *bus, if (m_rt->bus != bus) continue; + if (sdw_master_port_allocated(m_rt)) + stream->m_rt_count--; sdw_master_port_free(m_rt); sdw_master_rt_free(m_rt, stream); - stream->m_rt_count--; } if (list_empty(&stream->master_list)) @@ -2165,6 +2196,7 @@ int sdw_stream_add_slave(struct sdw_slave *slave, struct sdw_slave_runtime *s_rt; struct sdw_master_runtime *m_rt; bool alloc_master_rt = false; + bool alloc_slave_port = false; bool alloc_slave_rt = false; int ret; @@ -2215,24 +2247,30 @@ int sdw_stream_add_slave(struct sdw_slave *slave, ret = sdw_slave_port_alloc(slave, s_rt, num_ports); if (ret) goto alloc_error; + + alloc_slave_port = true; } - ret = sdw_master_rt_config(m_rt, stream_config); + ret = sdw_slave_port_config_valid(slave, s_rt, stream_config, + port_config); if (ret) - goto unlock; + goto alloc_error; - ret = sdw_slave_rt_config(s_rt, stream_config); + ret = sdw_config_stream(&slave->dev, stream, stream_config, true); if (ret) - goto unlock; + goto alloc_error; - ret = sdw_config_stream(&slave->dev, stream, stream_config, true); + ret = sdw_master_rt_config(m_rt, stream_config); if (ret) - goto unlock; + goto alloc_error; - ret = sdw_slave_port_config(slave, s_rt, port_config, - stream->type == SDW_STREAM_BPT); + ret = sdw_slave_rt_config(s_rt, stream_config); if (ret) - goto unlock; + goto alloc_error; + + ret = sdw_slave_port_config(s_rt, port_config); + if (ret) + goto alloc_error; /* * Change stream state to CONFIGURED on first Slave add. @@ -2249,6 +2287,8 @@ int sdw_stream_add_slave(struct sdw_slave *slave, * is intentional, the 'master_rt_free' will call sdw_slave_rt_free() * internally. */ + if (alloc_slave_port) + sdw_slave_port_free(slave, stream); if (alloc_master_rt) sdw_master_rt_free(m_rt, stream); else if (alloc_slave_rt) diff --git a/drivers/soundwire/sysfs_slave.c b/drivers/soundwire/sysfs_slave.c index a2ee064147e05a..35272cfe9fc8b5 100644 --- a/drivers/soundwire/sysfs_slave.c +++ b/drivers/soundwire/sysfs_slave.c @@ -161,9 +161,9 @@ static ssize_t words_show(struct device *dev, int i; for (i = 0; i < slave->prop.dp0_prop->num_words; i++) - size += sprintf(buf + size, "%d ", - slave->prop.dp0_prop->words[i]); - size += sprintf(buf + size, "\n"); + size += sysfs_emit_at(buf, size, "%d ", + slave->prop.dp0_prop->words[i]); + size += sysfs_emit_at(buf, size, "\n"); return size; } diff --git a/drivers/soundwire/sysfs_slave_dpn.c b/drivers/soundwire/sysfs_slave_dpn.c index d280913160a4b2..426894aeb5cf42 100644 --- a/drivers/soundwire/sysfs_slave_dpn.c +++ b/drivers/soundwire/sysfs_slave_dpn.c @@ -134,10 +134,10 @@ static ssize_t field##_dpn_show(struct sdw_slave *slave, \ for_each_set_bit(bit, &mask, 32) { \ if (bit == N) { \ for (j = 0; j < dpn[i].num_##field; j++) \ - size += sprintf(buf + size, \ - format_string, \ - dpn[i].field[j]); \ - size += sprintf(buf + size, "\n"); \ + size += sysfs_emit_at(buf, size, \ + format_string, \ + dpn[i].field[j]); \ + size += sysfs_emit_at(buf, size, "\n"); \ return size; \ } \ i++; \ diff --git a/drivers/spi/spi-fsl-lpspi.c b/drivers/spi/spi-fsl-lpspi.c index b25f94b2ef738f..cea72d0340357c 100644 --- a/drivers/spi/spi-fsl-lpspi.c +++ b/drivers/spi/spi-fsl-lpspi.c @@ -75,8 +75,8 @@ #define CFGR1_PCSPOL_MASK GENMASK(11, 8) #define CFGR1_NOSTALL BIT(3) #define CFGR1_HOST BIT(0) -#define FCR_RXWATER GENMASK(18, 16) -#define FCR_TXWATER GENMASK(2, 0) +#define FCR_RXWATER GENMASK(19, 16) +#define FCR_TXWATER GENMASK(3, 0) #define FSR_TXCOUNT (0xFF) #define RSR_RXEMPTY BIT(1) #define TCR_CPOL BIT(31) diff --git a/drivers/spi/spi-geni-qcom.c b/drivers/spi/spi-geni-qcom.c index 91e75e213f929e..bde3d434e4ca20 100644 --- a/drivers/spi/spi-geni-qcom.c +++ b/drivers/spi/spi-geni-qcom.c @@ -14,7 +14,6 @@ #include #include #include -#include #include #include #include @@ -306,22 +305,26 @@ static bool spi_geni_is_abort_still_pending(struct spi_geni_master *mas) return false; } +static unsigned int geni_spi_words_per_fifo(struct spi_geni_master *mas, + unsigned int bits_per_word) +{ + /* Each sub-byte SPI word occupies a separate byte in memory. */ + unsigned int packing_bits = max_t(unsigned int, bits_per_word, BITS_PER_BYTE); + + if (mas->fifo_width_bits % packing_bits) + return 1; + + return mas->fifo_width_bits / packing_bits; +} + static void spi_setup_word_len(struct spi_geni_master *mas, u16 mode, unsigned int bits_per_word) { - unsigned int pack_words; + unsigned int pack_words = geni_spi_words_per_fifo(mas, bits_per_word); bool msb_first = (mode & SPI_LSB_FIRST) ? false : true; struct geni_se *se = &mas->se; u32 word_len; - /* - * If bits_per_word isn't a byte aligned value, set the packing to be - * 1 SPI word per FIFO word. - */ - if (!(mas->fifo_width_bits % bits_per_word)) - pack_words = mas->fifo_width_bits / bits_per_word; - else - pack_words = 1; geni_se_config_packing(&mas->se, bits_per_word, pack_words, msb_first, true, true); word_len = (bits_per_word - MIN_WORD_LEN) & WORD_LEN_MSK; @@ -451,13 +454,7 @@ static int setup_gsi_xfer(struct spi_transfer *xfer, struct spi_geni_master *mas peripheral.rx_len = 0; } else if (xfer->rx_buf) { peripheral.cmd = SPI_RX; - if (!(mas->cur_bits_per_word % MIN_WORD_LEN)) { - peripheral.rx_len = ((xfer->len << 3) / mas->cur_bits_per_word); - } else { - int bytes_per_word = (mas->cur_bits_per_word / BITS_PER_BYTE) + 1; - - peripheral.rx_len = (xfer->len / bytes_per_word); - } + peripheral.rx_len = xfer->len / spi_bpw_to_bytes(xfer->bits_per_word); } peripheral.loopback_en = !!(spi_slv->mode & SPI_LOOP); @@ -523,15 +520,7 @@ static int setup_gsi_xfer(struct spi_transfer *xfer, struct spi_geni_master *mas static u32 get_xfer_len_in_words(struct spi_transfer *xfer, struct spi_geni_master *mas) { - u32 len; - - if (!(xfer->bits_per_word % MIN_WORD_LEN)) - len = xfer->len * BITS_PER_BYTE / xfer->bits_per_word; - else - len = xfer->len / (xfer->bits_per_word / BITS_PER_BYTE + 1); - len &= TRANS_LEN_MSK; - - return len; + return (xfer->len / spi_bpw_to_bytes(xfer->bits_per_word)) & TRANS_LEN_MSK; } static bool geni_can_dma(struct spi_controller *ctlr, @@ -548,7 +537,7 @@ static bool geni_can_dma(struct spi_controller *ctlr, return true; len = get_xfer_len_in_words(xfer, mas); - fifo_size = mas->tx_fifo_depth * mas->fifo_width_bits / xfer->bits_per_word; + fifo_size = mas->tx_fifo_depth * geni_spi_words_per_fifo(mas, xfer->bits_per_word); if (len > fifo_size) return true; @@ -725,16 +714,8 @@ static int spi_geni_init(struct spi_geni_master *mas) static unsigned int geni_byte_per_fifo_word(struct spi_geni_master *mas) { - /* - * Calculate how many bytes we'll put in each FIFO word. If the - * transfer words don't pack cleanly into a FIFO word we'll just put - * one transfer word in each FIFO word. If they do pack we'll pack 'em. - */ - if (mas->fifo_width_bits % mas->cur_bits_per_word) - return roundup_pow_of_two(DIV_ROUND_UP(mas->cur_bits_per_word, - BITS_PER_BYTE)); - - return mas->fifo_width_bits / BITS_PER_BYTE; + return geni_spi_words_per_fifo(mas, mas->cur_bits_per_word) * + spi_bpw_to_bytes(mas->cur_bits_per_word); } static bool geni_spi_handle_tx(struct spi_geni_master *mas) @@ -742,7 +723,7 @@ static bool geni_spi_handle_tx(struct spi_geni_master *mas) struct geni_se *se = &mas->se; unsigned int max_bytes; const u8 *tx_buf; - unsigned int bytes_per_fifo_word = geni_byte_per_fifo_word(mas); + unsigned int bytes_per_fifo_word; unsigned int i = 0; /* Stop the watermark IRQ if nothing to send */ @@ -751,6 +732,7 @@ static bool geni_spi_handle_tx(struct spi_geni_master *mas) return false; } + bytes_per_fifo_word = geni_byte_per_fifo_word(mas); max_bytes = (mas->tx_fifo_depth - mas->tx_wm) * bytes_per_fifo_word; if (mas->tx_rem_bytes < max_bytes) max_bytes = mas->tx_rem_bytes; @@ -782,25 +764,30 @@ static void geni_spi_handle_rx(struct spi_geni_master *mas) unsigned int rx_bytes; unsigned int rx_last_byte_valid; u8 *rx_buf; - unsigned int bytes_per_fifo_word = geni_byte_per_fifo_word(mas); + unsigned int bytes_per_fifo_word; unsigned int i = 0; rx_fifo_status = readl(se->base + SE_GENI_RX_FIFO_STATUS); + + /* Clear out the FIFO and bail if nowhere to put it. */ + if (!mas->cur_xfer || !mas->cur_xfer->rx_buf) { + for (i = 0; i < (rx_fifo_status & RX_FIFO_WC_MSK); i++) + readl(se->base + SE_GENI_RX_FIFOn); + return; + } + + bytes_per_fifo_word = geni_byte_per_fifo_word(mas); rx_bytes = (rx_fifo_status & RX_FIFO_WC_MSK) * bytes_per_fifo_word; if (rx_fifo_status & RX_LAST) { rx_last_byte_valid = rx_fifo_status & RX_LAST_BYTE_VALID_MSK; rx_last_byte_valid >>= RX_LAST_BYTE_VALID_SHFT; - if (rx_last_byte_valid && rx_last_byte_valid < 4) + /* Include the padding in the last in-memory SPI word. */ + rx_last_byte_valid = round_up(rx_last_byte_valid, + spi_bpw_to_bytes(mas->cur_bits_per_word)); + if (rx_last_byte_valid && rx_last_byte_valid < bytes_per_fifo_word) rx_bytes -= bytes_per_fifo_word - rx_last_byte_valid; } - /* Clear out the FIFO and bail if nowhere to put it */ - if (!mas->cur_xfer) { - for (i = 0; i < DIV_ROUND_UP(rx_bytes, bytes_per_fifo_word); i++) - readl(se->base + SE_GENI_RX_FIFOn); - return; - } - if (mas->rx_rem_bytes < rx_bytes) rx_bytes = mas->rx_rem_bytes; diff --git a/drivers/spi/spi.c b/drivers/spi/spi.c index 8a06fb4e309a96..f57f8d5c04345c 100644 --- a/drivers/spi/spi.c +++ b/drivers/spi/spi.c @@ -1967,7 +1967,6 @@ static int __spi_pump_transfer_message(struct spi_controller *ctlr, if (!was_busy && ctlr->auto_runtime_pm) { ret = pm_runtime_get_sync(ctlr->dev.parent); if (ret < 0) { - pm_runtime_put_noidle(ctlr->dev.parent); dev_err(&ctlr->dev, "Failed to power device: %d\n", ret); @@ -1988,9 +1987,6 @@ static int __spi_pump_transfer_message(struct spi_controller *ctlr, "failed to prepare transfer hardware: %d\n", ret); - if (ctlr->auto_runtime_pm) - pm_runtime_put(ctlr->dev.parent); - msg->status = ret; spi_finalize_current_message(ctlr); diff --git a/drivers/staging/Kconfig b/drivers/staging/Kconfig index 46b460bfb4361a..7c57f362f1b7e7 100644 --- a/drivers/staging/Kconfig +++ b/drivers/staging/Kconfig @@ -44,6 +44,4 @@ source "drivers/staging/vc04_services/Kconfig" source "drivers/staging/axis-fifo/Kconfig" -source "drivers/staging/vme_user/Kconfig" - endif # STAGING diff --git a/drivers/staging/Makefile b/drivers/staging/Makefile index 7e2e7a7e773ad2..f827853ad8a6b1 100644 --- a/drivers/staging/Makefile +++ b/drivers/staging/Makefile @@ -3,7 +3,6 @@ obj-y += media/ obj-$(CONFIG_OCTEON_ETHERNET) += octeon/ -obj-$(CONFIG_VME_BUS) += vme_user/ obj-$(CONFIG_IIO) += iio/ obj-$(CONFIG_FB_SM750) += sm750fb/ obj-$(CONFIG_MFD_NVEC) += nvec/ diff --git a/drivers/staging/vme_user/Kconfig b/drivers/staging/vme_user/Kconfig deleted file mode 100644 index 8e5df6ce36e8f9..00000000000000 --- a/drivers/staging/vme_user/Kconfig +++ /dev/null @@ -1,53 +0,0 @@ -# SPDX-License-Identifier: GPL-2.0 -menuconfig VME_BUS - bool "VME bridge support" - depends on PCI - help - Enable support for VME (VersaModular Eurocard bus) bridge modules. - The bridge allows connecting VME devices to systems with existing - interfaces (like USB or PCI) by means of translating VME protocol - operations. - - Note that this only enables the bridge framework. You'll also - likely want to enable driver for specific bridge device you have - to actually use it. If unsure, say N. - -if VME_BUS - -comment "VME Bridge Drivers" - -config VME_TSI148 - tristate "Tundra TSI148 VME bridge support" - depends on HAS_DMA - help - If you say Y here you get support for the Tundra TSI148 VME-to-PCI/X - bridge chip (and pin-compatible clones). - - TSI148 is a high-performant, 2eSST and VME64-compliant VME-to-PCI/X - interconnect bridge with support for PCI and PCI-X bus interface. - It is primarily used in industrial and embedded systems. - - To compile this driver as a module, say M - the module will be - called vme_tsi148. If unsure, say N. - -config VME_FAKE - tristate "Fake" - help - If you say Y here you get support for the fake VME bridge. This - provides a virtualised VME Bus for devices with no VME bridge. This - is mainly useful for VME development (in the absence of VME - hardware). - -comment "VME Device Drivers" - -config VME_USER - tristate "VME user space access driver" - help - If you say Y here you want to be able to access a limited number of - VME windows in a manner at least semi-compatible with the interface - provided with the original driver at . - - To compile this driver as a module, choose M here. The module will - be called vme_user. If unsure, say N. - -endif diff --git a/drivers/staging/vme_user/Makefile b/drivers/staging/vme_user/Makefile deleted file mode 100644 index 8dcc6938ce5c56..00000000000000 --- a/drivers/staging/vme_user/Makefile +++ /dev/null @@ -1,9 +0,0 @@ -# SPDX-License-Identifier: GPL-2.0 -# -# Makefile for the VME device drivers. -# - -obj-$(CONFIG_VME_BUS) += vme.o -obj-$(CONFIG_VME_USER) += vme_user.o -obj-$(CONFIG_VME_TSI148) += vme_tsi148.o -obj-$(CONFIG_VME_FAKE) += vme_fake.o diff --git a/drivers/staging/vme_user/vme.c b/drivers/staging/vme_user/vme.c deleted file mode 100644 index d38c792eb89056..00000000000000 --- a/drivers/staging/vme_user/vme.c +++ /dev/null @@ -1,1977 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-or-later -/* - * VME Bridge Framework - * - * Author: Martyn Welch - * Copyright 2008 GE Intelligent Platforms Embedded Systems, Inc. - * - * Based on work by Tom Armistead and Ajit Prem - * Copyright 2004 Motorola Inc. - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "vme.h" -#include "vme_bridge.h" - -/* Bitmask and list of registered buses both protected by common mutex */ -static unsigned int vme_bus_numbers; -static LIST_HEAD(vme_bus_list); -static DEFINE_MUTEX(vme_buses_lock); - -static int __init vme_init(void); - -static struct vme_dev *dev_to_vme_dev(struct device *dev) -{ - return container_of(dev, struct vme_dev, dev); -} - -/* - * Find the bridge that the resource is associated with. - */ -static struct vme_bridge *find_bridge(struct vme_resource *resource) -{ - /* Get list to search */ - switch (resource->type) { - case VME_MASTER: - return list_entry(resource->entry, struct vme_master_resource, - list)->parent; - case VME_SLAVE: - return list_entry(resource->entry, struct vme_slave_resource, - list)->parent; - case VME_DMA: - return list_entry(resource->entry, struct vme_dma_resource, - list)->parent; - case VME_LM: - return list_entry(resource->entry, struct vme_lm_resource, - list)->parent; - default: - return NULL; - } -} - -/** - * vme_alloc_consistent - Allocate contiguous memory. - * @resource: Pointer to VME resource. - * @size: Size of allocation required. - * @dma: Pointer to variable to store physical address of allocation. - * - * Allocate a contiguous block of memory for use by the driver. This is used to - * create the buffers for the slave windows. - * - * Return: Virtual address of allocation on success, NULL on failure. - */ -void *vme_alloc_consistent(struct vme_resource *resource, size_t size, - dma_addr_t *dma) -{ - struct vme_bridge *bridge = find_bridge(resource); - - if (!bridge->alloc_consistent) { - dev_err(bridge->parent, - "alloc_consistent not supported by bridge %s\n", - bridge->name); - return NULL; - } - - return bridge->alloc_consistent(bridge->parent, size, dma); -} -EXPORT_SYMBOL(vme_alloc_consistent); - -/** - * vme_free_consistent - Free previously allocated memory. - * @resource: Pointer to VME resource. - * @size: Size of allocation to free. - * @vaddr: Virtual address of allocation. - * @dma: Physical address of allocation. - * - * Free previously allocated block of contiguous memory. - */ -void vme_free_consistent(struct vme_resource *resource, size_t size, - void *vaddr, dma_addr_t dma) -{ - struct vme_bridge *bridge = find_bridge(resource); - - if (!bridge->free_consistent) { - dev_err(bridge->parent, - "free_consistent not supported by bridge %s\n", - bridge->name); - return; - } - - bridge->free_consistent(bridge->parent, size, vaddr, dma); -} -EXPORT_SYMBOL(vme_free_consistent); - -/** - * vme_get_size - Helper function returning size of a VME window - * @resource: Pointer to VME slave or master resource. - * - * Determine the size of the VME window provided. This is a helper - * function, wrappering the call to vme_master_get or vme_slave_get - * depending on the type of window resource handed to it. - * - * Return: Size of the window on success, zero on failure. - */ -size_t vme_get_size(struct vme_resource *resource) -{ - struct vme_bridge *bridge = find_bridge(resource); - int enabled, retval; - unsigned long long base, size; - dma_addr_t buf_base; - u32 aspace, cycle, dwidth; - - switch (resource->type) { - case VME_MASTER: - retval = vme_master_get(resource, &enabled, &base, &size, - &aspace, &cycle, &dwidth); - if (retval) - return 0; - - return size; - case VME_SLAVE: - retval = vme_slave_get(resource, &enabled, &base, &size, - &buf_base, &aspace, &cycle); - if (retval) - return 0; - - return size; - case VME_DMA: - return 0; - default: - dev_err(bridge->parent, "Unknown resource type\n"); - return 0; - } -} -EXPORT_SYMBOL(vme_get_size); - -int vme_check_window(struct vme_bridge *bridge, u32 aspace, - unsigned long long vme_base, unsigned long long size) -{ - int retval = 0; - - if (vme_base + size < size) - return -EINVAL; - - switch (aspace) { - case VME_A16: - if (vme_base + size > VME_A16_MAX) - retval = -EFAULT; - break; - case VME_A24: - if (vme_base + size > VME_A24_MAX) - retval = -EFAULT; - break; - case VME_A32: - if (vme_base + size > VME_A32_MAX) - retval = -EFAULT; - break; - case VME_A64: - /* The VME_A64_MAX limit is actually U64_MAX + 1 */ - break; - case VME_CRCSR: - if (vme_base + size > VME_CRCSR_MAX) - retval = -EFAULT; - break; - case VME_USER1: - case VME_USER2: - case VME_USER3: - case VME_USER4: - /* User Defined */ - break; - default: - dev_err(bridge->parent, "Invalid address space\n"); - retval = -EINVAL; - break; - } - - return retval; -} -EXPORT_SYMBOL(vme_check_window); - -static u32 vme_get_aspace(int am) -{ - switch (am) { - case 0x29: - case 0x2D: - return VME_A16; - case 0x38: - case 0x39: - case 0x3A: - case 0x3B: - case 0x3C: - case 0x3D: - case 0x3E: - case 0x3F: - return VME_A24; - case 0x8: - case 0x9: - case 0xA: - case 0xB: - case 0xC: - case 0xD: - case 0xE: - case 0xF: - return VME_A32; - case 0x0: - case 0x1: - case 0x3: - return VME_A64; - } - - return 0; -} - -/** - * vme_slave_request - Request a VME slave window resource. - * @vdev: Pointer to VME device struct vme_dev assigned to driver instance. - * @address: Required VME address space. - * @cycle: Required VME data transfer cycle type. - * - * Request use of a VME window resource capable of being set for the requested - * address space and data transfer cycle. - * - * Return: Pointer to VME resource on success, NULL on failure. - */ -struct vme_resource *vme_slave_request(struct vme_dev *vdev, u32 address, - u32 cycle) -{ - struct vme_bridge *bridge; - struct vme_slave_resource *allocated_image = NULL; - struct vme_slave_resource *slave_image; - struct vme_resource *resource = NULL; - - bridge = vdev->bridge; - if (!bridge) { - dev_err(&vdev->dev, "Can't find VME bus\n"); - goto err_bus; - } - - /* Loop through slave resources */ - list_for_each_entry(slave_image, &bridge->slave_resources, list) { - if (!slave_image) { - dev_err(bridge->parent, - "Registered NULL Slave resource\n"); - continue; - } - - /* Find an unlocked and compatible image */ - mutex_lock(&slave_image->mtx); - if (((slave_image->address_attr & address) == address) && - ((slave_image->cycle_attr & cycle) == cycle) && - !slave_image->locked) { - slave_image->locked = 1; - mutex_unlock(&slave_image->mtx); - allocated_image = slave_image; - break; - } - mutex_unlock(&slave_image->mtx); - } - - /* No free image */ - if (!allocated_image) - goto err_image; - - resource = kmalloc_obj(*resource); - if (!resource) - goto err_alloc; - - resource->type = VME_SLAVE; - resource->entry = &allocated_image->list; - - return resource; - -err_alloc: - /* Unlock image */ - mutex_lock(&allocated_image->mtx); - allocated_image->locked = 0; - mutex_unlock(&allocated_image->mtx); -err_image: -err_bus: - return NULL; -} -EXPORT_SYMBOL(vme_slave_request); - -/** - * vme_slave_set - Set VME slave window configuration. - * @resource: Pointer to VME slave resource. - * @enabled: State to which the window should be configured. - * @vme_base: Base address for the window. - * @size: Size of the VME window. - * @buf_base: Based address of buffer used to provide VME slave window storage. - * @aspace: VME address space for the VME window. - * @cycle: VME data transfer cycle type for the VME window. - * - * Set configuration for provided VME slave window. - * - * Return: Zero on success, -EINVAL if operation is not supported on this - * device, if an invalid resource has been provided or invalid - * attributes are provided. Hardware specific errors may also be - * returned. - */ -int vme_slave_set(struct vme_resource *resource, int enabled, - unsigned long long vme_base, unsigned long long size, - dma_addr_t buf_base, u32 aspace, u32 cycle) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_slave_resource *image; - int retval; - - if (resource->type != VME_SLAVE) { - dev_err(bridge->parent, "Not a slave resource\n"); - return -EINVAL; - } - - image = list_entry(resource->entry, struct vme_slave_resource, list); - - if (!bridge->slave_set) { - dev_err(bridge->parent, "%s not supported\n", __func__); - return -EINVAL; - } - - if (!(((image->address_attr & aspace) == aspace) && - ((image->cycle_attr & cycle) == cycle))) { - dev_err(bridge->parent, "Invalid attributes\n"); - return -EINVAL; - } - - retval = vme_check_window(bridge, aspace, vme_base, size); - if (retval) - return retval; - - return bridge->slave_set(image, enabled, vme_base, size, buf_base, - aspace, cycle); -} -EXPORT_SYMBOL(vme_slave_set); - -/** - * vme_slave_get - Retrieve VME slave window configuration. - * @resource: Pointer to VME slave resource. - * @enabled: Pointer to variable for storing state. - * @vme_base: Pointer to variable for storing window base address. - * @size: Pointer to variable for storing window size. - * @buf_base: Pointer to variable for storing slave buffer base address. - * @aspace: Pointer to variable for storing VME address space. - * @cycle: Pointer to variable for storing VME data transfer cycle type. - * - * Return configuration for provided VME slave window. - * - * Return: Zero on success, -EINVAL if operation is not supported on this - * device or if an invalid resource has been provided. - */ -int vme_slave_get(struct vme_resource *resource, int *enabled, - unsigned long long *vme_base, unsigned long long *size, - dma_addr_t *buf_base, u32 *aspace, u32 *cycle) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_slave_resource *image; - - if (resource->type != VME_SLAVE) { - dev_err(bridge->parent, "Not a slave resource\n"); - return -EINVAL; - } - - image = list_entry(resource->entry, struct vme_slave_resource, list); - - if (!bridge->slave_get) { - dev_err(bridge->parent, "%s not supported\n", __func__); - return -EINVAL; - } - - return bridge->slave_get(image, enabled, vme_base, size, buf_base, - aspace, cycle); -} -EXPORT_SYMBOL(vme_slave_get); - -/** - * vme_slave_free - Free VME slave window - * @resource: Pointer to VME slave resource. - * - * Free the provided slave resource so that it may be reallocated. - */ -void vme_slave_free(struct vme_resource *resource) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_slave_resource *slave_image; - - if (resource->type != VME_SLAVE) { - dev_err(bridge->parent, "Not a slave resource\n"); - return; - } - - slave_image = list_entry(resource->entry, struct vme_slave_resource, - list); - - /* Unlock image */ - mutex_lock(&slave_image->mtx); - if (!slave_image->locked) - dev_err(bridge->parent, "Image is already free\n"); - - slave_image->locked = 0; - mutex_unlock(&slave_image->mtx); - - /* Free up resource memory */ - kfree(resource); -} -EXPORT_SYMBOL(vme_slave_free); - -/** - * vme_master_request - Request a VME master window resource. - * @vdev: Pointer to VME device struct vme_dev assigned to driver instance. - * @address: Required VME address space. - * @cycle: Required VME data transfer cycle type. - * @dwidth: Required VME data transfer width. - * - * Request use of a VME window resource capable of being set for the requested - * address space, data transfer cycle and width. - * - * Return: Pointer to VME resource on success, NULL on failure. - */ -struct vme_resource *vme_master_request(struct vme_dev *vdev, u32 address, - u32 cycle, u32 dwidth) -{ - struct vme_bridge *bridge; - struct vme_master_resource *allocated_image = NULL; - struct vme_master_resource *master_image; - struct vme_resource *resource = NULL; - - bridge = vdev->bridge; - if (!bridge) { - dev_err(&vdev->dev, "Can't find VME bus\n"); - goto err_bus; - } - - /* Loop through master resources */ - list_for_each_entry(master_image, &bridge->master_resources, list) { - if (!master_image) { - dev_warn(bridge->parent, - "Registered NULL master resource\n"); - continue; - } - - /* Find an unlocked and compatible image */ - spin_lock(&master_image->lock); - if (((master_image->address_attr & address) == address) && - ((master_image->cycle_attr & cycle) == cycle) && - ((master_image->width_attr & dwidth) == dwidth) && - !master_image->locked) { - master_image->locked = 1; - spin_unlock(&master_image->lock); - allocated_image = master_image; - break; - } - spin_unlock(&master_image->lock); - } - - /* Check to see if we found a resource */ - if (!allocated_image) { - dev_err(&vdev->dev, "Can't find a suitable resource\n"); - goto err_image; - } - - resource = kmalloc_obj(*resource); - if (!resource) - goto err_alloc; - - resource->type = VME_MASTER; - resource->entry = &allocated_image->list; - - return resource; - -err_alloc: - /* Unlock image */ - spin_lock(&allocated_image->lock); - allocated_image->locked = 0; - spin_unlock(&allocated_image->lock); -err_image: -err_bus: - return NULL; -} -EXPORT_SYMBOL(vme_master_request); - -/** - * vme_master_set - Set VME master window configuration. - * @resource: Pointer to VME master resource. - * @enabled: State to which the window should be configured. - * @vme_base: Base address for the window. - * @size: Size of the VME window. - * @aspace: VME address space for the VME window. - * @cycle: VME data transfer cycle type for the VME window. - * @dwidth: VME data transfer width for the VME window. - * - * Set configuration for provided VME master window. - * - * Return: Zero on success, -EINVAL if operation is not supported on this - * device, if an invalid resource has been provided or invalid - * attributes are provided. Hardware specific errors may also be - * returned. - */ -int vme_master_set(struct vme_resource *resource, int enabled, - unsigned long long vme_base, unsigned long long size, - u32 aspace, u32 cycle, u32 dwidth) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_master_resource *image; - int retval; - - if (resource->type != VME_MASTER) { - dev_err(bridge->parent, "Not a master resource\n"); - return -EINVAL; - } - - image = list_entry(resource->entry, struct vme_master_resource, list); - - if (!bridge->master_set) { - dev_warn(bridge->parent, "%s not supported\n", __func__); - return -EINVAL; - } - - if (!(((image->address_attr & aspace) == aspace) && - ((image->cycle_attr & cycle) == cycle) && - ((image->width_attr & dwidth) == dwidth))) { - dev_warn(bridge->parent, "Invalid attributes\n"); - return -EINVAL; - } - - retval = vme_check_window(bridge, aspace, vme_base, size); - if (retval) - return retval; - - return bridge->master_set(image, enabled, vme_base, size, aspace, - cycle, dwidth); -} -EXPORT_SYMBOL(vme_master_set); - -/** - * vme_master_get - Retrieve VME master window configuration. - * @resource: Pointer to VME master resource. - * @enabled: Pointer to variable for storing state. - * @vme_base: Pointer to variable for storing window base address. - * @size: Pointer to variable for storing window size. - * @aspace: Pointer to variable for storing VME address space. - * @cycle: Pointer to variable for storing VME data transfer cycle type. - * @dwidth: Pointer to variable for storing VME data transfer width. - * - * Return configuration for provided VME master window. - * - * Return: Zero on success, -EINVAL if operation is not supported on this - * device or if an invalid resource has been provided. - */ -int vme_master_get(struct vme_resource *resource, int *enabled, - unsigned long long *vme_base, unsigned long long *size, - u32 *aspace, u32 *cycle, u32 *dwidth) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_master_resource *image; - - if (resource->type != VME_MASTER) { - dev_err(bridge->parent, "Not a master resource\n"); - return -EINVAL; - } - - image = list_entry(resource->entry, struct vme_master_resource, list); - - if (!bridge->master_get) { - dev_warn(bridge->parent, "%s not supported\n", __func__); - return -EINVAL; - } - - return bridge->master_get(image, enabled, vme_base, size, aspace, - cycle, dwidth); -} -EXPORT_SYMBOL(vme_master_get); - -/** - * vme_master_read - Read data from VME space into a buffer. - * @resource: Pointer to VME master resource. - * @buf: Pointer to buffer where data should be transferred. - * @count: Number of bytes to transfer. - * @offset: Offset into VME master window at which to start transfer. - * - * Perform read of count bytes of data from location on VME bus which maps into - * the VME master window at offset to buf. - * - * Return: Number of bytes read, -EINVAL if resource is not a VME master - * resource or read operation is not supported. -EFAULT returned if - * invalid offset is provided. Hardware specific errors may also be - * returned. - */ -ssize_t vme_master_read(struct vme_resource *resource, void *buf, size_t count, - loff_t offset) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_master_resource *image; - size_t length; - - if (!bridge->master_read) { - dev_warn(bridge->parent, - "Reading from resource not supported\n"); - return -EINVAL; - } - - if (resource->type != VME_MASTER) { - dev_err(bridge->parent, "Not a master resource\n"); - return -EINVAL; - } - - image = list_entry(resource->entry, struct vme_master_resource, list); - - length = vme_get_size(resource); - - if (offset > length) { - dev_warn(bridge->parent, "Invalid Offset\n"); - return -EFAULT; - } - - if ((offset + count) > length) - count = length - offset; - - return bridge->master_read(image, buf, count, offset); -} -EXPORT_SYMBOL(vme_master_read); - -/** - * vme_master_write - Write data out to VME space from a buffer. - * @resource: Pointer to VME master resource. - * @buf: Pointer to buffer holding data to transfer. - * @count: Number of bytes to transfer. - * @offset: Offset into VME master window at which to start transfer. - * - * Perform write of count bytes of data from buf to location on VME bus which - * maps into the VME master window at offset. - * - * Return: Number of bytes written, -EINVAL if resource is not a VME master - * resource or write operation is not supported. -EFAULT returned if - * invalid offset is provided. Hardware specific errors may also be - * returned. - */ -ssize_t vme_master_write(struct vme_resource *resource, void *buf, - size_t count, loff_t offset) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_master_resource *image; - size_t length; - - if (!bridge->master_write) { - dev_warn(bridge->parent, "Writing to resource not supported\n"); - return -EINVAL; - } - - if (resource->type != VME_MASTER) { - dev_err(bridge->parent, "Not a master resource\n"); - return -EINVAL; - } - - image = list_entry(resource->entry, struct vme_master_resource, list); - - length = vme_get_size(resource); - - if (offset > length) { - dev_warn(bridge->parent, "Invalid Offset\n"); - return -EFAULT; - } - - if ((offset + count) > length) - count = length - offset; - - return bridge->master_write(image, buf, count, offset); -} -EXPORT_SYMBOL(vme_master_write); - -/** - * vme_master_rmw - Perform read-modify-write cycle. - * @resource: Pointer to VME master resource. - * @mask: Bits to be compared and swapped in operation. - * @compare: Bits to be compared with data read from offset. - * @swap: Bits to be swapped in data read from offset. - * @offset: Offset into VME master window at which to perform operation. - * - * Perform read-modify-write cycle on provided location: - * - Location on VME bus is read. - * - Bits selected by mask are compared with compare. - * - Where a selected bit matches that in compare and are selected in swap, - * the bit is swapped. - * - Result written back to location on VME bus. - * - * Return: Bytes written on success, -EINVAL if resource is not a VME master - * resource or RMW operation is not supported. Hardware specific - * errors may also be returned. - */ -unsigned int vme_master_rmw(struct vme_resource *resource, unsigned int mask, - unsigned int compare, unsigned int swap, loff_t offset) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_master_resource *image; - - if (!bridge->master_rmw) { - dev_warn(bridge->parent, "Writing to resource not supported\n"); - return -EINVAL; - } - - if (resource->type != VME_MASTER) { - dev_err(bridge->parent, "Not a master resource\n"); - return -EINVAL; - } - - image = list_entry(resource->entry, struct vme_master_resource, list); - - return bridge->master_rmw(image, mask, compare, swap, offset); -} -EXPORT_SYMBOL(vme_master_rmw); - -/** - * vme_master_mmap_prepare - Mmap region of VME master window. - * @resource: Pointer to VME master resource. - * @desc: Pointer to descriptor of user mapping. - * - * Memory map a region of the VME master window into user space. - * - * Return: Zero on success, -EINVAL if resource is not a VME master - * resource or -EFAULT if map exceeds window size. Other generic mmap - * errors may also be returned. - */ -int vme_master_mmap_prepare(struct vme_resource *resource, - struct vm_area_desc *desc) -{ - const unsigned long vma_size = vma_desc_size(desc); - struct vme_bridge *bridge = find_bridge(resource); - struct vme_master_resource *image; - phys_addr_t phys_addr; - - if (resource->type != VME_MASTER) { - dev_err(bridge->parent, "Not a master resource\n"); - return -EINVAL; - } - - image = list_entry(resource->entry, struct vme_master_resource, list); - phys_addr = image->bus_resource.start + (desc->pgoff << PAGE_SHIFT); - - if (phys_addr + vma_size > image->bus_resource.end + 1) { - dev_err(bridge->parent, "Map size cannot exceed the window size\n"); - return -EFAULT; - } - - desc->page_prot = pgprot_noncached(desc->page_prot); - mmap_action_simple_ioremap(desc, phys_addr, vma_size); - return 0; -} -EXPORT_SYMBOL(vme_master_mmap_prepare); - -/** - * vme_master_free - Free VME master window - * @resource: Pointer to VME master resource. - * - * Free the provided master resource so that it may be reallocated. - */ -void vme_master_free(struct vme_resource *resource) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_master_resource *master_image; - - if (resource->type != VME_MASTER) { - dev_err(bridge->parent, "Not a master resource\n"); - return; - } - - master_image = list_entry(resource->entry, struct vme_master_resource, - list); - - /* Unlock image */ - spin_lock(&master_image->lock); - if (!master_image->locked) - dev_err(bridge->parent, "Image is already free\n"); - - master_image->locked = 0; - spin_unlock(&master_image->lock); - - /* Free up resource memory */ - kfree(resource); -} -EXPORT_SYMBOL(vme_master_free); - -/** - * vme_dma_request - Request a DMA controller. - * @vdev: Pointer to VME device struct vme_dev assigned to driver instance. - * @route: Required src/destination combination. - * - * Request a VME DMA controller with capability to perform transfers between - * requested source/destination combination. - * - * Return: Pointer to VME DMA resource on success, NULL on failure. - */ -struct vme_resource *vme_dma_request(struct vme_dev *vdev, u32 route) -{ - struct vme_bridge *bridge; - struct vme_dma_resource *allocated_ctrlr = NULL; - struct vme_dma_resource *dma_ctrlr; - struct vme_resource *resource = NULL; - - /* XXX Not checking resource attributes */ - dev_err(&vdev->dev, "No VME resource Attribute tests done\n"); - - bridge = vdev->bridge; - if (!bridge) { - dev_err(&vdev->dev, "Can't find VME bus\n"); - goto err_bus; - } - - /* Loop through DMA resources */ - list_for_each_entry(dma_ctrlr, &bridge->dma_resources, list) { - if (!dma_ctrlr) { - dev_err(bridge->parent, - "Registered NULL DMA resource\n"); - continue; - } - - /* Find an unlocked and compatible controller */ - mutex_lock(&dma_ctrlr->mtx); - if (((dma_ctrlr->route_attr & route) == route) && - !dma_ctrlr->locked) { - dma_ctrlr->locked = 1; - mutex_unlock(&dma_ctrlr->mtx); - allocated_ctrlr = dma_ctrlr; - break; - } - mutex_unlock(&dma_ctrlr->mtx); - } - - /* Check to see if we found a resource */ - if (!allocated_ctrlr) - goto err_ctrlr; - - resource = kmalloc_obj(*resource); - if (!resource) - goto err_alloc; - - resource->type = VME_DMA; - resource->entry = &allocated_ctrlr->list; - - return resource; - -err_alloc: - /* Unlock image */ - mutex_lock(&allocated_ctrlr->mtx); - allocated_ctrlr->locked = 0; - mutex_unlock(&allocated_ctrlr->mtx); -err_ctrlr: -err_bus: - return NULL; -} -EXPORT_SYMBOL(vme_dma_request); - -/** - * vme_new_dma_list - Create new VME DMA list. - * @resource: Pointer to VME DMA resource. - * - * Create a new VME DMA list. It is the responsibility of the user to free - * the list once it is no longer required with vme_dma_list_free(). - * - * Return: Pointer to new VME DMA list, NULL on allocation failure or invalid - * VME DMA resource. - */ -struct vme_dma_list *vme_new_dma_list(struct vme_resource *resource) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_dma_list *dma_list; - - if (resource->type != VME_DMA) { - dev_err(bridge->parent, "Not a DMA resource\n"); - return NULL; - } - - dma_list = kmalloc_obj(*dma_list); - if (!dma_list) - return NULL; - - INIT_LIST_HEAD(&dma_list->entries); - dma_list->parent = list_entry(resource->entry, - struct vme_dma_resource, - list); - mutex_init(&dma_list->mtx); - - return dma_list; -} -EXPORT_SYMBOL(vme_new_dma_list); - -/** - * vme_dma_pattern_attribute - Create "Pattern" type VME DMA list attribute. - * @pattern: Value to use used as pattern - * @type: Type of pattern to be written. - * - * Create VME DMA list attribute for pattern generation. It is the - * responsibility of the user to free used attributes using - * vme_dma_free_attribute(). - * - * Return: Pointer to VME DMA attribute, NULL on failure. - */ -struct vme_dma_attr *vme_dma_pattern_attribute(u32 pattern, u32 type) -{ - struct vme_dma_attr *attributes; - struct vme_dma_pattern *pattern_attr; - - attributes = kmalloc_obj(*attributes); - if (!attributes) - goto err_attr; - - pattern_attr = kmalloc_obj(*pattern_attr); - if (!pattern_attr) - goto err_pat; - - attributes->type = VME_DMA_PATTERN; - attributes->private = (void *)pattern_attr; - - pattern_attr->pattern = pattern; - pattern_attr->type = type; - - return attributes; - -err_pat: - kfree(attributes); -err_attr: - return NULL; -} -EXPORT_SYMBOL(vme_dma_pattern_attribute); - -/** - * vme_dma_pci_attribute - Create "PCI" type VME DMA list attribute. - * @address: PCI base address for DMA transfer. - * - * Create VME DMA list attribute pointing to a location on PCI for DMA - * transfers. It is the responsibility of the user to free used attributes - * using vme_dma_free_attribute(). - * - * Return: Pointer to VME DMA attribute, NULL on failure. - */ -struct vme_dma_attr *vme_dma_pci_attribute(dma_addr_t address) -{ - struct vme_dma_attr *attributes; - struct vme_dma_pci *pci_attr; - - /* XXX Run some sanity checks here */ - - attributes = kmalloc_obj(*attributes); - if (!attributes) - goto err_attr; - - pci_attr = kmalloc_obj(*pci_attr); - if (!pci_attr) - goto err_pci; - - attributes->type = VME_DMA_PCI; - attributes->private = (void *)pci_attr; - - pci_attr->address = address; - - return attributes; - -err_pci: - kfree(attributes); -err_attr: - return NULL; -} -EXPORT_SYMBOL(vme_dma_pci_attribute); - -/** - * vme_dma_vme_attribute - Create "VME" type VME DMA list attribute. - * @address: VME base address for DMA transfer. - * @aspace: VME address space to use for DMA transfer. - * @cycle: VME bus cycle to use for DMA transfer. - * @dwidth: VME data width to use for DMA transfer. - * - * Create VME DMA list attribute pointing to a location on the VME bus for DMA - * transfers. It is the responsibility of the user to free used attributes - * using vme_dma_free_attribute(). - * - * Return: Pointer to VME DMA attribute, NULL on failure. - */ -struct vme_dma_attr *vme_dma_vme_attribute(unsigned long long address, - u32 aspace, u32 cycle, u32 dwidth) -{ - struct vme_dma_attr *attributes; - struct vme_dma_vme *vme_attr; - - attributes = kmalloc_obj(*attributes); - if (!attributes) - goto err_attr; - - vme_attr = kmalloc_obj(*vme_attr); - if (!vme_attr) - goto err_vme; - - attributes->type = VME_DMA_VME; - attributes->private = (void *)vme_attr; - - vme_attr->address = address; - vme_attr->aspace = aspace; - vme_attr->cycle = cycle; - vme_attr->dwidth = dwidth; - - return attributes; - -err_vme: - kfree(attributes); -err_attr: - return NULL; -} -EXPORT_SYMBOL(vme_dma_vme_attribute); - -/** - * vme_dma_free_attribute - Free DMA list attribute. - * @attributes: Pointer to DMA list attribute. - * - * Free VME DMA list attribute. VME DMA list attributes can be safely freed - * once vme_dma_list_add() has returned. - */ -void vme_dma_free_attribute(struct vme_dma_attr *attributes) -{ - kfree(attributes->private); - kfree(attributes); -} -EXPORT_SYMBOL(vme_dma_free_attribute); - -/** - * vme_dma_list_add - Add entry to a VME DMA list. - * @list: Pointer to VME list. - * @src: Pointer to DMA list attribute to use as source. - * @dest: Pointer to DMA list attribute to use as destination. - * @count: Number of bytes to transfer. - * - * Add an entry to the provided VME DMA list. Entry requires pointers to source - * and destination DMA attributes and a count. - * - * Please note, the attributes supported as source and destinations for - * transfers are hardware dependent. - * - * Return: Zero on success, -EINVAL if operation is not supported on this - * device or if the link list has already been submitted for execution. - * Hardware specific errors also possible. - */ -int vme_dma_list_add(struct vme_dma_list *list, struct vme_dma_attr *src, - struct vme_dma_attr *dest, size_t count) -{ - struct vme_bridge *bridge = list->parent->parent; - int retval; - - if (!bridge->dma_list_add) { - dev_warn(bridge->parent, - "Link List DMA generation not supported\n"); - return -EINVAL; - } - - if (!mutex_trylock(&list->mtx)) { - dev_err(bridge->parent, "Link List already submitted\n"); - return -EINVAL; - } - - retval = bridge->dma_list_add(list, src, dest, count); - - mutex_unlock(&list->mtx); - - return retval; -} -EXPORT_SYMBOL(vme_dma_list_add); - -/** - * vme_dma_list_exec - Queue a VME DMA list for execution. - * @list: Pointer to VME list. - * - * Queue the provided VME DMA list for execution. The call will return once the - * list has been executed. - * - * Return: Zero on success, -EINVAL if operation is not supported on this - * device. Hardware specific errors also possible. - */ -int vme_dma_list_exec(struct vme_dma_list *list) -{ - struct vme_bridge *bridge = list->parent->parent; - int retval; - - if (!bridge->dma_list_exec) { - dev_err(bridge->parent, - "Link List DMA execution not supported\n"); - return -EINVAL; - } - - mutex_lock(&list->mtx); - - retval = bridge->dma_list_exec(list); - - mutex_unlock(&list->mtx); - - return retval; -} -EXPORT_SYMBOL(vme_dma_list_exec); - -/** - * vme_dma_list_free - Free a VME DMA list. - * @list: Pointer to VME list. - * - * Free the provided DMA list and all its entries. - * - * Return: Zero on success, -EINVAL on invalid VME resource, -EBUSY if resource - * is still in use. Hardware specific errors also possible. - */ -int vme_dma_list_free(struct vme_dma_list *list) -{ - struct vme_bridge *bridge = list->parent->parent; - int retval; - - if (!bridge->dma_list_empty) { - dev_warn(bridge->parent, - "Emptying of Link Lists not supported\n"); - return -EINVAL; - } - - if (!mutex_trylock(&list->mtx)) { - dev_err(bridge->parent, "Link List in use\n"); - return -EBUSY; - } - - /* - * Empty out all of the entries from the DMA list. We need to go to the - * low level driver as DMA entries are driver specific. - */ - retval = bridge->dma_list_empty(list); - if (retval) { - dev_err(bridge->parent, "Unable to empty link-list entries\n"); - mutex_unlock(&list->mtx); - return retval; - } - mutex_unlock(&list->mtx); - kfree(list); - - return retval; -} -EXPORT_SYMBOL(vme_dma_list_free); - -/** - * vme_dma_free - Free a VME DMA resource. - * @resource: Pointer to VME DMA resource. - * - * Free the provided DMA resource so that it may be reallocated. - * - * Return: Zero on success, -EINVAL on invalid VME resource, -EBUSY if resource - * is still active. - */ -int vme_dma_free(struct vme_resource *resource) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_dma_resource *ctrlr; - - if (resource->type != VME_DMA) { - dev_err(bridge->parent, "Not a DMA resource\n"); - return -EINVAL; - } - - ctrlr = list_entry(resource->entry, struct vme_dma_resource, list); - - if (!mutex_trylock(&ctrlr->mtx)) { - dev_err(bridge->parent, "Resource busy, can't free\n"); - return -EBUSY; - } - - if (!(list_empty(&ctrlr->pending) && list_empty(&ctrlr->running))) { - dev_warn(bridge->parent, - "Resource still processing transfers\n"); - mutex_unlock(&ctrlr->mtx); - return -EBUSY; - } - - ctrlr->locked = 0; - - mutex_unlock(&ctrlr->mtx); - - kfree(resource); - - return 0; -} -EXPORT_SYMBOL(vme_dma_free); - -void vme_bus_error_handler(struct vme_bridge *bridge, - unsigned long long address, int am) -{ - struct vme_error_handler *handler; - int handler_triggered = 0; - u32 aspace = vme_get_aspace(am); - - list_for_each_entry(handler, &bridge->vme_error_handlers, list) { - if ((aspace == handler->aspace) && - (address >= handler->start) && - (address < handler->end)) { - if (!handler->num_errors) - handler->first_error = address; - if (handler->num_errors != UINT_MAX) - handler->num_errors++; - handler_triggered = 1; - } - } - - if (!handler_triggered) - dev_err(bridge->parent, - "Unhandled VME access error at address 0x%llx\n", - address); -} -EXPORT_SYMBOL(vme_bus_error_handler); - -struct vme_error_handler *vme_register_error_handler(struct vme_bridge *bridge, u32 aspace, - unsigned long long address, size_t len) -{ - struct vme_error_handler *handler; - - handler = kmalloc_obj(*handler, GFP_ATOMIC); - if (!handler) - return NULL; - - handler->aspace = aspace; - handler->start = address; - handler->end = address + len; - handler->num_errors = 0; - handler->first_error = 0; - list_add_tail(&handler->list, &bridge->vme_error_handlers); - - return handler; -} -EXPORT_SYMBOL(vme_register_error_handler); - -void vme_unregister_error_handler(struct vme_error_handler *handler) -{ - list_del(&handler->list); - kfree(handler); -} -EXPORT_SYMBOL(vme_unregister_error_handler); - -void vme_irq_handler(struct vme_bridge *bridge, int level, int statid) -{ - void (*call)(int level, int statid, void *priv_data); - void *priv_data; - - call = bridge->irq[level - 1].callback[statid].func; - priv_data = bridge->irq[level - 1].callback[statid].priv_data; - if (call) - call(level, statid, priv_data); - else - dev_warn(bridge->parent, - "Spurious VME interrupt, level:%x, vector:%x\n", level, - statid); -} -EXPORT_SYMBOL(vme_irq_handler); - -/** - * vme_irq_request - Request a specific VME interrupt. - * @vdev: Pointer to VME device struct vme_dev assigned to driver instance. - * @level: Interrupt priority being requested. - * @statid: Interrupt vector being requested. - * @callback: Pointer to callback function called when VME interrupt/vector - * received. - * @priv_data: Generic pointer that will be passed to the callback function. - * - * Request callback to be attached as a handler for VME interrupts with provided - * level and statid. - * - * Return: Zero on success, -EINVAL on invalid vme device, level or if the - * function is not supported, -EBUSY if the level/statid combination is - * already in use. Hardware specific errors also possible. - */ -int vme_irq_request(struct vme_dev *vdev, int level, int statid, - void (*callback)(int level, int statid, void *priv_data), - void *priv_data) -{ - struct vme_bridge *bridge; - - bridge = vdev->bridge; - if (!bridge) { - dev_err(&vdev->dev, "Can't find VME bus\n"); - return -EINVAL; - } - - if ((level < 1) || (level > 7)) { - dev_err(bridge->parent, "Invalid interrupt level\n"); - return -EINVAL; - } - - if (!bridge->irq_set) { - dev_err(bridge->parent, - "Configuring interrupts not supported\n"); - return -EINVAL; - } - - mutex_lock(&bridge->irq_mtx); - - if (bridge->irq[level - 1].callback[statid].func) { - mutex_unlock(&bridge->irq_mtx); - dev_warn(bridge->parent, "VME Interrupt already taken\n"); - return -EBUSY; - } - - bridge->irq[level - 1].count++; - bridge->irq[level - 1].callback[statid].priv_data = priv_data; - bridge->irq[level - 1].callback[statid].func = callback; - - /* Enable IRQ level */ - bridge->irq_set(bridge, level, 1, 1); - - mutex_unlock(&bridge->irq_mtx); - - return 0; -} -EXPORT_SYMBOL(vme_irq_request); - -/** - * vme_irq_free - Free a VME interrupt. - * @vdev: Pointer to VME device struct vme_dev assigned to driver instance. - * @level: Interrupt priority of interrupt being freed. - * @statid: Interrupt vector of interrupt being freed. - * - * Remove previously attached callback from VME interrupt priority/vector. - */ -void vme_irq_free(struct vme_dev *vdev, int level, int statid) -{ - struct vme_bridge *bridge; - - bridge = vdev->bridge; - if (!bridge) { - dev_err(&vdev->dev, "Can't find VME bus\n"); - return; - } - - if ((level < 1) || (level > 7)) { - dev_err(bridge->parent, "Invalid interrupt level\n"); - return; - } - - if (!bridge->irq_set) { - dev_err(bridge->parent, - "Configuring interrupts not supported\n"); - return; - } - - mutex_lock(&bridge->irq_mtx); - - bridge->irq[level - 1].count--; - - /* Disable IRQ level if no more interrupts attached at this level*/ - if (!bridge->irq[level - 1].count) - bridge->irq_set(bridge, level, 0, 1); - - bridge->irq[level - 1].callback[statid].func = NULL; - bridge->irq[level - 1].callback[statid].priv_data = NULL; - - mutex_unlock(&bridge->irq_mtx); -} -EXPORT_SYMBOL(vme_irq_free); - -/** - * vme_irq_generate - Generate VME interrupt. - * @vdev: Pointer to VME device struct vme_dev assigned to driver instance. - * @level: Interrupt priority at which to assert the interrupt. - * @statid: Interrupt vector to associate with the interrupt. - * - * Generate a VME interrupt of the provided level and with the provided - * statid. - * - * Return: Zero on success, -EINVAL on invalid vme device, level or if the - * function is not supported. Hardware specific errors also possible. - */ -int vme_irq_generate(struct vme_dev *vdev, int level, int statid) -{ - struct vme_bridge *bridge; - - bridge = vdev->bridge; - if (!bridge) { - dev_err(&vdev->dev, "Can't find VME bus\n"); - return -EINVAL; - } - - if ((level < 1) || (level > 7)) { - dev_warn(bridge->parent, "Invalid interrupt level\n"); - return -EINVAL; - } - - if (!bridge->irq_generate) { - dev_warn(bridge->parent, - "Interrupt generation not supported\n"); - return -EINVAL; - } - - return bridge->irq_generate(bridge, level, statid); -} -EXPORT_SYMBOL(vme_irq_generate); - -/** - * vme_lm_request - Request a VME location monitor - * @vdev: Pointer to VME device struct vme_dev assigned to driver instance. - * - * Allocate a location monitor resource to the driver. A location monitor - * allows the driver to monitor accesses to a contiguous number of - * addresses on the VME bus. - * - * Return: Pointer to a VME resource on success or NULL on failure. - */ -struct vme_resource *vme_lm_request(struct vme_dev *vdev) -{ - struct vme_bridge *bridge; - struct vme_lm_resource *allocated_lm = NULL; - struct vme_lm_resource *lm; - struct vme_resource *resource = NULL; - - bridge = vdev->bridge; - if (!bridge) { - dev_err(&vdev->dev, "Can't find VME bus\n"); - goto err_bus; - } - - /* Loop through LM resources */ - list_for_each_entry(lm, &bridge->lm_resources, list) { - if (!lm) { - dev_err(bridge->parent, - "Registered NULL Location Monitor resource\n"); - continue; - } - - /* Find an unlocked controller */ - mutex_lock(&lm->mtx); - if (!lm->locked) { - lm->locked = 1; - mutex_unlock(&lm->mtx); - allocated_lm = lm; - break; - } - mutex_unlock(&lm->mtx); - } - - /* Check to see if we found a resource */ - if (!allocated_lm) - goto err_lm; - - resource = kmalloc_obj(*resource); - if (!resource) - goto err_alloc; - - resource->type = VME_LM; - resource->entry = &allocated_lm->list; - - return resource; - -err_alloc: - /* Unlock image */ - mutex_lock(&allocated_lm->mtx); - allocated_lm->locked = 0; - mutex_unlock(&allocated_lm->mtx); -err_lm: -err_bus: - return NULL; -} -EXPORT_SYMBOL(vme_lm_request); - -/** - * vme_lm_count - Determine number of VME Addresses monitored - * @resource: Pointer to VME location monitor resource. - * - * The number of contiguous addresses monitored is hardware dependent. - * Return the number of contiguous addresses monitored by the - * location monitor. - * - * Return: Count of addresses monitored or -EINVAL when provided with an - * invalid location monitor resource. - */ -int vme_lm_count(struct vme_resource *resource) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_lm_resource *lm; - - if (resource->type != VME_LM) { - dev_err(bridge->parent, "Not a Location Monitor resource\n"); - return -EINVAL; - } - - lm = list_entry(resource->entry, struct vme_lm_resource, list); - - return lm->monitors; -} -EXPORT_SYMBOL(vme_lm_count); - -/** - * vme_lm_set - Configure location monitor - * @resource: Pointer to VME location monitor resource. - * @lm_base: Base address to monitor. - * @aspace: VME address space to monitor. - * @cycle: VME bus cycle type to monitor. - * - * Set the base address, address space and cycle type of accesses to be - * monitored by the location monitor. - * - * Return: Zero on success, -EINVAL when provided with an invalid location - * monitor resource or function is not supported. Hardware specific - * errors may also be returned. - */ -int vme_lm_set(struct vme_resource *resource, unsigned long long lm_base, - u32 aspace, u32 cycle) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_lm_resource *lm; - - if (resource->type != VME_LM) { - dev_err(bridge->parent, "Not a Location Monitor resource\n"); - return -EINVAL; - } - - lm = list_entry(resource->entry, struct vme_lm_resource, list); - - if (!bridge->lm_set) { - dev_err(bridge->parent, "%s not supported\n", __func__); - return -EINVAL; - } - - return bridge->lm_set(lm, lm_base, aspace, cycle); -} -EXPORT_SYMBOL(vme_lm_set); - -/** - * vme_lm_get - Retrieve location monitor settings - * @resource: Pointer to VME location monitor resource. - * @lm_base: Pointer used to output the base address monitored. - * @aspace: Pointer used to output the address space monitored. - * @cycle: Pointer used to output the VME bus cycle type monitored. - * - * Retrieve the base address, address space and cycle type of accesses to - * be monitored by the location monitor. - * - * Return: Zero on success, -EINVAL when provided with an invalid location - * monitor resource or function is not supported. Hardware specific - * errors may also be returned. - */ -int vme_lm_get(struct vme_resource *resource, unsigned long long *lm_base, - u32 *aspace, u32 *cycle) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_lm_resource *lm; - - if (resource->type != VME_LM) { - dev_err(bridge->parent, "Not a Location Monitor resource\n"); - return -EINVAL; - } - - lm = list_entry(resource->entry, struct vme_lm_resource, list); - - if (!bridge->lm_get) { - dev_err(bridge->parent, "%s not supported\n", __func__); - return -EINVAL; - } - - return bridge->lm_get(lm, lm_base, aspace, cycle); -} -EXPORT_SYMBOL(vme_lm_get); - -/** - * vme_lm_attach - Provide callback for location monitor address - * @resource: Pointer to VME location monitor resource. - * @monitor: Offset to which callback should be attached. - * @callback: Pointer to callback function called when triggered. - * @data: Generic pointer that will be passed to the callback function. - * - * Attach a callback to the specified offset into the location monitors - * monitored addresses. A generic pointer is provided to allow data to be - * passed to the callback when called. - * - * Return: Zero on success, -EINVAL when provided with an invalid location - * monitor resource or function is not supported. Hardware specific - * errors may also be returned. - */ -int vme_lm_attach(struct vme_resource *resource, int monitor, - void (*callback)(void *), void *data) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_lm_resource *lm; - - if (resource->type != VME_LM) { - dev_err(bridge->parent, "Not a Location Monitor resource\n"); - return -EINVAL; - } - - lm = list_entry(resource->entry, struct vme_lm_resource, list); - - if (!bridge->lm_attach) { - dev_err(bridge->parent, "%s not supported\n", __func__); - return -EINVAL; - } - - return bridge->lm_attach(lm, monitor, callback, data); -} -EXPORT_SYMBOL(vme_lm_attach); - -/** - * vme_lm_detach - Remove callback for location monitor address - * @resource: Pointer to VME location monitor resource. - * @monitor: Offset to which callback should be removed. - * - * Remove the callback associated with the specified offset into the - * location monitors monitored addresses. - * - * Return: Zero on success, -EINVAL when provided with an invalid location - * monitor resource or function is not supported. Hardware specific - * errors may also be returned. - */ -int vme_lm_detach(struct vme_resource *resource, int monitor) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_lm_resource *lm; - - if (resource->type != VME_LM) { - dev_err(bridge->parent, "Not a Location Monitor resource\n"); - return -EINVAL; - } - - lm = list_entry(resource->entry, struct vme_lm_resource, list); - - if (!bridge->lm_detach) { - dev_err(bridge->parent, "%s not supported\n", __func__); - return -EINVAL; - } - - return bridge->lm_detach(lm, monitor); -} -EXPORT_SYMBOL(vme_lm_detach); - -/** - * vme_lm_free - Free allocated VME location monitor - * @resource: Pointer to VME location monitor resource. - * - * Free allocation of a VME location monitor. - * - * WARNING: This function currently expects that any callbacks that have - * been attached to the location monitor have been removed. - * - * Return: Zero on success, -EINVAL when provided with an invalid location - * monitor resource. - */ -void vme_lm_free(struct vme_resource *resource) -{ - struct vme_bridge *bridge = find_bridge(resource); - struct vme_lm_resource *lm; - - if (resource->type != VME_LM) { - dev_err(bridge->parent, "Not a Location Monitor resource\n"); - return; - } - - lm = list_entry(resource->entry, struct vme_lm_resource, list); - - mutex_lock(&lm->mtx); - - /* XXX - * Check to see that there aren't any callbacks still attached, if - * there are we should probably be detaching them! - */ - - lm->locked = 0; - - mutex_unlock(&lm->mtx); - - kfree(resource); -} -EXPORT_SYMBOL(vme_lm_free); - -/** - * vme_slot_num - Retrieve slot ID - * @vdev: Pointer to VME device struct vme_dev assigned to driver instance. - * - * Retrieve the slot ID associated with the provided VME device. - * - * Return: The slot ID on success, -EINVAL if VME bridge cannot be determined - * or the function is not supported. Hardware specific errors may also - * be returned. - */ -int vme_slot_num(struct vme_dev *vdev) -{ - struct vme_bridge *bridge; - - bridge = vdev->bridge; - if (!bridge) { - dev_err(&vdev->dev, "Can't find VME bus\n"); - return -EINVAL; - } - - if (!bridge->slot_get) { - dev_warn(bridge->parent, "%s not supported\n", __func__); - return -EINVAL; - } - - return bridge->slot_get(bridge); -} -EXPORT_SYMBOL(vme_slot_num); - -/** - * vme_bus_num - Retrieve bus number - * @vdev: Pointer to VME device struct vme_dev assigned to driver instance. - * - * Retrieve the bus enumeration associated with the provided VME device. - * - * Return: The bus number on success, -EINVAL if VME bridge cannot be - * determined. - */ -int vme_bus_num(struct vme_dev *vdev) -{ - struct vme_bridge *bridge; - - bridge = vdev->bridge; - if (!bridge) { - dev_err(&vdev->dev, "Can't find VME bus\n"); - return -EINVAL; - } - - return bridge->num; -} -EXPORT_SYMBOL(vme_bus_num); - -/* - Bridge Registration --------------------------------------------------- */ - -static void vme_dev_release(struct device *dev) -{ - kfree(dev_to_vme_dev(dev)); -} - -/* Common bridge initialization */ -struct vme_bridge *vme_init_bridge(struct vme_bridge *bridge) -{ - INIT_LIST_HEAD(&bridge->vme_error_handlers); - INIT_LIST_HEAD(&bridge->master_resources); - INIT_LIST_HEAD(&bridge->slave_resources); - INIT_LIST_HEAD(&bridge->dma_resources); - INIT_LIST_HEAD(&bridge->lm_resources); - mutex_init(&bridge->irq_mtx); - - return bridge; -} -EXPORT_SYMBOL(vme_init_bridge); - -int vme_register_bridge(struct vme_bridge *bridge) -{ - int i; - int ret = -1; - - mutex_lock(&vme_buses_lock); - for (i = 0; i < sizeof(vme_bus_numbers) * 8; i++) { - if (!(vme_bus_numbers & (1 << i))) { - vme_bus_numbers |= (1 << i); - bridge->num = i; - INIT_LIST_HEAD(&bridge->devices); - list_add_tail(&bridge->bus_list, &vme_bus_list); - ret = 0; - break; - } - } - mutex_unlock(&vme_buses_lock); - - return ret; -} -EXPORT_SYMBOL(vme_register_bridge); - -void vme_unregister_bridge(struct vme_bridge *bridge) -{ - struct vme_dev *vdev; - struct vme_dev *tmp; - - mutex_lock(&vme_buses_lock); - vme_bus_numbers &= ~(1 << bridge->num); - list_for_each_entry_safe(vdev, tmp, &bridge->devices, bridge_list) { - list_del(&vdev->drv_list); - list_del(&vdev->bridge_list); - device_unregister(&vdev->dev); - } - list_del(&bridge->bus_list); - mutex_unlock(&vme_buses_lock); -} -EXPORT_SYMBOL(vme_unregister_bridge); - -/* - Driver Registration --------------------------------------------------- */ - -static int __vme_register_driver_bus(struct vme_driver *drv, - struct vme_bridge *bridge, - unsigned int ndevs) -{ - int err; - unsigned int i; - struct vme_dev *vdev; - struct vme_dev *tmp; - - for (i = 0; i < ndevs; i++) { - vdev = kzalloc_obj(*vdev); - if (!vdev) { - err = -ENOMEM; - goto err_devalloc; - } - vdev->num = i; - vdev->bridge = bridge; - vdev->dev.platform_data = drv; - vdev->dev.release = vme_dev_release; - vdev->dev.parent = bridge->parent; - vdev->dev.bus = &vme_bus_type; - dev_set_name(&vdev->dev, "%s.%u-%u", drv->name, bridge->num, - vdev->num); - - err = device_register(&vdev->dev); - if (err) - goto err_reg; - - if (vdev->dev.platform_data) { - list_add_tail(&vdev->drv_list, &drv->devices); - list_add_tail(&vdev->bridge_list, &bridge->devices); - } else { - device_unregister(&vdev->dev); - } - } - return 0; - -err_reg: - put_device(&vdev->dev); -err_devalloc: - list_for_each_entry_safe(vdev, tmp, &drv->devices, drv_list) { - list_del(&vdev->drv_list); - list_del(&vdev->bridge_list); - device_unregister(&vdev->dev); - } - return err; -} - -static int __vme_register_driver(struct vme_driver *drv, unsigned int ndevs) -{ - struct vme_bridge *bridge; - int err = 0; - - mutex_lock(&vme_buses_lock); - list_for_each_entry(bridge, &vme_bus_list, bus_list) { - /* - * This cannot cause trouble as we already have vme_buses_lock - * and if the bridge is removed, it will have to go through - * vme_unregister_bridge() to do it (which calls remove() on - * the bridge which in turn tries to acquire vme_buses_lock and - * will have to wait). - */ - err = __vme_register_driver_bus(drv, bridge, ndevs); - if (err) - break; - } - mutex_unlock(&vme_buses_lock); - return err; -} - -/** - * vme_register_driver - Register a VME driver - * @drv: Pointer to VME driver structure to register. - * @ndevs: Maximum number of devices to allow to be enumerated. - * - * Register a VME device driver with the VME subsystem. - * - * Return: Zero on success, error value on registration failure. - */ -int vme_register_driver(struct vme_driver *drv, unsigned int ndevs) -{ - int err; - - drv->driver.name = drv->name; - drv->driver.bus = &vme_bus_type; - INIT_LIST_HEAD(&drv->devices); - - err = driver_register(&drv->driver); - if (err) - return err; - - err = __vme_register_driver(drv, ndevs); - if (err) - driver_unregister(&drv->driver); - - return err; -} -EXPORT_SYMBOL(vme_register_driver); - -/** - * vme_unregister_driver - Unregister a VME driver - * @drv: Pointer to VME driver structure to unregister. - * - * Unregister a VME device driver from the VME subsystem. - */ -void vme_unregister_driver(struct vme_driver *drv) -{ - struct vme_dev *dev, *dev_tmp; - - mutex_lock(&vme_buses_lock); - list_for_each_entry_safe(dev, dev_tmp, &drv->devices, drv_list) { - list_del(&dev->drv_list); - list_del(&dev->bridge_list); - device_unregister(&dev->dev); - } - mutex_unlock(&vme_buses_lock); - - driver_unregister(&drv->driver); -} -EXPORT_SYMBOL(vme_unregister_driver); - -/* - Bus Registration ------------------------------------------------------ */ - -static int vme_bus_match(struct device *dev, const struct device_driver *drv) -{ - const struct vme_driver *vme_drv; - - vme_drv = container_of(drv, struct vme_driver, driver); - - if (dev->platform_data == vme_drv) { - struct vme_dev *vdev = dev_to_vme_dev(dev); - - if (vme_drv->match && vme_drv->match(vdev)) - return 1; - - dev->platform_data = NULL; - } - return 0; -} - -static int vme_bus_probe(struct device *dev) -{ - struct vme_driver *driver; - struct vme_dev *vdev = dev_to_vme_dev(dev); - - driver = dev->platform_data; - if (driver->probe) - return driver->probe(vdev); - - return -ENODEV; -} - -static void vme_bus_remove(struct device *dev) -{ - struct vme_driver *driver; - struct vme_dev *vdev = dev_to_vme_dev(dev); - - driver = dev->platform_data; - if (driver->remove) - driver->remove(vdev); -} - -const struct bus_type vme_bus_type = { - .name = "vme", - .match = vme_bus_match, - .probe = vme_bus_probe, - .remove = vme_bus_remove, -}; -EXPORT_SYMBOL(vme_bus_type); - -static int __init vme_init(void) -{ - return bus_register(&vme_bus_type); -} -subsys_initcall(vme_init); diff --git a/drivers/staging/vme_user/vme.h b/drivers/staging/vme_user/vme.h deleted file mode 100644 index b6413605ea49c3..00000000000000 --- a/drivers/staging/vme_user/vme.h +++ /dev/null @@ -1,190 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0 */ -#ifndef _VME_H_ -#define _VME_H_ - -#include - -/* Resource Type */ -enum vme_resource_type { - VME_MASTER, - VME_SLAVE, - VME_DMA, - VME_LM -}; - -/* VME Address Spaces */ -#define VME_A16 0x1 -#define VME_A24 0x2 -#define VME_A32 0x4 -#define VME_A64 0x8 -#define VME_CRCSR 0x10 -#define VME_USER1 0x20 -#define VME_USER2 0x40 -#define VME_USER3 0x80 -#define VME_USER4 0x100 - -#define VME_A16_MAX 0x10000ULL -#define VME_A24_MAX 0x1000000ULL -#define VME_A32_MAX 0x100000000ULL -#define VME_A64_MAX 0x10000000000000000ULL -#define VME_CRCSR_MAX 0x1000000ULL - -/* VME Cycle Types */ -#define VME_SCT 0x1 -#define VME_BLT 0x2 -#define VME_MBLT 0x4 -#define VME_2eVME 0x8 -#define VME_2eSST 0x10 -#define VME_2eSSTB 0x20 - -#define VME_2eSST160 0x100 -#define VME_2eSST267 0x200 -#define VME_2eSST320 0x400 - -#define VME_SUPER 0x1000 -#define VME_USER 0x2000 -#define VME_PROG 0x4000 -#define VME_DATA 0x8000 - -/* VME Data Widths */ -#define VME_D8 0x1 -#define VME_D16 0x2 -#define VME_D32 0x4 -#define VME_D64 0x8 - -/* Arbitration Scheduling Modes */ -#define VME_R_ROBIN_MODE 0x1 -#define VME_PRIORITY_MODE 0x2 - -#define VME_DMA_PATTERN BIT(0) -#define VME_DMA_PCI BIT(1) -#define VME_DMA_VME BIT(2) - -#define VME_DMA_PATTERN_BYTE BIT(0) -#define VME_DMA_PATTERN_WORD BIT(1) -#define VME_DMA_PATTERN_INCREMENT BIT(2) - -#define VME_DMA_VME_TO_MEM BIT(0) -#define VME_DMA_MEM_TO_VME BIT(1) -#define VME_DMA_VME_TO_VME BIT(2) -#define VME_DMA_MEM_TO_MEM BIT(3) -#define VME_DMA_PATTERN_TO_VME BIT(4) -#define VME_DMA_PATTERN_TO_MEM BIT(5) - -struct vme_dma_attr { - u32 type; - void *private; -}; - -struct vme_resource { - enum vme_resource_type type; - struct list_head *entry; -}; - -extern const struct bus_type vme_bus_type; - -/* Number of VME interrupt vectors */ -#define VME_NUM_STATUSID 256 - -/* VME_MAX_BRIDGES comes from the type of vme_bus_numbers */ -#define VME_MAX_BRIDGES (sizeof(unsigned int) * 8) -#define VME_MAX_SLOTS 32 - -#define VME_SLOT_CURRENT -1 -#define VME_SLOT_ALL -2 - -/** - * struct vme_dev - Structure representing a VME device - * @num: The device number - * @bridge: Pointer to the bridge device this device is on - * @dev: Internal device structure - * @drv_list: List of devices (per driver) - * @bridge_list: List of devices (per bridge) - */ -struct vme_dev { - int num; - struct vme_bridge *bridge; - struct device dev; - struct list_head drv_list; - struct list_head bridge_list; -}; - -/** - * struct vme_driver - Structure representing a VME driver - * @name: Driver name, should be unique among VME drivers and usually the same - * as the module name. - * @match: Callback used to determine whether probe should be run. - * @probe: Callback for device binding, called when new device is detected. - * @remove: Callback, called on device removal. - * @driver: Underlying generic device driver structure. - * @devices: List of VME devices (struct vme_dev) associated with this driver. - */ -struct vme_driver { - const char *name; - int (*match)(struct vme_dev *vdev); - int (*probe)(struct vme_dev *vdev); - void (*remove)(struct vme_dev *vdev); - struct device_driver driver; - struct list_head devices; -}; - -void *vme_alloc_consistent(struct vme_resource *resource, size_t size, dma_addr_t *dma); -void vme_free_consistent(struct vme_resource *resource, size_t size, void *vaddr, dma_addr_t dma); - -size_t vme_get_size(struct vme_resource *resource); -int vme_check_window(struct vme_bridge *bridge, u32 aspace, - unsigned long long vme_base, unsigned long long size); - -struct vme_resource *vme_slave_request(struct vme_dev *vdev, u32 address, u32 cycle); -int vme_slave_set(struct vme_resource *resource, int enabled, unsigned long long vme_base, - unsigned long long size, dma_addr_t buf_base, u32 aspace, u32 cycle); -int vme_slave_get(struct vme_resource *resource, int *enabled, unsigned long long *vme_base, - unsigned long long *size, dma_addr_t *buf_base, u32 *aspace, u32 *cycle); -void vme_slave_free(struct vme_resource *resource); - -struct vme_resource *vme_master_request(struct vme_dev *vdev, u32 address, u32 cycle, u32 dwidth); -int vme_master_set(struct vme_resource *resource, int enabled, unsigned long long vme_base, - unsigned long long size, u32 aspace, u32 cycle, u32 dwidth); -int vme_master_get(struct vme_resource *resource, int *enabled, unsigned long long *vme_base, - unsigned long long *size, u32 *aspace, u32 *cycle, u32 *dwidth); -ssize_t vme_master_read(struct vme_resource *resource, void *buf, size_t count, loff_t offset); -ssize_t vme_master_write(struct vme_resource *resource, void *buf, size_t count, loff_t offset); -unsigned int vme_master_rmw(struct vme_resource *resource, unsigned int mask, unsigned int compare, - unsigned int swap, loff_t offset); -int vme_master_mmap_prepare(struct vme_resource *resource, struct vm_area_desc *desc); -void vme_master_free(struct vme_resource *resource); - -struct vme_resource *vme_dma_request(struct vme_dev *vdev, u32 route); -struct vme_dma_list *vme_new_dma_list(struct vme_resource *resource); -struct vme_dma_attr *vme_dma_pattern_attribute(u32 pattern, u32 type); -struct vme_dma_attr *vme_dma_pci_attribute(dma_addr_t address); -struct vme_dma_attr *vme_dma_vme_attribute(unsigned long long address, - u32 aspace, u32 cycle, u32 dwidth); -void vme_dma_free_attribute(struct vme_dma_attr *attributes); -int vme_dma_list_add(struct vme_dma_list *list, struct vme_dma_attr *src, - struct vme_dma_attr *dest, size_t count); -int vme_dma_list_exec(struct vme_dma_list *list); -int vme_dma_list_free(struct vme_dma_list *list); -int vme_dma_free(struct vme_resource *resource); - -int vme_irq_request(struct vme_dev *vdev, int level, int statid, - void (*callback)(int level, int statid, void *priv_data), void *priv_data); -void vme_irq_free(struct vme_dev *vdev, int level, int statid); -int vme_irq_generate(struct vme_dev *vdev, int level, int statid); - -struct vme_resource *vme_lm_request(struct vme_dev *vdev); -int vme_lm_count(struct vme_resource *resource); -int vme_lm_set(struct vme_resource *resource, unsigned long long lm_base, u32 aspace, u32 cycle); -int vme_lm_get(struct vme_resource *resource, unsigned long long *lm_base, u32 *aspace, u32 *cycle); -int vme_lm_attach(struct vme_resource *resource, int monitor, void (*callback)(void *), void *data); -int vme_lm_detach(struct vme_resource *resource, int monitor); -void vme_lm_free(struct vme_resource *resource); - -int vme_slot_num(struct vme_dev *vdev); -int vme_bus_num(struct vme_dev *vdev); - -int vme_register_driver(struct vme_driver *drv, unsigned int ndevs); -void vme_unregister_driver(struct vme_driver *drv); - -#endif /* _VME_H_ */ - diff --git a/drivers/staging/vme_user/vme_bridge.h b/drivers/staging/vme_user/vme_bridge.h deleted file mode 100644 index 92b0baa793d73d..00000000000000 --- a/drivers/staging/vme_user/vme_bridge.h +++ /dev/null @@ -1,190 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0 */ -#ifndef _VME_BRIDGE_H_ -#define _VME_BRIDGE_H_ - -#include "vme.h" - -#define VME_CRCSR_BUF_SIZE (508 * 1024) -/* - * Resource structures - */ -struct vme_master_resource { - struct list_head list; - struct vme_bridge *parent; - /* - * We are likely to need to access the VME bus in interrupt context, so - * protect master routines with a spinlock rather than a mutex. - */ - spinlock_t lock; - int locked; - int number; - u32 address_attr; - u32 cycle_attr; - u32 width_attr; - struct resource bus_resource; - void __iomem *kern_base; -}; - -struct vme_slave_resource { - struct list_head list; - struct vme_bridge *parent; - struct mutex mtx; - int locked; - int number; - u32 address_attr; - u32 cycle_attr; -}; - -struct vme_dma_pattern { - u32 pattern; - u32 type; -}; - -struct vme_dma_pci { - dma_addr_t address; -}; - -struct vme_dma_vme { - unsigned long long address; - u32 aspace; - u32 cycle; - u32 dwidth; -}; - -struct vme_dma_list { - struct list_head list; - struct vme_dma_resource *parent; - struct list_head entries; - struct mutex mtx; -}; - -struct vme_dma_resource { - struct list_head list; - struct vme_bridge *parent; - struct mutex mtx; - int locked; - int number; - struct list_head pending; - struct list_head running; - u32 route_attr; -}; - -struct vme_lm_resource { - struct list_head list; - struct vme_bridge *parent; - struct mutex mtx; - int locked; - int number; - int monitors; -}; - -struct vme_error_handler { - struct list_head list; - unsigned long long start; /* Beginning of error window */ - unsigned long long end; /* End of error window */ - unsigned long long first_error; /* Address of the first error */ - u32 aspace; /* Address space of error window*/ - unsigned int num_errors; /* Number of errors */ -}; - -struct vme_callback { - void (*func)(int level, int statid, void *priv_data); - void *priv_data; -}; - -struct vme_irq { - int count; - struct vme_callback callback[VME_NUM_STATUSID]; -}; - -/* Allow 16 characters for name (including null character) */ -#define VMENAMSIZ 16 - -/* This structure stores all the information about one bridge - * The structure should be dynamically allocated by the driver and one instance - * of the structure should be present for each VME chip present in the system. - */ -struct vme_bridge { - char name[VMENAMSIZ]; - int num; - struct list_head master_resources; - struct list_head slave_resources; - struct list_head dma_resources; - struct list_head lm_resources; - - /* List for registered errors handlers */ - struct list_head vme_error_handlers; - /* List of devices on this bridge */ - struct list_head devices; - - /* Bridge Info - XXX Move to private structure? */ - struct device *parent; /* Parent device (eg. pdev->dev for PCI) */ - void *driver_priv; /* Private pointer for the bridge driver */ - struct list_head bus_list; /* list of VME buses */ - - /* Interrupt callbacks */ - struct vme_irq irq[7]; - /* Locking for VME irq callback configuration */ - struct mutex irq_mtx; - - /* Slave Functions */ - int (*slave_get)(struct vme_slave_resource *image, int *enabled, - unsigned long long *vme_base, unsigned long long *size, - dma_addr_t *buf_base, u32 *aspace, u32 *cycle); - int (*slave_set)(struct vme_slave_resource *image, int enabled, - unsigned long long vme_base, unsigned long long size, - dma_addr_t buf_base, u32 aspace, u32 cycle); - - /* Master Functions */ - int (*master_get)(struct vme_master_resource *image, int *enabled, - unsigned long long *vme_base, unsigned long long *size, - u32 *aspace, u32 *cycle, u32 *dwidth); - int (*master_set)(struct vme_master_resource *image, int enabled, - unsigned long long vme_base, unsigned long long size, - u32 aspace, u32 cycle, u32 dwidth); - ssize_t (*master_read)(struct vme_master_resource *image, void *buf, - size_t count, loff_t offset); - ssize_t (*master_write)(struct vme_master_resource *image, void *buf, - size_t count, loff_t offset); - unsigned int (*master_rmw)(struct vme_master_resource *image, - unsigned int mask, unsigned int compare, - unsigned int swap, loff_t offset); - - /* DMA Functions */ - int (*dma_list_add)(struct vme_dma_list *list, struct vme_dma_attr *src, - struct vme_dma_attr *dest, size_t count); - int (*dma_list_exec)(struct vme_dma_list *list); - int (*dma_list_empty)(struct vme_dma_list *list); - - /* Interrupt Functions */ - void (*irq_set)(struct vme_bridge *bridge, int level, int state, int sync); - int (*irq_generate)(struct vme_bridge *bridge, int level, int statid); - - /* Location monitor functions */ - int (*lm_set)(struct vme_lm_resource *lm, unsigned long long lm_base, - u32 aspace, u32 cycle); - int (*lm_get)(struct vme_lm_resource *lm, unsigned long long *lm_base, - u32 *aspace, u32 *cycle); - int (*lm_attach)(struct vme_lm_resource *lm, int monitor, - void (*callback)(void *), void *data); - int (*lm_detach)(struct vme_lm_resource *lm, int monitor); - - /* CR/CSR space functions */ - int (*slot_get)(struct vme_bridge *bridge); - - /* Bridge parent interface */ - void *(*alloc_consistent)(struct device *dev, size_t size, dma_addr_t *dma); - void (*free_consistent)(struct device *dev, size_t size, void *vaddr, dma_addr_t dma); -}; - -void vme_bus_error_handler(struct vme_bridge *bridge, unsigned long long address, int am); -void vme_irq_handler(struct vme_bridge *bridge, int level, int statid); - -struct vme_bridge *vme_init_bridge(struct vme_bridge *bridge); -int vme_register_bridge(struct vme_bridge *bridge); -void vme_unregister_bridge(struct vme_bridge *bridge); -struct vme_error_handler *vme_register_error_handler(struct vme_bridge *bridge, u32 aspace, - unsigned long long address, size_t len); -void vme_unregister_error_handler(struct vme_error_handler *handler); - -#endif /* _VME_BRIDGE_H_ */ diff --git a/drivers/staging/vme_user/vme_fake.c b/drivers/staging/vme_user/vme_fake.c deleted file mode 100644 index 434cf760ade6c8..00000000000000 --- a/drivers/staging/vme_user/vme_fake.c +++ /dev/null @@ -1,1308 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-or-later -/* - * Fake VME bridge support. - * - * This drive provides a fake VME bridge chip, this enables debugging of the - * VME framework in the absence of a VME system. - * - * This driver has to do a number of things in software that would be driven - * by hardware if it was available, it will also result in extra overhead at - * times when compared with driving actual hardware. - * - * Author: Martyn Welch - * Copyright (c) 2014 Martyn Welch - * - * Based on vme_tsi148.c: - * - * Author: Martyn Welch - * Copyright 2008 GE Intelligent Platforms Embedded Systems, Inc. - * - * Based on work by Tom Armistead and Ajit Prem - * Copyright 2004 Motorola Inc. - */ - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "vme.h" -#include "vme_bridge.h" - -/* - * Define the number of each that the fake driver supports. - */ -#define FAKE_MAX_MASTER 8 /* Max Master Windows */ -#define FAKE_MAX_SLAVE 8 /* Max Slave Windows */ - -/* Structures to hold information normally held in device registers */ -struct fake_slave_window { - int enabled; - unsigned long long vme_base; - unsigned long long size; - void *buf_base; - u32 aspace; - u32 cycle; -}; - -struct fake_master_window { - int enabled; - unsigned long long vme_base; - unsigned long long size; - u32 aspace; - u32 cycle; - u32 dwidth; -}; - -/* Structure used to hold driver specific information */ -struct fake_driver { - struct vme_bridge *parent; - struct fake_slave_window slaves[FAKE_MAX_SLAVE]; - struct fake_master_window masters[FAKE_MAX_MASTER]; - u32 lm_enabled; - unsigned long long lm_base; - u32 lm_aspace; - u32 lm_cycle; - void (*lm_callback[4])(void *); - void *lm_data[4]; - struct tasklet_struct int_tasklet; - int int_level; - int int_statid; - void *crcsr_kernel; - dma_addr_t crcsr_bus; - /* Only one VME interrupt can be generated at a time, provide locking */ - struct mutex vme_int; -}; - -/* Module parameter */ -static u32 geoid; - -static const char driver_name[] = "vme_fake"; - -static struct vme_bridge *exit_pointer; - -static struct device *vme_root; - -/* - * Calling VME bus interrupt callback if provided. - */ -static void fake_VIRQ_tasklet(unsigned long data) -{ - struct vme_bridge *fake_bridge; - struct fake_driver *bridge; - - fake_bridge = (struct vme_bridge *)data; - bridge = fake_bridge->driver_priv; - - vme_irq_handler(fake_bridge, bridge->int_level, bridge->int_statid); -} - -/* - * Configure VME interrupt - */ -static void fake_irq_set(struct vme_bridge *fake_bridge, int level, - int state, int sync) -{ - /* Nothing to do */ -} - -static void *fake_pci_to_ptr(dma_addr_t addr) -{ - return (void *)(uintptr_t)addr; -} - -static dma_addr_t fake_ptr_to_pci(void *addr) -{ - return (dma_addr_t)(uintptr_t)addr; -} - -/* - * Generate a VME bus interrupt at the requested level & vector. Wait for - * interrupt to be acked. - */ -static int fake_irq_generate(struct vme_bridge *fake_bridge, int level, - int statid) -{ - struct fake_driver *bridge; - - bridge = fake_bridge->driver_priv; - - mutex_lock(&bridge->vme_int); - - bridge->int_level = level; - - bridge->int_statid = statid; - - /* - * Schedule tasklet to run VME handler to emulate normal VME interrupt - * handler behaviour. - */ - tasklet_schedule(&bridge->int_tasklet); - - mutex_unlock(&bridge->vme_int); - - return 0; -} - -/* - * Initialize a slave window with the requested attributes. - */ -static int fake_slave_set(struct vme_slave_resource *image, int enabled, - unsigned long long vme_base, unsigned long long size, - dma_addr_t buf_base, u32 aspace, u32 cycle) -{ - unsigned int i, granularity = 0; - unsigned long long vme_bound; - struct vme_bridge *fake_bridge; - struct fake_driver *bridge; - - fake_bridge = image->parent; - bridge = fake_bridge->driver_priv; - - i = image->number; - - switch (aspace) { - case VME_A16: - granularity = 0x10; - break; - case VME_A24: - granularity = 0x1000; - break; - case VME_A32: - granularity = 0x10000; - break; - case VME_A64: - granularity = 0x10000; - break; - case VME_CRCSR: - case VME_USER1: - case VME_USER2: - case VME_USER3: - case VME_USER4: - default: - pr_err("Invalid address space\n"); - return -EINVAL; - } - - /* - * Bound address is a valid address for the window, adjust - * accordingly - */ - vme_bound = vme_base + size - granularity; - - if (vme_base & (granularity - 1)) { - pr_err("Invalid VME base alignment\n"); - return -EINVAL; - } - if (vme_bound & (granularity - 1)) { - pr_err("Invalid VME bound alignment\n"); - return -EINVAL; - } - - mutex_lock(&image->mtx); - - bridge->slaves[i].enabled = enabled; - bridge->slaves[i].vme_base = vme_base; - bridge->slaves[i].size = size; - bridge->slaves[i].buf_base = fake_pci_to_ptr(buf_base); - bridge->slaves[i].aspace = aspace; - bridge->slaves[i].cycle = cycle; - - mutex_unlock(&image->mtx); - - return 0; -} - -/* - * Get slave window configuration. - */ -static int fake_slave_get(struct vme_slave_resource *image, int *enabled, - unsigned long long *vme_base, unsigned long long *size, - dma_addr_t *buf_base, u32 *aspace, u32 *cycle) -{ - unsigned int i; - struct fake_driver *bridge; - - bridge = image->parent->driver_priv; - - i = image->number; - - mutex_lock(&image->mtx); - - *enabled = bridge->slaves[i].enabled; - *vme_base = bridge->slaves[i].vme_base; - *size = bridge->slaves[i].size; - *buf_base = fake_ptr_to_pci(bridge->slaves[i].buf_base); - *aspace = bridge->slaves[i].aspace; - *cycle = bridge->slaves[i].cycle; - - mutex_unlock(&image->mtx); - - return 0; -} - -/* - * Set the attributes of an outbound window. - */ -static int fake_master_set(struct vme_master_resource *image, int enabled, - unsigned long long vme_base, unsigned long long size, - u32 aspace, u32 cycle, u32 dwidth) -{ - int retval = 0; - unsigned int i; - struct vme_bridge *fake_bridge; - struct fake_driver *bridge; - - fake_bridge = image->parent; - - bridge = fake_bridge->driver_priv; - - /* Verify input data */ - if (vme_base & 0xFFFF) { - pr_err("Invalid VME Window alignment\n"); - retval = -EINVAL; - goto err_window; - } - - if (size & 0xFFFF) { - pr_err("Invalid size alignment\n"); - retval = -EINVAL; - goto err_window; - } - - if ((size == 0) && (enabled != 0)) { - pr_err("Size must be non-zero for enabled windows\n"); - retval = -EINVAL; - goto err_window; - } - - /* Setup data width */ - switch (dwidth) { - case VME_D8: - case VME_D16: - case VME_D32: - break; - default: - pr_err("Invalid data width\n"); - retval = -EINVAL; - goto err_dwidth; - } - - /* Setup address space */ - switch (aspace) { - case VME_A16: - case VME_A24: - case VME_A32: - case VME_A64: - case VME_CRCSR: - case VME_USER1: - case VME_USER2: - case VME_USER3: - case VME_USER4: - break; - default: - pr_err("Invalid address space\n"); - retval = -EINVAL; - goto err_aspace; - } - - spin_lock(&image->lock); - - i = image->number; - - bridge->masters[i].enabled = enabled; - bridge->masters[i].vme_base = vme_base; - bridge->masters[i].size = size; - bridge->masters[i].aspace = aspace; - bridge->masters[i].cycle = cycle; - bridge->masters[i].dwidth = dwidth; - - spin_unlock(&image->lock); - - return 0; - -err_aspace: -err_dwidth: -err_window: - return retval; -} - -/* - * Set the attributes of an outbound window. - */ -static int __fake_master_get(struct vme_master_resource *image, int *enabled, - unsigned long long *vme_base, unsigned long long *size, - u32 *aspace, u32 *cycle, u32 *dwidth) -{ - unsigned int i; - struct fake_driver *bridge; - - bridge = image->parent->driver_priv; - - i = image->number; - - *enabled = bridge->masters[i].enabled; - *vme_base = bridge->masters[i].vme_base; - *size = bridge->masters[i].size; - *aspace = bridge->masters[i].aspace; - *cycle = bridge->masters[i].cycle; - *dwidth = bridge->masters[i].dwidth; - - return 0; -} - -static int fake_master_get(struct vme_master_resource *image, int *enabled, - unsigned long long *vme_base, unsigned long long *size, - u32 *aspace, u32 *cycle, u32 *dwidth) -{ - int retval; - - spin_lock(&image->lock); - - retval = __fake_master_get(image, enabled, vme_base, size, aspace, - cycle, dwidth); - - spin_unlock(&image->lock); - - return retval; -} - -static void fake_lm_check(struct fake_driver *bridge, unsigned long long addr, - u32 aspace, u32 cycle) -{ - struct vme_bridge *fake_bridge; - unsigned long long lm_base; - u32 lm_aspace, lm_cycle; - int i; - struct vme_lm_resource *lm; - struct list_head *pos = NULL, *n; - - /* Get vme_bridge */ - fake_bridge = bridge->parent; - - /* Loop through each location monitor resource */ - list_for_each_safe(pos, n, &fake_bridge->lm_resources) { - lm = list_entry(pos, struct vme_lm_resource, list); - - /* If disabled, we're done */ - if (bridge->lm_enabled == 0) - return; - - lm_base = bridge->lm_base; - lm_aspace = bridge->lm_aspace; - lm_cycle = bridge->lm_cycle; - - /* First make sure that the cycle and address space match */ - if ((lm_aspace == aspace) && (lm_cycle == cycle)) { - for (i = 0; i < lm->monitors; i++) { - /* Each location monitor covers 8 bytes */ - if (((lm_base + (8 * i)) <= addr) && - ((lm_base + (8 * i) + 8) > addr)) { - if (bridge->lm_callback[i]) - bridge->lm_callback[i](bridge->lm_data[i]); - } - } - } - } -} - -static noinline_for_stack u8 fake_vmeread8(struct fake_driver *bridge, - unsigned long long addr, - u32 aspace, u32 cycle) -{ - u8 retval = 0xff; - int i; - unsigned long long start, end, offset; - u8 *loc; - - for (i = 0; i < FAKE_MAX_SLAVE; i++) { - start = bridge->slaves[i].vme_base; - end = bridge->slaves[i].vme_base + bridge->slaves[i].size; - - if (aspace != bridge->slaves[i].aspace) - continue; - - if (cycle != bridge->slaves[i].cycle) - continue; - - if ((addr >= start) && (addr < end)) { - offset = addr - bridge->slaves[i].vme_base; - loc = (u8 *)(bridge->slaves[i].buf_base + offset); - retval = *loc; - - break; - } - } - - fake_lm_check(bridge, addr, aspace, cycle); - - return retval; -} - -static noinline_for_stack u16 fake_vmeread16(struct fake_driver *bridge, - unsigned long long addr, - u32 aspace, u32 cycle) -{ - u16 retval = 0xffff; - int i; - unsigned long long start, end, offset; - u16 *loc; - - for (i = 0; i < FAKE_MAX_SLAVE; i++) { - if (aspace != bridge->slaves[i].aspace) - continue; - - if (cycle != bridge->slaves[i].cycle) - continue; - - start = bridge->slaves[i].vme_base; - end = bridge->slaves[i].vme_base + bridge->slaves[i].size; - - if ((addr >= start) && ((addr + 1) < end)) { - offset = addr - bridge->slaves[i].vme_base; - loc = (u16 *)(bridge->slaves[i].buf_base + offset); - retval = *loc; - - break; - } - } - - fake_lm_check(bridge, addr, aspace, cycle); - - return retval; -} - -static noinline_for_stack u32 fake_vmeread32(struct fake_driver *bridge, - unsigned long long addr, - u32 aspace, u32 cycle) -{ - u32 retval = 0xffffffff; - int i; - unsigned long long start, end, offset; - u32 *loc; - - for (i = 0; i < FAKE_MAX_SLAVE; i++) { - if (aspace != bridge->slaves[i].aspace) - continue; - - if (cycle != bridge->slaves[i].cycle) - continue; - - start = bridge->slaves[i].vme_base; - end = bridge->slaves[i].vme_base + bridge->slaves[i].size; - - if ((addr >= start) && ((addr + 3) < end)) { - offset = addr - bridge->slaves[i].vme_base; - loc = (u32 *)(bridge->slaves[i].buf_base + offset); - retval = *loc; - - break; - } - } - - fake_lm_check(bridge, addr, aspace, cycle); - - return retval; -} - -static ssize_t fake_master_read(struct vme_master_resource *image, void *buf, - size_t count, loff_t offset) -{ - int retval; - u32 aspace, cycle, dwidth; - struct vme_bridge *fake_bridge; - struct fake_driver *priv; - int i; - unsigned long long addr; - unsigned int done = 0; - unsigned int count32; - - fake_bridge = image->parent; - - priv = fake_bridge->driver_priv; - - i = image->number; - - addr = (unsigned long long)priv->masters[i].vme_base + offset; - aspace = priv->masters[i].aspace; - cycle = priv->masters[i].cycle; - dwidth = priv->masters[i].dwidth; - - spin_lock(&image->lock); - - /* The following code handles VME address alignment. We cannot use - * memcpy_xxx here because it may cut data transfers in to 8-bit - * cycles when D16 or D32 cycles are required on the VME bus. - * On the other hand, the bridge itself assures that the maximum data - * cycle configured for the transfer is used and splits it - * automatically for non-aligned addresses, so we don't want the - * overhead of needlessly forcing small transfers for the entire cycle. - */ - if (addr & 0x1) { - *(u8 *)buf = fake_vmeread8(priv, addr, aspace, cycle); - done += 1; - if (done == count) - goto out; - } - if ((dwidth == VME_D16) || (dwidth == VME_D32)) { - if ((addr + done) & 0x2) { - if ((count - done) < 2) { - *(u8 *)(buf + done) = fake_vmeread8(priv, - addr + done, aspace, cycle); - done += 1; - goto out; - } else { - *(u16 *)(buf + done) = fake_vmeread16(priv, - addr + done, aspace, cycle); - done += 2; - } - } - } - - if (dwidth == VME_D32) { - count32 = (count - done) & ~0x3; - while (done < count32) { - *(u32 *)(buf + done) = fake_vmeread32(priv, addr + done, - aspace, cycle); - done += 4; - } - } else if (dwidth == VME_D16) { - count32 = (count - done) & ~0x3; - while (done < count32) { - *(u16 *)(buf + done) = fake_vmeread16(priv, addr + done, - aspace, cycle); - done += 2; - } - } else if (dwidth == VME_D8) { - count32 = (count - done); - while (done < count32) { - *(u8 *)(buf + done) = fake_vmeread8(priv, addr + done, - aspace, cycle); - done += 1; - } - } - - if ((dwidth == VME_D16) || (dwidth == VME_D32)) { - if ((count - done) & 0x2) { - *(u16 *)(buf + done) = fake_vmeread16(priv, addr + done, - aspace, cycle); - done += 2; - } - } - if ((count - done) & 0x1) { - *(u8 *)(buf + done) = fake_vmeread8(priv, addr + done, aspace, - cycle); - done += 1; - } - -out: - retval = count; - - spin_unlock(&image->lock); - - return retval; -} - -static noinline_for_stack void fake_vmewrite8(struct fake_driver *bridge, - u8 *buf, unsigned long long addr, - u32 aspace, u32 cycle) -{ - int i; - unsigned long long start, end, offset; - u8 *loc; - - for (i = 0; i < FAKE_MAX_SLAVE; i++) { - if (aspace != bridge->slaves[i].aspace) - continue; - - if (cycle != bridge->slaves[i].cycle) - continue; - - start = bridge->slaves[i].vme_base; - end = bridge->slaves[i].vme_base + bridge->slaves[i].size; - - if ((addr >= start) && (addr < end)) { - offset = addr - bridge->slaves[i].vme_base; - loc = (u8 *)((void *)bridge->slaves[i].buf_base + offset); - *loc = *buf; - - break; - } - } - - fake_lm_check(bridge, addr, aspace, cycle); -} - -static noinline_for_stack void fake_vmewrite16(struct fake_driver *bridge, - u16 *buf, unsigned long long addr, - u32 aspace, u32 cycle) -{ - int i; - unsigned long long start, end, offset; - u16 *loc; - - for (i = 0; i < FAKE_MAX_SLAVE; i++) { - if (aspace != bridge->slaves[i].aspace) - continue; - - if (cycle != bridge->slaves[i].cycle) - continue; - - start = bridge->slaves[i].vme_base; - end = bridge->slaves[i].vme_base + bridge->slaves[i].size; - - if ((addr >= start) && ((addr + 1) < end)) { - offset = addr - bridge->slaves[i].vme_base; - loc = (u16 *)((void *)bridge->slaves[i].buf_base + offset); - *loc = *buf; - - break; - } - } - - fake_lm_check(bridge, addr, aspace, cycle); -} - -static noinline_for_stack void fake_vmewrite32(struct fake_driver *bridge, - u32 *buf, unsigned long long addr, - u32 aspace, u32 cycle) -{ - int i; - unsigned long long start, end, offset; - u32 *loc; - - for (i = 0; i < FAKE_MAX_SLAVE; i++) { - if (aspace != bridge->slaves[i].aspace) - continue; - - if (cycle != bridge->slaves[i].cycle) - continue; - - start = bridge->slaves[i].vme_base; - end = bridge->slaves[i].vme_base + bridge->slaves[i].size; - - if ((addr >= start) && ((addr + 3) < end)) { - offset = addr - bridge->slaves[i].vme_base; - loc = (u32 *)((void *)bridge->slaves[i].buf_base + offset); - *loc = *buf; - - break; - } - } - - fake_lm_check(bridge, addr, aspace, cycle); -} - -static ssize_t fake_master_write(struct vme_master_resource *image, void *buf, - size_t count, loff_t offset) -{ - int retval = 0; - u32 aspace, cycle, dwidth; - unsigned long long addr; - int i; - unsigned int done = 0; - unsigned int count32; - - struct vme_bridge *fake_bridge; - struct fake_driver *bridge; - - fake_bridge = image->parent; - - bridge = fake_bridge->driver_priv; - - i = image->number; - - addr = bridge->masters[i].vme_base + offset; - aspace = bridge->masters[i].aspace; - cycle = bridge->masters[i].cycle; - dwidth = bridge->masters[i].dwidth; - - spin_lock(&image->lock); - - /* Here we apply for the same strategy we do in master_read - * function in order to assure the correct cycles. - */ - if (addr & 0x1) { - fake_vmewrite8(bridge, (u8 *)buf, addr, aspace, cycle); - done += 1; - if (done == count) - goto out; - } - - if ((dwidth == VME_D16) || (dwidth == VME_D32)) { - if ((addr + done) & 0x2) { - if ((count - done) < 2) { - fake_vmewrite8(bridge, (u8 *)(buf + done), - addr + done, aspace, cycle); - done += 1; - goto out; - } else { - fake_vmewrite16(bridge, (u16 *)(buf + done), - addr + done, aspace, cycle); - done += 2; - } - } - } - - if (dwidth == VME_D32) { - count32 = (count - done) & ~0x3; - while (done < count32) { - fake_vmewrite32(bridge, (u32 *)(buf + done), - addr + done, aspace, cycle); - done += 4; - } - } else if (dwidth == VME_D16) { - count32 = (count - done) & ~0x3; - while (done < count32) { - fake_vmewrite16(bridge, (u16 *)(buf + done), - addr + done, aspace, cycle); - done += 2; - } - } else if (dwidth == VME_D8) { - count32 = (count - done); - while (done < count32) { - fake_vmewrite8(bridge, (u8 *)(buf + done), addr + done, - aspace, cycle); - done += 1; - } - } - - if ((dwidth == VME_D16) || (dwidth == VME_D32)) { - if ((count - done) & 0x2) { - fake_vmewrite16(bridge, (u16 *)(buf + done), - addr + done, aspace, cycle); - done += 2; - } - } - - if ((count - done) & 0x1) { - fake_vmewrite8(bridge, (u8 *)(buf + done), addr + done, aspace, - cycle); - done += 1; - } - -out: - retval = count; - - spin_unlock(&image->lock); - - return retval; -} - -/* - * Perform an RMW cycle on the VME bus. - * - * Requires a previously configured master window, returns final value. - */ -static unsigned int fake_master_rmw(struct vme_master_resource *image, - unsigned int mask, unsigned int compare, - unsigned int swap, loff_t offset) -{ - u32 tmp, base; - u32 aspace, cycle; - int i; - struct fake_driver *bridge; - - bridge = image->parent->driver_priv; - - /* Find the PCI address that maps to the desired VME address */ - i = image->number; - - base = bridge->masters[i].vme_base; - aspace = bridge->masters[i].aspace; - cycle = bridge->masters[i].cycle; - - /* Lock image */ - spin_lock(&image->lock); - - /* Read existing value */ - tmp = fake_vmeread32(bridge, base + offset, aspace, cycle); - - /* Perform check */ - if ((tmp && mask) == (compare && mask)) { - tmp = tmp | (mask | swap); - tmp = tmp & (~mask | swap); - - /* Write back */ - fake_vmewrite32(bridge, &tmp, base + offset, aspace, cycle); - } - - /* Unlock image */ - spin_unlock(&image->lock); - - return tmp; -} - -/* - * All 4 location monitors reside at the same base - this is therefore a - * system wide configuration. - * - * This does not enable the LM monitor - that should be done when the first - * callback is attached and disabled when the last callback is removed. - */ -static int fake_lm_set(struct vme_lm_resource *lm, unsigned long long lm_base, - u32 aspace, u32 cycle) -{ - int i; - struct vme_bridge *fake_bridge; - struct fake_driver *bridge; - - fake_bridge = lm->parent; - - bridge = fake_bridge->driver_priv; - - mutex_lock(&lm->mtx); - - /* If we already have a callback attached, we can't move it! */ - for (i = 0; i < lm->monitors; i++) { - if (bridge->lm_callback[i]) { - mutex_unlock(&lm->mtx); - pr_err("Location monitor callback attached, can't reset\n"); - return -EBUSY; - } - } - - switch (aspace) { - case VME_A16: - case VME_A24: - case VME_A32: - case VME_A64: - break; - default: - mutex_unlock(&lm->mtx); - pr_err("Invalid address space\n"); - return -EINVAL; - } - - bridge->lm_base = lm_base; - bridge->lm_aspace = aspace; - bridge->lm_cycle = cycle; - - mutex_unlock(&lm->mtx); - - return 0; -} - -/* Get configuration of the callback monitor and return whether it is enabled - * or disabled. - */ -static int fake_lm_get(struct vme_lm_resource *lm, - unsigned long long *lm_base, - u32 *aspace, u32 *cycle) -{ - struct fake_driver *bridge; - - bridge = lm->parent->driver_priv; - - mutex_lock(&lm->mtx); - - *lm_base = bridge->lm_base; - *aspace = bridge->lm_aspace; - *cycle = bridge->lm_cycle; - - mutex_unlock(&lm->mtx); - - return bridge->lm_enabled; -} - -/* - * Attach a callback to a specific location monitor. - * - * Callback will be passed the monitor triggered. - */ -static int fake_lm_attach(struct vme_lm_resource *lm, int monitor, - void (*callback)(void *), void *data) -{ - struct vme_bridge *fake_bridge; - struct fake_driver *bridge; - - fake_bridge = lm->parent; - - bridge = fake_bridge->driver_priv; - - mutex_lock(&lm->mtx); - - /* Ensure that the location monitor is configured - need PGM or DATA */ - if (bridge->lm_cycle == 0) { - mutex_unlock(&lm->mtx); - pr_err("Location monitor not properly configured\n"); - return -EINVAL; - } - - /* Check that a callback isn't already attached */ - if (bridge->lm_callback[monitor]) { - mutex_unlock(&lm->mtx); - pr_err("Existing callback attached\n"); - return -EBUSY; - } - - /* Attach callback */ - bridge->lm_callback[monitor] = callback; - bridge->lm_data[monitor] = data; - - /* Ensure that global Location Monitor Enable set */ - bridge->lm_enabled = 1; - - mutex_unlock(&lm->mtx); - - return 0; -} - -/* - * Detach a callback function forn a specific location monitor. - */ -static int fake_lm_detach(struct vme_lm_resource *lm, int monitor) -{ - u32 tmp; - int i; - struct fake_driver *bridge; - - bridge = lm->parent->driver_priv; - - mutex_lock(&lm->mtx); - - /* Detach callback */ - bridge->lm_callback[monitor] = NULL; - bridge->lm_data[monitor] = NULL; - - /* If all location monitors disabled, disable global Location Monitor */ - tmp = 0; - for (i = 0; i < lm->monitors; i++) { - if (bridge->lm_callback[i]) - tmp = 1; - } - - if (tmp == 0) - bridge->lm_enabled = 0; - - mutex_unlock(&lm->mtx); - - return 0; -} - -/* - * Determine Geographical Addressing - */ -static int fake_slot_get(struct vme_bridge *fake_bridge) -{ - return geoid; -} - -static void *fake_alloc_consistent(struct device *parent, size_t size, - dma_addr_t *dma) -{ - void *alloc = kmalloc(size, GFP_KERNEL); - - if (alloc) - *dma = fake_ptr_to_pci(alloc); - - return alloc; -} - -static void fake_free_consistent(struct device *parent, size_t size, - void *vaddr, dma_addr_t dma) -{ - kfree(vaddr); -} - -/* - * Configure CR/CSR space - * - * Access to the CR/CSR can be configured at power-up. The location of the - * CR/CSR registers in the CR/CSR address space is determined by the boards - * Geographic address. - * - * Each board has a 512kB window, with the highest 4kB being used for the - * boards registers, this means there is a fix length 508kB window which must - * be mapped onto PCI memory. - */ -static int fake_crcsr_init(struct vme_bridge *fake_bridge) -{ - u32 vstat; - struct fake_driver *bridge; - - bridge = fake_bridge->driver_priv; - - /* Allocate mem for CR/CSR image */ - bridge->crcsr_kernel = kzalloc(VME_CRCSR_BUF_SIZE, GFP_KERNEL); - bridge->crcsr_bus = fake_ptr_to_pci(bridge->crcsr_kernel); - if (!bridge->crcsr_kernel) - return -ENOMEM; - - vstat = fake_slot_get(fake_bridge); - - pr_info("CR/CSR Offset: %d\n", vstat); - - return 0; -} - -static void fake_crcsr_exit(struct vme_bridge *fake_bridge) -{ - struct fake_driver *bridge; - - bridge = fake_bridge->driver_priv; - - kfree(bridge->crcsr_kernel); -} - -static int __init fake_init(void) -{ - int retval, i; - struct list_head *pos = NULL, *n; - struct vme_bridge *fake_bridge; - struct fake_driver *fake_device; - struct vme_master_resource *master_image; - struct vme_slave_resource *slave_image; - struct vme_lm_resource *lm; - - if (geoid >= VME_MAX_SLOTS) { - pr_err("VME geographical address must be between 0 and %d (exclusive), but got %d\n", - VME_MAX_SLOTS, geoid); - return -EINVAL; - } - - /* We need a fake parent device */ - vme_root = root_device_register("vme"); - if (IS_ERR(vme_root)) - return PTR_ERR(vme_root); - - /* If we want to support more than one bridge at some point, we need to - * dynamically allocate this so we get one per device. - */ - fake_bridge = kzalloc_obj(*fake_bridge); - if (!fake_bridge) { - retval = -ENOMEM; - goto err_struct; - } - - fake_device = kzalloc_obj(*fake_device); - if (!fake_device) { - retval = -ENOMEM; - goto err_driver; - } - - fake_bridge->driver_priv = fake_device; - - fake_bridge->parent = vme_root; - - fake_device->parent = fake_bridge; - - /* Initialize wait queues & mutual exclusion flags */ - mutex_init(&fake_device->vme_int); - mutex_init(&fake_bridge->irq_mtx); - tasklet_init(&fake_device->int_tasklet, fake_VIRQ_tasklet, - (unsigned long)fake_bridge); - - strscpy(fake_bridge->name, driver_name, sizeof(fake_bridge->name)); - - /* Add master windows to list */ - INIT_LIST_HEAD(&fake_bridge->master_resources); - for (i = 0; i < FAKE_MAX_MASTER; i++) { - master_image = kmalloc_obj(*master_image); - if (!master_image) { - retval = -ENOMEM; - goto err_master; - } - master_image->parent = fake_bridge; - spin_lock_init(&master_image->lock); - master_image->locked = 0; - master_image->number = i; - master_image->address_attr = VME_A16 | VME_A24 | VME_A32 | - VME_A64; - master_image->cycle_attr = VME_SCT | VME_BLT | VME_MBLT | - VME_2eVME | VME_2eSST | VME_2eSSTB | VME_2eSST160 | - VME_2eSST267 | VME_2eSST320 | VME_SUPER | VME_USER | - VME_PROG | VME_DATA; - master_image->width_attr = VME_D16 | VME_D32; - memset(&master_image->bus_resource, 0, - sizeof(struct resource)); - master_image->kern_base = NULL; - list_add_tail(&master_image->list, - &fake_bridge->master_resources); - } - - /* Add slave windows to list */ - INIT_LIST_HEAD(&fake_bridge->slave_resources); - for (i = 0; i < FAKE_MAX_SLAVE; i++) { - slave_image = kmalloc_obj(*slave_image); - if (!slave_image) { - retval = -ENOMEM; - goto err_slave; - } - slave_image->parent = fake_bridge; - mutex_init(&slave_image->mtx); - slave_image->locked = 0; - slave_image->number = i; - slave_image->address_attr = VME_A16 | VME_A24 | VME_A32 | - VME_A64 | VME_CRCSR | VME_USER1 | VME_USER2 | - VME_USER3 | VME_USER4; - slave_image->cycle_attr = VME_SCT | VME_BLT | VME_MBLT | - VME_2eVME | VME_2eSST | VME_2eSSTB | VME_2eSST160 | - VME_2eSST267 | VME_2eSST320 | VME_SUPER | VME_USER | - VME_PROG | VME_DATA; - list_add_tail(&slave_image->list, - &fake_bridge->slave_resources); - } - - /* Add location monitor to list */ - INIT_LIST_HEAD(&fake_bridge->lm_resources); - lm = kmalloc_obj(*lm); - if (!lm) { - retval = -ENOMEM; - goto err_lm; - } - lm->parent = fake_bridge; - mutex_init(&lm->mtx); - lm->locked = 0; - lm->number = 1; - lm->monitors = 4; - list_add_tail(&lm->list, &fake_bridge->lm_resources); - - fake_bridge->slave_get = fake_slave_get; - fake_bridge->slave_set = fake_slave_set; - fake_bridge->master_get = fake_master_get; - fake_bridge->master_set = fake_master_set; - fake_bridge->master_read = fake_master_read; - fake_bridge->master_write = fake_master_write; - fake_bridge->master_rmw = fake_master_rmw; - fake_bridge->irq_set = fake_irq_set; - fake_bridge->irq_generate = fake_irq_generate; - fake_bridge->lm_set = fake_lm_set; - fake_bridge->lm_get = fake_lm_get; - fake_bridge->lm_attach = fake_lm_attach; - fake_bridge->lm_detach = fake_lm_detach; - fake_bridge->slot_get = fake_slot_get; - fake_bridge->alloc_consistent = fake_alloc_consistent; - fake_bridge->free_consistent = fake_free_consistent; - - pr_info("Board is%s the VME system controller\n", - (geoid == 1) ? "" : " not"); - - pr_info("VME geographical address is set to %d\n", geoid); - - retval = fake_crcsr_init(fake_bridge); - if (retval) { - pr_err("CR/CSR configuration failed.\n"); - goto err_crcsr; - } - - retval = vme_register_bridge(fake_bridge); - if (retval != 0) { - pr_err("Chip Registration failed.\n"); - goto err_reg; - } - - exit_pointer = fake_bridge; - - return 0; - -err_reg: - fake_crcsr_exit(fake_bridge); -err_crcsr: -err_lm: - /* resources are stored in link list */ - list_for_each_safe(pos, n, &fake_bridge->lm_resources) { - lm = list_entry(pos, struct vme_lm_resource, list); - list_del(pos); - kfree(lm); - } -err_slave: - /* resources are stored in link list */ - list_for_each_safe(pos, n, &fake_bridge->slave_resources) { - slave_image = list_entry(pos, struct vme_slave_resource, list); - list_del(pos); - kfree(slave_image); - } -err_master: - /* resources are stored in link list */ - list_for_each_safe(pos, n, &fake_bridge->master_resources) { - master_image = list_entry(pos, struct vme_master_resource, - list); - list_del(pos); - kfree(master_image); - } - - kfree(fake_device); -err_driver: - kfree(fake_bridge); -err_struct: - root_device_unregister(vme_root); - - return retval; -} - -static void __exit fake_exit(void) -{ - struct list_head *pos = NULL; - struct list_head *tmplist; - struct vme_lm_resource *lm; - struct vme_master_resource *master_image; - struct vme_slave_resource *slave_image; - int i; - struct vme_bridge *fake_bridge; - struct fake_driver *bridge; - - fake_bridge = exit_pointer; - - bridge = fake_bridge->driver_priv; - - pr_debug("Driver is being unloaded.\n"); - - /* - * Shutdown all inbound and outbound windows. - */ - for (i = 0; i < FAKE_MAX_MASTER; i++) - bridge->masters[i].enabled = 0; - - for (i = 0; i < FAKE_MAX_SLAVE; i++) - bridge->slaves[i].enabled = 0; - - /* - * Shutdown Location monitor. - */ - bridge->lm_enabled = 0; - - vme_unregister_bridge(fake_bridge); - - fake_crcsr_exit(fake_bridge); - /* resources are stored in link list */ - list_for_each_safe(pos, tmplist, &fake_bridge->lm_resources) { - lm = list_entry(pos, struct vme_lm_resource, list); - list_del(pos); - kfree(lm); - } - - /* resources are stored in link list */ - list_for_each_safe(pos, tmplist, &fake_bridge->slave_resources) { - slave_image = list_entry(pos, struct vme_slave_resource, list); - list_del(pos); - kfree(slave_image); - } - - /* resources are stored in link list */ - list_for_each_safe(pos, tmplist, &fake_bridge->master_resources) { - master_image = list_entry(pos, struct vme_master_resource, - list); - list_del(pos); - kfree(master_image); - } - - kfree(fake_bridge->driver_priv); - - kfree(fake_bridge); - - root_device_unregister(vme_root); -} - -MODULE_PARM_DESC(geoid, "Set geographical addressing"); -module_param(geoid, uint, 0); - -MODULE_DESCRIPTION("Fake VME bridge driver"); -MODULE_LICENSE("GPL"); - -module_init(fake_init); -module_exit(fake_exit); diff --git a/drivers/staging/vme_user/vme_tsi148.c b/drivers/staging/vme_user/vme_tsi148.c deleted file mode 100644 index 9447c00bc013d7..00000000000000 --- a/drivers/staging/vme_user/vme_tsi148.c +++ /dev/null @@ -1,2643 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-or-later -/* - * Support for the Tundra TSI148 VME-PCI Bridge Chip - * - * Author: Martyn Welch - * Copyright 2008 GE Intelligent Platforms Embedded Systems, Inc. - * - * Based on work by Tom Armistead and Ajit Prem - * Copyright 2004 Motorola Inc. - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "vme.h" -#include "vme_bridge.h" -#include "vme_tsi148.h" - -static int tsi148_probe(struct pci_dev *, const struct pci_device_id *); -static void tsi148_remove(struct pci_dev *); - -/* Module parameter */ -static bool err_chk; -static u32 geoid; - -static const char driver_name[] = "vme_tsi148"; - -static const struct pci_device_id tsi148_ids[] = { - { PCI_DEVICE(PCI_VENDOR_ID_TUNDRA, PCI_DEVICE_ID_TUNDRA_TSI148) }, - { }, -}; - -MODULE_DEVICE_TABLE(pci, tsi148_ids); - -static struct pci_driver tsi148_driver = { - .name = driver_name, - .id_table = tsi148_ids, - .probe = tsi148_probe, - .remove = tsi148_remove, -}; - -static void reg_join(unsigned int high, unsigned int low, - unsigned long long *variable) -{ - *variable = (unsigned long long)high << 32; - *variable |= (unsigned long long)low; -} - -static void reg_split(unsigned long long variable, unsigned int *high, - unsigned int *low) -{ - *low = (unsigned int)variable & 0xFFFFFFFF; - *high = (unsigned int)(variable >> 32); -} - -/* - * Wakes up DMA queue. - */ -static u32 tsi148_DMA_irqhandler(struct tsi148_driver *bridge, - int channel_mask) -{ - u32 serviced = 0; - - if (channel_mask & TSI148_LCSR_INTS_DMA0S) { - wake_up(&bridge->dma_queue[0]); - serviced |= TSI148_LCSR_INTC_DMA0C; - } - if (channel_mask & TSI148_LCSR_INTS_DMA1S) { - wake_up(&bridge->dma_queue[1]); - serviced |= TSI148_LCSR_INTC_DMA1C; - } - - return serviced; -} - -/* - * Wake up location monitor queue - */ -static u32 tsi148_LM_irqhandler(struct tsi148_driver *bridge, u32 stat) -{ - int i; - u32 serviced = 0; - - for (i = 0; i < 4; i++) { - if (stat & TSI148_LCSR_INTS_LMS[i]) { - /* We only enable interrupts if the callback is set */ - bridge->lm_callback[i](bridge->lm_data[i]); - serviced |= TSI148_LCSR_INTC_LMC[i]; - } - } - - return serviced; -} - -/* - * Wake up mail box queue. - * - * XXX This functionality is not exposed up though API. - */ -static u32 tsi148_MB_irqhandler(struct vme_bridge *tsi148_bridge, u32 stat) -{ - int i; - u32 val; - u32 serviced = 0; - struct tsi148_driver *bridge; - - bridge = tsi148_bridge->driver_priv; - - for (i = 0; i < 4; i++) { - if (stat & TSI148_LCSR_INTS_MBS[i]) { - val = ioread32be(bridge->base + TSI148_GCSR_MBOX[i]); - dev_err(tsi148_bridge->parent, "VME Mailbox %d received: 0x%x\n", - i, val); - serviced |= TSI148_LCSR_INTC_MBC[i]; - } - } - - return serviced; -} - -/* - * Display error & status message when PERR (PCI) exception interrupt occurs. - */ -static u32 tsi148_PERR_irqhandler(struct vme_bridge *tsi148_bridge) -{ - struct tsi148_driver *bridge; - - bridge = tsi148_bridge->driver_priv; - - dev_err(tsi148_bridge->parent, "PCI Exception at address: 0x%08x:%08x, attributes: %08x\n", - ioread32be(bridge->base + TSI148_LCSR_EDPAU), - ioread32be(bridge->base + TSI148_LCSR_EDPAL), - ioread32be(bridge->base + TSI148_LCSR_EDPAT)); - - dev_err(tsi148_bridge->parent, "PCI-X attribute reg: %08x, PCI-X split completion reg: %08x\n", - ioread32be(bridge->base + TSI148_LCSR_EDPXA), - ioread32be(bridge->base + TSI148_LCSR_EDPXS)); - - iowrite32be(TSI148_LCSR_EDPAT_EDPCL, bridge->base + TSI148_LCSR_EDPAT); - - return TSI148_LCSR_INTC_PERRC; -} - -/* - * Save address and status when VME error interrupt occurs. - */ -static u32 tsi148_VERR_irqhandler(struct vme_bridge *tsi148_bridge) -{ - unsigned int error_addr_high, error_addr_low; - unsigned long long error_addr; - u32 error_attrib; - int error_am; - struct tsi148_driver *bridge; - - bridge = tsi148_bridge->driver_priv; - - error_addr_high = ioread32be(bridge->base + TSI148_LCSR_VEAU); - error_addr_low = ioread32be(bridge->base + TSI148_LCSR_VEAL); - error_attrib = ioread32be(bridge->base + TSI148_LCSR_VEAT); - error_am = (error_attrib & TSI148_LCSR_VEAT_AM_M) >> 8; - - reg_join(error_addr_high, error_addr_low, &error_addr); - - /* Check for exception register overflow (we have lost error data) */ - if (error_attrib & TSI148_LCSR_VEAT_VEOF) - dev_err(tsi148_bridge->parent, "VME Bus Exception Overflow Occurred\n"); - - if (err_chk) - vme_bus_error_handler(tsi148_bridge, error_addr, error_am); - else - dev_err(tsi148_bridge->parent, - "VME Bus Error at address: 0x%llx, attributes: %08x\n", - error_addr, error_attrib); - - /* Clear Status */ - iowrite32be(TSI148_LCSR_VEAT_VESCL, bridge->base + TSI148_LCSR_VEAT); - - return TSI148_LCSR_INTC_VERRC; -} - -/* - * Wake up IACK queue. - */ -static u32 tsi148_IACK_irqhandler(struct tsi148_driver *bridge) -{ - wake_up(&bridge->iack_queue); - - return TSI148_LCSR_INTC_IACKC; -} - -/* - * Calling VME bus interrupt callback if provided. - */ -static u32 tsi148_VIRQ_irqhandler(struct vme_bridge *tsi148_bridge, - u32 stat) -{ - int vec, i, serviced = 0; - struct tsi148_driver *bridge; - - bridge = tsi148_bridge->driver_priv; - - for (i = 7; i > 0; i--) { - if (stat & (1 << i)) { - /* - * Note: Even though the registers are defined as - * 32-bits in the spec, we only want to issue 8-bit - * IACK cycles on the bus, read from offset 3. - */ - vec = ioread8(bridge->base + TSI148_LCSR_VIACK[i] + 3); - - vme_irq_handler(tsi148_bridge, i, vec); - - serviced |= (1 << i); - } - } - - return serviced; -} - -/* - * Top level interrupt handler. Clears appropriate interrupt status bits and - * then calls appropriate sub handler(s). - */ -static irqreturn_t tsi148_irqhandler(int irq, void *ptr) -{ - u32 stat, enable, serviced = 0; - struct vme_bridge *tsi148_bridge; - struct tsi148_driver *bridge; - - tsi148_bridge = ptr; - - bridge = tsi148_bridge->driver_priv; - - /* Determine which interrupts are unmasked and set */ - enable = ioread32be(bridge->base + TSI148_LCSR_INTEO); - stat = ioread32be(bridge->base + TSI148_LCSR_INTS); - - /* Only look at unmasked interrupts */ - stat &= enable; - - if (unlikely(!stat)) - return IRQ_NONE; - - /* Call subhandlers as appropriate */ - /* DMA irqs */ - if (stat & (TSI148_LCSR_INTS_DMA1S | TSI148_LCSR_INTS_DMA0S)) - serviced |= tsi148_DMA_irqhandler(bridge, stat); - - /* Location monitor irqs */ - if (stat & (TSI148_LCSR_INTS_LM3S | TSI148_LCSR_INTS_LM2S | - TSI148_LCSR_INTS_LM1S | TSI148_LCSR_INTS_LM0S)) - serviced |= tsi148_LM_irqhandler(bridge, stat); - - /* Mail box irqs */ - if (stat & (TSI148_LCSR_INTS_MB3S | TSI148_LCSR_INTS_MB2S | - TSI148_LCSR_INTS_MB1S | TSI148_LCSR_INTS_MB0S)) - serviced |= tsi148_MB_irqhandler(tsi148_bridge, stat); - - /* PCI bus error */ - if (stat & TSI148_LCSR_INTS_PERRS) - serviced |= tsi148_PERR_irqhandler(tsi148_bridge); - - /* VME bus error */ - if (stat & TSI148_LCSR_INTS_VERRS) - serviced |= tsi148_VERR_irqhandler(tsi148_bridge); - - /* IACK irq */ - if (stat & TSI148_LCSR_INTS_IACKS) - serviced |= tsi148_IACK_irqhandler(bridge); - - /* VME bus irqs */ - if (stat & (TSI148_LCSR_INTS_IRQ7S | TSI148_LCSR_INTS_IRQ6S | - TSI148_LCSR_INTS_IRQ5S | TSI148_LCSR_INTS_IRQ4S | - TSI148_LCSR_INTS_IRQ3S | TSI148_LCSR_INTS_IRQ2S | - TSI148_LCSR_INTS_IRQ1S)) - serviced |= tsi148_VIRQ_irqhandler(tsi148_bridge, stat); - - /* Clear serviced interrupts */ - iowrite32be(serviced, bridge->base + TSI148_LCSR_INTC); - - return IRQ_HANDLED; -} - -static int tsi148_irq_init(struct vme_bridge *tsi148_bridge) -{ - int result; - unsigned int tmp; - struct pci_dev *pdev; - struct tsi148_driver *bridge; - - pdev = to_pci_dev(tsi148_bridge->parent); - - bridge = tsi148_bridge->driver_priv; - - result = request_irq(pdev->irq, - tsi148_irqhandler, - IRQF_SHARED, - driver_name, tsi148_bridge); - if (result) { - dev_err(tsi148_bridge->parent, "Can't get assigned pci irq vector %02X\n", - pdev->irq); - return result; - } - - /* Enable and unmask interrupts */ - tmp = TSI148_LCSR_INTEO_DMA1EO | TSI148_LCSR_INTEO_DMA0EO | - TSI148_LCSR_INTEO_MB3EO | TSI148_LCSR_INTEO_MB2EO | - TSI148_LCSR_INTEO_MB1EO | TSI148_LCSR_INTEO_MB0EO | - TSI148_LCSR_INTEO_PERREO | TSI148_LCSR_INTEO_VERREO | - TSI148_LCSR_INTEO_IACKEO; - - /* This leaves the following interrupts masked. - * TSI148_LCSR_INTEO_VIEEO - * TSI148_LCSR_INTEO_SYSFLEO - * TSI148_LCSR_INTEO_ACFLEO - */ - - /* Don't enable Location Monitor interrupts here - they will be - * enabled when the location monitors are properly configured and - * a callback has been attached. - * TSI148_LCSR_INTEO_LM0EO - * TSI148_LCSR_INTEO_LM1EO - * TSI148_LCSR_INTEO_LM2EO - * TSI148_LCSR_INTEO_LM3EO - */ - - /* Don't enable VME interrupts until we add a handler, else the board - * will respond to it and we don't want that unless it knows how to - * properly deal with it. - * TSI148_LCSR_INTEO_IRQ7EO - * TSI148_LCSR_INTEO_IRQ6EO - * TSI148_LCSR_INTEO_IRQ5EO - * TSI148_LCSR_INTEO_IRQ4EO - * TSI148_LCSR_INTEO_IRQ3EO - * TSI148_LCSR_INTEO_IRQ2EO - * TSI148_LCSR_INTEO_IRQ1EO - */ - - iowrite32be(tmp, bridge->base + TSI148_LCSR_INTEO); - iowrite32be(tmp, bridge->base + TSI148_LCSR_INTEN); - - return 0; -} - -static void tsi148_irq_exit(struct vme_bridge *tsi148_bridge, - struct pci_dev *pdev) -{ - struct tsi148_driver *bridge = tsi148_bridge->driver_priv; - - /* Turn off interrupts */ - iowrite32be(0x0, bridge->base + TSI148_LCSR_INTEO); - iowrite32be(0x0, bridge->base + TSI148_LCSR_INTEN); - - /* Clear all interrupts */ - iowrite32be(0xFFFFFFFF, bridge->base + TSI148_LCSR_INTC); - - /* Detach interrupt handler */ - free_irq(pdev->irq, tsi148_bridge); -} - -/* - * Check to see if an IACk has been received, return true (1) or false (0). - */ -static int tsi148_iack_received(struct tsi148_driver *bridge) -{ - u32 tmp; - - tmp = ioread32be(bridge->base + TSI148_LCSR_VICR); - - if (tmp & TSI148_LCSR_VICR_IRQS) - return 0; - else - return 1; -} - -/* - * Configure VME interrupt - */ -static void tsi148_irq_set(struct vme_bridge *tsi148_bridge, int level, - int state, int sync) -{ - struct pci_dev *pdev; - u32 tmp; - struct tsi148_driver *bridge; - - bridge = tsi148_bridge->driver_priv; - - /* We need to do the ordering differently for enabling and disabling */ - if (state == 0) { - tmp = ioread32be(bridge->base + TSI148_LCSR_INTEN); - tmp &= ~TSI148_LCSR_INTEN_IRQEN[level - 1]; - iowrite32be(tmp, bridge->base + TSI148_LCSR_INTEN); - - tmp = ioread32be(bridge->base + TSI148_LCSR_INTEO); - tmp &= ~TSI148_LCSR_INTEO_IRQEO[level - 1]; - iowrite32be(tmp, bridge->base + TSI148_LCSR_INTEO); - - if (sync != 0) { - pdev = to_pci_dev(tsi148_bridge->parent); - synchronize_irq(pdev->irq); - } - } else { - tmp = ioread32be(bridge->base + TSI148_LCSR_INTEO); - tmp |= TSI148_LCSR_INTEO_IRQEO[level - 1]; - iowrite32be(tmp, bridge->base + TSI148_LCSR_INTEO); - - tmp = ioread32be(bridge->base + TSI148_LCSR_INTEN); - tmp |= TSI148_LCSR_INTEN_IRQEN[level - 1]; - iowrite32be(tmp, bridge->base + TSI148_LCSR_INTEN); - } -} - -/* - * Generate a VME bus interrupt at the requested level & vector. Wait for - * interrupt to be acked. - */ -static int tsi148_irq_generate(struct vme_bridge *tsi148_bridge, int level, - int statid) -{ - u32 tmp; - struct tsi148_driver *bridge; - - bridge = tsi148_bridge->driver_priv; - - mutex_lock(&bridge->vme_int); - - /* Read VICR register */ - tmp = ioread32be(bridge->base + TSI148_LCSR_VICR); - - /* Set Status/ID */ - tmp = (tmp & ~TSI148_LCSR_VICR_STID_M) | - (statid & TSI148_LCSR_VICR_STID_M); - iowrite32be(tmp, bridge->base + TSI148_LCSR_VICR); - - /* Assert VMEbus IRQ */ - tmp = tmp | TSI148_LCSR_VICR_IRQL[level]; - iowrite32be(tmp, bridge->base + TSI148_LCSR_VICR); - - /* XXX Consider implementing a timeout? */ - wait_event_interruptible(bridge->iack_queue, - tsi148_iack_received(bridge)); - - mutex_unlock(&bridge->vme_int); - - return 0; -} - -/* - * Initialize a slave window with the requested attributes. - */ -static int tsi148_slave_set(struct vme_slave_resource *image, int enabled, - unsigned long long vme_base, unsigned long long size, - dma_addr_t pci_base, u32 aspace, u32 cycle) -{ - unsigned int i, addr = 0, granularity = 0; - unsigned int temp_ctl = 0; - unsigned int vme_base_low, vme_base_high; - unsigned int vme_bound_low, vme_bound_high; - unsigned int pci_offset_low, pci_offset_high; - unsigned long long vme_bound, pci_offset; - struct vme_bridge *tsi148_bridge; - struct tsi148_driver *bridge; - - tsi148_bridge = image->parent; - bridge = tsi148_bridge->driver_priv; - - i = image->number; - - switch (aspace) { - case VME_A16: - granularity = 0x10; - addr |= TSI148_LCSR_ITAT_AS_A16; - break; - case VME_A24: - granularity = 0x1000; - addr |= TSI148_LCSR_ITAT_AS_A24; - break; - case VME_A32: - granularity = 0x10000; - addr |= TSI148_LCSR_ITAT_AS_A32; - break; - case VME_A64: - granularity = 0x10000; - addr |= TSI148_LCSR_ITAT_AS_A64; - break; - default: - dev_err(tsi148_bridge->parent, "Invalid address space\n"); - return -EINVAL; - } - - /* Convert 64-bit variables to 2x 32-bit variables */ - reg_split(vme_base, &vme_base_high, &vme_base_low); - - /* - * Bound address is a valid address for the window, adjust - * accordingly - */ - vme_bound = vme_base + size - granularity; - reg_split(vme_bound, &vme_bound_high, &vme_bound_low); - pci_offset = (unsigned long long)pci_base - vme_base; - reg_split(pci_offset, &pci_offset_high, &pci_offset_low); - - if (vme_base_low & (granularity - 1)) { - dev_err(tsi148_bridge->parent, "Invalid VME base alignment\n"); - return -EINVAL; - } - if (vme_bound_low & (granularity - 1)) { - dev_err(tsi148_bridge->parent, "Invalid VME bound alignment\n"); - return -EINVAL; - } - if (pci_offset_low & (granularity - 1)) { - dev_err(tsi148_bridge->parent, "Invalid PCI Offset alignment\n"); - return -EINVAL; - } - - /* Disable while we are mucking around */ - temp_ctl = ioread32be(bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITAT); - temp_ctl &= ~TSI148_LCSR_ITAT_EN; - iowrite32be(temp_ctl, bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITAT); - - /* Setup mapping */ - iowrite32be(vme_base_high, bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITSAU); - iowrite32be(vme_base_low, bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITSAL); - iowrite32be(vme_bound_high, bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITEAU); - iowrite32be(vme_bound_low, bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITEAL); - iowrite32be(pci_offset_high, bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITOFU); - iowrite32be(pci_offset_low, bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITOFL); - - /* Setup 2eSST speeds */ - temp_ctl &= ~TSI148_LCSR_ITAT_2eSSTM_M; - switch (cycle & (VME_2eSST160 | VME_2eSST267 | VME_2eSST320)) { - case VME_2eSST160: - temp_ctl |= TSI148_LCSR_ITAT_2eSSTM_160; - break; - case VME_2eSST267: - temp_ctl |= TSI148_LCSR_ITAT_2eSSTM_267; - break; - case VME_2eSST320: - temp_ctl |= TSI148_LCSR_ITAT_2eSSTM_320; - break; - } - - /* Setup cycle types */ - temp_ctl &= ~(0x1F << 7); - if (cycle & VME_BLT) - temp_ctl |= TSI148_LCSR_ITAT_BLT; - if (cycle & VME_MBLT) - temp_ctl |= TSI148_LCSR_ITAT_MBLT; - if (cycle & VME_2eVME) - temp_ctl |= TSI148_LCSR_ITAT_2eVME; - if (cycle & VME_2eSST) - temp_ctl |= TSI148_LCSR_ITAT_2eSST; - if (cycle & VME_2eSSTB) - temp_ctl |= TSI148_LCSR_ITAT_2eSSTB; - - /* Setup address space */ - temp_ctl &= ~TSI148_LCSR_ITAT_AS_M; - temp_ctl |= addr; - - temp_ctl &= ~0xF; - if (cycle & VME_SUPER) - temp_ctl |= TSI148_LCSR_ITAT_SUPR; - if (cycle & VME_USER) - temp_ctl |= TSI148_LCSR_ITAT_NPRIV; - if (cycle & VME_PROG) - temp_ctl |= TSI148_LCSR_ITAT_PGM; - if (cycle & VME_DATA) - temp_ctl |= TSI148_LCSR_ITAT_DATA; - - /* Write ctl reg without enable */ - iowrite32be(temp_ctl, bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITAT); - - if (enabled) - temp_ctl |= TSI148_LCSR_ITAT_EN; - - iowrite32be(temp_ctl, bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITAT); - - return 0; -} - -/* - * Get slave window configuration. - */ -static int tsi148_slave_get(struct vme_slave_resource *image, int *enabled, - unsigned long long *vme_base, unsigned long long *size, - dma_addr_t *pci_base, u32 *aspace, u32 *cycle) -{ - unsigned int i, granularity = 0, ctl = 0; - unsigned int vme_base_low, vme_base_high; - unsigned int vme_bound_low, vme_bound_high; - unsigned int pci_offset_low, pci_offset_high; - unsigned long long vme_bound, pci_offset; - struct tsi148_driver *bridge; - - bridge = image->parent->driver_priv; - - i = image->number; - - /* Read registers */ - ctl = ioread32be(bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITAT); - - vme_base_high = ioread32be(bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITSAU); - vme_base_low = ioread32be(bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITSAL); - vme_bound_high = ioread32be(bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITEAU); - vme_bound_low = ioread32be(bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITEAL); - pci_offset_high = ioread32be(bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITOFU); - pci_offset_low = ioread32be(bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITOFL); - - /* Convert 64-bit variables to 2x 32-bit variables */ - reg_join(vme_base_high, vme_base_low, vme_base); - reg_join(vme_bound_high, vme_bound_low, &vme_bound); - reg_join(pci_offset_high, pci_offset_low, &pci_offset); - - *pci_base = (dma_addr_t)(*vme_base + pci_offset); - - *enabled = 0; - *aspace = 0; - *cycle = 0; - - if (ctl & TSI148_LCSR_ITAT_EN) - *enabled = 1; - - if ((ctl & TSI148_LCSR_ITAT_AS_M) == TSI148_LCSR_ITAT_AS_A16) { - granularity = 0x10; - *aspace |= VME_A16; - } - if ((ctl & TSI148_LCSR_ITAT_AS_M) == TSI148_LCSR_ITAT_AS_A24) { - granularity = 0x1000; - *aspace |= VME_A24; - } - if ((ctl & TSI148_LCSR_ITAT_AS_M) == TSI148_LCSR_ITAT_AS_A32) { - granularity = 0x10000; - *aspace |= VME_A32; - } - if ((ctl & TSI148_LCSR_ITAT_AS_M) == TSI148_LCSR_ITAT_AS_A64) { - granularity = 0x10000; - *aspace |= VME_A64; - } - - /* Need granularity before we set the size */ - *size = (unsigned long long)((vme_bound - *vme_base) + granularity); - - if ((ctl & TSI148_LCSR_ITAT_2eSSTM_M) == TSI148_LCSR_ITAT_2eSSTM_160) - *cycle |= VME_2eSST160; - if ((ctl & TSI148_LCSR_ITAT_2eSSTM_M) == TSI148_LCSR_ITAT_2eSSTM_267) - *cycle |= VME_2eSST267; - if ((ctl & TSI148_LCSR_ITAT_2eSSTM_M) == TSI148_LCSR_ITAT_2eSSTM_320) - *cycle |= VME_2eSST320; - - if (ctl & TSI148_LCSR_ITAT_BLT) - *cycle |= VME_BLT; - if (ctl & TSI148_LCSR_ITAT_MBLT) - *cycle |= VME_MBLT; - if (ctl & TSI148_LCSR_ITAT_2eVME) - *cycle |= VME_2eVME; - if (ctl & TSI148_LCSR_ITAT_2eSST) - *cycle |= VME_2eSST; - if (ctl & TSI148_LCSR_ITAT_2eSSTB) - *cycle |= VME_2eSSTB; - - if (ctl & TSI148_LCSR_ITAT_SUPR) - *cycle |= VME_SUPER; - if (ctl & TSI148_LCSR_ITAT_NPRIV) - *cycle |= VME_USER; - if (ctl & TSI148_LCSR_ITAT_PGM) - *cycle |= VME_PROG; - if (ctl & TSI148_LCSR_ITAT_DATA) - *cycle |= VME_DATA; - - return 0; -} - -/* - * Allocate and map PCI Resource - */ -static int tsi148_alloc_resource(struct vme_master_resource *image, - unsigned long long size) -{ - unsigned long long existing_size; - int retval = 0; - struct pci_dev *pdev; - struct vme_bridge *tsi148_bridge; - - tsi148_bridge = image->parent; - - pdev = to_pci_dev(tsi148_bridge->parent); - - existing_size = (unsigned long long)(image->bus_resource.end - - image->bus_resource.start); - - /* If the existing size is OK, return */ - if ((size != 0) && (existing_size == (size - 1))) - return 0; - - if (existing_size != 0) { - iounmap(image->kern_base); - image->kern_base = NULL; - kfree(image->bus_resource.name); - release_resource(&image->bus_resource); - memset(&image->bus_resource, 0, sizeof(image->bus_resource)); - } - - /* Exit here if size is zero */ - if (size == 0) - return 0; - - if (!image->bus_resource.name) { - image->bus_resource.name = kmalloc(VMENAMSIZ + 3, GFP_ATOMIC); - if (!image->bus_resource.name) { - retval = -ENOMEM; - goto err_name; - } - } - - sprintf((char *)image->bus_resource.name, "%s.%d", tsi148_bridge->name, - image->number); - - image->bus_resource.start = 0; - image->bus_resource.end = (unsigned long)size; - image->bus_resource.flags = IORESOURCE_MEM; - - retval = pci_bus_alloc_resource(pdev->bus, &image->bus_resource, - size, 0x10000, PCIBIOS_MIN_MEM, - 0, NULL, NULL); - if (retval) { - dev_err(tsi148_bridge->parent, "Failed to allocate mem resource for window %d size 0x%lx start 0x%lx\n", - image->number, (unsigned long)size, - (unsigned long)image->bus_resource.start); - goto err_resource; - } - - image->kern_base = ioremap(image->bus_resource.start, size); - if (!image->kern_base) { - dev_err(tsi148_bridge->parent, "Failed to remap resource\n"); - retval = -ENOMEM; - goto err_remap; - } - - return 0; - -err_remap: - release_resource(&image->bus_resource); -err_resource: - kfree(image->bus_resource.name); - memset(&image->bus_resource, 0, sizeof(image->bus_resource)); -err_name: - return retval; -} - -/* - * Free and unmap PCI Resource - */ -static void tsi148_free_resource(struct vme_master_resource *image) -{ - iounmap(image->kern_base); - image->kern_base = NULL; - release_resource(&image->bus_resource); - kfree(image->bus_resource.name); - memset(&image->bus_resource, 0, sizeof(image->bus_resource)); -} - -/* - * Set the attributes of an outbound window. - */ -static int tsi148_master_set(struct vme_master_resource *image, int enabled, - unsigned long long vme_base, unsigned long long size, - u32 aspace, u32 cycle, u32 dwidth) -{ - int retval = 0; - unsigned int i; - unsigned int temp_ctl = 0; - unsigned int pci_base_low, pci_base_high; - unsigned int pci_bound_low, pci_bound_high; - unsigned int vme_offset_low, vme_offset_high; - unsigned long long pci_bound, vme_offset, pci_base; - struct vme_bridge *tsi148_bridge; - struct tsi148_driver *bridge; - struct pci_bus_region region; - struct pci_dev *pdev; - - tsi148_bridge = image->parent; - - bridge = tsi148_bridge->driver_priv; - - pdev = to_pci_dev(tsi148_bridge->parent); - - /* Verify input data */ - if (vme_base & 0xFFFF) { - dev_err(tsi148_bridge->parent, "Invalid VME Window alignment\n"); - retval = -EINVAL; - goto err_window; - } - - if ((size == 0) && (enabled != 0)) { - dev_err(tsi148_bridge->parent, "Size must be non-zero for enabled windows\n"); - retval = -EINVAL; - goto err_window; - } - - spin_lock(&image->lock); - - /* Let's allocate the resource here rather than further up the stack as - * it avoids pushing loads of bus dependent stuff up the stack. If size - * is zero, any existing resource will be freed. - */ - retval = tsi148_alloc_resource(image, size); - if (retval) { - spin_unlock(&image->lock); - dev_err(tsi148_bridge->parent, "Unable to allocate memory for resource\n"); - goto err_res; - } - - if (size == 0) { - pci_base = 0; - pci_bound = 0; - vme_offset = 0; - } else { - pcibios_resource_to_bus(pdev->bus, ®ion, - &image->bus_resource); - pci_base = region.start; - - /* - * Bound address is a valid address for the window, adjust - * according to window granularity. - */ - pci_bound = pci_base + (size - 0x10000); - vme_offset = vme_base - pci_base; - } - - /* Convert 64-bit variables to 2x 32-bit variables */ - reg_split(pci_base, &pci_base_high, &pci_base_low); - reg_split(pci_bound, &pci_bound_high, &pci_bound_low); - reg_split(vme_offset, &vme_offset_high, &vme_offset_low); - - if (pci_base_low & 0xFFFF) { - spin_unlock(&image->lock); - dev_err(tsi148_bridge->parent, "Invalid PCI base alignment\n"); - retval = -EINVAL; - goto err_gran; - } - if (pci_bound_low & 0xFFFF) { - spin_unlock(&image->lock); - dev_err(tsi148_bridge->parent, "Invalid PCI bound alignment\n"); - retval = -EINVAL; - goto err_gran; - } - if (vme_offset_low & 0xFFFF) { - spin_unlock(&image->lock); - dev_err(tsi148_bridge->parent, "Invalid VME Offset alignment\n"); - retval = -EINVAL; - goto err_gran; - } - - i = image->number; - - /* Disable while we are mucking around */ - temp_ctl = ioread32be(bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTAT); - temp_ctl &= ~TSI148_LCSR_OTAT_EN; - iowrite32be(temp_ctl, bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTAT); - - /* Setup 2eSST speeds */ - temp_ctl &= ~TSI148_LCSR_OTAT_2eSSTM_M; - switch (cycle & (VME_2eSST160 | VME_2eSST267 | VME_2eSST320)) { - case VME_2eSST160: - temp_ctl |= TSI148_LCSR_OTAT_2eSSTM_160; - break; - case VME_2eSST267: - temp_ctl |= TSI148_LCSR_OTAT_2eSSTM_267; - break; - case VME_2eSST320: - temp_ctl |= TSI148_LCSR_OTAT_2eSSTM_320; - break; - } - - /* Setup cycle types */ - if (cycle & VME_BLT) { - temp_ctl &= ~TSI148_LCSR_OTAT_TM_M; - temp_ctl |= TSI148_LCSR_OTAT_TM_BLT; - } - if (cycle & VME_MBLT) { - temp_ctl &= ~TSI148_LCSR_OTAT_TM_M; - temp_ctl |= TSI148_LCSR_OTAT_TM_MBLT; - } - if (cycle & VME_2eVME) { - temp_ctl &= ~TSI148_LCSR_OTAT_TM_M; - temp_ctl |= TSI148_LCSR_OTAT_TM_2eVME; - } - if (cycle & VME_2eSST) { - temp_ctl &= ~TSI148_LCSR_OTAT_TM_M; - temp_ctl |= TSI148_LCSR_OTAT_TM_2eSST; - } - if (cycle & VME_2eSSTB) { - dev_warn(tsi148_bridge->parent, "Currently not setting Broadcast Select Registers\n"); - temp_ctl &= ~TSI148_LCSR_OTAT_TM_M; - temp_ctl |= TSI148_LCSR_OTAT_TM_2eSSTB; - } - - /* Setup data width */ - temp_ctl &= ~TSI148_LCSR_OTAT_DBW_M; - switch (dwidth) { - case VME_D16: - temp_ctl |= TSI148_LCSR_OTAT_DBW_16; - break; - case VME_D32: - temp_ctl |= TSI148_LCSR_OTAT_DBW_32; - break; - default: - spin_unlock(&image->lock); - dev_err(tsi148_bridge->parent, "Invalid data width\n"); - retval = -EINVAL; - goto err_dwidth; - } - - /* Setup address space */ - temp_ctl &= ~TSI148_LCSR_OTAT_AMODE_M; - switch (aspace) { - case VME_A16: - temp_ctl |= TSI148_LCSR_OTAT_AMODE_A16; - break; - case VME_A24: - temp_ctl |= TSI148_LCSR_OTAT_AMODE_A24; - break; - case VME_A32: - temp_ctl |= TSI148_LCSR_OTAT_AMODE_A32; - break; - case VME_A64: - temp_ctl |= TSI148_LCSR_OTAT_AMODE_A64; - break; - case VME_CRCSR: - temp_ctl |= TSI148_LCSR_OTAT_AMODE_CRCSR; - break; - case VME_USER1: - temp_ctl |= TSI148_LCSR_OTAT_AMODE_USER1; - break; - case VME_USER2: - temp_ctl |= TSI148_LCSR_OTAT_AMODE_USER2; - break; - case VME_USER3: - temp_ctl |= TSI148_LCSR_OTAT_AMODE_USER3; - break; - case VME_USER4: - temp_ctl |= TSI148_LCSR_OTAT_AMODE_USER4; - break; - default: - spin_unlock(&image->lock); - dev_err(tsi148_bridge->parent, "Invalid address space\n"); - retval = -EINVAL; - goto err_aspace; - } - - temp_ctl &= ~(3 << 4); - if (cycle & VME_SUPER) - temp_ctl |= TSI148_LCSR_OTAT_SUP; - if (cycle & VME_PROG) - temp_ctl |= TSI148_LCSR_OTAT_PGM; - - /* Setup mapping */ - iowrite32be(pci_base_high, bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTSAU); - iowrite32be(pci_base_low, bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTSAL); - iowrite32be(pci_bound_high, bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTEAU); - iowrite32be(pci_bound_low, bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTEAL); - iowrite32be(vme_offset_high, bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTOFU); - iowrite32be(vme_offset_low, bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTOFL); - - /* Write ctl reg without enable */ - iowrite32be(temp_ctl, bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTAT); - - if (enabled) - temp_ctl |= TSI148_LCSR_OTAT_EN; - - iowrite32be(temp_ctl, bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTAT); - - spin_unlock(&image->lock); - return 0; - -err_aspace: -err_dwidth: -err_gran: - tsi148_free_resource(image); -err_res: -err_window: - return retval; -} - -/* - * Set the attributes of an outbound window. - * - * XXX Not parsing prefetch information. - */ -static int __tsi148_master_get(struct vme_master_resource *image, int *enabled, - unsigned long long *vme_base, unsigned long long *size, - u32 *aspace, u32 *cycle, u32 *dwidth) -{ - unsigned int i, ctl; - unsigned int pci_base_low, pci_base_high; - unsigned int pci_bound_low, pci_bound_high; - unsigned int vme_offset_low, vme_offset_high; - - unsigned long long pci_base, pci_bound, vme_offset; - struct tsi148_driver *bridge; - - bridge = image->parent->driver_priv; - - i = image->number; - - ctl = ioread32be(bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTAT); - - pci_base_high = ioread32be(bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTSAU); - pci_base_low = ioread32be(bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTSAL); - pci_bound_high = ioread32be(bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTEAU); - pci_bound_low = ioread32be(bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTEAL); - vme_offset_high = ioread32be(bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTOFU); - vme_offset_low = ioread32be(bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTOFL); - - /* Convert 64-bit variables to 2x 32-bit variables */ - reg_join(pci_base_high, pci_base_low, &pci_base); - reg_join(pci_bound_high, pci_bound_low, &pci_bound); - reg_join(vme_offset_high, vme_offset_low, &vme_offset); - - *vme_base = pci_base + vme_offset; - *size = (unsigned long long)(pci_bound - pci_base) + 0x10000; - - *enabled = 0; - *aspace = 0; - *cycle = 0; - *dwidth = 0; - - if (ctl & TSI148_LCSR_OTAT_EN) - *enabled = 1; - - /* Setup address space */ - if ((ctl & TSI148_LCSR_OTAT_AMODE_M) == TSI148_LCSR_OTAT_AMODE_A16) - *aspace |= VME_A16; - if ((ctl & TSI148_LCSR_OTAT_AMODE_M) == TSI148_LCSR_OTAT_AMODE_A24) - *aspace |= VME_A24; - if ((ctl & TSI148_LCSR_OTAT_AMODE_M) == TSI148_LCSR_OTAT_AMODE_A32) - *aspace |= VME_A32; - if ((ctl & TSI148_LCSR_OTAT_AMODE_M) == TSI148_LCSR_OTAT_AMODE_A64) - *aspace |= VME_A64; - if ((ctl & TSI148_LCSR_OTAT_AMODE_M) == TSI148_LCSR_OTAT_AMODE_CRCSR) - *aspace |= VME_CRCSR; - if ((ctl & TSI148_LCSR_OTAT_AMODE_M) == TSI148_LCSR_OTAT_AMODE_USER1) - *aspace |= VME_USER1; - if ((ctl & TSI148_LCSR_OTAT_AMODE_M) == TSI148_LCSR_OTAT_AMODE_USER2) - *aspace |= VME_USER2; - if ((ctl & TSI148_LCSR_OTAT_AMODE_M) == TSI148_LCSR_OTAT_AMODE_USER3) - *aspace |= VME_USER3; - if ((ctl & TSI148_LCSR_OTAT_AMODE_M) == TSI148_LCSR_OTAT_AMODE_USER4) - *aspace |= VME_USER4; - - /* Setup 2eSST speeds */ - if ((ctl & TSI148_LCSR_OTAT_2eSSTM_M) == TSI148_LCSR_OTAT_2eSSTM_160) - *cycle |= VME_2eSST160; - if ((ctl & TSI148_LCSR_OTAT_2eSSTM_M) == TSI148_LCSR_OTAT_2eSSTM_267) - *cycle |= VME_2eSST267; - if ((ctl & TSI148_LCSR_OTAT_2eSSTM_M) == TSI148_LCSR_OTAT_2eSSTM_320) - *cycle |= VME_2eSST320; - - /* Setup cycle types */ - if ((ctl & TSI148_LCSR_OTAT_TM_M) == TSI148_LCSR_OTAT_TM_SCT) - *cycle |= VME_SCT; - if ((ctl & TSI148_LCSR_OTAT_TM_M) == TSI148_LCSR_OTAT_TM_BLT) - *cycle |= VME_BLT; - if ((ctl & TSI148_LCSR_OTAT_TM_M) == TSI148_LCSR_OTAT_TM_MBLT) - *cycle |= VME_MBLT; - if ((ctl & TSI148_LCSR_OTAT_TM_M) == TSI148_LCSR_OTAT_TM_2eVME) - *cycle |= VME_2eVME; - if ((ctl & TSI148_LCSR_OTAT_TM_M) == TSI148_LCSR_OTAT_TM_2eSST) - *cycle |= VME_2eSST; - if ((ctl & TSI148_LCSR_OTAT_TM_M) == TSI148_LCSR_OTAT_TM_2eSSTB) - *cycle |= VME_2eSSTB; - - if (ctl & TSI148_LCSR_OTAT_SUP) - *cycle |= VME_SUPER; - else - *cycle |= VME_USER; - - if (ctl & TSI148_LCSR_OTAT_PGM) - *cycle |= VME_PROG; - else - *cycle |= VME_DATA; - - /* Setup data width */ - if ((ctl & TSI148_LCSR_OTAT_DBW_M) == TSI148_LCSR_OTAT_DBW_16) - *dwidth = VME_D16; - if ((ctl & TSI148_LCSR_OTAT_DBW_M) == TSI148_LCSR_OTAT_DBW_32) - *dwidth = VME_D32; - - return 0; -} - -static int tsi148_master_get(struct vme_master_resource *image, int *enabled, - unsigned long long *vme_base, unsigned long long *size, - u32 *aspace, u32 *cycle, u32 *dwidth) -{ - int retval; - - spin_lock(&image->lock); - - retval = __tsi148_master_get(image, enabled, vme_base, size, aspace, - cycle, dwidth); - - spin_unlock(&image->lock); - - return retval; -} - -static ssize_t tsi148_master_read(struct vme_master_resource *image, void *buf, - size_t count, loff_t offset) -{ - int retval, enabled; - unsigned long long vme_base, size; - u32 aspace, cycle, dwidth; - struct vme_error_handler *handler = NULL; - struct vme_bridge *tsi148_bridge; - void __iomem *addr = image->kern_base + offset; - unsigned int done = 0; - unsigned int count32; - - tsi148_bridge = image->parent; - - spin_lock(&image->lock); - - if (err_chk) { - __tsi148_master_get(image, &enabled, &vme_base, &size, &aspace, - &cycle, &dwidth); - handler = vme_register_error_handler(tsi148_bridge, aspace, - vme_base + offset, count); - if (!handler) { - spin_unlock(&image->lock); - return -ENOMEM; - } - } - - /* The following code handles VME address alignment. We cannot use - * memcpy_xxx here because it may cut data transfers in to 8-bit - * cycles when D16 or D32 cycles are required on the VME bus. - * On the other hand, the bridge itself assures that the maximum data - * cycle configured for the transfer is used and splits it - * automatically for non-aligned addresses, so we don't want the - * overhead of needlessly forcing small transfers for the entire cycle. - */ - if ((uintptr_t)addr & 0x1) { - *(u8 *)buf = ioread8(addr); - done += 1; - if (done == count) - goto out; - } - if ((uintptr_t)(addr + done) & 0x2) { - if ((count - done) < 2) { - *(u8 *)(buf + done) = ioread8(addr + done); - done += 1; - goto out; - } else { - *(u16 *)(buf + done) = ioread16(addr + done); - done += 2; - } - } - - count32 = (count - done) & ~0x3; - while (done < count32) { - *(u32 *)(buf + done) = ioread32(addr + done); - done += 4; - } - - if ((count - done) & 0x2) { - *(u16 *)(buf + done) = ioread16(addr + done); - done += 2; - } - if ((count - done) & 0x1) { - *(u8 *)(buf + done) = ioread8(addr + done); - done += 1; - } - -out: - retval = count; - - if (err_chk) { - if (handler->num_errors) { - dev_err(image->parent->parent, - "First VME read error detected an at address 0x%llx\n", - handler->first_error); - retval = handler->first_error - (vme_base + offset); - } - vme_unregister_error_handler(handler); - } - - spin_unlock(&image->lock); - - return retval; -} - -static ssize_t tsi148_master_write(struct vme_master_resource *image, void *buf, - size_t count, loff_t offset) -{ - int retval = 0, enabled; - unsigned long long vme_base, size; - u32 aspace, cycle, dwidth; - void __iomem *addr = image->kern_base + offset; - unsigned int done = 0; - unsigned int count32; - - struct vme_error_handler *handler = NULL; - struct vme_bridge *tsi148_bridge; - struct tsi148_driver *bridge; - - tsi148_bridge = image->parent; - - bridge = tsi148_bridge->driver_priv; - - spin_lock(&image->lock); - - if (err_chk) { - __tsi148_master_get(image, &enabled, &vme_base, &size, &aspace, - &cycle, &dwidth); - handler = vme_register_error_handler(tsi148_bridge, aspace, - vme_base + offset, count); - if (!handler) { - spin_unlock(&image->lock); - return -ENOMEM; - } - } - - /* Here we apply for the same strategy we do in master_read - * function in order to assure the correct cycles. - */ - if ((uintptr_t)addr & 0x1) { - iowrite8(*(u8 *)buf, addr); - done += 1; - if (done == count) - goto out; - } - if ((uintptr_t)(addr + done) & 0x2) { - if ((count - done) < 2) { - iowrite8(*(u8 *)(buf + done), addr + done); - done += 1; - goto out; - } else { - iowrite16(*(u16 *)(buf + done), addr + done); - done += 2; - } - } - - count32 = (count - done) & ~0x3; - while (done < count32) { - iowrite32(*(u32 *)(buf + done), addr + done); - done += 4; - } - - if ((count - done) & 0x2) { - iowrite16(*(u16 *)(buf + done), addr + done); - done += 2; - } - if ((count - done) & 0x1) { - iowrite8(*(u8 *)(buf + done), addr + done); - done += 1; - } - -out: - retval = count; - - /* - * Writes are posted. We need to do a read on the VME bus to flush out - * all of the writes before we check for errors. We can't guarantee - * that reading the data we have just written is safe. It is believed - * that there isn't any read, write re-ordering, so we can read any - * location in VME space, so lets read the Device ID from the tsi148's - * own registers as mapped into CR/CSR space. - * - * We check for saved errors in the written address range/space. - */ - - if (err_chk) { - ioread16(bridge->flush_image->kern_base + 0x7F000); - - if (handler->num_errors) { - dev_warn(tsi148_bridge->parent, - "First VME write error detected an at address 0x%llx\n", - handler->first_error); - retval = handler->first_error - (vme_base + offset); - } - vme_unregister_error_handler(handler); - } - - spin_unlock(&image->lock); - - return retval; -} - -/* - * Perform an RMW cycle on the VME bus. - * - * Requires a previously configured master window, returns final value. - */ -static unsigned int tsi148_master_rmw(struct vme_master_resource *image, unsigned int mask, - unsigned int compare, unsigned int swap, loff_t offset) -{ - unsigned long long pci_addr; - unsigned int pci_addr_high, pci_addr_low; - u32 tmp, result; - int i; - struct tsi148_driver *bridge; - - bridge = image->parent->driver_priv; - - /* Find the PCI address that maps to the desired VME address */ - i = image->number; - - /* Locking as we can only do one of these at a time */ - mutex_lock(&bridge->vme_rmw); - - /* Lock image */ - spin_lock(&image->lock); - - pci_addr_high = ioread32be(bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTSAU); - pci_addr_low = ioread32be(bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTSAL); - - reg_join(pci_addr_high, pci_addr_low, &pci_addr); - reg_split(pci_addr + offset, &pci_addr_high, &pci_addr_low); - - /* Configure registers */ - iowrite32be(mask, bridge->base + TSI148_LCSR_RMWEN); - iowrite32be(compare, bridge->base + TSI148_LCSR_RMWC); - iowrite32be(swap, bridge->base + TSI148_LCSR_RMWS); - iowrite32be(pci_addr_high, bridge->base + TSI148_LCSR_RMWAU); - iowrite32be(pci_addr_low, bridge->base + TSI148_LCSR_RMWAL); - - /* Enable RMW */ - tmp = ioread32be(bridge->base + TSI148_LCSR_VMCTRL); - tmp |= TSI148_LCSR_VMCTRL_RMWEN; - iowrite32be(tmp, bridge->base + TSI148_LCSR_VMCTRL); - - /* Kick process off with a read to the required address. */ - result = ioread32be(image->kern_base + offset); - - /* Disable RMW */ - tmp = ioread32be(bridge->base + TSI148_LCSR_VMCTRL); - tmp &= ~TSI148_LCSR_VMCTRL_RMWEN; - iowrite32be(tmp, bridge->base + TSI148_LCSR_VMCTRL); - - spin_unlock(&image->lock); - - mutex_unlock(&bridge->vme_rmw); - - return result; -} - -static int tsi148_dma_set_vme_src_attributes(struct device *dev, __be32 *attr, - u32 aspace, u32 cycle, u32 dwidth) -{ - u32 val; - - val = be32_to_cpu(*attr); - - /* Setup 2eSST speeds */ - switch (cycle & (VME_2eSST160 | VME_2eSST267 | VME_2eSST320)) { - case VME_2eSST160: - val |= TSI148_LCSR_DSAT_2eSSTM_160; - break; - case VME_2eSST267: - val |= TSI148_LCSR_DSAT_2eSSTM_267; - break; - case VME_2eSST320: - val |= TSI148_LCSR_DSAT_2eSSTM_320; - break; - } - - /* Setup cycle types */ - if (cycle & VME_SCT) - val |= TSI148_LCSR_DSAT_TM_SCT; - - if (cycle & VME_BLT) - val |= TSI148_LCSR_DSAT_TM_BLT; - - if (cycle & VME_MBLT) - val |= TSI148_LCSR_DSAT_TM_MBLT; - - if (cycle & VME_2eVME) - val |= TSI148_LCSR_DSAT_TM_2eVME; - - if (cycle & VME_2eSST) - val |= TSI148_LCSR_DSAT_TM_2eSST; - - if (cycle & VME_2eSSTB) { - dev_err(dev, "Currently not setting Broadcast Select Registers\n"); - val |= TSI148_LCSR_DSAT_TM_2eSSTB; - } - - /* Setup data width */ - switch (dwidth) { - case VME_D16: - val |= TSI148_LCSR_DSAT_DBW_16; - break; - case VME_D32: - val |= TSI148_LCSR_DSAT_DBW_32; - break; - default: - dev_err(dev, "Invalid data width\n"); - return -EINVAL; - } - - /* Setup address space */ - switch (aspace) { - case VME_A16: - val |= TSI148_LCSR_DSAT_AMODE_A16; - break; - case VME_A24: - val |= TSI148_LCSR_DSAT_AMODE_A24; - break; - case VME_A32: - val |= TSI148_LCSR_DSAT_AMODE_A32; - break; - case VME_A64: - val |= TSI148_LCSR_DSAT_AMODE_A64; - break; - case VME_CRCSR: - val |= TSI148_LCSR_DSAT_AMODE_CRCSR; - break; - case VME_USER1: - val |= TSI148_LCSR_DSAT_AMODE_USER1; - break; - case VME_USER2: - val |= TSI148_LCSR_DSAT_AMODE_USER2; - break; - case VME_USER3: - val |= TSI148_LCSR_DSAT_AMODE_USER3; - break; - case VME_USER4: - val |= TSI148_LCSR_DSAT_AMODE_USER4; - break; - default: - dev_err(dev, "Invalid address space\n"); - return -EINVAL; - } - - if (cycle & VME_SUPER) - val |= TSI148_LCSR_DSAT_SUP; - if (cycle & VME_PROG) - val |= TSI148_LCSR_DSAT_PGM; - - *attr = cpu_to_be32(val); - - return 0; -} - -static int tsi148_dma_set_vme_dest_attributes(struct device *dev, __be32 *attr, - u32 aspace, u32 cycle, u32 dwidth) -{ - u32 val; - - val = be32_to_cpu(*attr); - - /* Setup 2eSST speeds */ - switch (cycle & (VME_2eSST160 | VME_2eSST267 | VME_2eSST320)) { - case VME_2eSST160: - val |= TSI148_LCSR_DDAT_2eSSTM_160; - break; - case VME_2eSST267: - val |= TSI148_LCSR_DDAT_2eSSTM_267; - break; - case VME_2eSST320: - val |= TSI148_LCSR_DDAT_2eSSTM_320; - break; - } - - /* Setup cycle types */ - if (cycle & VME_SCT) - val |= TSI148_LCSR_DDAT_TM_SCT; - - if (cycle & VME_BLT) - val |= TSI148_LCSR_DDAT_TM_BLT; - - if (cycle & VME_MBLT) - val |= TSI148_LCSR_DDAT_TM_MBLT; - - if (cycle & VME_2eVME) - val |= TSI148_LCSR_DDAT_TM_2eVME; - - if (cycle & VME_2eSST) - val |= TSI148_LCSR_DDAT_TM_2eSST; - - if (cycle & VME_2eSSTB) { - dev_err(dev, "Currently not setting Broadcast Select Registers\n"); - val |= TSI148_LCSR_DDAT_TM_2eSSTB; - } - - /* Setup data width */ - switch (dwidth) { - case VME_D16: - val |= TSI148_LCSR_DDAT_DBW_16; - break; - case VME_D32: - val |= TSI148_LCSR_DDAT_DBW_32; - break; - default: - dev_err(dev, "Invalid data width\n"); - return -EINVAL; - } - - /* Setup address space */ - switch (aspace) { - case VME_A16: - val |= TSI148_LCSR_DDAT_AMODE_A16; - break; - case VME_A24: - val |= TSI148_LCSR_DDAT_AMODE_A24; - break; - case VME_A32: - val |= TSI148_LCSR_DDAT_AMODE_A32; - break; - case VME_A64: - val |= TSI148_LCSR_DDAT_AMODE_A64; - break; - case VME_CRCSR: - val |= TSI148_LCSR_DDAT_AMODE_CRCSR; - break; - case VME_USER1: - val |= TSI148_LCSR_DDAT_AMODE_USER1; - break; - case VME_USER2: - val |= TSI148_LCSR_DDAT_AMODE_USER2; - break; - case VME_USER3: - val |= TSI148_LCSR_DDAT_AMODE_USER3; - break; - case VME_USER4: - val |= TSI148_LCSR_DDAT_AMODE_USER4; - break; - default: - dev_err(dev, "Invalid address space\n"); - return -EINVAL; - } - - if (cycle & VME_SUPER) - val |= TSI148_LCSR_DDAT_SUP; - if (cycle & VME_PROG) - val |= TSI148_LCSR_DDAT_PGM; - - *attr = cpu_to_be32(val); - - return 0; -} - -/* - * Add a link list descriptor to the list - * - * Note: DMA engine expects the DMA descriptor to be big endian. - */ -static int tsi148_dma_list_add(struct vme_dma_list *list, struct vme_dma_attr *src, - struct vme_dma_attr *dest, size_t count) -{ - struct tsi148_dma_entry *entry, *prev; - u32 address_high, address_low, val; - struct vme_dma_pattern *pattern_attr; - struct vme_dma_pci *pci_attr; - struct vme_dma_vme *vme_attr; - int retval = 0; - struct vme_bridge *tsi148_bridge; - - tsi148_bridge = list->parent->parent; - - /* Descriptor must be aligned on 64-bit boundaries */ - entry = kmalloc_obj(*entry); - if (!entry) { - retval = -ENOMEM; - goto err_mem; - } - - /* Test descriptor alignment */ - if ((unsigned long)&entry->descriptor & 0x7) { - dev_err(tsi148_bridge->parent, "Descriptor not aligned to 8 byte boundary as required: %p\n", - &entry->descriptor); - retval = -EINVAL; - goto err_align; - } - - /* Given we are going to fill out the structure, we probably don't - * need to zero it, but better safe than sorry for now. - */ - memset(&entry->descriptor, 0, sizeof(entry->descriptor)); - - /* Fill out source part */ - switch (src->type) { - case VME_DMA_PATTERN: - pattern_attr = src->private; - - entry->descriptor.dsal = cpu_to_be32(pattern_attr->pattern); - - val = TSI148_LCSR_DSAT_TYP_PAT; - - /* Default behaviour is 32 bit pattern */ - if (pattern_attr->type & VME_DMA_PATTERN_BYTE) - val |= TSI148_LCSR_DSAT_PSZ; - - /* It seems that the default behaviour is to increment */ - if ((pattern_attr->type & VME_DMA_PATTERN_INCREMENT) == 0) - val |= TSI148_LCSR_DSAT_NIN; - entry->descriptor.dsat = cpu_to_be32(val); - break; - case VME_DMA_PCI: - pci_attr = src->private; - - reg_split((unsigned long long)pci_attr->address, &address_high, &address_low); - entry->descriptor.dsau = cpu_to_be32(address_high); - entry->descriptor.dsal = cpu_to_be32(address_low); - entry->descriptor.dsat = cpu_to_be32(TSI148_LCSR_DSAT_TYP_PCI); - break; - case VME_DMA_VME: - vme_attr = src->private; - - reg_split((unsigned long long)vme_attr->address, &address_high, &address_low); - entry->descriptor.dsau = cpu_to_be32(address_high); - entry->descriptor.dsal = cpu_to_be32(address_low); - entry->descriptor.dsat = cpu_to_be32(TSI148_LCSR_DSAT_TYP_VME); - - retval = tsi148_dma_set_vme_src_attributes(tsi148_bridge->parent, - &entry->descriptor.dsat, - vme_attr->aspace, - vme_attr->cycle, - vme_attr->dwidth); - if (retval < 0) - goto err_source; - break; - default: - dev_err(tsi148_bridge->parent, "Invalid source type\n"); - retval = -EINVAL; - goto err_source; - } - - /* Assume last link - this will be over-written by adding another */ - entry->descriptor.dnlau = cpu_to_be32(0); - entry->descriptor.dnlal = cpu_to_be32(TSI148_LCSR_DNLAL_LLA); - - /* Fill out destination part */ - switch (dest->type) { - case VME_DMA_PCI: - pci_attr = dest->private; - - reg_split((unsigned long long)pci_attr->address, &address_high, - &address_low); - entry->descriptor.ddau = cpu_to_be32(address_high); - entry->descriptor.ddal = cpu_to_be32(address_low); - entry->descriptor.ddat = cpu_to_be32(TSI148_LCSR_DDAT_TYP_PCI); - break; - case VME_DMA_VME: - vme_attr = dest->private; - - reg_split((unsigned long long)vme_attr->address, &address_high, - &address_low); - entry->descriptor.ddau = cpu_to_be32(address_high); - entry->descriptor.ddal = cpu_to_be32(address_low); - entry->descriptor.ddat = cpu_to_be32(TSI148_LCSR_DDAT_TYP_VME); - - retval = tsi148_dma_set_vme_dest_attributes(tsi148_bridge->parent, - &entry->descriptor.ddat, - vme_attr->aspace, - vme_attr->cycle, - vme_attr->dwidth); - if (retval < 0) - goto err_dest; - break; - default: - dev_err(tsi148_bridge->parent, "Invalid destination type\n"); - retval = -EINVAL; - goto err_dest; - } - - /* Fill out count */ - entry->descriptor.dcnt = cpu_to_be32((u32)count); - - /* Add to list */ - list_add_tail(&entry->list, &list->entries); - - entry->dma_handle = dma_map_single(tsi148_bridge->parent, - &entry->descriptor, - sizeof(entry->descriptor), - DMA_TO_DEVICE); - if (dma_mapping_error(tsi148_bridge->parent, entry->dma_handle)) { - dev_err(tsi148_bridge->parent, "DMA mapping error\n"); - retval = -EINVAL; - goto err_dma; - } - - /* Fill out previous descriptors "Next Address" */ - if (entry->list.prev != &list->entries) { - reg_split((unsigned long long)entry->dma_handle, &address_high, - &address_low); - prev = list_entry(entry->list.prev, struct tsi148_dma_entry, - list); - prev->descriptor.dnlau = cpu_to_be32(address_high); - prev->descriptor.dnlal = cpu_to_be32(address_low); - } - - return 0; - -err_dma: - list_del(&entry->list); -err_dest: -err_source: -err_align: - kfree(entry); -err_mem: - return retval; -} - -/* - * Check to see if the provided DMA channel is busy. - */ -static int tsi148_dma_busy(struct vme_bridge *tsi148_bridge, int channel) -{ - u32 tmp; - struct tsi148_driver *bridge; - - bridge = tsi148_bridge->driver_priv; - - tmp = ioread32be(bridge->base + TSI148_LCSR_DMA[channel] + - TSI148_LCSR_OFFSET_DSTA); - - if (tmp & TSI148_LCSR_DSTA_BSY) - return 0; - else - return 1; -} - -/* - * Execute a previously generated link list - * - * XXX Need to provide control register configuration. - */ -static int tsi148_dma_list_exec(struct vme_dma_list *list) -{ - struct vme_dma_resource *ctrlr; - int channel, retval; - struct tsi148_dma_entry *entry; - u32 bus_addr_high, bus_addr_low; - u32 val, dctlreg = 0; - struct vme_bridge *tsi148_bridge; - struct tsi148_driver *bridge; - - ctrlr = list->parent; - - tsi148_bridge = ctrlr->parent; - - bridge = tsi148_bridge->driver_priv; - - mutex_lock(&ctrlr->mtx); - - channel = ctrlr->number; - - if (!list_empty(&ctrlr->running)) { - /* - * XXX We have an active DMA transfer and currently haven't - * sorted out the mechanism for "pending" DMA transfers. - * Return busy. - */ - /* Need to add to pending here */ - mutex_unlock(&ctrlr->mtx); - return -EBUSY; - } - - list_add(&list->list, &ctrlr->running); - - /* Get first bus address and write into registers */ - entry = list_first_entry(&list->entries, struct tsi148_dma_entry, - list); - - mutex_unlock(&ctrlr->mtx); - - reg_split(entry->dma_handle, &bus_addr_high, &bus_addr_low); - - iowrite32be(bus_addr_high, bridge->base + - TSI148_LCSR_DMA[channel] + TSI148_LCSR_OFFSET_DNLAU); - iowrite32be(bus_addr_low, bridge->base + - TSI148_LCSR_DMA[channel] + TSI148_LCSR_OFFSET_DNLAL); - - dctlreg = ioread32be(bridge->base + TSI148_LCSR_DMA[channel] + - TSI148_LCSR_OFFSET_DCTL); - - /* Start the operation */ - iowrite32be(dctlreg | TSI148_LCSR_DCTL_DGO, bridge->base + - TSI148_LCSR_DMA[channel] + TSI148_LCSR_OFFSET_DCTL); - - retval = wait_event_interruptible(bridge->dma_queue[channel], - tsi148_dma_busy(ctrlr->parent, channel)); - - if (retval) { - iowrite32be(dctlreg | TSI148_LCSR_DCTL_ABT, bridge->base + - TSI148_LCSR_DMA[channel] + TSI148_LCSR_OFFSET_DCTL); - /* Wait for the operation to abort */ - wait_event(bridge->dma_queue[channel], - tsi148_dma_busy(ctrlr->parent, channel)); - retval = -EINTR; - goto exit; - } - - /* - * Read status register, this register is valid until we kick off a - * new transfer. - */ - val = ioread32be(bridge->base + TSI148_LCSR_DMA[channel] + - TSI148_LCSR_OFFSET_DSTA); - - if (val & TSI148_LCSR_DSTA_VBE) { - dev_err(tsi148_bridge->parent, "DMA Error. DSTA=%08X\n", val); - retval = -EIO; - } - -exit: - /* Remove list from running list */ - mutex_lock(&ctrlr->mtx); - list_del(&list->list); - mutex_unlock(&ctrlr->mtx); - - return retval; -} - -/* - * Clean up a previously generated link list - * - * We have a separate function, don't assume that the chain can't be reused. - */ -static int tsi148_dma_list_empty(struct vme_dma_list *list) -{ - struct list_head *pos, *temp; - struct tsi148_dma_entry *entry; - - struct vme_bridge *tsi148_bridge = list->parent->parent; - - /* detach and free each entry */ - list_for_each_safe(pos, temp, &list->entries) { - list_del(pos); - entry = list_entry(pos, struct tsi148_dma_entry, list); - - dma_unmap_single(tsi148_bridge->parent, entry->dma_handle, - sizeof(struct tsi148_dma_descriptor), DMA_TO_DEVICE); - kfree(entry); - } - - return 0; -} - -/* - * All 4 location monitors reside at the same base - this is therefore a - * system wide configuration. - * - * This does not enable the LM monitor - that should be done when the first - * callback is attached and disabled when the last callback is removed. - */ -static int tsi148_lm_set(struct vme_lm_resource *lm, unsigned long long lm_base, - u32 aspace, u32 cycle) -{ - u32 lm_base_high, lm_base_low, lm_ctl = 0; - int i; - struct vme_bridge *tsi148_bridge; - struct tsi148_driver *bridge; - - tsi148_bridge = lm->parent; - - bridge = tsi148_bridge->driver_priv; - - mutex_lock(&lm->mtx); - - /* If we already have a callback attached, we can't move it! */ - for (i = 0; i < lm->monitors; i++) { - if (bridge->lm_callback[i]) { - mutex_unlock(&lm->mtx); - dev_err(tsi148_bridge->parent, "Location monitor callback attached, can't reset\n"); - return -EBUSY; - } - } - - switch (aspace) { - case VME_A16: - lm_ctl |= TSI148_LCSR_LMAT_AS_A16; - break; - case VME_A24: - lm_ctl |= TSI148_LCSR_LMAT_AS_A24; - break; - case VME_A32: - lm_ctl |= TSI148_LCSR_LMAT_AS_A32; - break; - case VME_A64: - lm_ctl |= TSI148_LCSR_LMAT_AS_A64; - break; - default: - mutex_unlock(&lm->mtx); - dev_err(tsi148_bridge->parent, "Invalid address space\n"); - return -EINVAL; - } - - if (cycle & VME_SUPER) - lm_ctl |= TSI148_LCSR_LMAT_SUPR; - if (cycle & VME_USER) - lm_ctl |= TSI148_LCSR_LMAT_NPRIV; - if (cycle & VME_PROG) - lm_ctl |= TSI148_LCSR_LMAT_PGM; - if (cycle & VME_DATA) - lm_ctl |= TSI148_LCSR_LMAT_DATA; - - reg_split(lm_base, &lm_base_high, &lm_base_low); - - iowrite32be(lm_base_high, bridge->base + TSI148_LCSR_LMBAU); - iowrite32be(lm_base_low, bridge->base + TSI148_LCSR_LMBAL); - iowrite32be(lm_ctl, bridge->base + TSI148_LCSR_LMAT); - - mutex_unlock(&lm->mtx); - - return 0; -} - -/* Get configuration of the callback monitor and return whether it is enabled - * or disabled. - */ -static int tsi148_lm_get(struct vme_lm_resource *lm, - unsigned long long *lm_base, u32 *aspace, u32 *cycle) -{ - u32 lm_base_high, lm_base_low, lm_ctl, enabled = 0; - struct tsi148_driver *bridge; - - bridge = lm->parent->driver_priv; - - mutex_lock(&lm->mtx); - - lm_base_high = ioread32be(bridge->base + TSI148_LCSR_LMBAU); - lm_base_low = ioread32be(bridge->base + TSI148_LCSR_LMBAL); - lm_ctl = ioread32be(bridge->base + TSI148_LCSR_LMAT); - - reg_join(lm_base_high, lm_base_low, lm_base); - - if (lm_ctl & TSI148_LCSR_LMAT_EN) - enabled = 1; - - if ((lm_ctl & TSI148_LCSR_LMAT_AS_M) == TSI148_LCSR_LMAT_AS_A16) - *aspace |= VME_A16; - - if ((lm_ctl & TSI148_LCSR_LMAT_AS_M) == TSI148_LCSR_LMAT_AS_A24) - *aspace |= VME_A24; - - if ((lm_ctl & TSI148_LCSR_LMAT_AS_M) == TSI148_LCSR_LMAT_AS_A32) - *aspace |= VME_A32; - - if ((lm_ctl & TSI148_LCSR_LMAT_AS_M) == TSI148_LCSR_LMAT_AS_A64) - *aspace |= VME_A64; - - if (lm_ctl & TSI148_LCSR_LMAT_SUPR) - *cycle |= VME_SUPER; - if (lm_ctl & TSI148_LCSR_LMAT_NPRIV) - *cycle |= VME_USER; - if (lm_ctl & TSI148_LCSR_LMAT_PGM) - *cycle |= VME_PROG; - if (lm_ctl & TSI148_LCSR_LMAT_DATA) - *cycle |= VME_DATA; - - mutex_unlock(&lm->mtx); - - return enabled; -} - -/* - * Attach a callback to a specific location monitor. - * - * Callback will be passed the monitor triggered. - */ -static int tsi148_lm_attach(struct vme_lm_resource *lm, int monitor, - void (*callback)(void *), void *data) -{ - u32 lm_ctl, tmp; - struct vme_bridge *tsi148_bridge; - struct tsi148_driver *bridge; - - tsi148_bridge = lm->parent; - - bridge = tsi148_bridge->driver_priv; - - mutex_lock(&lm->mtx); - - /* Ensure that the location monitor is configured - need PGM or DATA */ - lm_ctl = ioread32be(bridge->base + TSI148_LCSR_LMAT); - if ((lm_ctl & (TSI148_LCSR_LMAT_PGM | TSI148_LCSR_LMAT_DATA)) == 0) { - mutex_unlock(&lm->mtx); - dev_err(tsi148_bridge->parent, "Location monitor not properly configured\n"); - return -EINVAL; - } - - /* Check that a callback isn't already attached */ - if (bridge->lm_callback[monitor]) { - mutex_unlock(&lm->mtx); - dev_err(tsi148_bridge->parent, "Existing callback attached\n"); - return -EBUSY; - } - - /* Attach callback */ - bridge->lm_callback[monitor] = callback; - bridge->lm_data[monitor] = data; - - /* Enable Location Monitor interrupt */ - tmp = ioread32be(bridge->base + TSI148_LCSR_INTEN); - tmp |= TSI148_LCSR_INTEN_LMEN[monitor]; - iowrite32be(tmp, bridge->base + TSI148_LCSR_INTEN); - - tmp = ioread32be(bridge->base + TSI148_LCSR_INTEO); - tmp |= TSI148_LCSR_INTEO_LMEO[monitor]; - iowrite32be(tmp, bridge->base + TSI148_LCSR_INTEO); - - /* Ensure that global Location Monitor Enable set */ - if ((lm_ctl & TSI148_LCSR_LMAT_EN) == 0) { - lm_ctl |= TSI148_LCSR_LMAT_EN; - iowrite32be(lm_ctl, bridge->base + TSI148_LCSR_LMAT); - } - - mutex_unlock(&lm->mtx); - - return 0; -} - -/* - * Detach a callback function forn a specific location monitor. - */ -static int tsi148_lm_detach(struct vme_lm_resource *lm, int monitor) -{ - u32 lm_en, tmp; - struct tsi148_driver *bridge; - - bridge = lm->parent->driver_priv; - - mutex_lock(&lm->mtx); - - /* Disable Location Monitor and ensure previous interrupts are clear */ - lm_en = ioread32be(bridge->base + TSI148_LCSR_INTEN); - lm_en &= ~TSI148_LCSR_INTEN_LMEN[monitor]; - iowrite32be(lm_en, bridge->base + TSI148_LCSR_INTEN); - - tmp = ioread32be(bridge->base + TSI148_LCSR_INTEO); - tmp &= ~TSI148_LCSR_INTEO_LMEO[monitor]; - iowrite32be(tmp, bridge->base + TSI148_LCSR_INTEO); - - iowrite32be(TSI148_LCSR_INTC_LMC[monitor], - bridge->base + TSI148_LCSR_INTC); - - /* Detach callback */ - bridge->lm_callback[monitor] = NULL; - bridge->lm_data[monitor] = NULL; - - /* If all location monitors disabled, disable global Location Monitor */ - if ((lm_en & (TSI148_LCSR_INTS_LM0S | TSI148_LCSR_INTS_LM1S | - TSI148_LCSR_INTS_LM2S | TSI148_LCSR_INTS_LM3S)) == 0) { - tmp = ioread32be(bridge->base + TSI148_LCSR_LMAT); - tmp &= ~TSI148_LCSR_LMAT_EN; - iowrite32be(tmp, bridge->base + TSI148_LCSR_LMAT); - } - - mutex_unlock(&lm->mtx); - - return 0; -} - -/* - * Determine Geographical Addressing - */ -static int tsi148_slot_get(struct vme_bridge *tsi148_bridge) -{ - u32 slot = 0; - struct tsi148_driver *bridge; - - bridge = tsi148_bridge->driver_priv; - - if (!geoid) { - slot = ioread32be(bridge->base + TSI148_LCSR_VSTAT); - slot = slot & TSI148_LCSR_VSTAT_GA_M; - } else { - slot = geoid; - } - - return (int)slot; -} - -static void *tsi148_alloc_consistent(struct device *parent, size_t size, - dma_addr_t *dma) -{ - struct pci_dev *pdev; - - /* Find pci_dev container of dev */ - pdev = to_pci_dev(parent); - - return dma_alloc_coherent(&pdev->dev, size, dma, GFP_KERNEL); -} - -static void tsi148_free_consistent(struct device *parent, size_t size, - void *vaddr, dma_addr_t dma) -{ - struct pci_dev *pdev; - - /* Find pci_dev container of dev */ - pdev = to_pci_dev(parent); - - dma_free_coherent(&pdev->dev, size, vaddr, dma); -} - -/* - * Configure CR/CSR space - * - * Access to the CR/CSR can be configured at power-up. The location of the - * CR/CSR registers in the CR/CSR address space is determined by the boards - * Auto-ID or Geographic address. This function ensures that the window is - * enabled at an offset consistent with the boards geopgraphic address. - * - * Each board has a 512kB window, with the highest 4kB being used for the - * boards registers, this means there is a fix length 508kB window which must - * be mapped onto PCI memory. - */ -static int tsi148_crcsr_init(struct vme_bridge *tsi148_bridge, - struct pci_dev *pdev) -{ - u32 cbar, crat, vstat; - u32 crcsr_bus_high, crcsr_bus_low; - int retval; - struct tsi148_driver *bridge; - - bridge = tsi148_bridge->driver_priv; - - /* Allocate mem for CR/CSR image */ - bridge->crcsr_kernel = dma_alloc_coherent(&pdev->dev, - VME_CRCSR_BUF_SIZE, - &bridge->crcsr_bus, GFP_KERNEL); - if (!bridge->crcsr_kernel) { - dev_err(tsi148_bridge->parent, "Failed to allocate memory for CR/CSR image\n"); - return -ENOMEM; - } - - reg_split(bridge->crcsr_bus, &crcsr_bus_high, &crcsr_bus_low); - - iowrite32be(crcsr_bus_high, bridge->base + TSI148_LCSR_CROU); - iowrite32be(crcsr_bus_low, bridge->base + TSI148_LCSR_CROL); - - /* Ensure that the CR/CSR is configured at the correct offset */ - cbar = ioread32be(bridge->base + TSI148_CBAR); - cbar = (cbar & TSI148_CRCSR_CBAR_M) >> 3; - - vstat = tsi148_slot_get(tsi148_bridge); - - if (cbar != vstat) { - cbar = vstat; - dev_info(tsi148_bridge->parent, "Setting CR/CSR offset\n"); - iowrite32be(cbar << 3, bridge->base + TSI148_CBAR); - } - dev_info(tsi148_bridge->parent, "CR/CSR Offset: %d\n", cbar); - - crat = ioread32be(bridge->base + TSI148_LCSR_CRAT); - if (crat & TSI148_LCSR_CRAT_EN) { - dev_info(tsi148_bridge->parent, "CR/CSR already enabled\n"); - } else { - dev_info(tsi148_bridge->parent, "Enabling CR/CSR space\n"); - iowrite32be(crat | TSI148_LCSR_CRAT_EN, bridge->base + TSI148_LCSR_CRAT); - } - - /* If we want flushed, error-checked writes, set up a window - * over the CR/CSR registers. We read from here to safely flush - * through VME writes. - */ - if (err_chk) { - retval = tsi148_master_set(bridge->flush_image, 1, (vstat * 0x80000), - 0x80000, VME_CRCSR, VME_SCT, VME_D16); - if (retval) - dev_err(tsi148_bridge->parent, "Configuring flush image failed\n"); - } - - return 0; -} - -static void tsi148_crcsr_exit(struct vme_bridge *tsi148_bridge, - struct pci_dev *pdev) -{ - u32 crat; - struct tsi148_driver *bridge; - - bridge = tsi148_bridge->driver_priv; - - /* Turn off CR/CSR space */ - crat = ioread32be(bridge->base + TSI148_LCSR_CRAT); - iowrite32be(crat & ~TSI148_LCSR_CRAT_EN, - bridge->base + TSI148_LCSR_CRAT); - - /* Free image */ - iowrite32be(0, bridge->base + TSI148_LCSR_CROU); - iowrite32be(0, bridge->base + TSI148_LCSR_CROL); - - dma_free_coherent(&pdev->dev, VME_CRCSR_BUF_SIZE, - bridge->crcsr_kernel, bridge->crcsr_bus); -} - -static int tsi148_probe(struct pci_dev *pdev, const struct pci_device_id *id) -{ - int retval, i, master_num; - u32 data; - struct list_head *pos = NULL, *n; - struct vme_bridge *tsi148_bridge; - struct tsi148_driver *tsi148_device; - struct vme_master_resource *master_image; - struct vme_slave_resource *slave_image; - struct vme_dma_resource *dma_ctrlr; - struct vme_lm_resource *lm; - - if (geoid >= VME_MAX_SLOTS) { - dev_err(&pdev->dev, "VME geographical address must be between 0 and %d (exclusive), but got %d\n", - VME_MAX_SLOTS, geoid); - return -EINVAL; - } - - /* If we want to support more than one of each bridge, we need to - * dynamically generate this so we get one per device - */ - tsi148_bridge = kzalloc_obj(*tsi148_bridge); - if (!tsi148_bridge) { - retval = -ENOMEM; - goto err_struct; - } - vme_init_bridge(tsi148_bridge); - - tsi148_device = kzalloc_obj(*tsi148_device); - if (!tsi148_device) { - retval = -ENOMEM; - goto err_driver; - } - - tsi148_bridge->driver_priv = tsi148_device; - - /* Enable the device */ - retval = pci_enable_device(pdev); - if (retval) { - dev_err(&pdev->dev, "Unable to enable device\n"); - goto err_enable; - } - - /* Map Registers */ - retval = pci_request_regions(pdev, driver_name); - if (retval) { - dev_err(&pdev->dev, "Unable to reserve resources\n"); - goto err_resource; - } - - /* map registers in BAR 0 */ - tsi148_device->base = ioremap(pci_resource_start(pdev, 0), - 4096); - if (!tsi148_device->base) { - dev_err(&pdev->dev, "Unable to remap CRG region\n"); - retval = -EIO; - goto err_remap; - } - - /* Check to see if the mapping worked out */ - data = ioread32(tsi148_device->base + TSI148_PCFS_ID) & 0x0000FFFF; - if (data != PCI_VENDOR_ID_TUNDRA) { - dev_err(&pdev->dev, "CRG region check failed\n"); - retval = -EIO; - goto err_test; - } - - /* Initialize wait queues & mutual exclusion flags */ - init_waitqueue_head(&tsi148_device->dma_queue[0]); - init_waitqueue_head(&tsi148_device->dma_queue[1]); - init_waitqueue_head(&tsi148_device->iack_queue); - mutex_init(&tsi148_device->vme_int); - mutex_init(&tsi148_device->vme_rmw); - - tsi148_bridge->parent = &pdev->dev; - strscpy(tsi148_bridge->name, driver_name, VMENAMSIZ); - - /* Setup IRQ */ - retval = tsi148_irq_init(tsi148_bridge); - if (retval != 0) { - dev_err(&pdev->dev, "Chip Initialization failed.\n"); - goto err_irq; - } - - /* If we are going to flush writes, we need to read from the VME bus. - * We need to do this safely, thus we read the devices own CR/CSR - * register. To do this we must set up a window in CR/CSR space and - * hence have one less master window resource available. - */ - master_num = TSI148_MAX_MASTER; - if (err_chk) { - master_num--; - - tsi148_device->flush_image = kmalloc_obj(*tsi148_device->flush_image); - if (!tsi148_device->flush_image) { - retval = -ENOMEM; - goto err_master; - } - tsi148_device->flush_image->parent = tsi148_bridge; - spin_lock_init(&tsi148_device->flush_image->lock); - tsi148_device->flush_image->locked = 1; - tsi148_device->flush_image->number = master_num; - memset(&tsi148_device->flush_image->bus_resource, 0, - sizeof(tsi148_device->flush_image->bus_resource)); - tsi148_device->flush_image->kern_base = NULL; - } - - /* Add master windows to list */ - for (i = 0; i < master_num; i++) { - master_image = kmalloc_obj(*master_image); - if (!master_image) { - retval = -ENOMEM; - goto err_master; - } - master_image->parent = tsi148_bridge; - spin_lock_init(&master_image->lock); - master_image->locked = 0; - master_image->number = i; - master_image->address_attr = VME_A16 | VME_A24 | VME_A32 | - VME_A64 | VME_CRCSR | VME_USER1 | VME_USER2 | - VME_USER3 | VME_USER4; - master_image->cycle_attr = VME_SCT | VME_BLT | VME_MBLT | - VME_2eVME | VME_2eSST | VME_2eSSTB | VME_2eSST160 | - VME_2eSST267 | VME_2eSST320 | VME_SUPER | VME_USER | - VME_PROG | VME_DATA; - master_image->width_attr = VME_D16 | VME_D32; - memset(&master_image->bus_resource, 0, - sizeof(master_image->bus_resource)); - master_image->kern_base = NULL; - list_add_tail(&master_image->list, - &tsi148_bridge->master_resources); - } - - /* Add slave windows to list */ - for (i = 0; i < TSI148_MAX_SLAVE; i++) { - slave_image = kmalloc_obj(*slave_image); - if (!slave_image) { - retval = -ENOMEM; - goto err_slave; - } - slave_image->parent = tsi148_bridge; - mutex_init(&slave_image->mtx); - slave_image->locked = 0; - slave_image->number = i; - slave_image->address_attr = VME_A16 | VME_A24 | VME_A32 | - VME_A64; - slave_image->cycle_attr = VME_SCT | VME_BLT | VME_MBLT | - VME_2eVME | VME_2eSST | VME_2eSSTB | VME_2eSST160 | - VME_2eSST267 | VME_2eSST320 | VME_SUPER | VME_USER | - VME_PROG | VME_DATA; - list_add_tail(&slave_image->list, - &tsi148_bridge->slave_resources); - } - - /* Add dma engines to list */ - for (i = 0; i < TSI148_MAX_DMA; i++) { - dma_ctrlr = kmalloc_obj(*dma_ctrlr); - if (!dma_ctrlr) { - retval = -ENOMEM; - goto err_dma; - } - dma_ctrlr->parent = tsi148_bridge; - mutex_init(&dma_ctrlr->mtx); - dma_ctrlr->locked = 0; - dma_ctrlr->number = i; - dma_ctrlr->route_attr = VME_DMA_VME_TO_MEM | - VME_DMA_MEM_TO_VME | VME_DMA_VME_TO_VME | - VME_DMA_MEM_TO_MEM | VME_DMA_PATTERN_TO_VME | - VME_DMA_PATTERN_TO_MEM; - INIT_LIST_HEAD(&dma_ctrlr->pending); - INIT_LIST_HEAD(&dma_ctrlr->running); - list_add_tail(&dma_ctrlr->list, - &tsi148_bridge->dma_resources); - } - - /* Add location monitor to list */ - lm = kmalloc_obj(*lm); - if (!lm) { - retval = -ENOMEM; - goto err_lm; - } - lm->parent = tsi148_bridge; - mutex_init(&lm->mtx); - lm->locked = 0; - lm->number = 1; - lm->monitors = 4; - list_add_tail(&lm->list, &tsi148_bridge->lm_resources); - - tsi148_bridge->slave_get = tsi148_slave_get; - tsi148_bridge->slave_set = tsi148_slave_set; - tsi148_bridge->master_get = tsi148_master_get; - tsi148_bridge->master_set = tsi148_master_set; - tsi148_bridge->master_read = tsi148_master_read; - tsi148_bridge->master_write = tsi148_master_write; - tsi148_bridge->master_rmw = tsi148_master_rmw; - tsi148_bridge->dma_list_add = tsi148_dma_list_add; - tsi148_bridge->dma_list_exec = tsi148_dma_list_exec; - tsi148_bridge->dma_list_empty = tsi148_dma_list_empty; - tsi148_bridge->irq_set = tsi148_irq_set; - tsi148_bridge->irq_generate = tsi148_irq_generate; - tsi148_bridge->lm_set = tsi148_lm_set; - tsi148_bridge->lm_get = tsi148_lm_get; - tsi148_bridge->lm_attach = tsi148_lm_attach; - tsi148_bridge->lm_detach = tsi148_lm_detach; - tsi148_bridge->slot_get = tsi148_slot_get; - tsi148_bridge->alloc_consistent = tsi148_alloc_consistent; - tsi148_bridge->free_consistent = tsi148_free_consistent; - - data = ioread32be(tsi148_device->base + TSI148_LCSR_VSTAT); - dev_info(&pdev->dev, "Board is%s the VME system controller\n", - (data & TSI148_LCSR_VSTAT_SCONS) ? "" : " not"); - if (!geoid) - dev_info(&pdev->dev, "VME geographical address is %d\n", - data & TSI148_LCSR_VSTAT_GA_M); - else - dev_info(&pdev->dev, "VME geographical address is set to %d\n", - geoid); - - dev_info(&pdev->dev, "VME Write and flush and error check is %s\n", - str_enabled_disabled(err_chk)); - - retval = tsi148_crcsr_init(tsi148_bridge, pdev); - if (retval) { - dev_err(&pdev->dev, "CR/CSR configuration failed.\n"); - goto err_crcsr; - } - - retval = vme_register_bridge(tsi148_bridge); - if (retval != 0) { - dev_err(&pdev->dev, "Chip Registration failed.\n"); - goto err_reg; - } - - pci_set_drvdata(pdev, tsi148_bridge); - - /* Clear VME bus "board fail", and "power-up reset" lines */ - data = ioread32be(tsi148_device->base + TSI148_LCSR_VSTAT); - data &= ~TSI148_LCSR_VSTAT_BRDFL; - data |= TSI148_LCSR_VSTAT_CPURST; - iowrite32be(data, tsi148_device->base + TSI148_LCSR_VSTAT); - - return 0; - -err_reg: - tsi148_crcsr_exit(tsi148_bridge, pdev); -err_crcsr: -err_lm: - /* resources are stored in link list */ - list_for_each_safe(pos, n, &tsi148_bridge->lm_resources) { - lm = list_entry(pos, struct vme_lm_resource, list); - list_del(pos); - kfree(lm); - } -err_dma: - /* resources are stored in link list */ - list_for_each_safe(pos, n, &tsi148_bridge->dma_resources) { - dma_ctrlr = list_entry(pos, struct vme_dma_resource, list); - list_del(pos); - kfree(dma_ctrlr); - } -err_slave: - /* resources are stored in link list */ - list_for_each_safe(pos, n, &tsi148_bridge->slave_resources) { - slave_image = list_entry(pos, struct vme_slave_resource, list); - list_del(pos); - kfree(slave_image); - } -err_master: - /* resources are stored in link list */ - list_for_each_safe(pos, n, &tsi148_bridge->master_resources) { - master_image = list_entry(pos, struct vme_master_resource, list); - list_del(pos); - kfree(master_image); - } - - tsi148_irq_exit(tsi148_bridge, pdev); -err_irq: -err_test: - iounmap(tsi148_device->base); -err_remap: - pci_release_regions(pdev); -err_resource: - pci_disable_device(pdev); -err_enable: - kfree(tsi148_device); -err_driver: - kfree(tsi148_bridge); -err_struct: - return retval; -} - -static void tsi148_remove(struct pci_dev *pdev) -{ - struct list_head *pos = NULL; - struct list_head *tmplist; - struct vme_lm_resource *lm; - struct vme_master_resource *master_image; - struct vme_slave_resource *slave_image; - struct vme_dma_resource *dma_ctrlr; - int i; - struct tsi148_driver *bridge; - struct vme_bridge *tsi148_bridge = pci_get_drvdata(pdev); - - bridge = tsi148_bridge->driver_priv; - - dev_dbg(&pdev->dev, "Driver is being unloaded.\n"); - - /* - * Shutdown all inbound and outbound windows. - */ - for (i = 0; i < 8; i++) { - iowrite32be(0, bridge->base + TSI148_LCSR_IT[i] + - TSI148_LCSR_OFFSET_ITAT); - iowrite32be(0, bridge->base + TSI148_LCSR_OT[i] + - TSI148_LCSR_OFFSET_OTAT); - } - - /* - * Shutdown Location monitor. - */ - iowrite32be(0, bridge->base + TSI148_LCSR_LMAT); - - /* - * Shutdown CRG map. - */ - iowrite32be(0, bridge->base + TSI148_LCSR_CSRAT); - - /* - * Clear error status. - */ - iowrite32be(0xFFFFFFFF, bridge->base + TSI148_LCSR_EDPAT); - iowrite32be(0xFFFFFFFF, bridge->base + TSI148_LCSR_VEAT); - iowrite32be(0x07000700, bridge->base + TSI148_LCSR_PSTAT); - - /* - * Remove VIRQ interrupt (if any) - */ - if (ioread32be(bridge->base + TSI148_LCSR_VICR) & 0x800) - iowrite32be(0x8000, bridge->base + TSI148_LCSR_VICR); - - /* - * Map all Interrupts to PCI INTA - */ - iowrite32be(0x0, bridge->base + TSI148_LCSR_INTM1); - iowrite32be(0x0, bridge->base + TSI148_LCSR_INTM2); - - tsi148_irq_exit(tsi148_bridge, pdev); - - vme_unregister_bridge(tsi148_bridge); - - tsi148_crcsr_exit(tsi148_bridge, pdev); - - /* resources are stored in link list */ - list_for_each_safe(pos, tmplist, &tsi148_bridge->lm_resources) { - lm = list_entry(pos, struct vme_lm_resource, list); - list_del(pos); - kfree(lm); - } - - /* resources are stored in link list */ - list_for_each_safe(pos, tmplist, &tsi148_bridge->dma_resources) { - dma_ctrlr = list_entry(pos, struct vme_dma_resource, list); - list_del(pos); - kfree(dma_ctrlr); - } - - /* resources are stored in link list */ - list_for_each_safe(pos, tmplist, &tsi148_bridge->slave_resources) { - slave_image = list_entry(pos, struct vme_slave_resource, list); - list_del(pos); - kfree(slave_image); - } - - /* resources are stored in link list */ - list_for_each_safe(pos, tmplist, &tsi148_bridge->master_resources) { - master_image = list_entry(pos, struct vme_master_resource, list); - list_del(pos); - kfree(master_image); - } - - iounmap(bridge->base); - - pci_release_regions(pdev); - - pci_disable_device(pdev); - - kfree(tsi148_bridge->driver_priv); - - kfree(tsi148_bridge); -} - -module_pci_driver(tsi148_driver); - -MODULE_PARM_DESC(err_chk, "Check for VME errors on reads and writes"); -module_param(err_chk, bool, 0); - -MODULE_PARM_DESC(geoid, "Override geographical addressing"); -module_param(geoid, uint, 0); - -MODULE_DESCRIPTION("VME driver for the Tundra Tempe VME bridge"); -MODULE_LICENSE("GPL"); diff --git a/drivers/staging/vme_user/vme_tsi148.h b/drivers/staging/vme_user/vme_tsi148.h deleted file mode 100644 index f73ac92320bbf2..00000000000000 --- a/drivers/staging/vme_user/vme_tsi148.h +++ /dev/null @@ -1,1392 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-or-later */ -/* - * tsi148.h - * - * Support for the Tundra TSI148 VME Bridge chip - * - * Author: Tom Armistead - * Updated and maintained by Ajit Prem - * Copyright 2004 Motorola Inc. - */ - -#ifndef TSI148_H -#define TSI148_H - -#ifndef PCI_VENDOR_ID_TUNDRA -#define PCI_VENDOR_ID_TUNDRA 0x10e3 -#endif - -#ifndef PCI_DEVICE_ID_TUNDRA_TSI148 -#define PCI_DEVICE_ID_TUNDRA_TSI148 0x148 -#endif - -/* - * Define the number of each that the Tsi148 supports. - */ -#define TSI148_MAX_MASTER 8 /* Max Master Windows */ -#define TSI148_MAX_SLAVE 8 /* Max Slave Windows */ -#define TSI148_MAX_DMA 2 /* Max DMA Controllers */ -#define TSI148_MAX_MAILBOX 4 /* Max Mail Box registers */ -#define TSI148_MAX_SEMAPHORE 8 /* Max Semaphores */ - -/* Structure used to hold driver specific information */ -struct tsi148_driver { - void __iomem *base; /* Base Address of device registers */ - wait_queue_head_t dma_queue[2]; - wait_queue_head_t iack_queue; - void (*lm_callback[4])(void *); /* Called in interrupt handler */ - void *lm_data[4]; - void *crcsr_kernel; - dma_addr_t crcsr_bus; - struct vme_master_resource *flush_image; - struct mutex vme_rmw; /* Only one RMW cycle at a time */ - struct mutex vme_int; /* - * Only one VME interrupt can be - * generated at a time, provide locking - */ -}; - -/* - * Layout of a DMAC Linked-List Descriptor - * - * Note: This structure is accessed via the chip and therefore must be - * correctly laid out - It must also be aligned on 64-bit boundaries. - */ -struct tsi148_dma_descriptor { - __be32 dsau; /* Source Address */ - __be32 dsal; - __be32 ddau; /* Destination Address */ - __be32 ddal; - __be32 dsat; /* Source attributes */ - __be32 ddat; /* Destination attributes */ - __be32 dnlau; /* Next link address */ - __be32 dnlal; - __be32 dcnt; /* Byte count */ - __be32 ddbs; /* 2eSST Broadcast select */ -}; - -struct tsi148_dma_entry { - /* - * The descriptor needs to be aligned on a 64-bit boundary, we increase - * the chance of this by putting it first in the structure. - */ - struct tsi148_dma_descriptor descriptor; - struct list_head list; - dma_addr_t dma_handle; -}; - -/* - * TSI148 ASIC register structure overlays and bit field definitions. - * - * Note: Tsi148 Register Group (CRG) consists of the following - * combination of registers: - * PCFS - PCI Configuration Space Registers - * LCSR - Local Control and Status Registers - * GCSR - Global Control and Status Registers - * CR/CSR - Subset of Configuration ROM / - * Control and Status Registers - */ - -/* - * Command/Status Registers (CRG + $004) - */ -#define TSI148_PCFS_ID 0x0 -#define TSI148_PCFS_CSR 0x4 -#define TSI148_PCFS_CLASS 0x8 -#define TSI148_PCFS_MISC0 0xC -#define TSI148_PCFS_MBARL 0x10 -#define TSI148_PCFS_MBARU 0x14 -#define TSI148_PCFS_SUBID 0x28 -#define TSI148_PCFS_CAPP 0x34 -#define TSI148_PCFS_MISC1 0x3C -#define TSI148_PCFS_XCAPP 0x40 -#define TSI148_PCFS_XSTAT 0x44 - -/* - * LCSR definitions - */ - -/* - * Outbound Translations - */ -#define TSI148_LCSR_OT0_OTSAU 0x100 -#define TSI148_LCSR_OT0_OTSAL 0x104 -#define TSI148_LCSR_OT0_OTEAU 0x108 -#define TSI148_LCSR_OT0_OTEAL 0x10C -#define TSI148_LCSR_OT0_OTOFU 0x110 -#define TSI148_LCSR_OT0_OTOFL 0x114 -#define TSI148_LCSR_OT0_OTBS 0x118 -#define TSI148_LCSR_OT0_OTAT 0x11C - -#define TSI148_LCSR_OT1_OTSAU 0x120 -#define TSI148_LCSR_OT1_OTSAL 0x124 -#define TSI148_LCSR_OT1_OTEAU 0x128 -#define TSI148_LCSR_OT1_OTEAL 0x12C -#define TSI148_LCSR_OT1_OTOFU 0x130 -#define TSI148_LCSR_OT1_OTOFL 0x134 -#define TSI148_LCSR_OT1_OTBS 0x138 -#define TSI148_LCSR_OT1_OTAT 0x13C - -#define TSI148_LCSR_OT2_OTSAU 0x140 -#define TSI148_LCSR_OT2_OTSAL 0x144 -#define TSI148_LCSR_OT2_OTEAU 0x148 -#define TSI148_LCSR_OT2_OTEAL 0x14C -#define TSI148_LCSR_OT2_OTOFU 0x150 -#define TSI148_LCSR_OT2_OTOFL 0x154 -#define TSI148_LCSR_OT2_OTBS 0x158 -#define TSI148_LCSR_OT2_OTAT 0x15C - -#define TSI148_LCSR_OT3_OTSAU 0x160 -#define TSI148_LCSR_OT3_OTSAL 0x164 -#define TSI148_LCSR_OT3_OTEAU 0x168 -#define TSI148_LCSR_OT3_OTEAL 0x16C -#define TSI148_LCSR_OT3_OTOFU 0x170 -#define TSI148_LCSR_OT3_OTOFL 0x174 -#define TSI148_LCSR_OT3_OTBS 0x178 -#define TSI148_LCSR_OT3_OTAT 0x17C - -#define TSI148_LCSR_OT4_OTSAU 0x180 -#define TSI148_LCSR_OT4_OTSAL 0x184 -#define TSI148_LCSR_OT4_OTEAU 0x188 -#define TSI148_LCSR_OT4_OTEAL 0x18C -#define TSI148_LCSR_OT4_OTOFU 0x190 -#define TSI148_LCSR_OT4_OTOFL 0x194 -#define TSI148_LCSR_OT4_OTBS 0x198 -#define TSI148_LCSR_OT4_OTAT 0x19C - -#define TSI148_LCSR_OT5_OTSAU 0x1A0 -#define TSI148_LCSR_OT5_OTSAL 0x1A4 -#define TSI148_LCSR_OT5_OTEAU 0x1A8 -#define TSI148_LCSR_OT5_OTEAL 0x1AC -#define TSI148_LCSR_OT5_OTOFU 0x1B0 -#define TSI148_LCSR_OT5_OTOFL 0x1B4 -#define TSI148_LCSR_OT5_OTBS 0x1B8 -#define TSI148_LCSR_OT5_OTAT 0x1BC - -#define TSI148_LCSR_OT6_OTSAU 0x1C0 -#define TSI148_LCSR_OT6_OTSAL 0x1C4 -#define TSI148_LCSR_OT6_OTEAU 0x1C8 -#define TSI148_LCSR_OT6_OTEAL 0x1CC -#define TSI148_LCSR_OT6_OTOFU 0x1D0 -#define TSI148_LCSR_OT6_OTOFL 0x1D4 -#define TSI148_LCSR_OT6_OTBS 0x1D8 -#define TSI148_LCSR_OT6_OTAT 0x1DC - -#define TSI148_LCSR_OT7_OTSAU 0x1E0 -#define TSI148_LCSR_OT7_OTSAL 0x1E4 -#define TSI148_LCSR_OT7_OTEAU 0x1E8 -#define TSI148_LCSR_OT7_OTEAL 0x1EC -#define TSI148_LCSR_OT7_OTOFU 0x1F0 -#define TSI148_LCSR_OT7_OTOFL 0x1F4 -#define TSI148_LCSR_OT7_OTBS 0x1F8 -#define TSI148_LCSR_OT7_OTAT 0x1FC - -#define TSI148_LCSR_OT0 0x100 -#define TSI148_LCSR_OT1 0x120 -#define TSI148_LCSR_OT2 0x140 -#define TSI148_LCSR_OT3 0x160 -#define TSI148_LCSR_OT4 0x180 -#define TSI148_LCSR_OT5 0x1A0 -#define TSI148_LCSR_OT6 0x1C0 -#define TSI148_LCSR_OT7 0x1E0 - -static const int TSI148_LCSR_OT[8] = { TSI148_LCSR_OT0, TSI148_LCSR_OT1, - TSI148_LCSR_OT2, TSI148_LCSR_OT3, - TSI148_LCSR_OT4, TSI148_LCSR_OT5, - TSI148_LCSR_OT6, TSI148_LCSR_OT7 }; - -#define TSI148_LCSR_OFFSET_OTSAU 0x0 -#define TSI148_LCSR_OFFSET_OTSAL 0x4 -#define TSI148_LCSR_OFFSET_OTEAU 0x8 -#define TSI148_LCSR_OFFSET_OTEAL 0xC -#define TSI148_LCSR_OFFSET_OTOFU 0x10 -#define TSI148_LCSR_OFFSET_OTOFL 0x14 -#define TSI148_LCSR_OFFSET_OTBS 0x18 -#define TSI148_LCSR_OFFSET_OTAT 0x1C - -/* - * VMEbus interrupt ack - * offset 0x200 - */ -#define TSI148_LCSR_VIACK1 0x204 -#define TSI148_LCSR_VIACK2 0x208 -#define TSI148_LCSR_VIACK3 0x20C -#define TSI148_LCSR_VIACK4 0x210 -#define TSI148_LCSR_VIACK5 0x214 -#define TSI148_LCSR_VIACK6 0x218 -#define TSI148_LCSR_VIACK7 0x21C - -static const int TSI148_LCSR_VIACK[8] = { 0, TSI148_LCSR_VIACK1, - TSI148_LCSR_VIACK2, TSI148_LCSR_VIACK3, - TSI148_LCSR_VIACK4, TSI148_LCSR_VIACK5, - TSI148_LCSR_VIACK6, TSI148_LCSR_VIACK7 }; - -/* - * RMW - * offset 0x220 - */ -#define TSI148_LCSR_RMWAU 0x220 -#define TSI148_LCSR_RMWAL 0x224 -#define TSI148_LCSR_RMWEN 0x228 -#define TSI148_LCSR_RMWC 0x22C -#define TSI148_LCSR_RMWS 0x230 - -/* - * VMEbus control - * offset 0x234 - */ -#define TSI148_LCSR_VMCTRL 0x234 -#define TSI148_LCSR_VCTRL 0x238 -#define TSI148_LCSR_VSTAT 0x23C - -/* - * PCI status - * offset 0x240 - */ -#define TSI148_LCSR_PSTAT 0x240 - -/* - * VME filter. - * offset 0x250 - */ -#define TSI148_LCSR_VMEFL 0x250 - -/* - * VME exception. - * offset 0x260 - */ -#define TSI148_LCSR_VEAU 0x260 -#define TSI148_LCSR_VEAL 0x264 -#define TSI148_LCSR_VEAT 0x268 - -/* - * PCI error - * offset 0x270 - */ -#define TSI148_LCSR_EDPAU 0x270 -#define TSI148_LCSR_EDPAL 0x274 -#define TSI148_LCSR_EDPXA 0x278 -#define TSI148_LCSR_EDPXS 0x27C -#define TSI148_LCSR_EDPAT 0x280 - -/* - * Inbound Translations - * offset 0x300 - */ -#define TSI148_LCSR_IT0_ITSAU 0x300 -#define TSI148_LCSR_IT0_ITSAL 0x304 -#define TSI148_LCSR_IT0_ITEAU 0x308 -#define TSI148_LCSR_IT0_ITEAL 0x30C -#define TSI148_LCSR_IT0_ITOFU 0x310 -#define TSI148_LCSR_IT0_ITOFL 0x314 -#define TSI148_LCSR_IT0_ITAT 0x318 - -#define TSI148_LCSR_IT1_ITSAU 0x320 -#define TSI148_LCSR_IT1_ITSAL 0x324 -#define TSI148_LCSR_IT1_ITEAU 0x328 -#define TSI148_LCSR_IT1_ITEAL 0x32C -#define TSI148_LCSR_IT1_ITOFU 0x330 -#define TSI148_LCSR_IT1_ITOFL 0x334 -#define TSI148_LCSR_IT1_ITAT 0x338 - -#define TSI148_LCSR_IT2_ITSAU 0x340 -#define TSI148_LCSR_IT2_ITSAL 0x344 -#define TSI148_LCSR_IT2_ITEAU 0x348 -#define TSI148_LCSR_IT2_ITEAL 0x34C -#define TSI148_LCSR_IT2_ITOFU 0x350 -#define TSI148_LCSR_IT2_ITOFL 0x354 -#define TSI148_LCSR_IT2_ITAT 0x358 - -#define TSI148_LCSR_IT3_ITSAU 0x360 -#define TSI148_LCSR_IT3_ITSAL 0x364 -#define TSI148_LCSR_IT3_ITEAU 0x368 -#define TSI148_LCSR_IT3_ITEAL 0x36C -#define TSI148_LCSR_IT3_ITOFU 0x370 -#define TSI148_LCSR_IT3_ITOFL 0x374 -#define TSI148_LCSR_IT3_ITAT 0x378 - -#define TSI148_LCSR_IT4_ITSAU 0x380 -#define TSI148_LCSR_IT4_ITSAL 0x384 -#define TSI148_LCSR_IT4_ITEAU 0x388 -#define TSI148_LCSR_IT4_ITEAL 0x38C -#define TSI148_LCSR_IT4_ITOFU 0x390 -#define TSI148_LCSR_IT4_ITOFL 0x394 -#define TSI148_LCSR_IT4_ITAT 0x398 - -#define TSI148_LCSR_IT5_ITSAU 0x3A0 -#define TSI148_LCSR_IT5_ITSAL 0x3A4 -#define TSI148_LCSR_IT5_ITEAU 0x3A8 -#define TSI148_LCSR_IT5_ITEAL 0x3AC -#define TSI148_LCSR_IT5_ITOFU 0x3B0 -#define TSI148_LCSR_IT5_ITOFL 0x3B4 -#define TSI148_LCSR_IT5_ITAT 0x3B8 - -#define TSI148_LCSR_IT6_ITSAU 0x3C0 -#define TSI148_LCSR_IT6_ITSAL 0x3C4 -#define TSI148_LCSR_IT6_ITEAU 0x3C8 -#define TSI148_LCSR_IT6_ITEAL 0x3CC -#define TSI148_LCSR_IT6_ITOFU 0x3D0 -#define TSI148_LCSR_IT6_ITOFL 0x3D4 -#define TSI148_LCSR_IT6_ITAT 0x3D8 - -#define TSI148_LCSR_IT7_ITSAU 0x3E0 -#define TSI148_LCSR_IT7_ITSAL 0x3E4 -#define TSI148_LCSR_IT7_ITEAU 0x3E8 -#define TSI148_LCSR_IT7_ITEAL 0x3EC -#define TSI148_LCSR_IT7_ITOFU 0x3F0 -#define TSI148_LCSR_IT7_ITOFL 0x3F4 -#define TSI148_LCSR_IT7_ITAT 0x3F8 - -#define TSI148_LCSR_IT0 0x300 -#define TSI148_LCSR_IT1 0x320 -#define TSI148_LCSR_IT2 0x340 -#define TSI148_LCSR_IT3 0x360 -#define TSI148_LCSR_IT4 0x380 -#define TSI148_LCSR_IT5 0x3A0 -#define TSI148_LCSR_IT6 0x3C0 -#define TSI148_LCSR_IT7 0x3E0 - -static const int TSI148_LCSR_IT[8] = { TSI148_LCSR_IT0, TSI148_LCSR_IT1, - TSI148_LCSR_IT2, TSI148_LCSR_IT3, - TSI148_LCSR_IT4, TSI148_LCSR_IT5, - TSI148_LCSR_IT6, TSI148_LCSR_IT7 }; - -#define TSI148_LCSR_OFFSET_ITSAU 0x0 -#define TSI148_LCSR_OFFSET_ITSAL 0x4 -#define TSI148_LCSR_OFFSET_ITEAU 0x8 -#define TSI148_LCSR_OFFSET_ITEAL 0xC -#define TSI148_LCSR_OFFSET_ITOFU 0x10 -#define TSI148_LCSR_OFFSET_ITOFL 0x14 -#define TSI148_LCSR_OFFSET_ITAT 0x18 - -/* - * Inbound Translation GCSR - * offset 0x400 - */ -#define TSI148_LCSR_GBAU 0x400 -#define TSI148_LCSR_GBAL 0x404 -#define TSI148_LCSR_GCSRAT 0x408 - -/* - * Inbound Translation CRG - * offset 0x40C - */ -#define TSI148_LCSR_CBAU 0x40C -#define TSI148_LCSR_CBAL 0x410 -#define TSI148_LCSR_CSRAT 0x414 - -/* - * Inbound Translation CR/CSR - * CRG - * offset 0x418 - */ -#define TSI148_LCSR_CROU 0x418 -#define TSI148_LCSR_CROL 0x41C -#define TSI148_LCSR_CRAT 0x420 - -/* - * Inbound Translation Location Monitor - * offset 0x424 - */ -#define TSI148_LCSR_LMBAU 0x424 -#define TSI148_LCSR_LMBAL 0x428 -#define TSI148_LCSR_LMAT 0x42C - -/* - * VMEbus Interrupt Control. - * offset 0x430 - */ -#define TSI148_LCSR_BCU 0x430 -#define TSI148_LCSR_BCL 0x434 -#define TSI148_LCSR_BPGTR 0x438 -#define TSI148_LCSR_BPCTR 0x43C -#define TSI148_LCSR_VICR 0x440 - -/* - * Local Bus Interrupt Control. - * offset 0x448 - */ -#define TSI148_LCSR_INTEN 0x448 -#define TSI148_LCSR_INTEO 0x44C -#define TSI148_LCSR_INTS 0x450 -#define TSI148_LCSR_INTC 0x454 -#define TSI148_LCSR_INTM1 0x458 -#define TSI148_LCSR_INTM2 0x45C - -/* - * DMA Controllers - * offset 0x500 - */ -#define TSI148_LCSR_DCTL0 0x500 -#define TSI148_LCSR_DSTA0 0x504 -#define TSI148_LCSR_DCSAU0 0x508 -#define TSI148_LCSR_DCSAL0 0x50C -#define TSI148_LCSR_DCDAU0 0x510 -#define TSI148_LCSR_DCDAL0 0x514 -#define TSI148_LCSR_DCLAU0 0x518 -#define TSI148_LCSR_DCLAL0 0x51C -#define TSI148_LCSR_DSAU0 0x520 -#define TSI148_LCSR_DSAL0 0x524 -#define TSI148_LCSR_DDAU0 0x528 -#define TSI148_LCSR_DDAL0 0x52C -#define TSI148_LCSR_DSAT0 0x530 -#define TSI148_LCSR_DDAT0 0x534 -#define TSI148_LCSR_DNLAU0 0x538 -#define TSI148_LCSR_DNLAL0 0x53C -#define TSI148_LCSR_DCNT0 0x540 -#define TSI148_LCSR_DDBS0 0x544 - -#define TSI148_LCSR_DCTL1 0x580 -#define TSI148_LCSR_DSTA1 0x584 -#define TSI148_LCSR_DCSAU1 0x588 -#define TSI148_LCSR_DCSAL1 0x58C -#define TSI148_LCSR_DCDAU1 0x590 -#define TSI148_LCSR_DCDAL1 0x594 -#define TSI148_LCSR_DCLAU1 0x598 -#define TSI148_LCSR_DCLAL1 0x59C -#define TSI148_LCSR_DSAU1 0x5A0 -#define TSI148_LCSR_DSAL1 0x5A4 -#define TSI148_LCSR_DDAU1 0x5A8 -#define TSI148_LCSR_DDAL1 0x5AC -#define TSI148_LCSR_DSAT1 0x5B0 -#define TSI148_LCSR_DDAT1 0x5B4 -#define TSI148_LCSR_DNLAU1 0x5B8 -#define TSI148_LCSR_DNLAL1 0x5BC -#define TSI148_LCSR_DCNT1 0x5C0 -#define TSI148_LCSR_DDBS1 0x5C4 - -#define TSI148_LCSR_DMA0 0x500 -#define TSI148_LCSR_DMA1 0x580 - -static const int TSI148_LCSR_DMA[TSI148_MAX_DMA] = { TSI148_LCSR_DMA0, - TSI148_LCSR_DMA1 }; - -#define TSI148_LCSR_OFFSET_DCTL 0x0 -#define TSI148_LCSR_OFFSET_DSTA 0x4 -#define TSI148_LCSR_OFFSET_DCSAU 0x8 -#define TSI148_LCSR_OFFSET_DCSAL 0xC -#define TSI148_LCSR_OFFSET_DCDAU 0x10 -#define TSI148_LCSR_OFFSET_DCDAL 0x14 -#define TSI148_LCSR_OFFSET_DCLAU 0x18 -#define TSI148_LCSR_OFFSET_DCLAL 0x1C -#define TSI148_LCSR_OFFSET_DSAU 0x20 -#define TSI148_LCSR_OFFSET_DSAL 0x24 -#define TSI148_LCSR_OFFSET_DDAU 0x28 -#define TSI148_LCSR_OFFSET_DDAL 0x2C -#define TSI148_LCSR_OFFSET_DSAT 0x30 -#define TSI148_LCSR_OFFSET_DDAT 0x34 -#define TSI148_LCSR_OFFSET_DNLAU 0x38 -#define TSI148_LCSR_OFFSET_DNLAL 0x3C -#define TSI148_LCSR_OFFSET_DCNT 0x40 -#define TSI148_LCSR_OFFSET_DDBS 0x44 - -/* - * GCSR Register Group - */ - -/* - * GCSR CRG - * offset 0x00 0x600 - DEVI/VENI - * offset 0x04 0x604 - CTRL/GA/REVID - * offset 0x08 0x608 - Semaphore3/2/1/0 - * offset 0x0C 0x60C - Seamphore7/6/5/4 - */ -#define TSI148_GCSR_ID 0x600 -#define TSI148_GCSR_CSR 0x604 -#define TSI148_GCSR_SEMA0 0x608 -#define TSI148_GCSR_SEMA1 0x60C - -/* - * Mail Box - * GCSR CRG - * offset 0x10 0x610 - Mailbox0 - */ -#define TSI148_GCSR_MBOX0 0x610 -#define TSI148_GCSR_MBOX1 0x614 -#define TSI148_GCSR_MBOX2 0x618 -#define TSI148_GCSR_MBOX3 0x61C - -static const int TSI148_GCSR_MBOX[4] = { TSI148_GCSR_MBOX0, - TSI148_GCSR_MBOX1, - TSI148_GCSR_MBOX2, - TSI148_GCSR_MBOX3 }; - -/* - * CR/CSR - */ - -/* - * CR/CSR CRG - * offset 0x7FFF4 0xFF4 - CSRBCR - * offset 0x7FFF8 0xFF8 - CSRBSR - * offset 0x7FFFC 0xFFC - CBAR - */ -#define TSI148_CSRBCR 0xFF4 -#define TSI148_CSRBSR 0xFF8 -#define TSI148_CBAR 0xFFC - -/* - * TSI148 Register Bit Definitions - */ - -/* - * PFCS Register Set - */ -#define TSI148_PCFS_CMMD_SERR BIT(8) /* SERR_L out pin ssys err */ -#define TSI148_PCFS_CMMD_PERR BIT(6) /* PERR_L out pin parity */ -#define TSI148_PCFS_CMMD_MSTR BIT(2) /* PCI bus master */ -#define TSI148_PCFS_CMMD_MEMSP BIT(1) /* PCI mem space access */ -#define TSI148_PCFS_CMMD_IOSP BIT(0) /* PCI I/O space enable */ - -#define TSI148_PCFS_STAT_RCPVE BIT(15) /* Detected Parity Error */ -#define TSI148_PCFS_STAT_SIGSE BIT(14) /* Signalled System Error */ -#define TSI148_PCFS_STAT_RCVMA BIT(13) /* Received Master Abort */ -#define TSI148_PCFS_STAT_RCVTA BIT(12) /* Received Target Abort */ -#define TSI148_PCFS_STAT_SIGTA BIT(11) /* Signalled Target Abort */ -#define TSI148_PCFS_STAT_SELTIM (3 << 9) /* DELSEL Timing */ -#define TSI148_PCFS_STAT_DPAR BIT(8) /* Data Parity Err Reported */ -#define TSI148_PCFS_STAT_FAST BIT(7) /* Fast back-to-back Cap */ -#define TSI148_PCFS_STAT_P66M BIT(5) /* 66 MHz Capable */ -#define TSI148_PCFS_STAT_CAPL BIT(4) /* Capab List - address $34 */ - -/* - * Revision ID/Class Code Registers (CRG +$008) - */ -#define TSI148_PCFS_CLAS_M (0xFF << 24) /* Class ID */ -#define TSI148_PCFS_SUBCLAS_M (0xFF << 16) /* Sub-Class ID */ -#define TSI148_PCFS_PROGIF_M (0xFF << 8) /* Sub-Class ID */ -#define TSI148_PCFS_REVID_M (0xFF << 0) /* Rev ID */ - -/* - * Cache Line Size/ Master Latency Timer/ Header Type Registers (CRG + $00C) - */ -#define TSI148_PCFS_HEAD_M (0xFF << 16) /* Master Lat Timer */ -#define TSI148_PCFS_MLAT_M (0xFF << 8) /* Master Lat Timer */ -#define TSI148_PCFS_CLSZ_M (0xFF << 0) /* Cache Line Size */ - -/* - * Memory Base Address Lower Reg (CRG + $010) - */ -#define TSI148_PCFS_MBARL_BASEL_M (0xFFFFF << 12) /* Base Addr Lower Mask */ -#define TSI148_PCFS_MBARL_PRE BIT(3) /* Prefetch */ -#define TSI148_PCFS_MBARL_MTYPE_M (3 << 1) /* Memory Type Mask */ -#define TSI148_PCFS_MBARL_IOMEM BIT(0) /* I/O Space Indicator */ - -/* - * Message Signaled Interrupt Capabilities Register (CRG + $040) - */ -#define TSI148_PCFS_MSICAP_64BAC BIT(7) /* 64-bit Address Capable */ -#define TSI148_PCFS_MSICAP_MME_M (7 << 4) /* Multiple Msg Enable Mask */ -#define TSI148_PCFS_MSICAP_MMC_M (7 << 1) /* Multiple Msg Capable Mask */ -#define TSI148_PCFS_MSICAP_MSIEN BIT(0) /* Msg signaled INT Enable */ - -/* - * Message Address Lower Register (CRG +$044) - */ -#define TSI148_PCFS_MSIAL_M (0x3FFFFFFF << 2) /* Mask */ - -/* - * Message Data Register (CRG + 4C) - */ -#define TSI148_PCFS_MSIMD_M (0xFFFF << 0) /* Mask */ - -/* - * PCI-X Capabilities Register (CRG + $050) - */ -#define TSI148_PCFS_PCIXCAP_MOST_M (7 << 4) /* Max outstanding Split Tran */ -#define TSI148_PCFS_PCIXCAP_MMRBC_M (3 << 2) /* Max Mem Read byte cnt */ -#define TSI148_PCFS_PCIXCAP_ERO BIT(1) /* Enable Relaxed Ordering */ -#define TSI148_PCFS_PCIXCAP_DPERE BIT(0) /* Data Parity Recover Enable */ - -/* - * PCI-X Status Register (CRG +$054) - */ -#define TSI148_PCFS_PCIXSTAT_RSCEM BIT(29) /* Received Split Comp Error */ -#define TSI148_PCFS_PCIXSTAT_DMCRS_M (7 << 26) /* max Cumulative Read Size */ -#define TSI148_PCFS_PCIXSTAT_DMOST_M (7 << 23) /* max outstanding Split Trans */ -#define TSI148_PCFS_PCIXSTAT_DMMRC_M (3 << 21) /* max mem read byte count */ -#define TSI148_PCFS_PCIXSTAT_DC BIT(20) /* Device Complexity */ -#define TSI148_PCFS_PCIXSTAT_USC BIT(19) /* Unexpected Split comp */ -#define TSI148_PCFS_PCIXSTAT_SCD BIT(18) /* Split completion discard */ -#define TSI148_PCFS_PCIXSTAT_133C BIT(17) /* 133MHz capable */ -#define TSI148_PCFS_PCIXSTAT_64D BIT(16) /* 64 bit device */ -#define TSI148_PCFS_PCIXSTAT_BN_M (0xFF << 8) /* Bus number */ -#define TSI148_PCFS_PCIXSTAT_DN_M (0x1F << 3) /* Device number */ -#define TSI148_PCFS_PCIXSTAT_FN_M (7 << 0) /* Function Number */ - -/* - * LCSR Registers - */ - -/* - * Outbound Translation Starting Address Lower - */ -#define TSI148_LCSR_OTSAL_M (0xFFFF << 16) /* Mask */ - -/* - * Outbound Translation Ending Address Lower - */ -#define TSI148_LCSR_OTEAL_M (0xFFFF << 16) /* Mask */ - -/* - * Outbound Translation Offset Lower - */ -#define TSI148_LCSR_OTOFFL_M (0xFFFF << 16) /* Mask */ - -/* - * Outbound Translation 2eSST Broadcast Select - */ -#define TSI148_LCSR_OTBS_M (0xFFFFF << 0) /* Mask */ - -/* - * Outbound Translation Attribute - */ -#define TSI148_LCSR_OTAT_EN BIT(31) /* Window Enable */ -#define TSI148_LCSR_OTAT_MRPFD BIT(18) /* Prefetch Disable */ - -#define TSI148_LCSR_OTAT_PFS_M (3 << 16) /* Prefetch Size Mask */ -#define TSI148_LCSR_OTAT_PFS_2 (0 << 16) /* 2 Cache Lines P Size */ -#define TSI148_LCSR_OTAT_PFS_4 BIT(16) /* 4 Cache Lines P Size */ -#define TSI148_LCSR_OTAT_PFS_8 (2 << 16) /* 8 Cache Lines P Size */ -#define TSI148_LCSR_OTAT_PFS_16 (3 << 16) /* 16 Cache Lines P Size */ - -#define TSI148_LCSR_OTAT_2eSSTM_M (7 << 11) /* 2eSST Xfer Rate Mask */ -#define TSI148_LCSR_OTAT_2eSSTM_160 (0 << 11) /* 160MB/s 2eSST Xfer Rate */ -#define TSI148_LCSR_OTAT_2eSSTM_267 BIT(11) /* 267MB/s 2eSST Xfer Rate */ -#define TSI148_LCSR_OTAT_2eSSTM_320 (2 << 11) /* 320MB/s 2eSST Xfer Rate */ - -#define TSI148_LCSR_OTAT_TM_M (7 << 8) /* Xfer Protocol Mask */ -#define TSI148_LCSR_OTAT_TM_SCT (0 << 8) /* SCT Xfer Protocol */ -#define TSI148_LCSR_OTAT_TM_BLT BIT(8) /* BLT Xfer Protocol */ -#define TSI148_LCSR_OTAT_TM_MBLT (2 << 8) /* MBLT Xfer Protocol */ -#define TSI148_LCSR_OTAT_TM_2eVME (3 << 8) /* 2eVME Xfer Protocol */ -#define TSI148_LCSR_OTAT_TM_2eSST (4 << 8) /* 2eSST Xfer Protocol */ -#define TSI148_LCSR_OTAT_TM_2eSSTB (5 << 8) /* 2eSST Bcast Xfer Protocol */ - -#define TSI148_LCSR_OTAT_DBW_M (3 << 6) /* Max Data Width */ -#define TSI148_LCSR_OTAT_DBW_16 (0 << 6) /* 16-bit Data Width */ -#define TSI148_LCSR_OTAT_DBW_32 BIT(6) /* 32-bit Data Width */ - -#define TSI148_LCSR_OTAT_SUP BIT(5) /* Supervisory Access */ -#define TSI148_LCSR_OTAT_PGM BIT(4) /* Program Access */ - -#define TSI148_LCSR_OTAT_AMODE_M (0xf << 0) /* Address Mode Mask */ -#define TSI148_LCSR_OTAT_AMODE_A16 (0 << 0) /* A16 Address Space */ -#define TSI148_LCSR_OTAT_AMODE_A24 BIT(0) /* A24 Address Space */ -#define TSI148_LCSR_OTAT_AMODE_A32 (2 << 0) /* A32 Address Space */ -#define TSI148_LCSR_OTAT_AMODE_A64 (4 << 0) /* A32 Address Space */ -#define TSI148_LCSR_OTAT_AMODE_CRCSR (5 << 0) /* CR/CSR Address Space */ -#define TSI148_LCSR_OTAT_AMODE_USER1 (8 << 0) /* User1 Address Space */ -#define TSI148_LCSR_OTAT_AMODE_USER2 (9 << 0) /* User2 Address Space */ -#define TSI148_LCSR_OTAT_AMODE_USER3 (10 << 0) /* User3 Address Space */ -#define TSI148_LCSR_OTAT_AMODE_USER4 (11 << 0) /* User4 Address Space */ - -/* - * VME Master Control Register CRG+$234 - */ -#define TSI148_LCSR_VMCTRL_VSA BIT(27) /* VMEbus Stop Ack */ -#define TSI148_LCSR_VMCTRL_VS BIT(26) /* VMEbus Stop */ -#define TSI148_LCSR_VMCTRL_DHB BIT(25) /* Device Has Bus */ -#define TSI148_LCSR_VMCTRL_DWB BIT(24) /* Device Wants Bus */ - -#define TSI148_LCSR_VMCTRL_RMWEN BIT(20) /* RMW Enable */ - -#define TSI148_LCSR_VMCTRL_ATO_M (7 << 16) /* Master Access Time-out Mask */ -#define TSI148_LCSR_VMCTRL_ATO_32 (0 << 16) /* 32 us */ -#define TSI148_LCSR_VMCTRL_ATO_128 BIT(16) /* 128 us */ -#define TSI148_LCSR_VMCTRL_ATO_512 (2 << 16) /* 512 us */ -#define TSI148_LCSR_VMCTRL_ATO_2M (3 << 16) /* 2 ms */ -#define TSI148_LCSR_VMCTRL_ATO_8M (4 << 16) /* 8 ms */ -#define TSI148_LCSR_VMCTRL_ATO_32M (5 << 16) /* 32 ms */ -#define TSI148_LCSR_VMCTRL_ATO_128M (6 << 16) /* 128 ms */ -#define TSI148_LCSR_VMCTRL_ATO_DIS (7 << 16) /* Disabled */ - -#define TSI148_LCSR_VMCTRL_VTOFF_M (7 << 12) /* VMEbus Master Time off */ -#define TSI148_LCSR_VMCTRL_VTOFF_0 (0 << 12) /* 0us */ -#define TSI148_LCSR_VMCTRL_VTOFF_1 BIT(12) /* 1us */ -#define TSI148_LCSR_VMCTRL_VTOFF_2 (2 << 12) /* 2us */ -#define TSI148_LCSR_VMCTRL_VTOFF_4 (3 << 12) /* 4us */ -#define TSI148_LCSR_VMCTRL_VTOFF_8 (4 << 12) /* 8us */ -#define TSI148_LCSR_VMCTRL_VTOFF_16 (5 << 12) /* 16us */ -#define TSI148_LCSR_VMCTRL_VTOFF_32 (6 << 12) /* 32us */ -#define TSI148_LCSR_VMCTRL_VTOFF_64 (7 << 12) /* 64us */ - -#define TSI148_LCSR_VMCTRL_VTON_M (7 << 8) /* VMEbus Master Time On */ -#define TSI148_LCSR_VMCTRL_VTON_4 (0 << 8) /* 8us */ -#define TSI148_LCSR_VMCTRL_VTON_8 BIT(8) /* 8us */ -#define TSI148_LCSR_VMCTRL_VTON_16 (2 << 8) /* 16us */ -#define TSI148_LCSR_VMCTRL_VTON_32 (3 << 8) /* 32us */ -#define TSI148_LCSR_VMCTRL_VTON_64 (4 << 8) /* 64us */ -#define TSI148_LCSR_VMCTRL_VTON_128 (5 << 8) /* 128us */ -#define TSI148_LCSR_VMCTRL_VTON_256 (6 << 8) /* 256us */ -#define TSI148_LCSR_VMCTRL_VTON_512 (7 << 8) /* 512us */ - -#define TSI148_LCSR_VMCTRL_VREL_M (3 << 3) /* VMEbus Master Rel Mode Mask - */ -#define TSI148_LCSR_VMCTRL_VREL_T_D (0 << 3) /* Time on or Done */ -#define TSI148_LCSR_VMCTRL_VREL_T_R_D BIT(3) /* Time on and REQ or Done */ -#define TSI148_LCSR_VMCTRL_VREL_T_B_D (2 << 3) /* Time on and BCLR or Done */ -#define TSI148_LCSR_VMCTRL_VREL_T_D_R (3 << 3) /* Time on or Done and REQ */ - -#define TSI148_LCSR_VMCTRL_VFAIR BIT(2) /* VMEbus Master Fair Mode */ -#define TSI148_LCSR_VMCTRL_VREQL_M (3 << 0) /* VMEbus Master Req Level Mask - */ - -/* - * VMEbus Control Register CRG+$238 - */ -#define TSI148_LCSR_VCTRL_LRE BIT(31) /* Late Retry Enable */ - -#define TSI148_LCSR_VCTRL_DLT_M (0xF << 24) /* Deadlock Timer */ -#define TSI148_LCSR_VCTRL_DLT_OFF (0 << 24) /* Deadlock Timer Off */ -#define TSI148_LCSR_VCTRL_DLT_16 BIT(24) /* 16 VCLKS */ -#define TSI148_LCSR_VCTRL_DLT_32 (2 << 24) /* 32 VCLKS */ -#define TSI148_LCSR_VCTRL_DLT_64 (3 << 24) /* 64 VCLKS */ -#define TSI148_LCSR_VCTRL_DLT_128 (4 << 24) /* 128 VCLKS */ -#define TSI148_LCSR_VCTRL_DLT_256 (5 << 24) /* 256 VCLKS */ -#define TSI148_LCSR_VCTRL_DLT_512 (6 << 24) /* 512 VCLKS */ -#define TSI148_LCSR_VCTRL_DLT_1024 (7 << 24) /* 1024 VCLKS */ -#define TSI148_LCSR_VCTRL_DLT_2048 (8 << 24) /* 2048 VCLKS */ -#define TSI148_LCSR_VCTRL_DLT_4096 (9 << 24) /* 4096 VCLKS */ -#define TSI148_LCSR_VCTRL_DLT_8192 (0xA << 24) /* 8192 VCLKS */ -#define TSI148_LCSR_VCTRL_DLT_16384 (0xB << 24) /* 16384 VCLKS */ -#define TSI148_LCSR_VCTRL_DLT_32768 (0xC << 24) /* 32768 VCLKS */ - -#define TSI148_LCSR_VCTRL_NERBB BIT(20) /* No Early Release of Bus Busy */ - -#define TSI148_LCSR_VCTRL_SRESET BIT(17) /* System Reset */ -#define TSI148_LCSR_VCTRL_LRESET BIT(16) /* Local Reset */ - -#define TSI148_LCSR_VCTRL_SFAILAI BIT(15) /* SYSFAIL Auto Slot ID */ -#define TSI148_LCSR_VCTRL_BID_M (0x1F << 8) /* Broadcast ID Mask */ - -#define TSI148_LCSR_VCTRL_ATOEN BIT(7) /* Arbiter Time-out Enable */ -#define TSI148_LCSR_VCTRL_ROBIN BIT(6) /* VMEbus Round Robin */ - -#define TSI148_LCSR_VCTRL_GTO_M (7 << 0) /* VMEbus Global Time-out Mask*/ -#define TSI148_LCSR_VCTRL_GTO_8 (0 << 0) /* 8 us */ -#define TSI148_LCSR_VCTRL_GTO_16 BIT(0) /* 16 us */ -#define TSI148_LCSR_VCTRL_GTO_32 (2 << 0) /* 32 us */ -#define TSI148_LCSR_VCTRL_GTO_64 (3 << 0) /* 64 us */ -#define TSI148_LCSR_VCTRL_GTO_128 (4 << 0) /* 128 us */ -#define TSI148_LCSR_VCTRL_GTO_256 (5 << 0) /* 256 us */ -#define TSI148_LCSR_VCTRL_GTO_512 (6 << 0) /* 512 us */ -#define TSI148_LCSR_VCTRL_GTO_DIS (7 << 0) /* Disabled */ - -/* - * VMEbus Status Register CRG + $23C - */ -#define TSI148_LCSR_VSTAT_CPURST BIT(15) /* Clear power up reset */ -#define TSI148_LCSR_VSTAT_BRDFL BIT(14) /* Board fail */ -#define TSI148_LCSR_VSTAT_PURSTS BIT(12) /* Power up reset status */ -#define TSI148_LCSR_VSTAT_BDFAILS BIT(11) /* Board Fail Status */ -#define TSI148_LCSR_VSTAT_SYSFAILS BIT(10) /* System Fail Status */ -#define TSI148_LCSR_VSTAT_ACFAILS BIT(9) /* AC fail status */ -#define TSI148_LCSR_VSTAT_SCONS BIT(8) /* System Cont Status */ -#define TSI148_LCSR_VSTAT_GAP BIT(5) /* Geographic Addr Parity */ -#define TSI148_LCSR_VSTAT_GA_M (0x1F << 0) /* Geographic Addr Mask */ - -/* - * PCI Configuration Status Register CRG+$240 - */ -#define TSI148_LCSR_PSTAT_REQ64S BIT(6) /* Request 64 status set */ -#define TSI148_LCSR_PSTAT_M66ENS BIT(5) /* M66ENS 66Mhz enable */ -#define TSI148_LCSR_PSTAT_FRAMES BIT(4) /* Frame Status */ -#define TSI148_LCSR_PSTAT_IRDYS BIT(3) /* IRDY status */ -#define TSI148_LCSR_PSTAT_DEVSELS BIT(2) /* DEVL status */ -#define TSI148_LCSR_PSTAT_STOPS BIT(1) /* STOP status */ -#define TSI148_LCSR_PSTAT_TRDYS BIT(0) /* TRDY status */ - -/* - * VMEbus Exception Attributes Register CRG + $268 - */ -#define TSI148_LCSR_VEAT_VES BIT(31) /* Status */ -#define TSI148_LCSR_VEAT_VEOF BIT(30) /* Overflow */ -#define TSI148_LCSR_VEAT_VESCL BIT(29) /* Status Clear */ -#define TSI148_LCSR_VEAT_2EOT BIT(21) /* 2e Odd Termination */ -#define TSI148_LCSR_VEAT_2EST BIT(20) /* 2e Slave terminated */ -#define TSI148_LCSR_VEAT_BERR BIT(19) /* Bus Error */ -#define TSI148_LCSR_VEAT_LWORD BIT(18) /* LWORD_ signal state */ -#define TSI148_LCSR_VEAT_WRITE BIT(17) /* WRITE_ signal state */ -#define TSI148_LCSR_VEAT_IACK BIT(16) /* IACK_ signal state */ -#define TSI148_LCSR_VEAT_DS1 BIT(15) /* DS1_ signal state */ -#define TSI148_LCSR_VEAT_DS0 BIT(14) /* DS0_ signal state */ -#define TSI148_LCSR_VEAT_AM_M (0x3F << 8) /* Address Mode Mask */ -#define TSI148_LCSR_VEAT_XAM_M (0xFF << 0) /* Master AMode Mask */ - -/* - * VMEbus PCI Error Diagnostics PCI/X Attributes Register CRG + $280 - */ -#define TSI148_LCSR_EDPAT_EDPCL BIT(29) - -/* - * Inbound Translation Starting Address Lower - */ -#define TSI148_LCSR_ITSAL6432_M (0xFFFF << 16) /* Mask */ -#define TSI148_LCSR_ITSAL24_M (0x00FFF << 12) /* Mask */ -#define TSI148_LCSR_ITSAL16_M (0x0000FFF << 4) /* Mask */ - -/* - * Inbound Translation Ending Address Lower - */ -#define TSI148_LCSR_ITEAL6432_M (0xFFFF << 16) /* Mask */ -#define TSI148_LCSR_ITEAL24_M (0x00FFF << 12) /* Mask */ -#define TSI148_LCSR_ITEAL16_M (0x0000FFF << 4) /* Mask */ - -/* - * Inbound Translation Offset Lower - */ -#define TSI148_LCSR_ITOFFL6432_M (0xFFFF << 16) /* Mask */ -#define TSI148_LCSR_ITOFFL24_M (0xFFFFF << 12) /* Mask */ -#define TSI148_LCSR_ITOFFL16_M (0xFFFFFFF << 4) /* Mask */ - -/* - * Inbound Translation Attribute - */ -#define TSI148_LCSR_ITAT_EN BIT(31) /* Window Enable */ -#define TSI148_LCSR_ITAT_TH BIT(18) /* Prefetch Threshold */ - -#define TSI148_LCSR_ITAT_VFS_M (3 << 16) /* Virtual FIFO Size Mask */ -#define TSI148_LCSR_ITAT_VFS_64 (0 << 16) /* 64 bytes Virtual FIFO Size */ -#define TSI148_LCSR_ITAT_VFS_128 BIT(16) /* 128 bytes Virtual FIFO Sz */ -#define TSI148_LCSR_ITAT_VFS_256 (2 << 16) /* 256 bytes Virtual FIFO Sz */ -#define TSI148_LCSR_ITAT_VFS_512 (3 << 16) /* 512 bytes Virtual FIFO Sz */ - -#define TSI148_LCSR_ITAT_2eSSTM_M (7 << 12) /* 2eSST Xfer Rate Mask */ -#define TSI148_LCSR_ITAT_2eSSTM_160 (0 << 12) /* 160MB/s 2eSST Xfer Rate */ -#define TSI148_LCSR_ITAT_2eSSTM_267 BIT(12) /* 267MB/s 2eSST Xfer Rate */ -#define TSI148_LCSR_ITAT_2eSSTM_320 (2 << 12) /* 320MB/s 2eSST Xfer Rate */ - -#define TSI148_LCSR_ITAT_2eSSTB BIT(11) /* 2eSST Bcast Xfer Protocol */ -#define TSI148_LCSR_ITAT_2eSST BIT(10) /* 2eSST Xfer Protocol */ -#define TSI148_LCSR_ITAT_2eVME BIT(9) /* 2eVME Xfer Protocol */ -#define TSI148_LCSR_ITAT_MBLT BIT(8) /* MBLT Xfer Protocol */ -#define TSI148_LCSR_ITAT_BLT BIT(7) /* BLT Xfer Protocol */ - -#define TSI148_LCSR_ITAT_AS_M (7 << 4) /* Address Space Mask */ -#define TSI148_LCSR_ITAT_AS_A16 (0 << 4) /* A16 Address Space */ -#define TSI148_LCSR_ITAT_AS_A24 BIT(4) /* A24 Address Space */ -#define TSI148_LCSR_ITAT_AS_A32 (2 << 4) /* A32 Address Space */ -#define TSI148_LCSR_ITAT_AS_A64 (4 << 4) /* A64 Address Space */ - -#define TSI148_LCSR_ITAT_SUPR BIT(3) /* Supervisor Access */ -#define TSI148_LCSR_ITAT_NPRIV BIT(2) /* Non-Priv (User) Access */ -#define TSI148_LCSR_ITAT_PGM BIT(1) /* Program Access */ -#define TSI148_LCSR_ITAT_DATA BIT(0) /* Data Access */ - -/* - * GCSR Base Address Lower Address CRG +$404 - */ -#define TSI148_LCSR_GBAL_M (0x7FFFFFF << 5) /* Mask */ - -/* - * GCSR Attribute Register CRG + $408 - */ -#define TSI148_LCSR_GCSRAT_EN BIT(7) /* Enable access to GCSR */ - -#define TSI148_LCSR_GCSRAT_AS_M (7 << 4) /* Address Space Mask */ -#define TSI148_LCSR_GCSRAT_AS_A16 (0 << 4) /* Address Space 16 */ -#define TSI148_LCSR_GCSRAT_AS_A24 BIT(4) /* Address Space 24 */ -#define TSI148_LCSR_GCSRAT_AS_A32 (2 << 4) /* Address Space 32 */ -#define TSI148_LCSR_GCSRAT_AS_A64 (4 << 4) /* Address Space 64 */ - -#define TSI148_LCSR_GCSRAT_SUPR BIT(3) /* Sup set -GCSR decoder */ -#define TSI148_LCSR_GCSRAT_NPRIV BIT(2) /* Non-Privliged set - CGSR */ -#define TSI148_LCSR_GCSRAT_PGM BIT(1) /* Program set - GCSR decoder */ -#define TSI148_LCSR_GCSRAT_DATA BIT(0) /* DATA set GCSR decoder */ - -/* - * CRG Base Address Lower Address CRG + $410 - */ -#define TSI148_LCSR_CBAL_M (0xFFFFF << 12) - -/* - * CRG Attribute Register CRG + $414 - */ -#define TSI148_LCSR_CRGAT_EN BIT(7) /* Enable PRG Access */ - -#define TSI148_LCSR_CRGAT_AS_M (7 << 4) /* Address Space */ -#define TSI148_LCSR_CRGAT_AS_A16 (0 << 4) /* Address Space 16 */ -#define TSI148_LCSR_CRGAT_AS_A24 BIT(4) /* Address Space 24 */ -#define TSI148_LCSR_CRGAT_AS_A32 (2 << 4) /* Address Space 32 */ -#define TSI148_LCSR_CRGAT_AS_A64 (4 << 4) /* Address Space 64 */ - -#define TSI148_LCSR_CRGAT_SUPR BIT(3) /* Supervisor Access */ -#define TSI148_LCSR_CRGAT_NPRIV BIT(2) /* Non-Privliged(User) Access */ -#define TSI148_LCSR_CRGAT_PGM BIT(1) /* Program Access */ -#define TSI148_LCSR_CRGAT_DATA BIT(0) /* Data Access */ - -/* - * CR/CSR Offset Lower Register CRG + $41C - */ -#define TSI148_LCSR_CROL_M (0x1FFF << 19) /* Mask */ - -/* - * CR/CSR Attribute register CRG + $420 - */ -#define TSI148_LCSR_CRAT_EN BIT(7) /* Enable access to CR/CSR */ - -/* - * Location Monitor base address lower register CRG + $428 - */ -#define TSI148_LCSR_LMBAL_M (0x7FFFFFF << 5) /* Mask */ - -/* - * Location Monitor Attribute Register CRG + $42C - */ -#define TSI148_LCSR_LMAT_EN BIT(7) /* Enable Location Monitor */ - -#define TSI148_LCSR_LMAT_AS_M (7 << 4) /* Address Space MASK */ -#define TSI148_LCSR_LMAT_AS_A16 (0 << 4) /* A16 */ -#define TSI148_LCSR_LMAT_AS_A24 BIT(4) /* A24 */ -#define TSI148_LCSR_LMAT_AS_A32 (2 << 4) /* A32 */ -#define TSI148_LCSR_LMAT_AS_A64 (4 << 4) /* A64 */ - -#define TSI148_LCSR_LMAT_SUPR BIT(3) /* Supervisor Access */ -#define TSI148_LCSR_LMAT_NPRIV BIT(2) /* Non-Priv (User) Access */ -#define TSI148_LCSR_LMAT_PGM BIT(1) /* Program Access */ -#define TSI148_LCSR_LMAT_DATA BIT(0) /* Data Access */ - -/* - * Broadcast Pulse Generator Timer Register CRG + $438 - */ -#define TSI148_LCSR_BPGTR_BPGT_M (0xFFFF << 0) /* Mask */ - -/* - * Broadcast Programmable Clock Timer Register CRG + $43C - */ -#define TSI148_LCSR_BPCTR_BPCT_M (0xFFFFFF << 0) /* Mask */ - -/* - * VMEbus Interrupt Control Register CRG + $43C - */ -#define TSI148_LCSR_VICR_CNTS_M (3 << 22) /* Cntr Source MASK */ -#define TSI148_LCSR_VICR_CNTS_DIS BIT(22) /* Cntr Disable */ -#define TSI148_LCSR_VICR_CNTS_IRQ1 (2 << 22) /* IRQ1 to Cntr */ -#define TSI148_LCSR_VICR_CNTS_IRQ2 (3 << 22) /* IRQ2 to Cntr */ - -#define TSI148_LCSR_VICR_EDGIS_M (3 << 20) /* Edge interrupt MASK */ -#define TSI148_LCSR_VICR_EDGIS_DIS BIT(20) /* Edge interrupt Disable */ -#define TSI148_LCSR_VICR_EDGIS_IRQ1 (2 << 20) /* IRQ1 to Edge */ -#define TSI148_LCSR_VICR_EDGIS_IRQ2 (3 << 20) /* IRQ2 to Edge */ - -#define TSI148_LCSR_VICR_IRQIF_M (3 << 18) /* IRQ1* Function MASK */ -#define TSI148_LCSR_VICR_IRQIF_NORM BIT(18) /* Normal */ -#define TSI148_LCSR_VICR_IRQIF_PULSE (2 << 18) /* Pulse Generator */ -#define TSI148_LCSR_VICR_IRQIF_PROG (3 << 18) /* Programmable Clock */ -#define TSI148_LCSR_VICR_IRQIF_1U (4 << 18) /* 1us Clock */ - -#define TSI148_LCSR_VICR_IRQ2F_M (3 << 16) /* IRQ2* Function MASK */ -#define TSI148_LCSR_VICR_IRQ2F_NORM BIT(16) /* Normal */ -#define TSI148_LCSR_VICR_IRQ2F_PULSE (2 << 16) /* Pulse Generator */ -#define TSI148_LCSR_VICR_IRQ2F_PROG (3 << 16) /* Programmable Clock */ -#define TSI148_LCSR_VICR_IRQ2F_1U (4 << 16) /* 1us Clock */ - -#define TSI148_LCSR_VICR_BIP BIT(15) /* Broadcast Interrupt Pulse */ - -#define TSI148_LCSR_VICR_IRQC BIT(12) /* VMEbus IRQ Clear */ -#define TSI148_LCSR_VICR_IRQS BIT(11) /* VMEbus IRQ Status */ - -#define TSI148_LCSR_VICR_IRQL_M (7 << 8) /* VMEbus SW IRQ Level Mask */ -#define TSI148_LCSR_VICR_IRQL_1 BIT(8) /* VMEbus SW IRQ Level 1 */ -#define TSI148_LCSR_VICR_IRQL_2 (2 << 8) /* VMEbus SW IRQ Level 2 */ -#define TSI148_LCSR_VICR_IRQL_3 (3 << 8) /* VMEbus SW IRQ Level 3 */ -#define TSI148_LCSR_VICR_IRQL_4 (4 << 8) /* VMEbus SW IRQ Level 4 */ -#define TSI148_LCSR_VICR_IRQL_5 (5 << 8) /* VMEbus SW IRQ Level 5 */ -#define TSI148_LCSR_VICR_IRQL_6 (6 << 8) /* VMEbus SW IRQ Level 6 */ -#define TSI148_LCSR_VICR_IRQL_7 (7 << 8) /* VMEbus SW IRQ Level 7 */ - -static const int TSI148_LCSR_VICR_IRQL[8] = { 0, TSI148_LCSR_VICR_IRQL_1, - TSI148_LCSR_VICR_IRQL_2, TSI148_LCSR_VICR_IRQL_3, - TSI148_LCSR_VICR_IRQL_4, TSI148_LCSR_VICR_IRQL_5, - TSI148_LCSR_VICR_IRQL_6, TSI148_LCSR_VICR_IRQL_7 }; - -#define TSI148_LCSR_VICR_STID_M (0xFF << 0) /* Status/ID Mask */ - -/* - * Interrupt Enable Register CRG + $440 - */ -#define TSI148_LCSR_INTEN_DMA1EN BIT(25) /* DMAC 1 */ -#define TSI148_LCSR_INTEN_DMA0EN BIT(24) /* DMAC 0 */ -#define TSI148_LCSR_INTEN_LM3EN BIT(23) /* Location Monitor 3 */ -#define TSI148_LCSR_INTEN_LM2EN BIT(22) /* Location Monitor 2 */ -#define TSI148_LCSR_INTEN_LM1EN BIT(21) /* Location Monitor 1 */ -#define TSI148_LCSR_INTEN_LM0EN BIT(20) /* Location Monitor 0 */ -#define TSI148_LCSR_INTEN_MB3EN BIT(19) /* Mail Box 3 */ -#define TSI148_LCSR_INTEN_MB2EN BIT(18) /* Mail Box 2 */ -#define TSI148_LCSR_INTEN_MB1EN BIT(17) /* Mail Box 1 */ -#define TSI148_LCSR_INTEN_MB0EN BIT(16) /* Mail Box 0 */ -#define TSI148_LCSR_INTEN_PERREN BIT(13) /* PCI/X Error */ -#define TSI148_LCSR_INTEN_VERREN BIT(12) /* VMEbus Error */ -#define TSI148_LCSR_INTEN_VIEEN BIT(11) /* VMEbus IRQ Edge */ -#define TSI148_LCSR_INTEN_IACKEN BIT(10) /* IACK */ -#define TSI148_LCSR_INTEN_SYSFLEN BIT(9) /* System Fail */ -#define TSI148_LCSR_INTEN_ACFLEN BIT(8) /* AC Fail */ -#define TSI148_LCSR_INTEN_IRQ7EN BIT(7) /* IRQ7 */ -#define TSI148_LCSR_INTEN_IRQ6EN BIT(6) /* IRQ6 */ -#define TSI148_LCSR_INTEN_IRQ5EN BIT(5) /* IRQ5 */ -#define TSI148_LCSR_INTEN_IRQ4EN BIT(4) /* IRQ4 */ -#define TSI148_LCSR_INTEN_IRQ3EN BIT(3) /* IRQ3 */ -#define TSI148_LCSR_INTEN_IRQ2EN BIT(2) /* IRQ2 */ -#define TSI148_LCSR_INTEN_IRQ1EN BIT(1) /* IRQ1 */ - -static const int TSI148_LCSR_INTEN_LMEN[4] = { TSI148_LCSR_INTEN_LM0EN, - TSI148_LCSR_INTEN_LM1EN, - TSI148_LCSR_INTEN_LM2EN, - TSI148_LCSR_INTEN_LM3EN }; - -static const int TSI148_LCSR_INTEN_IRQEN[7] = { TSI148_LCSR_INTEN_IRQ1EN, - TSI148_LCSR_INTEN_IRQ2EN, - TSI148_LCSR_INTEN_IRQ3EN, - TSI148_LCSR_INTEN_IRQ4EN, - TSI148_LCSR_INTEN_IRQ5EN, - TSI148_LCSR_INTEN_IRQ6EN, - TSI148_LCSR_INTEN_IRQ7EN }; - -/* - * Interrupt Enable Out Register CRG + $444 - */ -#define TSI148_LCSR_INTEO_DMA1EO BIT(25) /* DMAC 1 */ -#define TSI148_LCSR_INTEO_DMA0EO BIT(24) /* DMAC 0 */ -#define TSI148_LCSR_INTEO_LM3EO BIT(23) /* Loc Monitor 3 */ -#define TSI148_LCSR_INTEO_LM2EO BIT(22) /* Loc Monitor 2 */ -#define TSI148_LCSR_INTEO_LM1EO BIT(21) /* Loc Monitor 1 */ -#define TSI148_LCSR_INTEO_LM0EO BIT(20) /* Location Monitor 0 */ -#define TSI148_LCSR_INTEO_MB3EO BIT(19) /* Mail Box 3 */ -#define TSI148_LCSR_INTEO_MB2EO BIT(18) /* Mail Box 2 */ -#define TSI148_LCSR_INTEO_MB1EO BIT(17) /* Mail Box 1 */ -#define TSI148_LCSR_INTEO_MB0EO BIT(16) /* Mail Box 0 */ -#define TSI148_LCSR_INTEO_PERREO BIT(13) /* PCI/X Error */ -#define TSI148_LCSR_INTEO_VERREO BIT(12) /* VMEbus Error */ -#define TSI148_LCSR_INTEO_VIEEO BIT(11) /* VMEbus IRQ Edge */ -#define TSI148_LCSR_INTEO_IACKEO BIT(10) /* IACK */ -#define TSI148_LCSR_INTEO_SYSFLEO BIT(9) /* System Fail */ -#define TSI148_LCSR_INTEO_ACFLEO BIT(8) /* AC Fail */ -#define TSI148_LCSR_INTEO_IRQ7EO BIT(7) /* IRQ7 */ -#define TSI148_LCSR_INTEO_IRQ6EO BIT(6) /* IRQ6 */ -#define TSI148_LCSR_INTEO_IRQ5EO BIT(5) /* IRQ5 */ -#define TSI148_LCSR_INTEO_IRQ4EO BIT(4) /* IRQ4 */ -#define TSI148_LCSR_INTEO_IRQ3EO BIT(3) /* IRQ3 */ -#define TSI148_LCSR_INTEO_IRQ2EO BIT(2) /* IRQ2 */ -#define TSI148_LCSR_INTEO_IRQ1EO BIT(1) /* IRQ1 */ - -static const int TSI148_LCSR_INTEO_LMEO[4] = { TSI148_LCSR_INTEO_LM0EO, - TSI148_LCSR_INTEO_LM1EO, - TSI148_LCSR_INTEO_LM2EO, - TSI148_LCSR_INTEO_LM3EO }; - -static const int TSI148_LCSR_INTEO_IRQEO[7] = { TSI148_LCSR_INTEO_IRQ1EO, - TSI148_LCSR_INTEO_IRQ2EO, - TSI148_LCSR_INTEO_IRQ3EO, - TSI148_LCSR_INTEO_IRQ4EO, - TSI148_LCSR_INTEO_IRQ5EO, - TSI148_LCSR_INTEO_IRQ6EO, - TSI148_LCSR_INTEO_IRQ7EO }; - -/* - * Interrupt Status Register CRG + $448 - */ -#define TSI148_LCSR_INTS_DMA1S BIT(25) /* DMA 1 */ -#define TSI148_LCSR_INTS_DMA0S BIT(24) /* DMA 0 */ -#define TSI148_LCSR_INTS_LM3S BIT(23) /* Location Monitor 3 */ -#define TSI148_LCSR_INTS_LM2S BIT(22) /* Location Monitor 2 */ -#define TSI148_LCSR_INTS_LM1S BIT(21) /* Location Monitor 1 */ -#define TSI148_LCSR_INTS_LM0S BIT(20) /* Location Monitor 0 */ -#define TSI148_LCSR_INTS_MB3S BIT(19) /* Mail Box 3 */ -#define TSI148_LCSR_INTS_MB2S BIT(18) /* Mail Box 2 */ -#define TSI148_LCSR_INTS_MB1S BIT(17) /* Mail Box 1 */ -#define TSI148_LCSR_INTS_MB0S BIT(16) /* Mail Box 0 */ -#define TSI148_LCSR_INTS_PERRS BIT(13) /* PCI/X Error */ -#define TSI148_LCSR_INTS_VERRS BIT(12) /* VMEbus Error */ -#define TSI148_LCSR_INTS_VIES BIT(11) /* VMEbus IRQ Edge */ -#define TSI148_LCSR_INTS_IACKS BIT(10) /* IACK */ -#define TSI148_LCSR_INTS_SYSFLS BIT(9) /* System Fail */ -#define TSI148_LCSR_INTS_ACFLS BIT(8) /* AC Fail */ -#define TSI148_LCSR_INTS_IRQ7S BIT(7) /* IRQ7 */ -#define TSI148_LCSR_INTS_IRQ6S BIT(6) /* IRQ6 */ -#define TSI148_LCSR_INTS_IRQ5S BIT(5) /* IRQ5 */ -#define TSI148_LCSR_INTS_IRQ4S BIT(4) /* IRQ4 */ -#define TSI148_LCSR_INTS_IRQ3S BIT(3) /* IRQ3 */ -#define TSI148_LCSR_INTS_IRQ2S BIT(2) /* IRQ2 */ -#define TSI148_LCSR_INTS_IRQ1S BIT(1) /* IRQ1 */ - -static const int TSI148_LCSR_INTS_LMS[4] = { TSI148_LCSR_INTS_LM0S, - TSI148_LCSR_INTS_LM1S, - TSI148_LCSR_INTS_LM2S, - TSI148_LCSR_INTS_LM3S }; - -static const int TSI148_LCSR_INTS_MBS[4] = { TSI148_LCSR_INTS_MB0S, - TSI148_LCSR_INTS_MB1S, - TSI148_LCSR_INTS_MB2S, - TSI148_LCSR_INTS_MB3S }; - -/* - * Interrupt Clear Register CRG + $44C - */ -#define TSI148_LCSR_INTC_DMA1C BIT(25) /* DMA 1 */ -#define TSI148_LCSR_INTC_DMA0C BIT(24) /* DMA 0 */ -#define TSI148_LCSR_INTC_LM3C BIT(23) /* Location Monitor 3 */ -#define TSI148_LCSR_INTC_LM2C BIT(22) /* Location Monitor 2 */ -#define TSI148_LCSR_INTC_LM1C BIT(21) /* Location Monitor 1 */ -#define TSI148_LCSR_INTC_LM0C BIT(20) /* Location Monitor 0 */ -#define TSI148_LCSR_INTC_MB3C BIT(19) /* Mail Box 3 */ -#define TSI148_LCSR_INTC_MB2C BIT(18) /* Mail Box 2 */ -#define TSI148_LCSR_INTC_MB1C BIT(17) /* Mail Box 1 */ -#define TSI148_LCSR_INTC_MB0C BIT(16) /* Mail Box 0 */ -#define TSI148_LCSR_INTC_PERRC BIT(13) /* VMEbus Error */ -#define TSI148_LCSR_INTC_VERRC BIT(12) /* VMEbus Access Time-out */ -#define TSI148_LCSR_INTC_VIEC BIT(11) /* VMEbus IRQ Edge */ -#define TSI148_LCSR_INTC_IACKC BIT(10) /* IACK */ -#define TSI148_LCSR_INTC_SYSFLC BIT(9) /* System Fail */ -#define TSI148_LCSR_INTC_ACFLC BIT(8) /* AC Fail */ - -static const int TSI148_LCSR_INTC_LMC[4] = { TSI148_LCSR_INTC_LM0C, - TSI148_LCSR_INTC_LM1C, - TSI148_LCSR_INTC_LM2C, - TSI148_LCSR_INTC_LM3C }; - -static const int TSI148_LCSR_INTC_MBC[4] = { TSI148_LCSR_INTC_MB0C, - TSI148_LCSR_INTC_MB1C, - TSI148_LCSR_INTC_MB2C, - TSI148_LCSR_INTC_MB3C }; - -/* - * Interrupt Map Register 1 CRG + $458 - */ -#define TSI148_LCSR_INTM1_DMA1M_M (3 << 18) /* DMA 1 */ -#define TSI148_LCSR_INTM1_DMA0M_M (3 << 16) /* DMA 0 */ -#define TSI148_LCSR_INTM1_LM3M_M (3 << 14) /* Location Monitor 3 */ -#define TSI148_LCSR_INTM1_LM2M_M (3 << 12) /* Location Monitor 2 */ -#define TSI148_LCSR_INTM1_LM1M_M (3 << 10) /* Location Monitor 1 */ -#define TSI148_LCSR_INTM1_LM0M_M (3 << 8) /* Location Monitor 0 */ -#define TSI148_LCSR_INTM1_MB3M_M (3 << 6) /* Mail Box 3 */ -#define TSI148_LCSR_INTM1_MB2M_M (3 << 4) /* Mail Box 2 */ -#define TSI148_LCSR_INTM1_MB1M_M (3 << 2) /* Mail Box 1 */ -#define TSI148_LCSR_INTM1_MB0M_M (3 << 0) /* Mail Box 0 */ - -/* - * Interrupt Map Register 2 CRG + $45C - */ -#define TSI148_LCSR_INTM2_PERRM_M (3 << 26) /* PCI Bus Error */ -#define TSI148_LCSR_INTM2_VERRM_M (3 << 24) /* VMEbus Error */ -#define TSI148_LCSR_INTM2_VIEM_M (3 << 22) /* VMEbus IRQ Edge */ -#define TSI148_LCSR_INTM2_IACKM_M (3 << 20) /* IACK */ -#define TSI148_LCSR_INTM2_SYSFLM_M (3 << 18) /* System Fail */ -#define TSI148_LCSR_INTM2_ACFLM_M (3 << 16) /* AC Fail */ -#define TSI148_LCSR_INTM2_IRQ7M_M (3 << 14) /* IRQ7 */ -#define TSI148_LCSR_INTM2_IRQ6M_M (3 << 12) /* IRQ6 */ -#define TSI148_LCSR_INTM2_IRQ5M_M (3 << 10) /* IRQ5 */ -#define TSI148_LCSR_INTM2_IRQ4M_M (3 << 8) /* IRQ4 */ -#define TSI148_LCSR_INTM2_IRQ3M_M (3 << 6) /* IRQ3 */ -#define TSI148_LCSR_INTM2_IRQ2M_M (3 << 4) /* IRQ2 */ -#define TSI148_LCSR_INTM2_IRQ1M_M (3 << 2) /* IRQ1 */ - -/* - * DMA Control (0-1) Registers CRG + $500 - */ -#define TSI148_LCSR_DCTL_ABT BIT(27) /* Abort */ -#define TSI148_LCSR_DCTL_PAU BIT(26) /* Pause */ -#define TSI148_LCSR_DCTL_DGO BIT(25) /* DMA Go */ - -#define TSI148_LCSR_DCTL_MOD BIT(23) /* Mode */ - -#define TSI148_LCSR_DCTL_VBKS_M (7 << 12) /* VMEbus block Size MASK */ -#define TSI148_LCSR_DCTL_VBKS_32 (0 << 12) /* VMEbus block Size 32 */ -#define TSI148_LCSR_DCTL_VBKS_64 BIT(12) /* VMEbus block Size 64 */ -#define TSI148_LCSR_DCTL_VBKS_128 (2 << 12) /* VMEbus block Size 128 */ -#define TSI148_LCSR_DCTL_VBKS_256 (3 << 12) /* VMEbus block Size 256 */ -#define TSI148_LCSR_DCTL_VBKS_512 (4 << 12) /* VMEbus block Size 512 */ -#define TSI148_LCSR_DCTL_VBKS_1024 (5 << 12) /* VMEbus block Size 1024 */ -#define TSI148_LCSR_DCTL_VBKS_2048 (6 << 12) /* VMEbus block Size 2048 */ -#define TSI148_LCSR_DCTL_VBKS_4096 (7 << 12) /* VMEbus block Size 4096 */ - -#define TSI148_LCSR_DCTL_VBOT_M (7 << 8) /* VMEbus back-off MASK */ -#define TSI148_LCSR_DCTL_VBOT_0 (0 << 8) /* VMEbus back-off 0us */ -#define TSI148_LCSR_DCTL_VBOT_1 BIT(8) /* VMEbus back-off 1us */ -#define TSI148_LCSR_DCTL_VBOT_2 (2 << 8) /* VMEbus back-off 2us */ -#define TSI148_LCSR_DCTL_VBOT_4 (3 << 8) /* VMEbus back-off 4us */ -#define TSI148_LCSR_DCTL_VBOT_8 (4 << 8) /* VMEbus back-off 8us */ -#define TSI148_LCSR_DCTL_VBOT_16 (5 << 8) /* VMEbus back-off 16us */ -#define TSI148_LCSR_DCTL_VBOT_32 (6 << 8) /* VMEbus back-off 32us */ -#define TSI148_LCSR_DCTL_VBOT_64 (7 << 8) /* VMEbus back-off 64us */ - -#define TSI148_LCSR_DCTL_PBKS_M (7 << 4) /* PCI block size MASK */ -#define TSI148_LCSR_DCTL_PBKS_32 (0 << 4) /* PCI block size 32 bytes */ -#define TSI148_LCSR_DCTL_PBKS_64 BIT(4) /* PCI block size 64 bytes */ -#define TSI148_LCSR_DCTL_PBKS_128 (2 << 4) /* PCI block size 128 bytes */ -#define TSI148_LCSR_DCTL_PBKS_256 (3 << 4) /* PCI block size 256 bytes */ -#define TSI148_LCSR_DCTL_PBKS_512 (4 << 4) /* PCI block size 512 bytes */ -#define TSI148_LCSR_DCTL_PBKS_1024 (5 << 4) /* PCI block size 1024 bytes */ -#define TSI148_LCSR_DCTL_PBKS_2048 (6 << 4) /* PCI block size 2048 bytes */ -#define TSI148_LCSR_DCTL_PBKS_4096 (7 << 4) /* PCI block size 4096 bytes */ - -#define TSI148_LCSR_DCTL_PBOT_M (7 << 0) /* PCI back off MASK */ -#define TSI148_LCSR_DCTL_PBOT_0 (0 << 0) /* PCI back off 0us */ -#define TSI148_LCSR_DCTL_PBOT_1 BIT(0) /* PCI back off 1us */ -#define TSI148_LCSR_DCTL_PBOT_2 (2 << 0) /* PCI back off 2us */ -#define TSI148_LCSR_DCTL_PBOT_4 (3 << 0) /* PCI back off 3us */ -#define TSI148_LCSR_DCTL_PBOT_8 (4 << 0) /* PCI back off 4us */ -#define TSI148_LCSR_DCTL_PBOT_16 (5 << 0) /* PCI back off 8us */ -#define TSI148_LCSR_DCTL_PBOT_32 (6 << 0) /* PCI back off 16us */ -#define TSI148_LCSR_DCTL_PBOT_64 (7 << 0) /* PCI back off 32us */ - -/* - * DMA Status Registers (0-1) CRG + $504 - */ -#define TSI148_LCSR_DSTA_SMA BIT(31) /* PCI Signalled Master Abt */ -#define TSI148_LCSR_DSTA_RTA BIT(30) /* PCI Received Target Abt */ -#define TSI148_LCSR_DSTA_MRC BIT(29) /* PCI Max Retry Count */ -#define TSI148_LCSR_DSTA_VBE BIT(28) /* VMEbus error */ -#define TSI148_LCSR_DSTA_ABT BIT(27) /* Abort */ -#define TSI148_LCSR_DSTA_PAU BIT(26) /* Pause */ -#define TSI148_LCSR_DSTA_DON BIT(25) /* Done */ -#define TSI148_LCSR_DSTA_BSY BIT(24) /* Busy */ - -/* - * DMA Current Link Address Lower (0-1) - */ -#define TSI148_LCSR_DCLAL_M (0x3FFFFFF << 6) /* Mask */ - -/* - * DMA Source Attribute (0-1) Reg - */ -#define TSI148_LCSR_DSAT_TYP_M (3 << 28) /* Source Bus Type */ -#define TSI148_LCSR_DSAT_TYP_PCI (0 << 28) /* PCI Bus */ -#define TSI148_LCSR_DSAT_TYP_VME BIT(28) /* VMEbus */ -#define TSI148_LCSR_DSAT_TYP_PAT (2 << 28) /* Data Pattern */ - -#define TSI148_LCSR_DSAT_PSZ BIT(25) /* Pattern Size */ -#define TSI148_LCSR_DSAT_NIN BIT(24) /* No Increment */ - -#define TSI148_LCSR_DSAT_2eSSTM_M (3 << 11) /* 2eSST Trans Rate Mask */ -#define TSI148_LCSR_DSAT_2eSSTM_160 (0 << 11) /* 160 MB/s */ -#define TSI148_LCSR_DSAT_2eSSTM_267 BIT(11) /* 267 MB/s */ -#define TSI148_LCSR_DSAT_2eSSTM_320 (2 << 11) /* 320 MB/s */ - -#define TSI148_LCSR_DSAT_TM_M (7 << 8) /* Bus Transfer Protocol Mask */ -#define TSI148_LCSR_DSAT_TM_SCT (0 << 8) /* SCT */ -#define TSI148_LCSR_DSAT_TM_BLT BIT(8) /* BLT */ -#define TSI148_LCSR_DSAT_TM_MBLT (2 << 8) /* MBLT */ -#define TSI148_LCSR_DSAT_TM_2eVME (3 << 8) /* 2eVME */ -#define TSI148_LCSR_DSAT_TM_2eSST (4 << 8) /* 2eSST */ -#define TSI148_LCSR_DSAT_TM_2eSSTB (5 << 8) /* 2eSST Broadcast */ - -#define TSI148_LCSR_DSAT_DBW_M (3 << 6) /* Max Data Width MASK */ -#define TSI148_LCSR_DSAT_DBW_16 (0 << 6) /* 16 Bits */ -#define TSI148_LCSR_DSAT_DBW_32 BIT(6) /* 32 Bits */ - -#define TSI148_LCSR_DSAT_SUP BIT(5) /* Supervisory Mode */ -#define TSI148_LCSR_DSAT_PGM BIT(4) /* Program Mode */ - -#define TSI148_LCSR_DSAT_AMODE_M (0xf << 0) /* Address Space Mask */ -#define TSI148_LCSR_DSAT_AMODE_A16 (0 << 0) /* A16 */ -#define TSI148_LCSR_DSAT_AMODE_A24 BIT(0) /* A24 */ -#define TSI148_LCSR_DSAT_AMODE_A32 (2 << 0) /* A32 */ -#define TSI148_LCSR_DSAT_AMODE_A64 (4 << 0) /* A64 */ -#define TSI148_LCSR_DSAT_AMODE_CRCSR (5 << 0) /* CR/CSR */ -#define TSI148_LCSR_DSAT_AMODE_USER1 (8 << 0) /* User1 */ -#define TSI148_LCSR_DSAT_AMODE_USER2 (9 << 0) /* User2 */ -#define TSI148_LCSR_DSAT_AMODE_USER3 (0xa << 0) /* User3 */ -#define TSI148_LCSR_DSAT_AMODE_USER4 (0xb << 0) /* User4 */ - -/* - * DMA Destination Attribute Registers (0-1) - */ -#define TSI148_LCSR_DDAT_TYP_PCI (0 << 28) /* Destination PCI Bus */ -#define TSI148_LCSR_DDAT_TYP_VME BIT(28) /* Destination VMEbus */ - -#define TSI148_LCSR_DDAT_2eSSTM_M (3 << 11) /* 2eSST Transfer Rate Mask */ -#define TSI148_LCSR_DDAT_2eSSTM_160 (0 << 11) /* 160 MB/s */ -#define TSI148_LCSR_DDAT_2eSSTM_267 BIT(11) /* 267 MB/s */ -#define TSI148_LCSR_DDAT_2eSSTM_320 (2 << 11) /* 320 MB/s */ - -#define TSI148_LCSR_DDAT_TM_M (7 << 8) /* Bus Transfer Protocol Mask */ -#define TSI148_LCSR_DDAT_TM_SCT (0 << 8) /* SCT */ -#define TSI148_LCSR_DDAT_TM_BLT BIT(8) /* BLT */ -#define TSI148_LCSR_DDAT_TM_MBLT (2 << 8) /* MBLT */ -#define TSI148_LCSR_DDAT_TM_2eVME (3 << 8) /* 2eVME */ -#define TSI148_LCSR_DDAT_TM_2eSST (4 << 8) /* 2eSST */ -#define TSI148_LCSR_DDAT_TM_2eSSTB (5 << 8) /* 2eSST Broadcast */ - -#define TSI148_LCSR_DDAT_DBW_M (3 << 6) /* Max Data Width MASK */ -#define TSI148_LCSR_DDAT_DBW_16 (0 << 6) /* 16 Bits */ -#define TSI148_LCSR_DDAT_DBW_32 BIT(6) /* 32 Bits */ - -#define TSI148_LCSR_DDAT_SUP BIT(5) /* Supervisory/User Access */ -#define TSI148_LCSR_DDAT_PGM BIT(4) /* Program/Data Access */ - -#define TSI148_LCSR_DDAT_AMODE_M (0xf << 0) /* Address Space Mask */ -#define TSI148_LCSR_DDAT_AMODE_A16 (0 << 0) /* A16 */ -#define TSI148_LCSR_DDAT_AMODE_A24 BIT(0) /* A24 */ -#define TSI148_LCSR_DDAT_AMODE_A32 (2 << 0) /* A32 */ -#define TSI148_LCSR_DDAT_AMODE_A64 (4 << 0) /* A64 */ -#define TSI148_LCSR_DDAT_AMODE_CRCSR (5 << 0) /* CRC/SR */ -#define TSI148_LCSR_DDAT_AMODE_USER1 (8 << 0) /* User1 */ -#define TSI148_LCSR_DDAT_AMODE_USER2 (9 << 0) /* User2 */ -#define TSI148_LCSR_DDAT_AMODE_USER3 (0xa << 0) /* User3 */ -#define TSI148_LCSR_DDAT_AMODE_USER4 (0xb << 0) /* User4 */ - -/* - * DMA Next Link Address Lower - */ -#define TSI148_LCSR_DNLAL_DNLAL_M (0x3FFFFFF << 6) /* Address Mask */ -#define TSI148_LCSR_DNLAL_LLA BIT(0) /* Last Link Address Indicator */ - -/* - * DMA 2eSST Broadcast Select - */ -#define TSI148_LCSR_DBS_M (0x1FFFFF << 0) /* Mask */ - -/* - * GCSR Register Group - */ - -/* - * GCSR Control and Status Register CRG + $604 - */ -#define TSI148_GCSR_GCTRL_LRST BIT(15) /* Local Reset */ -#define TSI148_GCSR_GCTRL_SFAILEN BIT(14) /* System Fail enable */ -#define TSI148_GCSR_GCTRL_BDFAILS BIT(13) /* Board Fail Status */ -#define TSI148_GCSR_GCTRL_SCON BIT(12) /* System Controller */ -#define TSI148_GCSR_GCTRL_MEN BIT(11) /* Module Enable (READY) */ - -#define TSI148_GCSR_GCTRL_LMI3S BIT(7) /* Loc Monitor 3 Int Status */ -#define TSI148_GCSR_GCTRL_LMI2S BIT(6) /* Loc Monitor 2 Int Status */ -#define TSI148_GCSR_GCTRL_LMI1S BIT(5) /* Loc Monitor 1 Int Status */ -#define TSI148_GCSR_GCTRL_LMI0S BIT(4) /* Loc Monitor 0 Int Status */ -#define TSI148_GCSR_GCTRL_MBI3S BIT(3) /* Mail box 3 Int Status */ -#define TSI148_GCSR_GCTRL_MBI2S BIT(2) /* Mail box 2 Int Status */ -#define TSI148_GCSR_GCTRL_MBI1S BIT(1) /* Mail box 1 Int Status */ -#define TSI148_GCSR_GCTRL_MBI0S BIT(0) /* Mail box 0 Int Status */ - -#define TSI148_GCSR_GAP BIT(5) /* Geographic Addr Parity */ -#define TSI148_GCSR_GA_M (0x1F << 0) /* Geographic Address Mask */ - -/* - * CR/CSR Register Group - */ - -/* - * CR/CSR Bit Clear Register CRG + $FF4 - */ -#define TSI148_CRCSR_CSRBCR_LRSTC BIT(7) /* Local Reset Clear */ -#define TSI148_CRCSR_CSRBCR_SFAILC BIT(6) /* System Fail Enable Clear */ -#define TSI148_CRCSR_CSRBCR_BDFAILS BIT(5) /* Board Fail Status */ -#define TSI148_CRCSR_CSRBCR_MENC BIT(4) /* Module Enable Clear */ -#define TSI148_CRCSR_CSRBCR_BERRSC BIT(3) /* Bus Error Status Clear */ - -/* - * CR/CSR Bit Set Register CRG+$FF8 - */ -#define TSI148_CRCSR_CSRBSR_LISTS BIT(7) /* Local Reset Clear */ -#define TSI148_CRCSR_CSRBSR_SFAILS BIT(6) /* System Fail Enable Clear */ -#define TSI148_CRCSR_CSRBSR_BDFAILS BIT(5) /* Board Fail Status */ -#define TSI148_CRCSR_CSRBSR_MENS BIT(4) /* Module Enable Clear */ -#define TSI148_CRCSR_CSRBSR_BERRS BIT(3) /* Bus Error Status Clear */ - -/* - * CR/CSR Base Address Register CRG + FFC - */ -#define TSI148_CRCSR_CBAR_M (0x1F << 3) /* Mask */ - -#endif /* TSI148_H */ diff --git a/drivers/staging/vme_user/vme_user.c b/drivers/staging/vme_user/vme_user.c deleted file mode 100644 index a472a38ef613a6..00000000000000 --- a/drivers/staging/vme_user/vme_user.c +++ /dev/null @@ -1,812 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0+ -/* - * VMEbus User access driver - * - * Author: Martyn Welch - * Copyright 2008 GE Intelligent Platforms Embedded Systems, Inc. - * - * Based on work by: - * Tom Armistead and Ajit Prem - * Copyright 2004 Motorola Inc. - */ - -#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include "vme.h" -#include "vme_user.h" - -#define DRIVER_NAME "vme_user" - -static int bus[VME_USER_BUS_MAX]; -static unsigned int bus_num; - -/* Currently Documentation/admin-guide/devices.rst defines the - * following for VME: - * - * 221 char VME bus - * 0 = /dev/bus/vme/m0 First master image - * 1 = /dev/bus/vme/m1 Second master image - * 2 = /dev/bus/vme/m2 Third master image - * 3 = /dev/bus/vme/m3 Fourth master image - * 4 = /dev/bus/vme/s0 First slave image - * 5 = /dev/bus/vme/s1 Second slave image - * 6 = /dev/bus/vme/s2 Third slave image - * 7 = /dev/bus/vme/s3 Fourth slave image - * 8 = /dev/bus/vme/ctl Control - * - * It is expected that all VME bus drivers will use the - * same interface. For interface documentation see - * http://www.vmelinux.org/. - * - * However the VME driver at http://www.vmelinux.org/ is rather old and doesn't - * even support the tsi148 chipset (which has 8 master and 8 slave windows). - * We'll run with this for now as far as possible, however it probably makes - * sense to get rid of the old mappings and just do everything dynamically. - * - * So for now, we'll restrict the driver to providing 4 masters and 4 slaves as - * defined above and try to support at least some of the interface from - * http://www.vmelinux.org/ as an alternative the driver can be written - * providing a saner interface later. - * - * The vmelinux.org driver never supported slave images, the devices reserved - * for slaves were repurposed to support all 8 master images on the UniverseII! - * We shall support 4 masters and 4 slaves with this driver. - */ -#define VME_MAJOR 221 /* VME Major Device Number */ -#define VME_DEVS 9 /* Number of dev entries */ - -#define MASTER_MINOR 0 -#define MASTER_MAX 3 -#define SLAVE_MINOR 4 -#define SLAVE_MAX 7 -#define CONTROL_MINOR 8 - -#define PCI_BUF_SIZE 0x20000 /* Size of one slave image buffer */ - -/* - * Structure to handle image related parameters. - */ -struct image_desc { - void *kern_buf; /* Buffer address in kernel space */ - dma_addr_t pci_buf; /* Buffer address in PCI address space */ - unsigned long long size_buf; /* Buffer size */ - struct mutex mutex; /* Mutex for locking image */ - struct device *device; /* Sysfs device */ - struct vme_resource *resource; /* VME resource */ - int mmap_count; /* Number of current mmap's */ -}; - -static struct image_desc image[VME_DEVS]; - -static struct cdev *vme_user_cdev; /* Character device */ -static struct vme_dev *vme_user_bridge; /* Pointer to user device */ - -static const struct class vme_user_sysfs_class = { - .name = DRIVER_NAME, -}; - -static const int type[VME_DEVS] = { MASTER_MINOR, MASTER_MINOR, - MASTER_MINOR, MASTER_MINOR, - SLAVE_MINOR, SLAVE_MINOR, - SLAVE_MINOR, SLAVE_MINOR, - CONTROL_MINOR - }; - -struct vme_user_vma_priv { - unsigned int minor; - refcount_t refcnt; -}; - -static ssize_t resource_to_user(int minor, char __user *buf, size_t count, - loff_t *ppos) -{ - ssize_t copied = 0; - - if (count > image[minor].size_buf) - count = image[minor].size_buf; - - copied = vme_master_read(image[minor].resource, image[minor].kern_buf, - count, *ppos); - if (copied < 0) - return (int)copied; - - if (copy_to_user(buf, image[minor].kern_buf, (unsigned long)copied)) - return -EFAULT; - - return copied; -} - -static ssize_t resource_from_user(unsigned int minor, const char __user *buf, - size_t count, loff_t *ppos) -{ - if (count > image[minor].size_buf) - count = image[minor].size_buf; - - if (copy_from_user(image[minor].kern_buf, buf, (unsigned long)count)) - return -EFAULT; - - return vme_master_write(image[minor].resource, image[minor].kern_buf, - count, *ppos); -} - -static ssize_t buffer_to_user(unsigned int minor, char __user *buf, - size_t count, loff_t *ppos) -{ - void *image_ptr; - - /* - * The slave window (image_size) can exceed the fixed kern_buf - * (size_buf == PCI_BUF_SIZE), so bound the copy to kern_buf. - * *ppos is >= 0 here (checked by the caller), so the - * subtraction below cannot wrap. - */ - if (*ppos >= image[minor].size_buf) - return 0; - if (count > image[minor].size_buf - *ppos) - count = image[minor].size_buf - *ppos; - - image_ptr = image[minor].kern_buf + *ppos; - if (copy_to_user(buf, image_ptr, (unsigned long)count)) - return -EFAULT; - - return count; -} - -static ssize_t buffer_from_user(unsigned int minor, const char __user *buf, - size_t count, loff_t *ppos) -{ - void *image_ptr; - - /* - * The slave window (image_size) can exceed the fixed kern_buf - * (size_buf == PCI_BUF_SIZE), so bound the copy to kern_buf. - * *ppos is >= 0 here (checked by the caller), so the - * subtraction below cannot wrap. - */ - if (*ppos >= image[minor].size_buf) - return 0; - if (count > image[minor].size_buf - *ppos) - count = image[minor].size_buf - *ppos; - - image_ptr = image[minor].kern_buf + *ppos; - if (copy_from_user(image_ptr, buf, (unsigned long)count)) - return -EFAULT; - - return count; -} - -static ssize_t vme_user_read(struct file *file, char __user *buf, size_t count, - loff_t *ppos) -{ - unsigned int minor = iminor(file_inode(file)); - ssize_t retval; - size_t image_size; - - if (minor == CONTROL_MINOR) - return 0; - - mutex_lock(&image[minor].mutex); - - /* XXX Do we *really* want this helper - we can use vme_*_get ? */ - image_size = vme_get_size(image[minor].resource); - - /* Ensure we are starting at a valid location */ - if ((*ppos < 0) || (*ppos > (image_size - 1))) { - mutex_unlock(&image[minor].mutex); - return 0; - } - - /* Ensure not reading past end of the image */ - if (*ppos + count > image_size) - count = image_size - *ppos; - - switch (type[minor]) { - case MASTER_MINOR: - retval = resource_to_user(minor, buf, count, ppos); - break; - case SLAVE_MINOR: - retval = buffer_to_user(minor, buf, count, ppos); - break; - default: - retval = -EINVAL; - } - - mutex_unlock(&image[minor].mutex); - if (retval > 0) - *ppos += retval; - - return retval; -} - -static ssize_t vme_user_write(struct file *file, const char __user *buf, - size_t count, loff_t *ppos) -{ - unsigned int minor = iminor(file_inode(file)); - ssize_t retval; - size_t image_size; - - if (minor == CONTROL_MINOR) - return 0; - - mutex_lock(&image[minor].mutex); - - image_size = vme_get_size(image[minor].resource); - - /* Ensure we are starting at a valid location */ - if ((*ppos < 0) || (*ppos > (image_size - 1))) { - mutex_unlock(&image[minor].mutex); - return 0; - } - - /* Ensure not reading past end of the image */ - if (*ppos + count > image_size) - count = image_size - *ppos; - - switch (type[minor]) { - case MASTER_MINOR: - retval = resource_from_user(minor, buf, count, ppos); - break; - case SLAVE_MINOR: - retval = buffer_from_user(minor, buf, count, ppos); - break; - default: - retval = -EINVAL; - } - - mutex_unlock(&image[minor].mutex); - - if (retval > 0) - *ppos += retval; - - return retval; -} - -static loff_t vme_user_llseek(struct file *file, loff_t off, int whence) -{ - unsigned int minor = iminor(file_inode(file)); - size_t image_size; - loff_t res; - - switch (type[minor]) { - case MASTER_MINOR: - case SLAVE_MINOR: - mutex_lock(&image[minor].mutex); - image_size = vme_get_size(image[minor].resource); - res = fixed_size_llseek(file, off, whence, image_size); - mutex_unlock(&image[minor].mutex); - return res; - } - - return -EINVAL; -} - -/* - * The ioctls provided by the old VME access method (the one at vmelinux.org) - * are most certainly wrong as the effectively push the registers layout - * through to user space. Given that the VME core can handle multiple bridges, - * with different register layouts this is most certainly not the way to go. - * - * We aren't using the structures defined in the Motorola driver either - these - * are also quite low level, however we should use the definitions that have - * already been defined. - */ -static int vme_user_ioctl(struct inode *inode, struct file *file, - unsigned int cmd, unsigned long arg) -{ - struct vme_master master; - struct vme_slave slave; - struct vme_irq_id irq_req; - unsigned long copied; - unsigned int minor = iminor(inode); - int retval; - dma_addr_t pci_addr; - void __user *argp = (void __user *)arg; - - switch (type[minor]) { - case CONTROL_MINOR: - switch (cmd) { - case VME_IRQ_GEN: - copied = copy_from_user(&irq_req, argp, - sizeof(irq_req)); - if (copied) { - pr_warn("Partial copy from userspace\n"); - return -EFAULT; - } - - return vme_irq_generate(vme_user_bridge, - irq_req.level, - irq_req.statid); - } - break; - case MASTER_MINOR: - switch (cmd) { - case VME_GET_MASTER: - memset(&master, 0, sizeof(master)); - - /* XXX We do not want to push aspace, cycle and width - * to userspace as they are - */ - retval = vme_master_get(image[minor].resource, - &master.enable, - &master.vme_addr, - &master.size, &master.aspace, - &master.cycle, &master.dwidth); - - copied = copy_to_user(argp, &master, - sizeof(master)); - if (copied) { - pr_warn("Partial copy to userspace\n"); - return -EFAULT; - } - - return retval; - - case VME_SET_MASTER: - - if (image[minor].mmap_count != 0) { - pr_warn("Can't adjust mapped window\n"); - return -EPERM; - } - - copied = copy_from_user(&master, argp, sizeof(master)); - if (copied) { - pr_warn("Partial copy from userspace\n"); - return -EFAULT; - } - - /* XXX We do not want to push aspace, cycle and width - * to userspace as they are - */ - return vme_master_set(image[minor].resource, - master.enable, master.vme_addr, master.size, - master.aspace, master.cycle, master.dwidth); - - break; - } - break; - case SLAVE_MINOR: - switch (cmd) { - case VME_GET_SLAVE: - memset(&slave, 0, sizeof(slave)); - - /* XXX We do not want to push aspace, cycle and width - * to userspace as they are - */ - retval = vme_slave_get(image[minor].resource, - &slave.enable, &slave.vme_addr, - &slave.size, &pci_addr, - &slave.aspace, &slave.cycle); - - copied = copy_to_user(argp, &slave, - sizeof(slave)); - if (copied) { - pr_warn("Partial copy to userspace\n"); - return -EFAULT; - } - - return retval; - - case VME_SET_SLAVE: - - copied = copy_from_user(&slave, argp, sizeof(slave)); - if (copied) { - pr_warn("Partial copy from userspace\n"); - return -EFAULT; - } - - /* XXX We do not want to push aspace, cycle and width - * to userspace as they are - */ - return vme_slave_set(image[minor].resource, - slave.enable, slave.vme_addr, slave.size, - image[minor].pci_buf, slave.aspace, - slave.cycle); - - break; - } - break; - } - - return -EINVAL; -} - -static long -vme_user_unlocked_ioctl(struct file *file, unsigned int cmd, unsigned long arg) -{ - int ret; - struct inode *inode = file_inode(file); - unsigned int minor = iminor(inode); - - mutex_lock(&image[minor].mutex); - ret = vme_user_ioctl(inode, file, cmd, arg); - mutex_unlock(&image[minor].mutex); - - return ret; -} - -static void vme_user_vm_open(struct vm_area_struct *vma) -{ - struct vme_user_vma_priv *vma_priv = vma->vm_private_data; - - refcount_inc(&vma_priv->refcnt); -} - -static void vme_user_vm_close(struct vm_area_struct *vma) -{ - struct vme_user_vma_priv *vma_priv = vma->vm_private_data; - unsigned int minor = vma_priv->minor; - - if (!refcount_dec_and_test(&vma_priv->refcnt)) - return; - - mutex_lock(&image[minor].mutex); - image[minor].mmap_count--; - mutex_unlock(&image[minor].mutex); - - kfree(vma_priv); -} - -static int vme_user_vm_mapped(unsigned long start, unsigned long end, pgoff_t pgoff, - const struct file *file, void **vm_private_data) -{ - const unsigned int minor = iminor(file_inode(file)); - struct vme_user_vma_priv *vma_priv; - - mutex_lock(&image[minor].mutex); - - vma_priv = kmalloc_obj(*vma_priv); - if (!vma_priv) { - mutex_unlock(&image[minor].mutex); - return -ENOMEM; - } - - vma_priv->minor = minor; - refcount_set(&vma_priv->refcnt, 1); - *vm_private_data = vma_priv; - image[minor].mmap_count++; - - mutex_unlock(&image[minor].mutex); - return 0; -} - -static const struct vm_operations_struct vme_user_vm_ops = { - .mapped = vme_user_vm_mapped, - .open = vme_user_vm_open, - .close = vme_user_vm_close, -}; - -static int vme_user_master_mmap_prepare(unsigned int minor, - struct vm_area_desc *desc) -{ - int err; - - mutex_lock(&image[minor].mutex); - - err = vme_master_mmap_prepare(image[minor].resource, desc); - if (!err) - desc->vm_ops = &vme_user_vm_ops; - - mutex_unlock(&image[minor].mutex); - return err; -} - -static int vme_user_mmap_prepare(struct vm_area_desc *desc) -{ - const struct file *file = desc->file; - const unsigned int minor = iminor(file_inode(file)); - - if (type[minor] == MASTER_MINOR) - return vme_user_master_mmap_prepare(minor, desc); - - return -ENODEV; -} - -static const struct file_operations vme_user_fops = { - .read = vme_user_read, - .write = vme_user_write, - .llseek = vme_user_llseek, - .unlocked_ioctl = vme_user_unlocked_ioctl, - .compat_ioctl = compat_ptr_ioctl, - .mmap_prepare = vme_user_mmap_prepare, -}; - -static int vme_user_match(struct vme_dev *vdev) -{ - int i; - - int cur_bus = vme_bus_num(vdev); - int cur_slot = vme_slot_num(vdev); - - for (i = 0; i < bus_num; i++) - if ((cur_bus == bus[i]) && (cur_slot == vdev->num)) - return 1; - - return 0; -} - -/* - * In this simple access driver, the old behaviour is being preserved as much - * as practical. We will therefore reserve the buffers and request the images - * here so that we don't have to do it later. - */ -static int vme_user_probe(struct vme_dev *vdev) -{ - int i, err; - char *name; - - /* Save pointer to the bridge device */ - if (vme_user_bridge) { - dev_err(&vdev->dev, "Driver can only be loaded for 1 device\n"); - err = -EINVAL; - goto err_dev; - } - vme_user_bridge = vdev; - - /* Initialise descriptors */ - for (i = 0; i < VME_DEVS; i++) { - image[i].kern_buf = NULL; - image[i].pci_buf = 0; - mutex_init(&image[i].mutex); - image[i].device = NULL; - image[i].resource = NULL; - } - - /* Assign major and minor numbers for the driver */ - err = register_chrdev_region(MKDEV(VME_MAJOR, 0), VME_DEVS, DRIVER_NAME); - if (err) { - dev_warn(&vdev->dev, "Error getting Major Number %d for driver.\n", - VME_MAJOR); - goto err_region; - } - - /* Register the driver as a char device */ - vme_user_cdev = cdev_alloc(); - if (!vme_user_cdev) { - err = -ENOMEM; - goto err_char; - } - vme_user_cdev->ops = &vme_user_fops; - vme_user_cdev->owner = THIS_MODULE; - err = cdev_add(vme_user_cdev, MKDEV(VME_MAJOR, 0), VME_DEVS); - if (err) - goto err_class; - - /* Request slave resources and allocate buffers (128kB wide) */ - for (i = SLAVE_MINOR; i < (SLAVE_MAX + 1); i++) { - /* XXX Need to properly request attributes */ - /* For ca91cx42 bridge there are only two slave windows - * supporting A16 addressing, so we request A24 supported - * by all windows. - */ - image[i].resource = vme_slave_request(vme_user_bridge, - VME_A24, VME_SCT); - if (!image[i].resource) { - dev_warn(&vdev->dev, - "Unable to allocate slave resource\n"); - err = -ENOMEM; - goto err_slave; - } - image[i].size_buf = PCI_BUF_SIZE; - image[i].kern_buf = vme_alloc_consistent(image[i].resource, - image[i].size_buf, - &image[i].pci_buf); - if (!image[i].kern_buf) { - dev_warn(&vdev->dev, - "Unable to allocate memory for buffer\n"); - image[i].pci_buf = 0; - vme_slave_free(image[i].resource); - err = -ENOMEM; - goto err_slave; - } - } - - /* - * Request master resources allocate page sized buffers for small - * reads and writes - */ - for (i = MASTER_MINOR; i < (MASTER_MAX + 1); i++) { - /* XXX Need to properly request attributes */ - image[i].resource = vme_master_request(vme_user_bridge, - VME_A32, VME_SCT, - VME_D32); - if (!image[i].resource) { - dev_warn(&vdev->dev, - "Unable to allocate master resource\n"); - err = -ENOMEM; - goto err_master; - } - image[i].size_buf = PCI_BUF_SIZE; - image[i].kern_buf = kmalloc(image[i].size_buf, GFP_KERNEL); - if (!image[i].kern_buf) { - err = -ENOMEM; - vme_master_free(image[i].resource); - goto err_master; - } - } - - /* Create sysfs entries - on udev systems this creates the dev files */ - err = class_register(&vme_user_sysfs_class); - if (err) { - dev_err(&vdev->dev, "Error creating vme_user class.\n"); - goto err_master; - } - - /* Add sysfs Entries */ - for (i = 0; i < VME_DEVS; i++) { - int num; - - switch (type[i]) { - case MASTER_MINOR: - name = "bus/vme/m%d"; - break; - case CONTROL_MINOR: - name = "bus/vme/ctl"; - break; - case SLAVE_MINOR: - name = "bus/vme/s%d"; - break; - default: - err = -EINVAL; - goto err_sysfs; - } - - num = (type[i] == SLAVE_MINOR) ? i - (MASTER_MAX + 1) : i; - image[i].device = device_create(&vme_user_sysfs_class, NULL, - MKDEV(VME_MAJOR, i), NULL, - name, num); - if (IS_ERR(image[i].device)) { - dev_info(&vdev->dev, "Error creating sysfs device\n"); - err = PTR_ERR(image[i].device); - goto err_sysfs; - } - } - - return 0; - -err_sysfs: - while (i > 0) { - i--; - device_destroy(&vme_user_sysfs_class, MKDEV(VME_MAJOR, i)); - } - class_unregister(&vme_user_sysfs_class); - - /* Ensure counter set correctly to unalloc all master windows */ - i = MASTER_MAX + 1; -err_master: - while (i > MASTER_MINOR) { - i--; - kfree(image[i].kern_buf); - vme_master_free(image[i].resource); - } - - /* - * Ensure counter set correctly to unalloc all slave windows and buffers - */ - i = SLAVE_MAX + 1; -err_slave: - while (i > SLAVE_MINOR) { - i--; - vme_free_consistent(image[i].resource, image[i].size_buf, - image[i].kern_buf, image[i].pci_buf); - vme_slave_free(image[i].resource); - } -err_class: - cdev_del(vme_user_cdev); -err_char: - unregister_chrdev_region(MKDEV(VME_MAJOR, 0), VME_DEVS); -err_region: -err_dev: - return err; -} - -static void vme_user_remove(struct vme_dev *vdev) -{ - int i; - - /* Remove sysfs Entries */ - for (i = 0; i < VME_DEVS; i++) { - mutex_destroy(&image[i].mutex); - device_destroy(&vme_user_sysfs_class, MKDEV(VME_MAJOR, i)); - } - class_unregister(&vme_user_sysfs_class); - - for (i = MASTER_MINOR; i < (MASTER_MAX + 1); i++) { - kfree(image[i].kern_buf); - vme_master_free(image[i].resource); - } - - for (i = SLAVE_MINOR; i < (SLAVE_MAX + 1); i++) { - vme_slave_set(image[i].resource, 0, 0, 0, 0, VME_A32, 0); - vme_free_consistent(image[i].resource, image[i].size_buf, - image[i].kern_buf, image[i].pci_buf); - vme_slave_free(image[i].resource); - } - - /* Unregister device driver */ - cdev_del(vme_user_cdev); - - /* Unregister the major and minor device numbers */ - unregister_chrdev_region(MKDEV(VME_MAJOR, 0), VME_DEVS); -} - -static struct vme_driver vme_user_driver = { - .name = DRIVER_NAME, - .match = vme_user_match, - .probe = vme_user_probe, - .remove = vme_user_remove, -}; - -static int __init vme_user_init(void) -{ - int retval = 0; - - pr_info("VME User Space Access Driver\n"); - - if (bus_num == 0) { - pr_err("No cards, skipping registration\n"); - retval = -ENODEV; - goto err_nocard; - } - - /* Let's start by supporting one bus, we can support more than one - * in future revisions if that ever becomes necessary. - */ - if (bus_num > VME_USER_BUS_MAX) { - pr_err("Driver only able to handle %d buses\n", - VME_USER_BUS_MAX); - bus_num = VME_USER_BUS_MAX; - } - - /* - * Here we just register the maximum number of devices we can and - * leave vme_user_match() to allow only 1 to go through to probe(). - * This way, if we later want to allow multiple user access devices, - * we just change the code in vme_user_match(). - */ - retval = vme_register_driver(&vme_user_driver, VME_MAX_SLOTS); - if (retval) - goto err_reg; - - return retval; - -err_reg: -err_nocard: - return retval; -} - -static void __exit vme_user_exit(void) -{ - vme_unregister_driver(&vme_user_driver); -} - -MODULE_PARM_DESC(bus, "Enumeration of VMEbus to which the driver is connected"); -module_param_array(bus, int, &bus_num, 0000); - -MODULE_DESCRIPTION("VME User Space Access Driver"); -MODULE_AUTHOR("Martyn Welch "); -MODULE_LICENSE("GPL"); - -module_init(vme_user_init); -module_exit(vme_user_exit); diff --git a/drivers/staging/vme_user/vme_user.h b/drivers/staging/vme_user/vme_user.h deleted file mode 100644 index 9e010974351dce..00000000000000 --- a/drivers/staging/vme_user/vme_user.h +++ /dev/null @@ -1,47 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0 */ -#ifndef _VME_USER_H_ -#define _VME_USER_H_ - -#define VME_USER_BUS_MAX 1 - -/* - * VMEbus Master Window Configuration Structure - */ -struct vme_master { - __u32 enable; /* State of Window */ - __u64 vme_addr; /* Starting Address on the VMEbus */ - __u64 size; /* Window Size */ - __u32 aspace; /* Address Space */ - __u32 cycle; /* Cycle properties */ - __u32 dwidth; /* Maximum Data Width */ -} __packed; - -/* - * IOCTL Commands and structures - */ - -/* Magic number for use in ioctls */ -#define VME_IOC_MAGIC 0xAE - -/* VMEbus Slave Window Configuration Structure */ -struct vme_slave { - __u32 enable; /* State of Window */ - __u64 vme_addr; /* Starting Address on the VMEbus */ - __u64 size; /* Window Size */ - __u32 aspace; /* Address Space */ - __u32 cycle; /* Cycle properties */ -} __packed; - -struct vme_irq_id { - __u8 level; - __u8 statid; -}; - -#define VME_GET_SLAVE _IOR(VME_IOC_MAGIC, 1, struct vme_slave) -#define VME_SET_SLAVE _IOW(VME_IOC_MAGIC, 2, struct vme_slave) -#define VME_GET_MASTER _IOR(VME_IOC_MAGIC, 3, struct vme_master) -#define VME_SET_MASTER _IOW(VME_IOC_MAGIC, 4, struct vme_master) -#define VME_IRQ_GEN _IOW(VME_IOC_MAGIC, 5, struct vme_irq_id) - -#endif /* _VME_USER_H_ */ - diff --git a/drivers/target/iscsi/iscsi_target.c b/drivers/target/iscsi/iscsi_target.c index 124ff269b8e759..2b4956f46c132e 100644 --- a/drivers/target/iscsi/iscsi_target.c +++ b/drivers/target/iscsi/iscsi_target.c @@ -1518,25 +1518,6 @@ __iscsit_check_dataout_hdr(struct iscsit_conn *conn, void *buf, if (hdr->flags & ISCSI_FLAG_CMD_FINAL) iscsit_stop_dataout_timer(cmd); - return iscsit_dump_data_payload(conn, payload_length, 1); - } - } else { - /* - * For the normal solicited data path: - * - * Check for a delayed TASK_ABORTED status and dump any - * incoming data out payload if one exists. Also, when the - * ISCSI_FLAG_CMD_FINAL is set to denote the end of the current - * data out sequence, we decrement outstanding_r2ts. Once - * outstanding_r2ts reaches zero, go ahead and send the delayed - * TASK_ABORTED status. - */ - if (se_cmd->transport_state & CMD_T_ABORTED) { - if (hdr->flags & ISCSI_FLAG_CMD_FINAL && - --cmd->outstanding_r2ts < 1) { - iscsit_stop_dataout_timer(cmd); - target_complete_cmd(se_cmd, SAM_STAT_TASK_ABORTED); - } return iscsit_dump_data_payload(conn, payload_length, 1); } @@ -4504,8 +4485,8 @@ int iscsit_close_session(struct iscsit_session *sess, bool can_sleep) /* * If any other processes are accessing this session pointer we must - * wait until they have completed. If we are in an interrupt (the - * time2retain handler) and contain and active session usage count we + * wait until they have completed. If we are the Time2Retain work + * (can_sleep is false) and contain and active session usage count we * restart the timer and exit. */ if (iscsit_check_session_usage_count(sess, can_sleep)) { @@ -4535,6 +4516,16 @@ int iscsit_close_session(struct iscsit_session *sess, bool can_sleep) sess->sess_ops = NULL; spin_unlock_bh(&se_tpg->session_lock); + /* + * Neither the Time2Retain timer nor its work may outlive the session; + * a work never runs twice at once, so this work finds a queued one. + */ + timer_delete_sync(&sess->time2retain_timer); + if (can_sleep) + cancel_work_sync(&sess->time2retain_work); + else + cancel_work(&sess->time2retain_work); + kfree(sess); return 0; } diff --git a/drivers/target/iscsi/iscsi_target_erl0.c b/drivers/target/iscsi/iscsi_target_erl0.c index 24db6b07493e62..036ddc1002f6ca 100644 --- a/drivers/target/iscsi/iscsi_target_erl0.c +++ b/drivers/target/iscsi/iscsi_target_erl0.c @@ -741,15 +741,17 @@ int iscsit_check_post_dataout( } } -void iscsit_handle_time2retain_timeout(struct timer_list *t) +void iscsit_time2retain_work(struct work_struct *work) { - struct iscsit_session *sess = timer_container_of(sess, t, - time2retain_timer); + struct iscsit_session *sess = container_of(work, struct iscsit_session, + time2retain_work); struct iscsi_portal_group *tpg = sess->tpg; struct se_portal_group *se_tpg = &tpg->tpg_se_tpg; spin_lock_bh(&se_tpg->session_lock); - if (sess->time2retain_timer_flags & ISCSI_TF_STOP) { + /* A stop after the timer fired takes ->time2retain_fired back. */ + if (!atomic_xchg(&sess->time2retain_fired, 0) || + (sess->time2retain_timer_flags & ISCSI_TF_STOP)) { spin_unlock_bh(&se_tpg->session_lock); return; } @@ -769,6 +771,15 @@ void iscsit_handle_time2retain_timeout(struct timer_list *t) iscsit_close_session(sess, false); } +void iscsit_handle_time2retain_timeout(struct timer_list *t) +{ + struct iscsit_session *sess = timer_container_of(sess, t, + time2retain_timer); + + atomic_set(&sess->time2retain_fired, 1); + queue_work(system_dfl_wq, &sess->time2retain_work); +} + void iscsit_start_time2retain_handler(struct iscsit_session *sess) { int tpg_active; @@ -814,6 +825,7 @@ int iscsit_stop_time2retain_timer(struct iscsit_session *sess) timer_delete_sync(&sess->time2retain_timer); spin_lock(&se_tpg->session_lock); + atomic_set(&sess->time2retain_fired, 0); sess->time2retain_timer_flags &= ~ISCSI_TF_RUNNING; pr_debug("Stopped Time2Retain Timer for SID: %u\n", sess->sid); diff --git a/drivers/target/iscsi/iscsi_target_erl0.h b/drivers/target/iscsi/iscsi_target_erl0.h index 2a877d13977d24..f0e157b0a2f5c3 100644 --- a/drivers/target/iscsi/iscsi_target_erl0.h +++ b/drivers/target/iscsi/iscsi_target_erl0.h @@ -13,6 +13,7 @@ extern int iscsit_check_pre_dataout(struct iscsit_cmd *, unsigned char *); extern int iscsit_check_post_dataout(struct iscsit_cmd *, unsigned char *, u8); extern void iscsit_start_time2retain_handler(struct iscsit_session *); extern void iscsit_handle_time2retain_timeout(struct timer_list *t); +void iscsit_time2retain_work(struct work_struct *work); extern int iscsit_stop_time2retain_timer(struct iscsit_session *); extern void iscsit_connection_reinstatement_rcfr(struct iscsit_conn *); extern void iscsit_cause_connection_reinstatement(struct iscsit_conn *, int); diff --git a/drivers/target/iscsi/iscsi_target_erl1.c b/drivers/target/iscsi/iscsi_target_erl1.c index d8ca06e697d63f..44b851e4a602d8 100644 --- a/drivers/target/iscsi/iscsi_target_erl1.c +++ b/drivers/target/iscsi/iscsi_target_erl1.c @@ -908,8 +908,6 @@ int iscsit_execute_cmd(struct iscsit_cmd *cmd, int ooo) return 0; } spin_unlock_bh(&cmd->istate_lock); - if (cmd->se_cmd.transport_state & CMD_T_ABORTED) - return 0; return transport_send_check_condition_and_sense(se_cmd, cmd->sense_reason, 0); } @@ -927,9 +925,6 @@ int iscsit_execute_cmd(struct iscsit_cmd *cmd, int ooo) if (!(cmd->cmd_flags & ICF_NON_IMMEDIATE_UNSOLICITED_DATA)) { - if (cmd->se_cmd.transport_state & CMD_T_ABORTED) - return 0; - iscsit_set_dataout_sequence_values(cmd); conn->conn_transport->iscsit_get_dataout(conn, cmd, false); } @@ -942,9 +937,6 @@ int iscsit_execute_cmd(struct iscsit_cmd *cmd, int ooo) if ((cmd->data_direction == DMA_TO_DEVICE) && !(cmd->cmd_flags & ICF_NON_IMMEDIATE_UNSOLICITED_DATA)) { - if (cmd->se_cmd.transport_state & CMD_T_ABORTED) - return 0; - iscsit_set_unsolicited_dataout(cmd); } return target_submit(&cmd->se_cmd); diff --git a/drivers/target/iscsi/iscsi_target_login.c b/drivers/target/iscsi/iscsi_target_login.c index c282b6a7029684..fda04eb15d3a27 100644 --- a/drivers/target/iscsi/iscsi_target_login.c +++ b/drivers/target/iscsi/iscsi_target_login.c @@ -250,6 +250,7 @@ static int iscsi_login_zero_tsih_s1( timer_setup(&sess->time2retain_timer, iscsit_handle_time2retain_timeout, 0); + INIT_WORK(&sess->time2retain_work, iscsit_time2retain_work); ret = ida_alloc(&sess_ida, GFP_KERNEL); if (ret < 0) { diff --git a/drivers/target/iscsi/iscsi_target_nego.c b/drivers/target/iscsi/iscsi_target_nego.c index b03ed154ca34e9..ccd468e26fb925 100644 --- a/drivers/target/iscsi/iscsi_target_nego.c +++ b/drivers/target/iscsi/iscsi_target_nego.c @@ -982,9 +982,6 @@ static int iscsi_target_handle_csg_one(struct iscsit_conn *conn, struct iscsi_lo if (iscsi_target_check_first_request(conn, login) < 0) return -1; - if (iscsi_target_check_for_existing_instances(conn, login) < 0) - return -1; - ret = iscsi_encode_text_output( PHASE_OPERATIONAL|PHASE_DECLARATIVE, SENDER_TARGET, @@ -1008,6 +1005,9 @@ static int iscsi_target_handle_csg_one(struct iscsit_conn *conn, struct iscsi_lo return -1; } + if (iscsi_target_check_for_existing_instances(conn, login) < 0) + return -1; + if (!iscsi_check_negotiated_keys(conn->param_list)) if ((login_req->flags & ISCSI_FLAG_LOGIN_NEXT_STAGE3) && (login_req->flags & ISCSI_FLAG_LOGIN_TRANSIT)) diff --git a/drivers/target/target_core_alua.c b/drivers/target/target_core_alua.c index 140154d93c4308..17386c96de1333 100644 --- a/drivers/target/target_core_alua.c +++ b/drivers/target/target_core_alua.c @@ -1081,8 +1081,15 @@ int core_alua_do_port_transition( return -EINVAL; local_lu_gp_mem = l_dev->dev_alua_lu_gp_mem; + if (!local_lu_gp_mem) + return -ENODEV; + spin_lock(&local_lu_gp_mem->lu_gp_mem_lock); lu_gp = local_lu_gp_mem->lu_gp; + if (!lu_gp) { + spin_unlock(&local_lu_gp_mem->lu_gp_mem_lock); + return -ENODEV; + } atomic_inc(&lu_gp->lu_gp_ref_cnt); spin_unlock(&local_lu_gp_mem->lu_gp_mem_lock); /* diff --git a/drivers/target/target_core_configfs.c b/drivers/target/target_core_configfs.c index 2b19a956007b73..385b84bcbfb26e 100644 --- a/drivers/target/target_core_configfs.c +++ b/drivers/target/target_core_configfs.c @@ -2126,8 +2126,8 @@ static match_table_t tokens = { {Opt_initiator_sid, "initiator_sid=%s"}, {Opt_sa_res_key, "sa_res_key=%s"}, {Opt_res_holder, "res_holder=%d"}, - {Opt_res_type, "res_type=%d"}, - {Opt_res_scope, "res_scope=%d"}, + {Opt_res_type, "res_type=%x"}, + {Opt_res_scope, "res_scope=%x"}, {Opt_res_all_tg_pt, "res_all_tg_pt=%d"}, {Opt_mapped_lun, "mapped_lun=%u"}, {Opt_target_fabric, "target_fabric=%s"}, @@ -2229,13 +2229,13 @@ static ssize_t target_pr_res_aptpl_metadata_store(struct config_item *item, res_holder = arg; break; case Opt_res_type: - ret = match_int(args, &arg); + ret = match_hex(args, &arg); if (ret) goto out; type = (u8)arg; break; case Opt_res_scope: - ret = match_int(args, &arg); + ret = match_hex(args, &arg); if (ret) goto out; break; @@ -2547,6 +2547,14 @@ static ssize_t target_dev_alua_lu_gp_store(struct config_item *item, spin_lock(&lu_gp_mem->lu_gp_mem_lock); lu_gp = lu_gp_mem->lu_gp; + if (!lu_gp && !lu_gp_new) { + /* + * The LU group association has already been cleared, so + * there is nothing left to do. + */ + spin_unlock(&lu_gp_mem->lu_gp_mem_lock); + return count; + } if (lu_gp) { /* * Clearing an existing lu_gp association, and replacing diff --git a/drivers/target/target_core_fabric_lib.c b/drivers/target/target_core_fabric_lib.c index ad024009df56bb..ccfeba64518c28 100644 --- a/drivers/target/target_core_fabric_lib.c +++ b/drivers/target/target_core_fabric_lib.c @@ -372,10 +372,11 @@ static bool iscsi_parse_pr_out_transport_id( return false; } /* - * The registration code reads the ISID as a C string, - * and its first 8 bytes with get_unaligned_be64(), so - * require 8 bytes after the separator and a NUL inside - * the rest of the descriptor. + * The registration code reads the ISID as a C string, so + * require a NUL inside the rest of the descriptor. Keep the + * existing minimum of 8 bytes after the separator: a valid + * ISID is twelve hex digits, and target_isid_to_bin() falls + * back to the first eight characters of anything else. */ if (buf + tid_len - p < 8 || !memchr(p, '\0', buf + tid_len - p)) { pr_err("Incomplete or unterminated ISID in iSCSI Initiator port TransportID\n"); diff --git a/drivers/target/target_core_pr.c b/drivers/target/target_core_pr.c index ca1a2802aa228c..0f2ff9d42150ba 100644 --- a/drivers/target/target_core_pr.c +++ b/drivers/target/target_core_pr.c @@ -19,6 +19,7 @@ #include #include #include +#include #include #include @@ -30,6 +31,28 @@ #include "target_core_pr.h" #include "target_core_ua.h" +/* + * lio_sess_get_initiator_sid() prints the six ISID bytes as twelve hex + * digits, and iSCSI TransportIDs carry the same digits. Convert all six + * bytes: reading the first eight digits as a big-endian u64 keeps only the + * first four ISID bytes, so two sessions of one initiator that differ only + * in the qualifier, the usual case, would compare equal. Text in any other + * format keeps the old conversion of its first eight characters, without + * reading past the end of a shorter string. + */ +u64 target_isid_to_bin(const char *isid) +{ + u8 bin[6]; + char raw[8] = {}; + + if (strnlen(isid, 2 * sizeof(bin) + 1) == 2 * sizeof(bin) && + !hex2bin(bin, isid, sizeof(bin))) + return get_unaligned_be48(bin); + + memcpy(raw, isid, strnlen(isid, sizeof(raw))); + return get_unaligned_be64(raw); +} + /* * Used for Specify Initiator Ports Capable Bit (SPEC_I_PT) */ @@ -285,7 +308,11 @@ target_scsi2_reservation_reserve(struct se_cmd *cmd) dev->reservation_holder = sess; dev->dev_reservation_flags |= DRF_SPC2_RESERVATIONS; - if (sess->sess_bin_isid != 0) { + /* + * An all-zero ISID converts to 0, so test whether the fabric has + * ISIDs rather than the value. + */ + if (tpg->se_tpg_tfo->sess_get_initiator_sid) { dev->dev_res_bin_isid = sess->sess_bin_isid; dev->dev_reservation_flags |= DRF_SPC2_RESERVATIONS_WITH_ISID; } @@ -323,7 +350,18 @@ static int core_scsi3_pr_seq_non_holder(struct se_cmd *cmd, u32 pr_reg_type, * RESERVATION CONFLICT on some CDBs */ if (isid_mismatch) { - registered_nexus = 0; + struct t10_pr_registration *pr_reg; + + /* + * Another I_T nexus of the holder's initiator. DEF_PR_REG_ACTIVE + * is shared by all of its sessions, so look for a registration + * made through this one. + */ + pr_reg = core_scsi3_locate_pr_reg(cmd->se_dev, nacl, se_sess); + if (pr_reg) { + registered_nexus = 1; + core_scsi3_put_pr_reg(pr_reg); + } } else { struct se_dev_entry *se_deve; @@ -674,7 +712,7 @@ static struct t10_pr_registration *__core_scsi3_do_alloc_registration( * save it to the registration now. */ if (isid != NULL) { - pr_reg->pr_reg_bin_isid = get_unaligned_be64(isid); + pr_reg->pr_reg_bin_isid = target_isid_to_bin(isid); snprintf(pr_reg->pr_reg_isid, PR_REG_ISID_LEN, "%s", isid); pr_reg->isid_present_at_reg = 1; } @@ -866,7 +904,7 @@ int core_scsi3_alloc_aptpl_registration( * SCSI Initiator Port, restore it now. */ if (isid != NULL) { - pr_reg->pr_reg_bin_isid = get_unaligned_be64(isid); + pr_reg->pr_reg_bin_isid = target_isid_to_bin(isid); snprintf(pr_reg->pr_reg_isid, PR_REG_ISID_LEN, "%s", isid); pr_reg->isid_present_at_reg = 1; } diff --git a/drivers/target/target_core_pr.h b/drivers/target/target_core_pr.h index b793c99637ab91..4debfe4be4d698 100644 --- a/drivers/target/target_core_pr.h +++ b/drivers/target/target_core_pr.h @@ -72,6 +72,7 @@ extern void core_scsi3_free_pr_reg_from_nacl(struct se_device *, struct se_node_acl *); extern void core_scsi3_free_all_registrations(struct se_device *); extern unsigned char *core_scsi3_pr_dump_type(int); +u64 target_isid_to_bin(const char *isid); extern sense_reason_t target_scsi3_emulate_pr_in(struct se_cmd *); extern sense_reason_t target_scsi3_emulate_pr_out(struct se_cmd *); diff --git a/drivers/target/target_core_sbc.c b/drivers/target/target_core_sbc.c index 21f5cb86d70c00..560e62cef7dd3a 100644 --- a/drivers/target/target_core_sbc.c +++ b/drivers/target/target_core_sbc.c @@ -721,6 +721,12 @@ sbc_check_prot(struct se_device *dev, struct se_cmd *cmd, unsigned char protect, if (sbc_set_prot_op_checks(protect, fabric_prot, pi_prot_type, is_write, cmd)) return TCM_INVALID_CDB_FIELD; + if (!sectors) { + cmd->prot_op = TARGET_PROT_NORMAL; + cmd->prot_checks = 0; + pi_prot_type = TARGET_DIF_TYPE0_PROT; + } + cmd->prot_type = pi_prot_type; cmd->prot_length = dev->prot_length * sectors; diff --git a/drivers/target/target_core_transport.c b/drivers/target/target_core_transport.c index 927861c30afc44..4629c9343bb6c3 100644 --- a/drivers/target/target_core_transport.c +++ b/drivers/target/target_core_transport.c @@ -419,7 +419,7 @@ void __transport_register_session( memset(&buf[0], 0, PR_REG_ISID_LEN); se_tpg->se_tpg_tfo->sess_get_initiator_sid(se_sess, &buf[0], PR_REG_ISID_LEN); - se_sess->sess_bin_isid = get_unaligned_be64(&buf[0]); + se_sess->sess_bin_isid = target_isid_to_bin(buf); } spin_lock_irqsave(&se_nacl->nacl_sess_lock, flags); diff --git a/drivers/thermal/intel/int340x_thermal/processor_thermal_device.h b/drivers/thermal/intel/int340x_thermal/processor_thermal_device.h index b79937a386ec0f..87d8ff9c717352 100644 --- a/drivers/thermal/intel/int340x_thermal/processor_thermal_device.h +++ b/drivers/thermal/intel/int340x_thermal/processor_thermal_device.h @@ -27,8 +27,7 @@ #define PCI_DEVICE_ID_INTEL_JSL_THERMAL 0x4E03 #define PCI_DEVICE_ID_INTEL_LNLM_THERMAL 0x641D #define PCI_DEVICE_ID_INTEL_MTLP_THERMAL 0x7D03 -#define PCI_DEVICE_ID_INTEL_NVL_H_THERMAL 0xD703 -#define PCI_DEVICE_ID_INTEL_NVL_S_THERMAL 0xAD03 +#define PCI_DEVICE_ID_INTEL_NVL_THERMAL 0xD703 #define PCI_DEVICE_ID_INTEL_RPL_THERMAL 0xA71D #define PCI_DEVICE_ID_INTEL_SKL_THERMAL 0x1903 #define PCI_DEVICE_ID_INTEL_TGL_THERMAL 0x9A03 diff --git a/drivers/thermal/intel/int340x_thermal/processor_thermal_device_pci.c b/drivers/thermal/intel/int340x_thermal/processor_thermal_device_pci.c index 7d6fee59ade202..f218ee247ab485 100644 --- a/drivers/thermal/intel/int340x_thermal/processor_thermal_device_pci.c +++ b/drivers/thermal/intel/int340x_thermal/processor_thermal_device_pci.c @@ -501,12 +501,7 @@ static const struct pci_device_id proc_thermal_pci_ids[] = { PROC_THERMAL_FEATURE_DVFS | PROC_THERMAL_FEATURE_WT_HINT | PROC_THERMAL_FEATURE_POWER_FLOOR | PROC_THERMAL_FEATURE_PTC | PROC_THERMAL_FEATURE_SOC_POWER_SLIDER) }, - { PCI_DEVICE_DATA(INTEL, NVL_H_THERMAL, PROC_THERMAL_FEATURE_RAPL | - PROC_THERMAL_FEATURE_DLVR | PROC_THERMAL_FEATURE_DVFS | - PROC_THERMAL_FEATURE_MSI_SUPPORT | PROC_THERMAL_FEATURE_WT_HINT | - PROC_THERMAL_FEATURE_POWER_FLOOR | PROC_THERMAL_FEATURE_PTC | - PROC_THERMAL_FEATURE_SOC_POWER_SLIDER) }, - { PCI_DEVICE_DATA(INTEL, NVL_S_THERMAL, PROC_THERMAL_FEATURE_RAPL | + { PCI_DEVICE_DATA(INTEL, NVL_THERMAL, PROC_THERMAL_FEATURE_RAPL | PROC_THERMAL_FEATURE_DLVR | PROC_THERMAL_FEATURE_DVFS | PROC_THERMAL_FEATURE_MSI_SUPPORT | PROC_THERMAL_FEATURE_WT_HINT | PROC_THERMAL_FEATURE_POWER_FLOOR | PROC_THERMAL_FEATURE_PTC | diff --git a/drivers/thermal/intel/int340x_thermal/processor_thermal_rfim.c b/drivers/thermal/intel/int340x_thermal/processor_thermal_rfim.c index 96279756177f67..1832f13634d857 100644 --- a/drivers/thermal/intel/int340x_thermal/processor_thermal_rfim.c +++ b/drivers/thermal/intel/int340x_thermal/processor_thermal_rfim.c @@ -472,8 +472,7 @@ int proc_thermal_rfim_add(struct pci_dev *pdev, struct proc_thermal_device *proc dlvr_mmio_regs_table = lnl_dlvr_mmio_regs; dlvr_mapping = lnl_dlvr_mapping; break; - case PCI_DEVICE_ID_INTEL_NVL_H_THERMAL: - case PCI_DEVICE_ID_INTEL_NVL_S_THERMAL: + case PCI_DEVICE_ID_INTEL_NVL_THERMAL: dlvr_mmio_regs_table = nvl_dlvr_mmio_regs; ddr_data_rate_reg = &nvl_ddr_data_rate_reg; break; diff --git a/drivers/thermal/thermal_sysfs.c b/drivers/thermal/thermal_sysfs.c index 47daba943a7644..0c2313c794272d 100644 --- a/drivers/thermal/thermal_sysfs.c +++ b/drivers/thermal/thermal_sysfs.c @@ -258,6 +258,8 @@ sustainable_power_show(struct device *dev, struct device_attribute *devattr, { struct thermal_zone_device *tz = to_thermal_zone(dev); + guard(thermal_zone)(tz); + if (tz->tzp) return sysfs_emit(buf, "%u\n", tz->tzp->sustainable_power); else @@ -271,6 +273,8 @@ sustainable_power_store(struct device *dev, struct device_attribute *devattr, struct thermal_zone_device *tz = to_thermal_zone(dev); u32 sustainable_power; + guard(thermal_zone)(tz); + if (!tz->tzp) return -EIO; @@ -289,6 +293,8 @@ sustainable_power_store(struct device *dev, struct device_attribute *devattr, { \ struct thermal_zone_device *tz = to_thermal_zone(dev); \ \ + guard(thermal_zone)(tz); \ + \ if (!tz->tzp) \ return -EIO; \ \ @@ -302,6 +308,8 @@ sustainable_power_store(struct device *dev, struct device_attribute *devattr, struct thermal_zone_device *tz = to_thermal_zone(dev); \ s32 value; \ \ + guard(thermal_zone)(tz); \ + \ if (!tz->tzp) \ return -EIO; \ \ diff --git a/drivers/thunderbolt/stream.c b/drivers/thunderbolt/stream.c index 4f9a57b77bfa28..c9e1987a69242d 100644 --- a/drivers/thunderbolt/stream.c +++ b/drivers/thunderbolt/stream.c @@ -683,6 +683,12 @@ static int tbstream_dev_start(struct tbstream_dev *sdev) err_stop: tb_ring_stop(sdev->rx_ring.ring); tb_ring_stop(sdev->tx_ring.ring); + tb_xdomain_disable_paths(xd, sdev->out_hopid, + sdev->tx_ring.ring->hop, + sdev->in_hopid, + sdev->rx_ring.ring->hop); + if (sdev->rx_ring.frames) + tbstream_ring_free(&sdev->rx_ring); err_free_rx: tb_ring_free(sdev->rx_ring.ring); err_free_tx_buffers: diff --git a/drivers/thunderbolt/tb.h b/drivers/thunderbolt/tb.h index e86845762e226c..8ed373e94b652f 100644 --- a/drivers/thunderbolt/tb.h +++ b/drivers/thunderbolt/tb.h @@ -314,6 +314,7 @@ struct tb_port { * @can_offline: Does the port have necessary platform support to move * it into offline mode and back * @offline: The port is currently in offline mode + * @component_added: The port was added to the component framework * @margining: Pointer to margining structure if enabled */ struct usb4_port { @@ -321,6 +322,7 @@ struct usb4_port { struct tb_port *port; bool can_offline; bool offline; + bool component_added; #ifdef CONFIG_USB4_DEBUGFS_MARGINING struct tb_margining *margining; #endif diff --git a/drivers/thunderbolt/usb4_port.c b/drivers/thunderbolt/usb4_port.c index 890de530debc1f..7582acadf37cfa 100644 --- a/drivers/thunderbolt/usb4_port.c +++ b/drivers/thunderbolt/usb4_port.c @@ -320,11 +320,12 @@ struct usb4_port *usb4_port_device_add(struct tb_port *port) return ERR_PTR(ret); } + /* The port works fine without the component, so don't fail here */ ret = component_add(&usb4->dev, &connector_ops); - if (ret) { - dev_err(&usb4->dev, "failed to add component\n"); - device_unregister(&usb4->dev); - } + if (ret) + dev_err(&usb4->dev, "failed to add component: %d\n", ret); + else + usb4->component_added = true; if (!tb_is_upstream_port(port)) device_set_wakeup_capable(&usb4->dev, true); @@ -348,7 +349,8 @@ struct usb4_port *usb4_port_device_add(struct tb_port *port) */ void usb4_port_device_remove(struct usb4_port *usb4) { - component_del(&usb4->dev, &connector_ops); + if (usb4->component_added) + component_del(&usb4->dev, &connector_ops); device_unregister(&usb4->dev); } diff --git a/drivers/thunderbolt/xdomain.c b/drivers/thunderbolt/xdomain.c index 45e26833c95307..0e9d507f9bbc03 100644 --- a/drivers/thunderbolt/xdomain.c +++ b/drivers/thunderbolt/xdomain.c @@ -509,8 +509,8 @@ tb_xdp_properties_changed_response(struct tb_ctl *ctl, u64 route, u8 sequence) memset(&res, 0, sizeof(res)); tb_xdp_fill_header(&res.hdr, route, sequence, - PROPERTIES_CHANGED_RESPONSE, sizeof(res)); - return __tb_xdomain_response(ctl, &res, sizeof(res), + PROPERTIES_CHANGED_RESPONSE, sizeof(res.hdr)); + return __tb_xdomain_response(ctl, &res.hdr, sizeof(res.hdr), TB_CFG_PKG_XDOMAIN_RESP); } @@ -1370,7 +1370,7 @@ static int tb_xdomain_get_uuid(struct tb_xdomain *xd) return -EAGAIN; } dev_dbg(&xd->dev, "failed to read remote UUID\n"); - return ret; + return ret != -EAGAIN ? ret : -ETIMEDOUT; } dev_dbg(&xd->dev, "got remote UUID %pUb\n", &uuid); @@ -1425,7 +1425,7 @@ static int tb_xdomain_get_link_status(struct tb_xdomain *xd) return -EAGAIN; } dev_dbg(&xd->dev, "failed to receive remote link status\n"); - return ret; + return ret != -EAGAIN ? ret : -ETIMEDOUT; } dev_dbg(&xd->dev, "remote link supports width %#x speed %#x\n", slw, sls); @@ -1472,7 +1472,7 @@ static int tb_xdomain_link_state_change(struct tb_xdomain *xd, return -EAGAIN; } dev_err(&xd->dev, "failed request link state change, aborting\n"); - return ret; + return ret != -EAGAIN ? ret : -ETIMEDOUT; } dev_dbg(&xd->dev, "received link state change response\n"); @@ -1564,7 +1564,7 @@ static int tb_xdomain_get_properties(struct tb_xdomain *xd) dev_err(&xd->dev, "failed read XDomain properties from %pUb\n", xd->remote_uuid); - return ret; + return ret != -EAGAIN ? ret : -ETIMEDOUT; } mutex_lock(&xd->lock); diff --git a/drivers/tty/serial/8250/8250_exar.c b/drivers/tty/serial/8250/8250_exar.c index 2737a09cf8be19..42e55a8f8c69be 100644 --- a/drivers/tty/serial/8250/8250_exar.c +++ b/drivers/tty/serial/8250/8250_exar.c @@ -1181,7 +1181,7 @@ static int xr17v35x_register_gpio(struct exar8250 *priv, struct pci_dev *pcidev, static void xr17v35x_unregister_gpio(struct exar8250 *priv) { - if (priv->gpio) { + if (!IS_ERR_OR_NULL(priv->gpio)) { __xr17v35x_unregister_gpio(priv->gpio); priv->gpio = NULL; } diff --git a/drivers/tty/serial/8250/8250_hp300.c b/drivers/tty/serial/8250/8250_hp300.c index e9599c5c2feada..68ce5972c296b3 100644 --- a/drivers/tty/serial/8250/8250_hp300.c +++ b/drivers/tty/serial/8250/8250_hp300.c @@ -34,29 +34,6 @@ struct hp300_port { static struct hp300_port *hp300_ports; #endif -#ifdef CONFIG_HPDCA - -static int hpdca_init_one(struct dio_dev *d, - const struct dio_device_id *ent); -static void hpdca_remove_one(struct dio_dev *d); - -static struct dio_device_id hpdca_dio_tbl[] = { - { DIO_ID_DCA0 }, - { DIO_ID_DCA0REM }, - { DIO_ID_DCA1 }, - { DIO_ID_DCA1REM }, - { 0 } -}; - -static struct dio_driver hpdca_driver = { - .name = "hpdca", - .id_table = hpdca_dio_tbl, - .probe = hpdca_init_one, - .remove = hpdca_remove_one, -}; - -#endif - static unsigned int num_ports; extern int hp300_uart_scode; @@ -197,6 +174,32 @@ static int hpdca_init_one(struct dio_dev *d, return 0; } + +static void hpdca_remove_one(struct dio_dev *d) +{ + struct uart_8250_port *uport = dio_get_drvdata(d); + + if (d->resource.start) { + /* Disable board-interrupts */ + out_8(d->resource.start + DIO_VIRADDRBASE + DCA_IC, 0); + } + serial8250_unregister_port(uport); +} + +static struct dio_device_id hpdca_dio_tbl[] = { + { DIO_ID_DCA0 }, + { DIO_ID_DCA0REM }, + { DIO_ID_DCA1 }, + { DIO_ID_DCA1REM }, + { 0 } +}; + +static struct dio_driver hpdca_driver = { + .name = "hpdca", + .id_table = hpdca_dio_tbl, + .probe = hpdca_init_one, + .remove = hpdca_remove_one, +}; #endif static int __init hp300_8250_init(void) @@ -280,19 +283,6 @@ static int __init hp300_8250_init(void) return 0; } -#ifdef CONFIG_HPDCA -static void hpdca_remove_one(struct dio_dev *d) -{ - struct uart_8250_port *uport = dio_get_drvdata(d); - - if (d->resource.start) { - /* Disable board-interrupts */ - out_8(d->resource.start + DIO_VIRADDRBASE + DCA_IC, 0); - } - serial8250_unregister_port(uport); -} -#endif - static void __exit hp300_8250_exit(void) { #ifdef CONFIG_HPAPCI diff --git a/drivers/tty/serial/8250/8250_lpss.c b/drivers/tty/serial/8250/8250_lpss.c index f94a54cc57ca93..fc9ac24340e6f1 100644 --- a/drivers/tty/serial/8250/8250_lpss.c +++ b/drivers/tty/serial/8250/8250_lpss.c @@ -83,6 +83,9 @@ static void byt_set_termios(struct uart_port *p, struct ktermios *termios, /* Gracefully handle the B0 case: fall back to B9600 */ fuart = fuart ? fuart : 9600 * 16; + /* Fuart <= Fref: leave it to the core to refuse a higher baud rate */ + fuart = min(fuart, fref); + /* Get Fuart closer to Fref */ fuart *= rounddown_pow_of_two(fref / fuart); diff --git a/drivers/tty/serial/8250/8250_mxpcie.c b/drivers/tty/serial/8250/8250_mxpcie.c index a4e45e3923ae7c..0a3fb63991c1ca 100644 --- a/drivers/tty/serial/8250/8250_mxpcie.c +++ b/drivers/tty/serial/8250/8250_mxpcie.c @@ -412,7 +412,7 @@ static int mxpcie8250_handle_irq(struct uart_port *port) static void mxpcie8250_software_break_ctl(struct uart_port *port, int break_state) { struct uart_8250_port *up = up_to_u8250p(port); - struct tty_struct *tty = port->state->port.tty; + struct tty_struct *tty; unsigned int baud, quot; u8 sfr, tx_byte = 0x01; @@ -439,9 +439,14 @@ static void mxpcie8250_software_break_ctl(struct uart_port *port, int break_stat serial_out(up, UART_FCR, UART_FCR_CLEAR_XMIT); - baud = tty_get_baud_rate(tty); - quot = uart_get_divisor(port, baud); - serial8250_do_set_divisor(port, baud, quot); + /* A hangup during the break detaches the tty */ + tty = tty_port_tty_get(&port->state->port); + if (tty) { + baud = tty_get_baud_rate(tty); + quot = uart_get_divisor(port, baud); + serial8250_do_set_divisor(port, baud, quot); + tty_kref_put(tty); + } serial_out(up, UART_LCR, up->lcr); } } diff --git a/drivers/tty/serial/fsl_lpuart.c b/drivers/tty/serial/fsl_lpuart.c index 6ccc6a8b653b05..cd2575a3aef74c 100644 --- a/drivers/tty/serial/fsl_lpuart.c +++ b/drivers/tty/serial/fsl_lpuart.c @@ -3113,8 +3113,14 @@ static int lpuart_resume_noirq(struct device *dev) /* check whether lpuart wakeup was triggered */ wake_active = stat & (UARTSTAT_RDRF | UARTSTAT_RXEDGIF); - if (wake_active && irqd_is_wakeup_set(irq_get_irq_data(sport->port.irq))) - pm_wakeup_event(tty_port_tty_get(port)->dev, 0); + if (wake_active && irqd_is_wakeup_set(irq_get_irq_data(sport->port.irq))) { + struct tty_struct *tty = tty_port_tty_get(port); + + if (tty) { + pm_wakeup_event(tty->dev, 0); + tty_kref_put(tty); + } + } } } diff --git a/drivers/tty/serial/imx.c b/drivers/tty/serial/imx.c index 256d85e398d13f..0831bd5ee3dc25 100644 --- a/drivers/tty/serial/imx.c +++ b/drivers/tty/serial/imx.c @@ -2742,8 +2742,14 @@ static void imx_uart_enable_wakeup(struct imx_port *sport, bool on) imx_uart_writel(sport, ucr1, UCR1); } - if (wake_active && irqd_is_wakeup_set(irq_get_irq_data(sport->port.irq))) - pm_wakeup_event(tty_port_tty_get(port)->dev, 0); + if (wake_active && irqd_is_wakeup_set(irq_get_irq_data(sport->port.irq))) { + struct tty_struct *tty = tty_port_tty_get(port); + + if (tty) { + pm_wakeup_event(tty->dev, 0); + tty_kref_put(tty); + } + } uart_port_unlock_irq(&sport->port); } diff --git a/drivers/tty/serial/rda-uart.c b/drivers/tty/serial/rda-uart.c index 9da58ffa02d545..cf1886ab1d2bcd 100644 --- a/drivers/tty/serial/rda-uart.c +++ b/drivers/tty/serial/rda-uart.c @@ -471,6 +471,8 @@ static void rda_uart_shutdown(struct uart_port *port) rda_uart_write(port, val, RDA_UART_CTRL); uart_port_unlock_irqrestore(port, flags); + + free_irq(port->irq, port); } static const char *rda_uart_type(struct uart_port *port) diff --git a/drivers/tty/serial/samsung_tty.c b/drivers/tty/serial/samsung_tty.c index 738536014742eb..7ce8f2f993e215 100644 --- a/drivers/tty/serial/samsung_tty.c +++ b/drivers/tty/serial/samsung_tty.c @@ -736,14 +736,13 @@ static irqreturn_t s3c24xx_serial_rx_chars_dma(struct s3c24xx_uart_port *ourport s3c24xx_serial_rx_drain_fifo(ourport); - if (tty) { + if (tty) tty_flip_buffer_push(t); - tty_kref_put(tty); - } wr_regl(port, S3C2410_UTRSTAT, S3C2410_UTRSTAT_TIMEOUT); finish: + tty_kref_put(tty); uart_port_unlock(port); return IRQ_HANDLED; @@ -1502,11 +1501,14 @@ static void s3c24xx_serial_set_termios(struct uart_port *port, if (!IS_ERR(ourport->baudclk)) { clk_disable_unprepare(ourport->baudclk); + clk_put(ourport->baudclk); ourport->baudclk = ERR_PTR(-EINVAL); } ourport->baudclk = clk; ourport->baudclk_rate = clk ? clk_get_rate(clk) : 0; + } else { + clk_put(clk); } if (ourport->info->has_divslot) { diff --git a/drivers/tty/serial/serial_core.c b/drivers/tty/serial/serial_core.c index c0deec0e6af41d..b06d2649be343a 100644 --- a/drivers/tty/serial/serial_core.c +++ b/drivers/tty/serial/serial_core.c @@ -135,17 +135,11 @@ static void uart_stop(struct tty_struct *tty) uart_port_unlock_deref(port, flags); } -static void __uart_start(struct uart_state *state) +static void uart_port_start_tx(struct uart_port *port) { - struct uart_port *port = state->uart_port; - struct serial_port_device *port_dev; + struct serial_port_device *port_dev = port->port_dev; int err; - if (!port || port->flags & UPF_DEAD || uart_tx_stopped(port)) - return; - - port_dev = port->port_dev; - /* Increment the runtime PM usage count for the active check below */ err = pm_runtime_get(&port_dev->dev); if (err < 0 && err != -EINPROGRESS) { @@ -164,6 +158,16 @@ static void __uart_start(struct uart_state *state) pm_runtime_put_autosuspend(&port_dev->dev); } +static void __uart_start(struct uart_state *state) +{ + struct uart_port *port = state->uart_port; + + if (!port || port->flags & UPF_DEAD || uart_tx_stopped(port)) + return; + + uart_port_start_tx(port); +} + static void uart_start(struct tty_struct *tty) { struct uart_state *state = tty->driver_data; @@ -718,8 +722,9 @@ static void uart_send_xchar(struct tty_struct *tty, u8 ch) else { guard(uart_port_lock_irqsave)(port); port->x_char = ch; - if (ch) - port->ops->start_tx(port); + /* It goes out even if the transmission is stopped */ + if (ch && !(port->flags & UPF_DEAD)) + uart_port_start_tx(port); } uart_port_deref(port); } diff --git a/drivers/tty/serial/serial_port.c b/drivers/tty/serial/serial_port.c index 2fc48cd63f6cff..f2f7cdd3a54c9a 100644 --- a/drivers/tty/serial/serial_port.c +++ b/drivers/tty/serial/serial_port.c @@ -23,8 +23,8 @@ /* Only considers pending TX for now. Caller must take care of locking */ static int __serial_port_busy(struct uart_port *port) { - return !uart_tx_stopped(port) && - !kfifo_is_empty(&port->state->port.xmit_fifo); + return port->x_char || (!uart_tx_stopped(port) && + !kfifo_is_empty(&port->state->port.xmit_fifo)); } static int serial_port_runtime_resume(struct device *dev) diff --git a/drivers/tty/tty_io.c b/drivers/tty/tty_io.c index 1a6c8a1bc764a3..150052f6d9dbf2 100644 --- a/drivers/tty/tty_io.c +++ b/drivers/tty/tty_io.c @@ -2969,8 +2969,7 @@ static long tty_compat_ioctl(struct file *file, unsigned int cmd, if (ld->ops->compat_ioctl) retval = ld->ops->compat_ioctl(tty, cmd, arg); if (retval == -ENOIOCTLCMD && ld->ops->ioctl) - retval = ld->ops->ioctl(tty, (unsigned long)compat_ptr(cmd), - arg); + retval = ld->ops->ioctl(tty, cmd, (unsigned long)compat_ptr(arg)); tty_ldisc_deref(ld); return retval; diff --git a/drivers/tty/vt/keyboard.c b/drivers/tty/vt/keyboard.c index d59d51dafa55ef..51d6d42519cfc4 100644 --- a/drivers/tty/vt/keyboard.c +++ b/drivers/tty/vt/keyboard.c @@ -322,15 +322,20 @@ int kbd_rate(struct kbd_repeat *rpt) /* * Helper Functions. + * + * A flip buffer allows one producer at a time, and respond_string() in vt.c + * feeds the same one under the console lock. So take the lock of the port. */ static void put_queue(struct vc_data *vc, int ch) { + guard(spinlock_irqsave)(&vc->port.lock); tty_insert_flip_char(&vc->port, ch, 0); tty_flip_buffer_push(&vc->port); } static void puts_queue(struct vc_data *vc, const char *cp) { + guard(spinlock_irqsave)(&vc->port.lock); tty_insert_flip_string(&vc->port, cp, strlen(cp)); tty_flip_buffer_push(&vc->port); } @@ -587,6 +592,7 @@ static void fn_inc_console(struct vc_data *vc) static void fn_send_intr(struct vc_data *vc) { + guard(spinlock_irqsave)(&vc->port.lock); tty_insert_flip_char(&vc->port, 0, TTY_BREAK); tty_flip_buffer_push(&vc->port); } diff --git a/drivers/tty/vt/vt.c b/drivers/tty/vt/vt.c index 7dbc0072a40a95..6a6eb8b2a6dece 100644 --- a/drivers/tty/vt/vt.c +++ b/drivers/tty/vt/vt.c @@ -1971,6 +1971,8 @@ static void csi_m(struct vc_data *vc) static void respond_string(const char *p, size_t len, struct tty_port *port) { + /* The keyboard handler feeds the same flip buffer. */ + guard(spinlock_irqsave)(&port->lock); tty_insert_flip_string(port, p, len); tty_flip_buffer_push(port); } diff --git a/drivers/ufs/core/ufs-debugfs.c b/drivers/ufs/core/ufs-debugfs.c index 9f83628f3e2cfd..44a1a969232428 100644 --- a/drivers/ufs/core/ufs-debugfs.c +++ b/drivers/ufs/core/ufs-debugfs.c @@ -70,12 +70,18 @@ token_context_lock(ufs_debugfs); static int ufs_debugfs_get_user_access(struct ufs_hba *hba) __cond_acquires(0, ufs_debugfs) { + int err; + down(&hba->host_sem); if (!ufshcd_is_user_access_allowed(hba)) { up(&hba->host_sem); return -EBUSY; } - ufshcd_rpm_get_sync(hba); + err = ufshcd_rpm_resume_and_get(hba); + if (err) { + up(&hba->host_sem); + return err; + } __acquire(ufs_debugfs); return 0; } diff --git a/drivers/ufs/core/ufs-hwmon.c b/drivers/ufs/core/ufs-hwmon.c index aa0b60a0ee8a77..2b9673d925737a 100644 --- a/drivers/ufs/core/ufs-hwmon.c +++ b/drivers/ufs/core/ufs-hwmon.c @@ -61,7 +61,11 @@ static int ufs_hwmon_read(struct device *dev, enum hwmon_sensor_types type, u32 return -EBUSY; } - ufshcd_rpm_get_sync(hba); + err = ufshcd_rpm_resume_and_get(hba); + if (err) { + up(&hba->host_sem); + return err; + } switch (attr) { case hwmon_temp_enable: @@ -113,7 +117,11 @@ static int ufs_hwmon_write(struct device *dev, enum hwmon_sensor_types type, u32 return -EBUSY; } - ufshcd_rpm_get_sync(hba); + err = ufshcd_rpm_resume_and_get(hba); + if (err) { + up(&hba->host_sem); + return err; + } if (val == 1) err = ufshcd_update_ee_usr_mask(hba, MASK_EE_URGENT_TEMP, 0); diff --git a/drivers/ufs/core/ufs-mcq.c b/drivers/ufs/core/ufs-mcq.c index 25e392f8ede2bf..005a7046247303 100644 --- a/drivers/ufs/core/ufs-mcq.c +++ b/drivers/ufs/core/ufs-mcq.c @@ -554,6 +554,23 @@ static int ufshcd_mcq_sq_start(struct ufs_hba *hba, struct ufs_hw_queue *hwq) return err; } +/* + * Reap the CQ directly so that progress does not depend on interrupt + * delivery. ufshcd_compl_one_cqe() updates the OCS under cq_lock before + * calling scsi_done(). Holding cq_lock while reading the OCS makes sure that + * the completion has finished once the updated OCS is observed, even if the + * CQE was reaped by the interrupt handler. + */ +static enum utp_ocs ufshcd_mcq_poll_ocs(struct ufs_hba *hba, + struct ufs_hw_queue *hwq, + struct ufshcd_lrb *lrbp) +{ + ufshcd_mcq_poll_cqe_lock(hba, hwq); + + guard(spinlock_irqsave)(&hwq->cq_lock); + return lrbp->utr_descriptor_ptr->header.ocs; +} + /** * ufshcd_mcq_sq_cleanup - Clean up submission queue resources * associated with the pending command. @@ -613,6 +630,23 @@ int ufshcd_mcq_sq_cleanup(struct ufs_hba *hba, int task_tag) __func__, id, FIELD_GET(SQ_ICU_ERR_CODE_MASK, readl(reg))); + /* + * For device management commands, there is no order guaranteed between + * OCS update and CUS update, which is why we need to wait here. SCSI + * commands are excluded because the OCS in their UTRD is not updated + * from the CQE. + */ + if (!err && blk_mq_is_reserved_rq(rq)) { + enum utp_ocs ocs; + + err = read_poll_timeout(ufshcd_mcq_poll_ocs, ocs, + ocs != OCS_INVALID_COMMAND_STATUS, 20, + MCQ_POLL_US, false, hba, hwq, lrbp); + if (err) + dev_err(hba->dev, "%s: OCS not updated. hwq=%d, tag=%d err=%d\n", + __func__, id, task_tag, err); + } + if (ufshcd_mcq_sq_start(hba, hwq)) err = -ETIMEDOUT; diff --git a/drivers/ufs/core/ufs-rpmb.c b/drivers/ufs/core/ufs-rpmb.c index 75667333764802..6803f3e62d786c 100644 --- a/drivers/ufs/core/ufs-rpmb.c +++ b/drivers/ufs/core/ufs-rpmb.c @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -27,22 +28,19 @@ #define UFS_RPMB_SEC_PROTOCOL 0xEC /* JEDEC UFS application */ #define UFS_RPMB_SEC_PROTOCOL_ID 0x01 /* JEDEC UFS RPMB protocol ID, CDB byte3 */ -static const struct bus_type ufs_rpmb_bus_type = { - .name = "ufs_rpmb", -}; - /* UFS RPMB device structure */ struct ufs_rpmb_dev { u8 region_id; struct device dev; struct rpmb_dev *rdev; - struct ufs_hba *hba; + struct scsi_device *sdev; struct list_head node; }; -static int ufs_sec_submit(struct ufs_hba *hba, u16 spsp, void *buffer, size_t len, bool send) +static int ufs_sec_submit(struct ufs_rpmb_dev *ufs_rpmb, u16 spsp, + void *buffer, size_t len, bool send) { - struct scsi_device *sdev = hba->ufs_rpmb_wlun; + struct scsi_device *sdev = ufs_rpmb->sdev; struct scsi_failure failure_defs[] = { { .sense_key = UNIT_ATTENTION, @@ -62,6 +60,9 @@ static int ufs_sec_submit(struct ufs_hba *hba, u16 spsp, void *buffer, size_t le }; u8 cdb[12] = { }; + if (!sdev || !scsi_device_online(sdev)) + return -ENODEV; + cdb[0] = send ? SECURITY_PROTOCOL_OUT : SECURITY_PROTOCOL_IN; cdb[1] = UFS_RPMB_SEC_PROTOCOL; put_unaligned_be16(spsp, &cdb[2]); @@ -74,13 +75,12 @@ static int ufs_sec_submit(struct ufs_hba *hba, u16 spsp, void *buffer, size_t le /* UFS RPMB route frames implementation */ static int ufs_rpmb_route_frames(struct device *dev, u8 *req, unsigned int req_len, u8 *resp, - unsigned int resp_len) + unsigned int resp_len) { struct ufs_rpmb_dev *ufs_rpmb = dev_get_drvdata(dev); struct rpmb_frame *frm_out = (struct rpmb_frame *)req; bool need_result_read = true; u16 req_type, protocol_id; - struct ufs_hba *hba; int ret; if (!ufs_rpmb) { @@ -88,8 +88,6 @@ static int ufs_rpmb_route_frames(struct device *dev, u8 *req, unsigned int req_l return -ENODEV; } - hba = ufs_rpmb->hba; - /* req_resp is at the end of an RPMB frame. */ if (req_len < sizeof(*frm_out)) return -EINVAL; @@ -122,7 +120,7 @@ static int ufs_rpmb_route_frames(struct device *dev, u8 *req, unsigned int req_l protocol_id = ufs_rpmb->region_id << 8 | UFS_RPMB_SEC_PROTOCOL_ID; - ret = ufs_sec_submit(hba, protocol_id, req, req_len, true); + ret = ufs_sec_submit(ufs_rpmb, protocol_id, req, req_len, true); if (ret) { dev_err(dev, "Command failed with ret=%d\n", ret); return ret; @@ -133,7 +131,8 @@ static int ufs_rpmb_route_frames(struct device *dev, u8 *req, unsigned int req_l memset(frm_resp, 0, sizeof(*frm_resp)); put_unaligned_be16(RPMB_RESULT_READ, &frm_resp->req_resp); - ret = ufs_sec_submit(hba, protocol_id, resp, resp_len, true); + ret = ufs_sec_submit(ufs_rpmb, protocol_id, resp, resp_len, + true); if (ret) { dev_err(dev, "Result read request failed with ret=%d\n", ret); return ret; @@ -141,7 +140,8 @@ static int ufs_rpmb_route_frames(struct device *dev, u8 *req, unsigned int req_l } if (!ret) { - ret = ufs_sec_submit(hba, protocol_id, resp, resp_len, false); + ret = ufs_sec_submit(ufs_rpmb, protocol_id, resp, resp_len, + false); if (ret) dev_err(dev, "Response read failed with ret=%d\n", ret); } @@ -151,23 +151,31 @@ static int ufs_rpmb_route_frames(struct device *dev, u8 *req, unsigned int req_l static void ufs_rpmb_device_release(struct device *dev) { - struct ufs_rpmb_dev *ufs_rpmb = dev_get_drvdata(dev); + struct ufs_rpmb_dev *ufs_rpmb = + container_of(dev, struct ufs_rpmb_dev, dev); - rpmb_dev_unregister(ufs_rpmb->rdev); + put_device(&ufs_rpmb->sdev->sdev_gendev); + kfree(ufs_rpmb); } /* UFS RPMB device registration */ int ufs_rpmb_probe(struct ufs_hba *hba) { + struct rpmb_descr descr = { + .type = RPMB_TYPE_UFS, + .route_frames = ufs_rpmb_route_frames, + .reliable_wr_count = hba->dev_info.rpmb_io_size, + }; + struct scsi_device *sdev = hba->ufs_rpmb_wlun; struct ufs_rpmb_dev *ufs_rpmb, *it, *tmp; u8 dev_id[UFS_RPMB_ID_LEN]; struct rpmb_dev *rdev; - char *cid = NULL; + char *cid; int region; u32 cap; int ret; - if (!hba->ufs_rpmb_wlun || hba->dev_info.b_advanced_rpmb_en) { + if (!sdev || hba->dev_info.b_advanced_rpmb_en) { dev_info(hba->dev, "Skip OP-TEE RPMB registration\n"); return -ENODEV; } @@ -178,26 +186,22 @@ int ufs_rpmb_probe(struct ufs_hba *hba) return -EINVAL; } - struct rpmb_descr descr = { - .type = RPMB_TYPE_UFS, - .route_frames = ufs_rpmb_route_frames, - .reliable_wr_count = hba->dev_info.rpmb_io_size, - }; - for (region = 0; region < ARRAY_SIZE(hba->dev_info.rpmb_region_size); region++) { cap = hba->dev_info.rpmb_region_size[region]; if (!cap) continue; - ufs_rpmb = devm_kzalloc_obj(hba->dev, *ufs_rpmb); + ufs_rpmb = kzalloc_obj(*ufs_rpmb); if (!ufs_rpmb) { ret = -ENOMEM; goto err_out; } - ufs_rpmb->hba = hba; - ufs_rpmb->dev.parent = &hba->ufs_rpmb_wlun->sdev_gendev; - ufs_rpmb->dev.bus = &ufs_rpmb_bus_type; + get_device(&sdev->sdev_gendev); + + ufs_rpmb->sdev = sdev; + ufs_rpmb->region_id = region; + ufs_rpmb->dev.parent = &sdev->sdev_gendev; ufs_rpmb->dev.release = ufs_rpmb_device_release; dev_set_name(&ufs_rpmb->dev, "ufs_rpmb%d", region); @@ -207,16 +211,14 @@ int ufs_rpmb_probe(struct ufs_hba *hba) ret = device_register(&ufs_rpmb->dev); if (ret) { dev_err(hba->dev, "Failed to register UFS RPMB device %d\n", region); - put_device(&ufs_rpmb->dev); - goto err_out; + goto err_put; } /* Create unique ID by appending region number to device_id */ cid = kasprintf(GFP_KERNEL, "%s-R%d", hba->dev_info.device_id, region); if (!cid) { - device_unregister(&ufs_rpmb->dev); ret = -ENOMEM; - goto err_out; + goto err_unreg; } blake2b(NULL, 0, cid, strlen(cid), dev_id, UFS_RPMB_ID_LEN); @@ -227,29 +229,30 @@ int ufs_rpmb_probe(struct ufs_hba *hba) /* Register RPMB device */ rdev = rpmb_dev_register(&ufs_rpmb->dev, &descr); + kfree(cid); if (IS_ERR(rdev)) { dev_err(hba->dev, "Failed to register UFS RPMB device.\n"); - device_unregister(&ufs_rpmb->dev); ret = PTR_ERR(rdev); - goto err_out; + goto err_unreg; } - kfree(cid); - cid = NULL; - ufs_rpmb->rdev = rdev; - ufs_rpmb->region_id = region; - list_add_tail(&ufs_rpmb->node, &hba->rpmbs); dev_info(hba->dev, "UFS RPMB region %d registered (capacity=%u)\n", region, cap); } return 0; + +err_unreg: + device_unregister(&ufs_rpmb->dev); + goto err_out; +err_put: + put_device(&ufs_rpmb->dev); err_out: - kfree(cid); list_for_each_entry_safe(it, tmp, &hba->rpmbs, node) { list_del(&it->node); + rpmb_dev_unregister(it->rdev); device_unregister(&it->dev); } @@ -269,6 +272,7 @@ void ufs_rpmb_remove(struct ufs_hba *hba) dev_info(hba->dev, "Removing UFS RPMB region %d\n", ufs_rpmb->region_id); /* Remove from list first */ list_del(&ufs_rpmb->node); + rpmb_dev_unregister(ufs_rpmb->rdev); /* Unregister device */ device_unregister(&ufs_rpmb->dev); } diff --git a/drivers/ufs/core/ufs-sysfs.c b/drivers/ufs/core/ufs-sysfs.c index cf49ad0258e140..19b62cf52410bb 100644 --- a/drivers/ufs/core/ufs-sysfs.c +++ b/drivers/ufs/core/ufs-sysfs.c @@ -250,13 +250,19 @@ EXPORT_SYMBOL_GPL(ufshcd_us_to_ahit); static int ufshcd_read_hci_reg(struct ufs_hba *hba, u32 *val, unsigned int reg) { + int ret; + down(&hba->host_sem); if (!ufshcd_is_user_access_allowed(hba)) { up(&hba->host_sem); return -EBUSY; } - ufshcd_rpm_get_sync(hba); + ret = ufshcd_rpm_resume_and_get(hba); + if (ret) { + up(&hba->host_sem); + return ret; + } ufshcd_hold(hba); *val = ufshcd_readl(hba, reg); ufshcd_release(hba); @@ -350,7 +356,9 @@ static ssize_t wb_on_store(struct device *dev, struct device_attribute *attr, goto out; } - ufshcd_rpm_get_sync(hba); + res = ufshcd_rpm_resume_and_get(hba); + if (res) + goto out; res = ufshcd_wb_toggle(hba, wb_enable); ufshcd_rpm_put_sync(hba); out: @@ -421,7 +429,9 @@ static ssize_t enable_wb_buf_flush_store(struct device *dev, goto out; } - ufshcd_rpm_get_sync(hba); + res = ufshcd_rpm_resume_and_get(hba); + if (res) + goto out; res = ufshcd_wb_toggle_buf_flush(hba, enable_wb_buf_flush); ufshcd_rpm_put_sync(hba); @@ -490,7 +500,9 @@ static ssize_t wb_resize_enable_store(struct device *dev, goto out; } - ufshcd_rpm_get_sync(hba); + res = ufshcd_rpm_resume_and_get(hba); + if (res) + goto out; res = ufshcd_wb_set_resize_en(hba, mode); ufshcd_rpm_put_sync(hba); @@ -598,7 +610,9 @@ static ssize_t device_lvl_exception_id_show(struct device *dev, if (hba->dev_info.wspecversion < 0x410) return -EOPNOTSUPP; - ufshcd_rpm_get_sync(hba); + err = ufshcd_rpm_resume_and_get(hba); + if (err) + return err; err = ufshcd_query_attr_qword(hba, UPIU_QUERY_OPCODE_READ_ATTR, QUERY_ATTR_IDN_DEV_LVL_EXCEPTION_ID, 0, 0, &exception_id); @@ -1101,7 +1115,9 @@ static ssize_t ufs_sysfs_read_desc_param(struct ufs_hba *hba, goto out; } - ufshcd_rpm_get_sync(hba); + ret = ufshcd_rpm_resume_and_get(hba); + if (ret) + goto out; ret = ufshcd_read_desc_param(hba, desc_id, desc_index, param_offset, desc_buf, param_size); ufshcd_rpm_put_sync(hba); @@ -1482,7 +1498,12 @@ static ssize_t _name##_show(struct device *dev, \ up(&hba->host_sem); \ return -ENOMEM; \ } \ - ufshcd_rpm_get_sync(hba); \ + ret = ufshcd_rpm_resume_and_get(hba); \ + if (ret) { \ + kfree(desc_buf); \ + up(&hba->host_sem); \ + return ret; \ + } \ ret = ufshcd_query_descriptor_retry(hba, \ UPIU_QUERY_OPCODE_READ_DESC, QUERY_DESC_IDN_DEVICE, \ 0, 0, desc_buf, &desc_len); \ @@ -1548,7 +1569,9 @@ static ssize_t _name##_show(struct device *dev, \ } \ if (ufshcd_is_wb_flags(QUERY_FLAG_IDN##_uname)) \ index = ufshcd_wb_get_query_index(hba); \ - ufshcd_rpm_get_sync(hba); \ + ret = ufshcd_rpm_resume_and_get(hba); \ + if (ret) \ + goto out; \ ret = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_READ_FLAG, \ QUERY_FLAG_IDN##_uname, index, &flag); \ ufshcd_rpm_put_sync(hba); \ @@ -1608,7 +1631,9 @@ static ssize_t max_number_of_rtt_show(struct device *dev, return -EBUSY; } - ufshcd_rpm_get_sync(hba); + ret = ufshcd_rpm_resume_and_get(hba); + if (ret) + goto out; ret = ufshcd_query_attr(hba, UPIU_QUERY_OPCODE_READ_ATTR, QUERY_ATTR_IDN_MAX_NUM_OF_RTT, 0, 0, &rtt); ufshcd_rpm_put_sync(hba); @@ -1648,7 +1673,9 @@ static ssize_t max_number_of_rtt_store(struct device *dev, goto out; } - ufshcd_rpm_get_sync(hba); + ret = ufshcd_rpm_resume_and_get(hba); + if (ret) + goto out; memflags = memalloc_noio_save(); shost_for_each_device(sdev, hba->host) @@ -1700,7 +1727,11 @@ static int wb_read_resize_attrs(struct ufs_hba *hba, } index = ufshcd_wb_get_query_index(hba); - ufshcd_rpm_get_sync(hba); + ret = ufshcd_rpm_resume_and_get(hba); + if (ret) { + up(&hba->host_sem); + return ret; + } ret = ufshcd_query_attr(hba, UPIU_QUERY_OPCODE_READ_ATTR, idn, index, 0, attr_val); ufshcd_rpm_put_sync(hba); @@ -1760,7 +1791,9 @@ static ssize_t _name##_show(struct device *dev, \ } \ if (ufshcd_is_wb_attrs(QUERY_ATTR_IDN##_uname)) \ index = ufshcd_wb_get_query_index(hba); \ - ufshcd_rpm_get_sync(hba); \ + ret = ufshcd_rpm_resume_and_get(hba); \ + if (ret) \ + goto out; \ if (ufshcd_is_qword_attr(QUERY_ATTR_IDN##_uname)) \ ret = ufshcd_query_attr_qword(hba, \ UPIU_QUERY_OPCODE_READ_ATTR, \ @@ -1848,7 +1881,11 @@ static int hid_query_attr(struct ufs_hba *hba, enum query_opcode opcode, return -EBUSY; } - ufshcd_rpm_get_sync(hba); + ret = ufshcd_rpm_resume_and_get(hba); + if (ret) { + up(&hba->host_sem); + return ret; + } ret = ufshcd_query_attr(hba, opcode, idn, 0, 0, attr_val); ufshcd_rpm_put_sync(hba); @@ -2121,7 +2158,9 @@ static ssize_t dyn_cap_needed_attribute_show(struct device *dev, goto out; } - ufshcd_rpm_get_sync(hba); + ret = ufshcd_rpm_resume_and_get(hba); + if (ret) + goto out; ret = ufshcd_query_attr(hba, UPIU_QUERY_OPCODE_READ_ATTR, QUERY_ATTR_IDN_DYN_CAP_NEEDED, lun, 0, &value); ufshcd_rpm_put_sync(hba); diff --git a/drivers/ufs/core/ufs_bsg.c b/drivers/ufs/core/ufs_bsg.c index baf6ae917d36e4..8df1a2c6abf6a7 100644 --- a/drivers/ufs/core/ufs_bsg.c +++ b/drivers/ufs/core/ufs_bsg.c @@ -150,7 +150,9 @@ static int ufs_bsg_request(struct bsg_job *job) goto out_complete; } - ufshcd_rpm_get_sync(hba); + ret = ufshcd_rpm_resume_and_get(hba); + if (ret) + goto out_complete; msgcode = bsg_request->msgcode; switch (msgcode) { diff --git a/drivers/ufs/core/ufshcd-priv.h b/drivers/ufs/core/ufshcd-priv.h index e55c2a02c1f506..99f654b79035fc 100644 --- a/drivers/ufs/core/ufshcd-priv.h +++ b/drivers/ufs/core/ufshcd-priv.h @@ -388,6 +388,11 @@ static inline int ufshcd_rpm_get_sync(struct ufs_hba *hba) return pm_runtime_get_sync(&hba->ufs_device_wlun->sdev_gendev); } +static inline int ufshcd_rpm_resume_and_get(struct ufs_hba *hba) +{ + return pm_runtime_resume_and_get(&hba->ufs_device_wlun->sdev_gendev); +} + static inline int ufshcd_rpm_get_if_active(struct ufs_hba *hba) { return pm_runtime_get_if_active(&hba->ufs_device_wlun->sdev_gendev); diff --git a/drivers/ufs/core/ufshcd.c b/drivers/ufs/core/ufshcd.c index 3c28bc67c65f1a..c9b2eefbd7b0b2 100644 --- a/drivers/ufs/core/ufshcd.c +++ b/drivers/ufs/core/ufshcd.c @@ -1864,7 +1864,9 @@ static ssize_t ufshcd_clkscale_enable_store(struct device *dev, if (value == hba->clk_scaling.is_enabled) goto out; - ufshcd_rpm_get_sync(hba); + err = ufshcd_rpm_resume_and_get(hba); + if (err) + goto out; ufshcd_hold(hba); hba->clk_scaling.is_enabled = value; @@ -3390,7 +3392,7 @@ static int ufshcd_issue_dev_cmd(struct ufs_hba *hba, struct scsi_cmnd *cmd, struct request *rq = scsi_cmd_to_rq(cmd); blk_status_t sts; - rq->timeout = timeout; + rq->timeout = msecs_to_jiffies(timeout); sts = blk_execute_rq(rq, true); if (sts != BLK_STS_OK) return blk_status_to_errno(sts); @@ -4792,7 +4794,8 @@ void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit) WRITE_ONCE(hba->ahit, ahit); if (!pm_runtime_suspended(&hba->ufs_device_wlun->sdev_gendev)) { - ufshcd_rpm_get_sync(hba); + if (ufshcd_rpm_resume_and_get(hba)) + return; ufshcd_hold(hba); /* * Serialize with the host driver's AHIT control. Skip the @@ -8064,11 +8067,15 @@ static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap) * @hba: Pointer to adapter instance * @tag: Tag of the task to be aborted * - * Abort the pending command in device by sending UFS_ABORT_TASK task management - * command, and in host controller by clearing the door-bell register. There can - * be race between controller sending the command to the device while abort is - * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is - * really issued and then try to abort it. + * Abort the pending SCSI command in device by sending UFS_ABORT_TASK task + * management command, and in host controller by clearing the door-bell + * register. There can be race between controller sending the command to the + * device while abort is issued. To avoid that, first issue UFS_QUERY_TASK to + * check if the command is really issued and then try to abort it. + * + * Device management commands are not SCSI commands, so no task management + * function is issued for them; only the command is cleared in the host + * controller. * * Return: zero on success, non-zero on failure. */ @@ -8085,6 +8092,9 @@ int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag) lrbp = scsi_cmd_priv(cmd); + if (!ufshcd_is_scsi_cmd(cmd)) + goto clear_cmd; + for (poll_cnt = 100; poll_cnt; poll_cnt--) { err = ufshcd_issue_tm_cmd(hba, lrbp->lun, tag, UFS_QUERY_TASK, &resp); @@ -8130,6 +8140,7 @@ int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag) return err; } +clear_cmd: err = ufshcd_clear_cmd(hba, tag); if (err) dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n", @@ -8223,10 +8234,7 @@ static int ufshcd_abort(struct scsi_cmnd *cmd) goto release; } - if (blk_mq_is_reserved_rq(rq)) - err = ufshcd_clear_cmd(hba, tag); - else - err = ufshcd_try_to_abort_task(hba, tag); + err = ufshcd_try_to_abort_task(hba, tag); if (err) { dev_err(hba->dev, "%s: failed with err %d\n", __func__, err); ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs); @@ -10651,8 +10659,14 @@ static int __ufshcd_wl_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op) out: if (ret) ufshcd_update_evt_hist(hba, UFS_EVT_WL_RES_ERR, (u32)ret); - hba->clk_gating.is_suspended = false; - ufshcd_release(hba); + /* + * A failed runtime resume leaves the W-LUN RPM_SUSPENDED, so keep + * is_suspended and the suspend hold for the next resume. + */ + if (!ret || pm_op != UFS_RUNTIME_PM) { + hba->clk_gating.is_suspended = false; + ufshcd_release(hba); + } hba->pm_op_in_progress = false; return ret; } diff --git a/drivers/ufs/host/ufs-mediatek.c b/drivers/ufs/host/ufs-mediatek.c index 7691349c502a36..1a25fa0814d1e6 100644 --- a/drivers/ufs/host/ufs-mediatek.c +++ b/drivers/ufs/host/ufs-mediatek.c @@ -541,6 +541,16 @@ static int ufs_mtk_mphy_power_on(struct ufs_hba *hba, bool on) if (ufs_mtk_is_va09_supported(hba)) { ufs_mtk_va09_pwr_ctrl(res, 0); ret = regulator_disable(host->reg_va09); + if (ret) { + /* + * The va09 regulator stays enabled, so + * bring the M-PHY back up to keep the + * software state in sync with the + * hardware. + */ + ufs_mtk_va09_pwr_ctrl(res, 1); + phy_power_on(mphy); + } } } out: @@ -691,7 +701,7 @@ static void ufs_mtk_init_va09_pwr_ctrl(struct ufs_hba *hba) { struct ufs_mtk_host *host = ufshcd_get_variant(hba); - host->reg_va09 = regulator_get(hba->dev, "va09"); + host->reg_va09 = devm_regulator_get(hba->dev, "va09"); if (IS_ERR(host->reg_va09)) dev_info(hba->dev, "failed to get va09"); else @@ -1330,6 +1340,14 @@ static int ufs_mtk_init(struct ufs_hba *hba) return err; } +static void ufs_mtk_exit(struct ufs_hba *hba) +{ + struct ufs_mtk_host *host = ufshcd_get_variant(hba); + + if (host) + ufs_mtk_mphy_power_on(hba, false); +} + static int ufs_mtk_negotiate_pwr_mode(struct ufs_hba *hba, const struct ufs_pa_layer_attr *dev_max_params, struct ufs_pa_layer_attr *dev_req_params) @@ -2352,6 +2370,7 @@ static void ufs_mtk_config_scsi_dev(struct scsi_device *sdev) static const struct ufs_hba_variant_ops ufs_hba_mtk_vops = { .name = "mediatek.ufshci", .init = ufs_mtk_init, + .exit = ufs_mtk_exit, .get_ufs_hci_version = ufs_mtk_get_ufs_hci_version, .setup_clocks = ufs_mtk_setup_clocks, .hce_enable_notify = ufs_mtk_hce_enable_notify, diff --git a/drivers/ufs/host/ufs-qcom.c b/drivers/ufs/host/ufs-qcom.c index 67c2a3b95e5806..a9ee9cd97b524e 100644 --- a/drivers/ufs/host/ufs-qcom.c +++ b/drivers/ufs/host/ufs-qcom.c @@ -2413,7 +2413,9 @@ static void ufs_qcom_write_msi_msg(struct msi_desc *desc, struct msi_msg *msg) { struct device *dev = msi_desc_to_dev(desc); struct ufs_hba *hba = dev_get_drvdata(dev); + struct ufs_qcom_host *host = ufshcd_get_variant(hba); + host->esi_msg = *msg; ufshcd_mcq_config_esi(hba, msg); } @@ -2441,8 +2443,10 @@ static int ufs_qcom_config_esi(struct ufs_hba *hba) struct ufs_qcom_irq *qi; int nr_irqs, ret; - if (host->esi_enabled) - return 0; + if (host->esi_enabled) { + ufshcd_mcq_config_esi(hba, &host->esi_msg); + goto enable; + } /* * 1. We only handle CQs as of now. @@ -2480,12 +2484,14 @@ static int ufs_qcom_config_esi(struct ufs_hba *hba) } } + host->esi_enabled = true; + +enable: if (host->hw_ver.major >= 6) { ufshcd_rmwl(hba, ESI_VEC_MASK, FIELD_PREP(ESI_VEC_MASK, MAX_ESI_VEC - 1), REG_UFS_CFG3); } ufshcd_mcq_enable_esi(hba); - host->esi_enabled = true; return 0; } diff --git a/drivers/ufs/host/ufs-qcom.h b/drivers/ufs/host/ufs-qcom.h index 944b2e532a0962..d2647695abe3ab 100644 --- a/drivers/ufs/host/ufs-qcom.h +++ b/drivers/ufs/host/ufs-qcom.h @@ -5,6 +5,7 @@ #ifndef UFS_QCOM_H_ #define UFS_QCOM_H_ +#include #include #include #include @@ -360,6 +361,7 @@ struct ufs_qcom_host { u32 phy_gear; bool esi_enabled; + struct msi_msg esi_msg; u32 saved_tx_eq_g1_setting; u32 boot_spare_cfg; diff --git a/drivers/ufs/host/ufs-rockchip.c b/drivers/ufs/host/ufs-rockchip.c index 8ce6534a73de4b..a97d1523f016b6 100644 --- a/drivers/ufs/host/ufs-rockchip.c +++ b/drivers/ufs/host/ufs-rockchip.c @@ -82,6 +82,7 @@ static int ufs_rockchip_rk3576_phy_init(struct ufs_hba *hba) ufshcd_dme_set(hba, UIC_ARG_MIB_SEL(VND_RX_LINERESET_PVALUE2, SEL_RX_LANE0 + i), 0x02); ufshcd_dme_set(hba, UIC_ARG_MIB_SEL(VND_RX_LINERESET_OPTION, SEL_RX_LANE0 + i), 0xf6); ufshcd_dme_set(hba, UIC_ARG_MIB_SEL(VND_RX_POWER_SAVING_CTRL, SEL_RX_LANE0 + i), 0x69); + ufshcd_dme_set(hba, UIC_ARG_MIB_SEL(VND_RX_SAVE_DET_CTRL, SEL_RX_LANE0 + i), 0x18); } /* disable the mphy DME_SET cfg */ diff --git a/drivers/ufs/host/ufshcd-pci.c b/drivers/ufs/host/ufshcd-pci.c index 8d7a266f4529f8..be6ad88b4f2fc8 100644 --- a/drivers/ufs/host/ufshcd-pci.c +++ b/drivers/ufs/host/ufshcd-pci.c @@ -644,7 +644,7 @@ static int ufshcd_pci_suspend_prepare(struct device *dev) { struct ufs_hba *hba = dev_get_drvdata(dev); - if (!strcmp(hba->vops->name, "intel-pci")) + if (hba->vops && !strcmp(hba->vops->name, "intel-pci")) return ufs_intel_suspend_prepare(dev); return ufshcd_suspend_prepare(dev); @@ -654,7 +654,7 @@ static void ufshcd_pci_resume_complete(struct device *dev) { struct ufs_hba *hba = dev_get_drvdata(dev); - if (!strcmp(hba->vops->name, "intel-pci")) { + if (hba->vops && !strcmp(hba->vops->name, "intel-pci")) { ufs_intel_resume_complete(dev); return; } diff --git a/drivers/usb/cdns3/cdns3-gadget.c b/drivers/usb/cdns3/cdns3-gadget.c index 380c4fde8298e3..e2db946560c1a2 100644 --- a/drivers/usb/cdns3/cdns3-gadget.c +++ b/drivers/usb/cdns3/cdns3-gadget.c @@ -2530,9 +2530,9 @@ static int cdns3_gadget_ep_disable(struct usb_ep *ep) !(val & EP_STS_DBUSY), 1, 10); writel(EP_CMD_EPRST, &priv_dev->regs->ep_cmd); - readl_poll_timeout_atomic(&priv_dev->regs->ep_cmd, val, - !(val & (EP_CMD_CSTALL | EP_CMD_EPRST)), - 1, 1000); + ret = readl_poll_timeout_atomic(&priv_dev->regs->ep_cmd, val, + !(val & (EP_CMD_CSTALL | EP_CMD_EPRST)), + 1, 1000); if (unlikely(ret)) dev_err(priv_dev->dev, "Timeout: %s resetting failed.\n", priv_ep->name); diff --git a/drivers/usb/cdns3/cdns3-imx.c b/drivers/usb/cdns3/cdns3-imx.c index 710334c3431e74..5e92623296e502 100644 --- a/drivers/usb/cdns3/cdns3-imx.c +++ b/drivers/usb/cdns3/cdns3-imx.c @@ -218,12 +218,20 @@ static int cdns_imx_probe(struct platform_device *pdev) return ret; } +static int cdns_imx_reset_pdata(struct device *dev, void *data) +{ + if (device_is_compatible(dev, "cdns,usb3")) + dev->platform_data = NULL; + return 0; +} + static void cdns_imx_remove(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct cdns_imx *data = dev_get_drvdata(dev); pm_runtime_get_sync(dev); + device_for_each_child(dev, NULL, cdns_imx_reset_pdata); of_platform_depopulate(dev); clk_bulk_disable_unprepare(data->num_clks, data->clks); pm_runtime_disable(dev); diff --git a/drivers/usb/class/cdc-acm.c b/drivers/usb/class/cdc-acm.c index 489575d40bd148..4a0c7806fc0b45 100644 --- a/drivers/usb/class/cdc-acm.c +++ b/drivers/usb/class/cdc-acm.c @@ -294,6 +294,7 @@ static void acm_process_notification(struct acm *acm, unsigned char *buf) unsigned long flags; struct usb_cdc_notification *dr = (struct usb_cdc_notification *)buf; unsigned char *data = buf + sizeof(struct usb_cdc_notification); + struct tty_struct *tty; switch (dr->bNotificationType) { case USB_CDC_NOTIFY_NETWORK_CONNECTION: @@ -320,12 +321,17 @@ static void acm_process_notification(struct acm *acm, unsigned char *buf) difference = acm->ctrlin ^ newctrl; - if ((difference & USB_CDC_SERIAL_STATE_DCD) && acm->port.tty) { - struct tty_ldisc *ld = tty_ldisc_ref(acm->port.tty); - if (ld) { - if (ld->ops->dcd_change) - ld->ops->dcd_change(acm->port.tty, newctrl & USB_CDC_SERIAL_STATE_DCD); - tty_ldisc_deref(ld); + if (difference & USB_CDC_SERIAL_STATE_DCD) { + tty = tty_port_tty_get(&acm->port); + if (tty) { + struct tty_ldisc *ld = tty_ldisc_ref(tty); + + if (ld) { + if (ld->ops->dcd_change) + ld->ops->dcd_change(tty, newctrl & USB_CDC_SERIAL_STATE_DCD); + tty_ldisc_deref(ld); + } + tty_kref_put(tty); } } @@ -2043,6 +2049,18 @@ static const struct usb_device_id acm_ids[] = { { USB_DEVICE(0x1bc7, 0x0023), /* Telit 3G ACM + ECM composition */ .driver_info = SEND_ZERO_PACKET, }, + { USB_DEVICE_INTERFACE_NUMBER(0x1bc7, 0x7020, 4), /* Telit LE910Q1 (RNDIS) diag port */ + .driver_info = QUIRK_CONTROL_LINE_STATE, + }, + { USB_DEVICE_INTERFACE_NUMBER(0x1bc7, 0x7021, 4), /* Telit LE910Q1 (ECM) diag port */ + .driver_info = QUIRK_CONTROL_LINE_STATE, + }, + { USB_DEVICE_INTERFACE_NUMBER(0x1bc7, 0x7028, 4), /* Telit LE310Q1 (RNDIS) diag port */ + .driver_info = QUIRK_CONTROL_LINE_STATE, + }, + { USB_DEVICE_INTERFACE_NUMBER(0x1bc7, 0x7029, 4), /* Telit LE310Q1 (ECM) diag port */ + .driver_info = QUIRK_CONTROL_LINE_STATE, + }, /* Exclude Goodix Fingerprint Reader */ { USB_DEVICE(0x27c6, 0x5395), diff --git a/drivers/usb/core/quirks.c b/drivers/usb/core/quirks.c index a4bcbe9c913cf5..98544785e4627f 100644 --- a/drivers/usb/core/quirks.c +++ b/drivers/usb/core/quirks.c @@ -423,7 +423,8 @@ static const struct usb_device_id usb_quirk_list[] = { USB_QUIRK_CONFIG_INTF_STRINGS }, /* Kingston DataTraveler 3.0 */ - { USB_DEVICE(0x0951, 0x1666), .driver_info = USB_QUIRK_NO_LPM }, + { USB_DEVICE(0x0951, 0x1666), .driver_info = USB_QUIRK_NO_LPM | + USB_QUIRK_DELAY_INIT }, /* TOSHIBA TransMemory-Mx */ { USB_DEVICE(0x0930, 0x1408), .driver_info = USB_QUIRK_NO_LPM }, diff --git a/drivers/usb/dwc2/core.h b/drivers/usb/dwc2/core.h index 015a5fb7842d57..54c040da0cae12 100644 --- a/drivers/usb/dwc2/core.h +++ b/drivers/usb/dwc2/core.h @@ -1108,6 +1108,7 @@ struct dwc2_hsotg { /* DWC OTG HW Release versions */ #define DWC2_CORE_REV_4_30a 0x4f54430a +#define DWC2_CORE_REV_2_70a 0x4f54270a #define DWC2_CORE_REV_2_71a 0x4f54271a #define DWC2_CORE_REV_2_72a 0x4f54272a #define DWC2_CORE_REV_2_80a 0x4f54280a diff --git a/drivers/usb/dwc2/gadget.c b/drivers/usb/dwc2/gadget.c index c72f02adff5955..adc3df0ca7dd2c 100644 --- a/drivers/usb/dwc2/gadget.c +++ b/drivers/usb/dwc2/gadget.c @@ -1582,7 +1582,7 @@ static struct dwc2_hsotg_ep *ep_from_windex(struct dwc2_hsotg *hsotg, if (windex >= 0x100) return NULL; - if (idx > hsotg->num_of_eps) + if (idx >= hsotg->num_of_eps) return NULL; return index_to_ep(hsotg, idx, dir); @@ -3486,8 +3486,6 @@ void dwc2_hsotg_core_init_disconnected(struct dwc2_hsotg *hsotg, dwc2_phy_init(hsotg, true); - dwc2_hsotg_init_fifo(hsotg); - if (!is_usb_reset) { dwc2_set_bit(hsotg, DCTL, DCTL_SFTDISCON); if (hsotg->params.eusb2_disc) @@ -3513,8 +3511,25 @@ void dwc2_hsotg_core_init_disconnected(struct dwc2_hsotg *hsotg, if (hsotg->params.ipg_isoc_en) dcfg |= DCFG_IPG_ISOC_SUPPORDED; + /* + * WA for Device Flushes Ongoing ISOC IN Packet at End-of-Periodic-Frame Boundary. + * Once passed the end of periodic frame, and the controller is transmitting an + * ISOC IN packet, the device flushes the transmit FIFO. Tune periodic frame + * interval to 95% instead of 80% to avoid it. + */ + if (using_desc_dma(hsotg) && + ((hsotg->hw_params.snpsid >= DWC2_CORE_REV_2_70a && + hsotg->hw_params.snpsid <= DWC2_CORE_REV_4_00a) || + hsotg->hw_params.snpsid == DWC2_FS_IOT_REV_1_00a || + hsotg->hw_params.snpsid == DWC2_HS_IOT_REV_1_00a)) { + dcfg &= ~DCFG_PERFRINT_MASK; + dcfg |= DCFG_PERFRINT(DCFG_PERFRINT_LIMIT); + } + dwc2_writel(hsotg, dcfg, DCFG); + dwc2_hsotg_init_fifo(hsotg); + /* Clear any pending OTG interrupts */ dwc2_writel(hsotg, 0xffffffff, GOTGINT); diff --git a/drivers/usb/dwc2/hcd.c b/drivers/usb/dwc2/hcd.c index 2e1927dfa34f1f..40ab50538334af 100644 --- a/drivers/usb/dwc2/hcd.c +++ b/drivers/usb/dwc2/hcd.c @@ -1993,6 +1993,21 @@ static int dwc2_hcd_endpoint_disable(struct dwc2_hsotg *hsotg, } } + /* + * The hub driver still has a pointer to the endpoint. Wait until it + * has called _dwc2_hcd_clear_tt_buffer_complete(). + */ + while (qh->tt_buffer_dirty) { + spin_unlock_irqrestore(&hsotg->lock, flags); + msleep(20); + spin_lock_irqsave(&hsotg->lock, flags); + qh = ep->hcpriv; + if (!qh) { + rc = -EINVAL; + goto err; + } + } + dwc2_hcd_qh_unlink(hsotg, qh); /* Free each QTD in the QH's QTD list */ diff --git a/drivers/usb/dwc3/core.c b/drivers/usb/dwc3/core.c index 372737f4750b10..f4aa6a01e50013 100644 --- a/drivers/usb/dwc3/core.c +++ b/drivers/usb/dwc3/core.c @@ -2373,6 +2373,7 @@ int dwc3_core_probe(const struct dwc3_probe_data *data) } mutex_init(&dwc->mutex); + mutex_init(&dwc->connect_mutex); pm_runtime_get_noresume(dev); pm_runtime_set_active(dev); diff --git a/drivers/usb/dwc3/core.h b/drivers/usb/dwc3/core.h index f3dabb37f806b6..267c922ca11bb6 100644 --- a/drivers/usb/dwc3/core.h +++ b/drivers/usb/dwc3/core.h @@ -771,6 +771,7 @@ struct dwc3_ep { #define DWC3_EP_TXFIFO_RESIZED BIT(12) #define DWC3_EP_DELAY_STOP BIT(13) #define DWC3_EP_RESOURCE_ALLOCATED BIT(14) +#define DWC3_EP_PENDING_NOOP_START BIT(15) /* This last one is specific to EP0 */ #define DWC3_EP0_DIR_IN BIT(31) @@ -1695,7 +1696,8 @@ int dwc3_send_gadget_ep_cmd(struct dwc3_ep *dep, unsigned int cmd, int dwc3_send_gadget_generic_command(struct dwc3 *dwc, unsigned int cmd, u32 param); void dwc3_gadget_clear_tx_fifos(struct dwc3 *dwc); -void dwc3_remove_requests(struct dwc3 *dwc, struct dwc3_ep *dep, int status); +void dwc3_remove_requests(struct dwc3 *dwc, struct dwc3_ep *dep, int status, + bool interrupt); #else static inline int dwc3_gadget_init(struct dwc3 *dwc) { return 0; } diff --git a/drivers/usb/dwc3/dwc3-am62.c b/drivers/usb/dwc3/dwc3-am62.c index 88702868436472..80e3c74d8cfcdb 100644 --- a/drivers/usb/dwc3/dwc3-am62.c +++ b/drivers/usb/dwc3/dwc3-am62.c @@ -320,9 +320,11 @@ static void dwc3_ti_remove(struct platform_device *pdev) reg &= ~USBSS_MODE_VALID; dwc3_ti_writel(am62, USBSS_MODE_CONTROL, reg); - pm_runtime_put_sync(dev); + pm_runtime_put_noidle(dev); pm_runtime_disable(dev); pm_runtime_dont_use_autosuspend(dev); + if (!pm_runtime_status_suspended(dev)) + clk_disable_unprepare(am62->usb2_refclk); pm_runtime_set_suspended(dev); } diff --git a/drivers/usb/dwc3/dwc3-xilinx.c b/drivers/usb/dwc3/dwc3-xilinx.c index c9fb8c259493ef..095bc3dde0fa36 100644 --- a/drivers/usb/dwc3/dwc3-xilinx.c +++ b/drivers/usb/dwc3/dwc3-xilinx.c @@ -48,6 +48,9 @@ struct dwc3_xlnx { void __iomem *regs; int (*pltfm_init)(struct dwc3_xlnx *data); struct phy *usb3_phy; + struct reset_control *usb_crst; + struct reset_control *usb_hibrst; + struct reset_control *usb_apbrst; }; static void dwc3_xlnx_mask_phy_rst(struct dwc3_xlnx *priv_data, bool mask) @@ -109,10 +112,42 @@ static int dwc3_xlnx_init_versal(struct dwc3_xlnx *priv_data) return 0; } +static void dwc3_xlnx_zynqmp_teardown(void *data) +{ + struct dwc3_xlnx *priv_data = data; + + phy_power_off(priv_data->usb3_phy); + + /* + * Undo only the reset cycle init performed. As on the init error + * path, the unconditional deasserts are not paired with an assert + * here: with no usb3-phy, resetting the core could break a USB3 + * configuration that is live but missing from the device tree. + */ + if (priv_data->usb3_phy) { + reset_control_assert(priv_data->usb_hibrst); + reset_control_assert(priv_data->usb_crst); + reset_control_assert(priv_data->usb_apbrst); + } + + phy_exit(priv_data->usb3_phy); +} + +/* + * Run the platform teardown explicitly, so the resets are asserted while the + * clocks are still running. devm_release_action() unlinks the action before + * calling it, so devres will not run it a second time. + */ +static void dwc3_xlnx_release_teardown(struct device *dev, + struct dwc3_xlnx *priv_data) +{ + if (devm_is_action_added(dev, dwc3_xlnx_zynqmp_teardown, priv_data)) + devm_release_action(dev, dwc3_xlnx_zynqmp_teardown, priv_data); +} + static int dwc3_xlnx_init_zynqmp(struct dwc3_xlnx *priv_data) { struct device *dev = priv_data->dev; - struct reset_control *crst, *hibrst, *apbrst; struct gpio_desc *reset_gpio; int ret = 0; @@ -124,25 +159,25 @@ static int dwc3_xlnx_init_zynqmp(struct dwc3_xlnx *priv_data) goto err; } - crst = devm_reset_control_get_exclusive(dev, "usb_crst"); - if (IS_ERR(crst)) { - ret = PTR_ERR(crst); + priv_data->usb_crst = devm_reset_control_get_exclusive(dev, "usb_crst"); + if (IS_ERR(priv_data->usb_crst)) { + ret = PTR_ERR(priv_data->usb_crst); dev_err_probe(dev, ret, "failed to get core reset signal\n"); goto err; } - hibrst = devm_reset_control_get_exclusive(dev, "usb_hibrst"); - if (IS_ERR(hibrst)) { - ret = PTR_ERR(hibrst); + priv_data->usb_hibrst = devm_reset_control_get_exclusive(dev, "usb_hibrst"); + if (IS_ERR(priv_data->usb_hibrst)) { + ret = PTR_ERR(priv_data->usb_hibrst); dev_err_probe(dev, ret, "failed to get hibernation reset signal\n"); goto err; } - apbrst = devm_reset_control_get_exclusive(dev, "usb_apbrst"); - if (IS_ERR(apbrst)) { - ret = PTR_ERR(apbrst); + priv_data->usb_apbrst = devm_reset_control_get_exclusive(dev, "usb_apbrst"); + if (IS_ERR(priv_data->usb_apbrst)) { + ret = PTR_ERR(priv_data->usb_apbrst); dev_err_probe(dev, ret, "failed to get APB reset signal\n"); goto err; @@ -156,19 +191,19 @@ static int dwc3_xlnx_init_zynqmp(struct dwc3_xlnx *priv_data) * absent. */ if (priv_data->usb3_phy) { - ret = reset_control_assert(crst); + ret = reset_control_assert(priv_data->usb_crst); if (ret < 0) { dev_err(dev, "Failed to assert core reset\n"); goto err; } - ret = reset_control_assert(hibrst); + ret = reset_control_assert(priv_data->usb_hibrst); if (ret < 0) { dev_err(dev, "Failed to assert hibernation reset\n"); goto err; } - ret = reset_control_assert(apbrst); + ret = reset_control_assert(priv_data->usb_apbrst); if (ret < 0) { dev_err(dev, "Failed to assert APB reset\n"); goto err; @@ -179,7 +214,7 @@ static int dwc3_xlnx_init_zynqmp(struct dwc3_xlnx *priv_data) if (ret < 0) goto err; - ret = reset_control_deassert(apbrst); + ret = reset_control_deassert(priv_data->usb_apbrst); if (ret < 0) { dev_err(dev, "Failed to release APB reset\n"); goto err_phy_exit; @@ -195,21 +230,21 @@ static int dwc3_xlnx_init_zynqmp(struct dwc3_xlnx *priv_data) writel(PIPE_CLK_DESELECT, priv_data->regs + XLNX_USB_FPD_PIPE_CLK); } - ret = reset_control_deassert(crst); + ret = reset_control_deassert(priv_data->usb_crst); if (ret < 0) { dev_err(dev, "Failed to release core reset\n"); - goto err_phy_exit; + goto err_reset_assert; } - ret = reset_control_deassert(hibrst); + ret = reset_control_deassert(priv_data->usb_hibrst); if (ret < 0) { dev_err(dev, "Failed to release hibernation reset\n"); - goto err_phy_exit; + goto err_reset_assert; } ret = phy_power_on(priv_data->usb3_phy); if (ret < 0) - goto err_phy_exit; + goto err_reset_assert; /* ulpi reset via gpio-modepin or gpio-framework driver */ reset_gpio = devm_gpiod_get_optional(dev, "reset", GPIOD_OUT_HIGH); @@ -226,10 +261,26 @@ static int dwc3_xlnx_init_zynqmp(struct dwc3_xlnx *priv_data) dwc3_xlnx_set_coherency(priv_data, XLNX_USB_TRAFFIC_ROUTE_CONFIG); - return 0; + return devm_add_action_or_reset(dev, dwc3_xlnx_zynqmp_teardown, + priv_data); err_phy_power_off: phy_power_off(priv_data->usb3_phy); +err_reset_assert: + /* + * Undo only the reset cycle performed above. That cycle is skipped + * when there is no usb3-phy. The deasserts stay unconditional so a + * core the bootloader left in reset still comes up, but they are + * deliberately not paired with an assert here: resetting a USB3 + * configuration that is live but missing from the device tree could + * break it. Asserting an already asserted reset is harmless, so one + * block covers however far the cycle's deasserts got. + */ + if (priv_data->usb3_phy) { + reset_control_assert(priv_data->usb_hibrst); + reset_control_assert(priv_data->usb_crst); + reset_control_assert(priv_data->usb_apbrst); + } err_phy_exit: phy_exit(priv_data->usb3_phy); err: @@ -338,6 +389,7 @@ static int dwc3_xlnx_probe(struct platform_device *pdev) pm_runtime_set_suspended(dev); err_clk_put: + dwc3_xlnx_release_teardown(dev, priv_data); clk_bulk_disable_unprepare(priv_data->num_clocks, priv_data->clks); return ret; @@ -350,6 +402,13 @@ static void dwc3_xlnx_remove(struct platform_device *pdev) of_platform_depopulate(dev); + /* + * This is also what makes .shutdown behave the same as .remove: + * device_shutdown() does not call devres_release_all(), so a teardown + * left to devres would never run on the shutdown path. + */ + dwc3_xlnx_release_teardown(dev, priv_data); + clk_bulk_disable_unprepare(priv_data->num_clocks, priv_data->clks); priv_data->num_clocks = 0; @@ -383,13 +442,26 @@ static int __maybe_unused dwc3_xlnx_runtime_idle(struct device *dev) static int __maybe_unused dwc3_xlnx_suspend(struct device *dev) { struct dwc3_xlnx *priv_data = dev_get_drvdata(dev); + int ret; - phy_exit(priv_data->usb3_phy); + ret = phy_power_off(priv_data->usb3_phy); + if (ret < 0) + return ret; + + ret = phy_exit(priv_data->usb3_phy); + if (ret < 0) + goto err_phy_power_on; /* Disable the clocks */ clk_bulk_disable(priv_data->num_clocks, priv_data->clks); return 0; + +err_phy_power_on: + if (phy_power_on(priv_data->usb3_phy)) + dev_err(dev, "failed to restore PHY power after suspend error\n"); + + return ret; } static int __maybe_unused dwc3_xlnx_resume(struct device *dev) @@ -403,15 +475,20 @@ static int __maybe_unused dwc3_xlnx_resume(struct device *dev) ret = phy_init(priv_data->usb3_phy); if (ret < 0) - return ret; + goto err_clk_disable; ret = phy_power_on(priv_data->usb3_phy); if (ret < 0) { phy_exit(priv_data->usb3_phy); - return ret; + goto err_clk_disable; } return 0; + +err_clk_disable: + clk_bulk_disable(priv_data->num_clocks, priv_data->clks); + + return ret; } static const struct dev_pm_ops dwc3_xlnx_dev_pm_ops = { diff --git a/drivers/usb/dwc3/ep0.c b/drivers/usb/dwc3/ep0.c index 46a34c4a046b40..cf5a47b71efc81 100644 --- a/drivers/usb/dwc3/ep0.c +++ b/drivers/usb/dwc3/ep0.c @@ -315,7 +315,7 @@ void dwc3_ep0_out_start(struct dwc3 *dwc) if (dwc->connected) dwc3_stop_active_transfer(dwc3_ep, false, true); else - dwc3_remove_requests(dwc, dwc3_ep, -ESHUTDOWN); + dwc3_remove_requests(dwc, dwc3_ep, -ESHUTDOWN, false); } } diff --git a/drivers/usb/dwc3/gadget.c b/drivers/usb/dwc3/gadget.c index ee837235630ad9..c7d82a2550f525 100644 --- a/drivers/usb/dwc3/gadget.c +++ b/drivers/usb/dwc3/gadget.c @@ -906,6 +906,54 @@ static int dwc3_gadget_resize_tx_fifos(struct dwc3_ep *dep) return 0; } +static int dwc3_gadget_ep_start_noop_transfer(struct dwc3_ep *dep) +{ + struct dwc3_gadget_ep_cmd_params params; + struct dwc3 *dwc = dep->dwc; + struct dwc3_trb *trb; + dma_addr_t trb_dma; + u32 cmd; + int ret; + + memset(¶ms, 0, sizeof(params)); + trb = &dep->trb_pool[0]; + trb_dma = dwc3_trb_dma_offset(dep, trb); + + params.param0 = upper_32_bits(trb_dma); + params.param1 = lower_32_bits(trb_dma); + + cmd = DWC3_DEPCMD_STARTTRANSFER; + + ret = dwc3_send_gadget_ep_cmd(dep, cmd, ¶ms); + if (ret < 0) + return ret; + + /* + * For streams, at start, there maybe a race where the host primes the + * endpoint before the function driver queues a request to initiate a + * stream. In that case, the controller will not see the prime to + * generate the ERDY and start stream. To workaround this, issue a + * no-op TRB as normal, but end it immediately. As a result, when the + * function driver queues the request, the next START_TRANSFER command + * will cause the controller to generate an ERDY to initiate the + * stream. + */ + dwc3_stop_active_transfer(dep, false, true); + + /* + * All stream eps will reinitiate stream on NoStream rejection. + * + * However, if the controller is capable of TXF_FLUSH_BYPASS, then IN + * direction endpoints will automatically restart the stream without + * the driver initiation. + */ + if (!dep->direction || + !(dwc->hwparams.hwparams9 & DWC3_GHWPARAMS9_DEV_TXF_FLUSH_BYPASS)) + dep->flags |= DWC3_EP_FORCE_RESTART_STREAM; + + return 0; +} + /** * __dwc3_gadget_ep_enable - initializes a hw endpoint * @dep: endpoint to be initialized @@ -971,54 +1019,14 @@ static int __dwc3_gadget_ep_enable(struct dwc3_ep *dep, unsigned int action) * Issue StartTransfer here with no-op TRB so we can always rely on No * Response Update Transfer command. */ - if (usb_endpoint_xfer_bulk(desc) || - usb_endpoint_xfer_int(desc)) { - struct dwc3_gadget_ep_cmd_params params; - struct dwc3_trb *trb; - dma_addr_t trb_dma; - u32 cmd; - - memset(¶ms, 0, sizeof(params)); - trb = &dep->trb_pool[0]; - trb_dma = dwc3_trb_dma_offset(dep, trb); - - params.param0 = upper_32_bits(trb_dma); - params.param1 = lower_32_bits(trb_dma); - - cmd = DWC3_DEPCMD_STARTTRANSFER; - - ret = dwc3_send_gadget_ep_cmd(dep, cmd, ¶ms); - if (ret < 0) - return ret; - - if (dep->stream_capable) { - /* - * For streams, at start, there maybe a race where the - * host primes the endpoint before the function driver - * queues a request to initiate a stream. In that case, - * the controller will not see the prime to generate the - * ERDY and start stream. To workaround this, issue a - * no-op TRB as normal, but end it immediately. As a - * result, when the function driver queues the request, - * the next START_TRANSFER command will cause the - * controller to generate an ERDY to initiate the - * stream. - */ - dwc3_stop_active_transfer(dep, false, true); - - /* - * All stream eps will reinitiate stream on NoStream - * rejection. - * - * However, if the controller is capable of - * TXF_FLUSH_BYPASS, then IN direction endpoints will - * automatically restart the stream without the driver - * initiation. - */ - if (!dep->direction || - !(dwc->hwparams.hwparams9 & - DWC3_GHWPARAMS9_DEV_TXF_FLUSH_BYPASS)) - dep->flags |= DWC3_EP_FORCE_RESTART_STREAM; + if (dep->stream_capable) { + if (dep->flags & (DWC3_EP_END_TRANSFER_PENDING | + DWC3_EP_DELAY_STOP)) { + dep->flags |= DWC3_EP_PENDING_NOOP_START; + } else { + ret = dwc3_gadget_ep_start_noop_transfer(dep); + if (ret < 0) + return ret; } } @@ -1028,16 +1036,21 @@ static int __dwc3_gadget_ep_enable(struct dwc3_ep *dep, unsigned int action) return 0; } -void dwc3_remove_requests(struct dwc3 *dwc, struct dwc3_ep *dep, int status) +void dwc3_remove_requests(struct dwc3 *dwc, struct dwc3_ep *dep, int status, + bool interrupt) { struct dwc3_request *req; - dwc3_stop_active_transfer(dep, false, false); + dwc3_stop_active_transfer(dep, false, interrupt); /* If endxfer is delayed, avoid unmapping requests */ if (dep->flags & DWC3_EP_DELAY_STOP) return; + /* Give the controller time to stop accessing the request buffers */ + if (dep->flags & DWC3_EP_END_TRANSFER_PENDING) + mdelay(1); + /* - giveback all requests to gadget driver */ while (!list_empty(&dep->started_list)) { req = next_request(&dep->started_list); @@ -1084,7 +1097,9 @@ static int __dwc3_gadget_ep_disable(struct dwc3_ep *dep) reg &= ~DWC3_DALEPENA_EP(dep->number); dwc3_writel(dwc, DWC3_DALEPENA, reg); - dwc3_remove_requests(dwc, dep, -ESHUTDOWN); + dep->flags &= ~DWC3_EP_ENABLED; + + dwc3_remove_requests(dwc, dep, -ESHUTDOWN, true); dep->stream_capable = false; dep->type = 0; @@ -1096,6 +1111,15 @@ static int __dwc3_gadget_ep_disable(struct dwc3_ep *dep) */ if (dep->flags & DWC3_EP_DELAY_STOP) mask |= (DWC3_EP_DELAY_STOP | DWC3_EP_TRANSFER_STARTED); + + /* + * The End Transfer command is still in progress. Do not clear the + * flags, so that the ep is only rearmed once the command completes. + */ + if (dep->flags & DWC3_EP_END_TRANSFER_PENDING) + mask |= (DWC3_EP_END_TRANSFER_PENDING | + DWC3_EP_TRANSFER_STARTED); + dep->flags &= mask; /* Clear out the ep descriptors for non-ep0 */ @@ -1751,6 +1775,8 @@ static int __dwc3_gadget_get_frame(struct dwc3 *dwc) return DWC3_DSTS_SOFFN(reg); } +static void dwc3_schedule_err_recovery(struct dwc3 *dwc); + /** * __dwc3_stop_active_transfer - stop the current active transfer * @dep: isoc endpoint @@ -1794,11 +1820,14 @@ static int __dwc3_stop_active_transfer(struct dwc3_ep *dep, bool force, bool int dev_err_ratelimited(dep->dwc->dev, "end transfer failed: %d\n", ret); + if (ret == -ETIMEDOUT && dep->dwc->err_state == DWC3_ERR_NONE) + dwc3_schedule_err_recovery(dep->dwc); + dep->resource_index = 0; - if (!interrupt) + if (!interrupt || (ret && ret != -ETIMEDOUT)) dep->flags &= ~DWC3_EP_TRANSFER_STARTED; - else if (!ret) + else dep->flags |= DWC3_EP_END_TRANSFER_PENDING; dep->flags &= ~DWC3_EP_DELAY_STOP; @@ -1990,7 +2019,8 @@ static int __dwc3_gadget_ep_queue(struct dwc3_ep *dep, struct dwc3_request *req) { struct dwc3 *dwc = dep->dwc; - if (!dep->endpoint.desc || !dwc->pullups_connected || !dwc->connected) { + if (!(dep->flags & DWC3_EP_ENABLED) || !dep->endpoint.desc || + !dwc->pullups_connected || !dwc->connected) { dev_dbg(dwc->dev, "%s: can't queue to disabled endpoint\n", dep->name); return -ESHUTDOWN; @@ -2547,7 +2577,7 @@ static void dwc3_stop_active_transfers(struct dwc3 *dwc) if (!dep) continue; - dwc3_remove_requests(dwc, dep, -ESHUTDOWN); + dwc3_remove_requests(dwc, dep, -ESHUTDOWN, false); } } @@ -2947,6 +2977,7 @@ static int __dwc3_gadget_start(struct dwc3 *dwc) { struct dwc3_ep *dep; int ret = 0; + u32 epnum; u32 reg; /* @@ -3004,6 +3035,15 @@ static int __dwc3_gadget_start(struct dwc3 *dwc) return ret; } + for (epnum = 2; epnum < dwc->num_eps; epnum++) { + dep = dwc->eps[epnum]; + if (!dep) + continue; + + dep->flags &= (DWC3_EP_TXFIFO_RESIZED | + DWC3_EP_RESOURCE_ALLOCATED); + } + dep = dwc->eps[0]; dep->flags = 0; ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT); @@ -3872,6 +3912,7 @@ static void dwc3_gadget_endpoint_command_complete(struct dwc3_ep *dep, if (dep->stream_capable) dep->flags |= DWC3_EP_IGNORE_NEXT_NOSTREAM; + dep->flags &= ~DWC3_EP_DELAY_STOP; dep->flags &= ~DWC3_EP_END_TRANSFER_PENDING; dep->flags &= ~DWC3_EP_TRANSFER_STARTED; dwc3_gadget_ep_cleanup_cancelled_requests(dep); @@ -3894,7 +3935,16 @@ static void dwc3_gadget_endpoint_command_complete(struct dwc3_ep *dep, dwc3_ep0_send_delayed_status(dwc); } + if (dep->flags & DWC3_EP_PENDING_NOOP_START) { + dep->flags &= ~DWC3_EP_PENDING_NOOP_START; + + if (!(dep->flags & DWC3_EP_DELAY_START) && + (dep->flags & DWC3_EP_ENABLED)) + dwc3_gadget_ep_start_noop_transfer(dep); + } + if ((dep->flags & DWC3_EP_DELAY_START) && + (dep->flags & DWC3_EP_ENABLED) && !usb_endpoint_xfer_isoc(dep->endpoint.desc)) __dwc3_gadget_kick_transfer(dep); @@ -4879,7 +4929,6 @@ int dwc3_gadget_init(struct dwc3 *dwc) init_completion(&dwc->ep0_in_setup); INIT_WORK(&dwc->err_recovery_work, dwc3_err_recovery_work); - mutex_init(&dwc->connect_mutex); dwc->gadget = kzalloc_obj(struct usb_gadget); if (!dwc->gadget) { ret = -ENOMEM; @@ -4977,7 +5026,6 @@ void dwc3_gadget_exit(struct dwc3 *dwc) return; cancel_work_sync(&dwc->err_recovery_work); - mutex_destroy(&dwc->connect_mutex); dwc3_enable_susphy(dwc, true); usb_del_gadget(dwc->gadget); dwc3_gadget_free_endpoints(dwc); diff --git a/drivers/usb/dwc3/host.c b/drivers/usb/dwc3/host.c index c5674161b2b08e..cd1e5204ac3a9b 100644 --- a/drivers/usb/dwc3/host.c +++ b/drivers/usb/dwc3/host.c @@ -130,7 +130,7 @@ static int dwc3_host_get_irq(struct dwc3 *dwc) int dwc3_host_init(struct dwc3 *dwc) { - struct property_entry props[6]; + struct property_entry props[7]; struct platform_device *xhci; int ret, irq; int prop_idx = 0; @@ -219,12 +219,16 @@ int dwc3_host_init(struct dwc3 *dwc) return 0; err: platform_device_put(xhci); + dwc->xhci = NULL; return ret; } EXPORT_SYMBOL_GPL(dwc3_host_init); void dwc3_host_exit(struct dwc3 *dwc) { + if (!dwc->xhci) + return; + if (dwc->sys_wakeup) device_init_wakeup(&dwc->xhci->dev, false); diff --git a/drivers/usb/dwc3/trace.h b/drivers/usb/dwc3/trace.h index 5253da23d8b003..0caaa0b396d1c4 100644 --- a/drivers/usb/dwc3/trace.h +++ b/drivers/usb/dwc3/trace.h @@ -141,6 +141,7 @@ DECLARE_EVENT_CLASS(dwc3_log_request, ), TP_fast_assign( __entry->base_address = req->dep->dwc->xhci_resources[0].start; + __assign_str(name); __entry->req = req; __entry->actual = req->request.actual; __entry->length = req->request.length; diff --git a/drivers/usb/gadget/composite.c b/drivers/usb/gadget/composite.c index 1b2238147cfe38..de677685069a22 100644 --- a/drivers/usb/gadget/composite.c +++ b/drivers/usb/gadget/composite.c @@ -1930,7 +1930,7 @@ composite_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl) break; spin_lock(&cdev->lock); - value = f->set_alt(f, w_index, w_value); + value = f->set_alt(f, intf, w_value); if (value == USB_GADGET_DELAYED_STATUS) { DBG(cdev, "%s: interface %d (%s) requested delayed status\n", @@ -1950,7 +1950,7 @@ composite_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl) if (!f) break; /* lots of interfaces only need altsetting zero... */ - value = f->get_alt ? f->get_alt(f, w_index) : 0; + value = f->get_alt ? f->get_alt(f, intf) : 0; if (value < 0) break; *((u8 *)req->buf) = value; diff --git a/drivers/usb/gadget/configfs.c b/drivers/usb/gadget/configfs.c index 51df6d1d1487af..568b2a0a6df812 100644 --- a/drivers/usb/gadget/configfs.c +++ b/drivers/usb/gadget/configfs.c @@ -1351,9 +1351,10 @@ static ssize_t ext_prop_data_store(struct config_item *item, if (page[len - 1] == '\n' || page[len - 1] == '\0') --len; - new_data = kmemdup(page, len, GFP_KERNEL); + new_data = kzalloc(len + 1, GFP_KERNEL); if (!new_data) return -ENOMEM; + memcpy(new_data, page, len); if (desc->opts_mutex) mutex_lock(desc->opts_mutex); diff --git a/drivers/usb/gadget/function/f_ecm.c b/drivers/usb/gadget/function/f_ecm.c index e495bac4efeb5a..c8c3a7d1c80426 100644 --- a/drivers/usb/gadget/function/f_ecm.c +++ b/drivers/usb/gadget/function/f_ecm.c @@ -581,14 +581,6 @@ static int ecm_set_alt(struct usb_function *f, unsigned intf, unsigned alt) if (IS_ERR(net)) return PTR_ERR(net); } - - /* NOTE this can be a minor disagreement with the ECM spec, - * which says speed notifications will "always" follow - * connection notifications. But we allow one connect to - * follow another (if the first is in flight), and instead - * just guarantee that a speed notification is always sent. - */ - ecm_notify(ecm); } else goto fail; diff --git a/drivers/usb/gadget/function/f_fs.c b/drivers/usb/gadget/function/f_fs.c index c64a268e98a433..c4fba4d11570a1 100644 --- a/drivers/usb/gadget/function/f_fs.c +++ b/drivers/usb/gadget/function/f_fs.c @@ -246,6 +246,7 @@ struct ffs_buffer { struct ffs_io_data { bool aio; bool read; + bool aio_active; struct kiocb *kiocb; struct iov_iter data; @@ -884,9 +885,11 @@ static void ffs_user_copy_worker(struct work_struct *work) } else { ret = -EFAULT; } - mmdrop(io_data->mm); } + mmdrop(io_data->mm); + /* Make sure kiocb_set_cancel_fn() was already called. */ + smp_cond_load_acquire(&io_data->aio_active, VAL == true); io_data->kiocb->ki_complete(io_data->kiocb, ret); if (io_data->ffs->ffs_eventfd && !kiocb_has_eventfd) @@ -1014,8 +1017,12 @@ static struct ffs_ep *ffs_epfile_wait_ep(struct ffs_epfile *epfile, struct file return ep; } -static ssize_t ffs_epfile_io(struct file *file, struct ffs_io_data *io_data) +static int ffs_aio_cancel(struct kiocb *kiocb); + +static ssize_t ffs_epfile_io(struct ffs_io_data *io_data) { + struct kiocb *kiocb = io_data->kiocb; + struct file *file = kiocb->ki_filp; struct ffs_epfile *epfile = file->private_data; struct usb_request *req; struct ffs_ep *ep; @@ -1104,11 +1111,17 @@ static ssize_t ffs_epfile_io(struct file *file, struct ffs_io_data *io_data) if (epfile->ep != ep) { /* In the meantime, endpoint got disabled or changed. */ ret = -ESHUTDOWN; - } else if (halt) { + goto error_lock; + } + + if (halt) { ret = usb_ep_set_halt(ep->ep); if (!ret) ret = -EBADMSG; - } else if (data_len == -EINVAL) { + goto error_lock; + } + + if (data_len == -EINVAL) { /* * Sanity Check: even though data_len can't be used * uninitialized at the time I write this comment, some @@ -1122,7 +1135,10 @@ static ssize_t ffs_epfile_io(struct file *file, struct ffs_io_data *io_data) */ WARN(1, "%s: data_len == -EINVAL\n", __func__); ret = -EINVAL; - } else if (!io_data->aio) { + goto error_lock; + } + + if (!io_data->aio) { bool interrupted = false; req = ep->req; @@ -1176,43 +1192,51 @@ static ssize_t ffs_epfile_io(struct file *file, struct ffs_io_data *io_data) else ret = io_data->status; goto error_mutex; - } else if (!(req = usb_ep_alloc_request(ep->ep, GFP_ATOMIC))) { + } + + /* It's an AIO request */ + req = usb_ep_alloc_request(ep->ep, GFP_ATOMIC); + if (!req) { ret = -ENOMEM; - } else { - if (io_data->use_sg) { - req->buf = NULL; - req->sg = io_data->sgt.sgl; - req->num_sgs = io_data->sgt.nents; - } else { - req->buf = data; - req->num_sgs = 0; - } + goto error_lock; + } - req->zero = !io_data->read ? epfile->zlp_enabled : 0; - req->length = data_len; + if (io_data->use_sg) { + req->buf = NULL; + req->sg = io_data->sgt.sgl; + req->num_sgs = io_data->sgt.nents; + } else { + req->buf = data; + req->num_sgs = 0; + } - io_data->buf = data; - io_data->ep = ep->ep; - io_data->req = req; - io_data->ffs = epfile->ffs; + req->zero = !io_data->read ? epfile->zlp_enabled : 0; + req->length = data_len; - req->context = io_data; - req->complete = ffs_epfile_async_io_complete; + io_data->buf = data; + io_data->ep = ep->ep; + io_data->req = req; + io_data->ffs = epfile->ffs; - ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC); - if (ret) { - io_data->req = NULL; - usb_ep_free_request(ep->ep, req); - goto error_lock; - } + req->context = io_data; + req->complete = ffs_epfile_async_io_complete; - ret = -EIOCBQUEUED; - /* - * Do not kfree the buffer in this function. It will be freed - * by ffs_user_copy_worker. - */ - data = NULL; + ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC); + if (ret) { + io_data->req = NULL; + usb_ep_free_request(ep->ep, req); + goto error_lock; } + kiocb->private = io_data; + kiocb_set_cancel_fn(kiocb, ffs_aio_cancel); + /* + * prevent ffs_user_copy_worker() from calling + * io_data->kiocb->ki_complete() + * before kiocb_set_cancel_fn() was called. + */ + smp_store_release(&io_data->aio_active, true); + + ret = -EIOCBQUEUED; error_lock: spin_unlock_irq(&epfile->ffs->eps_lock); @@ -1285,21 +1309,15 @@ static ssize_t ffs_epfile_write_iter(struct kiocb *kiocb, struct iov_iter *from) p->data = *from; p->mm = current->mm; - kiocb->private = p; - - if (p->aio) { + if (p->aio) mmgrab(p->mm); - kiocb_set_cancel_fn(kiocb, ffs_aio_cancel); - } - res = ffs_epfile_io(kiocb->ki_filp, p); + res = ffs_epfile_io(p); if (res == -EIOCBQUEUED) return res; if (p->aio) { - kiocb->ki_complete(kiocb, res); mmdrop(p->mm); kfree(p); - return -EIOCBQUEUED; } else { *from = p->data; } @@ -1335,23 +1353,17 @@ static ssize_t ffs_epfile_read_iter(struct kiocb *kiocb, struct iov_iter *to) } p->mm = current->mm; - kiocb->private = p; - - if (p->aio) { + if (p->aio) mmgrab(p->mm); - kiocb_set_cancel_fn(kiocb, ffs_aio_cancel); - } - res = ffs_epfile_io(kiocb->ki_filp, p); + res = ffs_epfile_io(p); if (res == -EIOCBQUEUED) return res; if (p->aio) { - kiocb->ki_complete(kiocb, res); mmdrop(p->mm); kfree(p->to_free); kfree(p); - return -EIOCBQUEUED; } else { *to = p->data; } @@ -1447,13 +1459,12 @@ static void ffs_dmabuf_signal_done(struct ffs_dma_fence *dma_fence, int ret) struct dma_fence *fence = &dma_fence->base; bool cookie = dma_fence_begin_signalling(); - dma_fence_get(fence); fence->error = ret; dma_fence_signal(fence); dma_fence_end_signalling(cookie); /* - * The fence will be unref'd in ffs_dmabuf_cleanup. + * The reference of the request will be dropped in ffs_dmabuf_cleanup. * It can't be done here, as the unref functions might try to lock * the resv object, which would deadlock. */ @@ -1737,8 +1748,13 @@ static int ffs_dmabuf_transfer(struct file *file, resv_dir = epfile->in ? DMA_RESV_USAGE_READ : DMA_RESV_USAGE_WRITE; + /* + * The reservation object takes a reference of its own, and drops it as + * soon as a later fence of this attachment takes the place of this + * one. The initial reference stays with the request, which points to + * the fence until ffs_dmabuf_cleanup() has run. + */ dma_resv_add_fence(dmabuf->resv, &fence->base, resv_dir); - dma_fence_put(&fence->base); dma_resv_unlock(dmabuf->resv); /* Now that the dma_fence is in place, queue the transfer. */ @@ -2462,7 +2478,7 @@ static int ffs_epfiles_create(struct ffs_data *ffs) mutex_init(&comp->mutex); mutex_init(&comp->dmabufs_mutex); INIT_LIST_HEAD(&comp->dmabufs); - snprintf(comp->name, sizeof(comp->name), "%s_rw", + snprintf(comp->name, sizeof(comp->name), "%.4s_rw", epfiles[i].name); err = ffs_sb_create_file(ffs->sb, comp->name, comp, &ffs_epfile_operations); diff --git a/drivers/usb/gadget/function/f_hid.c b/drivers/usb/gadget/function/f_hid.c index 3c6b43d06a6d1d..428635e580bb7e 100644 --- a/drivers/usb/gadget/function/f_hid.c +++ b/drivers/usb/gadget/function/f_hid.c @@ -94,8 +94,11 @@ struct f_hidg { /* get report */ struct usb_request *get_req; - struct usb_hidg_report get_report; + void *get_req_buf; bool get_report_returned; + /* Cancel pending work and distinguish requests across reconfiguration. */ + bool get_report_cancelled; + unsigned int get_report_req_tag; int get_report_req_report_id; int get_report_req_report_length; spinlock_t get_report_spinlock; @@ -121,7 +124,14 @@ static inline struct f_hidg *func_to_hidg(struct usb_function *f) static void hidg_release(struct device *dev) { struct f_hidg *hidg = container_of(dev, struct f_hidg, dev); + struct report_entry *entry, *tmp; + list_for_each_entry_safe(entry, tmp, &hidg->report_list, node) { + list_del(&entry->node); + kfree(entry); + } + + kfree(hidg->get_req_buf); kfree(hidg->report_desc); kfree(hidg->set_report_buf); kfree(hidg); @@ -562,10 +572,16 @@ static void get_report_workqueue_handler(struct work_struct *work) struct usb_request *req; struct report_entry *ptr; unsigned long flags; + unsigned int req_tag; int status = 0; spin_lock_irqsave(&hidg->get_report_spinlock, flags); + if (hidg->get_report_cancelled) { + spin_unlock_irqrestore(&hidg->get_report_spinlock, flags); + return; + } + req_tag = hidg->get_report_req_tag; req = hidg->get_req; if (!req) { spin_unlock_irqrestore(&hidg->get_report_spinlock, flags); @@ -581,7 +597,7 @@ static void get_report_workqueue_handler(struct work_struct *work) ptr = f_hidg_search_for_report(hidg, hidg->get_report_req_report_id); if (ptr && !ptr->report_data.userspace_req) { /* Report exists in list and it is to be used for immediate response */ - req->buf = ptr->report_data.data; + memcpy(req->buf, ptr->report_data.data, req->length); status = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC); hidg->get_report_returned = true; spin_unlock_irqrestore(&hidg->get_report_spinlock, flags); @@ -598,6 +614,11 @@ static void get_report_workqueue_handler(struct work_struct *work) status = wait_event_interruptible_timeout(hidg->get_queue, !GET_REPORT_COND, msecs_to_jiffies(GET_REPORT_TIMEOUT_MS)); spin_lock_irqsave(&hidg->get_report_spinlock, flags); + if (hidg->get_report_cancelled || + req_tag != hidg->get_report_req_tag) { + spin_unlock_irqrestore(&hidg->get_report_spinlock, flags); + return; + } req = hidg->get_req; if (!req) { spin_unlock_irqrestore(&hidg->get_report_spinlock, flags); @@ -616,10 +637,9 @@ static void get_report_workqueue_handler(struct work_struct *work) * Either get an updated response just serviced by userspace * or send the latest response in the list */ - req->buf = ptr->report_data.data; + memcpy(req->buf, ptr->report_data.data, req->length); } else { /* If there are no prevoiusly sent reports send empty report */ - req->buf = hidg->get_report.data; memset(req->buf, 0x0, req->length); } @@ -668,13 +688,7 @@ static int f_hidg_get_report(struct file *file, struct usb_hidg_report __user *b if (ptr) { /* Report already exists in list - update it */ - if (copy_from_user(&ptr->report_data, buffer, - sizeof(struct usb_hidg_report))) { - spin_unlock_irqrestore(&hidg->get_report_spinlock, flags); - ERROR(cdev, "copy_from_user error\n"); - kfree(entry); - return -EINVAL; - } + ptr->report_data = entry->report_data; kfree(entry); } else { /* Report does not exist in list - add it */ @@ -864,6 +878,8 @@ static int hidg_setup(struct usb_function *f, * GET_REPORT the request was actually for. */ spin_lock_irqsave(&hidg->get_report_spinlock, flags); + hidg->get_report_cancelled = false; + hidg->get_report_req_tag++; hidg->get_report_req_report_id = value & 0xff; hidg->get_report_req_report_length = length; spin_unlock_irqrestore(&hidg->get_report_spinlock, flags); @@ -997,12 +1013,11 @@ static void hidg_disable(struct usb_function *f) } spin_lock_irqsave(&hidg->get_report_spinlock, flags); - if (!hidg->get_report_returned) { - usb_ep_free_request(f->config->cdev->gadget->ep0, hidg->get_req); - hidg->get_req = NULL; - hidg->get_report_returned = true; - } + hidg->get_report_cancelled = true; + hidg->get_report_req_tag++; + hidg->get_report_returned = true; spin_unlock_irqrestore(&hidg->get_report_spinlock, flags); + wake_up(&hidg->get_queue); spin_lock_irqsave(&hidg->read_spinlock, flags); hidg->disabled = true; @@ -1155,6 +1170,15 @@ static int hidg_bind(struct usb_configuration *c, struct usb_function *f) if (!hidg->get_req) return -ENOMEM; + /* + * The GET_REPORT response is served from a dedicated buffer + * (allocated in hidg_alloc()), not from the report_list + * entries: userspace may update an entry while the controller + * is still reading the previous response, which would corrupt + * the data on the wire. + */ + hidg->get_req->buf = hidg->get_req_buf; + hidg->get_req->zero = 0; hidg->get_req->complete = hidg_get_report_complete; hidg->get_req->context = hidg; @@ -1163,8 +1187,10 @@ static int hidg_bind(struct usb_configuration *c, struct usb_function *f) /* maybe allocate device-global string IDs, and patch descriptors */ us = usb_gstrings_attach(c->cdev, ct_func_strings, ARRAY_SIZE(ct_func_string_defs)); - if (IS_ERR(us)) - return PTR_ERR(us); + if (IS_ERR(us)) { + status = PTR_ERR(us); + goto fail; + } hidg_interface_desc.iInterface = us[CT_FUNC_HID_IDX].id; /* allocate instance-specific interface IDs, and patch descriptors */ @@ -1588,6 +1614,7 @@ static void hidg_unbind(struct usb_configuration *c, struct usb_function *f) cdev_device_del(hidg->cdev, &hidg->dev); destroy_workqueue(hidg->workqueue); + usb_ep_free_request(c->cdev->gadget->ep0, hidg->get_req); usb_free_all_descriptors(f); } @@ -1641,6 +1668,18 @@ static struct usb_function *hidg_alloc(struct usb_function_instance *fi) } hidg->use_out_ep = !opts->no_out_endpoint; + /* + * Dedicated buffer for GET_REPORT responses, allocated once for + * the whole lifetime of this function instance: hidg_release() + * is the only safe free point, as it runs after all USB + * activity has ceased and all file references are gone. + */ + hidg->get_req_buf = kmalloc(MAX_REPORT_LENGTH, GFP_KERNEL); + if (!hidg->get_req_buf) { + ret = -ENOMEM; + goto err_put_device; + } + ++opts->refcnt; mutex_unlock(&opts->lock); diff --git a/drivers/usb/gadget/function/f_loopback.c b/drivers/usb/gadget/function/f_loopback.c index d2d07fb49e704b..40aaf2eb00f24d 100644 --- a/drivers/usb/gadget/function/f_loopback.c +++ b/drivers/usb/gadget/function/f_loopback.c @@ -216,6 +216,11 @@ static int loopback_bind(struct usb_configuration *c, struct usb_function *f) return 0; } +static void loopback_unbind(struct usb_configuration *c, struct usb_function *f) +{ + usb_free_all_descriptors(f); +} + static void lb_free_func(struct usb_function *f) { struct f_lb_opts *opts; @@ -226,7 +231,6 @@ static void lb_free_func(struct usb_function *f) opts->refcnt--; mutex_unlock(&opts->lock); - usb_free_all_descriptors(f); kfree(func_to_loop(f)); } @@ -442,6 +446,7 @@ static struct usb_function *loopback_alloc(struct usb_function_instance *fi) loop->function.name = "loopback"; loop->function.bind = loopback_bind; + loop->function.unbind = loopback_unbind; loop->function.set_alt = loopback_set_alt; loop->function.disable = loopback_disable; loop->function.strings = loopback_strings; diff --git a/drivers/usb/gadget/function/f_mass_storage.c b/drivers/usb/gadget/function/f_mass_storage.c index e3c9b7ab9f39ba..52314a00d8e64f 100644 --- a/drivers/usb/gadget/function/f_mass_storage.c +++ b/drivers/usb/gadget/function/f_mass_storage.c @@ -2669,8 +2669,9 @@ static ssize_t nofua_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct fsg_lun *curlun = fsg_lun_from_dev(dev); + struct rw_semaphore *filesem = dev_get_drvdata(dev); - return fsg_store_nofua(curlun, buf, count); + return fsg_store_nofua(curlun, filesem, buf, count); } static ssize_t file_store(struct device *dev, struct device_attribute *attr, @@ -3248,7 +3249,10 @@ static ssize_t fsg_lun_opts_nofua_show(struct config_item *item, char *page) static ssize_t fsg_lun_opts_nofua_store(struct config_item *item, const char *page, size_t len) { - return fsg_store_nofua(to_fsg_lun_opts(item)->lun, page, len); + struct fsg_lun_opts *opts = to_fsg_lun_opts(item); + struct fsg_opts *fsg_opts = to_fsg_opts(opts->group.cg_item.ci_parent); + + return fsg_store_nofua(opts->lun, &fsg_opts->common->filesem, page, len); } CONFIGFS_ATTR(fsg_lun_opts_, nofua); diff --git a/drivers/usb/gadget/function/f_midi.c b/drivers/usb/gadget/function/f_midi.c index 63fb6ee70a3d65..48cda34399e818 100644 --- a/drivers/usb/gadget/function/f_midi.c +++ b/drivers/usb/gadget/function/f_midi.c @@ -420,6 +420,7 @@ static void f_midi_disable(struct usb_function *f) struct f_midi *midi = func_to_midi(f); struct usb_composite_dev *cdev = f->config->cdev; struct usb_request *req = NULL; + unsigned long flags; DBG(cdev, "disable\n"); @@ -431,8 +432,10 @@ static void f_midi_disable(struct usb_function *f) usb_ep_disable(midi->out_ep); /* release IN requests */ + spin_lock_irqsave(&midi->transmit_lock, flags); while (kfifo_get(&midi->in_req_fifo, &req)) free_ep_req(midi->in_ep, req); + spin_unlock_irqrestore(&midi->transmit_lock, flags); f_midi_drop_out_substreams(midi); } @@ -661,6 +664,7 @@ static int f_midi_do_transmit(struct f_midi *midi, struct usb_ep *ep) ERROR(midi, "%s failed to queue req: %d\n", midi->in_ep->name, err); req->length = 0; /* Re-use request next time. */ + return err; } else { /* Upon success, put request at the back of the queue. */ kfifo_skip(&midi->in_req_fifo); diff --git a/drivers/usb/gadget/function/f_midi2.c b/drivers/usb/gadget/function/f_midi2.c index d693de427641dd..c02d6f11be14f8 100644 --- a/drivers/usb/gadget/function/f_midi2.c +++ b/drivers/usb/gadget/function/f_midi2.c @@ -171,6 +171,31 @@ static const char *ump_fb_name(const struct f_midi2_block_info *info) return info->name ? info->name : "MIDI 2.0 Gadget I/O"; } +static int f_midi2_copy_string(const char **dst, const char *src) +{ + *dst = NULL; + if (!src) + return 0; + + *dst = kstrdup(src, GFP_KERNEL); + return *dst ? 0 : -ENOMEM; +} + +static void f_midi2_free_strings(struct f_midi2 *midi2) +{ + int i, blk; + + kfree(midi2->info.iface_name); + for (i = 0; i < midi2->num_eps; i++) { + struct f_midi2_ep *ep = &midi2->midi2_eps[i]; + + kfree(ep->info.ep_name); + kfree(ep->info.product_id); + for (blk = 0; blk < ep->num_blks; blk++) + kfree(ep->blks[blk].info.name); + } +} + /* * USB Descriptor Definitions */ @@ -2701,6 +2726,7 @@ static void do_f_midi2_free(struct f_midi2 *midi2, struct f_midi2_opts *opts) --opts->refcnt; mutex_unlock(&opts->lock); kfree(midi2->string_defs); + f_midi2_free_strings(midi2); kfree(midi2); } @@ -2811,7 +2837,7 @@ static struct usb_function *f_midi2_alloc(struct usb_function_instance *fi) struct f_midi2_opts *opts; struct f_midi2_ep *ep; struct f_midi2_block *bp; - int i, num_eps, blk; + int i, num_eps, blk, ret; midi2 = kzalloc_obj(*midi2); if (!midi2) @@ -2826,7 +2852,6 @@ static struct usb_function *f_midi2_alloc(struct usb_function_instance *fi) return ERR_PTR(num_eps); } ++opts->refcnt; - mutex_unlock(&opts->lock); spin_lock_init(&midi2->queue_lock); @@ -2841,19 +2866,38 @@ static struct usb_function *f_midi2_alloc(struct usb_function_instance *fi) midi2->info = opts->info; midi2->num_eps = num_eps; + ret = f_midi2_copy_string(&midi2->info.iface_name, + opts->info.iface_name); + if (ret) + goto err_unlock; for (i = 0; i < num_eps; i++) { ep = &midi2->midi2_eps[i]; ep->info = opts->eps[i]->info; + ep->info.ep_name = NULL; + ep->info.product_id = NULL; + ret = f_midi2_copy_string(&ep->info.ep_name, + opts->eps[i]->info.ep_name); + if (ret) + goto err_unlock; + ret = f_midi2_copy_string(&ep->info.product_id, + opts->eps[i]->info.product_id); + if (ret) + goto err_unlock; ep->card = midi2; for (blk = 0; blk < SNDRV_UMP_MAX_BLOCKS && opts->eps[i]->blks[blk]; blk++) { bp = &ep->blks[blk]; ep->num_blks++; bp->info = opts->eps[i]->blks[blk]->info; + ret = f_midi2_copy_string(&bp->info.name, + opts->eps[i]->blks[blk]->info.name); + if (ret) + goto err_unlock; bp->gtb_id = ++midi2->total_blocks; } } + mutex_unlock(&opts->lock); midi2->string_defs = kzalloc_objs(*midi2->string_defs, midi2->total_blocks + 1); @@ -2862,8 +2906,8 @@ static struct usb_function *f_midi2_alloc(struct usb_function_instance *fi) return ERR_PTR(-ENOMEM); } - if (opts->info.iface_name && *opts->info.iface_name) - midi2->string_defs[STR_IFACE].s = opts->info.iface_name; + if (midi2->info.iface_name && *midi2->info.iface_name) + midi2->string_defs[STR_IFACE].s = midi2->info.iface_name; else midi2->string_defs[STR_IFACE].s = ump_ep_name(&midi2->midi2_eps[0]); @@ -2885,6 +2929,11 @@ static struct usb_function *f_midi2_alloc(struct usb_function_instance *fi) } return &midi2->func; + +err_unlock: + mutex_unlock(&opts->lock); + do_f_midi2_free(midi2, opts); + return ERR_PTR(ret); } DECLARE_USB_FUNCTION_INIT(midi2, f_midi2_alloc_inst, f_midi2_alloc); diff --git a/drivers/usb/gadget/function/f_ncm.c b/drivers/usb/gadget/function/f_ncm.c index 7f4324981eb31a..5b28b871b0f3b9 100644 --- a/drivers/usb/gadget/function/f_ncm.c +++ b/drivers/usb/gadget/function/f_ncm.c @@ -921,10 +921,6 @@ static int ncm_set_alt(struct usb_function *f, unsigned intf, unsigned alt) return PTR_ERR(net); ncm->netdev = net; } - - spin_lock(&ncm->lock); - ncm_notify(ncm); - spin_unlock(&ncm->lock); } else goto fail; @@ -1132,10 +1128,14 @@ static struct sk_buff *ncm_wrap_ntb(struct gether *port, if (skb) dev_kfree_skb_any(skb); - if (ncm->skb_tx_data) + if (ncm->skb_tx_data) { dev_kfree_skb_any(ncm->skb_tx_data); - if (ncm->skb_tx_ndp) + ncm->skb_tx_data = NULL; + } + if (ncm->skb_tx_ndp) { dev_kfree_skb_any(ncm->skb_tx_ndp); + ncm->skb_tx_ndp = NULL; + } return NULL; } @@ -1148,6 +1148,7 @@ static enum hrtimer_restart ncm_tx_timeout(struct hrtimer *data) { struct f_ncm *ncm = container_of(data, struct f_ncm, task_timer); struct net_device *netdev = READ_ONCE(ncm->netdev); + netdev_tx_t ret; if (netdev) { /* XXX This allowance of a NULL skb argument to ndo_start_xmit @@ -1158,7 +1159,11 @@ static enum hrtimer_restart ncm_tx_timeout(struct hrtimer *data) * * This will call directly into u_ether's eth_start_xmit() */ - netdev->netdev_ops->ndo_start_xmit(NULL, netdev); + ret = netdev->netdev_ops->ndo_start_xmit(NULL, netdev); + if (ret == NETDEV_TX_BUSY) { + hrtimer_forward_now(data, TX_TIMEOUT_NSECS); + return HRTIMER_RESTART; + } } return HRTIMER_NORESTART; } @@ -1175,6 +1180,7 @@ static int ncm_unwrap_ntb(struct gether *port, unsigned dg_len, dg_len2; unsigned ndp_len; unsigned block_len; + unsigned int ndp_count, next_ndp_index; struct sk_buff *skb2; int ret = -EINVAL; unsigned ntb_max = le32_to_cpu(ntb_parameters.dwNtbOutMaxSize); @@ -1224,6 +1230,30 @@ static int ncm_unwrap_ntb(struct gether *port, } ndp_index = get_ncm(&tmp, opts->ndp_index); + next_ndp_index = ndp_index; + ndp_count = 0; + + /* Validate the NDP chain before allocating datagram skbs. */ + while (next_ndp_index) { + if (next_ndp_index % 4 || + next_ndp_index < opts->nth_size || + next_ndp_index > block_len - opts->ndp_size) { + INFO(port->func.config->cdev, "Bad index: %#X\n", + next_ndp_index); + goto err; + } + + /* More aligned offsets than fit in the NTB imply a cycle. */ + if (++ndp_count > block_len / 4) { + INFO(port->func.config->cdev, "NDP chain cycle\n"); + goto err; + } + + tmp = (__le16 *)(ntb_ptr + next_ndp_index); + tmp += 3; /* skip the signature and length */ + tmp += opts->reserved1; + next_ndp_index = get_ncm(&tmp, opts->next_ndp_index); + } /* Run through all the NDP's in the NTB */ do { @@ -1741,6 +1771,7 @@ static void ncm_unbind(struct usb_configuration *c, struct usb_function *f) hrtimer_cancel(&ncm->task_timer); kfree(f->os_desc_table); + f->os_desc_table = NULL; f->os_desc_n = 0; ncm_string_defs[0].id = 0; diff --git a/drivers/usb/gadget/function/f_phonet.c b/drivers/usb/gadget/function/f_phonet.c index b1ee9a7c2e9440..2c6558b1a2ff2d 100644 --- a/drivers/usb/gadget/function/f_phonet.c +++ b/drivers/usb/gadget/function/f_phonet.c @@ -23,7 +23,6 @@ #include #include "u_phonet.h" -#include "u_ether.h" #define PN_MEDIA_USB 0x1B #define MAXPACKET 512 @@ -600,7 +599,9 @@ static const struct configfs_item_operations phonet_item_ops = { static ssize_t f_phonet_ifname_show(struct config_item *item, char *page) { - return gether_get_ifname(to_f_phonet_opts(item)->net, page, PAGE_SIZE); + struct net_device *net = to_f_phonet_opts(item)->net; + + return sysfs_emit(page, "%s\n", netdev_name(net)); } CONFIGFS_ATTR_RO(f_phonet_, ifname); diff --git a/drivers/usb/gadget/function/f_printer.c b/drivers/usb/gadget/function/f_printer.c index 1857d786110b4f..10eeeedb8bcbac 100644 --- a/drivers/usb/gadget/function/f_printer.c +++ b/drivers/usb/gadget/function/f_printer.c @@ -736,7 +736,7 @@ printer_fsync(struct file *fd, loff_t start, loff_t end, int datasync) return -ENODEV; } - tx_list_empty = (likely(list_empty(&dev->tx_reqs))); + tx_list_empty = (likely(list_empty(&dev->tx_reqs_active))); spin_unlock_irqrestore(&dev->lock, flags); if (!tx_list_empty) { @@ -940,8 +940,8 @@ static void printer_soft_reset(struct printer_dev *dev) } while (likely(!(list_empty(&dev->rx_reqs_active)))) { - req = container_of(dev->rx_buffers.next, struct usb_request, - list); + req = list_first_entry(&dev->rx_reqs_active, + struct usb_request, list); list_del_init(&req->list); list_add(&req->list, &dev->rx_reqs); } @@ -1034,7 +1034,8 @@ static int printer_func_setup(struct usb_function *f, value = 0; break; } - value = strlen(*dev->pnp_string); + value = min_t(int, strlen(*dev->pnp_string), + USB_COMP_EP0_BUFSIZ - 2); buf[0] = (value >> 8) & 0xFF; buf[1] = value & 0xFF; memcpy(buf + 2, *dev->pnp_string, value); @@ -1269,6 +1270,11 @@ static ssize_t f_printer_opts_pnp_string_store(struct config_item *item, mutex_lock(&opts->lock); + if (opts->refcnt) { + result = -EBUSY; + goto unlock; + } + new_pnp = kstrndup(page, len, GFP_KERNEL); if (!new_pnp) { result = -ENOMEM; diff --git a/drivers/usb/gadget/function/f_tcm.c b/drivers/usb/gadget/function/f_tcm.c index 9e6d4f39900a27..3af28419a8bca9 100644 --- a/drivers/usb/gadget/function/f_tcm.c +++ b/drivers/usb/gadget/function/f_tcm.c @@ -139,7 +139,7 @@ static void bot_send_bad_status(struct usbg_cmd *cmd) req->complete = bot_err_compl; req->context = cmd; req->buf = fu->cmd[0].buf; - usb_ep_queue(ep, req, GFP_KERNEL); + usb_ep_queue(ep, req, GFP_ATOMIC); } else { bot_enqueue_sense_code(fu, cmd); } @@ -167,7 +167,7 @@ static int bot_send_status(struct usbg_cmd *cmd, bool moved_data) csw->Status = US_BULK_STAT_OK; fu->bot_status.req->context = cmd; - ret = usb_ep_queue(fu->ep_in, fu->bot_status.req, GFP_KERNEL); + ret = usb_ep_queue(fu->ep_in, fu->bot_status.req, GFP_ATOMIC); if (ret) pr_err("%s(%d) ERR: %d\n", __func__, __LINE__, ret); } else { @@ -1275,6 +1275,7 @@ static void usbg_cmd_work(struct work_struct *work) struct uas_stream *stream = NULL; struct hlist_node *tmp; struct usbg_cmd *active_cmd = NULL; + struct usb_request *req; se_sess = cmd->fu->tpg->tpg_nexus->tvn_se_sess; @@ -1318,6 +1319,12 @@ static void usbg_cmd_work(struct work_struct *work) return; } + /* + * Take the request before the slot goes back to the pool; it + * is queued on ep_cmd below. + */ + req = cmd->req; + /* * The command isn't submitted to the target core, so we're safe * to remove the bitmap index from the session tag pool. @@ -1333,6 +1340,8 @@ static void usbg_cmd_work(struct work_struct *work) active_cmd->tmr_rsp = RC_OVERLAPPED_TAG; usbg_aborted_task(&active_cmd->se_cmd); + usb_ep_queue(fu->ep_cmd, req, GFP_ATOMIC); + /* Send the response after the transfer is aborted. */ return; } diff --git a/drivers/usb/gadget/function/f_uac1_legacy.c b/drivers/usb/gadget/function/f_uac1_legacy.c index 7c8d60c7e87d12..e183251ec25999 100644 --- a/drivers/usb/gadget/function/f_uac1_legacy.c +++ b/drivers/usb/gadget/function/f_uac1_legacy.c @@ -732,6 +732,7 @@ f_audio_bind(struct usb_configuration *c, struct usb_function *f) int status; struct usb_ep *ep = NULL; struct f_uac1_legacy_opts *audio_opts; + bool bound_here = false; audio_opts = container_of(f->fi, struct f_uac1_legacy_opts, func_inst); audio->card.gadget = c->cdev->gadget; @@ -741,6 +742,7 @@ f_audio_bind(struct usb_configuration *c, struct usb_function *f) if (status < 0) return status; audio_opts->bound = true; + bound_here = true; } us = usb_gstrings_attach(cdev, uac1_strings, ARRAY_SIZE(strings_uac1)); if (IS_ERR(us)) @@ -789,7 +791,11 @@ f_audio_bind(struct usb_configuration *c, struct usb_function *f) return 0; fail: - gaudio_cleanup(&audio->card); + /* Only tear down the ALSA devices if this bind opened them; the */ + if (bound_here) { + gaudio_cleanup(&audio->card); + audio_opts->bound = false; + } return status; } diff --git a/drivers/usb/gadget/function/f_uac2.c b/drivers/usb/gadget/function/f_uac2.c index d8cf710085a05e..9bd59ea5f7fbc8 100644 --- a/drivers/usb/gadget/function/f_uac2.c +++ b/drivers/usb/gadget/function/f_uac2.c @@ -728,11 +728,11 @@ static int set_ep_max_packet_size_bint(struct device *dev, const struct f_uac2_o bint = opts_bint; max_size_bw = get_max_bw_for_bint(uac2_opts, bint, 8000, is_playback); } else { - /* checking bInterval from 4 to 1 whether the required bandwidth fits */ - for (bint = 4; bint > 0; --bint) { + /* select the largest bInterval that fits, or 1 if none fit */ + for (bint = 4; ; --bint) { max_size_bw = get_max_bw_for_bint( uac2_opts, bint, 8000, is_playback); - if (max_size_bw <= max_size_ep) + if (max_size_bw <= max_size_ep || bint == 1) break; } } diff --git a/drivers/usb/gadget/function/storage_common.c b/drivers/usb/gadget/function/storage_common.c index 75831f2c7abeb0..51a70f2abe574a 100644 --- a/drivers/usb/gadget/function/storage_common.c +++ b/drivers/usb/gadget/function/storage_common.c @@ -415,7 +415,8 @@ ssize_t fsg_store_ro(struct fsg_lun *curlun, struct rw_semaphore *filesem, } EXPORT_SYMBOL_GPL(fsg_store_ro); -ssize_t fsg_store_nofua(struct fsg_lun *curlun, const char *buf, size_t count) +ssize_t fsg_store_nofua(struct fsg_lun *curlun, struct rw_semaphore *filesem, + const char *buf, size_t count) { bool nofua; int ret; @@ -425,8 +426,10 @@ ssize_t fsg_store_nofua(struct fsg_lun *curlun, const char *buf, size_t count) return ret; /* Sync data when switching from async mode to sync */ - if (!nofua && curlun->nofua) + if (!nofua && curlun->nofua) { + guard(rwsem_read)(filesem); fsg_lun_fsync_sub(curlun); + } curlun->nofua = nofua; diff --git a/drivers/usb/gadget/function/storage_common.h b/drivers/usb/gadget/function/storage_common.h index e73a30cc553fc4..e66b753d7cbd98 100644 --- a/drivers/usb/gadget/function/storage_common.h +++ b/drivers/usb/gadget/function/storage_common.h @@ -245,7 +245,8 @@ ssize_t fsg_show_cdrom(struct fsg_lun *curlun, char *buf); ssize_t fsg_show_removable(struct fsg_lun *curlun, char *buf); ssize_t fsg_store_ro(struct fsg_lun *curlun, struct rw_semaphore *filesem, const char *buf, size_t count); -ssize_t fsg_store_nofua(struct fsg_lun *curlun, const char *buf, size_t count); +ssize_t fsg_store_nofua(struct fsg_lun *curlun, struct rw_semaphore *filesem, + const char *buf, size_t count); ssize_t fsg_store_file(struct fsg_lun *curlun, struct rw_semaphore *filesem, const char *buf, size_t count); ssize_t fsg_store_cdrom(struct fsg_lun *curlun, struct rw_semaphore *filesem, diff --git a/drivers/usb/gadget/function/u_audio.c b/drivers/usb/gadget/function/u_audio.c index f0ee83abcebc70..83019d359c8d19 100644 --- a/drivers/usb/gadget/function/u_audio.c +++ b/drivers/usb/gadget/function/u_audio.c @@ -156,6 +156,7 @@ static void u_audio_iso_complete(struct usb_ep *ep, struct usb_request *req) struct uac_rtd_params *prm = req->context; struct snd_uac_chip *uac = prm->uac; unsigned int frames, p_pktsize; + unsigned int period_bytes; unsigned long long pitched_rate_mil, p_pktsize_residue_mil, residue_frames_mil, div_result; @@ -230,9 +231,13 @@ static void u_audio_iso_complete(struct usb_ep *ep, struct usb_request *req) do_div(div_result, uac->p_interval); do_div(div_result, 1000000); if ((unsigned int) div_result >= uac->p_framesize) { - req->length += uac->p_framesize; + /* req->length is bounded by ep->maxpacket above. */ + if (uac->p_framesize <= ep->maxpacket - req->length) { + req->length += uac->p_framesize; + pr_debug("increased req length to %d\n", req->length); + } + uac->p_residue_mil -= uac->p_framesize * p_interval_mil; - pr_debug("increased req length to %d\n", req->length); } pr_debug("remains uac->p_residue_mil %llu\n", uac->p_residue_mil); @@ -267,10 +272,12 @@ static void u_audio_iso_complete(struct usb_ep *ep, struct usb_request *req) /* update hw_ptr after data is copied to memory */ prm->hw_ptr = (hw_ptr + req->actual) % runtime->dma_bytes; hw_ptr = prm->hw_ptr; - snd_pcm_stream_unlock(substream); + period_bytes = snd_pcm_lib_period_bytes(substream); - if ((hw_ptr % snd_pcm_lib_period_bytes(substream)) < req->actual) - snd_pcm_period_elapsed(substream); + if ((hw_ptr % period_bytes) < req->actual) + snd_pcm_period_elapsed_under_stream_lock(substream); + + snd_pcm_stream_unlock(substream); exit: if (usb_ep_queue(ep, req, GFP_ATOMIC)) diff --git a/drivers/usb/gadget/function/u_ether.c b/drivers/usb/gadget/function/u_ether.c index 59d85d6a84a896..2a9ae598e61266 100644 --- a/drivers/usb/gadget/function/u_ether.c +++ b/drivers/usb/gadget/function/u_ether.c @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -54,8 +55,7 @@ #define GETHER_MAX_ETH_FRAME_LEN (GETHER_MAX_MTU_SIZE + ETH_HLEN) struct eth_dev { - /* lock is held while accessing port_usb - */ + /* lock is held while accessing port_usb and gadget */ spinlock_t lock; struct gether *port_usb; @@ -113,6 +113,8 @@ static void eth_get_drvinfo(struct net_device *net, struct ethtool_drvinfo *p) strscpy(p->driver, "g_ether", sizeof(p->driver)); strscpy(p->version, UETH__VERSION, sizeof(p->version)); + + guard(spinlock_irqsave)(&dev->lock); if (dev->gadget) { strscpy(p->fw_version, dev->gadget->name, sizeof(p->fw_version)); strscpy(p->bus_info, dev_name(&dev->gadget->dev), sizeof(p->bus_info)); @@ -135,9 +137,9 @@ static void defer_kevent(struct eth_dev *dev, int flag) if (test_and_set_bit(flag, &dev->todo)) return; if (!schedule_work(&dev->work)) - ERROR(dev, "kevent %d may have been dropped\n", flag); + netdev_err(dev->net, "kevent %d may have been dropped\n", flag); else - DBG(dev, "kevent %d scheduled\n", flag); + netdev_dbg(dev->net, "kevent %d scheduled\n", flag); } static void rx_complete(struct usb_ep *ep, struct usb_request *req); @@ -145,7 +147,7 @@ static void rx_complete(struct usb_ep *ep, struct usb_request *req); static int rx_submit(struct eth_dev *dev, struct usb_request *req, gfp_t gfp_flags) { - struct usb_gadget *g = dev->gadget; + struct usb_gadget *g; struct sk_buff *skb; int retval = -ENOMEM; size_t size = 0; @@ -153,6 +155,7 @@ rx_submit(struct eth_dev *dev, struct usb_request *req, gfp_t gfp_flags) unsigned long flags; spin_lock_irqsave(&dev->lock, flags); + g = dev->gadget; if (dev->port_usb) out = dev->port_usb->out_ep; else @@ -190,7 +193,7 @@ rx_submit(struct eth_dev *dev, struct usb_request *req, gfp_t gfp_flags) skb = __netdev_alloc_skb(dev->net, size + NET_IP_ALIGN, gfp_flags); if (skb == NULL) { - DBG(dev, "no rx skb\n"); + netdev_dbg(dev->net, "no rx skb\n"); goto enomem; } @@ -211,7 +214,7 @@ rx_submit(struct eth_dev *dev, struct usb_request *req, gfp_t gfp_flags) enomem: defer_kevent(dev, WORK_RX_MEMORY); if (retval) { - DBG(dev, "rx submit --> %d\n", retval); + netdev_dbg(dev->net, "rx submit --> %d\n", retval); if (skb) dev_kfree_skb_any(skb); spin_lock_irqsave(&dev->req_lock, flags); @@ -258,7 +261,7 @@ static void rx_complete(struct usb_ep *ep, struct usb_request *req) || skb2->len > GETHER_MAX_ETH_FRAME_LEN) { dev->net->stats.rx_errors++; dev->net->stats.rx_length_errors++; - DBG(dev, "rx length %d\n", skb2->len); + netdev_dbg(dev->net, "rx length %d\n", skb2->len); dev_kfree_skb_any(skb2); goto next_frame; } @@ -278,12 +281,12 @@ static void rx_complete(struct usb_ep *ep, struct usb_request *req) /* software-driven interface shutdown */ case -ECONNRESET: /* unlink */ case -ESHUTDOWN: /* disconnect etc */ - VDBG(dev, "rx shutdown, code %d\n", status); + netdev_vdbg(dev->net, "rx shutdown, code %d\n", status); goto quiesce; /* for hardware automagic (such as pxa) */ case -ECONNABORTED: /* endpoint reset */ - DBG(dev, "rx %s reset\n", ep->name); + netdev_dbg(dev->net, "rx %s reset\n", ep->name); defer_kevent(dev, WORK_RX_MEMORY); quiesce: dev_kfree_skb_any(skb); @@ -296,7 +299,7 @@ static void rx_complete(struct usb_ep *ep, struct usb_request *req) default: dev->net->stats.rx_errors++; - DBG(dev, "rx status %d\n", status); + netdev_dbg(dev->net, "rx status %d\n", status); break; } @@ -365,7 +368,7 @@ static int alloc_requests(struct eth_dev *dev, struct gether *link, unsigned n) goto fail; goto done; fail: - DBG(dev, "can't alloc requests\n"); + netdev_dbg(dev->net, "can't alloc requests\n"); done: spin_unlock(&dev->req_lock); return status; @@ -403,7 +406,7 @@ static void eth_work(struct work_struct *work) } if (dev->todo) - DBG(dev, "work done, flags = 0x%lx\n", dev->todo); + netdev_dbg(dev->net, "work done, flags = 0x%lx\n", dev->todo); } static void tx_complete(struct usb_ep *ep, struct usb_request *req) @@ -414,7 +417,7 @@ static void tx_complete(struct usb_ep *ep, struct usb_request *req) switch (req->status) { default: dev->net->stats.tx_errors++; - VDBG(dev, "tx err %d\n", req->status); + netdev_vdbg(dev->net, "tx err %d\n", req->status); fallthrough; case -ECONNRESET: /* unlink */ case -ESHUTDOWN: /* disconnect etc */ @@ -475,7 +478,7 @@ static netdev_tx_t eth_start_xmit(struct sk_buff *skb, } if (dev->port_usb && dev->port_usb->is_suspend) { - DBG(dev, "Port suspended. Triggering wakeup\n"); + netdev_dbg(dev->net, "Port suspended. Triggering wakeup\n"); netif_stop_queue(net); spin_unlock_irqrestore(&dev->lock, flags); ether_wakeup_host(dev->port_usb); @@ -579,7 +582,7 @@ static netdev_tx_t eth_start_xmit(struct sk_buff *skb, retval = usb_ep_queue(in, req, GFP_ATOMIC); switch (retval) { default: - DBG(dev, "tx queue err %d\n", retval); + netdev_dbg(dev->net, "tx queue err %d\n", retval); break; case 0: netif_trans_update(net); @@ -604,7 +607,7 @@ static netdev_tx_t eth_start_xmit(struct sk_buff *skb, static void eth_start(struct eth_dev *dev, gfp_t gfp_flags) { - DBG(dev, "%s\n", __func__); + netdev_dbg(dev->net, "%s\n", __func__); /* fill the rx queue */ rx_fill(dev, gfp_flags); @@ -619,7 +622,7 @@ static int eth_open(struct net_device *net) struct eth_dev *dev = netdev_priv(net); struct gether *link; - DBG(dev, "%s\n", __func__); + netdev_dbg(dev->net, "%s\n", __func__); if (netif_carrier_ok(dev->net)) eth_start(dev, GFP_KERNEL); @@ -637,13 +640,12 @@ static int eth_stop(struct net_device *net) struct eth_dev *dev = netdev_priv(net); unsigned long flags; - VDBG(dev, "%s\n", __func__); + netdev_vdbg(dev->net, "%s\n", __func__); netif_stop_queue(net); - DBG(dev, "stop stats: rx/tx %ld/%ld, errs %ld/%ld\n", - dev->net->stats.rx_packets, dev->net->stats.tx_packets, - dev->net->stats.rx_errors, dev->net->stats.tx_errors - ); + netdev_dbg(dev->net, "stop stats: rx/tx %ld/%ld, errs %ld/%ld\n", + dev->net->stats.rx_packets, dev->net->stats.tx_packets, + dev->net->stats.rx_errors, dev->net->stats.tx_errors); /* ensure there are no more active requests */ spin_lock_irqsave(&dev->lock, flags); @@ -669,7 +671,7 @@ static int eth_stop(struct net_device *net) usb_ep_disable(link->in_ep); usb_ep_disable(link->out_ep); if (netif_carrier_ok(net)) { - DBG(dev, "host still using in/out endpoints\n"); + netdev_dbg(dev->net, "host still using in/out endpoints\n"); link->in_ep->desc = in; link->out_ep->desc = out; usb_ep_enable(link->in_ep); @@ -789,8 +791,7 @@ struct eth_dev *gether_setup_name(struct usb_gadget *g, net->min_mtu = ETH_HLEN; net->max_mtu = GETHER_MAX_MTU_SIZE; - dev->gadget = g; - SET_NETDEV_DEV(net, &g->dev); + gether_set_gadget(net, g); SET_NETDEV_DEVTYPE(net, &gadget_type); status = register_netdev(net); @@ -799,8 +800,8 @@ struct eth_dev *gether_setup_name(struct usb_gadget *g, free_netdev(net); dev = ERR_PTR(status); } else { - INFO(dev, "MAC %pM\n", net->dev_addr); - INFO(dev, "HOST MAC %pM\n", dev->host_mac); + netdev_info(net, "MAC %pM\n", net->dev_addr); + netdev_info(net, "HOST MAC %pM\n", dev->host_mac); /* * two kinds of host-initiated state changes: @@ -875,8 +876,8 @@ int gether_register_netdev(struct net_device *net) dev_dbg(&g->dev, "register_netdev failed, %d\n", status); return status; } else { - INFO(dev, "HOST MAC %pM\n", dev->host_mac); - INFO(dev, "MAC %pM\n", dev->dev_mac); + netdev_info(net, "HOST MAC %pM\n", dev->host_mac); + netdev_info(net, "MAC %pM\n", dev->dev_mac); /* two kinds of host-initiated state changes: * - iff DATA transfer is active, carrier is "on" @@ -891,10 +892,11 @@ EXPORT_SYMBOL_GPL(gether_register_netdev); void gether_set_gadget(struct net_device *net, struct usb_gadget *g) { - struct eth_dev *dev; + struct eth_dev *dev = netdev_priv(net); + + scoped_guard(spinlock_irqsave, &dev->lock) + dev->gadget = g; - dev = netdev_priv(net); - dev->gadget = g; SET_NETDEV_DEV(net, &g->dev); } EXPORT_SYMBOL_GPL(gether_set_gadget); @@ -916,8 +918,10 @@ void gether_detach_gadget(struct net_device *net) { struct eth_dev *dev = netdev_priv(net); + scoped_guard(spinlock_irqsave, &dev->lock) + dev->gadget = NULL; + device_move(&net->dev, NULL, DPM_ORDER_NONE); - dev->gadget = NULL; } EXPORT_SYMBOL_GPL(gether_detach_gadget); @@ -1147,16 +1151,16 @@ struct net_device *gether_connect(struct gether *link) link->in_ep->driver_data = dev; result = usb_ep_enable(link->in_ep); if (result != 0) { - DBG(dev, "enable %s --> %d\n", - link->in_ep->name, result); + netdev_dbg(dev->net, "enable %s --> %d\n", + link->in_ep->name, result); goto fail0; } link->out_ep->driver_data = dev; result = usb_ep_enable(link->out_ep); if (result != 0) { - DBG(dev, "enable %s --> %d\n", - link->out_ep->name, result); + netdev_dbg(dev->net, "enable %s --> %d\n", + link->out_ep->name, result); goto fail1; } @@ -1167,7 +1171,7 @@ struct net_device *gether_connect(struct gether *link) if (result == 0) { dev->zlp = link->is_zlp_ok; dev->no_skb_reserve = gadget_avoids_skb_reserve(dev->gadget); - DBG(dev, "qlen %d\n", qlen(dev->gadget, dev->qmult)); + netdev_dbg(dev->net, "qlen %d\n", qlen(dev->gadget, dev->qmult)); dev->header_len = link->header_len; dev->unwrap = link->unwrap; @@ -1223,7 +1227,7 @@ void gether_disconnect(struct gether *link) if (!dev) return; - DBG(dev, "%s\n", __func__); + netdev_dbg(dev->net, "%s\n", __func__); spin_lock(&dev->lock); dev->port_usb = NULL; diff --git a/drivers/usb/gadget/function/u_serial.c b/drivers/usb/gadget/function/u_serial.c index cdd1dfc666c4f6..0a304f508bc384 100644 --- a/drivers/usb/gadget/function/u_serial.c +++ b/drivers/usb/gadget/function/u_serial.c @@ -70,10 +70,28 @@ * gserial->ioport == usb_ep->driver_data ... gs_port * gs_port->port_usb ... gserial * - * gs_port <---> tty_struct ... links will be null when the TTY file - * isn't opened; managed by gs_open()/gs_close() - * gserial->port_tty ... tty_struct - * tty_struct->driver_data ... gserial + * gs_port <---> tty_struct: + * tty->driver_data refers to gs_port from install through cleanup, + * pinning the port via tty_port reference counting. + * gs_port->port.tty exists only while the port is open. + * + * Each entry in ports[] is guarded by ports[i].lock and models three states: + * - Free: !port && !reserved + * - Published: port && reserved + * - Retiring: !port && reserved + * + * A minor remains reserved until gs_port_destruct() runs upon final tty_port + * release, preventing minor reuse while cleanup of the installed TTY is still + * underway. The owner reference is retained through device unregister so the + * destructor releases the reservation only after device teardown is complete. + * + * open_close_failures tracks failed gs_open() calls where port->port.count + * was not incremented. The TTY core calls gs_close() on open failure to tear + * down the tty; tracking failures as aggregate credits allows gs_close() to + * consume a credit and exit without decrementing port->port.count. Credits + * are aggregate rather than paired with individual files (another gs_close() + * can consume a failed open's credit before that file's own close runs). + * It is protected by tty_lock. */ /* RX and TX queues can buffer QUEUE_SIZE packets before they hit the @@ -128,6 +146,7 @@ struct gs_port { wait_queue_head_t close_wait; bool suspended; /* port suspended */ bool start_delayed; /* delay start when suspended */ + unsigned int open_close_failures; /* protected by tty_lock */ struct async_icount icount; /* REVISIT this state ... */ @@ -135,8 +154,9 @@ struct gs_port { }; static struct portmaster { - struct mutex lock; /* protect open/close */ + struct mutex lock; /* protect open/close and port slot */ struct gs_port *port; + bool reserved; } ports[MAX_U_SERIAL_PORTS]; #define GS_CLOSE_TIMEOUT 15 /* seconds */ @@ -603,22 +623,60 @@ static int gserial_wakeup_host(struct gserial *gser) /* TTY Driver */ +static int gs_install(struct tty_driver *driver, struct tty_struct *tty) +{ + struct gs_port *port; + struct tty_port *tport; + int ret; + + mutex_lock(&ports[tty->index].lock); + port = ports[tty->index].port; + if (!port) { + mutex_unlock(&ports[tty->index].lock); + return -ENODEV; + } + + tport = tty_port_get(&port->port); + if (!tport) { + mutex_unlock(&ports[tty->index].lock); + return -ENODEV; + } + + ret = tty_port_install(tport, driver, tty); + if (ret) { + mutex_unlock(&ports[tty->index].lock); + tty_port_put(tport); + return ret; + } + + tty->driver_data = port; + mutex_unlock(&ports[tty->index].lock); + + return 0; +} + +static void gs_cleanup(struct tty_struct *tty) +{ + tty_port_put(tty->port); +} + /* - * gs_open sets up the link between a gs_port and its associated TTY. - * That link is broken *only* by TTY close(), and all driver methods - * know that. + * gs_open associates an open TTY with its gs_port. + * + * There are two TTY-to-port relationships: port->port.tty exists from the + * first successful open until final close, while tty->driver_data is assigned + * during gs_install() and remains valid through gs_cleanup(). */ static int gs_open(struct tty_struct *tty, struct file *file) { int port_num = tty->index; - struct gs_port *port; + struct gs_port *port = tty->driver_data; int status = 0; mutex_lock(&ports[port_num].lock); - port = ports[port_num].port; - if (!port) { + if (ports[port_num].port != port) { status = -ENODEV; - goto out; + goto fail_unlock; } spin_lock_irq(&port->port_lock); @@ -638,7 +696,7 @@ static int gs_open(struct tty_struct *tty, struct file *file) if (status) { pr_debug("gs_open: ttyGS%d (%p,%p) no buffer\n", port_num, tty, file); - goto out; + goto fail_unlock; } spin_lock_irq(&port->port_lock); @@ -648,7 +706,6 @@ static int gs_open(struct tty_struct *tty, struct file *file) if (port->port.count++) goto exit_unlock_port; - tty->driver_data = port; port->port.tty = tty; /* if connected, start the I/O stream */ @@ -672,7 +729,11 @@ static int gs_open(struct tty_struct *tty, struct file *file) exit_unlock_port: spin_unlock_irq(&port->port_lock); -out: + mutex_unlock(&ports[port_num].lock); + return status; + +fail_unlock: + port->open_close_failures++; mutex_unlock(&ports[port_num].lock); return status; } @@ -695,6 +756,14 @@ static void gs_close(struct tty_struct *tty, struct file *file) struct gs_port *port = tty->driver_data; struct gserial *gser; + if (!port) + return; + + if (port->open_close_failures > 0) { + port->open_close_failures--; + return; + } + spin_lock_irq(&port->port_lock); if (port->port.count != 1) { @@ -909,8 +978,10 @@ static int gs_get_icount(struct tty_struct *tty, } static const struct tty_operations gs_tty_ops = { + .install = gs_install, .open = gs_open, .close = gs_close, + .cleanup = gs_cleanup, .write = gs_write, .put_char = gs_put_char, .flush_chars = gs_flush_chars, @@ -1203,14 +1274,41 @@ static void gs_console_exit(struct gs_port *port) #endif -static int +static void gs_port_destruct(struct tty_port *tport) +{ + struct gs_port *port = container_of(tport, struct gs_port, port); + unsigned int port_num = port->port_num; + + mutex_lock(&ports[port_num].lock); + if (WARN_ON(ports[port_num].port)) + ports[port_num].port = NULL; + WARN_ON(!ports[port_num].reserved); + if (gs_tty_driver) + gs_tty_driver->ports[port_num] = NULL; + ports[port_num].reserved = false; + mutex_unlock(&ports[port_num].lock); + + kfifo_free(&port->port_write_buf); + kfree(port); +} + +static const struct tty_port_operations gs_port_ops = { + .destruct = gs_port_destruct, +}; + +static struct gs_port * gs_port_alloc(unsigned port_num, struct usb_cdc_line_coding *coding) { struct gs_port *port; int ret = 0; mutex_lock(&ports[port_num].lock); - if (ports[port_num].port) { + if (WARN_ON_ONCE(ports[port_num].port && !ports[port_num].reserved)) { + ret = -EBUSY; + goto out; + } + + if (ports[port_num].reserved) { ret = -EBUSY; goto out; } @@ -1222,6 +1320,7 @@ gs_port_alloc(unsigned port_num, struct usb_cdc_line_coding *coding) } tty_port_init(&port->port); + port->port.ops = &gs_port_ops; spin_lock_init(&port->port_lock); init_waitqueue_head(&port->drain_wait); init_waitqueue_head(&port->close_wait); @@ -1235,10 +1334,14 @@ gs_port_alloc(unsigned port_num, struct usb_cdc_line_coding *coding) port->port_num = port_num; port->port_line_coding = *coding; + ports[port_num].reserved = true; ports[port_num].port = port; + mutex_unlock(&ports[port_num].lock); + return port; + out: mutex_unlock(&ports[port_num].lock); - return ret; + return ERR_PTR(ret); } static int gs_closed(struct gs_port *port) @@ -1258,8 +1361,7 @@ static void gserial_free_port(struct gs_port *port) /* wait for old opens to finish */ wait_event(port->close_wait, gs_closed(port)); WARN_ON(port->port_usb != NULL); - tty_port_destroy(&port->port); - kfree(port); + tty_port_put(&port->port); } void gserial_free_line(unsigned char port_num) @@ -1276,15 +1378,15 @@ void gserial_free_line(unsigned char port_num) ports[port_num].port = NULL; mutex_unlock(&ports[port_num].lock); - gserial_free_port(port); tty_unregister_device(gs_tty_driver, port_num); + gserial_free_port(port); } EXPORT_SYMBOL_GPL(gserial_free_line); int gserial_alloc_line_no_console(unsigned char *line_num) { struct usb_cdc_line_coding coding; - struct gs_port *port; + struct gs_port *port = ERR_PTR(-EBUSY); struct device *tty_dev; int ret; int port_num; @@ -1295,19 +1397,20 @@ int gserial_alloc_line_no_console(unsigned char *line_num) coding.bDataBits = USB_CDC_1_STOP_BITS; for (port_num = 0; port_num < MAX_U_SERIAL_PORTS; port_num++) { - ret = gs_port_alloc(port_num, &coding); - if (ret == -EBUSY) - continue; - if (ret) + port = gs_port_alloc(port_num, &coding); + if (IS_ERR(port)) { + ret = PTR_ERR(port); + if (ret == -EBUSY) + continue; return ret; + } break; } - if (ret) - return ret; + if (IS_ERR(port)) + return PTR_ERR(port); /* ... and sysfs class devices, so mdev/udev make /dev/ttyGS* */ - port = ports[port_num].port; tty_dev = tty_port_register_device(&port->port, gs_tty_driver, port_num, NULL); if (IS_ERR(tty_dev)) { @@ -1316,14 +1419,15 @@ int gserial_alloc_line_no_console(unsigned char *line_num) ret = PTR_ERR(tty_dev); mutex_lock(&ports[port_num].lock); + WARN_ON(ports[port_num].port != port); ports[port_num].port = NULL; mutex_unlock(&ports[port_num].lock); - gserial_free_port(port); - goto err; + tty_port_put(&port->port); + return ret; } + *line_num = port_num; -err: - return ret; + return 0; } EXPORT_SYMBOL_GPL(gserial_alloc_line_no_console); diff --git a/drivers/usb/gadget/function/u_uac1_legacy.c b/drivers/usb/gadget/function/u_uac1_legacy.c index 01016102fa1728..c2b6c88b0bdc99 100644 --- a/drivers/usb/gadget/function/u_uac1_legacy.c +++ b/drivers/usb/gadget/function/u_uac1_legacy.c @@ -259,18 +259,29 @@ static int gaudio_close_snd_dev(struct gaudio *gau) /* Close control device */ snd = &gau->control; - if (snd->filp) + if (snd->filp) { filp_close(snd->filp, NULL); + snd->filp = NULL; + snd->card = NULL; + } /* Close PCM playback device and setup substream */ snd = &gau->playback; - if (snd->filp) + if (snd->filp) { filp_close(snd->filp, NULL); + snd->filp = NULL; + snd->substream = NULL; + snd->card = NULL; + } /* Close PCM capture device and setup substream */ snd = &gau->capture; - if (snd->filp) + if (snd->filp) { filp_close(snd->filp, NULL); + snd->filp = NULL; + snd->substream = NULL; + snd->card = NULL; + } return 0; } diff --git a/drivers/usb/gadget/function/uvc_configfs.c b/drivers/usb/gadget/function/uvc_configfs.c index b9af49940d5f21..a8717c95e5edfc 100644 --- a/drivers/usb/gadget/function/uvc_configfs.c +++ b/drivers/usb/gadget/function/uvc_configfs.c @@ -1256,11 +1256,12 @@ static void uvcg_extension_drop(struct config_group *group, struct config_item * mutex_lock(&opts->lock); - config_item_put(item); list_del(&xu->list); kfree(xu->desc.baSourceID); kfree(xu->desc.bmControls); + config_item_put(item); + mutex_unlock(&opts->lock); } @@ -2142,14 +2143,26 @@ static struct configfs_attribute *uvcg_frame_attrs2[] = { NULL, }; +static void uvcg_frame_release(struct config_item *item) +{ + struct uvcg_frame *frm = to_uvcg_frame(item); + + kfree(frm->dw_frame_interval); + kfree(frm); +} + +static const struct configfs_item_operations uvcg_frame_item_ops = { + .release = uvcg_frame_release, +}; + static const struct config_item_type uvcg_frame_type1 = { - .ct_item_ops = &uvcg_config_item_ops, + .ct_item_ops = &uvcg_frame_item_ops, .ct_attrs = uvcg_frame_attrs1, .ct_owner = THIS_MODULE, }; static const struct config_item_type uvcg_frame_type2 = { - .ct_item_ops = &uvcg_config_item_ops, + .ct_item_ops = &uvcg_frame_item_ops, .ct_attrs = uvcg_frame_attrs2, .ct_owner = THIS_MODULE, }; diff --git a/drivers/usb/gadget/function/uvc_v4l2.c b/drivers/usb/gadget/function/uvc_v4l2.c index dfa0521a243ac0..e9b9288c5c2a3d 100644 --- a/drivers/usb/gadget/function/uvc_v4l2.c +++ b/drivers/usb/gadget/function/uvc_v4l2.c @@ -368,6 +368,11 @@ static int uvc_v4l2_s_parm(struct file *file, void *fh, video->interval = v4l2_fraction_to_interval(timeperframe.numerator, timeperframe.denominator); + if (!video->interval) { + uvcg_dbg(&uvc->func, "Invalid zero interval, rejecting\n"); + return -EINVAL; + } + uvcg_dbg(&uvc->func, "Setting frame interval to %u/%u (%u)\n", timeperframe.numerator, timeperframe.denominator, video->interval); diff --git a/drivers/usb/gadget/legacy/inode.c b/drivers/usb/gadget/legacy/inode.c index 7f6d8460152f90..9950008db12162 100644 --- a/drivers/usb/gadget/legacy/inode.c +++ b/drivers/usb/gadget/legacy/inode.c @@ -2191,6 +2191,7 @@ gadgetfs_fill_super (struct super_block *sb, struct fs_context *fc) rc = gadgetfs_create_file(sb, CHIP, dev, &ep0_operations); if (rc) { put_dev(dev); + the_device = NULL; goto Enomem; } diff --git a/drivers/usb/gadget/udc/bdc/bdc_udc.c b/drivers/usb/gadget/udc/bdc/bdc_udc.c index 7a12219edac6fd..88a8f6550e02f3 100644 --- a/drivers/usb/gadget/udc/bdc/bdc_udc.c +++ b/drivers/usb/gadget/udc/bdc/bdc_udc.c @@ -218,7 +218,8 @@ static void handle_link_state_change(struct bdc *bdc, u32 uspc) case BDC_LINK_STATE_RESUME: dev_dbg(bdc->dev, "Resumed from Suspend\n"); if (bdc->devstatus & DEVICE_SUSPENDED) { - bdc->gadget_driver->resume(&bdc->gadget); + if (bdc->gadget_driver->resume) + bdc->gadget_driver->resume(&bdc->gadget); bdc->devstatus &= ~DEVICE_SUSPENDED; } break; diff --git a/drivers/usb/gadget/udc/core.c b/drivers/usb/gadget/udc/core.c index d5844384c36805..577bc15f61a15b 100644 --- a/drivers/usb/gadget/udc/core.c +++ b/drivers/usb/gadget/udc/core.c @@ -1236,8 +1236,16 @@ static inline int usb_gadget_udc_start_locked(struct usb_udc *udc) } ret = udc->gadget->ops->udc_start(udc->gadget, udc->driver); - if (!ret) + if (!ret) { udc->started = true; + /* + * The pullup is never enabled while the UDC is stopped, so any + * connection recorded meanwhile was only a request. Forget it, + * so that the next usb_gadget_connect_locked() enables the + * pullup rather than returning early. + */ + udc->gadget->connected = false; + } return ret; } diff --git a/drivers/usb/gadget/udc/m66592-udc.c b/drivers/usb/gadget/udc/m66592-udc.c index d77c11c4eb38bb..773cd00fbf1d33 100644 --- a/drivers/usb/gadget/udc/m66592-udc.c +++ b/drivers/usb/gadget/udc/m66592-udc.c @@ -1515,12 +1515,16 @@ static const struct usb_gadget_ops m66592_gadget_ops = { static void m66592_remove(struct platform_device *pdev) { struct m66592 *m66592 = platform_get_drvdata(pdev); - - usb_del_gadget_udc(&m66592->gadget); + unsigned long flags; timer_shutdown_sync(&m66592->timer); - iounmap(m66592->reg); + spin_lock_irqsave(&m66592->lock, flags); + m66592_write(m66592, 0, M66592_INTENB0); + spin_unlock_irqrestore(&m66592->lock, flags); + + usb_del_gadget_udc(&m66592->gadget); free_irq(platform_get_irq(pdev, 0), m66592); + iounmap(m66592->reg); m66592_free_request(&m66592->ep[0].ep, m66592->ep0_req); if (m66592->pdata->on_chip) { clk_disable(m66592->clk); diff --git a/drivers/usb/gadget/udc/pch_udc.c b/drivers/usb/gadget/udc/pch_udc.c index 78183eff931846..ef966c8e84f6d8 100644 --- a/drivers/usb/gadget/udc/pch_udc.c +++ b/drivers/usb/gadget/udc/pch_udc.c @@ -1372,6 +1372,8 @@ static int pch_vbus_gpio_init(struct pch_udc_dev *dev) dev->vbus_gpio.port = NULL; dev->vbus_gpio.intr = 0; + INIT_WORK(&dev->vbus_gpio.irq_work_fall, pch_vbus_gpio_work_fall); + INIT_WORK(&dev->vbus_gpio.irq_work_rise, pch_vbus_gpio_work_rise); /* Retrieve the GPIO line from the USB gadget device */ gpiod = devm_gpiod_get_optional(d, NULL, GPIOD_IN); @@ -1380,7 +1382,6 @@ static int pch_vbus_gpio_init(struct pch_udc_dev *dev) gpiod_set_consumer_name(gpiod, "pch_vbus"); dev->vbus_gpio.port = gpiod; - INIT_WORK(&dev->vbus_gpio.irq_work_fall, pch_vbus_gpio_work_fall); irq_num = gpiod_to_irq(gpiod); if (irq_num > 0) { @@ -1389,8 +1390,6 @@ static int pch_vbus_gpio_init(struct pch_udc_dev *dev) "vbus_detect", dev); if (!err) { dev->vbus_gpio.intr = irq_num; - INIT_WORK(&dev->vbus_gpio.irq_work_rise, - pch_vbus_gpio_work_rise); } else { pr_err("%s: can't request irq %d, err: %d\n", __func__, irq_num, err); @@ -2978,16 +2977,8 @@ static void pch_udc_shutdown(struct pci_dev *pdev) pch_udc_set_disconnect(dev); } -static void pch_udc_remove(struct pci_dev *pdev) +static void pch_udc_cleanup(struct pch_udc_dev *dev) { - struct pch_udc_dev *dev = pci_get_drvdata(pdev); - - usb_del_gadget_udc(&dev->gadget); - - /* gadget driver must not be registered */ - if (dev->driver) - dev_err(&pdev->dev, - "%s: gadget driver still bound!!!\n", __func__); /* dma pool cleanup */ dma_pool_destroy(dev->data_requests); @@ -3015,6 +3006,23 @@ static void pch_udc_remove(struct pci_dev *pdev) pch_udc_exit(dev); } +static void pch_udc_remove(struct pci_dev *pdev) +{ + struct pch_udc_dev *dev = pci_get_drvdata(pdev); + + disable_work_sync(&dev->vbus_gpio.irq_work_fall); + disable_work_sync(&dev->vbus_gpio.irq_work_rise); + + usb_del_gadget_udc(&dev->gadget); + + /* gadget driver must not be registered */ + if (dev->driver) + dev_err(&pdev->dev, + "%s: gadget driver still bound!!!\n", __func__); + + pch_udc_cleanup(dev); +} + static int __maybe_unused pch_udc_suspend(struct device *d) { struct pch_udc_dev *dev = dev_get_drvdata(d); @@ -3105,7 +3113,7 @@ static int pch_udc_probe(struct pci_dev *pdev, const struct pci_device_id *id) return 0; finished: - pch_udc_remove(pdev); + pch_udc_cleanup(dev); return retval; } diff --git a/drivers/usb/gadget/udc/r8a66597-udc.c b/drivers/usb/gadget/udc/r8a66597-udc.c index 469075b064baf2..f9afa9812bdcb8 100644 --- a/drivers/usb/gadget/udc/r8a66597-udc.c +++ b/drivers/usb/gadget/udc/r8a66597-udc.c @@ -1174,6 +1174,10 @@ __acquires(r8a66597->lock) break; case USB_RECIP_ENDPOINT: ep = r8a66597->epaddr2ep[w_index & USB_ENDPOINT_NUMBER_MASK]; + if (!ep) { + pipe_stall(r8a66597, 0); + return; /* exit */ + } pid = control_reg_get_pid(r8a66597, ep->pipenum); if (pid == PID_STALL) status = 1 << USB_ENDPOINT_HALT; @@ -1210,6 +1214,10 @@ static void clear_feature(struct r8a66597 *r8a66597, u16 w_index = le16_to_cpu(ctrl->wIndex); ep = r8a66597->epaddr2ep[w_index & USB_ENDPOINT_NUMBER_MASK]; + if (!ep) { + pipe_stall(r8a66597, 0); + break; + } if (!ep->wedge) { pipe_stop(r8a66597, ep->pipenum); control_reg_sqclr(r8a66597, ep->pipenum); @@ -1270,6 +1278,10 @@ static void set_feature(struct r8a66597 *r8a66597, struct usb_ctrlrequest *ctrl) u16 w_index = le16_to_cpu(ctrl->wIndex); ep = r8a66597->epaddr2ep[w_index & USB_ENDPOINT_NUMBER_MASK]; + if (!ep) { + pipe_stall(r8a66597, 0); + break; + } pipe_stall(r8a66597, ep->pipenum); control_end(r8a66597, 1); @@ -1810,6 +1822,13 @@ static void r8a66597_remove(struct platform_device *pdev) struct r8a66597 *r8a66597 = platform_get_drvdata(pdev); usb_del_gadget_udc(&r8a66597->gadget); + + /* + * The interrupt handler re-arms the timer on VBUS changes; the + * IRQ is devm-managed and freed only at detach, so free it + * before deleting the timer. + */ + devm_free_irq(&pdev->dev, r8a66597->irq, r8a66597); timer_delete_sync(&r8a66597->timer); r8a66597_free_request(&r8a66597->ep[0].ep, r8a66597->ep0_req); @@ -1896,6 +1915,7 @@ static int r8a66597_probe(struct platform_device *pdev) udc_name, r8a66597); if (ret < 0) goto clean_up2; + r8a66597->irq = irq; INIT_LIST_HEAD(&r8a66597->gadget.ep_list); r8a66597->gadget.ep0 = &r8a66597->ep[0].ep; diff --git a/drivers/usb/gadget/udc/r8a66597-udc.h b/drivers/usb/gadget/udc/r8a66597-udc.h index 9a115caba66107..08acabe02421de 100644 --- a/drivers/usb/gadget/udc/r8a66597-udc.h +++ b/drivers/usb/gadget/udc/r8a66597-udc.h @@ -110,6 +110,7 @@ struct r8a66597 { unsigned char interrupt; unsigned char isochronous; unsigned char num_dma; + int irq; unsigned irq_sense_low:1; }; diff --git a/drivers/usb/gadget/udc/snps_udc_plat.c b/drivers/usb/gadget/udc/snps_udc_plat.c index 3687690ca33da4..79fccdd52790e5 100644 --- a/drivers/usb/gadget/udc/snps_udc_plat.c +++ b/drivers/usb/gadget/udc/snps_udc_plat.c @@ -34,7 +34,7 @@ static void stop_udc(struct udc *udc) int tmp; u32 reg; - spin_lock(&udc->lock); + spin_lock_irq(&udc->lock); /* Flush the receieve fifo */ reg = readl(&udc->regs->ctl); @@ -53,9 +53,9 @@ static void stop_udc(struct udc *udc) /* Disconnect gadget driver */ if (udc->driver) { - spin_unlock(&udc->lock); + spin_unlock_irq(&udc->lock); udc->driver->disconnect(&udc->gadget); - spin_lock(&udc->lock); + spin_lock_irq(&udc->lock); /* empty queues */ for (tmp = 0; tmp < UDC_EP_NUM; tmp++) @@ -63,7 +63,7 @@ static void stop_udc(struct udc *udc) } udc->connected = 0; - spin_unlock(&udc->lock); + spin_unlock_irq(&udc->lock); dev_info(udc->dev, "Device disconnected\n"); } diff --git a/drivers/usb/gadget/udc/tegra-xudc.c b/drivers/usb/gadget/udc/tegra-xudc.c index a7736627e6e214..f696b9bf222f5c 100644 --- a/drivers/usb/gadget/udc/tegra-xudc.c +++ b/drivers/usb/gadget/udc/tegra-xudc.c @@ -3923,7 +3923,14 @@ static void tegra_xudc_remove(struct platform_device *pdev) pm_runtime_get_sync(xudc->dev); - cancel_delayed_work_sync(&xudc->plc_reset_work); + for (i = 0; i < xudc->soc->num_phys; i++) { + if (xudc->usbphy[i]) + usb_unregister_notifier(xudc->usbphy[i], + &xudc->vbus_nb); + } + + disable_delayed_work_sync(&xudc->port_reset_war_work); + disable_delayed_work_sync(&xudc->plc_reset_work); cancel_work_sync(&xudc->usb_role_sw_work); usb_del_gadget_udc(&xudc->gadget); diff --git a/drivers/usb/host/ehci-orion.c b/drivers/usb/host/ehci-orion.c index eaaa49712a8c64..2071c3d6e582c9 100644 --- a/drivers/usb/host/ehci-orion.c +++ b/drivers/usb/host/ehci-orion.c @@ -218,7 +218,7 @@ static int ehci_orion_drv_probe(struct platform_device *pdev) int irq, err; enum orion_ehci_phy_ver phy_version; struct orion_ehci_hcd *priv; - u64 *dma_mask_ptr; + const u64 *dma_mask_ptr; if (usb_disabled()) return -ENODEV; @@ -236,7 +236,9 @@ static int ehci_orion_drv_probe(struct platform_device *pdev) * set. Since shared usb code relies on it, set it here for * now. Once we have dma capability bindings this can go away. */ - dma_mask_ptr = (u64 *)of_device_get_match_data(&pdev->dev); + dma_mask_ptr = of_device_get_match_data(&pdev->dev); + if (!dma_mask_ptr) + dma_mask_ptr = &dma_mask_orion; err = dma_coerce_mask_and_coherent(&pdev->dev, *dma_mask_ptr); if (err) goto err; diff --git a/drivers/usb/host/oxu210hp-hcd.c b/drivers/usb/host/oxu210hp-hcd.c index d12cf85bbf22f6..a0fade1a54ba9e 100644 --- a/drivers/usb/host/oxu210hp-hcd.c +++ b/drivers/usb/host/oxu210hp-hcd.c @@ -1034,6 +1034,14 @@ static struct ehci_qh *oxu_qh_alloc(struct oxu_hcd *oxu) { int i; struct ehci_qh *qh = NULL; + struct ehci_qtd *dummy; + + /* dummy td enables safe urb queuing; this takes mem_lock */ + dummy = ehci_qtd_alloc(oxu); + if (!dummy) { + oxu_dbg(oxu, "no dummy td\n"); + return NULL; + } spin_lock(&oxu->mem_lock); @@ -1049,21 +1057,16 @@ static struct ehci_qh *oxu_qh_alloc(struct oxu_hcd *oxu) qh->oxu = oxu; qh->qh_dma = virt_to_phys(qh); INIT_LIST_HEAD(&qh->qtd_list); - - /* dummy td enables safe urb queuing */ - qh->dummy = ehci_qtd_alloc(oxu); - if (qh->dummy == NULL) { - oxu_dbg(oxu, "no dummy td\n"); - oxu->qh_used[i] = 0; - qh = NULL; - goto unlock; - } + qh->dummy = dummy; oxu->qh_used[i] = 1; } -unlock: + spin_unlock(&oxu->mem_lock); + if (!qh) + oxu_qtd_free(oxu, dummy); + return qh; } diff --git a/drivers/usb/host/pci-quirks.c b/drivers/usb/host/pci-quirks.c index f670e7aab98433..6a40d3ab43b597 100644 --- a/drivers/usb/host/pci-quirks.c +++ b/drivers/usb/host/pci-quirks.c @@ -1026,15 +1026,22 @@ static void quirk_usb_disable_ehci(struct pci_dev *pdev) * Returns 0 when the mask bits have the value done. * Returns -ETIMEDOUT if this condition is not true after * wait_usec microseconds have passed. + * Returns -ENODEV if the register reads as all-ones (hardware removed). */ static int handshake(void __iomem *ptr, u32 mask, u32 done, int wait_usec, int delay_usec) { u32 result; + int ret; - return readl_poll_timeout_atomic(ptr, result, - ((result & mask) == done), - delay_usec, wait_usec); + ret = readl_poll_timeout_atomic(ptr, result, + (result & mask) == done || + PCI_POSSIBLE_ERROR(result), + delay_usec, wait_usec); + if (PCI_POSSIBLE_ERROR(result)) + return -ENODEV; + + return ret; } /* @@ -1195,22 +1202,28 @@ static void quirk_usb_handoff_xhci(struct pci_dev *pdev) && pdev->device == 0x0014)) { val = (val | XHCI_HC_OS_OWNED) & ~XHCI_HC_BIOS_OWNED; writel(val, base + ext_cap_offset); - } - - /* If the BIOS owns the HC, signal that the OS wants it, and wait */ - if (val & XHCI_HC_BIOS_OWNED) { + } else { + /* + * Perform the standard handoff and leave OS ownership set to + * keep the BIOS at bay during subsequent suspends. + */ writel(val | XHCI_HC_OS_OWNED, base + ext_cap_offset); /* Wait for 1 second with 10 microsecond polling interval */ timeout = handshake(base + ext_cap_offset, XHCI_HC_BIOS_OWNED, 0, 1000000, 10); + if (timeout == -ENODEV) + goto iounmap; + /* Assume a buggy BIOS and take HC ownership anyway */ if (timeout) { dev_warn(&pdev->dev, "xHCI BIOS handoff failed (BIOS bug ?) %08x\n", val); - writel(val & ~XHCI_HC_BIOS_OWNED, base + ext_cap_offset); + writel((val | XHCI_HC_OS_OWNED) & + ~XHCI_HC_BIOS_OWNED, + base + ext_cap_offset); } } @@ -1233,6 +1246,9 @@ static void quirk_usb_handoff_xhci(struct pci_dev *pdev) */ timeout = handshake(op_reg_base + XHCI_STS_OFFSET, XHCI_STS_CNR, 0, 5000000, 10); + if (timeout == -ENODEV) + goto iounmap; + /* Assume a buggy HC and start HC initialization anyway */ if (timeout) { val = readl(op_reg_base + XHCI_STS_OFFSET); @@ -1249,6 +1265,9 @@ static void quirk_usb_handoff_xhci(struct pci_dev *pdev) /* Wait for the HC to halt - poll every 125 usec (one microframe). */ timeout = handshake(op_reg_base + XHCI_STS_OFFSET, XHCI_STS_HALT, 1, XHCI_MAX_HALT_USEC, 125); + if (timeout == -ENODEV) + goto iounmap; + if (timeout) { val = readl(op_reg_base + XHCI_STS_OFFSET); dev_warn(&pdev->dev, diff --git a/drivers/usb/host/xhci-hub.c b/drivers/usb/host/xhci-hub.c index 470bafe1802be5..55430b673f1e94 100644 --- a/drivers/usb/host/xhci-hub.c +++ b/drivers/usb/host/xhci-hub.c @@ -1166,6 +1166,12 @@ static u32 xhci_get_port_status(struct usb_hcd *hcd, struct xhci_bus_state *bus_ if (portsc & PORT_RESET) status |= USB_PORT_STAT_RESET; + /* track connect and link error status when hub is polling */ + if (!(portsc & PORT_RESET)) { + port->link_inactive = (portsc & PORT_PLS_MASK) == XDEV_INACTIVE; + port->connected = !!(portsc & PORT_CONNECT); + } + /* USB2 and USB3 specific bits, including Port Link State */ if (hcd->speed >= HCD_USB3) xhci_get_usb3_port_status(port, &status, portsc); diff --git a/drivers/usb/host/xhci-mem.c b/drivers/usb/host/xhci-mem.c index af8d4b74c4ba0c..75577f441cddc5 100644 --- a/drivers/usb/host/xhci-mem.c +++ b/drivers/usb/host/xhci-mem.c @@ -1903,24 +1903,38 @@ EXPORT_SYMBOL_GPL(xhci_remove_secondary_interrupter); void xhci_rh_bw_cleanup(struct xhci_hcd *xhci) { struct xhci_root_port_bw_info *rh_bw; + struct xhci_interval_bw_table *bw_table; + struct xhci_interval_bw *interval_bw; struct xhci_tt_bw_info *tt_info, *tt_next; struct list_head *eps, *ep, *ep_next; for (int i = 0; i < xhci->max_ports; i++) { rh_bw = &xhci->rh_bw[i]; + rh_bw->num_active_tts = 0; /* Clear and free all TT bandwidth entries */ list_for_each_entry_safe(tt_info, tt_next, &rh_bw->tts, tt_list) { list_del(&tt_info->tt_list); kfree(tt_info); } + bw_table = &rh_bw->bw_table; + bw_table->interval0_esit_payload = 0; + bw_table->bw_used = 0; + bw_table->ss_bw_in = 0; + bw_table->ss_bw_out = 0; + /* Clear per-interval endpoint lists */ for (int j = 0; j < XHCI_MAX_INTERVAL; j++) { - eps = &rh_bw->bw_table.interval_bw[j].endpoints; + interval_bw = &bw_table->interval_bw[j]; + eps = &interval_bw->endpoints; + interval_bw->num_packets = 0; list_for_each_safe(ep, ep_next, eps) list_del_init(ep); + interval_bw->overhead[LS_OVERHEAD_TYPE] = 0; + interval_bw->overhead[FS_OVERHEAD_TYPE] = 0; + interval_bw->overhead[HS_OVERHEAD_TYPE] = 0; } } } diff --git a/drivers/usb/host/xhci-ring.c b/drivers/usb/host/xhci-ring.c index c23434001e9cbf..a1fa188680f586 100644 --- a/drivers/usb/host/xhci-ring.c +++ b/drivers/usb/host/xhci-ring.c @@ -65,6 +65,7 @@ static int queue_command(struct xhci_hcd *xhci, struct xhci_command *cmd, u32 field1, u32 field2, u32 field3, u32 field4, bool command_must_succeed); +static void xhci_kill_endpoint_urbs(struct xhci_hcd *xhci, int slot_id, int ep_index); /* * Returns zero if the TRB isn't in this segment, otherwise it returns the DMA @@ -962,6 +963,24 @@ static void xhci_giveback_invalidated_tds(struct xhci_hcd *xhci, struct xhci_vir } } +static void xhci_cancel_ring_tds(struct xhci_hcd *xhci, struct xhci_virt_ep *ep, + struct xhci_ring *ring, int td_status) +{ + struct xhci_td *tmp_td; + struct xhci_td *td; + + /* Add all TDs on ring to cancelled td list */ + list_for_each_entry_safe(td, tmp_td, &ring->td_list, td_list) { + if (list_empty(&td->cancelled_td_list)) { + list_add_tail(&td->cancelled_td_list, + &ep->cancelled_td_list); + td->cancel_status = TD_DIRTY; + if (!td->status) + td->status = td_status; + } + } +} + static int xhci_reset_halted_ep(struct xhci_hcd *xhci, unsigned int slot_id, unsigned int ep_index, enum xhci_ep_reset_type reset_type) { @@ -993,25 +1012,53 @@ static int xhci_handle_halted_endpoint(struct xhci_hcd *xhci, { struct xhci_port *rhub_port = ep->vdev->rhub_port; unsigned int slot_id = ep->vdev->slot_id; + bool disconnected = false; + struct xhci_ring *ring; int err; - /* - * Avoid resetting endpoint if link is inactive or device disconnected. - * Can cause host hang. - * Device will be reset to recover an inactive link, so don't do anything - */ + /* link is inactive or device disconnected */ if (rhub_port->link_inactive || !rhub_port->connected) { ep->ep_state |= EP_DROP_PENDING; - return -ENODEV; + disconnected = true; + if (!td && ep->ep_index != 0) { + xhci_kill_endpoint_urbs(xhci, slot_id, ep->ep_index); + return -ENODEV; + } } - /* add td to cancelled list and let reset ep handler take care of it */ - if (reset_type == EP_HARD_RESET) { - ep->ep_state |= EP_HARD_CLEAR_TOGGLE; + /* Add halted td to cancelled list and let reset ep handler take care of it */ + if (reset_type == EP_HARD_RESET || disconnected) { if (td && list_empty(&td->cancelled_td_list)) { list_add_tail(&td->cancelled_td_list, &ep->cancelled_td_list); td->cancel_status = TD_HALTED; + if (disconnected && !td->status) + td->status = -EPROTO; + } + } + + /* + * Avoid resetting non-ep0 endpoints if link is inactive or device + * disconnected. Can cause host hang. + * Endpoints other than ep0 won't restart before the device is reset or + * the endpoint is dropped, so cancel all TDs, and give back non-ep0 TDs + * now instead of letting them time out. Ep0 can survive a short device + * disconnect during enumeration so reset ep0 normally and clean it up. + */ + if (disconnected) { + ring = td ? xhci_urb_to_transfer_ring(xhci, td->urb) : ep->ring; + xhci_cancel_ring_tds(xhci, ep, ring, -ESHUTDOWN); + if (ep->ep_index != 0) { + xhci_dbg(xhci, "Not resetting ep %u slot %u after disconnect\n", + ep->ep_index, slot_id); + + xhci_process_cancelled_tds(xhci, ep); + xhci_kill_endpoint_urbs(xhci, slot_id, ep->ep_index); + return -ENODEV; } + /* hard-reset a halted disconnected ep0 */ + xhci_dbg(xhci, "Reset and clean up ep0 slot %u after disconnect\n", + slot_id); + reset_type = EP_HARD_RESET; } if (ep->ep_state & EP_HALTED) { @@ -1020,6 +1067,9 @@ static int xhci_handle_halted_endpoint(struct xhci_hcd *xhci, return 0; } + if (reset_type == EP_HARD_RESET) + ep->ep_state |= EP_HARD_CLEAR_TOGGLE; + err = xhci_reset_halted_ep(xhci, slot_id, ep->ep_index, reset_type); if (err) return err; @@ -1070,8 +1120,9 @@ static int xhci_invalidate_cancelled_tds(struct xhci_hcd *xhci, struct xhci_virt continue; } - /* device disconnected or link error, ep will be dropped */ - if (ep->ep_state & EP_DROP_PENDING) { + /* device disconnected or link error, non-ep0 endpoints will be dropped */ + if (ep->ep_state & EP_DROP_PENDING && ep->ep_index != 0) { + td_to_noop(xhci, ep, td, false); td->cancel_status = TD_CLEARED; continue; } diff --git a/drivers/usb/host/xhci.c b/drivers/usb/host/xhci.c index 30ac1bc4559b74..fc1b0a6b04297e 100644 --- a/drivers/usb/host/xhci.c +++ b/drivers/usb/host/xhci.c @@ -1185,6 +1185,7 @@ int xhci_resume(struct xhci_hcd *xhci, bool power_lost, bool is_auto_resume) for (int i = xhci->max_slots; i > 0; i--) xhci_free_virt_devices_depth_first(xhci, i); + xhci->num_active_eps = 0; xhci_rh_bw_cleanup(xhci); xhci->cmd_ring_reserved_trbs = 0; @@ -1665,12 +1666,6 @@ static int xhci_urb_enqueue(struct usb_hcd *hcd, struct urb *urb, gfp_t mem_flag goto free_priv; } - if (xhci->devs[slot_id]->rhub_port->link_inactive) { - xhci_dbg(xhci, "Can't queue urb, port error, link inactive\n"); - ret = -ENODEV; - goto free_priv; - } - if (xhci->xhc_state & XHCI_STATE_DYING) { xhci_dbg(xhci, "Ep 0x%x: URB %p submitted for non-responsive xHCI host.\n", urb->ep->desc.bEndpointAddress, urb); @@ -1680,6 +1675,13 @@ static int xhci_urb_enqueue(struct usb_hcd *hcd, struct urb *urb, gfp_t mem_flag ep_state = &xhci->devs[slot_id]->eps[ep_index].ep_state; + if (xhci->devs[slot_id]->rhub_port->link_inactive || + *ep_state & EP_DROP_PENDING) { + xhci_dbg(xhci, "Can't queue urb, port disconnect or link inactive\n"); + ret = -ENODEV; + goto free_priv; + } + if (*ep_state & (EP_GETTING_STREAMS | EP_GETTING_NO_STREAMS)) { xhci_warn(xhci, "WARN: Can't enqueue URB, ep in streams transition state %x\n", *ep_state); @@ -4278,6 +4280,11 @@ int xhci_alloc_dev(struct usb_hcd *hcd, struct usb_device *udev) */ if (!xhci_alloc_virt_device(xhci, slot_id, udev, GFP_NOIO)) { xhci_warn(xhci, "Could not allocate xHCI USB device data structures\n"); + if (xhci->quirks & XHCI_EP_LIMIT_QUIRK) { + spin_lock_irqsave(&xhci->lock, flags); + xhci->num_active_eps -= 1; + spin_unlock_irqrestore(&xhci->lock, flags); + } goto disable_slot; } vdev = xhci->devs[slot_id]; @@ -4300,7 +4307,7 @@ int xhci_alloc_dev(struct usb_hcd *hcd, struct usb_device *udev) return 1; disable_slot: - xhci_disable_and_free_slot(xhci, udev->slot_id); + xhci_disable_and_free_slot(xhci, slot_id); return 0; } diff --git a/drivers/usb/isp1760/isp1760-hcd.c b/drivers/usb/isp1760/isp1760-hcd.c index 6c52c6f59d693c..3cbf5fe3ed3434 100644 --- a/drivers/usb/isp1760/isp1760-hcd.c +++ b/drivers/usb/isp1760/isp1760-hcd.c @@ -2071,12 +2071,23 @@ static void isp1760_endpoint_disable(struct usb_hcd *hcd, struct isp1760_qh *qh, *qh_iter; int i; +rescan: spin_lock_irqsave(&priv->lock, spinflags); qh = ep->hcpriv; if (!qh) goto out; + /* + * The hub driver still has a pointer to the endpoint. Wait until it + * has called isp1760_clear_tt_buffer_complete(). + */ + if (qh->tt_buffer_dirty) { + spin_unlock_irqrestore(&priv->lock, spinflags); + schedule_timeout_uninterruptible(1); + goto rescan; + } + WARN_ON(!list_empty(&qh->qtd_list)); for (i = 0; i < QH_END; i++) diff --git a/drivers/usb/misc/onboard_usb_dev.c b/drivers/usb/misc/onboard_usb_dev.c index 0606d405c16f11..b43d9d41dce452 100644 --- a/drivers/usb/misc/onboard_usb_dev.c +++ b/drivers/usb/misc/onboard_usb_dev.c @@ -667,6 +667,7 @@ static const struct usb_device_id onboard_dev_id_table[] = { { USB_DEVICE(VENDOR_ID_GENESYS, 0x0620) }, /* Genesys Logic GL3523 USB 3.1 HUB */ { USB_DEVICE(VENDOR_ID_GENESYS, 0x0625) }, /* Genesys Logic GL3590 USB 3.2 HUB */ { USB_DEVICE(VENDOR_ID_MICROCHIP, 0x2412) }, /* USB2412 USB 2.0 HUB */ + { USB_DEVICE(VENDOR_ID_MICROCHIP, 0x2422) }, /* USB2422 USB 2.0 HUB */ { USB_DEVICE(VENDOR_ID_MICROCHIP, 0x2514) }, /* USB2514B USB 2.0 HUB */ { USB_DEVICE(VENDOR_ID_MICROCHIP, 0x2517) }, /* USB2517 USB 2.0 HUB */ { USB_DEVICE(VENDOR_ID_MICROCHIP, 0x2744) }, /* USB5744 USB 2.0 HUB */ diff --git a/drivers/usb/misc/onboard_usb_dev.h b/drivers/usb/misc/onboard_usb_dev.h index 3523f8f8a1496d..e425a94e117598 100644 --- a/drivers/usb/misc/onboard_usb_dev.h +++ b/drivers/usb/misc/onboard_usb_dev.h @@ -137,6 +137,7 @@ static const struct onboard_dev_pdata xmos_xvf3500_data = { static const struct of_device_id onboard_dev_match[] = { { .compatible = "usb-a-connector", .data = &usb_a_conn_data, }, { .compatible = "usb424,2412", .data = µchip_usb424_data, }, + { .compatible = "usb424,2422", .data = µchip_usb424_data, }, { .compatible = "usb424,2514", .data = µchip_usb2514_data, }, { .compatible = "usb424,2517", .data = µchip_usb424_data, }, { .compatible = "usb424,2744", .data = µchip_usb5744_data, }, diff --git a/drivers/usb/misc/usbtest.c b/drivers/usb/misc/usbtest.c index 8759df49be2873..e2f5e6be353acb 100644 --- a/drivers/usb/misc/usbtest.c +++ b/drivers/usb/misc/usbtest.c @@ -466,6 +466,9 @@ static int simple_io( int retval = 0; unsigned long expire; + if (vary && !max) + return -EINVAL; + urb->context = &completion; while (retval == 0 && iterations-- > 0) { init_completion(&completion); diff --git a/drivers/usb/mtu3/mtu3_core.c b/drivers/usb/mtu3/mtu3_core.c index 386fcb5d628e8c..fc274646fcdebb 100644 --- a/drivers/usb/mtu3/mtu3_core.c +++ b/drivers/usb/mtu3/mtu3_core.c @@ -790,10 +790,9 @@ static irqreturn_t mtu3_u2_common_isr(struct mtu3 *mtu) static irqreturn_t mtu3_irq(int irq, void *data) { struct mtu3 *mtu = (struct mtu3 *)data; - unsigned long flags; u32 level1; - spin_lock_irqsave(&mtu->lock, flags); + spin_lock_bh(&mtu->lock); /* U3D_LV1ISR is RU */ level1 = mtu3_readl(mtu->mac_base, U3D_LV1ISR); @@ -814,7 +813,7 @@ static irqreturn_t mtu3_irq(int irq, void *data) if (level1 & QMU_INTR) mtu3_qmu_isr(mtu); - spin_unlock_irqrestore(&mtu->lock, flags); + spin_unlock_bh(&mtu->lock); return IRQ_HANDLED; } diff --git a/drivers/usb/mtu3/mtu3_dr.c b/drivers/usb/mtu3/mtu3_dr.c index ffa5b9401dad0a..262922057b13b6 100644 --- a/drivers/usb/mtu3/mtu3_dr.c +++ b/drivers/usb/mtu3/mtu3_dr.c @@ -326,6 +326,6 @@ void ssusb_otg_switch_exit(struct ssusb_mtk *ssusb) { struct otg_switch_mtk *otg_sx = &ssusb->otg_switch; - cancel_work_sync(&otg_sx->dr_work); + disable_work_sync(&otg_sx->dr_work); usb_role_switch_unregister(otg_sx->role_sw); } diff --git a/drivers/usb/musb/musb_core.c b/drivers/usb/musb/musb_core.c index 9b63b56edc4531..eb29ae47697c29 100644 --- a/drivers/usb/musb/musb_core.c +++ b/drivers/usb/musb/musb_core.c @@ -2630,9 +2630,6 @@ static void musb_remove(struct platform_device *pdev) */ musb_exit_debugfs(musb); - cancel_delayed_work_sync(&musb->irq_work); - cancel_delayed_work_sync(&musb->finish_resume_work); - cancel_delayed_work_sync(&musb->deassert_reset_work); pm_runtime_get_sync(musb->controller); musb_host_cleanup(musb); musb_gadget_cleanup(musb); @@ -2642,6 +2639,18 @@ static void musb_remove(struct platform_device *pdev) musb_disable_interrupts(musb); musb_writeb(musb->mregs, MUSB_DEVCTL, 0); spin_unlock_irqrestore(&musb->lock, flags); + + /* + * musb_stage0_irq() arms irq_work (and finish_resume_work on + * remote wakeup) from interrupt context, so the works can only be + * cancelled for good once interrupts are masked and any in-flight + * handler has completed. + */ + synchronize_irq(musb->nIrq); + cancel_delayed_work_sync(&musb->irq_work); + cancel_delayed_work_sync(&musb->finish_resume_work); + cancel_delayed_work_sync(&musb->deassert_reset_work); + musb_platform_exit(musb); pm_runtime_dont_use_autosuspend(musb->controller); @@ -2825,18 +2834,26 @@ static int musb_suspend(struct device *dev) spin_lock_irqsave(&musb->lock, flags); + musb_save_context(musb); + if (is_peripheral_active(musb)) { - /* FIXME force disconnect unless we know USB will wake - * the system up quickly enough to respond ... + /* + * We can't answer a host with the interrupts off, so disable + * the D+ pullup. musb_restore_context() puts back the state + * saved above. Where the PHY is powered off during suspend + * (AM335x, for one), D+ drops anyway; where it stays powered, + * as on sunxi, the host would see a device that can't answer. */ + u8 power = musb_readb(musb->mregs, MUSB_POWER); + + musb_writeb(musb->mregs, MUSB_POWER, + power & ~MUSB_POWER_SOFTCONN); } else if (is_host_active(musb)) { /* we know all the children are suspended; sometimes * they will even be wakeup-enabled. */ } - musb_save_context(musb); - spin_unlock_irqrestore(&musb->lock, flags); return 0; } diff --git a/drivers/usb/musb/musb_dsps.c b/drivers/usb/musb/musb_dsps.c index 91d8712efa41b1..69c8b4b3ffa76a 100644 --- a/drivers/usb/musb/musb_dsps.c +++ b/drivers/usb/musb/musb_dsps.c @@ -942,6 +942,17 @@ static void dsps_remove(struct platform_device *pdev) { struct dsps_glue *glue = platform_get_drvdata(pdev); + /* + * The VBUS interrupt handler re-arms musb->dev_timer via + * dsps_mod_timer(); the IRQ is devm-managed and would only be + * freed after this function returns, while the child teardown + * below deletes the timer and frees the musb structure. Free + * the interrupt first so no VBUS event can re-arm the timer + * past that point. + */ + if (glue->vbus_irq) + devm_free_irq(glue->dev, glue->vbus_irq, glue); + platform_device_unregister(glue->musb); pm_runtime_disable(&pdev->dev); diff --git a/drivers/usb/phy/phy-gpio-vbus-usb.c b/drivers/usb/phy/phy-gpio-vbus-usb.c index 60b7c1219dd2c7..82d2301c380422 100644 --- a/drivers/usb/phy/phy-gpio-vbus-usb.c +++ b/drivers/usb/phy/phy-gpio-vbus-usb.c @@ -325,6 +325,14 @@ static void gpio_vbus_remove(struct platform_device *pdev) struct gpio_vbus_data *gpio_vbus = platform_get_drvdata(pdev); device_init_wakeup(&pdev->dev, 0); + + /* + * The VBUS sensing GPIO interrupt is devm-managed and freed only + * at detach, and its handler schedules the work with a 100ms + * delay; free the interrupt before cancelling the work so a + * late plug event cannot re-arm it past the cancel. + */ + devm_free_irq(&pdev->dev, gpio_vbus->irq, pdev); cancel_delayed_work_sync(&gpio_vbus->work); usb_remove_phy(&gpio_vbus->phy); diff --git a/drivers/usb/renesas_usbhs/mod_host.c b/drivers/usb/renesas_usbhs/mod_host.c index f7ef3a9f82a4b2..0652525d06feca 100644 --- a/drivers/usb/renesas_usbhs/mod_host.c +++ b/drivers/usb/renesas_usbhs/mod_host.c @@ -633,6 +633,7 @@ static void usbhsh_queue_done(struct usbhs_priv *priv, struct usbhs_pkt *pkt) struct usb_hcd *hcd = usbhsh_hpriv_to_hcd(hpriv); struct urb *urb = ureq->urb; struct device *dev = usbhs_priv_to_dev(priv); + unsigned long flags; int status = 0; dev_dbg(dev, "%s\n", __func__); @@ -652,7 +653,10 @@ static void usbhsh_queue_done(struct usbhs_priv *priv, struct usbhs_pkt *pkt) usbhsh_pipe_detach(hpriv, usbhsh_ep_to_uep(urb->ep)); + usbhs_lock(priv, flags); usb_hcd_unlink_urb_from_ep(hcd, urb); + usbhs_unlock(priv, flags); + usb_hcd_giveback_urb(hcd, urb, status); } @@ -955,6 +959,7 @@ static int usbhsh_urb_enqueue(struct usb_hcd *hcd, struct usb_host_endpoint *ep = urb->ep; struct usbhsh_device *new_udev = NULL; int is_dir_in = usb_pipein(urb->pipe); + unsigned long flags; int ret; dev_dbg(dev, "%s (%s)\n", __func__, is_dir_in ? "in" : "out"); @@ -965,7 +970,9 @@ static int usbhsh_urb_enqueue(struct usb_hcd *hcd, goto usbhsh_urb_enqueue_error_not_linked; } + usbhs_lock(priv, flags); ret = usb_hcd_link_urb_to_ep(hcd, urb); + usbhs_unlock(priv, flags); if (ret) { dev_err(dev, "urb link failed\n"); goto usbhsh_urb_enqueue_error_not_linked; diff --git a/drivers/usb/serial/f81232.c b/drivers/usb/serial/f81232.c index 9a3ede35a3d9ea..b62e93e7612c40 100644 --- a/drivers/usb/serial/f81232.c +++ b/drivers/usb/serial/f81232.c @@ -695,6 +695,7 @@ static int f81232_tiocmset(struct tty_struct *tty, static int f81232_open(struct tty_struct *tty, struct usb_serial_port *port) { + struct f81232_private *priv = usb_get_serial_port_data(port); int result; result = f81232_port_enable(port); @@ -715,6 +716,8 @@ static int f81232_open(struct tty_struct *tty, struct usb_serial_port *port) result = usb_serial_generic_open(tty, port); if (result) { usb_kill_urb(port->interrupt_in_urb); + flush_work(&priv->interrupt_work); + flush_work(&priv->lsr_work); return result; } diff --git a/drivers/usb/serial/garmin_gps.c b/drivers/usb/serial/garmin_gps.c index 8020149f5658dc..a7c18a8fdf59c6 100644 --- a/drivers/usb/serial/garmin_gps.c +++ b/drivers/usb/serial/garmin_gps.c @@ -746,11 +746,7 @@ static int nat_receive(struct garmin_data *garmin_data_p, len = GARMIN_PKTHDR_LENGTH; if (len >= GPS_IN_BUFSIZ) { - /* seems to be an invalid packet, ignore rest - of input */ - dev_dbg(&garmin_data_p->port->dev, - "%s - packet size too large: %d\n", - __func__, len); + /* should never end up here given the dlen check below */ garmin_data_p->insize = 0; count = 0; result = -EINVPKT; @@ -769,8 +765,17 @@ static int nat_receive(struct garmin_data *garmin_data_p, /* do we have a complete packet ? */ if (garmin_data_p->insize >= GARMIN_PKTHDR_LENGTH) { - len = GARMIN_PKTHDR_LENGTH+ - getDataLength(garmin_data_p->inbuffer); + u32 dlen = getDataLength(garmin_data_p->inbuffer); + + if (dlen >= GPS_IN_BUFSIZ - GARMIN_PKTHDR_LENGTH) { + /* invalid packet, ignore rest of input */ + dev_dbg(&garmin_data_p->port->dev, "%s - invalid length: %u\n", + __func__, dlen); + garmin_data_p->insize = 0; + result = -EINVPKT; + break; + } + len = GARMIN_PKTHDR_LENGTH + dlen; if (garmin_data_p->insize >= len) { garmin_write_bulk(garmin_data_p->port, garmin_data_p->inbuffer, @@ -818,10 +823,9 @@ static void priv_status_resp(struct usb_serial_port *port) * Garmin specific driver functions ******************************************************************************/ -static int process_resetdev_request(struct usb_serial_port *port) +static void process_resetdev_request(struct usb_serial_port *port) { unsigned long flags; - int status; struct garmin_data *garmin_data_p = usb_get_serial_port_data(port); spin_lock_irqsave(&garmin_data_p->lock, flags); @@ -830,13 +834,8 @@ static int process_resetdev_request(struct usb_serial_port *port) garmin_data_p->serial_num = 0; spin_unlock_irqrestore(&garmin_data_p->lock, flags); - usb_kill_urb(port->interrupt_in_urb); - dev_dbg(&port->dev, "%s - usb_reset_device\n", __func__); - status = usb_reset_device(port->serial->dev); - if (status) - dev_dbg(&port->dev, "%s - usb_reset_device failed: %d\n", - __func__, status); - return status; + dev_dbg(&port->dev, "%s - usb_queue_reset_device\n", __func__); + usb_queue_reset_device(port->serial->interface); } diff --git a/drivers/usb/serial/io_edgeport.c b/drivers/usb/serial/io_edgeport.c index eaa8f00716c87d..0fd68faa8427c0 100644 --- a/drivers/usb/serial/io_edgeport.c +++ b/drivers/usb/serial/io_edgeport.c @@ -168,6 +168,7 @@ struct edgeport_port { struct urb *write_urb; /* write URB for this port */ bool write_in_progress; /* 'true' while a write URB is outstanding */ spinlock_t ep_lock; + struct mutex mutex; __u8 shadowLCR; /* last LCR value received */ __u8 shadowMCR; /* last MCR value received */ @@ -225,6 +226,7 @@ struct edgeport_serial { __u8 rxStatusParam; /* the receive status parameter */ __s16 rxBytesRemaining; /* the number of port bytes left to read */ struct usb_serial *serial; /* loop back to the owner of this object */ + struct usb_anchor cmd_anchor; }; /* baud rate information */ @@ -261,9 +263,6 @@ static const struct divisor_table_entry divisor_table[] = { { 230400, 1}, }; -/* Number of outstanding Command Write Urbs */ -static atomic_t CmdUrbs = ATOMIC_INIT(0); - /* function prototypes */ @@ -281,8 +280,7 @@ static void handle_new_lsr(struct edgeport_port *edge_port, __u8 lsrData, static int send_iosp_ext_cmd(struct edgeport_port *edge_port, __u8 command, __u8 param); static int calc_baud_rate_divisor(struct device *dev, int baud_rate, int *divisor); -static void change_port_settings(struct tty_struct *tty, - struct edgeport_port *edge_port, +static void edge_set_termios(struct tty_struct *tty, struct usb_serial_port *port, const struct ktermios *old_termios); static int send_cmd_write_uart_register(struct edgeport_port *edge_port, __u8 regNum, __u8 regValue); @@ -777,11 +775,6 @@ static void edge_bulk_out_cmd_callback(struct urb *urb) struct device *dev = &urb->dev->dev; int status = urb->status; - atomic_dec(&CmdUrbs); - dev_dbg(dev, "%s - FREE URB %p (outstanding %d)\n", __func__, urb, - atomic_read(&CmdUrbs)); - - /* clean up the transfer buffer */ kfree(urb->transfer_buffer); @@ -877,22 +870,22 @@ static int edge_open(struct tty_struct *tty, struct usb_serial_port *port) } } - /* initialize our wait queues */ - init_waitqueue_head(&edge_port->wait_open); - init_waitqueue_head(&edge_port->wait_chase); - init_waitqueue_head(&edge_port->wait_command); - /* initialize our port settings */ + spin_lock_irq(&edge_port->ep_lock); edge_port->txCredits = 0; /* Can't send any data yet */ + edge_port->maxTxCredits = 0; + edge_port->openPending = true; + spin_unlock_irq(&edge_port->ep_lock); + /* Must always set this bit to enable ints! */ + mutex_lock(&edge_port->mutex); edge_port->shadowMCR = MCR_MASTER_IE; + mutex_unlock(&edge_port->mutex); + edge_port->chaseResponsePending = false; /* send a open port command */ - edge_port->openPending = true; - edge_port->open = false; response = send_iosp_ext_cmd(edge_port, IOSP_CMD_OPEN_PORT, 0); - if (response < 0) { dev_err(dev, "%s - error sending open port command\n", __func__); edge_port->openPending = false; @@ -902,8 +895,7 @@ static int edge_open(struct tty_struct *tty, struct usb_serial_port *port) /* now wait for the port to be completely opened */ wait_event_timeout(edge_port->wait_open, !edge_port->openPending, OPEN_TIMEOUT); - - if (!edge_port->open) { + if (edge_port->openPending) { /* open timed out */ dev_dbg(dev, "%s - open timeout\n", __func__); edge_port->openPending = false; @@ -931,6 +923,13 @@ static int edge_open(struct tty_struct *tty, struct usb_serial_port *port) return -ENOMEM; } + if (tty) + edge_set_termios(tty, port, NULL); + + spin_lock_irq(&edge_port->ep_lock); + edge_port->open = true; + spin_unlock_irq(&edge_port->ep_lock); + dev_dbg(dev, "%s - Initialize TX fifo to %d bytes\n", __func__, edge_port->maxTxCredits); @@ -1090,7 +1089,9 @@ static void edge_close(struct usb_serial_port *port) /* port->close = true; */ edge_port->closePending = false; + spin_lock_irq(&edge_port->ep_lock); edge_port->open = false; + spin_unlock_irq(&edge_port->ep_lock); edge_port->openPending = false; usb_kill_urb(edge_port->write_urb); @@ -1132,6 +1133,12 @@ static int edge_write(struct tty_struct *tty, struct usb_serial_port *port, spin_lock_irqsave(&edge_port->ep_lock, flags); + /* avoid accessing freed fifo if tty_wakeup() races with close() */ + if (!edge_port->open) { + spin_unlock_irqrestore(&edge_port->ep_lock, flags); + return 0; + } + /* calculate number of bytes to put in fifo */ copySize = min_t(unsigned int, count, (edge_port->txCredits - fifo->count)); @@ -1395,9 +1402,11 @@ static void edge_throttle(struct tty_struct *tty) /* if we are implementing RTS/CTS, toggle that line */ if (C_CRTSCTS(tty)) { + mutex_lock(&edge_port->mutex); edge_port->shadowMCR &= ~MCR_RTS; status = send_cmd_write_uart_register(edge_port, MCR, edge_port->shadowMCR); + mutex_unlock(&edge_port->mutex); if (status != 0) return; } @@ -1432,37 +1441,15 @@ static void edge_unthrottle(struct tty_struct *tty) } /* if we are implementing RTS/CTS, toggle that line */ if (C_CRTSCTS(tty)) { + mutex_lock(&edge_port->mutex); edge_port->shadowMCR |= MCR_RTS; send_cmd_write_uart_register(edge_port, MCR, edge_port->shadowMCR); + mutex_unlock(&edge_port->mutex); } } -/***************************************************************************** - * SerialSetTermios - * this function is called by the tty driver when it wants to change - * the termios structure - *****************************************************************************/ -static void edge_set_termios(struct tty_struct *tty, - struct usb_serial_port *port, - const struct ktermios *old_termios) -{ - struct edgeport_port *edge_port = usb_get_serial_port_data(port); - - if (edge_port == NULL) - return; - - if (!edge_port->open) { - dev_dbg(&port->dev, "%s - port not opened\n", __func__); - return; - } - - /* change the port settings to the new ones specified */ - change_port_settings(tty, edge_port, old_termios); -} - - /***************************************************************************** * get_lsr_info - get line status register info * @@ -1499,6 +1486,7 @@ static int edge_tiocmset(struct tty_struct *tty, struct edgeport_port *edge_port = usb_get_serial_port_data(port); unsigned int mcr; + mutex_lock(&edge_port->mutex); mcr = edge_port->shadowMCR; if (set & TIOCM_RTS) mcr |= MCR_RTS; @@ -1517,6 +1505,7 @@ static int edge_tiocmset(struct tty_struct *tty, edge_port->shadowMCR = mcr; send_cmd_write_uart_register(edge_port, MCR, edge_port->shadowMCR); + mutex_unlock(&edge_port->mutex); return 0; } @@ -1530,6 +1519,7 @@ static int edge_tiocmget(struct tty_struct *tty) unsigned int mcr; msr = edge_port->shadowMSR; + mutex_lock(&edge_port->mutex); mcr = edge_port->shadowMCR; result = ((mcr & MCR_DTR) ? TIOCM_DTR: 0) /* 0x002 */ | ((mcr & MCR_RTS) ? TIOCM_RTS: 0) /* 0x004 */ @@ -1537,6 +1527,7 @@ static int edge_tiocmget(struct tty_struct *tty) | ((msr & EDGEPORT_MSR_CD) ? TIOCM_CAR: 0) /* 0x040 */ | ((msr & EDGEPORT_MSR_RI) ? TIOCM_RI: 0) /* 0x080 */ | ((msr & EDGEPORT_MSR_DSR) ? TIOCM_DSR: 0); /* 0x100 */ + mutex_unlock(&edge_port->mutex); return result; } @@ -1752,9 +1743,9 @@ static void process_rcvd_status(struct edgeport_serial *edge_serial, { struct usb_serial_port *port; struct edgeport_port *edge_port; - struct tty_struct *tty; struct device *dev; __u8 code = edge_serial->rxStatusCode; + unsigned long flags; /* switch the port pointer to the one being currently talked about */ if (edge_serial->rxPort >= edge_serial->serial->num_ports) @@ -1798,24 +1789,22 @@ static void process_rcvd_status(struct edgeport_serial *edge_serial, } if (code == IOSP_STATUS_OPEN_RSP) { + spin_lock_irqsave(&edge_port->ep_lock, flags); + /* reject stray open responses to avoid FIFO corruption */ + if (!edge_port->openPending) { + spin_unlock_irqrestore(&edge_port->ep_lock, flags); + return; + } edge_port->txCredits = GET_TX_BUFFER_SIZE(byte3); edge_port->maxTxCredits = edge_port->txCredits; dev_dbg(dev, "%s - Port %u Open Response Initial MSR = %02x TxBufferSize = %d\n", __func__, edge_serial->rxPort, byte2, edge_port->txCredits); handle_new_msr(edge_port, byte2); - /* send the current line settings to the port so we are - in sync with any further termios calls */ - tty = tty_port_tty_get(&edge_port->port->port); - if (tty) { - change_port_settings(tty, - edge_port, &tty->termios); - tty_kref_put(tty); - } - /* we have completed the open */ edge_port->openPending = false; - edge_port->open = true; + spin_unlock_irqrestore(&edge_port->ep_lock, flags); + wake_up(&edge_port->wait_open); return; } @@ -2143,24 +2132,21 @@ static int write_cmd_usb(struct edgeport_port *edge_port, if (!urb) return -ENOMEM; - atomic_inc(&CmdUrbs); - dev_dbg(dev, "%s - ALLOCATE URB %p (outstanding %d)\n", - __func__, urb, atomic_read(&CmdUrbs)); - usb_fill_bulk_urb(urb, edge_serial->serial->dev, usb_sndbulkpipe(edge_serial->serial->dev, edge_serial->bulk_out_endpoint), buffer, length, edge_bulk_out_cmd_callback, edge_port); edge_port->commandPending = true; + usb_anchor_urb(urb, &edge_serial->cmd_anchor); status = usb_submit_urb(urb, GFP_ATOMIC); if (status) { /* something went wrong */ dev_err(dev, "%s - usb_submit_urb(write command) failed, status = %d\n", __func__, status); + usb_unanchor_urb(urb); usb_free_urb(urb); - atomic_dec(&CmdUrbs); return status; } @@ -2325,18 +2311,12 @@ static int send_cmd_write_uart_register(struct edgeport_port *edge_port, } -/***************************************************************************** - * change_port_settings - * This routine is called to set the UART on the device to match the - * specified new settings. - *****************************************************************************/ - -static void change_port_settings(struct tty_struct *tty, - struct edgeport_port *edge_port, const struct ktermios *old_termios) +static void edge_set_termios(struct tty_struct *tty, struct usb_serial_port *port, + const struct ktermios *old_termios) { - struct device *dev = &edge_port->port->dev; - struct edgeport_serial *edge_serial = - usb_get_serial_data(edge_port->port->serial); + struct edgeport_serial *edge_serial = usb_get_serial_data(port->serial); + struct edgeport_port *edge_port = usb_get_serial_port_data(port); + struct device *dev = &port->dev; int baud; unsigned cflag; __u8 mask = 0xff; @@ -2347,12 +2327,6 @@ static void change_port_settings(struct tty_struct *tty, __u8 txFlow; int status; - if (!edge_port->open && - !edge_port->openPending) { - dev_dbg(dev, "%s - port not opened\n", __func__); - return; - } - cflag = tty->termios.c_cflag; switch (cflag & CSIZE) { @@ -2468,12 +2442,14 @@ static void change_port_settings(struct tty_struct *tty, return; /* set up the MCR register and send it to the EdgePort */ + mutex_lock(&edge_port->mutex); edge_port->shadowMCR = MCR_MASTER_IE; if (cflag & CBAUD) edge_port->shadowMCR |= (MCR_DTR | MCR_RTS); status = send_cmd_write_uart_register(edge_port, MCR, edge_port->shadowMCR); + mutex_unlock(&edge_port->mutex); if (status != 0) return; @@ -2486,7 +2462,7 @@ static void change_port_settings(struct tty_struct *tty, dev_dbg(dev, "%s - baud rate = %d\n", __func__, baud); status = send_cmd_write_baud_rate(edge_port, baud); - if (status == -1) { + if (status == -1 && old_termios) { /* Speed change was not possible - put back the old speed */ baud = tty_termios_baud_rate(old_termios); tty_encode_baud_rate(tty, baud, baud); @@ -2724,6 +2700,7 @@ static int edge_startup(struct usb_serial *serial) spin_lock_init(&edge_serial->es_lock); edge_serial->serial = serial; + init_usb_anchor(&edge_serial->cmd_anchor); usb_set_serial_data(serial, edge_serial); /* get the name for the device from the device */ @@ -2928,6 +2905,8 @@ static void edge_disconnect(struct usb_serial *serial) { struct edgeport_serial *edge_serial = usb_get_serial_data(serial); + usb_kill_anchored_urbs(&edge_serial->cmd_anchor); + if (edge_serial->is_epic) { usb_kill_urb(edge_serial->interrupt_read_urb); usb_kill_urb(edge_serial->read_urb); @@ -2965,6 +2944,12 @@ static int edge_port_probe(struct usb_serial_port *port) return -ENOMEM; spin_lock_init(&edge_port->ep_lock); + mutex_init(&edge_port->mutex); + + init_waitqueue_head(&edge_port->wait_open); + init_waitqueue_head(&edge_port->wait_chase); + init_waitqueue_head(&edge_port->wait_command); + edge_port->port = port; usb_set_serial_port_data(port, edge_port); diff --git a/drivers/usb/serial/mct_u232.c b/drivers/usb/serial/mct_u232.c index a6de18917ec9fd..8a7aee2b26dda4 100644 --- a/drivers/usb/serial/mct_u232.c +++ b/drivers/usb/serial/mct_u232.c @@ -457,7 +457,7 @@ static int mct_u232_open(struct tty_struct *tty, struct usb_serial_port *port) if (retval) { dev_err(&port->dev, "usb_submit_urb(read) failed pipe 0x%x err %d\n", - port->read_urb->pipe, retval); + priv->read_urb->pipe, retval); goto error; } diff --git a/drivers/usb/serial/oti6858.c b/drivers/usb/serial/oti6858.c index c6364e8ff71f95..005fe19c3cd4f1 100644 --- a/drivers/usb/serial/oti6858.c +++ b/drivers/usb/serial/oti6858.c @@ -248,7 +248,7 @@ static void setup_line(struct work_struct *work) dev_dbg(&port->dev, "%s(): submitting interrupt urb\n", __func__); result = usb_submit_urb(port->interrupt_in_urb, GFP_KERNEL); - if (result != 0) { + if (result != 0 && result != -EPERM) { dev_err(&port->dev, "%s(): usb_submit_urb() failed with error %d\n", __func__, result); } @@ -300,7 +300,7 @@ static void send_data(struct work_struct *work) dev_dbg(&port->dev, "%s(): submitting interrupt urb\n", __func__); result = usb_submit_urb(port->interrupt_in_urb, GFP_NOIO); - if (result != 0) { + if (result != 0 && result != -EPERM) { dev_err(&port->dev, "%s(): usb_submit_urb() failed with error %d\n", __func__, result); } @@ -561,6 +561,13 @@ static void oti6858_close(struct usb_serial_port *port) dev_dbg(&port->dev, "%s(): after buf_clear()\n", __func__); + /* + * The interrupt urb schedules the works, and the works and the bulk + * urbs resubmit the interrupt urb: keep it from being submitted until + * all of them are gone. + */ + usb_poison_urb(port->interrupt_in_urb); + /* cancel scheduled setup */ cancel_delayed_work_sync(&priv->delayed_setup_work); cancel_delayed_work_sync(&priv->delayed_write_work); @@ -569,7 +576,8 @@ static void oti6858_close(struct usb_serial_port *port) dev_dbg(&port->dev, "%s(): shutting down urbs\n", __func__); usb_kill_urb(port->write_urb); usb_kill_urb(port->read_urb); - usb_kill_urb(port->interrupt_in_urb); + + usb_unpoison_urb(port->interrupt_in_urb); } static int oti6858_tiocmset(struct tty_struct *tty, @@ -826,7 +834,7 @@ static void oti6858_write_bulk_callback(struct urb *urb) /* schedule the interrupt urb if we are still open */ dev_dbg(&port->dev, "%s(): submitting interrupt urb\n", __func__); result = usb_submit_urb(port->interrupt_in_urb, GFP_ATOMIC); - if (result != 0) { + if (result != 0 && result != -EPERM) { dev_err(&port->dev, "%s(): failed submitting int urb," " error %d\n", __func__, result); } diff --git a/drivers/usb/serial/sierra.c b/drivers/usb/serial/sierra.c index f2cc7f364d2040..c6aa5dfe468b1a 100644 --- a/drivers/usb/serial/sierra.c +++ b/drivers/usb/serial/sierra.c @@ -575,12 +575,24 @@ static void sierra_instat_callback(struct urb *urb) __func__); return; } + if (urb->actual_length < sizeof(*req_pkt)) { + dev_err(&port->dev, "%s: short transfer\n", + __func__); + return; + } if ((req_pkt->bRequestType == 0xA1) && (req_pkt->bRequest == 0x20)) { int old_dcd_state; - unsigned char signals = *((unsigned char *) - urb->transfer_buffer + - sizeof(struct usb_ctrlrequest)); + unsigned char signals; + + if (urb->actual_length < sizeof(*req_pkt) + 1) { + dev_err(&port->dev, + "%s: short interrupt transfer\n", + __func__); + return; + } + signals = *((unsigned char *)urb->transfer_buffer + + sizeof(*req_pkt)); dev_dbg(&port->dev, "%s: signal x%x\n", __func__, signals); diff --git a/drivers/usb/serial/upd78f0730.c b/drivers/usb/serial/upd78f0730.c index 78c4d3c19a8ec4..f2189b994ed7b1 100644 --- a/drivers/usb/serial/upd78f0730.c +++ b/drivers/usb/serial/upd78f0730.c @@ -201,10 +201,9 @@ static int upd78f0730_tiocmget(struct tty_struct *tty) return res; } -static int upd78f0730_tiocmset(struct tty_struct *tty, +static int upd78f0730_port_tiocmset(struct usb_serial_port *port, unsigned int set, unsigned int clear) { - struct usb_serial_port *port = tty->driver_data; struct upd78f0730_port_private *private; struct upd78f0730_set_dtr_rts request; struct device *dev = &port->dev; @@ -238,6 +237,13 @@ static int upd78f0730_tiocmset(struct tty_struct *tty, return res; } +static int upd78f0730_tiocmset(struct tty_struct *tty, unsigned int set, unsigned int clear) +{ + struct usb_serial_port *port = tty->driver_data; + + return upd78f0730_port_tiocmset(port, set, clear); +} + static int upd78f0730_break_ctl(struct tty_struct *tty, int break_state) { struct upd78f0730_port_private *private; @@ -267,7 +273,6 @@ static int upd78f0730_break_ctl(struct tty_struct *tty, int break_state) static void upd78f0730_dtr_rts(struct usb_serial_port *port, int on) { - struct tty_struct *tty = port->port.tty; unsigned int set = 0; unsigned int clear = 0; @@ -276,7 +281,7 @@ static void upd78f0730_dtr_rts(struct usb_serial_port *port, int on) else clear = TIOCM_DTR | TIOCM_RTS; - upd78f0730_tiocmset(tty, set, clear); + upd78f0730_port_tiocmset(port, set, clear); } static speed_t upd78f0730_get_baud_rate(struct tty_struct *tty) diff --git a/drivers/usb/storage/ene_ub6250.c b/drivers/usb/storage/ene_ub6250.c index fea2614e767c70..bf661d8e2c5405 100644 --- a/drivers/usb/storage/ene_ub6250.c +++ b/drivers/usb/storage/ene_ub6250.c @@ -24,6 +24,9 @@ #define DRV_NAME "ums_eneub6250" +/* Timeout for each transfer of the probe-time card-type query, in jiffies. */ +#define ENE_PROBE_TIMEOUT (10 * HZ) + MODULE_DESCRIPTION("Driver for ENE UB6250 reader"); MODULE_LICENSE("GPL"); MODULE_IMPORT_NS("USB_STORAGE"); @@ -34,6 +37,8 @@ MODULE_FIRMWARE(MS_INIT_FIRMWARE); MODULE_FIRMWARE(MSP_RW_FIRMWARE); MODULE_FIRMWARE(MS_RW_FIRMWARE); +static int ene_ub6250_init(struct us_data *us); + /* * The table of devices */ @@ -487,7 +492,12 @@ static void ene_ub6250_info_destructor(void *extra) kfree(info->bbuf); } -static int ene_send_scsi_cmd(struct us_data *us, u8 fDir, void *buf, int use_sg) +/* + * Send an ENE SCSI command. @timeout bounds the wait for each transfer of + * the transaction, in jiffies; zero means no limit. + */ +static int ene_send_scsi_cmd_timeout(struct us_data *us, u8 fdir, void *buf, + int use_sg, unsigned int timeout) { struct bulk_cb_wrap *bcb = (struct bulk_cb_wrap *) us->iobuf; struct bulk_cs_wrap *bcs = (struct bulk_cs_wrap *) us->iobuf; @@ -499,27 +509,33 @@ static int ene_send_scsi_cmd(struct us_data *us, u8 fDir, void *buf, int use_sg) /* usb_stor_dbg(us, "transport --- ene_send_scsi_cmd\n"); */ /* send cmd to out endpoint */ - result = usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe, - bcb, US_BULK_CB_WRAP_LEN, NULL); + result = usb_stor_bulk_transfer_buf_timeout(us, us->send_bulk_pipe, + bcb, US_BULK_CB_WRAP_LEN, + NULL, timeout); if (result != USB_STOR_XFER_GOOD) { usb_stor_dbg(us, "send cmd to out endpoint fail ---\n"); return USB_STOR_TRANSPORT_ERROR; } if (buf) { - unsigned int pipe = fDir; + unsigned int pipe; - if (fDir == FDIR_READ) + if (fdir == FDIR_READ) pipe = us->recv_bulk_pipe; else pipe = us->send_bulk_pipe; /* Bulk */ if (use_sg) { + /* + * Scatter-gather transfers belong to SCSI commands, + * whose timeout and abort machinery bound the wait. + */ result = usb_stor_bulk_srb(us, pipe, us->srb); } else { - result = usb_stor_bulk_transfer_sg(us, pipe, buf, - transfer_length, 0, &partial); + result = usb_stor_bulk_transfer_buf_timeout(us, pipe, + buf, transfer_length, + &partial, timeout); } if (result != USB_STOR_XFER_GOOD) { usb_stor_dbg(us, "data transfer fail ---\n"); @@ -528,20 +544,25 @@ static int ene_send_scsi_cmd(struct us_data *us, u8 fDir, void *buf, int use_sg) } /* Get CSW for device status */ - result = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe, bcs, - US_BULK_CS_WRAP_LEN, &cswlen); + result = usb_stor_bulk_transfer_buf_timeout(us, us->recv_bulk_pipe, + bcs, US_BULK_CS_WRAP_LEN, + &cswlen, timeout); if (result == USB_STOR_XFER_SHORT && cswlen == 0) { usb_stor_dbg(us, "Received 0-length CSW; retrying...\n"); - result = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe, - bcs, US_BULK_CS_WRAP_LEN, &cswlen); + result = usb_stor_bulk_transfer_buf_timeout(us, + us->recv_bulk_pipe, bcs, + US_BULK_CS_WRAP_LEN, + &cswlen, timeout); } if (result == USB_STOR_XFER_STALLED) { /* get the status again */ usb_stor_dbg(us, "Attempting to get CSW (2nd try)...\n"); - result = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe, - bcs, US_BULK_CS_WRAP_LEN, NULL); + result = usb_stor_bulk_transfer_buf_timeout(us, + us->recv_bulk_pipe, bcs, + US_BULK_CS_WRAP_LEN, NULL, + timeout); } if (result != USB_STOR_XFER_GOOD) @@ -567,6 +588,15 @@ static int ene_send_scsi_cmd(struct us_data *us, u8 fDir, void *buf, int use_sg) return USB_STOR_TRANSPORT_GOOD; } +/* + * Unbounded variant for the command path: a SCSI command's timeout and + * abort machinery terminate the transfer if the device stops responding. + */ +static int ene_send_scsi_cmd(struct us_data *us, u8 fdir, void *buf, int use_sg) +{ + return ene_send_scsi_cmd_timeout(us, fdir, buf, use_sg, 0); +} + static int do_scsi_request_sense(struct us_data *us, struct scsi_cmnd *srb) { struct ene_ub6250_info *info = (struct ene_ub6250_info *) us->extra; @@ -1824,7 +1854,8 @@ static int ms_scsi_write(struct us_data *us, struct scsi_cmnd *srb) * ENE MS Card */ -static int ene_get_card_type(struct us_data *us, u16 index, void *buf) +static int ene_get_card_type(struct us_data *us, u16 index, void *buf, + unsigned int timeout) { struct bulk_cb_wrap *bcb = (struct bulk_cb_wrap *) us->iobuf; int result; @@ -1837,7 +1868,7 @@ static int ene_get_card_type(struct us_data *us, u16 index, void *buf) bcb->CDB[2] = (unsigned char)(index>>8); bcb->CDB[3] = (unsigned char)index; - result = ene_send_scsi_cmd(us, FDIR_READ, buf, 0); + result = ene_send_scsi_cmd_timeout(us, FDIR_READ, buf, 0, timeout); return result; } @@ -2191,7 +2222,7 @@ static int ene_init(struct us_data *us) struct ene_ub6250_info *info = (struct ene_ub6250_info *)(us->extra); u8 *bbuf = info->bbuf; - result = ene_get_card_type(us, REG_CARD_STATUS, bbuf); + result = ene_get_card_type(us, REG_CARD_STATUS, bbuf, 0); if (result != USB_STOR_XFER_GOOD) return USB_STOR_TRANSPORT_ERROR; @@ -2319,13 +2350,35 @@ static int ene_transport(struct scsi_cmnd *srb, struct us_data *us) static struct scsi_host_template ene_ub6250_host_template; +/* + * Probe-time card-type query. It runs from usb_stor_acquire_resources(), + * before the usb-storage control thread and the SCSI scan work exist, so + * nothing else can be using us->current_urb. Give every transfer a + * timeout: there is no SCSI command whose timeout or abort handling could + * end the wait, and a timeout at any stage fails the whole query. + */ +static int ene_ub6250_init(struct us_data *us) +{ + struct ene_ub6250_info *info = (struct ene_ub6250_info *)us->extra; + int result; + + result = ene_get_card_type(us, REG_CARD_STATUS, info->bbuf, + ENE_PROBE_TIMEOUT); + if (result != USB_STOR_XFER_GOOD) + return -EIO; + + if (!(info->bbuf[0] & 0x01)) + pr_info("ums_eneub6250: SM cards are not supported\n"); + + return 0; +} + static int ene_ub6250_probe(struct usb_interface *intf, const struct usb_device_id *id) { - int result; - u8 misc_reg03; struct us_data *us; struct ene_ub6250_info *info; + int result; result = usb_stor_probe1(&us, intf, id, (id - ene_ub6250_usb_ids) + ene_ub6250_unusual_dev_list, @@ -2352,26 +2405,7 @@ static int ene_ub6250_probe(struct usb_interface *intf, us->transport_reset = usb_stor_Bulk_reset; us->max_lun = 0; - result = usb_stor_probe2(us); - if (result) - return result; - - /* probe card type */ - mutex_lock(&us->dev_mutex); - result = ene_get_card_type(us, REG_CARD_STATUS, info->bbuf); - mutex_unlock(&us->dev_mutex); - if (result != USB_STOR_XFER_GOOD) { - usb_stor_disconnect(intf); - return USB_STOR_TRANSPORT_ERROR; - } - - misc_reg03 = info->bbuf[0]; - if (!(misc_reg03 & 0x01)) { - pr_info("ums_eneub6250: This driver only supports SD/MS cards. " - "It does not support SM cards.\n"); - } - - return result; + return usb_stor_probe2(us); } diff --git a/drivers/usb/storage/onetouch.c b/drivers/usb/storage/onetouch.c index 49d281f7bef693..e09b3c6b9a6a51 100644 --- a/drivers/usb/storage/onetouch.c +++ b/drivers/usb/storage/onetouch.c @@ -237,16 +237,16 @@ static int onetouch_connect_input(struct us_data *ss) onetouch->irq->transfer_dma = onetouch->data_dma; onetouch->irq->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; + error = input_register_device(onetouch->dev); + if (error) + goto fail3; + ss->extra_destructor = onetouch_release_input; ss->extra = onetouch; #ifdef CONFIG_PM ss->suspend_resume_hook = usb_onetouch_pm_hook; #endif - error = input_register_device(onetouch->dev); - if (error) - goto fail3; - return 0; fail3: usb_free_urb(onetouch->irq); diff --git a/drivers/usb/storage/scsiglue.c b/drivers/usb/storage/scsiglue.c index 97de28e8556263..7a55cfc18236dc 100644 --- a/drivers/usb/storage/scsiglue.c +++ b/drivers/usb/storage/scsiglue.c @@ -593,6 +593,10 @@ static ssize_t max_sectors_store(struct device *dev, struct device_attribute *at return -EINVAL; lim = queue_limits_start_update(sdev->request_queue); + if (ms < PAGE_SECTORS || ms < lim.logical_block_size >> SECTOR_SHIFT) { + queue_limits_cancel_update(sdev->request_queue); + return -EINVAL; + } lim.max_hw_sectors = ms; ret = queue_limits_commit_update_frozen(sdev->request_queue, &lim); if (ret) diff --git a/drivers/usb/storage/shuttle_usbat.c b/drivers/usb/storage/shuttle_usbat.c index 7e5424268c733c..267c823814656f 100644 --- a/drivers/usb/storage/shuttle_usbat.c +++ b/drivers/usb/storage/shuttle_usbat.c @@ -1038,6 +1038,8 @@ static int usbat_set_transport(struct us_data *us, break; case USBAT_DEV_FLASH: + /* The ATA sector size of these readers is fixed at 512 bytes */ + info->ssize = 0x200; us->transport = usbat_flash_transport; break; } @@ -1703,8 +1705,6 @@ static int usbat_flash_transport(struct scsi_cmnd * srb, struct us_data *us) if (rc != USB_STOR_TRANSPORT_GOOD) return rc; - /* hard coded 512 byte sectors as per ATA spec */ - info->ssize = 0x200; usb_stor_dbg(us, "READ_CAPACITY: %ld sectors, %ld bytes per sector\n", info->sectors, info->ssize); diff --git a/drivers/usb/storage/transport.c b/drivers/usb/storage/transport.c index 8de3015bce0502..424293658918a5 100644 --- a/drivers/usb/storage/transport.c +++ b/drivers/usb/storage/transport.c @@ -378,12 +378,17 @@ static int usb_stor_intr_transfer(struct us_data *us, void *buf, } /* - * Transfer one buffer via bulk pipe, without timeouts, but allowing early - * termination. Return codes are USB_STOR_XFER_xxx. If the bulk pipe - * stalls during the transfer, the halt is automatically cleared. + * Transfer one buffer via bulk pipe, allowing early termination. Return + * codes are USB_STOR_XFER_xxx. If the bulk pipe stalls during the + * transfer, the halt is automatically cleared. + * + * A nonzero @timeout bounds the wait for URB completion, in jiffies. It + * must only be used for transfers which are not part of a SCSI command: + * those rely on the command's timeout and abort handling. */ -int usb_stor_bulk_transfer_buf(struct us_data *us, unsigned int pipe, - void *buf, unsigned int length, unsigned int *act_len) +int usb_stor_bulk_transfer_buf_timeout(struct us_data *us, unsigned int pipe, + void *buf, unsigned int length, + unsigned int *act_len, int timeout) { int result; @@ -392,14 +397,26 @@ int usb_stor_bulk_transfer_buf(struct us_data *us, unsigned int pipe, /* fill and submit the URB */ usb_fill_bulk_urb(us->current_urb, us->pusb_dev, pipe, buf, length, usb_stor_blocking_completion, NULL); - result = usb_stor_msg_common(us, 0); + result = usb_stor_msg_common(us, timeout); /* store the actual length of the data transferred */ if (act_len) *act_len = us->current_urb->actual_length; - return interpret_urb_result(us, pipe, length, result, + return interpret_urb_result(us, pipe, length, result, us->current_urb->actual_length); } +EXPORT_SYMBOL_GPL(usb_stor_bulk_transfer_buf_timeout); + +/* + * Same as usb_stor_bulk_transfer_buf_timeout() with an unbounded wait. + */ +int usb_stor_bulk_transfer_buf(struct us_data *us, unsigned int pipe, + void *buf, unsigned int length, + unsigned int *act_len) +{ + return usb_stor_bulk_transfer_buf_timeout(us, pipe, buf, length, + act_len, 0); +} EXPORT_SYMBOL_GPL(usb_stor_bulk_transfer_buf); /* diff --git a/drivers/usb/storage/transport.h b/drivers/usb/storage/transport.h index 74ffd0d7e7b6cf..361dbd77f15e38 100644 --- a/drivers/usb/storage/transport.h +++ b/drivers/usb/storage/transport.h @@ -77,6 +77,11 @@ extern int usb_stor_clear_halt(struct us_data *us, unsigned int pipe); extern int usb_stor_ctrl_transfer(struct us_data *us, unsigned int pipe, u8 request, u8 requesttype, u16 value, u16 index, void *data, u16 size); +extern int usb_stor_bulk_transfer_buf_timeout(struct us_data *us, + unsigned int pipe, void *buf, + unsigned int length, + unsigned int *act_len, + int timeout); extern int usb_stor_bulk_transfer_buf(struct us_data *us, unsigned int pipe, void *buf, unsigned int length, unsigned int *act_len); extern int usb_stor_bulk_transfer_sg(struct us_data *us, unsigned int pipe, diff --git a/drivers/usb/storage/uas-detect.h b/drivers/usb/storage/uas-detect.h index 4d3b49e5b87a9d..523a17cf0a3c10 100644 --- a/drivers/usb/storage/uas-detect.h +++ b/drivers/usb/storage/uas-detect.h @@ -78,6 +78,8 @@ static int uas_use_uas_driver(struct usb_interface *intf, * ASM1051 - with broken (*) uas support * ASM1053 - with working uas support, but problems with large xfers * ASM1153 - with working uas support + * ASMT135x - broken uas support, shares the ASM1153 MaxPower == 0 + * signature, identify it by its product string * * Devices with these chips re-use a number of device-ids over the * entire line, so the device-id is useless to determine if we're @@ -99,7 +101,11 @@ static int uas_use_uas_driver(struct usb_interface *intf, (le16_to_cpu(udev->descriptor.idProduct) == 0x5106 || le16_to_cpu(udev->descriptor.idProduct) == 0x55aa)) { if (udev->actconfig->desc.bMaxPower == 0) { - /* ASM1153, do nothing */ + if (udev->product && strstr(udev->product, "ASMT135")) { + /* ASMT135x, broken uas */ + flags |= US_FL_IGNORE_UAS; + } + /* else ASM1153, do nothing */ } else if (udev->speed < USB_SPEED_SUPER) { /* No streams info, assume ASM1051 */ flags |= US_FL_IGNORE_UAS; diff --git a/drivers/usb/storage/unusual_devs.h b/drivers/usb/storage/unusual_devs.h index ac22fa31873439..492b5f050f0b2f 100644 --- a/drivers/usb/storage/unusual_devs.h +++ b/drivers/usb/storage/unusual_devs.h @@ -1168,6 +1168,25 @@ UNUSUAL_DEV( 0x07cf, 0x1167, 0x0100, 0x0100, "EX-N1 DigitalCamera", USB_SC_8070, USB_PR_DEVICE, NULL, 0), +/* + * CASIO calculators using UMS for "USB Key" mode always + * reports non-zero residue when the transfer length is larger + * than 4096 bytes. + * + * Reported by Thomas Touhey + * and augmented by 0v0katai <0v0katai@gmail.com> + */ +UNUSUAL_DEV( 0x07cf, 0x6102, 0x0100, 0x0100, + "Casio", + "fx-CP400", + USB_SC_DEVICE, USB_PR_DEVICE, NULL, + US_FL_IGNORE_RESIDUE ), +UNUSUAL_DEV( 0x07cf, 0x6103, 0x0100, 0x0100, + "Casio", + "fx-CG50", + USB_SC_DEVICE, USB_PR_DEVICE, NULL, + US_FL_IGNORE_RESIDUE ), + /* Submitted by Hartmut Wahl */ UNUSUAL_DEV( 0x0839, 0x000a, 0x0001, 0x0001, "Samsung", diff --git a/drivers/usb/storage/unusual_ene_ub6250.h b/drivers/usb/storage/unusual_ene_ub6250.h index a3b32abc2b2fff..bc9d7ea4e398ba 100644 --- a/drivers/usb/storage/unusual_ene_ub6250.h +++ b/drivers/usb/storage/unusual_ene_ub6250.h @@ -5,6 +5,6 @@ UNUSUAL_DEV(0x0cf2, 0x6250, 0x0000, 0x9999, "ENE", "ENE UB6250 reader", - USB_SC_DEVICE, USB_PR_DEVICE, NULL, 0), + USB_SC_DEVICE, USB_PR_DEVICE, ene_ub6250_init, 0), #endif /* defined(CONFIG_USB_STORAGE_ENE_UB6250) || ... */ diff --git a/drivers/usb/typec/anx7411.c b/drivers/usb/typec/anx7411.c index 6f9c15ee0d8699..c4730b96e696e8 100644 --- a/drivers/usb/typec/anx7411.c +++ b/drivers/usb/typec/anx7411.c @@ -552,7 +552,7 @@ static int anx7411_typec_register_altmode(struct anx7411_data *ctx, int svid, int vdo) { struct device *dev = &ctx->spi_client->dev; - struct typec_altmode_desc desc; + struct typec_altmode_desc desc = {}; int err; int i; diff --git a/drivers/usb/typec/class.c b/drivers/usb/typec/class.c index 54c7810b563beb..9d9703c708209e 100644 --- a/drivers/usb/typec/class.c +++ b/drivers/usb/typec/class.c @@ -2684,7 +2684,7 @@ void typec_port_register_altmodes(struct typec_port *port, struct typec_altmode **altmodes, size_t n) { struct fwnode_handle *child; - struct typec_altmode_desc desc; + struct typec_altmode_desc desc = {}; struct typec_altmode *alt; size_t index = 0; u16 svid; diff --git a/drivers/usb/typec/mux.c b/drivers/usb/typec/mux.c index afa6fc18139781..57149f53769298 100644 --- a/drivers/usb/typec/mux.c +++ b/drivers/usb/typec/mux.c @@ -81,7 +81,7 @@ static void *typec_switch_match(const struct fwnode_handle *fwnode, */ struct typec_switch *fwnode_typec_switch_get(struct fwnode_handle *fwnode) { - struct typec_switch_dev *sw_devs[TYPEC_MUX_MAX_DEVS]; + struct typec_switch_dev *sw_devs[TYPEC_MUX_MAX_DEVS] = { }; struct typec_switch *sw; int count; int err; diff --git a/drivers/usb/typec/mux/fsa4480.c b/drivers/usb/typec/mux/fsa4480.c index 88783f9ed44cad..c3c629212574f2 100644 --- a/drivers/usb/typec/mux/fsa4480.c +++ b/drivers/usb/typec/mux/fsa4480.c @@ -93,16 +93,9 @@ static int fsa4480_set(struct fsa4480 *fsa) sel = FSA4480_SEL_USB; } else if (fsa->svid) { switch (fsa->mode) { - /* DP Only */ case TYPEC_DP_STATE_C: - case TYPEC_DP_STATE_E: - enable |= FSA4480_ENABLE_SBU; - if (reverse) - sel = FSA4480_SEL_SBU_REVERSE; - break; - - /* DP + USB */ case TYPEC_DP_STATE_D: + case TYPEC_DP_STATE_E: case TYPEC_DP_STATE_F: enable |= FSA4480_ENABLE_USB | FSA4480_ENABLE_SBU; sel = FSA4480_SEL_USB; diff --git a/drivers/usb/typec/mux/nb7vpq904m.c b/drivers/usb/typec/mux/nb7vpq904m.c index 00b2a1784e6cc8..d1856a3fd60cc7 100644 --- a/drivers/usb/typec/mux/nb7vpq904m.c +++ b/drivers/usb/typec/mux/nb7vpq904m.c @@ -396,6 +396,7 @@ static int nb7vpq904m_probe(struct i2c_client *client) return -ENOMEM; nb7->client = client; + i2c_set_clientdata(client, nb7); nb7->regmap = devm_regmap_init_i2c(client, &nb7_regmap); if (IS_ERR(nb7->regmap)) { diff --git a/drivers/usb/typec/mux/tusb1046.c b/drivers/usb/typec/mux/tusb1046.c index 55a7b246f3f999..1e071e9193d82b 100644 --- a/drivers/usb/typec/mux/tusb1046.c +++ b/drivers/usb/typec/mux/tusb1046.c @@ -43,11 +43,17 @@ static int tusb1046_mux_set(struct typec_mux_dev *mux, struct tusb1046_priv *priv = typec_mux_get_drvdata(mux); struct i2c_client *client = priv->client; struct device *dev = &client->dev; + unsigned long req = state->mode; int mode, val, ret = 0; - if (state->mode >= TYPEC_STATE_MODAL && - state->alt->svid != USB_TYPEC_DP_SID) - return -EINVAL; + if (req >= TYPEC_STATE_MODAL) { + /* USB and accessory modes: not the DP pin assignments */ + if (!state->alt) + req = req == TYPEC_MODE_USB3 ? TYPEC_STATE_USB : + TYPEC_STATE_SAFE; + else if (state->alt->svid != USB_TYPEC_DP_SID) + return -EINVAL; + } dev_dbg(dev, "mux mode requested: %lu\n", state->mode); @@ -60,7 +66,7 @@ static int tusb1046_mux_set(struct typec_mux_dev *mux, goto out_unlock; } - switch (state->mode) { + switch (req) { case TYPEC_STATE_USB: mode = TUSB1046_CTLSEL_USB3; break; diff --git a/drivers/usb/typec/tcpm/tcpm.c b/drivers/usb/typec/tcpm/tcpm.c index bb90211660cae3..bf7fd632d815ee 100644 --- a/drivers/usb/typec/tcpm/tcpm.c +++ b/drivers/usb/typec/tcpm/tcpm.c @@ -542,6 +542,7 @@ struct tcpm_port { struct kthread_work enable_frs; struct hrtimer vdm_discovery_timer; struct kthread_work vdm_discovery_work; + bool vdm_discovery_armed; bool state_machine_running; /* Set to true when VDM State Machine has following actions. */ bool vdm_sm_running; @@ -1768,15 +1769,20 @@ static void mod_enable_frs_delayed_work(struct tcpm_port *port, unsigned int del } } +/* + * Called with port->lock held, which the work takes, and not only from the + * worker: the work cannot be waited for. It does nothing unless it is armed. + */ static void mod_vdm_discovery_cancel_delayed_work(struct tcpm_port *port) { hrtimer_cancel(&port->vdm_discovery_timer); - if (port->wq) - kthread_cancel_work_sync(&port->vdm_discovery_work); + port->vdm_discovery_armed = false; } static void mod_vdm_discovery_delayed_work(struct tcpm_port *port, unsigned int delay_ms) { + port->vdm_discovery_armed = true; + if (delay_ms) { hrtimer_start(&port->vdm_discovery_timer, ms_to_ktime(delay_ms), HRTIMER_MODE_REL); } else { @@ -7295,6 +7301,10 @@ static void tcpm_vdm_discovery_work(struct kthread_work *work) mutex_lock(&port->lock); + if (!port->vdm_discovery_armed) + goto unlock; + port->vdm_discovery_armed = false; + tcpm_log_force(port, "%s state [%s]", __func__, vdm_discovery_state_strings[port->vdm_discovery_state]); diff --git a/drivers/usb/typec/ucsi/debugfs.c b/drivers/usb/typec/ucsi/debugfs.c index 77a0dd75edd3c3..3cffd3778c67e4 100644 --- a/drivers/usb/typec/ucsi/debugfs.c +++ b/drivers/usb/typec/ucsi/debugfs.c @@ -60,7 +60,8 @@ static int ucsi_cmd(void *data, u64 val) case UCSI_GET_LPM_PPM_INFO: ret = ucsi_send_command(ucsi, val, &ucsi->debugfs->response, - sizeof(ucsi->debugfs->response)); + min(sizeof(ucsi->debugfs->response), + UCSI_MAX_DATA_LENGTH(ucsi))); break; default: ret = -EOPNOTSUPP; diff --git a/drivers/usb/typec/ucsi/ucsi.c b/drivers/usb/typec/ucsi/ucsi.c index 5aab8ab9f0132d..9e453d216c169b 100644 --- a/drivers/usb/typec/ucsi/ucsi.c +++ b/drivers/usb/typec/ucsi/ucsi.c @@ -2106,7 +2106,7 @@ static int ucsi_init(struct ucsi *ucsi) goto err_reset; if (!ucsi->cap.num_connectors) { - ret = -ENODEV; + ret = -EAGAIN; goto err_reset; } /* Check if reserved bit set. This is out of spec but happens in buggy FW */ @@ -2134,6 +2134,14 @@ static int ucsi_init(struct ucsi *ucsi) goto err_unregister; } + /* + * Set ucsi->connector before enabling notifications. A connector + * change event can be handled as soon as the notifications are + * enabled below, and ucsi_connector_change() indexes into + * ucsi->connector, so it must not be NULL at that point. + */ + ucsi->connector = connector; + /* Enable all supported notifications */ ntfy = ucsi_get_supported_notifications(ucsi); command = UCSI_SET_NOTIFICATION_ENABLE | ntfy; @@ -2141,7 +2149,6 @@ static int ucsi_init(struct ucsi *ucsi) if (ret < 0) goto err_unregister; - ucsi->connector = connector; ucsi->ntfy = ntfy; mutex_lock(&ucsi->ppm_lock); @@ -2155,6 +2162,7 @@ static int ucsi_init(struct ucsi *ucsi) return 0; err_unregister: + ucsi->connector = NULL; for (con = connector; con->port; con++) ucsi_unregister_port(con); for (i = 0; i < ucsi->cap.num_connectors; i++) @@ -2164,6 +2172,16 @@ static int ucsi_init(struct ucsi *ucsi) err_reset: memset(&ucsi->cap, 0, sizeof(ucsi->cap)); ucsi_reset_ppm(ucsi); + + /* + * The only -EINVAL expected on this path is ucsi_read_error()'s: + * the PPM rejected a standard command. Some PPMs do that, or + * report zero connectors above, for a short while after boot + * before they are ready. Report both as -EAGAIN so that + * ucsi_init_work() can retry them, and only them. + */ + if (ret == -EINVAL) + ret = -EAGAIN; err: return ret; } @@ -2241,16 +2259,23 @@ static void ucsi_init_work(struct work_struct *work) } /* - * On some platforms the PPM is not ready to answer commands - * correctly for a short window during boot: standard commands are - * rejected or GET_CAPABILITY reports zero connectors, seen as - * -EINVAL or -ENODEV from ucsi_init(), and a retry moments later - * succeeds (observed on Lenovo ThinkPad X1 Carbon Gen 14, where - * this affects roughly half of all boots). Retry those like the - * USB role switch wait instead of giving up on the first attempt. + * -EPROBE_DEFER: the USB role switch is not registered yet. Wait + * up to ten seconds for it. + * + * -EAGAIN: the PPM is not ready to answer commands correctly yet. + * On some platforms that lasts for a short window during boot + * (observed on Lenovo ThinkPad X1 Carbon Gen 14, where it affects + * roughly half of all boots and a retry moments later succeeds). + * One second is plenty for that. + * + * Anything else is not going to change with a retry, so report it + * once and stop. */ - if (ret == -EPROBE_DEFER || ret == -ENODEV || ret == -EINVAL) { - if (ucsi->work_count++ < UCSI_ROLE_SWITCH_WAIT_COUNT) { + if (ret == -EPROBE_DEFER || ret == -EAGAIN) { + int limit = ret == -EPROBE_DEFER ? UCSI_ROLE_SWITCH_WAIT_COUNT : + UCSI_PPM_READY_WAIT_COUNT; + + if (ucsi->work_count++ < limit) { dev_dbg(ucsi->dev, "PPM init failed (%pe), retrying\n", ERR_PTR(ret)); queue_delayed_work(system_dfl_long_wq, &ucsi->work, diff --git a/drivers/usb/typec/ucsi/ucsi.h b/drivers/usb/typec/ucsi/ucsi.h index 1996f04ed5e68d..140d34e90c7c4c 100644 --- a/drivers/usb/typec/ucsi/ucsi.h +++ b/drivers/usb/typec/ucsi/ucsi.h @@ -491,6 +491,7 @@ struct ucsi { #define UCSI_ROLE_SWITCH_RETRY_PER_HZ 10 #define UCSI_ROLE_SWITCH_INTERVAL (HZ / UCSI_ROLE_SWITCH_RETRY_PER_HZ) #define UCSI_ROLE_SWITCH_WAIT_COUNT (10 * UCSI_ROLE_SWITCH_RETRY_PER_HZ) +#define UCSI_PPM_READY_WAIT_COUNT (1 * UCSI_ROLE_SWITCH_RETRY_PER_HZ) /* PPM Communication lock */ struct mutex ppm_lock; diff --git a/drivers/usb/typec/ucsi/ucsi_acpi.c b/drivers/usb/typec/ucsi/ucsi_acpi.c index 2d079d7177ac54..9c14f93a93408e 100644 --- a/drivers/usb/typec/ucsi/ucsi_acpi.c +++ b/drivers/usb/typec/ucsi/ucsi_acpi.c @@ -148,6 +148,34 @@ static const struct ucsi_operations ucsi_acer_ops = { .async_control = ucsi_acpi_async_control }; +static int ucsi_hp_read_version(struct ucsi *ucsi, u16 *version) +{ + struct ucsi_acpi *ua = ucsi_get_drvdata(ucsi); + int ret; + + ret = ucsi_acpi_read_version(ucsi, version); + if (ret) + return ret; + + /* Firmware fills in VERSION (1.0) only after the first command completes */ + if (!*version) { + dev_warn(ua->dev, "UCSI version is zero, assuming 1.0\n"); + *version = UCSI_VERSION_1_0; + } + + return 0; +} + +static const struct ucsi_operations ucsi_hp_ops = { + .read_version = ucsi_hp_read_version, + .read_cci = ucsi_acpi_read_cci, + .poll_cci = ucsi_acpi_poll_cci, + .read_message_in = ucsi_acpi_read_message_in, + .write_message_out = ucsi_acpi_write_message_out, + .sync_control = ucsi_sync_control_common, + .async_control = ucsi_acpi_async_control +}; + static int ucsi_gram_sync_control(struct ucsi *ucsi, u64 command, u32 *cci, void *val, size_t len, void *msg_out, size_t msg_out_size) @@ -188,6 +216,39 @@ static const struct ucsi_operations ucsi_gram_ops = { .async_control = ucsi_acpi_async_control }; +static int ucsi_dell_sync_control(struct ucsi *ucsi, u64 command, u32 *cci, + void *val, size_t len, void *msg_out, + size_t msg_out_size) +{ + int ret; + + ret = ucsi_sync_control_common(ucsi, command, cci, val, len, + msg_out, msg_out_size); + if (ret < 0) + return ret; + + if (UCSI_COMMAND(command) == UCSI_GET_CAPABILITY && val) { + struct ucsi_capability *cap = val; + + if (cap->features & UCSI_CAP_ALT_MODE_DETAILS) { + dev_warn(ucsi->dev, + "Firmware bug: broken altmode details reporting, disabling\n"); + cap->features &= ~UCSI_CAP_ALT_MODE_DETAILS; + } + } + + return ret; +} + +static const struct ucsi_operations ucsi_dell_ops = { + .read_version = ucsi_acpi_read_version, + .read_cci = ucsi_acpi_read_cci, + .poll_cci = ucsi_acpi_poll_cci, + .read_message_in = ucsi_acpi_read_message_in, + .sync_control = ucsi_dell_sync_control, + .async_control = ucsi_acpi_async_control +}; + static const struct dmi_system_id ucsi_acpi_quirks[] = { { .matches = { @@ -196,6 +257,13 @@ static const struct dmi_system_id ucsi_acpi_quirks[] = { }, .driver_data = (void *)&ucsi_acer_ops, }, + { + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "HP"), + DMI_MATCH(DMI_BOARD_NAME, "8ED9"), + }, + .driver_data = (void *)&ucsi_hp_ops, + }, { .matches = { DMI_MATCH(DMI_SYS_VENDOR, "LG Electronics"), @@ -204,6 +272,14 @@ static const struct dmi_system_id ucsi_acpi_quirks[] = { }, .driver_data = (void *)&ucsi_gram_ops, }, + { + .ident = "Dell XPS", + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."), + DMI_MATCH(DMI_PRODUCT_NAME, "XPS"), + }, + .driver_data = (void *)&ucsi_dell_ops, + }, { } }; diff --git a/drivers/usb/usbip/vhci_rx.c b/drivers/usb/usbip/vhci_rx.c index a678e7c8983752..741107a9646603 100644 --- a/drivers/usb/usbip/vhci_rx.c +++ b/drivers/usb/usbip/vhci_rx.c @@ -79,6 +79,7 @@ static void vhci_recv_ret_submit(struct vhci_device *vdev, /* recv transfer buffer */ if (usbip_recv_xbuff(ud, urb) < 0) { urb->status = -EPROTO; + urb->actual_length = 0; goto error; } diff --git a/drivers/usb/usbip/vudc_tx.c b/drivers/usb/usbip/vudc_tx.c index 88edfbcc00350e..d78ff29e9654ba 100644 --- a/drivers/usb/usbip/vudc_tx.c +++ b/drivers/usb/usbip/vudc_tx.c @@ -59,13 +59,13 @@ static int v_send_ret_unlink(struct vudc *udc, struct v_unlink *unlink) ret = kernel_sendmsg(udc->ud.tcp_socket, &msg, iov, 1, txsize); + kfree(unlink); if (ret != txsize) { usbip_event_add(&udc->ud, VUDC_EVENT_ERROR_TCP); if (ret >= 0) return -EPIPE; return ret; } - kfree(unlink); return txsize; } diff --git a/drivers/vhost/net.c b/drivers/vhost/net.c index 4570a4ffbab2c5..10ed2d55ff0723 100644 --- a/drivers/vhost/net.c +++ b/drivers/vhost/net.c @@ -538,7 +538,7 @@ static int sock_has_rx_data(struct socket *sock) if (sock->ops->peek_len) return sock->ops->peek_len(sock); - return skb_queue_empty(&sock->sk->sk_receive_queue); + return !skb_queue_empty(&sock->sk->sk_receive_queue); } static void vhost_net_busy_poll_try_queue(struct vhost_net *net, diff --git a/drivers/vhost/vhost.c b/drivers/vhost/vhost.c index e29f154706da03..dc973287567c8b 100644 --- a/drivers/vhost/vhost.c +++ b/drivers/vhost/vhost.c @@ -3152,18 +3152,21 @@ static int vhost_add_used_n_ooo(struct vhost_virtqueue *vq, struct vring_used_elem *heads, unsigned count) { - int start, n, r; + unsigned int n; + int r; - start = vq->last_used_idx & (vq->num - 1); - n = vq->num - start; - if (n < count) { + do { + unsigned int start = vq->last_used_idx & (vq->num - 1); + + n = min(vq->num - start, count); r = __vhost_add_used_n(vq, heads, n); if (r < 0) return r; heads += n; count -= n; - } - return __vhost_add_used_n(vq, heads, count); + } while (count); + + return 0; } static int vhost_add_used_n_in_order(struct vhost_virtqueue *vq, diff --git a/drivers/video/console/vgacon.c b/drivers/video/console/vgacon.c index e7e6750f1f8737..09f7c376b46890 100644 --- a/drivers/video/console/vgacon.c +++ b/drivers/video/console/vgacon.c @@ -324,6 +324,8 @@ static const char *vgacon_startup(void) } vga_vram_base = VGA_MAP_MEM(vga_vram_base, vga_vram_size); + if (!vga_vram_base) + goto no_vga; vga_vram_end = vga_vram_base + vga_vram_size; /* diff --git a/drivers/video/fbdev/atafb.c b/drivers/video/fbdev/atafb.c index c32576cb172029..5d9265caa9abfb 100644 --- a/drivers/video/fbdev/atafb.c +++ b/drivers/video/fbdev/atafb.c @@ -2065,6 +2065,15 @@ static void st_ovsc_switch(void) #ifdef ATAFB_EXT +/* + * Only a Falcon can have a SuperVidel; a TT with a VME graphics card can + * have its framebuffer in the same address range. + */ +static bool ext_is_supervidel(void) +{ + return ATARIHW_PRESENT(VIDEL_SHIFTER) && external_addr >= 0xa0000000; +} + static int ext_encode_fix(struct fb_fix_screeninfo *fix, struct atafb_par *par) { strcpy(fix->id, "Unknown Extern"); @@ -2083,8 +2092,7 @@ static int ext_encode_fix(struct fb_fix_screeninfo *fix, struct atafb_par *par) * SuperVidel 8bpp chunky (fb in SV RAM) uses the Falcon palette */ int visual = (external_vgaiobase || - (external_depth == 8 && - external_addr >= 0xa0000000)) ? + (external_depth == 8 && ext_is_supervidel())) ? FB_VISUAL_PSEUDOCOLOR : FB_VISUAL_STATIC_PSEUDOCOLOR; switch (external_pmode) { @@ -2181,7 +2189,7 @@ static int ext_encode_var(struct fb_var_screeninfo *var, struct atafb_par *par) var->transp.offset = 24; var->transp.length = 8; } else if (external_pmode == FB_TYPE_PACKED_PIXELS && - external_depth == 8 && external_addr >= 0xa0000000) { + external_depth == 8 && ext_is_supervidel()) { /* SuperVidel 8bpp chunky: palette has 8 bits per channel. * Without this, fb_get_color_depth() sees length 0 and * fbcon falls back to its 2-color palette — the console @@ -2245,7 +2253,7 @@ static int ext_setcolreg(unsigned int regno, unsigned int red, return 0; } if (external_pmode == FB_TYPE_PACKED_PIXELS && external_depth == 8 && - external_addr >= 0xa0000000) { + ext_is_supervidel()) { /* SuperVidel native 8bpp chunky scans out via the Falcon * palette registers, honoring all 8 bits per channel */ @@ -3336,7 +3344,7 @@ static int __init atafb_probe(struct platform_device *pdev) memset (screen_base, 0, external_len); /* framebuffer in SV RAM: enable the SuperBlitter */ - if (external_addr >= 0xa0000000 && + if (ext_is_supervidel() && ((external_pmode == FB_TYPE_PACKED_PIXELS && external_depth == 8) || (external_pmode == -1 && diff --git a/drivers/video/fbdev/aty/radeon_base.c b/drivers/video/fbdev/aty/radeon_base.c index 387bc5f9676517..45dd42134e813a 100644 --- a/drivers/video/fbdev/aty/radeon_base.c +++ b/drivers/video/fbdev/aty/radeon_base.c @@ -836,6 +836,9 @@ static int radeonfb_check_var (struct fb_var_screeninfo *var, struct fb_info *in int nom, den; unsigned int pitch; + if (!var->pixclock) + return -EINVAL; + if (radeon_match_mode(rinfo, &v, var)) return -EINVAL; diff --git a/drivers/video/fbdev/cobalt_lcdfb.c b/drivers/video/fbdev/cobalt_lcdfb.c index f7faa95fefd3ca..e90f45c91725b6 100644 --- a/drivers/video/fbdev/cobalt_lcdfb.c +++ b/drivers/video/fbdev/cobalt_lcdfb.c @@ -297,8 +297,9 @@ static int cobalt_lcdfb_probe(struct platform_device *dev) info->screen_base = devm_platform_get_and_ioremap_resource(dev, 0, &res); if (IS_ERR(info->screen_base)) { + retval = PTR_ERR(info->screen_base); framebuffer_release(info); - return PTR_ERR(info->screen_base); + return retval; } info->screen_size = resource_size(res); diff --git a/drivers/video/fbdev/core/fbcon.c b/drivers/video/fbdev/core/fbcon.c index 7720dfc80c165c..d7890e119dc7d0 100644 --- a/drivers/video/fbdev/core/fbcon.c +++ b/drivers/video/fbdev/core/fbcon.c @@ -410,7 +410,8 @@ static void fb_flashcursor(struct work_struct *work) if (par->currcon != -1) vc = vc_cons[par->currcon].d; - if (!vc || !con_is_visible(vc) || + if (!par->cursor_blink_on || + !vc || !con_is_visible(vc) || fbcon_info_from_console(vc->vc_num) != info || vc->vc_deccm != 1) { console_unlock(); @@ -422,25 +423,53 @@ static void fb_flashcursor(struct work_struct *work) par->bitops->cursor(vc, info, enable, get_fg_color(vc, info, c), get_bg_color(vc, info, c)); - console_unlock(); + /* + * Re-arm under console_lock so that a concurrent + * fbcon_del_cursor_work() cannot race with this requeue. + */ queue_delayed_work(system_power_efficient_wq, &par->cursor_work, par->cur_blink_jiffies); + console_unlock(); } static void fbcon_add_cursor_work(struct fb_info *info) { struct fbcon_par *par = info->fbcon_par; - if (fbcon_cursor_blink) - queue_delayed_work(system_power_efficient_wq, &par->cursor_work, - par->cur_blink_jiffies); + if (!fbcon_cursor_blink) + return; + + par->cursor_blink_on = true; + queue_delayed_work(system_power_efficient_wq, &par->cursor_work, + par->cur_blink_jiffies); } +/* + * Stop the cursor blink. + * + * Does not wait for a callback that is already running, so it is safe to + * call from any context. + * + * console_lock serializes this with the requeue in fb_flashcursor(); + * otherwise a running callback could re-arm the work. + */ static void fbcon_del_cursor_work(struct fb_info *info) { struct fbcon_par *par = info->fbcon_par; + par->cursor_blink_on = false; + cancel_delayed_work(&par->cursor_work); +} + +/* + * Stop the cursor blink and wait for a running callback to finish before + * @par is freed. May sleep, only for teardown paths. + */ +static void fbcon_del_cursor_work_sync(struct fb_info *info) +{ + struct fbcon_par *par = info->fbcon_par; + cancel_delayed_work_sync(&par->cursor_work); } @@ -765,7 +794,7 @@ static void fbcon_release(struct fb_info *info) if (info->fbcon_par) { struct fbcon_par *par = info->fbcon_par; - fbcon_del_cursor_work(info); + fbcon_del_cursor_work_sync(info); kfree(par->cursor_state.mask); kfree(par->cursor_data); kfree(par->cursor_src); diff --git a/drivers/video/fbdev/core/fbcon.h b/drivers/video/fbdev/core/fbcon.h index d93a89877d0433..6a2f7f6e5a8c32 100644 --- a/drivers/video/fbdev/core/fbcon.h +++ b/drivers/video/fbdev/core/fbcon.h @@ -97,6 +97,7 @@ struct fbcon_par { int blank_state; int graphics; bool initialized; + bool cursor_blink_on; int rotate; char *cursor_data; #ifdef CONFIG_FRAMEBUFFER_CONSOLE_ROTATION diff --git a/drivers/video/fbdev/fm2fb.c b/drivers/video/fbdev/fm2fb.c index 25d2e716edf2d4..ed4457df7707a9 100644 --- a/drivers/video/fbdev/fm2fb.c +++ b/drivers/video/fbdev/fm2fb.c @@ -257,7 +257,7 @@ static int fm2fb_probe(struct zorro_dev *z, const struct zorro_device_id *id) strcpy(fb_fix.id, is_fm ? "FrameMaster II" : "Rainbow II"); /* make EBU color bars on display */ - ptr = (unsigned long *)fb_fix.smem_start; + ptr = (unsigned long *)info->screen_base; for (y = 0; y < 576; y++) { for (x = 0; x < 96; x++) *ptr++ = 0xffffff;/* white */ for (x = 0; x < 96; x++) *ptr++ = 0xffff00;/* yellow */ diff --git a/drivers/video/fbdev/macmodes.c b/drivers/video/fbdev/macmodes.c index b16a9d9bef982f..7ea40fd34a10a5 100644 --- a/drivers/video/fbdev/macmodes.c +++ b/drivers/video/fbdev/macmodes.c @@ -342,7 +342,7 @@ int mac_var_to_vmode(const struct fb_var_screeninfo *var, int *vmode, if (mode->xres != clk_mode->xres || mode->yres != clk_mode->yres) break; - if (var->pixclock > mode->pixclock) + if (var->pixclock > clk_mode->pixclock) break; if (mode->vmode != clk_mode->vmode) continue; diff --git a/drivers/video/fbdev/smscufx.c b/drivers/video/fbdev/smscufx.c index 34d8abd5b35447..ad3288b0d4df79 100644 --- a/drivers/video/fbdev/smscufx.c +++ b/drivers/video/fbdev/smscufx.c @@ -661,8 +661,12 @@ static int ufx_set_vid_mode(struct ufx_data *dev, struct fb_var_screeninfo *var) u32 temp; u16 h_total, h_active, h_blank_start, h_blank_end, h_sync_start, h_sync_end; u16 v_total, v_active, v_blank_start, v_blank_end, v_sync_start, v_sync_end; + int status; + + if (!atomic_read(&dev->usb_active)) + return -ENODEV; - int status = ufx_reg_write(dev, 0x8028, 0); + status = ufx_reg_write(dev, 0x8028, 0); check_warn_return(status, "ufx_set_vid_mode error disabling RGB pad"); status = ufx_reg_write(dev, 0x8024, 0); @@ -1067,6 +1071,7 @@ static void ufx_free(struct kref *kref) { struct ufx_data *dev = container_of(kref, struct ufx_data, kref); + usb_put_dev(dev->udev); kfree(dev); } @@ -1280,9 +1285,10 @@ static int ufx_realloc_framebuffer(struct ufx_data *dev, struct fb_info *info) if (PAGE_ALIGN(new_len) > old_len) { /* - * Alloc system memory for virtual framebuffer + * Alloc system memory for virtual framebuffer. smem_len is + * rounded up to a page, so allocate that much as well. */ - new_fb = vmalloc(new_len); + new_fb = vmalloc(PAGE_ALIGN(new_len)); if (!new_fb) return -ENOMEM; @@ -1609,6 +1615,8 @@ static int ufx_usb_probe(struct usb_interface *interface, dev->udev = usbdev; dev->gdev = &usbdev->dev; /* our generic struct device * */ + /* keep the device alive until the last ufx_data user is gone */ + usb_get_dev(usbdev); usb_set_intfdata(interface, dev); dev_dbg(dev->gdev, "%s %s - serial #%s\n", @@ -1700,8 +1708,16 @@ static int ufx_usb_probe(struct usb_interface *interface, dev_dbg(dev->gdev, "registering framebuffer"); retval = register_framebuffer(info); if (retval < 0) { - dev_err(dev->gdev, "error %d register_framebuffer", retval); - goto reset_active; + /* + * info is installed before the takeover can fail; freeing @dev + * here would leave registered_fb[] and /dev/fbN pointing at + * freed memory. + */ + if (!refcount_read(&info->count)) { /* not registered */ + dev_err(dev->gdev, "error %d register_framebuffer", retval); + goto reset_active; + } + dev_warn(dev->gdev, "console takeover failed: %d\n", retval); } dev_info(dev->gdev, "SMSC UDX USB device /dev/fb%d attached. %dx%d resolution." diff --git a/drivers/video/fbdev/sstfb.c b/drivers/video/fbdev/sstfb.c index 8e2c2421028df7..de0769eb4a2fa7 100644 --- a/drivers/video/fbdev/sstfb.c +++ b/drivers/video/fbdev/sstfb.c @@ -359,6 +359,9 @@ static int sstfb_check_var(struct fb_var_screeninfo *var, int tiles_in_X, real_length; unsigned int freq; + if (!var->pixclock) + return -EINVAL; + if (sst_calc_pll(PICOS2KHZ(var->pixclock), &freq, &par->pll)) { printk(KERN_ERR "sstfb: Pixclock at %ld KHZ out of range\n", PICOS2KHZ(var->pixclock)); diff --git a/drivers/video/fbdev/valkyriefb.c b/drivers/video/fbdev/valkyriefb.c index ec3cf45890567f..e067c89c91bfce 100644 --- a/drivers/video/fbdev/valkyriefb.c +++ b/drivers/video/fbdev/valkyriefb.c @@ -510,7 +510,7 @@ static void valkyrie_init_fix(struct fb_fix_screeninfo *fix, struct fb_info_valk fix->mmio_len = sizeof(struct valkyrie_regs); fix->type = FB_TYPE_PACKED_PIXELS; fix->smem_start = p->frame_buffer_phys + 0x1000; - fix->smem_len = p->total_vram; + fix->smem_len = p->total_vram - 0x1000; fix->type_aux = 0; fix->ywrapstep = 0; @@ -523,7 +523,6 @@ static void valkyrie_init_fix(struct fb_fix_screeninfo *fix, struct fb_info_valk static void valkyrie_par_to_fix(struct fb_par_valkyrie *par, struct fb_fix_screeninfo *fix) { - fix->smem_len = valkyrie_vram_reqd(par->vmode, par->cmode); fix->visual = (par->cmode == CMODE_8) ? FB_VISUAL_PSEUDOCOLOR : FB_VISUAL_DIRECTCOLOR; fix->line_length = par->vxres << par->cmode; diff --git a/drivers/video/fbdev/vfb.c b/drivers/video/fbdev/vfb.c index de137b2bdaedc6..721c70962503f8 100644 --- a/drivers/video/fbdev/vfb.c +++ b/drivers/video/fbdev/vfb.c @@ -30,7 +30,10 @@ * The default can be overridden if the driver is compiled as a module */ -#define VIDEOMEMSIZE (1*1024*1024) /* 1 MB */ +#define MAX_XRES 8192 +#define MAX_YRES 8192 +#define VIDEOMEMSIZE (1 * 1024 * 1024) /* 1 MB */ +#define MAX_VIDEOMEMSIZE (8192 * 8192 * sizeof(u32)) static void *videomemory; static u_long videomemorysize = VIDEOMEMSIZE; @@ -159,6 +162,14 @@ static int vfb_check_var(struct fb_var_screeninfo *var, else return -EINVAL; + if (var->xres_virtual > MAX_XRES || + var->yres_virtual > MAX_YRES) + return -EINVAL; + + if (var->xoffset > MAX_XRES - var->xres || + var->yoffset > MAX_YRES - var->yres) + return -EINVAL; + if (var->xres_virtual < var->xoffset + var->xres) var->xres_virtual = var->xoffset + var->xres; if (var->yres_virtual < var->yoffset + var->yres) @@ -434,9 +445,12 @@ static int __init vfb_setup(char *options) static int vfb_probe(struct platform_device *dev) { struct fb_info *info; - unsigned int size = PAGE_ALIGN(videomemorysize); + unsigned int size; int retval = -ENOMEM; + videomemorysize = min(videomemorysize, MAX_VIDEOMEMSIZE); + size = PAGE_ALIGN(videomemorysize); + /* * For real video cards we use ioremap. */ diff --git a/drivers/w1/masters/ds2482.c b/drivers/w1/masters/ds2482.c index eee9df238f6a4c..700c11aecbad41 100644 --- a/drivers/w1/masters/ds2482.c +++ b/drivers/w1/masters/ds2482.c @@ -103,6 +103,7 @@ struct ds2482_data; struct ds2482_w1_chan { struct ds2482_data *pdev; u8 channel; + bool spu; /* strong pullup after the next byte */ struct w1_bus_master w1_bm; }; @@ -336,6 +337,19 @@ static void ds2482_w1_write_byte(void *data, u8 byte) if (pdev->w1_count > 1) ds2482_set_channel(pdev, pchan->channel); + if (pchan->spu) { + pchan->spu = false; + /* the wait above and this one are crucial, otherwise devices + * might not be powered long enough, causing e.g. a w1_therm + * sensor to provide wrong conversion results + */ + /* note: it seems like both SPU and APU have to be set! */ + ds2482_send_cmd_data(pdev, DS2482_CMD_WRITE_CONFIG, + ds2482_calculate_config(DS2482_REG_CFG_SPU | + DS2482_REG_CFG_APU)); + ds2482_wait_1wire_idle(pdev); + } + /* Send the write byte command */ ds2482_send_cmd_data(pdev, DS2482_CMD_1WIRE_WRITE_BYTE, byte); @@ -420,27 +434,19 @@ static u8 ds2482_w1_reset_bus(void *data) static u8 ds2482_w1_set_pullup(void *data, int delay) { struct ds2482_w1_chan *pchan = data; - struct ds2482_data *pdev = pchan->pdev; - u8 retval = 1; /* if delay is non-zero activate the pullup, * the strong pullup will be automatically deactivated * by the master, so do not explicitly deactive it + * + * The setting is used up by the next byte on any channel of the chip: + * ds2482_w1_write_byte() makes it, in one go with the byte. */ - if (delay) { - /* both waits are crucial, otherwise devices might not be - * powered long enough, causing e.g. a w1_therm sensor to - * provide wrong conversion results - */ - ds2482_wait_1wire_idle(pdev); - /* note: it seems like both SPU and APU have to be set! */ - retval = ds2482_send_cmd_data(pdev, DS2482_CMD_WRITE_CONFIG, - ds2482_calculate_config(DS2482_REG_CFG_SPU | - DS2482_REG_CFG_APU)); - ds2482_wait_1wire_idle(pdev); - } + if (!delay) + return 1; - return retval; + pchan->spu = true; + return 0; } diff --git a/drivers/w1/slaves/w1_ds2805.c b/drivers/w1/slaves/w1_ds2805.c index 9c86b7985d0bd6..bfcc02ecbdb9b7 100644 --- a/drivers/w1/slaves/w1_ds2805.c +++ b/drivers/w1/slaves/w1_ds2805.c @@ -102,7 +102,7 @@ static ssize_t w1_f0d_read_bin(struct file *filp, struct kobject *kobj, if (count == 0) return 0; - mutex_lock(&sl->master->mutex); + mutex_lock(&sl->master->bus_mutex); /* read directly from the EEPROM in chunks of W1_F0D_READ_MAXLEN */ while (todo > 0) { @@ -123,7 +123,7 @@ static ssize_t w1_f0d_read_bin(struct file *filp, struct kobject *kobj, off += W1_F0D_READ_MAXLEN; } - mutex_unlock(&sl->master->mutex); + mutex_unlock(&sl->master->bus_mutex); return count; } @@ -211,7 +211,7 @@ static ssize_t w1_f0d_write_bin(struct file *filp, struct kobject *kobj, if (count == 0) return 0; - mutex_lock(&sl->master->mutex); + mutex_lock(&sl->master->bus_mutex); /* Can only write data in blocks of the size of the scratchpad */ addr = off; @@ -256,7 +256,7 @@ static ssize_t w1_f0d_write_bin(struct file *filp, struct kobject *kobj, } out_up: - mutex_unlock(&sl->master->mutex); + mutex_unlock(&sl->master->bus_mutex); return count; } diff --git a/drivers/w1/slaves/w1_ds28e04.c b/drivers/w1/slaves/w1_ds28e04.c index 3b3c0789e1adf3..30fb8415b659e0 100644 --- a/drivers/w1/slaves/w1_ds28e04.c +++ b/drivers/w1/slaves/w1_ds28e04.c @@ -123,7 +123,7 @@ static ssize_t eeprom_read(struct file *filp, struct kobject *kobj, if (count == 0) return 0; - mutex_lock(&sl->master->mutex); + mutex_lock(&sl->master->bus_mutex); if (w1_enable_crccheck) { min_page = (off >> W1_PAGE_BITS); @@ -140,7 +140,7 @@ static ssize_t eeprom_read(struct file *filp, struct kobject *kobj, } out_up: - mutex_unlock(&sl->master->mutex); + mutex_unlock(&sl->master->bus_mutex); return count; } @@ -253,7 +253,7 @@ static ssize_t eeprom_write(struct file *filp, struct kobject *kobj, } } - mutex_lock(&sl->master->mutex); + mutex_lock(&sl->master->bus_mutex); /* Can only write data to one page at a time */ idx = 0; @@ -271,7 +271,7 @@ static ssize_t eeprom_write(struct file *filp, struct kobject *kobj, } out_up: - mutex_unlock(&sl->master->mutex); + mutex_unlock(&sl->master->bus_mutex); return count; } @@ -290,9 +290,9 @@ static ssize_t pio_read(struct file *filp, struct kobject *kobj, if (off != 0 || count != 1 || buf == NULL) return -EINVAL; - mutex_lock(&sl->master->mutex); + mutex_lock(&sl->master->bus_mutex); ret = w1_f1C_read(sl, W1_1C_REG_LOGIC_STATE, count, buf); - mutex_unlock(&sl->master->mutex); + mutex_unlock(&sl->master->bus_mutex); return ret; } @@ -310,11 +310,11 @@ static ssize_t pio_write(struct file *filp, struct kobject *kobj, if (off != 0 || count != 1 || buf == NULL) return -EINVAL; - mutex_lock(&sl->master->mutex); + mutex_lock(&sl->master->bus_mutex); /* Write the PIO data */ if (w1_reset_select_slave(sl)) { - mutex_unlock(&sl->master->mutex); + mutex_unlock(&sl->master->bus_mutex); return -1; } @@ -328,7 +328,7 @@ static ssize_t pio_write(struct file *filp, struct kobject *kobj, w1_read_block(sl->master, &ack, sizeof(ack)); - mutex_unlock(&sl->master->mutex); + mutex_unlock(&sl->master->bus_mutex); /* check for acknowledgement */ if (ack != 0xAA) diff --git a/drivers/w1/slaves/w1_therm.c b/drivers/w1/slaves/w1_therm.c index d96b224e221503..d8751b29f4205a 100644 --- a/drivers/w1/slaves/w1_therm.c +++ b/drivers/w1/slaves/w1_therm.c @@ -906,6 +906,19 @@ static inline bool bulk_read_support(struct w1_slave *sl) return false; /* No device family */ } +/** + * bulk_read_slave() - check if a slave of the bus takes part in a bulk read + * @sl: any slave on the list of the master + * + * The family data of the slaves of other families is none of our business. + * + * Return: true if it is one of our devices and supports bulk read + */ +static bool bulk_read_slave(struct w1_slave *sl) +{ + return device_family(sl) && sl->family_data && bulk_read_support(sl); +} + /** * conversion_time() - get the Tconv for the slave * @sl: device to get the conversion time @@ -1495,10 +1508,9 @@ static int trigger_bulk_read(struct w1_master *dev_master) * and compute duration of conversion for these devices * so we can apply a strong pullup if required */ + mutex_lock(&dev_master->list_mutex); list_for_each_entry(sl, &dev_master->slist, w1_slave_entry) { - if (!sl->family_data) - goto error; - if (bulk_read_support(sl)) { + if (bulk_read_slave(sl)) { int t_cur = conversion_time(sl); t_conv = max(t_cur, t_conv); @@ -1508,6 +1520,7 @@ static int trigger_bulk_read(struct w1_master *dev_master) w1_strong_pullup)); } } + mutex_unlock(&dev_master->list_mutex); /* * t_conv is the max conversion time required on the bus @@ -1534,11 +1547,13 @@ static int trigger_bulk_read(struct w1_master *dev_master) w1_write_8(dev_master, W1_CONVERT_TEMP); /* set a flag to instruct that converT pending */ + mutex_lock(&dev_master->list_mutex); list_for_each_entry(sl, &dev_master->slist, w1_slave_entry) { - if (bulk_read_support(sl)) + if (bulk_read_slave(sl)) SLAVE_CONVERT_TRIGGERED(sl) = -1; } + mutex_unlock(&dev_master->list_mutex); if (strong_pullup) { /* some device need pullup */ sleep_rem = msleep_interruptible(t_conv); @@ -1564,10 +1579,12 @@ static int trigger_bulk_read(struct w1_master *dev_master) mutex_unlock(&dev_master->bus_mutex); set_flag: /* set a flag to register convsersion is done */ + mutex_lock(&dev_master->list_mutex); list_for_each_entry(sl, &dev_master->slist, w1_slave_entry) { - if (bulk_read_support(sl)) + if (bulk_read_slave(sl)) SLAVE_CONVERT_TRIGGERED(sl) = 1; } + mutex_unlock(&dev_master->list_mutex); error: return ret; } @@ -1932,20 +1949,20 @@ static ssize_t therm_bulk_read_show(struct device *device, struct w1_slave *sl = NULL; int ret = 0; + mutex_lock(&dev_master->list_mutex); list_for_each_entry(sl, &dev_master->slist, w1_slave_entry) { - if (sl->family_data) { - if (bulk_read_support(sl)) { - if (SLAVE_CONVERT_TRIGGERED(sl) == -1) { - ret = -1; - goto show_result; - } - if (SLAVE_CONVERT_TRIGGERED(sl) == 1) - /* continue to check other slaves */ - ret = 1; + if (bulk_read_slave(sl)) { + if (SLAVE_CONVERT_TRIGGERED(sl) == -1) { + ret = -1; + goto show_result; } + if (SLAVE_CONVERT_TRIGGERED(sl) == 1) + /* continue to check other slaves */ + ret = 1; } } show_result: + mutex_unlock(&dev_master->list_mutex); return sprintf(buf, "%d\n", ret); } diff --git a/drivers/w1/w1.c b/drivers/w1/w1.c index c1694664278929..4eb785c643c928 100644 --- a/drivers/w1/w1.c +++ b/drivers/w1/w1.c @@ -116,7 +116,7 @@ static ssize_t rw_write(struct file *filp, struct kobject *kobj, { struct w1_slave *sl = kobj_to_w1_slave(kobj); - mutex_lock(&sl->master->mutex); + mutex_lock(&sl->master->bus_mutex); if (w1_reset_select_slave(sl)) { count = 0; goto out_up; @@ -125,7 +125,7 @@ static ssize_t rw_write(struct file *filp, struct kobject *kobj, w1_write_block(sl->master, buf, count); out_up: - mutex_unlock(&sl->master->mutex); + mutex_unlock(&sl->master->bus_mutex); return count; } @@ -135,9 +135,9 @@ static ssize_t rw_read(struct file *filp, struct kobject *kobj, { struct w1_slave *sl = kobj_to_w1_slave(kobj); - mutex_lock(&sl->master->mutex); + mutex_lock(&sl->master->bus_mutex); w1_read_block(sl->master, buf, count); - mutex_unlock(&sl->master->mutex); + mutex_unlock(&sl->master->bus_mutex); return count; } @@ -781,16 +781,24 @@ int w1_unref_slave(struct w1_slave *sl) { struct w1_master *dev = sl->master; int refcnt; + + /* + * Once it is off the list nobody can find the slave and take a new + * reference. The lock must not be held any longer than that: the rest + * waits for sysfs callbacks and for users of the family data. + */ mutex_lock(&dev->list_mutex); refcnt = atomic_sub_return(1, &sl->refcnt); + if (refcnt == 0) + list_del(&sl->w1_slave_entry); + mutex_unlock(&dev->list_mutex); + if (refcnt == 0) { struct w1_netlink_msg msg; dev_dbg(&sl->dev, "%s: detaching %s [%p].\n", __func__, sl->name, sl); - list_del(&sl->w1_slave_entry); - memset(&msg, 0, sizeof(msg)); memcpy(msg.id.id, &sl->reg_num, sizeof(msg.id)); msg.type = W1_SLAVE_REMOVE; @@ -804,7 +812,6 @@ int w1_unref_slave(struct w1_slave *sl) kfree(sl); } atomic_dec(&dev->refcnt); - mutex_unlock(&dev->list_mutex); return refcnt; } diff --git a/drivers/w1/w1_int.c b/drivers/w1/w1_int.c index 19a0ea28e9f39a..3fcc9ee567278a 100644 --- a/drivers/w1/w1_int.c +++ b/drivers/w1/w1_int.c @@ -176,6 +176,13 @@ void __w1_remove_master_device(struct w1_master *dev) mutex_unlock(&w1_mlock); set_bit(W1_ABORT_SEARCH, &dev->flags); + + /* + * This waits for the callbacks, which take the locks below. One of + * them wakes the thread up. + */ + w1_destroy_master_attributes(dev); + kthread_stop(dev->thread); mutex_lock(&dev->mutex); @@ -185,7 +192,6 @@ void __w1_remove_master_device(struct w1_master *dev) w1_slave_detach(sl); mutex_lock(&dev->list_mutex); } - w1_destroy_master_attributes(dev); mutex_unlock(&dev->list_mutex); mutex_unlock(&dev->mutex); atomic_dec(&dev->refcnt); diff --git a/drivers/w1/w1_netlink.c b/drivers/w1/w1_netlink.c index e6b59d92107661..40fbb96a793e99 100644 --- a/drivers/w1/w1_netlink.c +++ b/drivers/w1/w1_netlink.c @@ -478,15 +478,17 @@ static void w1_process_cb(struct w1_master *dev, struct w1_async_cmd *async_cmd) if (!cmd || err) w1_netlink_queue_status(node->block, node->msg, cmd, err); + dev->priv = NULL; + mutex_unlock(&dev->bus_mutex); + /* ref taken in w1_search_slave or w1_search_master_id when building - * the block + * the block. If it is the last one, the slave is removed, which waits + * for users of the bus. */ if (sl) w1_unref_slave(sl); else atomic_dec(&dev->refcnt); - dev->priv = NULL; - mutex_unlock(&dev->bus_mutex); mutex_lock(&dev->list_mutex); list_del(&async_cmd->async_entry); diff --git a/drivers/watchdog/intel_oc_wdt.c b/drivers/watchdog/intel_oc_wdt.c index 0b012aeb18e155..4400a2a8811c93 100644 --- a/drivers/watchdog/intel_oc_wdt.c +++ b/drivers/watchdog/intel_oc_wdt.c @@ -44,6 +44,7 @@ struct intel_oc_wdt { struct resource *ctrl_res; struct watchdog_info info; bool locked; + bool suspended; }; static int heartbeat; @@ -204,6 +205,7 @@ static int intel_oc_wdt_probe(struct platform_device *pdev) if (ret) return ret; + platform_set_drvdata(pdev, oc_wdt); watchdog_set_drvdata(wdd, oc_wdt); watchdog_set_nowayout(wdd, nowayout); watchdog_stop_on_reboot(wdd); @@ -212,6 +214,55 @@ static int intel_oc_wdt_probe(struct platform_device *pdev) return devm_watchdog_register_device(dev, wdd); } +/* + * Neither user space nor the watchdog core can ping the watchdog while the + * system sleeps, and in suspend-to-idle the counter keeps running, so stop the + * watchdog late in suspend and restart it early in resume. Check the hardware + * enable bit, as the watchdog may also have been started by the firmware. + */ +static int intel_oc_wdt_suspend_noirq(struct device *dev) +{ + struct intel_oc_wdt *oc_wdt = dev_get_drvdata(dev); + + oc_wdt->suspended = false; + + if (oc_wdt->locked || + !(inl(INTEL_OC_WDT_CTRL_REG(oc_wdt)) & INTEL_OC_WDT_EN)) + return 0; + + intel_oc_wdt_stop(&oc_wdt->wdd); + oc_wdt->suspended = true; + + return 0; +} + +static int intel_oc_wdt_resume_noirq(struct device *dev) +{ + struct intel_oc_wdt *oc_wdt = dev_get_drvdata(dev); + + if (oc_wdt->locked) + return 0; + + /* + * The timeout in hardware may have been reset by the platform firmware + * or, when resuming from hibernation, set by the boot kernel, and + * intel_oc_wdt_start() does not program it. + */ + intel_oc_wdt_set_timeout(&oc_wdt->wdd, oc_wdt->wdd.timeout); + + if (!oc_wdt->suspended) + return 0; + + intel_oc_wdt_start(&oc_wdt->wdd); + intel_oc_wdt_ping(&oc_wdt->wdd); + oc_wdt->suspended = false; + + return 0; +} + +static DEFINE_NOIRQ_DEV_PM_OPS(intel_oc_wdt_pm_ops, intel_oc_wdt_suspend_noirq, + intel_oc_wdt_resume_noirq); + static const struct acpi_device_id intel_oc_wdt_match[] = { { "INT3F0D" }, { "INTC1099" }, @@ -223,6 +274,7 @@ static struct platform_driver intel_oc_wdt_platform_driver = { .driver = { .name = DRV_NAME, .acpi_match_table = intel_oc_wdt_match, + .pm = pm_sleep_ptr(&intel_oc_wdt_pm_ops), }, .probe = intel_oc_wdt_probe, }; diff --git a/drivers/watchdog/npcm_wdt.c b/drivers/watchdog/npcm_wdt.c index 07ea810fb8c90e..df7f66e7796508 100644 --- a/drivers/watchdog/npcm_wdt.c +++ b/drivers/watchdog/npcm_wdt.c @@ -180,7 +180,7 @@ static int npcm_wdt_start(struct watchdog_device *wdd) { struct npcm_wdt *wdt = to_npcm_wdt(wdd); - clk_prepare_enable(wdt->clk); + clk_enable(wdt->clk); __npcm_wdt_start(wdd); @@ -193,7 +193,7 @@ static int npcm_wdt_stop(struct watchdog_device *wdd) writel(0, wdt->reg); - clk_disable_unprepare(wdt->clk); + clk_disable(wdt->clk); return 0; } @@ -242,8 +242,12 @@ static int npcm_wdt_restart(struct watchdog_device *wdd, { struct npcm_wdt *wdt = to_npcm_wdt(wdd); - /* For reset, we start the WDT clock and leave it running. */ - clk_prepare_enable(wdt->clk); + /* + * For reset, we start the WDT clock and leave it running. + * The clock was prepared at probe time; only clk_enable() is + * safe in this atomic (restart notifier) context. + */ + clk_enable(wdt->clk); writel(NPCM_WTR | NPCM_WTRE | NPCM_WTE, wdt->reg); udelay(1000); @@ -417,7 +421,12 @@ static int npcm_wdt_probe(struct platform_device *pdev) start = res->start; - wdt->clk = devm_clk_get_optional(&pdev->dev, NULL); + /* + * Keep the clock prepared for the lifetime of the driver: + * npcm_wdt_restart() runs in atomic context and may only call + * clk_enable(). + */ + wdt->clk = devm_clk_get_optional_prepared(&pdev->dev, NULL); if (IS_ERR(wdt->clk)) return PTR_ERR(wdt->clk); diff --git a/drivers/watchdog/sp805_wdt.c b/drivers/watchdog/sp805_wdt.c index a14ff7ac0db486..4e4febc5285357 100644 --- a/drivers/watchdog/sp805_wdt.c +++ b/drivers/watchdog/sp805_wdt.c @@ -138,6 +138,13 @@ wdt_restart(struct watchdog_device *wdd, unsigned long mode, void *cmd) { struct sp805_wdt *wdt = watchdog_get_drvdata(wdd); + /* + * For reset, we start the WDT clock and leave it running. + * The clock was prepared at probe time; only clk_enable() is + * safe in this atomic (restart notifier) context. + */ + clk_enable(wdt->clk); + writel_relaxed(UNLOCK, wdt->base + WDTLOCK); writel_relaxed(0, wdt->base + WDTCONTROL); writel_relaxed(0, wdt->base + WDTLOAD); @@ -156,7 +163,7 @@ static int wdt_config(struct watchdog_device *wdd, bool ping) if (!ping) { - ret = clk_prepare_enable(wdt->clk); + ret = clk_enable(wdt->clk); if (ret) { dev_err(&wdt->adev->dev, "clock enable fail"); return ret; @@ -208,7 +215,7 @@ static int wdt_disable(struct watchdog_device *wdd) readl_relaxed(wdt->base + WDTLOCK); spin_unlock(&wdt->lock); - clk_disable_unprepare(wdt->clk); + clk_disable(wdt->clk); return 0; } @@ -253,7 +260,11 @@ sp805_wdt_probe(struct amba_device *adev, const struct amba_id *id) */ device_property_read_u64(&adev->dev, "clock-frequency", &rate); - wdt->clk = devm_clk_get_optional(&adev->dev, NULL); + /* + * Keep the clock prepared for the lifetime of the driver: + * wdt_restart() runs in atomic context and may only call clk_enable(). + */ + wdt->clk = devm_clk_get_optional_prepared(&adev->dev, NULL); if (IS_ERR(wdt->clk)) return dev_err_probe(&adev->dev, PTR_ERR(wdt->clk), "Clock not found\n"); diff --git a/drivers/watchdog/stm32_iwdg.c b/drivers/watchdog/stm32_iwdg.c index 8a6f0b78a2b0a6..2d37fce0ff680f 100644 --- a/drivers/watchdog/stm32_iwdg.c +++ b/drivers/watchdog/stm32_iwdg.c @@ -19,6 +19,7 @@ #include #include #include +#include #include #define DEFAULT_TIMEOUT 10 @@ -82,6 +83,7 @@ struct stm32_iwdg { struct clk *clk_lsi; struct clk *clk_pclk; unsigned int rate; + spinlock_t lock; /* serialize IWDG_EWCR register access */ }; static inline u32 reg_read(void __iomem *base, u32 reg) @@ -98,6 +100,7 @@ static int stm32_iwdg_start(struct watchdog_device *wdd) { struct stm32_iwdg *wdt = watchdog_get_drvdata(wdd); u32 tout, ptot, presc, iwdg_rlr, iwdg_ewcr, iwdg_pr, iwdg_sr; + unsigned long flags; int ret; dev_dbg(wdd->parent, "%s\n", __func__); @@ -124,8 +127,11 @@ static int stm32_iwdg_start(struct watchdog_device *wdd) /* set prescaler & reload registers */ reg_write(wdt->regs, IWDG_PR, iwdg_pr); reg_write(wdt->regs, IWDG_RLR, iwdg_rlr); - if (wdt->data->has_early_wakeup) - reg_write(wdt->regs, IWDG_EWCR, iwdg_ewcr | EWCR_EWIE); + if (wdt->data->has_early_wakeup) { + spin_lock_irqsave(&wdt->lock, flags); + writel(iwdg_ewcr | EWCR_EWIE, wdt->regs + IWDG_EWCR); + spin_unlock_irqrestore(&wdt->lock, flags); + } reg_write(wdt->regs, IWDG_KR, KR_KEY_ENABLE); /* wait for the registers to be updated (max 100ms) */ @@ -185,11 +191,16 @@ static irqreturn_t stm32_iwdg_isr(int irq, void *wdog_arg) { struct watchdog_device *wdd = wdog_arg; struct stm32_iwdg *wdt = watchdog_get_drvdata(wdd); + unsigned long flags; u32 reg; - reg = reg_read(wdt->regs, IWDG_EWCR); + spin_lock_irqsave(&wdt->lock, flags); + + reg = readl(wdt->regs + IWDG_EWCR); reg |= EWCR_EWIC; - reg_write(wdt->regs, IWDG_EWCR, reg); + writel(reg, wdt->regs + IWDG_EWCR); + + spin_unlock_irqrestore(&wdt->lock, flags); watchdog_notify_pretimeout(wdd); @@ -298,7 +309,7 @@ static int stm32_iwdg_irq_init(struct platform_device *pdev, if (ret) return ret; - ret = dev_pm_set_wake_irq(dev, irq); + ret = devm_pm_set_wake_irq(dev, irq); if (ret) return ret; } @@ -323,6 +334,8 @@ static int stm32_iwdg_probe(struct platform_device *pdev) if (!wdt) return -ENOMEM; + spin_lock_init(&wdt->lock); + wdt->data = of_device_get_match_data(&pdev->dev); if (!wdt->data) return -ENODEV; @@ -346,15 +359,15 @@ static int stm32_iwdg_probe(struct platform_device *pdev) wdd->max_hw_heartbeat_ms = ((RLR_MAX + 1) * wdt->data->max_prescaler * 1000) / wdt->rate; + watchdog_set_drvdata(wdd, wdt); + watchdog_set_nowayout(wdd, WATCHDOG_NOWAYOUT); + watchdog_init_timeout(wdd, 0, dev); + /* Initialize IRQ, this might override wdd->info, hence it is here. */ ret = stm32_iwdg_irq_init(pdev, wdt); if (ret) return ret; - watchdog_set_drvdata(wdd, wdt); - watchdog_set_nowayout(wdd, WATCHDOG_NOWAYOUT); - watchdog_init_timeout(wdd, 0, dev); - /* * In case of CONFIG_WATCHDOG_HANDLE_BOOT_ENABLED is set * (Means U-Boot/bootloaders leaves the watchdog running) diff --git a/drivers/watchdog/watchdog_core.h b/drivers/watchdog/watchdog_core.h index ab825d9f9248d0..c6df5a584357a2 100644 --- a/drivers/watchdog/watchdog_core.h +++ b/drivers/watchdog/watchdog_core.h @@ -60,6 +60,7 @@ struct watchdog_core_data { #define _WDOG_DEV_OPEN 0 /* Opened ? */ #define _WDOG_ALLOW_RELEASE 1 /* Did we receive the magic char ? */ #define _WDOG_KEEPALIVE 2 /* Did we receive a keepalive ? */ +#define _WDOG_SUSPENDED 3 /* Suspended ? */ }; /* diff --git a/drivers/watchdog/watchdog_dev.c b/drivers/watchdog/watchdog_dev.c index e8c1fcb53c56c0..9b175730fa9898 100644 --- a/drivers/watchdog/watchdog_dev.c +++ b/drivers/watchdog/watchdog_dev.c @@ -55,6 +55,7 @@ static dev_t watchdog_devt; /* Reference to watchdog device behind /dev/watchdog */ static struct watchdog_core_data *old_wd_data; +static DEFINE_MUTEX(old_wd_data_lock); static struct kthread_worker *watchdog_kworker; @@ -80,6 +81,9 @@ static inline bool watchdog_need_worker(struct watchdog_device *wdd) unsigned int hm = wdd->max_hw_heartbeat_ms; unsigned int t = wdd->timeout * 1000; + if (test_bit(_WDOG_SUSPENDED, &wdd->wd_data->status)) + return false; + /* * A worker to generate heartbeat requests is needed if all of the * following conditions are true. @@ -153,9 +157,10 @@ static int __watchdog_ping(struct watchdog_device *wdd) now = ktime_get(); if (ktime_after(earliest_keepalive, now)) { - hrtimer_start(&wd_data->timer, - ktime_sub(earliest_keepalive, now), - HRTIMER_MODE_REL_HARD); + if (!test_bit(_WDOG_SUSPENDED, &wd_data->status)) + hrtimer_start(&wd_data->timer, + ktime_sub(earliest_keepalive, now), + HRTIMER_MODE_REL_HARD); return 0; } @@ -206,7 +211,7 @@ static bool watchdog_worker_should_ping(struct watchdog_core_data *wd_data) { struct watchdog_device *wdd = wd_data->wdd; - if (!wdd) + if (!wdd || test_bit(_WDOG_SUSPENDED, &wd_data->status)) return false; if (watchdog_active(wdd)) @@ -259,10 +264,14 @@ static int watchdog_start(struct watchdog_device *wdd) started_at = ktime_get(); if (watchdog_hw_running(wdd) && wdd->ops->ping) { + set_bit(WDOG_ACTIVE, &wdd->status); + wd_data->last_keepalive = started_at; err = __watchdog_ping(wdd); if (err == 0) { - set_bit(WDOG_ACTIVE, &wdd->status); watchdog_hrtimer_pretimeout_start(wdd); + } else { + clear_bit(WDOG_ACTIVE, &wdd->status); + watchdog_update_worker(wdd); } } else { err = wdd->ops->start(wdd); @@ -307,6 +316,7 @@ static int watchdog_stop(struct watchdog_device *wdd) clear_bit(WDOG_HW_RUNNING, &wdd->status); err = wdd->ops->stop(wdd); if (err < 0) { + set_bit(WDOG_HW_RUNNING, &wdd->status); pr_err("watchdog%d: Failed to stop watchdog: %pe\n", wdd->id, ERR_PTR(err)); } @@ -435,6 +445,9 @@ static void watchdog_get_timeleft(struct watchdog_device *wdd, { *timeleft = 0; + if (!watchdog_active(wdd) && !watchdog_hw_running(wdd)) + return; + if (wdd->ops->get_timeleft) { *timeleft = wdd->ops->get_timeleft(wdd); } else { @@ -869,17 +882,32 @@ static int watchdog_open(struct inode *inode, struct file *file) int err; /* Get the corresponding watchdog device */ - if (imajor(inode) == MISC_MAJOR) + if (imajor(inode) == MISC_MAJOR) { + mutex_lock(&old_wd_data_lock); wd_data = old_wd_data; - else + if (!wd_data) { + mutex_unlock(&old_wd_data_lock); + return -ENODEV; + } + mutex_lock(&wd_data->lock); + mutex_unlock(&old_wd_data_lock); + } else { wd_data = container_of(inode->i_cdev, struct watchdog_core_data, cdev); + mutex_lock(&wd_data->lock); + } /* the watchdog is single open! */ - if (test_and_set_bit(_WDOG_DEV_OPEN, &wd_data->status)) + if (test_and_set_bit(_WDOG_DEV_OPEN, &wd_data->status)) { + mutex_unlock(&wd_data->lock); return -EBUSY; + } wdd = wd_data->wdd; + if (!wdd) { + err = -ENODEV; + goto out_clear; + } /* * If the /dev/watchdog device is open, we don't want the module @@ -909,13 +937,17 @@ static int watchdog_open(struct inode *inode, struct file *file) */ wd_data->open_deadline = KTIME_MAX; + mutex_unlock(&wd_data->lock); + /* dev/watchdog is a virtual (and thus non-seekable) filesystem */ return stream_open(inode, file); out_mod: - module_put(wd_data->wdd->ops->owner); + if (!hw_running) + module_put(wd_data->wdd->ops->owner); out_clear: clear_bit(_WDOG_DEV_OPEN, &wd_data->status); + mutex_unlock(&wd_data->lock); return err; } @@ -1022,6 +1054,7 @@ static const struct class watchdog_class = { static int watchdog_cdev_register(struct watchdog_device *wdd) { struct watchdog_core_data *wd_data; + bool hw_running; int err; wd_data = kzalloc_obj(struct watchdog_core_data); @@ -1033,6 +1066,7 @@ static int watchdog_cdev_register(struct watchdog_device *wdd) wdd->wd_data = wd_data; if (IS_ERR_OR_NULL(watchdog_kworker)) { + wdd->wd_data = NULL; kfree(wd_data); return -ENODEV; } @@ -1046,6 +1080,7 @@ static int watchdog_cdev_register(struct watchdog_device *wdd) dev_set_drvdata(&wd_data->dev, wdd); err = dev_set_name(&wd_data->dev, "watchdog%d", wdd->id); if (err) { + wdd->wd_data = NULL; put_device(&wd_data->dev); return err; } @@ -1055,6 +1090,29 @@ static int watchdog_cdev_register(struct watchdog_device *wdd) HRTIMER_MODE_REL_HARD); watchdog_hrtimer_pretimeout_init(wdd); + /* Fill in the data structures */ + cdev_init(&wd_data->cdev, &watchdog_fops); + wd_data->cdev.owner = wdd->ops->owner; + + /* Record time of most recent heartbeat as 'just before now'. */ + wd_data->last_hw_keepalive = ktime_sub(ktime_get(), 1); + watchdog_set_open_deadline(wd_data); + + /* + * If the watchdog is running, prevent its driver from being unloaded, + * and schedule an immediate ping. + */ + if (watchdog_hw_running(wdd)) { + __module_get(wdd->ops->owner); + get_device(&wd_data->dev); + if (handle_boot_enabled) + hrtimer_start(&wd_data->timer, 0, + HRTIMER_MODE_REL_HARD); + else + pr_info("watchdog%d running and kernel based pre-userspace handler disabled\n", + wdd->id); + } + if (wdd->id == 0) { old_wd_data = wd_data; watchdog_miscdev.parent = wdd->parent; @@ -1066,15 +1124,10 @@ static int watchdog_cdev_register(struct watchdog_device *wdd) pr_err("%s: a legacy watchdog module is probably present.\n", wdd->info->identity); old_wd_data = NULL; - put_device(&wd_data->dev); - return err; + goto err_clear; } } - /* Fill in the data structures */ - cdev_init(&wd_data->cdev, &watchdog_fops); - wd_data->cdev.owner = wdd->ops->owner; - /* Add the device */ err = cdev_device_add(&wd_data->cdev, &wd_data->dev); if (err) { @@ -1082,32 +1135,33 @@ static int watchdog_cdev_register(struct watchdog_device *wdd) wdd->id, MAJOR(watchdog_devt), wdd->id); if (wdd->id == 0) { misc_deregister(&watchdog_miscdev); + mutex_lock(&old_wd_data_lock); old_wd_data = NULL; + mutex_unlock(&old_wd_data_lock); } - put_device(&wd_data->dev); - return err; + goto err_clear; } - /* Record time of most recent heartbeat as 'just before now'. */ - wd_data->last_hw_keepalive = ktime_sub(ktime_get(), 1); - watchdog_set_open_deadline(wd_data); + return 0; - /* - * If the watchdog is running, prevent its driver from being unloaded, - * and schedule an immediate ping. - */ - if (watchdog_hw_running(wdd)) { - __module_get(wdd->ops->owner); - get_device(&wd_data->dev); - if (handle_boot_enabled) - hrtimer_start(&wd_data->timer, 0, - HRTIMER_MODE_REL_HARD); - else - pr_info("watchdog%d running and kernel based pre-userspace handler disabled\n", - wdd->id); +err_clear: + mutex_lock(&wd_data->lock); + hw_running = watchdog_hw_running(wdd); + if (watchdog_active(wdd)) + watchdog_stop(wdd); + watchdog_hrtimer_pretimeout_stop(wdd); + if (hw_running && !test_bit(_WDOG_DEV_OPEN, &wd_data->status)) { + module_put(wdd->ops->owner); + put_device(&wd_data->dev); } + wd_data->wdd = NULL; + wdd->wd_data = NULL; + mutex_unlock(&wd_data->lock); - return 0; + hrtimer_cancel(&wd_data->timer); + kthread_cancel_work_sync(&wd_data->work); + put_device(&wd_data->dev); + return err; } /** @@ -1120,13 +1174,18 @@ static int watchdog_cdev_register(struct watchdog_device *wdd) static void watchdog_cdev_unregister(struct watchdog_device *wdd) { struct watchdog_core_data *wd_data = wdd->wd_data; + bool hw_running; cdev_device_del(&wd_data->cdev, &wd_data->dev); if (wdd->id == 0) { misc_deregister(&watchdog_miscdev); + mutex_lock(&old_wd_data_lock); old_wd_data = NULL; + mutex_unlock(&old_wd_data_lock); } + mutex_lock(&wd_data->lock); + hw_running = watchdog_hw_running(wdd); if (watchdog_active(wdd) && test_bit(WDOG_STOP_ON_UNREGISTER, &wdd->status)) { watchdog_stop(wdd); @@ -1134,7 +1193,10 @@ static void watchdog_cdev_unregister(struct watchdog_device *wdd) watchdog_hrtimer_pretimeout_stop(wdd); - mutex_lock(&wd_data->lock); + if (hw_running && !test_bit(_WDOG_DEV_OPEN, &wd_data->status)) { + module_put(wdd->ops->owner); + put_device(&wd_data->dev); + } wd_data->wdd = NULL; wdd->wd_data = NULL; mutex_unlock(&wd_data->lock); @@ -1201,20 +1263,27 @@ int watchdog_set_last_hw_keepalive(struct watchdog_device *wdd, { struct watchdog_core_data *wd_data; ktime_t now; + int ret = 0; if (!wdd) return -EINVAL; wd_data = wdd->wd_data; + if (!wd_data) + return -ENODEV; + + mutex_lock(&wd_data->lock); now = ktime_get(); wd_data->last_hw_keepalive = ktime_sub(now, ms_to_ktime(last_ping_ms)); if (watchdog_hw_running(wdd) && handle_boot_enabled) - return __watchdog_ping(wdd); + ret = __watchdog_ping(wdd); - return 0; + mutex_unlock(&wd_data->lock); + + return ret; } EXPORT_SYMBOL_GPL(watchdog_set_last_hw_keepalive); @@ -1281,6 +1350,8 @@ int watchdog_dev_suspend(struct watchdog_device *wdd) mutex_lock(&wd_data->lock); if (watchdog_worker_should_ping(wd_data)) ret = __watchdog_ping(wd_data->wdd); + if (!ret) + set_bit(_WDOG_SUSPENDED, &wd_data->status); mutex_unlock(&wd_data->lock); if (ret) @@ -1291,6 +1362,7 @@ int watchdog_dev_suspend(struct watchdog_device *wdd) * suspended */ hrtimer_cancel(&wd_data->timer); + watchdog_hrtimer_pretimeout_stop(wdd); kthread_cancel_work_sync(&wd_data->work); return 0; @@ -1309,8 +1381,11 @@ int watchdog_dev_resume(struct watchdog_device *wdd) * ping worker if needed. */ mutex_lock(&wd_data->lock); + clear_bit(_WDOG_SUSPENDED, &wd_data->status); if (watchdog_worker_should_ping(wd_data)) ret = __watchdog_ping(wd_data->wdd); + if (watchdog_hw_running(wdd) && !ret) + watchdog_hrtimer_pretimeout_start(wdd); mutex_unlock(&wd_data->lock); return ret; diff --git a/drivers/watchdog/watchdog_hrtimer_pretimeout.c b/drivers/watchdog/watchdog_hrtimer_pretimeout.c index 49a05ea60c9792..5c88e6467994b9 100644 --- a/drivers/watchdog/watchdog_hrtimer_pretimeout.c +++ b/drivers/watchdog/watchdog_hrtimer_pretimeout.c @@ -31,7 +31,8 @@ void watchdog_hrtimer_pretimeout_start(struct watchdog_device *wdd) { if (!(wdd->info->options & WDIOF_PRETIMEOUT) && wdd->pretimeout && - !watchdog_pretimeout_invalid(wdd, wdd->pretimeout)) + !watchdog_pretimeout_invalid(wdd, wdd->pretimeout) && + !test_bit(_WDOG_SUSPENDED, &wdd->wd_data->status)) hrtimer_start(&wdd->wd_data->pretimeout_timer, ktime_set(wdd->timeout - wdd->pretimeout, 0), HRTIMER_MODE_REL); diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c index f923d27f1bf2ea..73bb8b3228701c 100644 --- a/fs/btrfs/block-group.c +++ b/fs/btrfs/block-group.c @@ -1830,12 +1830,15 @@ void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info) /* * A concurrent scrub might have added us to the list * fs_info->unused_bgs, so use a list_move operation - * to add the block group to the deleted_bgs list. + * to add the block group to the deleted_bgs list. In + * that case the list reference moves along with it, + * so only take a new one if we were not on any list. */ + if (list_empty(&block_group->bg_list)) + btrfs_get_block_group(block_group); list_move(&block_group->bg_list, &trans->transaction->deleted_bgs); spin_unlock(&fs_info->unused_bgs_lock); - btrfs_get_block_group(block_group); } end_trans: /* diff --git a/fs/btrfs/delayed-inode.c b/fs/btrfs/delayed-inode.c index 333ce8b5248999..295329d67b219f 100644 --- a/fs/btrfs/delayed-inode.c +++ b/fs/btrfs/delayed-inode.c @@ -1053,7 +1053,7 @@ static int __btrfs_update_delayed_inode(struct btrfs_trans_handle *trans, ret = btrfs_search_slot(trans, root, &key, path, -1, 1); if (unlikely(ret < 0)) { btrfs_abort_transaction(trans, ret); - goto err_out; + goto out; } ASSERT(ret > 0); ASSERT(path->slots[0] > 0); @@ -1081,7 +1081,6 @@ static int __btrfs_update_delayed_inode(struct btrfs_trans_handle *trans, out: btrfs_release_delayed_iref(node); btrfs_release_path(path); -err_out: btrfs_delayed_inode_release_metadata(fs_info, node, (ret < 0)); btrfs_release_delayed_inode(node); return ret; diff --git a/fs/btrfs/direct-io.c b/fs/btrfs/direct-io.c index 90919d79d069c7..cf737539ced6f6 100644 --- a/fs/btrfs/direct-io.c +++ b/fs/btrfs/direct-io.c @@ -892,9 +892,13 @@ ssize_t btrfs_direct_write(struct kiocb *iocb, struct iov_iter *from) * If the write DIO is within EOF, use a shared lock and also only if * security bits will likely not be dropped by file_remove_privs() called * from btrfs_write_check(). Either will need to be rechecked after the - * lock was acquired. + * lock was acquired. Also if this is a sync write we will need to fsync + * and therefore we must lock in exclusive mode, otherwise we would race + * with other concurrent DIO writes and the fsync would not wait for + * their ordered extent to finish IO before logging the new extent maps. */ - if (iocb->ki_pos + iov_iter_count(from) <= i_size_read(inode) && IS_NOSEC(inode)) + if (iocb->ki_pos + iov_iter_count(from) <= i_size_read(inode) && + IS_NOSEC(inode) && !iocb_is_dsync(iocb)) ilock_flags |= BTRFS_ILOCK_SHARED; relock: @@ -916,6 +920,13 @@ ssize_t btrfs_direct_write(struct kiocb *iocb, struct iov_iter *from) goto relock; } + /* Sync writes must use exclusive locking, see the comment above. */ + if ((ilock_flags & BTRFS_ILOCK_SHARED) && iocb_is_dsync(iocb)) { + btrfs_inode_unlock(BTRFS_I(inode), ilock_flags); + ilock_flags &= ~BTRFS_ILOCK_SHARED; + goto relock; + } + ret = generic_write_checks(iocb, from); if (ret <= 0) { btrfs_inode_unlock(BTRFS_I(inode), ilock_flags); diff --git a/fs/btrfs/disk-io.c b/fs/btrfs/disk-io.c index 9100874093469b..8e8fb942d2b2a1 100644 --- a/fs/btrfs/disk-io.c +++ b/fs/btrfs/disk-io.c @@ -1129,6 +1129,15 @@ static struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info, { struct btrfs_root *root; +#if BITS_PER_LONG == 32 + /* + * Roots with ids above ULONG_MAX are never inserted into the radix + * tree, and a truncated index may hit an unrelated root. + */ + if (root_id > ULONG_MAX) + return NULL; +#endif + spin_lock(&fs_info->fs_roots_radix_lock); root = radix_tree_lookup(&fs_info->fs_roots_radix, (unsigned long)root_id); @@ -1181,6 +1190,10 @@ int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info, { int ret; + ret = btrfs_check_subvolid(fs_info, btrfs_root_id(root)); + if (ret) + return ret; + ret = radix_tree_preload(GFP_NOFS); if (ret) return ret; @@ -4347,10 +4360,6 @@ static void warn_about_uncommitted_trans(struct btrfs_fs_info *fs_info) trans->transid, dirty_bytes); btrfs_cleanup_one_transaction(trans); - if (trans == fs_info->running_transaction) - fs_info->running_transaction = NULL; - list_del_init(&trans->list); - btrfs_put_transaction(trans); } ASSERT(!found); @@ -4972,7 +4981,13 @@ void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans) EXTENT_DIRTY); btrfs_destroy_pinned_extent(fs_info, &cur_trans->pinned_extents); - cur_trans->state =TRANS_STATE_COMPLETED; + spin_lock(&fs_info->trans_lock); + if (cur_trans == fs_info->running_transaction) + fs_info->running_transaction = NULL; + list_del_init(&cur_trans->list); + spin_unlock(&fs_info->trans_lock); + + cur_trans->state = TRANS_STATE_COMPLETED; wake_up(&cur_trans->commit_wait); } @@ -5008,12 +5023,6 @@ static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info) } btrfs_cleanup_one_transaction(t); - spin_lock(&fs_info->trans_lock); - if (t == fs_info->running_transaction) - fs_info->running_transaction = NULL; - list_del_init(&t->list); - spin_unlock(&fs_info->trans_lock); - btrfs_put_transaction(t); spin_lock(&fs_info->trans_lock); } diff --git a/fs/btrfs/disk-io.h b/fs/btrfs/disk-io.h index 290508894f7ceb..e4e9f50a2c29eb 100644 --- a/fs/btrfs/disk-io.h +++ b/fs/btrfs/disk-io.h @@ -106,6 +106,24 @@ static inline struct btrfs_root *btrfs_grab_root(struct btrfs_root *root) return NULL; } +/* + * fs_roots_radix is indexed by unsigned long, so on 32-bit systems a subvolume + * id above ULONG_MAX is truncated, and can conflict with other subvolumes. + * Such subvolumes are not supported. + */ +static inline int btrfs_check_subvolid(const struct btrfs_fs_info *fs_info, u64 subvolid) +{ +#if BITS_PER_LONG == 32 + if (unlikely(subvolid > ULONG_MAX)) { + btrfs_err_rl(fs_info, + "subvolume id %llu is too large for 32-bit systems, max supported id is %lu", + subvolid, ULONG_MAX); + return -EOVERFLOW; + } +#endif + return 0; +} + void btrfs_put_root(struct btrfs_root *root); void btrfs_mark_buffer_dirty(struct btrfs_trans_handle *trans, struct extent_buffer *buf); diff --git a/fs/btrfs/extent_io.c b/fs/btrfs/extent_io.c index 5ff630630490e3..b2739838c6462d 100644 --- a/fs/btrfs/extent_io.c +++ b/fs/btrfs/extent_io.c @@ -2879,8 +2879,7 @@ static int extent_write_cache_pages(struct address_space *mapping, * locked. */ void extent_write_locked_range(struct inode *inode, const struct folio *locked_folio, - u64 start, u64 end, struct writeback_control *wbc, - bool pages_dirty) + u64 start, u64 end, struct writeback_control *wbc) { bool found_error = false; int ret = 0; @@ -2923,7 +2922,7 @@ void extent_write_locked_range(struct inode *inode, const struct folio *locked_f cur_len = cur_end + 1 - cur; ASSERT(folio_test_locked(folio)); - if (pages_dirty && folio != locked_folio) + if (folio != locked_folio) ASSERT(folio_test_dirty(folio)); /* diff --git a/fs/btrfs/extent_io.h b/fs/btrfs/extent_io.h index d8dd2ae9ff9a8a..c55b37cb24b709 100644 --- a/fs/btrfs/extent_io.h +++ b/fs/btrfs/extent_io.h @@ -280,8 +280,7 @@ void btrfs_check_folio_write_protected(struct folio *folio); static inline void btrfs_check_folio_write_protected(struct folio *folio) { } #endif void extent_write_locked_range(struct inode *inode, const struct folio *locked_folio, - u64 start, u64 end, struct writeback_control *wbc, - bool pages_dirty); + u64 start, u64 end, struct writeback_control *wbc); int btrfs_writepages(struct address_space *mapping, struct writeback_control *wbc); int btree_writepages(struct address_space *mapping, struct writeback_control *wbc); void btrfs_btree_wait_writeback_range(struct btrfs_fs_info *fs_info, u64 start, u64 end); diff --git a/fs/btrfs/fiemap.c b/fs/btrfs/fiemap.c index 817171028413c1..285398eb36dc14 100644 --- a/fs/btrfs/fiemap.c +++ b/fs/btrfs/fiemap.c @@ -621,6 +621,8 @@ static int fiemap_find_last_extent_offset(struct btrfs_inode *inode, leaf = path->nodes[0]; ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item); + if (btrfs_file_extent_type(leaf, ei) == BTRFS_FILE_EXTENT_INLINE) + break; disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei); } diff --git a/fs/btrfs/file.c b/fs/btrfs/file.c index f978c6524aa03f..cf033c08ec181b 100644 --- a/fs/btrfs/file.c +++ b/fs/btrfs/file.c @@ -916,7 +916,14 @@ lock_and_cleanup_extent(struct btrfs_inode *inode, struct folio *folio, cached_state); folio_unlock(folio); folio_put(folio); - btrfs_start_ordered_extent(ordered); + /* + * Waiting for the ordered extent blocks uninterruptibly, which + * a nowait caller must not do. Leave it alone and let the + * caller retry where blocking is acceptable, like + * btrfs_try_lock_ordered_range() does. + */ + if (!nowait) + btrfs_start_ordered_extent(ordered); btrfs_put_ordered_extent(ordered); return -EAGAIN; } @@ -2747,7 +2754,10 @@ static int btrfs_punch_hole(struct file *file, loff_t offset, loff_t len) inode_inc_iversion(inode); inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode)); ret = btrfs_update_inode(trans, BTRFS_I(inode)); - updated_inode = true; + if (ret) + btrfs_abort_transaction(trans, ret); + else + updated_inode = true; btrfs_end_transaction(trans); btrfs_btree_balance_dirty(fs_info); out: @@ -2773,6 +2783,8 @@ static int btrfs_punch_hole(struct file *file, loff_t offset, loff_t len) int ret2; ret = btrfs_update_inode(trans, BTRFS_I(inode)); + if (ret) + btrfs_abort_transaction(trans, ret); ret2 = btrfs_end_transaction(trans); if (!ret) ret = ret2; diff --git a/fs/btrfs/inode.c b/fs/btrfs/inode.c index abaa334714566f..95c9530554d021 100644 --- a/fs/btrfs/inode.c +++ b/fs/btrfs/inode.c @@ -120,8 +120,7 @@ static int btrfs_truncate(struct btrfs_inode *inode, bool skip_writeback); static noinline int run_delalloc_cow(struct btrfs_inode *inode, struct folio *locked_folio, u64 start, - u64 end, struct writeback_control *wbc, - bool pages_dirty); + u64 end, struct writeback_control *wbc); static int data_reloc_print_warning_inode(u64 inum, u64 offset, u64 num_bytes, u64 root, void *warn_ctx) @@ -776,33 +775,29 @@ static inline void inode_should_defrag(struct btrfs_inode *inode, btrfs_add_inode_defrag(inode, small_write); } -static int extent_range_clear_dirty_for_io(struct btrfs_inode *inode, u64 start, u64 end) +static void extent_range_check_write_protected(struct btrfs_inode *inode, u64 start, u64 end) { pgoff_t index = start >> PAGE_SHIFT; const pgoff_t end_index = end >> PAGE_SHIFT; struct folio *folio; - int ret = 0; + + if (!IS_ENABLED(CONFIG_BTRFS_DEBUG)) + return; while (index <= end_index) { folio = filemap_get_folio(inode->vfs_inode.i_mapping, index); + /* Compression should have all involved folios still locked. */ if (IS_ERR(folio)) { - if (!ret) - ret = PTR_ERR(folio); + DEBUG_WARN( +"missing a folio inside the compression range, index %lu start %llu end %llu", + index, start, end); index++; continue; } - /* - * We are about to compress the folio, so it must not be mmap - * writeable or we could corrupt the data as we attempt to - * compress it. - */ btrfs_check_folio_write_protected(folio); - btrfs_folio_clamp_clear_dirty(inode->root->fs_info, folio, start, - end + 1 - start); index = folio_next_index(folio); folio_put(folio); } - return ret; } static struct folio *compressed_bio_last_folio(struct compressed_bio *cb) @@ -889,16 +884,7 @@ static void compress_file_range(struct btrfs_work *work) inode_should_defrag(inode, start, end, end - start + 1, SZ_16K); - ret = extent_range_clear_dirty_for_io(inode, start, end); - - /* - * All the folios should have been locked thus no failure. - * - * And even if some folios are missing, btrfs_compress_bio() - * would handle them correctly, so here just do an ASSERT() check for - * early logic errors. - */ - ASSERT(ret == 0); + extent_range_check_write_protected(inode, start, end); /* * We need to save i_size before now because it could change in between @@ -1014,8 +1000,7 @@ static void submit_uncompressed_range(struct btrfs_inode *inode, }; wbc_attach_fdatawrite_inode(&wbc, &inode->vfs_inode); - ret = run_delalloc_cow(inode, locked_folio, start, end, - &wbc, false); + ret = run_delalloc_cow(inode, locked_folio, start, end, &wbc); wbc_detach_inode(&wbc); if (ret < 0) { if (locked_folio) @@ -1655,8 +1640,7 @@ static bool run_delalloc_compressed(struct btrfs_inode *inode, */ static noinline int run_delalloc_cow(struct btrfs_inode *inode, struct folio *locked_folio, u64 start, - u64 end, struct writeback_control *wbc, - bool pages_dirty) + u64 end, struct writeback_control *wbc) { u64 done_offset = end; int ret; @@ -1667,7 +1651,7 @@ static noinline int run_delalloc_cow(struct btrfs_inode *inode, if (ret) return ret; extent_write_locked_range(&inode->vfs_inode, locked_folio, - start, done_offset, wbc, pages_dirty); + start, done_offset, wbc); start = done_offset + 1; } @@ -2443,7 +2427,7 @@ int btrfs_run_delalloc_range(struct btrfs_inode *inode, struct folio *locked_fol return 1; if (zoned) - return run_delalloc_cow(inode, locked_folio, start, end, wbc, true); + return run_delalloc_cow(inode, locked_folio, start, end, wbc); else return cow_file_range(inode, locked_folio, start, end, NULL, 0); } @@ -4850,6 +4834,7 @@ int btrfs_delete_subvolume(struct btrfs_inode *dir, struct dentry *dentry) out_up_write: up_write(&fs_info->subvol_sem); if (!ret) { + drop_nlink(inode); d_invalidate(dentry); btrfs_prune_dentries(dest); ASSERT(dest->send_in_progress == 0); @@ -5609,6 +5594,14 @@ void btrfs_evict_inode(struct inode *inode) if (is_bad_inode(inode)) goto out; + /* + * For a deleted subvolume we drop the link count to 0 and we don't need + * to truncate items in its btree (which is dropped all at once). + */ + if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID && + btrfs_root_refs(&root->root_item) == 0) + goto out; + if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) goto out; @@ -6654,11 +6647,20 @@ int btrfs_create_new_inode(struct btrfs_trans_handle *trans, btrfs_set_inode_mapping_order(BTRFS_I(inode)); if (S_ISREG(inode->i_mode)) { - if (btrfs_test_opt(fs_info, NODATASUM)) - BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM; - if (btrfs_test_opt(fs_info, NODATACOW)) - BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW | - BTRFS_INODE_NODATASUM; + /* + * If we inherited compression from the parent directory, it + * takes precedence to nodatacow/nodatasum and we don't set + * compression along with nodatacow/nodatasun, otherwise if a + * user attempts to change some other attribute (say chattr +i), + * it will fail at -EINVAL. + */ + if (!(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS)) { + if (btrfs_test_opt(fs_info, NODATASUM)) + BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM; + if (btrfs_test_opt(fs_info, NODATACOW)) + BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW | + BTRFS_INODE_NODATASUM; + } btrfs_update_inode_mapping_flags(BTRFS_I(inode)); } @@ -9477,9 +9479,9 @@ static ssize_t btrfs_encoded_read_inline( ptr += iocb->ki_pos - extent_start; } - tmp = kmalloc(count, GFP_NOFS); + tmp = kmalloc(count, nowait ? GFP_NOWAIT : GFP_NOFS); if (!tmp) - return -ENOMEM; + return nowait ? -EAGAIN : -ENOMEM; read_extent_buffer(leaf, tmp, ptr, count); btrfs_release_path(path); @@ -10044,6 +10046,16 @@ ssize_t btrfs_do_encoded_write(struct kiocb *iocb, struct iov_iter *from, ret = PTR_ERR(ordered); goto out_free_reserved; } + /* + * A fast fsync can't deal with encoded writes because it neither + * dirties folios nor it waits for ordered extent completion (or finish + * its IO only) before unlocking the inode. + * The consequence is that it results in a race that can make the fast + * fsync log file extent items with the incorrect csum items, + * as the data may not reach disks, or the csum is not properly + * generated yet. + */ + btrfs_set_inode_full_sync(inode); btrfs_dec_block_group_reservations(fs_info, ins.objectid); if (start + encoded->len > inode->vfs_inode.i_size) diff --git a/fs/btrfs/ioctl.c b/fs/btrfs/ioctl.c index 6ba883db107b46..ba239d0d1a6d77 100644 --- a/fs/btrfs/ioctl.c +++ b/fs/btrfs/ioctl.c @@ -4661,7 +4661,8 @@ static void btrfs_uring_read_finished(struct io_tw_req tw_req, io_tw_token_t tw) btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED); io_uring_cmd_done(cmd, ret, IO_URING_CMD_TASK_WORK_ISSUE_FLAGS); - add_rchar(current, ret); + if (ret > 0) + add_rchar(current, ret); for (index = 0; index < priv->nr_pages; index++) __free_page(priv->pages[index]); @@ -5051,6 +5052,7 @@ static int btrfs_ioctl_subvol_sync(struct btrfs_fs_info *fs_info, void __user *a struct btrfs_ioctl_subvol_wait args = { 0 }; signed long sched_ret; int refs; + int ret; u64 root_flags; bool wait_for_deletion = false; bool found = false; @@ -5121,8 +5123,9 @@ static int btrfs_ioctl_subvol_sync(struct btrfs_fs_info *fs_info, void __user *a } /* 32bit limitation: fs_roots_radix key is not wide enough. */ - if (sizeof(unsigned long) != sizeof(u64) && args.subvolid > U32_MAX) - return -EOVERFLOW; + ret = btrfs_check_subvolid(fs_info, args.subvolid); + if (ret < 0) + return ret; while (1) { /* Wait for the specific one. */ diff --git a/fs/btrfs/reflink.c b/fs/btrfs/reflink.c index b5d2c094941df6..7d7e304c69243b 100644 --- a/fs/btrfs/reflink.c +++ b/fs/btrfs/reflink.c @@ -120,8 +120,21 @@ static int copy_inline_to_page(struct btrfs_inode *inode, ret = btrfs_decompress(comp_type, data_start, folio, offset_in_folio(folio, file_offset), inline_size, datal); - if (ret) + if (ret) { + /* + * btrfs_reset_extent_delalloc() set the range as + * delalloc, so clear it, otherwise we will free the + * reserved data and metadata space twice, once below by + * btrfs_delalloc_release_space() and once again when + * someone else clears the delalloc range with + * EXTENT_DO_ACCOUNTING (like + * btrfs_reset_extent_delalloc() does). + */ + btrfs_clear_extent_bit(&inode->io_tree, file_offset, + range_end, EXTENT_DELALLOC | + EXTENT_DELALLOC_NEW, NULL); goto out_unlock; + } flush_dcache_folio(folio); } diff --git a/fs/btrfs/send.c b/fs/btrfs/send.c index c523bf950c898f..3cc7749f04522a 100644 --- a/fs/btrfs/send.c +++ b/fs/btrfs/send.c @@ -5842,7 +5842,7 @@ static int clone_range(struct send_ctx *sctx, struct btrfs_path *dst_path, u8 type; u64 ext_len; u64 clone_len; - u64 clone_data_offset; + u64 clone_data_offset = 0; bool crossed_src_i_size = false; if (slot >= btrfs_header_nritems(leaf)) { @@ -5906,23 +5906,26 @@ static int clone_range(struct send_ctx *sctx, struct btrfs_path *dst_path, crossed_src_i_size = true; } - clone_data_offset = btrfs_file_extent_offset(leaf, ei); - if (btrfs_file_extent_disk_bytenr(leaf, ei) == disk_byte) { - clone_root->offset = key.offset; - if (clone_data_offset < data_offset && - clone_data_offset + ext_len > data_offset) { - u64 extent_offset; - - extent_offset = data_offset - clone_data_offset; - ext_len -= extent_offset; - clone_data_offset += extent_offset; - clone_root->offset += extent_offset; + if (type != BTRFS_FILE_EXTENT_INLINE) { + clone_data_offset = btrfs_file_extent_offset(leaf, ei); + if (btrfs_file_extent_disk_bytenr(leaf, ei) == disk_byte) { + clone_root->offset = key.offset; + if (clone_data_offset < data_offset && + clone_data_offset + ext_len > data_offset) { + u64 extent_offset; + + extent_offset = data_offset - clone_data_offset; + ext_len -= extent_offset; + clone_data_offset += extent_offset; + clone_root->offset += extent_offset; + } } } clone_len = min_t(u64, ext_len, len); - if (btrfs_file_extent_disk_bytenr(leaf, ei) == disk_byte && + if (type != BTRFS_FILE_EXTENT_INLINE && + btrfs_file_extent_disk_bytenr(leaf, ei) == disk_byte && clone_data_offset == data_offset) { const u64 src_end = clone_root->offset + clone_len; const u64 sectorsize = SZ_64K; @@ -6371,6 +6374,9 @@ static int range_is_hole_in_parent(struct send_ctx *sctx, static int maybe_send_hole(struct send_ctx *sctx, struct btrfs_path *path, struct btrfs_key *key) { + BTRFS_PATH_AUTO_FREE(next_path); + const u64 cur_extent_end = btrfs_file_extent_end(path); + u64 next_offset; int ret = 0; if (sctx->cur_ino != key->objectid || !need_send_hole(sctx)) @@ -6397,14 +6403,72 @@ static int maybe_send_hole(struct send_ctx *sctx, struct btrfs_path *path, ret = range_is_hole_in_parent(sctx, sctx->cur_inode_last_extent, key->offset); + if (ret == 0) + ret = send_hole(sctx, key->offset); + else if (ret == 1) + ret = 0; + if (ret < 0) return ret; - else if (ret == 0) - ret = send_hole(sctx, key->offset); + } + sctx->cur_inode_last_extent = cur_extent_end; + + /* + * If we are the last file extent item in a leaf, we may have had a tail + * section that got a hole punched or the extent replaced with a smaller + * one, and if there is no change in the next leaf, we must find out if + * we have such a hole and punch it. + */ + if (!btrfs_fs_incompat(sctx->send_root->fs_info, NO_HOLES) || + (sctx->cur_inode_size <= cur_extent_end) || + (path->slots[0] != btrfs_header_nritems(path->nodes[0]) - 1)) + return 0; + + next_path = alloc_path_for_send(); + if (!next_path) + return -ENOMEM; + + ret = btrfs_search_slot(NULL, sctx->send_root, key, next_path, 0, 0); + if (ret < 0) + return ret; + if (WARN_ON(ret != 0)) + return -EUCLEAN; + + ret = btrfs_next_leaf(sctx->send_root, next_path); + if (ret < 0) { + return ret; + } else if (ret > 0) { + /* + * No next leaf, must punch hole to i_size and set the path back + * to where it was before. + */ + next_offset = sctx->cur_inode_size; + } else { + struct btrfs_key next_key; + + btrfs_item_key_to_cpu(next_path->nodes[0], &next_key, + next_path->slots[0]); + if (next_key.objectid != key->objectid || + next_key.type != BTRFS_EXTENT_DATA_KEY) + next_offset = sctx->cur_inode_size; else - ret = 0; + next_offset = next_key.offset; } - sctx->cur_inode_last_extent = btrfs_file_extent_end(path); + + if (next_offset == cur_extent_end) + return 0; + + btrfs_free_path(next_path); + next_path = NULL; + + ret = range_is_hole_in_parent(sctx, sctx->cur_inode_last_extent, next_offset); + if (ret == 0) + ret = send_hole(sctx, next_offset); + else if (ret == 1) + ret = 0; + + sctx->cur_inode_last_extent = next_offset; + return ret; } diff --git a/fs/btrfs/transaction.c b/fs/btrfs/transaction.c index d265fac023e58e..cd7dff5ba59b6d 100644 --- a/fs/btrfs/transaction.c +++ b/fs/btrfs/transaction.c @@ -2124,12 +2124,7 @@ static void cleanup_transaction(struct btrfs_trans_handle *trans, int err) spin_unlock(&fs_info->trans_lock); - btrfs_cleanup_one_transaction(trans->transaction); - - spin_lock(&fs_info->trans_lock); - if (cur_trans == fs_info->running_transaction) - fs_info->running_transaction = NULL; - spin_unlock(&fs_info->trans_lock); + btrfs_cleanup_one_transaction(cur_trans); if (trans->type & TRANS_SB_INTWRITER_MASK) sb_end_intwrite(fs_info->sb); @@ -2641,6 +2636,10 @@ int btrfs_commit_transaction(struct btrfs_trans_handle *trans) btrfs_clear_space_info_full(fs_info); btrfs_set_last_trans_committed(fs_info, cur_trans->transid); + + spin_lock(&fs_info->trans_lock); + list_del_init(&cur_trans->list); + spin_unlock(&fs_info->trans_lock); /* * We needn't acquire the lock here because there is no other task * which can change it. @@ -2650,10 +2649,6 @@ int btrfs_commit_transaction(struct btrfs_trans_handle *trans) wake_up(&cur_trans->commit_wait); btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED); - spin_lock(&fs_info->trans_lock); - list_del_init(&cur_trans->list); - spin_unlock(&fs_info->trans_lock); - btrfs_put_transaction(cur_trans); btrfs_put_transaction(cur_trans); diff --git a/fs/btrfs/tree-log.c b/fs/btrfs/tree-log.c index 1d9dfb63fc5a4f..62d94d1a0a1a3b 100644 --- a/fs/btrfs/tree-log.c +++ b/fs/btrfs/tree-log.c @@ -3064,7 +3064,7 @@ static noinline int walk_up_log_tree(struct btrfs_path *path, int *level, int slot; int ret; - for (i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) { + for (i = *level; i < BTRFS_MAX_LEVEL && path->nodes[i]; i++) { slot = path->slots[i]; if (slot + 1 < btrfs_header_nritems(path->nodes[i])) { path->slots[i]++; diff --git a/fs/btrfs/volumes.c b/fs/btrfs/volumes.c index f1305f68b1f8ab..d297acfcf2fa6a 100644 --- a/fs/btrfs/volumes.c +++ b/fs/btrfs/volumes.c @@ -2475,11 +2475,11 @@ int btrfs_rm_device(struct btrfs_fs_info *fs_info, btrfs_assign_next_active_device(device, NULL); - if (device->bdev_file) { + if (device->bdev_file) cur_devices->open_devices--; - /* remove sysfs entry */ - btrfs_sysfs_remove_device(device); - } + + /* Remove sysfs entry, including for a missing device. */ + btrfs_sysfs_remove_device(device); num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1; btrfs_set_super_num_devices(fs_info->super_copy, num_devices); @@ -3206,6 +3206,7 @@ int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path btrfs_update_per_profile_avail(fs_info); mutex_unlock(&fs_info->chunk_mutex); mutex_unlock(&fs_info->fs_devices->device_list_mutex); + synchronize_rcu(); error_trans: if (trans) btrfs_end_transaction(trans); diff --git a/fs/btrfs/zstd.c b/fs/btrfs/zstd.c index 9b7c7f43527f7f..588d7af2953fc0 100644 --- a/fs/btrfs/zstd.c +++ b/fs/btrfs/zstd.c @@ -340,6 +340,7 @@ void zstd_put_workspace(struct btrfs_fs_info *fs_info, struct list_head *ws) { struct zstd_workspace_manager *zwsm = fs_info->compr_wsm[BTRFS_COMPRESS_ZSTD]; struct workspace *workspace = list_to_workspace(ws); + bool wakeup; ASSERT(zwsm); spin_lock_bh(&zwsm->lock); @@ -363,9 +364,14 @@ void zstd_put_workspace(struct btrfs_fs_info *fs_info, struct list_head *ws) list_add(&workspace->list, &zwsm->idle_ws[workspace->level]); workspace->req_level = 0; + /* + * Check if we should wakeup before releasing the lock because after + * that the reclaim function can run and free the workspace. + */ + wakeup = (workspace->level == clip_level(ZSTD_BTRFS_MAX_LEVEL)); spin_unlock_bh(&zwsm->lock); - if (workspace->level == clip_level(ZSTD_BTRFS_MAX_LEVEL)) + if (wakeup) cond_wake_up(&zwsm->wait); } diff --git a/fs/crypto/keysetup.c b/fs/crypto/keysetup.c index a77b889d7578cb..0beec01c041850 100644 --- a/fs/crypto/keysetup.c +++ b/fs/crypto/keysetup.c @@ -621,6 +621,13 @@ fscrypt_setup_encryption_info(struct inode *inode, if (res) goto out; + /* + * Preemptively initialize ->ci_master_key, even though we don't know + * whether we'll win the race below yet, because if we do win the race + * then other tasks can see it right away and need ->ci_master_key. + */ + crypt_info->ci_master_key = mk; + /* * For existing inodes, multiple tasks may race to set the inode's * fscrypt info pointer. So use cmpxchg_release(). This pairs with the @@ -634,7 +641,6 @@ fscrypt_setup_encryption_info(struct inode *inode, * crypt_info. Now link it into the master key's inode list. */ if (mk) { - crypt_info->ci_master_key = mk; refcount_inc(&mk->mk_active_refs); spin_lock(&mk->mk_decrypted_inodes_lock); list_add(&crypt_info->ci_master_key_link, @@ -642,6 +648,12 @@ fscrypt_setup_encryption_info(struct inode *inode, spin_unlock(&mk->mk_decrypted_inodes_lock); } crypt_info = NULL; + } else { + /* + * Lost the race, so we won't be taking an active reference to + * the master key. Clear ->ci_master_key accordingly. + */ + crypt_info->ci_master_key = NULL; } res = 0; out: diff --git a/fs/efivarfs/vars.c b/fs/efivarfs/vars.c index 6833c3d24b541a..9f18bf48615cfc 100644 --- a/fs/efivarfs/vars.c +++ b/fs/efivarfs/vars.c @@ -274,7 +274,7 @@ efivar_validate(efi_guid_t vendor, efi_char16_t *var_name, u8 *data, if (efi_guidcmp(vendor, variable_validate[i].vendor)) continue; - if (variable_matches(utf8_name, utf8_size+1, name, &match)) { + if (variable_matches(utf8_name, utf8_size, name, &match)) { if (variable_validate[i].validate == NULL) break; kfree(utf8_name); diff --git a/fs/eventpoll.c b/fs/eventpoll.c index b959af04772c87..58c0cb845dc722 100644 --- a/fs/eventpoll.c +++ b/fs/eventpoll.c @@ -1626,9 +1626,8 @@ static void ep_ptable_queue_proc(struct file *file, wait_queue_head_t *whead, pwq->whead = whead; pwq->base = epi; if (epi->event.events & EPOLLEXCLUSIVE) - add_wait_queue_exclusive(whead, &pwq->wait); - else - add_wait_queue(whead, &pwq->wait); + pwq->wait.flags |= WQ_FLAG_POLL_EXCLUSIVE; + add_wait_queue(whead, &pwq->wait); pwq->next = epi->pwqlist; epi->pwqlist = pwq; } diff --git a/fs/ext4/.kunitconfig b/fs/ext4/.kunitconfig index bf51da7cd9fc7d..17103c583fdb7d 100644 --- a/fs/ext4/.kunitconfig +++ b/fs/ext4/.kunitconfig @@ -1,3 +1,10 @@ CONFIG_KUNIT=y CONFIG_EXT4_FS=y +CONFIG_EXT4_FS_POSIX_ACL=y +CONFIG_EXT4_FS_SECURITY=y CONFIG_EXT4_KUNIT_TESTS=y +CONFIG_FS_VERITY=y +CONFIG_FS_ENCRYPTION=y +CONFIG_QUOTA=y +CONFIG_QFMT_V2=y +CONFIG_UNICODE=y diff --git a/fs/ext4/Makefile b/fs/ext4/Makefile index 3f9fc0eb8ecadb..a427f6f361e5ac 100644 --- a/fs/ext4/Makefile +++ b/fs/ext4/Makefile @@ -15,7 +15,17 @@ ext4-y := balloc.o bitmap.o block_validity.o dir.o ext4_jbd2.o extents.o \ ext4-$(CONFIG_EXT4_FS_POSIX_ACL) += acl.o ext4-$(CONFIG_EXT4_FS_SECURITY) += xattr_security.o ext4-test-objs += inode-test.o mballoc-test.o \ - extents-test.o hash-test.o + extents-test.o hash-test.o \ + extents_status-test.o xattr-test.o \ + namei-test.o inline-test.o \ + fast_commit-test.o ialloc-test.o \ + balloc-test.o orphan-test.o \ + block_validity-test.o super-test.o \ + sysfs-test.o ioctl-test.o \ + resize-test.o migrate-test.o \ + indirect-test.o fsmap-test.o \ + move_extent-test.o mmp-test.o \ + dir-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o diff --git a/fs/ext4/balloc-test.c b/fs/ext4/balloc-test.c new file mode 100644 index 00000000000000..ab076c0edf9994 --- /dev/null +++ b/fs/ext4/balloc-test.c @@ -0,0 +1,2403 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for fs/ext4/balloc.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_jbd2.h" +#include "mballoc.h" + +/* + * Default multi-group mock filesystem geometry: + * - 4 active block groups (capacity up to 32 groups across 2 GDT blocks) + * - 1024-byte blocks (8192 bits per bitmap block, 16 64-byte GDs per block) + * - s_first_data_block = 1, 1024 blocks (clusters) per group (total 4097) + * - 64 inodes per group, 16 inode table blocks per group + * - sparse_super + metadata_csum + 64bit enabled, s_gdb_count = 1: + * - Groups 0, 1, 3 have super + 1 gdb (2 base blocks) + bbitmap + ibitmap + + * 16 itable blocks = 20 overhead clusters -> 1004 free clusters. + * - Group 2 has 0 base blocks + bbitmap + ibitmap + 16 itable blocks = + * 18 overhead clusters -> 1006 free clusters. + */ +#define BALLOC_TEST_NGROUPS 4U +#define BALLOC_TEST_MAX_GROUPS 32U +#define BALLOC_TEST_GDESC_BLKS 2U +#define BALLOC_TEST_BLK_SIZE 1024U +#define BALLOC_TEST_BLK_BITS 10U +#define BALLOC_TEST_BLOCKS_PER_GRP 1024U +#define BALLOC_TEST_FIRST_DATA_BLK 1U +#define BALLOC_TEST_TOTAL_BLKS (BALLOC_TEST_FIRST_DATA_BLK + \ + BALLOC_TEST_NGROUPS * \ + BALLOC_TEST_BLOCKS_PER_GRP) +#define BALLOC_TEST_INODE_SIZE 256U +#define BALLOC_TEST_INODES_PER_GRP 64U +#define BALLOC_TEST_ITB_PER_GRP 16U +#define BALLOC_TEST_CSUM_SEED 0x5a3c91e7U +#define BALLOC_TEST_GDESC_BLK0 2ULL +#define BALLOC_TEST_POOL_SIZE 16U + +struct balloc_test_blk { + bool in_use; + ext4_fsblk_t blocknr; + struct buffer_head bh; + char cache_buf[BALLOC_TEST_BLK_SIZE] __aligned(8); + char disk_buf[BALLOC_TEST_BLK_SIZE] __aligned(8); +}; + +struct balloc_test_ctx { + struct super_block *sb; + struct ext4_sb_info sbi; + struct ext4_super_block es; + struct blockgroup_lock bgl; + struct block_device bdev; + struct request_queue bdev_queue; + struct inode bd_inode; + struct buffer_head sb_bh; + + struct ext4_group_desc gdps[BALLOC_TEST_MAX_GROUPS] __aligned(8); + struct buffer_head gdesc_bh[BALLOC_TEST_GDESC_BLKS]; + struct buffer_head *gdesc_bh_ptrs[BALLOC_TEST_GDESC_BLKS]; + + struct ext4_group_info *grp_infos[BALLOC_TEST_MAX_GROUPS]; + struct ext4_group_info *grp_info_slice0[16]; + struct ext4_group_info *grp_info_slice1[16]; + struct ext4_group_info **grp_info_slices[BALLOC_TEST_GDESC_BLKS]; + + struct inode *test_inode; + journal_t journal; + + struct balloc_test_blk pool[BALLOC_TEST_POOL_SIZE]; + + bool fcc_inited; + bool dcc_inited; + bool fic_inited; + bool sra_inited; + + /* Credential override tracking for deterministic cleanup */ + const struct cred *saved_cred; + struct cred *override_cred; + + /* Discard work tracking */ + unsigned int discard_work_runs; + int discard_saw_retry_pending; + s64 discard_release_clusters; + bool discard_wait_retry_pending; + + /* Stub fault injection and call capture */ + bool fail_getblk; + bool fail_read_eio; + unsigned int read_nowait_calls; + blk_opf_t last_read_op_flags; + + unsigned int mb_new_blocks_calls; + struct ext4_allocation_request last_ar; + ext4_fsblk_t mock_alloc_blk; + unsigned int mock_alloc_len; + int mock_alloc_err; +}; + +static inline ext4_fsblk_t balloc_test_group_start(ext4_group_t g) +{ + return BALLOC_TEST_FIRST_DATA_BLK + + (ext4_fsblk_t)g * BALLOC_TEST_BLOCKS_PER_GRP; +} + +static inline unsigned int balloc_test_default_base_blks(ext4_group_t g) +{ + return (g == 2) ? 0U : 2U; +} + +static inline ext4_fsblk_t balloc_test_bbitmap_blk(ext4_group_t g) +{ + return balloc_test_group_start(g) + balloc_test_default_base_blks(g); +} + +static inline ext4_fsblk_t balloc_test_ibitmap_blk(ext4_group_t g) +{ + return balloc_test_bbitmap_blk(g) + 1; +} + +static inline ext4_fsblk_t balloc_test_itable_blk(ext4_group_t g) +{ + return balloc_test_bbitmap_blk(g) + 2; +} + +static inline void clear_bitmap_uptodate(struct buffer_head *bh) +{ + clear_bit(BH_BITMAP_UPTODATE, &bh->b_state); +} + +static struct inode *balloc_test_alloc_inode(struct super_block *sb) +{ + struct ext4_inode_info *ei; + + ei = kzalloc_obj(*ei); + if (!ei) + return NULL; + + init_rwsem(&ei->i_data_sem); + init_rwsem(&ei->xattr_sem); + INIT_LIST_HEAD(&ei->i_orphan); + inode_init_once(&ei->vfs_inode); + ext4_fc_init_inode(&ei->vfs_inode); + spin_lock_init(&ei->i_raw_lock); + spin_lock_init(&ei->i_block_reservation_lock); +#ifdef CONFIG_QUOTA + memset(&ei->i_dquot, 0, sizeof(ei->i_dquot)); +#endif + return &ei->vfs_inode; +} + +static void balloc_test_free_inode_mem(struct inode *inode) +{ + kfree(EXT4_I(inode)); +} + +#ifdef CONFIG_QUOTA +static struct dquot __rcu **balloc_test_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} + +static qsize_t *balloc_test_get_reserved_space(struct inode *inode) +{ + return &EXT4_I(inode)->i_reserved_quota; +} + +static const struct dquot_operations balloc_test_qops = { + .get_reserved_space = balloc_test_get_reserved_space, +}; +#endif + +static const struct super_operations balloc_test_sops = { + .alloc_inode = balloc_test_alloc_inode, + .free_inode = balloc_test_free_inode_mem, + .drop_inode = inode_just_drop, +#ifdef CONFIG_QUOTA + .get_dquots = balloc_test_get_dquots, +#endif +}; + +static int balloc_test_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static struct file_system_type balloc_test_fs_type = { + .name = "ext4_balloc_kunit", + .init_fs_context = balloc_test_init_fs_context, + .kill_sb = kill_anon_super, +}; + +static struct balloc_test_blk *balloc_test_find_blk(struct balloc_test_ctx *ctx, + ext4_fsblk_t blocknr) +{ + unsigned int i; + + for (i = 0; i < BALLOC_TEST_POOL_SIZE; i++) { + if (ctx->pool[i].in_use && ctx->pool[i].blocknr == blocknr) + return &ctx->pool[i]; + } + return NULL; +} + +static struct balloc_test_blk * +balloc_test_find_blk_by_bh(struct balloc_test_ctx *ctx, struct buffer_head *bh) +{ + unsigned int i; + + for (i = 0; i < BALLOC_TEST_POOL_SIZE; i++) { + if (ctx->pool[i].in_use && &ctx->pool[i].bh == bh) + return &ctx->pool[i]; + } + return NULL; +} + +static struct balloc_test_blk * +balloc_test_setup_blk(struct balloc_test_ctx *ctx, ext4_fsblk_t blocknr, + bool uptodate) +{ + struct balloc_test_blk *slot = balloc_test_find_blk(ctx, blocknr); + unsigned int i; + + if (!slot) { + for (i = 0; i < BALLOC_TEST_POOL_SIZE; i++) { + if (!ctx->pool[i].in_use) { + slot = &ctx->pool[i]; + break; + } + } + } + if (!slot) + return NULL; + + memset(slot, 0, sizeof(*slot)); + slot->in_use = true; + slot->blocknr = blocknr; + slot->bh.b_bdev = &ctx->bdev; + slot->bh.b_blocknr = blocknr; + slot->bh.b_size = BALLOC_TEST_BLK_SIZE; + slot->bh.b_data = slot->cache_buf; + atomic_set(&slot->bh.b_count, 1); + if (uptodate) + set_buffer_uptodate(&slot->bh); + return slot; +} + +static void balloc_test_sync_bbitmap_csum(struct balloc_test_ctx *ctx, + ext4_group_t g, bool sync_disk) +{ + struct ext4_group_desc *gdp = &ctx->gdps[g]; + struct balloc_test_blk *slot; + + slot = balloc_test_find_blk(ctx, ext4_block_bitmap(ctx->sb, gdp)); + if (slot) { + ext4_block_bitmap_csum_set(ctx->sb, gdp, &slot->bh); + if (sync_disk) + memcpy(slot->disk_buf, slot->cache_buf, + BALLOC_TEST_BLK_SIZE); + } + ext4_group_desc_csum_set(ctx->sb, g, gdp); +} + +static void balloc_test_discard_work_fn(struct work_struct *work) +{ + struct ext4_sb_info *sbi = + container_of(work, struct ext4_sb_info, s_discard_work); + struct balloc_test_ctx *ctx = + container_of(sbi, struct balloc_test_ctx, sbi); + + if (ctx->discard_wait_retry_pending) { + ktime_t deadline = ktime_add_ms(ktime_get(), 500); + + while (!atomic_read(&sbi->s_retry_alloc_pending) && + ktime_before(ktime_get(), deadline)) + usleep_range(100, 500); + } + + ctx->discard_work_runs++; + ctx->discard_saw_retry_pending = atomic_read(&sbi->s_retry_alloc_pending); + if (ctx->discard_release_clusters) + percpu_counter_add(&sbi->s_freeclusters_counter, + ctx->discard_release_clusters); +} + +static void balloc_test_restore_creds(struct balloc_test_ctx *ctx) +{ + if (ctx->saved_cred) { + revert_creds(ctx->saved_cred); + ctx->saved_cred = NULL; + } + if (ctx->override_cred) { + put_cred(ctx->override_cred); + ctx->override_cred = NULL; + } +} + +static void balloc_test_override_creds(struct kunit *test, + struct balloc_test_ctx *ctx, + uid_t uid, gid_t gid, bool cap_sys_res, + int supp_gid) +{ + struct cred *cred; + + balloc_test_restore_creds(ctx); + + cred = prepare_creds(); + KUNIT_ASSERT_NOT_NULL(test, cred); + ctx->override_cred = cred; + + cred->uid = KUIDT_INIT(uid); + cred->euid = KUIDT_INIT(uid); + cred->suid = KUIDT_INIT(uid); + cred->fsuid = KUIDT_INIT(uid); + cred->gid = KGIDT_INIT(gid); + cred->egid = KGIDT_INIT(gid); + cred->sgid = KGIDT_INIT(gid); + cred->fsgid = KGIDT_INIT(gid); + cap_clear(cred->cap_effective); + cap_clear(cred->cap_permitted); + cap_clear(cred->cap_inheritable); + cap_clear(cred->cap_ambient); + if (cap_sys_res) { + cap_raise(cred->cap_permitted, CAP_SYS_RESOURCE); + cap_raise(cred->cap_effective, CAP_SYS_RESOURCE); + } +#ifdef CONFIG_MULTIUSER + { + struct group_info *gi = groups_alloc(supp_gid >= 0 ? 1 : 0); + + KUNIT_ASSERT_NOT_NULL(test, gi); + if (supp_gid >= 0) { + gi->gid[0] = KGIDT_INIT((gid_t)supp_gid); + groups_sort(gi); + } + set_groups(cred, gi); + put_group_info(gi); + } +#endif + ctx->saved_cred = override_creds(cred); +} + +/* --- Static Stubs --- */ + +static struct buffer_head *balloc_test_sb_getblk_stub(struct super_block *sb, + ext4_fsblk_t block) +{ + struct kunit *test = kunit_get_current_test(); + struct balloc_test_ctx *ctx = test ? test->priv : NULL; + struct balloc_test_blk *slot; + + if (!ctx || ctx->fail_getblk) + return NULL; + slot = balloc_test_find_blk(ctx, block); + if (!slot) + return NULL; + get_bh(&slot->bh); + return &slot->bh; +} + +static void balloc_test_read_bh_nowait_stub(struct buffer_head *bh, + blk_opf_t op_flags, + bio_end_io_t end_io, + bool simu_fail) +{ + struct kunit *test = kunit_get_current_test(); + struct balloc_test_ctx *ctx = test ? test->priv : NULL; + struct balloc_test_blk *slot; + bool fail; + + if (!ctx) { + unlock_buffer(bh); + return; + } + ctx->read_nowait_calls++; + ctx->last_read_op_flags = op_flags; + + if (simu_fail) { + clear_buffer_uptodate(bh); + unlock_buffer(bh); + return; + } + + clear_buffer_verified(bh); + slot = balloc_test_find_blk_by_bh(ctx, bh); + fail = ctx->fail_read_eio || !slot; + if (!fail) + memcpy(bh->b_data, slot->disk_buf, bh->b_size); + + if (end_io) { + struct bio *bio = bio_alloc(NULL, 0, REQ_OP_READ, GFP_KERNEL); + + if (bio) { + bio->bi_private = bh; + bio->bi_status = fail ? BLK_STS_IOERR : BLK_STS_OK; + end_io(bio); + return; + } + } + + if (fail) { + clear_buffer_uptodate(bh); + } else { + set_buffer_uptodate(bh); + set_bitmap_uptodate(bh); + } + unlock_buffer(bh); +} + +static ext4_fsblk_t +balloc_test_mb_new_blocks_stub(handle_t *handle, + struct ext4_allocation_request *ar, int *errp) +{ + struct kunit *test = kunit_get_current_test(); + struct balloc_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) { + *errp = -EIO; + return 0; + } + ctx->mb_new_blocks_calls++; + ctx->last_ar = *ar; + *errp = ctx->mock_alloc_err; + if (ctx->mock_alloc_err) + return 0; + if (ctx->mock_alloc_len) + ar->len = ctx->mock_alloc_len; + return ctx->mock_alloc_blk; +} + +/* --- Fixture Setup & Teardown --- */ + +static void balloc_test_cleanup(struct balloc_test_ctx *ctx) +{ + unsigned int i; + + balloc_test_restore_creds(ctx); + + for (i = 0; i < BALLOC_TEST_POOL_SIZE; i++) { + if (ctx->pool[i].in_use && buffer_locked(&ctx->pool[i].bh)) + unlock_buffer(&ctx->pool[i].bh); + } + + cancel_work_sync(&ctx->sbi.s_discard_work); + ctx->sbi.s_journal = NULL; + + if (ctx->test_inode) { + spin_lock(&ctx->test_inode->i_lock); + inode_state_clear(ctx->test_inode, I_DIRTY_ALL); + spin_unlock(&ctx->test_inode->i_lock); + iput(ctx->test_inode); + ctx->test_inode = NULL; + } + + if (ctx->sb) { + deactivate_super(ctx->sb); + rcu_barrier(); + ctx->sb = NULL; + } + + if (ctx->sra_inited) + percpu_counter_destroy(&ctx->sbi.s_sra_exceeded_retry_limit); + if (ctx->fic_inited) + percpu_counter_destroy(&ctx->sbi.s_freeinodes_counter); + if (ctx->dcc_inited) + percpu_counter_destroy(&ctx->sbi.s_dirtyclusters_counter); + if (ctx->fcc_inited) + percpu_counter_destroy(&ctx->sbi.s_freeclusters_counter); + + kfree(ctx); +} + +KUNIT_DEFINE_ACTION_WRAPPER(balloc_test_cleanup_action, balloc_test_cleanup, + struct balloc_test_ctx *); + +static int balloc_test_init(struct kunit *test) +{ + struct balloc_test_ctx *ctx; + struct fs_context *fc; + struct super_block *sb; + struct ext4_sb_info *sbi; + struct inode *root_inode; + ext4_group_t g; + s64 total_free_clusters = 0; + s64 total_free_inodes = 0; + int err; + + ctx = kzalloc_obj(*ctx); + KUNIT_ASSERT_NOT_NULL(test, ctx); + test->priv = ctx; + + for (g = 0; g < BALLOC_TEST_MAX_GROUPS; g++) { + ctx->grp_infos[g] = kunit_kzalloc(test, + sizeof(*ctx->grp_infos[g]), + GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->grp_infos[g]); + } + + INIT_WORK(&ctx->sbi.s_discard_work, balloc_test_discard_work_fn); + rwlock_init(&ctx->journal.j_state_lock); + + err = kunit_add_action_or_reset(test, balloc_test_cleanup_action, ctx); + KUNIT_ASSERT_EQ(test, err, 0); + + fc = fs_context_for_mount(&balloc_test_fs_type, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(fc)); + sb = sget_fc(fc, NULL, set_anon_super_fc); + put_fs_context(fc); + KUNIT_ASSERT_FALSE(test, IS_ERR(sb)); + + sbi = &ctx->sbi; + sbi->s_sb = sb; + sb->s_fs_info = sbi; + sb->s_op = &balloc_test_sops; +#ifdef CONFIG_QUOTA + sb->dq_op = &balloc_test_qops; +#endif +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; +#endif + sb->s_flags |= SB_ACTIVE; + sb->s_blocksize = BALLOC_TEST_BLK_SIZE; + sb->s_blocksize_bits = BALLOC_TEST_BLK_BITS; + sb->s_maxbytes = MAX_LFS_FILESIZE; + strscpy(sb->s_id, "ext4_balloc_kunit", sizeof(sb->s_id)); + + inode_init_once(&ctx->bd_inode); + ctx->bd_inode.i_sb = sb; + ctx->bd_inode.i_blkbits = BALLOC_TEST_BLK_BITS; + ctx->bd_inode.i_mapping = &ctx->bd_inode.i_data; + ctx->bd_inode.i_data.host = &ctx->bd_inode; + ctx->bdev_queue.limits.logical_block_size = 512; + ctx->bdev_queue.limits.dma_alignment = 511; + ctx->bdev.bd_queue = &ctx->bdev_queue; + ctx->bdev.bd_mapping = &ctx->bd_inode.i_data; + bdev_set_flag(&ctx->bdev, BD_READ_ONLY); + sb->s_bdev = &ctx->bdev; + + root_inode = new_inode(sb); + if (!root_inode) { + deactivate_locked_super(sb); + rcu_barrier(); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc root_inode"); + } + root_inode->i_ino = EXT4_ROOT_INO; + root_inode->i_mode = S_IFDIR | 0755; + root_inode->i_op = &simple_dir_inode_operations; + set_nlink(root_inode, 2); + sb->s_root = d_make_root(root_inode); + if (!sb->s_root) { + deactivate_locked_super(sb); + rcu_barrier(); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc s_root"); + } + + up_write(&sb->s_umount); + ctx->sb = sb; + + bgl_lock_init(&ctx->bgl); + sbi->s_blockgroup_lock = &ctx->bgl; + + sbi->s_es = &ctx->es; + ctx->es.s_magic = cpu_to_le16(EXT4_SUPER_MAGIC); + ctx->es.s_first_data_block = cpu_to_le32(BALLOC_TEST_FIRST_DATA_BLK); + ctx->es.s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + ctx->es.s_inodes_count = cpu_to_le32(BALLOC_TEST_NGROUPS * + BALLOC_TEST_INODES_PER_GRP); + ctx->es.s_inodes_per_group = cpu_to_le32(BALLOC_TEST_INODES_PER_GRP); + ctx->es.s_blocks_per_group = cpu_to_le32(BALLOC_TEST_BLOCKS_PER_GRP); + ctx->es.s_clusters_per_group = cpu_to_le32(BALLOC_TEST_BLOCKS_PER_GRP); + ctx->es.s_inode_size = cpu_to_le16(BALLOC_TEST_INODE_SIZE); + ctx->es.s_checksum_type = EXT4_CRC32C_CHKSUM; + ext4_blocks_count_set(&ctx->es, BALLOC_TEST_TOTAL_BLKS); + + ext4_set_feature_sparse_super(sb); + ext4_set_feature_extents(sb); + ext4_set_feature_metadata_csum(sb); + ext4_set_feature_64bit(sb); + + ctx->sb_bh.b_data = (char *)&ctx->es; + ctx->sb_bh.b_size = sizeof(ctx->es); + ctx->sb_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->sb_bh.b_count, 1); + set_buffer_uptodate(&ctx->sb_bh); + sbi->s_sbh = &ctx->sb_bh; + + for (g = 0; g < BALLOC_TEST_GDESC_BLKS; g++) { + ctx->gdesc_bh[g].b_data = (char *)&ctx->gdps[g * 16]; + ctx->gdesc_bh[g].b_size = BALLOC_TEST_BLK_SIZE; + ctx->gdesc_bh[g].b_blocknr = BALLOC_TEST_GDESC_BLK0 + g; + ctx->gdesc_bh[g].b_bdev = &ctx->bdev; + atomic_set(&ctx->gdesc_bh[g].b_count, 1); + set_buffer_uptodate(&ctx->gdesc_bh[g]); + ctx->gdesc_bh_ptrs[g] = &ctx->gdesc_bh[g]; + } + rcu_assign_pointer(sbi->s_group_desc, ctx->gdesc_bh_ptrs); + + sbi->s_inode_size = BALLOC_TEST_INODE_SIZE; + sbi->s_inodes_per_block = BALLOC_TEST_BLK_SIZE / BALLOC_TEST_INODE_SIZE; + sbi->s_inodes_per_group = BALLOC_TEST_INODES_PER_GRP; + sbi->s_itb_per_group = BALLOC_TEST_ITB_PER_GRP; + sbi->s_blocks_per_group = BALLOC_TEST_BLOCKS_PER_GRP; + sbi->s_clusters_per_group = BALLOC_TEST_BLOCKS_PER_GRP; + sbi->s_cluster_ratio = 1; + sbi->s_cluster_bits = 0; + sbi->s_groups_count = BALLOC_TEST_NGROUPS; + sbi->s_gdb_count = 1; + sbi->s_desc_size = EXT4_MIN_DESC_SIZE_64BIT; + sbi->s_desc_per_block = BALLOC_TEST_BLK_SIZE / EXT4_MIN_DESC_SIZE_64BIT; + sbi->s_desc_per_block_bits = ilog2(sbi->s_desc_per_block); + sbi->s_csum_seed = BALLOC_TEST_CSUM_SEED; + sbi->s_resuid = make_kuid(&init_user_ns, EXT4_DEF_RESUID); + sbi->s_resgid = make_kgid(&init_user_ns, EXT4_DEF_RESGID); + + set_opt(sb, ERRORS_CONT); + set_opt(sb, DELALLOC); + spin_lock_init(&sbi->s_bdev_wb_lock); + spin_lock_init(&sbi->s_error_lock); + spin_lock_init(&sbi->s_md_lock); + + ratelimit_state_init(&sbi->s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + + for (g = 0; g < BALLOC_TEST_MAX_GROUPS; g++) { + init_rwsem(&ctx->grp_infos[g]->alloc_sem); + ctx->grp_infos[g]->bb_state = 0; + if (g < 16) + ctx->grp_info_slice0[g] = ctx->grp_infos[g]; + else + ctx->grp_info_slice1[g - 16] = ctx->grp_infos[g]; + } + ctx->grp_info_slices[0] = ctx->grp_info_slice0; + ctx->grp_info_slices[1] = ctx->grp_info_slice1; + rcu_assign_pointer(sbi->s_group_info, ctx->grp_info_slices); + + for (g = 0; g < BALLOC_TEST_NGROUPS; g++) { + struct balloc_test_blk *bblk; + unsigned int overhead = balloc_test_default_base_blks(g) + + 2U + BALLOC_TEST_ITB_PER_GRP; + u32 free_clu = BALLOC_TEST_BLOCKS_PER_GRP - overhead; + unsigned int bit; + + ext4_block_bitmap_set(sb, &ctx->gdps[g], + balloc_test_bbitmap_blk(g)); + ext4_inode_bitmap_set(sb, &ctx->gdps[g], + balloc_test_ibitmap_blk(g)); + ext4_inode_table_set(sb, &ctx->gdps[g], + balloc_test_itable_blk(g)); + ext4_free_group_clusters_set(sb, &ctx->gdps[g], free_clu); + ext4_free_inodes_set(sb, &ctx->gdps[g], + BALLOC_TEST_INODES_PER_GRP); + ctx->grp_infos[g]->bb_free = free_clu; + + bblk = balloc_test_setup_blk(ctx, balloc_test_bbitmap_blk(g), + true); + KUNIT_ASSERT_NOT_NULL(test, bblk); + + for (bit = 0; bit < overhead; bit++) + ext4_set_bit(bit, bblk->cache_buf); + ext4_mark_bitmap_end(BALLOC_TEST_BLOCKS_PER_GRP, + BALLOC_TEST_BLK_SIZE * 8, + bblk->cache_buf); + set_bitmap_uptodate(&bblk->bh); + set_buffer_verified(&bblk->bh); + balloc_test_sync_bbitmap_csum(ctx, g, true); + + total_free_clusters += free_clu; + total_free_inodes += BALLOC_TEST_INODES_PER_GRP; + } + + err = percpu_counter_init(&sbi->s_freeclusters_counter, + total_free_clusters, GFP_KERNEL); + if (!err) + ctx->fcc_inited = true; + KUNIT_ASSERT_EQ(test, err, 0); + + err = percpu_counter_init(&sbi->s_dirtyclusters_counter, 0, GFP_KERNEL); + if (!err) + ctx->dcc_inited = true; + KUNIT_ASSERT_EQ(test, err, 0); + + err = percpu_counter_init(&sbi->s_freeinodes_counter, + total_free_inodes, GFP_KERNEL); + if (!err) + ctx->fic_inited = true; + KUNIT_ASSERT_EQ(test, err, 0); + + err = percpu_counter_init(&sbi->s_sra_exceeded_retry_limit, 0, + GFP_KERNEL); + if (!err) + ctx->sra_inited = true; + KUNIT_ASSERT_EQ(test, err, 0); + + ctx->test_inode = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, ctx->test_inode); + ctx->test_inode->i_ino = EXT4_FIRST_INO(sb); + ctx->test_inode->i_mode = S_IFREG | 0644; + ctx->test_inode->i_blkbits = BALLOC_TEST_BLK_BITS; + inode_set_bytes(ctx->test_inode, 0); + EXT4_I(ctx->test_inode)->i_block_group = 0; + + kunit_activate_static_stub(test, ext4_sb_getblk, + balloc_test_sb_getblk_stub); + kunit_activate_static_stub(test, ext4_read_bh_nowait, + balloc_test_read_bh_nowait_stub); + kunit_activate_static_stub(test, ext4_mb_new_blocks, + balloc_test_mb_new_blocks_stub); + + return 0; +} + +/* ========================================================================= + * 1. Group Number & Offset Calculation + * ========================================================================= + */ + +struct group_offset_param { + const char *desc; + unsigned char blocksize_bits; + unsigned int cluster_bits; + u32 blocks_per_group; + u32 first_data_block; + bool std_group_size; + ext4_fsblk_t block; + ext4_group_t expected_group; + ext4_grpblk_t expected_offset; +}; + +static const struct group_offset_param group_offset_params[] = { + { + .desc = "std_1k_bg0_first_block", + .blocksize_bits = 10, + .cluster_bits = 0, + .blocks_per_group = 8192, + .first_data_block = 1, + .std_group_size = true, + .block = 1, + .expected_group = 0, + .expected_offset = 0, + }, + { + .desc = "std_1k_bg0_last_block", + .blocksize_bits = 10, + .cluster_bits = 0, + .blocks_per_group = 8192, + .first_data_block = 1, + .std_group_size = true, + .block = 8192, + .expected_group = 0, + .expected_offset = 8191, + }, + { + .desc = "std_1k_bg1_first_block", + .blocksize_bits = 10, + .cluster_bits = 0, + .blocks_per_group = 8192, + .first_data_block = 1, + .std_group_size = true, + .block = 8193, + .expected_group = 1, + .expected_offset = 0, + }, + { + .desc = "std_1k_bg3_interior_block", + .blocksize_bits = 10, + .cluster_bits = 0, + .blocks_per_group = 8192, + .first_data_block = 1, + .std_group_size = true, + .block = 25000, + .expected_group = 3, + .expected_offset = 423, + }, + { + .desc = "std_4k_bg0_last_block", + .blocksize_bits = 12, + .cluster_bits = 0, + .blocks_per_group = 32768, + .first_data_block = 0, + .std_group_size = true, + .block = 32767, + .expected_group = 0, + .expected_offset = 32767, + }, + { + .desc = "std_4k_bg1_first_block", + .blocksize_bits = 12, + .cluster_bits = 0, + .blocks_per_group = 32768, + .first_data_block = 0, + .std_group_size = true, + .block = 32768, + .expected_group = 1, + .expected_offset = 0, + }, + { + .desc = "std_4k_above_32bit_blocknr", + .blocksize_bits = 12, + .cluster_bits = 0, + .blocks_per_group = 32768, + .first_data_block = 0, + .std_group_size = true, + .block = 0x100008005ULL, + .expected_group = 131073, + .expected_offset = 5, + }, + { + .desc = "nonstd_bg0_last_block", + .blocksize_bits = 10, + .cluster_bits = 0, + .blocks_per_group = 1000, + .first_data_block = 1, + .std_group_size = false, + .block = 1000, + .expected_group = 0, + .expected_offset = 999, + }, + { + .desc = "nonstd_bg1_first_block", + .blocksize_bits = 10, + .cluster_bits = 0, + .blocks_per_group = 1000, + .first_data_block = 1, + .std_group_size = false, + .block = 1001, + .expected_group = 1, + .expected_offset = 0, + }, + { + .desc = "nonstd_bg2_interior_block", + .blocksize_bits = 10, + .cluster_bits = 0, + .blocks_per_group = 1000, + .first_data_block = 1, + .std_group_size = false, + .block = 2346, + .expected_group = 2, + .expected_offset = 345, + }, + { + .desc = "bigalloc_std_cluster_start", + .blocksize_bits = 12, + .cluster_bits = 3, + .blocks_per_group = 262144, + .first_data_block = 0, + .std_group_size = true, + .block = 16, + .expected_group = 0, + .expected_offset = 2, + }, + { + .desc = "bigalloc_std_cluster_end_same_offset", + .blocksize_bits = 12, + .cluster_bits = 3, + .blocks_per_group = 262144, + .first_data_block = 0, + .std_group_size = true, + .block = 23, + .expected_group = 0, + .expected_offset = 2, + }, + { + .desc = "bigalloc_std_next_cluster", + .blocksize_bits = 12, + .cluster_bits = 3, + .blocks_per_group = 262144, + .first_data_block = 0, + .std_group_size = true, + .block = 24, + .expected_group = 0, + .expected_offset = 3, + }, + { + .desc = "bigalloc_std_bg2_offset", + .blocksize_bits = 12, + .cluster_bits = 3, + .blocks_per_group = 262144, + .first_data_block = 0, + .std_group_size = true, + .block = 524303, + .expected_group = 2, + .expected_offset = 1, + }, + { + .desc = "bigalloc_nonstd_bg3_offset", + .blocksize_bits = 10, + .cluster_bits = 2, + .blocks_per_group = 600, + .first_data_block = 1, + .std_group_size = false, + .block = 1820, + .expected_group = 3, + .expected_offset = 4, + }, +}; + +static void group_offset_param_get_desc(const struct group_offset_param *p, + char *desc) +{ + strscpy(desc, p->desc, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(group_offset, group_offset_params, + group_offset_param_get_desc); + +static void test_group_no_and_offset_matrix(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + const struct group_offset_param *p = test->param_value; + ext4_group_t grp = 0xdeadbeefU; + ext4_grpblk_t off = 0x7654321; + + sb->s_blocksize_bits = p->blocksize_bits; + sb->s_blocksize = 1UL << p->blocksize_bits; + sbi->s_cluster_bits = p->cluster_bits; + sbi->s_cluster_ratio = 1U << p->cluster_bits; + sbi->s_blocks_per_group = p->blocks_per_group; + sbi->s_clusters_per_group = p->blocks_per_group >> p->cluster_bits; + ctx->es.s_first_data_block = cpu_to_le32(p->first_data_block); + if (p->std_group_size) + set_opt2(sb, STD_GROUP_SIZE); + else + clear_opt2(sb, STD_GROUP_SIZE); + + KUNIT_EXPECT_EQ(test, ext4_get_group_number(sb, p->block), + p->expected_group); + + ext4_get_group_no_and_offset(sb, p->block, &grp, &off); + KUNIT_EXPECT_EQ(test, grp, p->expected_group); + KUNIT_EXPECT_EQ(test, off, p->expected_offset); +} + +static void test_group_no_and_offset_optional_out_ptrs(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + ext4_group_t grp = 999; + ext4_grpblk_t off = 999; + + /* Block 2060 = first_data_block (1) + 2 * 1024 + 11 */ + ext4_get_group_no_and_offset(sb, 2060, &grp, NULL); + KUNIT_EXPECT_EQ(test, grp, 2U); + + ext4_get_group_no_and_offset(sb, 2060, NULL, &off); + KUNIT_EXPECT_EQ(test, off, 11); + + /* Both output pointers NULL must be a safe no-op */ + ext4_get_group_no_and_offset(sb, 2060, NULL, NULL); +} + +/* ========================================================================= + * 2. Backup Superblock Placement (ext4_bg_has_super) + * ========================================================================= + */ + +static void test_bg_has_super_dense_all_groups(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + static const ext4_group_t groups[] = { 0, 1, 2, 3, 4, 6, 8, 15, 22 }; + unsigned int i; + + ext4_clear_feature_sparse_super(sb); + ext4_clear_feature_sparse_super2(sb); + + for (i = 0; i < ARRAY_SIZE(groups); i++) + KUNIT_EXPECT_EQ_MSG(test, ext4_bg_has_super(sb, groups[i]), 1, + "dense group %u should have super", + groups[i]); +} + +static void test_bg_has_super_sparse_super_powers(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + static const ext4_group_t with_super[] = { + 0, 1, 3, 9, 27, 81, 5, 25, 125, 7, 49, 343 + }; + static const ext4_group_t without_super[] = { + 2, 4, 6, 8, 10, 11, 15, 21, 35, 45, 63, 77 + }; + unsigned int i; + + ext4_set_feature_sparse_super(sb); + ext4_clear_feature_sparse_super2(sb); + + for (i = 0; i < ARRAY_SIZE(with_super); i++) + KUNIT_EXPECT_EQ_MSG(test, ext4_bg_has_super(sb, with_super[i]), + 1, "sparse_super group %u expected 1", + with_super[i]); + + for (i = 0; i < ARRAY_SIZE(without_super); i++) + KUNIT_EXPECT_EQ_MSG(test, + ext4_bg_has_super(sb, without_super[i]), 0, + "sparse_super group %u expected 0", + without_super[i]); +} + +static void test_bg_has_super_sparse_super2_explicit_backups(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + + ext4_set_feature_sparse_super2(sb); + ctx->es.s_backup_bgs[0] = cpu_to_le32(6); + ctx->es.s_backup_bgs[1] = cpu_to_le32(42); + + KUNIT_EXPECT_EQ(test, ext4_bg_has_super(sb, 0), 1); + KUNIT_EXPECT_EQ(test, ext4_bg_has_super(sb, 6), 1); + KUNIT_EXPECT_EQ(test, ext4_bg_has_super(sb, 42), 1); + KUNIT_EXPECT_EQ(test, ext4_bg_has_super(sb, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_bg_has_super(sb, 3), 0); + KUNIT_EXPECT_EQ(test, ext4_bg_has_super(sb, 5), 0); + KUNIT_EXPECT_EQ(test, ext4_bg_has_super(sb, 7), 0); + + /* Single backup group configured (s_backup_bgs[1] == 0) */ + ctx->es.s_backup_bgs[0] = cpu_to_le32(12); + ctx->es.s_backup_bgs[1] = cpu_to_le32(0); + KUNIT_EXPECT_EQ(test, ext4_bg_has_super(sb, 0), 1); + KUNIT_EXPECT_EQ(test, ext4_bg_has_super(sb, 12), 1); + KUNIT_EXPECT_EQ(test, ext4_bg_has_super(sb, 6), 0); + KUNIT_EXPECT_EQ(test, ext4_bg_has_super(sb, 42), 0); +} + +/* ========================================================================= + * 3. GDT & Base Metadata Blocks (ext4_bg_num_gdb, ext4_num_base_meta_blocks) + * ========================================================================= + */ + +static void test_bg_num_gdb_and_base_meta_non_metabg(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + + ext4_clear_feature_meta_bg(sb); + ext4_set_feature_sparse_super(sb); + ctx->sbi.s_gdb_count = 4; + ctx->es.s_reserved_gdt_blocks = cpu_to_le16(7); + + /* Groups with super: 1 super + 4 gdb + 7 reserved_gdt = 12 blocks */ + KUNIT_EXPECT_EQ(test, ext4_bg_num_gdb(sb, 0), 4UL); + KUNIT_EXPECT_EQ(test, ext4_num_base_meta_blocks(sb, 0), 12U); + KUNIT_EXPECT_EQ(test, ext4_bg_num_gdb(sb, 3), 4UL); + KUNIT_EXPECT_EQ(test, ext4_num_base_meta_blocks(sb, 3), 12U); + + /* Groups without super: 0 gdb and reserved_gdt is not present */ + KUNIT_EXPECT_EQ(test, ext4_bg_num_gdb(sb, 2), 0UL); + KUNIT_EXPECT_EQ(test, ext4_num_base_meta_blocks(sb, 2), 0U); + KUNIT_EXPECT_EQ(test, ext4_bg_num_gdb(sb, 15), 0UL); + KUNIT_EXPECT_EQ(test, ext4_num_base_meta_blocks(sb, 15), 0U); +} + +static void test_bg_num_gdb_and_base_meta_hybrid_metabg(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + + /* + * s_desc_per_block = 16, s_first_meta_bg = 2: + * - Groups 0..31 (metagroups 0..1) use traditional GDT layout with + * s_first_meta_bg (2) GDT blocks + s_reserved_gdt_blocks (9) when + * backup super is present. + * - Groups >= 32 (metagroups >= 2) place 1 descriptor block in the + * 1st, 2nd, and last group of each 16-group metagroup, with no + * reserved GDT blocks. + */ + ext4_set_feature_meta_bg(sb); + ext4_set_feature_sparse_super(sb); + ctx->sbi.s_gdb_count = 5; + ctx->es.s_first_meta_bg = cpu_to_le32(2); + ctx->es.s_reserved_gdt_blocks = cpu_to_le16(9); + + /* Pre-meta_bg groups with super: 1 + 2 + 9 = 12 */ + KUNIT_EXPECT_EQ(test, ext4_bg_num_gdb(sb, 0), 2UL); + KUNIT_EXPECT_EQ(test, ext4_num_base_meta_blocks(sb, 0), 12U); + KUNIT_EXPECT_EQ(test, ext4_bg_num_gdb(sb, 27), 2UL); + KUNIT_EXPECT_EQ(test, ext4_num_base_meta_blocks(sb, 27), 12U); + + /* Pre-meta_bg groups without super */ + KUNIT_EXPECT_EQ(test, ext4_bg_num_gdb(sb, 2), 0UL); + KUNIT_EXPECT_EQ(test, ext4_num_base_meta_blocks(sb, 2), 0U); + KUNIT_EXPECT_EQ(test, ext4_bg_num_gdb(sb, 31), 0UL); + KUNIT_EXPECT_EQ(test, ext4_num_base_meta_blocks(sb, 31), 0U); + + /* Metagroup 2 (groups 32..47): first=32, second=33, last=47 (no super) */ + KUNIT_EXPECT_EQ(test, ext4_bg_num_gdb(sb, 32), 1UL); + KUNIT_EXPECT_EQ(test, ext4_num_base_meta_blocks(sb, 32), 1U); + KUNIT_EXPECT_EQ(test, ext4_bg_num_gdb(sb, 33), 1UL); + KUNIT_EXPECT_EQ(test, ext4_num_base_meta_blocks(sb, 33), 1U); + KUNIT_EXPECT_EQ(test, ext4_bg_num_gdb(sb, 47), 1UL); + KUNIT_EXPECT_EQ(test, ext4_num_base_meta_blocks(sb, 47), 1U); + + /* Interior meta_bg group with neither super nor meta gdb */ + KUNIT_EXPECT_EQ(test, ext4_bg_num_gdb(sb, 34), 0UL); + KUNIT_EXPECT_EQ(test, ext4_num_base_meta_blocks(sb, 34), 0U); + + /* Group 125 (5^3 in metagroup 112..127): super=1, meta_gdb=0 -> 1 */ + KUNIT_EXPECT_EQ(test, ext4_bg_num_gdb(sb, 125), 0UL); + KUNIT_EXPECT_EQ(test, ext4_num_base_meta_blocks(sb, 125), 1U); + + /* Group 49 (7^2, second of 48..63): super=1, meta_gdb=1 -> 2 */ + KUNIT_EXPECT_EQ(test, ext4_bg_num_gdb(sb, 49), 1UL); + KUNIT_EXPECT_EQ(test, ext4_num_base_meta_blocks(sb, 49), 2U); +} + +/* ========================================================================= + * 4. Overhead & Free Clusters After Init (ext4_free_clusters_after_init) + * ========================================================================= + */ + +static void +test_free_clusters_after_init_standard_and_partial_last(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + + KUNIT_EXPECT_EQ(test, + ext4_free_clusters_after_init(sb, 0, &ctx->gdps[0]), + 1004U); + KUNIT_EXPECT_EQ(test, + ext4_free_clusters_after_init(sb, 2, &ctx->gdps[2]), + 1006U); + + /* Shrink total blocks so last group 3 has only 300 blocks (20 overhead) */ + ext4_blocks_count_set(&ctx->es, balloc_test_group_start(3) + 300); + KUNIT_EXPECT_EQ(test, + ext4_free_clusters_after_init(sb, 3, &ctx->gdps[3]), + 280U); + /* Non-last group 1 still uses full s_blocks_per_group (1024) */ + KUNIT_EXPECT_EQ(test, + ext4_free_clusters_after_init(sb, 1, &ctx->gdps[1]), + 1004U); +} + +static void +test_free_clusters_after_init_external_and_spanning_meta(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + ext4_fsblk_t g2_start = balloc_test_group_start(2); + + /* + * Group 2 has 0 base metadata blocks. Relocate its bitmaps and inode + * table into group 0 -> 0 overhead clusters in group 2 -> 1024 free. + */ + ext4_block_bitmap_set(sb, &ctx->gdps[2], balloc_test_group_start(0) + 50); + ext4_inode_bitmap_set(sb, &ctx->gdps[2], balloc_test_group_start(0) + 51); + ext4_inode_table_set(sb, &ctx->gdps[2], balloc_test_group_start(0) + 52); + KUNIT_EXPECT_EQ(test, + ext4_free_clusters_after_init(sb, 2, &ctx->gdps[2]), + 1024U); + + /* + * Inode table of 16 blocks starting 6 blocks before group 2 overlaps + * 10 blocks [g2_start .. g2_start + 9] inside group 2 -> 1014 free. + */ + ext4_inode_table_set(sb, &ctx->gdps[2], g2_start - 6); + KUNIT_EXPECT_EQ(test, + ext4_free_clusters_after_init(sb, 2, &ctx->gdps[2]), + 1014U); + + /* + * Inode table starting 5 blocks before end of group 2 overlaps 5 + * blocks [g2_end - 4 .. g2_end] inside group 2 -> 1019 free. + */ + ext4_inode_table_set(sb, &ctx->gdps[2], + g2_start + BALLOC_TEST_BLOCKS_PER_GRP - 5); + KUNIT_EXPECT_EQ(test, + ext4_free_clusters_after_init(sb, 2, &ctx->gdps[2]), + 1019U); +} + +static void +test_free_clusters_after_init_bigalloc_cluster_sharing(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + ext4_fsblk_t g1_start = balloc_test_group_start(1); + ext4_fsblk_t g2_start = balloc_test_group_start(2); + + /* 4 blocks per cluster -> 1024 / 4 = 256 clusters per full group */ + sbi->s_cluster_bits = 2; + sbi->s_cluster_ratio = 4; + sbi->s_clusters_per_group = 256; + sbi->s_itb_per_group = 8; + + /* + * Case 1 (border overlap with base_clusters): + * Group 1 has 2 base blocks (offsets 0..1 -> base_clusters = 1, clu 0). + * Place 8-block itable at offsets 2..9 (clusters 0..2, overlapping + * border clu 0), bbitmap at offset 12 (clu 3), ibitmap at offset 16 + * (clu 4) -> 5 unique overhead clusters (0..4) -> 251 free clusters. + */ + ext4_inode_table_set(sb, &ctx->gdps[1], g1_start + 2); + ext4_block_bitmap_set(sb, &ctx->gdps[1], g1_start + 12); + ext4_inode_bitmap_set(sb, &ctx->gdps[1], g1_start + 16); + KUNIT_EXPECT_EQ(test, + ext4_free_clusters_after_init(sb, 1, &ctx->gdps[1]), + 251U); + + /* + * Case 2 (bitmaps inside base_clusters): + * Base blocks at offsets 0..1 (clu 0), bbitmap at offset 2 (clu 0), + * ibitmap at offset 3 (clu 0), 8-block itable at offsets 4..11 + * (clusters 1..2) -> 3 overhead clusters (0..2) -> 253 free clusters. + */ + ext4_block_bitmap_set(sb, &ctx->gdps[1], g1_start + 2); + ext4_inode_bitmap_set(sb, &ctx->gdps[1], g1_start + 3); + ext4_inode_table_set(sb, &ctx->gdps[1], g1_start + 4); + KUNIT_EXPECT_EQ(test, + ext4_free_clusters_after_init(sb, 1, &ctx->gdps[1]), + 253U); + + /* + * Case 3 (bbitmap and ibitmap sharing the same non-base cluster): + * Group 2 has 0 base clusters. bbitmap at offset 0 (clu 0), ibitmap at + * offset 1 (clu 0), 8-block itable at offsets 4..11 (clusters 1..2) -> + * 3 overhead clusters -> 253 free clusters. + */ + ext4_block_bitmap_set(sb, &ctx->gdps[2], g2_start + 0); + ext4_inode_bitmap_set(sb, &ctx->gdps[2], g2_start + 1); + ext4_inode_table_set(sb, &ctx->gdps[2], g2_start + 4); + KUNIT_EXPECT_EQ(test, + ext4_free_clusters_after_init(sb, 2, &ctx->gdps[2]), + 253U); + + /* + * Case 4 (bitmaps sharing tail cluster of inode table): + * Group 2 with 6-block itable at offsets 0..5 (clusters 0..1), bbitmap + * at offset 6 (clu 1), ibitmap at offset 7 (clu 1) -> 2 overhead + * clusters (0..1) -> 254 free clusters. + */ + sbi->s_itb_per_group = 6; + ext4_inode_table_set(sb, &ctx->gdps[2], g2_start + 0); + ext4_block_bitmap_set(sb, &ctx->gdps[2], g2_start + 6); + ext4_inode_bitmap_set(sb, &ctx->gdps[2], g2_start + 7); + KUNIT_EXPECT_EQ(test, + ext4_free_clusters_after_init(sb, 2, &ctx->gdps[2]), + 254U); + + /* + * Case 5 (partial last group rounding up blocks to clusters): + * Group 3 with 301 blocks -> EXT4_NUM_B2C(4, 301) = 76 clusters; + * external metadata -> 0 overhead in group 3 -> 76 free clusters. + */ + ext4_blocks_count_set(&ctx->es, balloc_test_group_start(3) + 301); + ext4_block_bitmap_set(sb, &ctx->gdps[3], balloc_test_group_start(0) + 40); + ext4_inode_bitmap_set(sb, &ctx->gdps[3], balloc_test_group_start(0) + 44); + ext4_inode_table_set(sb, &ctx->gdps[3], balloc_test_group_start(0) + 48); + /* Group 3 has 2 base blocks = 1 base cluster -> 76 - 1 = 75 free */ + KUNIT_EXPECT_EQ(test, + ext4_free_clusters_after_init(sb, 3, &ctx->gdps[3]), + 75U); +} + +/* ========================================================================= + * 5. Group Descriptor & Group Info Lookup + * ========================================================================= + */ + +static void test_get_group_desc_lookup_and_bounds(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct buffer_head *bh = NULL; + struct ext4_group_desc *desc; + + /* Expand to 20 groups spanning gdesc_bh[0] (0..15) and gdesc_bh[1] (16..19) */ + ctx->sbi.s_groups_count = 20; + + desc = ext4_get_group_desc(sb, 0, &bh); + KUNIT_EXPECT_PTR_EQ(test, desc, &ctx->gdps[0]); + KUNIT_EXPECT_PTR_EQ(test, bh, &ctx->gdesc_bh[0]); + + desc = ext4_get_group_desc(sb, 15, &bh); + KUNIT_EXPECT_PTR_EQ(test, desc, &ctx->gdps[15]); + KUNIT_EXPECT_PTR_EQ(test, bh, &ctx->gdesc_bh[0]); + + desc = ext4_get_group_desc(sb, 16, &bh); + KUNIT_EXPECT_PTR_EQ(test, desc, &ctx->gdps[16]); + KUNIT_EXPECT_PTR_EQ(test, bh, &ctx->gdesc_bh[1]); + + desc = ext4_get_group_desc(sb, 19, NULL); + KUNIT_EXPECT_PTR_EQ(test, desc, &ctx->gdps[19]); + + /* Out-of-range block_group >= s_groups_count returns NULL */ + ctx->sbi.s_mount_state &= ~EXT4_ERROR_FS; + KUNIT_EXPECT_NULL(test, ext4_get_group_desc(sb, 20, &bh)); + KUNIT_EXPECT_TRUE(test, !!(ctx->sbi.s_mount_state & EXT4_ERROR_FS)); + + /* Missing group descriptor buffer_head slot returns NULL */ + ctx->gdesc_bh_ptrs[1] = NULL; + ctx->sbi.s_mount_state &= ~EXT4_ERROR_FS; + KUNIT_EXPECT_NULL(test, ext4_get_group_desc(sb, 16, &bh)); + KUNIT_EXPECT_TRUE(test, !!(ctx->sbi.s_mount_state & EXT4_ERROR_FS)); +} + +static void test_get_group_info_lookup_and_null_guards(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + + ctx->sbi.s_groups_count = 20; + + KUNIT_EXPECT_PTR_EQ(test, ext4_get_group_info(sb, 0), + ctx->grp_infos[0]); + KUNIT_EXPECT_PTR_EQ(test, ext4_get_group_info(sb, 15), + ctx->grp_infos[15]); + KUNIT_EXPECT_PTR_EQ(test, ext4_get_group_info(sb, 16), + ctx->grp_infos[16]); + KUNIT_EXPECT_PTR_EQ(test, ext4_get_group_info(sb, 19), + ctx->grp_infos[19]); + + /* Out-of-bounds group returns NULL */ + KUNIT_EXPECT_NULL(test, ext4_get_group_info(sb, 20)); + + /* NULL second-level slice returns NULL only for that slice */ + ctx->grp_info_slices[1] = NULL; + KUNIT_EXPECT_PTR_EQ(test, ext4_get_group_info(sb, 15), + ctx->grp_infos[15]); + KUNIT_EXPECT_NULL(test, ext4_get_group_info(sb, 16)); + + /* NULL s_group_info table returns NULL */ + rcu_assign_pointer(ctx->sbi.s_group_info, NULL); + KUNIT_EXPECT_NULL(test, ext4_get_group_info(sb, 0)); +} + +/* ========================================================================= + * 6. Block Bitmap Validation (CSUM, Metadata Self-Checks, Padding, Flags) + * ========================================================================= + */ + +static void test_read_block_bitmap_validates_csum(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct balloc_test_blk *slot; + struct buffer_head *bh; + s64 free_before; + + slot = balloc_test_find_blk(ctx, balloc_test_bbitmap_blk(1)); + KUNIT_ASSERT_NOT_NULL(test, slot); + + /* 1. Unverified buffer with valid CRC32C verifies and sets BH_Verified */ + clear_buffer_verified(&slot->bh); + bh = ext4_read_block_bitmap(sb, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + KUNIT_EXPECT_TRUE(test, buffer_verified(bh)); + KUNIT_EXPECT_FALSE(test, EXT4_MB_GRP_BBITMAP_CORRUPT(ctx->grp_infos[1])); + put_bh(bh); + +#ifdef CONFIG_EXT4_DEBUG + /* Simulated CRC failure triggers -EFSBADCRC and resets s_simulate_fail */ + clear_buffer_verified(&slot->bh); + ctx->sbi.s_simulate_fail = EXT4_SIM_BBITMAP_CRC; + bh = ext4_read_block_bitmap(sb, 1); + KUNIT_EXPECT_EQ(test, PTR_ERR(bh), -EFSBADCRC); + KUNIT_EXPECT_EQ(test, ctx->sbi.s_simulate_fail, 0UL); + ctx->grp_infos[1]->bb_state = 0; + percpu_counter_add(&ctx->sbi.s_freeclusters_counter, + ctx->grp_infos[1]->bb_free); +#endif + + /* 2. Corrupting free-space bit without updating csum -> -EFSBADCRC */ + free_before = percpu_counter_sum(&ctx->sbi.s_freeclusters_counter); + clear_buffer_verified(&slot->bh); + slot->cache_buf[40] ^= 0x01; + + bh = ext4_read_block_bitmap(sb, 1); + KUNIT_EXPECT_TRUE(test, IS_ERR(bh)); + KUNIT_EXPECT_EQ(test, PTR_ERR(bh), -EFSBADCRC); + KUNIT_EXPECT_TRUE(test, EXT4_MB_GRP_BBITMAP_CORRUPT(ctx->grp_infos[1])); + KUNIT_EXPECT_EQ(test, + percpu_counter_sum(&ctx->sbi.s_freeclusters_counter), + free_before - ctx->grp_infos[1]->bb_free); + + /* + * 3. Subsequent read on already-corrupt group returns -EFSCORRUPTED + * immediately without subtracting bb_free a second time. + */ + slot->cache_buf[40] ^= 0x01; + bh = ext4_read_block_bitmap(sb, 1); + KUNIT_EXPECT_TRUE(test, IS_ERR(bh)); + KUNIT_EXPECT_EQ(test, PTR_ERR(bh), -EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, + percpu_counter_sum(&ctx->sbi.s_freeclusters_counter), + free_before - ctx->grp_infos[1]->bb_free); +} + +static void test_read_block_bitmap_validates_metadata_bits(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct balloc_test_blk *slot; + struct buffer_head *bh; + static const unsigned int meta_bits[] = { + 0, /* block bitmap in group 2 */ + 1, /* inode bitmap in group 2 */ + 2, /* first inode table block in group 2 */ + 10, /* middle inode table block in group 2 */ + 17, /* last inode table block in group 2 */ + }; + unsigned int i; + + slot = balloc_test_find_blk(ctx, balloc_test_bbitmap_blk(2)); + KUNIT_ASSERT_NOT_NULL(test, slot); + + /* Clearing any in-group metadata bit (with valid CRC) -> -EFSCORRUPTED */ + for (i = 0; i < ARRAY_SIZE(meta_bits); i++) { + ctx->grp_infos[2]->bb_state = 0; + clear_buffer_verified(&slot->bh); + ext4_clear_bit(meta_bits[i], slot->cache_buf); + balloc_test_sync_bbitmap_csum(ctx, 2, false); + + bh = ext4_read_block_bitmap(sb, 2); + KUNIT_EXPECT_EQ_MSG(test, PTR_ERR_OR_ZERO(bh), -EFSCORRUPTED, + "cleared bit %u should fail validation", + meta_bits[i]); + KUNIT_EXPECT_TRUE_MSG(test, + EXT4_MB_GRP_BBITMAP_CORRUPT(ctx->grp_infos[2]), + "bit %u should mark BBITMAP_CORRUPT", + meta_bits[i]); + + ext4_set_bit(meta_bits[i], slot->cache_buf); + } + + /* Out-of-group block bitmap (< start and >= end) without FLEX_BG */ + { + struct balloc_test_blk *slot1, *slot3; + + slot1 = balloc_test_find_blk(ctx, balloc_test_bbitmap_blk(1)); + slot3 = balloc_test_find_blk(ctx, balloc_test_bbitmap_blk(3)); + KUNIT_ASSERT_NOT_NULL(test, slot1); + KUNIT_ASSERT_NOT_NULL(test, slot3); + + ctx->grp_infos[2]->bb_state = 0; + clear_buffer_verified(&slot1->bh); + ext4_block_bitmap_set(sb, &ctx->gdps[2], + balloc_test_bbitmap_blk(1)); + balloc_test_sync_bbitmap_csum(ctx, 2, false); + bh = ext4_read_block_bitmap(sb, 2); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EFSCORRUPTED); + + ctx->grp_infos[2]->bb_state = 0; + clear_buffer_verified(&slot3->bh); + ext4_block_bitmap_set(sb, &ctx->gdps[2], + balloc_test_bbitmap_blk(3)); + balloc_test_sync_bbitmap_csum(ctx, 2, false); + bh = ext4_read_block_bitmap(sb, 2); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EFSCORRUPTED); + + ext4_block_bitmap_set(sb, &ctx->gdps[2], + balloc_test_bbitmap_blk(2)); + balloc_test_sync_bbitmap_csum(ctx, 1, false); + balloc_test_sync_bbitmap_csum(ctx, 3, false); + } + + /* Out-of-group inode bitmap without FLEX_BG -> -EFSCORRUPTED */ + ctx->grp_infos[2]->bb_state = 0; + clear_buffer_verified(&slot->bh); + ext4_inode_bitmap_set(sb, &ctx->gdps[2], balloc_test_group_start(0) + 5); + balloc_test_sync_bbitmap_csum(ctx, 2, false); + bh = ext4_read_block_bitmap(sb, 2); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EFSCORRUPTED); + ext4_inode_bitmap_set(sb, &ctx->gdps[2], balloc_test_ibitmap_blk(2)); + + /* Inode table before start or past end of group without FLEX_BG */ + ctx->grp_infos[2]->bb_state = 0; + clear_buffer_verified(&slot->bh); + ext4_inode_table_set(sb, &ctx->gdps[2], balloc_test_group_start(1) + 50); + balloc_test_sync_bbitmap_csum(ctx, 2, false); + bh = ext4_read_block_bitmap(sb, 2); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EFSCORRUPTED); + + ctx->grp_infos[2]->bb_state = 0; + clear_buffer_verified(&slot->bh); + ext4_inode_table_set(sb, &ctx->gdps[2], + balloc_test_group_start(2) + + BALLOC_TEST_BLOCKS_PER_GRP - 8); + balloc_test_sync_bbitmap_csum(ctx, 2, false); + bh = ext4_read_block_bitmap(sb, 2); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EFSCORRUPTED); + + /* With FLEX_BG enabled, out-of-group metadata skips per-group bit check */ + ext4_set_feature_flex_bg(sb); + ctx->grp_infos[2]->bb_state = 0; + clear_buffer_verified(&slot->bh); + ext4_inode_bitmap_set(sb, &ctx->gdps[2], balloc_test_group_start(0) + 5); + ext4_inode_table_set(sb, &ctx->gdps[2], balloc_test_group_start(0) + 20); + ext4_clear_bit(1, slot->cache_buf); + ext4_clear_bit(2, slot->cache_buf); + balloc_test_sync_bbitmap_csum(ctx, 2, false); + + bh = ext4_read_block_bitmap(sb, 2); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + KUNIT_EXPECT_TRUE(test, buffer_verified(bh)); + put_bh(bh); +} + +static void test_read_block_bitmap_validates_padding(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct balloc_test_blk *slot; + struct buffer_head *bh; + + slot = balloc_test_find_blk(ctx, balloc_test_bbitmap_blk(3)); + KUNIT_ASSERT_NOT_NULL(test, slot); + + /* 1. Zero bit at first padding bit (1024) -> -EFSCORRUPTED */ + clear_buffer_verified(&slot->bh); + ext4_clear_bit(1024, slot->cache_buf); + balloc_test_sync_bbitmap_csum(ctx, 3, false); + bh = ext4_read_block_bitmap(sb, 3); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EFSCORRUPTED); + KUNIT_EXPECT_TRUE(test, EXT4_MB_GRP_BBITMAP_CORRUPT(ctx->grp_infos[3])); + ext4_set_bit(1024, slot->cache_buf); + + /* 2. Zero bit at very last bit of bitmap block (8191) -> -EFSCORRUPTED */ + ctx->grp_infos[3]->bb_state = 0; + clear_buffer_verified(&slot->bh); + ext4_clear_bit(8191, slot->cache_buf); + balloc_test_sync_bbitmap_csum(ctx, 3, false); + bh = ext4_read_block_bitmap(sb, 3); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EFSCORRUPTED); + ext4_set_bit(8191, slot->cache_buf); + + /* 3. Partial last group (300 blocks): unset bit 300 in padding fails */ + ctx->grp_infos[3]->bb_state = 0; + clear_buffer_verified(&slot->bh); + ext4_blocks_count_set(&ctx->es, balloc_test_group_start(3) + 300); + balloc_test_sync_bbitmap_csum(ctx, 3, false); + bh = ext4_read_block_bitmap(sb, 3); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EFSCORRUPTED); + + /* Setting padding bits 300..1023 makes the partial last group valid */ + ctx->grp_infos[3]->bb_state = 0; + clear_buffer_verified(&slot->bh); + ext4_mark_bitmap_end(300, BALLOC_TEST_BLK_SIZE * 8, slot->cache_buf); + balloc_test_sync_bbitmap_csum(ctx, 3, false); + bh = ext4_read_block_bitmap(sb, 3); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + KUNIT_EXPECT_TRUE(test, buffer_verified(bh)); + put_bh(bh); + + /* 4. Full 8192-cluster group (bitmap_size == offset) has no padding */ + ctx->sbi.s_blocks_per_group = 8192; + ctx->sbi.s_clusters_per_group = 8192; + ctx->es.s_blocks_per_group = cpu_to_le32(8192); + ctx->es.s_clusters_per_group = cpu_to_le32(8192); + ext4_blocks_count_set(&ctx->es, 1 + 4 * 8192); + + slot = balloc_test_find_blk(ctx, balloc_test_bbitmap_blk(0)); + KUNIT_ASSERT_NOT_NULL(test, slot); + clear_buffer_verified(&slot->bh); + ext4_clear_bit(8191, slot->cache_buf); + balloc_test_sync_bbitmap_csum(ctx, 0, false); + + bh = ext4_read_block_bitmap(sb, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + KUNIT_EXPECT_TRUE(test, buffer_verified(bh)); + put_bh(bh); +} + +static void test_read_block_bitmap_validation_short_circuits(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct balloc_test_blk *slot; + struct buffer_head *bh; + + slot = balloc_test_find_blk(ctx, balloc_test_bbitmap_blk(1)); + KUNIT_ASSERT_NOT_NULL(test, slot); + + /* + * 1. EXT4_FC_REPLAY skips csum and corrupt-flag checks without setting + * BH_Verified. + */ + clear_buffer_verified(&slot->bh); + slot->cache_buf[50] ^= 0xff; + set_bit(EXT4_GROUP_INFO_BBITMAP_CORRUPT_BIT, + &ctx->grp_infos[1]->bb_state); + ctx->sbi.s_mount_state |= EXT4_FC_REPLAY; + + bh = ext4_read_block_bitmap(sb, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + KUNIT_EXPECT_FALSE(test, buffer_verified(bh)); + put_bh(bh); + + ctx->sbi.s_mount_state &= ~EXT4_FC_REPLAY; + slot->cache_buf[50] ^= 0xff; + + /* 2. Already buffer_verified(bh) short-circuits before checking grp */ + set_buffer_verified(&slot->bh); + bh = ext4_read_block_bitmap(sb, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + put_bh(bh); + + /* 3. NULL ext4_group_info when !buffer_verified returns -EFSCORRUPTED */ + clear_buffer_verified(&slot->bh); + ctx->grp_infos[1]->bb_state = 0; + rcu_assign_pointer(ctx->sbi.s_group_info, NULL); + bh = ext4_read_block_bitmap(sb, 1); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EFSCORRUPTED); +} + +/* ========================================================================= + * 7. Block Bitmap Reading, Prefetching, and Lazy Initialization + * ========================================================================= + */ + +static void test_read_block_bitmap_disk_and_cache_paths(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct balloc_test_blk *slot; + struct buffer_head *bh; + + slot = balloc_test_find_blk(ctx, balloc_test_bbitmap_blk(1)); + KUNIT_ASSERT_NOT_NULL(test, slot); + + /* 1. Cold read from disk populates cache, runs end_io, and validates */ + memset(slot->cache_buf, 0, sizeof(slot->cache_buf)); + clear_buffer_uptodate(&slot->bh); + clear_bitmap_uptodate(&slot->bh); + clear_buffer_verified(&slot->bh); + + bh = ext4_read_block_bitmap(sb, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + KUNIT_EXPECT_EQ(test, ctx->read_nowait_calls, 1U); + KUNIT_EXPECT_TRUE(test, ctx->last_read_op_flags == + (blk_opf_t)(REQ_META | REQ_PRIO)); + KUNIT_EXPECT_TRUE(test, buffer_uptodate(bh)); + KUNIT_EXPECT_TRUE(test, (bool)bitmap_uptodate(bh)); + KUNIT_EXPECT_TRUE(test, buffer_verified(bh)); + KUNIT_EXPECT_FALSE(test, buffer_new(bh)); + put_bh(bh); + + /* 2. Warm read hits bitmap_uptodate(bh) without issuing I/O */ + bh = ext4_read_block_bitmap(sb, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + KUNIT_EXPECT_EQ(test, ctx->read_nowait_calls, 1U); + put_bh(bh); + + /* + * 3. Initialized group with BH_Uptodate set and BH_BITMAP_UPTODATE + * clear promotes BH_BITMAP_UPTODATE and validates without disk I/O. + */ + clear_bitmap_uptodate(&slot->bh); + clear_buffer_verified(&slot->bh); + bh = ext4_read_block_bitmap(sb, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + KUNIT_EXPECT_EQ(test, ctx->read_nowait_calls, 1U); + KUNIT_EXPECT_TRUE(test, (bool)bitmap_uptodate(bh)); + KUNIT_EXPECT_TRUE(test, buffer_verified(bh)); + put_bh(bh); +} + +static void test_read_block_bitmap_nowait_prefetch_locked(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct balloc_test_blk *slot; + struct buffer_head *bh; + int ref_before; + + slot = balloc_test_find_blk(ctx, balloc_test_bbitmap_blk(2)); + KUNIT_ASSERT_NOT_NULL(test, slot); + + /* 1. Locked buffer with ignore_locked=true returns NULL without leaking ref */ + ref_before = atomic_read(&slot->bh.b_count); + lock_buffer(&slot->bh); + bh = ext4_read_block_bitmap_nowait(sb, 2, true); + unlock_buffer(&slot->bh); + + KUNIT_EXPECT_NULL(test, bh); + KUNIT_EXPECT_EQ(test, atomic_read(&slot->bh.b_count), ref_before); + KUNIT_EXPECT_EQ(test, ctx->read_nowait_calls, 0U); + + /* 2. Uncached unlocked buffer with ignore_locked=true sets REQ_RAHEAD */ + clear_buffer_uptodate(&slot->bh); + clear_bitmap_uptodate(&slot->bh); + clear_buffer_verified(&slot->bh); + + bh = ext4_read_block_bitmap_nowait(sb, 2, true); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, bh); + KUNIT_EXPECT_EQ(test, ctx->read_nowait_calls, 1U); + KUNIT_EXPECT_TRUE(test, ctx->last_read_op_flags == + (blk_opf_t)(REQ_META | REQ_PRIO | REQ_RAHEAD)); + KUNIT_EXPECT_EQ(test, ext4_wait_block_bitmap(sb, 2, bh), 0); + put_bh(bh); +} + +static void test_read_block_bitmap_uninit_group(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct balloc_test_blk *slot; + struct buffer_head *bh; + unsigned int bit; + + slot = balloc_test_find_blk(ctx, balloc_test_bbitmap_blk(1)); + KUNIT_ASSERT_NOT_NULL(test, slot); + + /* + * Mark group 1 EXT4_BG_BLOCK_UNINIT and poison cache_buf with 0xa5. + * Lazy init must zero the bitmap, set metadata bits 0..19, leave + * data bits 20..1023 free, set padding bits 1024..8191, and skip I/O. + */ + memset(slot->cache_buf, 0xa5, sizeof(slot->cache_buf)); + clear_buffer_uptodate(&slot->bh); + clear_bitmap_uptodate(&slot->bh); + clear_buffer_verified(&slot->bh); + ctx->gdps[1].bg_flags = cpu_to_le16(EXT4_BG_BLOCK_UNINIT); + ext4_group_desc_csum_set(sb, 1, &ctx->gdps[1]); + + bh = ext4_read_block_bitmap(sb, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + KUNIT_EXPECT_EQ(test, ctx->read_nowait_calls, 0U); + KUNIT_EXPECT_TRUE(test, buffer_uptodate(bh)); + KUNIT_EXPECT_TRUE(test, (bool)bitmap_uptodate(bh)); + KUNIT_EXPECT_TRUE(test, buffer_verified(bh)); + + for (bit = 0; bit < 20; bit++) + KUNIT_EXPECT_TRUE_MSG(test, + (bool)ext4_test_bit(bit, bh->b_data), + "metadata bit %u must be set", bit); + KUNIT_EXPECT_FALSE(test, (bool)ext4_test_bit(20, bh->b_data)); + KUNIT_EXPECT_FALSE(test, (bool)ext4_test_bit(1023, bh->b_data)); + KUNIT_EXPECT_TRUE(test, (bool)ext4_test_bit(1024, bh->b_data)); + KUNIT_EXPECT_TRUE(test, (bool)ext4_test_bit(8191, bh->b_data)); + + KUNIT_EXPECT_EQ(test, ext4_count_free(bh->b_data, 1024 / 8), + ext4_free_clusters_after_init(sb, 1, &ctx->gdps[1])); + put_bh(bh); + + /* + * Legacy GDT_CSUM (CRC16 without metadata_csum) with FLEX_BG external + * metadata on group 2 (0 base blocks, bitmaps & itable in group 3) + * initializes all 1024 data bits in group 2 to free without I/O. + */ + { + struct balloc_test_blk *ext_slot; + ext4_fsblk_t ext_bbitmap = balloc_test_group_start(3) + 50; + + ext4_clear_feature_metadata_csum(sb); + ext4_set_feature_gdt_csum(sb); + ext4_set_feature_flex_bg(sb); + + ext_slot = balloc_test_setup_blk(ctx, ext_bbitmap, false); + KUNIT_ASSERT_NOT_NULL(test, ext_slot); + memset(ext_slot->cache_buf, 0x5a, sizeof(ext_slot->cache_buf)); + + ext4_block_bitmap_set(sb, &ctx->gdps[2], ext_bbitmap); + ext4_inode_bitmap_set(sb, &ctx->gdps[2], ext_bbitmap + 1); + ext4_inode_table_set(sb, &ctx->gdps[2], ext_bbitmap + 2); + ctx->gdps[2].bg_flags = cpu_to_le16(EXT4_BG_BLOCK_UNINIT); + ext4_group_desc_csum_set(sb, 2, &ctx->gdps[2]); + + bh = ext4_read_block_bitmap(sb, 2); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + KUNIT_EXPECT_EQ(test, ctx->read_nowait_calls, 0U); + KUNIT_EXPECT_EQ(test, ext4_count_free(bh->b_data, 1024 / 8), + 1024U); + KUNIT_EXPECT_TRUE(test, (bool)ext4_test_bit(1024, bh->b_data)); + put_bh(bh); + + ext4_clear_feature_flex_bg(sb); + } + + /* + * Without GDT checksums (neither metadata_csum nor gdt_csum), + * EXT4_BG_BLOCK_UNINIT is ignored and bitmap is read from disk. + */ + ext4_clear_feature_metadata_csum(sb); + ext4_clear_feature_gdt_csum(sb); + clear_buffer_uptodate(&slot->bh); + clear_bitmap_uptodate(&slot->bh); + clear_buffer_verified(&slot->bh); + + bh = ext4_read_block_bitmap(sb, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + KUNIT_EXPECT_EQ(test, ctx->read_nowait_calls, 1U); + put_bh(bh); +} + +static void test_read_block_bitmap_uninit_errors(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct balloc_test_blk *slot0, *slot1; + struct buffer_head *bh; + s64 free_clu_before, free_ino_before; + + slot0 = balloc_test_find_blk(ctx, balloc_test_bbitmap_blk(0)); + slot1 = balloc_test_find_blk(ctx, balloc_test_bbitmap_blk(1)); + KUNIT_ASSERT_NOT_NULL(test, slot0); + KUNIT_ASSERT_NOT_NULL(test, slot1); + + /* 1. Group 0 marked EXT4_BG_BLOCK_UNINIT is rejected -> -EFSCORRUPTED */ + clear_buffer_uptodate(&slot0->bh); + clear_bitmap_uptodate(&slot0->bh); + ctx->gdps[0].bg_flags = cpu_to_le16(EXT4_BG_BLOCK_UNINIT); + ext4_group_desc_csum_set(sb, 0, &ctx->gdps[0]); + + bh = ext4_read_block_bitmap(sb, 0); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EFSCORRUPTED); + + /* + * 2. Group 1 marked EXT4_BG_BLOCK_UNINIT with bad GDT checksum fails + * with -EFSBADCRC and marks BOTH block and inode bitmaps corrupt. + */ + free_clu_before = percpu_counter_sum(&ctx->sbi.s_freeclusters_counter); + free_ino_before = percpu_counter_sum(&ctx->sbi.s_freeinodes_counter); + clear_buffer_uptodate(&slot1->bh); + clear_bitmap_uptodate(&slot1->bh); + ctx->gdps[1].bg_flags = cpu_to_le16(EXT4_BG_BLOCK_UNINIT); + ctx->gdps[1].bg_checksum = cpu_to_le16(0xdead); + + bh = ext4_read_block_bitmap(sb, 1); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EFSBADCRC); + KUNIT_EXPECT_TRUE(test, EXT4_MB_GRP_BBITMAP_CORRUPT(ctx->grp_infos[1])); + KUNIT_EXPECT_TRUE(test, EXT4_MB_GRP_IBITMAP_CORRUPT(ctx->grp_infos[1])); + KUNIT_EXPECT_EQ(test, + percpu_counter_sum(&ctx->sbi.s_freeclusters_counter), + free_clu_before - ctx->grp_infos[1]->bb_free); + KUNIT_EXPECT_EQ(test, + percpu_counter_sum(&ctx->sbi.s_freeinodes_counter), + free_ino_before - BALLOC_TEST_INODES_PER_GRP); + + /* + * 3. Base metadata clusters exceeding bitmap block size ((bit_max >> 3) + * >= bh->b_size) returns -EFSCORRUPTED instead of overflowing bh. + */ + ctx->grp_infos[1]->bb_state = 0; + clear_buffer_uptodate(&slot1->bh); + clear_bitmap_uptodate(&slot1->bh); + ctx->sbi.s_gdb_count = BALLOC_TEST_BLK_SIZE * 8; + ext4_group_desc_csum_set(sb, 1, &ctx->gdps[1]); + + bh = ext4_read_block_bitmap(sb, 1); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EFSCORRUPTED); +} + +static void test_read_and_wait_block_bitmap_errors(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct balloc_test_blk *slot; + struct buffer_head *bh; + int ref_before; + + /* 1. Out-of-range block group -> -EFSCORRUPTED */ + bh = ext4_read_block_bitmap(sb, 99); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EFSCORRUPTED); + + /* 2. Block bitmap <= s_first_data_block (1) -> -EFSCORRUPTED + corrupt */ + ext4_block_bitmap_set(sb, &ctx->gdps[2], BALLOC_TEST_FIRST_DATA_BLK); + bh = ext4_read_block_bitmap(sb, 2); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EFSCORRUPTED); + KUNIT_EXPECT_TRUE(test, EXT4_MB_GRP_BBITMAP_CORRUPT(ctx->grp_infos[2])); + + /* 3. Block bitmap >= ext4_blocks_count(es) -> -EFSCORRUPTED + corrupt */ + ctx->grp_infos[2]->bb_state = 0; + ext4_block_bitmap_set(sb, &ctx->gdps[2], BALLOC_TEST_TOTAL_BLKS); + bh = ext4_read_block_bitmap(sb, 2); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EFSCORRUPTED); + KUNIT_EXPECT_TRUE(test, EXT4_MB_GRP_BBITMAP_CORRUPT(ctx->grp_infos[2])); + ext4_block_bitmap_set(sb, &ctx->gdps[2], balloc_test_bbitmap_blk(2)); + + /* 4. ext4_sb_getblk allocation failure -> -ENOMEM without corrupt flag */ + ctx->grp_infos[2]->bb_state = 0; + ctx->fail_getblk = true; + bh = ext4_read_block_bitmap(sb, 2); + ctx->fail_getblk = false; + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -ENOMEM); + KUNIT_EXPECT_FALSE(test, EXT4_MB_GRP_BBITMAP_CORRUPT(ctx->grp_infos[2])); + + /* 5. Async read I/O failure -> -EIO, marks corrupt, releases bh ref */ + slot = balloc_test_find_blk(ctx, balloc_test_bbitmap_blk(2)); + KUNIT_ASSERT_NOT_NULL(test, slot); + ref_before = atomic_read(&slot->bh.b_count); + clear_buffer_uptodate(&slot->bh); + clear_bitmap_uptodate(&slot->bh); + clear_buffer_verified(&slot->bh); + ctx->fail_read_eio = true; + + bh = ext4_read_block_bitmap(sb, 2); + ctx->fail_read_eio = false; + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EIO); + KUNIT_EXPECT_TRUE(test, EXT4_MB_GRP_BBITMAP_CORRUPT(ctx->grp_infos[2])); + KUNIT_EXPECT_EQ(test, atomic_read(&slot->bh.b_count), ref_before); + +#ifdef CONFIG_EXT4_DEBUG + ctx->grp_infos[2]->bb_state = 0; + clear_buffer_uptodate(&slot->bh); + clear_bitmap_uptodate(&slot->bh); + ctx->sbi.s_simulate_fail = EXT4_SIM_BBITMAP_EIO; + bh = ext4_read_block_bitmap(sb, 2); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(bh), -EIO); + KUNIT_EXPECT_EQ(test, ctx->sbi.s_simulate_fail, 0UL); +#endif + + /* 6. ext4_wait_block_bitmap guards on BH_New and group descriptor */ + clear_buffer_new(&slot->bh); + KUNIT_EXPECT_EQ(test, ext4_wait_block_bitmap(sb, 99, &slot->bh), 0); + set_buffer_new(&slot->bh); + KUNIT_EXPECT_EQ(test, ext4_wait_block_bitmap(sb, 99, &slot->bh), + -EFSCORRUPTED); + clear_buffer_new(&slot->bh); +} + +/* ========================================================================= + * 8. Free Cluster Reservation & Pool Accounting (ext4_claim_free_clusters) + * ========================================================================= + */ + +static void balloc_test_set_cluster_pools(struct balloc_test_ctx *ctx, + s64 free_clu, s64 dirty_clu, + u64 r_blocks, s64 resv_clu) +{ + percpu_counter_set(&ctx->sbi.s_freeclusters_counter, free_clu); + percpu_counter_set(&ctx->sbi.s_dirtyclusters_counter, dirty_clu); + ctx->es.s_r_blocks_count_lo = cpu_to_le32(lower_32_bits(r_blocks)); + ctx->es.s_r_blocks_count_hi = cpu_to_le32(upper_32_bits(r_blocks)); + atomic64_set(&ctx->sbi.s_resv_clusters, resv_clu); +} + +static void +test_claim_free_clusters_unprivileged_and_bigalloc(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct ext4_sb_info *sbi = &ctx->sbi; + + sbi->s_resuid = KUIDT_INIT(500); + sbi->s_resgid = GLOBAL_ROOT_GID; + balloc_test_override_creds(test, ctx, 1000, 1000, false, -1); + + /* Above-watermark fast path */ + balloc_test_set_cluster_pools(ctx, 100000, 10, 30, 15); + KUNIT_EXPECT_EQ(test, ext4_claim_free_clusters(sbi, 25, 0), 0); + KUNIT_EXPECT_EQ(test, percpu_counter_sum(&sbi->s_dirtyclusters_counter), + 35LL); + + /* + * Exact unprivileged limit: + * free=100, dirty=20, r_blocks=30, resv=15 -> usable = 100 - 20 - 45 = 35 + */ + balloc_test_set_cluster_pools(ctx, 100, 20, 30, 15); + KUNIT_EXPECT_EQ(test, ext4_claim_free_clusters(sbi, 36, 0), -ENOSPC); + KUNIT_EXPECT_EQ(test, percpu_counter_sum(&sbi->s_dirtyclusters_counter), + 20LL); + + KUNIT_EXPECT_EQ(test, ext4_claim_free_clusters(sbi, 35, 0), 0); + KUNIT_EXPECT_EQ(test, percpu_counter_sum(&sbi->s_dirtyclusters_counter), + 55LL); + + /* + * Bigalloc (cluster_bits = 2 -> 4 blocks/cluster): + * r_blocks_count = 120 blocks -> 30 reserved clusters -> usable = 35. + */ + sbi->s_cluster_bits = 2; + sbi->s_cluster_ratio = 4; + balloc_test_set_cluster_pools(ctx, 100, 20, 120, 15); + KUNIT_EXPECT_EQ(test, ext4_claim_free_clusters(sbi, 36, 0), -ENOSPC); + KUNIT_EXPECT_EQ(test, ext4_claim_free_clusters(sbi, 35, 0), 0); + KUNIT_EXPECT_EQ(test, percpu_counter_sum(&sbi->s_dirtyclusters_counter), + 55LL); + + balloc_test_restore_creds(ctx); +} + +static void test_claim_free_clusters_root_and_reserved_pools(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct ext4_sb_info *sbi = &ctx->sbi; + + /* + * Pool layout: free=100, dirty=20, r_blocks=30, resv=15: + * - Unprivileged limit: 35 clusters (100 - 20 - 30 - 15) + * - Root-pool limit: 65 clusters (100 - 20 - 15; resv protected) + * - Internal resv limit: 80 clusters (100 - 20; EXT4_MB_USE_RESERVED) + */ + sbi->s_resuid = KUIDT_INIT(500); + sbi->s_resgid = GLOBAL_ROOT_GID; + + /* 1. Matching s_resuid grants root pool (65), still protects resv (66) */ + balloc_test_override_creds(test, ctx, 500, 1000, false, -1); + balloc_test_set_cluster_pools(ctx, 100, 20, 30, 15); + KUNIT_EXPECT_EQ(test, ext4_claim_free_clusters(sbi, 66, 0), -ENOSPC); + KUNIT_EXPECT_EQ(test, ext4_claim_free_clusters(sbi, 65, 0), 0); + + /* + * 2. s_resgid == GLOBAL_ROOT_GID (0) does NOT grant root blocks via + * group membership even when caller's fsgid is 0. + */ + balloc_test_override_creds(test, ctx, 1000, 0, false, -1); + balloc_test_set_cluster_pools(ctx, 100, 20, 30, 15); + KUNIT_EXPECT_EQ(test, ext4_claim_free_clusters(sbi, 36, 0), -ENOSPC); + +#ifdef CONFIG_MULTIUSER + /* 3. Non-root s_resgid grants root pool only when caller is in group */ + sbi->s_resgid = KGIDT_INIT(2000); + balloc_test_override_creds(test, ctx, 1000, 1000, false, -1); + balloc_test_set_cluster_pools(ctx, 100, 20, 30, 15); + KUNIT_EXPECT_EQ(test, ext4_claim_free_clusters(sbi, 36, 0), -ENOSPC); + + balloc_test_override_creds(test, ctx, 1000, 1000, false, 2000); + balloc_test_set_cluster_pools(ctx, 100, 20, 30, 15); + KUNIT_EXPECT_EQ(test, ext4_claim_free_clusters(sbi, 66, 0), -ENOSPC); + KUNIT_EXPECT_EQ(test, ext4_claim_free_clusters(sbi, 65, 0), 0); + sbi->s_resgid = GLOBAL_ROOT_GID; +#endif + + /* 4. EXT4_MB_USE_ROOT_BLOCKS grants root pool to unprivileged caller */ + balloc_test_override_creds(test, ctx, 1000, 1000, false, -1); + balloc_test_set_cluster_pools(ctx, 100, 20, 30, 15); + KUNIT_EXPECT_EQ(test, + ext4_claim_free_clusters(sbi, 66, + EXT4_MB_USE_ROOT_BLOCKS), + -ENOSPC); + KUNIT_EXPECT_EQ(test, + ext4_claim_free_clusters(sbi, 65, + EXT4_MB_USE_ROOT_BLOCKS), + 0); + + /* 5. CAP_SYS_RESOURCE grants root pool regardless of uid/gid/flags */ + balloc_test_override_creds(test, ctx, 1000, 1000, true, -1); + balloc_test_set_cluster_pools(ctx, 100, 20, 30, 15); + KUNIT_EXPECT_EQ(test, ext4_claim_free_clusters(sbi, 66, 0), -ENOSPC); + KUNIT_EXPECT_EQ(test, ext4_claim_free_clusters(sbi, 65, 0), 0); + + /* 6. EXT4_MB_USE_RESERVED dips into s_resv_clusters up to 80 clusters */ + balloc_test_override_creds(test, ctx, 1000, 1000, false, -1); + balloc_test_set_cluster_pools(ctx, 100, 20, 30, 15); + KUNIT_EXPECT_EQ(test, + ext4_claim_free_clusters(sbi, 81, EXT4_MB_USE_RESERVED), + -ENOSPC); + KUNIT_EXPECT_EQ(test, + ext4_claim_free_clusters(sbi, 80, EXT4_MB_USE_RESERVED), + 0); + KUNIT_EXPECT_EQ(test, percpu_counter_sum(&sbi->s_dirtyclusters_counter), + 100LL); + + balloc_test_restore_creds(ctx); +} + +/* ========================================================================= + * 9. Allocation Retry Policy (ext4_should_retry_alloc) + * ========================================================================= + */ + +static void +test_should_retry_alloc_no_journal_and_retry_limit(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + int retries = 1; + + /* Without a journal, returns 0 without incrementing *retries */ + sbi->s_journal = NULL; + KUNIT_EXPECT_EQ(test, ext4_should_retry_alloc(sb, &retries), 0); + KUNIT_EXPECT_EQ(test, retries, 1); + + /* With journal and pending mb frees, retries 1..3 succeed, 4th stops */ + sbi->s_journal = &ctx->journal; + atomic_set(&sbi->s_mb_free_pending, 4); + retries = 0; + + KUNIT_EXPECT_EQ(test, ext4_should_retry_alloc(sb, &retries), 1); + KUNIT_EXPECT_EQ(test, retries, 1); + KUNIT_EXPECT_EQ(test, ext4_should_retry_alloc(sb, &retries), 1); + KUNIT_EXPECT_EQ(test, retries, 2); + KUNIT_EXPECT_EQ(test, ext4_should_retry_alloc(sb, &retries), 1); + KUNIT_EXPECT_EQ(test, retries, 3); + KUNIT_EXPECT_EQ(test, + percpu_counter_sum(&sbi->s_sra_exceeded_retry_limit), + 0LL); + + KUNIT_EXPECT_EQ(test, ext4_should_retry_alloc(sb, &retries), 0); + KUNIT_EXPECT_EQ(test, retries, 4); + KUNIT_EXPECT_EQ(test, + percpu_counter_sum(&sbi->s_sra_exceeded_retry_limit), + 1LL); +} + +static void +test_should_retry_alloc_free_space_and_discard_flush(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + int retries; + + sbi->s_journal = &ctx->journal; + atomic_set(&sbi->s_mb_free_pending, 0); + clear_opt(sb, DISCARD); + balloc_test_override_creds(test, ctx, 1000, 1000, false, -1); + + /* 1. No pending frees, no discard, 0 free clusters -> returns 0 */ + balloc_test_set_cluster_pools(ctx, 10, 10, 0, 0); + retries = 0; + KUNIT_EXPECT_EQ(test, ext4_should_retry_alloc(sb, &retries), 0); + KUNIT_EXPECT_EQ(test, retries, 1); + KUNIT_EXPECT_EQ(test, ctx->discard_work_runs, 0U); + + /* 2. Free cluster available -> returns 1 */ + balloc_test_set_cluster_pools(ctx, 11, 10, 0, 0); + retries = 0; + KUNIT_EXPECT_EQ(test, ext4_should_retry_alloc(sb, &retries), 1); + + /* + * 3. With DISCARD enabled, flushes s_discard_work while holding + * s_retry_alloc_pending == 1 and rechecks free clusters afterward. + */ + set_opt(sb, DISCARD); + balloc_test_set_cluster_pools(ctx, 10, 10, 0, 0); + ctx->discard_release_clusters = 8; + ctx->discard_wait_retry_pending = true; + schedule_work(&sbi->s_discard_work); + + retries = 0; + KUNIT_EXPECT_EQ(test, ext4_should_retry_alloc(sb, &retries), 1); + ctx->discard_wait_retry_pending = false; + KUNIT_EXPECT_EQ(test, ctx->discard_work_runs, 1U); + KUNIT_EXPECT_EQ(test, ctx->discard_saw_retry_pending, 1); + KUNIT_EXPECT_EQ(test, atomic_read(&sbi->s_retry_alloc_pending), 0); + + balloc_test_restore_creds(ctx); +} + +/* ========================================================================= + * 10. Metadata Block Allocation (ext4_new_meta_blocks) + * ========================================================================= + */ + +static void test_new_meta_blocks_alloc_and_delalloc_quota(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct inode *inode = ctx->test_inode; + unsigned long count; + ext4_fsblk_t blk; + int err = -EINVAL; + + /* 1. count == NULL defaults ar.len to 1; non-delalloc skips quota */ + ctx->mock_alloc_blk = 1234ULL; + ctx->mock_alloc_len = 0; + ctx->mock_alloc_err = 0; + inode_set_bytes(inode, 0); + + blk = ext4_new_meta_blocks(NULL, inode, 500ULL, EXT4_MB_USE_ROOT_BLOCKS, + NULL, &err); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, blk, 1234ULL); + KUNIT_EXPECT_PTR_EQ(test, ctx->last_ar.inode, inode); + KUNIT_EXPECT_EQ(test, ctx->last_ar.goal, 500ULL); + KUNIT_EXPECT_EQ(test, ctx->last_ar.len, 1U); + KUNIT_EXPECT_EQ(test, ctx->last_ar.flags, + (unsigned int)EXT4_MB_USE_ROOT_BLOCKS); + KUNIT_EXPECT_EQ(test, inode_get_bytes(inode), 0LL); + + /* + * 2. Partial allocation (requested 8 clusters, granted 3) with + * EXT4_MB_DELALLOC_RESERVED and bigalloc (4 blocks/cluster = 4096B + * per cluster) updates *count to 3 and charges 12288 quota bytes. + */ + ctx->sbi.s_cluster_bits = 2; + ctx->sbi.s_cluster_ratio = 4; + ctx->mock_alloc_blk = 2400ULL; + ctx->mock_alloc_len = 3; + ctx->mock_alloc_err = 0; + count = 8; + + blk = ext4_new_meta_blocks(NULL, inode, 2048ULL, + EXT4_MB_DELALLOC_RESERVED, &count, &err); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, blk, 2400ULL); + KUNIT_EXPECT_EQ(test, count, 3UL); + KUNIT_EXPECT_EQ(test, inode_get_bytes(inode), 12288LL); + + /* 3. Error from ext4_mb_new_blocks does not charge quota bytes */ + ctx->mock_alloc_err = -ENOSPC; + count = 4; + blk = ext4_new_meta_blocks(NULL, inode, 2048ULL, + EXT4_MB_DELALLOC_RESERVED, &count, &err); + KUNIT_EXPECT_EQ(test, err, -ENOSPC); + KUNIT_EXPECT_EQ(test, blk, 0ULL); + KUNIT_EXPECT_EQ(test, inode_get_bytes(inode), 12288LL); +} + +/* ========================================================================= + * 11. Free Cluster Summation (ext4_count_free_clusters) + * ========================================================================= + */ + +static void +test_count_free_clusters_corrupt_and_64bit_groups(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct balloc_test_blk *slot2; + + slot2 = balloc_test_find_blk(ctx, balloc_test_bbitmap_blk(2)); + KUNIT_ASSERT_NOT_NULL(test, slot2); + + /* Default 4 groups: 1004 + 1004 + 1006 + 1004 = 4018 free clusters */ + KUNIT_EXPECT_EQ(test, ext4_count_free_clusters(sb), 4018ULL); + + /* Corrupt bitmap flag on group 2 excludes its 1006 clusters -> 3012 */ + clear_buffer_verified(&slot2->bh); + set_bit(EXT4_GROUP_INFO_BBITMAP_CORRUPT_BIT, + &ctx->grp_infos[2]->bb_state); + KUNIT_EXPECT_EQ(test, ext4_count_free_clusters(sb), 3012ULL); + + /* NULL s_group_info still sums all valid group descriptors -> 4018 */ + set_buffer_verified(&slot2->bh); + rcu_assign_pointer(ctx->sbi.s_group_info, NULL); + KUNIT_EXPECT_EQ(test, ext4_count_free_clusters(sb), 4018ULL); + rcu_assign_pointer(ctx->sbi.s_group_info, ctx->grp_info_slices); + ctx->grp_infos[2]->bb_state = 0; + +#ifndef EXT4FS_DEBUG + /* 64-bit group descriptors with bg_free_blocks_count_hi > 0 */ + ctx->sbi.s_groups_count = 2; + ext4_free_group_clusters_set(sb, &ctx->gdps[0], 0x10005U); + ext4_free_group_clusters_set(sb, &ctx->gdps[1], 0x20003U); + KUNIT_EXPECT_EQ(test, ext4_count_free_clusters(sb), 0x30008ULL); + + /* Unloaded group descriptor block is skipped cleanly */ + ctx->sbi.s_groups_count = 20; + ctx->gdesc_bh_ptrs[1] = NULL; + KUNIT_EXPECT_EQ(test, ext4_count_free_clusters(sb), + 0x30008ULL + 1006ULL + 1004ULL); +#endif +} + +/* ========================================================================= + * 12. Inode Goal Block Selection (ext4_inode_to_goal_block) + * ========================================================================= + */ + +static void test_inode_to_goal_block_flex_bg_and_delalloc(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct inode *inode = ctx->test_inode; + + ctx->sbi.s_groups_count = 8; + ext4_blocks_count_set(&ctx->es, 1 + 8 * BALLOC_TEST_BLOCKS_PER_GRP); + set_opt(sb, DELALLOC); + + /* flex_size = 2 (< EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME = 4): stays in bg 3 */ + ctx->sbi.s_log_groups_per_flex = 1; + EXT4_I(inode)->i_block_group = 3; + inode->i_mode = S_IFDIR | 0755; + KUNIT_EXPECT_EQ(test, ext4_inode_to_goal_block(inode), + balloc_test_group_start(3)); + inode->i_mode = S_IFREG | 0644; + KUNIT_EXPECT_EQ(test, ext4_inode_to_goal_block(inode), + balloc_test_group_start(3)); + + /* + * flex_size = 4 (== EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME): + * - Directories and special/symlink inodes map to 1st group of flex_bg + * - Regular files map to 2nd group of flex_bg (flex_start + 1) + */ + ctx->sbi.s_log_groups_per_flex = 2; + + EXT4_I(inode)->i_block_group = 3; + inode->i_mode = S_IFDIR | 0755; + KUNIT_EXPECT_EQ(test, ext4_inode_to_goal_block(inode), + balloc_test_group_start(0)); + inode->i_mode = S_IFLNK | 0777; + KUNIT_EXPECT_EQ(test, ext4_inode_to_goal_block(inode), + balloc_test_group_start(0)); + inode->i_mode = S_IFREG | 0644; + KUNIT_EXPECT_EQ(test, ext4_inode_to_goal_block(inode), + balloc_test_group_start(1)); + + EXT4_I(inode)->i_block_group = 6; + inode->i_mode = S_IFDIR | 0755; + KUNIT_EXPECT_EQ(test, ext4_inode_to_goal_block(inode), + balloc_test_group_start(4)); + inode->i_mode = S_IFREG | 0644; + KUNIT_EXPECT_EQ(test, ext4_inode_to_goal_block(inode), + balloc_test_group_start(5)); +} + +static void test_inode_to_goal_block_nodelalloc_colour(struct kunit *test) +{ + struct balloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct inode *inode = ctx->test_inode; + ext4_fsblk_t g0_start = balloc_test_group_start(0); + ext4_fsblk_t g3_start = balloc_test_group_start(3); + ext4_fsblk_t goal_full, goal_partial; + u32 rem; + + clear_opt(sb, DELALLOC); + ctx->sbi.s_log_groups_per_flex = 0; + inode->i_mode = S_IFREG | 0644; + + /* + * Full group 0 (1024 blocks -> step = 64) vs partial last group 3 with + * last_block - g3_start == 320 (321 blocks -> step = 20). Both calls + * execute in the same kthread, so (task_pid_nr(current) % 16) is fixed. + */ + ext4_blocks_count_set(&ctx->es, g3_start + 321); + + EXT4_I(inode)->i_block_group = 0; + goal_full = ext4_inode_to_goal_block(inode); + KUNIT_EXPECT_GE(test, goal_full, g0_start); + KUNIT_EXPECT_LE(test, goal_full, g0_start + 15 * 64); + div_u64_rem(goal_full - g0_start, 64, &rem); + KUNIT_EXPECT_EQ(test, rem, 0U); + + EXT4_I(inode)->i_block_group = 3; + goal_partial = ext4_inode_to_goal_block(inode); + KUNIT_EXPECT_GE(test, goal_partial, g3_start); + KUNIT_EXPECT_LE(test, goal_partial, g3_start + 15 * 20); + div_u64_rem(goal_partial - g3_start, 20, &rem); + KUNIT_EXPECT_EQ(test, rem, 0U); + KUNIT_EXPECT_EQ(test, (goal_full - g0_start) * 20, + (goal_partial - g3_start) * 64); + + /* Partial last group with < 16 blocks yields colour step 0 -> g3_start */ + ext4_blocks_count_set(&ctx->es, g3_start + 16); + KUNIT_EXPECT_EQ(test, ext4_inode_to_goal_block(inode), g3_start); +} + +static struct kunit_case balloc_test_cases[] = { + KUNIT_CASE_PARAM(test_group_no_and_offset_matrix, + group_offset_gen_params), + KUNIT_CASE(test_group_no_and_offset_optional_out_ptrs), + KUNIT_CASE(test_bg_has_super_dense_all_groups), + KUNIT_CASE(test_bg_has_super_sparse_super_powers), + KUNIT_CASE(test_bg_has_super_sparse_super2_explicit_backups), + KUNIT_CASE(test_bg_num_gdb_and_base_meta_non_metabg), + KUNIT_CASE(test_bg_num_gdb_and_base_meta_hybrid_metabg), + KUNIT_CASE(test_free_clusters_after_init_standard_and_partial_last), + KUNIT_CASE(test_free_clusters_after_init_external_and_spanning_meta), + KUNIT_CASE(test_free_clusters_after_init_bigalloc_cluster_sharing), + KUNIT_CASE(test_get_group_desc_lookup_and_bounds), + KUNIT_CASE(test_get_group_info_lookup_and_null_guards), + KUNIT_CASE(test_read_block_bitmap_validates_csum), + KUNIT_CASE(test_read_block_bitmap_validates_metadata_bits), + KUNIT_CASE(test_read_block_bitmap_validates_padding), + KUNIT_CASE(test_read_block_bitmap_validation_short_circuits), + KUNIT_CASE(test_read_block_bitmap_disk_and_cache_paths), + KUNIT_CASE(test_read_block_bitmap_nowait_prefetch_locked), + KUNIT_CASE(test_read_block_bitmap_uninit_group), + KUNIT_CASE(test_read_block_bitmap_uninit_errors), + KUNIT_CASE(test_read_and_wait_block_bitmap_errors), + KUNIT_CASE(test_claim_free_clusters_unprivileged_and_bigalloc), + KUNIT_CASE(test_claim_free_clusters_root_and_reserved_pools), + KUNIT_CASE(test_should_retry_alloc_no_journal_and_retry_limit), + KUNIT_CASE(test_should_retry_alloc_free_space_and_discard_flush), + KUNIT_CASE(test_new_meta_blocks_alloc_and_delalloc_quota), + KUNIT_CASE(test_count_free_clusters_corrupt_and_64bit_groups), + KUNIT_CASE(test_inode_to_goal_block_flex_bg_and_delalloc), + KUNIT_CASE(test_inode_to_goal_block_nodelalloc_colour), + {} +}; + +static struct kunit_suite balloc_test_suite = { + .name = "ext4_balloc_test", + .init = balloc_test_init, + .test_cases = balloc_test_cases, +}; + +kunit_test_suites(&balloc_test_suite); + +MODULE_DESCRIPTION("KUnit tests for ext4 block allocation helpers in balloc.c"); +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/balloc.c b/fs/ext4/balloc.c index 778fe8788f06e1..d2f0f27bbc9aab 100644 --- a/fs/ext4/balloc.c +++ b/fs/ext4/balloc.c @@ -243,6 +243,7 @@ unsigned ext4_free_clusters_after_init(struct super_block *sb, return num_clusters_in_group(sb, block_group) - ext4_num_overhead_clusters(sb, block_group, gdp); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_free_clusters_after_init); /* * The free blocks are managed by bitmaps. A file system contains several @@ -489,7 +490,7 @@ ext4_read_block_bitmap_nowait(struct super_block *sb, ext4_group_t block_group, EXT4_GROUP_INFO_BBITMAP_CORRUPT); return ERR_PTR(-EFSCORRUPTED); } - bh = sb_getblk(sb, bitmap_blk); + bh = ext4_sb_getblk(sb, bitmap_blk); if (unlikely(!bh)) { ext4_warning(sb, "Cannot get buffer for block bitmap - " "block_group = %u, block_bitmap = %llu", @@ -611,6 +612,7 @@ ext4_read_block_bitmap(struct super_block *sb, ext4_group_t block_group) } return bh; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_read_block_bitmap); /** * ext4_has_free_clusters() @@ -678,6 +680,7 @@ int ext4_claim_free_clusters(struct ext4_sb_info *sbi, } else return -ENOSPC; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_claim_free_clusters); /** * ext4_should_retry_alloc() - check if a block allocation should be retried @@ -724,6 +727,7 @@ int ext4_should_retry_alloc(struct super_block *sb, int *retries) (void) jbd2_journal_force_commit_nested(sbi->s_journal); return 1; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_should_retry_alloc); /* * ext4_new_meta_blocks() -- allocate block for meta data (indexing) blocks @@ -764,6 +768,7 @@ ext4_fsblk_t ext4_new_meta_blocks(handle_t *handle, struct inode *inode, } return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_new_meta_blocks); /** * ext4_count_free_clusters() -- count filesystem free clusters @@ -877,6 +882,7 @@ int ext4_bg_has_super(struct super_block *sb, ext4_group_t group) return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_bg_has_super); static unsigned long ext4_bg_num_gdb_meta(struct super_block *sb, ext4_group_t group) @@ -923,6 +929,7 @@ unsigned long ext4_bg_num_gdb(struct super_block *sb, ext4_group_t group) return ext4_bg_num_gdb_meta(sb,group); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_bg_num_gdb); /* * This function returns the number of file system metadata blocks at @@ -949,6 +956,7 @@ unsigned int ext4_num_base_meta_blocks(struct super_block *sb, } return num; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_num_base_meta_blocks); static unsigned int ext4_num_base_meta_clusters(struct super_block *sb, ext4_group_t block_group) @@ -1004,4 +1012,5 @@ ext4_fsblk_t ext4_inode_to_goal_block(struct inode *inode) ((last_block - bg_start) / 16); return bg_start + colour; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_to_goal_block); diff --git a/fs/ext4/bitmap.c b/fs/ext4/bitmap.c index 87760fabdd2eba..f9c22427891f20 100644 --- a/fs/ext4/bitmap.c +++ b/fs/ext4/bitmap.c @@ -15,6 +15,7 @@ unsigned int ext4_count_free(char *bitmap, unsigned int numchars) { return numchars * BITS_PER_BYTE - memweight(bitmap, numchars); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_count_free); int ext4_inode_bitmap_csum_verify(struct super_block *sb, struct ext4_group_desc *gdp, @@ -39,6 +40,7 @@ int ext4_inode_bitmap_csum_verify(struct super_block *sb, return provided == calculated; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_bitmap_csum_verify); void ext4_inode_bitmap_csum_set(struct super_block *sb, struct ext4_group_desc *gdp, @@ -57,6 +59,7 @@ void ext4_inode_bitmap_csum_set(struct super_block *sb, if (sbi->s_desc_size >= EXT4_BG_INODE_BITMAP_CSUM_HI_END) gdp->bg_inode_bitmap_csum_hi = cpu_to_le16(csum >> 16); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_bitmap_csum_set); int ext4_block_bitmap_csum_verify(struct super_block *sb, struct ext4_group_desc *gdp, @@ -80,6 +83,7 @@ int ext4_block_bitmap_csum_verify(struct super_block *sb, return provided == calculated; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_block_bitmap_csum_verify); void ext4_block_bitmap_csum_set(struct super_block *sb, struct ext4_group_desc *gdp, @@ -97,3 +101,4 @@ void ext4_block_bitmap_csum_set(struct super_block *sb, if (sbi->s_desc_size >= EXT4_BG_BLOCK_BITMAP_CSUM_HI_END) gdp->bg_block_bitmap_csum_hi = cpu_to_le16(csum >> 16); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_block_bitmap_csum_set); diff --git a/fs/ext4/block_validity-test.c b/fs/ext4/block_validity-test.c new file mode 100644 index 00000000000000..97817befd6e783 --- /dev/null +++ b/fs/ext4/block_validity-test.c @@ -0,0 +1,1598 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for fs/ext4/block_validity.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_extents.h" +#include "ext4_jbd2.h" +#include "xattr.h" + +/* + * Default mock filesystem geometry: + * - 4 block groups, 1024-byte blocks, s_first_data_block = 1 + * - 1024 blocks per group -> total blocks = 4097 (valid blocks 0..4096) + * - sparse_super enabled, s_gdb_count = 1, s_reserved_gdt_blocks = 2: + * group 0 (blocks 1..1024): 4 base meta blocks (1..4) + * group 1 (blocks 1025..2048): 4 base meta blocks (1025..1028) + * group 2 (blocks 2049..3072): 0 base meta blocks (sparse_super) + * group 3 (blocks 3073..4096): 4 base meta blocks (3073..3076) + * - 32 inodes per group (128 total), 256-byte inodes -> 8 inode table + * blocks per group + */ +#define BV_TEST_NGROUPS 4U +#define BV_TEST_BLK_SIZE 1024U +#define BV_TEST_BLK_BITS 10U +#define BV_TEST_BLOCKS_PER_GRP 1024U +#define BV_TEST_FIRST_DATA_BLK 1U +#define BV_TEST_TOTAL_BLKS (BV_TEST_FIRST_DATA_BLK + \ + BV_TEST_NGROUPS * \ + BV_TEST_BLOCKS_PER_GRP) +#define BV_TEST_INODE_SIZE 256U +#define BV_TEST_EXTRA_ISIZE 32U +#define BV_TEST_INODES_PER_BLK (BV_TEST_BLK_SIZE / BV_TEST_INODE_SIZE) +#define BV_TEST_INODES_PER_GRP 32U +#define BV_TEST_ITB_PER_GRP (BV_TEST_INODES_PER_GRP / \ + BV_TEST_INODES_PER_BLK) +#define BV_TEST_TOTAL_INODES (BV_TEST_NGROUPS * \ + BV_TEST_INODES_PER_GRP) +#define BV_TEST_FIRST_INO 11U +#define BV_TEST_GDB_COUNT 1U +#define BV_TEST_RSV_GDT_BLKS 2U +#define BV_TEST_GDESC_BLK 2ULL +#define BV_TEST_MAX_SLOTS 8U + +struct bv_test_inode_slot { + bool in_use; + unsigned long ino; + struct inode *inode; +}; + +struct bv_test_ctx { + struct super_block *sb; + struct ext4_sb_info sbi; + struct ext4_super_block es; + struct blockgroup_lock bgl; + struct gendisk bdev_disk; + struct block_device bdev; + struct request_queue bdev_queue; + struct inode bd_inode; + struct buffer_head sb_bh; + struct buffer_head gdesc_bh; + char gdesc_buf[BV_TEST_BLK_SIZE] __aligned(8); + char ind_buf[BV_TEST_BLK_SIZE] __aligned(8); + + struct ext4_group_desc gdps[BV_TEST_NGROUPS]; + journal_t mock_journal; + + struct bv_test_inode_slot slots[BV_TEST_MAX_SLOTS]; + + /* Fault injection and call tracking */ + int fail_iget_err; + unsigned int iget_calls; + ext4_iget_flags last_iget_flags; + + int fail_map_err; + unsigned int fail_map_on_call; + unsigned int map_calls; +}; + +static inline ext4_fsblk_t bv_group_first_blk(ext4_group_t g) +{ + return BV_TEST_FIRST_DATA_BLK + + (ext4_fsblk_t)g * BV_TEST_BLOCKS_PER_GRP; +} + +/* + * Number of base metadata blocks in group @g under the default 4-group + * sparse_super configuration (groups 0, 1, 3 have super + 1 gdb + 2 rsv_gdt; + * group 2 has 0). + */ +static inline unsigned int bv_default_base_meta(ext4_group_t g) +{ + if (g == 2) + return 0; + return 1U + BV_TEST_GDB_COUNT + BV_TEST_RSV_GDT_BLKS; +} + +static inline ext4_fsblk_t bv_default_bbitmap_blk(ext4_group_t g) +{ + return bv_group_first_blk(g) + bv_default_base_meta(g); +} + +static inline ext4_fsblk_t bv_default_ibitmap_blk(ext4_group_t g) +{ + return bv_default_bbitmap_blk(g) + 1ULL; +} + +static inline ext4_fsblk_t bv_default_itable_blk(ext4_group_t g) +{ + return bv_default_ibitmap_blk(g) + 1ULL; +} + +static inline ext4_fsblk_t bv_default_first_free_blk(ext4_group_t g) +{ + return bv_default_itable_blk(g) + BV_TEST_ITB_PER_GRP; +} + +static void bv_test_sb_upd_work(struct work_struct *work) +{ +} + +static void bv_test_err_timer(struct timer_list *t) +{ +} + +static unsigned long bv_dummy_shrinker_count(struct shrinker *shrink, + struct shrink_control *sc) +{ + return 0; +} + +static unsigned long bv_dummy_shrinker_scan(struct shrinker *shrink, + struct shrink_control *sc) +{ + return SHRINK_STOP; +} + +static void bv_test_init_ei_fields(struct ext4_inode_info *ei) +{ + inode_set_iversion(&ei->vfs_inode, 1); + ei->i_flags = 0; + ext4_clear_state_flags(ei); + spin_lock_init(&ei->i_raw_lock); + ei->i_prealloc_node = RB_ROOT; + atomic_set(&ei->i_prealloc_active, 0); + rwlock_init(&ei->i_prealloc_lock); + ext4_es_init_tree(&ei->i_es_tree); + rwlock_init(&ei->i_es_lock); + INIT_LIST_HEAD(&ei->i_es_list); + ei->i_es_all_nr = 0; + ei->i_es_shk_nr = 0; + ei->i_es_shrink_lblk = 0; + ei->i_es_seq = 0; + ei->i_reserved_data_blocks = 0; + spin_lock_init(&ei->i_block_reservation_lock); + ext4_init_pending_tree(&ei->i_pending_tree); +#ifdef CONFIG_QUOTA + ei->i_reserved_quota = 0; + memset(&ei->i_dquot, 0, sizeof(ei->i_dquot)); +#endif +#ifdef CONFIG_FS_ENCRYPTION + ei->i_crypt_info = NULL; +#endif + ei->jinode = NULL; + init_rwsem(&ei->xattr_sem); + INIT_LIST_HEAD(&ei->i_rsv_conversion_list); + spin_lock_init(&ei->i_completed_io_lock); + ei->i_sync_tid = 0; + ei->i_datasync_tid = 0; + INIT_LIST_HEAD(&ei->i_orphan); + ext4_fc_init_inode(&ei->vfs_inode); + spin_lock_init(&ei->i_fc_lock); + ei->i_metadata_bhs = NULL; + ei->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + ei->i_extra_isize = BV_TEST_EXTRA_ISIZE; + ei->i_last_alloc_group = ~0U; +} + +static struct inode *bv_test_alloc_inode(struct super_block *sb) +{ + struct ext4_inode_info *ei; + + ei = kzalloc_obj(*ei); + if (!ei) + return NULL; + + init_rwsem(&ei->i_data_sem); + inode_init_once(&ei->vfs_inode); + bv_test_init_ei_fields(ei); + return &ei->vfs_inode; +} + +static void bv_test_evict_inode(struct inode *inode) +{ + truncate_inode_pages_final(&inode->i_data); + ext4_clear_inode(inode); +} + +static void bv_test_destroy_inode(struct inode *inode) +{ + kfree(ext4_i_metadata_bhs(inode)); + EXT4_I(inode)->i_metadata_bhs = NULL; +} + +static void bv_test_free_inode_mem(struct inode *inode) +{ + kfree(EXT4_I(inode)); +} + +#ifdef CONFIG_QUOTA +static struct dquot __rcu **bv_test_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} +#endif + +static const struct super_operations bv_test_sops = { + .alloc_inode = bv_test_alloc_inode, + .evict_inode = bv_test_evict_inode, + .destroy_inode = bv_test_destroy_inode, + .free_inode = bv_test_free_inode_mem, + .drop_inode = inode_just_drop, +#ifdef CONFIG_QUOTA + .get_dquots = bv_test_get_dquots, +#endif +}; + +static int bv_test_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static struct file_system_type bv_test_fs_type = { + .name = "ext4_bv_kunit", + .init_fs_context = bv_test_init_fs_context, + .kill_sb = kill_anon_super, +}; + +/* --- Helpers & Static Stubs --- */ + +static void bv_release_system_zone_locked(struct super_block *sb) +{ + down_write(&sb->s_umount); + ext4_release_system_zone(sb); + up_write(&sb->s_umount); +} + +static struct bv_test_inode_slot * +bv_find_slot(struct bv_test_ctx *ctx, unsigned long ino) +{ + unsigned int i; + + for (i = 0; i < BV_TEST_MAX_SLOTS; i++) { + if (ctx->slots[i].in_use && ctx->slots[i].ino == ino) + return &ctx->slots[i]; + } + return NULL; +} + +static struct inode *bv_create_inode(struct kunit *test, + struct bv_test_ctx *ctx, + unsigned long ino, umode_t mode, + bool use_extents) +{ + struct bv_test_inode_slot *slot = NULL; + struct ext4_extent_header *eh; + struct inode *inode; + unsigned int i; + + for (i = 0; i < BV_TEST_MAX_SLOTS; i++) { + if (!ctx->slots[i].in_use) { + slot = &ctx->slots[i]; + break; + } + } + KUNIT_ASSERT_NOT_NULL(test, slot); + + inode = new_inode(ctx->sb); + KUNIT_ASSERT_NOT_NULL(test, inode); + + slot->in_use = true; + slot->ino = ino; + slot->inode = inode; + + inode->i_ino = ino; + inode->i_mode = mode; + inode->i_blkbits = ctx->sb->s_blocksize_bits; + inode->i_flags |= S_NOQUOTA; + set_nlink(inode, 1); + EXT4_I(inode)->i_block_group = (ino - 1) / BV_TEST_INODES_PER_GRP; + memset(EXT4_I(inode)->i_data, 0, sizeof(EXT4_I(inode)->i_data)); + + if (use_extents) { + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + eh = ext_inode_hdr(inode); + eh->eh_magic = EXT4_EXT_MAGIC; + eh->eh_entries = 0; + eh->eh_max = cpu_to_le16((sizeof(EXT4_I(inode)->i_data) - + sizeof(*eh)) / + sizeof(struct ext4_extent)); + eh->eh_depth = 0; + } + + return inode; +} + +static void bv_append_extent(struct kunit *test, struct inode *inode, + ext4_lblk_t lblk, ext4_fsblk_t pblk, + unsigned short len) +{ + struct ext4_extent_header *eh = ext_inode_hdr(inode); + u16 entries = le16_to_cpu(eh->eh_entries); + struct ext4_extent *ex; + + KUNIT_ASSERT_LT(test, entries, le16_to_cpu(eh->eh_max)); + ex = EXT_FIRST_EXTENT(eh) + entries; + ex->ee_block = cpu_to_le32(lblk); + ex->ee_len = cpu_to_le16(len); + ext4_ext_store_pblock(ex, pblk); + eh->eh_entries = cpu_to_le16(entries + 1); +} + +static void bv_set_group_meta(struct super_block *sb, + struct ext4_group_desc *gdp, + ext4_fsblk_t bbitmap, ext4_fsblk_t ibitmap, + ext4_fsblk_t itable) +{ + ext4_block_bitmap_set(sb, gdp, bbitmap); + ext4_inode_bitmap_set(sb, gdp, ibitmap); + ext4_inode_table_set(sb, gdp, itable); +} + +static void bv_clear_fs_error(struct bv_test_ctx *ctx) +{ + ctx->sbi.s_mount_state &= ~EXT4_ERROR_FS; + ctx->es.s_last_error_block = 0; + ctx->es.s_last_error_ino = 0; + ctx->es.s_last_error_errcode = 0; +} + +static struct ext4_group_desc * +bv_get_group_desc_stub(struct super_block *sb, ext4_group_t block_group, + struct buffer_head **bh) +{ + struct kunit *test = kunit_get_current_test(); + struct bv_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx || block_group >= BV_TEST_NGROUPS) + return NULL; + if (bh) + *bh = &ctx->gdesc_bh; + return &ctx->gdps[block_group]; +} + +static struct inode *bv_iget_stub(struct super_block *sb, unsigned long ino, + ext4_iget_flags flags, const char *function, + unsigned int line) +{ + struct kunit *test = kunit_get_current_test(); + struct bv_test_ctx *ctx = test ? test->priv : NULL; + struct bv_test_inode_slot *slot; + + if (!ctx) + return ERR_PTR(-EIO); + + ctx->iget_calls++; + ctx->last_iget_flags = flags; + if (ctx->fail_iget_err) + return ERR_PTR(ctx->fail_iget_err); + + slot = bv_find_slot(ctx, ino); + if (!slot || !slot->inode) + return ERR_PTR(-ENOENT); + + ihold(slot->inode); + return slot->inode; +} + +static int bv_map_blocks_fault_stub(handle_t *handle, struct inode *inode, + struct ext4_map_blocks *map, int flags) +{ + struct kunit *test = kunit_get_current_test(); + struct bv_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) + return -EIO; + + ctx->map_calls++; + if (ctx->fail_map_err && + (!ctx->fail_map_on_call || + ctx->map_calls == ctx->fail_map_on_call)) + return ctx->fail_map_err; + + map->m_pblk = bv_default_first_free_blk(0) + map->m_lblk; + map->m_len = 1; + map->m_flags = EXT4_MAP_MAPPED; + return 1; +} + +/* --- Fixture Setup & Teardown --- */ + +static void bv_test_cleanup(struct bv_test_ctx *ctx) +{ + unsigned int i; + + ctx->sbi.s_journal = NULL; + bv_release_system_zone_locked(ctx->sb); + + for (i = 0; i < BV_TEST_MAX_SLOTS; i++) { + struct inode *inode = ctx->slots[i].inode; + + if (!inode) + continue; + spin_lock(&inode->i_lock); + inode_state_clear(inode, I_DIRTY_TIME | I_NEW); + spin_unlock(&inode->i_lock); + set_nlink(inode, 1); + iput(inode); + ctx->slots[i].inode = NULL; + ctx->slots[i].in_use = false; + } + + deactivate_super(ctx->sb); + ext4_es_unregister_shrinker(&ctx->sbi); + ext4_es_destroy_stats(&ctx->sbi); + rcu_barrier(); + + cancel_work_sync(&ctx->sbi.s_sb_upd_work); + timer_delete_sync(&ctx->sbi.s_err_report); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); +} + +KUNIT_DEFINE_ACTION_WRAPPER(bv_test_cleanup_action, bv_test_cleanup, + struct bv_test_ctx *); + +static int bv_test_init(struct kunit *test) +{ + struct bv_test_ctx *ctx; + struct fs_context *fc; + struct super_block *sb; + struct ext4_sb_info *sbi; + struct inode *root_inode; + ext4_group_t g; + int err; + + ctx = kzalloc_obj(*ctx); + KUNIT_ASSERT_NOT_NULL(test, ctx); + test->priv = ctx; + + ctx->bdev.bd_stats = alloc_percpu(struct disk_stats); + if (!ctx->bdev.bd_stats) { + kfree(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc bd_stats"); + } + + fc = fs_context_for_mount(&bv_test_fs_type, 0); + if (IS_ERR(fc)) { + err = PTR_ERR(fc); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + sb = sget_fc(fc, NULL, set_anon_super_fc); + put_fs_context(fc); + if (IS_ERR(sb)) { + err = PTR_ERR(sb); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + ctx->sb = sb; + sbi = &ctx->sbi; + + sbi->s_sb = sb; + sb->s_fs_info = sbi; + sb->s_op = &bv_test_sops; +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; +#endif + sb->s_flags |= SB_ACTIVE; + sb->s_blocksize = BV_TEST_BLK_SIZE; + sb->s_blocksize_bits = BV_TEST_BLK_BITS; + sb->s_maxbytes = MAX_LFS_FILESIZE; + sb->s_time_gran = 1; + sb->s_xattr = ext4_xattr_handlers; + strscpy(sb->s_id, "ext4_bv_kunit", sizeof(sb->s_id)); + + inode_init_once(&ctx->bd_inode); + ctx->bd_inode.i_sb = sb; + ctx->bd_inode.i_blkbits = BV_TEST_BLK_BITS; + ctx->bd_inode.i_mapping = &ctx->bd_inode.i_data; + ctx->bd_inode.i_data.host = &ctx->bd_inode; + ctx->bdev_queue.limits.logical_block_size = 512; + ctx->bdev_queue.limits.dma_alignment = 511; + ctx->bdev_disk.part0 = &ctx->bdev; + ctx->bdev_disk.queue = &ctx->bdev_queue; + ctx->bdev.bd_disk = &ctx->bdev_disk; + ctx->bdev.bd_queue = &ctx->bdev_queue; + ctx->bdev.bd_mapping = &ctx->bd_inode.i_data; + bdev_clear_flag(&ctx->bdev, BD_READ_ONLY); + sb->s_bdev = &ctx->bdev; + + bgl_lock_init(&ctx->bgl); + sbi->s_blockgroup_lock = &ctx->bgl; + + sbi->s_es = &ctx->es; + ctx->es.s_magic = cpu_to_le16(EXT4_SUPER_MAGIC); + ctx->es.s_first_data_block = cpu_to_le32(BV_TEST_FIRST_DATA_BLK); + ctx->es.s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + ctx->es.s_creator_os = cpu_to_le32(EXT4_OS_LINUX); + ctx->es.s_inodes_count = cpu_to_le32(BV_TEST_TOTAL_INODES); + ctx->es.s_inodes_per_group = cpu_to_le32(BV_TEST_INODES_PER_GRP); + ctx->es.s_blocks_per_group = cpu_to_le32(BV_TEST_BLOCKS_PER_GRP); + ctx->es.s_clusters_per_group = cpu_to_le32(BV_TEST_BLOCKS_PER_GRP); + ctx->es.s_first_ino = cpu_to_le32(BV_TEST_FIRST_INO); + ctx->es.s_inode_size = cpu_to_le16(BV_TEST_INODE_SIZE); + ctx->es.s_min_extra_isize = cpu_to_le16(BV_TEST_EXTRA_ISIZE); + ctx->es.s_want_extra_isize = cpu_to_le16(BV_TEST_EXTRA_ISIZE); + ctx->es.s_reserved_gdt_blocks = cpu_to_le16(BV_TEST_RSV_GDT_BLKS); + ctx->es.s_checksum_type = EXT4_CRC32C_CHKSUM; + ext4_blocks_count_set(&ctx->es, BV_TEST_TOTAL_BLKS); + + ext4_set_feature_sparse_super(sb); + ext4_set_feature_extents(sb); + ext4_set_feature_extra_isize(sb); + ext4_set_feature_metadata_csum(sb); + ext4_set_feature_64bit(sb); + + ctx->sb_bh.b_data = (char *)&ctx->es; + ctx->sb_bh.b_size = sizeof(ctx->es); + ctx->sb_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->sb_bh.b_count, 1); + set_buffer_uptodate(&ctx->sb_bh); + sbi->s_sbh = &ctx->sb_bh; + + ctx->gdesc_bh.b_data = ctx->gdesc_buf; + ctx->gdesc_bh.b_size = BV_TEST_BLK_SIZE; + ctx->gdesc_bh.b_blocknr = BV_TEST_GDESC_BLK; + ctx->gdesc_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->gdesc_bh.b_count, 1); + set_buffer_uptodate(&ctx->gdesc_bh); + + sbi->s_inode_size = BV_TEST_INODE_SIZE; + sbi->s_inodes_per_block = BV_TEST_INODES_PER_BLK; + sbi->s_inodes_per_group = BV_TEST_INODES_PER_GRP; + sbi->s_itb_per_group = BV_TEST_ITB_PER_GRP; + sbi->s_first_ino = BV_TEST_FIRST_INO; + sbi->s_want_extra_isize = BV_TEST_EXTRA_ISIZE; + sbi->s_blocks_per_group = BV_TEST_BLOCKS_PER_GRP; + sbi->s_clusters_per_group = BV_TEST_BLOCKS_PER_GRP; + sbi->s_cluster_ratio = 1; + sbi->s_cluster_bits = 0; + sbi->s_groups_count = BV_TEST_NGROUPS; + sbi->s_gdb_count = BV_TEST_GDB_COUNT; + sbi->s_desc_size = EXT4_MIN_DESC_SIZE_64BIT; + sbi->s_desc_per_block = BV_TEST_BLK_SIZE / EXT4_MIN_DESC_SIZE_64BIT; + sbi->s_desc_per_block_bits = ilog2(sbi->s_desc_per_block); + sbi->s_bitmap_maxbytes = 0x1ff7ffff000ULL; + + mutex_init(&sbi->s_orphan_lock); + INIT_LIST_HEAD(&sbi->s_orphan); + set_opt(sb, ERRORS_CONT); + spin_lock_init(&sbi->s_bdev_wb_lock); + spin_lock_init(&sbi->s_error_lock); + spin_lock_init(&sbi->s_md_lock); + INIT_WORK(&sbi->s_sb_upd_work, bv_test_sb_upd_work); + timer_setup(&sbi->s_err_report, bv_test_err_timer, 0); + mutex_init(&sbi->s_fc_lock); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_STAGING]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_STAGING]); + + ratelimit_state_init(&sbi->s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + + for (g = 0; g < BV_TEST_NGROUPS; g++) { + bv_set_group_meta(sb, &ctx->gdps[g], + bv_default_bbitmap_blk(g), + bv_default_ibitmap_blk(g), + bv_default_itable_blk(g)); + } + + err = ext4_es_register_shrinker(sbi); + if (err) { + deactivate_locked_super(sb); + rcu_barrier(); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + WRITE_ONCE(sbi->s_es_shrinker->count_objects, bv_dummy_shrinker_count); + WRITE_ONCE(sbi->s_es_shrinker->scan_objects, bv_dummy_shrinker_scan); + + root_inode = new_inode(sb); + if (!root_inode) { + deactivate_locked_super(sb); + ext4_es_unregister_shrinker(sbi); + ext4_es_destroy_stats(sbi); + rcu_barrier(); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc root_inode"); + } + root_inode->i_ino = EXT4_ROOT_INO; + root_inode->i_mode = S_IFDIR | 0755; + root_inode->i_op = &simple_dir_inode_operations; + set_nlink(root_inode, 2); + sb->s_root = d_make_root(root_inode); + if (!sb->s_root) { + deactivate_locked_super(sb); + ext4_es_unregister_shrinker(sbi); + ext4_es_destroy_stats(sbi); + rcu_barrier(); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to create s_root"); + } + + up_write(&sb->s_umount); + + kunit_activate_static_stub(test, ext4_get_group_desc, + bv_get_group_desc_stub); + kunit_activate_static_stub(test, __ext4_iget, bv_iget_stub); + + err = kunit_add_action_or_reset(test, bv_test_cleanup_action, ctx); + KUNIT_ASSERT_EQ(test, err, 0); + return 0; +} + +/* --- Parameterized Test 1: Bounds & 64-bit Overflow Checks --- */ + +struct bv_bounds_case { + const char *desc; + u32 first_data_blk; + ext4_fsblk_t total_blks; + bool enable_64bit; + ext4_fsblk_t start_blk; + unsigned int count; + int expected; +}; + +static const struct bv_bounds_case bv_bounds_cases[] = { + { + .desc = "1k_block_0_below_first_data", + .first_data_blk = 1, + .total_blks = 4097, + .enable_64bit = true, + .start_blk = 0, + .count = 1, + .expected = 0, + }, + { + .desc = "1k_block_1_equals_first_data", + .first_data_blk = 1, + .total_blks = 4097, + .enable_64bit = true, + .start_blk = 1, + .count = 1, + .expected = 0, + }, + { + .desc = "1k_block_2_just_above_first_data", + .first_data_blk = 1, + .total_blks = 4097, + .enable_64bit = true, + .start_blk = 2, + .count = 1, + .expected = 1, + }, + { + .desc = "4k_block_0_equals_first_data", + .first_data_blk = 0, + .total_blks = 4096, + .enable_64bit = true, + .start_blk = 0, + .count = 1, + .expected = 0, + }, + { + .desc = "4k_block_1_just_above_first_data", + .first_data_blk = 0, + .total_blks = 4096, + .enable_64bit = true, + .start_blk = 1, + .count = 1, + .expected = 1, + }, + { + .desc = "exact_last_single_block", + .first_data_blk = 1, + .total_blks = 4097, + .enable_64bit = true, + .start_blk = 4096, + .count = 1, + .expected = 1, + }, + { + .desc = "multiblock_ending_at_last_block", + .first_data_blk = 1, + .total_blks = 4097, + .enable_64bit = true, + .start_blk = 4093, + .count = 4, + .expected = 1, + }, + { + .desc = "multiblock_exceeding_end_by_one", + .first_data_blk = 1, + .total_blks = 4097, + .enable_64bit = true, + .start_blk = 4093, + .count = 5, + .expected = 0, + }, + { + .desc = "start_at_blocks_count", + .first_data_blk = 1, + .total_blks = 4097, + .enable_64bit = true, + .start_blk = 4097, + .count = 1, + .expected = 0, + }, + { + .desc = "u64_wrap_around_into_in_bounds_value", + .first_data_blk = 1, + .total_blks = 4097, + .enable_64bit = true, + .start_blk = U64_MAX - 3ULL, + .count = 10, + .expected = 0, + }, + { + .desc = "u64_max_single_block_overflow", + .first_data_blk = 1, + .total_blks = 4097, + .enable_64bit = true, + .start_blk = U64_MAX, + .count = 1, + .expected = 0, + }, + { + .desc = "64bit_high_block_at_exact_end", + .first_data_blk = 0, + .total_blks = (1ULL << 33) + 64ULL, + .enable_64bit = true, + .start_blk = (1ULL << 33) + 60ULL, + .count = 4, + .expected = 1, + }, + { + .desc = "32bit_fs_ignores_high_blocks_count", + .first_data_blk = 0, + .total_blks = (1ULL << 33) + 4096ULL, + .enable_64bit = false, + .start_blk = (1ULL << 33) + 10ULL, + .count = 1, + .expected = 0, + }, +}; + +KUNIT_ARRAY_PARAM_DESC(bv_bounds, bv_bounds_cases, desc); + +static void test_sb_block_valid_bounds(struct kunit *test) +{ + const struct bv_bounds_case *tc = test->param_value; + struct bv_test_ctx *ctx = test->priv; + struct inode *inode; + + ctx->es.s_first_data_block = cpu_to_le32(tc->first_data_blk); + ext4_blocks_count_set(&ctx->es, tc->total_blks); + if (tc->enable_64bit) + ext4_set_feature_64bit(ctx->sb); + else + ext4_clear_feature_64bit(ctx->sb); + + inode = bv_create_inode(test, ctx, 12, S_IFREG | 0644, true); + + KUNIT_EXPECT_EQ(test, + ext4_sb_block_valid(ctx->sb, NULL, tc->start_blk, + tc->count), + tc->expected); + KUNIT_EXPECT_EQ(test, + ext4_inode_block_valid(inode, tc->start_blk, tc->count), + tc->expected); +} + +/* --- Test 2: Setup and Release Lifecycle (noblock_validity / RCU) --- */ + +static void test_release_system_zone_lifecycle(struct kunit *test) +{ + struct bv_test_ctx *ctx = test->priv; + ext4_fsblk_t meta_blk = bv_default_bbitmap_blk(0); + ext4_fsblk_t data_blk = bv_default_first_free_blk(0); + + /* + * Before ext4_setup_system_zone(), s_system_blks is NULL: releasing is + * a safe no-op and metadata block numbers pass validity as long as + * they are within (s_first_data_block, blocks_count]. + */ + KUNIT_EXPECT_NULL(test, rcu_access_pointer(ctx->sbi.s_system_blks)); + bv_release_system_zone_locked(ctx->sb); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, meta_blk, 1), + 1); + KUNIT_EXPECT_EQ(test, + ext4_sb_block_valid(ctx->sb, NULL, + BV_TEST_FIRST_DATA_BLK, 1), + 0); + + KUNIT_ASSERT_EQ(test, ext4_setup_system_zone(ctx->sb), 0); + KUNIT_EXPECT_NOT_NULL(test, + rcu_access_pointer(ctx->sbi.s_system_blks)); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, meta_blk, 1), + 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, data_blk, 1), + 1); + + /* + * Releasing clears s_system_blks immediately and frees the rbtree via + * RCU; repeating release when already NULL remains a safe no-op. + */ + bv_release_system_zone_locked(ctx->sb); + rcu_barrier(); + KUNIT_EXPECT_NULL(test, rcu_access_pointer(ctx->sbi.s_system_blks)); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, meta_blk, 1), + 1); + + bv_release_system_zone_locked(ctx->sb); +} + +/* --- Test 3: Multi-group sparse_super, flex_bg, and DEBUG Tree Print --- */ + +static void test_setup_multigroup_sparse_super_and_flex_bg(struct kunit *test) +{ + struct bv_test_ctx *ctx = test->priv; + ext4_fsblk_t g2_bbitmap = 20ULL; + ext4_fsblk_t g2_ibitmap = 22ULL; + ext4_fsblk_t g2_itable = 30ULL; + + /* + * Relocate group 2's bitmaps and inode table into group 0 (flex_bg + * layout). Since group 2 also has 0 base metadata blocks under + * sparse_super, every block in group 2 (2049..3072) becomes valid for + * data, while group 0 gains three separated system zones. + */ + bv_set_group_meta(ctx->sb, &ctx->gdps[2], g2_bbitmap, g2_ibitmap, + g2_itable); + set_opt(ctx->sb, DEBUG); + + KUNIT_ASSERT_EQ(test, ext4_setup_system_zone(ctx->sb), 0); + + /* Group 0 contiguous metadata [1..14] rejected; gap [15..19] valid */ + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 2, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 14, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 15, 5), 1); + + /* Relocated group 2 metadata inside group 0 and surrounding gaps */ + KUNIT_EXPECT_EQ(test, + ext4_sb_block_valid(ctx->sb, NULL, g2_bbitmap, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 21, 1), 1); + KUNIT_EXPECT_EQ(test, + ext4_sb_block_valid(ctx->sb, NULL, g2_ibitmap, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 23, 7), 1); + KUNIT_EXPECT_EQ(test, + ext4_sb_block_valid(ctx->sb, NULL, g2_itable, 1), 0); + KUNIT_EXPECT_EQ(test, + ext4_sb_block_valid(ctx->sb, NULL, + g2_itable + BV_TEST_ITB_PER_GRP - 1, + 1), + 0); + KUNIT_EXPECT_EQ(test, + ext4_sb_block_valid(ctx->sb, NULL, + g2_itable + BV_TEST_ITB_PER_GRP, + 10), + 1); + + /* Group 1 [1025..1038] protected, 1024 and 1039 valid */ + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 1024, 1), 1); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 1025, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 1038, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 1039, 1), 1); + + /* Group 2 [2049..3072] has zero metadata blocks at all */ + KUNIT_EXPECT_EQ(test, ext4_num_base_meta_blocks(ctx->sb, 2), 0U); + KUNIT_EXPECT_EQ(test, + ext4_sb_block_valid(ctx->sb, NULL, + bv_group_first_blk(2), + BV_TEST_BLOCKS_PER_GRP), + 1); + + /* Group 3 (backup superblock 3^1): [3073..3086] protected, 3087+ ok */ + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 3073, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 3086, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 3087, 10), 1); +} + +/* --- Test 4: Left, Right, and 3-Way Bridge Merging (+ 64-bit Zones) --- */ + +static void test_rbtree_left_right_and_bridge_merges(struct kunit *test) +{ + struct bv_test_ctx *ctx = test->priv; + ext4_fsblk_t hi_base = (1ULL << 33) + 100ULL; + + ext4_blocks_count_set(&ctx->es, hi_base + 512ULL); + + /* + * Group 0: base_meta = [1..4], bbitmap = 5 (merges left -> [1..5]), + * ibitmap = 14 (standalone [14..14]), itable = [6..13] (bridges + * [1..5] on the left AND [14..14] on the right into [1..14]). + */ + bv_set_group_meta(ctx->sb, &ctx->gdps[0], 5ULL, 14ULL, 6ULL); + + /* + * Group 2 (0 base meta): bbitmap = 2100, ibitmap = 2099 (inserted left + * of 2100 and merges right into [2099..2100]), itable = [2110..2117]. + */ + bv_set_group_meta(ctx->sb, &ctx->gdps[2], 2100ULL, 2099ULL, 2110ULL); + + /* + * Group 3: relocate bbitmap/ibitmap/itable above 2^32 to exercise + * 64-bit group descriptor blocks and 3-way merge above 4G blocks: + * bbitmap = hi_base, ibitmap = hi_base + 9, itable = hi_base + 1..8 + * -> merged 10-block 64-bit zone [hi_base .. hi_base + 9]. + */ + bv_set_group_meta(ctx->sb, &ctx->gdps[3], hi_base, hi_base + 9ULL, + hi_base + 1ULL); + + KUNIT_ASSERT_EQ(test, ext4_setup_system_zone(ctx->sb), 0); + + /* Group 0 bridged zone [1..14] */ + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 5, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 6, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 13, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 14, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 15, 1), 1); + + /* Group 2 right-merged zone [2099..2100] and separate [2110..2117] */ + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 2098, 1), 1); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 2099, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 2100, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 2101, 9), 1); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 2110, 8), 0); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 2118, 1), 1); + + /* Group 3 64-bit bridged zone [hi_base .. hi_base + 9] */ + KUNIT_EXPECT_EQ(test, + ext4_sb_block_valid(ctx->sb, NULL, hi_base - 1ULL, 1), + 1); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, hi_base, 1), + 0); + KUNIT_EXPECT_EQ(test, + ext4_sb_block_valid(ctx->sb, NULL, hi_base + 5ULL, 1), + 0); + KUNIT_EXPECT_EQ(test, + ext4_sb_block_valid(ctx->sb, NULL, hi_base + 9ULL, 1), + 0); + KUNIT_EXPECT_EQ(test, + ext4_sb_block_valid(ctx->sb, NULL, hi_base + 10ULL, 4), + 1); +} + +/* --- Parameterized Test 5: Interval Overlap Geometries --- */ + +/* + * Tests against an isolated 8-block system zone [50, 58) (blocks 50..57) + * surrounded by valid data blocks on both sides. + */ +struct bv_overlap_case { + const char *desc; + ext4_fsblk_t start_blk; + unsigned int count; + int expected; +}; + +static const struct bv_overlap_case bv_overlap_cases[] = { + { + .desc = "strictly_before_adjacent", + .start_blk = 46, + .count = 4, + .expected = 1, + }, + { + .desc = "strictly_after_adjacent", + .start_blk = 58, + .count = 4, + .expected = 1, + }, + { + .desc = "single_first_block_of_zone", + .start_blk = 50, + .count = 1, + .expected = 0, + }, + { + .desc = "single_interior_block_of_zone", + .start_blk = 54, + .count = 1, + .expected = 0, + }, + { + .desc = "single_last_block_of_zone", + .start_blk = 57, + .count = 1, + .expected = 0, + }, + { + .desc = "straddle_left_boundary_by_one", + .start_blk = 47, + .count = 4, + .expected = 0, + }, + { + .desc = "straddle_right_boundary_by_one", + .start_blk = 57, + .count = 4, + .expected = 0, + }, + { + .desc = "strictly_inside_zone", + .start_blk = 52, + .count = 3, + .expected = 0, + }, + { + .desc = "exact_zone_span", + .start_blk = 50, + .count = 8, + .expected = 0, + }, + { + .desc = "strictly_enclosing_entire_zone", + .start_blk = 45, + .count = 20, + .expected = 0, + }, +}; + +KUNIT_ARRAY_PARAM_DESC(bv_overlap, bv_overlap_cases, desc); + +static void test_sb_block_valid_interval_overlaps(struct kunit *test) +{ + const struct bv_overlap_case *tc = test->param_value; + struct bv_test_ctx *ctx = test->priv; + struct inode *inode; + + /* Place group 2's 8-block inode table at [50..57] */ + bv_set_group_meta(ctx->sb, &ctx->gdps[2], 2049ULL, 2050ULL, 50ULL); + KUNIT_ASSERT_EQ(test, ext4_setup_system_zone(ctx->sb), 0); + + inode = bv_create_inode(test, ctx, 13, S_IFREG | 0644, true); + + KUNIT_EXPECT_EQ(test, + ext4_sb_block_valid(ctx->sb, NULL, tc->start_blk, + tc->count), + tc->expected); + KUNIT_EXPECT_EQ(test, + ext4_inode_block_valid(inode, tc->start_blk, tc->count), + tc->expected); +} + +/* --- Parameterized Test 6: Corrupt Overlapping Group Metadata --- */ + +struct bv_corrupt_meta_case { + const char *desc; + ext4_group_t grp; + ext4_fsblk_t bbitmap; + ext4_fsblk_t ibitmap; + ext4_fsblk_t itable; +}; + +static const struct bv_corrupt_meta_case bv_corrupt_meta_cases[] = { + { + .desc = "bbitmap_overlaps_group0_base_meta", + .grp = 0, + .bbitmap = 2, + .ibitmap = 6, + .itable = 7, + }, + { + .desc = "ibitmap_collides_with_bbitmap", + .grp = 0, + .bbitmap = 20, + .ibitmap = 20, + .itable = 30, + }, + { + .desc = "itable_collides_with_ibitmap", + .grp = 0, + .bbitmap = 20, + .ibitmap = 25, + .itable = 25, + }, + { + .desc = "group2_bbitmap_collides_with_group0_itable", + .grp = 2, + .bbitmap = 10, + .ibitmap = 2050, + .itable = 2051, + }, + { + .desc = "itable_starts_before_and_overlaps_bbitmap", + .grp = 0, + .bbitmap = 20, + .ibitmap = 40, + .itable = 15, + }, + { + .desc = "itable_starts_before_and_encloses_ibitmap", + .grp = 2, + .bbitmap = 50, + .ibitmap = 55, + .itable = 52, + }, + { + .desc = "itable_u64_wrap_around_overflow", + .grp = 2, + .bbitmap = 2049, + .ibitmap = 2050, + .itable = U64_MAX - 2ULL, + }, +}; + +KUNIT_ARRAY_PARAM_DESC(bv_corrupt_meta, bv_corrupt_meta_cases, desc); + +static void test_setup_corrupt_group_metadata_overlaps(struct kunit *test) +{ + const struct bv_corrupt_meta_case *tc = test->param_value; + struct bv_test_ctx *ctx = test->priv; + + bv_set_group_meta(ctx->sb, &ctx->gdps[tc->grp], tc->bbitmap, + tc->ibitmap, tc->itable); + + KUNIT_EXPECT_EQ(test, ext4_setup_system_zone(ctx->sb), -EFSCORRUPTED); + KUNIT_EXPECT_NULL(test, rcu_access_pointer(ctx->sbi.s_system_blks)); +} + +/* --- Test 7: Journal Reserved Inode Ownership & can_merge Isolation --- */ + +static void test_journal_inode_protection_and_ino_isolation(struct kunit *test) +{ + struct bv_test_ctx *ctx = test->priv; + struct inode *j_inode; + struct inode *reg_inode; + + /* + * Place group 2's block bitmap at block 20 (ino = 0) while group 0's + * metadata occupies [1..14] (ino = 0). + */ + bv_set_group_meta(ctx->sb, &ctx->gdps[2], 20ULL, 2050ULL, 2051ULL); + + ext4_set_feature_journal(ctx->sb); + ctx->es.s_journal_inum = cpu_to_le32(EXT4_JOURNAL_INO); + + j_inode = bv_create_inode(test, ctx, EXT4_JOURNAL_INO, + S_IFREG | 0600, true); + reg_inode = bv_create_inode(test, ctx, 14, S_IFREG | 0644, true); + + /* + * Non-block-aligned i_size (7 blocks + 1 byte -> rounds up to 8 logical + * blocks 0..7) with 4 real extents, an interior sparse hole at lblk 2, + * and a trailing sparse hole at lblk 7: + * - lblk [0..1] -> pblk [15..16] (right-adjacent to [1..14] ino=0) + * - lblk 2 -> sparse hole (n == 0) + * - lblk [3..4] -> pblk [18..19] (left-adjacent to [20..20] ino=0) + * - lblk 5 -> pblk [201..201] (ino=8) + * - lblk 6 -> pblk [200..200] (merges right with 201 -> [200..201]) + * - lblk 7 -> sparse hole (n == 0) + */ + i_size_write(j_inode, 7 * BV_TEST_BLK_SIZE + 1); + bv_append_extent(test, j_inode, 0, 15ULL, 2); + bv_append_extent(test, j_inode, 3, 18ULL, 2); + bv_append_extent(test, j_inode, 5, 201ULL, 1); + bv_append_extent(test, j_inode, 6, 200ULL, 1); + + KUNIT_ASSERT_EQ(test, ext4_setup_system_zone(ctx->sb), 0); + KUNIT_EXPECT_EQ(test, ctx->iget_calls, 1U); + KUNIT_EXPECT_TRUE(test, + (bool)(ctx->last_iget_flags & EXT4_IGET_SPECIAL)); + KUNIT_EXPECT_EQ(test, atomic_read(&j_inode->i_count), 1); + + /* Journal blocks are rejected for NULL and regular inodes */ + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 15, 2), 0); + KUNIT_EXPECT_EQ(test, ext4_inode_block_valid(reg_inode, 15, 2), 0); + KUNIT_EXPECT_EQ(test, ext4_inode_block_valid(reg_inode, 18, 2), 0); + KUNIT_EXPECT_EQ(test, ext4_inode_block_valid(reg_inode, 200, 2), 0); + + /* Journal inode is permitted on all of its own extents */ + KUNIT_EXPECT_EQ(test, ext4_inode_block_valid(j_inode, 15, 2), 1); + KUNIT_EXPECT_EQ(test, ext4_inode_block_valid(j_inode, 18, 2), 1); + KUNIT_EXPECT_EQ(test, ext4_inode_block_valid(j_inode, 200, 2), 1); + + /* + * Verify can_merge() kept ino=0 and ino=8 zones separate on both the + * left ([1..14] vs [15..16]) and right ([18..19] vs [20..20]): the + * journal inode must still be rejected on adjacent group metadata. + */ + KUNIT_EXPECT_EQ(test, ext4_inode_block_valid(j_inode, 14, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_inode_block_valid(j_inode, 20, 1), 0); + + /* Unmapped physical gap block 17 remains valid for regular files */ + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 17, 1), 1); + KUNIT_EXPECT_EQ(test, ext4_inode_block_valid(reg_inode, 17, 1), 1); +} + +/* --- Test 8: Disabled Journal Feature, Zero inum, and Empty Journal --- */ + +static void test_journal_disabled_or_empty_skips_zones(struct kunit *test) +{ + struct bv_test_ctx *ctx = test->priv; + struct inode *j_inode; + + j_inode = bv_create_inode(test, ctx, EXT4_JOURNAL_INO, + S_IFREG | 0600, true); + i_size_write(j_inode, 2 * BV_TEST_BLK_SIZE); + bv_append_extent(test, j_inode, 0, 100ULL, 2); + + /* Case 1: s_journal_inum set, but HAS_JOURNAL feature cleared */ + ext4_clear_feature_journal(ctx->sb); + ctx->es.s_journal_inum = cpu_to_le32(EXT4_JOURNAL_INO); + KUNIT_ASSERT_EQ(test, ext4_setup_system_zone(ctx->sb), 0); + KUNIT_EXPECT_EQ(test, ctx->iget_calls, 0U); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 100, 2), 1); + bv_release_system_zone_locked(ctx->sb); + + /* Case 2: HAS_JOURNAL set, but s_journal_inum == 0 */ + ext4_set_feature_journal(ctx->sb); + ctx->es.s_journal_inum = 0; + KUNIT_ASSERT_EQ(test, ext4_setup_system_zone(ctx->sb), 0); + KUNIT_EXPECT_EQ(test, ctx->iget_calls, 0U); + bv_release_system_zone_locked(ctx->sb); + + /* Case 3: HAS_JOURNAL + valid s_journal_inum, but i_size == 0 */ + ctx->es.s_journal_inum = cpu_to_le32(EXT4_JOURNAL_INO); + i_size_write(j_inode, 0); + KUNIT_ASSERT_EQ(test, ext4_setup_system_zone(ctx->sb), 0); + KUNIT_EXPECT_EQ(test, ctx->iget_calls, 1U); + KUNIT_EXPECT_EQ(test, atomic_read(&j_inode->i_count), 1); + KUNIT_EXPECT_EQ(test, ext4_sb_block_valid(ctx->sb, NULL, 100, 2), 1); +} + +/* --- Test 9: Journal Reserved Inode Error Paths --- */ + +static void test_journal_inode_invalid_inum(struct kunit *test) +{ + struct bv_test_ctx *ctx = test->priv; + + ext4_set_feature_journal(ctx->sb); + + /* Below EXT4_ROOT_INO (e.g. EXT4_BAD_INO = 1) */ + ctx->es.s_journal_inum = cpu_to_le32(EXT4_BAD_INO); + KUNIT_EXPECT_EQ(test, ext4_setup_system_zone(ctx->sb), -EINVAL); + KUNIT_EXPECT_EQ(test, ctx->iget_calls, 0U); + KUNIT_EXPECT_NULL(test, rcu_access_pointer(ctx->sbi.s_system_blks)); + + /* Above s_inodes_count */ + ctx->es.s_journal_inum = cpu_to_le32(BV_TEST_TOTAL_INODES + 1); + KUNIT_EXPECT_EQ(test, ext4_setup_system_zone(ctx->sb), -EINVAL); + KUNIT_EXPECT_EQ(test, ctx->iget_calls, 0U); + KUNIT_EXPECT_NULL(test, rcu_access_pointer(ctx->sbi.s_system_blks)); +} + +static void test_journal_inode_iget_error(struct kunit *test) +{ + struct bv_test_ctx *ctx = test->priv; + + ext4_set_feature_journal(ctx->sb); + ctx->es.s_journal_inum = cpu_to_le32(EXT4_JOURNAL_INO); + ctx->fail_iget_err = -EIO; + + KUNIT_EXPECT_EQ(test, ext4_setup_system_zone(ctx->sb), -EIO); + KUNIT_EXPECT_EQ(test, ctx->iget_calls, 1U); + KUNIT_EXPECT_NULL(test, rcu_access_pointer(ctx->sbi.s_system_blks)); +} + +static void test_journal_inode_map_blocks_error(struct kunit *test) +{ + struct bv_test_ctx *ctx = test->priv; + struct inode *j_inode; + + ext4_set_feature_journal(ctx->sb); + ctx->es.s_journal_inum = cpu_to_le32(EXT4_JOURNAL_INO); + j_inode = bv_create_inode(test, ctx, EXT4_JOURNAL_INO, + S_IFREG | 0600, true); + i_size_write(j_inode, 3 * BV_TEST_BLK_SIZE); + + /* Fail on 2nd ext4_map_blocks call after 1st extent was inserted */ + ctx->fail_map_err = -EIO; + ctx->fail_map_on_call = 2; + kunit_activate_static_stub(test, ext4_map_blocks, + bv_map_blocks_fault_stub); + + KUNIT_EXPECT_EQ(test, ext4_setup_system_zone(ctx->sb), -EIO); + KUNIT_EXPECT_EQ(test, ctx->map_calls, 2U); + KUNIT_EXPECT_EQ(test, atomic_read(&j_inode->i_count), 1); + KUNIT_EXPECT_FALSE(test, + (bool)(ctx->sbi.s_mount_state & EXT4_ERROR_FS)); + KUNIT_EXPECT_NULL(test, rcu_access_pointer(ctx->sbi.s_system_blks)); +} + +static void test_journal_inode_overlap_sets_fs_error(struct kunit *test) +{ + struct bv_test_ctx *ctx = test->priv; + struct inode *j_inode; + + ext4_set_feature_journal(ctx->sb); + ctx->es.s_journal_inum = cpu_to_le32(EXT4_JOURNAL_INO); + j_inode = bv_create_inode(test, ctx, EXT4_JOURNAL_INO, + S_IFREG | 0600, true); + i_size_write(j_inode, 2 * BV_TEST_BLK_SIZE); + + /* Extent at block 10 collides with group 0's inode table [7..14] */ + bv_append_extent(test, j_inode, 0, 10ULL, 2); + + KUNIT_EXPECT_EQ(test, ext4_setup_system_zone(ctx->sb), -EFSCORRUPTED); + KUNIT_EXPECT_TRUE(test, + (bool)(ctx->sbi.s_mount_state & EXT4_ERROR_FS)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_error_ino), + (u32)EXT4_JOURNAL_INO); + KUNIT_EXPECT_EQ(test, ctx->es.s_last_error_errcode, + EXT4_ERR_EFSCORRUPTED); + KUNIT_EXPECT_NULL(test, rcu_access_pointer(ctx->sbi.s_system_blks)); +} + +static void test_journal_extent_left_overlap_rejected(struct kunit *test) +{ + struct bv_test_ctx *ctx = test->priv; + struct inode *j_inode; + + /* + * Place group 2's block bitmap at block 20 (ino = 0) and map a + * multi-block journal extent at [18..21] that starts strictly before + * block 20 and extends across it. During ext4_setup_system_zone(), + * s_system_blks is still NULL when ext4_map_blocks() runs, so + * add_system_zone() must catch this left-traversal overlap. + */ + bv_set_group_meta(ctx->sb, &ctx->gdps[2], 20ULL, 2050ULL, 2051ULL); + ext4_set_feature_journal(ctx->sb); + ctx->es.s_journal_inum = cpu_to_le32(EXT4_JOURNAL_INO); + + j_inode = bv_create_inode(test, ctx, EXT4_JOURNAL_INO, + S_IFREG | 0600, true); + i_size_write(j_inode, 4 * BV_TEST_BLK_SIZE); + bv_append_extent(test, j_inode, 0, 18ULL, 4); + + KUNIT_EXPECT_EQ(test, ext4_setup_system_zone(ctx->sb), -EFSCORRUPTED); + KUNIT_EXPECT_TRUE(test, + (bool)(ctx->sbi.s_mount_state & EXT4_ERROR_FS)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_error_ino), + (u32)EXT4_JOURNAL_INO); + KUNIT_EXPECT_EQ(test, ctx->es.s_last_error_errcode, + EXT4_ERR_EFSCORRUPTED); + KUNIT_EXPECT_NULL(test, rcu_access_pointer(ctx->sbi.s_system_blks)); + + /* + * Also verify a journal extent [1020..1040] that completely encloses + * group 1's entire metadata zone [1025..1038]. + */ + bv_clear_fs_error(ctx); + ext4_es_remove_extent(j_inode, 0, EXT_MAX_BLOCKS); + ext_inode_hdr(j_inode)->eh_entries = 0; + i_size_write(j_inode, 21 * BV_TEST_BLK_SIZE); + bv_append_extent(test, j_inode, 0, 1020ULL, 21); + + KUNIT_EXPECT_EQ(test, ext4_setup_system_zone(ctx->sb), -EFSCORRUPTED); + KUNIT_EXPECT_TRUE(test, + (bool)(ctx->sbi.s_mount_state & EXT4_ERROR_FS)); + KUNIT_EXPECT_NULL(test, rcu_access_pointer(ctx->sbi.s_system_blks)); +} + +/* --- Test 10: ext4_check_blockref and Indirect Macros --- */ + +static void test_check_blockref_valid_and_sparse(struct kunit *test) +{ + struct bv_test_ctx *ctx = test->priv; + struct inode *inode; + __le32 zero_refs[4] = { 0, 0, 0, 0 }; + __le32 mixed_refs[5] = { + 0, + cpu_to_le32(15), + 0, + cpu_to_le32(1039), + cpu_to_le32(4096), + }; + __le32 bad_first = cpu_to_le32(7); + + KUNIT_ASSERT_EQ(test, ext4_setup_system_zone(ctx->sb), 0); + inode = bv_create_inode(test, ctx, 15, S_IFREG | 0644, false); + + /* max == 0 does not inspect entries */ + KUNIT_EXPECT_EQ(test, + ext4_check_blockref(__func__, __LINE__, inode, + &bad_first, 0), + 0); + KUNIT_EXPECT_EQ(test, + ext4_check_blockref(__func__, __LINE__, inode, + zero_refs, ARRAY_SIZE(zero_refs)), + 0); + KUNIT_EXPECT_EQ(test, + ext4_check_blockref(__func__, __LINE__, inode, + mixed_refs, ARRAY_SIZE(mixed_refs)), + 0); + KUNIT_EXPECT_FALSE(test, + (bool)(ctx->sbi.s_mount_state & EXT4_ERROR_FS)); +} + +static void +test_check_blockref_corrupt_entries_and_journal_bypass(struct kunit *test) +{ + struct bv_test_ctx *ctx = test->priv; + struct inode *reg_inode; + struct inode *j_inode; + __le32 meta_refs[4] = { + cpu_to_le32(15), + 0, + cpu_to_le32(7), + cpu_to_le32(9), + }; + __le32 oob_refs[2] = { + cpu_to_le32(16), + cpu_to_le32(BV_TEST_TOTAL_BLKS), + }; + + KUNIT_ASSERT_EQ(test, ext4_setup_system_zone(ctx->sb), 0); + reg_inode = bv_create_inode(test, ctx, 16, S_IFREG | 0644, false); + j_inode = bv_create_inode(test, ctx, EXT4_JOURNAL_INO, + S_IFREG | 0600, false); + + /* Stops at the first metadata block (7) and records error details */ + KUNIT_EXPECT_EQ(test, + ext4_check_blockref(__func__, __LINE__, reg_inode, + meta_refs, ARRAY_SIZE(meta_refs)), + -EFSCORRUPTED); + KUNIT_EXPECT_TRUE(test, + (bool)(ctx->sbi.s_mount_state & EXT4_ERROR_FS)); + KUNIT_EXPECT_EQ(test, le64_to_cpu(ctx->es.s_last_error_block), 7ULL); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_error_ino), 16U); + + /* Out-of-bounds block reference also triggers -EFSCORRUPTED */ + bv_clear_fs_error(ctx); + KUNIT_EXPECT_EQ(test, + ext4_check_blockref(__func__, __LINE__, reg_inode, + oob_refs, ARRAY_SIZE(oob_refs)), + -EFSCORRUPTED); + KUNIT_EXPECT_TRUE(test, + (bool)(ctx->sbi.s_mount_state & EXT4_ERROR_FS)); + KUNIT_EXPECT_EQ(test, le64_to_cpu(ctx->es.s_last_error_block), + (u64)BV_TEST_TOTAL_BLKS); + + /* Active journal inode (s_journal->j_inode) bypasses blockref checks */ + bv_clear_fs_error(ctx); + ctx->mock_journal.j_inode = j_inode; + ctx->sbi.s_journal = &ctx->mock_journal; + KUNIT_EXPECT_EQ(test, + ext4_check_blockref(__func__, __LINE__, j_inode, + meta_refs, ARRAY_SIZE(meta_refs)), + 0); + KUNIT_EXPECT_FALSE(test, + (bool)(ctx->sbi.s_mount_state & EXT4_ERROR_FS)); +} + +static void test_ind_check_inode_and_indirect_blockref(struct kunit *test) +{ + struct bv_test_ctx *ctx = test->priv; + unsigned int max_addrs = EXT4_ADDR_PER_BLOCK(ctx->sb); + struct buffer_head ind_bh; + struct inode *inode; + __le32 *addrs; + + KUNIT_ASSERT_EQ(test, ext4_setup_system_zone(ctx->sb), 0); + inode = bv_create_inode(test, ctx, 17, S_IFREG | 0644, false); + + /* ext4_ind_check_inode() checks direct slots i_data[0..11] */ + EXT4_I(inode)->i_data[0] = cpu_to_le32(15); + EXT4_I(inode)->i_data[EXT4_NDIR_BLOCKS - 1] = cpu_to_le32(20); + KUNIT_EXPECT_EQ(test, ext4_ind_check_inode(inode), 0); + + EXT4_I(inode)->i_data[EXT4_NDIR_BLOCKS - 1] = cpu_to_le32(6); + KUNIT_EXPECT_EQ(test, ext4_ind_check_inode(inode), -EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, le64_to_cpu(ctx->es.s_last_error_block), 6ULL); + + /* + * ext4_check_indirect_blockref() checks all EXT4_ADDR_PER_BLOCK(sb) + * entries (256 for 1KiB blocks), including the final slot. + */ + bv_clear_fs_error(ctx); + memset(&ind_bh, 0, sizeof(ind_bh)); + memset(ctx->ind_buf, 0, sizeof(ctx->ind_buf)); + ind_bh.b_data = ctx->ind_buf; + ind_bh.b_size = BV_TEST_BLK_SIZE; + addrs = (__le32 *)ind_bh.b_data; + + addrs[0] = cpu_to_le32(15); + addrs[max_addrs / 2] = cpu_to_le32(1039); + addrs[max_addrs - 1] = cpu_to_le32(4096); + KUNIT_EXPECT_EQ(test, ext4_check_indirect_blockref(inode, &ind_bh), 0); + KUNIT_EXPECT_FALSE(test, + (bool)(ctx->sbi.s_mount_state & EXT4_ERROR_FS)); + + addrs[max_addrs - 1] = cpu_to_le32(1029); + KUNIT_EXPECT_EQ(test, ext4_check_indirect_blockref(inode, &ind_bh), + -EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, le64_to_cpu(ctx->es.s_last_error_block), 1029ULL); +} + +/* --- Test 11: Integration with ext4_map_blocks() Validity Check --- */ + +static void test_map_blocks_rejects_extent_in_system_zone(struct kunit *test) +{ + struct bv_test_ctx *ctx = test->priv; + struct ext4_map_blocks map; + struct inode *bad_inode; + struct inode *ok_inode; + + KUNIT_ASSERT_EQ(test, ext4_setup_system_zone(ctx->sb), 0); + + ok_inode = bv_create_inode(test, ctx, 18, S_IFREG | 0644, true); + bv_append_extent(test, ok_inode, 0, 25ULL, 3); + memset(&map, 0, sizeof(map)); + map.m_lblk = 0; + map.m_len = 3; + KUNIT_EXPECT_EQ(test, ext4_map_blocks(NULL, ok_inode, &map, 0), 3); + KUNIT_EXPECT_FALSE(test, + (bool)(ctx->sbi.s_mount_state & EXT4_ERROR_FS)); + + /* Corrupt extent mapped onto group 0's inode table [7..14] */ + bad_inode = bv_create_inode(test, ctx, 19, S_IFREG | 0644, true); + bv_append_extent(test, bad_inode, 0, 8ULL, 2); + memset(&map, 0, sizeof(map)); + map.m_lblk = 0; + map.m_len = 2; + KUNIT_EXPECT_EQ(test, ext4_map_blocks(NULL, bad_inode, &map, 0), + -EFSCORRUPTED); + KUNIT_EXPECT_TRUE(test, + (bool)(ctx->sbi.s_mount_state & EXT4_ERROR_FS)); + KUNIT_EXPECT_EQ(test, le64_to_cpu(ctx->es.s_last_error_block), 8ULL); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_error_ino), 19U); +} + +static struct kunit_case ext4_block_validity_test_cases[] = { + KUNIT_CASE_PARAM(test_sb_block_valid_bounds, bv_bounds_gen_params), + KUNIT_CASE(test_release_system_zone_lifecycle), + KUNIT_CASE(test_setup_multigroup_sparse_super_and_flex_bg), + KUNIT_CASE(test_rbtree_left_right_and_bridge_merges), + KUNIT_CASE_PARAM(test_sb_block_valid_interval_overlaps, + bv_overlap_gen_params), + KUNIT_CASE_PARAM(test_setup_corrupt_group_metadata_overlaps, + bv_corrupt_meta_gen_params), + KUNIT_CASE(test_journal_inode_protection_and_ino_isolation), + KUNIT_CASE(test_journal_disabled_or_empty_skips_zones), + KUNIT_CASE(test_journal_inode_invalid_inum), + KUNIT_CASE(test_journal_inode_iget_error), + KUNIT_CASE(test_journal_inode_map_blocks_error), + KUNIT_CASE(test_journal_inode_overlap_sets_fs_error), + KUNIT_CASE(test_journal_extent_left_overlap_rejected), + KUNIT_CASE(test_check_blockref_valid_and_sparse), + KUNIT_CASE(test_check_blockref_corrupt_entries_and_journal_bypass), + KUNIT_CASE(test_ind_check_inode_and_indirect_blockref), + KUNIT_CASE(test_map_blocks_rejects_extent_in_system_zone), + {} +}; + +static struct kunit_suite ext4_block_validity_test_suite = { + .name = "ext4_block_validity_test", + .init = bv_test_init, + .test_cases = ext4_block_validity_test_cases, +}; + +kunit_test_suites(&ext4_block_validity_test_suite); + +MODULE_DESCRIPTION("KUnit tests for ext4 block validity (system zone) tracking"); +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/block_validity.c b/fs/ext4/block_validity.c index 3a31e3d718c95a..34468932e461d9 100644 --- a/fs/ext4/block_validity.c +++ b/fs/ext4/block_validity.c @@ -17,6 +17,7 @@ #include #include #include +#include #include #include "ext4.h" @@ -74,10 +75,13 @@ static int add_system_zone(struct ext4_system_blocks *system_blks, struct rb_node **n = &system_blks->root.rb_node, *node; struct rb_node *parent = NULL, *new_node; + if (!count || (start_blk + count < start_blk)) + return -EFSCORRUPTED; + while (*n) { parent = *n; entry = rb_entry(parent, struct ext4_system_zone, node); - if (start_blk < entry->start_blk) + if (start_blk + count <= entry->start_blk) n = &(*n)->rb_left; else if (start_blk >= (entry->start_blk + entry->count)) n = &(*n)->rb_right; @@ -269,6 +273,7 @@ int ext4_setup_system_zone(struct super_block *sb) kfree(system_blks); return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_setup_system_zone); /* * Called when the filesystem is unmounted or when remounting it with @@ -291,6 +296,7 @@ void ext4_release_system_zone(struct super_block *sb) if (system_blks) call_rcu(&system_blks->rcu, ext4_destroy_system_zone); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_release_system_zone); int ext4_sb_block_valid(struct super_block *sb, struct inode *inode, ext4_fsblk_t start_blk, unsigned int count) @@ -334,6 +340,7 @@ int ext4_sb_block_valid(struct super_block *sb, struct inode *inode, rcu_read_unlock(); return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sb_block_valid); /* * Returns 1 if the passed-in block region (start_blk, @@ -345,6 +352,7 @@ int ext4_inode_block_valid(struct inode *inode, ext4_fsblk_t start_blk, { return ext4_sb_block_valid(inode->i_sb, inode, start_blk, count); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_block_valid); int ext4_check_blockref(const char *function, unsigned int line, struct inode *inode, __le32 *p, unsigned int max) @@ -367,4 +375,5 @@ int ext4_check_blockref(const char *function, unsigned int line, } return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_check_blockref); diff --git a/fs/ext4/crypto.c b/fs/ext4/crypto.c index 318b2eaea74127..002ba8837d33af 100644 --- a/fs/ext4/crypto.c +++ b/fs/ext4/crypto.c @@ -37,6 +37,7 @@ int ext4_fname_setup_filename(struct inode *dir, const struct qstr *iname, return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fname_setup_filename); int ext4_fname_prepare_lookup(struct inode *dir, struct dentry *dentry, struct ext4_filename *fname) @@ -55,6 +56,7 @@ int ext4_fname_prepare_lookup(struct inode *dir, struct dentry *dentry, ext4_fname_free_filename(fname); return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fname_prepare_lookup); void ext4_fname_free_filename(struct ext4_filename *fname) { @@ -69,6 +71,7 @@ void ext4_fname_free_filename(struct ext4_filename *fname) ext4_fname_free_ci_filename(fname); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fname_free_filename); static bool uuid_is_zero(__u8 u[16]) { @@ -255,3 +258,4 @@ const struct fscrypt_operations ext4_cryptops = { .empty_dir = ext4_empty_dir, .has_stable_inodes = ext4_has_stable_inodes, }; +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_cryptops); diff --git a/fs/ext4/dir-test.c b/fs/ext4/dir-test.c new file mode 100644 index 00000000000000..5939fbfd85b5b5 --- /dev/null +++ b/fs/ext4/dir-test.c @@ -0,0 +1,995 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for ext4 directory entry validation, linear/HTree readdir, + * hash-cookie conversions, and directory llseek (fs/ext4/dir.c). + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_jbd2.h" + +#define DIR_TEST_BLK_SIZE 1024 +#define DIR_TEST_BLK_BITS 10 +#define DIR_TEST_INODE_SIZE 256 +#define DIR_TEST_EXTRA_ISIZE (sizeof(struct ext4_inode) - \ + EXT4_GOOD_OLD_INODE_SIZE) +#define DIR_TEST_FIRST_PBLK 200 +#define DIR_TEST_MAX_BLOCKS 16 +#define DIR_TEST_MAX_LBLOCKS 8 +#define DIR_TEST_CSUM_SEED 0x4d3c2b1aU + +#define DIR_TEST_ROOT_INO EXT4_ROOT_INO +#define DIR_TEST_DIR_INO 12 +#define DIR_TEST_MAX_EMIT 32 + +struct dir_mock_block { + bool in_use; + struct buffer_head bh; + char data[DIR_TEST_BLK_SIZE] __aligned(8); +}; + +struct dir_emit_record { + char name[32]; + u64 ino; + loff_t offset; + unsigned int d_type; +}; + +struct dir_capture_ctx { + struct dir_context ctx; + int count; + int max_emit; + struct inode *bump_iversion_after_first; + struct dir_emit_record recs[DIR_TEST_MAX_EMIT]; +}; + +struct dir_test_ctx { + struct super_block sb; + struct ext4_sb_info sbi; + struct ext4_super_block es; + struct block_device bdev; + struct address_space bd_mapping; + struct buffer_head sb_bh; + + struct ext4_inode_info dir_ei; + ext4_fsblk_t lblk_to_pblk[DIR_TEST_MAX_LBLOCKS]; + struct dir_mock_block blocks[DIR_TEST_MAX_BLOCKS]; + + struct dentry dentry; + struct file filp; + struct dir_capture_ctx cap; + + int fail_map_blocks; + int fail_getblk; + int htree_mode; + int htree_fill_calls; + __u32 last_fill_start_hash; + __u32 last_fill_start_minor; +}; + +enum dir_htree_stub_mode { + DIR_HTREE_STUB_NONE = 0, + DIR_HTREE_STUB_BAD_DX, + DIR_HTREE_STUB_TWO_BATCH, +}; + +static const struct super_operations dir_test_sops = { +}; + +static void init_mock_dir_file(struct dir_test_ctx *ctx, fmode_t extra_mode) +{ + struct inode *dir = &ctx->dir_ei.vfs_inode; + struct file tmp = { + .f_path = { .dentry = &ctx->dentry }, + .f_inode = dir, + .f_mapping = dir->i_mapping, + .f_op = &ext4_dir_operations, + .f_mode = FMODE_READ | FMODE_LSEEK | FMODE_PREAD | extra_mode, + }; + + memset(&ctx->dentry, 0, sizeof(ctx->dentry)); + spin_lock_init(&ctx->dentry.d_lock); + seqcount_spinlock_init(&ctx->dentry.d_seq, &ctx->dentry.d_lock); + ctx->dentry.d_parent = &ctx->dentry; + ctx->dentry.d_sb = &ctx->sb; + ctx->dentry.d_inode = dir; + ctx->dentry.__d_name.name = (const unsigned char *)"testdir"; + ctx->dentry.__d_name.len = 7; + + memcpy(&ctx->filp, &tmp, sizeof(ctx->filp)); + spin_lock_init(&ctx->filp.f_lock); + mutex_init(&ctx->filp.f_pos_lock); + /* + * Pre-populate the readahead window across our mock block range so + * ext4_readdir() does not issue block-device pagecache readahead I/O. + */ + ctx->filp.f_ra.start = 0; + ctx->filp.f_ra.size = 4096; +} + +static bool dir_capture_actor(struct dir_context *dctx, const char *name, + int namelen, loff_t offset, u64 ino, + unsigned int d_type) +{ + struct dir_capture_ctx *cap = + container_of(dctx, struct dir_capture_ctx, ctx); + + if (cap->max_emit > 0 && cap->count >= cap->max_emit) + return false; + + if (cap->count < DIR_TEST_MAX_EMIT) { + struct dir_emit_record *rec = &cap->recs[cap->count]; + int copy_len = min_t(int, namelen, sizeof(rec->name) - 1); + + memcpy(rec->name, name, copy_len); + rec->name[copy_len] = '\0'; + rec->ino = ino; + rec->offset = offset; + rec->d_type = d_type; + } + cap->count++; + + if (cap->bump_iversion_after_first && cap->count == 1) { + inode_inc_iversion(cap->bump_iversion_after_first); + cap->bump_iversion_after_first = NULL; + } + + return true; +} + +static void reset_capture(struct dir_capture_ctx *cap, loff_t pos, int max_emit) +{ + memset(cap, 0, sizeof(*cap)); + cap->ctx.actor = dir_capture_actor; + cap->ctx.pos = pos; + cap->max_emit = max_emit; +} + +static struct buffer_head *alloc_dir_lblk(struct dir_test_ctx *ctx, + ext4_lblk_t lblk) +{ + int i; + + if (lblk >= DIR_TEST_MAX_LBLOCKS) + return NULL; + + if (ctx->lblk_to_pblk[lblk]) { + unsigned long idx = ctx->lblk_to_pblk[lblk] - + DIR_TEST_FIRST_PBLK; + + return &ctx->blocks[idx].bh; + } + + for (i = 0; i < DIR_TEST_MAX_BLOCKS; i++) { + if (!ctx->blocks[i].in_use) { + struct buffer_head *bh = &ctx->blocks[i].bh; + + ctx->blocks[i].in_use = true; + memset(ctx->blocks[i].data, 0, DIR_TEST_BLK_SIZE); + set_buffer_uptodate(bh); + clear_buffer_verified(bh); + ctx->lblk_to_pblk[lblk] = DIR_TEST_FIRST_PBLK + i; + return bh; + } + } + return NULL; +} + +static struct ext4_dir_entry_2 *write_de(char *buf, unsigned int offset, + u32 ino, u16 rec_len, u8 file_type, + const char *name) +{ + struct ext4_dir_entry_2 *de = (struct ext4_dir_entry_2 *)(buf + offset); + size_t nlen = strlen(name); + + memset(de, 0, rec_len); + de->inode = cpu_to_le32(ino); + de->rec_len = ext4_rec_len_to_disk(rec_len, DIR_TEST_BLK_SIZE); + de->name_len = (u8)nlen; + de->file_type = file_type; + memcpy(de->name, name, nlen); + return de; +} + +static int store_stub_dirent(struct file *dir_file, __u32 hash, + __u32 minor_hash, u32 ino, u8 file_type, + const char *name) +{ + struct ext4_dir_entry_2 de = { + .inode = cpu_to_le32(ino), + .file_type = file_type, + }; + struct fscrypt_str ent_name = { + .name = (unsigned char *)name, + .len = strlen(name), + }; + + return ext4_htree_store_dirent(dir_file, hash, minor_hash, + &de, &ent_name); +} + +/* --- KUnit Static Stubs --- */ + +static int dir_map_blocks_stub(handle_t *handle, struct inode *inode, + struct ext4_map_blocks *map, int flags) +{ + struct kunit *test = kunit_get_current_test(); + struct dir_test_ctx *ctx = test->priv; + ext4_fsblk_t pblk; + + if (ctx->fail_map_blocks) + return ctx->fail_map_blocks; + if (map->m_lblk >= DIR_TEST_MAX_LBLOCKS) + return 0; + + pblk = ctx->lblk_to_pblk[map->m_lblk]; + if (!pblk) { + map->m_pblk = 0; + map->m_len = 1; + map->m_flags = 0; + return 0; + } + + map->m_pblk = pblk; + map->m_len = 1; + map->m_flags = EXT4_MAP_MAPPED; + return 1; +} + +static struct buffer_head *dir_getblk_stub(handle_t *handle, + struct inode *inode, + ext4_lblk_t block, int map_flags) +{ + struct kunit *test = kunit_get_current_test(); + struct dir_test_ctx *ctx = test->priv; + ext4_fsblk_t pblk; + struct buffer_head *bh; + + if (ctx->fail_getblk) + return ERR_PTR(ctx->fail_getblk); + if (block >= DIR_TEST_MAX_LBLOCKS) + return NULL; + + pblk = ctx->lblk_to_pblk[block]; + if (!pblk) + return NULL; + + bh = &ctx->blocks[pblk - DIR_TEST_FIRST_PBLK].bh; + get_bh(bh); + return bh; +} + +static int dir_dirty_metadata_stub(const char *where, unsigned int line, + handle_t *handle, struct inode *inode, + struct buffer_head *bh) +{ + return 0; +} + +static int dir_htree_fill_tree_stub(struct file *dir_file, __u32 start_hash, + __u32 start_minor_hash, __u32 *next_hash) +{ + struct kunit *test = kunit_get_current_test(); + struct dir_test_ctx *ctx = test->priv; + int err; + + ctx->htree_fill_calls++; + ctx->last_fill_start_hash = start_hash; + ctx->last_fill_start_minor = start_minor_hash; + + if (ctx->htree_mode == DIR_HTREE_STUB_BAD_DX) + return ERR_BAD_DX_DIR; + + if (ctx->htree_mode == DIR_HTREE_STUB_TWO_BATCH) { + int count = 0; + + if (start_hash < 0x2000) { + if (start_hash == 0 && start_minor_hash == 0) { + err = store_stub_dirent(dir_file, 0, 0, + DIR_TEST_DIR_INO, + EXT4_FT_DIR, "."); + if (err) + return err; + count++; + } + if (start_hash < 2 || + (start_hash == 2 && start_minor_hash == 0)) { + err = store_stub_dirent(dir_file, 2, 0, + DIR_TEST_ROOT_INO, + EXT4_FT_DIR, ".."); + if (err) + return err; + count++; + } + if (start_hash < 0x1000 || + (start_hash == 0x1000 && + start_minor_hash <= 0x55)) { + err = store_stub_dirent(dir_file, 0x1000, 0x55, + 21, EXT4_FT_REG_FILE, + "coll_a"); + if (err) + return err; + err = store_stub_dirent(dir_file, 0x1000, 0x55, + 22, EXT4_FT_SYMLINK, + "coll_b"); + if (err) + return err; + count += 2; + } + *next_hash = 0x2000; + return count; + } + + if (start_hash <= 0x2000) { + err = store_stub_dirent(dir_file, 0x2000, 0x09, + 23, EXT4_FT_DIR, "leaf2_sub"); + if (err) + return err; + *next_hash = ~0U; + return 1; + } + + *next_hash = ~0U; + return 0; + } + + *next_hash = ~0U; + return 0; +} + +static int dir_test_init(struct kunit *test) +{ + struct dir_test_ctx *ctx; + struct inode *dir; + int i; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx); + test->priv = ctx; + + ctx->sb.s_blocksize = DIR_TEST_BLK_SIZE; + ctx->sb.s_blocksize_bits = DIR_TEST_BLK_BITS; + ctx->sb.s_magic = EXT4_SUPER_MAGIC; + ctx->sb.s_maxbytes = 64ULL * DIR_TEST_BLK_SIZE; + ctx->sb.s_op = &dir_test_sops; + ctx->sb.s_fs_info = &ctx->sbi; + ctx->sb.s_user_ns = &init_user_ns; + ctx->sb.s_bdev = &ctx->bdev; + ctx->bdev.bd_mapping = &ctx->bd_mapping; + bdev_set_flag(&ctx->bdev, BD_READ_ONLY); + init_rwsem(&ctx->sb.s_umount); + strscpy(ctx->sb.s_id, "ext4_dir_kunit", sizeof(ctx->sb.s_id)); + + ctx->sbi.s_sb = &ctx->sb; + ctx->sbi.s_es = &ctx->es; + ctx->sbi.s_sbh = &ctx->sb_bh; + ctx->sbi.s_inode_size = DIR_TEST_INODE_SIZE; + ctx->sbi.s_first_ino = EXT4_GOOD_OLD_FIRST_INO; + ctx->sbi.s_bitmap_maxbytes = 16ULL * DIR_TEST_BLK_SIZE; + ctx->sbi.s_csum_seed = DIR_TEST_CSUM_SEED; + set_opt(&ctx->sb, ERRORS_CONT); + spin_lock_init(&ctx->sbi.s_bdev_wb_lock); + spin_lock_init(&ctx->sbi.s_error_lock); + spin_lock_init(&ctx->sbi.s_md_lock); + ratelimit_state_init(&ctx->sbi.s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&ctx->sbi.s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&ctx->sbi.s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + + ctx->es.s_inodes_count = cpu_to_le32(1024); + ctx->es.s_first_ino = cpu_to_le32(EXT4_GOOD_OLD_FIRST_INO); + ctx->es.s_inode_size = cpu_to_le16(DIR_TEST_INODE_SIZE); + ctx->es.s_feature_incompat = cpu_to_le32(EXT4_FEATURE_INCOMPAT_FILETYPE); + ctx->es.s_feature_compat = cpu_to_le32(EXT4_FEATURE_COMPAT_DIR_INDEX); + ctx->es.s_feature_ro_compat = + cpu_to_le32(EXT4_FEATURE_RO_COMPAT_METADATA_CSUM); + + ctx->sb_bh.b_data = (char *)&ctx->es; + ctx->sb_bh.b_size = DIR_TEST_BLK_SIZE; + ctx->sb_bh.b_blocknr = 1; + atomic_set(&ctx->sb_bh.b_count, 1); + set_buffer_uptodate(&ctx->sb_bh); + + for (i = 0; i < DIR_TEST_MAX_BLOCKS; i++) { + struct buffer_head *bh = &ctx->blocks[i].bh; + + bh->b_data = ctx->blocks[i].data; + bh->b_size = DIR_TEST_BLK_SIZE; + bh->b_blocknr = DIR_TEST_FIRST_PBLK + i; + atomic_set(&bh->b_count, 1); + set_buffer_uptodate(bh); + } + + dir = &ctx->dir_ei.vfs_inode; + dir->i_sb = &ctx->sb; + dir->i_ino = DIR_TEST_DIR_INO; + dir->i_mode = S_IFDIR | 0755; + dir->i_blkbits = DIR_TEST_BLK_BITS; + dir->i_mapping = &dir->i_data; + dir->i_data.host = dir; + set_nlink(dir, 2); + atomic_set(&dir->i_count, 1); + spin_lock_init(&dir->i_lock); + i_size_ordered_init(dir); + init_rwsem(&dir->i_rwsem); + INIT_LIST_HEAD(&dir->i_io_list); + INIT_LIST_HEAD(&dir->i_wb_list); + INIT_LIST_HEAD(&dir->i_lru); + INIT_HLIST_NODE(&dir->i_hash); + inode_state_set_raw(dir, I_DIRTY); + inode_set_iversion_raw(dir, 10); + + init_rwsem(&ctx->dir_ei.xattr_sem); + init_rwsem(&ctx->dir_ei.i_data_sem); + INIT_LIST_HEAD(&ctx->dir_ei.i_orphan); + INIT_LIST_HEAD(&ctx->dir_ei.i_fc_list); + spin_lock_init(&ctx->dir_ei.i_fc_lock); + spin_lock_init(&ctx->dir_ei.i_raw_lock); + ctx->dir_ei.i_extra_isize = DIR_TEST_EXTRA_ISIZE; + ctx->dir_ei.i_csum_seed = DIR_TEST_CSUM_SEED ^ DIR_TEST_DIR_INO; + + init_mock_dir_file(ctx, FMODE_64BITHASH); + + kunit_activate_static_stub(test, ext4_map_blocks, dir_map_blocks_stub); + kunit_activate_static_stub(test, ext4_getblk, dir_getblk_stub); + kunit_activate_static_stub(test, __ext4_handle_dirty_metadata, + dir_dirty_metadata_stub); + + return 0; +} + +/* + * Test 1: Validate __ext4_check_dir_entry() and ext4_check_all_de() across + * valid directory blocks (including fake '.' / '..' / csum tail entries and + * casefold+encrypted extended-hash entries) and every corruption condition. + */ +static void test_check_dir_entry_and_all_de(struct kunit *test) +{ + struct dir_test_ctx *ctx = test->priv; + struct inode *dir = &ctx->dir_ei.vfs_inode; + struct buffer_head *bh; + struct ext4_dir_entry_2 *de; + unsigned int tail_len = sizeof(struct ext4_dir_entry_tail); + char *buf; + + bh = alloc_dir_lblk(ctx, 0); + KUNIT_ASSERT_NOT_NULL(test, bh); + buf = bh->b_data; + + /* Valid block: '.', '..', 'alpha', and a 12-byte csum tail */ + write_de(buf, 0, DIR_TEST_DIR_INO, 12, EXT4_FT_DIR, "."); + write_de(buf, 12, DIR_TEST_ROOT_INO, 12, EXT4_FT_DIR, ".."); + write_de(buf, 24, 15, DIR_TEST_BLK_SIZE - 24 - tail_len, + EXT4_FT_REG_FILE, "alpha"); + ext4_initialize_dirent_tail(bh, DIR_TEST_BLK_SIZE); + + KUNIT_EXPECT_EQ(test, ext4_check_all_de(dir, bh, buf, + DIR_TEST_BLK_SIZE), 0); + + /* 1. rec_len smaller than minimal (8 < 12) */ + de = (struct ext4_dir_entry_2 *)(buf + 24); + de->rec_len = cpu_to_le16(8); + KUNIT_EXPECT_EQ(test, __ext4_check_dir_entry(__func__, __LINE__, dir, + &ctx->filp, de, bh, buf, + DIR_TEST_BLK_SIZE, 24), 1); + KUNIT_EXPECT_EQ(test, ext4_check_all_de(dir, bh, buf, + DIR_TEST_BLK_SIZE), + -EFSCORRUPTED); + + /* 2. rec_len not a multiple of 4 (14 % 4 != 0) */ + de->rec_len = cpu_to_le16(14); + KUNIT_EXPECT_EQ(test, __ext4_check_dir_entry(__func__, __LINE__, dir, + NULL, de, bh, buf, + DIR_TEST_BLK_SIZE, 24), 1); + + /* 3. rec_len too small for name_len (name_len=10 needs 20 bytes) */ + de->name_len = 10; + de->rec_len = cpu_to_le16(16); + KUNIT_EXPECT_EQ(test, __ext4_check_dir_entry(__func__, __LINE__, dir, + NULL, de, bh, buf, + DIR_TEST_BLK_SIZE, 24), 1); + + /* + * 4. Casefolded + encrypted directory requires space for + * ext4_dir_entry_hash (+8 bytes) on regular entries, while fake + * entries ('.', '..', csum tail) remain 12 bytes. + */ + dir->i_flags |= S_CASEFOLD | S_ENCRYPTED; + write_de(buf, 24, 15, 16, EXT4_FT_REG_FILE, "ab"); + de = (struct ext4_dir_entry_2 *)(buf + 24); + KUNIT_EXPECT_EQ(test, __ext4_check_dir_entry(__func__, __LINE__, dir, + NULL, de, bh, buf, + DIR_TEST_BLK_SIZE, 24), 1); + write_de(buf, 24, 15, DIR_TEST_BLK_SIZE - 24 - tail_len, + EXT4_FT_REG_FILE, "ab"); + ext4_initialize_dirent_tail(bh, DIR_TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, ext4_check_all_de(dir, bh, buf, + DIR_TEST_BLK_SIZE), 0); + dir->i_flags &= ~(S_CASEFOLD | S_ENCRYPTED); + + /* 5. Directory entry overrun (next_offset > size) */ + de = (struct ext4_dir_entry_2 *)(buf + 24); + de->rec_len = cpu_to_le16(DIR_TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, __ext4_check_dir_entry(__func__, __LINE__, dir, + NULL, de, bh, buf, + DIR_TEST_BLK_SIZE, 24), 1); + + /* 6. Entry too close to block end (leaves only 8 bytes < 12) */ + de->rec_len = cpu_to_le16(DIR_TEST_BLK_SIZE - 24 - 8); + KUNIT_EXPECT_EQ(test, __ext4_check_dir_entry(__func__, __LINE__, dir, + NULL, de, bh, buf, + DIR_TEST_BLK_SIZE, 24), 1); + + /* 7. Inode number out of bounds (> s_inodes_count) */ + de->rec_len = cpu_to_le16(DIR_TEST_BLK_SIZE - 24 - tail_len); + de->inode = cpu_to_le32(2048); + KUNIT_EXPECT_EQ(test, __ext4_check_dir_entry(__func__, __LINE__, dir, + NULL, de, bh, buf, + DIR_TEST_BLK_SIZE, 24), 1); + + /* 8. '.' directory entry cannot span to the end of the block */ + write_de(buf, 0, DIR_TEST_DIR_INO, DIR_TEST_BLK_SIZE, EXT4_FT_DIR, "."); + de = (struct ext4_dir_entry_2 *)buf; + KUNIT_EXPECT_EQ(test, __ext4_check_dir_entry(__func__, __LINE__, dir, + NULL, de, bh, buf, + DIR_TEST_BLK_SIZE, 0), 1); +} + +/* + * Test 2: Verify is_dx_dir(), get_dtype(), and 32-bit / 64-bit HTree telldir + * hash-position cookie helpers. + */ +static void test_dx_detection_and_hash_pos_cookies(struct kunit *test) +{ + struct dir_test_ctx *ctx = test->priv; + struct inode *dir = &ctx->dir_ei.vfs_inode; + __u32 major = 0xaabbccdeU; + __u32 minor = 0x12345678U; + loff_t pos; + + /* Without DIR_INDEX feature, is_dx_dir() is always 0 */ + ext4_clear_feature_dir_index(&ctx->sb); + ext4_set_inode_flag(dir, EXT4_INODE_INDEX); + i_size_write(dir, DIR_TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, ext4_is_dx_dir_test(dir), 0); + + /* With DIR_INDEX: multi-block dir without INDEX or inline is non-dx */ + ext4_set_feature_dir_index(&ctx->sb); + ext4_clear_inode_flag(dir, EXT4_INODE_INDEX); + i_size_write(dir, 2 * DIR_TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, ext4_is_dx_dir_test(dir), 0); + + /* Single-block dir with DIR_INDEX is treated as dx-capable */ + i_size_write(dir, DIR_TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, ext4_is_dx_dir_test(dir), 1); + + /* Multi-block dir with EXT4_INODE_INDEX is dx */ + i_size_write(dir, 4 * DIR_TEST_BLK_SIZE); + ext4_set_inode_flag(dir, EXT4_INODE_INDEX); + KUNIT_EXPECT_EQ(test, ext4_is_dx_dir_test(dir), 1); + ext4_clear_inode_flag(dir, EXT4_INODE_INDEX); + + /* Inline-data dir with DIR_INDEX is treated as dx */ + ext4_set_inode_flag(dir, EXT4_INODE_INLINE_DATA); + ctx->dir_ei.i_inline_off = 160; + KUNIT_EXPECT_EQ(test, ext4_is_dx_dir_test(dir), 1); + ext4_clear_inode_flag(dir, EXT4_INODE_INLINE_DATA); + ctx->dir_ei.i_inline_off = 0; + + /* get_dtype() mapping with and without FILETYPE feature */ + KUNIT_EXPECT_EQ(test, get_dtype(&ctx->sb, EXT4_FT_REG_FILE), DT_REG); + KUNIT_EXPECT_EQ(test, get_dtype(&ctx->sb, EXT4_FT_DIR), DT_DIR); + KUNIT_EXPECT_EQ(test, get_dtype(&ctx->sb, EXT4_FT_SYMLINK), DT_LNK); + KUNIT_EXPECT_EQ(test, get_dtype(&ctx->sb, EXT4_FT_DIR_CSUM), + DT_UNKNOWN); + ext4_clear_feature_filetype(&ctx->sb); + KUNIT_EXPECT_EQ(test, get_dtype(&ctx->sb, EXT4_FT_REG_FILE), + DT_UNKNOWN); + ext4_set_feature_filetype(&ctx->sb); + + /* 64-bit hash cookie round-trip */ + ctx->filp.f_mode = FMODE_READ | FMODE_64BITHASH; + KUNIT_EXPECT_EQ(test, ext4_get_htree_eof_test(&ctx->filp), + (loff_t)EXT4_HTREE_EOF_64BIT); + pos = ext4_dir_hash2pos_test(&ctx->filp, major, minor); + KUNIT_EXPECT_EQ(test, ext4_dir_pos2maj_hash_test(&ctx->filp, pos), + major & ~1U); + KUNIT_EXPECT_EQ(test, ext4_dir_pos2min_hash_test(&ctx->filp, pos), + minor); + + /* 32-bit hash cookie round-trip */ + ctx->filp.f_mode = FMODE_READ | FMODE_32BITHASH; + KUNIT_EXPECT_EQ(test, ext4_get_htree_eof_test(&ctx->filp), + (loff_t)EXT4_HTREE_EOF_32BIT); + pos = ext4_dir_hash2pos_test(&ctx->filp, major, minor); + KUNIT_EXPECT_EQ(test, pos, (loff_t)(major >> 1)); + KUNIT_EXPECT_EQ(test, ext4_dir_pos2maj_hash_test(&ctx->filp, pos), + major & ~1U); + KUNIT_EXPECT_EQ(test, ext4_dir_pos2min_hash_test(&ctx->filp, pos), 0U); +} + +/* + * Test 3: Verify ext4_dir_operations open(), llseek(), and release() across + * 64-bit dx dirs, 32-bit dx dirs, and non-dx indirect/extent linear dirs. + */ +static void test_dir_open_llseek_and_release(struct kunit *test) +{ + struct dir_test_ctx *ctx = test->priv; + struct inode *dir = &ctx->dir_ei.vfs_inode; + struct dir_private_info *info; + loff_t ret; + + KUNIT_ASSERT_EQ(test, ext4_dir_operations.open(dir, &ctx->filp), 0); + info = ctx->filp.private_data; + KUNIT_ASSERT_NOT_NULL(test, info); + + /* 1. DX directory with 64-bit hash cookies */ + ext4_set_inode_flag(dir, EXT4_INODE_INDEX); + i_size_write(dir, 2 * DIR_TEST_BLK_SIZE); + ctx->filp.f_mode = FMODE_READ | FMODE_LSEEK | FMODE_64BITHASH; + info->cookie = inode_query_iversion(dir); + + ret = ext4_dir_operations.llseek(&ctx->filp, EXT4_HTREE_EOF_64BIT, + SEEK_SET); + KUNIT_EXPECT_EQ(test, ret, (loff_t)EXT4_HTREE_EOF_64BIT); + KUNIT_EXPECT_FALSE(test, inode_eq_iversion(dir, info->cookie)); + + ret = ext4_dir_operations.llseek(&ctx->filp, -1, SEEK_SET); + KUNIT_EXPECT_EQ(test, ret, (loff_t)-EINVAL); + + /* 2. DX directory with 32-bit hash cookies caps at 32-bit EOF */ + ctx->filp.f_mode = FMODE_READ | FMODE_LSEEK | FMODE_32BITHASH; + ret = ext4_dir_operations.llseek(&ctx->filp, EXT4_HTREE_EOF_32BIT, + SEEK_SET); + KUNIT_EXPECT_EQ(test, ret, (loff_t)EXT4_HTREE_EOF_32BIT); + ret = ext4_dir_operations.llseek(&ctx->filp, + (loff_t)EXT4_HTREE_EOF_32BIT + 1, + SEEK_SET); + KUNIT_EXPECT_EQ(test, ret, (loff_t)-EINVAL); + + /* 3. Non-DX indirect directory uses s_bitmap_maxbytes and i_size */ + ext4_clear_inode_flag(dir, EXT4_INODE_INDEX); + ext4_clear_inode_flag(dir, EXT4_INODE_EXTENTS); + i_size_write(dir, 3 * DIR_TEST_BLK_SIZE); + info->cookie = inode_query_iversion(dir); + + ret = ext4_dir_operations.llseek(&ctx->filp, 0, SEEK_END); + KUNIT_EXPECT_EQ(test, ret, (loff_t)(3 * DIR_TEST_BLK_SIZE)); + KUNIT_EXPECT_FALSE(test, inode_eq_iversion(dir, info->cookie)); + + ret = ext4_dir_operations.llseek(&ctx->filp, + ctx->sbi.s_bitmap_maxbytes + 1, + SEEK_SET); + KUNIT_EXPECT_EQ(test, ret, (loff_t)-EINVAL); + + KUNIT_EXPECT_EQ(test, ext4_dir_operations.release(dir, &ctx->filp), 0); + ctx->filp.private_data = NULL; +} + +/* + * Test 4: Verify ext4_htree_store_dirent() rbtree sorting across major and + * minor hashes, exact 64-bit hash collision chaining, and cleanup via + * ext4_htree_free_dir_info(). + */ +static void test_htree_store_dirent_and_free(struct kunit *test) +{ + struct dir_test_ctx *ctx = test->priv; + struct inode *dir = &ctx->dir_ei.vfs_inode; + struct dir_private_info *info; + int err; + + ext4_set_inode_flag(dir, EXT4_INODE_INDEX); + i_size_write(dir, 2 * DIR_TEST_BLK_SIZE); + KUNIT_ASSERT_EQ(test, ext4_dir_operations.open(dir, &ctx->filp), 0); + info = ctx->filp.private_data; + + /* Insert out of hash order, including 3 colliding entries at 0x200:7 */ + KUNIT_ASSERT_EQ(test, store_stub_dirent(&ctx->filp, 0x400, 0x10, 34, + EXT4_FT_REG_FILE, "fourth"), 0); + KUNIT_ASSERT_EQ(test, store_stub_dirent(&ctx->filp, 0x100, 0x20, 31, + EXT4_FT_DIR, "first"), 0); + KUNIT_ASSERT_EQ(test, store_stub_dirent(&ctx->filp, 0x400, 0x05, 33, + EXT4_FT_SYMLINK, "third"), 0); + KUNIT_ASSERT_EQ(test, store_stub_dirent(&ctx->filp, 0x200, 0x07, 32, + EXT4_FT_REG_FILE, "c1"), 0); + KUNIT_ASSERT_EQ(test, store_stub_dirent(&ctx->filp, 0x200, 0x07, 35, + EXT4_FT_REG_FILE, "c2"), 0); + KUNIT_ASSERT_EQ(test, store_stub_dirent(&ctx->filp, 0x200, 0x07, 36, + EXT4_FT_REG_FILE, "c3"), 0); + + /* Pre-prime cookie and next_hash so ext4_dx_readdir drains info->root */ + info->cookie = inode_query_iversion(dir); + info->next_hash = ~0U; + reset_capture(&ctx->cap, 0, 0); + + inode_lock_shared(dir); + err = ext4_dir_operations.iterate_shared(&ctx->filp, &ctx->cap.ctx); + inode_unlock_shared(dir); + + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_ASSERT_EQ(test, ctx->cap.count, 6); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[0].name, "first"); + KUNIT_EXPECT_EQ(test, ctx->cap.recs[0].d_type, (unsigned int)DT_DIR); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[1].name, "c1"); + /* Collision list inserts after head: c1 -> c3 -> c2 */ + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[2].name, "c3"); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[3].name, "c2"); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[4].name, "third"); + KUNIT_EXPECT_EQ(test, ctx->cap.recs[4].d_type, (unsigned int)DT_LNK); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[5].name, "fourth"); + KUNIT_EXPECT_EQ(test, ctx->cap.ctx.pos, (loff_t)EXT4_HTREE_EOF_64BIT); + + /* Re-populate nodes so release exercises non-empty free_rb_tree_fname */ + KUNIT_ASSERT_EQ(test, store_stub_dirent(&ctx->filp, 0x300, 0x01, 40, + EXT4_FT_REG_FILE, "leftover1"), + 0); + KUNIT_ASSERT_EQ(test, store_stub_dirent(&ctx->filp, 0x300, 0x01, 41, + EXT4_FT_REG_FILE, "leftover2"), + 0); + KUNIT_EXPECT_EQ(test, ext4_dir_operations.release(dir, &ctx->filp), 0); + ctx->filp.private_data = NULL; +} + +/* + * Test 5: Verify linear ext4_readdir() across multi-block directories with + * sparse holes, deleted entries, dir_emit() stop/resume, i_version change + * mid-entry revalidation, checksum/corruption block skipping, and + * ERR_BAD_DX_DIR fallback clearing EXT4_INODE_INDEX. + */ +static void test_linear_readdir(struct kunit *test) +{ + struct dir_test_ctx *ctx = test->priv; + struct inode *dir = &ctx->dir_ei.vfs_inode; + struct buffer_head *bh0, *bh2, *bh3; + unsigned int tail_len = sizeof(struct ext4_dir_entry_tail); + loff_t resume_pos; + int err; + + /* + * 4-block non-indexed linear directory: + * lblk 0: '.', '..', deleted (ino=0), 'file_a', 'sym_b' + csum tail + * lblk 1: sparse hole (unmapped) + * lblk 2: 'sub_c', 'fifo_d' + csum tail + * lblk 3: 'last_e' + csum tail + */ + ext4_clear_inode_flag(dir, EXT4_INODE_INDEX); + i_size_write(dir, 4 * DIR_TEST_BLK_SIZE); + dir->i_blocks = (4 * DIR_TEST_BLK_SIZE) >> 9; + + bh0 = alloc_dir_lblk(ctx, 0); + bh2 = alloc_dir_lblk(ctx, 2); + bh3 = alloc_dir_lblk(ctx, 3); + KUNIT_ASSERT_NOT_NULL(test, bh0); + KUNIT_ASSERT_NOT_NULL(test, bh2); + KUNIT_ASSERT_NOT_NULL(test, bh3); + + write_de(bh0->b_data, 0, DIR_TEST_DIR_INO, 12, EXT4_FT_DIR, "."); + write_de(bh0->b_data, 12, DIR_TEST_ROOT_INO, 12, EXT4_FT_DIR, ".."); + write_de(bh0->b_data, 24, 0, 16, EXT4_FT_REG_FILE, "deleted"); + write_de(bh0->b_data, 40, 51, 20, EXT4_FT_REG_FILE, "file_a"); + write_de(bh0->b_data, 60, 52, DIR_TEST_BLK_SIZE - 60 - tail_len, + EXT4_FT_SYMLINK, "sym_b"); + ext4_initialize_dirent_tail(bh0, DIR_TEST_BLK_SIZE); + KUNIT_ASSERT_EQ(test, ext4_handle_dirty_dirblock(NULL, dir, bh0), 0); + + write_de(bh2->b_data, 0, 53, 16, EXT4_FT_DIR, "sub_c"); + write_de(bh2->b_data, 16, 54, DIR_TEST_BLK_SIZE - 16 - tail_len, + EXT4_FT_FIFO, "fifo_d"); + ext4_initialize_dirent_tail(bh2, DIR_TEST_BLK_SIZE); + KUNIT_ASSERT_EQ(test, ext4_handle_dirty_dirblock(NULL, dir, bh2), 0); + + write_de(bh3->b_data, 0, 55, DIR_TEST_BLK_SIZE - tail_len, + EXT4_FT_REG_FILE, "last_e"); + ext4_initialize_dirent_tail(bh3, DIR_TEST_BLK_SIZE); + KUNIT_ASSERT_EQ(test, ext4_handle_dirty_dirblock(NULL, dir, bh3), 0); + + KUNIT_ASSERT_EQ(test, ext4_dir_operations.open(dir, &ctx->filp), 0); + + /* 1. Stop after 3 emitted entries ('.', '..', 'file_a'), then resume */ + reset_capture(&ctx->cap, 0, 3); + inode_lock_shared(dir); + err = ext4_dir_operations.iterate_shared(&ctx->filp, &ctx->cap.ctx); + inode_unlock_shared(dir); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_ASSERT_EQ(test, ctx->cap.count, 3); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[0].name, "."); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[1].name, ".."); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[2].name, "file_a"); + KUNIT_EXPECT_EQ(test, ctx->cap.recs[2].d_type, (unsigned int)DT_REG); + + resume_pos = ctx->cap.ctx.pos; + KUNIT_EXPECT_EQ(test, resume_pos, (loff_t)60); + + reset_capture(&ctx->cap, resume_pos, 0); + inode_lock_shared(dir); + err = ext4_dir_operations.iterate_shared(&ctx->filp, &ctx->cap.ctx); + inode_unlock_shared(dir); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_ASSERT_EQ(test, ctx->cap.count, 4); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[0].name, "sym_b"); + KUNIT_EXPECT_EQ(test, ctx->cap.recs[0].d_type, (unsigned int)DT_LNK); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[1].name, "sub_c"); + KUNIT_EXPECT_EQ(test, ctx->cap.recs[1].d_type, (unsigned int)DT_DIR); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[2].name, "fifo_d"); + KUNIT_EXPECT_EQ(test, ctx->cap.recs[2].d_type, (unsigned int)DT_FIFO); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[3].name, "last_e"); + + /* + * 2. Unaligned ctx->pos (44, inside 'file_a' at [40..60)) combined + * with an i_version bump triggers block-start rescan and snaps to 60. + */ + inode_inc_iversion(dir); + reset_capture(&ctx->cap, 44, 1); + inode_lock_shared(dir); + err = ext4_dir_operations.iterate_shared(&ctx->filp, &ctx->cap.ctx); + inode_unlock_shared(dir); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_ASSERT_EQ(test, ctx->cap.count, 1); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[0].name, "sym_b"); + KUNIT_EXPECT_EQ(test, ctx->cap.recs[0].offset, (loff_t)60); + + /* + * 3. Corrupt block 0 checksum and corrupt second entry in block 2: + * ext4_readdir() skips block 0, emits 'sub_c' from block 2 before + * skipping the rest of block 2, and still emits 'last_e' from block 3. + */ + clear_buffer_verified(bh0); + bh0->b_data[DIR_TEST_BLK_SIZE - 1] ^= 0xff; + ((struct ext4_dir_entry_2 *)(bh2->b_data + 16))->rec_len = + cpu_to_le16(8); + + reset_capture(&ctx->cap, 0, 0); + inode_lock_shared(dir); + err = ext4_dir_operations.iterate_shared(&ctx->filp, &ctx->cap.ctx); + inode_unlock_shared(dir); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_ASSERT_EQ(test, ctx->cap.count, 2); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[0].name, "sub_c"); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[1].name, "last_e"); + + /* + * 4. ERR_BAD_DX_DIR fallback when !metadata_csum clears + * EXT4_INODE_INDEX and falls back to linear block scanning. + */ + ext4_clear_feature_metadata_csum(&ctx->sb); + ext4_set_inode_flag(dir, EXT4_INODE_INDEX); + write_de(bh3->b_data, 0, 55, DIR_TEST_BLK_SIZE, + EXT4_FT_REG_FILE, "last_e"); + kunit_activate_static_stub(test, ext4_htree_fill_tree, + dir_htree_fill_tree_stub); + ctx->htree_mode = DIR_HTREE_STUB_BAD_DX; + + reset_capture(&ctx->cap, 3 * DIR_TEST_BLK_SIZE, 0); + inode_lock_shared(dir); + err = ext4_dir_operations.iterate_shared(&ctx->filp, &ctx->cap.ctx); + inode_unlock_shared(dir); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_FALSE(test, ext4_test_inode_flag(dir, EXT4_INODE_INDEX)); + KUNIT_ASSERT_EQ(test, ctx->cap.count, 1); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[0].name, "last_e"); + + KUNIT_EXPECT_EQ(test, ext4_dir_operations.release(dir, &ctx->filp), 0); + ctx->filp.private_data = NULL; +} + +/* + * Test 6: Verify ext4_dx_readdir() across multi-batch leaf refills, + * mid-collision-chain stop & extra_fname resumption, EOF short-circuit, + * f_pos seek tree reset, and mid-stream i_version invalidation. + */ +static void test_dx_readdir(struct kunit *test) +{ + struct dir_test_ctx *ctx = test->priv; + struct inode *dir = &ctx->dir_ei.vfs_inode; + loff_t saved_pos, seek_pos; + int err; + + ext4_set_inode_flag(dir, EXT4_INODE_INDEX); + i_size_write(dir, 2 * DIR_TEST_BLK_SIZE); + kunit_activate_static_stub(test, ext4_htree_fill_tree, + dir_htree_fill_tree_stub); + ctx->htree_mode = DIR_HTREE_STUB_TWO_BATCH; + + KUNIT_ASSERT_EQ(test, ext4_dir_operations.open(dir, &ctx->filp), 0); + + /* + * 1. Stop after 3 entries ('.', '..', and first collision entry): + * leaves the second colliding entry queued on info->extra_fname. + */ + reset_capture(&ctx->cap, 0, 3); + inode_lock_shared(dir); + err = ext4_dir_operations.iterate_shared(&ctx->filp, &ctx->cap.ctx); + inode_unlock_shared(dir); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->htree_fill_calls, 1); + KUNIT_ASSERT_EQ(test, ctx->cap.count, 3); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[0].name, "."); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[1].name, ".."); + /* Collision chain at 0x1000:0x55 emits coll_a then coll_b */ + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[2].name, "coll_a"); + saved_pos = ctx->cap.ctx.pos; + + /* + * 2. Resume from saved_pos: emits leftover 'coll_b' from extra_fname + * without refilling batch 1, then refills at next_hash=0x2000 for + * 'leaf2_sub', and finishes at EXT4_HTREE_EOF_64BIT. + */ + reset_capture(&ctx->cap, saved_pos, 0); + inode_lock_shared(dir); + err = ext4_dir_operations.iterate_shared(&ctx->filp, &ctx->cap.ctx); + inode_unlock_shared(dir); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->htree_fill_calls, 2); + KUNIT_EXPECT_EQ(test, ctx->last_fill_start_hash, 0x2000U); + KUNIT_ASSERT_EQ(test, ctx->cap.count, 2); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[0].name, "coll_b"); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[1].name, "leaf2_sub"); + KUNIT_EXPECT_EQ(test, ctx->cap.ctx.pos, (loff_t)EXT4_HTREE_EOF_64BIT); + + /* 3. Calling again at HTREE_EOF returns 0 immediately without refill */ + reset_capture(&ctx->cap, ctx->cap.ctx.pos, 0); + inode_lock_shared(dir); + err = ext4_dir_operations.iterate_shared(&ctx->filp, &ctx->cap.ctx); + inode_unlock_shared(dir); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->cap.count, 0); + KUNIT_EXPECT_EQ(test, ctx->htree_fill_calls, 2); + + /* + * 4. Seeking to a 64-bit hash cookie resets the cached state and + * refills starting from (pos2maj_hash, pos2min_hash); bumping + * i_version after the first entry forces an rbtree refill mid-walk. + */ + seek_pos = ext4_dir_hash2pos_test(&ctx->filp, 0x1000, 0x55); + reset_capture(&ctx->cap, seek_pos, 0); + ctx->cap.bump_iversion_after_first = dir; + + inode_lock_shared(dir); + err = ext4_dir_operations.iterate_shared(&ctx->filp, &ctx->cap.ctx); + inode_unlock_shared(dir); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_GE(test, ctx->htree_fill_calls, 4); + KUNIT_EXPECT_GE(test, ctx->cap.count, 3); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[0].name, "coll_a"); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[1].name, "coll_b"); + KUNIT_EXPECT_STREQ(test, ctx->cap.recs[ctx->cap.count - 1].name, + "leaf2_sub"); + + KUNIT_EXPECT_EQ(test, ext4_dir_operations.release(dir, &ctx->filp), 0); + ctx->filp.private_data = NULL; +} + +static struct kunit_case ext4_dir_test_cases[] = { + KUNIT_CASE(test_check_dir_entry_and_all_de), + KUNIT_CASE(test_dx_detection_and_hash_pos_cookies), + KUNIT_CASE(test_dir_open_llseek_and_release), + KUNIT_CASE(test_htree_store_dirent_and_free), + KUNIT_CASE(test_linear_readdir), + KUNIT_CASE(test_dx_readdir), + {} +}; + +static struct kunit_suite ext4_dir_test_suite = { + .name = "ext4_dir_test", + .init = dir_test_init, + .test_cases = ext4_dir_test_cases, +}; + +kunit_test_suites(&ext4_dir_test_suite); + +MODULE_DESCRIPTION("KUnit tests for ext4 directory operations"); +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/dir.c b/fs/ext4/dir.c index 8d7b81e6948e72..43f4f2d451aa89 100644 --- a/fs/ext4/dir.c +++ b/fs/ext4/dir.c @@ -126,6 +126,7 @@ int __ext4_check_dir_entry(const char *function, unsigned int line, return 1; } +EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_check_dir_entry); static int ext4_readdir(struct file *file, struct dir_context *ctx) { @@ -256,7 +257,7 @@ static int ext4_readdir(struct file *file, struct dir_context *ctx) sb->s_blocksize); } offset = i; - ctx->pos = (ctx->pos & ~(sb->s_blocksize - 1)) + ctx->pos = (ctx->pos & ~((loff_t)sb->s_blocksize - 1)) | offset; info->cookie = inode_query_iversion(inode); } @@ -475,6 +476,7 @@ void ext4_htree_free_dir_info(struct dir_private_info *p) free_rb_tree_fname(&p->root); kfree(p); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_htree_free_dir_info); /* * Given a directory entry, enter it into the fname rb tree. @@ -535,6 +537,7 @@ int ext4_htree_store_dirent(struct file *dir_file, __u32 hash, rb_insert_color(&new_fn->rb_hash, &info->root); return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_htree_store_dirent); @@ -683,6 +686,7 @@ int ext4_check_all_de(struct inode *dir, struct buffer_head *bh, void *buf, return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_check_all_de); static int ext4_dir_open(struct inode *inode, struct file *file) { @@ -708,3 +712,36 @@ const struct file_operations ext4_dir_operations = { .release = ext4_release_dir, .setlease = generic_setlease, }; +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_dir_operations); + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +int ext4_is_dx_dir_test(struct inode *inode) +{ + return is_dx_dir(inode); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_is_dx_dir_test); + +loff_t ext4_dir_hash2pos_test(struct file *filp, __u32 major, __u32 minor) +{ + return hash2pos(filp, major, minor); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_dir_hash2pos_test); + +__u32 ext4_dir_pos2maj_hash_test(struct file *filp, loff_t pos) +{ + return pos2maj_hash(filp, pos); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_dir_pos2maj_hash_test); + +__u32 ext4_dir_pos2min_hash_test(struct file *filp, loff_t pos) +{ + return pos2min_hash(filp, pos); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_dir_pos2min_hash_test); + +loff_t ext4_get_htree_eof_test(struct file *filp) +{ + return ext4_get_htree_eof(filp); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_htree_eof_test); +#endif diff --git a/fs/ext4/ext4.h b/fs/ext4/ext4.h index bf0325ecbec7a4..dc2c181337a163 100644 --- a/fs/ext4/ext4.h +++ b/fs/ext4/ext4.h @@ -689,6 +689,17 @@ enum { GROUP_TABLE_COUNT, }; +/* + * ext4_new_flex_group_data is used by 64bit-resize interface to add a flex + * group each time. + */ +struct ext4_new_flex_group_data { + struct ext4_new_group_data *groups; + __u16 *bg_flags; + ext4_group_t resize_bg; + ext4_group_t count; +}; + /* * Flags used by ext4_map_blocks() */ @@ -1648,10 +1659,6 @@ struct ext4_sb_info { /* Journaling */ struct journal_s *s_journal; unsigned long s_ext4_flags; /* Ext4 superblock flags */ - struct mutex s_orphan_lock; /* Protects on disk list changes */ - struct list_head s_orphan; /* List of orphaned inodes in on disk - list */ - struct ext4_orphan_info s_orphan_info; unsigned long s_commit_interval; u32 s_max_batch_time; u32 s_min_batch_time; @@ -1792,6 +1799,12 @@ struct ext4_sb_info { /* Journal triggers for checksum computation */ struct ext4_journal_trigger s_journal_triggers[EXT4_JOURNAL_TRIGGER_COUNT]; + /* Orphan inode tracking */ + struct mutex s_orphan_lock; /* Protects on disk list changes */ + struct list_head s_orphan; /* List of orphaned inodes in on disk + list */ + struct ext4_orphan_info s_orphan_info; + /* Ratelimit ext4 messages. */ struct ratelimit_state s_err_ratelimit_state; struct ratelimit_state s_warning_ratelimit_state; @@ -2627,6 +2640,13 @@ ext4_rec_len_from_disk(__le16 dlen, unsigned blocksize) { unsigned len = le16_to_cpu(dlen); + /* + * Only blocks of 64k and more need the special encoding of rec_len. + * For smaller blocks 0 and EXT4_MAX_REC_LEN are not valid lengths + * and must not be taken for an entry that spans the whole block. + */ + if (blocksize < 65536) + return len; if (len == EXT4_MAX_REC_LEN || len == 0) return blocksize; return (len & 65532) | ((len & 3) << 16); @@ -3050,6 +3070,14 @@ static inline unsigned char get_dtype(struct super_block *sb, int filetype) } extern int ext4_check_all_de(struct inode *dir, struct buffer_head *bh, void *buf, int buf_size); +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +extern int ext4_is_dx_dir_test(struct inode *inode); +extern loff_t ext4_dir_hash2pos_test(struct file *filp, __u32 major, + __u32 minor); +extern __u32 ext4_dir_pos2maj_hash_test(struct file *filp, loff_t pos); +extern __u32 ext4_dir_pos2min_hash_test(struct file *filp, loff_t pos); +extern loff_t ext4_get_htree_eof_test(struct file *filp); +#endif /* fsync.c */ extern int ext4_sync_file(struct file *, loff_t, loff_t, int); @@ -3081,11 +3109,35 @@ extern struct inode * ext4_orphan_get(struct super_block *, unsigned long); extern unsigned long ext4_count_free_inodes(struct super_block *); extern unsigned long ext4_count_dirs(struct super_block *); extern void ext4_mark_bitmap_end(int start_bit, int end_bit, char *bitmap); +int ext4_itable_zeroout(struct super_block *sb, ext4_fsblk_t blk, int num, + int barrier); extern int ext4_init_inode_table(struct super_block *sb, ext4_group_t group, int barrier); void ext4_end_bitmap_read(struct bio *bio); +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +int ext4_validate_inode_bitmap_test(struct super_block *sb, + struct ext4_group_desc *desc, + ext4_group_t block_group, + struct buffer_head *bh); +struct buffer_head *ext4_read_inode_bitmap_test(struct super_block *sb, + ext4_group_t block_group); +int ext4_find_group_orlov_test(struct super_block *sb, struct inode *parent, + ext4_group_t *group, umode_t mode, + const struct qstr *qstr); +int ext4_find_group_other_test(struct super_block *sb, struct inode *parent, + ext4_group_t *group, umode_t mode); +int ext4_recently_deleted_test(struct super_block *sb, ext4_group_t group, + int ino); +int ext4_find_inode_bit_test(struct super_block *sb, ext4_group_t group, + struct buffer_head *bitmap, unsigned long *ino); +int ext4_xattr_credits_for_new_inode_test(struct inode *dir, mode_t mode, + bool encrypt); +#endif /* fast_commit.c */ +int ext4_fc_get_buf(journal_t *journal, struct buffer_head **bh); +void ext4_fc_submit_bh(struct super_block *sb, bool is_tail); +int ext4_fc_issue_flush(struct block_device *bdev); int ext4_fc_info_show(struct seq_file *seq, void *v); void ext4_fc_init(struct super_block *sb, journal_t *journal); void ext4_fc_init_inode(struct inode *inode); @@ -3112,6 +3164,38 @@ void ext4_fc_destroy_dentry_cache(void); int ext4_fc_record_regions(struct super_block *sb, int ino, ext4_lblk_t lblk, ext4_fsblk_t pblk, int len, int replay); +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +void ext4_fc_set_snap_err_test(int *snap_err, int err); +bool ext4_fc_disabled_test(struct super_block *sb); +bool ext4_fc_eligible_test(struct super_block *sb); +void ext4_fc_snap_stats_update_max_test(atomic64_t *stat, u64 value); +void ext4_fc_wake_inode_state_test(struct inode *inode, int bit); +u8 *ext4_fc_reserve_space_test(struct super_block *sb, int len, u32 *crc); +int ext4_fc_write_tail_test(struct super_block *sb, u32 crc); +bool ext4_fc_add_tlv_test(struct super_block *sb, u16 tag, u16 len, u8 *val, + u32 *crc); +int ext4_fc_write_inode_test(struct inode *inode, u32 *crc); +int ext4_fc_write_inode_data_test(struct inode *inode, u32 *crc); +void ext4_fc_free_inode_snap_test(struct inode *inode); +int ext4_fc_snapshot_inode_test(struct inode *inode, + unsigned int nr_ranges_total, + unsigned int *nr_rangesp, int *snap_err); +unsigned int ext4_fc_count_snapshot_inodes_test(struct super_block *sb); +int ext4_fc_alloc_snapshot_inodes_test(struct super_block *sb, + struct inode ***inodesp, + unsigned int *nr_inodesp); +int ext4_fc_snapshot_inodes_test(journal_t *journal, struct inode **inodes, + unsigned int inodes_size, + unsigned int *nr_inodesp, + unsigned int *nr_rangesp, int *snap_err); +void ext4_fc_update_stats_test(struct super_block *sb, int status, + u64 commit_time, int nblks, tid_t commit_tid); +void ext4_fc_cleanup_test(journal_t *journal, int full, tid_t tid); +int ext4_fc_record_modified_inode_test(struct super_block *sb, int ino); +bool ext4_fc_value_len_isvalid_test(struct ext4_sb_info *sbi, int tag, int len); +int ext4_fc_replay_test(journal_t *journal, struct buffer_head *bh, + enum passtype pass, int off, tid_t expected_tid); +#endif /* mballoc.c */ extern const struct seq_operations ext4_mb_seq_groups_ops; @@ -3245,8 +3329,40 @@ extern int ext4_get_projid(struct inode *inode, kprojid_t *projid); extern void ext4_da_release_space(struct inode *inode, int to_free); extern void ext4_da_update_reserve_space(struct inode *inode, int used, int quota_claim); -extern int ext4_issue_zeroout(struct inode *inode, ext4_lblk_t lblk, - ext4_fsblk_t pblk, ext4_lblk_t len); +extern int ext4_issue_zeroout(handle_t *handle, struct inode *inode, + ext4_lblk_t lblk, ext4_fsblk_t pblk, + ext4_lblk_t len); +struct buffer_head *ext4_sb_getblk(struct super_block *sb, ext4_fsblk_t block); +struct buffer_head *ext4_sb_find_get_block(struct super_block *sb, + ext4_fsblk_t block); +struct buffer_head *ext4_sb_find_get_block_nonatomic(struct super_block *sb, + ext4_fsblk_t block); +struct buffer_head *ext4_sb_getblk_unmovable(struct super_block *sb, + ext4_fsblk_t block); +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +int ext4_inode_csum_verify_test(struct inode *inode, struct ext4_inode *raw, + struct ext4_inode_info *ei); +int ext4_inode_blocks_set_test(struct ext4_inode *raw_inode, + struct ext4_inode_info *ei); +blkcnt_t ext4_inode_blocks_test(struct ext4_inode *raw_inode, + struct ext4_inode_info *ei); +int ext4_fill_raw_inode_test(struct inode *inode, + struct ext4_inode *raw_inode); +int ext4_expand_extra_isize_test(struct inode *inode, + unsigned int new_extra_isize, + struct ext4_iloc *iloc, + handle_t *handle, int *no_expand); +int ext4_try_to_expand_extra_isize_test(struct inode *inode, + unsigned int new_extra_isize, + struct ext4_iloc *iloc, + handle_t *handle); +int ext4_da_reserve_space_test(struct inode *inode, int nr_resv); +int ext4_clu_alloc_state_test(struct inode *inode, ext4_lblk_t lblk); +int ext4_insert_delayed_blocks_test(struct inode *inode, ext4_lblk_t lblk, + ext4_lblk_t len); +int ext4_da_map_blocks_test(struct inode *inode, struct ext4_map_blocks *map); +int ext4_nonda_switch_test(struct super_block *sb); +#endif static inline bool is_special_ino(struct super_block *sb, unsigned long ino) { @@ -3266,6 +3382,10 @@ extern int ext4_ind_trans_blocks(struct inode *inode, int nrblocks); extern void ext4_ind_truncate(handle_t *, struct inode *inode); extern int ext4_ind_remove_space(handle_t *handle, struct inode *inode, ext4_lblk_t start, ext4_lblk_t end); +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +extern int ext4_block_to_path_test(struct inode *inode, ext4_lblk_t i_block, + ext4_lblk_t offsets[4], int *boundary); +#endif /* ioctl.c */ extern long ext4_ioctl(struct file *, unsigned int, unsigned long); @@ -3276,10 +3396,47 @@ int ext4_fileattr_get(struct dentry *dentry, struct file_kattr *fa); extern void ext4_reset_inode_seed(struct inode *inode); int ext4_update_overhead(struct super_block *sb, bool force); int ext4_force_shutdown(struct super_block *sb, u32 flags); +int ext4_ioctl_sync_bh(struct buffer_head *bh); +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +struct ext4_tune_sb_params; +void ext4_sb_setlabel_test(struct ext4_sb_info *sbi, + struct ext4_super_block *es, const void *arg); +void ext4_sb_setuuid_test(struct ext4_sb_info *sbi, + struct ext4_super_block *es, const void *arg); +void ext4_sb_setparams_test(struct ext4_sb_info *sbi, + struct ext4_super_block *es, const void *arg); +int ext4_validate_tune_sb_params_test(struct super_block *sb, + struct ext4_tune_sb_params *params); +int ext4_update_primary_sb_test(struct super_block *sb, handle_t *handle, + void (*func)(struct ext4_sb_info *, + struct ext4_super_block *, + const void *), + const void *arg); +int ext4_update_backup_sb_test(struct super_block *sb, handle_t *handle, + ext4_group_t grp, + void (*func)(struct ext4_sb_info *, + struct ext4_super_block *, + const void *), + const void *arg); +int ext4_update_superblocks_fn_test(struct super_block *sb, + void (*func)(struct ext4_sb_info *, + struct ext4_super_block *, + const void *), + const void *arg); +void ext4_swap_inode_data_test(struct inode *inode1, struct inode *inode2); +int ext4_ioctl_check_immutable_test(struct inode *inode, __u32 new_projid, + unsigned int flags); +bool ext4_dax_compatible_test(struct inode *inode, unsigned int oldflags, + unsigned int flags); +#endif /* migrate.c */ extern int ext4_ext_migrate(struct inode *); extern int ext4_ind_migrate(struct inode *inode); +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +extern int ext4_ext_swap_inode_data_test(handle_t *handle, struct inode *inode, + struct inode *tmp_inode); +#endif /* namei.c */ extern int ext4_init_new_dir(handle_t *handle, struct inode *dir, @@ -3305,6 +3462,8 @@ extern bool ext4_empty_dir(struct inode *inode); /* resize.c */ extern void ext4_kvfree_array_rcu(void *to_free); +extern int ext4_resize_issue_zeroout(struct super_block *sb, sector_t blk, + sector_t nr_blks, gfp_t gfp_mask); extern int ext4_group_add(struct super_block *sb, struct ext4_new_group_data *input); extern int ext4_group_extend(struct super_block *sb, @@ -3314,6 +3473,25 @@ extern int ext4_resize_fs(struct super_block *sb, ext4_fsblk_t n_blocks_count); extern unsigned int ext4_list_backups(struct super_block *sb, unsigned int *three, unsigned int *five, unsigned int *seven); +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +extern int ext4_verify_group_input_test(struct super_block *sb, + struct ext4_new_group_data *input); +extern struct ext4_new_flex_group_data * +ext4_alloc_flex_gd_test(unsigned int flexbg_size, ext4_group_t o_group, + ext4_group_t n_group); +extern void ext4_free_flex_gd_test(struct ext4_new_flex_group_data *flex_gd); +extern int ext4_alloc_group_tables_test(struct super_block *sb, + struct ext4_new_flex_group_data *flex_gd, + unsigned int flexbg_size); +extern int ext4_verify_reserved_gdb_test(struct super_block *sb, + ext4_group_t end, + struct buffer_head *primary); +extern int ext4_setup_next_flex_gd_test(struct super_block *sb, + struct ext4_new_flex_group_data *flex_gd, + ext4_fsblk_t n_blocks_count); +extern int ext4_convert_meta_bg_test(struct super_block *sb, + struct inode *inode); +#endif /* super.c */ extern struct buffer_head *ext4_sb_bread(struct super_block *sb, @@ -3343,6 +3521,51 @@ extern unsigned int ext4_num_base_meta_blocks(struct super_block *sb, ext4_group_t block_group); extern void print_daily_error_info(struct timer_list *t); +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +extern int ext4_errno_to_code_test(int err); +extern void ext4_save_error_info_test(struct super_block *sb, int error, + __u32 ino, __u64 block, + const char *func, unsigned int line); +extern void ext4_update_super_test(struct super_block *sb); +extern int ext4_check_descriptors_test(struct super_block *sb, + ext4_fsblk_t sb_block, + ext4_group_t *first_not_zeroed); +extern loff_t ext4_max_size_test(int blkbits, int has_huge_files); +extern loff_t ext4_max_bitmap_size_test(int bits, int has_huge_files); +extern ext4_fsblk_t ext4_descriptor_loc_test(struct super_block *sb, + ext4_fsblk_t logical_sb_block, + int nr); +extern unsigned long ext4_get_stripe_size_test(struct ext4_sb_info *sbi); +extern int ext4_count_overhead_test(struct super_block *sb, ext4_group_t grp, + char *buf); +extern void ext4_set_resv_clusters_test(struct super_block *sb); +extern void ext4_set_def_opts_test(struct super_block *sb, + struct ext4_super_block *es); +extern int ext4_handle_clustersize_test(struct super_block *sb); +extern int ext4_inode_info_init_test(struct super_block *sb, + struct ext4_super_block *es); +extern int ext4_init_metadata_csum_test(struct super_block *sb, + struct ext4_super_block *es); +extern int ext4_check_feature_compatibility_test(struct super_block *sb, + struct ext4_super_block *es, + int silent); +extern int ext4_check_geometry_test(struct super_block *sb, + struct ext4_super_block *es); +extern int ext4_hash_info_init_test(struct super_block *sb); +extern int ext4_block_group_meta_init_test(struct super_block *sb, int silent); +extern int ext4_fill_flex_info_test(struct super_block *sb); +extern void ext4_flex_groups_free_test(struct ext4_sb_info *sbi); +extern int ext4_show_options_test(struct seq_file *seq, struct super_block *sb, + int nodefs); +extern int ext4_statfs_test(struct dentry *dentry, struct kstatfs *buf); +extern int ext4_parse_and_apply_options_test(struct super_block *sb, + const char *options, + bool is_remount); +extern int ext4_parse_sb_mount_options_test(struct super_block *sb, + unsigned long *journal_devnum, + unsigned int *journal_ioprio); +#endif + extern __printf(7, 8) void __ext4_error(struct super_block *, const char *, unsigned int, bool, int, __u64, const char *, ...); @@ -3530,8 +3753,8 @@ static inline ext4_fsblk_t ext4_free_blocks_count(struct ext4_super_block *es) static inline void ext4_blocks_count_set(struct ext4_super_block *es, ext4_fsblk_t blk) { - es->s_blocks_count_lo = cpu_to_le32((u32)blk); - es->s_blocks_count_hi = cpu_to_le32(blk >> 32); + es->s_blocks_count_lo = cpu_to_le32(lower_32_bits(blk)); + es->s_blocks_count_hi = cpu_to_le32(upper_32_bits(blk)); } static inline void ext4_free_blocks_count_set(struct ext4_super_block *es, @@ -3822,6 +4045,8 @@ extern const struct file_operations ext4_file_operations; extern loff_t ext4_llseek(struct file *file, loff_t offset, int origin); /* inline.c */ +extern struct buffer_head *ext4_inline_getblk(struct super_block *sb, + ext4_fsblk_t block); extern int ext4_get_max_inline_size(struct inode *inode); extern int ext4_find_inline_data_nolock(struct inode *inode); extern int ext4_destroy_inline_data(handle_t *handle, struct inode *inode); @@ -3933,6 +4158,14 @@ extern int ext4_register_sysfs(struct super_block *sb); extern void ext4_unregister_sysfs(struct super_block *sb); extern int __init ext4_init_sysfs(void); extern void ext4_exit_sysfs(void); +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +extern ssize_t ext4_sysfs_attr_show_test(struct ext4_sb_info *sbi, + const char *name, char *buf); +extern ssize_t ext4_sysfs_attr_store_test(struct ext4_sb_info *sbi, + const char *name, const char *buf, + size_t len); +extern ssize_t ext4_sysfs_feat_show_test(const char *name, char *buf); +#endif /* block_validity */ extern void ext4_release_system_zone(struct super_block *sb); @@ -3958,6 +4191,7 @@ struct ext4_extent; */ #define EXT_MAX_BLOCKS 0xffffffff +extern void ext4_ext_init_root(struct inode *inode); extern void ext4_ext_tree_init(handle_t *handle, struct inode *inode); extern int ext4_ext_index_trans_blocks(struct inode *inode, int extents); extern int ext4_ext_map_blocks(handle_t *handle, struct inode *inode, @@ -4027,6 +4261,14 @@ extern void ext4_double_up_write_data_sem(struct inode *orig_inode, extern int ext4_move_extents(struct file *o_filp, struct file *d_filp, __u64 start_orig, __u64 start_donor, __u64 len, __u64 *moved_len); +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +extern int ext4_mext_check_validity_test(struct inode *orig_inode, + struct inode *donor_inode); +extern int ext4_mext_check_adjust_range_test(struct inode *orig_inode, + struct inode *donor_inode, + __u64 orig_start, + __u64 donor_start, __u64 *len); +#endif /* page-io.c */ /* @@ -4054,9 +4296,25 @@ extern void ext4_iomap_end_bio(struct bio *bio); /* mmp.c */ extern int ext4_multi_mount_protect(struct super_block *, ext4_fsblk_t); - -/* mmp.c */ extern void ext4_stop_mmpd(struct ext4_sb_info *sbi); +extern int ext4_mmp_submit_write(struct buffer_head *bh); +extern int ext4_mmp_load_bh(struct super_block *sb, struct buffer_head **bh, + ext4_fsblk_t mmp_block); +extern long ext4_mmp_wait_timeout(long timeout); +extern struct task_struct *ext4_mmp_run_thread(struct super_block *sb, + const char *bdevname, + int bdevname_len); +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +extern int ext4_mmp_csum_verify_test(struct super_block *sb, + struct mmp_struct *mmp); +extern void ext4_mmp_csum_set_test(struct super_block *sb, + struct mmp_struct *mmp); +extern int ext4_read_mmp_block_test(struct super_block *sb, + struct buffer_head **bh, + ext4_fsblk_t mmp_block); +extern int ext4_write_mmp_block_test(struct super_block *sb, + struct buffer_head *bh); +#endif /* verity.c */ extern const struct fsverity_operations ext4_verityops; @@ -4129,12 +4387,19 @@ static inline int ext4_buffer_uptodate(struct buffer_head *bh) return buffer_uptodate(bh); } +/* + * Atomic writes are only supported through direct I/O, so an inode that + * can't do direct I/O at all (journaled data, inline data, verity) can't do + * atomic writes either. DAX inodes bypass the direct I/O path entirely. + */ static inline bool ext4_inode_can_atomic_write(struct inode *inode) { return S_ISREG(inode->i_mode) && + !IS_DAX(inode) && ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS) && - EXT4_SB(inode->i_sb)->s_awu_min > 0; + EXT4_SB(inode->i_sb)->s_awu_min > 0 && + ext4_dio_alignment(inode) != 0; } extern int ext4_block_write_begin(handle_t *handle, struct folio *folio, @@ -4144,6 +4409,8 @@ extern int ext4_block_write_begin(handle_t *handle, struct folio *folio, #if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) #define EXPORT_SYMBOL_FOR_EXT4_TEST(sym) \ EXPORT_SYMBOL_FOR_MODULES(sym, "ext4-test") +#else +#define EXPORT_SYMBOL_FOR_EXT4_TEST(sym) #endif #endif /* __KERNEL__ */ diff --git a/fs/ext4/ext4_extents.h b/fs/ext4/ext4_extents.h index ebaf7cc42430fa..f819ae995a103c 100644 --- a/fs/ext4/ext4_extents.h +++ b/fs/ext4/ext4_extents.h @@ -267,7 +267,10 @@ static inline void ext4_idx_store_pblock(struct ext4_extent_idx *ix, extern int __ext4_ext_dirty(const char *where, unsigned int line, handle_t *handle, struct inode *inode, struct ext4_ext_path *path); -extern int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex); +extern int ext4_ext_zeroout(handle_t *handle, struct inode *inode, + struct ext4_extent *ex); +extern struct buffer_head *ext4_ext_getblk(struct inode *inode, + ext4_fsblk_t pblk, gfp_t gfp_flags); #if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) extern int ext4_ext_space_root_idx_test(struct inode *inode, int check); extern struct ext4_ext_path *ext4_split_convert_extents_test( @@ -275,6 +278,25 @@ extern struct ext4_ext_path *ext4_split_convert_extents_test( struct ext4_map_blocks *map, struct ext4_ext_path *path, int flags, unsigned int *allocated); +extern int ext4_ext_check_test(struct inode *inode, + struct ext4_extent_header *eh, int depth, + ext4_fsblk_t pblk, ext4_lblk_t lblk); +extern void ext4_extent_block_csum_set_test(struct inode *inode, + struct ext4_extent_header *eh); +extern int ext4_can_extents_be_merged_test(struct inode *inode, + struct ext4_extent *ex1, + struct ext4_extent *ex2); +extern int ext4_ext_search_left_test(struct inode *inode, + struct ext4_ext_path *path, + ext4_lblk_t *logical, ext4_fsblk_t *phys); +extern int ext4_ext_search_right_test(struct inode *inode, + struct ext4_ext_path *path, + ext4_lblk_t *logical, ext4_fsblk_t *phys, + struct ext4_extent *ret_ex, int flags); +extern ext4_lblk_t ext4_ext_next_leaf_block_test(struct ext4_ext_path *path); +extern int ext4_ext_shift_extents_test(struct inode *inode, handle_t *handle, + ext4_lblk_t start, ext4_lblk_t shift, + enum SHIFT_DIRECTION direction); #endif #endif /* _EXT4_EXTENTS */ diff --git a/fs/ext4/ext4_jbd2.c b/fs/ext4/ext4_jbd2.c index cf1032a8c89a25..a52998c709da9b 100644 --- a/fs/ext4/ext4_jbd2.c +++ b/fs/ext4/ext4_jbd2.c @@ -4,11 +4,14 @@ */ #include "ext4_jbd2.h" +#include #include int ext4_inode_journal_mode(struct inode *inode) { + KUNIT_STATIC_STUB_REDIRECT(ext4_inode_journal_mode, inode); + if (EXT4_JOURNAL(inode) == NULL) return EXT4_INODE_WRITEBACK_DATA_MODE; /* writeback */ /* We do not support data journalling with delayed allocation */ @@ -126,6 +129,7 @@ handle_t *__ext4_journal_start_sb(struct inode *inode, return jbd2__journal_start(journal, blocks, rsv_blocks, revoke_creds, GFP_NOFS, type, line); } +EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_journal_start_sb); int __ext4_journal_stop(const char *where, unsigned int line, handle_t *handle) { @@ -153,6 +157,7 @@ int __ext4_journal_stop(const char *where, unsigned int line, handle_t *handle) __ext4_std_error(sb, where, line, err); return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_journal_stop); handle_t *__ext4_journal_start_reserved(handle_t *handle, unsigned int line, int type) @@ -181,6 +186,9 @@ handle_t *__ext4_journal_start_reserved(handle_t *handle, unsigned int line, int __ext4_journal_ensure_credits(handle_t *handle, int check_cred, int extend_cred, int revoke_cred) { + KUNIT_STATIC_STUB_REDIRECT(__ext4_journal_ensure_credits, handle, + check_cred, extend_cred, revoke_cred); + if (!ext4_handle_valid(handle)) return 0; if (is_handle_aborted(handle)) @@ -192,6 +200,7 @@ int __ext4_journal_ensure_credits(handle_t *handle, int check_cred, revoke_cred = max(0, revoke_cred - handle->h_revoke_credits); return ext4_journal_extend(handle, extend_cred, revoke_cred); } +EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_journal_ensure_credits); static void ext4_journal_abort_handle(const char *caller, unsigned int line, const char *err_fn, @@ -247,6 +256,9 @@ int __ext4_journal_get_write_access(const char *where, unsigned int line, { int err; + KUNIT_STATIC_STUB_REDIRECT(__ext4_journal_get_write_access, where, line, + handle, sb, bh, trigger_type); + might_sleep(); if (ext4_handle_valid(handle)) { @@ -266,6 +278,7 @@ int __ext4_journal_get_write_access(const char *where, unsigned int line, &EXT4_SB(sb)->s_journal_triggers[trigger_type].tr_triggers); return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_journal_get_write_access); /* * The ext4 forget function must perform a revoke if we are freeing data @@ -383,6 +396,9 @@ int __ext4_handle_dirty_metadata(const char *where, unsigned int line, { int err = 0; + KUNIT_STATIC_STUB_REDIRECT(__ext4_handle_dirty_metadata, where, line, + handle, inode, bh); + might_sleep(); set_buffer_meta(bh); @@ -416,7 +432,19 @@ int __ext4_handle_dirty_metadata(const char *where, unsigned int line, err); } } else { - if (inode) { + /* + * Fast commit replay runs without a handle, before the + * writeback paths are set up. Don't track the buffer in the + * inode's metadata list then: mmb_mark_buffer_dirty() sets + * I_METADATA_WRITEBACK, and since the superblock isn't active + * yet the iput() ending the replay step writes the inode out + * and enters ext4_writepages() before s_writepages_rwsem is + * initialized. Journal recovery flushes the whole block + * device once replay is done, so the buffer still gets + * written. + */ + if (inode && !(EXT4_SB(inode->i_sb)->s_mount_state & + EXT4_FC_REPLAY)) { if (!ext4_i_metadata_bhs(inode)) ext4_inode_attach_mmb(inode); mmb_mark_buffer_dirty(bh, ext4_i_metadata_bhs(inode)); @@ -435,3 +463,8 @@ int __ext4_handle_dirty_metadata(const char *where, unsigned int line, } return err; } + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_journal_mode); +EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_handle_dirty_metadata); +#endif diff --git a/fs/ext4/extents-test.c b/fs/ext4/extents-test.c index 2e997f228330f5..6458345ea958c3 100644 --- a/fs/ext4/extents-test.c +++ b/fs/ext4/extents-test.c @@ -3,60 +3,85 @@ * Written by Ojaswin Mujoo (IBM) * * These Kunit tests are designed to test the functionality of - * extent split and conversion in ext4. - * - * Currently, ext4 can split extents in 2 ways: - * 1. By splitting the extents in the extent tree and optionally converting them - * to written or unwritten based on flags passed. - * 2. In case 1 encounters an error, ext4 instead zerooes out the unwritten - * areas of the extent and marks the complete extent written. - * - * The primary function that handles this is ext4_split_convert_extents(). - * - * We test both of the methods of split. The behavior we try to enforce is: - * 1. When passing EXT4_GET_BLOCKS_CONVERT flag to ext4_split_convert_extents(), - * the split extent should be converted to initialized. - * 2. When passing EXT4_GET_BLOCKS_CONVERT_UNWRITTEN flag to - * ext4_split_convert_extents(), the split extent should be converted to - * uninitialized. - * 3. In case we use the zeroout method, then we should correctly write zeroes - * to the unwritten areas of the extent and we should not corrupt/leak any - * data. - * - * Enforcing 1 and 2 is straight forward, we just setup a minimal inode with - * extent tree, call ext4_split_convert_extents() and check the final state of - * the extent tree. - * - * For zeroout testing, we maintain a separate buffer which represents the disk - * data corresponding to the extents. We then override ext4's zeroout functions - * to instead write zeroes to our buffer. Then, we override - * ext4_ext_insert_extent() to return -ENOSPC, which triggers the zeroout. - * Finally, we check the state of the extent tree and zeroout buffer to confirm - * everything went well. + * fs/ext4/extents.c, including extent tree initialization and validation, + * binary search and multi-level navigation, extent insertion, merging, + * splitting, tree depth growth and collapse, space removal and bigalloc + * partial cluster handling, block mapping, unwritten-to-written conversion, + * zeroout fallback, extent shifting, extent swapping, cluster mapping, + * transaction credit calculation, and fast-commit replay helpers. */ #include #include +#include +#include +#include +#include #include #include +#include #include #include "ext4.h" #include "ext4_extents.h" +#include "ext4_jbd2.h" #define EXT_DATA_PBLK 100 #define EXT_DATA_LBLK 10 #define EXT_DATA_LEN 3 -struct kunit_ctx { +#define EXT_MAX_META_BLOCKS 16 +#define EXT_META_BASE_PBLK 500 +#define EXT_ALLOC_BASE_PBLK 1000 +#define EXT_TOTAL_BLOCKS 0x100000ULL + +struct kunit_meta_block { + ext4_fsblk_t pblk; + struct buffer_head bh; + char data[4096]; + bool in_use; +}; + +static struct kunit_ctx { /* - * Ext4 inode which has only 1 unwrit extent + * Ext4 inode initialized with 1 extent by default */ struct ext4_inode_info *k_ei; + /* + * Optional secondary inode (used for swap_extents tests) + */ + struct ext4_inode_info *k_ei2; /* * Represents the underlying data area (used for zeroout testing) */ char *k_data; + /* + * In-memory pool of external extent tree blocks (leaf/index blocks) + */ + struct kunit_meta_block *meta_blocks; + /* + * Mock block allocator and free tracking + */ + ext4_fsblk_t next_alloc_pblk; + unsigned int alloc_calls; + ext4_fsblk_t last_alloc_pblk; + unsigned int last_alloc_len; + int fail_alloc_err; + + unsigned int free_calls; + ext4_fsblk_t last_free_pblk; + unsigned long last_free_count; + int last_free_flags; + unsigned long total_freed_blocks; + + unsigned int zeroout_calls; + ext4_lblk_t last_zeroout_lblk; + ext4_lblk_t last_zeroout_len; + unsigned int orphan_add_calls; + unsigned int orphan_del_calls; + struct dentry k_dentry; + + bool fail_getblk; } k_ctx; /* @@ -126,6 +151,40 @@ struct kunit_ext_test_param { struct kunit_ext_data_state exp_data_state[3]; }; +static unsigned long ext_dummy_shrinker_count(struct shrinker *shrink, + struct shrink_control *sc) +{ + return 0; +} + +static unsigned long ext_dummy_shrinker_scan(struct shrinker *shrink, + struct shrink_control *sc) +{ + return SHRINK_STOP; +} + +#ifdef CONFIG_QUOTA +static struct dquot __rcu **ext_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} + +static qsize_t *ext_get_reserved_space(struct inode *inode) +{ + return &EXT4_I(inode)->i_reserved_quota; +} + +static const struct dquot_operations ext_dummy_qops = { + .get_reserved_space = ext_get_reserved_space, +}; +#endif + +static const struct super_operations ext_dummy_sops = { +#ifdef CONFIG_QUOTA + .get_dquots = ext_get_dquots, +#endif +}; + static int ext_init_fs_context(struct fs_context *fc) { return 0; @@ -142,41 +201,224 @@ static struct file_system_type ext_fs_type = { .kill_sb = kill_anon_super, }; +static void ext_init_mock_inode(struct ext4_inode_info *ei, + struct super_block *sb, unsigned long ino) +{ + struct inode *inode = &ei->vfs_inode; + + memset(ei, 0, sizeof(*ei)); + inode->i_sb = sb; + inode->i_ino = ino; + inode->i_mode = S_IFREG | 0644; + set_nlink(inode, 1); + inode->i_blkbits = sb->s_blocksize_bits; + inode->i_flags |= S_NOQUOTA | S_NOSEC; + inode->i_mapping = &inode->i_data; + inode_set_iversion(inode, 1); + + spin_lock_init(&inode->i_lock); + i_size_ordered_init(inode); + init_rwsem(&inode->i_rwsem); + address_space_init_once(&inode->i_data); + init_rwsem(&inode->i_data.invalidate_lock); + inode->i_data.host = inode; + inode_state_set_raw(inode, I_DIRTY_SYNC | I_DIRTY_DATASYNC); + + ext4_es_init_tree(&ei->i_es_tree); + ext4_init_pending_tree(&ei->i_pending_tree); + rwlock_init(&ei->i_es_lock); + INIT_LIST_HEAD(&ei->i_es_list); + INIT_LIST_HEAD(&ei->i_orphan); + INIT_LIST_HEAD(&ei->i_fc_list); + INIT_LIST_HEAD(&ei->i_fc_dilist); + spin_lock_init(&ei->i_fc_lock); + init_rwsem(&ei->i_data_sem); + init_rwsem(&ei->xattr_sem); + spin_lock_init(&ei->i_raw_lock); + spin_lock_init(&ei->i_block_reservation_lock); + rwlock_init(&ei->i_prealloc_lock); + ei->i_prealloc_node = RB_ROOT; + ei->i_csum_seed = 0x12345678; + + ei->i_disksize = (EXT_DATA_LBLK + EXT_DATA_LEN + 10) + << sb->s_blocksize_bits; + inode->i_size = ei->i_disksize; + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); +} + +static void ext_cleanup_inode(struct inode *inode) +{ + struct ext4_inode_info *ei = EXT4_I(inode); + struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); + struct rb_node *node; + + down_write(&ei->i_data_sem); + ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS); + up_write(&ei->i_data_sem); + + while ((node = rb_first(&ei->i_pending_tree.root)) != NULL) { + struct pending_reservation *pr; + + pr = rb_entry(node, struct pending_reservation, rb_node); + ext4_remove_pending(inode, EXT4_C2B(sbi, pr->lclu)); + } +} + static void extents_kunit_exit(struct kunit *test) { + struct block_device *bdev; struct ext4_sb_info *sbi; + struct super_block *sb; if (!k_ctx.k_ei) return; - sbi = k_ctx.k_ei->vfs_inode.i_sb->s_fs_info; + sb = k_ctx.k_ei->vfs_inode.i_sb; + sbi = sb->s_fs_info; + bdev = sb->s_bdev; + + if (k_ctx.k_ei2) { + ext_cleanup_inode(&k_ctx.k_ei2->vfs_inode); + kfree(k_ctx.k_ei2); + } + ext_cleanup_inode(&k_ctx.k_ei->vfs_inode); + + percpu_counter_destroy(&sbi->s_freeclusters_counter); + percpu_counter_destroy(&sbi->s_dirtyclusters_counter); ext4_es_unregister_shrinker(sbi); ext4_es_destroy_stats(sbi); - deactivate_super(sbi->s_sb); + deactivate_super(sb); + + kfree(k_ctx.meta_blocks); + kfree(sbi->s_es); + kfree(bdev->bd_queue); + kfree(bdev->bd_mapping); + kfree(bdev); kfree(sbi); kfree(k_ctx.k_ei); kfree(k_ctx.k_data); + memset(&k_ctx, 0, sizeof(k_ctx)); } static int __ext4_ext_dirty_stub(const char *where, unsigned int line, handle_t *handle, struct inode *inode, struct ext4_ext_path *path) +{ + if (path && path->p_bh) { + ext4_extent_block_csum_set_test(inode, + ext_block_hdr(path->p_bh)); + set_buffer_verified(path->p_bh); + } + return 0; +} + +static int __ext4_handle_dirty_metadata_stub(const char *where, + unsigned int line, + handle_t *handle, + struct inode *inode, + struct buffer_head *bh) +{ + if (bh) + set_buffer_uptodate(bh); + return 0; +} + +static int __ext4_mark_inode_dirty_stub(handle_t *handle, struct inode *inode, + const char *func, unsigned int line) { return 0; } +static struct buffer_head *ext4_ext_getblk_stub(struct inode *inode, + ext4_fsblk_t pblk, + gfp_t gfp_flags) +{ + struct kunit_meta_block *slot = NULL; + int i; + + if (k_ctx.fail_getblk || !k_ctx.meta_blocks) + return NULL; + + for (i = 0; i < EXT_MAX_META_BLOCKS; i++) { + if (k_ctx.meta_blocks[i].in_use && + k_ctx.meta_blocks[i].pblk == pblk) { + slot = &k_ctx.meta_blocks[i]; + break; + } + } + + if (!slot) { + for (i = 0; i < EXT_MAX_META_BLOCKS; i++) { + if (!k_ctx.meta_blocks[i].in_use) { + slot = &k_ctx.meta_blocks[i]; + break; + } + } + if (!slot) + return NULL; + + memset(slot, 0, sizeof(*slot)); + slot->in_use = true; + slot->pblk = pblk; + slot->bh.b_data = slot->data; + slot->bh.b_size = inode->i_sb->s_blocksize; + slot->bh.b_blocknr = pblk; + slot->bh.b_bdev = inode->i_sb->s_bdev; + atomic_set(&slot->bh.b_count, 1); + set_buffer_uptodate(&slot->bh); + set_buffer_mapped(&slot->bh); + } + + get_bh(&slot->bh); + return &slot->bh; +} + +static ext4_fsblk_t ext4_mb_new_blocks_stub(handle_t *handle, + struct ext4_allocation_request *ar, + int *errp) +{ + struct ext4_sb_info *sbi = EXT4_SB(ar->inode->i_sb); + ext4_fsblk_t pblk; + + k_ctx.alloc_calls++; + if (k_ctx.fail_alloc_err) { + *errp = k_ctx.fail_alloc_err; + return 0; + } + + pblk = k_ctx.next_alloc_pblk; + k_ctx.next_alloc_pblk += EXT4_C2B(sbi, ar->len); + k_ctx.last_alloc_pblk = pblk; + k_ctx.last_alloc_len = ar->len; + *errp = 0; + return pblk; +} + +static void ext4_free_blocks_stub(handle_t *handle, struct inode *inode, + struct buffer_head *bh, ext4_fsblk_t block, + unsigned long count, int flags) +{ + k_ctx.free_calls++; + k_ctx.last_free_pblk = block; + k_ctx.last_free_count = count; + k_ctx.last_free_flags = flags; + k_ctx.total_freed_blocks += count; +} + static struct ext4_ext_path * ext4_ext_insert_extent_stub(handle_t *handle, struct inode *inode, struct ext4_ext_path *path, struct ext4_extent *newext, int gb_flags) { + ext4_free_ext_path(path); return ERR_PTR(-ENOSPC); } /* * We will zeroout the equivalent range in the data area */ -static int ext4_ext_zeroout_stub(struct inode *inode, struct ext4_extent *ex) +static int ext4_ext_zeroout_stub(handle_t *handle, struct inode *inode, + struct ext4_extent *ex) { ext4_lblk_t ee_block, off_blk; loff_t ee_len; @@ -199,8 +441,9 @@ static int ext4_ext_zeroout_stub(struct inode *inode, struct ext4_extent *ex) return 0; } -static int ext4_issue_zeroout_stub(struct inode *inode, ext4_lblk_t lblk, - ext4_fsblk_t pblk, ext4_lblk_t len) +static int ext4_issue_zeroout_stub(handle_t *handle, struct inode *inode, + ext4_lblk_t lblk, ext4_fsblk_t pblk, + ext4_lblk_t len) { ext4_lblk_t off_blk; loff_t off_bytes; @@ -228,10 +471,11 @@ static int extents_kunit_init(struct kunit *test) struct super_block *sb; struct fs_context *fc; struct ext4_sb_info *sbi = NULL; - struct kunit_ext_test_param *param = - (struct kunit_ext_test_param *)(test->param_value); int err; + memset(&k_ctx, 0, sizeof(k_ctx)); + k_ctx.next_alloc_pblk = EXT_ALLOC_BASE_PBLK; + sbi = kzalloc_obj(struct ext4_sb_info); if (sbi == NULL) return -ENOMEM; @@ -250,16 +494,93 @@ static int extents_kunit_init(struct kunit *test) sbi->s_sb = sb; sb->s_fs_info = sbi; - + sb->s_op = &ext_dummy_sops; +#ifdef CONFIG_QUOTA + sb->dq_op = &ext_dummy_qops; +#endif +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; +#endif sb->s_blocksize = 4096; sb->s_blocksize_bits = 12; + sb->s_maxbytes = MAX_LFS_FILESIZE; + strscpy(sb->s_id, "extents_kunit", sizeof(sb->s_id)); + + sb->s_bdev = kzalloc_obj(struct block_device); + if (!sb->s_bdev) { + err = -ENOMEM; + goto out_deactivate; + } + bdev_set_flag(sb->s_bdev, BD_READ_ONLY); + sb->s_bdev->bd_mapping = kzalloc_obj(struct address_space); + if (!sb->s_bdev->bd_mapping) { + err = -ENOMEM; + goto out_bdev; + } + sb->s_bdev->bd_queue = kzalloc_obj(struct request_queue); + if (!sb->s_bdev->bd_queue) { + err = -ENOMEM; + goto out_bdev_mapping; + } - if (!param || !param->disable_zeroout) - sbi->s_extent_max_zeroout_kb = 32; + sbi->s_es = kzalloc_obj(struct ext4_super_block); + if (!sbi->s_es) { + err = -ENOMEM; + goto out_bdev_queue; + } + sbi->s_es->s_first_data_block = cpu_to_le32(1); + sbi->s_es->s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + ext4_blocks_count_set(sbi->s_es, EXT_TOTAL_BLOCKS); + set_opt(sb, ERRORS_CONT); + sbi->s_bitmap_maxbytes = 1ULL << 40; + sbi->s_blocks_per_group = 32768; + sbi->s_clusters_per_group = 32768; + sbi->s_cluster_ratio = 1; + sbi->s_cluster_bits = 0; + sbi->s_desc_per_block = 64; + sbi->s_groups_count = 32; + sbi->s_extent_max_zeroout_kb = 32; + mutex_init(&sbi->s_orphan_lock); + INIT_LIST_HEAD(&sbi->s_orphan); + spin_lock_init(&sbi->s_bdev_wb_lock); + spin_lock_init(&sbi->s_error_lock); + spin_lock_init(&sbi->s_md_lock); + ratelimit_state_init(&sbi->s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, + DEFAULT_RATELIMIT_BURST); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, + DEFAULT_RATELIMIT_BURST); + ratelimit_state_init(&sbi->s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, + DEFAULT_RATELIMIT_BURST); + + err = percpu_counter_init(&sbi->s_freeclusters_counter, 100000, + GFP_KERNEL); + if (err) + goto out_es; + err = percpu_counter_init(&sbi->s_dirtyclusters_counter, 0, + GFP_KERNEL); + if (err) + goto out_freeclusters; err = ext4_es_register_shrinker(sbi); if (err) - goto out_deactivate; + goto out_dirtyclusters; + + /* + * Isolate the mock shrinker from asynchronous background reclaim. + */ + sbi->s_es_shrinker->count_objects = ext_dummy_shrinker_count; + sbi->s_es_shrinker->scan_objects = ext_dummy_shrinker_scan; + + k_ctx.meta_blocks = kcalloc(EXT_MAX_META_BLOCKS, + sizeof(struct kunit_meta_block), + GFP_KERNEL); + if (!k_ctx.meta_blocks) { + err = -ENOMEM; + goto out; + } /* setup the mock inode */ k_ctx.k_ei = kzalloc_obj(struct ext4_inode_info); @@ -269,19 +590,7 @@ static int extents_kunit_init(struct kunit *test) } ei = k_ctx.k_ei; inode = &ei->vfs_inode; - - ext4_es_init_tree(&ei->i_es_tree); - rwlock_init(&ei->i_es_lock); - INIT_LIST_HEAD(&ei->i_es_list); - ei->i_es_all_nr = 0; - ei->i_es_shk_nr = 0; - ei->i_es_shrink_lblk = 0; - - ei->i_disksize = (EXT_DATA_LBLK + EXT_DATA_LEN + 10) - << sb->s_blocksize_bits; - ei->i_flags = 0; - ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); - inode->i_sb = sb; + ext_init_mock_inode(ei, sb, 12); k_ctx.k_data = kzalloc(EXT_DATA_LEN * 4096, GFP_KERNEL); if (k_ctx.k_data == NULL) { @@ -294,9 +603,6 @@ static int extents_kunit_init(struct kunit *test) */ memset(k_ctx.k_data, 'X', EXT_DATA_LEN * 4096); - /* create a tree with depth 0 */ - eh = (struct ext4_extent_header *)k_ctx.k_ei->i_data; - /* Fill extent header */ eh = ext_inode_hdr(&k_ctx.k_ei->vfs_inode); eh->eh_depth = 0; @@ -308,25 +614,34 @@ static int extents_kunit_init(struct kunit *test) /* * add 1 extent in leaf node covering: - * - lblks: [EXT_DATA_LBLK, EXT_DATA_LBLK * + EXT_DATA_LEN) + * - lblks: [EXT_DATA_LBLK, EXT_DATA_LBLK + EXT_DATA_LEN) * - pblks: [EXT_DATA_PBLK, EXT_DATA_PBLK + EXT_DATA_LEN) */ EXT_FIRST_EXTENT(eh)->ee_block = cpu_to_le32(EXT_DATA_LBLK); EXT_FIRST_EXTENT(eh)->ee_len = cpu_to_le16(EXT_DATA_LEN); ext4_ext_store_pblock(EXT_FIRST_EXTENT(eh), EXT_DATA_PBLK); - if (!param || param->is_unwrit_at_start) - ext4_ext_mark_unwritten(EXT_FIRST_EXTENT(eh)); + ext4_ext_mark_unwritten(EXT_FIRST_EXTENT(eh)); + down_write(&ei->i_data_sem); ext4_es_insert_extent(inode, EXT_DATA_LBLK, EXT_DATA_LEN, EXT_DATA_PBLK, - ext4_ext_is_unwritten(EXT_FIRST_EXTENT(eh)) ? - EXTENT_STATUS_UNWRITTEN : - EXTENT_STATUS_WRITTEN, - 0); + EXTENT_STATUS_UNWRITTEN, 0); + up_write(&ei->i_data_sem); /* Add stubs */ kunit_activate_static_stub(test, __ext4_ext_dirty, __ext4_ext_dirty_stub); - kunit_activate_static_stub(test, ext4_ext_zeroout, ext4_ext_zeroout_stub); + kunit_activate_static_stub(test, __ext4_handle_dirty_metadata, + __ext4_handle_dirty_metadata_stub); + kunit_activate_static_stub(test, __ext4_mark_inode_dirty, + __ext4_mark_inode_dirty_stub); + kunit_activate_static_stub(test, ext4_ext_getblk, + ext4_ext_getblk_stub); + kunit_activate_static_stub(test, ext4_mb_new_blocks, + ext4_mb_new_blocks_stub); + kunit_activate_static_stub(test, ext4_free_blocks, + ext4_free_blocks_stub); + kunit_activate_static_stub(test, ext4_ext_zeroout, + ext4_ext_zeroout_stub); kunit_activate_static_stub(test, ext4_issue_zeroout, ext4_issue_zeroout_stub); up_write(&sb->s_umount); @@ -334,14 +649,26 @@ static int extents_kunit_init(struct kunit *test) return 0; out: - kfree(k_ctx.k_ei); - k_ctx.k_ei = NULL; - kfree(k_ctx.k_data); k_ctx.k_data = NULL; - + kfree(k_ctx.k_ei); + k_ctx.k_ei = NULL; + kfree(k_ctx.meta_blocks); + k_ctx.meta_blocks = NULL; ext4_es_unregister_shrinker(sbi); ext4_es_destroy_stats(sbi); +out_dirtyclusters: + percpu_counter_destroy(&sbi->s_dirtyclusters_counter); +out_freeclusters: + percpu_counter_destroy(&sbi->s_freeclusters_counter); +out_es: + kfree(sbi->s_es); +out_bdev_queue: + kfree(sb->s_bdev->bd_queue); +out_bdev_mapping: + kfree(sb->s_bdev->bd_mapping); +out_bdev: + kfree(sb->s_bdev); out_deactivate: deactivate_locked_super(sb); kfree(sbi); @@ -394,12 +721,24 @@ static void test_split_convert(struct kunit *test) { struct ext4_ext_path *path; struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_extent_header *eh = ext_inode_hdr(inode); struct ext4_extent *ex; struct ext4_map_blocks map; const struct kunit_ext_test_param *param = (const struct kunit_ext_test_param *)(test->param_value); int blkbits = inode->i_sb->s_blocksize_bits; + if (param->disable_zeroout) + EXT4_SB(inode->i_sb)->s_extent_max_zeroout_kb = 0; + + if (!param->is_unwrit_at_start) { + ext4_ext_mark_initialized(EXT_FIRST_EXTENT(eh)); + down_write(&EXT4_I(inode)->i_data_sem); + ext4_es_insert_extent(inode, EXT_DATA_LBLK, EXT_DATA_LEN, + EXT_DATA_PBLK, EXTENT_STATUS_WRITTEN, 0); + up_write(&EXT4_I(inode)->i_data_sem); + } + if (param->is_zeroout_test) /* * Force zeroout by making ext4_ext_insert_extent return ENOSPC @@ -408,6 +747,7 @@ static void test_split_convert(struct kunit *test) ext4_ext_insert_extent_stub); path = ext4_find_extent(inode, EXT_DATA_LBLK, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); ex = path->p_ext; KUNIT_EXPECT_EQ(test, EXT_DATA_LBLK, le32_to_cpu(ex->ee_block)); KUNIT_EXPECT_EQ(test, EXT_DATA_LEN, ext4_ext_get_actual_len(ex)); @@ -425,15 +765,21 @@ static void test_split_convert(struct kunit *test) case TEST_SPLIT_CONVERT: path = ext4_split_convert_extents_test(NULL, inode, &map, path, param->split_flags, NULL); + if (!IS_ERR(path)) + ext4_free_ext_path(path); break; case TEST_CREATE_BLOCKS: + ext4_free_ext_path(path); ext4_map_create_blocks_helper(test, inode, &map, param->split_flags); break; default: + ext4_free_ext_path(path); KUNIT_FAIL(test, "param->type %d not support.", param->type); + return; } path = ext4_find_extent(inode, EXT_DATA_LBLK, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); ex = path->p_ext; for (int i = 0; i < param->nr_exp_ext; i++) { @@ -496,6 +842,8 @@ static void test_split_convert(struct kunit *test) ex = ex + 1; } + ext4_free_ext_path(path); + if (!param->is_zeroout_test) return; @@ -514,8 +862,2118 @@ static void test_split_convert(struct kunit *test) "# corruption in byte range [%lld, %lld)", off, len); } +} + +/* + * Helper to reset an inode's extent tree and extent status cache to empty. + */ +static void ext_reset_tree(struct inode *inode) +{ + struct ext4_inode_info *ei = EXT4_I(inode); + + down_write(&ei->i_data_sem); + ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS); + memset(ei->i_data, 0, sizeof(ei->i_data)); + ext4_ext_tree_init(NULL, inode); + up_write(&ei->i_data_sem); +} + +/* + * Helper to insert an extent into @inode's extent tree under i_data_sem. + */ +static int ext_insert_one(struct inode *inode, ext4_lblk_t lblk, + unsigned short len, ext4_fsblk_t pblk, + bool unwritten, int gb_flags) +{ + struct ext4_ext_path *path; + struct ext4_extent newex = {}; + + newex.ee_block = cpu_to_le32(lblk); + newex.ee_len = cpu_to_le16(len); + ext4_ext_store_pblock(&newex, pblk); + if (unwritten) + ext4_ext_mark_unwritten(&newex); + + down_write(&EXT4_I(inode)->i_data_sem); + path = ext4_find_extent(inode, lblk, NULL, EXT4_EX_NOCACHE); + if (IS_ERR(path)) { + up_write(&EXT4_I(inode)->i_data_sem); + return PTR_ERR(path); + } + path = ext4_ext_insert_extent(NULL, inode, path, &newex, + gb_flags | EXT4_EX_NOCACHE); + up_write(&EXT4_I(inode)->i_data_sem); + if (IS_ERR(path)) + return PTR_ERR(path); + + ext4_free_ext_path(path); + return 0; +} + +/* + * Verify 48-bit physical block number store and load helpers for both + * leaf extents (ext4_extent) and index entries (ext4_extent_idx). + */ +static void test_ext_pblock_48bit(struct kunit *test) +{ + struct ext4_extent ex = {}; + struct ext4_extent_idx idx = {}; + const ext4_fsblk_t pblk_48 = 0x123456789abcULL; + const ext4_fsblk_t pblk_max = 0xffffffffffffULL; + + ext4_ext_store_pblock(&ex, 0); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex), 0ULL); + + ext4_ext_store_pblock(&ex, 0xffffffffULL); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex), 0xffffffffULL); + KUNIT_EXPECT_EQ(test, le16_to_cpu(ex.ee_start_hi), 0); + + ext4_ext_store_pblock(&ex, pblk_48); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex.ee_start_lo), 0x56789abcU); + KUNIT_EXPECT_EQ(test, le16_to_cpu(ex.ee_start_hi), 0x1234U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex), pblk_48); + + ext4_ext_store_pblock(&ex, pblk_max); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex), pblk_max); + + ext4_idx_store_pblock(&idx, pblk_48); + KUNIT_EXPECT_EQ(test, le32_to_cpu(idx.ei_leaf_lo), 0x56789abcU); + KUNIT_EXPECT_EQ(test, le16_to_cpu(idx.ei_leaf_hi), 0x1234U); + KUNIT_EXPECT_EQ(test, ext4_idx_pblock(&idx), pblk_48); + + ext4_idx_store_pblock(&idx, pblk_max); + KUNIT_EXPECT_EQ(test, ext4_idx_pblock(&idx), pblk_max); +} + +/* + * Verify extent length encoding and unwritten bit manipulation at boundaries: + * - EXT_INIT_MAX_LEN (32768 = 0x8000) is the maximum initialized extent length + * and must NOT be treated as unwritten. + * - EXT_UNWRITTEN_MAX_LEN (32767 = 0x7fff) is the maximum unwritten extent + * length (stored on disk as 0xffff). + */ +static void test_ext_unwritten_len_encoding(struct kunit *test) +{ + struct ext4_extent ex = {}; + + ex.ee_len = cpu_to_le16(1); + KUNIT_EXPECT_EQ(test, ext4_ext_is_unwritten(&ex), 0); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex), 1); + + ext4_ext_mark_unwritten(&ex); + KUNIT_EXPECT_EQ(test, ext4_ext_is_unwritten(&ex), 1); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex), 1); + + ext4_ext_mark_initialized(&ex); + KUNIT_EXPECT_EQ(test, ext4_ext_is_unwritten(&ex), 0); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex), 1); + + ex.ee_len = cpu_to_le16(EXT_UNWRITTEN_MAX_LEN); + ext4_ext_mark_unwritten(&ex); + KUNIT_EXPECT_EQ(test, ext4_ext_is_unwritten(&ex), 1); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex), + EXT_UNWRITTEN_MAX_LEN); + + ext4_ext_mark_initialized(&ex); + KUNIT_EXPECT_EQ(test, ext4_ext_is_unwritten(&ex), 0); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex), + EXT_UNWRITTEN_MAX_LEN); + + ex.ee_len = cpu_to_le16(EXT_INIT_MAX_LEN); + KUNIT_EXPECT_EQ(test, ext4_ext_is_unwritten(&ex), 0); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex), EXT_INIT_MAX_LEN); +} + +/* + * Verify ext4_ext_tree_init() initializes the in-inode extent header and + * ext4_ext_check_inode() accepts valid empty and populated root headers. + */ +static void test_ext_tree_init_and_check_inode(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_extent_header *eh = ext_inode_hdr(inode); + + memset(k_ctx.k_ei->i_data, 0xff, sizeof(k_ctx.k_ei->i_data)); + ext4_ext_tree_init(NULL, inode); + + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_magic), + le16_to_cpu(EXT4_EXT_MAGIC)); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_depth), 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_max), 4); + KUNIT_EXPECT_EQ(test, le32_to_cpu(eh->eh_generation), 0U); + KUNIT_EXPECT_EQ(test, ext4_ext_check_inode(inode), 0); + + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 10, 5, 100, false, 0), 0); + KUNIT_EXPECT_EQ(test, ext4_ext_check_inode(inode), 0); +} + +enum ext_check_corrupt_type { + CORRUPT_BAD_MAGIC, + CORRUPT_BAD_DEPTH, + CORRUPT_ZERO_MAX, + CORRUPT_EXCESS_MAX, + CORRUPT_ENTRIES_GT_MAX, + CORRUPT_EMPTY_NONROOT_INDEX, + CORRUPT_ZERO_LEN_EXTENT, + CORRUPT_LBLK_OVERFLOW, + CORRUPT_PBLK_TOO_LOW, + CORRUPT_PBLK_TOO_HIGH, + CORRUPT_UNSORTED_EXTENTS, + CORRUPT_UNSORTED_INDEXES, + CORRUPT_NONROOT_LBLK_MISMATCH, +}; + +struct ext_check_corrupt_param { + const char *desc; + enum ext_check_corrupt_type type; +}; + +static const struct ext_check_corrupt_param ext_check_corrupt_params[] = { + { "invalid eh_magic", CORRUPT_BAD_MAGIC }, + { "mismatched eh_depth", CORRUPT_BAD_DEPTH }, + { "eh_max == 0", CORRUPT_ZERO_MAX }, + { "eh_max exceeds root capacity", CORRUPT_EXCESS_MAX }, + { "eh_entries exceeds eh_max", CORRUPT_ENTRIES_GT_MAX }, + { "empty index block at depth > 0", CORRUPT_EMPTY_NONROOT_INDEX }, + { "extent with ee_len == 0", CORRUPT_ZERO_LEN_EXTENT }, + { "extent logical block 32-bit wrap-around", CORRUPT_LBLK_OVERFLOW }, + { "extent physical block <= first_data_block", CORRUPT_PBLK_TOO_LOW }, + { "extent physical block past blocks_count", CORRUPT_PBLK_TOO_HIGH }, + { "overlapping/unsorted leaf extents", CORRUPT_UNSORTED_EXTENTS }, + { "unsorted index entries", CORRUPT_UNSORTED_INDEXES }, + { "non-root leaf first ee_block != parent ei_block", + CORRUPT_NONROOT_LBLK_MISMATCH }, +}; + +static void ext_check_corrupt_get_desc(struct kunit *test, const void *p, + char *desc) +{ + const struct ext_check_corrupt_param *param = p; + + strscpy(desc, param->desc, KUNIT_PARAM_DESC_SIZE); +} + +static int ext_check_corrupt_param_init(struct kunit *test) +{ + kunit_register_params_array(test, ext_check_corrupt_params, + ARRAY_SIZE(ext_check_corrupt_params), + ext_check_corrupt_get_desc); + return 0; +} + +/* + * Verify __ext4_ext_check() detects and rejects all classes of corrupt + * extent headers, leaf extents, and index entries with -EFSCORRUPTED. + */ +static void test_ext_check_corruptions(struct kunit *test) +{ + const struct ext_check_corrupt_param *param = test->param_value; + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); + struct ext4_extent_header *eh = ext_inode_hdr(inode); + struct ext4_extent *ex; + struct ext4_extent_idx *ix; + struct { + struct ext4_extent_header eh; + struct ext4_extent ex; + } nonroot_leaf; + int depth = 0; + ext4_fsblk_t pblk = 0; + ext4_lblk_t lblk = 0; + int err; + + ext_reset_tree(inode); + eh->eh_entries = cpu_to_le16(1); + ex = EXT_FIRST_EXTENT(eh); + ex->ee_block = cpu_to_le32(10); + ex->ee_len = cpu_to_le16(4); + ext4_ext_store_pblock(ex, 100); + + switch (param->type) { + case CORRUPT_BAD_MAGIC: + eh->eh_magic = cpu_to_le16(0xdead); + break; + case CORRUPT_BAD_DEPTH: + eh->eh_depth = cpu_to_le16(1); + depth = 0; + break; + case CORRUPT_ZERO_MAX: + eh->eh_max = 0; + break; + case CORRUPT_EXCESS_MAX: + eh->eh_max = cpu_to_le16(10); + break; + case CORRUPT_ENTRIES_GT_MAX: + eh->eh_entries = cpu_to_le16(5); + break; + case CORRUPT_EMPTY_NONROOT_INDEX: + eh->eh_depth = cpu_to_le16(1); + eh->eh_entries = 0; + depth = 1; + break; + case CORRUPT_ZERO_LEN_EXTENT: + ex->ee_len = 0; + break; + case CORRUPT_LBLK_OVERFLOW: + ex->ee_block = cpu_to_le32(0xfffffff0U); + ex->ee_len = cpu_to_le16(32); + break; + case CORRUPT_PBLK_TOO_LOW: + ext4_ext_store_pblock(ex, 1); + break; + case CORRUPT_PBLK_TOO_HIGH: + ext4_ext_store_pblock(ex, EXT_TOTAL_BLOCKS); + break; + case CORRUPT_UNSORTED_EXTENTS: + eh->eh_entries = cpu_to_le16(2); + ex[1].ee_block = cpu_to_le32(12); + ex[1].ee_len = cpu_to_le16(4); + ext4_ext_store_pblock(&ex[1], 200); + break; + case CORRUPT_UNSORTED_INDEXES: + eh->eh_depth = cpu_to_le16(1); + eh->eh_entries = cpu_to_le16(2); + depth = 1; + ix = EXT_FIRST_INDEX(eh); + ix[0].ei_block = cpu_to_le32(20); + ext4_idx_store_pblock(&ix[0], 500); + ix[1].ei_block = cpu_to_le32(10); + ext4_idx_store_pblock(&ix[1], 501); + break; + case CORRUPT_NONROOT_LBLK_MISMATCH: + eh->eh_depth = cpu_to_le16(1); + memset(&nonroot_leaf, 0, sizeof(nonroot_leaf)); + nonroot_leaf.eh.eh_magic = EXT4_EXT_MAGIC; + nonroot_leaf.eh.eh_depth = 0; + nonroot_leaf.eh.eh_entries = cpu_to_le16(1); + nonroot_leaf.eh.eh_max = cpu_to_le16(340); + nonroot_leaf.ex.ee_block = cpu_to_le32(10); + nonroot_leaf.ex.ee_len = cpu_to_le16(4); + ext4_ext_store_pblock(&nonroot_leaf.ex, 100); + eh = &nonroot_leaf.eh; + depth = 0; + pblk = 500; + lblk = 20; + break; + } + + /* Suppress __ext4_error_inode() log spam during expected failure */ + set_bit(EXT4_FLAGS_SHUTDOWN, &sbi->s_ext4_flags); + err = ext4_ext_check_test(inode, eh, depth, pblk, lblk); + clear_bit(EXT4_FLAGS_SHUTDOWN, &sbi->s_ext4_flags); + + KUNIT_EXPECT_EQ(test, err, -EFSCORRUPTED); +} + +/* + * Verify metadata checksum calculation and verification on external extent + * tree blocks when EXT4_FEATURE_RO_COMPAT_METADATA_CSUM is enabled. + */ +static void test_ext_block_csum_verify(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); + struct buffer_head *bh; + struct ext4_extent_header *eh; + struct ext4_extent *ex; + struct ext4_extent_tail *et; + int max_entries; + int err; + + ext_reset_tree(inode); + ext_inode_hdr(inode)->eh_depth = cpu_to_le16(1); + ext4_set_feature_metadata_csum(inode->i_sb); + bh = ext4_ext_getblk_stub(inode, EXT_META_BASE_PBLK, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, bh); + + max_entries = (inode->i_sb->s_blocksize - + sizeof(struct ext4_extent_header) - + sizeof(struct ext4_extent_tail)) / + sizeof(struct ext4_extent); + + eh = ext_block_hdr(bh); + eh->eh_magic = EXT4_EXT_MAGIC; + eh->eh_depth = 0; + eh->eh_entries = cpu_to_le16(1); + eh->eh_max = cpu_to_le16(max_entries); + + ex = EXT_FIRST_EXTENT(eh); + ex->ee_block = cpu_to_le32(10); + ex->ee_len = cpu_to_le16(5); + ext4_ext_store_pblock(ex, 100); + + ext4_extent_block_csum_set_test(inode, eh); + err = ext4_ext_check_test(inode, eh, 0, EXT_META_BASE_PBLK, 10); + KUNIT_EXPECT_EQ(test, err, 0); + + /* Flip a bit in the tail checksum and verify -EFSBADCRC */ + et = find_ext4_extent_tail(eh); + et->et_checksum ^= cpu_to_le32(0x1); + + set_bit(EXT4_FLAGS_SHUTDOWN, &sbi->s_ext4_flags); + err = ext4_ext_check_test(inode, eh, 0, EXT_META_BASE_PBLK, 10); + clear_bit(EXT4_FLAGS_SHUTDOWN, &sbi->s_ext4_flags); + + KUNIT_EXPECT_EQ(test, err, -EFSBADCRC); + brelse(bh); +} + +/* + * Verify ext4_find_extent() binary search on an empty tree and a multi-extent + * root leaf, as well as extent status caching vs EXT4_EX_NOCACHE. + */ +static void test_find_extent_root_binsearch(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_ext_path *path; + struct extent_status es; + + ext_reset_tree(inode); + + /* Empty tree returns NULL p_ext */ + path = ext4_find_extent(inode, 10, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + KUNIT_EXPECT_PTR_EQ(test, path[0].p_ext, NULL); + ext4_free_ext_path(path); + + /* Populate 3 separated extents: [10, 15), [20, 25), [30, 35) */ + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 10, 5, 100, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 20, 5, 200, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 30, 5, 300, false, 0), 0); + + /* Lookup before first extent (lblk 5) -> points to first extent */ + path = ext4_find_extent(inode, 5, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + KUNIT_ASSERT_NOT_NULL(test, path[0].p_ext); + KUNIT_EXPECT_EQ(test, le32_to_cpu(path[0].p_ext->ee_block), 10U); + ext4_free_ext_path(path); + + /* Lookup inside first extent (lblk 12) */ + path = ext4_find_extent(inode, 12, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(path[0].p_ext->ee_block), 10U); + ext4_free_ext_path(path); + + /* Lookup in hole between 1st and 2nd extent (lblk 17) -> 1st extent */ + path = ext4_find_extent(inode, 17, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(path[0].p_ext->ee_block), 10U); + ext4_free_ext_path(path); + + /* Lookup exact start of 2nd extent (lblk 20) */ + path = ext4_find_extent(inode, 20, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(path[0].p_ext->ee_block), 20U); + ext4_free_ext_path(path); + + /* Lookup past last extent (lblk 50) -> 3rd extent */ + path = ext4_find_extent(inode, 50, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(path[0].p_ext->ee_block), 30U); + ext4_free_ext_path(path); + + /* EXT4_EX_NOCACHE left i_es_tree empty */ + KUNIT_EXPECT_EQ(test, ext4_es_lookup_extent(inode, 10, NULL, &es, NULL), + 0); + + /* Lookup without EXT4_EX_NOCACHE populates extents and holes in es */ + down_read(&EXT4_I(inode)->i_data_sem); + path = ext4_find_extent(inode, 20, NULL, 0); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + ext4_free_ext_path(path); + + /* + * Verify inter-extent hole [15, 20) and extents are cached in es + * (ext4_cache_extents only caches holes where prev != 0). + */ + KUNIT_EXPECT_EQ(test, ext4_es_lookup_extent(inode, 5, NULL, &es, NULL), + 0); + KUNIT_EXPECT_EQ(test, ext4_es_lookup_extent(inode, 17, NULL, &es, NULL), + 1); + KUNIT_EXPECT_TRUE(test, ext4_es_is_hole(&es)); + KUNIT_EXPECT_EQ(test, es.es_lblk, 15U); + KUNIT_EXPECT_EQ(test, es.es_len, 5U); + + KUNIT_EXPECT_EQ(test, ext4_es_lookup_extent(inode, 22, NULL, &es, NULL), + 1); + KUNIT_EXPECT_TRUE(test, ext4_es_is_written(&es)); + KUNIT_EXPECT_EQ(test, ext4_es_pblock(&es), 200ULL); +} + +/* + * Helper to construct a depth-1 tree with two external leaf blocks: + * Leaf 0 (pblk 500): [10, 15) -> 1000 (written), [20, 25) -> 1100 (written) + * Leaf 1 (pblk 501): [40, 45) -> 2000 (unwritten), [50, 55) -> 2100 (written) + */ +static void setup_depth1_two_leaf_tree(struct kunit *test, struct inode *inode) +{ + struct ext4_extent_header *root_eh = ext_inode_hdr(inode); + struct ext4_extent_idx *idx; + struct buffer_head *bh0, *bh1; + struct ext4_extent_header *eh0, *eh1; + struct ext4_extent *ex; + int max_leaf = (inode->i_sb->s_blocksize - + sizeof(struct ext4_extent_header)) / + sizeof(struct ext4_extent); + + ext_reset_tree(inode); + + root_eh->eh_depth = cpu_to_le16(1); + root_eh->eh_entries = cpu_to_le16(2); + root_eh->eh_max = cpu_to_le16(ext4_ext_space_root_idx_test(inode, 0)); + + idx = EXT_FIRST_INDEX(root_eh); + idx[0].ei_block = cpu_to_le32(10); + ext4_idx_store_pblock(&idx[0], EXT_META_BASE_PBLK); + idx[1].ei_block = cpu_to_le32(40); + ext4_idx_store_pblock(&idx[1], EXT_META_BASE_PBLK + 1); + + bh0 = ext4_ext_getblk_stub(inode, EXT_META_BASE_PBLK, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, bh0); + eh0 = ext_block_hdr(bh0); + eh0->eh_magic = EXT4_EXT_MAGIC; + eh0->eh_depth = 0; + eh0->eh_entries = cpu_to_le16(2); + eh0->eh_max = cpu_to_le16(max_leaf); + ex = EXT_FIRST_EXTENT(eh0); + ex[0].ee_block = cpu_to_le32(10); + ex[0].ee_len = cpu_to_le16(5); + ext4_ext_store_pblock(&ex[0], 1000); + ex[1].ee_block = cpu_to_le32(20); + ex[1].ee_len = cpu_to_le16(5); + ext4_ext_store_pblock(&ex[1], 1100); + brelse(bh0); + + bh1 = ext4_ext_getblk_stub(inode, EXT_META_BASE_PBLK + 1, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, bh1); + eh1 = ext_block_hdr(bh1); + eh1->eh_magic = EXT4_EXT_MAGIC; + eh1->eh_depth = 0; + eh1->eh_entries = cpu_to_le16(2); + eh1->eh_max = cpu_to_le16(max_leaf); + ex = EXT_FIRST_EXTENT(eh1); + ex[0].ee_block = cpu_to_le32(40); + ex[0].ee_len = cpu_to_le16(5); + ext4_ext_store_pblock(&ex[0], 2000); + ext4_ext_mark_unwritten(&ex[0]); + ex[1].ee_block = cpu_to_le32(50); + ex[1].ee_len = cpu_to_le16(5); + ext4_ext_store_pblock(&ex[1], 2100); + brelse(bh1); +} + +/* + * Verify multi-level (depth 1) extent lookup and tree navigation helpers: + * ext4_ext_next_allocated_block(), ext4_ext_next_leaf_block(), + * ext4_ext_search_left(), and ext4_ext_search_right() across leaf boundaries. + */ +static void test_find_extent_multilevel_and_navigation(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_ext_path *path; + struct ext4_extent ret_ex; + ext4_lblk_t logical; + ext4_fsblk_t phys; + int ret; + + setup_depth1_two_leaf_tree(test, inode); + + /* Lookup first extent [10, 15) in leaf 0 */ + path = ext4_find_extent(inode, 10, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + KUNIT_EXPECT_EQ(test, path->p_depth, 1); + KUNIT_EXPECT_EQ(test, le32_to_cpu(path[1].p_ext->ee_block), 10U); + KUNIT_EXPECT_EQ(test, ext4_ext_next_allocated_block(path), 20U); + KUNIT_EXPECT_EQ(test, ext4_ext_next_leaf_block_test(path), 40U); + ext4_free_ext_path(path); - return; + /* + * Lookup lblk 30 (in hole between leaf 0 and leaf 1): + * path[1].p_ext points to [20, 25) (last extent in leaf 0). + */ + path = ext4_find_extent(inode, 30, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(path[1].p_ext->ee_block), 20U); + KUNIT_EXPECT_EQ(test, ext4_ext_next_allocated_block(path), 40U); + + /* Search left from lblk 30 finds last block of [20, 25) -> 24 @ 1104 */ + logical = 30; + ret = ext4_ext_search_left_test(inode, path, &logical, &phys); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, logical, 24U); + KUNIT_EXPECT_EQ(test, phys, 1104ULL); + + /* Search right from lblk 30 crosses into leaf 1 -> [40, 45) @ 2000 */ + logical = 30; + ret = ext4_ext_search_right_test(inode, path, &logical, &phys, &ret_ex, + EXT4_EX_NOCACHE); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, logical, 40U); + KUNIT_EXPECT_EQ(test, phys, 2000ULL); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ret_ex.ee_block), 40U); + ext4_free_ext_path(path); + + /* Lookup last extent [50, 55) in leaf 1 */ + path = ext4_find_extent(inode, 52, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(path[1].p_ext->ee_block), 50U); + KUNIT_EXPECT_EQ(test, ext4_ext_next_allocated_block(path), + EXT_MAX_BLOCKS); + KUNIT_EXPECT_EQ(test, ext4_ext_next_leaf_block_test(path), + EXT_MAX_BLOCKS); + ext4_free_ext_path(path); +} + +/* + * Verify ext4_ext_precache() walks all leaf blocks of a multi-level extent + * tree, caches all extents and holes into the extent status tree, and sets + * EXT4_STATE_EXT_PRECACHED. + */ +static void test_ext_precache(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct extent_status es; + int err; + + setup_depth1_two_leaf_tree(test, inode); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(inode, + EXT4_STATE_EXT_PRECACHED)); + + err = ext4_ext_precache(inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, + ext4_test_inode_state(inode, + EXT4_STATE_EXT_PRECACHED)); + + /* Verify cached inter-extent hole [15, 20) and extents from both leaves */ + KUNIT_EXPECT_EQ(test, ext4_es_lookup_extent(inode, 17, NULL, &es, NULL), + 1); + KUNIT_EXPECT_TRUE(test, ext4_es_is_hole(&es)); + KUNIT_EXPECT_EQ(test, es.es_lblk, 15U); + KUNIT_EXPECT_EQ(test, es.es_len, 5U); + + KUNIT_EXPECT_EQ(test, ext4_es_lookup_extent(inode, 10, NULL, &es, NULL), + 1); + KUNIT_EXPECT_TRUE(test, ext4_es_is_written(&es)); + KUNIT_EXPECT_EQ(test, ext4_es_pblock(&es), 1000ULL); + + KUNIT_EXPECT_EQ(test, ext4_es_lookup_extent(inode, 40, NULL, &es, NULL), + 1); + KUNIT_EXPECT_TRUE(test, ext4_es_is_unwritten(&es)); + KUNIT_EXPECT_EQ(test, ext4_es_pblock(&es), 2000ULL); + + KUNIT_EXPECT_EQ(test, ext4_es_lookup_extent(inode, 50, NULL, &es, NULL), + 1); + KUNIT_EXPECT_TRUE(test, ext4_es_is_written(&es)); + KUNIT_EXPECT_EQ(test, ext4_es_pblock(&es), 2100ULL); +} + +/* + * Verify ext4_can_extents_be_merged() rules for written/unwritten state, + * logical and physical contiguity, and maximum length limits. + */ +static void test_can_extents_be_merged(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_extent ex1 = {}, ex2 = {}; + + /* Contiguous written extents [10, 15) @ 100 and [15, 20) @ 105 */ + ex1.ee_block = cpu_to_le32(10); + ex1.ee_len = cpu_to_le16(5); + ext4_ext_store_pblock(&ex1, 100); + ex2.ee_block = cpu_to_le32(15); + ex2.ee_len = cpu_to_le16(5); + ext4_ext_store_pblock(&ex2, 105); + KUNIT_EXPECT_EQ(test, ext4_can_extents_be_merged_test(inode, &ex1, &ex2), + 1); + + /* Mismatched written vs unwritten cannot merge */ + ext4_ext_mark_unwritten(&ex2); + KUNIT_EXPECT_EQ(test, ext4_can_extents_be_merged_test(inode, &ex1, &ex2), + 0); + + /* Both unwritten and contiguous can merge */ + ext4_ext_mark_unwritten(&ex1); + KUNIT_EXPECT_EQ(test, ext4_can_extents_be_merged_test(inode, &ex1, &ex2), + 1); + + /* Non-contiguous physical blocks cannot merge */ + ext4_ext_mark_initialized(&ex1); + ext4_ext_mark_initialized(&ex2); + ext4_ext_store_pblock(&ex2, 200); + KUNIT_EXPECT_EQ(test, ext4_can_extents_be_merged_test(inode, &ex1, &ex2), + 0); + + /* Non-contiguous logical blocks cannot merge */ + ext4_ext_store_pblock(&ex2, 105); + ex2.ee_block = cpu_to_le32(16); + KUNIT_EXPECT_EQ(test, ext4_can_extents_be_merged_test(inode, &ex1, &ex2), + 0); + + /* Written max length boundary (EXT_INIT_MAX_LEN = 32768) */ + ex1.ee_block = cpu_to_le32(0); + ex1.ee_len = cpu_to_le16(32760); + ext4_ext_store_pblock(&ex1, 100); + ex2.ee_block = cpu_to_le32(32760); + ex2.ee_len = cpu_to_le16(8); + ext4_ext_store_pblock(&ex2, 100 + 32760); + KUNIT_EXPECT_EQ(test, ext4_can_extents_be_merged_test(inode, &ex1, &ex2), + 1); + ex2.ee_len = cpu_to_le16(9); + KUNIT_EXPECT_EQ(test, ext4_can_extents_be_merged_test(inode, &ex1, &ex2), + 0); + + /* Unwritten max length boundary (EXT_UNWRITTEN_MAX_LEN = 32767) */ + ex1.ee_len = cpu_to_le16(32760); + ext4_ext_mark_unwritten(&ex1); + ex2.ee_len = cpu_to_le16(7); + ext4_ext_mark_unwritten(&ex2); + KUNIT_EXPECT_EQ(test, ext4_can_extents_be_merged_test(inode, &ex1, &ex2), + 1); + ex2.ee_len = cpu_to_le16(8); + ext4_ext_mark_unwritten(&ex2); + KUNIT_EXPECT_EQ(test, ext4_can_extents_be_merged_test(inode, &ex1, &ex2), + 0); +} + +/* + * Verify ext4_ext_insert_extent() appending, prepending, 3-way bridge merging, + * and EXT4_GET_BLOCKS_SPLIT_NOMERGE suppression. + */ +static void test_insert_extent_merge_and_nomerge(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_extent_header *eh = ext_inode_hdr(inode); + struct ext4_extent *ex; + + ext_reset_tree(inode); + + /* Insert [10, 15) @ 100 and [20, 25) @ 110 */ + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 10, 5, 100, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 20, 5, 110, false, 0), 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 2); + + /* Append [15, 18) @ 105 -> merges with [10, 15) into [10, 18) */ + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 15, 3, 105, false, 0), 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 2); + ex = EXT_FIRST_EXTENT(eh); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[0].ee_block), 10U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[0]), 8); + + /* Insert [18, 20) @ 108 -> bridges [10, 18) and [20, 25) into [10, 25) */ + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 18, 2, 108, false, 0), 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 1); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[0].ee_block), 10U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[0]), 15); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex[0]), 100ULL); + + /* Insert contiguous [25, 30) @ 115 with SPLIT_NOMERGE -> stays separate */ + KUNIT_ASSERT_EQ(test, + ext_insert_one(inode, 25, 5, 115, false, + EXT4_GET_BLOCKS_SPLIT_NOMERGE), + 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 2); +} + +/* + * Verify tree growth (depth 0 -> 1 via ext4_ext_grow_indepth), parent index + * update when inserting a new lowest lblk (ext4_ext_correct_indexes), and + * tree collapse back into the inode root (depth 1 -> 0 via + * ext4_ext_try_to_merge_up) when merging reduces leaf entries to <= 4. + */ +static void test_insert_extent_grow_and_merge_up(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_extent_header *eh = ext_inode_hdr(inode); + struct ext4_extent *ex; + + ext_reset_tree(inode); + + /* + * Insert 4 non-contiguous extents that fill the root leaf (eh_max = 4): + * [10, 12) @ 100, [14, 16) @ 104, [18, 20) @ 108, [22, 24) @ 112. + */ + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 10, 2, 100, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 14, 2, 104, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 18, 2, 108, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 22, 2, 112, false, 0), 0); + KUNIT_EXPECT_EQ(test, ext_depth(inode), 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 4); + + /* + * Insert 5th extent [26, 28) @ 116: triggers ext4_ext_grow_indepth(), + * moving the leaf to a newly allocated external block and increasing + * tree depth to 1. + */ + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 26, 2, 116, false, 0), 0); + KUNIT_EXPECT_EQ(test, ext_depth(inode), 1); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 1); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT_FIRST_INDEX(eh)->ei_block), 10U); + KUNIT_EXPECT_EQ(test, k_ctx.alloc_calls, 1U); + + /* + * Prepend [8, 10) @ 98 to [10, 12) @ 100: modifies first extent in the + * leaf and triggers ext4_ext_correct_indexes(), updating root ei_block + * from 10 to 8. + */ + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 8, 2, 98, false, 0), 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT_FIRST_INDEX(eh)->ei_block), 8U); + + /* + * Bridge two gaps ([12, 14) @ 102 and [16, 18) @ 106): leaf entries + * shrink from 5 -> 4 -> 3. Once <= 4 (max_root), ext4_ext_try_to_merge_up() + * copies the extents back into the inode root and frees the leaf block! + */ + k_ctx.free_calls = 0; + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 12, 2, 102, false, 0), 0); + KUNIT_EXPECT_EQ(test, ext_depth(inode), 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 4); + KUNIT_EXPECT_EQ(test, k_ctx.free_calls, 1U); + + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 16, 2, 106, false, 0), 0); + KUNIT_EXPECT_EQ(test, ext_depth(inode), 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 3); + ex = EXT_FIRST_EXTENT(eh); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[0].ee_block), 8U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[0]), 12); +} + +/* + * Verify ext4_ext_split() at depth 1 both when splitting a full leaf in the + * middle (moving tail extents to a newly allocated leaf block) and when + * appending past the end of a full leaf (m == 0). + */ +static void test_insert_extent_leaf_split(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_extent_header *eh = ext_inode_hdr(inode); + struct ext4_ext_path *path; + int i; + + ext_reset_tree(inode); + + /* + * Insert 340 non-contiguous extents [i * 4, i * 4 + 2) @ 2000 + i * 4 + * to grow from depth 0 to depth 1 and completely fill the external + * 4096-byte leaf block (eh_max = 340). + */ + for (i = 0; i < 340; i++) { + KUNIT_ASSERT_EQ_MSG(test, + ext_insert_one(inode, i * 4, 2, + 2000 + i * 4, false, 0), + 0, "i=%d", i); + } + KUNIT_EXPECT_EQ(test, ext_depth(inode), 1); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 1); + + /* + * Insert [402, 403) @ 9000 in the middle of the full leaf between + * [400, 402) and [404, 406): triggers ext4_ext_split() with m = 239, + * moving [404..1358) into a newly allocated second leaf block. + */ + k_ctx.alloc_calls = 0; + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 402, 1, 9000, false, 0), 0); + KUNIT_EXPECT_EQ(test, k_ctx.alloc_calls, 1U); + KUNIT_EXPECT_EQ(test, ext_depth(inode), 1); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 2); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT_FIRST_INDEX(eh)[0].ei_block), 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT_FIRST_INDEX(eh)[1].ei_block), + 404U); + KUNIT_EXPECT_EQ(test, ext4_ext_check_inode(inode), 0); + + path = ext4_find_extent(inode, 402, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + KUNIT_EXPECT_EQ(test, le16_to_cpu(path[1].p_hdr->eh_entries), 102); + KUNIT_EXPECT_EQ(test, le32_to_cpu(path[1].p_ext->ee_block), 402U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(path[1].p_ext), 9000ULL); + ext4_free_ext_path(path); + + path = ext4_find_extent(inode, 404, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + KUNIT_EXPECT_EQ(test, le16_to_cpu(path[1].p_hdr->eh_entries), 239); + KUNIT_EXPECT_EQ(test, le32_to_cpu(path[1].p_ext->ee_block), 404U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(path[1].p_ext), 2404ULL); + ext4_free_ext_path(path); + + /* + * Fill the second leaf to capacity (239 + 101 = 340 entries), then + * append [1764, 1766) @ 3764 past its end to exercise ext4_ext_split() + * with m == 0 (adding a new leaf without moving existing entries). + */ + for (i = 340; i < 441; i++) { + KUNIT_ASSERT_EQ_MSG(test, + ext_insert_one(inode, i * 4, 2, + 2000 + i * 4, false, 0), + 0, "i=%d", i); + } + k_ctx.alloc_calls = 0; + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 1764, 2, 3764, false, 0), + 0); + KUNIT_EXPECT_EQ(test, k_ctx.alloc_calls, 1U); + KUNIT_EXPECT_EQ(test, ext_depth(inode), 1); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 3); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT_FIRST_INDEX(eh)[2].ei_block), + 1764U); + + path = ext4_find_extent(inode, 1764, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + KUNIT_EXPECT_EQ(test, le16_to_cpu(path[1].p_hdr->eh_entries), 1); + KUNIT_EXPECT_EQ(test, le32_to_cpu(path[1].p_ext->ee_block), 1764U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(path[1].p_ext), 3764ULL); + ext4_free_ext_path(path); +} + +/* + * Verify multi-level tree growth from depth 1 -> 2 followed by leaf split + * (ext4_ext_create_new_leaf repeat loop), and intermediate index block + * splitting in ext4_ext_split() when both leaf and depth-1 index are full. + */ +static void test_insert_extent_index_split(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_extent_header *eh = ext_inode_hdr(inode); + struct ext4_extent_idx *idx; + struct ext4_ext_path *path; + struct buffer_head *bh; + int i; + + ext_reset_tree(inode); + + /* + * Build a full depth-1 root index (eh_entries = eh_max = 4) pointing + * to 4 full leaf blocks (eh_entries = eh_max = 2). + */ + eh->eh_depth = cpu_to_le16(1); + eh->eh_entries = cpu_to_le16(4); + eh->eh_max = cpu_to_le16(ext4_ext_space_root_idx_test(inode, 0)); + idx = EXT_FIRST_INDEX(eh); + + for (i = 0; i < 4; i++) { + struct ext4_extent_header *leaf_eh; + struct ext4_extent *ex; + ext4_lblk_t lblk = 10 + i * 10; + + idx[i].ei_block = cpu_to_le32(lblk); + ext4_idx_store_pblock(&idx[i], EXT_META_BASE_PBLK + i); + + bh = ext4_ext_getblk_stub(inode, EXT_META_BASE_PBLK + i, + GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, bh); + leaf_eh = ext_block_hdr(bh); + leaf_eh->eh_magic = EXT4_EXT_MAGIC; + leaf_eh->eh_depth = 0; + leaf_eh->eh_entries = cpu_to_le16(2); + leaf_eh->eh_max = cpu_to_le16(2); + ex = EXT_FIRST_EXTENT(leaf_eh); + ex[0].ee_block = cpu_to_le32(lblk); + ex[0].ee_len = cpu_to_le16(2); + ext4_ext_store_pblock(&ex[0], 2000 + i * 10); + ex[1].ee_block = cpu_to_le32(lblk + 4); + ex[1].ee_len = cpu_to_le16(2); + ext4_ext_store_pblock(&ex[1], 2004 + i * 10); + brelse(bh); + } + + /* + * Inserting [48, 50) @ 2038 finds both leaf 3 and the root index full: + * ext4_ext_grow_indepth() grows depth 1 -> 2, and the repeat loop in + * ext4_ext_create_new_leaf() calls ext4_ext_split() at depth 1. + */ + k_ctx.alloc_calls = 0; + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 48, 2, 2038, false, 0), 0); + KUNIT_EXPECT_EQ(test, k_ctx.alloc_calls, 2U); + KUNIT_EXPECT_EQ(test, ext_depth(inode), 2); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 1); + + /* + * Clamp the depth-1 index block's eh_max to its current 5 entries so + * inserting [12, 13) @ 9000 into full leaf 0 splits both leaf 0 and + * the intermediate depth-1 index block (depth = 2, at = 0, k = 1). + */ + bh = ext4_ext_getblk_stub(inode, ext4_idx_pblock(EXT_FIRST_INDEX(eh)), + GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, bh); + KUNIT_ASSERT_EQ(test, le16_to_cpu(ext_block_hdr(bh)->eh_entries), 5); + ext_block_hdr(bh)->eh_max = cpu_to_le16(5); + brelse(bh); + + k_ctx.alloc_calls = 0; + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 12, 1, 9000, false, 0), 0); + KUNIT_EXPECT_EQ(test, k_ctx.alloc_calls, 2U); + KUNIT_EXPECT_EQ(test, ext_depth(inode), 2); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 2); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT_FIRST_INDEX(eh)[0].ei_block), + 10U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT_FIRST_INDEX(eh)[1].ei_block), + 14U); + KUNIT_EXPECT_EQ(test, ext4_ext_check_inode(inode), 0); + + path = ext4_find_extent(inode, 12, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + KUNIT_EXPECT_EQ(test, path->p_depth, 2); + KUNIT_EXPECT_EQ(test, le32_to_cpu(path[2].p_ext->ee_block), 12U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(path[2].p_ext), 9000ULL); + ext4_free_ext_path(path); + + path = ext4_find_extent(inode, 14, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + KUNIT_EXPECT_EQ(test, path->p_depth, 2); + KUNIT_EXPECT_EQ(test, le32_to_cpu(path[2].p_ext->ee_block), 14U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(path[2].p_ext), 2004ULL); + ext4_free_ext_path(path); + + path = ext4_find_extent(inode, 48, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + KUNIT_EXPECT_EQ(test, path->p_depth, 2); + KUNIT_EXPECT_EQ(test, le32_to_cpu(path[2].p_ext->ee_block), 48U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(path[2].p_ext), 2038ULL); + ext4_free_ext_path(path); +} + +/* + * Verify ext4_ext_remove_space() for middle-of-extent hole punching, full + * extent removal with left-scooting, and ext4_ext_truncate() tail removal. + */ +static void test_remove_space_tail_and_hole_punch(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_extent_header *eh = ext_inode_hdr(inode); + struct ext4_extent *ex; + int err; + + ext_reset_tree(inode); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 10, 10, 100, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 30, 10, 200, false, 0), 0); + + /* + * Punch hole [12, 17] inside [10, 20): splits [10, 20) into [10, 12) + * and [18, 20), leaving 3 extents total. + */ + down_write(&EXT4_I(inode)->i_data_sem); + err = ext4_ext_remove_space(inode, 12, 17); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 3); + + ex = EXT_FIRST_EXTENT(eh); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[0].ee_block), 10U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[0]), 2); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[1].ee_block), 18U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[1]), 2); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex[1]), 108ULL); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[2].ee_block), 30U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[2]), 10); + + /* + * Punch out the entire middle extent [18, 19]: scoots [30, 40) into + * slot 1 and reduces eh_entries to 2. + */ + down_write(&EXT4_I(inode)->i_data_sem); + err = ext4_ext_remove_space(inode, 18, 19); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 2); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[1].ee_block), 30U); + + /* + * Truncate file to 11 blocks (i_size = 11 * 4096): removes [30, 40) + * and trims [10, 12) down to [10, 11). + */ + inode->i_size = 11ULL << inode->i_sb->s_blocksize_bits; + down_write(&EXT4_I(inode)->i_data_sem); + err = ext4_ext_truncate(NULL, inode); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 1); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[0].ee_block), 10U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[0]), 1); +} + +/* + * Verify ext4_ext_remove_space() on a depth-1 tree removes all leaf extents, + * removes empty index entries via ext4_ext_rm_idx(), frees the leaf metadata + * blocks, and resets the root header to eh_depth == 0. + */ +static void test_remove_space_multilevel_collapse(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_extent_header *eh = ext_inode_hdr(inode); + int err; + + setup_depth1_two_leaf_tree(test, inode); + k_ctx.free_calls = 0; + k_ctx.total_freed_blocks = 0; + + down_write(&EXT4_I(inode)->i_data_sem); + err = ext4_ext_remove_space(inode, 0, EXT_MAX_BLOCKS - 1); + up_write(&EXT4_I(inode)->i_data_sem); + + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ext_depth(inode), 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_max), 4); + /* 4 data extents (5 blocks each = 20) + 2 leaf metadata blocks = 22 */ + KUNIT_EXPECT_EQ(test, k_ctx.total_freed_blocks, 22UL); +} + +/* + * Verify bigalloc partial cluster handling in ext4_ext_remove_space(): + * 1. When a cluster is shared with a remaining extent (state == nofree), + * the physical cluster is not freed. + * 2. When the entire unaligned extent is removed and has a pending reservation + * in i_pending_tree, the cluster is freed with RERESERVE_CLUSTER and + * ext4_rereserve_cluster() re-increments i_reserved_data_blocks and removes + * the pending reservation. + */ +static void test_remove_space_bigalloc_partial_cluster(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); + struct ext4_inode_info *ei = EXT4_I(inode); + int err; + + sbi->s_cluster_bits = 2; + sbi->s_cluster_ratio = 4; + + /* + * Case 1: [0, 2) @ 100 and [2, 4) @ 102 share physical cluster 25 + * (blocks 100..103). Punching [0, 1] must NOT free cluster 25. + */ + ext_reset_tree(inode); + KUNIT_ASSERT_EQ(test, + ext_insert_one(inode, 0, 2, 100, false, + EXT4_GET_BLOCKS_SPLIT_NOMERGE), + 0); + KUNIT_ASSERT_EQ(test, + ext_insert_one(inode, 2, 2, 102, false, + EXT4_GET_BLOCKS_SPLIT_NOMERGE), + 0); + + k_ctx.free_calls = 0; + k_ctx.total_freed_blocks = 0; + down_write(&ei->i_data_sem); + err = ext4_ext_remove_space(inode, 0, 1); + up_write(&ei->i_data_sem); + KUNIT_ASSERT_EQ(test, err, 0); + /* + * ext4_remove_blocks() is called with NOFREE_FIRST_CLUSTER | + * NOFREE_LAST_CLUSTER, and partial cluster 25 is marked nofree. + */ + KUNIT_EXPECT_EQ(test, k_ctx.free_calls, 1U); + KUNIT_EXPECT_TRUE(test, + (k_ctx.last_free_flags & + EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER) != 0); + + /* + * Case 2: Single unaligned extent [1, 3) @ 101 in cluster 0 (pclu 25) + * with a pending reservation on cluster 0. Truncating from 1 frees + * cluster 25 with RERESERVE_CLUSTER and calls ext4_rereserve_cluster(). + */ + ext_reset_tree(inode); + set_opt(inode->i_sb, DELALLOC); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 1, 2, 101, true, 0), 0); + + down_write(&ei->i_data_sem); + /* Insert delayed extent at lblk 0 in already-allocated cluster 0 */ + ext4_es_insert_delayed_extent(inode, 0, 1, true, false); + up_write(&ei->i_data_sem); + KUNIT_ASSERT_TRUE(test, ext4_is_pending(inode, 0)); + + ei->i_reserved_data_blocks = 0; + k_ctx.free_calls = 0; + down_write(&ei->i_data_sem); + err = ext4_ext_remove_space(inode, 1, EXT_MAX_BLOCKS - 1); + up_write(&ei->i_data_sem); + + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, k_ctx.last_free_pblk, 100ULL); + KUNIT_EXPECT_EQ(test, k_ctx.last_free_count, 4UL); + KUNIT_EXPECT_TRUE(test, + (k_ctx.last_free_flags & + EXT4_FREE_BLOCKS_RERESERVE_CLUSTER) != 0); + KUNIT_EXPECT_EQ(test, ei->i_reserved_data_blocks, 1U); + KUNIT_EXPECT_FALSE(test, ext4_is_pending(inode, 0)); +} + +/* + * Verify ext4_ext_map_blocks() hole lookup, delayed-extent hole truncation + * (ext4_ext_determine_insert_hole), and EXT4_GET_BLOCKS_QUERY_LAST_IN_LEAF. + */ +static void test_map_blocks_lookup_hole_and_query_last_in_leaf(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_map_blocks map = {}; + int ret; + + ext_reset_tree(inode); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 10, 5, 100, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 20, 5, 200, false, 0), 0); + + /* Hole lookup at [2, 22) returns 0 and trims m_len to [2, 10) (len 8) */ + map.m_lblk = 2; + map.m_len = 20; + map.m_flags = 0; + down_read(&EXT4_I(inode)->i_data_sem); + ret = ext4_ext_map_blocks(NULL, inode, &map, 0); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, map.m_pblk, 0ULL); + KUNIT_EXPECT_EQ(test, map.m_len, 8U); + + /* + * Insert a delayed extent at [5, 7) in the es tree: hole lookup at + * [2, 22) must stop at the delayed extent -> [2, 5) (len 3). + */ + down_write(&EXT4_I(inode)->i_data_sem); + ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS); + ext4_es_insert_delayed_extent(inode, 5, 2, false, false); + up_write(&EXT4_I(inode)->i_data_sem); + + map.m_lblk = 2; + map.m_len = 20; + map.m_flags = 0; + down_read(&EXT4_I(inode)->i_data_sem); + ret = ext4_ext_map_blocks(NULL, inode, &map, EXT4_EX_NOCACHE); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, map.m_len, 3U); + + /* QUERY_LAST_IN_LEAF on first extent [10, 15) -> flag NOT set */ + map.m_lblk = 10; + map.m_len = 5; + map.m_flags = 0; + down_read(&EXT4_I(inode)->i_data_sem); + ret = ext4_ext_map_blocks(NULL, inode, &map, + EXT4_GET_BLOCKS_QUERY_LAST_IN_LEAF); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 5); + KUNIT_EXPECT_FALSE(test, + (map.m_flags & EXT4_MAP_QUERY_LAST_IN_LEAF) != 0); + + /* QUERY_LAST_IN_LEAF on last extent [20, 25) -> flag IS set */ + map.m_lblk = 20; + map.m_len = 5; + map.m_flags = 0; + down_read(&EXT4_I(inode)->i_data_sem); + ret = ext4_ext_map_blocks(NULL, inode, &map, + EXT4_GET_BLOCKS_QUERY_LAST_IN_LEAF); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 5); + KUNIT_EXPECT_TRUE(test, + (map.m_flags & EXT4_MAP_QUERY_LAST_IN_LEAF) != 0); +} + +/* + * Verify ext4_ext_map_blocks() block allocation with overlap clamping + * (ext4_ext_check_overlap) and freeing of newly allocated blocks when + * ext4_ext_insert_extent() fails with -ENOSPC. + */ +static void test_map_blocks_alloc_overlap_and_enospc(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_map_blocks map = {}; + int ret; + + ext_reset_tree(inode); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 15, 5, 200, false, 0), 0); + + /* + * Request allocation for [10, 20) (len 10): ext4_ext_check_overlap() + * clamps the allocation to [10, 15) (len 5) to avoid overlapping [15, 20). + */ + k_ctx.alloc_calls = 0; + map.m_lblk = 10; + map.m_len = 10; + map.m_flags = 0; + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ext_map_blocks(NULL, inode, &map, EXT4_GET_BLOCKS_CREATE); + up_write(&EXT4_I(inode)->i_data_sem); + + KUNIT_EXPECT_EQ(test, ret, 5); + KUNIT_EXPECT_EQ(test, map.m_len, 5U); + KUNIT_EXPECT_EQ(test, map.m_pblk, EXT_ALLOC_BASE_PBLK); + KUNIT_EXPECT_TRUE(test, + (map.m_flags & (EXT4_MAP_NEW | EXT4_MAP_MAPPED)) == + (EXT4_MAP_NEW | EXT4_MAP_MAPPED)); + KUNIT_EXPECT_EQ(test, k_ctx.alloc_calls, 1U); + KUNIT_EXPECT_EQ(test, k_ctx.last_alloc_len, 5U); + + /* + * Force ext4_ext_insert_extent() to return -ENOSPC and verify that + * ext4_ext_map_blocks() frees the newly allocated blocks. + */ + kunit_activate_static_stub(test, ext4_ext_insert_extent, + ext4_ext_insert_extent_stub); + k_ctx.free_calls = 0; + map.m_lblk = 30; + map.m_len = 4; + map.m_flags = 0; + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ext_map_blocks(NULL, inode, &map, + EXT4_GET_BLOCKS_CREATE | + EXT4_GET_BLOCKS_DELALLOC_RESERVE); + up_write(&EXT4_I(inode)->i_data_sem); + + KUNIT_EXPECT_EQ(test, ret, -ENOSPC); + KUNIT_EXPECT_EQ(test, k_ctx.free_calls, 1U); + KUNIT_EXPECT_EQ(test, k_ctx.last_free_pblk, k_ctx.last_alloc_pblk); + KUNIT_EXPECT_EQ(test, k_ctx.last_free_count, 4UL); + KUNIT_EXPECT_EQ(test, k_ctx.last_free_flags, + EXT4_FREE_BLOCKS_NO_QUOT_UPDATE); +} + +/* + * Verify ext4_ext_convert_to_initialized() fastpath block transfers to + * abutting left (ex - 1) and right (ex + 1) initialized neighbors without + * splitting into new extent entries. + */ +static void test_convert_to_initialized_abut_neighbors(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_extent_header *eh = ext_inode_hdr(inode); + struct ext4_extent *ex; + struct ext4_map_blocks map = {}; + int ret; + + EXT4_SB(inode->i_sb)->s_extent_max_zeroout_kb = 0; + ext_reset_tree(inode); + + /* + * Setup: [10, 12) @ 100 (written), [12, 16) @ 102 (unwritten), + * [16, 18) @ 106 (written). + */ + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 10, 2, 100, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 12, 4, 102, true, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 16, 2, 106, false, 0), 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 3); + + /* + * Convert head of unwritten extent [12, 14): transfers 2 blocks to + * left neighbor [10, 12) -> [10, 14) written, [14, 16) unwritten. + */ + map.m_lblk = 12; + map.m_len = 2; + map.m_flags = 0; + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ext_map_blocks(NULL, inode, &map, EXT4_GET_BLOCKS_CREATE); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 2); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 3); + + ex = EXT_FIRST_EXTENT(eh); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[0].ee_block), 10U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[0]), 4); + KUNIT_EXPECT_EQ(test, ext4_ext_is_unwritten(&ex[0]), 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[1].ee_block), 14U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[1]), 2); + KUNIT_EXPECT_EQ(test, ext4_ext_is_unwritten(&ex[1]), 1); + + /* + * Convert tail of unwritten extent [15, 16): transfers 1 block to + * right neighbor [16, 18) -> [14, 15) unwritten, [15, 18) written. + * Drop stale unwritten extent status entries cached during the first + * ext4_ext_map_blocks() call (normally updated by ext4_map_blocks()). + */ + map.m_lblk = 15; + map.m_len = 1; + map.m_flags = 0; + down_write(&EXT4_I(inode)->i_data_sem); + ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS); + ret = ext4_ext_map_blocks(NULL, inode, &map, EXT4_GET_BLOCKS_CREATE); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 3); + + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[1].ee_block), 14U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[1]), 1); + KUNIT_EXPECT_EQ(test, ext4_ext_is_unwritten(&ex[1]), 1); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[2].ee_block), 15U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[2]), 3); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex[2]), 105ULL); + KUNIT_EXPECT_EQ(test, ext4_ext_is_unwritten(&ex[2]), 0); +} + +/* + * Verify bigalloc get_implied_cluster_alloc() in ext4_ext_map_blocks() when + * an existing extent to the left or right already maps the same logical + * cluster, avoiding a duplicate physical cluster allocation. + */ +static void test_map_blocks_bigalloc_implied_cluster(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); + struct ext4_map_blocks map = {}; + int ret; + + sbi->s_cluster_bits = 2; + sbi->s_cluster_ratio = 4; + + /* + * Case 1: Left extent [8, 9) @ 100 in logical cluster 2 (lblks 8..11). + * Allocating [10, 12) reuses physical cluster 25 (pblks 102..103) + * without calling ext4_mb_new_blocks(). + */ + ext_reset_tree(inode); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 8, 1, 100, false, 0), 0); + + k_ctx.alloc_calls = 0; + map.m_lblk = 10; + map.m_len = 2; + map.m_flags = 0; + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ext_map_blocks(NULL, inode, &map, EXT4_GET_BLOCKS_CREATE); + up_write(&EXT4_I(inode)->i_data_sem); + + KUNIT_EXPECT_EQ(test, ret, 2); + KUNIT_EXPECT_EQ(test, map.m_pblk, 102ULL); + KUNIT_EXPECT_EQ(test, k_ctx.alloc_calls, 0U); + + /* + * Case 2: Right extent [10, 12) @ 102 in logical cluster 2 (lblks 8..11). + * Allocating [8, 10) searches right, finds [10, 12), and reuses + * physical cluster 25 (pblks 100..101) without calling ext4_mb_new_blocks(). + */ + ext_reset_tree(inode); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 10, 2, 102, false, 0), 0); + + k_ctx.alloc_calls = 0; + map.m_lblk = 8; + map.m_len = 2; + map.m_flags = 0; + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ext_map_blocks(NULL, inode, &map, EXT4_GET_BLOCKS_CREATE); + up_write(&EXT4_I(inode)->i_data_sem); + + KUNIT_EXPECT_EQ(test, ret, 2); + KUNIT_EXPECT_EQ(test, map.m_pblk, 100ULL); + KUNIT_EXPECT_EQ(test, k_ctx.alloc_calls, 0U); +} + +/* + * Verify ext4_ext_shift_extents() for SHIFT_LEFT (collapse range) with + * neighbor merging, SHIFT_RIGHT (insert range), and -EINVAL boundary checks. + */ +static void test_ext_shift_extents(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_extent_header *eh = ext_inode_hdr(inode); + struct ext4_extent *ex; + int err; + + ext_reset_tree(inode); + /* [10, 15) @ 100 and [20, 25) @ 105 (physically contiguous!) */ + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 10, 5, 100, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 20, 5, 105, false, 0), 0); + + /* Shifting [20, 25) left by 6 overlaps [10, 15) -> -EINVAL */ + down_write(&EXT4_I(inode)->i_data_sem); + err = ext4_ext_shift_extents_test(inode, NULL, 20, 6, SHIFT_LEFT); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, err, -EINVAL); + + /* Shifting [20, 25) left by 5 merges with [10, 15) into [10, 20) @ 100 */ + down_write(&EXT4_I(inode)->i_data_sem); + err = ext4_ext_shift_extents_test(inode, NULL, 20, 5, SHIFT_LEFT); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 1); + ex = EXT_FIRST_EXTENT(eh); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[0].ee_block), 10U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[0]), 10); + + /* Shifting [10, 20) right by 4 moves it to [14, 24) @ 100 */ + down_write(&EXT4_I(inode)->i_data_sem); + err = ext4_ext_shift_extents_test(inode, NULL, 10, 4, SHIFT_RIGHT); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[0].ee_block), 14U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[0]), 10); + + /* Shifting right past EXT_MAX_BLOCKS -> -EINVAL */ + down_write(&EXT4_I(inode)->i_data_sem); + err = ext4_ext_shift_extents_test(inode, NULL, 14, EXT_MAX_BLOCKS, + SHIFT_RIGHT); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, err, -EINVAL); +} + +/* + * Verify ext4_swap_extents() splits unaligned boundaries on both inodes, + * swaps physical block mappings for the requested subrange, and marks + * the donor inode's swapped extent unwritten when requested. + */ +static void test_swap_extents(struct kunit *test) +{ + struct inode *inode1 = &k_ctx.k_ei->vfs_inode; + struct inode *inode2; + struct ext4_extent_header *eh1, *eh2; + struct ext4_extent *ex1, *ex2; + int replaced, err = 0; + + k_ctx.k_ei2 = kzalloc_obj(struct ext4_inode_info); + KUNIT_ASSERT_NOT_NULL(test, k_ctx.k_ei2); + ext_init_mock_inode(k_ctx.k_ei2, inode1->i_sb, 13); + inode2 = &k_ctx.k_ei2->vfs_inode; + + ext_reset_tree(inode1); + ext_reset_tree(inode2); + + /* inode1: [10, 20) @ 100; inode2: [10, 20) @ 200 */ + KUNIT_ASSERT_EQ(test, ext_insert_one(inode1, 10, 10, 100, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode2, 10, 10, 200, false, 0), 0); + + lock_two_nondirectories(inode1, inode2); + ext4_double_down_write_data_sem(inode1, inode2); + + replaced = ext4_swap_extents(NULL, inode1, inode2, 12, 12, 5, 1, &err); + + ext4_double_up_write_data_sem(inode1, inode2); + unlock_two_nondirectories(inode1, inode2); + + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, replaced, 5); + + eh1 = ext_inode_hdr(inode1); + eh2 = ext_inode_hdr(inode2); + KUNIT_ASSERT_EQ(test, le16_to_cpu(eh1->eh_entries), 3); + KUNIT_ASSERT_EQ(test, le16_to_cpu(eh2->eh_entries), 3); + + ex1 = EXT_FIRST_EXTENT(eh1); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex1[0].ee_block), 10U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex1[0]), 100ULL); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex1[1].ee_block), 12U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex1[1]), 5); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex1[1]), 202ULL); + KUNIT_EXPECT_EQ(test, ext4_ext_is_unwritten(&ex1[1]), 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex1[2].ee_block), 17U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex1[2]), 107ULL); + + ex2 = EXT_FIRST_EXTENT(eh2); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex2[0].ee_block), 10U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex2[0]), 200ULL); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex2[1].ee_block), 12U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex2[1]), 5); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex2[1]), 102ULL); + KUNIT_EXPECT_EQ(test, ext4_ext_is_unwritten(&ex2[1]), 1); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex2[2].ee_block), 17U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex2[2]), 207ULL); +} + +/* + * Verify ext4_clu_mapped() across inline-data inodes, empty trees, clusters + * mapped at the start or end of a cluster, and unmapped clusters. + */ +static void test_clu_mapped(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); + + sbi->s_cluster_bits = 2; + sbi->s_cluster_ratio = 4; + + ext_reset_tree(inode); + /* Empty tree -> unmapped */ + KUNIT_EXPECT_EQ(test, ext4_clu_mapped(inode, 0), 0); + + /* + * Insert [0, 2) @ 100 (in lclu 0 = lblks 0..3) and + * [6, 8) @ 106 (in lclu 1 = lblks 4..7). + */ + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 0, 2, 100, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 6, 2, 106, false, 0), 0); + + /* Inline-data state returns 0 immediately */ + ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + KUNIT_EXPECT_EQ(test, ext4_clu_mapped(inode, 0), 0); + ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + + /* lclu 0 (lblk 0) is mapped directly by [0, 2) */ + KUNIT_EXPECT_EQ(test, ext4_clu_mapped(inode, 0), 1); + /* lclu 1 (lblk 4) is mapped by next allocated extent [6, 8) */ + KUNIT_EXPECT_EQ(test, ext4_clu_mapped(inode, 1), 1); + /* lclu 2 (lblk 8..11) is unmapped */ + KUNIT_EXPECT_EQ(test, ext4_clu_mapped(inode, 2), 0); +} + +/* + * Verify ext4_ext_index_trans_blocks() and + * ext4_ext_calc_credits_for_single_extent() credit calculations. + */ +static void test_ext_credits_calculation(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_extent_header *eh = ext_inode_hdr(inode); + struct ext4_ext_path *path; + int credits_with_space, credits_full; + + /* 1 extent vs multiple extents */ + KUNIT_EXPECT_EQ(test, ext4_ext_index_trans_blocks(inode, 1), + EXT4_MAX_EXTENT_DEPTH * 2 + 1); + KUNIT_EXPECT_EQ(test, ext4_ext_index_trans_blocks(inode, 2), + EXT4_MAX_EXTENT_DEPTH * 3 + 2); + + /* Inline data inode needs only 1 index block credit */ + ext4_set_inode_flag(inode, EXT4_INODE_INLINE_DATA); + EXT4_I(inode)->i_inline_off = 1; + KUNIT_EXPECT_EQ(test, ext4_ext_index_trans_blocks(inode, 2), 1); + EXT4_I(inode)->i_inline_off = 0; + ext4_clear_inode_flag(inode, EXT4_INODE_INLINE_DATA); + + ext_reset_tree(inode); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 10, 2, 100, false, 0), 0); + + path = ext4_find_extent(inode, 10, NULL, EXT4_EX_NOCACHE); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(path)); + /* Leaf has free space (eh_entries = 1 < eh_max = 4) */ + credits_with_space = + ext4_ext_calc_credits_for_single_extent(inode, 1, path); + + /* Mark leaf full (eh_entries == eh_max) */ + eh->eh_entries = eh->eh_max; + credits_full = ext4_ext_calc_credits_for_single_extent(inode, 1, path); + eh->eh_entries = cpu_to_le16(1); + ext4_free_ext_path(path); + + KUNIT_EXPECT_LT(test, credits_with_space, credits_full); + KUNIT_EXPECT_EQ(test, credits_full, + ext4_ext_calc_credits_for_single_extent(inode, 1, NULL)); +} + +/* + * Verify fast-commit replay extent helpers: + * - ext4_ext_replay_update_ex() splits and updates extent state/pblk + * - ext4_ext_replay_shrink_inode() merges adjacent compatible extents + * - ext4_ext_replay_set_iblocks() counts data and extent tree blocks and + * updates inode->i_blocks. + */ +static void test_ext_fast_commit_replay(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); + struct ext4_extent_header *eh = ext_inode_hdr(inode); + struct ext4_extent *ex; + unsigned short saved_mount_state; + int err; + + ext_reset_tree(inode); + saved_mount_state = sbi->s_mount_state; + sbi->s_mount_state |= EXT4_FC_REPLAY; + + /* Start with unwritten extent [10, 20) @ 100 */ + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 10, 10, 100, true, 0), 0); + + /* Replay update converting middle [12, 16) to written @ 102 */ + err = ext4_ext_replay_update_ex(inode, 12, 4, 0, 102); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 3); + + /* Replay update converting [10, 12) @ 100 and [16, 20) @ 106 to written */ + KUNIT_ASSERT_EQ(test, ext4_ext_replay_update_ex(inode, 10, 2, 0, 100), + 0); + KUNIT_ASSERT_EQ(test, ext4_ext_replay_update_ex(inode, 16, 4, 0, 106), + 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 3); + + /* Shrink inode merges the 3 contiguous written extents into [10, 20) */ + ext4_ext_replay_shrink_inode(inode, 25); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 1); + ex = EXT_FIRST_EXTENT(eh); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[0].ee_block), 10U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[0]), 10); + KUNIT_EXPECT_EQ(test, ext4_ext_is_unwritten(&ex[0]), 0); + + /* Recalculate i_blocks for the 10-block extent (10 * 8 = 80 sectors) */ + inode->i_size = 30ULL << inode->i_sb->s_blocksize_bits; + inode->i_blocks = 0; + err = ext4_ext_replay_set_iblocks(inode); + sbi->s_mount_state = saved_mount_state; + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, inode->i_blocks, + 10ULL << (inode->i_sb->s_blocksize_bits - 9)); +} + +static int ext_range_ext_zeroout_stub(handle_t *handle, struct inode *inode, + struct ext4_extent *ex) +{ + k_ctx.zeroout_calls++; + k_ctx.last_zeroout_lblk = le32_to_cpu(ex->ee_block); + k_ctx.last_zeroout_len = ext4_ext_get_actual_len(ex); + return 0; +} + +static int ext_range_issue_zeroout_stub(handle_t *handle, struct inode *inode, + ext4_lblk_t lblk, ext4_fsblk_t pblk, + ext4_lblk_t len) +{ + k_ctx.zeroout_calls++; + k_ctx.last_zeroout_lblk = lblk; + k_ctx.last_zeroout_len = len; + return 0; +} + +static int ext_orphan_add_stub(handle_t *handle, struct inode *inode) +{ + k_ctx.orphan_add_calls++; + return 0; +} + +static int ext_orphan_del_stub(handle_t *handle, struct inode *inode) +{ + k_ctx.orphan_del_calls++; + return 0; +} + +static void ext_setup_range_test(struct kunit *test, struct inode *inode, + struct file *file) +{ + kunit_activate_static_stub(test, ext4_ext_zeroout, + ext_range_ext_zeroout_stub); + kunit_activate_static_stub(test, ext4_issue_zeroout, + ext_range_issue_zeroout_stub); + kunit_activate_static_stub(test, ext4_orphan_add, ext_orphan_add_stub); + kunit_activate_static_stub(test, ext4_orphan_del, ext_orphan_del_stub); + + ext_reset_tree(inode); + inode->i_size = 0; + EXT4_I(inode)->i_disksize = 0; + inode->i_blocks = 0; + + k_ctx.next_alloc_pblk = EXT_ALLOC_BASE_PBLK; + k_ctx.alloc_calls = 0; + k_ctx.free_calls = 0; + k_ctx.total_freed_blocks = 0; + k_ctx.zeroout_calls = 0; + k_ctx.orphan_add_calls = 0; + k_ctx.orphan_del_calls = 0; + + if (file) { + struct file tmp = { + .f_path = { .dentry = &k_ctx.k_dentry }, + .f_inode = inode, + .f_mapping = inode->i_mapping, + .f_mode = FMODE_READ | FMODE_WRITE | + FMODE_NOCMTIME, + }; + + memset(&k_ctx.k_dentry, 0, sizeof(k_ctx.k_dentry)); + k_ctx.k_dentry.d_inode = inode; + memcpy(file, &tmp, sizeof(tmp)); + } +} + +static void ext_expect_extent_at(struct kunit *test, struct inode *inode, + ext4_lblk_t lblk, unsigned short exp_len, + ext4_fsblk_t exp_pblk, bool exp_unwritten) +{ + struct ext4_ext_path *path; + struct ext4_extent ex; + bool found = false; + int err = 0; + + down_read(&EXT4_I(inode)->i_data_sem); + path = ext4_find_extent(inode, lblk, NULL, EXT4_EX_NOCACHE); + if (IS_ERR(path)) { + err = PTR_ERR(path); + } else { + if (path[path->p_depth].p_ext) { + ex = *path[path->p_depth].p_ext; + found = true; + } + ext4_free_ext_path(path); + } + up_read(&EXT4_I(inode)->i_data_sem); + + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_ASSERT_TRUE(test, found); + + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex.ee_block), lblk); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex), exp_len); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex), exp_pblk); + KUNIT_EXPECT_EQ(test, !!ext4_ext_is_unwritten(&ex), exp_unwritten); +} + +/* + * Verify ext4_fallocate() mode validation (unsupported flags, encrypted + * collapse/insert rejection, WRITE_ZEROES without bdev support, non-extent + * preallocation rejection), preallocation with and without FALLOC_FL_KEEP_SIZE, + * and hole punching via FALLOC_FL_PUNCH_HOLE. + */ +static void test_fallocate_modes_and_prealloc(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct file file; + long ret; + + ext_setup_range_test(test, inode, &file); + + /* Unsupported mode flag -> -EOPNOTSUPP */ + ret = ext4_fallocate(&file, 0x40000000, 0, 4096); + KUNIT_EXPECT_EQ(test, ret, -EOPNOTSUPP); + + /* FALLOC_FL_WRITE_ZEROES without unmap sectors -> -EOPNOTSUPP */ + ret = ext4_fallocate(&file, FALLOC_FL_WRITE_ZEROES, 0, 4096); + KUNIT_EXPECT_EQ(test, ret, -EOPNOTSUPP); + + /* Encrypted inode rejects COLLAPSE_RANGE and INSERT_RANGE */ + inode->i_flags |= S_ENCRYPTED; + ret = ext4_fallocate(&file, FALLOC_FL_COLLAPSE_RANGE, 0, 4096); + KUNIT_EXPECT_EQ(test, ret, -EOPNOTSUPP); + ret = ext4_fallocate(&file, FALLOC_FL_INSERT_RANGE, 0, 4096); + KUNIT_EXPECT_EQ(test, ret, -EOPNOTSUPP); + inode->i_flags &= ~S_ENCRYPTED; + + /* Non-extent (indirect) inode rejects fallocate preallocation */ + ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS); + ret = ext4_fallocate(&file, 0, 0, 4096); + KUNIT_EXPECT_EQ(test, ret, -EOPNOTSUPP); + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + + /* Preallocate [0, 4 blocks) with FALLOC_FL_KEEP_SIZE: i_size stays 0 */ + ret = ext4_fallocate(&file, FALLOC_FL_KEEP_SIZE, 0, 4 * 4096); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, inode->i_size, 0LL); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_disksize, 0LL); + ext_expect_extent_at(test, inode, 0, 4, EXT_ALLOC_BASE_PBLK, true); + + /* Extend allocation across [2, 6 blocks) without KEEP_SIZE */ + ret = ext4_fallocate(&file, 0, 2 * 4096, 4 * 4096); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, inode->i_size, 6LL * 4096); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_disksize, 6LL * 4096); + ext_expect_extent_at(test, inode, 0, 6, EXT_ALLOC_BASE_PBLK, true); + + /* Punch middle [2, 4) with FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE */ + ret = ext4_fallocate(&file, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, + 2 * 4096, 2 * 4096); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, inode->i_size, 6LL * 4096); + KUNIT_EXPECT_EQ(test, k_ctx.total_freed_blocks, 2UL); + KUNIT_EXPECT_EQ(test, le16_to_cpu(ext_inode_hdr(inode)->eh_entries), 2); + ext_expect_extent_at(test, inode, 0, 2, EXT_ALLOC_BASE_PBLK, true); + ext_expect_extent_at(test, inode, 4, 2, EXT_ALLOC_BASE_PBLK + 4, true); +} + +/* + * Verify ext4_zero_range() via both FALLOC_FL_ZERO_RANGE (splitting written + * extents to unwritten and allocating unwritten blocks past EOF) and + * FALLOC_FL_WRITE_ZEROES (issuing block zeroouts, converting to written, and + * tracking orphan state when extending i_disksize). + */ +static void test_zero_range_and_write_zeroes(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct super_block *sb = inode->i_sb; + struct file file; + long ret; + + /* Part A: FALLOC_FL_ZERO_RANGE across written tail + past EOF */ + ext_setup_range_test(test, inode, &file); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 0, 6, 200, false, 0), 0); + inode->i_size = 6LL * 4096; + EXT4_I(inode)->i_disksize = 6LL * 4096; + + ret = ext4_fallocate(&file, FALLOC_FL_ZERO_RANGE, 2 * 4096, 6 * 4096); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, inode->i_size, 8LL * 4096); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_disksize, 8LL * 4096); + KUNIT_EXPECT_EQ(test, le16_to_cpu(ext_inode_hdr(inode)->eh_entries), 3); + ext_expect_extent_at(test, inode, 0, 2, 200, false); + ext_expect_extent_at(test, inode, 2, 4, 202, true); + ext_expect_extent_at(test, inode, 6, 2, EXT_ALLOC_BASE_PBLK, true); + + /* Part B: FALLOC_FL_WRITE_ZEROES over unwritten + hole past EOF */ + ext_setup_range_test(test, inode, &file); + sb->s_bdev->bd_queue->limits.max_wzeroes_unmap_sectors = 1024; + + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 0, 2, 300, true, 0), 0); + inode->i_size = 2LL * 4096; + EXT4_I(inode)->i_disksize = 2LL * 4096; + + ret = ext4_fallocate(&file, FALLOC_FL_WRITE_ZEROES, 0, 4 * 4096); + sb->s_bdev->bd_queue->limits.max_wzeroes_unmap_sectors = 0; + + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_GE(test, k_ctx.zeroout_calls, 2U); + KUNIT_EXPECT_GE(test, k_ctx.orphan_add_calls, 1U); + KUNIT_EXPECT_EQ(test, k_ctx.orphan_del_calls, 1U); + KUNIT_EXPECT_EQ(test, inode->i_size, 4LL * 4096); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_disksize, 4LL * 4096); + ext_expect_extent_at(test, inode, 0, 2, 300, false); + ext_expect_extent_at(test, inode, 2, 2, EXT_ALLOC_BASE_PBLK, false); +} + +/* + * Verify ext4_collapse_range() validation checks, block removal, left-shift of + * subsequent extents, adjacent extent coalescing after collapse, and i_size + * reduction. + */ +static void test_collapse_range(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct file file; + long ret; + + ext_setup_range_test(test, inode, &file); + inode->i_size = 10LL * 4096; + EXT4_I(inode)->i_disksize = 10LL * 4096; + + /* Block-unaligned offset or length -> -EINVAL */ + ret = ext4_fallocate(&file, FALLOC_FL_COLLAPSE_RANGE, 512, 4096); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + ret = ext4_fallocate(&file, FALLOC_FL_COLLAPSE_RANGE, 4096, 512); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + + /* Non-extent inode -> -EOPNOTSUPP */ + ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS); + ret = ext4_fallocate(&file, FALLOC_FL_COLLAPSE_RANGE, 0, 4096); + KUNIT_EXPECT_EQ(test, ret, -EOPNOTSUPP); + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + + /* Collapsing up to or beyond i_size -> -EINVAL */ + ret = ext4_fallocate(&file, FALLOC_FL_COLLAPSE_RANGE, + 8 * 4096, 2 * 4096); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + + /* + * Build [0, 2)@200 writ, [2, 4)@500 writ, [4, 7)@202 writ, and + * [8, 10)@600 unwrit. Collapsing [2, 4) frees [2, 4)@500, shifts + * [4, 7)@202 left to [2, 5)@202 where it merges with [0, 2)@200 into + * [0, 5)@200, and shifts [8, 10)@600 left to [6, 8)@600. + */ + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 0, 2, 200, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 2, 2, 500, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 4, 3, 202, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 8, 2, 600, true, 0), 0); + + ret = ext4_fallocate(&file, FALLOC_FL_COLLAPSE_RANGE, + 2 * 4096, 2 * 4096); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, k_ctx.total_freed_blocks, 2UL); + KUNIT_EXPECT_EQ(test, inode->i_size, 8LL * 4096); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_disksize, 8LL * 4096); + KUNIT_EXPECT_EQ(test, le16_to_cpu(ext_inode_hdr(inode)->eh_entries), 2); + ext_expect_extent_at(test, inode, 0, 5, 200, false); + ext_expect_extent_at(test, inode, 6, 2, 600, true); +} + +/* + * Verify ext4_insert_range() alignment, EOF, and s_maxbytes checks, as well as + * mid-extent splitting, right-shift of trailing extents, and i_size growth. + */ +static void test_insert_range(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct file file; + long ret; + + ext_setup_range_test(test, inode, &file); + inode->i_size = 10LL * 4096; + EXT4_I(inode)->i_disksize = 10LL * 4096; + + /* Block-unaligned offset or length -> -EINVAL */ + ret = ext4_fallocate(&file, FALLOC_FL_INSERT_RANGE, 1024, 4096); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + ret = ext4_fallocate(&file, FALLOC_FL_INSERT_RANGE, 4096, 1024); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + + /* Non-extent inode -> -EOPNOTSUPP */ + ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS); + ret = ext4_fallocate(&file, FALLOC_FL_INSERT_RANGE, 0, 4096); + KUNIT_EXPECT_EQ(test, ret, -EOPNOTSUPP); + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + + /* Offset at or beyond i_size -> -EINVAL */ + ret = ext4_fallocate(&file, FALLOC_FL_INSERT_RANGE, 10 * 4096, 4096); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + + /* Length exceeding s_maxbytes - i_size -> -EFBIG */ + ret = ext4_fallocate(&file, FALLOC_FL_INSERT_RANGE, 4096, + round_down(inode->i_sb->s_maxbytes, 4096)); + KUNIT_EXPECT_EQ(test, ret, -EFBIG); + + /* + * Insert 3-block hole at lblk 2 inside [0, 6)@200 writ with trailing + * [8, 10)@400 unwrit: produces [0, 2)@200 writ, [5, 9)@202 writ, and + * [11, 13)@400 unwrit, with i_size = 13 blocks. + */ + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 0, 6, 200, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 8, 2, 400, true, 0), 0); + + ret = ext4_fallocate(&file, FALLOC_FL_INSERT_RANGE, + 2 * 4096, 3 * 4096); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, inode->i_size, 13LL * 4096); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_disksize, 13LL * 4096); + KUNIT_EXPECT_EQ(test, le16_to_cpu(ext_inode_hdr(inode)->eh_entries), 3); + ext_expect_extent_at(test, inode, 0, 2, 200, false); + ext_expect_extent_at(test, inode, 5, 4, 202, false); + ext_expect_extent_at(test, inode, 11, 2, 400, true); +} + +/* + * Verify unwritten-to-written IO completion conversion helpers: + * ext4_convert_unwritten_extents(), ext4_convert_unwritten_extents_atomic() + * across a split unwritten mapping, and ext4_convert_unwritten_io_end_vec(). + */ +static void test_convert_unwritten_extents_and_io_end(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + ext4_io_end_t io_end = {}; + struct ext4_io_end_vec vec1 = {}, vec2 = {}; + ext4_lblk_t converted = 0; + int err; + + /* 1. ext4_convert_unwritten_extents() on middle of unwritten extent */ + ext_setup_range_test(test, inode, NULL); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 0, 6, 200, true, 0), 0); + + err = ext4_convert_unwritten_extents(NULL, inode, 2 * 4096, 2 * 4096, + &converted); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, converted, 2U); + ext_expect_extent_at(test, inode, 0, 2, 200, true); + ext_expect_extent_at(test, inode, 2, 2, 202, false); + ext_expect_extent_at(test, inode, 4, 2, 204, true); + + /* 2. ext4_convert_unwritten_extents_atomic() across split unwritten */ + ext_setup_range_test(test, inode, NULL); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 0, 2, 200, true, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 2, 3, 300, true, 0), 0); + + err = ext4_convert_unwritten_extents_atomic(NULL, inode, 0, 5 * 4096); + KUNIT_ASSERT_EQ(test, err, 0); + ext_expect_extent_at(test, inode, 0, 2, 200, false); + ext_expect_extent_at(test, inode, 2, 3, 300, false); + + /* 3. ext4_convert_unwritten_io_end_vec() across multiple vecs */ + ext_setup_range_test(test, inode, NULL); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 0, 8, 200, true, 0), 0); + + io_end.inode = inode; + INIT_LIST_HEAD(&io_end.list_vec); + vec1.offset = 1 * 4096; + vec1.size = 2 * 4096; + vec2.offset = 5 * 4096; + vec2.size = 2 * 4096; + list_add_tail(&vec1.list, &io_end.list_vec); + list_add_tail(&vec2.list, &io_end.list_vec); + + err = ext4_convert_unwritten_io_end_vec(NULL, &io_end); + KUNIT_ASSERT_EQ(test, err, 0); + ext_expect_extent_at(test, inode, 0, 1, 200, true); + ext_expect_extent_at(test, inode, 1, 2, 201, false); + ext_expect_extent_at(test, inode, 3, 2, 203, true); + ext_expect_extent_at(test, inode, 5, 2, 205, false); + ext_expect_extent_at(test, inode, 7, 1, 207, true); +} + +/* + * Verify ext4_fiemap() (range checks, FIEMAP_FLAG_CACHE precaching, data and + * external xattr reporting) and ext4_get_es_cache() (flag checks, precaching, + * and reporting mapped + delayed status extents). + */ +static void test_ext_fiemap_and_get_es_cache(struct kunit *test) +{ + struct inode *inode = &k_ctx.k_ei->vfs_inode; + struct fiemap_extent_info fieinfo = {}; + struct extent_status es = {}; + int err; + + ext_setup_range_test(test, inode, NULL); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 0, 3, 200, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 6, 2, 300, true, 0), 0); + inode->i_size = 10LL * 4096; + EXT4_I(inode)->i_disksize = 10LL * 4096; + + /* Zero-length FIEMAP -> -EINVAL */ + err = ext4_fiemap(inode, &fieinfo, 0, 0); + KUNIT_EXPECT_EQ(test, err, -EINVAL); + + /* Start past maxbytes on non-extent inode -> -EFBIG */ + ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS); + err = ext4_fiemap(inode, &fieinfo, + EXT4_SB(inode->i_sb)->s_bitmap_maxbytes + 4096, 4096); + KUNIT_EXPECT_EQ(test, err, -EFBIG); + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + + /* Count-only data FIEMAP with FIEMAP_FLAG_CACHE populates ES cache */ + memset(&fieinfo, 0, sizeof(fieinfo)); + fieinfo.fi_flags = FIEMAP_FLAG_CACHE; + err = ext4_fiemap(inode, &fieinfo, 0, 10 * 4096); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, fieinfo.fi_flags & FIEMAP_FLAG_CACHE, 0U); + KUNIT_EXPECT_EQ(test, fieinfo.fi_extents_mapped, 2U); + KUNIT_EXPECT_EQ(test, ext4_es_lookup_extent(inode, 0, NULL, &es, NULL), + 1); + + /* FIEMAP_FLAG_XATTR with no xattrs vs external i_file_acl block */ + memset(&fieinfo, 0, sizeof(fieinfo)); + fieinfo.fi_flags = FIEMAP_FLAG_XATTR; + err = ext4_fiemap(inode, &fieinfo, 0, 4096); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, fieinfo.fi_extents_mapped, 0U); + + EXT4_I(inode)->i_file_acl = 750; + memset(&fieinfo, 0, sizeof(fieinfo)); + fieinfo.fi_flags = FIEMAP_FLAG_XATTR; + err = ext4_fiemap(inode, &fieinfo, 0, 4096); + EXT4_I(inode)->i_file_acl = 0; + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, fieinfo.fi_extents_mapped, 1U); + + /* ext4_get_es_cache: unsupported flag -> -EBADR, len == 0 -> -EINVAL */ + memset(&fieinfo, 0, sizeof(fieinfo)); + fieinfo.fi_flags = FIEMAP_FLAG_XATTR; + err = ext4_get_es_cache(inode, &fieinfo, 0, 4096); + KUNIT_EXPECT_EQ(test, err, -EBADR); + + memset(&fieinfo, 0, sizeof(fieinfo)); + err = ext4_get_es_cache(inode, &fieinfo, 0, 0); + KUNIT_EXPECT_EQ(test, err, -EINVAL); + + /* + * Populate ES tree with written, hole, delayed, and unwritten entries + * and verify ext4_get_es_cache reports all 4 entries. + */ + down_write(&EXT4_I(inode)->i_data_sem); + ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS); + ext4_es_insert_extent(inode, 0, 3, 200, EXTENT_STATUS_WRITTEN, 0); + ext4_es_insert_extent(inode, 3, 1, ~0, EXTENT_STATUS_HOLE, 0); + ext4_es_insert_delayed_extent(inode, 4, 2, false, false); + ext4_es_insert_extent(inode, 6, 2, 300, EXTENT_STATUS_UNWRITTEN, 0); + up_write(&EXT4_I(inode)->i_data_sem); + + memset(&fieinfo, 0, sizeof(fieinfo)); + err = ext4_get_es_cache(inode, &fieinfo, 0, 10 * 4096); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, fieinfo.fi_extents_mapped, 4U); + + /* + * Build a depth-1 tree (5 discontiguous extents), clear ES cache, and + * verify FIEMAP_FLAG_CACHE precaches external leaf extents + holes. + */ + ext_setup_range_test(test, inode, NULL); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 0, 1, 200, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 2, 1, 202, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 4, 1, 204, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 6, 1, 206, false, 0), 0); + KUNIT_ASSERT_EQ(test, ext_insert_one(inode, 8, 1, 208, false, 0), 0); + inode->i_size = 10LL * 4096; + EXT4_I(inode)->i_disksize = 10LL * 4096; + + down_write(&EXT4_I(inode)->i_data_sem); + ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS); + up_write(&EXT4_I(inode)->i_data_sem); + + memset(&fieinfo, 0, sizeof(fieinfo)); + fieinfo.fi_flags = FIEMAP_FLAG_CACHE; + err = ext4_get_es_cache(inode, &fieinfo, 0, 10 * 4096); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, fieinfo.fi_flags & FIEMAP_FLAG_CACHE, 0U); + KUNIT_EXPECT_GE(test, fieinfo.fi_extents_mapped, 5U); } static const struct kunit_ext_test_param test_split_convert_params[] = { @@ -1051,6 +3509,39 @@ static struct kunit_case extents_test_cases[] = { test_convert_initialized_param_init, NULL), KUNIT_CASE_PARAM_WITH_INIT(test_split_convert, kunit_array_gen_params, test_handle_unwritten_init, NULL), + KUNIT_CASE(test_ext_pblock_48bit), + KUNIT_CASE(test_ext_unwritten_len_encoding), + KUNIT_CASE(test_ext_tree_init_and_check_inode), + KUNIT_CASE_PARAM_WITH_INIT(test_ext_check_corruptions, + kunit_array_gen_params, + ext_check_corrupt_param_init, NULL), + KUNIT_CASE(test_ext_block_csum_verify), + KUNIT_CASE(test_find_extent_root_binsearch), + KUNIT_CASE(test_find_extent_multilevel_and_navigation), + KUNIT_CASE(test_ext_precache), + KUNIT_CASE(test_can_extents_be_merged), + KUNIT_CASE(test_insert_extent_merge_and_nomerge), + KUNIT_CASE(test_insert_extent_grow_and_merge_up), + KUNIT_CASE(test_insert_extent_leaf_split), + KUNIT_CASE(test_insert_extent_index_split), + KUNIT_CASE(test_remove_space_tail_and_hole_punch), + KUNIT_CASE(test_remove_space_multilevel_collapse), + KUNIT_CASE(test_remove_space_bigalloc_partial_cluster), + KUNIT_CASE(test_map_blocks_lookup_hole_and_query_last_in_leaf), + KUNIT_CASE(test_map_blocks_alloc_overlap_and_enospc), + KUNIT_CASE(test_convert_to_initialized_abut_neighbors), + KUNIT_CASE(test_map_blocks_bigalloc_implied_cluster), + KUNIT_CASE(test_ext_shift_extents), + KUNIT_CASE(test_swap_extents), + KUNIT_CASE(test_clu_mapped), + KUNIT_CASE(test_ext_credits_calculation), + KUNIT_CASE(test_ext_fast_commit_replay), + KUNIT_CASE(test_fallocate_modes_and_prealloc), + KUNIT_CASE(test_zero_range_and_write_zeroes), + KUNIT_CASE(test_collapse_range), + KUNIT_CASE(test_insert_range), + KUNIT_CASE(test_convert_unwritten_extents_and_io_end), + KUNIT_CASE(test_ext_fiemap_and_get_es_cache), {} }; diff --git a/fs/ext4/extents.c b/fs/ext4/extents.c index cd35e88bc372b1..b65b0261ee5c3c 100644 --- a/fs/ext4/extents.c +++ b/fs/ext4/extents.c @@ -142,12 +142,16 @@ int ext4_datasem_ensure_credits(handle_t *handle, struct inode *inode, int ret; int dropped = 0; + KUNIT_STATIC_STUB_REDIRECT(ext4_datasem_ensure_credits, handle, inode, + check_cred, restart_cred, revoke_cred); + ret = ext4_journal_ensure_credits_fn(handle, check_cred, restart_cred, revoke_cred, ext4_ext_trunc_restart_fn(inode, &dropped)); if (dropped) down_write(&EXT4_I(inode)->i_data_sem); return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_datasem_ensure_credits); /* * could return: @@ -547,6 +551,13 @@ static void ext4_cache_extents(struct inode *inode, } } +struct buffer_head *ext4_ext_getblk(struct inode *inode, ext4_fsblk_t pblk, + gfp_t gfp_flags) +{ + KUNIT_STATIC_STUB_REDIRECT(ext4_ext_getblk, inode, pblk, gfp_flags); + return sb_getblk_gfp(inode->i_sb, pblk, gfp_flags); +} + static struct buffer_head * __read_extent_tree_block(const char *function, unsigned int line, struct inode *inode, struct ext4_extent_idx *idx, @@ -561,7 +572,7 @@ __read_extent_tree_block(const char *function, unsigned int line, gfp_flags |= __GFP_NOFAIL; pblk = ext4_idx_pblock(idx); - bh = sb_getblk_gfp(inode->i_sb, pblk, gfp_flags); + bh = ext4_ext_getblk(inode, pblk, gfp_flags); if (unlikely(!bh)) return ERR_PTR(-ENOMEM); @@ -869,7 +880,11 @@ ext4_ext_binsearch(struct inode *inode, } -void ext4_ext_tree_init(handle_t *handle, struct inode *inode) +/* + * Initialize the extent tree of inode. This only changes the in-memory + * inode, the caller has to mark the inode dirty. + */ +void ext4_ext_init_root(struct inode *inode) { struct ext4_extent_header *eh; @@ -879,6 +894,11 @@ void ext4_ext_tree_init(handle_t *handle, struct inode *inode) eh->eh_magic = EXT4_EXT_MAGIC; eh->eh_max = cpu_to_le16(ext4_ext_space_root(inode, 0)); eh->eh_generation = 0; +} + +void ext4_ext_tree_init(handle_t *handle, struct inode *inode) +{ + ext4_ext_init_root(inode); ext4_mark_inode_dirty(handle, inode); } @@ -1124,7 +1144,7 @@ static int ext4_ext_split(handle_t *handle, struct inode *inode, err = -EFSCORRUPTED; goto cleanup; } - bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS); + bh = ext4_ext_getblk(inode, newblock, __GFP_MOVABLE | GFP_NOFS); if (unlikely(!bh)) { err = -ENOMEM; goto cleanup; @@ -1203,7 +1223,7 @@ static int ext4_ext_split(handle_t *handle, struct inode *inode, while (k--) { oldblock = newblock; newblock = ablocks[--a]; - bh = sb_getblk(inode->i_sb, newblock); + bh = ext4_ext_getblk(inode, newblock, __GFP_MOVABLE | GFP_NOFS); if (unlikely(!bh)) { err = -ENOMEM; goto cleanup; @@ -1332,7 +1352,7 @@ static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode, if (newblock == 0) return err; - bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS); + bh = ext4_ext_getblk(inode, newblock, __GFP_MOVABLE | GFP_NOFS); if (unlikely(!bh)) return -ENOMEM; lock_buffer(bh); @@ -3167,17 +3187,18 @@ static void ext4_zeroout_es(struct inode *inode, struct ext4_extent *ex) } /* FIXME!! we need to try to merge to left or right after zero-out */ -int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex) +int ext4_ext_zeroout(handle_t *handle, struct inode *inode, + struct ext4_extent *ex) { ext4_fsblk_t ee_pblock; unsigned int ee_len; - KUNIT_STATIC_STUB_REDIRECT(ext4_ext_zeroout, inode, ex); + KUNIT_STATIC_STUB_REDIRECT(ext4_ext_zeroout, handle, inode, ex); ee_len = ext4_ext_get_actual_len(ex); ee_pblock = ext4_ext_pblock(ex); - return ext4_issue_zeroout(inode, le32_to_cpu(ex->ee_block), ee_pblock, - ee_len); + return ext4_issue_zeroout(handle, inode, le32_to_cpu(ex->ee_block), + ee_pblock, ee_len); } /* @@ -3186,7 +3207,7 @@ int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex) * @handle: the journal handle * @inode: the file inode * @path: the path to the extent - * @split: the logical block where the extent is splitted. + * @split: the logical block where the extent is split. * @flags: flags used to insert new extent to extent tree. * * @@ -3347,7 +3368,8 @@ static int ext4_split_extent_zeroout(handle_t *handle, struct inode *inode, lblk = ee_block; len = map->m_lblk - ee_block; pblk = ext4_ext_pblock(ex); - err = ext4_issue_zeroout(inode, lblk, pblk, len); + err = ext4_issue_zeroout(handle, inode, lblk, pblk, + len); if (err) /* ZEROOUT failed, just return original error */ return err; @@ -3358,7 +3380,8 @@ static int ext4_split_extent_zeroout(handle_t *handle, struct inode *inode, lblk = map_end; len = ex_end - map_end; pblk = ext4_ext_pblock(ex) + (map_end - ee_block); - err = ext4_issue_zeroout(inode, lblk, pblk, len); + err = ext4_issue_zeroout(handle, inode, lblk, pblk, + len); if (err) /* ZEROOUT failed, just return original error */ return err; @@ -3377,7 +3400,7 @@ static int ext4_split_extent_zeroout(handle_t *handle, struct inode *inode, lblk = map->m_lblk; len = map->m_len; pblk = ext4_ext_pblock(ex) + (map->m_lblk - ee_block); - err = ext4_issue_zeroout(inode, lblk, pblk, len); + err = ext4_issue_zeroout(handle, inode, lblk, pblk, len); if (err) /* ZEROOUT failed, just return original error */ return err; @@ -3754,9 +3777,11 @@ ext4_ext_convert_to_initialized(handle_t *handle, struct inode *inode, ext4_ext_store_pblock(&zero_ex1, ext4_ext_pblock(ex) + split_map.m_lblk + split_map.m_len - ee_block); - err = ext4_ext_zeroout(inode, &zero_ex1); - if (err) + err = ext4_ext_zeroout(handle, inode, &zero_ex1); + if (err) { + zero_ex1.ee_len = 0; goto fallback; + } split_map.m_len = *allocated; } if (split_map.m_lblk - ee_block + split_map.m_len < @@ -3768,9 +3793,11 @@ ext4_ext_convert_to_initialized(handle_t *handle, struct inode *inode, ee_block); ext4_ext_store_pblock(&zero_ex2, ext4_ext_pblock(ex)); - err = ext4_ext_zeroout(inode, &zero_ex2); - if (err) + err = ext4_ext_zeroout(handle, inode, &zero_ex2); + if (err) { + zero_ex2.ee_len = 0; goto fallback; + } } split_map.m_len += split_map.m_lblk - ee_block; @@ -3830,6 +3857,7 @@ static struct ext4_ext_path *ext4_split_convert_extents(handle_t *handle, ext4_lblk_t eof_block; ext4_lblk_t ee_block; struct ext4_extent *ex; + struct ext4_extent converted_ex; unsigned int ee_len; int split_flag = 0, depth, err = 0; bool did_zeroout = false; @@ -3887,6 +3915,9 @@ static struct ext4_ext_path *ext4_split_convert_extents(handle_t *handle, else if (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN) ext4_ext_mark_unwritten(ex); + /* Merging can move ex or release the leaf containing it. */ + converted_ex = *ex; + if (!(flags & EXT4_GET_BLOCKS_SPLIT_NOMERGE)) /* * note: ext4_ext_correct_indexes() isn't needed here because @@ -3897,6 +3928,7 @@ static struct ext4_ext_path *ext4_split_convert_extents(handle_t *handle, err = ext4_ext_dirty(handle, inode, path + depth); if (err) goto err; + ex = &converted_ex; } /* Lets update the extent status tree after conversion */ @@ -4639,8 +4671,15 @@ static int ext4_alloc_file_blocks(struct file *file, loff_t offset, loff_t len, credits = ext4_chunk_trans_blocks(inode, len_lblk); depth = ext_depth(inode); - /* Zero to the end of the block containing i_size */ - if (new_size > old_size) { + /* + * Zero to the end of the block containing i_size. + * Loading the eof block back before it is converted to unwritten + * or zeroed out may leave the page cache inconsistent with the + * disk, and zeroing it is redundant, so skip it. + */ + if (new_size > old_size && + !(in_range(old_size >> blkbits, map.m_lblk, map.m_len) && + (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN || alloc_zero))) { ret = ext4_block_zero_eof(inode, old_size, LLONG_MAX); if (ret) return ret; @@ -4689,8 +4728,14 @@ static int ext4_alloc_file_blocks(struct file *file, loff_t offset, loff_t len, WARN_ON_ONCE(map.m_lblk + map.m_len > EXT4_B_TO_LBLK(inode, new_size ?: old_size)); - ret = ext4_issue_zeroout(inode, map.m_lblk, map.m_pblk, - map.m_len); + /* + * Zeroed out without a handle, see the comment + * on EXT4_GET_BLOCKS_ZERO above. The conversion + * below tracks the blocks it converts for fast + * commit, and written blocks keep their mapping. + */ + ret = ext4_issue_zeroout(NULL, inode, map.m_lblk, + map.m_pblk, map.m_len); if (unlikely(ret)) break; @@ -4701,6 +4746,23 @@ static int ext4_alloc_file_blocks(struct file *file, loff_t offset, loff_t len, break; } + /* + * Add the inode to the orphan list before the + * conversion, as it may restart the transaction and + * commit the extents converted so far. Written + * extents must stay covered by the orphan list until + * i_disksize catches up. + */ + if (new_size) { + ret2 = ext4_orphan_add(handle, inode); + orphan = true; + if (unlikely(ret2)) { + ret = ret2; + ext4_journal_stop(handle); + break; + } + } + ret = ext4_convert_unwritten_extents(handle, inode, (loff_t)map.m_lblk << blkbits, (loff_t)map.m_len << blkbits, @@ -4708,23 +4770,21 @@ static int ext4_alloc_file_blocks(struct file *file, loff_t offset, loff_t len, if (ret) map.m_len = converted; - /* - * If blocks beyond i_disksize are converted, add - * the inode to the orphan list and advance the epos. - */ - if (new_size && converted) { - ret2 = ext4_orphan_add(handle, inode); - ret = ret ? ret : ret2; - orphan = true; - } - ret3 = ext4_journal_stop(handle); ret = ret ? ret : ret3; } + /* + * The conversion may have failed without converting + * anything. Only move epos over the blocks that were + * actually converted, so that a failure updates + * i_disksize just far enough to cover them. + */ + if (map.m_len) + epos = EXT4_LBLK_TO_B(inode, map.m_lblk + map.m_len); + map.m_lblk += map.m_len; map.m_len = len_lblk = len_lblk - map.m_len; - epos = EXT4_LBLK_TO_B(inode, map.m_lblk); if (ret) break; } @@ -4732,12 +4792,13 @@ static int ext4_alloc_file_blocks(struct file *file, loff_t offset, loff_t len, if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries)) goto retry; - if (!epos || !new_size) + if (!new_size || (!epos && !orphan)) return ret; /* - * Allocate blocks, update the file size to match the size of the - * already successfully allocated blocks. + * Update the file size to match the size of the already + * successfully allocated blocks, and release the orphan entry + * if we added one. */ if (epos > new_size) epos = new_size; @@ -4755,7 +4816,8 @@ static int ext4_alloc_file_blocks(struct file *file, loff_t offset, loff_t len, goto out; } - ext4_update_inode_size(inode, epos); + if (epos) + ext4_update_inode_size(inode, epos); if (orphan && inode->i_nlink) ext4_orphan_del(handle, inode); @@ -5048,6 +5110,7 @@ long ext4_fallocate(struct file *file, int mode, loff_t offset, loff_t len) inode_unlock(inode); return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fallocate); /* * This function converts a range of blocks to written extents. The caller of @@ -5107,6 +5170,14 @@ int ext4_convert_unwritten_extents_atomic(handle_t *handle, struct inode *inode, map.m_lblk += ret; map.m_len = (max_blocks -= ret); ret = ext4_map_blocks(handle, inode, &map, flags); + if (ret == 0) { + ext4_msg(inode->i_sb, KERN_ERR, + "inode #%llu: block %u: len %u: " + "hole found while converting extents for atomic write", + inode->i_ino, map.m_lblk, map.m_len); + ret = -EINVAL; + break; + } if (ret != max_blocks) ext4_msg(inode->i_sb, KERN_INFO, "inode #%llu: block %u: len %u: " @@ -5135,6 +5206,7 @@ int ext4_convert_unwritten_extents_atomic(handle_t *handle, struct inode *inode, return ret > 0 ? ret2 : ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_convert_unwritten_extents_atomic); /* * This function convert a range of blocks to written extents @@ -5227,6 +5299,7 @@ int ext4_convert_unwritten_extents(handle_t *handle, struct inode *inode, return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_convert_unwritten_extents); int ext4_convert_unwritten_io_end_vec(handle_t *handle, ext4_io_end_t *io_end) { @@ -5258,6 +5331,7 @@ int ext4_convert_unwritten_io_end_vec(handle_t *handle, ext4_io_end_t *io_end) return ret < 0 ? ret : err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_convert_unwritten_io_end_vec); static int ext4_iomap_xattr_fiemap(struct inode *inode, struct iomap *iomap) { @@ -5366,6 +5440,7 @@ int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo, inode_unlock_shared(inode); return error; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fiemap); int ext4_get_es_cache(struct inode *inode, struct fiemap_extent_info *fieinfo, __u64 start, __u64 len) @@ -5413,6 +5488,7 @@ int ext4_get_es_cache(struct inode *inode, struct fiemap_extent_info *fieinfo, */ return ext4_fill_es_cache_info(inode, start_blk, len_blks, fieinfo); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_es_cache); /* * ext4_ext_shift_path_extents: @@ -6262,8 +6338,10 @@ void ext4_ext_replay_shrink_inode(struct inode *inode, ext4_lblk_t end) } old_cur = cur; cur = le32_to_cpu(ex->ee_block) + ext4_ext_get_actual_len(ex); + /* ex ends before old_cur, which is in a hole: skip the hole */ if (cur <= old_cur) - cur = old_cur + 1; + cur = max(old_cur + 1, + ext4_ext_next_allocated_block(path)); ext4_ext_try_to_merge(NULL, inode, path, ex); down_write(&EXT4_I(inode)->i_data_sem); ext4_ext_dirty(NULL, inode, &path[path->p_depth]); @@ -6318,7 +6396,7 @@ int ext4_ext_replay_set_iblocks(struct inode *inode) map.m_len = end - cur; ret = ext4_map_blocks(NULL, inode, &map, 0); if (ret < 0) - break; + goto cleanup; if (ret > 0) numblks += ret; cur = cur + map.m_len; @@ -6334,15 +6412,19 @@ int ext4_ext_replay_set_iblocks(struct inode *inode) cur = 0; ret = skip_hole(inode, &cur); if (ret < 0) - goto out; + goto cleanup; path = ext4_find_extent(inode, cur, path, 0); - if (IS_ERR(path)) - goto out; + if (IS_ERR(path)) { + ret = PTR_ERR(path); + goto cleanup; + } numblks += path->p_depth; while (cur < end) { path = ext4_find_extent(inode, cur, path, 0); - if (IS_ERR(path)) - break; + if (IS_ERR(path)) { + ret = PTR_ERR(path); + goto cleanup; + } ex = path[path->p_depth].p_ext; if (!ex) goto cleanup; @@ -6351,11 +6433,13 @@ int ext4_ext_replay_set_iblocks(struct inode *inode) ext4_ext_get_actual_len(ex)); ret = skip_hole(inode, &cur); if (ret < 0) - break; + goto cleanup; path2 = ext4_find_extent(inode, cur, path2, 0); - if (IS_ERR(path2)) - break; + if (IS_ERR(path2)) { + ret = PTR_ERR(path2); + goto cleanup; + } for (i = 0; i <= max(path->p_depth, path2->p_depth); i++) { cmp1 = cmp2 = 0; @@ -6376,7 +6460,7 @@ int ext4_ext_replay_set_iblocks(struct inode *inode) cleanup: ext4_free_ext_path(path); ext4_free_ext_path(path2); - return 0; + return ret; } int ext4_ext_clear_bb(struct inode *inode) @@ -6406,29 +6490,34 @@ int ext4_ext_clear_bb(struct inode *inode) map.m_len = end - cur; ret = ext4_map_blocks(NULL, inode, &map, 0); if (ret < 0) - break; + goto out; if (ret > 0) { path = ext4_find_extent(inode, map.m_lblk, path, 0); - if (!IS_ERR(path)) { - for (j = 0; j < path->p_depth; j++) { - ext4_mb_mark_bb(inode->i_sb, - path[j].p_block, 1, false); - ext4_fc_record_regions(inode->i_sb, inode->i_ino, - 0, path[j].p_block, 1, 1); - } - } else { - path = NULL; + if (IS_ERR(path)) { + ret = PTR_ERR(path); + goto out; + } + for (j = 0; j < path->p_depth; j++) { + ext4_mb_mark_bb(inode->i_sb, + path[j].p_block, 1, false); + ret = ext4_fc_record_regions(inode->i_sb, + inode->i_ino, 0, + path[j].p_block, 1, 1); + if (ret) + goto out; } ext4_mb_mark_bb(inode->i_sb, map.m_pblk, map.m_len, false); - ext4_fc_record_regions(inode->i_sb, inode->i_ino, - map.m_lblk, map.m_pblk, map.m_len, 1); + ret = ext4_fc_record_regions(inode->i_sb, inode->i_ino, + map.m_lblk, map.m_pblk, map.m_len, 1); + if (ret) + goto out; } cur = cur + map.m_len; } out: ext4_free_ext_path(path); - return 0; + return ret < 0 ? ret : 0; } #if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) @@ -6448,17 +6537,79 @@ struct ext4_ext_path *ext4_split_convert_extents_test(handle_t *handle, } EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_split_convert_extents_test); +int ext4_ext_check_test(struct inode *inode, struct ext4_extent_header *eh, + int depth, ext4_fsblk_t pblk, ext4_lblk_t lblk) +{ + return __ext4_ext_check(__func__, __LINE__, inode, eh, depth, pblk, + lblk); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_check_test); + +void ext4_extent_block_csum_set_test(struct inode *inode, + struct ext4_extent_header *eh) +{ + ext4_extent_block_csum_set(inode, eh); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_extent_block_csum_set_test); + +int ext4_can_extents_be_merged_test(struct inode *inode, + struct ext4_extent *ex1, + struct ext4_extent *ex2) +{ + return ext4_can_extents_be_merged(inode, ex1, ex2); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_can_extents_be_merged_test); + +int ext4_ext_search_left_test(struct inode *inode, struct ext4_ext_path *path, + ext4_lblk_t *logical, ext4_fsblk_t *phys) +{ + return ext4_ext_search_left(inode, path, logical, phys); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_search_left_test); + +int ext4_ext_search_right_test(struct inode *inode, struct ext4_ext_path *path, + ext4_lblk_t *logical, ext4_fsblk_t *phys, + struct ext4_extent *ret_ex, int flags) +{ + return ext4_ext_search_right(inode, path, logical, phys, ret_ex, flags); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_search_right_test); + +ext4_lblk_t ext4_ext_next_leaf_block_test(struct ext4_ext_path *path) +{ + return ext4_ext_next_leaf_block(path); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_next_leaf_block_test); + +int ext4_ext_shift_extents_test(struct inode *inode, handle_t *handle, + ext4_lblk_t start, ext4_lblk_t shift, + enum SHIFT_DIRECTION direction) +{ + return ext4_ext_shift_extents(inode, handle, start, shift, direction); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_shift_extents_test); + EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_ext_dirty); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_getblk); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_zeroout); -EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_register_shrinker); -EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_unregister_shrinker); -EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_destroy_stats); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_map_create_blocks); -EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_init_tree); -EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_lookup_extent); -EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_insert_extent); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_insert_extent); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_find_extent); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_issue_zeroout); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_map_query_blocks); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_free_ext_path); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_tree_init); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_check_inode); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_precache); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_next_allocated_block); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_calc_credits_for_single_extent); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_index_trans_blocks); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_remove_space); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_truncate); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_map_blocks); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_swap_extents); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_clu_mapped); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_replay_update_ex); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_replay_shrink_inode); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_replay_set_iblocks); #endif diff --git a/fs/ext4/extents_status-test.c b/fs/ext4/extents_status-test.c new file mode 100644 index 00000000000000..825d12513e4af2 --- /dev/null +++ b/fs/ext4/extents_status-test.c @@ -0,0 +1,1646 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for ext4 extents status tree and bigalloc pending reservations. + */ + +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_extents.h" + +#define ES_MAX_EXPECTED_EXTENTS 8 + +struct es_test_ctx { + struct super_block *sb; + struct ext4_sb_info *sbi; + struct ext4_inode_info *ei; + + /* + * Saved shrinker callbacks so the registered shrinker can be + * replaced with no-op stubs to prevent asynchronous background + * reclaim (kswapd / direct reclaim) from touching mock extents. + */ + unsigned long (*shrinker_count)(struct shrinker *shrink, + struct shrink_control *sc); + unsigned long (*shrinker_scan)(struct shrinker *shrink, + struct shrink_control *sc); + + /* Tracking for stubbed delalloc reservation callbacks */ + int da_update_calls; + int last_da_used; + int total_da_used; + int last_da_quota_claim; + + int da_release_calls; + int last_da_released; + int total_da_released; +}; + +struct expected_es { + ext4_lblk_t lblk; + ext4_lblk_t len; + ext4_fsblk_t pblk; + unsigned int type; +}; + +static void reset_da_stub_stats(struct es_test_ctx *ctx) +{ + ctx->da_update_calls = 0; + ctx->last_da_used = 0; + ctx->total_da_used = 0; + ctx->last_da_quota_claim = 0; + + ctx->da_release_calls = 0; + ctx->last_da_released = 0; + ctx->total_da_released = 0; +} + +static void ext4_da_update_reserve_space_stub(struct inode *inode, + int used, int quota_claim) +{ + struct kunit *test = kunit_get_current_test(); + struct es_test_ctx *ctx; + + if (!test || !test->priv) + return; + + ctx = test->priv; + ctx->da_update_calls++; + ctx->last_da_used = used; + ctx->total_da_used += used; + ctx->last_da_quota_claim = quota_claim; +} + +static void ext4_da_release_space_stub(struct inode *inode, int to_free) +{ + struct kunit *test = kunit_get_current_test(); + struct es_test_ctx *ctx; + + if (!to_free || !test || !test->priv) + return; + + ctx = test->priv; + ctx->da_release_calls++; + ctx->last_da_released = to_free; + ctx->total_da_released += to_free; +} + +static struct ext4_ext_path * +ext4_find_extent_stub(struct inode *inode, ext4_lblk_t block, + struct ext4_ext_path *path, int flags) +{ + return ERR_PTR(-EOPNOTSUPP); +} + +static unsigned long es_dummy_shrinker_count(struct shrinker *shrink, + struct shrink_control *sc) +{ + return 0; +} + +static unsigned long es_dummy_shrinker_scan(struct shrinker *shrink, + struct shrink_control *sc) +{ + return SHRINK_STOP; +} + +static unsigned long es_shrinker_count(struct es_test_ctx *ctx, + struct shrink_control *sc) +{ + return ctx->shrinker_count(ctx->sbi->s_es_shrinker, sc); +} + +static unsigned long es_shrinker_scan(struct es_test_ctx *ctx, + struct shrink_control *sc) +{ + return ctx->shrinker_scan(ctx->sbi->s_es_shrinker, sc); +} + +static void es_insert_extent(struct inode *inode, ext4_lblk_t lblk, + ext4_lblk_t len, ext4_fsblk_t pblk, + unsigned int status, bool delalloc_reserve_used) +{ + down_write(&EXT4_I(inode)->i_data_sem); + ext4_es_insert_extent(inode, lblk, len, pblk, status, + delalloc_reserve_used); + up_write(&EXT4_I(inode)->i_data_sem); +} + +static void es_insert_delayed_extent(struct inode *inode, ext4_lblk_t lblk, + ext4_lblk_t len, bool lclu_allocated, + bool end_allocated) +{ + down_write(&EXT4_I(inode)->i_data_sem); + ext4_es_insert_delayed_extent(inode, lblk, len, lclu_allocated, + end_allocated); + up_write(&EXT4_I(inode)->i_data_sem); +} + +static void es_cache_extent(struct inode *inode, ext4_lblk_t lblk, + ext4_lblk_t len, ext4_fsblk_t pblk, + unsigned int status) +{ + down_read(&EXT4_I(inode)->i_data_sem); + ext4_es_cache_extent(inode, lblk, len, pblk, status); + up_read(&EXT4_I(inode)->i_data_sem); +} + +static void es_remove_extent(struct inode *inode, ext4_lblk_t lblk, + ext4_lblk_t len) +{ + down_write(&EXT4_I(inode)->i_data_sem); + ext4_es_remove_extent(inode, lblk, len); + up_write(&EXT4_I(inode)->i_data_sem); +} + +static int es_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static int es_set_anon(struct super_block *sb, struct fs_context *fc) +{ + return set_anon_super_fc(sb, fc); +} + +static struct file_system_type es_fs_type = { + .name = "extents_status test", + .init_fs_context = es_init_fs_context, + .kill_sb = kill_anon_super, +}; + +static void es_init_mock_inode(struct ext4_inode_info *ei, + struct super_block *sb, unsigned long ino) +{ + struct inode *inode = &ei->vfs_inode; + + memset(ei, 0, sizeof(*ei)); + inode->i_sb = sb; + inode->i_ino = ino; + inode->i_blkbits = sb->s_blocksize_bits; + + ext4_es_init_tree(&ei->i_es_tree); + ext4_init_pending_tree(&ei->i_pending_tree); + rwlock_init(&ei->i_es_lock); + INIT_LIST_HEAD(&ei->i_es_list); + init_rwsem(&ei->i_data_sem); + spin_lock_init(&ei->i_block_reservation_lock); + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); +} + +static void es_cleanup_inode(struct inode *inode) +{ + struct ext4_inode_info *ei = EXT4_I(inode); + struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); + struct rb_node *node; + + sbi->s_mount_state &= ~EXT4_FC_REPLAY; + es_remove_extent(inode, 0, EXT_MAX_BLOCKS); + + while ((node = rb_first(&ei->i_pending_tree.root)) != NULL) { + struct pending_reservation *pr; + + pr = rb_entry(node, struct pending_reservation, rb_node); + ext4_remove_pending(inode, EXT4_C2B(sbi, pr->lclu)); + } +} + +KUNIT_DEFINE_ACTION_WRAPPER(es_cleanup_inode_action, es_cleanup_inode, + struct inode *); +static void es_cleanup_shrinker(struct ext4_sb_info *sbi) +{ + ext4_es_unregister_shrinker(sbi); + ext4_es_destroy_stats(sbi); +} + +KUNIT_DEFINE_ACTION_WRAPPER(es_unregister_shrinker_action, + es_cleanup_shrinker, + struct ext4_sb_info *); +KUNIT_DEFINE_ACTION_WRAPPER(es_deactivate_super_action, deactivate_super, + struct super_block *); + +static struct inode *es_alloc_test_inode(struct kunit *test, + struct super_block *sb, + unsigned long ino) +{ + struct ext4_inode_info *ei; + int ret; + + ei = kunit_kzalloc(test, sizeof(*ei), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ei); + es_init_mock_inode(ei, sb, ino); + + ret = kunit_add_action_or_reset(test, es_cleanup_inode_action, + &ei->vfs_inode); + KUNIT_ASSERT_EQ(test, ret, 0); + + return &ei->vfs_inode; +} + +static void es_set_cluster_bits(struct super_block *sb, + unsigned int cluster_bits) +{ + struct ext4_sb_info *sbi = EXT4_SB(sb); + + sbi->s_cluster_bits = cluster_bits; + sbi->s_cluster_ratio = 1U << cluster_bits; +} + +/* + * All test resources and deferred cleanup actions are registered with KUnit's + * resource stack (test->resources), which unwinds in strict LIFO order after + * each test case completes (or aborts). + * + * The registration order below (and in helpers like es_alloc_test_inode()) + * MUST be preserved when modifying these tests so that teardown happens in the + * reverse order: + * 1. kunit_kzalloc() of ctx, sbi, and ctx->ei (freed last) + * 2. es_deactivate_super_action(sb) (superblock deactivated after shrinker + * and all inodes are torn down) + * 3. es_unregister_shrinker_action(sbi) (shrinker and s_es_stats per-CPU + * counters destroyed after all inode extent trees are emptied) + * 4. kunit_activate_static_stub() for ext4_da_update_reserve_space, + * ext4_da_release_space, and ext4_find_extent (stubs must remain active + * while es_cleanup_inode() removes delayed extents via + * ext4_es_remove_extent()) + * 5. es_cleanup_inode_action() for ctx->ei and any additional test inodes + * allocated via es_alloc_test_inode() (run first during teardown; inside + * es_alloc_test_inode(), kunit_kzalloc() must precede + * kunit_add_action_or_reset() so the inode is cleaned up before freed) + */ +static int es_kunit_init(struct kunit *test) +{ + struct es_test_ctx *ctx; + struct ext4_sb_info *sbi; + struct super_block *sb; + struct fs_context *fc; + int err; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + if (!ctx) + return -ENOMEM; + + sbi = kunit_kzalloc(test, sizeof(*sbi), GFP_KERNEL); + if (!sbi) + return -ENOMEM; + + ctx->ei = kunit_kzalloc(test, sizeof(*ctx->ei), GFP_KERNEL); + if (!ctx->ei) + return -ENOMEM; + + fc = fs_context_for_mount(&es_fs_type, 0); + if (IS_ERR(fc)) + return PTR_ERR(fc); + + sb = sget_fc(fc, NULL, es_set_anon); + put_fs_context(fc); + if (IS_ERR(sb)) + return PTR_ERR(sb); + + sbi->s_sb = sb; + sb->s_fs_info = sbi; + sb->s_blocksize = 4096; + sb->s_blocksize_bits = 12; + strscpy(sb->s_id, "es_kunit", sizeof(sb->s_id)); + + es_set_cluster_bits(sb, 0); + set_opt(sb, DELALLOC); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, + DEFAULT_RATELIMIT_BURST); + up_write(&sb->s_umount); + + err = kunit_add_action_or_reset(test, es_deactivate_super_action, sb); + if (err) + return err; + + err = ext4_es_register_shrinker(sbi); + if (err) + return err; + + /* + * Detach the real callbacks from the globally registered shrinker + * before any extents are inserted so background kswapd / direct + * reclaim cannot asynchronously evict mock extents during a test. + */ + ctx->shrinker_count = sbi->s_es_shrinker->count_objects; + ctx->shrinker_scan = sbi->s_es_shrinker->scan_objects; + WRITE_ONCE(sbi->s_es_shrinker->count_objects, es_dummy_shrinker_count); + WRITE_ONCE(sbi->s_es_shrinker->scan_objects, es_dummy_shrinker_scan); + + err = kunit_add_action_or_reset(test, es_unregister_shrinker_action, + sbi); + if (err) + return err; + + ctx->sb = sb; + ctx->sbi = sbi; + test->priv = ctx; + + kunit_activate_static_stub(test, ext4_da_update_reserve_space, + ext4_da_update_reserve_space_stub); + kunit_activate_static_stub(test, ext4_da_release_space, + ext4_da_release_space_stub); + kunit_activate_static_stub(test, ext4_find_extent, + ext4_find_extent_stub); + + es_init_mock_inode(ctx->ei, sb, 12); + err = kunit_add_action_or_reset(test, es_cleanup_inode_action, + &ctx->ei->vfs_inode); + if (err) + return err; + + return 0; +} + +static void assert_es_tree(struct kunit *test, struct inode *inode, + const struct expected_es *exp, unsigned int nr_exp) +{ + struct ext4_inode_info *ei = EXT4_I(inode); + struct extent_status found[ES_MAX_EXPECTED_EXTENTS]; + struct rb_node *node; + unsigned int nr_found = 0; + unsigned int all_nr; + unsigned int i; + ext4_lblk_t prev_end = 0; + + KUNIT_ASSERT_LE(test, nr_exp, (unsigned int)ARRAY_SIZE(found)); + + /* + * Snapshot the tree under i_es_lock and release the lock before + * running any KUnit assertions or expectations. KUNIT_ASSERT_* + * aborts the test kthread on failure (which would leak i_es_lock + * and deadlock es_cleanup_inode()), and KUNIT_EXPECT_* allocates + * failure logs with GFP_KERNEL. + */ + read_lock(&ei->i_es_lock); + for (node = rb_first(&ei->i_es_tree.root); node; node = rb_next(node)) { + struct extent_status *es = + rb_entry(node, struct extent_status, rb_node); + + if (nr_found < ARRAY_SIZE(found)) + found[nr_found] = *es; + nr_found++; + } + all_nr = ei->i_es_all_nr; + read_unlock(&ei->i_es_lock); + + for (i = 0; i < nr_found; i++) { + struct extent_status *es = &found[min(i, + (unsigned int)ARRAY_SIZE(found) - 1)]; + + KUNIT_ASSERT_LT_MSG(test, i, nr_exp, + "unexpected extra extent [%u/%u) type 0x%x", + es->es_lblk, es->es_len, ext4_es_type(es)); + + if (i > 0) + KUNIT_EXPECT_GT_MSG(test, es->es_lblk, prev_end, + "extent %u not strictly ordered", + i); + + KUNIT_EXPECT_EQ_MSG(test, es->es_lblk, exp[i].lblk, + "extent %u lblk mismatch", i); + KUNIT_EXPECT_EQ_MSG(test, es->es_len, exp[i].len, + "extent %u len mismatch", i); + KUNIT_EXPECT_EQ_MSG(test, ext4_es_type(es), exp[i].type, + "extent %u type mismatch", i); + + if (exp[i].type & (EXTENT_STATUS_WRITTEN | + EXTENT_STATUS_UNWRITTEN)) + KUNIT_EXPECT_EQ_MSG(test, ext4_es_pblock(es), + exp[i].pblk, + "extent %u pblk mismatch", i); + + prev_end = es->es_lblk + es->es_len - 1; + } + + KUNIT_EXPECT_EQ(test, nr_found, nr_exp); + KUNIT_EXPECT_EQ(test, all_nr, nr_exp); +} + +/* + * Group 1: Bitfield Encoding & Inline Helpers + */ +static void test_es_bitfield_written_and_unwritten_encoding(struct kunit *test) +{ + struct extent_status es = {}; + const ext4_fsblk_t sample_pblk = 0x123456789abcULL; + + ext4_es_store_pblock_status(&es, sample_pblk, EXTENT_STATUS_WRITTEN); + KUNIT_EXPECT_EQ(test, ext4_es_pblock(&es), sample_pblk); + KUNIT_EXPECT_EQ(test, ext4_es_show_pblock(&es), sample_pblk); + KUNIT_EXPECT_EQ(test, ext4_es_type(&es), EXTENT_STATUS_WRITTEN); + KUNIT_EXPECT_EQ(test, ext4_es_status(&es), EXTENT_STATUS_WRITTEN); + KUNIT_EXPECT_TRUE(test, ext4_es_is_written(&es)); + KUNIT_EXPECT_FALSE(test, ext4_es_is_unwritten(&es)); + KUNIT_EXPECT_FALSE(test, ext4_es_is_delayed(&es)); + KUNIT_EXPECT_FALSE(test, ext4_es_is_hole(&es)); + KUNIT_EXPECT_TRUE(test, ext4_es_is_mapped(&es)); + KUNIT_EXPECT_FALSE(test, ext4_es_is_referenced(&es)); + + ext4_es_store_pblock_status(&es, sample_pblk, EXTENT_STATUS_UNWRITTEN); + KUNIT_EXPECT_EQ(test, ext4_es_pblock(&es), sample_pblk); + KUNIT_EXPECT_TRUE(test, ext4_es_is_unwritten(&es)); + KUNIT_EXPECT_TRUE(test, ext4_es_is_mapped(&es)); + KUNIT_EXPECT_FALSE(test, ext4_es_is_written(&es)); +} + +static void test_es_bitfield_delayed_and_hole_encoding(struct kunit *test) +{ + struct extent_status es = {}; + /* 59-bit physical block field (64 - 5 status bits) all ones */ + const ext4_fsblk_t max_59bit_pblk = 0x07ffffffffffffffULL; + + ext4_es_store_pblock_status(&es, ~0ULL, EXTENT_STATUS_DELAYED); + KUNIT_EXPECT_TRUE(test, ext4_es_is_delayed(&es)); + KUNIT_EXPECT_FALSE(test, ext4_es_is_mapped(&es)); + KUNIT_EXPECT_EQ(test, ext4_es_pblock(&es), max_59bit_pblk); + KUNIT_EXPECT_EQ(test, ext4_es_show_pblock(&es), 0ULL); + + ext4_es_store_pblock_status(&es, 0ULL, EXTENT_STATUS_HOLE); + KUNIT_EXPECT_TRUE(test, ext4_es_is_hole(&es)); + KUNIT_EXPECT_FALSE(test, ext4_es_is_mapped(&es)); + KUNIT_EXPECT_EQ(test, ext4_es_pblock(&es), 0ULL); +} + +static void +test_es_bitfield_referenced_and_pblock_update_preserve_state(struct kunit *test) +{ + struct extent_status es = {}; + const ext4_fsblk_t initial_pblk = 0x123456789abcULL; + const ext4_fsblk_t updated_pblk = 0x07ffffffffffffffULL; + + ext4_es_store_pblock_status(&es, initial_pblk, EXTENT_STATUS_WRITTEN); + + /* Setting referenced bit preserves pblk and type */ + ext4_es_set_referenced(&es); + KUNIT_EXPECT_TRUE(test, ext4_es_is_referenced(&es)); + KUNIT_EXPECT_EQ(test, ext4_es_type(&es), EXTENT_STATUS_WRITTEN); + KUNIT_EXPECT_EQ(test, ext4_es_pblock(&es), initial_pblk); + KUNIT_EXPECT_EQ(test, ext4_es_status(&es), + EXTENT_STATUS_WRITTEN | EXTENT_STATUS_REFERENCED); + + /* Updating pblock preserves status and referenced bit */ + ext4_es_store_pblock(&es, updated_pblk); + KUNIT_EXPECT_EQ(test, ext4_es_pblock(&es), updated_pblk); + KUNIT_EXPECT_EQ(test, ext4_es_type(&es), EXTENT_STATUS_WRITTEN); + KUNIT_EXPECT_TRUE(test, ext4_es_is_referenced(&es)); + + /* Clearing referenced bit preserves updated pblk and type */ + ext4_es_clear_referenced(&es); + KUNIT_EXPECT_FALSE(test, ext4_es_is_referenced(&es)); + KUNIT_EXPECT_EQ(test, ext4_es_pblock(&es), updated_pblk); + KUNIT_EXPECT_EQ(test, ext4_es_type(&es), EXTENT_STATUS_WRITTEN); +} + +/* + * Group 2: Insertion, Lookup, Sequence Numbers, and Merging + */ +static void test_es_lookup_empty_tree_returns_miss(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + struct extent_status es; + ext4_lblk_t next_lblk = 0xdead; + s64 misses_before; + int ret; + + misses_before = percpu_counter_sum_positive( + &ctx->sbi->s_es_stats.es_stats_cache_misses); + ret = ext4_es_lookup_extent(inode, 10, &next_lblk, &es, NULL); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, percpu_counter_sum_positive( + &ctx->sbi->s_es_stats.es_stats_cache_misses), + misses_before + 1); +} + +static void test_es_insert_zero_len_is_noop(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + + es_insert_extent(inode, 10, 0, 100, EXTENT_STATUS_WRITTEN, false); + es_insert_delayed_extent(inode, 20, 0, false, false); + es_cache_extent(inode, 30, 0, 300, EXTENT_STATUS_WRITTEN); + + KUNIT_EXPECT_EQ(test, ctx->ei->i_es_all_nr, 0U); + KUNIT_EXPECT_TRUE(test, RB_EMPTY_ROOT(&ctx->ei->i_es_tree.root)); +} + +static void +test_es_lookup_hits_cache_and_rbtree_with_next_lblk(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + struct extent_status es; + ext4_lblk_t next_lblk = 0xdead; + u64 seq_after_first, seq_after_second, lookup_seq = 0; + s64 hits_before; + int ret; + + es_insert_extent(inode, 10, 5, 100, EXTENT_STATUS_WRITTEN, false); + seq_after_first = ctx->ei->i_es_seq; + es_insert_extent(inode, 20, 5, 200, EXTENT_STATUS_UNWRITTEN, false); + seq_after_second = ctx->ei->i_es_seq; + KUNIT_EXPECT_GT(test, seq_after_second, seq_after_first); + + /* + * Right after inserting [20, 5), tree->cache_es points to [20, 5). + * Looking up lblk 22 hits cache_es and sets next_lblk to 0 because + * [20, 5) is the last extent in the tree. + */ + hits_before = percpu_counter_sum_positive( + &ctx->sbi->s_es_stats.es_stats_cache_hits); + + ret = ext4_es_lookup_extent(inode, 22, &next_lblk, &es, &lookup_seq); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, es.es_lblk, 20U); + KUNIT_EXPECT_EQ(test, es.es_len, 5U); + KUNIT_EXPECT_EQ(test, ext4_es_pblock(&es), 200ULL); + KUNIT_EXPECT_TRUE(test, ext4_es_is_unwritten(&es)); + KUNIT_EXPECT_EQ(test, next_lblk, 0U); + KUNIT_EXPECT_EQ(test, lookup_seq, seq_after_second); + + /* Lookup start, middle, and end of first extent [10, 5) via rb-tree */ + ret = ext4_es_lookup_extent(inode, 10, &next_lblk, &es, NULL); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, es.es_lblk, 10U); + KUNIT_EXPECT_EQ(test, next_lblk, 20U); + + ret = ext4_es_lookup_extent(inode, 12, &next_lblk, &es, NULL); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, es.es_lblk, 10U); + KUNIT_EXPECT_EQ(test, next_lblk, 20U); + + ret = ext4_es_lookup_extent(inode, 14, &next_lblk, &es, NULL); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, es.es_lblk, 10U); + KUNIT_EXPECT_EQ(test, next_lblk, 20U); + + KUNIT_EXPECT_EQ(test, percpu_counter_sum_positive( + &ctx->sbi->s_es_stats.es_stats_cache_hits), + hits_before + 4); + + /* Lookup in gap [15..19] returns 0 */ + ret = ext4_es_lookup_extent(inode, 15, &next_lblk, &es, NULL); + KUNIT_EXPECT_EQ(test, ret, 0); +} + +static void test_es_fc_replay_bypasses_tree_operations(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + struct extent_status es; + static const struct expected_es expected[] = { + { .lblk = 10, .len = 5, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + }; + + es_insert_extent(inode, 10, 5, 100, EXTENT_STATUS_WRITTEN, false); + + ctx->sbi->s_mount_state |= EXT4_FC_REPLAY; + KUNIT_EXPECT_EQ(test, + ext4_es_lookup_extent(inode, 10, NULL, &es, NULL), 0); + ext4_es_find_extent_range(inode, ext4_es_is_written, 0, 20, &es); + KUNIT_EXPECT_EQ(test, es.es_len, 0U); + KUNIT_EXPECT_FALSE(test, + ext4_es_scan_range(inode, ext4_es_is_written, + 0, 20)); + KUNIT_EXPECT_FALSE(test, + ext4_es_scan_clu(inode, ext4_es_is_written, 10)); + + es_insert_extent(inode, 30, 5, 300, EXTENT_STATUS_WRITTEN, false); + es_cache_extent(inode, 40, 5, 400, EXTENT_STATUS_WRITTEN); + es_insert_delayed_extent(inode, 50, 5, false, false); + es_remove_extent(inode, 10, 5); + ctx->sbi->s_mount_state &= ~EXT4_FC_REPLAY; + + assert_es_tree(test, inode, expected, ARRAY_SIZE(expected)); +} + +struct es_merge_test_param { + const char *desc; + unsigned int nr_inserts; + struct expected_es inserts[3]; + unsigned int nr_expected; + struct expected_es expected[3]; +}; + +static const struct es_merge_test_param es_merge_params[] = { + { + .desc = "left merge contiguous written extents", + .nr_inserts = 2, + .inserts = { + { .lblk = 10, .len = 5, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 15, .len = 5, .pblk = 105, + .type = EXTENT_STATUS_WRITTEN }, + }, + .nr_expected = 1, + .expected = { + { .lblk = 10, .len = 10, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + }, + }, + { + .desc = "right merge contiguous written extents", + .nr_inserts = 2, + .inserts = { + { .lblk = 15, .len = 5, .pblk = 105, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 10, .len = 5, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + }, + .nr_expected = 1, + .expected = { + { .lblk = 10, .len = 10, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + }, + }, + { + .desc = "three-way bridge merge via try_to_merge_right", + .nr_inserts = 3, + .inserts = { + { .lblk = 10, .len = 5, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 20, .len = 5, .pblk = 110, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 15, .len = 5, .pblk = 105, + .type = EXTENT_STATUS_WRITTEN }, + }, + .nr_expected = 1, + .expected = { + { .lblk = 10, .len = 15, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + }, + }, + { + .desc = "three-way bridge merge via try_to_merge_left", + .nr_inserts = 3, + .inserts = { + { .lblk = 20, .len = 5, .pblk = 110, + .type = EXTENT_STATUS_UNWRITTEN }, + { .lblk = 10, .len = 5, .pblk = 100, + .type = EXTENT_STATUS_UNWRITTEN }, + { .lblk = 15, .len = 5, .pblk = 105, + .type = EXTENT_STATUS_UNWRITTEN }, + }, + .nr_expected = 1, + .expected = { + { .lblk = 10, .len = 15, .pblk = 100, + .type = EXTENT_STATUS_UNWRITTEN }, + }, + }, + { + .desc = "adjacent hole extents merge", + .nr_inserts = 2, + .inserts = { + { .lblk = 10, .len = 5, .pblk = 0, + .type = EXTENT_STATUS_HOLE }, + { .lblk = 15, .len = 5, .pblk = 0, + .type = EXTENT_STATUS_HOLE }, + }, + .nr_expected = 1, + .expected = { + { .lblk = 10, .len = 10, .pblk = 0, + .type = EXTENT_STATUS_HOLE }, + }, + }, + { + .desc = "discontiguous physical blocks do not merge", + .nr_inserts = 2, + .inserts = { + { .lblk = 10, .len = 5, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 15, .len = 5, .pblk = 200, + .type = EXTENT_STATUS_WRITTEN }, + }, + .nr_expected = 2, + .expected = { + { .lblk = 10, .len = 5, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 15, .len = 5, .pblk = 200, + .type = EXTENT_STATUS_WRITTEN }, + }, + }, + { + .desc = "different status types with contiguous pblk do not merge", + .nr_inserts = 2, + .inserts = { + { .lblk = 10, .len = 5, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 15, .len = 5, .pblk = 105, + .type = EXTENT_STATUS_UNWRITTEN }, + }, + .nr_expected = 2, + .expected = { + { .lblk = 10, .len = 5, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 15, .len = 5, .pblk = 105, + .type = EXTENT_STATUS_UNWRITTEN }, + }, + }, + { + .desc = "logically separated extents with 1-block gap do not merge", + .nr_inserts = 2, + .inserts = { + { .lblk = 10, .len = 5, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 16, .len = 5, .pblk = 106, + .type = EXTENT_STATUS_WRITTEN }, + }, + .nr_expected = 2, + .expected = { + { .lblk = 10, .len = 5, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 16, .len = 5, .pblk = 106, + .type = EXTENT_STATUS_WRITTEN }, + }, + }, +}; + +static void es_merge_get_desc(const struct es_merge_test_param *param, + char *desc) +{ + strscpy(desc, param->desc, KUNIT_PARAM_DESC_SIZE); +} +KUNIT_ARRAY_PARAM(es_merge, es_merge_params, es_merge_get_desc); + +static void test_es_merge_cases(struct kunit *test) +{ + const struct es_merge_test_param *param = test->param_value; + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + unsigned int i; + + for (i = 0; i < param->nr_inserts; i++) { + const struct expected_es *ins = ¶m->inserts[i]; + + es_insert_extent(inode, ins->lblk, ins->len, + ins->pblk, ins->type, false); + } + + assert_es_tree(test, inode, param->expected, param->nr_expected); +} + +static void test_es_insert_adjacent_delayed_extents_merges(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + static const struct expected_es expected[] = { + { .lblk = 10, .len = 10, .pblk = 0, + .type = EXTENT_STATUS_DELAYED }, + }; + + es_insert_delayed_extent(inode, 10, 5, false, false); + es_insert_delayed_extent(inode, 15, 5, false, false); + + assert_es_tree(test, inode, expected, ARRAY_SIZE(expected)); +} + +static void test_es_merge_preserves_referenced(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + struct extent_status es; + struct rb_node *node; + bool is_ref = false; + + /* + * Insert [10, 5) and [20, 5), mark [20, 5) referenced via lookup, + * then bridge [15, 5) so [20, 5) is merged into [10, 10) via + * ext4_es_try_to_merge_right(). + */ + es_insert_extent(inode, 10, 5, 100, EXTENT_STATUS_WRITTEN, false); + es_insert_extent(inode, 20, 5, 110, EXTENT_STATUS_WRITTEN, false); + KUNIT_ASSERT_EQ(test, + ext4_es_lookup_extent(inode, 20, NULL, &es, NULL), 1); + + es_insert_extent(inode, 15, 5, 105, EXTENT_STATUS_WRITTEN, false); + KUNIT_ASSERT_EQ(test, ctx->ei->i_es_all_nr, 1U); + + read_lock(&ctx->ei->i_es_lock); + node = rb_first(&ctx->ei->i_es_tree.root); + if (node) + is_ref = ext4_es_is_referenced(rb_entry(node, + struct extent_status, + rb_node)); + read_unlock(&ctx->ei->i_es_lock); + + KUNIT_ASSERT_NOT_NULL(test, node); + KUNIT_EXPECT_TRUE(test, is_ref); +} + +static void +test_es_merge_at_max_blocks_boundary_succeeds(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + static const struct expected_es expected[] = { + { .lblk = 0, .len = EXT_MAX_BLOCKS, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + }; + + es_insert_extent(inode, 0, 0x80000000U, 100, + EXTENT_STATUS_WRITTEN, false); + es_insert_extent(inode, 0x80000000U, 0x7fffffffU, + 100ULL + 0x80000000ULL, + EXTENT_STATUS_WRITTEN, false); + + assert_es_tree(test, inode, expected, ARRAY_SIZE(expected)); +} + +/* + * Group 3: Removal, Trimming, Splitting, and Overwrites + */ +struct es_remove_test_param { + const char *desc; + ext4_lblk_t rem_lblk; + ext4_lblk_t rem_len; + unsigned int nr_expected; + struct expected_es expected[2]; +}; + +static const struct es_remove_test_param es_remove_params[] = { + { + .desc = "remove range before extent", + .rem_lblk = 0, + .rem_len = 5, + .nr_expected = 1, + .expected = { + { .lblk = 10, .len = 10, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + }, + }, + { + .desc = "remove range after extent", + .rem_lblk = 20, + .rem_len = 5, + .nr_expected = 1, + .expected = { + { .lblk = 10, .len = 10, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + }, + }, + { + .desc = "remove exact extent range", + .rem_lblk = 10, + .rem_len = 10, + .nr_expected = 0, + }, + { + .desc = "remove superset of extent range", + .rem_lblk = 5, + .rem_len = 20, + .nr_expected = 0, + }, + { + .desc = "prefix trim of extent", + .rem_lblk = 10, + .rem_len = 4, + .nr_expected = 1, + .expected = { + { .lblk = 14, .len = 6, .pblk = 104, + .type = EXTENT_STATUS_WRITTEN }, + }, + }, + { + .desc = "suffix trim of extent", + .rem_lblk = 16, + .rem_len = 4, + .nr_expected = 1, + .expected = { + { .lblk = 10, .len = 6, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + }, + }, + { + .desc = "middle split of extent into two", + .rem_lblk = 13, + .rem_len = 4, + .nr_expected = 2, + .expected = { + { .lblk = 10, .len = 3, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 17, .len = 3, .pblk = 107, + .type = EXTENT_STATUS_WRITTEN }, + }, + }, +}; + +static void es_remove_get_desc(const struct es_remove_test_param *param, + char *desc) +{ + strscpy(desc, param->desc, KUNIT_PARAM_DESC_SIZE); +} +KUNIT_ARRAY_PARAM(es_remove, es_remove_params, es_remove_get_desc); + +static void test_es_remove_geometries(struct kunit *test) +{ + const struct es_remove_test_param *param = test->param_value; + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + + es_insert_extent(inode, 10, 10, 100, EXTENT_STATUS_WRITTEN, false); + es_remove_extent(inode, param->rem_lblk, param->rem_len); + + assert_es_tree(test, inode, param->expected, param->nr_expected); +} + +static void +test_es_remove_multi_extent_span_trims_and_deletes(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + static const struct expected_es expected[] = { + { .lblk = 10, .len = 2, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 43, .len = 2, .pblk = 403, + .type = EXTENT_STATUS_UNWRITTEN }, + }; + + es_insert_extent(inode, 10, 5, 100, EXTENT_STATUS_WRITTEN, false); + es_insert_extent(inode, 20, 5, 200, EXTENT_STATUS_HOLE, false); + es_insert_extent(inode, 30, 5, 300, EXTENT_STATUS_WRITTEN, false); + es_insert_extent(inode, 40, 5, 400, EXTENT_STATUS_UNWRITTEN, false); + + /* + * Remove [12, 31) covering lblks 12..42 inclusive: + * - trims suffix of [10, 5) -> [10, 2) + * - completely removes [20, 5) and [30, 5) + * - trims prefix of [40, 5) -> [43, 2) + */ + es_remove_extent(inode, 12, 31); + assert_es_tree(test, inode, expected, ARRAY_SIZE(expected)); +} + +static void test_es_insert_overwrite_split_and_remerge(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + static const struct expected_es split_exp[] = { + { .lblk = 10, .len = 3, .pblk = 100, + .type = EXTENT_STATUS_UNWRITTEN }, + { .lblk = 13, .len = 4, .pblk = 103, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 17, .len = 3, .pblk = 107, + .type = EXTENT_STATUS_UNWRITTEN }, + }; + static const struct expected_es merged_exp[] = { + { .lblk = 10, .len = 10, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + }; + + es_insert_extent(inode, 10, 10, 100, EXTENT_STATUS_UNWRITTEN, false); + es_insert_extent(inode, 13, 4, 103, EXTENT_STATUS_WRITTEN, false); + assert_es_tree(test, inode, split_exp, ARRAY_SIZE(split_exp)); + + /* Convert the remaining prefix and suffix to WRITTEN; all 3 merge */ + es_insert_extent(inode, 10, 3, 100, EXTENT_STATUS_WRITTEN, false); + es_insert_extent(inode, 17, 3, 107, EXTENT_STATUS_WRITTEN, false); + assert_es_tree(test, inode, merged_exp, ARRAY_SIZE(merged_exp)); +} + +/* + * Group 4: On-Disk Caching & Conflict Detection (ext4_es_cache_extent) + */ +static void +test_es_cache_extent_inserts_and_coalesces_same_status(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + static const struct expected_es initial_exp[] = { + { .lblk = 10, .len = 5, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + }; + static const struct expected_es coalesced_exp[] = { + { .lblk = 8, .len = 10, .pblk = 98, + .type = EXTENT_STATUS_WRITTEN }, + }; + int warnings_before; + + warnings_before = atomic_read(&ctx->sbi->s_warning_count); + + /* Cache into empty tree */ + es_cache_extent(inode, 10, 5, 100, EXTENT_STATUS_WRITTEN); + assert_es_tree(test, inode, initial_exp, ARRAY_SIZE(initial_exp)); + + /* Caching sub-range with identical status is a no-op */ + es_cache_extent(inode, 11, 2, 101, EXTENT_STATUS_WRITTEN); + assert_es_tree(test, inode, initial_exp, ARRAY_SIZE(initial_exp)); + + /* Caching larger covering range with same status coalesces */ + es_cache_extent(inode, 8, 10, 98, EXTENT_STATUS_WRITTEN); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->sbi->s_warning_count), + warnings_before); + assert_es_tree(test, inode, coalesced_exp, ARRAY_SIZE(coalesced_exp)); +} + +static void +test_es_cache_extent_conflict_covered_range_warns(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + static const struct expected_es expected[] = { + { .lblk = 8, .len = 10, .pblk = 98, + .type = EXTENT_STATUS_WRITTEN }, + }; + int warnings_before; + + es_cache_extent(inode, 8, 10, 98, EXTENT_STATUS_WRITTEN); + warnings_before = atomic_read(&ctx->sbi->s_warning_count); + + /* Sub-range [10, 4) covered by [8, 10) with conflicting status */ + es_cache_extent(inode, 10, 4, 500, EXTENT_STATUS_UNWRITTEN); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->sbi->s_warning_count), + warnings_before + 1); + assert_es_tree(test, inode, expected, ARRAY_SIZE(expected)); +} + +static void +test_es_cache_extent_conflict_partial_overlap_warns(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + static const struct expected_es expected[] = { + { .lblk = 10, .len = 5, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + }; + int warnings_before; + + es_cache_extent(inode, 10, 5, 100, EXTENT_STATUS_WRITTEN); + warnings_before = atomic_read(&ctx->sbi->s_warning_count); + + /* + * Range [8, 10) is not covered by [10, 5), so ext4_es_cache_extent() + * enters __es_remove_extent() which detects the status conflict and + * returns -EINVAL without modifying [10, 5). + */ + es_cache_extent(inode, 8, 10, 500, EXTENT_STATUS_UNWRITTEN); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->sbi->s_warning_count), + warnings_before + 1); + assert_es_tree(test, inode, expected, ARRAY_SIZE(expected)); +} + +static void +test_es_cache_extent_hole_over_delayed_does_not_warn(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + static const struct expected_es expected[] = { + { .lblk = 30, .len = 5, .pblk = 0, + .type = EXTENT_STATUS_DELAYED }, + }; + int warnings_before; + + es_insert_delayed_extent(inode, 30, 5, false, false); + warnings_before = atomic_read(&ctx->sbi->s_warning_count); + + es_cache_extent(inode, 30, 5, 0, EXTENT_STATUS_HOLE); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->sbi->s_warning_count), + warnings_before); + assert_es_tree(test, inode, expected, ARRAY_SIZE(expected)); +} + +/* + * Group 5: Range Search & Cluster Scanning + */ +static void +test_es_find_extent_range_skips_nonmatching_and_finds_next(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + struct extent_status es; + + es_insert_extent(inode, 10, 5, 100, EXTENT_STATUS_WRITTEN, false); + es_insert_delayed_extent(inode, 20, 5, false, false); + es_insert_extent(inode, 30, 5, 300, EXTENT_STATUS_UNWRITTEN, false); + + /* + * Prime cache_es to [10, 5) WRITTEN, then search [10, 25] for DELAYED: + * cache_es is hit at lblk 10, fails matching_fn(ext4_es_is_delayed), + * and walks rb_next to find [20, 5) DELAYED. + */ + KUNIT_ASSERT_EQ(test, + ext4_es_lookup_extent(inode, 10, NULL, &es, NULL), 1); + ext4_es_find_extent_range(inode, ext4_es_is_delayed, 10, 25, &es); + KUNIT_EXPECT_EQ(test, es.es_lblk, 20U); + KUNIT_EXPECT_EQ(test, es.es_len, 5U); + KUNIT_EXPECT_TRUE(test, ext4_es_is_delayed(&es)); + + /* Search [10, 18] for DELAYED when starting inside [10, 5) returns 0 */ + KUNIT_ASSERT_EQ(test, + ext4_es_lookup_extent(inode, 10, NULL, &es, NULL), 1); + ext4_es_find_extent_range(inode, ext4_es_is_delayed, 10, 18, &es); + KUNIT_EXPECT_EQ(test, es.es_len, 0U); + + /* + * Search [16, 18] in gap before [20, 5): __es_tree_search(16) returns + * the next extent [20, 5) following the range. + */ + ext4_es_find_extent_range(inode, ext4_es_is_delayed, 16, 18, &es); + KUNIT_EXPECT_EQ(test, es.es_lblk, 20U); + KUNIT_EXPECT_EQ(test, es.es_len, 5U); +} + +static void +test_es_scan_range_matches_only_overlapping_extents(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + + es_insert_delayed_extent(inode, 20, 5, false, false); + es_insert_extent(inode, 30, 5, 300, EXTENT_STATUS_UNWRITTEN, false); + + /* Gap [16, 18] before [20, 5) does not overlap */ + KUNIT_EXPECT_FALSE(test, + ext4_es_scan_range(inode, ext4_es_is_delayed, + 16, 18)); + + /* Ranges overlapping [20, 5) or [30, 5) return true */ + KUNIT_EXPECT_TRUE(test, + ext4_es_scan_range(inode, ext4_es_is_delayed, + 16, 20)); + KUNIT_EXPECT_TRUE(test, + ext4_es_scan_range(inode, ext4_es_is_delayed, + 22, 23)); + KUNIT_EXPECT_TRUE(test, + ext4_es_scan_range(inode, ext4_es_is_mapped, + 34, 40)); + + /* Range [35, 40] after [30, 5) does not overlap */ + KUNIT_EXPECT_FALSE(test, + ext4_es_scan_range(inode, ext4_es_is_mapped, + 35, 40)); +} + +static void test_es_scan_clu_matches_extent_in_same_cluster(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + + /* Configure cluster size = 16 blocks (cluster_bits = 4) */ + es_set_cluster_bits(ctx->sb, 4); + + /* Insert delayed block at the very end of cluster 0 (lblk 15) */ + es_insert_delayed_extent(inode, 15, 1, false, false); + + KUNIT_EXPECT_TRUE(test, + ext4_es_scan_clu(inode, ext4_es_is_delayed, 0)); + KUNIT_EXPECT_TRUE(test, + ext4_es_scan_clu(inode, ext4_es_is_delayed, 8)); + KUNIT_EXPECT_TRUE(test, + ext4_es_scan_clu(inode, ext4_es_is_delayed, 15)); + KUNIT_EXPECT_FALSE(test, + ext4_es_scan_clu(inode, ext4_es_is_delayed, 16)); + KUNIT_EXPECT_FALSE(test, + ext4_es_scan_clu(inode, ext4_es_is_mapped, 0)); +} + +/* + * Group 6: Delayed Allocation & Bigalloc Pending Reservations + */ +static void +test_es_delalloc_remove_and_overwrite_account_reserved_blocks(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + static const struct expected_es after_rem_exp[] = { + { .lblk = 10, .len = 2, .pblk = 0, + .type = EXTENT_STATUS_DELAYED }, + { .lblk = 15, .len = 5, .pblk = 0, + .type = EXTENT_STATUS_DELAYED }, + }; + static const struct expected_es after_ins_exp[] = { + { .lblk = 10, .len = 6, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 16, .len = 4, .pblk = 0, + .type = EXTENT_STATUS_DELAYED }, + }; + + /* Delayed extents are must-keep: i_es_shk_nr remains 0 */ + es_insert_delayed_extent(inode, 10, 10, false, false); + KUNIT_EXPECT_EQ(test, ctx->ei->i_es_all_nr, 1U); + KUNIT_EXPECT_EQ(test, ctx->ei->i_es_shk_nr, 0U); + KUNIT_EXPECT_TRUE(test, list_empty(&ctx->ei->i_es_list)); + + /* Removing 3 delayed blocks [12, 3) releases 3 reserved blocks */ + reset_da_stub_stats(ctx); + es_remove_extent(inode, 12, 3); + KUNIT_EXPECT_EQ(test, ctx->da_release_calls, 1); + KUNIT_EXPECT_EQ(test, ctx->last_da_released, 3); + assert_es_tree(test, inode, after_rem_exp, ARRAY_SIZE(after_rem_exp)); + + /* + * Inserting WRITTEN [10, 6) overwrites [10, 2) delayed, [12, 3) gap, + * and [15, 1) delayed -> claims 3 delayed blocks of reservation. + */ + reset_da_stub_stats(ctx); + es_insert_extent(inode, 10, 6, 100, EXTENT_STATUS_WRITTEN, true); + KUNIT_EXPECT_EQ(test, ctx->da_update_calls, 1); + KUNIT_EXPECT_EQ(test, ctx->last_da_used, 3); + KUNIT_EXPECT_EQ(test, ctx->last_da_quota_claim, 1); + assert_es_tree(test, inode, after_ins_exp, ARRAY_SIZE(after_ins_exp)); +} + +static void +test_es_bigalloc_insert_delayed_creates_and_removes_pending(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + + /* Cluster size = 16 blocks: clu 0=[0..15], clu 1=[16..31], clu 2=[32..47] */ + es_set_cluster_bits(ctx->sb, 4); + + /* Single cluster with lclu_allocated = true */ + es_insert_delayed_extent(inode, 2, 4, true, false); + KUNIT_EXPECT_TRUE(test, ext4_is_pending(inode, 0)); + KUNIT_EXPECT_TRUE(test, ext4_is_pending(inode, 15)); + KUNIT_EXPECT_FALSE(test, ext4_is_pending(inode, 16)); + + /* Multi-cluster [20, 20) spanning clusters 1 and 2, both allocated */ + es_insert_delayed_extent(inode, 20, 20, true, true); + KUNIT_EXPECT_TRUE(test, ext4_is_pending(inode, 16)); + KUNIT_EXPECT_TRUE(test, ext4_is_pending(inode, 32)); + KUNIT_EXPECT_FALSE(test, ext4_is_pending(inode, 48)); + + /* Duplicate pending insertion on cluster 0 is idempotent */ + es_insert_delayed_extent(inode, 8, 2, true, false); + KUNIT_EXPECT_TRUE(test, ext4_is_pending(inode, 0)); + + /* Explicit removal of pending reservation */ + ext4_remove_pending(inode, 16); + KUNIT_EXPECT_FALSE(test, ext4_is_pending(inode, 16)); + KUNIT_EXPECT_TRUE(test, ext4_is_pending(inode, 32)); +} + +static void +test_es_bigalloc_revise_pending_single_cluster_halves(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + + /* Cluster size = 16 blocks */ + es_set_cluster_bits(ctx->sb, 4); + + /* Insert delayed extent [0, 32) covering clusters 0 and 1 */ + es_insert_delayed_extent(inode, 0, 32, false, false); + + /* + * 1. Allocate first half of cluster 0: [0, 8) -> WRITTEN. + * Delayed blocks [8, 8) remain after [0, 8) in cluster 0 (l_del=true): + * __revise_pending inserts pending on cluster 0 and claims 1 cluster. + */ + reset_da_stub_stats(ctx); + es_insert_extent(inode, 0, 8, 100, EXTENT_STATUS_WRITTEN, true); + KUNIT_EXPECT_TRUE(test, ext4_is_pending(inode, 0)); + KUNIT_EXPECT_EQ(test, ctx->da_update_calls, 1); + KUNIT_EXPECT_EQ(test, ctx->last_da_used, 1); + + /* + * 2. Allocate second half of cluster 0: [8, 8) -> WRITTEN. + * No delayed blocks remain in cluster 0; pending reservation on + * cluster 0 is removed and 0 additional clusters are claimed. + */ + reset_da_stub_stats(ctx); + es_insert_extent(inode, 8, 8, 108, EXTENT_STATUS_WRITTEN, true); + KUNIT_EXPECT_FALSE(test, ext4_is_pending(inode, 0)); + KUNIT_EXPECT_EQ(test, ctx->da_update_calls, 0); + + /* + * 3. Allocate second half of cluster 1 first: [24, 8) -> WRITTEN while + * [16, 8) remains delayed before it in cluster 1 (f_del=true branch in + * __revise_pending): inserts pending on cluster 1 and claims 1 cluster. + */ + reset_da_stub_stats(ctx); + es_insert_extent(inode, 24, 8, 224, EXTENT_STATUS_WRITTEN, true); + KUNIT_EXPECT_TRUE(test, ext4_is_pending(inode, 16)); + KUNIT_EXPECT_EQ(test, ctx->da_update_calls, 1); + KUNIT_EXPECT_EQ(test, ctx->last_da_used, 1); +} + +static void +test_es_bigalloc_revise_pending_multi_cluster_span(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + + /* Cluster size = 16 blocks */ + es_set_cluster_bits(ctx->sb, 4); + + /* + * Insert delayed [16, 32) across cluster 1 [16..31] and cluster 2 + * [32..47], then allocate [20, 24) (lblks 20..43), leaving delayed + * [16, 4) in cluster 1 and delayed [44, 4) in cluster 2. Both clusters + * get pending reservations and 2 clusters are claimed. + */ + es_insert_delayed_extent(inode, 16, 32, false, false); + reset_da_stub_stats(ctx); + es_insert_extent(inode, 20, 24, 220, EXTENT_STATUS_WRITTEN, true); + KUNIT_EXPECT_TRUE(test, ext4_is_pending(inode, 16)); + KUNIT_EXPECT_TRUE(test, ext4_is_pending(inode, 32)); + KUNIT_EXPECT_EQ(test, ctx->da_update_calls, 1); + KUNIT_EXPECT_EQ(test, ctx->last_da_used, 2); +} + +static void +test_es_bigalloc_remove_partial_cluster_holds_rsvd_until_empty(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + + /* Cluster size = 16 blocks */ + es_set_cluster_bits(ctx->sb, 4); + + es_insert_delayed_extent(inode, 0, 16, false, false); + reset_da_stub_stats(ctx); + + es_remove_extent(inode, 0, 4); + KUNIT_EXPECT_EQ(test, ctx->da_release_calls, 0); + + es_remove_extent(inode, 12, 4); + KUNIT_EXPECT_EQ(test, ctx->da_release_calls, 0); + + es_remove_extent(inode, 4, 8); + KUNIT_EXPECT_EQ(test, ctx->da_release_calls, 1); + KUNIT_EXPECT_EQ(test, ctx->last_da_released, 1); +} + +static void +test_es_bigalloc_remove_fragmented_cluster_releases_once(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + + /* Cluster size = 16 blocks */ + es_set_cluster_bits(ctx->sb, 4); + + /* + * Two fragmented delayed extents within cluster 0 ([2, 3) and [10, 3)) + * share a single cluster reservation and must release 1 cluster, not 2. + */ + es_insert_delayed_extent(inode, 2, 3, false, false); + es_insert_delayed_extent(inode, 10, 3, false, false); + reset_da_stub_stats(ctx); + + es_remove_extent(inode, 0, 16); + KUNIT_EXPECT_EQ(test, ctx->da_release_calls, 1); + KUNIT_EXPECT_EQ(test, ctx->last_da_released, 1); +} + +static void +test_es_bigalloc_remove_pending_cluster_cancels_pending_only(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + + /* Cluster size = 16 blocks */ + es_set_cluster_bits(ctx->sb, 4); + + /* + * Removing a delayed extent in a cluster with a pending reservation + * cancels the pending reservation and releases 0 clusters (because the + * cluster reservation was already claimed when allocated). + */ + es_insert_delayed_extent(inode, 16, 8, true, false); + KUNIT_ASSERT_TRUE(test, ext4_is_pending(inode, 16)); + reset_da_stub_stats(ctx); + + es_remove_extent(inode, 16, 8); + KUNIT_EXPECT_EQ(test, ctx->da_release_calls, 0); + KUNIT_EXPECT_FALSE(test, ext4_is_pending(inode, 16)); +} + +/* + * Group 7: Shrinker, Referenced Aging, and Cache Clearing + */ +static void +test_es_clear_inode_es_retains_only_delayed_extents(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + static const struct expected_es only_delayed_exp[] = { + { .lblk = 40, .len = 5, .pblk = 0, + .type = EXTENT_STATUS_DELAYED }, + }; + + es_insert_extent(inode, 10, 5, 100, EXTENT_STATUS_WRITTEN, false); + es_insert_extent(inode, 20, 5, 200, EXTENT_STATUS_UNWRITTEN, false); + es_insert_extent(inode, 30, 5, 0, EXTENT_STATUS_HOLE, false); + es_insert_delayed_extent(inode, 40, 5, false, false); + ext4_set_inode_state(inode, EXT4_STATE_EXT_PRECACHED); + + KUNIT_EXPECT_EQ(test, ctx->ei->i_es_all_nr, 4U); + KUNIT_EXPECT_EQ(test, ctx->ei->i_es_shk_nr, 3U); + + ext4_clear_inode_es(inode); + + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(inode, + EXT4_STATE_EXT_PRECACHED)); + KUNIT_EXPECT_EQ(test, ctx->ei->i_es_shk_nr, 0U); + KUNIT_EXPECT_TRUE(test, list_empty(&ctx->ei->i_es_list)); + assert_es_tree(test, inode, only_delayed_exp, + ARRAY_SIZE(only_delayed_exp)); +} + +static void +test_es_shrinker_ages_referenced_and_keeps_delayed(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + struct percpu_counter *shk_cnt = &ctx->sbi->s_es_stats.es_stats_shk_cnt; + struct shrink_control sc = { .nr_to_scan = 0 }; + struct extent_status es; + unsigned long count, shrunk; + static const struct expected_es after_first_scan[] = { + { .lblk = 10, .len = 2, .pblk = 100, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 30, .len = 2, .pblk = 300, + .type = EXTENT_STATUS_WRITTEN }, + { .lblk = 50, .len = 2, .pblk = 0, + .type = EXTENT_STATUS_DELAYED }, + }; + static const struct expected_es after_second_scan[] = { + { .lblk = 50, .len = 2, .pblk = 0, + .type = EXTENT_STATUS_DELAYED }, + }; + + /* Insert 4 reclaimable WRITTEN extents and 1 non-reclaimable DELAYED */ + es_insert_extent(inode, 10, 2, 100, EXTENT_STATUS_WRITTEN, false); + es_insert_extent(inode, 20, 2, 200, EXTENT_STATUS_WRITTEN, false); + es_insert_extent(inode, 30, 2, 300, EXTENT_STATUS_WRITTEN, false); + es_insert_extent(inode, 40, 2, 400, EXTENT_STATUS_WRITTEN, false); + es_insert_delayed_extent(inode, 50, 2, false, false); + + /* Mark [10, 2) and [30, 2) as EXTENT_STATUS_REFERENCED via lookup */ + KUNIT_ASSERT_EQ(test, + ext4_es_lookup_extent(inode, 10, NULL, &es, NULL), 1); + KUNIT_ASSERT_EQ(test, + ext4_es_lookup_extent(inode, 30, NULL, &es, NULL), 1); + + /* + * Fold per-CPU counter deltas into the central count so count_objects + * (which uses percpu_counter_read_positive) sees all 4 extents on SMP. + */ + percpu_counter_set(shk_cnt, percpu_counter_sum_positive(shk_cnt)); + count = es_shrinker_count(ctx, &sc); + KUNIT_EXPECT_EQ(test, count, 4UL); + + /* + * First scan (nr_to_scan = 5): + * - [20, 2) and [40, 2) are unreferenced and reclaimed (shrunk = 2) + * - [10, 2) and [30, 2) have REFERENCED cleared and survive + * - [50, 2) is DELAYED (must_keep) and survives + */ + sc.nr_to_scan = 5; + shrunk = es_shrinker_scan(ctx, &sc); + KUNIT_EXPECT_EQ(test, shrunk, 2UL); + KUNIT_EXPECT_EQ(test, ctx->ei->i_es_shk_nr, 2U); + assert_es_tree(test, inode, after_first_scan, + ARRAY_SIZE(after_first_scan)); + + /* + * Second scan (nr_to_scan = 5): + * - [10, 2) and [30, 2) are now unreferenced and reclaimed (shrunk = 2) + * - Only [50, 2) DELAYED remains; inode is removed from s_es_list + */ + sc.nr_to_scan = 5; + shrunk = es_shrinker_scan(ctx, &sc); + KUNIT_EXPECT_EQ(test, shrunk, 2UL); + KUNIT_EXPECT_EQ(test, ctx->ei->i_es_shk_nr, 0U); + KUNIT_EXPECT_TRUE(test, list_empty(&ctx->ei->i_es_list)); + assert_es_tree(test, inode, after_second_scan, + ARRAY_SIZE(after_second_scan)); +} + +static void +test_es_shrinker_cursor_advances_and_wraps_around(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + struct shrink_control sc = {}; + unsigned long shrunk; + + es_insert_extent(inode, 10, 2, 100, EXTENT_STATUS_WRITTEN, false); + es_insert_extent(inode, 20, 2, 200, EXTENT_STATUS_WRITTEN, false); + es_insert_extent(inode, 30, 2, 300, EXTENT_STATUS_WRITTEN, false); + + sc.nr_to_scan = 1; + shrunk = es_shrinker_scan(ctx, &sc); + KUNIT_EXPECT_EQ(test, shrunk, 1UL); + KUNIT_EXPECT_EQ(test, ctx->ei->i_es_shrink_lblk, 20U); + + /* Re-insert [10, 2) behind the shrink cursor; next scan wraps to it */ + es_insert_extent(inode, 10, 2, 100, EXTENT_STATUS_WRITTEN, false); + sc.nr_to_scan = 3; + shrunk = es_shrinker_scan(ctx, &sc); + KUNIT_EXPECT_EQ(test, shrunk, 3UL); + KUNIT_EXPECT_EQ(test, ctx->ei->i_es_all_nr, 0U); +} + +static void +test_es_shrinker_skips_precached_inode_until_last_resort(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode1 = &ctx->ei->vfs_inode; + struct inode *inode2; + struct shrink_control sc = {}; + unsigned long shrunk; + + inode2 = es_alloc_test_inode(test, ctx->sb, 13); + + es_insert_extent(inode1, 10, 2, 100, EXTENT_STATUS_WRITTEN, false); + ext4_set_inode_state(inode1, EXT4_STATE_EXT_PRECACHED); + es_insert_extent(inode2, 10, 2, 200, EXTENT_STATUS_WRITTEN, false); + + /* First scan skips precached inode1 and reclaims from inode2 */ + sc.nr_to_scan = 1; + shrunk = es_shrinker_scan(ctx, &sc); + KUNIT_EXPECT_EQ(test, shrunk, 1UL); + KUNIT_EXPECT_EQ(test, ctx->ei->i_es_shk_nr, 1U); + KUNIT_EXPECT_EQ(test, EXT4_I(inode2)->i_es_shk_nr, 0U); + + /* + * Now only precached inode1 remains on s_es_list; shrinker retries + * and reclaims from inode1 as a last resort. + */ + sc.nr_to_scan = 1; + shrunk = es_shrinker_scan(ctx, &sc); + KUNIT_EXPECT_EQ(test, shrunk, 1UL); + KUNIT_EXPECT_EQ(test, ctx->ei->i_es_shk_nr, 0U); +} + +static void test_es_seq_shrinker_info_show_formats_stats(struct kunit *test) +{ + struct es_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei->vfs_inode; + struct seq_file seq = {}; + char *buf; + + es_insert_extent(inode, 10, 2, 100, EXTENT_STATUS_WRITTEN, false); + + buf = kunit_kzalloc(test, PAGE_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, buf); + seq.buf = buf; + seq.size = PAGE_SIZE; + seq.private = ctx->sb; + + KUNIT_EXPECT_EQ(test, + ext4_seq_es_shrinker_info_show(&seq, SEQ_START_TOKEN), + 0); + KUNIT_EXPECT_GT(test, seq.count, 0UL); + KUNIT_EXPECT_NOT_NULL(test, strstr(buf, "reclaimable objects")); +} + +static struct kunit_case extents_status_test_cases[] = { + KUNIT_CASE(test_es_bitfield_written_and_unwritten_encoding), + KUNIT_CASE(test_es_bitfield_delayed_and_hole_encoding), + KUNIT_CASE(test_es_bitfield_referenced_and_pblock_update_preserve_state), + KUNIT_CASE(test_es_lookup_empty_tree_returns_miss), + KUNIT_CASE(test_es_insert_zero_len_is_noop), + KUNIT_CASE(test_es_lookup_hits_cache_and_rbtree_with_next_lblk), + KUNIT_CASE(test_es_fc_replay_bypasses_tree_operations), + KUNIT_CASE_PARAM(test_es_merge_cases, es_merge_gen_params), + KUNIT_CASE(test_es_insert_adjacent_delayed_extents_merges), + KUNIT_CASE(test_es_merge_preserves_referenced), + KUNIT_CASE(test_es_merge_at_max_blocks_boundary_succeeds), + KUNIT_CASE_PARAM(test_es_remove_geometries, es_remove_gen_params), + KUNIT_CASE(test_es_remove_multi_extent_span_trims_and_deletes), + KUNIT_CASE(test_es_insert_overwrite_split_and_remerge), + KUNIT_CASE(test_es_cache_extent_inserts_and_coalesces_same_status), + KUNIT_CASE(test_es_cache_extent_conflict_covered_range_warns), + KUNIT_CASE(test_es_cache_extent_conflict_partial_overlap_warns), + KUNIT_CASE(test_es_cache_extent_hole_over_delayed_does_not_warn), + KUNIT_CASE(test_es_find_extent_range_skips_nonmatching_and_finds_next), + KUNIT_CASE(test_es_scan_range_matches_only_overlapping_extents), + KUNIT_CASE(test_es_scan_clu_matches_extent_in_same_cluster), + KUNIT_CASE(test_es_delalloc_remove_and_overwrite_account_reserved_blocks), + KUNIT_CASE(test_es_bigalloc_insert_delayed_creates_and_removes_pending), + KUNIT_CASE(test_es_bigalloc_revise_pending_single_cluster_halves), + KUNIT_CASE(test_es_bigalloc_revise_pending_multi_cluster_span), + KUNIT_CASE(test_es_bigalloc_remove_partial_cluster_holds_rsvd_until_empty), + KUNIT_CASE(test_es_bigalloc_remove_fragmented_cluster_releases_once), + KUNIT_CASE(test_es_bigalloc_remove_pending_cluster_cancels_pending_only), + KUNIT_CASE(test_es_clear_inode_es_retains_only_delayed_extents), + KUNIT_CASE(test_es_shrinker_ages_referenced_and_keeps_delayed), + KUNIT_CASE(test_es_shrinker_cursor_advances_and_wraps_around), + KUNIT_CASE(test_es_shrinker_skips_precached_inode_until_last_resort), + KUNIT_CASE(test_es_seq_shrinker_info_show_formats_stats), + {} +}; + +static struct kunit_suite extents_status_test_suite = { + .name = "ext4_extents_status_test", + .init = es_kunit_init, + .test_cases = extents_status_test_cases, +}; + +kunit_test_suites(&extents_status_test_suite); + +MODULE_DESCRIPTION("KUnit tests for ext4 extents status tree and pending reservations"); +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/extents_status.c b/fs/ext4/extents_status.c index 018b6146b9d815..b7fb8502f9d460 100644 --- a/fs/ext4/extents_status.c +++ b/fs/ext4/extents_status.c @@ -184,7 +184,7 @@ static int __es_remove_extent(struct inode *inode, ext4_lblk_t lblk, struct extent_status *prealloc); static int es_reclaim_extents(struct ext4_inode_info *ei, int *nr_to_scan); static int __es_shrink(struct ext4_sb_info *sbi, int nr_to_scan, - struct ext4_inode_info *locked_ei); + int *nr_scanned); static int __revise_pending(struct inode *inode, ext4_lblk_t lblk, ext4_lblk_t len, struct pending_reservation **prealloc); @@ -1099,6 +1099,9 @@ int ext4_es_lookup_extent(struct inode *inode, ext4_lblk_t lblk, struct rb_node *node; int found = 0; + KUNIT_STATIC_STUB_REDIRECT(ext4_es_lookup_extent, inode, lblk, + next_lblk, es, pseq); + if (EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY) return 0; @@ -1670,7 +1673,7 @@ void ext4_es_remove_extent(struct inode *inode, ext4_lblk_t lblk, } static int __es_shrink(struct ext4_sb_info *sbi, int nr_to_scan, - struct ext4_inode_info *locked_ei) + int *nr_scanned) { struct ext4_inode_info *ei; struct ext4_es_stats *es_stats; @@ -1679,6 +1682,7 @@ static int __es_shrink(struct ext4_sb_info *sbi, int nr_to_scan, int nr_to_walk; int nr_shrunk = 0; int retried = 0, nr_skipped = 0; + int orig_nr_to_scan = nr_to_scan; es_stats = &sbi->s_es_stats; start_time = ktime_get(); @@ -1706,7 +1710,7 @@ static int __es_shrink(struct ext4_sb_info *sbi, int nr_to_scan, continue; } - if (ei == locked_ei || !write_trylock(&ei->i_es_lock)) { + if (!write_trylock(&ei->i_es_lock)) { nr_skipped++; continue; } @@ -1734,10 +1738,9 @@ static int __es_shrink(struct ext4_sb_info *sbi, int nr_to_scan, goto retry; } - if (locked_ei && nr_shrunk == 0) - nr_shrunk = es_reclaim_extents(locked_ei, &nr_to_scan); - out: + *nr_scanned = orig_nr_to_scan - nr_to_scan; + scan_time = ktime_to_ns(ktime_sub(ktime_get(), start_time)); if (likely(es_stats->es_stats_scan_time)) es_stats->es_stats_scan_time = (scan_time + @@ -1774,15 +1777,36 @@ static unsigned long ext4_es_scan(struct shrinker *shrink, { struct ext4_sb_info *sbi = shrink->private_data; int nr_to_scan = sc->nr_to_scan; - int ret, nr_shrunk; + int ret, nr_shrunk, nr_scanned; ret = percpu_counter_read_positive(&sbi->s_es_stats.es_stats_shk_cnt); trace_ext4_es_shrink_scan_enter(sbi->s_sb, nr_to_scan, ret); - nr_shrunk = __es_shrink(sbi, nr_to_scan, NULL); + nr_shrunk = __es_shrink(sbi, nr_to_scan, &nr_scanned); + sc->nr_scanned = nr_scanned; ret = percpu_counter_read_positive(&sbi->s_es_stats.es_stats_shk_cnt); trace_ext4_es_shrink_scan_exit(sbi->s_sb, nr_shrunk, ret); + + /* + * Key SHRINK_STOP off nr_scanned (extents actually examined), not + * nr_shrunk (extents actually freed): a batch that finds every + * extent still referenced correctly ages them without freeing + * any, and that is real progress nr_shrunk would miss. + * + * nr_scanned can come back 0 for more than a genuinely empty + * sbi->s_es_list: es_stats_shk_cnt is a stale percpu count, an + * inode can be momentarily skipped (precached, lock contended), + * or durably have nothing shrinkable (i_es_shk_nr == 0) without + * es_reclaim_extents() ever touching nr_to_scan. Treat all of + * these alike: not stopping doesn't help the transient cases + * either, since do_shrink_slab()'s budget only decrements by + * nr_scanned, so retrying forever at nr_scanned == 0 never + * terminates. + */ + if (nr_scanned == 0) + return SHRINK_STOP; + return nr_shrunk; } @@ -2395,3 +2419,23 @@ static int __revise_pending(struct inode *inode, ext4_lblk_t lblk, out: return (ret < 0) ? ret : pendings; } + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_init_tree); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_insert_extent); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_cache_extent); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_remove_extent); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_find_extent_range); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_lookup_extent); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_scan_range); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_scan_clu); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_register_shrinker); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_unregister_shrinker); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_destroy_stats); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_seq_es_shrinker_info_show); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_init_pending_tree); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_remove_pending); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_is_pending); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_insert_delayed_extent); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_clear_inode_es); +#endif diff --git a/fs/ext4/fast_commit-test.c b/fs/ext4/fast_commit-test.c new file mode 100644 index 00000000000000..07cb9c043cd2c1 --- /dev/null +++ b/fs/ext4/fast_commit-test.c @@ -0,0 +1,2714 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for ext4 fast commit operations (fs/ext4/fast_commit.c) + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_jbd2.h" +#include "ext4_extents.h" +#include "extents_status.h" +#include "fast_commit.h" +#include "namei.h" + +#define TEST_BLK_SIZE 1024 +#define TEST_BLK_BITS 10 +#define TEST_INODE_SIZE 256 +#define TEST_EXTRA_ISIZE 32 +#define TEST_FIRST_PBLK 100 +#define TEST_MAX_BLOCKS 32 +#define TEST_MAX_LBLOCKS 16 +#define TEST_MAX_INODES 8 +#define TEST_MAX_FC_BUFS 16 +#define TEST_MAX_BB_MARKS 32 + +#define TEST_ROOT_INO EXT4_ROOT_INO +#define TEST_DIR_INO 12 +#define TEST_FILE1_INO 13 +#define TEST_FILE2_INO 14 +#define TEST_SUBDIR_INO 15 +#define TEST_CSUM_SEED 0x12345678U + +struct fc_mock_block { + bool in_use; + struct buffer_head bh; + char data[TEST_BLK_SIZE] __aligned(8); +}; + +struct fc_mock_inode_slot { + bool allocated; + struct ext4_inode_info ei; + struct jbd2_inode jinode; + struct buffer_head iloc_bh; + char raw_buf[TEST_BLK_SIZE] __aligned(8); + ext4_fsblk_t lblk_to_pblk[TEST_MAX_LBLOCKS]; +}; + +struct fc_bb_mark { + ext4_fsblk_t block; + int len; + bool state; +}; + +struct fc_test_ctx { + struct super_block *sb; + struct ext4_sb_info *sbi; + struct ext4_super_block es; + struct block_device bdev; + struct block_device ext_jdev; + struct address_space bd_mapping; + struct buffer_head sb_bh; + + journal_t journal; + transaction_t running_txn; + handle_t handle; + struct buffer_head *fc_wbuf[TEST_MAX_FC_BUFS]; + struct buffer_head fc_bhs[TEST_MAX_FC_BUFS]; + char fc_buf_data[TEST_MAX_FC_BUFS][TEST_BLK_SIZE] __aligned(8); + + struct fc_mock_inode_slot inodes[TEST_MAX_INODES]; + struct fc_mock_block blocks[TEST_MAX_BLOCKS]; + + /* Shrinker callbacks saved during init */ + unsigned long (*shrinker_count)(struct shrinker *shrink, + struct shrink_control *sc); + unsigned long (*shrinker_scan)(struct shrinker *shrink, + struct shrink_control *sc); + bool es_shrinker_inited; + + /* Fault injection and call tracking */ + int journal_mode; + int fail_get_inode_loc; + int fail_get_inode_loc_noio; + int fail_get_fc_inode_loc; + int fail_dirty_metadata; + int fail_dirty_metadata_on_call; + int dirty_metadata_calls; + bool fail_sync_dirty_buffer; + int fail_mark_inode_used; + int fail_iget; + int fail_iget_on_call; + unsigned long fail_iget_ino; + int iget_calls; + int fail_map_blocks; + int force_map_blocks_ret; + ext4_fsblk_t force_map_pblk; + unsigned int force_map_flags; + int fail_find_extent; + int fail_insert_extent; + int fail_fc_get_buf; + int fail_fc_get_buf_on_call; + int fc_get_buf_calls; + bool fail_fc_wait_bufs; + int submit_inode_data_err; + + unsigned int fc_submit_bh_calls; + unsigned int fc_submit_tail_calls; + unsigned int fc_flush_calls; + struct block_device *last_flushed_bdev; + unsigned int mark_inode_used_calls; + int last_marked_ino; + + struct fc_bb_mark bb_marks[TEST_MAX_BB_MARKS]; + unsigned int nr_bb_marks; + + /* Custom ES lookup stub override */ + bool use_custom_es_lookup; + struct extent_status custom_es; + int custom_es_ret; +}; + +#ifdef CONFIG_QUOTA +static struct dquot __rcu **fc_test_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} + +static qsize_t *fc_test_get_reserved_space(struct inode *inode) +{ + return &EXT4_I(inode)->i_reserved_quota; +} + +static const struct dquot_operations fc_test_qops = { + .get_reserved_space = fc_test_get_reserved_space, +}; +#endif + +static const struct super_operations fc_test_sops = { +#ifdef CONFIG_QUOTA + .get_dquots = fc_test_get_dquots, +#endif +}; + +static unsigned long fc_dummy_shrinker_count(struct shrinker *shrink, + struct shrink_control *sc) +{ + return 0; +} + +static unsigned long fc_dummy_shrinker_scan(struct shrinker *shrink, + struct shrink_control *sc) +{ + return SHRINK_STOP; +} + +static int fc_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static int fc_set_anon(struct super_block *sb, struct fs_context *fc) +{ + return set_anon_super_fc(sb, fc); +} + +static struct file_system_type fc_fs_type = { + .name = "fast_commit_test", + .init_fs_context = fc_init_fs_context, + .kill_sb = kill_anon_super, +}; + +/* --- Mock Inode, Block, and Dentry Helpers --- */ + +static struct fc_mock_inode_slot *find_slot_by_ino(struct fc_test_ctx *ctx, + unsigned long ino) +{ + int i; + + for (i = 0; i < TEST_MAX_INODES; i++) { + if (ctx->inodes[i].allocated && + ctx->inodes[i].ei.vfs_inode.i_ino == ino) + return &ctx->inodes[i]; + } + return NULL; +} + +static struct fc_mock_inode_slot *find_slot(struct fc_test_ctx *ctx, + struct inode *inode) +{ + return find_slot_by_ino(ctx, inode->i_ino); +} + +static struct inode *get_mock_inode(struct fc_test_ctx *ctx, unsigned long ino) +{ + struct fc_mock_inode_slot *slot = find_slot_by_ino(ctx, ino); + + return slot ? &slot->ei.vfs_inode : NULL; +} + +static struct fc_mock_block *get_mock_block(struct fc_test_ctx *ctx, + ext4_fsblk_t pblk) +{ + unsigned long idx; + + if (pblk < TEST_FIRST_PBLK) + return NULL; + idx = pblk - TEST_FIRST_PBLK; + if (idx >= TEST_MAX_BLOCKS) + return NULL; + return &ctx->blocks[idx]; +} + +static ext4_fsblk_t alloc_mock_pblk(struct fc_test_ctx *ctx) +{ + int i; + + for (i = 0; i < TEST_MAX_BLOCKS; i++) { + if (!ctx->blocks[i].in_use) { + ctx->blocks[i].in_use = true; + memset(ctx->blocks[i].data, 0, TEST_BLK_SIZE); + set_buffer_uptodate(&ctx->blocks[i].bh); + clear_buffer_verified(&ctx->blocks[i].bh); + return TEST_FIRST_PBLK + i; + } + } + return 0; +} + +static void init_mock_inode_slot(struct fc_test_ctx *ctx, + struct fc_mock_inode_slot *slot, + unsigned long ino, umode_t mode) +{ + struct inode *inode = &slot->ei.vfs_inode; + struct ext4_inode *raw_inode; + + memset(slot, 0, sizeof(*slot)); + slot->allocated = true; + + inode->i_sb = ctx->sb; + inode->i_ino = ino; + inode->i_mode = mode; + inode->i_blkbits = TEST_BLK_BITS; + inode->i_flags |= S_NOQUOTA; + inode->i_mapping = &inode->i_data; + set_nlink(inode, S_ISDIR(mode) ? 2 : 1); + atomic_set(&inode->i_count, 1); + + spin_lock_init(&inode->i_lock); + i_size_ordered_init(inode); + init_rwsem(&inode->i_rwsem); + init_rwsem(&inode->i_data.invalidate_lock); + INIT_LIST_HEAD(&inode->i_io_list); + INIT_LIST_HEAD(&inode->i_wb_list); + INIT_LIST_HEAD(&inode->i_lru); + INIT_HLIST_NODE(&inode->i_hash); + inode_state_set_raw(inode, I_DIRTY); + + init_rwsem(&slot->ei.xattr_sem); + init_rwsem(&slot->ei.i_data_sem); + INIT_LIST_HEAD(&slot->ei.i_orphan); + spin_lock_init(&slot->ei.i_fc_lock); + spin_lock_init(&slot->ei.i_raw_lock); + spin_lock_init(&slot->ei.i_block_reservation_lock); + ext4_es_init_tree(&slot->ei.i_es_tree); + ext4_init_pending_tree(&slot->ei.i_pending_tree); + rwlock_init(&slot->ei.i_es_lock); + INIT_LIST_HEAD(&slot->ei.i_es_list); + ext4_fc_init_inode(inode); + + slot->ei.i_extra_isize = TEST_EXTRA_ISIZE; + slot->ei.i_csum_seed = TEST_CSUM_SEED ^ (u32)ino; + slot->ei.i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + + jbd2_journal_init_jbd_inode(&slot->jinode, inode); + slot->ei.jinode = &slot->jinode; + + slot->iloc_bh.b_data = slot->raw_buf; + slot->iloc_bh.b_size = TEST_BLK_SIZE; + slot->iloc_bh.b_blocknr = 10 + ino; + slot->iloc_bh.b_bdev = &ctx->bdev; + atomic_set(&slot->iloc_bh.b_count, 1); + set_buffer_uptodate(&slot->iloc_bh); + set_buffer_mapped(&slot->iloc_bh); + + raw_inode = (struct ext4_inode *)slot->raw_buf; + raw_inode->i_mode = cpu_to_le16(mode); + raw_inode->i_links_count = cpu_to_le16(inode->i_nlink); + raw_inode->i_extra_isize = cpu_to_le16(TEST_EXTRA_ISIZE); + if (S_ISREG(mode)) { + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + ext4_ext_tree_init(NULL, inode); + raw_inode->i_flags = cpu_to_le32(EXT4_EXTENTS_FL); + memcpy(raw_inode->i_block, slot->ei.i_data, + sizeof(raw_inode->i_block)); + } +} + +static void init_mock_dentry(struct dentry *dentry, struct dentry *parent, + const char *name, struct inode *inode, + struct super_block *sb) +{ + memset(dentry, 0, sizeof(*dentry)); + spin_lock_init(&dentry->d_lock); + seqcount_spinlock_init(&dentry->d_seq, &dentry->d_lock); + INIT_HLIST_NODE(&dentry->d_sib); + INIT_HLIST_HEAD(&dentry->d_children); + INIT_HLIST_BL_NODE(&dentry->d_hash); + dentry->d_parent = parent ? parent : dentry; + dentry->d_sb = sb; + strscpy((char *)dentry->d_shortname.string, name, + sizeof(dentry->d_shortname.string)); + dentry->__d_name.name = dentry->d_shortname.string; + dentry->__d_name.len = strlen(name); + if (inode) { + dentry->d_inode = inode; + dentry->d_flags = S_ISDIR(inode->i_mode) ? + DCACHE_DIRECTORY_TYPE : DCACHE_REGULAR_TYPE; + } else { + dentry->d_flags = DCACHE_MISS_TYPE; + } +} + +static void sync_inode_to_raw(struct fc_mock_inode_slot *slot) +{ + struct inode *inode = &slot->ei.vfs_inode; + struct ext4_inode *raw = (struct ext4_inode *)slot->raw_buf; + + raw->i_mode = cpu_to_le16(inode->i_mode); + raw->i_links_count = cpu_to_le16(inode->i_nlink); + raw->i_size_lo = cpu_to_le32(lower_32_bits(inode->i_size)); + raw->i_size_high = cpu_to_le32(upper_32_bits(inode->i_size)); + raw->i_flags = cpu_to_le32(slot->ei.i_flags); + raw->i_generation = cpu_to_le32(inode->i_generation); + raw->i_extra_isize = cpu_to_le16(slot->ei.i_extra_isize); + memcpy(raw->i_block, slot->ei.i_data, sizeof(raw->i_block)); +} + +/* --- KUnit Static Stubs --- */ + +static int stub_inode_journal_mode(struct inode *inode) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + + return ctx->journal_mode; +} + +static void stub_da_update_reserve_space(struct inode *inode, int used, + int quota_claim) +{ +} + +static void stub_da_release_space(struct inode *inode, int to_free) +{ +} + +static int stub_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + struct fc_mock_inode_slot *slot; + + if (ctx->fail_get_inode_loc) + return ctx->fail_get_inode_loc; + + slot = find_slot(ctx, inode); + if (!slot) + return -ENOENT; + + get_bh(&slot->iloc_bh); + iloc->bh = &slot->iloc_bh; + iloc->offset = 0; + iloc->block_group = 0; + return 0; +} + +static int stub_get_inode_loc_noio(struct inode *inode, struct ext4_iloc *iloc) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + struct fc_mock_inode_slot *slot; + + if (ctx->fail_get_inode_loc_noio) + return ctx->fail_get_inode_loc_noio; + + slot = find_slot(ctx, inode); + if (!slot) + return -EAGAIN; + + get_bh(&slot->iloc_bh); + iloc->bh = &slot->iloc_bh; + iloc->offset = 0; + iloc->block_group = 0; + return 0; +} + +static int stub_get_fc_inode_loc(struct super_block *sb, unsigned long ino, + struct ext4_iloc *iloc) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + struct fc_mock_inode_slot *slot; + + if (ctx->fail_get_fc_inode_loc) + return ctx->fail_get_fc_inode_loc; + + slot = find_slot_by_ino(ctx, ino); + if (!slot) + return -ENOENT; + + get_bh(&slot->iloc_bh); + iloc->bh = &slot->iloc_bh; + iloc->offset = 0; + iloc->block_group = 0; + return 0; +} + +static int stub_handle_dirty_metadata(const char *where, unsigned int line, + handle_t *handle, struct inode *inode, + struct buffer_head *bh) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + + ctx->dirty_metadata_calls++; + if (ctx->fail_dirty_metadata_on_call > 0 && + ctx->dirty_metadata_calls == ctx->fail_dirty_metadata_on_call) + return ctx->fail_dirty_metadata; + if (ctx->fail_dirty_metadata_on_call == 0 && ctx->fail_dirty_metadata) + return ctx->fail_dirty_metadata; + + if (ctx->fail_sync_dirty_buffer) { + /* + * __sync_dirty_buffer() checks test_clear_buffer_dirty(bh) + * and returns -EIO without submitting a bio if !buffer_mapped. + */ + set_buffer_dirty(bh); + clear_buffer_mapped(bh); + } else { + clear_buffer_dirty(bh); + set_buffer_mapped(bh); + } + return 0; +} + +static int stub_mark_iloc_dirty(handle_t *handle, struct inode *inode, + struct ext4_iloc *iloc) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + struct fc_mock_inode_slot *slot = find_slot(ctx, inode); + + if (slot) + sync_inode_to_raw(slot); + brelse(iloc->bh); + return 0; +} + +static int stub_mark_inode_dirty(handle_t *handle, struct inode *inode, + const char *func, unsigned int line) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + struct fc_mock_inode_slot *slot = find_slot(ctx, inode); + + if (slot) + sync_inode_to_raw(slot); + return 0; +} + +static int stub_ext_dirty(const char *where, unsigned int line, + handle_t *handle, struct inode *inode, + struct ext4_ext_path *path) +{ + return 0; +} + +static void stub_free_blocks(handle_t *handle, struct inode *inode, + struct buffer_head *bh, ext4_fsblk_t block, + unsigned long count, int flags) +{ +} + +static int stub_orphan_add(handle_t *handle, struct inode *inode) +{ + return 0; +} + +static int stub_orphan_del(handle_t *handle, struct inode *inode) +{ + return 0; +} + +static int stub_mark_inode_used(struct super_block *sb, int ino) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + + ctx->mark_inode_used_calls++; + ctx->last_marked_ino = ino; + if (ctx->fail_mark_inode_used) + return ctx->fail_mark_inode_used; + return 0; +} + +static void stub_mb_mark_bb(struct super_block *sb, ext4_fsblk_t block, + int len, bool state) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + + if (ctx->nr_bb_marks < TEST_MAX_BB_MARKS) { + ctx->bb_marks[ctx->nr_bb_marks].block = block; + ctx->bb_marks[ctx->nr_bb_marks].len = len; + ctx->bb_marks[ctx->nr_bb_marks].state = state; + } + ctx->nr_bb_marks++; +} + +static struct inode *stub_ext4_iget(struct super_block *sb, unsigned long ino, + ext4_iget_flags flags, + const char *function, unsigned int line) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + struct fc_mock_inode_slot *slot; + struct inode *inode; + struct ext4_inode *raw; + + ctx->iget_calls++; + if (ctx->fail_iget_on_call > 0 && + ctx->iget_calls == ctx->fail_iget_on_call) + return ERR_PTR(ctx->fail_iget ? ctx->fail_iget : -ENOENT); + if (ctx->fail_iget_ino && ino == ctx->fail_iget_ino) + return ERR_PTR(ctx->fail_iget ? ctx->fail_iget : -ENOENT); + if (ctx->fail_iget && !ctx->fail_iget_on_call && !ctx->fail_iget_ino) + return ERR_PTR(ctx->fail_iget); + + slot = find_slot_by_ino(ctx, ino); + if (!slot) + return ERR_PTR(-ENOENT); + + inode = &slot->ei.vfs_inode; + raw = (struct ext4_inode *)slot->raw_buf; + if (raw->i_mode) { + inode->i_mode = le16_to_cpu(raw->i_mode); + set_nlink(inode, le16_to_cpu(raw->i_links_count)); + inode->i_generation = le32_to_cpu(raw->i_generation); + i_size_write(inode, ext4_isize(sb, raw)); + slot->ei.i_flags = le32_to_cpu(raw->i_flags); + if (slot->ei.i_flags & EXT4_INLINE_DATA_FL) { + ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + memcpy(slot->ei.i_data, raw->i_block, + sizeof(raw->i_block)); + } else if (slot->ei.i_flags & EXT4_EXTENTS_FL) { + struct ext4_extent_header *eh = + (struct ext4_extent_header *)raw->i_block; + struct ext4_extent_header *ieh = + ext_inode_hdr(&slot->ei.vfs_inode); + + if (eh->eh_magic == EXT4_EXT_MAGIC && + ieh->eh_entries == 0) + memcpy(slot->ei.i_data, raw->i_block, + sizeof(raw->i_block)); + } + } + + atomic_inc(&inode->i_count); + return inode; +} + +static int stub_map_blocks(handle_t *handle, struct inode *inode, + struct ext4_map_blocks *map, int flags) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + struct fc_mock_inode_slot *slot; + ext4_fsblk_t pblk; + + if (ctx->fail_map_blocks) + return ctx->fail_map_blocks; + if (ctx->force_map_blocks_ret) { + map->m_pblk = ctx->force_map_pblk; + map->m_flags = ctx->force_map_flags; + if (ctx->force_map_blocks_ret > 0) + map->m_len = ctx->force_map_blocks_ret; + return ctx->force_map_blocks_ret; + } + + if (S_ISREG(inode->i_mode) && + ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) { + kunit_deactivate_static_stub(test, ext4_map_blocks); + int ret = ext4_ext_map_blocks(handle, inode, map, flags); + + kunit_activate_static_stub(test, ext4_map_blocks, + stub_map_blocks); + return ret; + } + + slot = find_slot(ctx, inode); + if (!slot || map->m_lblk >= TEST_MAX_LBLOCKS) + return -EFSCORRUPTED; + + pblk = slot->lblk_to_pblk[map->m_lblk]; + if (pblk) { + map->m_pblk = pblk; + map->m_len = 1; + map->m_flags = EXT4_MAP_MAPPED; + return 1; + } + + if (!(flags & EXT4_GET_BLOCKS_CREATE)) { + map->m_pblk = 0; + map->m_flags = 0; + return 0; + } + + pblk = alloc_mock_pblk(ctx); + if (!pblk) + return -ENOSPC; + + slot->lblk_to_pblk[map->m_lblk] = pblk; + map->m_pblk = pblk; + map->m_len = 1; + map->m_flags = EXT4_MAP_MAPPED | EXT4_MAP_NEW; + return 1; +} + +static struct buffer_head *stub_ext4_getblk(handle_t *handle, + struct inode *inode, + ext4_lblk_t block, int map_flags) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + struct fc_mock_inode_slot *slot; + struct fc_mock_block *blk; + ext4_fsblk_t pblk; + + slot = find_slot(ctx, inode); + if (!slot || block >= TEST_MAX_LBLOCKS) + return ERR_PTR(-EFSCORRUPTED); + + pblk = slot->lblk_to_pblk[block]; + if (!pblk) { + if (!(map_flags & EXT4_GET_BLOCKS_CREATE)) + return NULL; + pblk = alloc_mock_pblk(ctx); + if (!pblk) + return ERR_PTR(-ENOSPC); + slot->lblk_to_pblk[block] = pblk; + } + + blk = get_mock_block(ctx, pblk); + if (!blk) + return ERR_PTR(-EFSCORRUPTED); + + get_bh(&blk->bh); + return &blk->bh; +} + +static struct ext4_ext_path *stub_find_extent(struct inode *inode, + ext4_lblk_t block, + struct ext4_ext_path *path, + int flags) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + struct ext4_ext_path *ret; + + if (ctx->fail_find_extent) + return ERR_PTR(ctx->fail_find_extent); + + kunit_deactivate_static_stub(test, ext4_find_extent); + ret = ext4_find_extent(inode, block, path, flags); + kunit_activate_static_stub(test, ext4_find_extent, stub_find_extent); + return ret; +} + +static struct ext4_ext_path *stub_insert_extent(handle_t *handle, + struct inode *inode, + struct ext4_ext_path *path, + struct ext4_extent *newext, + int gb_flags) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + struct ext4_ext_path *ret; + + if (ctx->fail_insert_extent) { + ext4_free_ext_path(path); + return ERR_PTR(ctx->fail_insert_extent); + } + + kunit_deactivate_static_stub(test, ext4_ext_insert_extent); + ret = ext4_ext_insert_extent(handle, inode, path, newext, gb_flags); + kunit_activate_static_stub(test, ext4_ext_insert_extent, + stub_insert_extent); + return ret; +} + +static int stub_es_lookup_extent(struct inode *inode, ext4_lblk_t lblk, + ext4_lblk_t *next_lblk, + struct extent_status *es, u64 *pseq) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + int ret; + + if (ctx->use_custom_es_lookup) { + *es = ctx->custom_es; + return ctx->custom_es_ret; + } + + kunit_deactivate_static_stub(test, ext4_es_lookup_extent); + ret = ext4_es_lookup_extent(inode, lblk, next_lblk, es, pseq); + kunit_activate_static_stub(test, ext4_es_lookup_extent, + stub_es_lookup_extent); + return ret; +} + +static int stub_fc_get_buf(journal_t *journal, struct buffer_head **bh_out) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + struct buffer_head *bh; + int fc_off; + + *bh_out = NULL; + ctx->fc_get_buf_calls++; + if (ctx->fail_fc_get_buf_on_call > 0 && + ctx->fc_get_buf_calls == ctx->fail_fc_get_buf_on_call) + return ctx->fail_fc_get_buf ? ctx->fail_fc_get_buf : -ENOSPC; + if (ctx->fail_fc_get_buf && !ctx->fail_fc_get_buf_on_call) + return ctx->fail_fc_get_buf; + + if (journal->j_fc_off + journal->j_fc_first >= journal->j_fc_last) + return -EINVAL; + + fc_off = journal->j_fc_off; + if (fc_off >= TEST_MAX_FC_BUFS) + return -ENOSPC; + + journal->j_fc_off++; + bh = &ctx->fc_bhs[fc_off]; + memset(bh->b_data, 0, journal->j_blocksize); + set_buffer_uptodate(bh); + clear_buffer_write_io_error(bh); + get_bh(bh); + journal->j_fc_wbuf[fc_off] = bh; + *bh_out = bh; + return 0; +} + +static void stub_fc_submit_bh(struct super_block *sb, bool is_tail) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + struct buffer_head *bh = EXT4_SB(sb)->s_fc_bh; + + ctx->fc_submit_bh_calls++; + if (is_tail) + ctx->fc_submit_tail_calls++; + set_buffer_dirty(bh); + if (ctx->fail_fc_wait_bufs) { + clear_buffer_uptodate(bh); + set_buffer_write_io_error(bh); + } else { + set_buffer_uptodate(bh); + clear_buffer_write_io_error(bh); + } + EXT4_SB(sb)->s_fc_bh = NULL; +} + +static int stub_fc_issue_flush(struct block_device *bdev) +{ + struct kunit *test = kunit_get_current_test(); + struct fc_test_ctx *ctx = test->priv; + + ctx->fc_flush_calls++; + ctx->last_flushed_bdev = bdev; + return 0; +} + +static int mock_submit_inode_data_buffers(struct jbd2_inode *jinode) +{ + struct inode *inode = jinode->i_vfs_inode; + struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); + struct fc_test_ctx *ctx = container_of(sbi->s_es, struct fc_test_ctx, es); + + return ctx->submit_inode_data_err; +} + +/* + * Wrapper for journal->j_fc_cleanup_callback used during ext4_fc_commit() tests. + * Calls the real ext4_fc_cleanup() and, on fallback commits (tid != 0), marks + * the mock transaction as committed so jbd2_complete_transaction() returns + * immediately without waiting for a kjournald2 thread. + */ +static void test_j_fc_cleanup_cb(journal_t *journal, int full, tid_t tid) +{ + ext4_fc_cleanup_test(journal, full, tid); + if (!full && tid != 0) { + write_lock(&journal->j_state_lock); + journal->j_commit_request = tid; + journal->j_commit_sequence = tid; + journal->j_flags &= ~JBD2_FULL_COMMIT_ONGOING; + write_unlock(&journal->j_state_lock); + } +} + +/* --- Suite Setup & Teardown --- */ + +static void fc_cleanup_all(void *priv) +{ + struct fc_test_ctx *ctx = priv; + int i; + + ctx->sbi->s_mount_state &= ~EXT4_FC_REPLAY; + if (ctx->journal.j_private) { + /* + * Run cleanup twice: the first pass frees FC_Q_MAIN and + * splices FC_Q_STAGING onto FC_Q_MAIN; the second frees the + * spliced staging entries. + */ + ext4_fc_cleanup_test(&ctx->journal, 1, 999999); + ext4_fc_cleanup_test(&ctx->journal, 1, 999999); + } + ext4_fc_replay_cleanup(ctx->sb); + + for (i = 0; i < TEST_MAX_INODES; i++) { + if (!ctx->inodes[i].allocated) + continue; + down_write(&ctx->inodes[i].ei.i_data_sem); + ext4_es_remove_extent(&ctx->inodes[i].ei.vfs_inode, 0, + EXT_MAX_BLOCKS); + up_write(&ctx->inodes[i].ei.i_data_sem); + ext4_fc_free_inode_snap_test(&ctx->inodes[i].ei.vfs_inode); + } + + if (ctx->es_shrinker_inited) { + ext4_es_unregister_shrinker(ctx->sbi); + ext4_es_destroy_stats(ctx->sbi); + } + deactivate_super(ctx->sb); +} + +static int fast_commit_test_init(struct kunit *test) +{ + static struct lock_class_key fc_test_commit_key; + struct fc_test_ctx *ctx; + struct ext4_sb_info *sbi; + struct super_block *sb; + struct fs_context *fc; + int i, err; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx); + + sbi = kunit_kzalloc(test, sizeof(*sbi), GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, sbi); + + fc = fs_context_for_mount(&fc_fs_type, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(fc)); + sb = sget_fc(fc, NULL, fc_set_anon); + put_fs_context(fc); + KUNIT_ASSERT_FALSE(test, IS_ERR(sb)); + + ctx->sb = sb; + ctx->sbi = sbi; + test->priv = ctx; + + /* Superblock and ext4_sb_info setup */ + sb->s_blocksize = TEST_BLK_SIZE; + sb->s_blocksize_bits = TEST_BLK_BITS; + sb->s_maxbytes = MAX_LFS_FILESIZE; + sb->s_time_gran = 1; + sb->s_bdi = &noop_backing_dev_info; + sb->s_fs_info = sbi; + sb->s_op = &fc_test_sops; +#ifdef CONFIG_QUOTA + sb->dq_op = &fc_test_qops; +#endif +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; +#endif + strscpy(sb->s_id, "ext4-fc-test", sizeof(sb->s_id)); + + ctx->bdev.bd_mapping = &ctx->bd_mapping; + sb->s_bdev = &ctx->bdev; + + ctx->es.s_magic = cpu_to_le16(EXT4_SUPER_MAGIC); + ctx->es.s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + ctx->es.s_first_ino = cpu_to_le32(EXT4_GOOD_OLD_FIRST_INO); + ctx->es.s_inode_size = cpu_to_le16(TEST_INODE_SIZE); + ctx->es.s_inodes_count = cpu_to_le32(1024); + ctx->es.s_first_data_block = cpu_to_le32(1); + ctx->es.s_feature_compat = + cpu_to_le32(EXT4_FEATURE_COMPAT_DIR_INDEX | + EXT4_FEATURE_COMPAT_FAST_COMMIT); + ctx->es.s_feature_incompat = + cpu_to_le32(EXT4_FEATURE_INCOMPAT_FILETYPE | + EXT4_FEATURE_INCOMPAT_EXTENTS | + EXT4_FEATURE_INCOMPAT_INLINE_DATA); + ctx->es.s_feature_ro_compat = + cpu_to_le32(EXT4_FEATURE_RO_COMPAT_METADATA_CSUM); + + ctx->sb_bh.b_data = (char *)&ctx->es; + ctx->sb_bh.b_size = sizeof(ctx->es); + ctx->sb_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->sb_bh.b_count, 1); + set_buffer_uptodate(&ctx->sb_bh); + + sbi->s_sb = sb; + sbi->s_es = &ctx->es; + sbi->s_sbh = &ctx->sb_bh; + sbi->s_first_ino = EXT4_GOOD_OLD_FIRST_INO; + sbi->s_inode_size = TEST_INODE_SIZE; + sbi->s_want_extra_isize = TEST_EXTRA_ISIZE; + sbi->s_desc_size = EXT4_MIN_DESC_SIZE; + sbi->s_blocks_per_group = 32768; + sbi->s_inodes_per_group = 1024; + sbi->s_inodes_per_block = TEST_BLK_SIZE / TEST_INODE_SIZE; + sbi->s_csum_seed = TEST_CSUM_SEED; + sbi->s_cluster_bits = 0; + sbi->s_cluster_ratio = 1; + set_opt(sb, ERRORS_CONT); + set_opt2(sb, JOURNAL_FAST_COMMIT); + + mutex_init(&sbi->s_fc_lock); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_STAGING]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_STAGING]); + atomic_set(&sbi->s_fc_subtid, 0); + INIT_LIST_HEAD(&sbi->s_orphan); + mutex_init(&sbi->s_orphan_lock); + spin_lock_init(&sbi->s_bdev_wb_lock); + spin_lock_init(&sbi->s_error_lock); + spin_lock_init(&sbi->s_md_lock); + ratelimit_state_init(&sbi->s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + up_write(&sb->s_umount); + + err = kunit_add_action_or_reset(test, fc_cleanup_all, ctx); + KUNIT_ASSERT_EQ(test, err, 0); + + err = ext4_es_register_shrinker(sbi); + KUNIT_ASSERT_EQ(test, err, 0); + ctx->es_shrinker_inited = true; + ctx->shrinker_count = sbi->s_es_shrinker->count_objects; + ctx->shrinker_scan = sbi->s_es_shrinker->scan_objects; + WRITE_ONCE(sbi->s_es_shrinker->count_objects, fc_dummy_shrinker_count); + WRITE_ONCE(sbi->s_es_shrinker->scan_objects, fc_dummy_shrinker_scan); + + /* Mock journal, running transaction, and handle setup */ + rwlock_init(&ctx->journal.j_state_lock); + spin_lock_init(&ctx->journal.j_list_lock); + mutex_init(&ctx->journal.j_barrier); + lockdep_init_map(&ctx->journal.j_trans_commit_map, "jbd2_handle", + &fc_test_commit_key, 0); + init_waitqueue_head(&ctx->journal.j_wait_transaction_locked); + init_waitqueue_head(&ctx->journal.j_wait_done_commit); + init_waitqueue_head(&ctx->journal.j_wait_commit); + init_waitqueue_head(&ctx->journal.j_wait_updates); + init_waitqueue_head(&ctx->journal.j_wait_reserved); + init_waitqueue_head(&ctx->journal.j_fc_wait); + atomic_set(&ctx->journal.j_reserved_credits, 0); + ctx->journal.j_private = sb; + ctx->journal.j_blocksize = TEST_BLK_SIZE; + ctx->journal.j_dev = &ctx->bdev; + ctx->journal.j_fs_dev = &ctx->bdev; + ctx->journal.j_flags = JBD2_BARRIER; + ctx->journal.j_task = current; + ctx->journal.j_fc_first = 100; + ctx->journal.j_fc_last = 100 + TEST_MAX_FC_BUFS; + ctx->journal.j_fc_off = 0; + ctx->journal.j_fc_wbuf = ctx->fc_wbuf; + ctx->journal.j_stats.ts_tid = 1; + ctx->journal.j_commit_sequence = 9; + ctx->journal.j_commit_request = 9; + ctx->journal.j_submit_inode_data_buffers = + mock_submit_inode_data_buffers; + + ctx->running_txn.t_tid = 10; + ctx->running_txn.t_state = T_RUNNING; + atomic_set(&ctx->running_txn.t_updates, 0); + ctx->journal.j_running_transaction = &ctx->running_txn; + ctx->handle.h_transaction = &ctx->running_txn; + + sbi->s_journal = &ctx->journal; + ext4_fc_init(sb, &ctx->journal); + ctx->journal.j_fc_cleanup_callback = test_j_fc_cleanup_cb; + + for (i = 0; i < TEST_MAX_FC_BUFS; i++) { + struct buffer_head *bh = &ctx->fc_bhs[i]; + + bh->b_data = ctx->fc_buf_data[i]; + bh->b_size = TEST_BLK_SIZE; + bh->b_blocknr = 500 + i; + bh->b_bdev = &ctx->bdev; + atomic_set(&bh->b_count, 1); + set_buffer_uptodate(bh); + set_buffer_mapped(bh); + } + + for (i = 0; i < TEST_MAX_BLOCKS; i++) { + struct buffer_head *bh = &ctx->blocks[i].bh; + + bh->b_data = ctx->blocks[i].data; + bh->b_size = TEST_BLK_SIZE; + bh->b_blocknr = TEST_FIRST_PBLK + i; + bh->b_bdev = &ctx->bdev; + atomic_set(&bh->b_count, 1); + set_buffer_uptodate(bh); + set_buffer_mapped(bh); + } + + ctx->journal_mode = EXT4_INODE_ORDERED_DATA_MODE; + + kunit_activate_static_stub(test, ext4_inode_journal_mode, + stub_inode_journal_mode); + kunit_activate_static_stub(test, ext4_da_update_reserve_space, + stub_da_update_reserve_space); + kunit_activate_static_stub(test, ext4_da_release_space, + stub_da_release_space); + kunit_activate_static_stub(test, ext4_get_inode_loc, + stub_get_inode_loc); + kunit_activate_static_stub(test, ext4_get_inode_loc_noio, + stub_get_inode_loc_noio); + kunit_activate_static_stub(test, ext4_get_fc_inode_loc, + stub_get_fc_inode_loc); + kunit_activate_static_stub(test, __ext4_handle_dirty_metadata, + stub_handle_dirty_metadata); + kunit_activate_static_stub(test, ext4_mark_iloc_dirty, + stub_mark_iloc_dirty); + kunit_activate_static_stub(test, __ext4_mark_inode_dirty, + stub_mark_inode_dirty); + kunit_activate_static_stub(test, __ext4_ext_dirty, + stub_ext_dirty); + kunit_activate_static_stub(test, ext4_free_blocks, + stub_free_blocks); + kunit_activate_static_stub(test, ext4_orphan_add, + stub_orphan_add); + kunit_activate_static_stub(test, ext4_orphan_del, + stub_orphan_del); + kunit_activate_static_stub(test, ext4_mark_inode_used, + stub_mark_inode_used); + kunit_activate_static_stub(test, ext4_mb_mark_bb, + stub_mb_mark_bb); + kunit_activate_static_stub(test, __ext4_iget, + stub_ext4_iget); + kunit_activate_static_stub(test, ext4_map_blocks, + stub_map_blocks); + kunit_activate_static_stub(test, ext4_getblk, + stub_ext4_getblk); + kunit_activate_static_stub(test, ext4_find_extent, + stub_find_extent); + kunit_activate_static_stub(test, ext4_ext_insert_extent, + stub_insert_extent); + kunit_activate_static_stub(test, ext4_es_lookup_extent, + stub_es_lookup_extent); + kunit_activate_static_stub(test, ext4_fc_get_buf, + stub_fc_get_buf); + kunit_activate_static_stub(test, ext4_fc_submit_bh, + stub_fc_submit_bh); + kunit_activate_static_stub(test, ext4_fc_issue_flush, + stub_fc_issue_flush); + + init_mock_inode_slot(ctx, &ctx->inodes[0], TEST_ROOT_INO, + S_IFDIR | 0755); + init_mock_inode_slot(ctx, &ctx->inodes[1], TEST_DIR_INO, + S_IFDIR | 0755); + init_mock_inode_slot(ctx, &ctx->inodes[2], TEST_FILE1_INO, + S_IFREG | 0644); + init_mock_inode_slot(ctx, &ctx->inodes[3], TEST_FILE2_INO, + S_IFREG | 0644); + init_mock_inode_slot(ctx, &ctx->inodes[4], TEST_SUBDIR_INO, + S_IFDIR | 0755); + + return 0; +} + +/* ========================================================================= + * 1. Initialization, Eligibility, and Snapshot Stat Helpers + * ========================================================================= + */ + +static void test_fc_init_and_eligibility(struct kunit *test) +{ + struct fc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct inode *inode = get_mock_inode(ctx, TEST_FILE1_INO); + struct ext4_inode_info *ei = EXT4_I(inode); + journal_t *tmp_journal; + atomic64_t max_stat = ATOMIC64_INIT(0); + int snap_err = EXT4_FC_SNAP_ERR_NONE; + + tmp_journal = kunit_kzalloc(test, sizeof(*tmp_journal), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, tmp_journal); + + /* + * 1) ext4_fc_init sets j_fc_replay_callback unconditionally, but sets + * j_fc_cleanup_callback only when JOURNAL_FAST_COMMIT is enabled. + */ + clear_opt2(sb, JOURNAL_FAST_COMMIT); + ext4_fc_init(sb, tmp_journal); + KUNIT_EXPECT_NOT_NULL(test, tmp_journal->j_fc_replay_callback); + KUNIT_EXPECT_NULL(test, tmp_journal->j_fc_cleanup_callback); + + set_opt2(sb, JOURNAL_FAST_COMMIT); + ext4_fc_init(sb, tmp_journal); + KUNIT_EXPECT_NOT_NULL(test, tmp_journal->j_fc_replay_callback); + KUNIT_EXPECT_NOT_NULL(test, tmp_journal->j_fc_cleanup_callback); + + /* 2) ext4_fc_init_inode clears state and resets ranges */ + ei->i_fc_lblk_start = 42; + ei->i_fc_lblk_len = 10; + ext4_set_inode_state(inode, EXT4_STATE_FC_COMMITTING); + ext4_set_inode_state(inode, EXT4_STATE_FC_REQUEUE); + ext4_fc_init_inode(inode); + KUNIT_EXPECT_EQ(test, ei->i_fc_lblk_start, 0U); + KUNIT_EXPECT_EQ(test, ei->i_fc_lblk_len, 0U); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(inode, EXT4_STATE_FC_COMMITTING)); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(inode, EXT4_STATE_FC_REQUEUE)); + KUNIT_EXPECT_TRUE(test, list_empty(&ei->i_fc_list)); + KUNIT_EXPECT_TRUE(test, list_empty(&ei->i_fc_dilist)); + KUNIT_EXPECT_NULL(test, ei->i_fc_snap); + + /* 3) ext4_fc_disabled and ext4_fc_eligible transitions */ + KUNIT_EXPECT_FALSE(test, ext4_fc_disabled_test(sb)); + KUNIT_EXPECT_TRUE(test, ext4_fc_eligible_test(sb)); + + ctx->sbi->s_mount_state |= EXT4_FC_REPLAY; + KUNIT_EXPECT_TRUE(test, ext4_fc_disabled_test(sb)); + KUNIT_EXPECT_FALSE(test, ext4_fc_eligible_test(sb)); + ctx->sbi->s_mount_state &= ~EXT4_FC_REPLAY; + + ext4_set_mount_flag(sb, EXT4_MF_FC_INELIGIBLE); + KUNIT_EXPECT_FALSE(test, ext4_fc_disabled_test(sb)); + KUNIT_EXPECT_FALSE(test, ext4_fc_eligible_test(sb)); + ext4_clear_mount_flag(sb, EXT4_MF_FC_INELIGIBLE); + + clear_opt2(sb, JOURNAL_FAST_COMMIT); + KUNIT_EXPECT_TRUE(test, ext4_fc_disabled_test(sb)); + KUNIT_EXPECT_FALSE(test, ext4_fc_eligible_test(sb)); + set_opt2(sb, JOURNAL_FAST_COMMIT); + + /* 4) ext4_fc_set_snap_err preserves first error */ + ext4_fc_set_snap_err_test(&snap_err, EXT4_FC_SNAP_ERR_ES_MISS); + KUNIT_EXPECT_EQ(test, snap_err, (int)EXT4_FC_SNAP_ERR_ES_MISS); + ext4_fc_set_snap_err_test(&snap_err, EXT4_FC_SNAP_ERR_NOMEM); + KUNIT_EXPECT_EQ(test, snap_err, (int)EXT4_FC_SNAP_ERR_ES_MISS); + + /* 5) ext4_fc_snap_stats_update_max monotonically updates max */ + ext4_fc_snap_stats_update_max_test(&max_stat, 100); + KUNIT_EXPECT_EQ(test, atomic64_read(&max_stat), 100LL); + ext4_fc_snap_stats_update_max_test(&max_stat, 50); + KUNIT_EXPECT_EQ(test, atomic64_read(&max_stat), 100LL); + ext4_fc_snap_stats_update_max_test(&max_stat, 250); + KUNIT_EXPECT_EQ(test, atomic64_read(&max_stat), 250LL); +} + +/* ========================================================================= + * 2. Ineligibility Marking (ext4_fc_mark_ineligible) + * ========================================================================= + */ + +static void test_fc_mark_ineligible(struct kunit *test) +{ + struct fc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = ctx->sbi; + + /* 1) No-op when fast commit is disabled */ + clear_opt2(sb, JOURNAL_FAST_COMMIT); + ext4_fc_mark_ineligible(sb, EXT4_FC_REASON_XATTR, &ctx->handle); + KUNIT_EXPECT_FALSE(test, + ext4_test_mount_flag(sb, EXT4_MF_FC_INELIGIBLE)); + KUNIT_EXPECT_EQ(test, + sbi->s_fc_stats.fc_ineligible_reason_count[EXT4_FC_REASON_XATTR], + 0U); + set_opt2(sb, JOURNAL_FAST_COMMIT); + + /* 2) Valid handle records t_tid and sets EXT4_MF_FC_INELIGIBLE */ + ctx->running_txn.t_tid = 10; + ext4_fc_mark_ineligible(sb, EXT4_FC_REASON_XATTR, &ctx->handle); + KUNIT_EXPECT_TRUE(test, + ext4_test_mount_flag(sb, EXT4_MF_FC_INELIGIBLE)); + KUNIT_EXPECT_EQ(test, sbi->s_fc_ineligible_tid, 10U); + KUNIT_EXPECT_EQ(test, + sbi->s_fc_stats.fc_ineligible_reason_count[EXT4_FC_REASON_XATTR], + 1U); + + /* 3) Higher TID advances s_fc_ineligible_tid; lower TID does not */ + ctx->running_txn.t_tid = 15; + ext4_fc_mark_ineligible(sb, EXT4_FC_REASON_RESIZE, &ctx->handle); + KUNIT_EXPECT_EQ(test, sbi->s_fc_ineligible_tid, 15U); + KUNIT_EXPECT_EQ(test, + sbi->s_fc_stats.fc_ineligible_reason_count[EXT4_FC_REASON_RESIZE], + 1U); + + ctx->running_txn.t_tid = 12; + ext4_fc_mark_ineligible(sb, EXT4_FC_REASON_RESIZE, &ctx->handle); + KUNIT_EXPECT_EQ(test, sbi->s_fc_ineligible_tid, 15U); + KUNIT_EXPECT_EQ(test, + sbi->s_fc_stats.fc_ineligible_reason_count[EXT4_FC_REASON_RESIZE], + 2U); + + /* 4) NULL handle uses journal->j_running_transaction when present */ + ctx->running_txn.t_tid = 20; + ext4_fc_mark_ineligible(sb, EXT4_FC_REASON_NOMEM, NULL); + KUNIT_EXPECT_EQ(test, sbi->s_fc_ineligible_tid, 20U); + KUNIT_EXPECT_EQ(test, + sbi->s_fc_stats.fc_ineligible_reason_count[EXT4_FC_REASON_NOMEM], + 1U); + + /* 5) NULL handle with no running transaction sets flag without tid update */ + ext4_clear_mount_flag(sb, EXT4_MF_FC_INELIGIBLE); + sbi->s_fc_ineligible_tid = 0; + ctx->journal.j_running_transaction = NULL; + ext4_fc_mark_ineligible(sb, EXT4_FC_REASON_RENAME_DIR, NULL); + KUNIT_EXPECT_TRUE(test, + ext4_test_mount_flag(sb, EXT4_MF_FC_INELIGIBLE)); + KUNIT_EXPECT_EQ(test, sbi->s_fc_ineligible_tid, 0U); + KUNIT_EXPECT_EQ(test, + sbi->s_fc_stats.fc_ineligible_reason_count[EXT4_FC_REASON_RENAME_DIR], + 1U); + + ctx->journal.j_running_transaction = &ctx->running_txn; + ctx->running_txn.t_tid = 10; + ext4_clear_mount_flag(sb, EXT4_MF_FC_INELIGIBLE); +} + +/* ========================================================================= + * 3. Inode and Logical Range Tracking + * ========================================================================= + */ + +static void test_fc_track_inode_and_range(struct kunit *test) +{ + struct fc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = ctx->sbi; + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct inode *file2 = get_mock_inode(ctx, TEST_FILE2_INO); + struct ext4_inode_info *ei1 = EXT4_I(file1); + struct ext4_inode_info *ei2 = EXT4_I(file2); + + /* 1) Directory inodes are ignored by track_inode and track_range */ + ext4_fc_track_inode(&ctx->handle, dir); + ext4_fc_track_range(&ctx->handle, dir, 0, 5); + KUNIT_EXPECT_TRUE(test, list_empty(&EXT4_I(dir)->i_fc_list)); + + /* 2) Data journalling inode marks fs ineligible */ + ctx->journal_mode = EXT4_INODE_JOURNAL_DATA_MODE; + ext4_fc_track_inode(&ctx->handle, file1); + KUNIT_EXPECT_TRUE(test, + ext4_test_mount_flag(sb, EXT4_MF_FC_INELIGIBLE)); + KUNIT_EXPECT_EQ(test, + sbi->s_fc_stats.fc_ineligible_reason_count[EXT4_FC_REASON_INODE_JOURNAL_DATA], + 1U); + KUNIT_EXPECT_TRUE(test, list_empty(&ei1->i_fc_list)); + ctx->journal_mode = EXT4_INODE_ORDERED_DATA_MODE; + ext4_clear_mount_flag(sb, EXT4_MF_FC_INELIGIBLE); + sbi->s_fc_ineligible_tid = 0; + + /* 3) Inline data inode marks fs ineligible on track_range */ + ext4_set_inode_flag(file1, EXT4_INODE_INLINE_DATA); + ext4_set_inode_state(file1, EXT4_STATE_MAY_INLINE_DATA); + ei1->i_inline_off = 164; + ext4_fc_track_range(&ctx->handle, file1, 0, 1); + KUNIT_EXPECT_TRUE(test, + ext4_test_mount_flag(sb, EXT4_MF_FC_INELIGIBLE)); + KUNIT_EXPECT_EQ(test, + sbi->s_fc_stats.fc_ineligible_reason_count[EXT4_FC_REASON_XATTR], + 1U); + ext4_clear_inode_flag(file1, EXT4_INODE_INLINE_DATA); + ext4_clear_inode_state(file1, EXT4_STATE_MAY_INLINE_DATA); + ei1->i_inline_off = 0; + ext4_clear_mount_flag(sb, EXT4_MF_FC_INELIGIBLE); + sbi->s_fc_ineligible_tid = 0; + + /* 4) Special inode (< EXT4_FIRST_INO) does not record range */ + file1->i_ino = EXT4_ROOT_INO; + ext4_fc_track_range(&ctx->handle, file1, 5, 10); + KUNIT_EXPECT_EQ(test, ei1->i_fc_lblk_len, 0U); + list_del_init(&ei1->i_fc_list); + file1->i_ino = TEST_FILE1_INO; + ei1->i_sync_tid = 0; + + /* + * 5) Range tracking within the same TID merges disjoint and overlapping + * ranges into their bounding interval, and subsequent track_inode + * in the same TID preserves the range. + */ + ctx->running_txn.t_tid = 10; + ext4_fc_track_inode(&ctx->handle, file1); + KUNIT_EXPECT_EQ(test, ei1->i_sync_tid, 10U); + KUNIT_EXPECT_EQ(test, ei1->i_fc_lblk_len, 0U); + KUNIT_EXPECT_FALSE(test, list_empty(&ei1->i_fc_list)); + + /* Initial range [10, 20] -> start=10, len=11 */ + ext4_fc_track_range(&ctx->handle, file1, 10, 20); + KUNIT_EXPECT_EQ(test, ei1->i_fc_lblk_start, 10U); + KUNIT_EXPECT_EQ(test, ei1->i_fc_lblk_len, 11U); + + /* Expand right [25, 30] -> [10, 30], start=10, len=21 */ + ext4_fc_track_range(&ctx->handle, file1, 25, 30); + KUNIT_EXPECT_EQ(test, ei1->i_fc_lblk_start, 10U); + KUNIT_EXPECT_EQ(test, ei1->i_fc_lblk_len, 21U); + + /* Expand left [4, 8] -> [4, 30], start=4, len=27 */ + ext4_fc_track_range(&ctx->handle, file1, 4, 8); + KUNIT_EXPECT_EQ(test, ei1->i_fc_lblk_start, 4U); + KUNIT_EXPECT_EQ(test, ei1->i_fc_lblk_len, 27U); + + /* Contained sub-range [12, 18] -> unchanged [4, 30] */ + ext4_fc_track_range(&ctx->handle, file1, 12, 18); + KUNIT_EXPECT_EQ(test, ei1->i_fc_lblk_start, 4U); + KUNIT_EXPECT_EQ(test, ei1->i_fc_lblk_len, 27U); + + /* Calling track_inode again in same TID keeps tracked range intact */ + ext4_fc_track_inode(&ctx->handle, file1); + KUNIT_EXPECT_EQ(test, ei1->i_fc_lblk_start, 4U); + KUNIT_EXPECT_EQ(test, ei1->i_fc_lblk_len, 27U); + + /* + * 6) Tracking while EXT4_STATE_FC_COMMITTING is set marks the inode + * with EXT4_STATE_FC_REQUEUE, and tracking in a new TID resets the + * previous range. + */ + ext4_set_inode_state(file1, EXT4_STATE_FC_COMMITTING); + ctx->running_txn.t_tid = 11; + ext4_fc_track_range(&ctx->handle, file1, 50, 55); + KUNIT_EXPECT_TRUE(test, + ext4_test_inode_state(file1, EXT4_STATE_FC_REQUEUE)); + KUNIT_EXPECT_EQ(test, ei1->i_sync_tid, 11U); + KUNIT_EXPECT_EQ(test, ei1->i_fc_lblk_start, 50U); + KUNIT_EXPECT_EQ(test, ei1->i_fc_lblk_len, 6U); + ext4_clear_inode_state(file1, EXT4_STATE_FC_COMMITTING); + ext4_clear_inode_state(file1, EXT4_STATE_FC_REQUEUE); + + /* + * 7) Tracking a new inode while JBD2_FAST_COMMIT_ONGOING is set + * enqueues it on FC_Q_STAGING rather than FC_Q_MAIN. + */ + ctx->journal.j_flags |= JBD2_FAST_COMMIT_ONGOING; + ext4_fc_track_inode(&ctx->handle, file2); + KUNIT_EXPECT_FALSE(test, list_empty(&sbi->s_fc_q[FC_Q_STAGING])); + KUNIT_EXPECT_PTR_EQ(test, + list_first_entry(&sbi->s_fc_q[FC_Q_STAGING], + struct ext4_inode_info, i_fc_list), + ei2); + ctx->journal.j_flags &= ~JBD2_FAST_COMMIT_ONGOING; +} + +/* ========================================================================= + * 4. Dentry Update Tracking and Inode Deletion (ext4_fc_del) + * ========================================================================= + */ + +struct fc_del_wait_work { + struct work_struct work; + struct inode *inode; +}; + +static void fc_del_unblock_worker(struct work_struct *work) +{ + struct fc_del_wait_work *w = + container_of(work, struct fc_del_wait_work, work); + struct inode *inode = w->inode; + int alloc_ctx; + + /* + * Simulate the commit thread finishing data flush and transitioning + * FLUSHING_DATA -> COMMITTING -> done while ext4_fc_del() is waiting. + */ + alloc_ctx = ext4_fc_lock(inode->i_sb); + ext4_clear_inode_state(inode, EXT4_STATE_FC_FLUSHING_DATA); + ext4_set_inode_state(inode, EXT4_STATE_FC_COMMITTING); + ext4_fc_wake_inode_state_test(inode, EXT4_STATE_FC_FLUSHING_DATA); + ext4_fc_unlock(inode->i_sb, alloc_ctx); + + alloc_ctx = ext4_fc_lock(inode->i_sb); + ext4_clear_inode_state(inode, EXT4_STATE_FC_COMMITTING); + ext4_fc_wake_inode_state_test(inode, EXT4_STATE_FC_COMMITTING); + ext4_fc_unlock(inode->i_sb, alloc_ctx); +} + +static void test_fc_track_dentry_and_del(struct kunit *test) +{ + struct fc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = ctx->sbi; + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct inode *file2 = get_mock_inode(ctx, TEST_FILE2_INO); + struct ext4_inode_info *ei1 = EXT4_I(file1); + struct dentry *dentries; + struct dentry *d_parent, *d_f1, *d_f1_link, *d_f2; + struct ext4_fc_dentry_update *fcd; + struct fc_del_wait_work wait_work; + + dentries = kunit_kcalloc(test, 4, sizeof(*dentries), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dentries); + d_parent = &dentries[0]; + d_f1 = &dentries[1]; + d_f1_link = &dentries[2]; + d_f2 = &dentries[3]; + + init_mock_dentry(d_parent, NULL, "dir", dir, sb); + init_mock_dentry(d_f1, d_parent, "file1", file1, sb); + init_mock_dentry(d_f1_link, d_parent, "file1_ln", file1, sb); + init_mock_dentry(d_f2, d_parent, "file2", file2, sb); + + /* 1) Encrypted parent directory marks fs ineligible */ + dir->i_flags |= S_ENCRYPTED; + ext4_fc_track_create(&ctx->handle, d_f1); + KUNIT_EXPECT_TRUE(test, + ext4_test_mount_flag(sb, EXT4_MF_FC_INELIGIBLE)); + KUNIT_EXPECT_EQ(test, + sbi->s_fc_stats.fc_ineligible_reason_count[EXT4_FC_REASON_ENCRYPTED_FILENAME], + 1U); + KUNIT_EXPECT_TRUE(test, list_empty(&sbi->s_fc_dentry_q[FC_Q_MAIN])); + dir->i_flags &= ~S_ENCRYPTED; + ext4_clear_mount_flag(sb, EXT4_MF_FC_INELIGIBLE); + sbi->s_fc_ineligible_tid = 0; + + /* 2) Track create, link, and unlink onto MAIN and STAGING queues */ + ext4_fc_track_create(&ctx->handle, d_f1); + KUNIT_EXPECT_FALSE(test, list_empty(&sbi->s_fc_dentry_q[FC_Q_MAIN])); + KUNIT_EXPECT_FALSE(test, list_empty(&ei1->i_fc_dilist)); + + fcd = list_first_entry(&sbi->s_fc_dentry_q[FC_Q_MAIN], + struct ext4_fc_dentry_update, fcd_list); + KUNIT_EXPECT_EQ(test, fcd->fcd_op, EXT4_FC_TAG_CREAT); + KUNIT_EXPECT_EQ(test, fcd->fcd_parent, (int)TEST_DIR_INO); + KUNIT_EXPECT_EQ(test, fcd->fcd_ino, (int)TEST_FILE1_INO); + KUNIT_EXPECT_STREQ(test, (const char *)fcd->fcd_name.name.name, "file1"); + + ext4_fc_track_link(&ctx->handle, file1, d_f1_link); + ext4_fc_track_unlink(&ctx->handle, d_f1_link); + + ctx->journal.j_flags |= JBD2_FULL_COMMIT_ONGOING; + ext4_fc_track_create(&ctx->handle, d_f2); + KUNIT_EXPECT_FALSE(test, list_empty(&sbi->s_fc_dentry_q[FC_Q_STAGING])); + ctx->journal.j_flags &= ~JBD2_FULL_COMMIT_ONGOING; + + /* + * 3) ext4_fc_del removes file2's CREAT entry from s_fc_dentry_q and + * i_fc_dilist even when file2 is not on s_fc_q. + */ + ext4_fc_del(file2); + KUNIT_EXPECT_TRUE(test, list_empty(&EXT4_I(file2)->i_fc_dilist)); + KUNIT_EXPECT_TRUE(test, list_empty(&sbi->s_fc_dentry_q[FC_Q_STAGING])); + + /* + * 4) ext4_fc_del waits for EXT4_STATE_FC_FLUSHING_DATA and + * EXT4_STATE_FC_COMMITTING to clear before deleting file1. + */ + ext4_fc_track_inode(&ctx->handle, file1); + ext4_set_inode_state(file1, EXT4_STATE_FC_FLUSHING_DATA); + wait_work.inode = file1; + INIT_WORK_ONSTACK(&wait_work.work, fc_del_unblock_worker); + schedule_work(&wait_work.work); + + ext4_fc_del(file1); + flush_work(&wait_work.work); + destroy_work_on_stack(&wait_work.work); + + KUNIT_EXPECT_TRUE(test, list_empty(&ei1->i_fc_list)); + KUNIT_EXPECT_TRUE(test, list_empty(&ei1->i_fc_dilist)); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(file1, EXT4_STATE_FC_FLUSHING_DATA)); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(file1, EXT4_STATE_FC_COMMITTING)); +} + +/* ========================================================================= + * 5. Space Reservation, Padding, and TLV Writing + * ========================================================================= + */ + +static void test_fc_reserve_space_and_tlv_writing(struct kunit *test) +{ + struct fc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = ctx->sbi; + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct ext4_fc_tl tl; + struct ext4_fc_tail tail; + u8 payload[600]; + u8 *dst; + u32 crc = 0; + + memset(payload, 0xAB, sizeof(payload)); + + /* 1) Request exceeding bsize - EXT4_FC_TAG_BASE_LEN fails immediately */ + dst = ext4_fc_reserve_space_test(sb, + TEST_BLK_SIZE - EXT4_FC_TAG_BASE_LEN + 1, + &crc); + KUNIT_EXPECT_NULL(test, dst); + KUNIT_EXPECT_EQ(test, ctx->fc_get_buf_calls, 0); + + /* 2) ext4_fc_get_buf failure on initial block returns NULL */ + ctx->fail_fc_get_buf = -ENOSPC; + dst = ext4_fc_reserve_space_test(sb, 32, &crc); + KUNIT_EXPECT_NULL(test, dst); + ctx->fail_fc_get_buf = 0; + + /* + * 3) Add a 600-byte TLV into block 0 (takes 604 bytes), then add + * another 600-byte TLV. The second TLV does not fit in the + * remaining 420 bytes of block 0, so ext4_fc_reserve_space writes + * an EXT4_FC_TAG_PAD TLV of length 416 (420 - 4), submits block 0, + * and allocates block 1. + */ + KUNIT_EXPECT_TRUE(test, + ext4_fc_add_tlv_test(sb, EXT4_FC_TAG_HEAD, + sizeof(payload), payload, &crc)); + KUNIT_EXPECT_EQ(test, sbi->s_fc_bytes, + (unsigned int)(EXT4_FC_TAG_BASE_LEN + sizeof(payload))); + KUNIT_EXPECT_EQ(test, ctx->fc_submit_bh_calls, 0U); + + KUNIT_EXPECT_TRUE(test, + ext4_fc_add_tlv_test(sb, EXT4_FC_TAG_HEAD, + sizeof(payload), payload, &crc)); + KUNIT_EXPECT_EQ(test, ctx->fc_submit_bh_calls, 1U); + KUNIT_EXPECT_EQ(test, ctx->fc_submit_tail_calls, 0U); + KUNIT_EXPECT_EQ(test, sbi->s_fc_bytes, + (unsigned int)(TEST_BLK_SIZE + EXT4_FC_TAG_BASE_LEN + + sizeof(payload))); + + /* Verify PAD TLV was written at offset 604 of block 0 */ + memcpy(&tl, ctx->fc_buf_data[0] + EXT4_FC_TAG_BASE_LEN + sizeof(payload), + EXT4_FC_TAG_BASE_LEN); + KUNIT_EXPECT_EQ(test, le16_to_cpu(tl.fc_tag), (u16)EXT4_FC_TAG_PAD); + KUNIT_EXPECT_EQ(test, le16_to_cpu(tl.fc_len), + (u16)(TEST_BLK_SIZE - 2 * EXT4_FC_TAG_BASE_LEN - + sizeof(payload))); + + /* 4) Write tail tag into block 1 and verify rounding + tail submission */ + KUNIT_EXPECT_EQ(test, ext4_fc_write_tail_test(sb, crc), 0); + KUNIT_EXPECT_EQ(test, ctx->fc_submit_bh_calls, 2U); + KUNIT_EXPECT_EQ(test, ctx->fc_submit_tail_calls, 1U); + KUNIT_EXPECT_EQ(test, sbi->s_fc_bytes, (unsigned int)(2 * TEST_BLK_SIZE)); + + memcpy(&tl, ctx->fc_buf_data[1] + EXT4_FC_TAG_BASE_LEN + sizeof(payload), + EXT4_FC_TAG_BASE_LEN); + memcpy(&tail, + ctx->fc_buf_data[1] + 2 * EXT4_FC_TAG_BASE_LEN + sizeof(payload), + sizeof(tail)); + KUNIT_EXPECT_EQ(test, le16_to_cpu(tl.fc_tag), (u16)EXT4_FC_TAG_TAIL); + KUNIT_EXPECT_EQ(test, le32_to_cpu(tail.fc_tid), 10U); + + /* 5) Missing inode snapshot increments snap_fail_no_snap */ + KUNIT_EXPECT_EQ(test, ext4_fc_write_inode_test(file1, &crc), + -ECANCELED); + KUNIT_EXPECT_EQ(test, ext4_fc_write_inode_data_test(file1, &crc), + -ECANCELED); + KUNIT_EXPECT_EQ(test, + atomic64_read(&sbi->s_fc_snap_stats.snap_fail_no_snap), + 2LL); +} + +/* ========================================================================= + * 6. Inode and Extent Status Range Snapshotting + * ========================================================================= + */ + +static void test_fc_snapshot_inode_and_ranges(struct kunit *test) +{ + struct fc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = ctx->sbi; + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct inode *file2 = get_mock_inode(ctx, TEST_FILE2_INO); + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct ext4_inode_info *ei1 = EXT4_I(file1); + struct dentry d_parent, d_f2; + struct inode **inodes = NULL; + unsigned int nr_inodes = 0, nr_ranges = 0; + int snap_err = EXT4_FC_SNAP_ERR_NONE; + u32 crc = 0; + + /* 1) ext4_get_inode_loc_noio failure records EXT4_FC_SNAP_ERR_INODE_LOC */ + ctx->fail_get_inode_loc_noio = -EAGAIN; + KUNIT_EXPECT_EQ(test, + ext4_fc_snapshot_inode_test(file1, 0, &nr_ranges, + &snap_err), + -EAGAIN); + KUNIT_EXPECT_EQ(test, snap_err, (int)EXT4_FC_SNAP_ERR_INODE_LOC); + KUNIT_EXPECT_EQ(test, + atomic64_read(&sbi->s_fc_snap_stats.snap_fail_inode_loc), + 1LL); + ctx->fail_get_inode_loc_noio = 0; + + /* 2) ES miss on tracked range records EXT4_FC_SNAP_ERR_ES_MISS */ + snap_err = EXT4_FC_SNAP_ERR_NONE; + ext4_fc_track_range(&ctx->handle, file1, 0, 3); + KUNIT_EXPECT_EQ(test, + ext4_fc_snapshot_inode_test(file1, 0, &nr_ranges, + &snap_err), + -EAGAIN); + KUNIT_EXPECT_EQ(test, snap_err, (int)EXT4_FC_SNAP_ERR_ES_MISS); + KUNIT_EXPECT_EQ(test, + atomic64_read(&sbi->s_fc_snap_stats.snap_fail_es_miss), + 1LL); + + /* 3) Delayed extent in ES tree records EXT4_FC_SNAP_ERR_ES_DELAYED */ + snap_err = EXT4_FC_SNAP_ERR_NONE; + down_write(&ei1->i_data_sem); + ext4_es_insert_delayed_extent(file1, 0, 4, false, false); + up_write(&ei1->i_data_sem); + ext4_fc_track_range(&ctx->handle, file1, 0, 3); + KUNIT_EXPECT_EQ(test, + ext4_fc_snapshot_inode_test(file1, 0, &nr_ranges, + &snap_err), + -EAGAIN); + KUNIT_EXPECT_EQ(test, snap_err, (int)EXT4_FC_SNAP_ERR_ES_DELAYED); + KUNIT_EXPECT_EQ(test, + atomic64_read(&sbi->s_fc_snap_stats.snap_fail_es_delayed), + 1LL); + down_write(&ei1->i_data_sem); + ext4_es_remove_extent(file1, 0, EXT_MAX_BLOCKS); + up_write(&ei1->i_data_sem); + + /* 4) Unsupported ES status records EXT4_FC_SNAP_ERR_ES_OTHER */ + snap_err = EXT4_FC_SNAP_ERR_NONE; + ctx->use_custom_es_lookup = true; + ctx->custom_es_ret = 1; + ctx->custom_es.es_lblk = 0; + ctx->custom_es.es_len = 4; + ctx->custom_es.es_pblk = 0; + ext4_es_set_referenced(&ctx->custom_es); + ext4_fc_track_range(&ctx->handle, file1, 0, 3); + KUNIT_EXPECT_EQ(test, + ext4_fc_snapshot_inode_test(file1, 0, &nr_ranges, + &snap_err), + -EAGAIN); + KUNIT_EXPECT_EQ(test, snap_err, (int)EXT4_FC_SNAP_ERR_ES_OTHER); + KUNIT_EXPECT_EQ(test, + atomic64_read(&sbi->s_fc_snap_stats.snap_fail_es_other), + 1LL); + ctx->use_custom_es_lookup = false; + + /* 5) Exceeding EXT4_FC_SNAPSHOT_MAX_RANGES returns -E2BIG */ + snap_err = EXT4_FC_SNAP_ERR_NONE; + down_write(&ei1->i_data_sem); + ext4_es_insert_extent(file1, 0, 4, 200, EXTENT_STATUS_WRITTEN, false); + up_write(&ei1->i_data_sem); + ext4_fc_track_range(&ctx->handle, file1, 0, 3); + KUNIT_EXPECT_EQ(test, + ext4_fc_snapshot_inode_test(file1, 2048, &nr_ranges, + &snap_err), + -E2BIG); + KUNIT_EXPECT_EQ(test, snap_err, (int)EXT4_FC_SNAP_ERR_RANGES_CAP); + KUNIT_EXPECT_EQ(test, + atomic64_read(&sbi->s_fc_snap_stats.snap_fail_ranges_cap), + 1LL); + + /* + * 6) Snapshot mixed written, hole, unwritten, and large (>32768) + * extents, verifying automatic splitting at EXT_INIT_MAX_LEN (32768) + * and EXT_UNWRITTEN_MAX_LEN (32767). + */ + down_write(&ei1->i_data_sem); + ext4_es_remove_extent(file1, 0, EXT_MAX_BLOCKS); + /* [0, 3]: written at pblk 200 */ + ext4_es_insert_extent(file1, 0, 4, 200, EXTENT_STATUS_WRITTEN, false); + /* [4, 5]: hole */ + ext4_es_insert_extent(file1, 4, 2, 0, EXTENT_STATUS_HOLE, false); + /* [6, 40005]: 40000 unwritten blocks at pblk 1000 (splits into 32767 + 7233) */ + ext4_es_insert_extent(file1, 6, 40000, 1000, EXTENT_STATUS_UNWRITTEN, + false); + up_write(&ei1->i_data_sem); + + snap_err = EXT4_FC_SNAP_ERR_NONE; + ext4_fc_track_range(&ctx->handle, file1, 1, 40005); + KUNIT_EXPECT_EQ(test, + ext4_fc_snapshot_inode_test(file1, 0, &nr_ranges, + &snap_err), + 0); + /* 1 written [1..3] + 1 hole [4..5] + 2 split unwritten [6..32772, 32773..40005] = 4 */ + KUNIT_EXPECT_EQ(test, nr_ranges, 4U); + KUNIT_EXPECT_NOT_NULL(test, ei1->i_fc_snap); + + /* Serialize the snapshotted inode and ranges into fast commit buffer */ + sbi->s_fc_bytes = 0; + ctx->journal.j_fc_off = 0; + KUNIT_EXPECT_EQ(test, ext4_fc_write_inode_data_test(file1, &crc), 0); + KUNIT_EXPECT_EQ(test, ext4_fc_write_inode_test(file1, &crc), 0); + + /* + * 7) Count and snapshot both s_fc_q[MAIN] inodes and create-only + * inodes from s_fc_dentry_q[MAIN]. + */ + init_mock_dentry(&d_parent, NULL, "dir", dir, sb); + init_mock_dentry(&d_f2, &d_parent, "file2", file2, sb); + ext4_fc_track_create(&ctx->handle, &d_f2); + KUNIT_EXPECT_TRUE(test, list_empty(&EXT4_I(file2)->i_fc_list)); + KUNIT_EXPECT_EQ(test, ext4_fc_count_snapshot_inodes_test(sb), 2U); + + KUNIT_EXPECT_EQ(test, + ext4_fc_alloc_snapshot_inodes_test(sb, &inodes, + &nr_inodes), + 0); + KUNIT_EXPECT_EQ(test, nr_inodes, 2U); + KUNIT_ASSERT_NOT_NULL(test, inodes); + + /* Capacity smaller than queued inode count returns -E2BIG */ + snap_err = EXT4_FC_SNAP_ERR_NONE; + KUNIT_EXPECT_EQ(test, + ext4_fc_snapshot_inodes_test(&ctx->journal, inodes, 1, + &nr_inodes, &nr_ranges, + &snap_err), + -E2BIG); + KUNIT_EXPECT_EQ(test, snap_err, (int)EXT4_FC_SNAP_ERR_INODES_CAP); + + snap_err = EXT4_FC_SNAP_ERR_NONE; + KUNIT_EXPECT_EQ(test, + ext4_fc_snapshot_inodes_test(&ctx->journal, inodes, 2, + &nr_inodes, &nr_ranges, + &snap_err), + 0); + KUNIT_EXPECT_EQ(test, nr_inodes, 2U); + /* Create-only inode (file2) is marked EXT4_STATE_FC_COMMITTING */ + KUNIT_EXPECT_TRUE(test, + ext4_test_inode_state(file2, EXT4_STATE_FC_COMMITTING)); + KUNIT_EXPECT_NOT_NULL(test, EXT4_I(file2)->i_fc_snap); + kvfree(inodes); +} + +/* ========================================================================= + * 7. Fast Commit Cleanup, Stats, and Procfs Output (ext4_fc_info_show) + * ========================================================================= + */ + +static void test_fc_cleanup_and_stats(struct kunit *test) +{ + struct fc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = ctx->sbi; + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct inode *file2 = get_mock_inode(ctx, TEST_FILE2_INO); + struct ext4_inode_info *ei1 = EXT4_I(file1); + struct ext4_inode_info *ei2 = EXT4_I(file2); + struct seq_file seq = {}; + char *buf; + + /* + * 1) Fast commit cleanup (full = 0): + * - file1 (no FC_REQUEUE) is removed from FC_Q_MAIN and reset. + * - file2 (FC_REQUEUE set) is requeued and preserves its range. + */ + ctx->running_txn.t_tid = 10; + ext4_fc_track_range(&ctx->handle, file1, 2, 5); + ext4_fc_track_range(&ctx->handle, file2, 8, 12); + ext4_set_inode_state(file1, EXT4_STATE_FC_COMMITTING); + ext4_set_inode_state(file2, EXT4_STATE_FC_COMMITTING); + ext4_set_inode_state(file2, EXT4_STATE_FC_REQUEUE); + sbi->s_fc_bytes = 512; + + ext4_fc_cleanup_test(&ctx->journal, 0, 10); + KUNIT_EXPECT_TRUE(test, list_empty(&ei1->i_fc_list)); + KUNIT_EXPECT_EQ(test, ei1->i_fc_lblk_len, 0U); + KUNIT_EXPECT_FALSE(test, list_empty(&ei2->i_fc_list)); + KUNIT_EXPECT_EQ(test, ei2->i_fc_lblk_start, 8U); + KUNIT_EXPECT_EQ(test, ei2->i_fc_lblk_len, 5U); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(file2, EXT4_STATE_FC_REQUEUE)); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(file2, EXT4_STATE_FC_COMMITTING)); + /* Fast commit cleanup does not reset s_fc_bytes */ + KUNIT_EXPECT_EQ(test, sbi->s_fc_bytes, 512U); + + /* + * 2) Full commit cleanup (full = 1): + * - Inodes with i_sync_tid > tid are requeued; inodes with + * i_sync_tid <= tid are removed and reset. + * - s_fc_ineligible_tid is cleared only when tid >= s_fc_ineligible_tid. + * - s_fc_bytes is reset to 0. + */ + ctx->running_txn.t_tid = 15; + ext4_fc_track_range(&ctx->handle, file1, 1, 3); + ext4_fc_mark_ineligible(sb, EXT4_FC_REASON_XATTR, &ctx->handle); + KUNIT_EXPECT_EQ(test, sbi->s_fc_ineligible_tid, 15U); + + /* Full commit of TID 10: file2 (tid 10) removed, file1 (tid 15) kept */ + ext4_fc_cleanup_test(&ctx->journal, 1, 10); + KUNIT_EXPECT_TRUE(test, list_empty(&ei2->i_fc_list)); + KUNIT_EXPECT_FALSE(test, list_empty(&ei1->i_fc_list)); + KUNIT_EXPECT_TRUE(test, + ext4_test_mount_flag(sb, EXT4_MF_FC_INELIGIBLE)); + KUNIT_EXPECT_EQ(test, sbi->s_fc_bytes, 0U); + + /* Full commit of TID 15: file1 removed and ineligibility cleared */ + ext4_fc_cleanup_test(&ctx->journal, 1, 15); + KUNIT_EXPECT_TRUE(test, list_empty(&ei1->i_fc_list)); + KUNIT_EXPECT_FALSE(test, + ext4_test_mount_flag(sb, EXT4_MF_FC_INELIGIBLE)); + KUNIT_EXPECT_EQ(test, sbi->s_fc_ineligible_tid, 0U); + + /* + * 3) ext4_fc_update_stats and ext4_fc_info_show formatting + */ + memset(&sbi->s_fc_stats, 0, sizeof(sbi->s_fc_stats)); + ext4_fc_update_stats_test(sb, EXT4_FC_STATUS_OK, 40000, 2, 10); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_num_commits, 1UL); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_numblks, 2UL); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.s_fc_avg_commit_time, 40000ULL); + + /* EWMA update: (80000 + 40000 * 3) / 4 = 50000 */ + ext4_fc_update_stats_test(sb, EXT4_FC_STATUS_OK, 80000, 3, 10); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_num_commits, 2UL); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_numblks, 5UL); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.s_fc_avg_commit_time, 50000ULL); + + ext4_fc_update_stats_test(sb, EXT4_FC_STATUS_INELIGIBLE, 0, 0, 10); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_ineligible_commits, 1UL); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_failed_commits, 0UL); + + ext4_fc_update_stats_test(sb, EXT4_FC_STATUS_FAILED, 0, 0, 10); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_ineligible_commits, 2UL); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_failed_commits, 1UL); + + ext4_fc_update_stats_test(sb, EXT4_FC_STATUS_SKIPPED, 0, 0, 10); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_skipped_commits, 1UL); + + buf = kunit_kzalloc(test, PAGE_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, buf); + seq.buf = buf; + seq.size = PAGE_SIZE; + seq.private = sb; + + /* Non-start token produces no output */ + KUNIT_EXPECT_EQ(test, ext4_fc_info_show(&seq, NULL), 0); + KUNIT_EXPECT_EQ(test, seq.count, 0UL); + + /* SEQ_START_TOKEN outputs full stats table */ + KUNIT_EXPECT_EQ(test, ext4_fc_info_show(&seq, SEQ_START_TOKEN), 0); + KUNIT_EXPECT_GT(test, seq.count, 0UL); + KUNIT_EXPECT_NOT_NULL(test, strstr(buf, "fc stats:\n2 commits\n2 ineligible\n5 numblks\n50us avg_commit_time")); + KUNIT_EXPECT_NOT_NULL(test, strstr(buf, "Ineligible reasons:")); + KUNIT_EXPECT_NOT_NULL(test, strstr(buf, "Snapshot stats:")); + KUNIT_EXPECT_NOT_NULL(test, strstr(buf, "Snapshot failures:")); +} + +/* ========================================================================= + * 8. Top-Level Commit Paths and Fallbacks (ext4_fc_commit) + * ========================================================================= + */ + +static void test_fc_commit_paths(struct kunit *test) +{ + struct fc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = ctx->sbi; + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct ext4_inode_info *ei1 = EXT4_I(file1); + struct ext4_fc_tl tl; + + /* 1) Already-committed TID is skipped (-EALREADY) */ + ctx->journal.j_commit_sequence = 10; + KUNIT_EXPECT_EQ(test, ext4_fc_commit(&ctx->journal, 10), 0); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_skipped_commits, 1UL); + + /* 1b) JOURNAL_FAST_COMMIT disabled delegates to jbd2_complete_transaction */ + clear_opt2(sb, JOURNAL_FAST_COMMIT); + KUNIT_EXPECT_EQ(test, ext4_fc_commit(&ctx->journal, 10), 0); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_skipped_commits, 1UL); + set_opt2(sb, JOURNAL_FAST_COMMIT); + + /* 1c) jbd2_fc_begin_commit failure (ts_tid == 0 -> -EINVAL) records FAILED */ + ctx->journal.j_commit_sequence = 9; + ctx->journal.j_commit_request = 10; + ctx->journal.j_stats.ts_tid = 0; + ctx->journal.j_running_transaction = NULL; + KUNIT_EXPECT_EQ(test, ext4_fc_commit(&ctx->journal, 10), 0); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_failed_commits, 1UL); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_ineligible_commits, 1UL); + ctx->journal.j_stats.ts_tid = 1; + ctx->journal.j_running_transaction = &ctx->running_txn; + sbi->s_fc_stats.fc_failed_commits = 0; + sbi->s_fc_stats.fc_ineligible_commits = 0; + + /* 2) Ineligible filesystem falls back to full commit */ + ctx->journal.j_commit_sequence = 9; + ctx->journal.j_commit_request = 9; + ctx->running_txn.t_tid = 10; + ext4_fc_mark_ineligible(sb, EXT4_FC_REASON_XATTR, &ctx->handle); + KUNIT_EXPECT_EQ(test, ext4_fc_commit(&ctx->journal, 10), 0); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_ineligible_commits, 1UL); + ctx->journal.j_flags &= ~JBD2_FULL_COMMIT_ONGOING; + ext4_clear_mount_flag(sb, EXT4_MF_FC_INELIGIBLE); + sbi->s_fc_ineligible_tid = 0; + + /* 3) Data flush failure (-EIO) clears FLUSHING_DATA and falls back */ + ctx->journal.j_commit_sequence = 9; + ctx->journal.j_commit_request = 9; + ctx->running_txn.t_tid = 10; + ext4_fc_track_inode(&ctx->handle, file1); + WRITE_ONCE(ei1->jinode->i_flags, JI_WRITE_DATA); + ctx->submit_inode_data_err = -EIO; + KUNIT_EXPECT_EQ(test, ext4_fc_commit(&ctx->journal, 10), 0); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(file1, EXT4_STATE_FC_FLUSHING_DATA)); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_failed_commits, 1UL); + ctx->journal.j_flags &= ~JBD2_FULL_COMMIT_ONGOING; + WRITE_ONCE(ei1->jinode->i_flags, 0); + ctx->submit_inode_data_err = 0; + + /* 4) Snapshot ES miss (-EAGAIN) records INELIGIBLE status and falls back */ + ctx->journal.j_commit_sequence = 9; + ctx->journal.j_commit_request = 9; + ctx->running_txn.t_tid = 10; + ext4_fc_track_range(&ctx->handle, file1, 0, 1); + KUNIT_EXPECT_EQ(test, ext4_fc_commit(&ctx->journal, 10), 0); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_ineligible_commits, 3UL); + /* Failed commits count does not increment on -EAGAIN */ + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_failed_commits, 1UL); + ctx->journal.j_flags &= ~JBD2_FULL_COMMIT_ONGOING; + + /* 5) jbd2_fc_wait_bufs I/O failure (-EIO) records FAILED status */ + ctx->journal.j_commit_sequence = 9; + ctx->journal.j_commit_request = 9; + ctx->running_txn.t_tid = 10; + ctx->journal.j_fc_off = 0; + sbi->s_fc_bytes = 0; + ext4_fc_track_inode(&ctx->handle, file1); + ctx->fail_fc_wait_bufs = true; + KUNIT_EXPECT_EQ(test, ext4_fc_commit(&ctx->journal, 10), 0); + KUNIT_EXPECT_EQ(test, sbi->s_fc_stats.fc_failed_commits, 2UL); + ctx->journal.j_flags &= ~JBD2_FULL_COMMIT_ONGOING; + ctx->fail_fc_wait_bufs = false; + + /* + * 6) Two consecutive successful fast commits in the same TID, with an + * external journal device (j_fs_dev != j_dev) triggering cache flush. + */ + ctx->journal.j_commit_sequence = 9; + ctx->journal.j_commit_request = 9; + ctx->running_txn.t_tid = 10; + ctx->journal.j_fc_off = 0; + sbi->s_fc_bytes = 0; + atomic_set(&sbi->s_fc_subtid, 0); + ctx->journal.j_fs_dev = &ctx->ext_jdev; + ctx->fc_flush_calls = 0; + + down_write(&ei1->i_data_sem); + ext4_es_insert_extent(file1, 0, 2, 200, EXTENT_STATUS_WRITTEN, false); + up_write(&ei1->i_data_sem); + ext4_fc_track_range(&ctx->handle, file1, 0, 1); + + KUNIT_EXPECT_EQ(test, ext4_fc_commit(&ctx->journal, 10), 0); + KUNIT_EXPECT_EQ(test, atomic_read(&sbi->s_fc_subtid), 1); + KUNIT_EXPECT_EQ(test, ctx->fc_flush_calls, 1U); + KUNIT_EXPECT_PTR_EQ(test, ctx->last_flushed_bdev, &ctx->ext_jdev); + KUNIT_EXPECT_EQ(test, sbi->s_fc_bytes, (unsigned int)TEST_BLK_SIZE); + + /* Block 0 starts with EXT4_FC_TAG_HEAD */ + memcpy(&tl, ctx->fc_buf_data[0], EXT4_FC_TAG_BASE_LEN); + KUNIT_EXPECT_EQ(test, le16_to_cpu(tl.fc_tag), (u16)EXT4_FC_TAG_HEAD); + + /* Second fast commit in the same TID (block 1 starts with INODE, not HEAD) */ + ext4_fc_track_inode(&ctx->handle, file1); + KUNIT_EXPECT_EQ(test, ext4_fc_commit(&ctx->journal, 10), 0); + KUNIT_EXPECT_EQ(test, atomic_read(&sbi->s_fc_subtid), 2); + KUNIT_EXPECT_EQ(test, sbi->s_fc_bytes, (unsigned int)(2 * TEST_BLK_SIZE)); + memcpy(&tl, ctx->fc_buf_data[1], EXT4_FC_TAG_BASE_LEN); + KUNIT_EXPECT_EQ(test, le16_to_cpu(tl.fc_tag), (u16)EXT4_FC_TAG_INODE); + + ctx->journal.j_fs_dev = &ctx->bdev; +} + +/* ========================================================================= + * 9. Replay Regions, Modified Inode Tracking, and Scan Validation + * ========================================================================= + */ + +static void test_fc_replay_regions_and_scan(struct kunit *test) +{ + struct fc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = ctx->sbi; + struct ext4_fc_replay_state *state = &sbi->s_fc_replay_state; + struct ext4_fc_tl tl; + struct ext4_fc_head head; + int i; + + /* + * 1) ext4_fc_record_regions and ext4_fc_replay_check_excluded across + * dynamic krealloc (> EXT4_FC_REPLAY_REALLOC_INCREMENT = 4) + */ + for (i = 0; i < 6; i++) { + KUNIT_EXPECT_EQ(test, + ext4_fc_record_regions(sb, 12 + i, i * 10, + 100 + i * 10, 5, 1), + 0); + } + KUNIT_EXPECT_EQ(test, state->fc_regions_used, 6); + KUNIT_EXPECT_EQ(test, state->fc_regions_valid, 6); + KUNIT_EXPECT_GE(test, state->fc_regions_size, 6); + + KUNIT_EXPECT_TRUE(test, ext4_fc_replay_check_excluded(sb, 100)); + KUNIT_EXPECT_TRUE(test, ext4_fc_replay_check_excluded(sb, 104)); + KUNIT_EXPECT_FALSE(test, ext4_fc_replay_check_excluded(sb, 105)); + KUNIT_EXPECT_TRUE(test, ext4_fc_replay_check_excluded(sb, 152)); + + /* Unvalidated scan region (replay = 0) is not excluded until validated */ + KUNIT_EXPECT_EQ(test, + ext4_fc_record_regions(sb, 99, 0, 500, 10, 0), + 0); + KUNIT_EXPECT_EQ(test, state->fc_regions_used, 7); + KUNIT_EXPECT_EQ(test, state->fc_regions_valid, 6); + KUNIT_EXPECT_FALSE(test, ext4_fc_replay_check_excluded(sb, 502)); + + /* Next replay=1 addition resyncs fc_regions_used to fc_regions_valid */ + KUNIT_EXPECT_EQ(test, + ext4_fc_record_regions(sb, 100, 0, 600, 4, 1), + 0); + KUNIT_EXPECT_EQ(test, state->fc_regions_used, 7); + KUNIT_EXPECT_EQ(test, state->fc_regions_valid, 7); + KUNIT_EXPECT_TRUE(test, ext4_fc_replay_check_excluded(sb, 601)); + + /* 2) ext4_fc_record_modified_inode deduplication and krealloc growth */ + for (i = 0; i < 6; i++) { + KUNIT_EXPECT_EQ(test, + ext4_fc_record_modified_inode_test(sb, 20 + i), + 0); + /* Duplicate ino is ignored */ + KUNIT_EXPECT_EQ(test, + ext4_fc_record_modified_inode_test(sb, 20 + i), + 0); + } + KUNIT_EXPECT_EQ(test, state->fc_modified_inodes_used, 6); + + ext4_fc_replay_cleanup(sb); + memset(state, 0, sizeof(*state)); + + /* 3) ext4_fc_value_len_isvalid_test and tag2str */ + KUNIT_EXPECT_TRUE(test, + ext4_fc_value_len_isvalid_test(sbi, EXT4_FC_TAG_ADD_RANGE, + sizeof(struct ext4_fc_add_range))); + KUNIT_EXPECT_FALSE(test, + ext4_fc_value_len_isvalid_test(sbi, EXT4_FC_TAG_ADD_RANGE, 1)); + KUNIT_EXPECT_TRUE(test, + ext4_fc_value_len_isvalid_test(sbi, EXT4_FC_TAG_DEL_RANGE, + sizeof(struct ext4_fc_del_range))); + KUNIT_EXPECT_TRUE(test, + ext4_fc_value_len_isvalid_test(sbi, EXT4_FC_TAG_CREAT, + sizeof(struct ext4_fc_dentry_info) + 1)); + KUNIT_EXPECT_FALSE(test, + ext4_fc_value_len_isvalid_test(sbi, EXT4_FC_TAG_CREAT, + sizeof(struct ext4_fc_dentry_info))); + KUNIT_EXPECT_FALSE(test, + ext4_fc_value_len_isvalid_test(sbi, EXT4_FC_TAG_LINK, + sizeof(struct ext4_fc_dentry_info) + + EXT4_NAME_LEN + 1)); + KUNIT_EXPECT_TRUE(test, + ext4_fc_value_len_isvalid_test(sbi, EXT4_FC_TAG_INODE, + sizeof(struct ext4_fc_inode) + + EXT4_GOOD_OLD_INODE_SIZE)); + KUNIT_EXPECT_FALSE(test, + ext4_fc_value_len_isvalid_test(sbi, EXT4_FC_TAG_INODE, + sizeof(struct ext4_fc_inode) + + TEST_INODE_SIZE + 1)); + KUNIT_EXPECT_TRUE(test, + ext4_fc_value_len_isvalid_test(sbi, EXT4_FC_TAG_PAD, 0)); + KUNIT_EXPECT_TRUE(test, + ext4_fc_value_len_isvalid_test(sbi, EXT4_FC_TAG_TAIL, + sizeof(struct ext4_fc_tail))); + KUNIT_EXPECT_FALSE(test, + ext4_fc_value_len_isvalid_test(sbi, EXT4_FC_TAG_TAIL, + sizeof(struct ext4_fc_tail) - 1)); + KUNIT_EXPECT_TRUE(test, + ext4_fc_value_len_isvalid_test(sbi, EXT4_FC_TAG_HEAD, + sizeof(struct ext4_fc_head))); + KUNIT_EXPECT_FALSE(test, + ext4_fc_value_len_isvalid_test(sbi, 0x9999, 8)); + KUNIT_EXPECT_STREQ(test, tag2str(EXT4_FC_TAG_HEAD), "HEAD"); + KUNIT_EXPECT_STREQ(test, tag2str(0x9999), "ERROR"); + + /* 4) Scan error cases */ + /* Block 0 not starting with HEAD returns 0 (early stop) */ + memset(ctx->fc_buf_data[0], 0, TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_SCAN, 0, 10), + 0); + + /* Unexpected block offset returns -EFSCORRUPTED */ + state->fc_replay_expected_off = 2; + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_SCAN, 1, 10), + -EFSCORRUPTED); + + /* HEAD with unsupported features returns -EOPNOTSUPP */ + memset(state, 0, sizeof(*state)); + memset(ctx->fc_buf_data[0], 0, TEST_BLK_SIZE); + tl.fc_tag = cpu_to_le16(EXT4_FC_TAG_HEAD); + tl.fc_len = cpu_to_le16(sizeof(head)); + head.fc_features = cpu_to_le32(0x1); + head.fc_tid = cpu_to_le32(10); + memcpy(ctx->fc_buf_data[0], &tl, EXT4_FC_TAG_BASE_LEN); + memcpy(ctx->fc_buf_data[0] + EXT4_FC_TAG_BASE_LEN, &head, sizeof(head)); + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_SCAN, 0, 10), + -EOPNOTSUPP); + + /* HEAD with wrong TID returns JBD2_FC_REPLAY_STOP */ + memset(state, 0, sizeof(*state)); + head.fc_features = 0; + head.fc_tid = cpu_to_le32(99); + memcpy(ctx->fc_buf_data[0] + EXT4_FC_TAG_BASE_LEN, &head, sizeof(head)); + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_SCAN, 0, 10), + JBD2_FC_REPLAY_STOP); + + /* + * Corrupted TAIL CRC on first commit stops cleanly with + * JBD2_FC_REPLAY_STOP without failing journal recovery. + */ + memset(state, 0, sizeof(*state)); + sbi->s_fc_bytes = 0; + ctx->journal.j_fc_off = 0; + ctx->running_txn.t_tid = 10; + head.fc_tid = cpu_to_le32(10); + { + u32 crc = 0; + + ext4_fc_add_tlv_test(sb, EXT4_FC_TAG_HEAD, sizeof(head), + (u8 *)&head, &crc); + ext4_fc_write_tail_test(sb, crc); + } + /* Corrupt last byte of tail.fc_crc */ + ctx->fc_buf_data[0][2 * EXT4_FC_TAG_BASE_LEN + sizeof(head) + + offsetof(struct ext4_fc_tail, fc_crc)] ^= 0xFF; + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_SCAN, 0, 10), + JBD2_FC_REPLAY_STOP); + KUNIT_EXPECT_EQ(test, state->fc_replay_num_tags, 0); + + /* + * 5) Valid first commit in block 0 followed by a corrupted second + * commit in block 1 stops cleanly with JBD2_FC_REPLAY_STOP and + * keeps fc_replay_num_tags from block 0. + */ + memset(state, 0, sizeof(*state)); + sbi->s_fc_bytes = 0; + ctx->journal.j_fc_off = 0; + { + u32 crc = 0; + + ext4_fc_add_tlv_test(sb, EXT4_FC_TAG_HEAD, sizeof(head), + (u8 *)&head, &crc); + ext4_fc_write_tail_test(sb, crc); + } + /* Block 1 has an invalid TLV (tag=0) */ + memset(ctx->fc_buf_data[1], 0, TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_SCAN, 0, 10), + JBD2_FC_REPLAY_CONTINUE); + KUNIT_EXPECT_EQ(test, state->fc_replay_num_tags, 2); + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[1], + PASS_SCAN, 1, 10), + JBD2_FC_REPLAY_STOP); + KUNIT_EXPECT_EQ(test, state->fc_replay_num_tags, 2); + ext4_fc_replay_cleanup(sb); + memset(state, 0, sizeof(*state)); +} + +/* ========================================================================= + * 10. Replay of Inode, Create, Link, and Unlink Tags + * ========================================================================= + */ + +static void test_fc_replay_inode_and_dentries(struct kunit *test) +{ + struct fc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = ctx->sbi; + struct inode *root = get_mock_inode(ctx, TEST_ROOT_INO); + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct inode *subdir = get_mock_inode(ctx, TEST_SUBDIR_INO); + struct fc_mock_inode_slot *f1_slot = find_slot(ctx, file1); + struct dentry *dentries; + struct dentry *d_dir, *d_f1, *d_f1_link, *d_subdir, *d_f1_overwrite; + struct ext4_dir_entry_2 *de = NULL; + struct buffer_head *bh; + struct qstr q_f1 = QSTR_INIT("file1", 5); + struct qstr q_f1_ln = QSTR_INIT("file1_ln", 8); + struct qstr q_subdir = QSTR_INIT("subdir", 6); + struct ext4_fc_head head = { + .fc_features = 0, + .fc_tid = cpu_to_le32(10), + }; + u32 crc = 0; + int snap_err = EXT4_FC_SNAP_ERR_NONE; + + dentries = kunit_kcalloc(test, 5, sizeof(*dentries), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dentries); + d_dir = &dentries[0]; + d_f1 = &dentries[1]; + d_f1_link = &dentries[2]; + d_subdir = &dentries[3]; + d_f1_overwrite = &dentries[4]; + + /* Initialize parent directory on-disk block */ + KUNIT_ASSERT_EQ(test, ext4_init_new_dir(NULL, root, dir), 0); + + init_mock_dentry(d_dir, NULL, "dir", dir, sb); + init_mock_dentry(d_f1, d_dir, "file1", file1, sb); + init_mock_dentry(d_f1_link, d_dir, "file1_ln", file1, sb); + init_mock_dentry(d_subdir, d_dir, "subdir", subdir, sb); + + /* Prepare file1 and subdir snapshots */ + file1->i_generation = 0x4242; + i_size_write(file1, 2048); + sync_inode_to_raw(f1_slot); + sync_inode_to_raw(find_slot(ctx, subdir)); + KUNIT_ASSERT_EQ(test, + ext4_fc_snapshot_inode_test(file1, 0, NULL, &snap_err), + 0); + KUNIT_ASSERT_EQ(test, + ext4_fc_snapshot_inode_test(subdir, 0, NULL, &snap_err), + 0); + + /* + * Build a fast commit block containing: + * HEAD -> INODE(file1) -> CREAT(file1) -> LINK(file1_ln) -> + * INODE(subdir) -> CREAT(subdir) -> UNLINK(file1) -> TAIL + */ + sbi->s_fc_bytes = 0; + ctx->journal.j_fc_off = 0; + ctx->running_txn.t_tid = 10; + + ext4_fc_track_create(&ctx->handle, d_f1); + ext4_fc_track_link(&ctx->handle, file1, d_f1_link); + ext4_fc_track_create(&ctx->handle, d_subdir); + ext4_fc_track_unlink(&ctx->handle, d_f1); + + KUNIT_ASSERT_TRUE(test, + ext4_fc_add_tlv_test(sb, EXT4_FC_TAG_HEAD, + sizeof(head), (u8 *)&head, &crc)); + /* Commit all queued dentry updates into block 0 */ + { + struct ext4_fc_dentry_update *fcd; + + list_for_each_entry(fcd, &sbi->s_fc_dentry_q[FC_Q_MAIN], fcd_list) { + struct ext4_fc_dentry_info fcd_info = { + .fc_parent_ino = cpu_to_le32(fcd->fcd_parent), + .fc_ino = cpu_to_le32(fcd->fcd_ino), + }; + u8 d_buf[64]; + int dlen = fcd->fcd_name.name.len; + + if (fcd->fcd_op == EXT4_FC_TAG_CREAT) { + struct inode *c_ino = + get_mock_inode(ctx, fcd->fcd_ino); + KUNIT_ASSERT_EQ(test, + ext4_fc_write_inode_test(c_ino, &crc), + 0); + } + memcpy(d_buf, &fcd_info, sizeof(fcd_info)); + memcpy(d_buf + sizeof(fcd_info), + fcd->fcd_name.name.name, dlen); + KUNIT_ASSERT_TRUE(test, + ext4_fc_add_tlv_test(sb, fcd->fcd_op, + sizeof(fcd_info) + dlen, + d_buf, &crc)); + } + } + KUNIT_ASSERT_EQ(test, ext4_fc_write_tail_test(sb, crc), 0); + + /* Clear file1 generation in raw_buf to verify replay restores it */ + ((struct ext4_inode *)f1_slot->raw_buf)->i_generation = 0; + file1->i_generation = 0; + + /* Scan and replay block 0 */ + memset(&sbi->s_fc_replay_state, 0, sizeof(sbi->s_fc_replay_state)); + KUNIT_ASSERT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_SCAN, 0, 10), + JBD2_FC_REPLAY_CONTINUE); + KUNIT_EXPECT_EQ(test, sbi->s_fc_replay_state.fc_replay_num_tags, 8); + + /* Error injection: ext4_get_fc_inode_loc failure aborts INODE replay */ + ctx->fail_get_fc_inode_loc = -EIO; + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_REPLAY, 0, 10), + -EIO); + ctx->fail_get_fc_inode_loc = 0; + + /* Error injection: sync_dirty_buffer failure aborts INODE replay */ + sbi->s_fc_replay_state.fc_replay_num_tags = 8; + ctx->fail_sync_dirty_buffer = true; + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_REPLAY, 0, 10), + -EIO); + ctx->fail_sync_dirty_buffer = false; + + /* Successful full replay of block 0 */ + sbi->s_fc_replay_state.fc_replay_num_tags = 8; + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_REPLAY, 0, 10), + JBD2_FC_REPLAY_CONTINUE); + KUNIT_EXPECT_EQ(test, sbi->s_fc_replay_state.fc_replay_num_tags, 0); + + /* Calling PASS_REPLAY once fc_replay_num_tags == 0 runs bitmaps & stops */ + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_REPLAY, 1, 10), + 0); + + /* Verify replayed state: file1 generation restored, file1 unlinked, file1_ln & subdir present */ + KUNIT_EXPECT_EQ(test, file1->i_generation, 0x4242U); + + bh = ext4_find_entry_test(dir, &q_f1, &de, NULL); + KUNIT_EXPECT_NULL(test, bh); + + bh = ext4_find_entry_test(dir, &q_f1_ln, &de, NULL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, bh); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), (u32)TEST_FILE1_INO); + brelse(bh); + + bh = ext4_find_entry_test(dir, &q_subdir, &de, NULL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, bh); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), (u32)TEST_SUBDIR_INO); + brelse(bh); + + /* + * Exercise additional replay branches: + * - LINK on an already-existing entry ("file1_ln") ignores -EEXIST + * - UNLINK on an already-removed entry ("file1") returns 0 + * - UNLINK when dentry points to a different inode (simulating + * rename-overwrite) leaves the dentry intact + * - INODE replay of an inline-data inode copies raw_fc_inode->i_block + */ + { + struct inode *file2 = get_mock_inode(ctx, TEST_FILE2_INO); + struct fc_mock_inode_slot *f2_slot = find_slot(ctx, file2); + struct ext4_inode *raw_f2 = (struct ext4_inode *)f2_slot->raw_buf; + struct ext4_fc_dentry_info fcd_info; + u8 d_buf[64]; + + /* Prepare inline-data file2 snapshot */ + ext4_clear_inode_flag(file2, EXT4_INODE_EXTENTS); + ext4_set_inode_flag(file2, EXT4_INODE_INLINE_DATA); + sync_inode_to_raw(f2_slot); + memcpy(raw_f2->i_block, "inline-test-payload", 20); + KUNIT_ASSERT_EQ(test, + ext4_fc_snapshot_inode_test(file2, 0, NULL, + &snap_err), + 0); + memset(raw_f2->i_block, 0, sizeof(raw_f2->i_block)); + + /* Build block: HEAD -> LINK(file1_ln) -> UNLINK(file1) -> INODE(file2) -> TAIL */ + sbi->s_fc_bytes = 0; + ctx->journal.j_fc_off = 0; + crc = 0; + KUNIT_ASSERT_TRUE(test, + ext4_fc_add_tlv_test(sb, EXT4_FC_TAG_HEAD, + sizeof(head), + (u8 *)&head, &crc)); + + /* LINK("file1_ln") when "file1_ln" already exists */ + fcd_info.fc_parent_ino = cpu_to_le32(TEST_DIR_INO); + fcd_info.fc_ino = cpu_to_le32(TEST_FILE1_INO); + memcpy(d_buf, &fcd_info, sizeof(fcd_info)); + memcpy(d_buf + sizeof(fcd_info), "file1_ln", 8); + KUNIT_ASSERT_TRUE(test, + ext4_fc_add_tlv_test(sb, EXT4_FC_TAG_LINK, + sizeof(fcd_info) + 8, + d_buf, &crc)); + + /* UNLINK("file1", ino=TEST_FILE1_INO) */ + memcpy(d_buf, &fcd_info, sizeof(fcd_info)); + memcpy(d_buf + sizeof(fcd_info), "file1", 5); + KUNIT_ASSERT_TRUE(test, + ext4_fc_add_tlv_test(sb, EXT4_FC_TAG_UNLINK, + sizeof(fcd_info) + 5, + d_buf, &crc)); + + /* INODE(file2) with inline data */ + KUNIT_ASSERT_EQ(test, ext4_fc_write_inode_test(file2, &crc), 0); + KUNIT_ASSERT_EQ(test, ext4_fc_write_tail_test(sb, crc), 0); + + /* 1) Replay when "file1" does not exist (UNLINK no-op) */ + sbi->s_fc_replay_state.fc_replay_num_tags = 5; + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_REPLAY, 0, 10), + JBD2_FC_REPLAY_CONTINUE); + KUNIT_EXPECT_EQ(test, + memcmp(raw_f2->i_block, "inline-test-payload", 20), + 0); + + /* 2) Add "file1" pointing to file2, then replay UNLINK(file1, ino=file1) */ + init_mock_dentry(d_f1_overwrite, d_dir, "file1", file2, sb); + KUNIT_ASSERT_EQ(test, + __ext4_link(dir, file2, &d_f1_overwrite->d_name, + d_f1_overwrite), + 0); + + sbi->s_fc_replay_state.fc_replay_num_tags = 5; + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_REPLAY, 0, 10), + JBD2_FC_REPLAY_CONTINUE); + + /* Verify "file1" still points to file2 after UNLINK(file1, ino=file1) */ + bh = ext4_find_entry_test(dir, &q_f1, &de, NULL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, bh); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), + (u32)TEST_FILE2_INO); + brelse(bh); + } + + ext4_fc_replay_cleanup(sb); +} + +/* ========================================================================= + * 11. Replay of Extent Ranges and End-to-End Commit-to-Replay Round-Trip + * ========================================================================= + */ + +static void test_fc_replay_ranges_and_end_to_end(struct kunit *test) +{ + struct fc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = ctx->sbi; + struct inode *root = get_mock_inode(ctx, TEST_ROOT_INO); + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct ext4_inode_info *ei1 = EXT4_I(file1); + struct fc_mock_inode_slot *f1_slot = find_slot(ctx, file1); + struct dentry d_dir, d_f1; + struct ext4_map_blocks map; + struct ext4_dir_entry_2 *de = NULL; + struct buffer_head *bh; + struct qstr q_f1 = QSTR_INIT("e2e_file", 8); + + KUNIT_ASSERT_EQ(test, ext4_init_new_dir(NULL, root, dir), 0); + init_mock_dentry(&d_dir, NULL, "dir", dir, sb); + init_mock_dentry(&d_f1, &d_dir, "e2e_file", file1, sb); + + /* + * Set up file1 modifications for a real ext4_fc_commit(): + * - [0, 3]: written extent at pblk 300 + * - [4, 5]: hole (DEL_RANGE) + * - [6, 9]: unwritten extent at pblk 310 + */ + ctx->journal.j_commit_sequence = 9; + ctx->running_txn.t_tid = 10; + ctx->journal.j_fc_off = 0; + sbi->s_fc_bytes = 0; + + i_size_write(file1, 10 * TEST_BLK_SIZE); + file1->i_generation = 0x7777; + sync_inode_to_raw(f1_slot); + + down_write(&ei1->i_data_sem); + ext4_es_insert_extent(file1, 0, 4, 300, EXTENT_STATUS_WRITTEN, false); + ext4_es_insert_extent(file1, 4, 2, 0, EXTENT_STATUS_HOLE, false); + ext4_es_insert_extent(file1, 6, 4, 310, EXTENT_STATUS_UNWRITTEN, false); + up_write(&ei1->i_data_sem); + + ext4_fc_track_create(&ctx->handle, &d_f1); + ext4_fc_track_range(&ctx->handle, file1, 0, 9); + + /* Execute real ext4_fc_commit() */ + KUNIT_ASSERT_EQ(test, ext4_fc_commit(&ctx->journal, 10), 0); + KUNIT_EXPECT_EQ(test, ctx->journal.j_fc_off, 1U); + + /* + * Simulate pre-crash on-disk state before replay: + * - [0, 3] was mapped to old pblk 250 (to exercise pblk remap & + * old block bitmap freeing in ext4_fc_replay_add_range) + * - [4, 5] was mapped to pblk 260 (to exercise DEL_RANGE removal) + * - [6, 9] was mapped to pblk 310 as written (to exercise state toggle) + */ + ext4_ext_tree_init(NULL, file1); + { + struct ext4_ext_path *path; + struct ext4_extent ex; + + memset(&ex, 0, sizeof(ex)); + ex.ee_block = cpu_to_le32(0); + ex.ee_len = cpu_to_le16(4); + ext4_ext_store_pblock(&ex, 250); + path = ext4_find_extent(file1, 0, NULL, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(path)); + down_write(&ei1->i_data_sem); + path = ext4_ext_insert_extent(NULL, file1, path, &ex, 0); + up_write(&ei1->i_data_sem); + KUNIT_ASSERT_FALSE(test, IS_ERR(path)); + ext4_free_ext_path(path); + + memset(&ex, 0, sizeof(ex)); + ex.ee_block = cpu_to_le32(4); + ex.ee_len = cpu_to_le16(2); + ext4_ext_store_pblock(&ex, 260); + path = ext4_find_extent(file1, 4, NULL, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(path)); + down_write(&ei1->i_data_sem); + path = ext4_ext_insert_extent(NULL, file1, path, &ex, 0); + up_write(&ei1->i_data_sem); + KUNIT_ASSERT_FALSE(test, IS_ERR(path)); + ext4_free_ext_path(path); + + memset(&ex, 0, sizeof(ex)); + ex.ee_block = cpu_to_le32(6); + ex.ee_len = cpu_to_le16(4); + ext4_ext_store_pblock(&ex, 310); + path = ext4_find_extent(file1, 6, NULL, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(path)); + down_write(&ei1->i_data_sem); + path = ext4_ext_insert_extent(NULL, file1, path, &ex, 0); + up_write(&ei1->i_data_sem); + KUNIT_ASSERT_FALSE(test, IS_ERR(path)); + ext4_free_ext_path(path); + } + + /* Run PASS_SCAN followed by PASS_REPLAY on the committed block */ + ctx->nr_bb_marks = 0; + memset(&sbi->s_fc_replay_state, 0, sizeof(sbi->s_fc_replay_state)); + KUNIT_ASSERT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_SCAN, 0, 10), + JBD2_FC_REPLAY_CONTINUE); + KUNIT_EXPECT_GT(test, sbi->s_fc_replay_state.fc_replay_num_tags, 0); + /* Both ADD_RANGE extents ([0,3]->300 and [6,9]->310) are excluded */ + KUNIT_EXPECT_TRUE(test, ext4_fc_replay_check_excluded(sb, 300)); + KUNIT_EXPECT_TRUE(test, ext4_fc_replay_check_excluded(sb, 312)); + + KUNIT_ASSERT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_REPLAY, 0, 10), + JBD2_FC_REPLAY_CONTINUE); + KUNIT_ASSERT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_REPLAY, 1, 10), + 0); + + /* 1) Verify directory entry "e2e_file" was created in dir */ + bh = ext4_find_entry_test(dir, &q_f1, &de, NULL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, bh); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), (u32)TEST_FILE1_INO); + brelse(bh); + + /* 2) Verify [0, 3] is mapped to new pblk 300 (written) */ + map.m_lblk = 0; + map.m_len = 4; + KUNIT_EXPECT_EQ(test, ext4_ext_map_blocks(NULL, file1, &map, 0), 4); + KUNIT_EXPECT_EQ(test, map.m_pblk, 300ULL); + KUNIT_EXPECT_TRUE(test, (map.m_flags & EXT4_MAP_MAPPED) != 0); + + /* 3) Verify [4, 5] hole was punched by DEL_RANGE */ + map.m_lblk = 4; + map.m_len = 2; + KUNIT_EXPECT_EQ(test, ext4_ext_map_blocks(NULL, file1, &map, 0), 0); + + /* 4) Verify [6, 9] is mapped to pblk 310 as unwritten */ + map.m_lblk = 6; + map.m_len = 4; + KUNIT_EXPECT_EQ(test, ext4_ext_map_blocks(NULL, file1, &map, 0), 4); + KUNIT_EXPECT_EQ(test, map.m_pblk, 310ULL); + KUNIT_EXPECT_TRUE(test, (map.m_flags & EXT4_MAP_UNWRITTEN) != 0); + + /* 5) Verify ext4_mb_mark_bb was invoked to free old blocks & mark new ones */ + KUNIT_EXPECT_GT(test, ctx->nr_bb_marks, 0U); + + /* + * 6) Error handling in ADD_RANGE and DEL_RANGE replay: + * - DEL_RANGE when ext4_map_blocks fails propagates error + * - ADD_RANGE when ext4_map_blocks, ext4_find_extent, or + * ext4_ext_insert_extent fails propagates error + * - ADD_RANGE / DEL_RANGE when ext4_iget fails returns 0 + */ + { + struct ext4_fc_del_range del_arg; + struct ext4_fc_add_range add_arg; + struct ext4_extent *ex = (struct ext4_extent *)add_arg.fc_ex; + u32 crc = 0; + + /* DEL_RANGE: ext4_iget failure returns 0; ext4_map_blocks failure returns -EIO */ + sbi->s_fc_bh = NULL; + sbi->s_fc_bytes = 0; + ctx->journal.j_fc_off = 0; + del_arg.fc_ino = cpu_to_le32(TEST_FILE1_INO); + del_arg.fc_lblk = cpu_to_le32(0); + del_arg.fc_len = cpu_to_le32(2); + KUNIT_ASSERT_TRUE(test, + ext4_fc_add_tlv_test(sb, EXT4_FC_TAG_DEL_RANGE, + sizeof(del_arg), + (u8 *)&del_arg, &crc)); + + sbi->s_fc_replay_state.fc_replay_num_tags = 1; + ctx->fail_iget = -ENOENT; + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_REPLAY, 0, 10), + 0); + ctx->fail_iget = 0; + + sbi->s_fc_replay_state.fc_replay_num_tags = 1; + ctx->fail_map_blocks = -EIO; + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_REPLAY, 0, 10), + -EIO); + ctx->fail_map_blocks = 0; + + /* ADD_RANGE on unmapped range [20, 21]: test map_blocks, find_extent, insert_extent failures */ + sbi->s_fc_bh = NULL; + sbi->s_fc_bytes = 0; + ctx->journal.j_fc_off = 0; + memset(&add_arg, 0, sizeof(add_arg)); + add_arg.fc_ino = cpu_to_le32(TEST_FILE1_INO); + ex->ee_block = cpu_to_le32(20); + ex->ee_len = cpu_to_le16(2); + ext4_ext_store_pblock(ex, 400); + KUNIT_ASSERT_TRUE(test, + ext4_fc_add_tlv_test(sb, EXT4_FC_TAG_ADD_RANGE, + sizeof(add_arg), + (u8 *)&add_arg, &crc)); + + sbi->s_fc_replay_state.fc_replay_num_tags = 1; + ctx->fail_map_blocks = -EIO; + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_REPLAY, 0, 10), + -EIO); + ctx->fail_map_blocks = 0; + + sbi->s_fc_replay_state.fc_replay_num_tags = 1; + ctx->fail_find_extent = -EIO; + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_REPLAY, 0, 10), + -EIO); + ctx->fail_find_extent = 0; + + sbi->s_fc_replay_state.fc_replay_num_tags = 1; + ctx->fail_insert_extent = -ENOSPC; + KUNIT_EXPECT_EQ(test, + ext4_fc_replay_test(&ctx->journal, &ctx->fc_bhs[0], + PASS_REPLAY, 0, 10), + -ENOSPC); + ctx->fail_insert_extent = 0; + } + + ext4_fc_replay_cleanup(sb); + KUNIT_EXPECT_FALSE(test, (sbi->s_mount_state & EXT4_FC_REPLAY) != 0); +} + +static struct kunit_case fast_commit_test_cases[] = { + KUNIT_CASE(test_fc_init_and_eligibility), + KUNIT_CASE(test_fc_mark_ineligible), + KUNIT_CASE(test_fc_track_inode_and_range), + KUNIT_CASE(test_fc_track_dentry_and_del), + KUNIT_CASE(test_fc_reserve_space_and_tlv_writing), + KUNIT_CASE(test_fc_snapshot_inode_and_ranges), + KUNIT_CASE(test_fc_cleanup_and_stats), + KUNIT_CASE(test_fc_commit_paths), + KUNIT_CASE(test_fc_replay_regions_and_scan), + KUNIT_CASE(test_fc_replay_inode_and_dentries), + KUNIT_CASE(test_fc_replay_ranges_and_end_to_end), + {} +}; + +static struct kunit_suite fast_commit_test_suite = { + .name = "ext4_fast_commit_test", + .init = fast_commit_test_init, + .test_cases = fast_commit_test_cases, +}; + +kunit_test_suites(&fast_commit_test_suite); + +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/fast_commit.c b/fs/ext4/fast_commit.c index 0cac890cf37029..9beb423b208f80 100644 --- a/fs/ext4/fast_commit.c +++ b/fs/ext4/fast_commit.c @@ -14,6 +14,7 @@ #include #include +#include /* * Ext4 Fast Commits * ----------------- @@ -661,11 +662,25 @@ void ext4_fc_track_range(handle_t *handle, struct inode *inode, ext4_lblk_t star trace_ext4_fc_track_range(handle, inode, start, end, ret); } -static void ext4_fc_submit_bh(struct super_block *sb, bool is_tail) +int ext4_fc_get_buf(journal_t *journal, struct buffer_head **bh) +{ + KUNIT_STATIC_STUB_REDIRECT(ext4_fc_get_buf, journal, bh); + return jbd2_fc_get_buf(journal, bh); +} + +int ext4_fc_issue_flush(struct block_device *bdev) +{ + KUNIT_STATIC_STUB_REDIRECT(ext4_fc_issue_flush, bdev); + return blkdev_issue_flush(bdev); +} + +void ext4_fc_submit_bh(struct super_block *sb, bool is_tail) { blk_opf_t write_flags = JBD2_JOURNAL_REQ_FLAGS; struct buffer_head *bh = EXT4_SB(sb)->s_fc_bh; + KUNIT_STATIC_STUB_REDIRECT(ext4_fc_submit_bh, sb, is_tail); + /* Add REQ_FUA | REQ_PREFLUSH only its tail */ if (test_opt(sb, BARRIER) && is_tail) write_flags |= REQ_FUA | REQ_PREFLUSH; @@ -707,7 +722,7 @@ static u8 *ext4_fc_reserve_space(struct super_block *sb, int len, u32 *crc) return NULL; if (!sbi->s_fc_bh) { - ret = jbd2_fc_get_buf(EXT4_SB(sb)->s_journal, &bh); + ret = ext4_fc_get_buf(EXT4_SB(sb)->s_journal, &bh); if (ret) return NULL; sbi->s_fc_bh = bh; @@ -737,7 +752,7 @@ static u8 *ext4_fc_reserve_space(struct super_block *sb, int len, u32 *crc) ext4_fc_submit_bh(sb, false); - ret = jbd2_fc_get_buf(EXT4_SB(sb)->s_journal, &bh); + ret = ext4_fc_get_buf(EXT4_SB(sb)->s_journal, &bh); if (ret) return NULL; sbi->s_fc_bh = bh; @@ -1425,8 +1440,12 @@ static int ext4_fc_perform_commit(journal_t *journal, tid_t commit_tid) * Step 5: If file system device is different from journal device, * issue a cache flush before we start writing fast commit blocks. */ - if (journal->j_fs_dev != journal->j_dev) - blkdev_issue_flush(journal->j_fs_dev); + if (journal->j_fs_dev != journal->j_dev && + journal->j_flags & JBD2_BARRIER) { + ret = ext4_fc_issue_flush(journal->j_fs_dev); + if (ret) + return ret; + } blk_start_plug(&plug); alloc_ctx = ext4_fc_lock(sb); @@ -1941,8 +1960,11 @@ static int ext4_fc_replay_inode(struct super_block *sb, inode = ext4_iget(sb, ino, EXT4_IGET_NORMAL); if (!IS_ERR(inode)) { - ext4_ext_clear_bb(inode); + ret = ext4_ext_clear_bb(inode); iput(inode); + inode = NULL; + if (ret) + goto out; } inode = NULL; @@ -2002,8 +2024,11 @@ static int ext4_fc_replay_inode(struct super_block *sb, * crashing. This should be fixed but until then, we calculate * the number of blocks the inode. */ - if (!ext4_test_inode_flag(inode, EXT4_INODE_INLINE_DATA)) - ext4_ext_replay_set_iblocks(inode); + if (!ext4_test_inode_flag(inode, EXT4_INODE_INLINE_DATA)) { + ret = ext4_ext_replay_set_iblocks(inode); + if (ret) + goto out_brelse; + } inode->i_generation = le32_to_cpu(ext4_raw_inode(&iloc)->i_generation); ext4_reset_inode_seed(inode); @@ -2016,7 +2041,7 @@ static int ext4_fc_replay_inode(struct super_block *sb, out: iput(inode); if (!ret) - blkdev_issue_flush(sb->s_bdev); + ext4_fc_issue_flush(sb->s_bdev); return ret; } @@ -2062,12 +2087,12 @@ static int ext4_fc_replay_create(struct super_block *sb, dir = ext4_iget(sb, darg.parent_ino, EXT4_IGET_NORMAL); if (IS_ERR(dir)) { ext4_debug("Dir %d not found.", darg.ino); + ret = PTR_ERR(dir); goto out; } ret = ext4_init_new_dir(NULL, dir, inode); iput(dir); if (ret) { - ret = 0; goto out; } } @@ -2075,7 +2100,7 @@ static int ext4_fc_replay_create(struct super_block *sb, if (ret) goto out; set_nlink(inode, 1); - ext4_mark_inode_dirty(NULL, inode); + ret = ext4_mark_inode_dirty(NULL, inode); out: iput(inode); return ret; @@ -2314,13 +2339,13 @@ ext4_fc_replay_del_range(struct super_block *sb, u8 *val) return ret; } -static void ext4_fc_set_bitmaps_and_counters(struct super_block *sb) +static int ext4_fc_set_bitmaps_and_counters(struct super_block *sb) { struct ext4_fc_replay_state *state; struct inode *inode; struct ext4_ext_path *path = NULL; struct ext4_map_blocks map; - int i, ret, j; + int i, ret = 0, j; ext4_lblk_t cur, end; state = &EXT4_SB(sb)->s_fc_replay_state; @@ -2348,13 +2373,14 @@ static void ext4_fc_set_bitmaps_and_counters(struct super_block *sb) if (ret > 0) { path = ext4_find_extent(inode, map.m_lblk, path, 0); - if (!IS_ERR(path)) { - for (j = 0; j < path->p_depth; j++) - ext4_mb_mark_bb(inode->i_sb, - path[j].p_block, 1, true); - } else { + if (IS_ERR(path)) { + ret = PTR_ERR(path); path = NULL; + break; } + for (j = 0; j < path->p_depth; j++) + ext4_mb_mark_bb(inode->i_sb, + path[j].p_block, 1, true); cur += ret; ext4_mb_mark_bb(inode->i_sb, map.m_pblk, map.m_len, true); @@ -2363,9 +2389,14 @@ static void ext4_fc_set_bitmaps_and_counters(struct super_block *sb) } } iput(inode); + if (ret < 0) + goto out; } + ret = 0; +out: ext4_free_ext_path(path); + return ret; } /* @@ -2397,7 +2428,9 @@ void ext4_fc_replay_cleanup(struct super_block *sb) sbi->s_mount_state &= ~EXT4_FC_REPLAY; kfree(sbi->s_fc_replay_state.fc_regions); + sbi->s_fc_replay_state.fc_regions = NULL; kfree(sbi->s_fc_replay_state.fc_modified_inodes); + sbi->s_fc_replay_state.fc_modified_inodes = NULL; } static bool ext4_fc_value_len_isvalid(struct ext4_sb_info *sbi, @@ -2443,6 +2476,12 @@ static bool ext4_fc_value_len_isvalid(struct ext4_sb_info *sbi, * It returns a negative error to indicate that there was an error. At the end * of a successful scan phase, sbi->s_fc_replay_state.fc_replay_num_tags is set * to indicate the number of tags that need to replayed during the replay phase. + * + * An invalid tag or a tail that does not match ends the scan without an error. + * This is what a fast commit that was only partially written before a crash + * looks like. Its tail is written last and fsync() does not return before + * the tail is on disk, so such a fast commit was never reported as durable and + * is simply dropped, like jbd2 drops a transaction without a commit block. */ static int ext4_fc_replay_scan(journal_t *journal, struct buffer_head *bh, int off, @@ -2489,8 +2528,9 @@ static int ext4_fc_replay_scan(journal_t *journal, val = cur + EXT4_FC_TAG_BASE_LEN; if (tl.fc_len > end - val || !ext4_fc_value_len_isvalid(sbi, tl.fc_tag, tl.fc_len)) { - ret = state->fc_replay_num_tags ? - JBD2_FC_REPLAY_STOP : -ECANCELED; + ext4_debug("Scan phase, invalid tag length, blk %lld\n", + bh->b_blocknr); + ret = JBD2_FC_REPLAY_STOP; goto out_err; } ext4_debug("Scan phase, tag:%s, blk %lld\n", @@ -2530,8 +2570,9 @@ static int ext4_fc_replay_scan(journal_t *journal, state->fc_regions_valid = state->fc_regions_used; } else { - ret = state->fc_replay_num_tags ? - JBD2_FC_REPLAY_STOP : -EFSBADCRC; + ext4_debug("Scan phase, invalid tail, blk %lld\n", + bh->b_blocknr); + ret = JBD2_FC_REPLAY_STOP; } state->fc_crc = 0; break; @@ -2551,8 +2592,9 @@ static int ext4_fc_replay_scan(journal_t *journal, EXT4_FC_TAG_BASE_LEN + tl.fc_len); break; default: - ret = state->fc_replay_num_tags ? - JBD2_FC_REPLAY_STOP : -ECANCELED; + ext4_debug("Scan phase, unknown tag %d, blk %lld\n", + tl.fc_tag, bh->b_blocknr); + ret = JBD2_FC_REPLAY_STOP; } if (ret < 0 || ret == JBD2_FC_REPLAY_STOP) break; @@ -2589,8 +2631,7 @@ static int ext4_fc_replay(journal_t *journal, struct buffer_head *bh, } if (!sbi->s_fc_replay_state.fc_replay_num_tags) { ext4_debug("Replay stops\n"); - ext4_fc_set_bitmaps_and_counters(sb); - return 0; + return ext4_fc_set_bitmaps_and_counters(sb); } #ifdef CONFIG_EXT4_DEBUG @@ -2609,8 +2650,7 @@ static int ext4_fc_replay(journal_t *journal, struct buffer_head *bh, val = cur + EXT4_FC_TAG_BASE_LEN; if (state->fc_replay_num_tags == 0) { - ret = JBD2_FC_REPLAY_STOP; - ext4_fc_set_bitmaps_and_counters(sb); + ret = ext4_fc_set_bitmaps_and_counters(sb); break; } @@ -2764,3 +2804,158 @@ void ext4_fc_destroy_dentry_cache(void) kmem_cache_destroy(ext4_fc_range_cachep); kmem_cache_destroy(ext4_fc_dentry_cachep); } + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +void ext4_fc_set_snap_err_test(int *snap_err, int err) +{ + ext4_fc_set_snap_err(snap_err, err); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_set_snap_err_test); + +bool ext4_fc_disabled_test(struct super_block *sb) +{ + return ext4_fc_disabled(sb); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_disabled_test); + +bool ext4_fc_eligible_test(struct super_block *sb) +{ + return ext4_fc_eligible(sb); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_eligible_test); + +void ext4_fc_snap_stats_update_max_test(atomic64_t *stat, u64 value) +{ + ext4_fc_snap_stats_update_max(stat, value); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_snap_stats_update_max_test); + +void ext4_fc_wake_inode_state_test(struct inode *inode, int bit) +{ + ext4_fc_wake_inode_state(inode, bit); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_wake_inode_state_test); + +u8 *ext4_fc_reserve_space_test(struct super_block *sb, int len, u32 *crc) +{ + return ext4_fc_reserve_space(sb, len, crc); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_reserve_space_test); + +int ext4_fc_write_tail_test(struct super_block *sb, u32 crc) +{ + return ext4_fc_write_tail(sb, crc); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_write_tail_test); + +bool ext4_fc_add_tlv_test(struct super_block *sb, u16 tag, u16 len, u8 *val, + u32 *crc) +{ + return ext4_fc_add_tlv(sb, tag, len, val, crc); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_add_tlv_test); + +int ext4_fc_write_inode_test(struct inode *inode, u32 *crc) +{ + return ext4_fc_write_inode(inode, crc); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_write_inode_test); + +int ext4_fc_write_inode_data_test(struct inode *inode, u32 *crc) +{ + return ext4_fc_write_inode_data(inode, crc); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_write_inode_data_test); + +void ext4_fc_free_inode_snap_test(struct inode *inode) +{ + ext4_fc_free_inode_snap(inode); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_free_inode_snap_test); + +int ext4_fc_snapshot_inode_test(struct inode *inode, + unsigned int nr_ranges_total, + unsigned int *nr_rangesp, int *snap_err) +{ + return ext4_fc_snapshot_inode(inode, nr_ranges_total, nr_rangesp, + snap_err); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_snapshot_inode_test); + +unsigned int ext4_fc_count_snapshot_inodes_test(struct super_block *sb) +{ + return ext4_fc_count_snapshot_inodes(sb); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_count_snapshot_inodes_test); + +int ext4_fc_alloc_snapshot_inodes_test(struct super_block *sb, + struct inode ***inodesp, + unsigned int *nr_inodesp) +{ + return ext4_fc_alloc_snapshot_inodes(sb, inodesp, nr_inodesp); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_alloc_snapshot_inodes_test); + +int ext4_fc_snapshot_inodes_test(journal_t *journal, struct inode **inodes, + unsigned int inodes_size, + unsigned int *nr_inodesp, + unsigned int *nr_rangesp, int *snap_err) +{ + return ext4_fc_snapshot_inodes(journal, inodes, inodes_size, + nr_inodesp, nr_rangesp, snap_err); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_snapshot_inodes_test); + +void ext4_fc_update_stats_test(struct super_block *sb, int status, + u64 commit_time, int nblks, tid_t commit_tid) +{ + ext4_fc_update_stats(sb, status, commit_time, nblks, commit_tid); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_update_stats_test); + +void ext4_fc_cleanup_test(journal_t *journal, int full, tid_t tid) +{ + ext4_fc_cleanup(journal, full, tid); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_cleanup_test); + +int ext4_fc_record_modified_inode_test(struct super_block *sb, int ino) +{ + return ext4_fc_record_modified_inode(sb, ino); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_record_modified_inode_test); + +bool ext4_fc_value_len_isvalid_test(struct ext4_sb_info *sbi, int tag, int len) +{ + return ext4_fc_value_len_isvalid(sbi, tag, len); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_value_len_isvalid_test); + +int ext4_fc_replay_test(journal_t *journal, struct buffer_head *bh, + enum passtype pass, int off, tid_t expected_tid) +{ + return ext4_fc_replay(journal, bh, pass, off, expected_tid); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_replay_test); + +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_get_buf); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_submit_bh); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_issue_flush); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_init_inode); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_del); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_mark_ineligible); +EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_fc_track_unlink); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_track_unlink); +EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_fc_track_link); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_track_link); +EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_fc_track_create); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_track_create); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_track_inode); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_track_range); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_commit); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_record_regions); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_replay_check_excluded); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_replay_cleanup); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_init); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_info_show); +#endif diff --git a/fs/ext4/file.c b/fs/ext4/file.c index ad8985c529c61d..cfb22d0d57289d 100644 --- a/fs/ext4/file.c +++ b/fs/ext4/file.c @@ -354,6 +354,14 @@ static ssize_t ext4_buffered_write_iter(struct kiocb *iocb, if (iocb->ki_flags & IOCB_NOWAIT) return -EOPNOTSUPP; + /* + * Buffered I/O provides no torn-write protection. The direct I/O path + * falls back here for inodes that can't do direct I/O at all, so an + * atomic write must be rejected rather than silently done non-atomically. + */ + if (iocb->ki_flags & IOCB_ATOMIC) + return -EOPNOTSUPP; + inode_lock(inode); /* @@ -689,11 +697,12 @@ static ssize_t ext4_dio_write_iter(struct kiocb *iocb, struct iov_iter *from) loff_t endbyte; /* - * There is no support for atomic writes on buffered-io yet, - * we should never fallback to buffered-io for DIO atomic - * writes. + * Buffered I/O provides no torn-write protection, so never + * finish an atomic write through the page cache. iomap must + * not return a short atomic write, so treat one as a bug. */ - WARN_ON_ONCE(iocb->ki_flags & IOCB_ATOMIC); + if (WARN_ON_ONCE(iocb->ki_flags & IOCB_ATOMIC)) + return -EIO; offset = iocb->ki_pos; err = ext4_buffered_write_iter(iocb, from); diff --git a/fs/ext4/fsmap-test.c b/fs/ext4/fsmap-test.c new file mode 100644 index 00000000000000..0142dd7d2ec3a0 --- /dev/null +++ b/fs/ext4/fsmap-test.c @@ -0,0 +1,796 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for fs/ext4/fsmap.c (FS_IOC_GETFSMAP reverse-mapping queries). + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "fsmap.h" +#include "mballoc.h" + +#define FSMAP_TEST_MAX_GROUPS 4 +#define FSMAP_TEST_MAX_CLUSTERS_PER_GRP 1024 +#define FSMAP_TEST_MAX_RECS 24 +#define FSMAP_TEST_DATADEV MKDEV(8, 1) +#define FSMAP_TEST_LOGDEV MKDEV(8, 2) + +/* + * Matches struct bdev_inode layout in block/bdev.c so file_bdev() resolves + * &bdev via container_of(bdev_file->f_mapping->host, ...). + */ +struct fsmap_mock_bdev_inode { + struct block_device bdev; + struct inode vfs_inode; +}; + +struct fsmap_rec_sink { + struct ext4_fsmap recs[FSMAP_TEST_MAX_RECS]; + unsigned int count; + unsigned int abort_after; + int fail_err; +}; + +struct fsmap_test_ctx { + struct super_block *sb; + struct ext4_sb_info sbi; + struct ext4_super_block es; + struct buffer_head sbh; + char sbh_data[4096]; + + struct fsmap_mock_bdev_inode data_bdev; + struct fsmap_mock_bdev_inode log_bdev; + struct file log_bdev_file; + journal_t mock_journal; + + struct buffer_head gdb_bh; + struct buffer_head *gdb_bh_arr[1]; + u8 gdb_data[4096]; + + DECLARE_BITMAP(grp_bms[FSMAP_TEST_MAX_GROUPS], + FSMAP_TEST_MAX_CLUSTERS_PER_GRP); +}; + +static struct fsmap_test_ctx *fsmap_active_ctx; + +static void fsmap_noop_work(struct work_struct *work) +{ +} + +static void fsmap_noop_timer(struct timer_list *timer) +{ +} + +static const struct super_operations fsmap_test_sops = {}; + +static int fsmap_test_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static int fsmap_test_set_super(struct super_block *sb, struct fs_context *fc) +{ + return set_anon_super_fc(sb, fc); +} + +static struct file_system_type fsmap_test_fs_type = { + .name = "ext4-fsmap-test", + .init_fs_context = fsmap_test_init_fs_context, + .kill_sb = kill_anon_super, +}; + +static void fsmap_cleanup_ctx(void *data) +{ + struct fsmap_test_ctx *ctx = data; + + fsmap_active_ctx = NULL; + cancel_work_sync(&ctx->sbi.s_sb_upd_work); + timer_delete_sync(&ctx->sbi.s_err_report); + + if (ctx->sb) + deactivate_super(ctx->sb); + if (ctx->data_bdev.bdev.bd_stats) + free_percpu(ctx->data_bdev.bdev.bd_stats); + if (ctx->log_bdev.bdev.bd_stats) + free_percpu(ctx->log_bdev.bdev.bd_stats); +} + +static int fsmap_query_range_stub(struct super_block *sb, + ext4_group_t group, + ext4_grpblk_t first, + ext4_grpblk_t end, + ext4_mballoc_query_range_fn meta_formatter, + ext4_mballoc_query_range_fn formatter, + void *priv) +{ + struct fsmap_test_ctx *ctx = fsmap_active_ctx; + ext4_grpblk_t max_clu = EXT4_CLUSTERS_PER_GROUP(sb); + ext4_grpblk_t first_free, start, next; + unsigned long *bm; + int error; + + if (!ctx || group >= FSMAP_TEST_MAX_GROUPS) + return -EINVAL; + + bm = ctx->grp_bms[group]; + if ((unsigned long)end >= EXT4_CLUSTERS_PER_GROUP(sb)) + end = max_clu - 1; + + first_free = find_next_zero_bit(bm, max_clu, 0); + start = max_t(ext4_grpblk_t, first_free, first); + + if (meta_formatter && start != first) { + if (start > end) + start = end; + error = meta_formatter(sb, group, first, start - first, priv); + if (error) + return error; + } + + while (start <= end) { + start = find_next_zero_bit(bm, end + 1, start); + if (start > end) + break; + next = find_next_bit(bm, end + 1, start); + + error = formatter(sb, group, start, next - start, priv); + if (error) + return error; + + start = next + 1; + } + + return 0; +} + +static int fsmap_collect_cb(struct ext4_fsmap *fmr, void *priv) +{ + struct fsmap_rec_sink *sink = priv; + + if (sink->fail_err) + return sink->fail_err; + + if (sink->count < FSMAP_TEST_MAX_RECS) + sink->recs[sink->count] = *fmr; + sink->count++; + + if (sink->abort_after && sink->count >= sink->abort_after) + return EXT4_QUERY_RANGE_ABORT; + + return EXT4_QUERY_RANGE_CONTINUE; +} + +static void fsmap_mark_clusters_used(struct fsmap_test_ctx *ctx, + ext4_group_t agno, + ext4_grpblk_t start_clu, + ext4_grpblk_t len_clu) +{ + bitmap_set(ctx->grp_bms[agno], start_clu, len_clu); +} + +static void fsmap_set_group_tables(struct fsmap_test_ctx *ctx, + ext4_group_t agno, + ext4_fsblk_t blk_bm, + ext4_fsblk_t ino_bm, + ext4_fsblk_t itable) +{ + struct super_block *sb = ctx->sb; + struct ext4_group_desc *gdp; + + gdp = (struct ext4_group_desc *)(ctx->gdb_data + + agno * EXT4_DESC_SIZE(sb)); + ext4_block_bitmap_set(sb, gdp, blk_bm); + ext4_inode_bitmap_set(sb, gdp, ino_bm); + ext4_inode_table_set(sb, gdp, itable); +} + +static struct fsmap_test_ctx *fsmap_create_ctx(struct kunit *test, + unsigned int blocksize_bits, + unsigned int cluster_bits, + ext4_group_t groups_count, + ext4_grpblk_t blocks_per_group) +{ + struct fsmap_test_ctx *ctx; + struct fs_context *fc; + struct super_block *sb; + struct ext4_sb_info *sbi; + unsigned int blocksize = 1U << blocksize_bits; + ext4_fsblk_t bofs = (blocksize == 1024) ? 1 : 0; + int err; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + + sbi = &ctx->sbi; + INIT_WORK(&sbi->s_sb_upd_work, fsmap_noop_work); + timer_setup(&sbi->s_err_report, fsmap_noop_timer, 0); + err = kunit_add_action_or_reset(test, fsmap_cleanup_ctx, ctx); + KUNIT_ASSERT_EQ(test, err, 0); + + inode_init_once(&ctx->data_bdev.vfs_inode); + address_space_init_once(&ctx->data_bdev.vfs_inode.i_data); + ctx->data_bdev.vfs_inode.i_data.host = &ctx->data_bdev.vfs_inode; + ctx->data_bdev.bdev.bd_dev = FSMAP_TEST_DATADEV; + ctx->data_bdev.bdev.bd_mapping = &ctx->data_bdev.vfs_inode.i_data; + ctx->data_bdev.bdev.bd_stats = alloc_percpu(struct disk_stats); + KUNIT_ASSERT_TRUE(test, ctx->data_bdev.bdev.bd_stats != NULL); + + inode_init_once(&ctx->log_bdev.vfs_inode); + address_space_init_once(&ctx->log_bdev.vfs_inode.i_data); + ctx->log_bdev.vfs_inode.i_data.host = &ctx->log_bdev.vfs_inode; + ctx->log_bdev.bdev.bd_dev = FSMAP_TEST_LOGDEV; + ctx->log_bdev.bdev.bd_mapping = &ctx->log_bdev.vfs_inode.i_data; + ctx->log_bdev.bdev.bd_stats = alloc_percpu(struct disk_stats); + KUNIT_ASSERT_TRUE(test, ctx->log_bdev.bdev.bd_stats != NULL); + ctx->log_bdev_file.f_mapping = &ctx->log_bdev.vfs_inode.i_data; + + spin_lock_init(&sbi->s_error_lock); + spin_lock_init(&sbi->s_bdev_wb_lock); + ratelimit_state_init(&sbi->s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, + DEFAULT_RATELIMIT_BURST); + + fc = fs_context_for_mount(&fsmap_test_fs_type, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(fc)); + sb = sget_fc(fc, NULL, fsmap_test_set_super); + put_fs_context(fc); + KUNIT_ASSERT_FALSE(test, IS_ERR(sb)); + up_write(&sb->s_umount); + + ctx->sb = sb; + + sb->s_fs_info = sbi; + sb->s_op = &fsmap_test_sops; + sb->s_bdev = &ctx->data_bdev.bdev; + sb->s_blocksize = blocksize; + sb->s_blocksize_bits = blocksize_bits; + strscpy(sb->s_id, "ext4-fsmap", sizeof(sb->s_id)); + + ctx->sbh.b_data = ctx->sbh_data; + ctx->sbh.b_size = blocksize; + ctx->sbh.b_bdev = sb->s_bdev; + atomic_set(&ctx->sbh.b_count, 2); + set_buffer_uptodate(&ctx->sbh); + clear_buffer_mapped(&ctx->sbh); + + sbi->s_sb = sb; + sbi->s_es = &ctx->es; + sbi->s_sbh = &ctx->sbh; + set_opt(sb, ERRORS_CONT); + + ctx->es.s_magic = cpu_to_le16(EXT4_SUPER_MAGIC); + ctx->es.s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + ctx->es.s_first_data_block = cpu_to_le32(bofs); + ctx->es.s_feature_incompat = cpu_to_le32(EXT4_FEATURE_INCOMPAT_64BIT); + ctx->es.s_desc_size = cpu_to_le16(64); + ext4_blocks_count_set(&ctx->es, + bofs + (ext4_fsblk_t)groups_count * + blocks_per_group); + + sbi->s_desc_size = 64; + sbi->s_desc_per_block = blocksize / sbi->s_desc_size; + sbi->s_desc_per_block_bits = ilog2(sbi->s_desc_per_block); + sbi->s_addr_per_block_bits = ilog2(EXT4_ADDR_PER_BLOCK(sb)); + sbi->s_groups_count = groups_count; + sbi->s_blocks_per_group = blocks_per_group; + sbi->s_cluster_bits = cluster_bits; + sbi->s_cluster_ratio = 1U << cluster_bits; + sbi->s_clusters_per_group = blocks_per_group >> cluster_bits; + sbi->s_itb_per_group = 8; + sbi->s_gdb_count = 1; + + ctx->gdb_bh.b_data = ctx->gdb_data; + ctx->gdb_bh.b_size = blocksize; + ctx->gdb_bh.b_bdev = sb->s_bdev; + atomic_set(&ctx->gdb_bh.b_count, 2); + set_buffer_uptodate(&ctx->gdb_bh); + ctx->gdb_bh_arr[0] = &ctx->gdb_bh; + rcu_assign_pointer(sbi->s_group_desc, ctx->gdb_bh_arr); + + fsmap_active_ctx = ctx; + kunit_activate_static_stub(test, ext4_mballoc_query_range, + fsmap_query_range_stub); + + return ctx; +} + +static void fsmap_init_full_range_head(struct ext4_fsmap_head *head, + unsigned int count) +{ + memset(head, 0, sizeof(*head)); + head->fmh_count = count; + head->fmh_keys[1].fmr_device = UINT_MAX; + head->fmh_keys[1].fmr_physical = U64_MAX; + head->fmh_keys[1].fmr_owner = U64_MAX; + head->fmh_keys[1].fmr_flags = UINT_MAX; +} + +static void fsmap_expect_rec(struct kunit *test, const struct ext4_fsmap *rec, + u32 exp_dev, u64 exp_phys, u64 exp_len, + u64 exp_owner) +{ + KUNIT_EXPECT_EQ(test, (u32)rec->fmr_device, exp_dev); + KUNIT_EXPECT_EQ(test, rec->fmr_physical, exp_phys); + KUNIT_EXPECT_EQ(test, rec->fmr_length, exp_len); + KUNIT_EXPECT_EQ(test, rec->fmr_owner, exp_owner); + KUNIT_EXPECT_EQ(test, rec->fmr_flags, (u32)FMR_OF_SPECIAL_OWNER); +} + +/* + * Verify ext4_fsmap_from_internal() and ext4_fsmap_to_internal() block-to-byte + * and byte-to-block scaling across 1K, 4K, and 64K block sizes. + */ +static void test_fsmap_unit_conversions(struct kunit *test) +{ + static const unsigned int shifts[] = { 10, 12, 16 }; + struct fsmap_test_ctx *ctx; + struct ext4_fsmap internal = {}; + struct ext4_fsmap roundtrip = {}; + struct fsmap uapi = {}; + int i; + + ctx = fsmap_create_ctx(test, 12, 0, 1, 256); + + for (i = 0; i < ARRAY_SIZE(shifts); i++) { + unsigned int bits = shifts[i]; + + ctx->sb->s_blocksize_bits = bits; + ctx->sb->s_blocksize = 1U << bits; + + memset(&uapi, 0xaa, sizeof(uapi)); + internal.fmr_device = new_encode_dev(FSMAP_TEST_DATADEV); + internal.fmr_flags = FMR_OF_SPECIAL_OWNER; + internal.fmr_physical = 42; + internal.fmr_owner = EXT4_FMR_OWN_INODES; + internal.fmr_length = 17; + + ext4_fsmap_from_internal(ctx->sb, &uapi, &internal); + KUNIT_EXPECT_EQ(test, uapi.fmr_device, + (u32)internal.fmr_device); + KUNIT_EXPECT_EQ(test, uapi.fmr_flags, internal.fmr_flags); + KUNIT_EXPECT_EQ(test, uapi.fmr_physical, 42ULL << bits); + KUNIT_EXPECT_EQ(test, uapi.fmr_owner, EXT4_FMR_OWN_INODES); + KUNIT_EXPECT_EQ(test, uapi.fmr_offset, 0ULL); + KUNIT_EXPECT_EQ(test, uapi.fmr_length, 17ULL << bits); + KUNIT_EXPECT_EQ(test, uapi.fmr_reserved[0], 0U); + KUNIT_EXPECT_EQ(test, uapi.fmr_reserved[1], 0U); + KUNIT_EXPECT_EQ(test, uapi.fmr_reserved[2], 0U); + + /* Non-block-aligned byte tails truncate down to whole blocks */ + uapi.fmr_physical += (1ULL << bits) - 1; + uapi.fmr_length += (1ULL << bits) - 1; + ext4_fsmap_to_internal(ctx->sb, &roundtrip, &uapi); + KUNIT_EXPECT_EQ(test, roundtrip.fmr_device, + internal.fmr_device); + KUNIT_EXPECT_EQ(test, roundtrip.fmr_flags, internal.fmr_flags); + KUNIT_EXPECT_EQ(test, roundtrip.fmr_physical, 42ULL); + KUNIT_EXPECT_EQ(test, roundtrip.fmr_owner, EXT4_FMR_OWN_INODES); + KUNIT_EXPECT_EQ(test, roundtrip.fmr_length, 17ULL); + } +} + +/* + * Verify ext4_getfsmap() input flag, device ID, key ordering, out-of-range + * physical start, and missing group descriptor (-EFSCORRUPTED) checks. + */ +static void test_getfsmap_invalid_flags_devices_and_keys(struct kunit *test) +{ + struct fsmap_test_ctx *ctx; + struct ext4_fsmap_head head; + struct fsmap_rec_sink *sink; + u32 datadev = new_encode_dev(FSMAP_TEST_DATADEV); + int err; + + sink = kunit_kzalloc(test, sizeof(*sink), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, sink); + ctx = fsmap_create_ctx(test, 12, 0, 1, 256); + fsmap_set_group_tables(ctx, 0, 2, 3, 4); + fsmap_mark_clusters_used(ctx, 0, 0, 12); + + /* Invalid fmh_iflags -> -EINVAL */ + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + head.fmh_iflags = ~FMH_IF_VALID; + KUNIT_EXPECT_EQ(test, ext4_getfsmap(ctx->sb, &head, + fsmap_collect_cb, sink), -EINVAL); + + /* Unrecognized low or high device ID -> -EINVAL */ + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + head.fmh_keys[0].fmr_device = new_encode_dev(MKDEV(9, 9)); + KUNIT_EXPECT_EQ(test, ext4_getfsmap(ctx->sb, &head, + fsmap_collect_cb, sink), -EINVAL); + + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + head.fmh_keys[1].fmr_device = new_encode_dev(MKDEV(9, 9)); + KUNIT_EXPECT_EQ(test, ext4_getfsmap(ctx->sb, &head, + fsmap_collect_cb, sink), -EINVAL); + + /* Inverted device, physical block, or owner keys -> -EINVAL */ + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + head.fmh_keys[0].fmr_device = UINT_MAX; + head.fmh_keys[1].fmr_device = 0; + KUNIT_EXPECT_EQ(test, ext4_getfsmap(ctx->sb, &head, + fsmap_collect_cb, sink), -EINVAL); + + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + head.fmh_keys[0].fmr_device = datadev; + head.fmh_keys[1].fmr_device = datadev; + head.fmh_keys[0].fmr_physical = 50; + head.fmh_keys[1].fmr_physical = 40; + KUNIT_EXPECT_EQ(test, ext4_getfsmap(ctx->sb, &head, + fsmap_collect_cb, sink), -EINVAL); + + /* Equal low+len and high physical with owner 0 == 0 -> -EINVAL */ + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + head.fmh_keys[0].fmr_device = datadev; + head.fmh_keys[1].fmr_device = datadev; + head.fmh_keys[0].fmr_physical = 20; + head.fmh_keys[0].fmr_length = 10; + head.fmh_keys[1].fmr_physical = 30; + head.fmh_keys[1].fmr_owner = 0; + KUNIT_EXPECT_EQ(test, ext4_getfsmap(ctx->sb, &head, + fsmap_collect_cb, sink), -EINVAL); + + /* Low key starting past eofs returns 0 entries cleanly */ + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + head.fmh_keys[0].fmr_device = datadev; + head.fmh_keys[1].fmr_device = datadev; + head.fmh_keys[0].fmr_physical = 500; + head.fmh_keys[1].fmr_physical = 600; + err = ext4_getfsmap(ctx->sb, &head, fsmap_collect_cb, sink); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, head.fmh_entries, 0U); + KUNIT_EXPECT_EQ(test, head.fmh_oflags, (u32)FMH_OF_DEV_T); + + /* Missing group descriptor returns -EFSCORRUPTED */ + ctx->gdb_bh_arr[0] = NULL; + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + set_bit(EXT4_FLAGS_SHUTDOWN, &ctx->sbi.s_ext4_flags); + err = ext4_getfsmap(ctx->sb, &head, fsmap_collect_cb, sink); + clear_bit(EXT4_FLAGS_SHUTDOWN, &ctx->sbi.s_ext4_flags); + ctx->gdb_bh_arr[0] = &ctx->gdb_bh; + KUNIT_EXPECT_EQ(test, err, -EFSCORRUPTED); +} + +/* + * Verify synthesis of fixed per-group metadata (SB, GDT, reserved GDT, block + * bitmap, inode bitmap, inode table), free extents, and EXT4_FMR_OWN_UNKNOWN + * gaps both in the middle and at the very end of the filesystem. + */ +static void test_getfsmap_fixed_metadata_and_unknown_gaps(struct kunit *test) +{ + struct fsmap_test_ctx *ctx; + struct ext4_fsmap_head head; + struct fsmap_rec_sink *sink; + u32 datadev = new_encode_dev(FSMAP_TEST_DATADEV); + int err; + + sink = kunit_kzalloc(test, sizeof(*sink), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, sink); + ctx = fsmap_create_ctx(test, 12, 0, 1, 256); + ctx->es.s_reserved_gdt_blocks = cpu_to_le16(2); + + /* + * Group 0 layout [0, 256): + * 0 : superblock (OWN_FS, len 1) + * 1 : GDT (OWN_GDT, len 1) + * 2..3 : reserved GDT (OWN_RESV_GDT, len 2) + * 4 : block bitmap (OWN_BLKBM, len 1) + * 5 : inode bitmap (OWN_INOBM, len 1) + * 6..13 : inode table (OWN_INODES, len 8) + * 14..19 : allocated user data (OWN_UNKNOWN, len 6) + * 20..99 : free space (OWN_FREE, len 80) + * 100..109: allocated user data (OWN_UNKNOWN, len 10) + * 110..249: free space (OWN_FREE, len 140) + * 250..255: allocated user data at EOFS (OWN_UNKNOWN, len 6) + */ + fsmap_set_group_tables(ctx, 0, 4, 5, 6); + fsmap_mark_clusters_used(ctx, 0, 0, 20); + fsmap_mark_clusters_used(ctx, 0, 100, 10); + fsmap_mark_clusters_used(ctx, 0, 250, 6); + + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + err = ext4_getfsmap(ctx->sb, &head, fsmap_collect_cb, sink); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_ASSERT_EQ(test, head.fmh_entries, 11U); + KUNIT_ASSERT_EQ(test, sink->count, 11U); + + fsmap_expect_rec(test, &sink->recs[0], datadev, 0, 1, EXT4_FMR_OWN_FS); + fsmap_expect_rec(test, &sink->recs[1], datadev, 1, 1, EXT4_FMR_OWN_GDT); + fsmap_expect_rec(test, &sink->recs[2], datadev, 2, 2, + EXT4_FMR_OWN_RESV_GDT); + fsmap_expect_rec(test, &sink->recs[3], datadev, 4, 1, + EXT4_FMR_OWN_BLKBM); + fsmap_expect_rec(test, &sink->recs[4], datadev, 5, 1, + EXT4_FMR_OWN_INOBM); + fsmap_expect_rec(test, &sink->recs[5], datadev, 6, 8, + EXT4_FMR_OWN_INODES); + fsmap_expect_rec(test, &sink->recs[6], datadev, 14, 6, + EXT4_FMR_OWN_UNKNOWN); + fsmap_expect_rec(test, &sink->recs[7], datadev, 20, 80, + EXT4_FMR_OWN_FREE); + fsmap_expect_rec(test, &sink->recs[8], datadev, 100, 10, + EXT4_FMR_OWN_UNKNOWN); + fsmap_expect_rec(test, &sink->recs[9], datadev, 110, 140, + EXT4_FMR_OWN_FREE); + fsmap_expect_rec(test, &sink->recs[10], datadev, 250, 6, + EXT4_FMR_OWN_UNKNOWN); +} + +/* + * Verify flex_bg adjacent fixed-metadata merging via + * ext4_getfsmap_merge_fixed_metadata() and cross-group free-extent coalescing + * via info->gfi_lastfree. + */ +static void test_getfsmap_cross_group_free_and_fixed_meta_coalescing( + struct kunit *test) +{ + struct fsmap_test_ctx *ctx; + struct ext4_fsmap_head head; + struct fsmap_rec_sink *sink; + u32 datadev = new_encode_dev(FSMAP_TEST_DATADEV); + int err; + + sink = kunit_kzalloc(test, sizeof(*sink), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, sink); + ctx = fsmap_create_ctx(test, 12, 0, 2, 256); + /* SPARSE_SUPER2 with 0 backup groups -> group 1 has no SB/GDT */ + ctx->es.s_feature_compat = cpu_to_le32(EXT4_FEATURE_COMPAT_SPARSE_SUPER2); + + /* + * Flex_bg-packed metadata in group 0 for both groups 0 and 1: + * 0 : SB (len 1) + * 1 : GDT (len 1) + * 2..3 : group 0 + group 1 block bitmaps -> merged len 2! + * 4..5 : group 0 + group 1 inode bitmaps -> merged len 2! + * 6..21 : group 0 + group 1 inode tables (8 + 8) -> merged len 16! + * 22..255 (grp 0) + 256..511 (grp 1): contiguous free space across + * group boundary -> coalesced via gfi_lastfree into [22, 512) len 490! + */ + fsmap_set_group_tables(ctx, 0, 2, 4, 6); + fsmap_set_group_tables(ctx, 1, 3, 5, 14); + fsmap_mark_clusters_used(ctx, 0, 0, 22); + + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + err = ext4_getfsmap(ctx->sb, &head, fsmap_collect_cb, sink); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, head.fmh_entries, 6U); + + fsmap_expect_rec(test, &sink->recs[0], datadev, 0, 1, EXT4_FMR_OWN_FS); + fsmap_expect_rec(test, &sink->recs[1], datadev, 1, 1, EXT4_FMR_OWN_GDT); + fsmap_expect_rec(test, &sink->recs[2], datadev, 2, 2, + EXT4_FMR_OWN_BLKBM); + fsmap_expect_rec(test, &sink->recs[3], datadev, 4, 2, + EXT4_FMR_OWN_INOBM); + fsmap_expect_rec(test, &sink->recs[4], datadev, 6, 16, + EXT4_FMR_OWN_INODES); + fsmap_expect_rec(test, &sink->recs[5], datadev, 22, 490, + EXT4_FMR_OWN_FREE); +} + +/* + * Verify 1K blocksize (s_first_data_block == 1), bigalloc cluster-to-block + * scaling, and META_BG suppression of reserved GDT blocks. + */ +static void test_getfsmap_1k_bofs_bigalloc_and_meta_bg(struct kunit *test) +{ + struct fsmap_test_ctx *ctx; + struct ext4_fsmap_head head; + struct fsmap_rec_sink *sink; + u32 datadev = new_encode_dev(FSMAP_TEST_DATADEV); + int err; + + sink = kunit_kzalloc(test, sizeof(*sink), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, sink); + + /* + * 1K blocks (s_first_data_block = 1), cluster_bits = 2 (4 blks/clu), + * 1 group of 256 blocks (64 clusters) covering fsblks [1, 257). + * Enable META_BG with s_first_meta_bg = 0 and verify s_reserved_gdt_blocks + * is ignored. + */ + ctx = fsmap_create_ctx(test, 10, 2, 1, 256); + ext4_set_feature_meta_bg(ctx->sb); + ext4_set_feature_bigalloc(ctx->sb); + ctx->es.s_first_meta_bg = 0; + ctx->es.s_reserved_gdt_blocks = cpu_to_le16(5); + + /* + * Cluster 0 = fsblks [1, 5): SB(1), GDT(2), BLKBM(3), INOBM(4) + * Clusters 1..2 = fsblks [5, 13): INODES (len 8) + * Clusters 3..4 = fsblks [13, 21): allocated data (OWN_UNKNOWN, len 8) + * Clusters 5..63 = fsblks [21, 257): free (OWN_FREE, len 236) + */ + fsmap_set_group_tables(ctx, 0, 3, 4, 5); + fsmap_mark_clusters_used(ctx, 0, 0, 5); + + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + err = ext4_getfsmap(ctx->sb, &head, fsmap_collect_cb, sink); + KUNIT_ASSERT_EQ(test, err, 0); + /* Note: block 0 before s_first_data_block=1 is reported as gap [0, 1) */ + KUNIT_ASSERT_EQ(test, head.fmh_entries, 8U); + + fsmap_expect_rec(test, &sink->recs[0], datadev, 0, 1, + EXT4_FMR_OWN_UNKNOWN); + fsmap_expect_rec(test, &sink->recs[1], datadev, 1, 1, EXT4_FMR_OWN_FS); + fsmap_expect_rec(test, &sink->recs[2], datadev, 2, 1, EXT4_FMR_OWN_GDT); + fsmap_expect_rec(test, &sink->recs[3], datadev, 3, 1, + EXT4_FMR_OWN_BLKBM); + fsmap_expect_rec(test, &sink->recs[4], datadev, 4, 1, + EXT4_FMR_OWN_INOBM); + fsmap_expect_rec(test, &sink->recs[5], datadev, 5, 8, + EXT4_FMR_OWN_INODES); + fsmap_expect_rec(test, &sink->recs[6], datadev, 13, 8, + EXT4_FMR_OWN_UNKNOWN); + fsmap_expect_rec(test, &sink->recs[7], datadev, 21, 236, + EXT4_FMR_OWN_FREE); +} + +/* + * Verify count-only queries (fmh_count == 0), bounded pagination with + * continuation keys (non-zero low fmr_length), and formatter abort propagation. + */ +static void test_getfsmap_count_only_pagination_and_abort(struct kunit *test) +{ + struct fsmap_test_ctx *ctx; + struct ext4_fsmap_head head; + struct fsmap_rec_sink *full, *page, *cb_abort; + unsigned int collected = 0; + int err; + + full = kunit_kzalloc(test, sizeof(*full), GFP_KERNEL); + page = kunit_kzalloc(test, sizeof(*page), GFP_KERNEL); + cb_abort = kunit_kzalloc(test, sizeof(*cb_abort), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, full); + KUNIT_ASSERT_NOT_NULL(test, page); + KUNIT_ASSERT_NOT_NULL(test, cb_abort); + + ctx = fsmap_create_ctx(test, 12, 0, 1, 256); + fsmap_set_group_tables(ctx, 0, 2, 3, 4); + fsmap_mark_clusters_used(ctx, 0, 0, 16); + + /* Reference full run: SB(0), GDT(1), BLKBM(2), INOBM(3), INODES(4..11), + * UNKNOWN(12..15), FREE(16..255) -> 7 records. + */ + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + err = ext4_getfsmap(ctx->sb, &head, fsmap_collect_cb, full); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_ASSERT_EQ(test, full->count, 7U); + + /* 1. Count-only mode (fmh_count == 0) does not invoke formatter */ + fsmap_init_full_range_head(&head, 0); + err = ext4_getfsmap(ctx->sb, &head, NULL, NULL); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, head.fmh_entries, 7U); + + /* 2. Paginate 2 records at a time using last record as low key */ + fsmap_init_full_range_head(&head, 2); + while (true) { + unsigned int prev_count = page->count; + + err = ext4_getfsmap(ctx->sb, &head, fsmap_collect_cb, page); + collected += head.fmh_entries; + if (err == 0) + break; + KUNIT_ASSERT_EQ(test, err, EXT4_QUERY_RANGE_ABORT); + KUNIT_ASSERT_EQ(test, head.fmh_entries, 2U); + KUNIT_ASSERT_GT(test, page->count, prev_count); + head.fmh_keys[0] = page->recs[page->count - 1]; + } + KUNIT_ASSERT_EQ(test, collected, 7U); + KUNIT_ASSERT_EQ(test, page->count, 7U); + for (unsigned int i = 0; i < 7; i++) { + KUNIT_EXPECT_EQ(test, page->recs[i].fmr_physical, + full->recs[i].fmr_physical); + KUNIT_EXPECT_EQ(test, page->recs[i].fmr_length, + full->recs[i].fmr_length); + KUNIT_EXPECT_EQ(test, page->recs[i].fmr_owner, + full->recs[i].fmr_owner); + } + + /* 3. Formatter-initiated abort stops immediately */ + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + cb_abort->abort_after = 3; + err = ext4_getfsmap(ctx->sb, &head, fsmap_collect_cb, cb_abort); + KUNIT_EXPECT_EQ(test, err, EXT4_QUERY_RANGE_ABORT); + KUNIT_EXPECT_EQ(test, cb_abort->count, 3U); + + /* 4. Formatter error return propagates directly */ + memset(cb_abort, 0, sizeof(*cb_abort)); + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + cb_abort->fail_err = -EFAULT; + err = ext4_getfsmap(ctx->sb, &head, fsmap_collect_cb, cb_abort); + KUNIT_EXPECT_EQ(test, err, -EFAULT); + KUNIT_EXPECT_EQ(test, cb_abort->count, 0U); +} + +/* + * Verify external journal device reporting (EXT4_FMR_OWN_LOG and leading gap) + * across multi-device wildcard queries and log-device-targeted queries. + */ +static void test_getfsmap_external_logdev_and_multi_device(struct kunit *test) +{ + struct fsmap_test_ctx *ctx; + struct ext4_fsmap_head head; + struct fsmap_rec_sink *sink; + u32 datadev = new_encode_dev(FSMAP_TEST_DATADEV); + u32 logdev = new_encode_dev(FSMAP_TEST_LOGDEV); + int err; + + sink = kunit_kzalloc(test, sizeof(*sink), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, sink); + ctx = fsmap_create_ctx(test, 12, 0, 1, 128); + fsmap_set_group_tables(ctx, 0, 2, 3, 4); + fsmap_mark_clusters_used(ctx, 0, 0, 12); + + KUNIT_ASSERT_PTR_EQ(test, file_bdev(&ctx->log_bdev_file), + &ctx->log_bdev.bdev); + ctx->mock_journal.j_blk_offset = 16; + ctx->mock_journal.j_total_len = 64; + ctx->sbi.s_journal = &ctx->mock_journal; + ctx->sbi.s_journal_bdev_file = &ctx->log_bdev_file; + + /* Multi-device query [0, UINT_MAX] emits datadev (6 recs) + logdev (2) */ + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + err = ext4_getfsmap(ctx->sb, &head, fsmap_collect_cb, sink); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_ASSERT_EQ(test, head.fmh_entries, 8U); + KUNIT_EXPECT_EQ(test, (u32)sink->recs[0].fmr_device, datadev); + fsmap_expect_rec(test, &sink->recs[6], logdev, 0, 16, + EXT4_FMR_OWN_UNKNOWN); + fsmap_expect_rec(test, &sink->recs[7], logdev, 16, 64, + EXT4_FMR_OWN_LOG); + + /* Targeted query against only logdev starting at 0 */ + memset(sink, 0, sizeof(*sink)); + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + head.fmh_keys[0].fmr_device = logdev; + head.fmh_keys[1].fmr_device = logdev; + err = ext4_getfsmap(ctx->sb, &head, fsmap_collect_cb, sink); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_ASSERT_EQ(test, head.fmh_entries, 2U); + fsmap_expect_rec(test, &sink->recs[0], logdev, 0, 16, + EXT4_FMR_OWN_UNKNOWN); + fsmap_expect_rec(test, &sink->recs[1], logdev, 16, 64, + EXT4_FMR_OWN_LOG); + + /* Logdev query with physical > 0 returns 0 entries */ + memset(sink, 0, sizeof(*sink)); + fsmap_init_full_range_head(&head, FSMAP_TEST_MAX_RECS); + head.fmh_keys[0].fmr_device = logdev; + head.fmh_keys[0].fmr_physical = 80; + head.fmh_keys[1].fmr_device = logdev; + err = ext4_getfsmap(ctx->sb, &head, fsmap_collect_cb, sink); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, head.fmh_entries, 0U); +} + +static struct kunit_case fsmap_test_cases[] = { + KUNIT_CASE(test_fsmap_unit_conversions), + KUNIT_CASE(test_getfsmap_invalid_flags_devices_and_keys), + KUNIT_CASE(test_getfsmap_fixed_metadata_and_unknown_gaps), + KUNIT_CASE(test_getfsmap_cross_group_free_and_fixed_meta_coalescing), + KUNIT_CASE(test_getfsmap_1k_bofs_bigalloc_and_meta_bg), + KUNIT_CASE(test_getfsmap_count_only_pagination_and_abort), + KUNIT_CASE(test_getfsmap_external_logdev_and_multi_device), + {} +}; + +static struct kunit_suite fsmap_test_suite = { + .name = "ext4_fsmap_test", + .test_cases = fsmap_test_cases, +}; + +kunit_test_suites(&fsmap_test_suite); + +MODULE_DESCRIPTION("KUnit tests for ext4 FS_IOC_GETFSMAP implementation"); +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/fsmap.c b/fs/ext4/fsmap.c index 8b1138d2dc8efe..f41c2298d1969c 100644 --- a/fs/ext4/fsmap.c +++ b/fs/ext4/fsmap.c @@ -26,6 +26,7 @@ void ext4_fsmap_from_internal(struct super_block *sb, struct fsmap *dest, dest->fmr_reserved[1] = 0; dest->fmr_reserved[2] = 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fsmap_from_internal); /* Convert an fsmap to an ext4_fsmap. */ void ext4_fsmap_to_internal(struct super_block *sb, struct ext4_fsmap *dest, @@ -37,6 +38,7 @@ void ext4_fsmap_to_internal(struct super_block *sb, struct ext4_fsmap *dest, dest->fmr_owner = src->fmr_owner; dest->fmr_length = src->fmr_length >> sb->s_blocksize_bits; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fsmap_to_internal); /* getfsmap query state */ struct ext4_getfsmap_info { @@ -790,3 +792,4 @@ int ext4_getfsmap(struct super_block *sb, struct ext4_fsmap_head *head, head->fmh_oflags = FMH_OF_DEV_T; return error; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_getfsmap); diff --git a/fs/ext4/hash-test.c b/fs/ext4/hash-test.c index 49b0d874c833a5..2898f112a43790 100644 --- a/fs/ext4/hash-test.c +++ b/fs/ext4/hash-test.c @@ -9,6 +9,7 @@ #include #include #include +#include #include "ext4.h" static void ext4_hash_init_fake_dir(struct inode *dir, struct super_block *sb) @@ -16,6 +17,7 @@ static void ext4_hash_init_fake_dir(struct inode *dir, struct super_block *sb) memset(sb, 0, sizeof(*sb)); memset(dir, 0, sizeof(*dir)); dir->i_sb = sb; + sb->s_user_ns = &init_user_ns; strscpy(sb->s_id, "kunit-ext4", sizeof(sb->s_id)); } @@ -48,6 +50,7 @@ static void ext4_hash_init_fake_ext4_dir(struct ext4_inode_info *ei, memset(sbi, 0, sizeof(*sbi)); strscpy(sb->s_id, "kunit-ext4", sizeof(sb->s_id)); + sb->s_user_ns = &init_user_ns; sb->s_fs_info = sbi; sbi->s_sb = sb; diff --git a/fs/ext4/ialloc-test.c b/fs/ext4/ialloc-test.c new file mode 100644 index 00000000000000..c68b60c9596140 --- /dev/null +++ b/fs/ext4/ialloc-test.c @@ -0,0 +1,2731 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for fs/ext4/ialloc.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_jbd2.h" +#include "ext4_extents.h" +#include "xattr.h" +#include "acl.h" + +/* + * Multi-group mock filesystem geometry: + * - 4 block groups, 1024-byte blocks (8192 bits per bitmap block) + * - 64 inodes per group (256 total inodes), 256-byte inodes (4 per block) + * - 16 inode table blocks per group, 1024 blocks (clusters) per group + * - s_first_data_block = 1, s_first_ino = 11 (inodes 1..10 reserved in bg 0) + * - sparse_super enabled: groups 0, 1, 3 have backup super + 1 gdb (2 base + * clusters), while group 2 has 0 base clusters (18 total overhead clusters, + * leaving 1024 - 18 = 1006 free clusters after init). + */ +#define IALLOC_TEST_NGROUPS 4U +#define IALLOC_TEST_BLK_SIZE 1024U +#define IALLOC_TEST_BLK_BITS 10U +#define IALLOC_TEST_BLOCKS_PER_GRP 1024U +#define IALLOC_TEST_FIRST_DATA_BLK 1U +#define IALLOC_TEST_TOTAL_BLKS (IALLOC_TEST_FIRST_DATA_BLK + \ + IALLOC_TEST_NGROUPS * IALLOC_TEST_BLOCKS_PER_GRP) +#define IALLOC_TEST_INODE_SIZE 256U +#define IALLOC_TEST_EXTRA_ISIZE 32U +#define IALLOC_TEST_INODES_PER_BLK (IALLOC_TEST_BLK_SIZE / IALLOC_TEST_INODE_SIZE) +#define IALLOC_TEST_INODES_PER_GRP 64U +#define IALLOC_TEST_ITB_PER_GRP (IALLOC_TEST_INODES_PER_GRP / \ + IALLOC_TEST_INODES_PER_BLK) +#define IALLOC_TEST_TOTAL_INODES (IALLOC_TEST_NGROUPS * IALLOC_TEST_INODES_PER_GRP) +#define IALLOC_TEST_FIRST_INO 11U +#define IALLOC_TEST_BG0_FREE_INODES (IALLOC_TEST_INODES_PER_GRP - \ + (IALLOC_TEST_FIRST_INO - 1U)) +#define IALLOC_TEST_DEFAULT_FREE_CLU 800U +#define IALLOC_TEST_CSUM_SEED 0x6d4b29a3U + +#define IALLOC_TEST_GDESC_BLK 2ULL +#define IALLOC_TEST_POOL_SIZE 32U +#define IALLOC_TEST_MAX_TRACKED_INODES 32U + +struct ialloc_test_blk { + bool in_use; + bool in_cache; + bool marked_dirty; + ext4_fsblk_t blocknr; + struct buffer_head bh; + char cache_buf[IALLOC_TEST_BLK_SIZE] __aligned(8); + char disk_buf[IALLOC_TEST_BLK_SIZE] __aligned(8); +}; + +struct ialloc_test_ctx { + struct super_block *sb; + struct ext4_sb_info sbi; + struct ext4_super_block es; + struct blockgroup_lock bgl; + struct block_device bdev; + struct request_queue bdev_queue; + struct inode bd_inode; + struct buffer_head sb_bh; + struct buffer_head gdesc_bh; + char gdesc_buf[IALLOC_TEST_BLK_SIZE] __aligned(8); + bool gdesc_marked_dirty; + + struct ext4_group_desc gdps[IALLOC_TEST_NGROUPS]; + struct ext4_group_info *grp_infos[IALLOC_TEST_NGROUPS]; + struct ext4_group_info *grp_info_ptrs[16]; + struct ext4_group_info **grp_info_slice[1]; + + struct flex_groups flex_grps[IALLOC_TEST_NGROUPS]; + struct flex_groups *flex_grp_ptrs[IALLOC_TEST_NGROUPS]; + + struct inode *root_inode; + + struct ext4_inode_info standalone_ei; + struct inode *tracked_inodes[IALLOC_TEST_MAX_TRACKED_INODES]; + unsigned int nr_tracked_inodes; + bool evict_skip_free; + + struct ialloc_test_blk pool[IALLOC_TEST_POOL_SIZE]; + + /* Fault injection and call tracking */ + u32 fail_gdp_mask; + bool fail_getblk; + bool fail_read_eio; + bool fail_alloc_inode; + bool fail_sync_dirty_buffer; + int fail_bbitmap_err; + int fail_wait_bbitmap_err; + int fail_write_access_err; + int fail_write_access_on_call; + int fail_dirty_metadata_err; + int fail_dirty_metadata_on_call; + int fail_mark_inode_dirty_err; +#ifdef CONFIG_EXT4_FS_SECURITY + int fail_init_security_err; +#endif + int fail_itable_zeroout_err; + int fail_iget_err; + struct inode *iget_inode; + + unsigned int read_bh_calls; + unsigned int write_access_calls; + unsigned int dirty_metadata_calls; + unsigned int zeroout_calls; + ext4_fsblk_t last_zeroout_blk; + int last_zeroout_num; + int last_zeroout_barrier; +}; + +static inline ext4_fsblk_t ialloc_test_group_start(ext4_group_t g) +{ + return IALLOC_TEST_FIRST_DATA_BLK + + (ext4_fsblk_t)g * IALLOC_TEST_BLOCKS_PER_GRP; +} + +static inline ext4_fsblk_t ialloc_test_bbitmap_blk(ext4_group_t g) +{ + return ialloc_test_group_start(g) + 2; +} + +static inline ext4_fsblk_t ialloc_test_ibitmap_blk(ext4_group_t g) +{ + return ialloc_test_group_start(g) + 3; +} + +static inline ext4_fsblk_t ialloc_test_itable_blk(ext4_group_t g) +{ + return ialloc_test_group_start(g) + 4; +} + +static inline void clear_bitmap_uptodate(struct buffer_head *bh) +{ + clear_bit(BH_BITMAP_UPTODATE, &bh->b_state); +} + +static void ialloc_test_init_ei_fields(struct ext4_inode_info *ei) +{ + inode_set_iversion(&ei->vfs_inode, 1); + ei->i_flags = 0; + ext4_clear_state_flags(ei); + spin_lock_init(&ei->i_raw_lock); + ei->i_prealloc_node = RB_ROOT; + atomic_set(&ei->i_prealloc_active, 0); + rwlock_init(&ei->i_prealloc_lock); + ext4_es_init_tree(&ei->i_es_tree); + rwlock_init(&ei->i_es_lock); + INIT_LIST_HEAD(&ei->i_es_list); + ei->i_es_all_nr = 0; + ei->i_es_shk_nr = 0; + ei->i_es_shrink_lblk = 0; + ei->i_es_seq = 0; + ei->i_reserved_data_blocks = 0; + spin_lock_init(&ei->i_block_reservation_lock); + ext4_init_pending_tree(&ei->i_pending_tree); +#ifdef CONFIG_QUOTA + ei->i_reserved_quota = 0; + memset(&ei->i_dquot, 0, sizeof(ei->i_dquot)); +#endif +#ifdef CONFIG_FS_ENCRYPTION + ei->i_crypt_info = NULL; +#endif + ei->jinode = NULL; + init_rwsem(&ei->xattr_sem); + INIT_LIST_HEAD(&ei->i_rsv_conversion_list); + spin_lock_init(&ei->i_completed_io_lock); + ei->i_sync_tid = 0; + ei->i_datasync_tid = 0; + INIT_LIST_HEAD(&ei->i_orphan); + ext4_fc_init_inode(&ei->vfs_inode); + spin_lock_init(&ei->i_fc_lock); + ei->i_metadata_bhs = NULL; + ei->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + ei->i_extra_isize = IALLOC_TEST_EXTRA_ISIZE; + ei->i_csum_seed = IALLOC_TEST_CSUM_SEED; + ei->i_last_alloc_group = ~0U; +} + +static struct inode *ialloc_test_alloc_inode(struct super_block *sb) +{ + struct kunit *test = kunit_get_current_test(); + struct ialloc_test_ctx *ctx = test ? test->priv : NULL; + struct ext4_inode_info *ei; + + if (ctx && ctx->fail_alloc_inode) + return NULL; + + ei = kzalloc_obj(*ei); + if (!ei) + return NULL; + + init_rwsem(&ei->i_data_sem); + inode_init_once(&ei->vfs_inode); + ialloc_test_init_ei_fields(ei); + return &ei->vfs_inode; +} + +static void ialloc_test_evict_inode(struct inode *inode) +{ + struct kunit *test = kunit_get_current_test(); + struct ialloc_test_ctx *ctx = test ? test->priv : NULL; + + truncate_inode_pages_final(&inode->i_data); + if (ctx && !ctx->evict_skip_free && + !inode->i_nlink && !is_bad_inode(inode)) { + ext4_free_inode(NULL, inode); + return; + } + ext4_clear_inode(inode); +} + +static void ialloc_test_destroy_inode(struct inode *inode) +{ + kfree(ext4_i_metadata_bhs(inode)); + EXT4_I(inode)->i_metadata_bhs = NULL; +} + +static void ialloc_test_free_inode_mem(struct inode *inode) +{ + kfree(EXT4_I(inode)); +} + +#ifdef CONFIG_QUOTA +static struct dquot __rcu **ialloc_test_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} + +static qsize_t *ialloc_test_get_reserved_space(struct inode *inode) +{ + return &EXT4_I(inode)->i_reserved_quota; +} + +static const struct dquot_operations ialloc_test_qops = { + .get_reserved_space = ialloc_test_get_reserved_space, +}; +#endif + +static const struct super_operations ialloc_test_sops = { + .alloc_inode = ialloc_test_alloc_inode, + .evict_inode = ialloc_test_evict_inode, + .destroy_inode = ialloc_test_destroy_inode, + .free_inode = ialloc_test_free_inode_mem, + .drop_inode = inode_just_drop, +#ifdef CONFIG_QUOTA + .get_dquots = ialloc_test_get_dquots, +#endif +}; + +static int ialloc_test_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static struct file_system_type ialloc_test_fs_type = { + .name = "ext4_ialloc_kunit", + .init_fs_context = ialloc_test_init_fs_context, + .kill_sb = kill_anon_super, +}; + +static struct ialloc_test_blk *ialloc_test_find_blk(struct ialloc_test_ctx *ctx, + ext4_fsblk_t blocknr) +{ + unsigned int i; + + for (i = 0; i < IALLOC_TEST_POOL_SIZE; i++) { + if (ctx->pool[i].in_use && ctx->pool[i].blocknr == blocknr) + return &ctx->pool[i]; + } + return NULL; +} + +static struct ialloc_test_blk *ialloc_test_find_blk_by_bh( + struct ialloc_test_ctx *ctx, struct buffer_head *bh) +{ + unsigned int i; + + for (i = 0; i < IALLOC_TEST_POOL_SIZE; i++) { + if (ctx->pool[i].in_use && &ctx->pool[i].bh == bh) + return &ctx->pool[i]; + } + return NULL; +} + +static struct ialloc_test_blk *ialloc_test_setup_blk(struct ialloc_test_ctx *ctx, + ext4_fsblk_t blocknr, + bool in_cache, + bool uptodate) +{ + struct ialloc_test_blk *slot = ialloc_test_find_blk(ctx, blocknr); + unsigned int i; + + if (!slot) { + for (i = 0; i < IALLOC_TEST_POOL_SIZE; i++) { + if (!ctx->pool[i].in_use) { + slot = &ctx->pool[i]; + break; + } + } + } + if (!slot) + return NULL; + + memset(slot, 0, sizeof(*slot)); + slot->in_use = true; + slot->in_cache = in_cache; + slot->blocknr = blocknr; + slot->bh.b_bdev = &ctx->bdev; + slot->bh.b_blocknr = blocknr; + slot->bh.b_size = IALLOC_TEST_BLK_SIZE; + slot->bh.b_data = slot->cache_buf; + atomic_set(&slot->bh.b_count, 1); + if (uptodate) + set_buffer_uptodate(&slot->bh); + return slot; +} + +/* --- Static Stubs --- */ + +static struct ext4_group_desc *ialloc_test_get_group_desc_stub( + struct super_block *sb, ext4_group_t block_group, + struct buffer_head **bh) +{ + struct kunit *test = kunit_get_current_test(); + struct ialloc_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx || block_group >= EXT4_SB(sb)->s_groups_count) + return NULL; + if (block_group < 32 && (ctx->fail_gdp_mask & BIT(block_group))) + return NULL; + if (bh) + *bh = &ctx->gdesc_bh; + return &ctx->gdps[block_group]; +} + +static struct buffer_head *ialloc_test_sb_getblk_stub(struct super_block *sb, + ext4_fsblk_t block) +{ + struct kunit *test = kunit_get_current_test(); + struct ialloc_test_ctx *ctx = test ? test->priv : NULL; + struct ialloc_test_blk *slot; + + if (!ctx || ctx->fail_getblk) + return NULL; + slot = ialloc_test_find_blk(ctx, block); + if (!slot) + return NULL; + slot->in_cache = true; + get_bh(&slot->bh); + return &slot->bh; +} + +static struct buffer_head *ialloc_test_sb_find_get_block_stub( + struct super_block *sb, ext4_fsblk_t block) +{ + struct kunit *test = kunit_get_current_test(); + struct ialloc_test_ctx *ctx = test ? test->priv : NULL; + struct ialloc_test_blk *slot; + + if (!ctx) + return NULL; + slot = ialloc_test_find_blk(ctx, block); + if (!slot || !slot->in_cache) + return NULL; + get_bh(&slot->bh); + return &slot->bh; +} + +static int ialloc_test_read_bh_stub(struct buffer_head *bh, blk_opf_t op_flags, + bio_end_io_t end_io, bool simu_fail) +{ + struct kunit *test = kunit_get_current_test(); + struct ialloc_test_ctx *ctx = test ? test->priv : NULL; + struct ialloc_test_blk *slot; + bool fail; + + if (!ctx) { + unlock_buffer(bh); + return -EIO; + } + ctx->read_bh_calls++; + slot = ialloc_test_find_blk_by_bh(ctx, bh); + fail = ctx->fail_read_eio || simu_fail || !slot; + + if (!fail) + memcpy(bh->b_data, slot->disk_buf, bh->b_size); + + if (end_io) { + struct bio *bio = bio_alloc(NULL, 0, REQ_OP_READ, GFP_KERNEL); + + if (bio) { + bio->bi_private = bh; + bio->bi_status = fail ? BLK_STS_IOERR : BLK_STS_OK; + end_io(bio); + return fail ? -EIO : 0; + } + } + + if (fail) { + clear_buffer_uptodate(bh); + } else { + set_buffer_uptodate(bh); + set_bitmap_uptodate(bh); + } + unlock_buffer(bh); + return fail ? -EIO : 0; +} + +static struct buffer_head *ialloc_test_read_bbitmap_nowait_stub( + struct super_block *sb, ext4_group_t block_group, + bool ignore_locked) +{ + struct kunit *test = kunit_get_current_test(); + struct ialloc_test_ctx *ctx = test ? test->priv : NULL; + struct ialloc_test_blk *slot; + + if (!ctx) + return ERR_PTR(-EIO); + if (ctx->fail_bbitmap_err) + return ERR_PTR(ctx->fail_bbitmap_err); + slot = ialloc_test_find_blk(ctx, ialloc_test_bbitmap_blk(block_group)); + if (!slot) + return ERR_PTR(-ENOMEM); + set_buffer_uptodate(&slot->bh); + set_bitmap_uptodate(&slot->bh); + set_buffer_verified(&slot->bh); + get_bh(&slot->bh); + return &slot->bh; +} + +static int ialloc_test_wait_bbitmap_stub(struct super_block *sb, + ext4_group_t block_group, + struct buffer_head *bh) +{ + struct kunit *test = kunit_get_current_test(); + struct ialloc_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) + return -EIO; + return ctx->fail_wait_bbitmap_err; +} + +static int ialloc_test_get_write_access_stub( + const char *where, unsigned int line, handle_t *handle, + struct super_block *sb, struct buffer_head *bh, + enum ext4_journal_trigger_type trigger_type) +{ + struct kunit *test = kunit_get_current_test(); + struct ialloc_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) + return 0; + ctx->write_access_calls++; + if (ctx->fail_write_access_err && + (!ctx->fail_write_access_on_call || + ctx->write_access_calls == ctx->fail_write_access_on_call)) + return ctx->fail_write_access_err; + return 0; +} + +static int ialloc_test_dirty_metadata_stub(const char *where, unsigned int line, + handle_t *handle, + struct inode *inode, + struct buffer_head *bh) +{ + struct kunit *test = kunit_get_current_test(); + struct ialloc_test_ctx *ctx = test ? test->priv : NULL; + struct ialloc_test_blk *slot; + + if (!ctx) + return 0; + ctx->dirty_metadata_calls++; + if (ctx->fail_dirty_metadata_err && + (!ctx->fail_dirty_metadata_on_call || + ctx->dirty_metadata_calls == ctx->fail_dirty_metadata_on_call)) + return ctx->fail_dirty_metadata_err; + + if (bh) { + set_buffer_uptodate(bh); + if (bh == &ctx->gdesc_bh) { + ctx->gdesc_marked_dirty = true; + } else { + slot = ialloc_test_find_blk_by_bh(ctx, bh); + if (slot) + slot->marked_dirty = true; + } + if (ctx->fail_sync_dirty_buffer) { + clear_buffer_mapped(bh); + set_buffer_dirty(bh); + } else { + clear_buffer_dirty(bh); + } + } + return 0; +} + +static int ialloc_test_mark_inode_dirty_stub(handle_t *handle, + struct inode *inode, + const char *func, + unsigned int line) +{ + struct kunit *test = kunit_get_current_test(); + struct ialloc_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) + return 0; + return ctx->fail_mark_inode_dirty_err; +} + +#ifdef CONFIG_EXT4_FS_SECURITY +static int ialloc_test_init_security_stub(handle_t *handle, + struct inode *inode, + struct inode *dir, + const struct qstr *qstr) +{ + struct kunit *test = kunit_get_current_test(); + struct ialloc_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) + return 0; + return ctx->fail_init_security_err; +} +#endif + +static int ialloc_test_itable_zeroout_stub(struct super_block *sb, + ext4_fsblk_t blk, int num, + int barrier) +{ + struct kunit *test = kunit_get_current_test(); + struct ialloc_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) + return -EIO; + ctx->zeroout_calls++; + ctx->last_zeroout_blk = blk; + ctx->last_zeroout_num = num; + ctx->last_zeroout_barrier = barrier; + return ctx->fail_itable_zeroout_err; +} + +static struct inode *ialloc_test_iget_stub(struct super_block *sb, + unsigned long ino, + ext4_iget_flags flags, + const char *function, + unsigned int line) +{ + struct kunit *test = kunit_get_current_test(); + struct ialloc_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) + return ERR_PTR(-EIO); + if (ctx->fail_iget_err) + return ERR_PTR(ctx->fail_iget_err); + if (!ctx->iget_inode) + return ERR_PTR(-ENOENT); + ihold(ctx->iget_inode); + return ctx->iget_inode; +} + +/* --- Fixture Helpers & Cleanup --- */ + +static void ialloc_test_track_inode(struct kunit *test, + struct ialloc_test_ctx *ctx, + struct inode *inode) +{ + if (inode_state_read_once(inode) & I_NEW) + unlock_new_inode(inode); + KUNIT_ASSERT_LT(test, ctx->nr_tracked_inodes, + IALLOC_TEST_MAX_TRACKED_INODES); + ctx->tracked_inodes[ctx->nr_tracked_inodes++] = inode; +} + +static void ialloc_test_untrack_inode(struct ialloc_test_ctx *ctx, + struct inode *inode) +{ + unsigned int i; + + for (i = 0; i < ctx->nr_tracked_inodes; i++) { + if (ctx->tracked_inodes[i] == inode) { + ctx->tracked_inodes[i] = + ctx->tracked_inodes[--ctx->nr_tracked_inodes]; + ctx->tracked_inodes[ctx->nr_tracked_inodes] = NULL; + return; + } + } +} + +static void ialloc_test_sync_ibitmap_csum(struct ialloc_test_ctx *ctx, + ext4_group_t g, bool sync_disk) +{ + struct ialloc_test_blk *slot; + + slot = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(g)); + if (!slot) + return; + ext4_inode_bitmap_csum_set(ctx->sb, &ctx->gdps[g], &slot->bh); + ext4_group_desc_csum_set(ctx->sb, g, &ctx->gdps[g]); + if (sync_disk) + memcpy(slot->disk_buf, slot->cache_buf, IALLOC_TEST_BLK_SIZE); +} + +static void ialloc_test_enable_flex_bg(struct ialloc_test_ctx *ctx, + unsigned int log_groups_per_flex) +{ + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + ext4_group_t g, fg; + + ext4_set_feature_flex_bg(sb); + sbi->s_log_groups_per_flex = log_groups_per_flex; + for (g = 0; g < IALLOC_TEST_NGROUPS; g++) { + atomic_set(&ctx->flex_grps[g].free_inodes, 0); + atomic_set(&ctx->flex_grps[g].used_dirs, 0); + atomic64_set(&ctx->flex_grps[g].free_clusters, 0); + } + for (g = 0; g < IALLOC_TEST_NGROUPS; g++) { + fg = ext4_flex_group(sbi, g); + atomic_add(ext4_free_inodes_count(sb, &ctx->gdps[g]), + &ctx->flex_grps[fg].free_inodes); + atomic_add(ext4_used_dirs_count(sb, &ctx->gdps[g]), + &ctx->flex_grps[fg].used_dirs); + atomic64_add(ext4_free_group_clusters(sb, &ctx->gdps[g]), + &ctx->flex_grps[fg].free_clusters); + } +} + +static void ialloc_test_prep_standalone_free_inode(struct ialloc_test_ctx *ctx, + unsigned long ino, + umode_t mode) +{ + struct ext4_inode_info *ei = &ctx->standalone_ei; + struct inode *inode = &ei->vfs_inode; + + memset(ei, 0, sizeof(*ei)); + init_rwsem(&ei->i_data_sem); + inode_init_once(inode); + inode->i_sb = ctx->sb; + inode->i_ino = ino; + inode->i_mode = mode; + inode->i_blkbits = ctx->sb->s_blocksize_bits; + inode->i_flags = S_NOQUOTA; + inode->i_mapping = &inode->i_data; + inode->i_data.host = inode; + mapping_set_gfp_mask(&inode->i_data, GFP_HIGHUSER_MOVABLE); + init_rwsem(&inode->i_rwsem); + init_rwsem(&inode->i_data.invalidate_lock); + spin_lock_init(&inode->i_lock); + inode_state_assign_raw(inode, I_FREEING); + inode->__i_nlink = 0; + atomic_set(&inode->i_count, 1); + ialloc_test_init_ei_fields(ei); +} + +static void ialloc_test_cleanup(void *data) +{ + struct ialloc_test_ctx *ctx = data; + handle_t *handle; + unsigned int i; + + ctx->evict_skip_free = true; + ctx->sbi.s_journal = NULL; + + while ((handle = ext4_journal_current_handle()) != NULL) + ext4_journal_stop(handle); + + for (i = 0; i < ctx->nr_tracked_inodes; i++) { + struct inode *ti = ctx->tracked_inodes[i]; + + if (ti) { + if (inode_state_read_once(ti) & I_NEW) + unlock_new_inode(ti); + spin_lock(&ti->i_lock); + inode_state_clear(ti, I_DIRTY_TIME); + spin_unlock(&ti->i_lock); + set_nlink(ti, 1); + iput(ti); + ctx->tracked_inodes[i] = NULL; + } + } + ctx->nr_tracked_inodes = 0; + + if (ctx->root_inode) { + set_nlink(ctx->root_inode, 2); + ctx->root_inode = NULL; + } + + deactivate_super(ctx->sb); + rcu_barrier(); + + percpu_counter_destroy(&ctx->sbi.s_dirs_counter); + percpu_counter_destroy(&ctx->sbi.s_freeinodes_counter); + percpu_counter_destroy(&ctx->sbi.s_freeclusters_counter); + + kfree(ctx); +} + +static int ialloc_test_init(struct kunit *test) +{ + struct ialloc_test_ctx *ctx; + struct fs_context *fc; + struct super_block *sb; + struct ext4_sb_info *sbi; + ext4_group_t g; + unsigned int bit; + s64 total_free_inodes = 0; + s64 total_free_clusters = 0; + int err; + + ctx = kzalloc_obj(*ctx); + KUNIT_ASSERT_NOT_NULL(test, ctx); + test->priv = ctx; + + fc = fs_context_for_mount(&ialloc_test_fs_type, 0); + if (IS_ERR(fc)) { + err = PTR_ERR(fc); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + sb = sget_fc(fc, NULL, set_anon_super_fc); + put_fs_context(fc); + if (IS_ERR(sb)) { + err = PTR_ERR(sb); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + ctx->sb = sb; + sbi = &ctx->sbi; + + sbi->s_sb = sb; + sb->s_fs_info = sbi; + sb->s_op = &ialloc_test_sops; +#ifdef CONFIG_QUOTA + sb->dq_op = &ialloc_test_qops; +#endif +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; +#endif + sb->s_flags |= SB_ACTIVE; + sb->s_blocksize = IALLOC_TEST_BLK_SIZE; + sb->s_blocksize_bits = IALLOC_TEST_BLK_BITS; + sb->s_maxbytes = MAX_LFS_FILESIZE; + sb->s_time_gran = 1; + sb->s_xattr = ext4_xattr_handlers; + strscpy(sb->s_id, "ext4_ialloc_kunit", sizeof(sb->s_id)); + + inode_init_once(&ctx->bd_inode); + ctx->bd_inode.i_sb = sb; + ctx->bd_inode.i_blkbits = IALLOC_TEST_BLK_BITS; + ctx->bd_inode.i_mapping = &ctx->bd_inode.i_data; + ctx->bd_inode.i_data.host = &ctx->bd_inode; + ctx->bdev_queue.limits.logical_block_size = 512; + ctx->bdev_queue.limits.dma_alignment = 511; + ctx->bdev.bd_queue = &ctx->bdev_queue; + ctx->bdev.bd_mapping = &ctx->bd_inode.i_data; + bdev_set_flag(&ctx->bdev, BD_READ_ONLY); + sb->s_bdev = &ctx->bdev; + + bgl_lock_init(&ctx->bgl); + sbi->s_blockgroup_lock = &ctx->bgl; + + sbi->s_es = &ctx->es; + ctx->es.s_magic = cpu_to_le16(EXT4_SUPER_MAGIC); + ctx->es.s_first_data_block = cpu_to_le32(IALLOC_TEST_FIRST_DATA_BLK); + ctx->es.s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + ctx->es.s_creator_os = cpu_to_le32(EXT4_OS_LINUX); + ctx->es.s_inodes_count = cpu_to_le32(IALLOC_TEST_TOTAL_INODES); + ctx->es.s_inodes_per_group = cpu_to_le32(IALLOC_TEST_INODES_PER_GRP); + ctx->es.s_blocks_per_group = cpu_to_le32(IALLOC_TEST_BLOCKS_PER_GRP); + ctx->es.s_clusters_per_group = cpu_to_le32(IALLOC_TEST_BLOCKS_PER_GRP); + ctx->es.s_first_ino = cpu_to_le32(IALLOC_TEST_FIRST_INO); + ctx->es.s_inode_size = cpu_to_le16(IALLOC_TEST_INODE_SIZE); + ctx->es.s_min_extra_isize = cpu_to_le16(IALLOC_TEST_EXTRA_ISIZE); + ctx->es.s_want_extra_isize = cpu_to_le16(IALLOC_TEST_EXTRA_ISIZE); + ctx->es.s_checksum_type = EXT4_CRC32C_CHKSUM; + ext4_blocks_count_set(&ctx->es, IALLOC_TEST_TOTAL_BLKS); + + ext4_set_feature_sparse_super(sb); + ext4_set_feature_extents(sb); + ext4_set_feature_extra_isize(sb); + ext4_set_feature_metadata_csum(sb); + ext4_set_feature_64bit(sb); + ext4_set_feature_dir_index(sb); + + ctx->sb_bh.b_data = (char *)&ctx->es; + ctx->sb_bh.b_size = sizeof(ctx->es); + ctx->sb_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->sb_bh.b_count, 1); + set_buffer_uptodate(&ctx->sb_bh); + sbi->s_sbh = &ctx->sb_bh; + + ctx->gdesc_bh.b_data = ctx->gdesc_buf; + ctx->gdesc_bh.b_size = IALLOC_TEST_BLK_SIZE; + ctx->gdesc_bh.b_blocknr = IALLOC_TEST_GDESC_BLK; + ctx->gdesc_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->gdesc_bh.b_count, 1); + set_buffer_uptodate(&ctx->gdesc_bh); + + sbi->s_inode_size = IALLOC_TEST_INODE_SIZE; + sbi->s_inodes_per_block = IALLOC_TEST_INODES_PER_BLK; + sbi->s_inodes_per_group = IALLOC_TEST_INODES_PER_GRP; + sbi->s_itb_per_group = IALLOC_TEST_ITB_PER_GRP; + sbi->s_first_ino = IALLOC_TEST_FIRST_INO; + sbi->s_want_extra_isize = IALLOC_TEST_EXTRA_ISIZE; + sbi->s_blocks_per_group = IALLOC_TEST_BLOCKS_PER_GRP; + sbi->s_clusters_per_group = IALLOC_TEST_BLOCKS_PER_GRP; + sbi->s_cluster_ratio = 1; + sbi->s_cluster_bits = 0; + sbi->s_groups_count = IALLOC_TEST_NGROUPS; + sbi->s_gdb_count = 1; + sbi->s_desc_size = EXT4_MIN_DESC_SIZE_64BIT; + sbi->s_desc_per_block = IALLOC_TEST_BLK_SIZE / EXT4_MIN_DESC_SIZE_64BIT; + sbi->s_desc_per_block_bits = ilog2(sbi->s_desc_per_block); + sbi->s_bitmap_maxbytes = 0x1ff7ffff000ULL; + sbi->s_csum_seed = IALLOC_TEST_CSUM_SEED; + sbi->s_hash_seed[0] = 0x12345678U; + sbi->s_hash_seed[1] = 0x9abcdef0U; + sbi->s_hash_seed[2] = 0x13579bdfU; + sbi->s_hash_seed[3] = 0x2468ace0U; + + set_opt(sb, ERRORS_CONT); + set_opt(sb, ORDERED_DATA); + spin_lock_init(&sbi->s_bdev_wb_lock); + spin_lock_init(&sbi->s_error_lock); + spin_lock_init(&sbi->s_md_lock); + mutex_init(&sbi->s_fc_lock); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_STAGING]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_STAGING]); + + ratelimit_state_init(&sbi->s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + + /* Wire RCU-indexed group_info and flex_groups tables */ + for (g = 0; g < IALLOC_TEST_NGROUPS; g++) { + struct ialloc_test_blk *iblk, *bblk; + u32 free_inos = (g == 0) ? IALLOC_TEST_BG0_FREE_INODES : + IALLOC_TEST_INODES_PER_GRP; + + ctx->grp_infos[g] = kunit_kzalloc(test, + sizeof(*ctx->grp_infos[g]), + GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->grp_infos[g]); + init_rwsem(&ctx->grp_infos[g]->alloc_sem); + ctx->grp_infos[g]->bb_state = 0; + ctx->grp_info_ptrs[g] = ctx->grp_infos[g]; + ctx->flex_grp_ptrs[g] = &ctx->flex_grps[g]; + + ext4_block_bitmap_set(sb, &ctx->gdps[g], + ialloc_test_bbitmap_blk(g)); + ext4_inode_bitmap_set(sb, &ctx->gdps[g], + ialloc_test_ibitmap_blk(g)); + ext4_inode_table_set(sb, &ctx->gdps[g], + ialloc_test_itable_blk(g)); + ext4_free_inodes_set(sb, &ctx->gdps[g], free_inos); + ext4_used_dirs_set(sb, &ctx->gdps[g], (g == 0) ? 1U : 0U); + ext4_itable_unused_set(sb, &ctx->gdps[g], free_inos); + ext4_free_group_clusters_set(sb, &ctx->gdps[g], + IALLOC_TEST_DEFAULT_FREE_CLU); + + iblk = ialloc_test_setup_blk(ctx, ialloc_test_ibitmap_blk(g), + true, true); + bblk = ialloc_test_setup_blk(ctx, ialloc_test_bbitmap_blk(g), + true, true); + if (!iblk || !bblk) { + deactivate_locked_super(sb); + kfree(ctx); + KUNIT_FAIL_AND_ABORT(test, "block pool setup failed"); + } + + /* Mark reserved bits 0..9 in group 0 and end padding 64..8191 */ + if (g == 0) { + for (bit = 0; bit < IALLOC_TEST_FIRST_INO - 1; bit++) + ext4_set_bit(bit, iblk->cache_buf); + } + ext4_mark_bitmap_end(IALLOC_TEST_INODES_PER_GRP, + IALLOC_TEST_BLK_SIZE * 8, + iblk->cache_buf); + set_bitmap_uptodate(&iblk->bh); + set_buffer_verified(&iblk->bh); + + ext4_block_bitmap_csum_set(sb, &ctx->gdps[g], &bblk->bh); + memcpy(bblk->disk_buf, bblk->cache_buf, IALLOC_TEST_BLK_SIZE); + set_bitmap_uptodate(&bblk->bh); + set_buffer_verified(&bblk->bh); + + ialloc_test_sync_ibitmap_csum(ctx, g, true); + + total_free_inodes += free_inos; + total_free_clusters += IALLOC_TEST_DEFAULT_FREE_CLU; + } + ctx->grp_info_slice[0] = ctx->grp_info_ptrs; + rcu_assign_pointer(sbi->s_group_info, ctx->grp_info_slice); + rcu_assign_pointer(sbi->s_flex_groups, ctx->flex_grp_ptrs); + + err = percpu_counter_init(&sbi->s_freeclusters_counter, + total_free_clusters, GFP_KERNEL); + if (err) { + deactivate_locked_super(sb); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + err = percpu_counter_init(&sbi->s_freeinodes_counter, + total_free_inodes, GFP_KERNEL); + if (err) { + percpu_counter_destroy(&ctx->sbi.s_freeclusters_counter); + deactivate_locked_super(sb); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + err = percpu_counter_init(&sbi->s_dirs_counter, 1, GFP_KERNEL); + if (err) { + percpu_counter_destroy(&ctx->sbi.s_freeinodes_counter); + percpu_counter_destroy(&ctx->sbi.s_freeclusters_counter); + deactivate_locked_super(sb); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + + /* Create hashed VFS root directory inode (EXT4_ROOT_INO = 2) */ + ctx->root_inode = new_inode(sb); + if (!ctx->root_inode) { + percpu_counter_destroy(&ctx->sbi.s_dirs_counter); + percpu_counter_destroy(&ctx->sbi.s_freeinodes_counter); + percpu_counter_destroy(&ctx->sbi.s_freeclusters_counter); + deactivate_locked_super(sb); + kfree(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to allocate root_inode"); + } + ctx->root_inode->i_ino = EXT4_ROOT_INO; + ctx->root_inode->i_mode = S_IFDIR | 0755; + ctx->root_inode->i_op = &simple_dir_inode_operations; + set_nlink(ctx->root_inode, 2); + EXT4_I(ctx->root_inode)->i_block_group = 0; + insert_inode_locked(ctx->root_inode); + unlock_new_inode(ctx->root_inode); + + sb->s_root = d_make_root(ctx->root_inode); + if (!sb->s_root) { + percpu_counter_destroy(&ctx->sbi.s_dirs_counter); + percpu_counter_destroy(&ctx->sbi.s_freeinodes_counter); + percpu_counter_destroy(&ctx->sbi.s_freeclusters_counter); + deactivate_locked_super(sb); + rcu_barrier(); + kfree(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to allocate s_root"); + } + + up_write(&sb->s_umount); + + err = kunit_add_action_or_reset(test, ialloc_test_cleanup, ctx); + KUNIT_ASSERT_EQ(test, err, 0); + + kunit_activate_static_stub(test, ext4_get_group_desc, + ialloc_test_get_group_desc_stub); + kunit_activate_static_stub(test, ext4_sb_getblk, + ialloc_test_sb_getblk_stub); + kunit_activate_static_stub(test, ext4_sb_find_get_block, + ialloc_test_sb_find_get_block_stub); + kunit_activate_static_stub(test, ext4_read_bh, + ialloc_test_read_bh_stub); + kunit_activate_static_stub(test, ext4_read_block_bitmap_nowait, + ialloc_test_read_bbitmap_nowait_stub); + kunit_activate_static_stub(test, ext4_wait_block_bitmap, + ialloc_test_wait_bbitmap_stub); + kunit_activate_static_stub(test, __ext4_journal_get_write_access, + ialloc_test_get_write_access_stub); + kunit_activate_static_stub(test, __ext4_handle_dirty_metadata, + ialloc_test_dirty_metadata_stub); + kunit_activate_static_stub(test, __ext4_mark_inode_dirty, + ialloc_test_mark_inode_dirty_stub); +#ifdef CONFIG_EXT4_FS_SECURITY + kunit_activate_static_stub(test, ext4_init_security, + ialloc_test_init_security_stub); +#endif + kunit_activate_static_stub(test, ext4_itable_zeroout, + ialloc_test_itable_zeroout_stub); + kunit_activate_static_stub(test, __ext4_iget, + ialloc_test_iget_stub); + + return 0; +} + +/* ========================================================================= + * 1. Bitmap Helpers: ext4_mark_bitmap_end & ext4_end_bitmap_read + * ========================================================================= + */ + +struct mark_bitmap_end_param { + const char *desc; + int start_bit; + int end_bit; +}; + +static const struct mark_bitmap_end_param mark_bitmap_end_params[] = { + { "unaligned_start_to_aligned_end", 67, 128 }, + { "byte_aligned_memset_only", 64, 128 }, + { "single_partial_byte_no_memset", 3, 8 }, + { "unaligned_within_second_byte", 10, 16 }, + { "equal_start_and_end_noop", 64, 64 }, + { "start_greater_than_end_noop", 75, 64 }, +}; + +static void mark_bitmap_end_param_to_desc(const struct mark_bitmap_end_param *p, + char *desc) +{ + strscpy(desc, p->desc, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(mark_bitmap_end, mark_bitmap_end_params, + mark_bitmap_end_param_to_desc); + +static void ialloc_test_mark_bitmap_end(struct kunit *test) +{ + const struct mark_bitmap_end_param *p = test->param_value; + char bitmap[24] = {}; + int bit; + + ext4_mark_bitmap_end(p->start_bit, p->end_bit, bitmap); + + for (bit = 0; bit < (int)sizeof(bitmap) * 8; bit++) { + bool expected = (p->start_bit < p->end_bit) && + (bit >= p->start_bit && bit < p->end_bit); + + KUNIT_EXPECT_EQ_MSG(test, (bool)ext4_test_bit(bit, bitmap), + expected, "%s: unexpected value at bit %d", + p->desc, bit); + } +} + +static void ialloc_test_end_bitmap_read_ok(struct kunit *test) +{ + struct buffer_head bh = {}; + struct bio *bio; + + atomic_set(&bh.b_count, 1); + lock_buffer(&bh); + + bio = bio_alloc(NULL, 0, REQ_OP_READ, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, bio); + bio->bi_private = &bh; + bio->bi_status = BLK_STS_OK; + + ext4_end_bitmap_read(bio); + + KUNIT_EXPECT_FALSE(test, buffer_locked(&bh)); + KUNIT_EXPECT_TRUE(test, buffer_uptodate(&bh)); + KUNIT_EXPECT_TRUE(test, bitmap_uptodate(&bh)); +} + +static void ialloc_test_end_bitmap_read_ioerr(struct kunit *test) +{ + struct buffer_head bh = {}; + struct bio *bio; + + atomic_set(&bh.b_count, 1); + lock_buffer(&bh); + + bio = bio_alloc(NULL, 0, REQ_OP_READ, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, bio); + bio->bi_private = &bh; + bio->bi_status = BLK_STS_IOERR; + bio_set_flag(bio, BIO_QUIET); + + ext4_end_bitmap_read(bio); + + KUNIT_EXPECT_FALSE(test, buffer_locked(&bh)); + KUNIT_EXPECT_FALSE(test, buffer_uptodate(&bh)); + KUNIT_EXPECT_FALSE(test, bitmap_uptodate(&bh)); + KUNIT_EXPECT_TRUE(test, test_bit(BH_Quiet, &bh.b_state)); +} + +/* ========================================================================= + * 2. Inode Bitmap Validation: ext4_validate_inode_bitmap_test + * ========================================================================= + */ + +static void ialloc_test_validate_ibitmap_csum(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ialloc_test_blk *slot; + s64 free_before; + int err; + + slot = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(1)); + KUNIT_ASSERT_NOT_NULL(test, slot); + + /* 64-bit group descriptor valid CRC */ + clear_buffer_verified(&slot->bh); + err = ext4_validate_inode_bitmap_test(sb, &ctx->gdps[1], 1, &slot->bh); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, (bool)buffer_verified(&slot->bh)); + KUNIT_EXPECT_FALSE(test, + (bool)EXT4_MB_GRP_IBITMAP_CORRUPT(ctx->grp_infos[1])); + + /* 32-bit group descriptor valid CRC (low 16-bit checksum only) */ + ext4_clear_feature_64bit(sb); + ctx->sbi.s_desc_size = EXT4_MIN_DESC_SIZE; + ext4_inode_bitmap_csum_set(sb, &ctx->gdps[1], &slot->bh); + clear_buffer_verified(&slot->bh); + err = ext4_validate_inode_bitmap_test(sb, &ctx->gdps[1], 1, &slot->bh); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, (bool)buffer_verified(&slot->bh)); + + /* Restore 64-bit descriptor and corrupt bitmap byte */ + ext4_set_feature_64bit(sb); + ctx->sbi.s_desc_size = EXT4_MIN_DESC_SIZE_64BIT; + ialloc_test_sync_ibitmap_csum(ctx, 1, false); + clear_buffer_verified(&slot->bh); + slot->cache_buf[0] ^= 0x01; + free_before = percpu_counter_sum_positive(&ctx->sbi.s_freeinodes_counter); + + err = ext4_validate_inode_bitmap_test(sb, &ctx->gdps[1], 1, &slot->bh); + KUNIT_EXPECT_EQ(test, err, -EFSBADCRC); + KUNIT_EXPECT_FALSE(test, (bool)buffer_verified(&slot->bh)); + KUNIT_EXPECT_TRUE(test, + (bool)EXT4_MB_GRP_IBITMAP_CORRUPT(ctx->grp_infos[1])); + KUNIT_EXPECT_EQ(test, + percpu_counter_sum_positive(&ctx->sbi.s_freeinodes_counter), + free_before - IALLOC_TEST_INODES_PER_GRP); +} + +static void ialloc_test_validate_ibitmap_short_circuits(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ialloc_test_blk *slot; + int err; + + slot = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(2)); + KUNIT_ASSERT_NOT_NULL(test, slot); + + /* Corrupt byte, but EXT4_FC_REPLAY skips validation */ + clear_buffer_verified(&slot->bh); + slot->cache_buf[0] ^= 0xff; + ctx->sbi.s_mount_state |= EXT4_FC_REPLAY; + err = ext4_validate_inode_bitmap_test(sb, &ctx->gdps[2], 2, &slot->bh); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_FALSE(test, (bool)buffer_verified(&slot->bh)); + ctx->sbi.s_mount_state &= ~EXT4_FC_REPLAY; + + /* Already buffer_verified short-circuits before checking CRC */ + set_buffer_verified(&slot->bh); + err = ext4_validate_inode_bitmap_test(sb, &ctx->gdps[2], 2, &slot->bh); + KUNIT_EXPECT_EQ(test, err, 0); + + /* Out-of-range group (NULL ext4_get_group_info) -> -EFSCORRUPTED */ + clear_buffer_verified(&slot->bh); + err = ext4_validate_inode_bitmap_test(sb, &ctx->gdps[2], + IALLOC_TEST_NGROUPS + 1, + &slot->bh); + KUNIT_EXPECT_EQ(test, err, -EFSCORRUPTED); + + /* Pre-marked IBITMAP_CORRUPT -> -EFSCORRUPTED */ + set_bit(EXT4_GROUP_INFO_IBITMAP_CORRUPT_BIT, + &ctx->grp_infos[2]->bb_state); + err = ext4_validate_inode_bitmap_test(sb, &ctx->gdps[2], 2, &slot->bh); + KUNIT_EXPECT_EQ(test, err, -EFSCORRUPTED); + +#ifdef CONFIG_EXT4_DEBUG + slot = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(3)); + KUNIT_ASSERT_NOT_NULL(test, slot); + clear_buffer_verified(&slot->bh); + ctx->sbi.s_simulate_fail = EXT4_SIM_IBITMAP_CRC; + err = ext4_validate_inode_bitmap_test(sb, &ctx->gdps[3], 3, &slot->bh); + KUNIT_EXPECT_EQ(test, err, -EFSBADCRC); + KUNIT_EXPECT_EQ(test, ctx->sbi.s_simulate_fail, 0UL); +#endif +} + +/* ========================================================================= + * 3. Reading Inode Bitmaps: ext4_read_inode_bitmap_test + * ========================================================================= + */ + +static void ialloc_test_read_ibitmap_disk_and_cache(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ialloc_test_blk *slot; + struct buffer_head *bh; + + slot = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(1)); + KUNIT_ASSERT_NOT_NULL(test, slot); + + /* Put distinctive valid bitmap on disk and invalidate cache flags */ + ext4_set_bit(5, slot->disk_buf); + memcpy(slot->cache_buf, slot->disk_buf, IALLOC_TEST_BLK_SIZE); + ialloc_test_sync_ibitmap_csum(ctx, 1, true); + memset(slot->cache_buf, 0, IALLOC_TEST_BLK_SIZE); + clear_bitmap_uptodate(&slot->bh); + clear_buffer_uptodate(&slot->bh); + clear_buffer_verified(&slot->bh); + + bh = ext4_read_inode_bitmap_test(sb, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + KUNIT_EXPECT_EQ(test, ctx->read_bh_calls, 1U); + KUNIT_EXPECT_TRUE(test, (bool)ext4_test_bit(5, bh->b_data)); + KUNIT_EXPECT_TRUE(test, (bool)bitmap_uptodate(bh)); + KUNIT_EXPECT_TRUE(test, (bool)buffer_uptodate(bh)); + KUNIT_EXPECT_TRUE(test, (bool)buffer_verified(bh)); + brelse(bh); + KUNIT_EXPECT_EQ(test, atomic_read(&slot->bh.b_count), 1); + + /* Second read hits bitmap_uptodate fast path with zero I/O */ + bh = ext4_read_inode_bitmap_test(sb, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + KUNIT_EXPECT_EQ(test, ctx->read_bh_calls, 1U); + brelse(bh); + + /* buffer_uptodate && !bitmap_uptodate promotes bitmap_uptodate without I/O */ + clear_bitmap_uptodate(&slot->bh); + clear_buffer_verified(&slot->bh); + bh = ext4_read_inode_bitmap_test(sb, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + KUNIT_EXPECT_EQ(test, ctx->read_bh_calls, 1U); + KUNIT_EXPECT_TRUE(test, (bool)bitmap_uptodate(bh)); + KUNIT_EXPECT_TRUE(test, (bool)buffer_verified(bh)); + brelse(bh); + KUNIT_EXPECT_EQ(test, atomic_read(&slot->bh.b_count), 1); +} + +static void ialloc_test_read_ibitmap_uninit(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ialloc_test_blk *slot0, *slot1; + struct buffer_head *bh; + unsigned int bit; + + /* Group 1 with EXT4_BG_INODE_UNINIT initializes in memory without I/O */ + slot1 = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(1)); + KUNIT_ASSERT_NOT_NULL(test, slot1); + memset(slot1->cache_buf, 0xaa, IALLOC_TEST_BLK_SIZE); + clear_bitmap_uptodate(&slot1->bh); + clear_buffer_uptodate(&slot1->bh); + clear_buffer_verified(&slot1->bh); + ctx->gdps[1].bg_flags |= cpu_to_le16(EXT4_BG_INODE_UNINIT); + + bh = ext4_read_inode_bitmap_test(sb, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(bh)); + KUNIT_EXPECT_EQ(test, ctx->read_bh_calls, 0U); + KUNIT_EXPECT_TRUE(test, (bool)bitmap_uptodate(bh)); + KUNIT_EXPECT_TRUE(test, (bool)buffer_uptodate(bh)); + KUNIT_EXPECT_TRUE(test, (bool)buffer_verified(bh)); + for (bit = 0; bit < IALLOC_TEST_INODES_PER_GRP; bit++) + KUNIT_EXPECT_FALSE_MSG(test, (bool)ext4_test_bit(bit, bh->b_data), + "expected bit %u cleared", bit); + KUNIT_EXPECT_TRUE(test, + (bool)ext4_test_bit(IALLOC_TEST_INODES_PER_GRP, + bh->b_data)); + KUNIT_EXPECT_TRUE(test, + (bool)ext4_test_bit(IALLOC_TEST_BLK_SIZE * 8 - 1, + bh->b_data)); + brelse(bh); + + /* Group 0 marked EXT4_BG_INODE_UNINIT is rejected as corrupt */ + slot0 = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(0)); + KUNIT_ASSERT_NOT_NULL(test, slot0); + clear_bitmap_uptodate(&slot0->bh); + clear_buffer_uptodate(&slot0->bh); + ctx->gdps[0].bg_flags |= cpu_to_le16(EXT4_BG_INODE_UNINIT); + + bh = ext4_read_inode_bitmap_test(sb, 0); + KUNIT_EXPECT_EQ(test, PTR_ERR(bh), -EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, atomic_read(&slot0->bh.b_count), 1); +} + +static void ialloc_test_read_ibitmap_errors(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ialloc_test_blk *slot; + struct buffer_head *bh; + + /* NULL group descriptor */ + ctx->fail_gdp_mask = BIT(1); + bh = ext4_read_inode_bitmap_test(sb, 1); + KUNIT_EXPECT_EQ(test, PTR_ERR(bh), -EFSCORRUPTED); + ctx->fail_gdp_mask = 0; + + /* Invalid bitmap_blk <= s_first_data_block (1) */ + ext4_inode_bitmap_set(sb, &ctx->gdps[1], IALLOC_TEST_FIRST_DATA_BLK); + bh = ext4_read_inode_bitmap_test(sb, 1); + KUNIT_EXPECT_EQ(test, PTR_ERR(bh), -EFSCORRUPTED); + KUNIT_EXPECT_TRUE(test, + (bool)EXT4_MB_GRP_IBITMAP_CORRUPT(ctx->grp_infos[1])); + + /* Invalid bitmap_blk >= ext4_blocks_count(es) */ + ctx->grp_infos[1]->bb_state = 0; + ext4_inode_bitmap_set(sb, &ctx->gdps[1], IALLOC_TEST_TOTAL_BLKS); + bh = ext4_read_inode_bitmap_test(sb, 1); + KUNIT_EXPECT_EQ(test, PTR_ERR(bh), -EFSCORRUPTED); + KUNIT_EXPECT_TRUE(test, + (bool)EXT4_MB_GRP_IBITMAP_CORRUPT(ctx->grp_infos[1])); + ctx->grp_infos[1]->bb_state = 0; + ext4_inode_bitmap_set(sb, &ctx->gdps[1], ialloc_test_ibitmap_blk(1)); + + /* ext4_sb_getblk allocation failure */ + ctx->fail_getblk = true; + bh = ext4_read_inode_bitmap_test(sb, 1); + KUNIT_EXPECT_EQ(test, PTR_ERR(bh), -ENOMEM); + ctx->fail_getblk = false; + + /* Disk read I/O failure */ + slot = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(2)); + KUNIT_ASSERT_NOT_NULL(test, slot); + clear_bitmap_uptodate(&slot->bh); + clear_buffer_uptodate(&slot->bh); + ctx->fail_read_eio = true; + bh = ext4_read_inode_bitmap_test(sb, 2); + KUNIT_EXPECT_EQ(test, PTR_ERR(bh), -EIO); + KUNIT_EXPECT_TRUE(test, + (bool)EXT4_MB_GRP_IBITMAP_CORRUPT(ctx->grp_infos[2])); + KUNIT_EXPECT_EQ(test, atomic_read(&slot->bh.b_count), 1); + ctx->fail_read_eio = false; + + /* Bad CRC after successful disk read */ + slot = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(3)); + KUNIT_ASSERT_NOT_NULL(test, slot); + slot->disk_buf[0] ^= 0x80; + clear_bitmap_uptodate(&slot->bh); + clear_buffer_uptodate(&slot->bh); + clear_buffer_verified(&slot->bh); + bh = ext4_read_inode_bitmap_test(sb, 3); + KUNIT_EXPECT_EQ(test, PTR_ERR(bh), -EFSBADCRC); + KUNIT_EXPECT_TRUE(test, + (bool)EXT4_MB_GRP_IBITMAP_CORRUPT(ctx->grp_infos[3])); + KUNIT_EXPECT_EQ(test, atomic_read(&slot->bh.b_count), 1); +} + +/* ========================================================================= + * 4. Freeing Inodes: ext4_free_inode + * ========================================================================= + */ + +static void ialloc_test_free_inode_reg_and_dir(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ialloc_test_blk *iblk; + s64 free_before, dirs_before; + + iblk = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(1)); + KUNIT_ASSERT_NOT_NULL(test, iblk); + + /* Mark bit 2 (ino 67, reg) and bit 3 (ino 68, dir) allocated in group 1 */ + ext4_set_bit(2, iblk->cache_buf); + ext4_set_bit(3, iblk->cache_buf); + ext4_free_inodes_set(sb, &ctx->gdps[1], 62); + ext4_used_dirs_set(sb, &ctx->gdps[1], 1); + percpu_counter_add(&ctx->sbi.s_freeinodes_counter, -2); + percpu_counter_add(&ctx->sbi.s_dirs_counter, 1); + ialloc_test_sync_ibitmap_csum(ctx, 1, true); + ialloc_test_enable_flex_bg(ctx, 1); + + free_before = percpu_counter_sum_positive(&ctx->sbi.s_freeinodes_counter); + dirs_before = percpu_counter_sum_positive(&ctx->sbi.s_dirs_counter); + + /* Free regular file ino 67 (group 1, bit 2, flex_group 0) */ + ialloc_test_prep_standalone_free_inode(ctx, 67, S_IFREG | 0644); + ext4_free_inode(NULL, &ctx->standalone_ei.vfs_inode); + + KUNIT_EXPECT_FALSE(test, (bool)ext4_test_bit(2, iblk->cache_buf)); + KUNIT_EXPECT_EQ(test, ext4_free_inodes_count(sb, &ctx->gdps[1]), 63U); + KUNIT_EXPECT_EQ(test, ext4_used_dirs_count(sb, &ctx->gdps[1]), 1U); + KUNIT_EXPECT_EQ(test, + percpu_counter_sum_positive(&ctx->sbi.s_freeinodes_counter), + free_before + 1); + KUNIT_EXPECT_EQ(test, + percpu_counter_sum_positive(&ctx->sbi.s_dirs_counter), + dirs_before); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->flex_grps[0].free_inodes), + (int)(IALLOC_TEST_BG0_FREE_INODES + 63)); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->flex_grps[0].used_dirs), 2); + KUNIT_EXPECT_TRUE(test, iblk->marked_dirty); + KUNIT_EXPECT_TRUE(test, ctx->gdesc_marked_dirty); + KUNIT_EXPECT_TRUE(test, + (bool)ext4_inode_bitmap_csum_verify(sb, &ctx->gdps[1], + &iblk->bh)); + KUNIT_EXPECT_TRUE(test, + (bool)ext4_group_desc_csum_verify(sb, 1, + &ctx->gdps[1])); + + /* Free directory ino 68 (group 1, bit 3, flex_group 0) */ + ialloc_test_prep_standalone_free_inode(ctx, 68, S_IFDIR | 0755); + ext4_free_inode(NULL, &ctx->standalone_ei.vfs_inode); + + KUNIT_EXPECT_FALSE(test, (bool)ext4_test_bit(3, iblk->cache_buf)); + KUNIT_EXPECT_EQ(test, ext4_free_inodes_count(sb, &ctx->gdps[1]), 64U); + KUNIT_EXPECT_EQ(test, ext4_used_dirs_count(sb, &ctx->gdps[1]), 0U); + KUNIT_EXPECT_EQ(test, + percpu_counter_sum_positive(&ctx->sbi.s_freeinodes_counter), + free_before + 2); + KUNIT_EXPECT_EQ(test, + percpu_counter_sum_positive(&ctx->sbi.s_dirs_counter), + dirs_before - 1); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->flex_grps[0].used_dirs), 1); +} + +static void ialloc_test_free_inode_guards(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ialloc_test_blk *iblk0, *iblk1; + struct inode *inode = &ctx->standalone_ei.vfs_inode; + + iblk0 = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(0)); + iblk1 = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(1)); + KUNIT_ASSERT_NOT_NULL(test, iblk0); + KUNIT_ASSERT_NOT_NULL(test, iblk1); + + ext4_set_bit(0, iblk1->cache_buf); /* ino 65 */ + ext4_free_inodes_set(sb, &ctx->gdps[1], 63); + ialloc_test_sync_ibitmap_csum(ctx, 1, true); + + /* NULL i_sb is ignored */ + ialloc_test_prep_standalone_free_inode(ctx, 65, S_IFREG | 0644); + inode->i_sb = NULL; + ext4_free_inode(NULL, inode); + KUNIT_EXPECT_TRUE(test, (bool)ext4_test_bit(0, iblk1->cache_buf)); + + /* i_count > 1 is rejected before clear_inode */ + ialloc_test_prep_standalone_free_inode(ctx, 65, S_IFREG | 0644); + atomic_set(&inode->i_count, 2); + ext4_free_inode(NULL, inode); + KUNIT_EXPECT_TRUE(test, (bool)ext4_test_bit(0, iblk1->cache_buf)); + KUNIT_EXPECT_FALSE(test, !!(inode_state_read_once(inode) & I_CLEAR)); + + /* i_nlink > 0 is rejected before clear_inode */ + ialloc_test_prep_standalone_free_inode(ctx, 65, S_IFREG | 0644); + set_nlink(inode, 1); + ext4_free_inode(NULL, inode); + KUNIT_EXPECT_TRUE(test, (bool)ext4_test_bit(0, iblk1->cache_buf)); + KUNIT_EXPECT_FALSE(test, !!(inode_state_read_once(inode) & I_CLEAR)); + + /* Reserved ino < EXT4_FIRST_INO(sb) clears VFS inode then errors out */ + ialloc_test_prep_standalone_free_inode(ctx, 5, S_IFREG | 0644); + ext4_free_inode(NULL, inode); + KUNIT_EXPECT_TRUE(test, !!(inode_state_read_once(inode) & I_CLEAR)); + KUNIT_EXPECT_TRUE(test, (bool)ext4_test_bit(4, iblk0->cache_buf)); + + /* Out-of-range ino > s_inodes_count clears VFS inode then errors out */ + ialloc_test_prep_standalone_free_inode(ctx, IALLOC_TEST_TOTAL_INODES + 1, + S_IFREG | 0644); + ext4_free_inode(NULL, inode); + KUNIT_EXPECT_TRUE(test, !!(inode_state_read_once(inode) & I_CLEAR)); +} + +static void ialloc_test_free_inode_corrupt_and_journal_errors(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ialloc_test_blk *iblk1, *iblk2, *iblk3; + + /* 1. Double-free (bit already clear) marks group bitmap corrupt */ + iblk1 = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(1)); + KUNIT_ASSERT_NOT_NULL(test, iblk1); + ialloc_test_prep_standalone_free_inode(ctx, 66, S_IFREG | 0644); + ext4_free_inode(NULL, &ctx->standalone_ei.vfs_inode); + KUNIT_EXPECT_TRUE(test, + (bool)EXT4_MB_GRP_IBITMAP_CORRUPT(ctx->grp_infos[1])); + KUNIT_EXPECT_EQ(test, ext4_free_inodes_count(sb, &ctx->gdps[1]), 64U); + + /* 2. Pre-corrupt group skips bitmap clear unless EXT4_FC_REPLAY */ + iblk2 = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(2)); + KUNIT_ASSERT_NOT_NULL(test, iblk2); + ext4_set_bit(0, iblk2->cache_buf); /* ino 129 */ + ext4_free_inodes_set(sb, &ctx->gdps[2], 63); + ialloc_test_sync_ibitmap_csum(ctx, 2, true); + set_bit(EXT4_GROUP_INFO_IBITMAP_CORRUPT_BIT, + &ctx->grp_infos[2]->bb_state); + + ialloc_test_prep_standalone_free_inode(ctx, 129, S_IFREG | 0644); + ext4_free_inode(NULL, &ctx->standalone_ei.vfs_inode); + KUNIT_EXPECT_TRUE(test, (bool)ext4_test_bit(0, iblk2->cache_buf)); + + ctx->sbi.s_mount_state |= EXT4_FC_REPLAY; + ialloc_test_prep_standalone_free_inode(ctx, 129, S_IFREG | 0644); + ext4_free_inode(NULL, &ctx->standalone_ei.vfs_inode); + ctx->sbi.s_mount_state &= ~EXT4_FC_REPLAY; + KUNIT_EXPECT_FALSE(test, (bool)ext4_test_bit(0, iblk2->cache_buf)); + KUNIT_EXPECT_EQ(test, ext4_free_inodes_count(sb, &ctx->gdps[2]), 64U); + + /* 3. Write-access failure on bitmap_bh (1st) vs bh2 (2nd) */ + iblk3 = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(3)); + KUNIT_ASSERT_NOT_NULL(test, iblk3); + ext4_set_bit(0, iblk3->cache_buf); /* ino 193 */ + ext4_free_inodes_set(sb, &ctx->gdps[3], 63); + ialloc_test_sync_ibitmap_csum(ctx, 3, true); + + ctx->write_access_calls = 0; + ctx->fail_write_access_err = -EIO; + ctx->fail_write_access_on_call = 1; + ialloc_test_prep_standalone_free_inode(ctx, 193, S_IFREG | 0644); + ext4_free_inode(NULL, &ctx->standalone_ei.vfs_inode); + KUNIT_EXPECT_TRUE(test, (bool)ext4_test_bit(0, iblk3->cache_buf)); + KUNIT_EXPECT_EQ(test, ext4_free_inodes_count(sb, &ctx->gdps[3]), 63U); + + ctx->write_access_calls = 0; + ctx->fail_write_access_on_call = 2; + iblk3->marked_dirty = false; + ialloc_test_prep_standalone_free_inode(ctx, 193, S_IFREG | 0644); + ext4_free_inode(NULL, &ctx->standalone_ei.vfs_inode); + KUNIT_EXPECT_FALSE(test, (bool)ext4_test_bit(0, iblk3->cache_buf)); + KUNIT_EXPECT_TRUE(test, iblk3->marked_dirty); + KUNIT_EXPECT_EQ(test, ext4_free_inodes_count(sb, &ctx->gdps[3]), 63U); + ctx->fail_write_access_err = 0; + ctx->fail_write_access_on_call = 0; +} + +/* ========================================================================= + * 5. Orlov Directory Allocator: ext4_find_group_orlov_test + * ========================================================================= + */ + +static void ialloc_test_orlov_topdir_spread(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct qstr qname = QSTR_INIT("projects", 8); + struct inode *subdir; + ext4_group_t grp = 0; + int ret; + + /* + * Configure group 2 as the unique above-average group with the lowest + * directory count (0 used_dirs, 64 free_inodes, 900 free_clusters). + */ + ext4_used_dirs_set(sb, &ctx->gdps[0], 5); + ext4_used_dirs_set(sb, &ctx->gdps[1], 4); + ext4_used_dirs_set(sb, &ctx->gdps[2], 0); + ext4_used_dirs_set(sb, &ctx->gdps[3], 6); + ext4_free_group_clusters_set(sb, &ctx->gdps[2], 900); + + ret = ext4_find_group_orlov_test(sb, ctx->root_inode, &grp, + S_IFDIR | 0755, &qname); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 2U); + + /* qstr == NULL uses random start, still converges on best group 2 */ + grp = 0; + ret = ext4_find_group_orlov_test(sb, ctx->root_inode, &grp, + S_IFDIR | 0755, NULL); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 2U); + + /* Non-root directory with EXT4_INODE_TOPDIR also uses topdir spread */ + subdir = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, subdir); + subdir->i_ino = 65; + subdir->i_mode = S_IFDIR | 0755; + EXT4_I(subdir)->i_block_group = 1; + ext4_set_inode_flag(subdir, EXT4_INODE_TOPDIR); + ialloc_test_track_inode(test, ctx, subdir); + + grp = 0; + ret = ext4_find_group_orlov_test(sb, subdir, &grp, S_IFDIR | 0755, + &qname); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 2U); +} + +static void ialloc_test_orlov_subdir_and_thresholds(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct inode *parent; + ext4_group_t grp = 0; + int ret; + + parent = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, parent); + parent->i_ino = 65; + parent->i_mode = S_IFDIR | 0755; + EXT4_I(parent)->i_block_group = 1; + ialloc_test_track_inode(test, ctx, parent); + + /* Healthy parent_group (1) is preferred */ + ret = ext4_find_group_orlov_test(sb, parent, &grp, S_IFDIR | 0755, NULL); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 1U); + + /* i_last_alloc_group overrides parent_group */ + EXT4_I(parent)->i_last_alloc_group = 3; + ret = ext4_find_group_orlov_test(sb, parent, &grp, S_IFDIR | 0755, NULL); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 3U); + EXT4_I(parent)->i_last_alloc_group = ~0U; + + /* Group 1 exceeds max_dirs -> advances cyclically to group 2 */ + ext4_used_dirs_set(sb, &ctx->gdps[1], 40); + ret = ext4_find_group_orlov_test(sb, parent, &grp, S_IFDIR | 0755, NULL); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 2U); + ext4_used_dirs_set(sb, &ctx->gdps[1], 0); + + /* Group 1 below min_inodes -> advances to group 2 */ + ext4_free_inodes_set(sb, &ctx->gdps[1], 2); + ret = ext4_find_group_orlov_test(sb, parent, &grp, S_IFDIR | 0755, NULL); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 2U); + ext4_free_inodes_set(sb, &ctx->gdps[1], IALLOC_TEST_INODES_PER_GRP); + + /* Group 1 below min_clusters -> advances to group 2 */ + ext4_free_group_clusters_set(sb, &ctx->gdps[1], 10); + ret = ext4_find_group_orlov_test(sb, parent, &grp, S_IFDIR | 0755, NULL); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 2U); +} + +static void ialloc_test_orlov_flex_bg_and_fallback(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct inode *parent; + ext4_group_t grp = 0; + ext4_group_t g; + int ret; + + parent = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, parent); + parent->i_ino = 12; + parent->i_mode = S_IFDIR | 0755; + EXT4_I(parent)->i_block_group = 0; + ialloc_test_track_inode(test, ctx, parent); + + /* + * Flex size 2: flex 0 = {0, 1} has excessive dirs; flex 1 = {2, 3} + * is healthy, with group 2 full (0 free inodes) and group 3 having 64 + * free inodes -> packs into first available constituent group 3. + */ + ext4_used_dirs_set(sb, &ctx->gdps[0], 30); + ext4_used_dirs_set(sb, &ctx->gdps[1], 30); + ext4_free_inodes_set(sb, &ctx->gdps[2], 0); + ext4_free_inodes_set(sb, &ctx->gdps[3], 64); + percpu_counter_set(&ctx->sbi.s_dirs_counter, 60); + percpu_counter_set(&ctx->sbi.s_freeinodes_counter, + IALLOC_TEST_BG0_FREE_INODES + 64 + 0 + 64); + ialloc_test_enable_flex_bg(ctx, 1); + + ret = ext4_find_group_orlov_test(sb, parent, &grp, S_IFDIR | 0755, NULL); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 3U); + + /* Disable flex_bg and test fallback_retry with inflated counter */ + ctx->sbi.s_log_groups_per_flex = 0; + ext4_clear_feature_flex_bg(sb); + for (g = 0; g < IALLOC_TEST_NGROUPS; g++) { + ext4_used_dirs_set(sb, &ctx->gdps[g], 50); + ext4_free_inodes_set(sb, &ctx->gdps[g], (g == 3) ? 1U : 0U); + } + /* Counter claims 200 free inodes (avefreei = 50), only bg 3 has 1 */ + percpu_counter_set(&ctx->sbi.s_freeinodes_counter, 200); + + ret = ext4_find_group_orlov_test(sb, parent, &grp, S_IFDIR | 0755, NULL); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 3U); + + /* All groups completely full -> returns -1 */ + ext4_free_inodes_set(sb, &ctx->gdps[3], 0); + ret = ext4_find_group_orlov_test(sb, parent, &grp, S_IFDIR | 0755, NULL); + KUNIT_EXPECT_EQ(test, ret, -1); +} + +/* ========================================================================= + * 6. Non-Directory Group Allocator: ext4_find_group_other_test + * ========================================================================= + */ + +static void ialloc_test_find_group_other_non_flex(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct inode *parent; + ext4_group_t grp = 0; + ext4_group_t g; + int ret; + + parent = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, parent); + parent->i_ino = 65; + parent->i_mode = S_IFDIR | 0755; + EXT4_I(parent)->i_block_group = 1; + ialloc_test_track_inode(test, ctx, parent); + + /* 1. Parent group 1 has both free inodes and free clusters */ + ret = ext4_find_group_other_test(sb, parent, &grp, S_IFREG | 0644); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 1U); + + /* + * 2. Quadratic hash probe when parent group 1 has 0 free inodes: + * start = (1 + 65) % 4 = 2; step i = 1 -> (2 + 1) % 4 = 3. + */ + ext4_free_inodes_set(sb, &ctx->gdps[1], 0); + ret = ext4_find_group_other_test(sb, parent, &grp, S_IFREG | 0644); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 3U); + + /* + * 3. Linear fallback when no group has free clusters: + * starts at parent_group = 1, ++*group checks 2 first. + */ + for (g = 0; g < IALLOC_TEST_NGROUPS; g++) + ext4_free_group_clusters_set(sb, &ctx->gdps[g], 0); + ret = ext4_find_group_other_test(sb, parent, &grp, S_IFREG | 0644); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 2U); + + /* 4. Returns -1 when all groups have 0 free inodes */ + for (g = 0; g < IALLOC_TEST_NGROUPS; g++) + ext4_free_inodes_set(sb, &ctx->gdps[g], 0); + ret = ext4_find_group_other_test(sb, parent, &grp, S_IFREG | 0644); + KUNIT_EXPECT_EQ(test, ret, -1); +} + +static void ialloc_test_find_group_other_flex_bg(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct inode *parent; + ext4_group_t grp = 0; + int ret; + + parent = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, parent); + parent->i_ino = 65; + parent->i_mode = S_IFDIR | 0755; + EXT4_I(parent)->i_block_group = 1; + ialloc_test_track_inode(test, ctx, parent); + + /* + * Flex size 2: parent (i_ino = 65) in bg 1 (flex 0 = {0, 1}) spreads + * by parent->i_ino % flex_size -> bg 1 first, then falls back to bg 0. + */ + ialloc_test_enable_flex_bg(ctx, 1); + ret = ext4_find_group_other_test(sb, parent, &grp, S_IFREG | 0644); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 1U); + + ext4_free_inodes_set(sb, &ctx->gdps[1], 0); + ret = ext4_find_group_other_test(sb, parent, &grp, S_IFREG | 0644); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 0U); + + /* Flex 0 full, i_last_alloc_group = 2 (flex 1 = {2, 3}) retries flex 1 -> bg 3 */ + ext4_free_inodes_set(sb, &ctx->gdps[0], 0); + ialloc_test_enable_flex_bg(ctx, 1); + EXT4_I(parent)->i_last_alloc_group = 2; + ret = ext4_find_group_other_test(sb, parent, &grp, S_IFREG | 0644); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 3U); + + /* Flex 0 full and i_last_alloc_group unset -> Orlov fallback picks flex 1 -> bg 3 */ + EXT4_I(parent)->i_last_alloc_group = ~0U; + ret = ext4_find_group_other_test(sb, parent, &grp, S_IFREG | 0644); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp, 3U); +} + +/* ========================================================================= + * 7. Recently Deleted & Bit Search: recently_deleted & find_inode_bit + * ========================================================================= + */ + +static void ialloc_test_recently_deleted(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ialloc_test_blk *it_slot; + struct ext4_inode *raw; + u32 now; + + /* 1. EXT4_BG_INODE_UNINIT returns 0 immediately */ + ctx->gdps[1].bg_flags |= cpu_to_le16(EXT4_BG_INODE_UNINIT); + KUNIT_EXPECT_EQ(test, ext4_recently_deleted_test(sb, 1, 0), 0); + ctx->gdps[1].bg_flags &= ~cpu_to_le16(EXT4_BG_INODE_UNINIT); + + /* 2. Inode >= (64 - itable_unused) was never used -> returns 0 */ + ext4_itable_unused_set(sb, &ctx->gdps[1], 54); /* 0..9 used */ + KUNIT_EXPECT_EQ(test, ext4_recently_deleted_test(sb, 1, 10), 0); + + /* 3. Uncached inode table block -> returns 0 */ + it_slot = ialloc_test_setup_blk(ctx, ialloc_test_itable_blk(1), + false, true); + KUNIT_ASSERT_NOT_NULL(test, it_slot); + raw = (struct ext4_inode *)(it_slot->cache_buf + + 2 * IALLOC_TEST_INODE_SIZE); + now = ktime_get_real_seconds(); + raw->i_dtime = cpu_to_le32(now - 10); + KUNIT_EXPECT_EQ(test, ext4_recently_deleted_test(sb, 1, 2), 0); + + /* 4. Cached but !buffer_uptodate -> returns 0 */ + it_slot->in_cache = true; + clear_buffer_uptodate(&it_slot->bh); + KUNIT_EXPECT_EQ(test, ext4_recently_deleted_test(sb, 1, 2), 0); + set_buffer_uptodate(&it_slot->bh); + + /* 5. dtime == 0 -> returns 0 */ + raw->i_dtime = 0; + KUNIT_EXPECT_EQ(test, ext4_recently_deleted_test(sb, 1, 2), 0); + + /* 6. Clean buffer uses 60s window; dirty buffer extends to 360s */ + now = ktime_get_real_seconds(); + raw->i_dtime = cpu_to_le32(now - 20); + KUNIT_EXPECT_EQ(test, ext4_recently_deleted_test(sb, 1, 2), 1); + + raw->i_dtime = cpu_to_le32(now - 120); + KUNIT_EXPECT_EQ(test, ext4_recently_deleted_test(sb, 1, 2), 0); + + set_buffer_dirty(&it_slot->bh); + KUNIT_EXPECT_EQ(test, ext4_recently_deleted_test(sb, 1, 2), 1); + + raw->i_dtime = cpu_to_le32(now - 400); + KUNIT_EXPECT_EQ(test, ext4_recently_deleted_test(sb, 1, 2), 0); + clear_buffer_dirty(&it_slot->bh); +} + +static void ialloc_test_find_inode_bit(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ialloc_test_blk *iblk, *it_slot; + struct ext4_inode *raw1; + unsigned long ino; + unsigned int bit; + int ret; + + iblk = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(1)); + KUNIT_ASSERT_NOT_NULL(test, iblk); + ext4_itable_unused_set(sb, &ctx->gdps[1], 0); + + /* Mark all bits except bit 1 (recently deleted) and bit 6 (old) */ + for (bit = 0; bit < IALLOC_TEST_INODES_PER_GRP; bit++) { + if (bit != 1 && bit != 6) + ext4_set_bit(bit, iblk->cache_buf); + } + it_slot = ialloc_test_setup_blk(ctx, ialloc_test_itable_blk(1), + true, true); + KUNIT_ASSERT_NOT_NULL(test, it_slot); + raw1 = (struct ext4_inode *)(it_slot->cache_buf + IALLOC_TEST_INODE_SIZE); + raw1->i_dtime = cpu_to_le32((u32)ktime_get_real_seconds() - 10); + + /* No-journal mode skips recently deleted bit 1 in favor of bit 6 */ + ino = 0; + ret = ext4_find_inode_bit_test(sb, 1, &iblk->bh, &ino); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, ino, 6UL); + + /* Journaled mode ignores recently_deleted and picks bit 1 directly */ + ctx->sbi.s_journal = (journal_t *)1UL; + ino = 0; + ret = ext4_find_inode_bit_test(sb, 1, &iblk->bh, &ino); + ctx->sbi.s_journal = NULL; + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, ino, 1UL); + + /* Fallback: when bit 6 is also allocated, returns recently deleted bit 1 */ + ext4_set_bit(6, iblk->cache_buf); + ino = 0; + ret = ext4_find_inode_bit_test(sb, 1, &iblk->bh, &ino); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, ino, 1UL); + + /* Full bitmap returns 0 */ + ext4_set_bit(1, iblk->cache_buf); + ino = 0; + ret = ext4_find_inode_bit_test(sb, 1, &iblk->bh, &ino); + KUNIT_EXPECT_EQ(test, ret, 0); +} + +/* ========================================================================= + * 8. Marking Specific Inodes Used: ext4_mark_inode_used + * ========================================================================= + */ + +static void ialloc_test_mark_inode_used_uninit(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ialloc_test_blk *iblk, *bblk; + int err; + + /* + * Configure group 2 with both EXT4_BG_INODE_UNINIT and + * EXT4_BG_BLOCK_UNINIT. Group 2 has no backup superblock, so overhead + * is 1 (bbitmap) + 1 (ibitmap) + 16 (itable) = 18 clusters -> 1006 free. + */ + iblk = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(2)); + bblk = ialloc_test_find_blk(ctx, ialloc_test_bbitmap_blk(2)); + KUNIT_ASSERT_NOT_NULL(test, iblk); + KUNIT_ASSERT_NOT_NULL(test, bblk); + + clear_bitmap_uptodate(&iblk->bh); + clear_buffer_uptodate(&iblk->bh); + clear_buffer_verified(&iblk->bh); + ctx->gdps[2].bg_flags = cpu_to_le16(EXT4_BG_INODE_UNINIT | + EXT4_BG_BLOCK_UNINIT); + ext4_free_group_clusters_set(sb, &ctx->gdps[2], 0); + ext4_itable_unused_set(sb, &ctx->gdps[2], 64); + ext4_free_inodes_set(sb, &ctx->gdps[2], 64); + ext4_group_desc_csum_set(sb, 2, &ctx->gdps[2]); + + /* Inode 135 is in group 2, bit 6 ((135 - 1) % 64 == 6) */ + err = ext4_mark_inode_used(sb, 135); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, + le16_to_cpu(ctx->gdps[2].bg_flags) & + (EXT4_BG_INODE_UNINIT | EXT4_BG_BLOCK_UNINIT), 0); + KUNIT_EXPECT_EQ(test, ext4_free_group_clusters(sb, &ctx->gdps[2]), + 1006U); + KUNIT_EXPECT_TRUE(test, (bool)ext4_test_bit(6, iblk->cache_buf)); + KUNIT_EXPECT_EQ(test, ext4_itable_unused_count(sb, &ctx->gdps[2]), 57U); + KUNIT_EXPECT_EQ(test, ext4_free_inodes_count(sb, &ctx->gdps[2]), 63U); + KUNIT_EXPECT_TRUE(test, + (bool)ext4_block_bitmap_csum_verify(sb, &ctx->gdps[2], + &bblk->bh)); + KUNIT_EXPECT_TRUE(test, + (bool)ext4_inode_bitmap_csum_verify(sb, &ctx->gdps[2], + &iblk->bh)); + KUNIT_EXPECT_TRUE(test, + (bool)ext4_group_desc_csum_verify(sb, 2, + &ctx->gdps[2])); + + /* Idempotent when bit 6 is already set */ + err = ext4_mark_inode_used(sb, 135); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ext4_free_inodes_count(sb, &ctx->gdps[2]), 63U); + + /* Lower bit 2 (ino 131) decrements free_inodes without raising itable_unused */ + err = ext4_mark_inode_used(sb, 131); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, (bool)ext4_test_bit(2, iblk->cache_buf)); + KUNIT_EXPECT_EQ(test, ext4_itable_unused_count(sb, &ctx->gdps[2]), 57U); + KUNIT_EXPECT_EQ(test, ext4_free_inodes_count(sb, &ctx->gdps[2]), 62U); +} + +static void ialloc_test_mark_inode_used_errors(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ialloc_test_blk *iblk; + + /* Bounds checks: below EXT4_FIRST_INO and above max_ino */ + KUNIT_EXPECT_EQ(test, ext4_mark_inode_used(sb, 10), -EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, + ext4_mark_inode_used(sb, IALLOC_TEST_TOTAL_INODES + 1), + -EFSCORRUPTED); + + /* Inode bitmap read I/O failure */ + iblk = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(1)); + KUNIT_ASSERT_NOT_NULL(test, iblk); + clear_bitmap_uptodate(&iblk->bh); + clear_buffer_uptodate(&iblk->bh); + ctx->fail_read_eio = true; + KUNIT_EXPECT_EQ(test, ext4_mark_inode_used(sb, 65), -EIO); + ctx->fail_read_eio = false; + + /* Dirty metadata error on group 2 (ino 129) */ + ctx->fail_dirty_metadata_err = -EIO; + KUNIT_EXPECT_EQ(test, ext4_mark_inode_used(sb, 129), -EIO); + ctx->fail_dirty_metadata_err = 0; + + /* sync_dirty_buffer I/O error on unmapped dirty buffer (ino 130) */ + ctx->fail_sync_dirty_buffer = true; + KUNIT_EXPECT_EQ(test, ext4_mark_inode_used(sb, 130), -EIO); + ctx->fail_sync_dirty_buffer = false; + + /* Block bitmap read and wait failures during EXT4_BG_BLOCK_UNINIT init */ + ctx->gdps[3].bg_flags |= cpu_to_le16(EXT4_BG_BLOCK_UNINIT); + ext4_group_desc_csum_set(sb, 3, &ctx->gdps[3]); + ctx->fail_bbitmap_err = -EIO; + KUNIT_EXPECT_EQ(test, ext4_mark_inode_used(sb, 193), -EIO); + ctx->fail_bbitmap_err = 0; + + ctx->fail_wait_bbitmap_err = -EFSCORRUPTED; + KUNIT_EXPECT_EQ(test, ext4_mark_inode_used(sb, 194), -EFSCORRUPTED); + ctx->fail_wait_bbitmap_err = 0; +} + +/* ========================================================================= + * 9. Xattr Credits & Inode Allocation: __ext4_new_inode + * ========================================================================= + */ + +#ifdef CONFIG_EXT4_FS_POSIX_ACL +static struct posix_acl *ialloc_test_err_get_inode_acl(struct inode *inode, + int type, bool rcu) +{ + return ERR_PTR(-EIO); +} + +static const struct inode_operations ialloc_test_err_acl_iops = { + .get_inode_acl = ialloc_test_err_get_inode_acl, +}; +#endif + +static void ialloc_test_xattr_credits_for_new_inode(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + int base, enc_creds, base_ea, enc_ea_creds; + + base = ext4_xattr_credits_for_new_inode_test(ctx->root_inode, + S_IFREG | 0644, false); + KUNIT_ASSERT_GE(test, base, 0); + if (!IS_ENABLED(CONFIG_SECURITY)) + KUNIT_EXPECT_EQ(test, base, 0); + + /* Without ea_inode, encryption xattr adds 7 credits */ + enc_creds = ext4_xattr_credits_for_new_inode_test(ctx->root_inode, + S_IFREG | 0644, true); + KUNIT_EXPECT_EQ(test, enc_creds, base + 7); + + /* With ea_inode on 1024B blocks, 40B fscrypt context adds 17 credits */ + ext4_set_feature_ea_inode(sb); + base_ea = ext4_xattr_credits_for_new_inode_test(ctx->root_inode, + S_IFREG | 0644, false); + enc_ea_creds = ext4_xattr_credits_for_new_inode_test(ctx->root_inode, + S_IFREG | 0644, + true); + KUNIT_EXPECT_EQ(test, enc_ea_creds, base_ea + 17); + ext4_clear_feature_ea_inode(sb); + +#ifdef CONFIG_EXT4_FS_POSIX_ACL + { + struct posix_acl *acl; + const struct inode_operations *orig_iops; + int reg_acl, dir_acl, err_acl; + + acl = posix_acl_alloc(1, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, acl); + set_cached_acl(ctx->root_inode, ACL_TYPE_DEFAULT, acl); + posix_acl_release(acl); + + reg_acl = ext4_xattr_credits_for_new_inode_test(ctx->root_inode, + S_IFREG | 0644, + false); + dir_acl = ext4_xattr_credits_for_new_inode_test(ctx->root_inode, + S_IFDIR | 0755, + false); + KUNIT_EXPECT_EQ(test, reg_acl, base + 7); + KUNIT_EXPECT_EQ(test, dir_acl, base + 14); + forget_cached_acl(ctx->root_inode, ACL_TYPE_DEFAULT); + + orig_iops = ctx->root_inode->i_op; + ctx->root_inode->i_op = &ialloc_test_err_acl_iops; + sb->s_flags |= SB_POSIXACL; + err_acl = ext4_xattr_credits_for_new_inode_test(ctx->root_inode, + S_IFREG | 0644, + false); + sb->s_flags &= ~SB_POSIXACL; + ctx->root_inode->i_op = orig_iops; + KUNIT_EXPECT_EQ(test, err_acl, -EIO); + } +#endif +} + +static void ialloc_test_new_inode_types_and_flags(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + handle_t *nojournal; + struct ialloc_test_blk *iblk0; + struct inode *reg, *dir, *lnk, *fifo, *ea_ino; + __le32 inum_le, gen_le; + u32 expected_seed; + s64 free_after_reg; + + nojournal = ext4_journal_start_sb(sb, EXT4_HT_INODE, 2); + KUNIT_ASSERT_FALSE(test, IS_ERR(nojournal)); + + ext4_set_feature_inline_data(sb); + ialloc_test_enable_flex_bg(ctx, 1); + EXT4_I(ctx->root_inode)->i_flags = EXT4_SYNC_FL | EXT4_NODUMP_FL | + EXT4_DIRSYNC_FL | EXT4_TOPDIR_FL | + EXT4_EXTENTS_FL; + + /* 1. Regular file in group 0 (first free bit is 10 -> ino 11) */ + reg = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, + NULL, 0, NULL, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(reg)); + ialloc_test_track_inode(test, ctx, reg); + KUNIT_EXPECT_EQ(test, reg->i_ino, 11UL); + KUNIT_EXPECT_TRUE(test, ext4_test_inode_flag(reg, EXT4_INODE_EXTENTS)); + KUNIT_EXPECT_EQ(test, le16_to_cpu(ext_inode_hdr(reg)->eh_magic), + le16_to_cpu(EXT4_EXT_MAGIC)); + KUNIT_EXPECT_TRUE(test, ext4_test_inode_state(reg, EXT4_STATE_NEW)); + KUNIT_EXPECT_TRUE(test, + ext4_test_inode_state(reg, EXT4_STATE_MAY_INLINE_DATA)); + KUNIT_EXPECT_EQ(test, + EXT4_I(reg)->i_flags & + (EXT4_SYNC_FL | EXT4_NODUMP_FL | EXT4_DIRSYNC_FL | + EXT4_TOPDIR_FL), + (u32)(EXT4_SYNC_FL | EXT4_NODUMP_FL)); + KUNIT_EXPECT_EQ(test, EXT4_I(reg)->i_extra_isize, + (u16)IALLOC_TEST_EXTRA_ISIZE); + + inum_le = cpu_to_le32(reg->i_ino); + gen_le = cpu_to_le32(reg->i_generation); + expected_seed = ext4_chksum(ctx->sbi.s_csum_seed, (u8 *)&inum_le, + sizeof(inum_le)); + expected_seed = ext4_chksum(expected_seed, (u8 *)&gen_le, + sizeof(gen_le)); + KUNIT_EXPECT_EQ(test, EXT4_I(reg)->i_csum_seed, expected_seed); + + /* + * 2. Directory inherits DIRSYNC (unlike regular files), still strips + * non-inheritable TOPDIR, and increments directory counters. + */ + dir = ext4_new_inode(nojournal, ctx->root_inode, S_IFDIR | 0755, + NULL, 12, NULL, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(dir)); + ialloc_test_track_inode(test, ctx, dir); + KUNIT_EXPECT_EQ(test, dir->i_ino, 12UL); + KUNIT_EXPECT_TRUE(test, ext4_test_inode_flag(dir, EXT4_INODE_EXTENTS)); + KUNIT_EXPECT_EQ(test, + EXT4_I(dir)->i_flags & + (EXT4_SYNC_FL | EXT4_NODUMP_FL | EXT4_DIRSYNC_FL | + EXT4_TOPDIR_FL), + (u32)(EXT4_SYNC_FL | EXT4_NODUMP_FL | + EXT4_DIRSYNC_FL)); + KUNIT_EXPECT_EQ(test, ext4_used_dirs_count(sb, &ctx->gdps[0]), 2U); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->flex_grps[0].used_dirs), 2); + + /* 3. Symlink gets EXT4_INODE_EXTENTS; FIFO does not */ + lnk = ext4_new_inode(nojournal, ctx->root_inode, S_IFLNK | 0777, + NULL, 13, NULL, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(lnk)); + ialloc_test_track_inode(test, ctx, lnk); + KUNIT_EXPECT_TRUE(test, ext4_test_inode_flag(lnk, EXT4_INODE_EXTENTS)); + + fifo = ext4_new_inode(nojournal, ctx->root_inode, S_IFIFO | 0600, + NULL, 14, NULL, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(fifo)); + ialloc_test_track_inode(test, ctx, fifo); + KUNIT_EXPECT_FALSE(test, ext4_test_inode_flag(fifo, EXT4_INODE_EXTENTS)); + + /* 4. EXT4_EA_INODE_FL suppresses EXT4_STATE_MAY_INLINE_DATA */ + ea_ino = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0600, + NULL, 15, NULL, EXT4_EA_INODE_FL); + KUNIT_ASSERT_FALSE(test, IS_ERR(ea_ino)); + ialloc_test_track_inode(test, ctx, ea_ino); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(ea_ino, + EXT4_STATE_MAY_INLINE_DATA)); + + /* 5. Full lifecycle round-trip: unlink + iput frees ino 11 back */ + iblk0 = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(0)); + KUNIT_ASSERT_NOT_NULL(test, iblk0); + KUNIT_EXPECT_TRUE(test, (bool)ext4_test_bit(10, iblk0->cache_buf)); + free_after_reg = percpu_counter_sum_positive(&ctx->sbi.s_freeinodes_counter); + + ialloc_test_untrack_inode(ctx, reg); + clear_nlink(reg); + iput(reg); + + KUNIT_EXPECT_FALSE(test, (bool)ext4_test_bit(10, iblk0->cache_buf)); + KUNIT_EXPECT_EQ(test, + percpu_counter_sum_positive(&ctx->sbi.s_freeinodes_counter), + free_after_reg + 1); + + ext4_journal_stop(nojournal); +} + +static void ialloc_test_new_inode_ownership_and_projid(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + handle_t *nojournal; + uid_t explicit_owner[2] = { 1001, 2002 }; + struct inode *ino_own, *ino_grpid, *ino_sgid; + + nojournal = ext4_journal_start_sb(sb, EXT4_HT_INODE, 2); + KUNIT_ASSERT_FALSE(test, IS_ERR(nojournal)); + + i_gid_write(ctx->root_inode, 3003); + ext4_set_feature_project(sb); + EXT4_I(ctx->root_inode)->i_projid = make_kprojid(&init_user_ns, 42); + ext4_set_inode_flag(ctx->root_inode, EXT4_INODE_PROJINHERIT); + + /* Explicit owner overrides uid/gid and inherits projid 42 */ + ino_own = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0640, + NULL, 0, explicit_owner, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(ino_own)); + ialloc_test_track_inode(test, ctx, ino_own); + KUNIT_EXPECT_EQ(test, i_uid_read(ino_own), 1001U); + KUNIT_EXPECT_EQ(test, i_gid_read(ino_own), 2002U); + KUNIT_EXPECT_EQ(test, + from_kprojid(&init_user_ns, EXT4_I(ino_own)->i_projid), + 42U); + + /* Without PROJINHERIT on parent, child gets EXT4_DEF_PROJID (0) and GRPID gid */ + ext4_clear_inode_flag(ctx->root_inode, EXT4_INODE_PROJINHERIT); + set_opt(sb, GRPID); + ino_grpid = ext4_new_inode(nojournal, ctx->root_inode, S_IFDIR | 0750, + NULL, 0, NULL, 0); + clear_opt(sb, GRPID); + KUNIT_ASSERT_FALSE(test, IS_ERR(ino_grpid)); + ialloc_test_track_inode(test, ctx, ino_grpid); + KUNIT_EXPECT_EQ(test, i_gid_read(ino_grpid), 3003U); + KUNIT_EXPECT_FALSE(test, !!(ino_grpid->i_mode & S_ISGID)); + KUNIT_EXPECT_EQ(test, + from_kprojid(&init_user_ns, EXT4_I(ino_grpid)->i_projid), + 0U); + + /* Standard inode_init_owner propagates parent's S_ISGID to child dir */ + ctx->root_inode->i_mode |= S_ISGID; + ino_sgid = ext4_new_inode(nojournal, ctx->root_inode, S_IFDIR | 0755, + NULL, 0, NULL, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(ino_sgid)); + ialloc_test_track_inode(test, ctx, ino_sgid); + KUNIT_EXPECT_EQ(test, i_gid_read(ino_sgid), 3003U); + KUNIT_EXPECT_TRUE(test, !!(ino_sgid->i_mode & S_ISGID)); + + ext4_journal_stop(nojournal); +} + +static void ialloc_test_new_inode_goal_uninit_and_corrupt_skip(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + handle_t *nojournal; + struct ialloc_test_blk *iblk0, *iblk2; + struct inode *ino_goal, *ino_sb_goal, *ino_skip, *ino_started; + struct inode *ino_replay; + + nojournal = ext4_journal_start_sb(sb, EXT4_HT_INODE, 2); + KUNIT_ASSERT_FALSE(test, IS_ERR(nojournal)); + + /* 1. Explicit goal = 140 in uninitialized group 2 (bit 11) */ + iblk2 = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(2)); + KUNIT_ASSERT_NOT_NULL(test, iblk2); + clear_bitmap_uptodate(&iblk2->bh); + clear_buffer_uptodate(&iblk2->bh); + clear_buffer_verified(&iblk2->bh); + ctx->gdps[2].bg_flags = cpu_to_le16(EXT4_BG_INODE_UNINIT | + EXT4_BG_BLOCK_UNINIT); + ext4_group_desc_csum_set(sb, 2, &ctx->gdps[2]); + + ino_goal = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, + NULL, 140, NULL, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(ino_goal)); + ialloc_test_track_inode(test, ctx, ino_goal); + KUNIT_EXPECT_EQ(test, ino_goal->i_ino, 140UL); + KUNIT_EXPECT_EQ(test, + le16_to_cpu(ctx->gdps[2].bg_flags) & + (EXT4_BG_INODE_UNINIT | EXT4_BG_BLOCK_UNINIT), 0); + KUNIT_EXPECT_EQ(test, ext4_free_group_clusters(sb, &ctx->gdps[2]), + 1006U); + KUNIT_EXPECT_EQ(test, ext4_itable_unused_count(sb, &ctx->gdps[2]), 52U); + + /* 2. sbi->s_inode_goal = 200 (group 3, bit 7) used when goal == 0 */ + ctx->sbi.s_inode_goal = 200; + ino_sb_goal = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, + NULL, 0, NULL, 0); + ctx->sbi.s_inode_goal = 0; + KUNIT_ASSERT_FALSE(test, IS_ERR(ino_sb_goal)); + ialloc_test_track_inode(test, ctx, ino_sb_goal); + KUNIT_EXPECT_EQ(test, ino_sb_goal->i_ino, 200UL); + + /* + * 3. Reserved bit 3 (ino 4 < EXT4_FIRST_INO) cleared in group 0: + * marks group 0 IBITMAP_CORRUPT and advances to group 1 (ino 65). + */ + iblk0 = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(0)); + KUNIT_ASSERT_NOT_NULL(test, iblk0); + ext4_clear_bit(3, iblk0->cache_buf); + ialloc_test_sync_ibitmap_csum(ctx, 0, true); + + ino_skip = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, + NULL, 4, NULL, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(ino_skip)); + ialloc_test_track_inode(test, ctx, ino_skip); + KUNIT_EXPECT_TRUE(test, + (bool)EXT4_MB_GRP_IBITMAP_CORRUPT(ctx->grp_infos[0])); + KUNIT_EXPECT_EQ(test, ino_skip->i_ino, 65UL); + + ext4_journal_stop(nojournal); + + /* 4. ext4_new_inode_start_handle (handle == NULL) starts handle */ + KUNIT_ASSERT_NULL(test, ext4_journal_current_handle()); + ino_started = ext4_new_inode_start_handle(&nop_mnt_idmap, + ctx->root_inode, + S_IFREG | 0644, NULL, 66, + NULL, EXT4_HT_INODE, 2); + KUNIT_ASSERT_FALSE(test, IS_ERR(ino_started)); + ialloc_test_track_inode(test, ctx, ino_started); + KUNIT_EXPECT_EQ(test, ino_started->i_ino, 66UL); + KUNIT_ASSERT_NOT_NULL(test, ext4_journal_current_handle()); + ext4_journal_stop(ext4_journal_current_handle()); + KUNIT_EXPECT_NULL(test, ext4_journal_current_handle()); + + /* + * 5. EXT4_FC_REPLAY with handle == NULL allocates exact goal ino 15 in + * group 0 despite IBITMAP_CORRUPT and without starting a handle. + */ + ext4_set_bit(3, iblk0->cache_buf); + ialloc_test_sync_ibitmap_csum(ctx, 0, true); + ctx->sbi.s_mount_state |= EXT4_FC_REPLAY; + ino_replay = ext4_new_inode(NULL, ctx->root_inode, S_IFREG | 0644, + NULL, 15, NULL, 0); + ctx->sbi.s_mount_state &= ~EXT4_FC_REPLAY; + KUNIT_ASSERT_FALSE(test, IS_ERR(ino_replay)); + ialloc_test_track_inode(test, ctx, ino_replay); + KUNIT_EXPECT_EQ(test, ino_replay->i_ino, 15UL); + KUNIT_EXPECT_NULL(test, ext4_journal_current_handle()); +} + +static void ialloc_test_new_inode_errors(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + handle_t *nojournal; + struct inode *unlinked_dir, *dup_existing, *res; + struct ialloc_test_blk *iblk; + ext4_group_t g; + + nojournal = ext4_journal_start_sb(sb, EXT4_HT_INODE, 2); + KUNIT_ASSERT_FALSE(test, IS_ERR(nojournal)); + + /* 1. NULL dir or unlinked dir -> -EPERM */ + res = ext4_new_inode(nojournal, NULL, S_IFREG | 0644, NULL, 0, NULL, 0); + KUNIT_EXPECT_EQ(test, PTR_ERR(res), -EPERM); + + unlinked_dir = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, unlinked_dir); + unlinked_dir->i_ino = 50; + unlinked_dir->i_mode = S_IFDIR | 0755; + clear_nlink(unlinked_dir); + ialloc_test_track_inode(test, ctx, unlinked_dir); + res = ext4_new_inode(nojournal, unlinked_dir, S_IFREG | 0644, NULL, 0, + NULL, 0); + KUNIT_EXPECT_EQ(test, PTR_ERR(res), -EPERM); + + /* 2. Emergency shutdown (-EIO) and emergency RO (-EROFS) */ + set_bit(EXT4_FLAGS_SHUTDOWN, &ctx->sbi.s_ext4_flags); + res = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, NULL, + 0, NULL, 0); + clear_bit(EXT4_FLAGS_SHUTDOWN, &ctx->sbi.s_ext4_flags); + KUNIT_EXPECT_EQ(test, PTR_ERR(res), -EIO); + + set_bit(EXT4_FLAGS_EMERGENCY_RO, &ctx->sbi.s_ext4_flags); + res = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, NULL, + 0, NULL, 0); + clear_bit(EXT4_FLAGS_EMERGENCY_RO, &ctx->sbi.s_ext4_flags); + KUNIT_EXPECT_EQ(test, PTR_ERR(res), -EROFS); + + /* 3. VFS alloc_inode failure -> -ENOMEM */ + ctx->fail_alloc_inode = true; + res = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, NULL, + 0, NULL, 0); + ctx->fail_alloc_inode = false; + KUNIT_EXPECT_EQ(test, PTR_ERR(res), -ENOMEM); + + /* 4. Journal write-access and dirty-metadata failures in group 1 */ + iblk = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(1)); + KUNIT_ASSERT_NOT_NULL(test, iblk); + + ctx->write_access_calls = 0; + ctx->fail_write_access_err = -EIO; + ctx->fail_write_access_on_call = 1; + res = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, NULL, + 70, NULL, 0); + KUNIT_EXPECT_EQ(test, PTR_ERR(res), -EIO); + KUNIT_EXPECT_FALSE(test, (bool)ext4_test_bit(5, iblk->cache_buf)); + + ctx->write_access_calls = 0; + ctx->fail_write_access_on_call = 2; + res = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, NULL, + 71, NULL, 0); + ctx->fail_write_access_err = 0; + ctx->fail_write_access_on_call = 0; + KUNIT_EXPECT_EQ(test, PTR_ERR(res), -EIO); + KUNIT_EXPECT_TRUE(test, (bool)ext4_test_bit(6, iblk->cache_buf)); + ext4_clear_bit(6, iblk->cache_buf); + ialloc_test_sync_ibitmap_csum(ctx, 1, true); + + ctx->dirty_metadata_calls = 0; + ctx->fail_dirty_metadata_err = -EIO; + ctx->fail_dirty_metadata_on_call = 1; + res = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, NULL, + 71, NULL, 0); + KUNIT_EXPECT_EQ(test, PTR_ERR(res), -EIO); + ext4_clear_bit(6, iblk->cache_buf); + ialloc_test_sync_ibitmap_csum(ctx, 1, true); + + ctx->dirty_metadata_calls = 0; + ctx->fail_dirty_metadata_on_call = 2; + res = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, NULL, + 71, NULL, 0); + ctx->fail_dirty_metadata_err = 0; + ctx->fail_dirty_metadata_on_call = 0; + KUNIT_EXPECT_EQ(test, PTR_ERR(res), -EIO); + ext4_clear_bit(6, iblk->cache_buf); + ext4_free_inodes_set(sb, &ctx->gdps[1], 64); + ialloc_test_sync_ibitmap_csum(ctx, 1, true); + +#ifdef CONFIG_EXT4_FS_SECURITY + /* 5. ext4_init_security failure rolls back allocated inode bit */ + ctx->fail_init_security_err = -EACCES; + res = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, NULL, + 70, NULL, 0); + ctx->fail_init_security_err = 0; + KUNIT_EXPECT_EQ(test, PTR_ERR(res), -EACCES); + KUNIT_EXPECT_FALSE(test, (bool)ext4_test_bit(5, iblk->cache_buf)); + KUNIT_EXPECT_EQ(test, ext4_free_inodes_count(sb, &ctx->gdps[1]), 64U); +#endif + + /* 6. ext4_mark_inode_dirty failure rolls back allocated inode bit */ + ctx->fail_mark_inode_dirty_err = -EIO; + res = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, NULL, + 70, NULL, 0); + ctx->fail_mark_inode_dirty_err = 0; + KUNIT_EXPECT_EQ(test, PTR_ERR(res), -EIO); + KUNIT_EXPECT_FALSE(test, (bool)ext4_test_bit(5, iblk->cache_buf)); + KUNIT_EXPECT_EQ(test, ext4_free_inodes_count(sb, &ctx->gdps[1]), 64U); + + /* + * 7. Doubly-allocated inode (insert_inode_locked collision): + * Pre-hash ino 140 in VFS cache, leave only bg 2 non-empty with bit 11 + * clear -> marks bg 2 IBITMAP_CORRUPT and returns -EIO. + */ + dup_existing = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, dup_existing); + dup_existing->i_ino = 140; + dup_existing->i_mode = S_IFREG | 0644; + KUNIT_ASSERT_EQ(test, insert_inode_locked(dup_existing), 0); + ialloc_test_track_inode(test, ctx, dup_existing); + + ext4_free_inodes_set(sb, &ctx->gdps[0], 0); + ext4_free_inodes_set(sb, &ctx->gdps[1], 0); + ext4_free_inodes_set(sb, &ctx->gdps[3], 0); + res = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, NULL, + 140, NULL, 0); + KUNIT_EXPECT_EQ(test, PTR_ERR(res), -EIO); + KUNIT_EXPECT_TRUE(test, + (bool)EXT4_MB_GRP_IBITMAP_CORRUPT(ctx->grp_infos[2])); + + /* 8. Descriptor claims free inodes in bg 3, but bitmap is all ones -> -ENOSPC */ + iblk = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(3)); + KUNIT_ASSERT_NOT_NULL(test, iblk); + memset(iblk->cache_buf, 0xff, IALLOC_TEST_BLK_SIZE); + ialloc_test_sync_ibitmap_csum(ctx, 3, true); + ext4_free_inodes_set(sb, &ctx->gdps[2], 0); + ext4_free_inodes_set(sb, &ctx->gdps[3], 5); + res = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, NULL, + 193, NULL, 0); + KUNIT_EXPECT_EQ(test, PTR_ERR(res), -ENOSPC); + + /* 9. All groups report 0 free inodes -> -ENOSPC before loop */ + for (g = 0; g < IALLOC_TEST_NGROUPS; g++) + ext4_free_inodes_set(sb, &ctx->gdps[g], 0); + res = ext4_new_inode(nojournal, ctx->root_inode, S_IFREG | 0644, NULL, + 0, NULL, 0); + KUNIT_EXPECT_EQ(test, PTR_ERR(res), -ENOSPC); + + ext4_journal_stop(nojournal); +} + +/* ========================================================================= + * 10. Orphans, Counters, & Lazy Init: ext4_orphan_get, ext4_count_*, + * ext4_init_inode_table + * ========================================================================= + */ + +static void ialloc_test_orphan_get(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ialloc_test_blk *iblk1; + struct inode *orphan, *got; + + /* Bounds checks */ + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_orphan_get(sb, 5)), -EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, + PTR_ERR(ext4_orphan_get(sb, IALLOC_TEST_TOTAL_INODES + 1)), + -EFSCORRUPTED); + + /* Clear bit in bitmap -> -EFSCORRUPTED */ + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_orphan_get(sb, 65)), -EFSCORRUPTED); + + /* Mark bit 0 (ino 65) allocated in group 1 */ + iblk1 = ialloc_test_find_blk(ctx, ialloc_test_ibitmap_blk(1)); + KUNIT_ASSERT_NOT_NULL(test, iblk1); + ext4_set_bit(0, iblk1->cache_buf); + ialloc_test_sync_ibitmap_csum(ctx, 1, true); + + /* Bitmap read error propagates */ + clear_bitmap_uptodate(&iblk1->bh); + clear_buffer_uptodate(&iblk1->bh); + ctx->fail_read_eio = true; + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_orphan_get(sb, 65)), -EIO); + ctx->fail_read_eio = false; + set_buffer_uptodate(&iblk1->bh); + set_bitmap_uptodate(&iblk1->bh); + set_buffer_verified(&iblk1->bh); + + /* ext4_iget error propagates */ + ctx->fail_iget_err = -EIO; + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_orphan_get(sb, 65)), -EIO); + ctx->fail_iget_err = 0; + + /* Prepare mock orphan inode */ + orphan = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, orphan); + orphan->i_ino = 65; + ialloc_test_track_inode(test, ctx, orphan); + ctx->iget_inode = orphan; + + /* 1. Valid unlinked orphan (i_nlink == 0, NEXT_ORPHAN <= max_ino) */ + orphan->i_mode = S_IFREG | 0644; + clear_nlink(orphan); + orphan->i_blocks = 8; + NEXT_ORPHAN(orphan) = 0; + got = ext4_orphan_get(sb, 65); + KUNIT_ASSERT_PTR_EQ(test, got, orphan); + iput(got); + + /* 2. Valid live truncating regular file orphan (i_nlink == 1) */ + set_nlink(orphan, 1); + ext4_set_inode_flag(orphan, EXT4_INODE_EXTENTS); + got = ext4_orphan_get(sb, 65); + KUNIT_ASSERT_PTR_EQ(test, got, orphan); + iput(got); + + /* 3. Live non-truncatable FIFO (i_nlink == 1) -> -EFSCORRUPTED */ + orphan->i_mode = S_IFIFO | 0600; + got = ext4_orphan_get(sb, 65); + KUNIT_EXPECT_EQ(test, PTR_ERR(got), -EFSCORRUPTED); + + /* 4. Unlinked orphan with NEXT_ORPHAN > max_ino zeroes i_blocks */ + orphan->i_mode = S_IFREG | 0644; + clear_nlink(orphan); + orphan->i_blocks = 24; + NEXT_ORPHAN(orphan) = IALLOC_TEST_TOTAL_INODES + 50; + got = ext4_orphan_get(sb, 65); + KUNIT_EXPECT_EQ(test, PTR_ERR(got), -EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, orphan->i_blocks, (blkcnt_t)0); + + /* 5. Unlinked bad_inode zeroes i_blocks and returns -EFSCORRUPTED */ + NEXT_ORPHAN(orphan) = 0; + orphan->i_blocks = 16; + make_bad_inode(orphan); + got = ext4_orphan_get(sb, 65); + KUNIT_EXPECT_EQ(test, PTR_ERR(got), -EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, orphan->i_blocks, (blkcnt_t)0); +} + +static void ialloc_test_count_free_inodes_and_dirs(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + + /* Include 64-bit high-16-bit values (0x10000 + low) and a NULL gdp */ + ext4_free_inodes_set(sb, &ctx->gdps[0], 10); + ext4_free_inodes_set(sb, &ctx->gdps[1], 0x10020); + ext4_free_inodes_set(sb, &ctx->gdps[2], 999); /* masked out below */ + ext4_free_inodes_set(sb, &ctx->gdps[3], 5); + + ext4_used_dirs_set(sb, &ctx->gdps[0], 2); + ext4_used_dirs_set(sb, &ctx->gdps[1], 0x20003); + ext4_used_dirs_set(sb, &ctx->gdps[2], 777); /* masked out below */ + ext4_used_dirs_set(sb, &ctx->gdps[3], 4); + + ctx->fail_gdp_mask = BIT(2); + + KUNIT_EXPECT_EQ(test, ext4_count_free_inodes(sb), 0x1002fUL); + KUNIT_EXPECT_EQ(test, ext4_count_dirs(sb), 0x20009UL); +} + +static void ialloc_test_init_inode_table(struct kunit *test) +{ + struct ialloc_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + int err; + + /* 1. Already EXT4_BG_INODE_ZEROED is a no-op */ + ctx->gdps[1].bg_flags = cpu_to_le16(EXT4_BG_INODE_ZEROED); + err = ext4_init_inode_table(sb, 1, 1); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->zeroout_calls, 0U); + + /* 2. Uninitialized group 1 zeroes all 16 blocks with barrier = 1 */ + ctx->gdps[1].bg_flags = cpu_to_le16(EXT4_BG_INODE_UNINIT); + err = ext4_init_inode_table(sb, 1, 1); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->zeroout_calls, 1U); + KUNIT_EXPECT_EQ(test, ctx->last_zeroout_blk, ialloc_test_itable_blk(1)); + KUNIT_EXPECT_EQ(test, ctx->last_zeroout_num, 16); + KUNIT_EXPECT_EQ(test, ctx->last_zeroout_barrier, 1); + KUNIT_EXPECT_TRUE(test, + !!(le16_to_cpu(ctx->gdps[1].bg_flags) & + EXT4_BG_INODE_ZEROED)); + KUNIT_EXPECT_TRUE(test, + (bool)ext4_group_desc_csum_verify(sb, 1, + &ctx->gdps[1])); + + /* + * 3. Initialized group 2 with itable_unused = 54 -> used_inos = 10 -> + * used_blks = DIV_ROUND_UP(10, 4) = 3 -> zeroes remaining 13 blocks. + */ + ctx->gdps[2].bg_flags = 0; + ext4_itable_unused_set(sb, &ctx->gdps[2], 54); + err = ext4_init_inode_table(sb, 2, 0); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->zeroout_calls, 2U); + KUNIT_EXPECT_EQ(test, ctx->last_zeroout_blk, + ialloc_test_itable_blk(2) + 3); + KUNIT_EXPECT_EQ(test, ctx->last_zeroout_num, 13); + KUNIT_EXPECT_EQ(test, ctx->last_zeroout_barrier, 0); + KUNIT_EXPECT_TRUE(test, + !!(le16_to_cpu(ctx->gdps[2].bg_flags) & + EXT4_BG_INODE_ZEROED)); + + /* 4. Full inode table (itable_unused = 0 -> num = 0) skips zeroout, sets ZEROED */ + ctx->gdps[3].bg_flags = 0; + ext4_itable_unused_set(sb, &ctx->gdps[3], 0); + err = ext4_init_inode_table(sb, 3, 1); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->zeroout_calls, 2U); + KUNIT_EXPECT_TRUE(test, + !!(le16_to_cpu(ctx->gdps[3].bg_flags) & + EXT4_BG_INODE_ZEROED)); + + /* 5. Corrupt itable_unused > inodes_per_group returns 1 without ZEROED */ + ctx->gdps[3].bg_flags = 0; + ext4_itable_unused_set(sb, &ctx->gdps[3], 100); + err = ext4_init_inode_table(sb, 3, 0); + KUNIT_EXPECT_EQ(test, err, 1); + KUNIT_EXPECT_FALSE(test, + !!(le16_to_cpu(ctx->gdps[3].bg_flags) & + EXT4_BG_INODE_ZEROED)); + + /* 6. Group 0 with used_inos (4) < EXT4_FIRST_INO (11) returns 1 */ + ctx->gdps[0].bg_flags = 0; + ext4_itable_unused_set(sb, &ctx->gdps[0], 60); + err = ext4_init_inode_table(sb, 0, 0); + KUNIT_EXPECT_EQ(test, err, 1); + KUNIT_EXPECT_FALSE(test, + !!(le16_to_cpu(ctx->gdps[0].bg_flags) & + EXT4_BG_INODE_ZEROED)); + + /* 7. Zeroout I/O failure (-EIO) and emergency RO (-EROFS) */ + ctx->gdps[3].bg_flags = cpu_to_le16(EXT4_BG_INODE_UNINIT); + ctx->fail_itable_zeroout_err = -EIO; + err = ext4_init_inode_table(sb, 3, 0); + ctx->fail_itable_zeroout_err = 0; + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_FALSE(test, + !!(le16_to_cpu(ctx->gdps[3].bg_flags) & + EXT4_BG_INODE_ZEROED)); + + set_bit(EXT4_FLAGS_EMERGENCY_RO, &ctx->sbi.s_ext4_flags); + err = ext4_init_inode_table(sb, 3, 0); + clear_bit(EXT4_FLAGS_EMERGENCY_RO, &ctx->sbi.s_ext4_flags); + KUNIT_EXPECT_EQ(test, err, -EROFS); +} + +static struct kunit_case ialloc_test_cases[] = { + KUNIT_CASE_PARAM(ialloc_test_mark_bitmap_end, + mark_bitmap_end_gen_params), + KUNIT_CASE(ialloc_test_end_bitmap_read_ok), + KUNIT_CASE(ialloc_test_end_bitmap_read_ioerr), + KUNIT_CASE(ialloc_test_validate_ibitmap_csum), + KUNIT_CASE(ialloc_test_validate_ibitmap_short_circuits), + KUNIT_CASE(ialloc_test_read_ibitmap_disk_and_cache), + KUNIT_CASE(ialloc_test_read_ibitmap_uninit), + KUNIT_CASE(ialloc_test_read_ibitmap_errors), + KUNIT_CASE(ialloc_test_free_inode_reg_and_dir), + KUNIT_CASE(ialloc_test_free_inode_guards), + KUNIT_CASE(ialloc_test_free_inode_corrupt_and_journal_errors), + KUNIT_CASE(ialloc_test_orlov_topdir_spread), + KUNIT_CASE(ialloc_test_orlov_subdir_and_thresholds), + KUNIT_CASE(ialloc_test_orlov_flex_bg_and_fallback), + KUNIT_CASE(ialloc_test_find_group_other_non_flex), + KUNIT_CASE(ialloc_test_find_group_other_flex_bg), + KUNIT_CASE(ialloc_test_recently_deleted), + KUNIT_CASE(ialloc_test_find_inode_bit), + KUNIT_CASE(ialloc_test_mark_inode_used_uninit), + KUNIT_CASE(ialloc_test_mark_inode_used_errors), + KUNIT_CASE(ialloc_test_xattr_credits_for_new_inode), + KUNIT_CASE(ialloc_test_new_inode_types_and_flags), + KUNIT_CASE(ialloc_test_new_inode_ownership_and_projid), + KUNIT_CASE(ialloc_test_new_inode_goal_uninit_and_corrupt_skip), + KUNIT_CASE(ialloc_test_new_inode_errors), + KUNIT_CASE(ialloc_test_orphan_get), + KUNIT_CASE(ialloc_test_count_free_inodes_and_dirs), + KUNIT_CASE(ialloc_test_init_inode_table), + {} +}; + +static struct kunit_suite ialloc_test_suite = { + .name = "ext4_ialloc_test", + .init = ialloc_test_init, + .test_cases = ialloc_test_cases, +}; + +kunit_test_suites(&ialloc_test_suite); + +MODULE_DESCRIPTION("KUnit tests for ext4 inode allocation and deallocation"); +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/ialloc.c b/fs/ext4/ialloc.c index 527f1f703c3e08..3f24063d50e80c 100644 --- a/fs/ext4/ialloc.c +++ b/fs/ext4/ialloc.c @@ -23,6 +23,7 @@ #include #include #include +#include #include @@ -65,6 +66,7 @@ void ext4_mark_bitmap_end(int start_bit, int end_bit, char *bitmap) if (i < end_bit) memset(bitmap + (i >> 3), 0xff, (end_bit - i) >> 3); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mark_bitmap_end); void ext4_end_bitmap_read(struct bio *bio) { @@ -77,6 +79,7 @@ void ext4_end_bitmap_read(struct bio *bio) } unlock_buffer(bh); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_end_bitmap_read); static int ext4_validate_inode_bitmap(struct super_block *sb, struct ext4_group_desc *desc, @@ -143,7 +146,7 @@ ext4_read_inode_bitmap(struct super_block *sb, ext4_group_t block_group) EXT4_GROUP_INFO_IBITMAP_CORRUPT); return ERR_PTR(-EFSCORRUPTED); } - bh = sb_getblk(sb, bitmap_blk); + bh = ext4_sb_getblk(sb, bitmap_blk); if (unlikely(!bh)) { ext4_warning(sb, "Cannot read inode bitmap - " "block_group = %u, inode_bitmap = %llu", @@ -249,6 +252,8 @@ void ext4_free_inode(handle_t *handle, struct inode *inode) int fatal = 0, err, count, cleared; struct ext4_group_info *grp; + KUNIT_STATIC_STUB_REDIRECT(ext4_free_inode, handle, inode); + if (!sb) { printk(KERN_ERR "EXT4-fs: %s:%d: inode on " "nonexistent device\n", __func__, __LINE__); @@ -362,6 +367,7 @@ void ext4_free_inode(handle_t *handle, struct inode *inode) brelse(bitmap_bh); ext4_std_error(sb, fatal); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_free_inode); struct orlov_stats { __u64 free_clusters; @@ -569,11 +575,70 @@ static int find_group_orlov(struct super_block *sb, struct inode *parent, return -1; } +static bool ext4_group_has_free_inode(struct super_block *sb, ext4_group_t g) +{ + struct ext4_group_desc *desc = ext4_get_group_desc(sb, g, NULL); + + return desc && ext4_free_inodes_count(sb, desc); +} + +/* + * Pick a group with a free inode in the flex group that starts at @first. + * First try the group chosen by the parent's inode number, so that the + * files of different directories in a flex group are less likely to share + * an inode bitmap and inode table blocks. Once that group is full, keep + * using @last, the group last picked for this directory, if it is in this + * flex group, then prefer a group with no inode in use, which no other + * directory uses yet, then take any group with a free inode. Return -1 if + * no group in the flex group has a free inode. + */ +static int find_group_in_flex(struct super_block *sb, struct inode *parent, + ext4_group_t first, ext4_group_t last, + int flex_size, ext4_group_t *group) +{ + ext4_group_t ngroups = ext4_get_groups_count(sb); + ext4_group_t n = min_t(ext4_group_t, flex_size, ngroups - first); + ext4_group_t start = (unsigned int)parent->i_ino % n; + ext4_group_t i, g, avail = ngroups; + + if (ext4_group_has_free_inode(sb, first + start)) { + *group = first + start; + return 0; + } + if (last >= first && last < first + n && + ext4_group_has_free_inode(sb, last)) { + *group = last; + return 0; + } + for (i = 1; i < n; i++) { + struct ext4_group_desc *desc; + unsigned int nr_free; + + if (++start == n) + start = 0; + g = first + start; + desc = ext4_get_group_desc(sb, g, NULL); + if (!desc) + continue; + nr_free = ext4_free_inodes_count(sb, desc); + if (nr_free == EXT4_INODES_PER_GROUP(sb)) { + *group = g; + return 0; + } + if (nr_free && avail == ngroups) + avail = g; + } + if (avail == ngroups) + return -1; + *group = avail; + return 0; +} + static int find_group_other(struct super_block *sb, struct inode *parent, ext4_group_t *group, umode_t mode) { ext4_group_t parent_group = EXT4_I(parent)->i_block_group; - ext4_group_t i, last, ngroups = ext4_get_groups_count(sb); + ext4_group_t i, ngroups = ext4_get_groups_count(sb); struct ext4_group_desc *desc; int flex_size = ext4_flex_bg_size(EXT4_SB(sb)); @@ -585,34 +650,34 @@ static int find_group_other(struct super_block *sb, struct inode *parent, * group for future allocations. */ if (flex_size > 1) { + ext4_group_t last_alloc = EXT4_I(parent)->i_last_alloc_group; int retry = 0; try_again: parent_group &= ~(flex_size-1); - last = parent_group + flex_size; - if (last > ngroups) - last = ngroups; - for (i = parent_group; i < last; i++) { - desc = ext4_get_group_desc(sb, i, NULL); - if (desc && ext4_free_inodes_count(sb, desc)) { - *group = i; - return 0; - } - } - if (!retry && EXT4_I(parent)->i_last_alloc_group != ~0) { + if (!find_group_in_flex(sb, parent, parent_group, last_alloc, + flex_size, group)) + return 0; + if (!retry && last_alloc < ngroups) { retry = 1; - parent_group = EXT4_I(parent)->i_last_alloc_group; + parent_group = last_alloc; goto try_again; } /* * If this didn't work, use the Orlov search algorithm * to find a new flex group; we pass in the mode to - * avoid the topdir algorithms. + * avoid the topdir algorithms. Then pick the group inside + * the flex group Orlov chose the same way as above. */ *group = parent_group + flex_size; - if (*group > ngroups) + if (*group >= ngroups) *group = 0; - return find_group_orlov(sb, parent, group, mode, NULL); + if (find_group_orlov(sb, parent, group, mode, NULL)) + return -1; + /* Keep Orlov's group if its flex group has no free inode now */ + find_group_in_flex(sb, parent, *group & ~(flex_size - 1), + last_alloc, flex_size, group); + return 0; } /* @@ -694,7 +759,7 @@ static int recently_deleted(struct super_block *sb, ext4_group_t group, int ino) ino >= EXT4_INODES_PER_GROUP(sb) - ext4_itable_unused_count(sb, gdp))) return 0; - bh = sb_find_get_block(sb, ext4_inode_table(sb, gdp) + + bh = ext4_sb_find_get_block(sb, ext4_inode_table(sb, gdp) + (ino / inodes_per_block)); if (!bh || !buffer_uptodate(bh)) /* @@ -767,6 +832,8 @@ int ext4_mark_inode_used(struct super_block *sb, int ino) int bit; int err; + KUNIT_STATIC_STUB_REDIRECT(ext4_mark_inode_used, sb, ino); + if (ino < EXT4_FIRST_INO(sb) || ino > max_ino) return -EFSCORRUPTED; @@ -872,6 +939,7 @@ int ext4_mark_inode_used(struct super_block *sb, int ino) brelse(inode_bitmap_bh); return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mark_inode_used); static int ext4_xattr_credits_for_new_inode(struct inode *dir, mode_t mode, bool encrypt) @@ -953,6 +1021,10 @@ struct inode *__ext4_new_inode(const struct mnt_idmap *idmap, struct ext4_group_info *grp = NULL; bool encrypt = false; + KUNIT_STATIC_STUB_REDIRECT(__ext4_new_inode, idmap, handle, dir, mode, + qstr, goal, owner, i_flags, handle_type, + line_no, nblocks); + /* Cannot create files in a deleted directory */ if (!dir || !dir->i_nlink) return ERR_PTR(-EPERM); @@ -1374,6 +1446,7 @@ struct inode *__ext4_new_inode(const struct mnt_idmap *idmap, brelse(inode_bitmap_bh); return ERR_PTR(err); } +EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_new_inode); /* Verify that we are loading a valid orphan from disk */ struct inode *ext4_orphan_get(struct super_block *sb, unsigned long ino) @@ -1447,6 +1520,7 @@ struct inode *ext4_orphan_get(struct super_block *sb, unsigned long ino) brelse(bitmap_bh); return ERR_PTR(err); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_orphan_get); unsigned long ext4_count_free_inodes(struct super_block *sb) { @@ -1497,6 +1571,7 @@ unsigned long ext4_count_free_inodes(struct super_block *sb) return desc_count; #endif } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_count_free_inodes); /* Called at mount-time, super-block is locked */ unsigned long ext4_count_dirs(struct super_block * sb) @@ -1512,6 +1587,26 @@ unsigned long ext4_count_dirs(struct super_block * sb) } return count; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_count_dirs); + +int ext4_itable_zeroout(struct super_block *sb, ext4_fsblk_t blk, int num, + int barrier) +{ + int ret; + + KUNIT_STATIC_STUB_REDIRECT(ext4_itable_zeroout, sb, blk, num, barrier); + + ret = sb_issue_zeroout(sb, blk, num, GFP_NOFS); + if (ret < 0) + return ret; + if (barrier) { + ret = blkdev_issue_flush(sb->s_bdev); + if (ret) + return ret; + } + return 0; +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_itable_zeroout); /* * Zeroes not yet zeroed inode table - just write zeroes through the whole @@ -1608,11 +1703,9 @@ int ext4_init_inode_table(struct super_block *sb, ext4_group_t group, ext4_debug("going to zero out inode table in group %d\n", group); - ret = sb_issue_zeroout(sb, blk, num, GFP_NOFS); - if (ret < 0) + ret = ext4_itable_zeroout(sb, blk, num, barrier); + if (ret) goto err_out; - if (barrier) - blkdev_issue_flush(sb->s_bdev); skip_zeroout: ext4_lock_group(sb, group); @@ -1631,3 +1724,58 @@ int ext4_init_inode_table(struct super_block *sb, ext4_group_t group, out: return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_init_inode_table); + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +int ext4_validate_inode_bitmap_test(struct super_block *sb, + struct ext4_group_desc *desc, + ext4_group_t block_group, + struct buffer_head *bh) +{ + return ext4_validate_inode_bitmap(sb, desc, block_group, bh); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_validate_inode_bitmap_test); + +struct buffer_head *ext4_read_inode_bitmap_test(struct super_block *sb, + ext4_group_t block_group) +{ + return ext4_read_inode_bitmap(sb, block_group); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_read_inode_bitmap_test); + +int ext4_find_group_orlov_test(struct super_block *sb, struct inode *parent, + ext4_group_t *group, umode_t mode, + const struct qstr *qstr) +{ + return find_group_orlov(sb, parent, group, mode, qstr); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_find_group_orlov_test); + +int ext4_find_group_other_test(struct super_block *sb, struct inode *parent, + ext4_group_t *group, umode_t mode) +{ + return find_group_other(sb, parent, group, mode); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_find_group_other_test); + +int ext4_recently_deleted_test(struct super_block *sb, ext4_group_t group, + int ino) +{ + return recently_deleted(sb, group, ino); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_recently_deleted_test); + +int ext4_find_inode_bit_test(struct super_block *sb, ext4_group_t group, + struct buffer_head *bitmap, unsigned long *ino) +{ + return find_inode_bit(sb, group, bitmap, ino); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_find_inode_bit_test); + +int ext4_xattr_credits_for_new_inode_test(struct inode *dir, mode_t mode, + bool encrypt) +{ + return ext4_xattr_credits_for_new_inode(dir, mode, encrypt); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_credits_for_new_inode_test); +#endif diff --git a/fs/ext4/indirect-test.c b/fs/ext4/indirect-test.c new file mode 100644 index 00000000000000..8d4a430ecb272c --- /dev/null +++ b/fs/ext4/indirect-test.c @@ -0,0 +1,1293 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for fs/ext4/indirect.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_jbd2.h" + +#define IND_TEST_BLK_SIZE 1024U +#define IND_TEST_BLK_BITS 10U +#define IND_TEST_PTRS_PER_BLK (IND_TEST_BLK_SIZE / sizeof(__le32)) +#define IND_TEST_BLOCKS_PER_GRP 1024U +#define IND_TEST_NGROUPS 8U +#define IND_TEST_FIRST_DATA_BLK 1U +#define IND_TEST_TOTAL_BLKS (IND_TEST_FIRST_DATA_BLK + \ + IND_TEST_NGROUPS * \ + IND_TEST_BLOCKS_PER_GRP) +#define IND_TEST_INODE_SIZE 256U +#define IND_TEST_EXTRA_ISIZE 32U +#define IND_TEST_INODES_PER_GRP 32U +#define IND_TEST_MAX_FREED_REC 128U + +#define IND_TEST_IND_BASE EXT4_NDIR_BLOCKS +#define IND_TEST_DIND_BASE (IND_TEST_IND_BASE + \ + IND_TEST_PTRS_PER_BLK) +#define IND_TEST_TIND_BASE (IND_TEST_DIND_BASE + \ + IND_TEST_PTRS_PER_BLK * \ + IND_TEST_PTRS_PER_BLK) +#define IND_TEST_MAX_LBLK (IND_TEST_TIND_BASE + \ + IND_TEST_PTRS_PER_BLK * \ + IND_TEST_PTRS_PER_BLK * \ + IND_TEST_PTRS_PER_BLK) + +struct ind_mock_blk { + struct list_head node; + ext4_fsblk_t blocknr; + struct buffer_head bh; + u8 *data; +}; + +struct ind_test_ctx { + struct super_block *sb; + struct ext4_sb_info sbi; + struct ext4_super_block *es; + struct blockgroup_lock bgl; + struct gendisk bdev_disk; + struct block_device bdev; + struct request_queue bdev_queue; + struct inode bd_inode; + struct folio *bh_folio; + struct list_head blks; + ext4_fsblk_t device_blocks; + ext4_fsblk_t next_alloc_pblk; + unsigned int alloc_calls; + unsigned int fail_alloc_on_call; + int fail_alloc_err; + int read_bh_err; + ext4_fsblk_t freed_blks[IND_TEST_MAX_FREED_REC]; + unsigned int freed_cnt; + bool rwsem_inited; + bool es_shrinker_inited; +}; + +static struct kunit *active_ind_test; + +static struct inode *ind_test_alloc_inode(struct super_block *sb) +{ + struct ext4_inode_info *ei; + + ei = kzalloc_obj(*ei); + if (!ei) + return NULL; + + init_rwsem(&ei->i_data_sem); + inode_init_once(&ei->vfs_inode); + inode_set_iversion(&ei->vfs_inode, 1); + ei->i_prealloc_node = RB_ROOT; + rwlock_init(&ei->i_prealloc_lock); + ext4_es_init_tree(&ei->i_es_tree); + rwlock_init(&ei->i_es_lock); + INIT_LIST_HEAD(&ei->i_es_list); + spin_lock_init(&ei->i_raw_lock); + spin_lock_init(&ei->i_block_reservation_lock); + ext4_init_pending_tree(&ei->i_pending_tree); + init_rwsem(&ei->xattr_sem); + INIT_LIST_HEAD(&ei->i_rsv_conversion_list); + spin_lock_init(&ei->i_completed_io_lock); + INIT_LIST_HEAD(&ei->i_orphan); + ext4_fc_init_inode(&ei->vfs_inode); + spin_lock_init(&ei->i_fc_lock); + ei->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + ei->i_extra_isize = IND_TEST_EXTRA_ISIZE; + ei->i_last_alloc_group = ~0U; + + return &ei->vfs_inode; +} + +static void ind_test_free_inode(struct inode *inode) +{ + kfree(EXT4_I(inode)); +} + +static void ind_test_evict_inode(struct inode *inode) +{ + truncate_inode_pages_final(&inode->i_data); + ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS); + clear_inode(inode); +} + +#ifdef CONFIG_QUOTA +static struct dquot __rcu **ind_test_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} +#endif + +static const struct super_operations ind_test_sops = { + .alloc_inode = ind_test_alloc_inode, + .free_inode = ind_test_free_inode, + .evict_inode = ind_test_evict_inode, +#ifdef CONFIG_QUOTA + .get_dquots = ind_test_get_dquots, +#endif +}; + +static int ind_test_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static void ind_test_sb_upd_work(struct work_struct *work) +{ +} + +static void ind_test_err_timer(struct timer_list *t) +{ +} + +static struct file_system_type ind_test_fs_type = { + .name = "ext4_indirect_kunit", + .init_fs_context = ind_test_init_fs_context, + .kill_sb = kill_anon_super, +}; + +static void ind_init_mock_bh(struct buffer_head *bh, struct folio *folio, + u8 *data, size_t size, sector_t blocknr) +{ + memset(bh, 0, sizeof(*bh)); + bh->b_folio = folio; + bh->b_data = (char *)data; + bh->b_size = size; + bh->b_blocknr = blocknr; + atomic_set(&bh->b_count, 2); + set_buffer_uptodate(bh); + set_buffer_mapped(bh); +} + +static struct buffer_head *ind_lookup_bh(struct ind_test_ctx *ctx, + ext4_fsblk_t blocknr) +{ + struct ind_mock_blk *blk; + + list_for_each_entry(blk, &ctx->blks, node) { + if (blk->blocknr == blocknr) + return &blk->bh; + } + return NULL; +} + +static struct buffer_head *ind_get_or_create_bh(struct ind_test_ctx *ctx, + ext4_fsblk_t blocknr) +{ + struct buffer_head *bh; + struct ind_mock_blk *blk; + + bh = ind_lookup_bh(ctx, blocknr); + if (bh) { + get_bh(bh); + return bh; + } + + blk = kzalloc_obj(*blk); + if (!blk) + return NULL; + blk->data = kzalloc(IND_TEST_BLK_SIZE, GFP_KERNEL); + if (!blk->data) { + kfree(blk); + return NULL; + } + blk->blocknr = blocknr; + ind_init_mock_bh(&blk->bh, ctx->bh_folio, blk->data, + IND_TEST_BLK_SIZE, blocknr); + list_add_tail(&blk->node, &ctx->blks); + get_bh(&blk->bh); + return &blk->bh; +} + +static struct buffer_head *ind_sb_getblk_stub(struct super_block *sb, + ext4_fsblk_t block) +{ + struct kunit *test = active_ind_test; + struct ind_test_ctx *ctx; + + if (!test) + return NULL; + ctx = test->priv; + if (!ctx || sb != ctx->sb) + return NULL; + + return ind_get_or_create_bh(ctx, block); +} + +static struct buffer_head *ind_sb_bread_nofail_stub(struct super_block *sb, + sector_t block) +{ + struct kunit *test = active_ind_test; + struct ind_test_ctx *ctx; + struct buffer_head *bh; + + if (!test) + return ERR_PTR(-EIO); + ctx = test->priv; + if (!ctx || sb != ctx->sb) + return ERR_PTR(-EIO); + if ((ext4_fsblk_t)block >= ctx->device_blocks) + return ERR_PTR(-EIO); + + bh = ind_get_or_create_bh(ctx, block); + if (!bh) + return ERR_PTR(-ENOMEM); + return bh; +} + +static int ind_read_bh_stub(struct buffer_head *bh, blk_opf_t op_flags, + bio_end_io_t end_io, bool simu_fail) +{ + struct kunit *test = active_ind_test; + struct ind_test_ctx *ctx; + + if (!test) { + unlock_buffer(bh); + return -EIO; + } + ctx = test->priv; + if (ctx->read_bh_err) { + unlock_buffer(bh); + return ctx->read_bh_err; + } + + set_buffer_uptodate(bh); + unlock_buffer(bh); + return 0; +} + +static int ind_handle_dirty_metadata_stub(const char *where, unsigned int line, + handle_t *handle, struct inode *inode, + struct buffer_head *bh) +{ + if (bh) + set_buffer_uptodate(bh); + return 0; +} + +static int ind_mark_inode_dirty_stub(handle_t *handle, struct inode *inode, + const char *func, unsigned int line) +{ + return 0; +} + +static ext4_fsblk_t ind_mb_new_blocks_stub(handle_t *handle, + struct ext4_allocation_request *ar, + int *errp) +{ + struct kunit *test = active_ind_test; + struct ind_test_ctx *ctx; + ext4_fsblk_t pblk; + + if (!test) { + *errp = -EIO; + return 0; + } + ctx = test->priv; + ctx->alloc_calls++; + if (ctx->fail_alloc_on_call && + ctx->alloc_calls == ctx->fail_alloc_on_call) { + *errp = ctx->fail_alloc_err; + return 0; + } + + pblk = ctx->next_alloc_pblk; + ctx->next_alloc_pblk += ar->len; + ar->inode->i_blocks += (blkcnt_t)ar->len << + (ar->inode->i_blkbits - 9); + *errp = 0; + return pblk; +} + +static void ind_free_blocks_stub(handle_t *handle, struct inode *inode, + struct buffer_head *bh, ext4_fsblk_t block, + unsigned long count, int flags) +{ + struct kunit *test = active_ind_test; + struct ind_test_ctx *ctx; + ext4_fsblk_t start_blk = block; + blkcnt_t sectors; + unsigned long i; + + if (!test) + return; + ctx = test->priv; + if (!start_blk && bh) + start_blk = bh->b_blocknr; + + for (i = 0; i < count && ctx->freed_cnt < IND_TEST_MAX_FREED_REC; i++) + ctx->freed_blks[ctx->freed_cnt++] = start_blk + i; + + sectors = (blkcnt_t)count << (inode->i_blkbits - 9); + if (inode->i_blocks >= sectors) + inode->i_blocks -= sectors; + if (bh) + brelse(bh); +} + +static bool ind_was_freed(struct ind_test_ctx *ctx, ext4_fsblk_t blk) +{ + unsigned int i; + + for (i = 0; i < ctx->freed_cnt; i++) { + if (ctx->freed_blks[i] == blk) + return true; + } + return false; +} + +static __le32 *ind_blk_ptrs(struct kunit *test, ext4_fsblk_t blk) +{ + struct ind_test_ctx *ctx = test->priv; + struct buffer_head *bh; + + bh = ind_get_or_create_bh(ctx, blk); + KUNIT_ASSERT_NOT_NULL(test, bh); + brelse(bh); + return (__le32 *)bh->b_data; +} + +static struct inode *ind_make_test_inode(struct kunit *test, unsigned long ino) +{ + struct ind_test_ctx *ctx = test->priv; + struct inode *inode; + + inode = new_inode(ctx->sb); + KUNIT_ASSERT_NOT_NULL(test, inode); + inode->i_ino = ino; + inode->i_mode = S_IFREG | 0644; + inode->i_blkbits = IND_TEST_BLK_BITS; + inode->i_flags |= S_NOQUOTA; + EXT4_I(inode)->i_block_group = 0; + return inode; +} + +static void ind_test_cleanup(struct ind_test_ctx *ctx) +{ + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + struct ind_mock_blk *blk, *tmp; + + active_ind_test = NULL; + + cancel_work_sync(&sbi->s_sb_upd_work); + timer_delete_sync(&sbi->s_err_report); + + if (sb) { + deactivate_super(sb); + ctx->sb = NULL; + } + rcu_barrier(); + + if (ctx->es_shrinker_inited) { + ext4_es_unregister_shrinker(sbi); + ext4_es_destroy_stats(sbi); + ctx->es_shrinker_inited = false; + } + + percpu_counter_destroy(&sbi->s_freeclusters_counter); + percpu_counter_destroy(&sbi->s_dirtyclusters_counter); + percpu_counter_destroy(&sbi->s_freeinodes_counter); + + if (ctx->rwsem_inited) { + percpu_free_rwsem(&sbi->s_writepages_rwsem); + ctx->rwsem_inited = false; + } + + list_for_each_entry_safe(blk, tmp, &ctx->blks, node) { + list_del(&blk->node); + kfree(blk->data); + kfree(blk); + } + + if (ctx->bh_folio) { + folio_put(ctx->bh_folio); + ctx->bh_folio = NULL; + } + + if (ctx->bdev.bd_stats) { + free_percpu(ctx->bdev.bd_stats); + ctx->bdev.bd_stats = NULL; + } +} + +KUNIT_DEFINE_ACTION_WRAPPER(ind_test_cleanup_action, ind_test_cleanup, + struct ind_test_ctx *); + +static int ind_test_set_super(struct super_block *sb, struct fs_context *fc) +{ + return set_anon_super_fc(sb, fc); +} + +static int ind_test_init(struct kunit *test) +{ + struct ind_test_ctx *ctx; + struct fs_context *fc; + struct super_block *sb; + struct ext4_sb_info *sbi; + struct buffer_head *sbh; + struct inode *root_inode; + int ret; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + INIT_LIST_HEAD(&ctx->blks); + ctx->device_blocks = IND_TEST_TOTAL_BLKS; + ctx->next_alloc_pblk = 1000; + test->priv = ctx; + + ctx->bdev.bd_stats = alloc_percpu(struct disk_stats); + KUNIT_ASSERT_TRUE(test, ctx->bdev.bd_stats != NULL); + + ctx->bh_folio = folio_alloc(GFP_KERNEL, 0); + if (!ctx->bh_folio) { + free_percpu(ctx->bdev.bd_stats); + ctx->bdev.bd_stats = NULL; + KUNIT_FAIL_AND_ABORT(test, "folio_alloc failed"); + } + + fc = fs_context_for_mount(&ind_test_fs_type, 0); + if (IS_ERR(fc)) { + folio_put(ctx->bh_folio); + ctx->bh_folio = NULL; + free_percpu(ctx->bdev.bd_stats); + ctx->bdev.bd_stats = NULL; + KUNIT_FAIL_AND_ABORT(test, "fs_context_for_mount failed: %ld", + PTR_ERR(fc)); + } + sb = sget_fc(fc, NULL, ind_test_set_super); + put_fs_context(fc); + if (IS_ERR(sb)) { + folio_put(ctx->bh_folio); + ctx->bh_folio = NULL; + free_percpu(ctx->bdev.bd_stats); + ctx->bdev.bd_stats = NULL; + KUNIT_FAIL_AND_ABORT(test, "sget_fc failed: %ld", PTR_ERR(sb)); + } + ctx->sb = sb; + sbi = &ctx->sbi; + INIT_WORK(&sbi->s_sb_upd_work, ind_test_sb_upd_work); + timer_setup(&sbi->s_err_report, ind_test_err_timer, 0); + up_write(&sb->s_umount); + + ret = kunit_add_action_or_reset(test, ind_test_cleanup_action, ctx); + KUNIT_ASSERT_EQ(test, ret, 0); + + sb->s_fs_info = sbi; + sb->s_op = &ind_test_sops; + sb->s_blocksize = IND_TEST_BLK_SIZE; + sb->s_blocksize_bits = IND_TEST_BLK_BITS; + sb->s_magic = EXT4_SUPER_MAGIC; + sb->s_maxbytes = MAX_LFS_FILESIZE; + INIT_LIST_HEAD(&sb->s_inodes); +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; +#endif + + strscpy(sb->s_id, "ext4_indirect_kunit", sizeof(sb->s_id)); + inode_init_once(&ctx->bd_inode); + ctx->bd_inode.i_sb = sb; + ctx->bd_inode.i_blkbits = IND_TEST_BLK_BITS; + ctx->bd_inode.i_mapping = &ctx->bd_inode.i_data; + ctx->bd_inode.i_data.host = &ctx->bd_inode; + ctx->bdev_disk.part0 = &ctx->bdev; + ctx->bdev_disk.queue = &ctx->bdev_queue; + ctx->bdev.bd_disk = &ctx->bdev_disk; + ctx->bdev.bd_queue = &ctx->bdev_queue; + ctx->bdev.bd_mapping = &ctx->bd_inode.i_data; + bdev_clear_flag(&ctx->bdev, BD_READ_ONLY); + sb->s_bdev = &ctx->bdev; + + sbi->s_sb = sb; + sbi->s_blockgroup_lock = &ctx->bgl; + bgl_lock_init(&ctx->bgl); + spin_lock_init(&sbi->s_error_lock); + spin_lock_init(&sbi->s_md_lock); + spin_lock_init(&sbi->s_bdev_wb_lock); + spin_lock_init(&sbi->s_es_lock); + INIT_LIST_HEAD(&sbi->s_es_list); + mutex_init(&sbi->s_fc_lock); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_STAGING]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_STAGING]); + ratelimit_state_init(&sbi->s_err_ratelimit_state, 5 * HZ, 10); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, 5 * HZ, 10); + ratelimit_state_init(&sbi->s_msg_ratelimit_state, 5 * HZ, 10); + + ret = percpu_init_rwsem(&sbi->s_writepages_rwsem); + KUNIT_ASSERT_EQ(test, ret, 0); + ctx->rwsem_inited = true; + + ret = percpu_counter_init(&sbi->s_freeclusters_counter, 4096, + GFP_KERNEL); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = percpu_counter_init(&sbi->s_dirtyclusters_counter, 0, GFP_KERNEL); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = percpu_counter_init(&sbi->s_freeinodes_counter, 200, GFP_KERNEL); + KUNIT_ASSERT_EQ(test, ret, 0); + + ret = ext4_es_register_shrinker(sbi); + KUNIT_ASSERT_EQ(test, ret, 0); + ctx->es_shrinker_inited = true; + + sbi->s_addr_per_block_bits = ilog2(EXT4_ADDR_PER_BLOCK(sb)); + sbi->s_blocks_per_group = IND_TEST_BLOCKS_PER_GRP; + sbi->s_clusters_per_group = IND_TEST_BLOCKS_PER_GRP; + sbi->s_cluster_ratio = 1; + sbi->s_cluster_bits = 0; + sbi->s_groups_count = IND_TEST_NGROUPS; + sbi->s_inodes_per_group = IND_TEST_INODES_PER_GRP; + sbi->s_inode_size = IND_TEST_INODE_SIZE; + sbi->s_inodes_per_block = IND_TEST_BLK_SIZE / IND_TEST_INODE_SIZE; + sbi->s_first_ino = 11; + sbi->s_mount_state = EXT4_VALID_FS; + sbi->s_bitmap_maxbytes = ext4_max_bitmap_size_test(IND_TEST_BLK_BITS, + 1); + set_opt(sb, ERRORS_CONT); + + sbh = ind_get_or_create_bh(ctx, IND_TEST_FIRST_DATA_BLK); + KUNIT_ASSERT_NOT_NULL(test, sbh); + clear_buffer_mapped(sbh); + brelse(sbh); + sbi->s_sbh = sbh; + ctx->es = (struct ext4_super_block *)sbh->b_data; + sbi->s_es = ctx->es; + + ctx->es->s_magic = cpu_to_le16(EXT4_SUPER_MAGIC); + ctx->es->s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + ctx->es->s_first_data_block = cpu_to_le32(IND_TEST_FIRST_DATA_BLK); + ctx->es->s_blocks_per_group = cpu_to_le32(IND_TEST_BLOCKS_PER_GRP); + ctx->es->s_clusters_per_group = cpu_to_le32(IND_TEST_BLOCKS_PER_GRP); + ctx->es->s_inodes_per_group = cpu_to_le32(IND_TEST_INODES_PER_GRP); + ctx->es->s_inodes_count = cpu_to_le32(IND_TEST_NGROUPS * + IND_TEST_INODES_PER_GRP); + ctx->es->s_inode_size = cpu_to_le16(IND_TEST_INODE_SIZE); + ctx->es->s_checksum_type = EXT4_CRC32C_CHKSUM; + generate_random_uuid(ctx->es->s_uuid); + ext4_blocks_count_set(ctx->es, IND_TEST_TOTAL_BLKS); + ext4_set_feature_64bit(sb); + ext4_set_feature_metadata_csum(sb); + sbi->s_csum_seed = ext4_chksum(~0, ctx->es->s_uuid, + sizeof(ctx->es->s_uuid)); + ext4_superblock_csum_set(sb); + + root_inode = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, root_inode); + root_inode->i_ino = EXT4_ROOT_INO; + root_inode->i_mode = S_IFDIR | 0755; + root_inode->i_blkbits = IND_TEST_BLK_BITS; + root_inode->i_flags |= S_NOQUOTA; + root_inode->i_op = &simple_dir_inode_operations; + set_nlink(root_inode, 2); + sb->s_root = d_make_root(root_inode); + KUNIT_ASSERT_NOT_NULL(test, sb->s_root); + sb->s_flags |= SB_ACTIVE; + + active_ind_test = test; + kunit_activate_static_stub(test, ext4_sb_getblk, ind_sb_getblk_stub); + kunit_activate_static_stub(test, ext4_sb_bread_nofail, + ind_sb_bread_nofail_stub); + kunit_activate_static_stub(test, ext4_read_bh, ind_read_bh_stub); + kunit_activate_static_stub(test, __ext4_handle_dirty_metadata, + ind_handle_dirty_metadata_stub); + kunit_activate_static_stub(test, __ext4_mark_inode_dirty, + ind_mark_inode_dirty_stub); + kunit_activate_static_stub(test, ext4_mb_new_blocks, + ind_mb_new_blocks_stub); + kunit_activate_static_stub(test, ext4_free_blocks, + ind_free_blocks_stub); + + return 0; +} + +/* + * Test 1: ext4_block_to_path() across direct, single-, double-, and + * triple-indirect boundaries plus out-of-range block rejection, and + * ext4_ind_trans_blocks() credit estimation. + */ +static void test_block_to_path_and_trans_blocks(struct kunit *test) +{ + struct inode *inode = ind_make_test_inode(test, 12); + ext4_lblk_t offsets[4]; + int boundary = -1; + + /* Direct: block 0 and block 11 (boundary = 0) */ + KUNIT_EXPECT_EQ(test, + ext4_block_to_path_test(inode, 0, offsets, &boundary), + 1); + KUNIT_EXPECT_EQ(test, offsets[0], 0U); + KUNIT_EXPECT_EQ(test, boundary, 11); + + KUNIT_EXPECT_EQ(test, + ext4_block_to_path_test(inode, 11, offsets, &boundary), + 1); + KUNIT_EXPECT_EQ(test, offsets[0], 11U); + KUNIT_EXPECT_EQ(test, boundary, 0); + + /* Single-indirect: first (12) and last (267) */ + KUNIT_EXPECT_EQ(test, + ext4_block_to_path_test(inode, IND_TEST_IND_BASE, + offsets, &boundary), 2); + KUNIT_EXPECT_EQ(test, offsets[0], (ext4_lblk_t)EXT4_IND_BLOCK); + KUNIT_EXPECT_EQ(test, offsets[1], 0U); + KUNIT_EXPECT_EQ(test, boundary, 255); + + KUNIT_EXPECT_EQ(test, + ext4_block_to_path_test(inode, IND_TEST_DIND_BASE - 1, + offsets, &boundary), 2); + KUNIT_EXPECT_EQ(test, offsets[0], (ext4_lblk_t)EXT4_IND_BLOCK); + KUNIT_EXPECT_EQ(test, offsets[1], 255U); + KUNIT_EXPECT_EQ(test, boundary, 0); + + /* Double-indirect: first (268), end of first IND (523), last (65803) */ + KUNIT_EXPECT_EQ(test, + ext4_block_to_path_test(inode, IND_TEST_DIND_BASE, + offsets, &boundary), 3); + KUNIT_EXPECT_EQ(test, offsets[0], (ext4_lblk_t)EXT4_DIND_BLOCK); + KUNIT_EXPECT_EQ(test, offsets[1], 0U); + KUNIT_EXPECT_EQ(test, offsets[2], 0U); + KUNIT_EXPECT_EQ(test, boundary, 255); + + KUNIT_EXPECT_EQ(test, + ext4_block_to_path_test(inode, IND_TEST_DIND_BASE + 255, + offsets, &boundary), 3); + KUNIT_EXPECT_EQ(test, offsets[1], 0U); + KUNIT_EXPECT_EQ(test, offsets[2], 255U); + KUNIT_EXPECT_EQ(test, boundary, 0); + + KUNIT_EXPECT_EQ(test, + ext4_block_to_path_test(inode, IND_TEST_TIND_BASE - 1, + offsets, &boundary), 3); + KUNIT_EXPECT_EQ(test, offsets[0], (ext4_lblk_t)EXT4_DIND_BLOCK); + KUNIT_EXPECT_EQ(test, offsets[1], 255U); + KUNIT_EXPECT_EQ(test, offsets[2], 255U); + KUNIT_EXPECT_EQ(test, boundary, 0); + + /* Triple-indirect: first (65804) and last (16843019) */ + KUNIT_EXPECT_EQ(test, + ext4_block_to_path_test(inode, IND_TEST_TIND_BASE, + offsets, &boundary), 4); + KUNIT_EXPECT_EQ(test, offsets[0], (ext4_lblk_t)EXT4_TIND_BLOCK); + KUNIT_EXPECT_EQ(test, offsets[1], 0U); + KUNIT_EXPECT_EQ(test, offsets[2], 0U); + KUNIT_EXPECT_EQ(test, offsets[3], 0U); + KUNIT_EXPECT_EQ(test, boundary, 255); + + KUNIT_EXPECT_EQ(test, + ext4_block_to_path_test(inode, IND_TEST_MAX_LBLK - 1, + offsets, NULL), 4); + KUNIT_EXPECT_EQ(test, offsets[0], (ext4_lblk_t)EXT4_TIND_BLOCK); + KUNIT_EXPECT_EQ(test, offsets[1], 255U); + KUNIT_EXPECT_EQ(test, offsets[2], 255U); + KUNIT_EXPECT_EQ(test, offsets[3], 255U); + + /* Out-of-range block returns 0 */ + KUNIT_EXPECT_EQ(test, + ext4_block_to_path_test(inode, IND_TEST_MAX_LBLK, + offsets, NULL), 0); + + /* ext4_ind_trans_blocks(): DIV_ROUND_UP(nrblocks, 256) + 4 */ + KUNIT_EXPECT_EQ(test, ext4_ind_trans_blocks(inode, 1), 5); + KUNIT_EXPECT_EQ(test, ext4_ind_trans_blocks(inode, 256), 5); + KUNIT_EXPECT_EQ(test, ext4_ind_trans_blocks(inode, 257), 6); + KUNIT_EXPECT_EQ(test, ext4_ind_trans_blocks(inode, 512), 6); + + iput(inode); +} + +/* + * Test 2: ext4_ind_map_blocks() read-only lookup for contiguous mapped runs, + * EXT4_MAP_BOUNDARY detection, and multi-level unallocated hole span sizing. + */ +static void test_ind_map_blocks_lookup_mapped_and_holes(struct kunit *test) +{ + struct inode *inode = ind_make_test_inode(test, 13); + struct ext4_map_blocks map; + unsigned int i; + int ret; + + /* Map direct [0..3] -> [100..103], hole at [4], [5..11] -> [205..211] */ + for (i = 0; i < 4; i++) + EXT4_I(inode)->i_data[i] = cpu_to_le32(100 + i); + for (i = 5; i < EXT4_NDIR_BLOCKS; i++) + EXT4_I(inode)->i_data[i] = cpu_to_le32(200 + i); + + /* Contiguous direct run [0..3] stops at hole [4], not at boundary */ + memset(&map, 0, sizeof(map)); + map.m_lblk = 0; + map.m_len = 10; + down_read(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(NULL, inode, &map, 0); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 4); + KUNIT_EXPECT_EQ(test, map.m_pblk, 100ULL); + KUNIT_EXPECT_EQ(test, map.m_len, 4U); + KUNIT_EXPECT_TRUE(test, map.m_flags & EXT4_MAP_MAPPED); + KUNIT_EXPECT_FALSE(test, map.m_flags & EXT4_MAP_BOUNDARY); + + /* Contiguous direct run [5..11] hits end of direct array -> BOUNDARY */ + memset(&map, 0, sizeof(map)); + map.m_lblk = 5; + map.m_len = 10; + down_read(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(NULL, inode, &map, 0); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 7); + KUNIT_EXPECT_EQ(test, map.m_pblk, 205ULL); + KUNIT_EXPECT_EQ(test, map.m_len, 7U); + KUNIT_EXPECT_EQ(test, map.m_flags & (EXT4_MAP_MAPPED | EXT4_MAP_BOUNDARY), + (unsigned int)(EXT4_MAP_MAPPED | EXT4_MAP_BOUNDARY)); + + /* Direct hole at [4]: hole length is 1 */ + memset(&map, 0, sizeof(map)); + map.m_lblk = 4; + map.m_len = 5; + down_read(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(NULL, inode, &map, 0); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, map.m_pblk, 0ULL); + KUNIT_EXPECT_EQ(test, map.m_len, 1U); + + /* Absent IND subtree at lblk = 20 (offsets = [12, 8]) -> 256 - 8 = 248 */ + memset(&map, 0, sizeof(map)); + map.m_lblk = IND_TEST_IND_BASE + 8; + map.m_len = 500; + down_read(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(NULL, inode, &map, 0); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, map.m_len, 248U); + + /* + * Absent DIND subtree at offsets = [13, 2, 10]: + * remaining blocks in DIND = (255 - 2) * 256 + (256 - 10) = 65014. + */ + memset(&map, 0, sizeof(map)); + map.m_lblk = IND_TEST_DIND_BASE + 2 * IND_TEST_PTRS_PER_BLK + 10; + map.m_len = 100000; + down_read(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(NULL, inode, &map, 0); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, map.m_len, 65014U); + + iput(inode); +} + +/* + * Test 3: ext4_ind_map_blocks() block allocation and branch splicing across + * direct, single-indirect, double-indirect, and triple-indirect levels. + */ +static void test_ind_map_blocks_alloc_direct_ind_dind_tind(struct kunit *test) +{ + struct inode *inode = ind_make_test_inode(test, 14); + struct ext4_map_blocks map, check; + handle_t *handle; + int ret; + + handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, 8); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + + /* 1. Multi-block direct allocation at [2..5] */ + memset(&map, 0, sizeof(map)); + map.m_lblk = 2; + map.m_len = 4; + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(handle, inode, &map, EXT4_GET_BLOCKS_CREATE); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 4); + KUNIT_EXPECT_EQ(test, map.m_flags & (EXT4_MAP_NEW | EXT4_MAP_MAPPED), + (unsigned int)(EXT4_MAP_NEW | EXT4_MAP_MAPPED)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[1]), 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[2]), + (u32)map.m_pblk); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[5]), + (u32)(map.m_pblk + 3)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[6]), 0U); + + /* 2. Direct allocation clamped at direct boundary [9..11] */ + memset(&map, 0, sizeof(map)); + map.m_lblk = 9; + map.m_len = 6; + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(handle, inode, &map, EXT4_GET_BLOCKS_CREATE); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 3); + KUNIT_EXPECT_TRUE(test, map.m_flags & EXT4_MAP_BOUNDARY); + + /* 3. Single-indirect allocation at [15..19] */ + memset(&map, 0, sizeof(map)); + map.m_lblk = IND_TEST_IND_BASE + 3; + map.m_len = 5; + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(handle, inode, &map, EXT4_GET_BLOCKS_CREATE); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 5); + KUNIT_EXPECT_NE(test, le32_to_cpu(EXT4_I(inode)->i_data[EXT4_IND_BLOCK]), + 0U); + + memset(&check, 0, sizeof(check)); + check.m_lblk = IND_TEST_IND_BASE + 3; + check.m_len = 10; + down_read(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(NULL, inode, &check, 0); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 5); + KUNIT_EXPECT_EQ(test, check.m_pblk, map.m_pblk); + + /* 4. Double-indirect allocation at DIND_BASE + 300 (len = 3) */ + memset(&map, 0, sizeof(map)); + map.m_lblk = IND_TEST_DIND_BASE + 300; + map.m_len = 3; + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(handle, inode, &map, EXT4_GET_BLOCKS_CREATE); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 3); + KUNIT_EXPECT_NE(test, + le32_to_cpu(EXT4_I(inode)->i_data[EXT4_DIND_BLOCK]), + 0U); + + memset(&check, 0, sizeof(check)); + check.m_lblk = IND_TEST_DIND_BASE + 300; + check.m_len = 5; + down_read(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(NULL, inode, &check, 0); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 3); + KUNIT_EXPECT_EQ(test, check.m_pblk, map.m_pblk); + + /* 5. Triple-indirect allocation at TIND_BASE + 5 (len = 2) */ + memset(&map, 0, sizeof(map)); + map.m_lblk = IND_TEST_TIND_BASE + 5; + map.m_len = 2; + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(handle, inode, &map, EXT4_GET_BLOCKS_CREATE); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 2); + KUNIT_EXPECT_NE(test, + le32_to_cpu(EXT4_I(inode)->i_data[EXT4_TIND_BLOCK]), + 0U); + + memset(&check, 0, sizeof(check)); + check.m_lblk = IND_TEST_TIND_BASE + 5; + check.m_len = 4; + down_read(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(NULL, inode, &check, 0); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 2); + KUNIT_EXPECT_EQ(test, check.m_pblk, map.m_pblk); + + ext4_journal_stop(handle); + iput(inode); +} + +/* + * Test 4: ext4_ind_map_blocks() error paths and partial branch unwind in + * ext4_alloc_branch() when an intermediate indirect or leaf allocation fails. + */ +static void test_ind_map_blocks_errors_and_alloc_branch_unwind(struct kunit *test) +{ + struct ind_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct inode *inode = ind_make_test_inode(test, 15); + struct ext4_map_blocks map; + struct buffer_head *ind_bh; + ext4_fsblk_t alloc_base; + handle_t *handle; + int ret; + + handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, 8); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + + /* 1. Out-of-range m_lblk -> -EIO */ + memset(&map, 0, sizeof(map)); + map.m_lblk = IND_TEST_MAX_LBLK; + map.m_len = 1; + down_read(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(NULL, inode, &map, 0); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, -EIO); + + /* 2. Allocating on an indirect inode with bigalloc -> -EFSCORRUPTED */ + ext4_set_feature_bigalloc(sb); + memset(&map, 0, sizeof(map)); + map.m_lblk = 0; + map.m_len = 1; + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(handle, inode, &map, EXT4_GET_BLOCKS_CREATE); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, -EFSCORRUPTED); + ext4_clear_feature_bigalloc(sb); + + /* 3. Out-of-range indirect block pointer on lookup -> -EFSCORRUPTED */ + EXT4_I(inode)->i_data[EXT4_IND_BLOCK] = + cpu_to_le32(IND_TEST_TOTAL_BLKS + 10); + memset(&map, 0, sizeof(map)); + map.m_lblk = IND_TEST_IND_BASE; + map.m_len = 1; + down_read(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(NULL, inode, &map, 0); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, -EFSCORRUPTED); + + /* 4. Non-uptodate IND block read I/O failure -> -EIO */ + EXT4_I(inode)->i_data[EXT4_IND_BLOCK] = cpu_to_le32(300); + ind_bh = ind_get_or_create_bh(ctx, 300); + KUNIT_ASSERT_NOT_NULL(test, ind_bh); + clear_buffer_uptodate(ind_bh); + ctx->read_bh_err = -EIO; + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(handle, inode, &map, EXT4_GET_BLOCKS_CREATE); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, -EIO); + ctx->read_bh_err = 0; + + /* + * 5. Non-uptodate IND block containing invalid blockref (block 1 == + * s_first_data_block) fails ext4_check_indirect_blockref() -> -EIO. + */ + ((__le32 *)ind_bh->b_data)[0] = cpu_to_le32(IND_TEST_FIRST_DATA_BLK); + clear_buffer_uptodate(ind_bh); + down_read(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(NULL, inode, &map, 0); + up_read(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, -EIO); + brelse(ind_bh); + EXT4_I(inode)->i_data[EXT4_IND_BLOCK] = 0; + + /* + * 6. Partial TIND branch unwind: TIND (call 1), DIND (call 2), and + * IND (call 3) metadata blocks succeed; leaf data allocation (call 4) + * fails with -ENOSPC. All 3 metadata blocks must be freed and + * i_data[EXT4_TIND_BLOCK] must remain 0. + */ + ctx->freed_cnt = 0; + ctx->alloc_calls = 0; + ctx->fail_alloc_on_call = 4; + ctx->fail_alloc_err = -ENOSPC; + alloc_base = ctx->next_alloc_pblk; + + memset(&map, 0, sizeof(map)); + map.m_lblk = IND_TEST_TIND_BASE + 9; + map.m_len = 2; + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_map_blocks(handle, inode, &map, EXT4_GET_BLOCKS_CREATE); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, -ENOSPC); + KUNIT_EXPECT_EQ(test, + le32_to_cpu(EXT4_I(inode)->i_data[EXT4_TIND_BLOCK]), + 0U); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, alloc_base)); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, alloc_base + 1)); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, alloc_base + 2)); + KUNIT_EXPECT_EQ(test, inode->i_blocks, 0ULL); + + ctx->fail_alloc_on_call = 0; + ctx->fail_alloc_err = 0; + ext4_journal_stop(handle); + iput(inode); +} + +/* + * Test 5: ext4_ind_truncate() partial shared-branch truncation inside DIND, + * boundary truncation detaching IND, and full truncation to i_size = 0. + */ +static void test_ind_truncate_partial_and_full(struct kunit *test) +{ + struct ind_test_ctx *ctx = test->priv; + struct inode *inode = ind_make_test_inode(test, 16); + __le32 *ind, *dind, *dind_c0, *dind_c1, *tind, *tind_d0, *tind_i0; + handle_t *handle; + unsigned int i; + + /* Direct [0..11] -> [100..111] */ + for (i = 0; i < EXT4_NDIR_BLOCKS; i++) + EXT4_I(inode)->i_data[i] = cpu_to_le32(100 + i); + + /* IND (500): [0..5] -> [600..605] */ + EXT4_I(inode)->i_data[EXT4_IND_BLOCK] = cpu_to_le32(500); + ind = ind_blk_ptrs(test, 500); + for (i = 0; i < 6; i++) + ind[i] = cpu_to_le32(600 + i); + + /* DIND (501): child0 (502) -> [700..705], child1 (503) -> [710..713] */ + EXT4_I(inode)->i_data[EXT4_DIND_BLOCK] = cpu_to_le32(501); + dind = ind_blk_ptrs(test, 501); + dind[0] = cpu_to_le32(502); + dind[1] = cpu_to_le32(503); + dind_c0 = ind_blk_ptrs(test, 502); + for (i = 0; i < 6; i++) + dind_c0[i] = cpu_to_le32(700 + i); + dind_c1 = ind_blk_ptrs(test, 503); + for (i = 0; i < 4; i++) + dind_c1[i] = cpu_to_le32(710 + i); + + /* TIND (504) -> DIND (505) -> IND (506) -> data (800) */ + EXT4_I(inode)->i_data[EXT4_TIND_BLOCK] = cpu_to_le32(504); + tind = ind_blk_ptrs(test, 504); + tind[0] = cpu_to_le32(505); + tind_d0 = ind_blk_ptrs(test, 505); + tind_d0[0] = cpu_to_le32(506); + tind_i0 = ind_blk_ptrs(test, 506); + tind_i0[0] = cpu_to_le32(800); + + ext4_es_insert_extent(inode, 0, 100000, 100, EXTENT_STATUS_WRITTEN, 0); + + handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, 8); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + + /* + * Step A: Truncate to last_block = DIND_BASE + 3. + * DIND[0][0..2] (700..702) survive; DIND[0][3..5] (703..705), + * DIND[1] (503, 710..713), and TIND (504, 505, 506, 800) are freed. + */ + i_size_write(inode, (loff_t)(IND_TEST_DIND_BASE + 3) * + IND_TEST_BLK_SIZE); + down_write(&EXT4_I(inode)->i_data_sem); + ext4_ind_truncate(handle, inode); + up_write(&EXT4_I(inode)->i_data_sem); + + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_disksize, i_size_read(inode)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[EXT4_DIND_BLOCK]), + 501U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(dind[0]), 502U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(dind[1]), 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(dind_c0[2]), 702U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(dind_c0[3]), 0U); + KUNIT_EXPECT_FALSE(test, ind_was_freed(ctx, 702)); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 703)); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 705)); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 503)); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 710)); + KUNIT_EXPECT_EQ(test, + le32_to_cpu(EXT4_I(inode)->i_data[EXT4_TIND_BLOCK]), + 0U); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 504)); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 506)); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 800)); + + /* + * Step B: Truncate to last_block = IND_BASE (12). + * Direct [0..11] survive; IND (500) and remaining DIND (501, 502) + * are detached and freed. + */ + ctx->freed_cnt = 0; + i_size_write(inode, (loff_t)IND_TEST_IND_BASE * IND_TEST_BLK_SIZE); + down_write(&EXT4_I(inode)->i_data_sem); + ext4_ind_truncate(handle, inode); + up_write(&EXT4_I(inode)->i_data_sem); + + KUNIT_EXPECT_EQ(test, + le32_to_cpu(EXT4_I(inode)->i_data[EXT4_IND_BLOCK]), 0U); + KUNIT_EXPECT_EQ(test, + le32_to_cpu(EXT4_I(inode)->i_data[EXT4_DIND_BLOCK]), + 0U); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 500)); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 600)); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 501)); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 502)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[11]), 111U); + + /* Step C: Truncate to 0 frees all remaining direct blocks */ + ctx->freed_cnt = 0; + i_size_write(inode, 0); + down_write(&EXT4_I(inode)->i_data_sem); + ext4_ind_truncate(handle, inode); + up_write(&EXT4_I(inode)->i_data_sem); + + for (i = 0; i < EXT4_NDIR_BLOCKS; i++) + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[i]), + 0U); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 100)); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 111)); + + ext4_journal_stop(handle); + iput(inode); +} + +/* + * Test 6: ext4_ind_remove_space() hole punching within direct blocks, across + * different tree levels (n < n2), and within the same indirect level (n == n2) + * converging on a shared IND or DIND block. + */ +static void test_ind_remove_space_levels_and_convergence(struct kunit *test) +{ + struct ind_test_ctx *ctx = test->priv; + struct inode *inode = ind_make_test_inode(test, 17); + __le32 *ind, *dind, *c0, *c1, *c2; + handle_t *handle; + unsigned int i; + int ret; + + handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, 8); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + + /* Empty/out-of-range ranges are no-ops */ + down_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ext4_ind_remove_space(handle, inode, 5, 5), 0); + KUNIT_EXPECT_EQ(test, + ext4_ind_remove_space(handle, inode, + IND_TEST_MAX_LBLK + 10, + IND_TEST_MAX_LBLK + 20), 0); + up_write(&EXT4_I(inode)->i_data_sem); + + /* Populate direct [0..11], IND (510), and DIND (511 -> 512, 513, 514) */ + for (i = 0; i < EXT4_NDIR_BLOCKS; i++) + EXT4_I(inode)->i_data[i] = cpu_to_le32(120 + i); + + EXT4_I(inode)->i_data[EXT4_IND_BLOCK] = cpu_to_le32(510); + ind = ind_blk_ptrs(test, 510); + for (i = 0; i < 12; i++) + ind[i] = cpu_to_le32(620 + i); + + EXT4_I(inode)->i_data[EXT4_DIND_BLOCK] = cpu_to_le32(511); + dind = ind_blk_ptrs(test, 511); + dind[0] = cpu_to_le32(512); + dind[1] = cpu_to_le32(513); + dind[2] = cpu_to_le32(514); + c0 = ind_blk_ptrs(test, 512); + c1 = ind_blk_ptrs(test, 513); + c2 = ind_blk_ptrs(test, 514); + for (i = 0; i < 8; i++) { + c0[i] = cpu_to_le32(720 + i); + c1[i] = cpu_to_le32(740 + i); + c2[i] = cpu_to_le32(760 + i); + } + + /* 1. Direct-only hole punch [3, 8) */ + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_remove_space(handle, inode, 3, 8); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[2]), 122U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[3]), 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[7]), 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[8]), 128U); + + /* 2. Same-level IND convergence [IND_BASE + 3, IND_BASE + 8) */ + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_remove_space(handle, inode, IND_TEST_IND_BASE + 3, + IND_TEST_IND_BASE + 8); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ind[2]), 622U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ind[3]), 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ind[7]), 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ind[8]), 628U); + + /* + * 3. Same-level DIND convergence across 3 IND children: + * [DIND_BASE + 4, DIND_BASE + 2 * 256 + 3) frees c0[4..7], the entire + * middle c1 (513 + 740..747), and c2[0..2], preserving c0[0..3] and + * c2[3..7]. + */ + ctx->freed_cnt = 0; + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_remove_space(handle, inode, IND_TEST_DIND_BASE + 4, + IND_TEST_DIND_BASE + + 2 * IND_TEST_PTRS_PER_BLK + 3); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(c0[3]), 723U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(c0[4]), 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(dind[1]), 0U); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 513)); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 740)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(c2[2]), 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(c2[3]), 763U); + + /* + * 4. Cross-level punch (n = 1 < n2 = 3): [10, DIND_BASE + 2) frees + * direct [10..11], entire IND (510), and c0[0..1], preserving c0[2..3]. + */ + ctx->freed_cnt = 0; + down_write(&EXT4_I(inode)->i_data_sem); + ret = ext4_ind_remove_space(handle, inode, 10, IND_TEST_DIND_BASE + 2); + up_write(&EXT4_I(inode)->i_data_sem); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[9]), 129U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[10]), 0U); + KUNIT_EXPECT_EQ(test, + le32_to_cpu(EXT4_I(inode)->i_data[EXT4_IND_BLOCK]), 0U); + KUNIT_EXPECT_TRUE(test, ind_was_freed(ctx, 510)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(c0[1]), 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(c0[2]), 722U); + + ext4_journal_stop(handle); + iput(inode); +} + +/* + * Test 7: Corrupt out-of-range block pointers in ext4_clear_blocks() and + * ext4_free_branches() record filesystem errors without freeing invalid blocks. + */ +static void test_ind_free_corrupt_block_numbers(struct kunit *test) +{ + struct ind_test_ctx *ctx = test->priv; + struct inode *inode = ind_make_test_inode(test, 18); + ext4_fsblk_t bad_blk = IND_TEST_TOTAL_BLKS + 77; + handle_t *handle; + + handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, 4); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + + EXT4_I(inode)->i_data[0] = cpu_to_le32(bad_blk); + EXT4_I(inode)->i_data[EXT4_IND_BLOCK] = cpu_to_le32(bad_blk + 1); + i_size_write(inode, 0); + + down_write(&EXT4_I(inode)->i_data_sem); + ext4_ind_truncate(handle, inode); + up_write(&EXT4_I(inode)->i_data_sem); + + KUNIT_EXPECT_TRUE(test, ctx->sbi.s_mount_state & EXT4_ERROR_FS); + KUNIT_EXPECT_FALSE(test, ind_was_freed(ctx, bad_blk)); + KUNIT_EXPECT_FALSE(test, ind_was_freed(ctx, bad_blk + 1)); + + ext4_journal_stop(handle); + iput(inode); +} + +static struct kunit_case ext4_indirect_test_cases[] = { + KUNIT_CASE(test_block_to_path_and_trans_blocks), + KUNIT_CASE(test_ind_map_blocks_lookup_mapped_and_holes), + KUNIT_CASE(test_ind_map_blocks_alloc_direct_ind_dind_tind), + KUNIT_CASE(test_ind_map_blocks_errors_and_alloc_branch_unwind), + KUNIT_CASE(test_ind_truncate_partial_and_full), + KUNIT_CASE(test_ind_remove_space_levels_and_convergence), + KUNIT_CASE(test_ind_free_corrupt_block_numbers), + {} +}; + +static struct kunit_suite ext4_indirect_test_suite = { + .name = "ext4_indirect_test", + .init = ind_test_init, + .test_cases = ext4_indirect_test_cases, +}; + +kunit_test_suites(&ext4_indirect_test_suite); + +MODULE_DESCRIPTION("KUnit tests for ext4 indirect block mapping and truncation"); +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/indirect.c b/fs/ext4/indirect.c index a495080df71092..fd6d60f0323da9 100644 --- a/fs/ext4/indirect.c +++ b/fs/ext4/indirect.c @@ -163,7 +163,7 @@ static Indirect *ext4_get_branch(struct inode *inode, int depth, ret = -EFSCORRUPTED; goto failure; } - bh = sb_getblk(sb, key); + bh = ext4_sb_getblk(sb, key); if (unlikely(!bh)) { ret = -ENOMEM; goto failure; @@ -354,7 +354,8 @@ static int ext4_alloc_branch(handle_t *handle, if (i == 0) continue; - bh = branch[i].bh = sb_getblk(ar->inode->i_sb, new_blocks[i-1]); + bh = branch[i].bh = ext4_sb_getblk(ar->inode->i_sb, + new_blocks[i - 1]); if (unlikely(!bh)) { err = -ENOMEM; goto failed; @@ -620,7 +621,7 @@ int ext4_ind_map_blocks(handle_t *handle, struct inode *inode, EXT4_ERROR_INODE(inode, "Can't allocate blocks for " "non-extent mapped inodes with bigalloc"); err = -EFSCORRUPTED; - goto out; + goto cleanup; } /* Set up for the direct block allocation */ @@ -688,6 +689,7 @@ int ext4_ind_map_blocks(handle_t *handle, struct inode *inode, trace_ext4_ind_map_blocks_exit(inode, flags, map, err); return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ind_map_blocks); /* * Calculate number of indirect blocks touched by mapping @nrblocks logically @@ -702,6 +704,7 @@ int ext4_ind_trans_blocks(struct inode *inode, int nrblocks) */ return DIV_ROUND_UP(nrblocks, EXT4_ADDR_PER_BLOCK(inode->i_sb)) + 4; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ind_trans_blocks); static int ext4_ind_trunc_restart_fn(handle_t *handle, struct inode *inode, struct buffer_head *bh, int *dropped) @@ -1230,6 +1233,7 @@ void ext4_ind_truncate(handle_t *handle, struct inode *inode) ; } } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ind_truncate); /** * ext4_ind_remove_space - remove space from the range @@ -1489,3 +1493,13 @@ int ext4_ind_remove_space(handle_t *handle, struct inode *inode, } goto cleanup; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ind_remove_space); + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +int ext4_block_to_path_test(struct inode *inode, ext4_lblk_t i_block, + ext4_lblk_t offsets[4], int *boundary) +{ + return ext4_block_to_path(inode, i_block, offsets, boundary); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_block_to_path_test); +#endif diff --git a/fs/ext4/inline-test.c b/fs/ext4/inline-test.c new file mode 100644 index 00000000000000..b3d7c51ad216be --- /dev/null +++ b/fs/ext4/inline-test.c @@ -0,0 +1,1868 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for ext4 inline data operations (fs/ext4/inline.c) + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_jbd2.h" +#include "xattr.h" +#include "truncate.h" +#include "namei.h" + +#define TEST_INODE_SIZE 256 +#define TEST_EXTRA_ISIZE 32 +#define TEST_BLOCK_SIZE 1024 +#define TEST_BLOCK_BITS 10 +#define EXT4_MIN_INLINE_DATA_SIZE ((sizeof(__le32) * EXT4_N_BLOCKS)) +#define EXT4_INLINE_DOTDOT_SIZE 4 +/* + * For a 256-byte inode with 32-byte i_extra_isize: + * EXT4_GOOD_OLD_INODE_SIZE (128) + 32 = 160 bytes fixed fields + * Remaining ibody space = 96 bytes + * 4-byte xattr magic + 20-byte system.data entry + 4-byte gap = 28 bytes + * Available xattr value space = 68 bytes + * Plus 60 bytes in i_block (EXT4_MIN_INLINE_DATA_SIZE) = 128 bytes max inline size. + */ +#define TEST_MAX_INLINE_SIZE 128 + +#define TEST_INO 12 +#define TEST_PARENT_INO 2 +#define TEST_PBLK 100 + +struct inline_test_ctx { + struct super_block sb; + struct ext4_sb_info sbi; + struct ext4_super_block es; + struct block_device bdev; + struct address_space bd_mapping; + struct buffer_head sb_bh; + struct ext4_inode_info ei; + struct buffer_head iloc_bh; + u8 raw_inode_buf[TEST_BLOCK_SIZE]; + struct buffer_head data_bh; + u8 data_block_buf[PAGE_SIZE]; + int get_inode_loc_err; + int map_blocks_ret; + ext4_fsblk_t map_pblk; + unsigned int map_flags; + bool getblk_fail; + int dirty_metadata_err; + int dirty_metadata_fail_on_call; + int dirty_metadata_calls; + int da_get_block_prep_err; + int journal_mode; +}; + +static struct inline_test_ctx *t_ctx; + +#ifdef CONFIG_QUOTA +static struct dquot __rcu **inline_test_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} +#endif + +static const struct super_operations inline_test_sops = { +#ifdef CONFIG_QUOTA + .get_dquots = inline_test_get_dquots, +#endif +}; + +static bool test_release_folio(struct folio *folio, gfp_t wait) +{ + return try_to_free_buffers(folio); +} + +static const struct address_space_operations test_inline_aops = { + .dirty_folio = noop_dirty_folio, + .invalidate_folio = block_invalidate_folio, + .release_folio = test_release_folio, +}; + +/* --- Static Stubs --- */ + +static int stub_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc) +{ + if (t_ctx->get_inode_loc_err) + return t_ctx->get_inode_loc_err; + + memset(iloc, 0, sizeof(*iloc)); + atomic_inc(&t_ctx->iloc_bh.b_count); + iloc->bh = &t_ctx->iloc_bh; + iloc->offset = 0; + iloc->block_group = 0; + return 0; +} + +static int stub_handle_dirty_metadata(const char *where, unsigned int line, + handle_t *handle, struct inode *inode, + struct buffer_head *bh) +{ + t_ctx->dirty_metadata_calls++; + if (t_ctx->dirty_metadata_fail_on_call > 0 && + t_ctx->dirty_metadata_calls == t_ctx->dirty_metadata_fail_on_call) + return t_ctx->dirty_metadata_err; + if (t_ctx->dirty_metadata_fail_on_call == 0 && + t_ctx->dirty_metadata_err) + return t_ctx->dirty_metadata_err; + set_buffer_dirty(bh); + return 0; +} + +static int stub_mark_iloc_dirty(handle_t *handle, struct inode *inode, + struct ext4_iloc *iloc) +{ + brelse(iloc->bh); + return 0; +} + +static int stub_mark_inode_dirty(handle_t *handle, struct inode *inode, + const char *func, unsigned int line) +{ + return 0; +} + +static int stub_map_blocks(handle_t *handle, struct inode *inode, + struct ext4_map_blocks *map, int flags) +{ + if (t_ctx->map_blocks_ret < 0) + return t_ctx->map_blocks_ret; + + map->m_pblk = t_ctx->map_pblk; + map->m_flags = t_ctx->map_flags; + if (t_ctx->map_blocks_ret > 0) + map->m_len = t_ctx->map_blocks_ret; + return t_ctx->map_blocks_ret; +} + +static struct buffer_head *stub_inline_getblk(struct super_block *sb, + ext4_fsblk_t block) +{ + if (t_ctx->getblk_fail) + return NULL; + + atomic_inc(&t_ctx->data_bh.b_count); + t_ctx->data_bh.b_blocknr = block; + return &t_ctx->data_bh; +} + +static int stub_da_get_block_prep(struct inode *inode, sector_t iblock, + struct buffer_head *bh, int create) +{ + if (t_ctx->da_get_block_prep_err) + return t_ctx->da_get_block_prep_err; + + set_buffer_new(bh); + set_buffer_delay(bh); + bh->b_blocknr = 0; + bh->b_size = inode->i_sb->s_blocksize; + return 0; +} + +static int stub_inode_journal_mode(struct inode *inode) +{ + return t_ctx->journal_mode; +} + +/* --- Helpers --- */ + +static void *raw_inline_i_block(struct inline_test_ctx *ctx) +{ + struct ext4_inode *raw_inode = (struct ext4_inode *)ctx->raw_inode_buf; + + return (void *)raw_inode->i_block; +} + +static void *raw_inline_xattr_pos(struct inline_test_ctx *ctx) +{ + struct inode *inode = &ctx->ei.vfs_inode; + struct ext4_inode *raw_inode = (struct ext4_inode *)ctx->raw_inode_buf; + struct ext4_xattr_ibody_header *header = IHDR(inode, raw_inode); + struct ext4_xattr_entry *entry; + + entry = (struct ext4_xattr_entry *)((void *)raw_inode + + ctx->ei.i_inline_off); + return (void *)IFIRST(header) + le16_to_cpu(entry->e_value_offs); +} + +static void reset_inode_state(struct inline_test_ctx *ctx, umode_t mode) +{ + struct inode *inode = &ctx->ei.vfs_inode; + struct ext4_inode *raw_inode; + + if (!list_empty(&ctx->ei.i_orphan)) + list_del_init(&ctx->ei.i_orphan); + + truncate_inode_pages(&inode->i_data, 0); + + memset(ctx->raw_inode_buf, 0, sizeof(ctx->raw_inode_buf)); + memset(ctx->data_block_buf, 0, sizeof(ctx->data_block_buf)); + memset(ctx->ei.i_data, 0, sizeof(ctx->ei.i_data)); + + raw_inode = (struct ext4_inode *)ctx->raw_inode_buf; + raw_inode->i_extra_isize = cpu_to_le16(TEST_EXTRA_ISIZE); + + ctx->ei.i_extra_isize = TEST_EXTRA_ISIZE; + ctx->ei.i_inline_off = 0; + ctx->ei.i_inline_size = 0; + ctx->ei.i_flags = 0; + ext4_clear_state_flags(&ctx->ei); + ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + ctx->ei.i_disksize = 0; + + inode->i_mode = mode; + inode->i_size = 0; + inode->i_blocks = 0; + inode_set_iversion(inode, 1); + inode_state_set_raw(inode, I_DIRTY); +} + +static int create_inline_file(struct inode *inode, const void *data, size_t len) +{ + struct folio *folio = NULL; + void *kaddr; + int ret; + + inode_lock(inode); + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 0, len, + &folio); + if (ret != 1) { + inode_unlock(inode); + return ret < 0 ? ret : -ENOSPC; + } + + if (data && len) { + kaddr = kmap_local_folio(folio, 0); + memcpy(kaddr, data, len); + kunmap_local(kaddr); + } + + ret = ext4_write_inline_data_end(inode, 0, len, len, folio); + inode_unlock(inode); + if (ret < 0) + return ret; + + i_size_write(inode, len); + EXT4_I(inode)->i_disksize = len; + return 0; +} + +static int inline_test_init(struct kunit *test) +{ + struct inline_test_ctx *ctx; + struct inode *inode; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx); + t_ctx = ctx; + test->priv = ctx; + + /* Superblock and ext4_sb_info setup */ + ctx->sb.s_blocksize = TEST_BLOCK_SIZE; + ctx->sb.s_blocksize_bits = TEST_BLOCK_BITS; + ctx->sb.s_maxbytes = MAX_LFS_FILESIZE; + ctx->sb.s_time_gran = 1; + ctx->sb.s_bdi = &noop_backing_dev_info; + ctx->sb.s_fs_info = &ctx->sbi; + ctx->sb.s_user_ns = &init_user_ns; + ctx->sb.s_op = &inline_test_sops; +#ifdef CONFIG_FS_ENCRYPTION + ctx->sb.s_cop = &ext4_cryptops; +#endif + snprintf(ctx->sb.s_id, sizeof(ctx->sb.s_id), "ext4-inline-test"); + init_rwsem(&ctx->sb.s_umount); + + ctx->bdev.bd_mapping = &ctx->bd_mapping; + bdev_set_flag(&ctx->bdev, BD_READ_ONLY); + ctx->sb.s_bdev = &ctx->bdev; + + ctx->es.s_feature_incompat = + cpu_to_le32(EXT4_FEATURE_INCOMPAT_INLINE_DATA | + EXT4_FEATURE_INCOMPAT_EXTENTS | + EXT4_FEATURE_INCOMPAT_FILETYPE); + ctx->es.s_first_data_block = cpu_to_le32(1); + ctx->es.s_inodes_count = cpu_to_le32(1024); + ctx->es.s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + ctx->es.s_inode_size = cpu_to_le16(TEST_INODE_SIZE); + + ctx->sb_bh.b_data = (char *)&ctx->es; + ctx->sb_bh.b_size = sizeof(ctx->es); + ctx->sb_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->sb_bh.b_count, 1); + set_buffer_uptodate(&ctx->sb_bh); + ctx->sbi.s_sbh = &ctx->sb_bh; + + ctx->sbi.s_sb = &ctx->sb; + ctx->sbi.s_es = &ctx->es; + ctx->sbi.s_inode_size = TEST_INODE_SIZE; + ctx->sbi.s_want_extra_isize = TEST_EXTRA_ISIZE; + ctx->sbi.s_cluster_bits = 0; + ctx->sbi.s_cluster_ratio = 1; + INIT_LIST_HEAD(&ctx->sbi.s_orphan); + mutex_init(&ctx->sbi.s_orphan_lock); + set_opt(&ctx->sb, ERRORS_CONT); + spin_lock_init(&ctx->sbi.s_bdev_wb_lock); + spin_lock_init(&ctx->sbi.s_error_lock); + spin_lock_init(&ctx->sbi.s_md_lock); + ratelimit_state_init(&ctx->sbi.s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&ctx->sbi.s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&ctx->sbi.s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + + /* Mock buffer_head for raw inode (iloc.bh) */ + ctx->iloc_bh.b_data = (char *)ctx->raw_inode_buf; + ctx->iloc_bh.b_size = TEST_BLOCK_SIZE; + ctx->iloc_bh.b_blocknr = 10; + ctx->iloc_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->iloc_bh.b_count, 1); + set_buffer_uptodate(&ctx->iloc_bh); + set_buffer_mapped(&ctx->iloc_bh); + + /* Mock buffer_head for allocated data block (data_bh) */ + ctx->data_bh.b_data = (char *)ctx->data_block_buf; + ctx->data_bh.b_size = TEST_BLOCK_SIZE; + ctx->data_bh.b_blocknr = TEST_PBLK; + ctx->data_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->data_bh.b_count, 1); + set_buffer_uptodate(&ctx->data_bh); + set_buffer_mapped(&ctx->data_bh); + + /* Default stub behavior */ + ctx->map_blocks_ret = 1; + ctx->map_pblk = TEST_PBLK; + ctx->map_flags = EXT4_MAP_MAPPED; + ctx->journal_mode = EXT4_INODE_WRITEBACK_DATA_MODE; + + /* Initialize mock ext4_inode_info and embedded vfs_inode */ + inode = &ctx->ei.vfs_inode; + inode->i_sb = &ctx->sb; + inode->i_ino = TEST_INO; + inode->i_blkbits = TEST_BLOCK_BITS; + set_nlink(inode, 1); + atomic_set(&inode->i_count, 1); + spin_lock_init(&inode->i_lock); + i_size_ordered_init(inode); + init_rwsem(&inode->i_rwsem); + INIT_LIST_HEAD(&inode->i_io_list); + INIT_LIST_HEAD(&inode->i_wb_list); + INIT_LIST_HEAD(&inode->i_lru); + INIT_HLIST_NODE(&inode->i_hash); + inode_state_set_raw(inode, I_DIRTY); + + address_space_init_once(&inode->i_data); + inode->i_data.host = inode; + inode->i_data.a_ops = &test_inline_aops; + mapping_set_gfp_mask(&inode->i_data, GFP_HIGHUSER_MOVABLE); + init_rwsem(&inode->i_data.invalidate_lock); + inode->i_mapping = &inode->i_data; + + init_rwsem(&ctx->ei.xattr_sem); + init_rwsem(&ctx->ei.i_data_sem); + spin_lock_init(&ctx->ei.i_raw_lock); + spin_lock_init(&ctx->ei.i_block_reservation_lock); + INIT_LIST_HEAD(&ctx->ei.i_orphan); + ctx->ei.i_prealloc_node = RB_ROOT; + rwlock_init(&ctx->ei.i_prealloc_lock); + ext4_es_init_tree(&ctx->ei.i_es_tree); + rwlock_init(&ctx->ei.i_es_lock); + INIT_LIST_HEAD(&ctx->ei.i_es_list); + ctx->ei.i_es_all_nr = 0; + ctx->ei.i_es_shk_nr = 0; + + reset_inode_state(ctx, S_IFREG | 0644); + + /* Activate static stubs */ + kunit_activate_static_stub(test, ext4_get_inode_loc, + stub_get_inode_loc); + kunit_activate_static_stub(test, __ext4_handle_dirty_metadata, + stub_handle_dirty_metadata); + kunit_activate_static_stub(test, ext4_mark_iloc_dirty, + stub_mark_iloc_dirty); + kunit_activate_static_stub(test, __ext4_mark_inode_dirty, + stub_mark_inode_dirty); + kunit_activate_static_stub(test, ext4_map_blocks, + stub_map_blocks); + kunit_activate_static_stub(test, ext4_inline_getblk, + stub_inline_getblk); + kunit_activate_static_stub(test, ext4_da_get_block_prep, + stub_da_get_block_prep); + kunit_activate_static_stub(test, ext4_inode_journal_mode, + stub_inode_journal_mode); + + return 0; +} + +static void inline_test_exit(struct kunit *test) +{ + struct inline_test_ctx *ctx = test->priv; + + if (current->journal_info) + ext4_journal_stop(ext4_journal_current_handle()); + + if (ctx) { + if (!list_empty(&ctx->ei.i_orphan)) + list_del_init(&ctx->ei.i_orphan); + truncate_inode_pages(&ctx->ei.vfs_inode.i_data, 0); + } + t_ctx = NULL; +} + +/* ========================================================================= + * 1. Capacity and Lookup Tests (ext4_get_max_inline_size / + * ext4_find_inline_data_nolock) + * ========================================================================= + */ + +static void test_max_inline_size_variants(struct kunit *test) +{ + struct inline_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei.vfs_inode; + int ret; + + /* 1. Fresh 256-byte inode with 32-byte extra_isize -> 128 bytes */ + KUNIT_EXPECT_EQ(test, ext4_get_max_inline_size(inode), + TEST_MAX_INLINE_SIZE); + + /* 2. Inode with i_extra_isize == 0 -> 0 */ + ctx->ei.i_extra_isize = 0; + KUNIT_EXPECT_EQ(test, ext4_get_max_inline_size(inode), 0); + ctx->ei.i_extra_isize = TEST_EXTRA_ISIZE; + + /* 3. Old 128-byte inode size (no xattr space) -> 0 */ + ctx->sbi.s_inode_size = EXT4_GOOD_OLD_INODE_SIZE; + KUNIT_EXPECT_EQ(test, ext4_get_max_inline_size(inode), 0); + ctx->sbi.s_inode_size = TEST_INODE_SIZE; + + /* 4. ext4_get_inode_loc error -> 0 */ + ctx->get_inode_loc_err = -EIO; + KUNIT_EXPECT_EQ(test, ext4_get_max_inline_size(inode), 0); + ctx->get_inode_loc_err = 0; + + /* 5. With a user xattr in ibody reducing free space */ + { + struct ext4_xattr_ibody_find is = { + .s = { .not_found = -ENODATA, }, + }; + struct ext4_xattr_info i = { + .name_index = EXT4_XATTR_INDEX_USER, + .name = "foo", + .value = "12345678", + .value_len = 8, + }; + + ret = ext4_get_inode_loc(inode, &is.iloc); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = ext4_xattr_ibody_find(inode, &i, &is); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = ext4_xattr_ibody_set(NULL, inode, &i, &is); + KUNIT_ASSERT_EQ(test, ret, 0); + brelse(is.iloc.bh); + } + /* + * "foo" entry takes EXT4_XATTR_LEN(3) = 20 bytes + EXT4_XATTR_SIZE(8) = 8 + * Total 28 bytes consumed in ibody -> max inline size drops from 128 to 100. + */ + KUNIT_EXPECT_EQ(test, ext4_get_max_inline_size(inode), + TEST_MAX_INLINE_SIZE - 28); + + /* 6. When inline data already exists in system.data, its space counts as usable */ + reset_inode_state(ctx, S_IFREG | 0644); + { + char buf[80]; + + memset(buf, 'A', sizeof(buf)); + ret = create_inline_file(inode, buf, sizeof(buf)); + KUNIT_ASSERT_EQ(test, ret, 0); + } + KUNIT_EXPECT_EQ(test, ext4_get_max_inline_size(inode), + TEST_MAX_INLINE_SIZE); + + /* + * 7. When ibody free space is smaller than EXT4_XATTR_LEN(strlen("data")) + * (20 bytes), get_max_inline_xattr_value_size returns 0 -> max is 0. + */ + reset_inode_state(ctx, S_IFREG | 0644); + { + struct ext4_xattr_ibody_find is = { + .s = { .not_found = -ENODATA, }, + }; + char val[60]; + struct ext4_xattr_info i = { + .name_index = EXT4_XATTR_INDEX_USER, + .name = "bigattr", + .value = val, + .value_len = sizeof(val), + }; + + memset(val, 'x', sizeof(val)); + ret = ext4_get_inode_loc(inode, &is.iloc); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = ext4_xattr_ibody_find(inode, &i, &is); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = ext4_xattr_ibody_set(NULL, inode, &i, &is); + KUNIT_ASSERT_EQ(test, ret, 0); + brelse(is.iloc.bh); + } + KUNIT_EXPECT_EQ(test, ext4_get_max_inline_size(inode), 0); + + /* + * 8. Corrupted xattr entry in ibody (e_name_len overflows end of inode) + * -> get_max_inline_xattr_value_size returns 0 -> total max is 0. + */ + { + struct ext4_inode *raw_inode = + (struct ext4_inode *)ctx->raw_inode_buf; + struct ext4_xattr_ibody_header *header = IHDR(inode, raw_inode); + struct ext4_xattr_entry *entry = IFIRST(header); + + entry->e_name_len = 250; + KUNIT_EXPECT_EQ(test, ext4_get_max_inline_size(inode), 0); + } +} + +static void test_find_inline_data_nolock(struct kunit *test) +{ + struct inline_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei.vfs_inode; + struct ext4_iloc iloc = { 0 }; + char buf[90]; + int ret; + + /* 1. i_extra_isize == 0 -> returns 0 immediately without setting inline state */ + ctx->ei.i_extra_isize = 0; + ret = ext4_get_inode_loc(inode, &iloc); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = ext4_find_inline_data_nolock(inode); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_FALSE(test, ext4_has_inline_data(inode)); + brelse(iloc.bh); + ctx->ei.i_extra_isize = TEST_EXTRA_ISIZE; + + /* 2. ext4_get_inode_loc error -> propagates error */ + ctx->get_inode_loc_err = -EIO; + ret = ext4_find_inline_data_nolock(inode); + KUNIT_EXPECT_EQ(test, ret, -EIO); + ctx->get_inode_loc_err = 0; + + /* 3. Inode without EXT4_STATE_XATTR -> returns 0, inline_size == 0 */ + ret = ext4_find_inline_data_nolock(inode); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, 0); + + /* 4. Inode with EXT4_STATE_XATTR set, but no system.data xattr -> 0 */ + ext4_set_inode_state(inode, EXT4_STATE_XATTR); + { + struct ext4_inode *raw_inode = + (struct ext4_inode *)ctx->raw_inode_buf; + struct ext4_xattr_ibody_header *header = IHDR(inode, raw_inode); + + header->h_magic = cpu_to_le32(EXT4_XATTR_MAGIC); + } + ret = ext4_find_inline_data_nolock(inode); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, 0); + + /* 5. Inode with 30-byte inline file (0-byte system.data xattr) */ + reset_inode_state(ctx, S_IFREG | 0644); + memset(buf, 'B', sizeof(buf)); + ret = create_inline_file(inode, buf, 30); + KUNIT_ASSERT_EQ(test, ret, 0); + + ctx->ei.i_inline_off = 0; + ctx->ei.i_inline_size = 0; + ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + ret = ext4_find_inline_data_nolock(inode); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, EXT4_MIN_INLINE_DATA_SIZE); + KUNIT_EXPECT_NE(test, ctx->ei.i_inline_off, 0); + KUNIT_EXPECT_TRUE(test, ext4_has_inline_data(inode)); + + /* 6. Inode with 90-byte inline file (30-byte system.data xattr) */ + reset_inode_state(ctx, S_IFREG | 0644); + ret = create_inline_file(inode, buf, 90); + KUNIT_ASSERT_EQ(test, ret, 0); + + ctx->ei.i_inline_off = 0; + ctx->ei.i_inline_size = 0; + ret = ext4_find_inline_data_nolock(inode); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, 90); + KUNIT_EXPECT_GT(test, ctx->ei.i_inline_off, + EXT4_GOOD_OLD_INODE_SIZE + TEST_EXTRA_ISIZE); + + /* 7. Corrupted system.data entry with non-zero e_value_inum -> -EFSCORRUPTED */ + { + struct ext4_inode *raw_inode = + (struct ext4_inode *)ctx->raw_inode_buf; + struct ext4_xattr_ibody_header *header = IHDR(inode, raw_inode); + struct ext4_xattr_entry *entry = IFIRST(header); + + entry->e_value_inum = cpu_to_le32(99); + ret = ext4_find_inline_data_nolock(inode); + KUNIT_EXPECT_EQ(test, ret, -EFSCORRUPTED); + } +} + +/* ========================================================================= + * 2. Inline File Write & Destroy Lifecycle Tests + * ========================================================================= + */ + +static void test_write_and_destroy_inline_data(struct kunit *test) +{ + struct inline_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei.vfs_inode; + struct ext4_iloc iloc = { 0 }; + struct folio *folio = NULL; + handle_t *handle; + char pattern[100]; + char verify_buf[100]; + void *kaddr; + int i, ret; + + for (i = 0; i < sizeof(pattern); i++) + pattern[i] = (char)('A' + (i % 26)); + + /* + * Step 1: Write 20 bytes into a brand-new inode (fits in i_block). + */ + inode_lock(inode); + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 0, 20, + &folio); + KUNIT_ASSERT_EQ(test, ret, 1); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, folio); + KUNIT_EXPECT_TRUE(test, folio_test_locked(folio)); + KUNIT_EXPECT_TRUE(test, ext4_has_inline_data(inode)); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, + (u16)EXT4_MIN_INLINE_DATA_SIZE); + + kaddr = kmap_local_folio(folio, 0); + memcpy(kaddr, pattern, 20); + kunmap_local(kaddr); + + ret = ext4_write_inline_data_end(inode, 0, 20, 20, folio); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ret, 20); + KUNIT_EXPECT_NULL(test, current->journal_info); + i_size_write(inode, 20); + ctx->ei.i_disksize = 20; + + /* Verify i_block contents */ + KUNIT_EXPECT_MEMEQ(test, raw_inline_i_block(ctx), pattern, 20); + + /* + * Step 2: Expand from 20 bytes to 90 bytes (crosses 60-byte boundary + * into ibody system.data xattr via ext4_update_inline_data). + */ + inode_lock(inode); + folio = NULL; + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 20, 70, + &folio); + KUNIT_ASSERT_EQ(test, ret, 1); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, folio); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, 90); + + /* Verify existing first 20 bytes were loaded into the folio by prepare_inline_data */ + kaddr = kmap_local_folio(folio, 0); + KUNIT_EXPECT_MEMEQ(test, kaddr, pattern, 20); + memcpy((char *)kaddr + 20, pattern + 20, 70); + kunmap_local(kaddr); + + ret = ext4_write_inline_data_end(inode, 20, 70, 70, folio); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ret, 70); + i_size_write(inode, 90); + ctx->ei.i_disksize = 90; + + /* + * Step 3: Overwrite 15 bytes purely within the xattr region + * (pos = 65, len = 15 -> pos >= EXT4_MIN_INLINE_DATA_SIZE). + */ + memset(pattern + 65, 'Z', 15); + inode_lock(inode); + folio = NULL; + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 65, 15, + &folio); + KUNIT_ASSERT_EQ(test, ret, 1); + kaddr = kmap_local_folio(folio, 0); + memcpy((char *)kaddr + 65, pattern + 65, 15); + kunmap_local(kaddr); + ret = ext4_write_inline_data_end(inode, 65, 15, 15, folio); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ret, 15); + + /* Verify both i_block (first 60B) and ibody xattr (remaining 30B) */ + memcpy(verify_buf, raw_inline_i_block(ctx), EXT4_MIN_INLINE_DATA_SIZE); + memcpy(verify_buf + EXT4_MIN_INLINE_DATA_SIZE, + raw_inline_xattr_pos(ctx), 30); + KUNIT_EXPECT_MEMEQ(test, verify_buf, pattern, 90); + + /* + * Step 4: Destroy inline data on a regular file -> clears inline state + * and initializes extent tree (EXT4_INODE_EXTENTS). + */ + handle = ext4_journal_start(inode, EXT4_HT_INODE, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_get_inode_loc(inode, &iloc); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = ext4_destroy_inline_data(handle, inode); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_FALSE(test, ext4_has_inline_data(inode)); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_off, 0); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, 0); + KUNIT_EXPECT_TRUE(test, ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + brelse(iloc.bh); + + /* Calling destroy again when inline_off == 0 is a no-op returning 0 */ + ret = ext4_destroy_inline_data(handle, inode); + KUNIT_EXPECT_EQ(test, ret, 0); + ext4_journal_stop(handle); + + /* + * Step 5: Initial creation directly > 60 bytes (75 bytes) on a non-extent + * mode inode (e.g. S_IFIFO) -> destroy does NOT set EXT4_INODE_EXTENTS. + */ + reset_inode_state(ctx, S_IFIFO | 0644); + ret = create_inline_file(inode, pattern, 75); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, 75); + + handle = ext4_journal_start(inode, EXT4_HT_INODE, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_destroy_inline_data(handle, inode); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_FALSE(test, ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + ext4_journal_stop(handle); +} + +static void test_write_inline_short_copy_and_edge_cases(struct kunit *test) +{ + struct inline_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei.vfs_inode; + struct folio *folio = NULL; + char buf[80]; + void *kaddr; + int ret; + + memset(buf, 'M', sizeof(buf)); + ret = create_inline_file(inode, buf, 20); + KUNIT_ASSERT_EQ(test, ret, 0); + + /* + * 1. Short write (copied < len) when expanding from 20B to 80B: + * prepare_inline_data expands xattr to 80B, but only 10 bytes are + * copied (pos=20, len=60, copied=10 -> pos+copied=30 > i_size=20). + * ext4_write_inline_data_end adds to orphan, updates i_disksize to 30, + * and calls ext4_truncate_failed_write -> shrinks inline data back to + * 60B (i_block only). + */ + inode_lock(inode); + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 20, 60, + &folio); + KUNIT_ASSERT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, 80); + + kaddr = kmap_local_folio(folio, 0); + memcpy((char *)kaddr + 20, "0123456789", 10); + kunmap_local(kaddr); + + ret = ext4_write_inline_data_end(inode, 20, 60, 10, folio); + KUNIT_EXPECT_EQ(test, ret, 10); + KUNIT_EXPECT_EQ(test, i_size_read(inode), 30); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, + (u16)EXT4_MIN_INLINE_DATA_SIZE); + KUNIT_EXPECT_TRUE(test, list_empty(&ctx->ei.i_orphan)); + inode_unlock(inode); + + /* + * 2. Short write (copied < len) when folio is NOT uptodate -> + * copied is forced to 0. + */ + inode_lock(inode); + folio = NULL; + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 30, 10, + &folio); + KUNIT_ASSERT_EQ(test, ret, 1); + folio_clear_uptodate(folio); + ret = ext4_write_inline_data_end(inode, 30, 10, 5, folio); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, i_size_read(inode), 30); + inode_unlock(inode); + + /* + * 3. Emergency shutdown flag (EXT4_FLAGS_SHUTDOWN): + * 3a. Set before ext4_try_to_write_inline_data -> ext4_journal_start + * fails with -EIO. + * 3b. Set after ext4_try_to_write_inline_data -> ext4_write_inline_data + * returns early without modifying inline data. + */ + set_bit(EXT4_FLAGS_SHUTDOWN, &ctx->sbi.s_ext4_flags); + inode_lock(inode); + folio = NULL; + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 0, 10, + &folio); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ret, -EIO); + clear_bit(EXT4_FLAGS_SHUTDOWN, &ctx->sbi.s_ext4_flags); + + inode_lock(inode); + folio = NULL; + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 0, 10, + &folio); + KUNIT_ASSERT_EQ(test, ret, 1); + kaddr = kmap_local_folio(folio, 0); + memcpy(kaddr, "XXXXXXXXXX", 10); + kunmap_local(kaddr); + set_bit(EXT4_FLAGS_SHUTDOWN, &ctx->sbi.s_ext4_flags); + ret = ext4_write_inline_data_end(inode, 0, 10, 10, folio); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ret, 10); + /* i_block should still have 'M's because shutdown skipped ext4_write_inline_data */ + KUNIT_EXPECT_MEMEQ(test, raw_inline_i_block(ctx), buf, 10); + clear_bit(EXT4_FLAGS_SHUTDOWN, &ctx->sbi.s_ext4_flags); + + /* + * 4. Race condition where EXT4_INODE_INLINE_DATA is cleared before + * ext4_write_inline_data_end runs -> skips inline copy and returns 0. + */ + inode_lock(inode); + folio = NULL; + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 0, 10, + &folio); + KUNIT_ASSERT_EQ(test, ret, 1); + ext4_clear_inode_flag(inode, EXT4_INODE_INLINE_DATA); + ret = ext4_write_inline_data_end(inode, 0, 10, 10, folio); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ret, 0); + ext4_set_inode_flag(inode, EXT4_INODE_INLINE_DATA); + + /* + * 5. Corruption detection in ext4_create_inline_data when system.data + * already exists on an inode with i_inline_off == 0 (e.g. corrupted + * e_value_inum so ext4_find_inline_data_nolock leaves i_inline_off == 0). + */ + { + struct ext4_inode *raw_inode = + (struct ext4_inode *)ctx->raw_inode_buf; + struct ext4_xattr_ibody_header *header = IHDR(inode, raw_inode); + struct ext4_xattr_entry *entry = IFIRST(header); + + entry->e_value_inum = cpu_to_le32(1); + ctx->ei.i_inline_off = 0; + ctx->ei.i_inline_size = 0; + ext4_clear_inode_flag(inode, EXT4_INODE_INLINE_DATA); + ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + folio = NULL; + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 0, + 10, &folio); + KUNIT_EXPECT_EQ(test, ret, -EFSCORRUPTED); + } + + /* + * 6. Corruption detection in ext4_update_inline_data when inline state + * claims inline data exists, but system.data xattr was wiped. + */ + reset_inode_state(ctx, S_IFREG | 0644); + ctx->ei.i_inline_off = 164; + ctx->ei.i_inline_size = EXT4_MIN_INLINE_DATA_SIZE; + ext4_set_inode_flag(inode, EXT4_INODE_INLINE_DATA); + folio = NULL; + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 0, 80, + &folio); + KUNIT_EXPECT_EQ(test, ret, -EFSCORRUPTED); +} + +/* ========================================================================= + * 3. Reading Inline Data, Symlinks, and iomap Tests + * ========================================================================= + */ + +static void test_readpage_inline_link_and_iomap(struct kunit *test) +{ + struct inline_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei.vfs_inode; + struct folio *folio; + struct iomap iomap = { 0 }; + char content[85]; + const char *short_link = "/usr/bin/python3"; + char long_link[85]; + char *target; + void *kaddr; + int i, ret; + + for (i = 0; i < sizeof(content); i++) + content[i] = (char)('0' + (i % 10)); + + /* 1. ext4_readpage_inline and ext4_inline_data_iomap on non-inline inode -> -EAGAIN */ + folio = __filemap_get_folio(&inode->i_data, 0, + FGP_LOCK | FGP_ACCESSED | FGP_CREAT, + GFP_KERNEL); + KUNIT_ASSERT_FALSE(test, IS_ERR(folio)); + ret = ext4_readpage_inline(inode, folio); + KUNIT_EXPECT_EQ(test, ret, -EAGAIN); + folio_unlock(folio); + folio_put(folio); + + ret = ext4_inline_data_iomap(inode, &iomap); + KUNIT_EXPECT_EQ(test, ret, -EAGAIN); + + /* 2. Create 85-byte inline file and test ext4_readpage_inline on index 0 */ + truncate_inode_pages(&inode->i_data, 0); + ret = create_inline_file(inode, content, sizeof(content)); + KUNIT_ASSERT_EQ(test, ret, 0); + truncate_inode_pages(&inode->i_data, 0); + + folio = __filemap_get_folio(&inode->i_data, 0, + FGP_LOCK | FGP_ACCESSED | FGP_CREAT, + GFP_KERNEL); + KUNIT_ASSERT_FALSE(test, IS_ERR(folio)); + ret = ext4_readpage_inline(inode, folio); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_TRUE(test, folio_test_uptodate(folio)); + KUNIT_EXPECT_FALSE(test, folio_test_locked(folio)); + + kaddr = kmap_local_folio(folio, 0); + KUNIT_EXPECT_MEMEQ(test, kaddr, content, sizeof(content)); + /* Verify zero-padding past inline_size */ + KUNIT_EXPECT_EQ(test, ((char *)kaddr)[sizeof(content)], 0); + KUNIT_EXPECT_EQ(test, ((char *)kaddr)[PAGE_SIZE - 1], 0); + kunmap_local(kaddr); + folio_put(folio); + + /* 3. ext4_readpage_inline on folio->index > 0 zeros the folio and marks uptodate */ + folio = __filemap_get_folio(&inode->i_data, 1, + FGP_LOCK | FGP_ACCESSED | FGP_CREAT, + GFP_KERNEL); + KUNIT_ASSERT_FALSE(test, IS_ERR(folio)); + kaddr = kmap_local_folio(folio, 0); + memset(kaddr, 0xff, PAGE_SIZE); + kunmap_local(kaddr); + + ret = ext4_readpage_inline(inode, folio); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_TRUE(test, folio_test_uptodate(folio)); + kaddr = kmap_local_folio(folio, 0); + KUNIT_EXPECT_EQ(test, ((unsigned char *)kaddr)[0], 0); + kunmap_local(kaddr); + folio_put(folio); + + /* 4. ext4_readpage_inline when ext4_get_inode_loc fails -> propagates error */ + truncate_inode_pages(&inode->i_data, 0); + ctx->get_inode_loc_err = -EIO; + folio = __filemap_get_folio(&inode->i_data, 0, + FGP_LOCK | FGP_ACCESSED | FGP_CREAT, + GFP_KERNEL); + KUNIT_ASSERT_FALSE(test, IS_ERR(folio)); + ret = ext4_readpage_inline(inode, folio); + KUNIT_EXPECT_EQ(test, ret, -EIO); + folio_put(folio); + ctx->get_inode_loc_err = 0; + + /* + * 5. ext4_readpage_inline when i_inline_size > PAGE_SIZE -> -EFSCORRUPTED. + * i_inline_size is a u16, so it can only exceed PAGE_SIZE when + * PAGE_SIZE < U16_MAX (e.g. 4KB, 8KB, 16KB, or 32KB base pages). + */ + if (PAGE_SIZE < U16_MAX) { + truncate_inode_pages(&inode->i_data, 0); + ctx->ei.i_inline_size = U16_MAX; + i_size_write(inode, U16_MAX); + folio = __filemap_get_folio(&inode->i_data, 0, + FGP_LOCK | FGP_ACCESSED | FGP_CREAT, + GFP_KERNEL); + KUNIT_ASSERT_FALSE(test, IS_ERR(folio)); + ret = ext4_readpage_inline(inode, folio); + KUNIT_EXPECT_EQ(test, ret, -EFSCORRUPTED); + folio_put(folio); + ctx->ei.i_inline_size = sizeof(content); + i_size_write(inode, sizeof(content)); + } + + /* 6. ext4_inline_data_iomap populates IOMAP_INLINE with inline address/len */ + memset(&iomap, 0, sizeof(iomap)); + ret = ext4_inline_data_iomap(inode, &iomap); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, iomap.type, (u16)IOMAP_INLINE); + KUNIT_EXPECT_EQ(test, iomap.offset, 0ULL); + KUNIT_EXPECT_EQ(test, iomap.length, (u64)sizeof(content)); + KUNIT_EXPECT_EQ(test, iomap.addr, + ((u64)ctx->iloc_bh.b_blocknr << TEST_BLOCK_BITS) + + offsetof(struct ext4_inode, i_block)); + + /* 7. ext4_inline_data_iomap error when ext4_get_inode_loc fails */ + ctx->get_inode_loc_err = -EIO; + ret = ext4_inline_data_iomap(inode, &iomap); + KUNIT_EXPECT_EQ(test, ret, -EIO); + ctx->get_inode_loc_err = 0; + + /* 8. ext4_read_inline_link: short symlink (in i_block) and long symlink (in xattr) */ + reset_inode_state(ctx, S_IFLNK | 0777); + ret = create_inline_file(inode, short_link, strlen(short_link)); + KUNIT_ASSERT_EQ(test, ret, 0); + + target = ext4_read_inline_link(inode); + KUNIT_ASSERT_FALSE(test, IS_ERR(target)); + KUNIT_EXPECT_STREQ(test, target, short_link); + kfree(target); + + reset_inode_state(ctx, S_IFLNK | 0777); + memset(long_link, 'a', sizeof(long_link) - 1); + long_link[sizeof(long_link) - 1] = '\0'; + ret = create_inline_file(inode, long_link, strlen(long_link)); + KUNIT_ASSERT_EQ(test, ret, 0); + + target = ext4_read_inline_link(inode); + KUNIT_ASSERT_FALSE(test, IS_ERR(target)); + KUNIT_EXPECT_STREQ(test, target, long_link); + kfree(target); + + /* ext4_read_inline_link error when ext4_get_inode_loc fails */ + ctx->get_inode_loc_err = -EIO; + target = ext4_read_inline_link(inode); + KUNIT_EXPECT_TRUE(test, IS_ERR(target)); + KUNIT_EXPECT_EQ(test, PTR_ERR(target), -EIO); + ctx->get_inode_loc_err = 0; +} + +/* ========================================================================= + * 4. Inline Truncation Tests (ext4_inline_data_truncate) + * ========================================================================= + */ + +static void test_inline_data_truncate(struct kunit *test) +{ + struct inline_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei.vfs_inode; + int has_inline = 1; + char buf[100]; + int i, ret; + + for (i = 0; i < sizeof(buf); i++) + buf[i] = (char)('a' + (i % 26)); + + /* 1. Non-inline inode -> sets *has_inline = 0 and returns */ + inode_lock(inode); + ext4_inline_data_truncate(inode, &has_inline); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, has_inline, 0); + + /* 2. Create a 100-byte inline file (60B in i_block + 40B in xattr) */ + ret = create_inline_file(inode, buf, 100); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, 100); + + /* 3. Truncate extending i_size (100 -> 120): no-op on inline size */ + inode_lock(inode); + i_size_write(inode, 120); + has_inline = 1; + ext4_inline_data_truncate(inode, &has_inline); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, has_inline, 1); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, 100); + + /* 4. Shrink within xattr space (100 -> 75 bytes) */ + inode_lock(inode); + i_size_write(inode, 75); + ext4_inline_data_truncate(inode, &has_inline); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, has_inline, 1); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, 75); + KUNIT_EXPECT_EQ(test, ctx->ei.i_disksize, 75); + KUNIT_EXPECT_MEMEQ(test, raw_inline_xattr_pos(ctx), + buf + EXT4_MIN_INLINE_DATA_SIZE, 15); + + /* 5. Shrink from xattr space into i_block (75 -> 25 bytes): zeros i_block[25..59] */ + inode_lock(inode); + i_size_write(inode, 25); + ext4_inline_data_truncate(inode, &has_inline); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, + (u16)EXT4_MIN_INLINE_DATA_SIZE); + KUNIT_EXPECT_EQ(test, ctx->ei.i_disksize, 25); + KUNIT_EXPECT_MEMEQ(test, raw_inline_i_block(ctx), buf, 25); + for (i = 25; i < EXT4_MIN_INLINE_DATA_SIZE; i++) + KUNIT_EXPECT_EQ(test, ((char *)raw_inline_i_block(ctx))[i], 0); + + /* 6. Shrink to 0 bytes: zeros all of i_block */ + inode_lock(inode); + i_size_write(inode, 0); + ext4_inline_data_truncate(inode, &has_inline); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ctx->ei.i_disksize, 0); + for (i = 0; i < EXT4_MIN_INLINE_DATA_SIZE; i++) + KUNIT_EXPECT_EQ(test, ((char *)raw_inline_i_block(ctx))[i], 0); + + /* + * 7. When !EXT4_STATE_MAY_INLINE_DATA (being converted), + * ext4_inline_data_truncate clears the extent status tree. + */ + ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + inode_lock(inode); + ext4_inline_data_truncate(inode, &has_inline); + inode_unlock(inode); + KUNIT_EXPECT_TRUE(test, list_empty(&ctx->ei.i_orphan)); +} + +/* ========================================================================= + * 5. Inline-to-Extent Conversion Tests for Regular Files + * ========================================================================= + */ + +static void test_convert_inline_data_and_rollback(struct kunit *test) +{ + struct inline_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei.vfs_inode; + char buf[80]; + int i, ret; + + for (i = 0; i < sizeof(buf); i++) + buf[i] = (char)('A' + (i % 26)); + + /* 1. Non-inline inode -> clears MAY_INLINE_DATA and returns 0 immediately */ + ret = ext4_convert_inline_data(inode); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)); + ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + + /* + * 2. Inline inode without EXT4_STATE_MAY_INLINE_DATA -> calls + * filemap_flush() and finishes converting inline data if still inline. + */ + ret = create_inline_file(inode, buf, sizeof(buf)); + KUNIT_ASSERT_EQ(test, ret, 0); + ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + ret = ext4_convert_inline_data(inode); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_FALSE(test, ext4_has_inline_data(inode)); + KUNIT_EXPECT_MEMEQ(test, ctx->data_block_buf, buf, sizeof(buf)); + + /* + * 3. Error rollback when ext4_map_blocks fails (-ENOSPC): + * ext4_restore_inline_data restores the original 80 bytes of inline data. + */ + reset_inode_state(ctx, S_IFREG | 0644); + ret = create_inline_file(inode, buf, sizeof(buf)); + KUNIT_ASSERT_EQ(test, ret, 0); + ctx->map_blocks_ret = -ENOSPC; + ret = ext4_convert_inline_data(inode); + KUNIT_EXPECT_EQ(test, ret, -ENOSPC); + KUNIT_EXPECT_TRUE(test, ext4_has_inline_data(inode)); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, sizeof(buf)); + KUNIT_EXPECT_MEMEQ(test, raw_inline_i_block(ctx), buf, + EXT4_MIN_INLINE_DATA_SIZE); + KUNIT_EXPECT_MEMEQ(test, raw_inline_xattr_pos(ctx), + buf + EXT4_MIN_INLINE_DATA_SIZE, + sizeof(buf) - EXT4_MIN_INLINE_DATA_SIZE); + ctx->map_blocks_ret = 1; + + /* + * 4. Error rollback when ext4_map_blocks returns unmapped block -> -EIO + */ + ctx->map_flags = 0; + ret = ext4_convert_inline_data(inode); + KUNIT_EXPECT_EQ(test, ret, -EIO); + KUNIT_EXPECT_TRUE(test, ext4_has_inline_data(inode)); + ctx->map_flags = EXT4_MAP_MAPPED; + + /* + * 5. Error rollback when ext4_inline_getblk returns NULL -> -ENOMEM + */ + ctx->getblk_fail = true; + ret = ext4_convert_inline_data(inode); + KUNIT_EXPECT_EQ(test, ret, -ENOMEM); + KUNIT_EXPECT_TRUE(test, ext4_has_inline_data(inode)); + ctx->getblk_fail = false; + + /* + * 6. Error rollback when ext4_handle_dirty_metadata fails on data_bh + */ + ctx->dirty_metadata_err = -EIO; + ctx->dirty_metadata_fail_on_call = 1; + ctx->dirty_metadata_calls = 0; + ret = ext4_convert_inline_data(inode); + KUNIT_EXPECT_EQ(test, ret, -EIO); + KUNIT_EXPECT_TRUE(test, ext4_has_inline_data(inode)); + ctx->dirty_metadata_err = 0; + ctx->dirty_metadata_fail_on_call = 0; + + /* + * 7. Successful conversion via ext4_convert_inline_data(): + * copies 80 bytes into data_bh, destroys inline data, initializes + * extent tree. + */ + memset(ctx->data_block_buf, 0, sizeof(ctx->data_block_buf)); + ret = ext4_convert_inline_data(inode); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_FALSE(test, ext4_has_inline_data(inode)); + KUNIT_EXPECT_TRUE(test, ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + KUNIT_EXPECT_MEMEQ(test, ctx->data_block_buf, buf, sizeof(buf)); +} + +static void test_write_triggers_inline_to_extent_conversion(struct kunit *test) +{ + struct inline_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->ei.vfs_inode; + struct folio *folio = NULL; + char buf[50]; + int ret; + + memset(buf, 'K', sizeof(buf)); + + /* + * 1. Standard write (ext4_try_to_write_inline_data) exceeding + * TEST_MAX_INLINE_SIZE (pos=0, len=200) converts inline data via + * ext4_convert_inline_data_to_extent -> returns 0 so caller proceeds + * with normal block write. + */ + ret = create_inline_file(inode, buf, sizeof(buf)); + KUNIT_ASSERT_EQ(test, ret, 0); + + inode_lock(inode); + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 0, 200, + &folio); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_FALSE(test, ext4_has_inline_data(inode)); + KUNIT_EXPECT_TRUE(test, ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + + /* + * 2. Conversion with DIOREAD_NOLOCK + DELALLOC in writeback mode + * (exercises ext4_should_dioread_nolock -> ext4_get_block_unwritten), + * and separately with JOURNAL_DATA mode (exercises + * ext4_should_journal_data -> do_journal_get_write_access). + */ + reset_inode_state(ctx, S_IFREG | 0644); + ret = create_inline_file(inode, buf, sizeof(buf)); + KUNIT_ASSERT_EQ(test, ret, 0); + + set_opt(&ctx->sb, DIOREAD_NOLOCK); + set_opt(&ctx->sb, DELALLOC); + ctx->journal_mode = EXT4_INODE_WRITEBACK_DATA_MODE; + + inode_lock(inode); + folio = NULL; + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 0, 200, + &folio); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_FALSE(test, ext4_has_inline_data(inode)); + + clear_opt(&ctx->sb, DIOREAD_NOLOCK); + clear_opt(&ctx->sb, DELALLOC); + + reset_inode_state(ctx, S_IFREG | 0644); + ret = create_inline_file(inode, buf, sizeof(buf)); + KUNIT_ASSERT_EQ(test, ret, 0); + + ctx->journal_mode = EXT4_INODE_JOURNAL_DATA_MODE; + + inode_lock(inode); + folio = NULL; + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 0, 200, + &folio); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_FALSE(test, ext4_has_inline_data(inode)); + + ctx->journal_mode = EXT4_INODE_WRITEBACK_DATA_MODE; + + /* + * 3. Error paths in ext4_convert_inline_data_to_extent when + * ext4_get_block fails during ext4_block_write_begin (-EIO and -ENOSPC): + * cleans up orphan and propagates error. + */ + reset_inode_state(ctx, S_IFREG | 0644); + ret = create_inline_file(inode, buf, sizeof(buf)); + KUNIT_ASSERT_EQ(test, ret, 0); + + ctx->map_blocks_ret = -EIO; + inode_lock(inode); + folio = NULL; + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 0, 200, + &folio); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ret, -EIO); + KUNIT_EXPECT_TRUE(test, list_empty(&ctx->ei.i_orphan)); + ctx->map_blocks_ret = 1; + + reset_inode_state(ctx, S_IFREG | 0644); + ret = create_inline_file(inode, buf, sizeof(buf)); + KUNIT_ASSERT_EQ(test, ret, 0); + + ctx->map_blocks_ret = -ENOSPC; + inode_lock(inode); + folio = NULL; + ret = ext4_try_to_write_inline_data(&inode->i_data, inode, 0, 200, + &folio); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ret, -ENOSPC); + KUNIT_EXPECT_FALSE(test, ext4_has_inline_data(inode)); + KUNIT_EXPECT_TRUE(test, list_empty(&ctx->ei.i_orphan)); + ctx->map_blocks_ret = 1; + + /* + * 4. Delayed allocation conversion (da = true in + * ext4_generic_write_inline_data): + * 4a. Fresh inode without inline data yet -> clears MAY_INLINE_DATA + * and returns 0. + */ + reset_inode_state(ctx, S_IFREG | 0644); + folio = NULL; + ret = ext4_generic_write_inline_data(&inode->i_data, inode, 0, 200, + &folio, true); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)); + + /* + * 4b. Existing inline data -> ext4_da_convert_inline_data_to_extent + * loads inline bytes into folio, marks buffer delayed, and clears + * EXT4_STATE_MAY_INLINE_DATA while keeping inline data until + * writepages. + */ + reset_inode_state(ctx, S_IFREG | 0644); + ret = create_inline_file(inode, buf, sizeof(buf)); + KUNIT_ASSERT_EQ(test, ret, 0); + truncate_inode_pages(&inode->i_data, 0); + + folio = NULL; + ret = ext4_generic_write_inline_data(&inode->i_data, inode, 0, 200, + &folio, true); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)); + + /* + * 4c. Error in ext4_da_get_block_prep during DA conversion -> + * propagates error and unlocks folio. + */ + reset_inode_state(ctx, S_IFREG | 0644); + ret = create_inline_file(inode, buf, sizeof(buf)); + KUNIT_ASSERT_EQ(test, ret, 0); + truncate_inode_pages(&inode->i_data, 0); + + ctx->da_get_block_prep_err = -ENOSPC; + inode_lock(inode); + folio = NULL; + ret = ext4_generic_write_inline_data(&inode->i_data, inode, 0, 200, + &folio, true); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ret, -ENOSPC); + ctx->da_get_block_prep_err = 0; +} + +/* ========================================================================= + * 6. Inline Directory Operations Tests + * ========================================================================= + */ + +struct test_dir_ctx { + struct dir_context ctx; + int count; + char names[16][32]; + u64 inos[16]; + int max_emit; + struct inode *mutate_inode_on_second; +}; + +static bool test_filldir_actor(struct dir_context *dctx, const char *name, + int namelen, loff_t offset, u64 ino, + unsigned int d_type) +{ + struct test_dir_ctx *tctx = + container_of(dctx, struct test_dir_ctx, ctx); + + if (tctx->max_emit > 0 && tctx->count >= tctx->max_emit) + return false; + + if (tctx->count < 16) { + int copy_len = min(namelen, 31); + + memcpy(tctx->names[tctx->count], name, copy_len); + tctx->names[tctx->count][copy_len] = '\0'; + tctx->inos[tctx->count] = ino; + } + tctx->count++; + + if (tctx->mutate_inode_on_second && tctx->count == 2) { + inode_inc_iversion(tctx->mutate_inode_on_second); + tctx->mutate_inode_on_second = NULL; + } + return true; +} + +struct inline_dir_test_env { + struct inode parent; + struct inode child; + struct qstr qname; + struct ext4_filename fname; + struct dir_private_info info; + struct file filp; + struct test_dir_ctx dctx; + struct ext4_dir_entry_2 bogus_de; +}; + +static struct inline_dir_test_env * +alloc_dir_test_env(struct kunit *test, struct inline_test_ctx *ctx) +{ + struct inline_dir_test_env *env; + + env = kunit_kzalloc(test, sizeof(*env), GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, env); + env->parent.i_sb = &ctx->sb; + env->parent.i_ino = TEST_PARENT_INO; + env->parent.i_mode = S_IFDIR | 0755; + return env; +} + +static void init_mock_fname_and_child(struct inline_dir_test_env *env, + struct super_block *sb, + const char *name, ino_t ino, + umode_t mode) +{ + memset(&env->fname, 0, sizeof(env->fname)); + memset(&env->qname, 0, sizeof(env->qname)); + memset(&env->child, 0, sizeof(env->child)); + + env->child.i_sb = sb; + env->child.i_ino = ino; + env->child.i_mode = mode; + + env->qname.name = (const unsigned char *)name; + env->qname.len = strlen(name); + env->fname.usr_fname = &env->qname; + env->fname.disk_name.name = (unsigned char *)name; + env->fname.disk_name.len = strlen(name); +} + +static void test_update_final_de(struct kunit *test) +{ + u8 buf[64]; + struct ext4_dir_entry_2 *de1, *de2; + + memset(buf, 0, sizeof(buf)); + + /* 1. old_size == 0 -> sets de1->rec_len to new_size (32) */ + de1 = (struct ext4_dir_entry_2 *)buf; + ext4_update_final_de(buf, 0, 32); + KUNIT_EXPECT_EQ(test, le16_to_cpu(de1->rec_len), 32); + + /* 2. Two entries in 32 bytes (12 + 20), expand to 56 bytes -> last entry becomes 44 */ + de1->rec_len = cpu_to_le16(12); + de2 = (struct ext4_dir_entry_2 *)(buf + 12); + de2->rec_len = cpu_to_le16(20); + ext4_update_final_de(buf, 32, 56); + KUNIT_EXPECT_EQ(test, le16_to_cpu(de1->rec_len), 12); + KUNIT_EXPECT_EQ(test, le16_to_cpu(de2->rec_len), 44); +} + +static void test_inline_dir_lifecycle_and_operations(struct kunit *test) +{ + struct inline_test_ctx *ctx = test->priv; + struct inode *dir = &ctx->ei.vfs_inode; + struct inline_dir_test_env *env; + struct ext4_dir_entry_2 *de = NULL; + struct buffer_head *bh = NULL; + handle_t *handle; + int has_inline_data = 1; + int ret; + + env = alloc_dir_test_env(test, ctx); + reset_inode_state(ctx, S_IFDIR | 0755); + + /* + * 1. Create inline directory via ext4_try_create_inline_dir. + */ + handle = ext4_journal_start(dir, EXT4_HT_DIR, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_try_create_inline_dir(handle, &env->parent, dir); + ext4_journal_stop(handle); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_TRUE(test, ext4_has_inline_data(dir)); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, + (u16)EXT4_MIN_INLINE_DATA_SIZE); + KUNIT_EXPECT_EQ(test, i_size_read(dir), + (loff_t)EXT4_MIN_INLINE_DATA_SIZE); + + /* Newly created inline dir is empty */ + KUNIT_EXPECT_TRUE(test, empty_inline_dir(dir, &has_inline_data)); + KUNIT_EXPECT_EQ(test, has_inline_data, 1); + + /* + * 2. Verify ext4_get_first_inline_block returns the inline buffer + * starting at parent_de (whose inode field holds the parent ino). + */ + bh = ext4_get_first_inline_block(dir, &de, &ret); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, bh); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), (u32)TEST_PARENT_INO); + brelse(bh); + + /* + * 3. Add first entry "file1" (fits in i_block alongside parent ino). + * Return value 1 means added inline without block conversion. + */ + init_mock_fname_and_child(env, &ctx->sb, "file1", 101, S_IFREG | 0644); + handle = ext4_journal_start(dir, EXT4_HT_DIR, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_try_add_inline_entry(handle, &env->fname, dir, &env->child); + ext4_journal_stop(handle); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, + (u16)EXT4_MIN_INLINE_DATA_SIZE); + KUNIT_EXPECT_FALSE(test, empty_inline_dir(dir, &has_inline_data)); + + /* + * 4. Adding duplicate "file1" returns -EEXIST. + */ + handle = ext4_journal_start(dir, EXT4_HT_DIR, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_try_add_inline_entry(handle, &env->fname, dir, &env->child); + ext4_journal_stop(handle); + KUNIT_EXPECT_EQ(test, ret, -EEXIST); + + /* + * 5. Add more entries ("file2_longer_name", "file3_longer_name", + * "file4_in_xattr") to overflow i_block (56B) and trigger expansion + * into ibody system.data xattr via ext4_update_inline_dir (132B). + */ + init_mock_fname_and_child(env, &ctx->sb, "file2_longer_name", 102, + S_IFREG | 0644); + handle = ext4_journal_start(dir, EXT4_HT_DIR, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_try_add_inline_entry(handle, &env->fname, dir, &env->child); + ext4_journal_stop(handle); + KUNIT_EXPECT_EQ(test, ret, 1); + + init_mock_fname_and_child(env, &ctx->sb, "file3_longer_name", 103, + S_IFDIR | 0755); + handle = ext4_journal_start(dir, EXT4_HT_DIR, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_try_add_inline_entry(handle, &env->fname, dir, &env->child); + ext4_journal_stop(handle); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, ctx->ei.i_inline_size, TEST_MAX_INLINE_SIZE); + + init_mock_fname_and_child(env, &ctx->sb, "file4_in_xattr", 104, + S_IFREG | 0644); + handle = ext4_journal_start(dir, EXT4_HT_DIR, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_try_add_inline_entry(handle, &env->fname, dir, &env->child); + ext4_journal_stop(handle); + KUNIT_EXPECT_EQ(test, ret, 1); + + /* + * 6. Lookup entries in both i_block ("file1") and xattr ("file4_in_xattr"), + * and verify missing entry returns NULL. + */ + init_mock_fname_and_child(env, &ctx->sb, "file1", 0, 0); + bh = ext4_find_inline_entry(dir, &env->fname, &de, &has_inline_data); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, bh); + KUNIT_EXPECT_EQ(test, has_inline_data, 1); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), 101U); + brelse(bh); + + init_mock_fname_and_child(env, &ctx->sb, "file4_in_xattr", 0, 0); + bh = ext4_find_inline_entry(dir, &env->fname, &de, &has_inline_data); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, bh); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), 104U); + brelse(bh); + + init_mock_fname_and_child(env, &ctx->sb, "nonexistent", 0, 0); + bh = ext4_find_inline_entry(dir, &env->fname, &de, &has_inline_data); + KUNIT_EXPECT_NULL(test, bh); + KUNIT_EXPECT_EQ(test, has_inline_data, 1); + + /* + * 7. Test ext4_read_inline_dir (full iteration, partial iteration, + * and iversion change re-validation). + */ + env->filp.f_inode = dir; + env->filp.private_data = &env->info; + env->dctx.ctx.actor = test_filldir_actor; + env->dctx.ctx.pos = 0; + + ret = ext4_read_inline_dir(&env->filp, &env->dctx.ctx, + &has_inline_data); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, has_inline_data, 1); + /* + * Expect ".", "..", "file1", "file2_longer_name", + * "file3_longer_name", "file4_in_xattr" + */ + KUNIT_EXPECT_EQ(test, env->dctx.count, 6); + KUNIT_EXPECT_STREQ(test, env->dctx.names[0], "."); + KUNIT_EXPECT_STREQ(test, env->dctx.names[1], ".."); + KUNIT_EXPECT_STREQ(test, env->dctx.names[2], "file1"); + KUNIT_EXPECT_STREQ(test, env->dctx.names[5], "file4_in_xattr"); + /* + * extra_size = (dotdot_size - EXT4_INLINE_DOTDOT_SIZE) + + * TEST_MAX_INLINE_SIZE = (24 - 4) + 128 = 148 + */ + KUNIT_EXPECT_EQ(test, env->dctx.ctx.pos, + (loff_t)(TEST_MAX_INLINE_SIZE + 20)); + + /* Calling again at EOF (pos == inline_size) emits nothing */ + env->dctx.count = 0; + ret = ext4_read_inline_dir(&env->filp, &env->dctx.ctx, + &has_inline_data); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, env->dctx.count, 0); + + /* + * Mutating inode iversion during iteration and re-entering at nonzero + * ctx.pos triggers offset revalidation in ext4_read_inline_dir(). + */ + memset(&env->dctx, 0, sizeof(env->dctx)); + env->dctx.ctx.actor = test_filldir_actor; + env->dctx.ctx.pos = 0; + env->dctx.max_emit = 3; + env->dctx.mutate_inode_on_second = dir; + ret = ext4_read_inline_dir(&env->filp, &env->dctx.ctx, + &has_inline_data); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, env->dctx.count, 3); + KUNIT_EXPECT_GT(test, env->dctx.ctx.pos, (loff_t)0); + + env->dctx.max_emit = 0; + ret = ext4_read_inline_dir(&env->filp, &env->dctx.ctx, + &has_inline_data); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, env->dctx.count, 6); + + /* + * 8. Test ext4_inlinedir_to_tree (htree rbtree population). + */ + { + struct dir_private_info *info; + struct dx_hash_info hinfo = { + .hash_version = DX_HASH_HALF_MD4, + }; + + memset(&env->filp, 0, sizeof(env->filp)); + env->filp.f_inode = dir; + info = kzalloc_obj(*info, GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, info); + env->filp.private_data = info; + ret = ext4_inlinedir_to_tree(&env->filp, dir, 0, &hinfo, + 0, 0, &has_inline_data); + KUNIT_EXPECT_GT(test, ret, 0); + KUNIT_EXPECT_EQ(test, has_inline_data, 1); + + /* With start_hash = 0xffffffffU, entries with smaller hash are skipped */ + ext4_htree_free_dir_info(info); + info = kzalloc_obj(*info, GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, info); + env->filp.private_data = info; + ret = ext4_inlinedir_to_tree(&env->filp, dir, 0, &hinfo, + 0xffffffffU, 0xffffffffU, + &has_inline_data); + KUNIT_EXPECT_GE(test, ret, 0); + ext4_htree_free_dir_info(info); + } + + /* + * 9. Delete entries in both i_block and xattr regions and verify + * empty_inline_dir behavior when only xattr has an entry vs completely empty. + */ + { + static const char * const del_names[] = { + "file1", + "file2_longer_name", + "file3_longer_name", + }; + int i; + + for (i = 0; i < ARRAY_SIZE(del_names); i++) { + init_mock_fname_and_child(env, &ctx->sb, del_names[i], + 0, 0); + bh = ext4_find_inline_entry(dir, &env->fname, &de, + &has_inline_data); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, bh); + handle = ext4_journal_start(dir, EXT4_HT_DIR, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_delete_inline_entry(handle, dir, de, bh, + &has_inline_data); + ext4_journal_stop(handle); + KUNIT_EXPECT_EQ(test, ret, 0); + brelse(bh); + } + } + + /* i_block now has no live entries, but "file4_in_xattr" is still in xattr */ + KUNIT_EXPECT_FALSE(test, empty_inline_dir(dir, &has_inline_data)); + + /* Delete "file4_in_xattr" -> directory becomes completely empty */ + init_mock_fname_and_child(env, &ctx->sb, "file4_in_xattr", 0, 0); + bh = ext4_find_inline_entry(dir, &env->fname, &de, &has_inline_data); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, bh); + + /* Deleting an address outside inline buffers returns -ENOENT */ + handle = ext4_journal_start(dir, EXT4_HT_DIR, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_delete_inline_entry(handle, dir, &env->bogus_de, bh, + &has_inline_data); + ext4_journal_stop(handle); + KUNIT_EXPECT_EQ(test, ret, -ENOENT); + + handle = ext4_journal_start(dir, EXT4_HT_DIR, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_delete_inline_entry(handle, dir, de, bh, &has_inline_data); + ext4_journal_stop(handle); + KUNIT_EXPECT_EQ(test, ret, 0); + brelse(bh); + + KUNIT_EXPECT_TRUE(test, empty_inline_dir(dir, &has_inline_data)); +} + +static void test_inline_dir_conversion_and_corruptions(struct kunit *test) +{ + struct inline_test_ctx *ctx = test->priv; + struct inode *dir = &ctx->ei.vfs_inode; + struct inline_dir_test_env *env; + struct ext4_dir_entry_2 *de; + handle_t *handle; + int has_inline_data = 1; + int i, ret; + + env = alloc_dir_test_env(test, ctx); + reset_inode_state(ctx, S_IFDIR | 0755); + + handle = ext4_journal_start(dir, EXT4_HT_DIR, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_try_create_inline_dir(handle, &env->parent, dir); + ext4_journal_stop(handle); + KUNIT_ASSERT_EQ(test, ret, 0); + + /* Fill the inline directory up to its 128-byte limit */ + for (i = 0; i < 4; i++) { + char name[24]; + + snprintf(name, sizeof(name), "entry_long_name_%d", i); + init_mock_fname_and_child(env, &ctx->sb, name, 200 + i, + S_IFREG | 0644); + handle = ext4_journal_start(dir, EXT4_HT_DIR, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_try_add_inline_entry(handle, &env->fname, dir, + &env->child); + ext4_journal_stop(handle); + KUNIT_ASSERT_EQ(test, ret, 1); + } + + /* + * 1. When full, adding another entry triggers ext4_convert_inline_data_nolock. + * Test rollback first when ext4_map_blocks fails (-ENOSPC). + */ + init_mock_fname_and_child(env, &ctx->sb, "overflow_entry_name", 250, + S_IFREG | 0644); + ctx->map_blocks_ret = -ENOSPC; + handle = ext4_journal_start(dir, EXT4_HT_DIR, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_try_add_inline_entry(handle, &env->fname, dir, &env->child); + ext4_journal_stop(handle); + KUNIT_EXPECT_EQ(test, ret, -ENOSPC); + KUNIT_EXPECT_TRUE(test, ext4_has_inline_data(dir)); + ctx->map_blocks_ret = 1; + + /* + * 2. Successful conversion of full inline directory to a normal + * 1024-byte directory block -> ext4_try_add_inline_entry returns 0 + * and data_block_buf starts with "." and ".." followed by copied entries. + */ + memset(ctx->data_block_buf, 0, sizeof(ctx->data_block_buf)); + handle = ext4_journal_start(dir, EXT4_HT_DIR, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_try_add_inline_entry(handle, &env->fname, dir, &env->child); + ext4_journal_stop(handle); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_FALSE(test, ext4_has_inline_data(dir)); + KUNIT_EXPECT_EQ(test, i_size_read(dir), (loff_t)TEST_BLOCK_SIZE); + + /* Verify "." and ".." headers in converted block */ + de = (struct ext4_dir_entry_2 *)ctx->data_block_buf; + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), (u32)TEST_INO); + KUNIT_EXPECT_EQ(test, de->name_len, 1); + KUNIT_EXPECT_EQ(test, de->name[0], '.'); + de = ext4_next_entry(de, TEST_BLOCK_SIZE); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), (u32)TEST_PARENT_INO); + KUNIT_EXPECT_EQ(test, de->name_len, 2); + KUNIT_EXPECT_MEMEQ(test, de->name, "..", 2); + + /* + * 3. Non-inline directory behavior on inline dir functions: + * sets *has_inline_data = 0 and returns early. + */ + has_inline_data = 1; + KUNIT_EXPECT_TRUE(test, empty_inline_dir(dir, &has_inline_data)); + KUNIT_EXPECT_EQ(test, has_inline_data, 0); + + /* + * 4. Corrupted inline directory checks: + * 4a. Parent ino ("..") == 0 -> empty_inline_dir returns false. + * 4b. Zero rec_len dirent -> empty_inline_dir returns false and + * ext4_convert_inline_data aborts via ext4_check_all_de. + */ + reset_inode_state(ctx, S_IFDIR | 0755); + handle = ext4_journal_start(dir, EXT4_HT_DIR, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ret = ext4_try_create_inline_dir(handle, &env->parent, dir); + ext4_journal_stop(handle); + KUNIT_ASSERT_EQ(test, ret, 0); + + /* Corrupt parent ino to 0 */ + *(__le32 *)raw_inline_i_block(ctx) = cpu_to_le32(0); + KUNIT_EXPECT_FALSE(test, empty_inline_dir(dir, &has_inline_data)); + *(__le32 *)raw_inline_i_block(ctx) = cpu_to_le32(TEST_PARENT_INO); + + /* Corrupt first dirent rec_len to 0 */ + de = (struct ext4_dir_entry_2 *)((char *)raw_inline_i_block(ctx) + + EXT4_INLINE_DOTDOT_SIZE); + de->rec_len = cpu_to_le16(0); + KUNIT_EXPECT_FALSE(test, empty_inline_dir(dir, &has_inline_data)); + + /* ext4_convert_inline_data on corrupted inline dir fails in ext4_check_all_de */ + ret = ext4_convert_inline_data(dir); + KUNIT_EXPECT_EQ(test, ret, -EFSCORRUPTED); + KUNIT_EXPECT_TRUE(test, ext4_has_inline_data(dir)); +} + +static struct kunit_case ext4_inline_test_cases[] = { + KUNIT_CASE(test_max_inline_size_variants), + KUNIT_CASE(test_find_inline_data_nolock), + KUNIT_CASE(test_write_and_destroy_inline_data), + KUNIT_CASE(test_write_inline_short_copy_and_edge_cases), + KUNIT_CASE(test_readpage_inline_link_and_iomap), + KUNIT_CASE(test_inline_data_truncate), + KUNIT_CASE(test_convert_inline_data_and_rollback), + KUNIT_CASE(test_write_triggers_inline_to_extent_conversion), + KUNIT_CASE(test_update_final_de), + KUNIT_CASE(test_inline_dir_lifecycle_and_operations), + KUNIT_CASE(test_inline_dir_conversion_and_corruptions), + {} +}; + +static struct kunit_suite ext4_inline_test_suite = { + .name = "ext4_inline_test", + .init = inline_test_init, + .exit = inline_test_exit, + .test_cases = ext4_inline_test_cases, +}; + +kunit_test_suites(&ext4_inline_test_suite); + +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/inline.c b/fs/ext4/inline.c index ceee69a66482bc..acdc65ce47960a 100644 --- a/fs/ext4/inline.c +++ b/fs/ext4/inline.c @@ -9,6 +9,7 @@ #include #include #include +#include #include "ext4_jbd2.h" #include "ext4.h" @@ -151,7 +152,7 @@ int ext4_find_inline_data_nolock(struct inode *inode) }; int error; - if (EXT4_I(inode)->i_extra_isize == 0) + if (!EXT4_INODE_HAS_XATTR_SPACE(inode)) return 0; error = ext4_get_inode_loc(inode, &is.iloc); @@ -187,6 +188,8 @@ static int ext4_read_inline_data(struct inode *inode, void *buffer, struct ext4_xattr_ibody_header *header; int cp_len = 0; struct ext4_inode *raw_inode; + void *end, *p; + u16 offset; if (!len) return 0; @@ -205,13 +208,21 @@ static int ext4_read_inline_data(struct inode *inode, void *buffer, goto out; header = IHDR(inode, raw_inode); + end = ITAIL(inode, raw_inode); entry = (struct ext4_xattr_entry *)((void *)raw_inode + EXT4_I(inode)->i_inline_off); len = min_t(unsigned int, len, (unsigned int)le32_to_cpu(entry->e_value_size)); - memcpy(buffer, - (void *)IFIRST(header) + le16_to_cpu(entry->e_value_offs), len); + offset = le16_to_cpu(entry->e_value_offs); + p = (void *)IFIRST(header) + offset; + + if (unlikely(p + len > end)) { + EXT4_ERROR_INODE(inode, "corrupt inline xattr entry"); + return -EFSCORRUPTED; + } + + memcpy(buffer, p, len); cp_len += len; out: @@ -461,6 +472,12 @@ static int ext4_destroy_inline_data_nolock(handle_t *handle, error = ext4_xattr_ibody_find(inode, &i, &is); if (error) goto out; + if (is.s.not_found) { + EXT4_ERROR_INODE(inode, + "corrupted inline data without system.data xattr"); + error = -EFSCORRUPTED; + goto out; + } BUFFER_TRACE(is.iloc.bh, "get_write_access"); error = ext4_journal_get_write_access(handle, inode->i_sb, is.iloc.bh, @@ -1096,6 +1113,13 @@ static void ext4_restore_inline_data(handle_t *handle, struct inode *inode, ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); } +struct buffer_head *ext4_inline_getblk(struct super_block *sb, + ext4_fsblk_t block) +{ + KUNIT_STATIC_STUB_REDIRECT(ext4_inline_getblk, sb, block); + return sb_getblk(sb, block); +} + static int ext4_convert_inline_data_nolock(handle_t *handle, struct inode *inode, struct ext4_iloc *iloc) @@ -1144,7 +1168,7 @@ static int ext4_convert_inline_data_nolock(handle_t *handle, goto out_restore; } - data_bh = sb_getblk(inode->i_sb, map.m_pblk); + data_bh = ext4_inline_getblk(inode->i_sb, map.m_pblk); if (!data_bh) { error = -ENOMEM; goto out_restore; @@ -1905,8 +1929,12 @@ int ext4_inline_data_truncate(struct inode *inode, int *has_inline) * the extent status cache must be cleared to avoid leaving * behind stale delayed allocated extent entries */ - if (!ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) - ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS); + if (!ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) { + ext4_lblk_t lblk = EXT4_B_TO_LBLK(inode, i_size); + + ext4_es_remove_extent(inode, lblk, + EXT_MAX_BLOCKS - lblk); + } /* Clear the content in the xattr space. */ if (inline_size > EXT4_MIN_INLINE_DATA_SIZE) { @@ -2016,3 +2044,27 @@ int ext4_convert_inline_data(struct inode *inode) brelse(iloc.bh); return error; } + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inline_getblk); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_max_inline_size); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_find_inline_data_nolock); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_readpage_inline); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_generic_write_inline_data); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_try_to_write_inline_data); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_write_inline_data_end); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_update_final_de); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_try_add_inline_entry); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inlinedir_to_tree); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_read_inline_dir); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_read_inline_link); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_first_inline_block); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_try_create_inline_dir); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_find_inline_entry); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_delete_inline_entry); +EXPORT_SYMBOL_FOR_EXT4_TEST(empty_inline_dir); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_destroy_inline_data); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inline_data_iomap); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inline_data_truncate); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_convert_inline_data); +#endif diff --git a/fs/ext4/inode-test.c b/fs/ext4/inode-test.c index 749af7ad4e09c2..529cab24db48f3 100644 --- a/fs/ext4/inode-test.c +++ b/fs/ext4/inode-test.c @@ -1,14 +1,32 @@ // SPDX-License-Identifier: GPL-2.0 /* - * KUnit test of ext4 inode that verify the seconds part of [a/c/m] - * timestamps in ext4 inode structs are decoded correctly. + * KUnit tests for fs/ext4/inode.c */ #include +#include +#include +#include +#include +#include +#include +#include +#include #include +#include +#include +#include +#include +#include +#include #include +#include #include "ext4.h" +#include "ext4_jbd2.h" +#include "ext4_extents.h" +#include "xattr.h" +#include "truncate.h" /* * For constructing the nonnegative timestamp lower bound value. @@ -233,7 +251,6 @@ static time64_t get_32bit_time(const struct timestamp_expectation * const test) return UPPER_MSB_0; } - /* * Test data is derived from the table in the Inode Timestamps section of * Documentation/filesystems/ext4/inodes.rst. @@ -267,8 +284,3493 @@ static void inode_test_xtimestamp_decoding(struct kunit *test) test_param->extra_bits); } +/* ------------------------------------------------------------------------- + * Mock filesystem, block pool, and VFS inode fixture for fs/ext4/inode.c + * ------------------------------------------------------------------------- + */ + +#define INODE_TEST_BLK_SIZE 4096 +#define INODE_TEST_BLK_BITS 12 +#define INODE_TEST_TOTAL_BLKS 32768 +#define INODE_TEST_INODE_SIZE 256 +#define INODE_TEST_EXTRA_ISIZE 32 +#define INODE_TEST_INODES_PER_BLK (INODE_TEST_BLK_SIZE / INODE_TEST_INODE_SIZE) +#define INODE_TEST_INODES_PER_GRP 2048 +#define INODE_TEST_FIRST_INO 11 +#define INODE_TEST_PRIMARY_INO 12 +#define INODE_TEST_CSUM_SEED 0x5a3c9e71U + +#define INODE_TEST_IBITMAP_BLK 10 +#define INODE_TEST_ITABLE_BLK0 20 +#define INODE_TEST_ITABLE_BLK1 21 +#define INODE_TEST_META_BLK0 50 +#define INODE_TEST_META_BLK1 51 +#define INODE_TEST_DATA_BLK0 100 +#define INODE_TEST_DATA_NBLKS 8 +#define INODE_TEST_POOL_SIZE 16 +#define INODE_TEST_MAX_TRACKED_INODES 32 + +struct inode_test_blk { + bool in_use; + bool in_cache; + ext4_fsblk_t blocknr; + struct buffer_head bh; + char cache_buf[INODE_TEST_BLK_SIZE] __aligned(8); + char disk_buf[INODE_TEST_BLK_SIZE] __aligned(8); +}; + +struct inode_test_ctx { + struct super_block *sb; + struct ext4_sb_info sbi; + struct ext4_super_block es; + struct ext4_group_desc gdp; + struct block_device bdev; + struct request_queue bdev_queue; + struct inode bd_inode; + struct buffer_head sb_bh; + struct dentry root_dentry; + + struct ext4_inode_info ei; + struct ext4_inode_info scratch_ei; + union { + struct ext4_inode raw; + u8 bytes[INODE_TEST_INODE_SIZE]; + } scratch_raw; + struct inode *tracked_inodes[INODE_TEST_MAX_TRACKED_INODES]; + unsigned int nr_tracked_inodes; + + struct inode_test_blk pool[INODE_TEST_POOL_SIZE]; + + bool fail_group_desc; + bool fail_getblk; + bool fail_read_eio; + int fail_zeroout_err; + int fail_alloc_err; + int fail_orphan_err; + + ext4_fsblk_t next_alloc_pblk; + unsigned int alloc_calls; + unsigned int free_calls; + ext4_fsblk_t last_free_pblk; + unsigned long last_free_count; + unsigned long total_freed_blocks; + unsigned int zeroout_calls; + ext4_lblk_t last_zeroout_lblk; + ext4_fsblk_t last_zeroout_pblk; + ext4_lblk_t last_zeroout_len; + unsigned int read_nowait_calls; + unsigned int read_lock_calls; + unsigned int readahead_calls; + ext4_fsblk_t first_readahead_blk; + ext4_fsblk_t last_readahead_blk; + unsigned int orphan_add_calls; + unsigned int orphan_del_calls; + unsigned int free_inode_calls; +}; + +static unsigned long inode_test_shrinker_count(struct shrinker *shrink, + struct shrink_control *sc) +{ + return 0; +} + +static unsigned long inode_test_shrinker_scan(struct shrinker *shrink, + struct shrink_control *sc) +{ + return SHRINK_STOP; +} + +static void inode_test_init_ei_fields(struct ext4_inode_info *ei) +{ + inode_set_iversion(&ei->vfs_inode, 1); + ei->i_flags = 0; + ext4_clear_state_flags(ei); + spin_lock_init(&ei->i_raw_lock); + ei->i_prealloc_node = RB_ROOT; + atomic_set(&ei->i_prealloc_active, 0); + rwlock_init(&ei->i_prealloc_lock); + ext4_es_init_tree(&ei->i_es_tree); + rwlock_init(&ei->i_es_lock); + INIT_LIST_HEAD(&ei->i_es_list); + ei->i_es_all_nr = 0; + ei->i_es_shk_nr = 0; + ei->i_es_shrink_lblk = 0; + ei->i_es_seq = 0; + ei->i_reserved_data_blocks = 0; + spin_lock_init(&ei->i_block_reservation_lock); + ext4_init_pending_tree(&ei->i_pending_tree); +#ifdef CONFIG_QUOTA + ei->i_reserved_quota = 0; + memset(&ei->i_dquot, 0, sizeof(ei->i_dquot)); +#endif + ei->jinode = NULL; + init_rwsem(&ei->xattr_sem); + INIT_LIST_HEAD(&ei->i_rsv_conversion_list); + spin_lock_init(&ei->i_completed_io_lock); + ei->i_sync_tid = 0; + ei->i_datasync_tid = 0; + INIT_WORK(&ei->i_rsv_conversion_work, ext4_end_io_rsv_work); + INIT_LIST_HEAD(&ei->i_orphan); + ext4_fc_init_inode(&ei->vfs_inode); + spin_lock_init(&ei->i_fc_lock); + ei->i_metadata_bhs = NULL; + ei->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + ei->i_extra_isize = INODE_TEST_EXTRA_ISIZE; + ei->i_csum_seed = INODE_TEST_CSUM_SEED; +} + +static void inode_test_cleanup_ext4_trees(struct inode *inode) +{ + struct ext4_inode_info *ei = EXT4_I(inode); + struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); + struct rb_node *node; + + down_write(&ei->i_data_sem); + ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS); + while ((node = rb_first(&ei->i_pending_tree.root)) != NULL) { + struct pending_reservation *pr; + + pr = rb_entry(node, struct pending_reservation, rb_node); + ext4_remove_pending(inode, EXT4_C2B(sbi, pr->lclu)); + } + up_write(&ei->i_data_sem); +} + +static struct inode *inode_test_alloc_inode(struct super_block *sb) +{ + struct ext4_inode_info *ei; + + ei = kzalloc_obj(*ei); + if (!ei) + return NULL; + + init_rwsem(&ei->i_data_sem); + inode_init_once(&ei->vfs_inode); + inode_test_init_ei_fields(ei); + return &ei->vfs_inode; +} + +static void inode_test_destroy_inode(struct inode *inode) +{ + inode_test_cleanup_ext4_trees(inode); + kfree(ext4_i_metadata_bhs(inode)); + EXT4_I(inode)->i_metadata_bhs = NULL; +} + +static void inode_test_free_inode(struct inode *inode) +{ + kfree(EXT4_I(inode)); +} + +#ifdef CONFIG_QUOTA +static struct dquot __rcu **inode_test_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} + +static qsize_t *inode_test_get_reserved_space(struct inode *inode) +{ + return &EXT4_I(inode)->i_reserved_quota; +} + +static const struct dquot_operations inode_test_qops = { + .get_reserved_space = inode_test_get_reserved_space, +}; +#endif + +static const struct super_operations inode_test_sops = { + .alloc_inode = inode_test_alloc_inode, + .evict_inode = ext4_evict_inode, + .destroy_inode = inode_test_destroy_inode, + .free_inode = inode_test_free_inode, + .drop_inode = inode_just_drop, +#ifdef CONFIG_QUOTA + .get_dquots = inode_test_get_dquots, +#endif +}; + +static int inode_test_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static struct file_system_type inode_test_fs_type = { + .name = "ext4_inode_kunit", + .init_fs_context = inode_test_init_fs_context, + .kill_sb = kill_anon_super, +}; + +static struct inode_test_blk *inode_test_find_blk(struct inode_test_ctx *ctx, + ext4_fsblk_t blocknr) +{ + int i; + + for (i = 0; i < INODE_TEST_POOL_SIZE; i++) { + if (ctx->pool[i].in_use && ctx->pool[i].blocknr == blocknr) + return &ctx->pool[i]; + } + return NULL; +} + +static struct inode_test_blk *inode_test_find_blk_by_bh( + struct inode_test_ctx *ctx, struct buffer_head *bh) +{ + int i; + + for (i = 0; i < INODE_TEST_POOL_SIZE; i++) { + if (ctx->pool[i].in_use && &ctx->pool[i].bh == bh) + return &ctx->pool[i]; + } + return NULL; +} + +static struct inode_test_blk *inode_test_setup_blk(struct inode_test_ctx *ctx, + int idx, + ext4_fsblk_t blocknr, + bool in_cache, + bool uptodate) +{ + struct inode_test_blk *slot = &ctx->pool[idx]; + + memset(slot, 0, sizeof(*slot)); + slot->in_use = true; + slot->in_cache = in_cache; + slot->blocknr = blocknr; + slot->bh.b_bdev = &ctx->bdev; + slot->bh.b_blocknr = blocknr; + slot->bh.b_size = INODE_TEST_BLK_SIZE; + slot->bh.b_data = slot->cache_buf; + atomic_set(&slot->bh.b_count, 1); + if (uptodate) + set_buffer_uptodate(&slot->bh); + return slot; +} + +/* --- Static Stubs --- */ + +static struct ext4_group_desc *inode_test_get_group_desc_stub( + struct super_block *sb, ext4_group_t block_group, + struct buffer_head **bh) +{ + struct kunit *test = kunit_get_current_test(); + struct inode_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx || ctx->fail_group_desc || block_group != 0) + return NULL; + if (bh) + *bh = NULL; + return &ctx->gdp; +} + +static struct buffer_head *inode_test_sb_getblk_stub(struct super_block *sb, + ext4_fsblk_t block) +{ + struct kunit *test = kunit_get_current_test(); + struct inode_test_ctx *ctx = test ? test->priv : NULL; + struct inode_test_blk *slot; + + if (!ctx || ctx->fail_getblk) + return NULL; + slot = inode_test_find_blk(ctx, block); + if (!slot) + return NULL; + slot->in_cache = true; + get_bh(&slot->bh); + return &slot->bh; +} + +static struct buffer_head *inode_test_sb_find_get_block_stub( + struct super_block *sb, ext4_fsblk_t block) +{ + struct kunit *test = kunit_get_current_test(); + struct inode_test_ctx *ctx = test ? test->priv : NULL; + struct inode_test_blk *slot; + + if (!ctx) + return NULL; + slot = inode_test_find_blk(ctx, block); + if (!slot || !slot->in_cache) + return NULL; + get_bh(&slot->bh); + return &slot->bh; +} + +static struct buffer_head *inode_test_sb_getblk_unmovable_stub( + struct super_block *sb, ext4_fsblk_t block) +{ + return inode_test_sb_getblk_stub(sb, block); +} + +static struct buffer_head *inode_test_ext_getblk_stub(struct inode *inode, + ext4_fsblk_t pblk, + gfp_t gfp_flags) +{ + struct buffer_head *bh; + + bh = inode_test_sb_getblk_stub(inode->i_sb, pblk); + if (bh) { + set_buffer_uptodate(bh); + set_buffer_verified(bh); + } + return bh; +} + +static void inode_test_read_bh_nowait_stub(struct buffer_head *bh, + blk_opf_t op_flags, + bio_end_io_t end_io, + bool simu_fail) +{ + struct kunit *test = kunit_get_current_test(); + struct inode_test_ctx *ctx = test ? test->priv : NULL; + struct inode_test_blk *slot; + + if (!ctx) { + unlock_buffer(bh); + return; + } + ctx->read_nowait_calls++; + if (ctx->fail_read_eio || simu_fail) { + clear_buffer_uptodate(bh); + unlock_buffer(bh); + return; + } + slot = inode_test_find_blk_by_bh(ctx, bh); + if (!slot) + slot = inode_test_find_blk(ctx, bh->b_blocknr); + if (slot) { + if (bh->b_folio) + memcpy_to_folio(bh->b_folio, bh_offset(bh), + slot->disk_buf, bh->b_size); + else + memcpy(bh->b_data, slot->disk_buf, bh->b_size); + set_buffer_uptodate(bh); + } else { + clear_buffer_uptodate(bh); + } + unlock_buffer(bh); +} + +static int inode_test_read_bh_lock_stub(struct buffer_head *bh, + blk_opf_t op_flags, bool wait) +{ + struct kunit *test = kunit_get_current_test(); + struct inode_test_ctx *ctx = test ? test->priv : NULL; + struct inode_test_blk *slot; + + if (!ctx) + return -EIO; + ctx->read_lock_calls++; + lock_buffer(bh); + if (ctx->fail_read_eio) { + clear_buffer_uptodate(bh); + unlock_buffer(bh); + return wait ? -EIO : 0; + } + slot = inode_test_find_blk_by_bh(ctx, bh); + if (!slot) + slot = inode_test_find_blk(ctx, bh->b_blocknr); + if (!slot) { + clear_buffer_uptodate(bh); + unlock_buffer(bh); + return wait ? -EIO : 0; + } + if (bh->b_folio) + memcpy_to_folio(bh->b_folio, bh_offset(bh), slot->disk_buf, + bh->b_size); + else + memcpy(bh->b_data, slot->disk_buf, bh->b_size); + set_buffer_uptodate(bh); + unlock_buffer(bh); + return 0; +} + +static void inode_test_breadahead_stub(struct super_block *sb, sector_t block) +{ + struct kunit *test = kunit_get_current_test(); + struct inode_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) + return; + if (ctx->readahead_calls == 0) + ctx->first_readahead_blk = block; + ctx->last_readahead_blk = block; + ctx->readahead_calls++; +} + +static ext4_fsblk_t inode_test_mb_new_blocks_stub( + handle_t *handle, struct ext4_allocation_request *ar, int *errp) +{ + struct kunit *test = kunit_get_current_test(); + struct inode_test_ctx *ctx = test ? test->priv : NULL; + ext4_fsblk_t pblk; + + if (!ctx) { + *errp = -EIO; + return 0; + } + if (ctx->fail_alloc_err) { + *errp = ctx->fail_alloc_err; + return 0; + } + ctx->alloc_calls++; + pblk = ctx->next_alloc_pblk; + ctx->next_alloc_pblk += ar->len; + *errp = 0; + return pblk; +} + +static void inode_test_free_blocks_stub(handle_t *handle, struct inode *inode, + struct buffer_head *bh, + ext4_fsblk_t block, + unsigned long count, int flags) +{ + struct kunit *test = kunit_get_current_test(); + struct inode_test_ctx *ctx = test ? test->priv : NULL; + + if (bh && (flags & EXT4_FREE_BLOCKS_FORGET)) + brelse(bh); + if (!ctx) + return; + ctx->free_calls++; + ctx->last_free_pblk = block; + ctx->last_free_count = count; + ctx->total_freed_blocks += count; +} + +static int inode_test_issue_zeroout_stub(handle_t *handle, struct inode *inode, + ext4_lblk_t lblk, ext4_fsblk_t pblk, + ext4_lblk_t len) +{ + struct kunit *test = kunit_get_current_test(); + struct inode_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) + return -EIO; + ctx->zeroout_calls++; + ctx->last_zeroout_lblk = lblk; + ctx->last_zeroout_pblk = pblk; + ctx->last_zeroout_len = len; + return ctx->fail_zeroout_err; +} + +static int inode_test_dirty_metadata_stub(const char *where, unsigned int line, + handle_t *handle, + struct inode *inode, + struct buffer_head *bh) +{ + if (bh) { + set_buffer_uptodate(bh); + set_buffer_dirty(bh); + } + return 0; +} + +static int inode_test_ext_dirty_stub(const char *where, unsigned int line, + handle_t *handle, struct inode *inode, + struct ext4_ext_path *path) +{ + if (path && path->p_bh) { + ext4_extent_block_csum_set_test(inode, + ext_block_hdr(path->p_bh)); + set_buffer_verified(path->p_bh); + } + return 0; +} + +static int inode_test_orphan_add_stub(handle_t *handle, struct inode *inode) +{ + struct kunit *test = kunit_get_current_test(); + struct inode_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) + return -EIO; + if (ctx->fail_orphan_err) + return ctx->fail_orphan_err; + ctx->orphan_add_calls++; + return 0; +} + +static int inode_test_orphan_del_stub(handle_t *handle, struct inode *inode) +{ + struct kunit *test = kunit_get_current_test(); + struct inode_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) + return -EIO; + ctx->orphan_del_calls++; + return 0; +} + +static void inode_test_free_inode_stub(handle_t *handle, struct inode *inode) +{ + struct kunit *test = kunit_get_current_test(); + struct inode_test_ctx *ctx = test ? test->priv : NULL; + + if (ctx) + ctx->free_inode_calls++; + ext4_clear_inode(inode); +} + +/* --- Fixture Setup & Cleanup --- */ + +static void inode_test_track_iget_inode(struct kunit *test, + struct inode_test_ctx *ctx, + struct inode *inode) +{ + KUNIT_ASSERT_LT(test, ctx->nr_tracked_inodes, + (unsigned int)INODE_TEST_MAX_TRACKED_INODES); + ctx->tracked_inodes[ctx->nr_tracked_inodes++] = inode; +} + +static void inode_test_put_tracked_inode(struct inode_test_ctx *ctx, + struct inode *inode) +{ + unsigned int i; + + for (i = 0; i < ctx->nr_tracked_inodes; i++) { + if (ctx->tracked_inodes[i] == inode) { + ctx->tracked_inodes[i] = + ctx->tracked_inodes[--ctx->nr_tracked_inodes]; + ctx->tracked_inodes[ctx->nr_tracked_inodes] = NULL; + iput(inode); + return; + } + } + iput(inode); +} + +static void inode_test_reset_mock_inode(struct inode_test_ctx *ctx, umode_t mode) +{ + struct ext4_inode_info *ei = &ctx->ei; + struct inode *inode = &ei->vfs_inode; + struct mapping_metadata_bhs *mmb = ext4_i_metadata_bhs(inode); + + truncate_inode_pages_final(&inode->i_data); + inode_io_list_del(inode); + ext4_fc_del(inode); + if (mmb) + mmb_invalidate(mmb); + inode_test_cleanup_ext4_trees(inode); + if (ei->jinode) { + jbd2_free_inode(ei->jinode); + ei->jinode = NULL; + } + + inode_state_assign_raw(inode, 0); + inode->i_ino = INODE_TEST_PRIMARY_INO; + inode->i_mode = mode; + inode->i_blkbits = ctx->sb->s_blocksize_bits; + inode->i_flags = S_NOQUOTA; + set_nlink(inode, 1); + i_uid_write(inode, 0); + i_gid_write(inode, 0); + inode->i_size = 0; + inode->i_blocks = 0; + inode->i_generation = 1; + inode->i_rdev = 0; + ei->i_disksize = 0; + ei->i_flags = 0; + ei->i_file_acl = 0; + ei->i_dtime = 0; + ei->i_inline_off = 0; + ei->i_inline_size = 0; + ei->i_extra_isize = INODE_TEST_EXTRA_ISIZE; + ei->i_reserved_data_blocks = 0; + ei->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + ext4_clear_state_flags(ei); + memset(ei->i_data, 0, sizeof(ei->i_data)); + + if (S_ISREG(mode) || S_ISDIR(mode)) { + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + ext4_ext_tree_init(NULL, inode); + } + if (S_ISREG(mode)) + ext4_set_aops(inode); +} + +static void inode_test_cleanup(void *data) +{ + struct inode_test_ctx *ctx = data; + struct inode *inode = &ctx->ei.vfs_inode; + struct mapping_metadata_bhs *mmb; + unsigned int i; + + ctx->sbi.s_journal = NULL; + + for (i = 0; i < ctx->nr_tracked_inodes; i++) { + struct inode *ti = ctx->tracked_inodes[i]; + + if (ti) { + spin_lock(&ti->i_lock); + inode_state_clear(ti, I_DIRTY_TIME); + spin_unlock(&ti->i_lock); + iput(ti); + ctx->tracked_inodes[i] = NULL; + } + } + ctx->nr_tracked_inodes = 0; + + truncate_inode_pages_final(&inode->i_data); + inode_io_list_del(inode); + ext4_fc_del(inode); + mmb = ext4_i_metadata_bhs(inode); + if (mmb) + mmb_invalidate(mmb); + inode_test_cleanup_ext4_trees(inode); + if (ctx->ei.jinode) { + jbd2_free_inode(ctx->ei.jinode); + ctx->ei.jinode = NULL; + } + + deactivate_super(ctx->sb); + rcu_barrier(); + + ext4_es_unregister_shrinker(&ctx->sbi); + ext4_es_destroy_stats(&ctx->sbi); + percpu_counter_destroy(&ctx->sbi.s_dirtyclusters_counter); + percpu_counter_destroy(&ctx->sbi.s_freeclusters_counter); + + kfree(mmb); + kfree(ctx); +} + +static struct inode_test_ctx *inode_test_setup(struct kunit *test) +{ + struct inode_test_ctx *ctx; + struct fs_context *fc; + struct super_block *sb; + struct ext4_sb_info *sbi; + struct inode *inode, *root_inode; + int err, i; + + ctx = kzalloc_obj(*ctx); + KUNIT_ASSERT_NOT_NULL(test, ctx); + test->priv = ctx; + + fc = fs_context_for_mount(&inode_test_fs_type, 0); + if (IS_ERR(fc)) { + err = PTR_ERR(fc); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + sb = sget_fc(fc, NULL, set_anon_super_fc); + put_fs_context(fc); + if (IS_ERR(sb)) { + err = PTR_ERR(sb); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + ctx->sb = sb; + sbi = &ctx->sbi; + + sbi->s_sb = sb; + sb->s_fs_info = sbi; + sb->s_op = &inode_test_sops; +#ifdef CONFIG_QUOTA + sb->dq_op = &inode_test_qops; +#endif +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; +#endif + sb->s_blocksize = INODE_TEST_BLK_SIZE; + sb->s_blocksize_bits = INODE_TEST_BLK_BITS; + sb->s_maxbytes = MAX_LFS_FILESIZE; + sb->s_time_gran = 1; + sb->s_xattr = ext4_xattr_handlers; + strscpy(sb->s_id, "ext4_inode_kunit", sizeof(sb->s_id)); + + inode_init_once(&ctx->bd_inode); + ctx->bd_inode.i_sb = sb; + ctx->bd_inode.i_blkbits = INODE_TEST_BLK_BITS; + ctx->bd_inode.i_mapping = &ctx->bd_inode.i_data; + ctx->bd_inode.i_data.host = &ctx->bd_inode; + ctx->bdev_queue.limits.logical_block_size = 512; + ctx->bdev_queue.limits.dma_alignment = 511; + ctx->bdev.bd_queue = &ctx->bdev_queue; + ctx->bdev.bd_mapping = &ctx->bd_inode.i_data; + bdev_set_flag(&ctx->bdev, BD_READ_ONLY); + sb->s_bdev = &ctx->bdev; + + sbi->s_es = &ctx->es; + ctx->es.s_magic = cpu_to_le16(EXT4_SUPER_MAGIC); + ctx->es.s_first_data_block = cpu_to_le32(1); + ctx->es.s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + ctx->es.s_creator_os = cpu_to_le32(EXT4_OS_LINUX); + ctx->es.s_inodes_count = cpu_to_le32(INODE_TEST_INODES_PER_GRP); + ctx->es.s_inodes_per_group = cpu_to_le32(INODE_TEST_INODES_PER_GRP); + ctx->es.s_first_ino = cpu_to_le32(INODE_TEST_FIRST_INO); + ctx->es.s_inode_size = cpu_to_le16(INODE_TEST_INODE_SIZE); + ctx->es.s_min_extra_isize = cpu_to_le16(INODE_TEST_EXTRA_ISIZE); + ctx->es.s_want_extra_isize = cpu_to_le16(INODE_TEST_EXTRA_ISIZE); + ctx->es.s_checksum_type = EXT4_CRC32C_CHKSUM; + ext4_blocks_count_set(&ctx->es, INODE_TEST_TOTAL_BLKS); + ext4_set_feature_extents(sb); + ext4_set_feature_extra_isize(sb); + ext4_set_feature_metadata_csum(sb); + ext4_set_feature_64bit(sb); + ext4_set_feature_huge_file(sb); + ext4_set_feature_large_file(sb); + ext4_set_feature_dir_index(sb); + + ctx->sb_bh.b_data = (char *)&ctx->es; + ctx->sb_bh.b_size = sizeof(ctx->es); + ctx->sb_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->sb_bh.b_count, 1); + set_buffer_uptodate(&ctx->sb_bh); + sbi->s_sbh = &ctx->sb_bh; + + sbi->s_inode_size = INODE_TEST_INODE_SIZE; + sbi->s_inodes_per_block = INODE_TEST_INODES_PER_BLK; + sbi->s_inodes_per_group = INODE_TEST_INODES_PER_GRP; + sbi->s_first_ino = INODE_TEST_FIRST_INO; + sbi->s_want_extra_isize = INODE_TEST_EXTRA_ISIZE; + sbi->s_blocks_per_group = INODE_TEST_TOTAL_BLKS; + sbi->s_clusters_per_group = INODE_TEST_TOTAL_BLKS; + sbi->s_cluster_ratio = 1; + sbi->s_cluster_bits = 0; + sbi->s_groups_count = 1; + sbi->s_gdb_count = 1; + sbi->s_desc_size = EXT4_MIN_DESC_SIZE_64BIT; + sbi->s_desc_per_block = INODE_TEST_BLK_SIZE / EXT4_MIN_DESC_SIZE_64BIT; + sbi->s_bitmap_maxbytes = 0x1ff7ffff000ULL; + sbi->s_extent_max_zeroout_kb = 32; + sbi->s_csum_seed = INODE_TEST_CSUM_SEED; + + ext4_inode_bitmap_set(sb, &ctx->gdp, INODE_TEST_IBITMAP_BLK); + ext4_inode_table_set(sb, &ctx->gdp, INODE_TEST_ITABLE_BLK0); + + set_opt(sb, ERRORS_CONT); + set_opt(sb, ORDERED_DATA); + set_opt(sb, DELALLOC); + set_opt(sb, XATTR_USER); + spin_lock_init(&sbi->s_bdev_wb_lock); + spin_lock_init(&sbi->s_error_lock); + spin_lock_init(&sbi->s_md_lock); + mutex_init(&sbi->s_fc_lock); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_STAGING]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_STAGING]); + + ratelimit_state_init(&sbi->s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + + err = percpu_counter_init(&sbi->s_freeclusters_counter, + max_t(s64, 4096, + EXT4_FREECLUSTERS_WATERMARK + 1024), + GFP_KERNEL); + if (err) { + deactivate_locked_super(sb); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + err = percpu_counter_init(&sbi->s_dirtyclusters_counter, 0, + GFP_KERNEL); + if (err) { + percpu_counter_destroy(&sbi->s_freeclusters_counter); + deactivate_locked_super(sb); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + err = ext4_es_register_shrinker(sbi); + if (err) { + percpu_counter_destroy(&sbi->s_dirtyclusters_counter); + percpu_counter_destroy(&sbi->s_freeclusters_counter); + deactivate_locked_super(sb); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + sbi->s_es_shrinker->count_objects = inode_test_shrinker_count; + sbi->s_es_shrinker->scan_objects = inode_test_shrinker_scan; + + /* Initialize mock block pool */ + inode_test_setup_blk(ctx, 0, INODE_TEST_IBITMAP_BLK, true, true); + inode_test_setup_blk(ctx, 1, INODE_TEST_ITABLE_BLK0, true, true); + inode_test_setup_blk(ctx, 2, INODE_TEST_ITABLE_BLK1, true, true); + inode_test_setup_blk(ctx, 3, INODE_TEST_META_BLK0, true, true); + inode_test_setup_blk(ctx, 4, INODE_TEST_META_BLK1, true, true); + for (i = 0; i < INODE_TEST_DATA_NBLKS; i++) + inode_test_setup_blk(ctx, 5 + i, INODE_TEST_DATA_BLK0 + i, + true, true); + ctx->next_alloc_pblk = INODE_TEST_DATA_BLK0; + + /* Initialize standalone mock inode */ + inode = &ctx->ei.vfs_inode; + init_rwsem(&ctx->ei.i_data_sem); + inode_init_once(inode); + inode->i_sb = sb; + inode->i_mapping = &inode->i_data; + inode->i_data.host = inode; + mapping_set_gfp_mask(&inode->i_data, GFP_HIGHUSER_MOVABLE); + init_rwsem(&inode->i_rwsem); + init_rwsem(&inode->i_data.invalidate_lock); + spin_lock_init(&inode->i_lock); + inode->__i_nlink = 1; + atomic_set(&inode->i_count, 1); + inode_test_init_ei_fields(&ctx->ei); + + ctx->root_dentry.d_sb = sb; + ctx->root_dentry.d_inode = inode; + + root_inode = new_inode(sb); + if (!root_inode) { + ext4_es_unregister_shrinker(sbi); + ext4_es_destroy_stats(sbi); + percpu_counter_destroy(&sbi->s_dirtyclusters_counter); + percpu_counter_destroy(&sbi->s_freeclusters_counter); + deactivate_locked_super(sb); + kfree(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to allocate root inode"); + } + root_inode->i_ino = EXT4_ROOT_INO; + root_inode->i_mode = S_IFDIR | 0755; + set_nlink(root_inode, 2); + sb->s_root = d_make_root(root_inode); + if (!sb->s_root) { + ext4_es_unregister_shrinker(sbi); + ext4_es_destroy_stats(sbi); + percpu_counter_destroy(&sbi->s_dirtyclusters_counter); + percpu_counter_destroy(&sbi->s_freeclusters_counter); + deactivate_locked_super(sb); + kfree(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to allocate root dentry"); + } + sb->s_flags |= SB_ACTIVE; + + up_write(&sb->s_umount); + + kunit_activate_static_stub(test, ext4_get_group_desc, + inode_test_get_group_desc_stub); + kunit_activate_static_stub(test, ext4_sb_getblk, + inode_test_sb_getblk_stub); + kunit_activate_static_stub(test, ext4_sb_find_get_block, + inode_test_sb_find_get_block_stub); + kunit_activate_static_stub(test, ext4_sb_find_get_block_nonatomic, + inode_test_sb_find_get_block_stub); + kunit_activate_static_stub(test, ext4_sb_getblk_unmovable, + inode_test_sb_getblk_unmovable_stub); + kunit_activate_static_stub(test, ext4_ext_getblk, + inode_test_ext_getblk_stub); + kunit_activate_static_stub(test, ext4_read_bh_nowait, + inode_test_read_bh_nowait_stub); + kunit_activate_static_stub(test, ext4_read_bh_lock, + inode_test_read_bh_lock_stub); + kunit_activate_static_stub(test, ext4_sb_breadahead_unmovable, + inode_test_breadahead_stub); + kunit_activate_static_stub(test, ext4_mb_new_blocks, + inode_test_mb_new_blocks_stub); + kunit_activate_static_stub(test, ext4_free_blocks, + inode_test_free_blocks_stub); + kunit_activate_static_stub(test, ext4_issue_zeroout, + inode_test_issue_zeroout_stub); + kunit_activate_static_stub(test, __ext4_handle_dirty_metadata, + inode_test_dirty_metadata_stub); + kunit_activate_static_stub(test, __ext4_ext_dirty, + inode_test_ext_dirty_stub); + kunit_activate_static_stub(test, ext4_orphan_add, + inode_test_orphan_add_stub); + kunit_activate_static_stub(test, ext4_orphan_del, + inode_test_orphan_del_stub); + kunit_activate_static_stub(test, ext4_free_inode, + inode_test_free_inode_stub); + + err = kunit_add_action_or_reset(test, inode_test_cleanup, ctx); + KUNIT_ASSERT_EQ(test, err, 0); + + inode_test_reset_mock_inode(ctx, S_IFREG | 0644); + + return ctx; +} + +static struct ext4_inode *inode_test_raw_slot(struct inode_test_ctx *ctx, + unsigned long ino, bool disk) +{ + unsigned int grp_off = (ino - 1) % INODE_TEST_INODES_PER_GRP; + ext4_fsblk_t blk = INODE_TEST_ITABLE_BLK0 + + (grp_off / INODE_TEST_INODES_PER_BLK); + unsigned int byte_off = (grp_off % INODE_TEST_INODES_PER_BLK) * + INODE_TEST_INODE_SIZE; + struct inode_test_blk *slot = inode_test_find_blk(ctx, blk); + char *base = disk ? slot->disk_buf : slot->cache_buf; + + return (struct ext4_inode *)(base + byte_off); +} + +static void inode_test_stamp_raw_csum(struct inode_test_ctx *ctx, + unsigned long ino, + struct ext4_inode *raw) +{ + struct ext4_inode_info *tmp_ei = &ctx->scratch_ei; + struct inode *tmp_inode = &tmp_ei->vfs_inode; + __le32 inum = cpu_to_le32(ino); + __le32 gen = raw->i_generation; + u32 csum; + + memset(tmp_ei, 0, sizeof(*tmp_ei)); + tmp_inode->i_sb = ctx->sb; + tmp_inode->i_ino = ino; + tmp_ei->i_extra_isize = le16_to_cpu(raw->i_extra_isize); + csum = ext4_chksum(ctx->sbi.s_csum_seed, (u8 *)&inum, sizeof(inum)); + tmp_ei->i_csum_seed = ext4_chksum(csum, (u8 *)&gen, sizeof(gen)); + ext4_inode_csum_set(tmp_inode, raw, tmp_ei); +} + +static void inode_test_prepare_valid_raw_inode(struct inode_test_ctx *ctx, + unsigned long ino, umode_t mode) +{ + struct inode_test_blk *slot; + struct ext4_inode *raw; + struct ext4_extent_header *eh; + unsigned int grp_off = (ino - 1) % INODE_TEST_INODES_PER_GRP; + ext4_fsblk_t blk = INODE_TEST_ITABLE_BLK0 + + (grp_off / INODE_TEST_INODES_PER_BLK); + + slot = inode_test_find_blk(ctx, blk); + clear_buffer_uptodate(&slot->bh); + raw = inode_test_raw_slot(ctx, ino, true); + memset(raw, 0, INODE_TEST_INODE_SIZE); + + raw->i_mode = cpu_to_le16(mode); + raw->i_links_count = cpu_to_le16(1); + raw->i_extra_isize = cpu_to_le16(INODE_TEST_EXTRA_ISIZE); + raw->i_generation = cpu_to_le32(7); + if (S_ISREG(mode) || S_ISDIR(mode)) { + raw->i_flags = cpu_to_le32(EXT4_EXTENTS_FL); + eh = (struct ext4_extent_header *)raw->i_block; + eh->eh_magic = EXT4_EXT_MAGIC; + eh->eh_entries = 0; + eh->eh_max = cpu_to_le16(4); + eh->eh_depth = 0; + } + inode_test_stamp_raw_csum(ctx, ino, raw); +} + +/* ------------------------------------------------------------------------- + * 1. Timestamp Encoding & Macro Round-Trip Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_xtimestamp_encoding_roundtrip(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct ext4_inode_info *ei = &ctx->ei; + struct inode *inode = &ei->vfs_inode; + struct ext4_inode *raw = &ctx->scratch_raw.raw; + struct timespec64 ts_in, ts_out; + size_t i; + + for (i = 0; i < ARRAY_SIZE(test_data); i++) { + __le32 encoded_extra = ext4_encode_extra_time(test_data[i].expected); + __le32 encoded_base = cpu_to_le32((s32)test_data[i].expected.tv_sec); + + KUNIT_EXPECT_EQ_MSG(test, le32_to_cpu(encoded_extra), + test_data[i].extra_bits, + "%s", test_data[i].test_case_name); + ts_out = ext4_decode_extra_time(encoded_base, encoded_extra); + KUNIT_EXPECT_EQ(test, ts_out.tv_sec, + test_data[i].expected.tv_sec); + KUNIT_EXPECT_EQ(test, ts_out.tv_nsec, + test_data[i].expected.tv_nsec); + } + + /* 256-byte inode with extra_isize = 32: full 34-bit + nsec round-trip */ + ts_in.tv_sec = 0x240001234LL; + ts_in.tv_nsec = 987654321L; + inode_set_atime_to_ts(inode, ts_in); + ts_in.tv_sec = 0x190005678LL; + ts_in.tv_nsec = 123456789L; + inode_set_mtime_to_ts(inode, ts_in); + ts_in.tv_sec = 0x310009abcLL; + ts_in.tv_nsec = 555666777L; + inode_set_ctime_to_ts(inode, ts_in); + ei->i_crtime.tv_sec = 0x22000def0LL; + ei->i_crtime.tv_nsec = 444333222L; + + EXT4_INODE_SET_ATIME(inode, raw); + EXT4_INODE_SET_MTIME(inode, raw); + EXT4_INODE_SET_CTIME(inode, raw); + EXT4_EINODE_SET_XTIME(i_crtime, ei, raw); + + inode_set_atime(inode, 0, 0); + inode_set_mtime(inode, 0, 0); + inode_set_ctime(inode, 0, 0); + ei->i_crtime = (struct timespec64){}; + + EXT4_INODE_GET_ATIME(inode, raw); + EXT4_INODE_GET_MTIME(inode, raw); + EXT4_INODE_GET_CTIME(inode, raw); + EXT4_EINODE_GET_XTIME(i_crtime, ei, raw); + + KUNIT_EXPECT_EQ(test, inode_get_atime_sec(inode), 0x240001234LL); + KUNIT_EXPECT_EQ(test, inode_get_atime_nsec(inode), 987654321L); + KUNIT_EXPECT_EQ(test, inode_get_mtime_sec(inode), 0x190005678LL); + KUNIT_EXPECT_EQ(test, inode_get_mtime_nsec(inode), 123456789L); + KUNIT_EXPECT_EQ(test, inode_get_ctime_sec(inode), 0x310009abcLL); + KUNIT_EXPECT_EQ(test, inode_get_ctime_nsec(inode), 555666777L); + KUNIT_EXPECT_EQ(test, ctx->ei.i_crtime.tv_sec, 0x22000def0LL); + KUNIT_EXPECT_EQ(test, ctx->ei.i_crtime.tv_nsec, 444333222L); + + /* 128-byte old inode: 32-bit signed seconds only, extra ignored, nsec=0 */ + ctx->sbi.s_inode_size = EXT4_GOOD_OLD_INODE_SIZE; + ctx->ei.i_extra_isize = 0; + memset(ctx->scratch_raw.bytes, 0, INODE_TEST_INODE_SIZE); + + inode_set_mtime(inode, S32_MAX, 500); + inode_set_atime(inode, S32_MIN, 700); + EXT4_INODE_SET_MTIME(inode, raw); + EXT4_INODE_SET_ATIME(inode, raw); + KUNIT_EXPECT_EQ(test, le32_to_cpu(raw->i_mtime_extra), 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(raw->i_atime_extra), 0U); + + inode_set_mtime(inode, 0, 999); + inode_set_atime(inode, 0, 999); + EXT4_INODE_GET_MTIME(inode, raw); + EXT4_INODE_GET_ATIME(inode, raw); + + KUNIT_EXPECT_EQ(test, inode_get_mtime_sec(inode), (time64_t)S32_MAX); + KUNIT_EXPECT_EQ(test, inode_get_mtime_nsec(inode), 0L); + KUNIT_EXPECT_EQ(test, inode_get_atime_sec(inode), (time64_t)S32_MIN); + KUNIT_EXPECT_EQ(test, inode_get_atime_nsec(inode), 0L); + + ctx->sbi.s_inode_size = INODE_TEST_INODE_SIZE; + ctx->ei.i_extra_isize = INODE_TEST_EXTRA_ISIZE; +} + +/* ------------------------------------------------------------------------- + * 2. Inode Checksum Calculation & Verification Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_csum_set_and_verify(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct ext4_inode *raw = &ctx->scratch_raw.raw; + + raw->i_mode = cpu_to_le16(S_IFREG | 0644); + raw->i_links_count = cpu_to_le16(1); + raw->i_extra_isize = cpu_to_le16(INODE_TEST_EXTRA_ISIZE); + + /* Full 32-bit checksum (256B inode, extra_isize = 32) */ + ext4_inode_csum_set(inode, raw, &ctx->ei); + KUNIT_EXPECT_EQ(test, ext4_inode_csum_verify_test(inode, raw, &ctx->ei), + 1); + + /* Bit flip in low 16 bits fails */ + raw->i_checksum_lo ^= cpu_to_le16(0x0001); + KUNIT_EXPECT_EQ(test, ext4_inode_csum_verify_test(inode, raw, &ctx->ei), + 0); + raw->i_checksum_lo ^= cpu_to_le16(0x0001); + + /* Bit flip in high 16 bits fails */ + raw->i_checksum_hi ^= cpu_to_le16(0x8000); + KUNIT_EXPECT_EQ(test, ext4_inode_csum_verify_test(inode, raw, &ctx->ei), + 0); + raw->i_checksum_hi ^= cpu_to_le16(0x8000); + + /* Bit flip in raw inode body and in-body xattr tail (byte 200) fails */ + raw->i_mode ^= cpu_to_le16(0x0002); + KUNIT_EXPECT_EQ(test, ext4_inode_csum_verify_test(inode, raw, &ctx->ei), + 0); + raw->i_mode ^= cpu_to_le16(0x0002); + ctx->scratch_raw.bytes[200] ^= 0x01; + KUNIT_EXPECT_EQ(test, ext4_inode_csum_verify_test(inode, raw, &ctx->ei), + 0); + ctx->scratch_raw.bytes[200] ^= 0x01; + KUNIT_EXPECT_EQ(test, ext4_inode_csum_verify_test(inode, raw, &ctx->ei), + 1); + + /* Non-Linux creator OS bypasses checksum verification */ + ctx->es.s_creator_os = cpu_to_le32(EXT4_OS_HURD); + raw->i_checksum_lo ^= cpu_to_le16(0xffff); + KUNIT_EXPECT_EQ(test, ext4_inode_csum_verify_test(inode, raw, &ctx->ei), + 1); + ctx->es.s_creator_os = cpu_to_le32(EXT4_OS_LINUX); + + /* Disabled metadata_csum feature bypasses checksum verification */ + ext4_clear_feature_metadata_csum(ctx->sb); + KUNIT_EXPECT_EQ(test, ext4_inode_csum_verify_test(inode, raw, &ctx->ei), + 1); + ext4_set_feature_metadata_csum(ctx->sb); + + /* 256B inode with extra_isize = 0 (excludes i_checksum_hi): 16-bit */ + memset(ctx->scratch_raw.bytes, 0, INODE_TEST_INODE_SIZE); + ctx->ei.i_extra_isize = 0; + raw->i_extra_isize = 0; + raw->i_checksum_hi = cpu_to_le16(0xbeef); + ext4_inode_csum_set(inode, raw, &ctx->ei); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_checksum_hi), 0xbeef); + KUNIT_EXPECT_EQ(test, ext4_inode_csum_verify_test(inode, raw, &ctx->ei), + 1); + raw->i_checksum_lo ^= cpu_to_le16(0x0010); + KUNIT_EXPECT_EQ(test, ext4_inode_csum_verify_test(inode, raw, &ctx->ei), + 0); + + /* 256B inode with extra_isize = 4 (includes i_checksum_hi): 32-bit */ + memset(ctx->scratch_raw.bytes, 0, INODE_TEST_INODE_SIZE); + ctx->ei.i_extra_isize = 4; + raw->i_extra_isize = cpu_to_le16(4); + ext4_inode_csum_set(inode, raw, &ctx->ei); + KUNIT_EXPECT_EQ(test, ext4_inode_csum_verify_test(inode, raw, &ctx->ei), + 1); + raw->i_checksum_hi ^= cpu_to_le16(0x0001); + KUNIT_EXPECT_EQ(test, ext4_inode_csum_verify_test(inode, raw, &ctx->ei), + 0); + + /* 128B old inode: 16-bit checksum in i_checksum_lo only */ + memset(ctx->scratch_raw.bytes, 0, INODE_TEST_INODE_SIZE); + ctx->sbi.s_inode_size = EXT4_GOOD_OLD_INODE_SIZE; + ctx->ei.i_extra_isize = 0; + ext4_inode_csum_set(inode, raw, &ctx->ei); + KUNIT_EXPECT_EQ(test, ext4_inode_csum_verify_test(inode, raw, &ctx->ei), + 1); + raw->i_checksum_lo ^= cpu_to_le16(0x0100); + KUNIT_EXPECT_EQ(test, ext4_inode_csum_verify_test(inode, raw, &ctx->ei), + 0); +} + +/* ------------------------------------------------------------------------- + * 3. i_blocks Encoding & Decoding Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_blocks_encode_decode(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct ext4_inode *raw = &ctx->scratch_raw.raw; + blkcnt_t large_sectors; + int err; + + /* 32-bit sector count clears EXT4_INODE_HUGE_FILE */ + ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE); + inode->i_blocks = 0x12345678ULL; + err = ext4_inode_blocks_set_test(raw, &ctx->ei); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(raw->i_blocks_lo), 0x12345678U); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_blocks_high), 0); + KUNIT_EXPECT_EQ(test, ext4_inode_blocks_test(raw, &ctx->ei), + (blkcnt_t)0x12345678ULL); + + /* > 32-bit without huge_file feature fails with -EFSCORRUPTED */ + ext4_clear_feature_huge_file(ctx->sb); + inode->i_blocks = 0x100000000ULL; + err = ext4_inode_blocks_set_test(raw, &ctx->ei); + KUNIT_EXPECT_EQ(test, err, -EFSCORRUPTED); + ext4_set_feature_huge_file(ctx->sb); + + /* 48-bit sector count with huge_file feature (still sector units) */ + ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE); + inode->i_blocks = 0xabcd12345678ULL; + err = ext4_inode_blocks_set_test(raw, &ctx->ei); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(raw->i_blocks_lo), 0x12345678U); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_blocks_high), 0xabcd); + KUNIT_EXPECT_EQ(test, ext4_inode_blocks_test(raw, &ctx->ei), + (blkcnt_t)0xabcd12345678ULL); + + /* > 48-bit sector count scales by fs-block units and sets HUGE_FILE */ + large_sectors = 0x0002000000000008ULL; /* multiple of 8 (4K / 512B) */ + inode->i_blocks = large_sectors; + err = ext4_inode_blocks_set_test(raw, &ctx->ei); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, + ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)); + KUNIT_EXPECT_EQ(test, ext4_inode_blocks_test(raw, &ctx->ei), + large_sectors); +} + +/* ------------------------------------------------------------------------- + * 4. Raw Inode Serialization (ext4_fill_raw_inode) Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_fill_raw_inode(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct ext4_inode *raw = &ctx->scratch_raw.raw; + dev_t small_dev, large_dev; + int err; + + /* 32-bit uid/gid, 48-bit file_acl, 64-bit disksize & iversion, projid */ + ext4_set_feature_project(ctx->sb); + i_uid_write(inode, 0x12345678U); + i_gid_write(inode, 0x9abcdef0U); + ctx->ei.i_projid = make_kprojid(&init_user_ns, 0x55aa1122U); + ctx->ei.i_file_acl = 0x000344556677ULL; + ctx->ei.i_disksize = 0x0000000511223344LL; + inode_set_iversion_queried(inode, 0x000000078899aabbULL); + + err = ext4_fill_raw_inode_test(inode, raw); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_uid_low), 0x5678); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_uid_high), 0x1234); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_gid_low), 0xdef0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_gid_high), 0x9abc); + KUNIT_EXPECT_EQ(test, le32_to_cpu(raw->i_projid), 0x55aa1122U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(raw->i_file_acl_lo), 0x44556677U); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_file_acl_high), 0x0003); + KUNIT_EXPECT_EQ(test, ext4_isize(ctx->sb, raw), 0x0000000511223344LL); + KUNIT_EXPECT_EQ(test, le32_to_cpu(raw->i_disk_version), 0x8899aabbU); + KUNIT_EXPECT_EQ(test, le32_to_cpu(raw->i_version_hi), 0x00000007U); + KUNIT_EXPECT_EQ(test, ext4_inode_csum_verify_test(inode, raw, &ctx->ei), + 1); + + /* Non-default projid without PROJECT feature returns -EFSCORRUPTED */ + ext4_clear_feature_project(ctx->sb); + err = ext4_fill_raw_inode_test(inode, raw); + KUNIT_EXPECT_EQ(test, err, -EFSCORRUPTED); + ctx->ei.i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + + /* NO_UID32 masks uid/gid high bits; HURD_COMPAT skips file_acl_high */ + memset(ctx->scratch_raw.bytes, 0, INODE_TEST_INODE_SIZE); + raw->osd2.hurd2.h_i_mode_high = 0x7777; + set_opt(ctx->sb, NO_UID32); + set_opt2(ctx->sb, HURD_COMPAT); + err = ext4_fill_raw_inode_test(inode, raw); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_uid_high), 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_gid_high), 0); + KUNIT_EXPECT_EQ(test, raw->osd2.hurd2.h_i_mode_high, 0x7777); + clear_opt(ctx->sb, NO_UID32); + clear_opt2(ctx->sb, HURD_COMPAT); + + /* Deleted inode (i_dtime != 0) clears uid_high/gid_high unless orphan */ + ctx->ei.i_dtime = 100; + err = ext4_fill_raw_inode_test(inode, raw); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_uid_high), 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_gid_high), 0); + + ext4_set_inode_state(inode, EXT4_STATE_ORPHAN_FILE); + err = ext4_fill_raw_inode_test(inode, raw); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_uid_high), 0x1234); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_gid_high), 0x9abc); + ext4_clear_inode_state(inode, EXT4_STATE_ORPHAN_FILE); + ctx->ei.i_dtime = 0; + + /* EA_INODE stores raw iversion without shifting out flag bit */ + ext4_set_inode_flag(inode, EXT4_INODE_EA_INODE); + inode_set_iversion_raw(inode, 0x00000002cafebabeULL); + err = ext4_fill_raw_inode_test(inode, raw); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(raw->i_disk_version), 0xcafebabeU); + KUNIT_EXPECT_EQ(test, le32_to_cpu(raw->i_version_hi), 0x00000002U); + ext4_clear_inode_flag(inode, EXT4_INODE_EA_INODE); + + /* Inline-data inode preserves raw_inode->i_block contents */ + memset(ctx->scratch_raw.bytes, 0, INODE_TEST_INODE_SIZE); + raw->i_block[0] = cpu_to_le32(0xdeadbeefU); + ctx->ei.i_data[0] = cpu_to_le32(0x11111111U); + ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS); + ext4_set_inode_flag(inode, EXT4_INODE_INLINE_DATA); + ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + ctx->ei.i_inline_off = 164; + err = ext4_fill_raw_inode_test(inode, raw); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(raw->i_block[0]), 0xdeadbeefU); + ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + ext4_clear_inode_flag(inode, EXT4_INODE_INLINE_DATA); + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + ctx->ei.i_inline_off = 0; + + /* Special device inode encodes old vs new rdev into i_block[0]/[1] */ + inode->i_mode = S_IFCHR | 0600; + small_dev = MKDEV(8, 3); + inode->i_rdev = small_dev; + err = ext4_fill_raw_inode_test(inode, raw); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, old_decode_dev(le32_to_cpu(raw->i_block[0])), + small_dev); + KUNIT_EXPECT_EQ(test, le32_to_cpu(raw->i_block[1]), 0U); + + large_dev = MKDEV(512, 1024); + inode->i_rdev = large_dev; + err = ext4_fill_raw_inode_test(inode, raw); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(raw->i_block[0]), 0U); + KUNIT_EXPECT_EQ(test, new_decode_dev(le32_to_cpu(raw->i_block[1])), + large_dev); +} + +/* ------------------------------------------------------------------------- + * 5. Inode Dirtying, LARGE_FILE Promotion, and Lazytime Neighbor Flush + * ------------------------------------------------------------------------- + */ + +static void inode_test_mark_dirty_and_update(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct inode_test_blk *itable = inode_test_find_blk(ctx, + INODE_TEST_ITABLE_BLK0); + struct ext4_inode *raw; + struct ext4_inode *neighbor_raw; + struct inode *neighbor; + struct ext4_iloc iloc = {}; + handle_t *handle; + int ref_before, err; + + /* + * 1. EXT4_STATE_NEW + LARGE_FILE feature promotion in + * ext4_reserve_inode_write() / ext4_mark_iloc_dirty(). + */ + ext4_clear_feature_large_file(ctx->sb); + ext4_set_inode_state(inode, EXT4_STATE_NEW); + ctx->ei.i_disksize = 0x100000000LL; + inode->i_size = ctx->ei.i_disksize; + raw = inode_test_raw_slot(ctx, INODE_TEST_PRIMARY_INO, false); + memset(raw, 0xff, INODE_TEST_INODE_SIZE); + + handle = ext4_journal_start(inode, EXT4_HT_INODE, 2); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + err = ext4_reserve_inode_write(handle, inode, &iloc); + KUNIT_ASSERT_EQ(test, err, 0); + err = ext4_mark_iloc_dirty(handle, inode, &iloc); + ext4_journal_stop(handle); + + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_FALSE(test, ext4_test_inode_state(inode, EXT4_STATE_NEW)); + KUNIT_EXPECT_TRUE(test, ext4_has_feature_large_file(ctx->sb)); + KUNIT_EXPECT_EQ(test, ext4_isize(ctx->sb, raw), 0x100000000LL); + KUNIT_EXPECT_TRUE(test, + !!(inode_state_read_once(inode) & I_METADATA_WRITEBACK)); + + /* + * 2. SB_LAZYTIME opportunistic neighbor timestamp flush + automatic + * extra_isize expansion via __ext4_mark_inode_dirty(). + */ + inode_test_prepare_valid_raw_inode(ctx, 13, S_IFREG | 0644); + memcpy(itable->cache_buf, itable->disk_buf, INODE_TEST_BLK_SIZE); + set_buffer_uptodate(&itable->bh); + + neighbor = ext4_iget(ctx->sb, 13, EXT4_IGET_NORMAL); + KUNIT_ASSERT_FALSE(test, IS_ERR(neighbor)); + inode_test_track_iget_inode(test, ctx, neighbor); + + inode_set_mtime(neighbor, 0x55667788LL, 1234); + spin_lock(&neighbor->i_lock); + inode_state_set(neighbor, I_DIRTY_TIME); + spin_unlock(&neighbor->i_lock); + + ctx->sb->s_flags |= SB_LAZYTIME; + ctx->ei.i_extra_isize = 16; + ctx->sbi.s_want_extra_isize = 32; + + handle = ext4_journal_start(inode, EXT4_HT_INODE, 2); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + err = __ext4_mark_inode_dirty(handle, inode, __func__, __LINE__); + ext4_journal_stop(handle); + ctx->sb->s_flags &= ~SB_LAZYTIME; + + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->ei.i_extra_isize, (u16)32); + KUNIT_EXPECT_FALSE(test, + !!(inode_state_read_once(neighbor) & I_DIRTY_TIME)); + neighbor_raw = inode_test_raw_slot(ctx, 13, false); + KUNIT_EXPECT_EQ(test, le32_to_cpu(neighbor_raw->i_mtime), 0x55667788U); + KUNIT_EXPECT_EQ(test, + ext4_inode_csum_verify_test(neighbor, neighbor_raw, + EXT4_I(neighbor)), 1); + + /* 3. ext4_dirty_inode() updates raw inode on I_DIRTY_SYNC */ + inode_set_ctime(inode, 0x12340000LL, 0); + ext4_dirty_inode(inode, I_DIRTY_SYNC); + KUNIT_EXPECT_EQ(test, le32_to_cpu(raw->i_ctime), 0x12340000U); + + /* 4. Emergency RO state returns -EROFS and drops iloc.bh cleanly */ + err = ext4_get_inode_loc(inode, &iloc); + KUNIT_ASSERT_EQ(test, err, 0); + ref_before = atomic_read(&itable->bh.b_count); + set_bit(EXT4_FLAGS_EMERGENCY_RO, &ctx->sbi.s_ext4_flags); + err = ext4_mark_iloc_dirty(NULL, inode, &iloc); + clear_bit(EXT4_FLAGS_EMERGENCY_RO, &ctx->sbi.s_ext4_flags); + KUNIT_EXPECT_EQ(test, err, -EROFS); + KUNIT_EXPECT_EQ(test, atomic_read(&itable->bh.b_count), ref_before - 1); +} + +/* ------------------------------------------------------------------------- + * 6. Extra Isize Expansion Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_expand_extra_isize(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct ext4_iloc iloc = {}; + struct ext4_inode *raw; + struct ext4_xattr_ibody_header *ihdr; + struct ext4_xattr_entry *entry; + int no_expand = 0; + int err; + + err = ext4_get_inode_loc(inode, &iloc); + KUNIT_ASSERT_EQ(test, err, 0); + raw = ext4_raw_inode(&iloc); + + /* Corrupted current i_extra_isize (unaligned or oversize) */ + ctx->ei.i_extra_isize = 13; + err = ext4_expand_extra_isize_test(inode, 32, &iloc, NULL, &no_expand); + KUNIT_EXPECT_EQ(test, err, -EFSCORRUPTED); + + ctx->ei.i_extra_isize = 200; + err = ext4_expand_extra_isize_test(inode, 204, &iloc, NULL, &no_expand); + KUNIT_EXPECT_EQ(test, err, -EFSCORRUPTED); + + /* Invalid target new_extra_isize */ + ctx->ei.i_extra_isize = 16; + KUNIT_EXPECT_EQ(test, + ext4_expand_extra_isize_test(inode, 12, &iloc, NULL, + &no_expand), -EINVAL); + KUNIT_EXPECT_EQ(test, + ext4_expand_extra_isize_test(inode, 200, &iloc, NULL, + &no_expand), -EINVAL); + + /* Clean expansion without xattrs zeroes newly covered extra space */ + memset((u8 *)raw + EXT4_GOOD_OLD_INODE_SIZE + 16, 0xaa, 32); + err = ext4_expand_extra_isize_test(inode, 32, &iloc, NULL, &no_expand); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->ei.i_extra_isize, (u16)32); + KUNIT_EXPECT_EQ(test, *((u8 *)raw + EXT4_GOOD_OLD_INODE_SIZE + 16), 0); + KUNIT_EXPECT_EQ(test, *((u8 *)raw + EXT4_GOOD_OLD_INODE_SIZE + 31), 0); + KUNIT_EXPECT_EQ(test, *((u8 *)raw + EXT4_GOOD_OLD_INODE_SIZE + 32), + 0xaa); + + /* Guard checks in ext4_try_to_expand_extra_isize() */ + ctx->ei.i_extra_isize = 16; + ext4_set_inode_state(inode, EXT4_STATE_NO_EXPAND); + KUNIT_EXPECT_EQ(test, + ext4_try_to_expand_extra_isize_test(inode, 32, &iloc, + NULL), -EOVERFLOW); + ext4_clear_inode_state(inode, EXT4_STATE_NO_EXPAND); + + ctx->sb->s_flags &= ~SB_ACTIVE; + KUNIT_EXPECT_EQ(test, + ext4_try_to_expand_extra_isize_test(inode, 32, &iloc, + NULL), -EBUSY); + ctx->sb->s_flags |= SB_ACTIVE; + + down_read(&ctx->ei.xattr_sem); + err = ext4_try_to_expand_extra_isize_test(inode, 32, &iloc, NULL); + up_read(&ctx->ei.xattr_sem); + KUNIT_EXPECT_EQ(test, err, -EBUSY); + + /* Expansion with valid in-body xattr shifts entry forward cleanly */ + memset(raw, 0, INODE_TEST_INODE_SIZE); + ctx->ei.i_extra_isize = 16; + raw->i_extra_isize = cpu_to_le16(16); + ext4_set_inode_state(inode, EXT4_STATE_XATTR); + ihdr = IHDR(inode, raw); + ihdr->h_magic = cpu_to_le32(EXT4_XATTR_MAGIC); + entry = IFIRST(ihdr); + entry->e_name_len = 1; + entry->e_name_index = EXT4_XATTR_INDEX_USER; + entry->e_name[0] = 'k'; + entry->e_value_size = cpu_to_le32(4); + entry->e_value_offs = cpu_to_le16(INODE_TEST_INODE_SIZE - + EXT4_GOOD_OLD_INODE_SIZE - 16 - + sizeof(__u32) - 4); + memcpy((char *)IFIRST(ihdr) + le16_to_cpu(entry->e_value_offs), + "val!", 4); + inode_test_stamp_raw_csum(ctx, inode->i_ino, raw); + + /* ext4_expand_extra_isize() locks xattr_sem and consumes iloc.bh */ + err = ext4_expand_extra_isize(inode, 32, &iloc); + ctx->sb->s_flags &= ~SB_ACTIVE; + + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->ei.i_extra_isize, (u16)32); + ihdr = IHDR(inode, raw); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ihdr->h_magic), + (u32)EXT4_XATTR_MAGIC); +} + +/* ------------------------------------------------------------------------- + * 7. Inode Location Lookup (get_inode_loc / noio / fc_inode_loc) Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_get_inode_loc_variants(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct inode_test_blk *itable = inode_test_find_blk(ctx, + INODE_TEST_ITABLE_BLK0); + struct inode_test_blk *ibitmap = inode_test_find_blk(ctx, + INODE_TEST_IBITMAP_BLK); + struct ext4_iloc iloc = {}; + struct ext4_inode *raw; + int err; + + /* Out-of-range inode numbers */ + inode->i_ino = 1; + KUNIT_EXPECT_EQ(test, ext4_get_inode_loc(inode, &iloc), -EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, ext4_get_inode_loc_noio(inode, &iloc), + -EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, ext4_get_fc_inode_loc(ctx->sb, 99999, &iloc), + -EFSCORRUPTED); + inode->i_ino = INODE_TEST_PRIMARY_INO; + + /* Missing group descriptor -> -EIO */ + ctx->fail_group_desc = true; + KUNIT_EXPECT_EQ(test, ext4_get_inode_loc(inode, &iloc), -EIO); + KUNIT_EXPECT_EQ(test, ext4_get_inode_loc_noio(inode, &iloc), -EIO); + ctx->fail_group_desc = false; + + /* Invalid inode table block in group descriptor -> -EFSCORRUPTED */ + ext4_inode_table_set(ctx->sb, &ctx->gdp, 1); + KUNIT_EXPECT_EQ(test, ext4_get_inode_loc(inode, &iloc), -EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, ext4_get_inode_loc_noio(inode, &iloc), + -EFSCORRUPTED); + ext4_inode_table_set(ctx->sb, &ctx->gdp, INODE_TEST_ITABLE_BLK0); + + /* noio variant: uncached -> -EAGAIN, non-uptodate -> -EAGAIN, hit -> 0 */ + itable->in_cache = false; + KUNIT_EXPECT_EQ(test, ext4_get_inode_loc_noio(inode, &iloc), -EAGAIN); + itable->in_cache = true; + clear_buffer_uptodate(&itable->bh); + KUNIT_EXPECT_EQ(test, ext4_get_inode_loc_noio(inode, &iloc), -EAGAIN); + KUNIT_EXPECT_EQ(test, atomic_read(&itable->bh.b_count), 1); + + set_buffer_uptodate(&itable->bh); + err = ext4_get_inode_loc_noio(inode, &iloc); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, iloc.offset, + (unsigned long)((INODE_TEST_PRIMARY_INO - 1) * + INODE_TEST_INODE_SIZE)); + brelse(iloc.bh); + + /* + * Skip-I/O optimization: non-uptodate itable block + uptodate inode + * bitmap with ONLY primary inode bit set -> zero I/O reads! + */ + clear_buffer_uptodate(&itable->bh); + memset(itable->disk_buf, 0x77, INODE_TEST_BLK_SIZE); + memset(ibitmap->cache_buf, 0, INODE_TEST_BLK_SIZE); + ext4_set_bit(INODE_TEST_PRIMARY_INO - 1, ibitmap->cache_buf); + set_buffer_uptodate(&ibitmap->bh); + ctx->read_nowait_calls = 0; + i_uid_write(inode, 0x4242); + + err = ext4_get_inode_loc(inode, &iloc); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->read_nowait_calls, 0U); + raw = ext4_raw_inode(&iloc); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_uid_low), 0x4242); + /* Neighbor slot was zeroed rather than read from 0x77 disk_buf */ + KUNIT_EXPECT_EQ(test, (u8)itable->cache_buf[0], 0); + brelse(iloc.bh); + + /* + * Neighbor inode bit also set in bitmap -> cannot skip I/O; performs + * disk read and triggers inode table readahead window calculation. + */ + clear_buffer_uptodate(&itable->bh); + ext4_set_bit(INODE_TEST_PRIMARY_INO, ibitmap->cache_buf); + ctx->sbi.s_inode_readahead_blks = 4; + ctx->read_nowait_calls = 0; + ctx->readahead_calls = 0; + + err = ext4_get_inode_loc(inode, &iloc); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->read_nowait_calls, 1U); + KUNIT_EXPECT_GT(test, ctx->readahead_calls, 0U); + KUNIT_EXPECT_EQ(test, ctx->first_readahead_blk, + (ext4_fsblk_t)INODE_TEST_ITABLE_BLK0); + KUNIT_EXPECT_EQ(test, (u8)itable->cache_buf[0], 0x77); + brelse(iloc.bh); + ctx->sbi.s_inode_readahead_blks = 0; + + /* Disk read -EIO propagates cleanly with balanced bh refcount */ + clear_buffer_uptodate(&itable->bh); + ctx->fail_read_eio = true; + err = ext4_get_fc_inode_loc(ctx->sb, INODE_TEST_PRIMARY_INO, &iloc); + ctx->fail_read_eio = false; + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_EQ(test, atomic_read(&itable->bh.b_count), 1); +} + +/* ------------------------------------------------------------------------- + * 8. __ext4_iget() Valid Modes, Caching, & Special Inode Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_iget_validation_and_modes(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct ext4_inode *raw; + struct inode *inode, *cached; + + /* Illegal & special ino checks before VFS lookup */ + KUNIT_EXPECT_EQ(test, + PTR_ERR(ext4_iget(ctx->sb, 0, EXT4_IGET_NORMAL)), + -EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, + PTR_ERR(ext4_iget(ctx->sb, 0, EXT4_IGET_HANDLE)), + -ESTALE); + KUNIT_EXPECT_EQ(test, + PTR_ERR(ext4_iget(ctx->sb, 8, EXT4_IGET_NORMAL)), + -EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, + PTR_ERR(ext4_iget(ctx->sb, 99999, EXT4_IGET_HANDLE)), + -ESTALE); + + /* EXT4_IGET_NOWAIT returns -ENOENT when inode is not cached */ + KUNIT_EXPECT_EQ(test, + PTR_ERR(ext4_iget(ctx->sb, 14, EXT4_IGET_NOWAIT)), + -ENOENT); + + /* Valid regular file inode load & cached NOWAIT / check_igot_inode */ + ext4_set_feature_project(ctx->sb); + inode_test_prepare_valid_raw_inode(ctx, 14, S_IFREG | 0640); + raw = inode_test_raw_slot(ctx, 14, true); + raw->i_uid_low = cpu_to_le16(0x2222); + raw->i_uid_high = cpu_to_le16(0x1111); + raw->i_gid_low = cpu_to_le16(0x4444); + raw->i_gid_high = cpu_to_le16(0x3333); + raw->i_projid = cpu_to_le32(77); + raw->i_size_lo = cpu_to_le32(8192); + raw->i_disk_version = cpu_to_le32(9); + raw->i_version_hi = cpu_to_le32(2); + inode_test_stamp_raw_csum(ctx, 14, raw); + + inode = ext4_iget(ctx->sb, 14, EXT4_IGET_NORMAL); + KUNIT_ASSERT_FALSE(test, IS_ERR(inode)); + inode_test_track_iget_inode(test, ctx, inode); + KUNIT_EXPECT_EQ(test, i_uid_read(inode), 0x11112222U); + KUNIT_EXPECT_EQ(test, i_gid_read(inode), 0x33334444U); + KUNIT_EXPECT_EQ(test, from_kprojid(&init_user_ns, EXT4_I(inode)->i_projid), + 77U); + KUNIT_EXPECT_EQ(test, i_size_read(inode), 8192LL); + KUNIT_EXPECT_EQ(test, inode_peek_iversion(inode), + (0x2ULL << 32) | 9ULL); + + cached = ext4_iget(ctx->sb, 14, EXT4_IGET_NOWAIT); + KUNIT_ASSERT_PTR_EQ(test, cached, inode); + iput(cached); + + /* Cached non-EA inode rejected when EXT4_IGET_EA_INODE requested */ + cached = ext4_iget(ctx->sb, 14, EXT4_IGET_EA_INODE); + KUNIT_EXPECT_EQ(test, PTR_ERR(cached), -EFSCORRUPTED); + + /* Valid fast symlink sets cached i_link */ + inode_test_prepare_valid_raw_inode(ctx, 15, S_IFLNK | 0777); + raw = inode_test_raw_slot(ctx, 15, true); + raw->i_flags = 0; + raw->i_size_lo = cpu_to_le32(11); + memcpy(raw->i_block, "target/path", 11); + inode_test_stamp_raw_csum(ctx, 15, raw); + + inode = ext4_iget(ctx->sb, 15, EXT4_IGET_NORMAL); + KUNIT_ASSERT_FALSE(test, IS_ERR(inode)); + inode_test_track_iget_inode(test, ctx, inode); + KUNIT_EXPECT_STREQ(test, inode->i_link, "target/path"); + + /* Valid character & block device special inodes (old & new rdev) */ + inode_test_prepare_valid_raw_inode(ctx, 16, S_IFCHR | 0600); + raw = inode_test_raw_slot(ctx, 16, true); + raw->i_block[0] = cpu_to_le32(old_encode_dev(MKDEV(4, 64))); + inode_test_stamp_raw_csum(ctx, 16, raw); + + inode = ext4_iget(ctx->sb, 16, EXT4_IGET_NORMAL); + KUNIT_ASSERT_FALSE(test, IS_ERR(inode)); + inode_test_track_iget_inode(test, ctx, inode); + KUNIT_EXPECT_EQ(test, inode->i_rdev, MKDEV(4, 64)); + + inode_test_prepare_valid_raw_inode(ctx, 17, S_IFBLK | 0600); + raw = inode_test_raw_slot(ctx, 17, true); + raw->i_block[0] = 0; + raw->i_block[1] = cpu_to_le32(new_encode_dev(MKDEV(300, 700))); + inode_test_stamp_raw_csum(ctx, 17, raw); + + inode = ext4_iget(ctx->sb, 17, EXT4_IGET_NORMAL); + KUNIT_ASSERT_FALSE(test, IS_ERR(inode)); + inode_test_track_iget_inode(test, ctx, inode); + KUNIT_EXPECT_EQ(test, inode->i_rdev, MKDEV(300, 700)); + + /* Uninitialized EXT4_BOOT_LOADER_INO requires EXT4_IGET_BAD */ + inode_test_prepare_valid_raw_inode(ctx, EXT4_BOOT_LOADER_INO, 0); + raw = inode_test_raw_slot(ctx, EXT4_BOOT_LOADER_INO, true); + raw->i_links_count = 0; + inode_test_stamp_raw_csum(ctx, EXT4_BOOT_LOADER_INO, raw); + + inode = ext4_iget(ctx->sb, EXT4_BOOT_LOADER_INO, EXT4_IGET_SPECIAL); + KUNIT_EXPECT_EQ(test, PTR_ERR(inode), -EFSCORRUPTED); + + inode_test_prepare_valid_raw_inode(ctx, EXT4_BOOT_LOADER_INO, 0); + raw = inode_test_raw_slot(ctx, EXT4_BOOT_LOADER_INO, true); + raw->i_links_count = 0; + inode_test_stamp_raw_csum(ctx, EXT4_BOOT_LOADER_INO, raw); + + inode = ext4_iget(ctx->sb, EXT4_BOOT_LOADER_INO, + EXT4_IGET_SPECIAL | EXT4_IGET_BAD); + KUNIT_ASSERT_FALSE(test, IS_ERR(inode)); + inode_test_track_iget_inode(test, ctx, inode); + KUNIT_EXPECT_TRUE(test, is_bad_inode(inode)); + cached = ext4_iget(ctx->sb, EXT4_BOOT_LOADER_INO, EXT4_IGET_SPECIAL); + KUNIT_EXPECT_EQ(test, PTR_ERR(cached), -EFSCORRUPTED); +} + +/* ------------------------------------------------------------------------- + * 9. __ext4_iget() On-Disk Corruption Rejection Matrix + * ------------------------------------------------------------------------- + */ + +static void inode_test_iget_corruptions(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct ext4_inode *raw; + struct inode *inode; + + /* 1. Unallocated inode with EXT4_IGET_HANDLE -> -ESTALE */ + inode_test_prepare_valid_raw_inode(ctx, 18, 0); + raw = inode_test_raw_slot(ctx, 18, true); + raw->i_links_count = 0; + inode_test_stamp_raw_csum(ctx, 18, raw); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 18, EXT4_IGET_HANDLE)), + -ESTALE); + + /* 2. Unaligned i_extra_isize -> -EFSCORRUPTED */ + inode_test_prepare_valid_raw_inode(ctx, 19, S_IFREG | 0644); + raw = inode_test_raw_slot(ctx, 19, true); + raw->i_extra_isize = cpu_to_le16(5); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 19, EXT4_IGET_NORMAL)), + -EFSCORRUPTED); + + /* 3. Oversize i_extra_isize -> -EFSCORRUPTED */ + inode_test_prepare_valid_raw_inode(ctx, 20, S_IFREG | 0644); + raw = inode_test_raw_slot(ctx, 20, true); + raw->i_extra_isize = cpu_to_le16(132); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 20, EXT4_IGET_NORMAL)), + -EFSCORRUPTED); + + /* 4. Bad checksum -> -EFSBADCRC (and EXT4_FC_REPLAY bypasses it) */ + inode_test_prepare_valid_raw_inode(ctx, 21, S_IFREG | 0644); + raw = inode_test_raw_slot(ctx, 21, true); + raw->i_checksum_lo ^= cpu_to_le16(0x00ff); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 21, EXT4_IGET_NORMAL)), + -EFSBADCRC); + + inode_test_prepare_valid_raw_inode(ctx, 21, S_IFREG | 0644); + raw = inode_test_raw_slot(ctx, 21, true); + raw->i_checksum_lo ^= cpu_to_le16(0x00ff); + ctx->sbi.s_mount_state |= EXT4_FC_REPLAY; + inode = ext4_iget(ctx->sb, 21, EXT4_IGET_NORMAL); + ctx->sbi.s_mount_state &= ~EXT4_FC_REPLAY; + KUNIT_ASSERT_FALSE(test, IS_ERR(inode)); + inode_test_track_iget_inode(test, ctx, inode); + + /* 5. Deleted inode (nlink=0) -> -ESTALE normally, allowed in ORPHAN_FS */ + inode_test_prepare_valid_raw_inode(ctx, 22, S_IFREG | 0644); + raw = inode_test_raw_slot(ctx, 22, true); + raw->i_links_count = 0; + inode_test_stamp_raw_csum(ctx, 22, raw); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 22, EXT4_IGET_NORMAL)), + -ESTALE); + + inode_test_prepare_valid_raw_inode(ctx, 22, S_IFREG | 0644); + raw = inode_test_raw_slot(ctx, 22, true); + raw->i_links_count = 0; + inode_test_stamp_raw_csum(ctx, 22, raw); + ctx->sbi.s_mount_state |= EXT4_ORPHAN_FS; + inode = ext4_iget(ctx->sb, 22, EXT4_IGET_NORMAL); + ctx->sbi.s_mount_state &= ~EXT4_ORPHAN_FS; + KUNIT_ASSERT_FALSE(test, IS_ERR(inode)); + inode_test_put_tracked_inode(ctx, inode); + + /* 6. Unallocated special inode -> -EFSCORRUPTED */ + inode_test_prepare_valid_raw_inode(ctx, 7, S_IFREG | 0600); + raw = inode_test_raw_slot(ctx, 7, true); + raw->i_links_count = 0; + inode_test_stamp_raw_csum(ctx, 7, raw); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 7, EXT4_IGET_SPECIAL)), + -EFSCORRUPTED); + + /* 7. Conflicting INLINE_DATA | EXTENTS flags -> -EFSCORRUPTED */ + inode_test_prepare_valid_raw_inode(ctx, 23, S_IFREG | 0644); + raw = inode_test_raw_slot(ctx, 23, true); + raw->i_flags = cpu_to_le32(EXT4_INLINE_DATA_FL | EXT4_EXTENTS_FL); + inode_test_stamp_raw_csum(ctx, 23, raw); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 23, EXT4_IGET_NORMAL)), + -EFSCORRUPTED); + + /* 8. Indirect file i_size exceeding s_bitmap_maxbytes -> -EFSCORRUPTED */ + inode_test_prepare_valid_raw_inode(ctx, 24, S_IFREG | 0644); + raw = inode_test_raw_slot(ctx, 24, true); + raw->i_flags = 0; + memset(raw->i_block, 0, sizeof(raw->i_block)); + raw->i_size_high = cpu_to_le32(0x1000); + inode_test_stamp_raw_csum(ctx, 24, raw); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 24, EXT4_IGET_NORMAL)), + -EFSCORRUPTED); + + /* 9. Directory with INDEX flag when dir_index disabled -> -EFSCORRUPTED */ + ext4_clear_feature_dir_index(ctx->sb); + inode_test_prepare_valid_raw_inode(ctx, 25, S_IFDIR | 0755); + raw = inode_test_raw_slot(ctx, 25, true); + raw->i_flags |= cpu_to_le32(EXT4_INDEX_FL); + inode_test_stamp_raw_csum(ctx, 25, raw); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 25, EXT4_IGET_NORMAL)), + -EFSCORRUPTED); + ext4_set_feature_dir_index(ctx->sb); + + /* 10. Out-of-range i_file_acl block -> -EFSCORRUPTED */ + inode_test_prepare_valid_raw_inode(ctx, 26, S_IFREG | 0644); + raw = inode_test_raw_slot(ctx, 26, true); + raw->i_file_acl_lo = cpu_to_le32(INODE_TEST_TOTAL_BLKS + 100); + inode_test_stamp_raw_csum(ctx, 26, raw); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 26, EXT4_IGET_NORMAL)), + -EFSCORRUPTED); + + /* 11. Corrupted extent header magic -> -EFSCORRUPTED */ + inode_test_prepare_valid_raw_inode(ctx, 27, S_IFREG | 0644); + raw = inode_test_raw_slot(ctx, 27, true); + raw->i_block[0] = 0; + inode_test_stamp_raw_csum(ctx, 27, raw); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 27, EXT4_IGET_NORMAL)), + -EFSCORRUPTED); + + /* 12. Symlink with IMMUTABLE flag & fast symlink with embedded NUL */ + inode_test_prepare_valid_raw_inode(ctx, 28, S_IFLNK | 0777); + raw = inode_test_raw_slot(ctx, 28, true); + raw->i_flags = cpu_to_le32(EXT4_IMMUTABLE_FL); + raw->i_size_lo = cpu_to_le32(3); + memcpy(raw->i_block, "abc", 3); + inode_test_stamp_raw_csum(ctx, 28, raw); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 28, EXT4_IGET_NORMAL)), + -EFSCORRUPTED); + + inode_test_prepare_valid_raw_inode(ctx, 28, S_IFLNK | 0777); + raw = inode_test_raw_slot(ctx, 28, true); + raw->i_flags = 0; + raw->i_size_lo = cpu_to_le32(5); + memcpy(raw->i_block, "ab\0cd", 5); + inode_test_stamp_raw_csum(ctx, 28, raw); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 28, EXT4_IGET_NORMAL)), + -EFSCORRUPTED); + + /* 13. Bogus i_mode (0) with nlink > 0 & CASEFOLD without feature */ + inode_test_prepare_valid_raw_inode(ctx, 29, 0); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 29, EXT4_IGET_NORMAL)), + -EFSCORRUPTED); + + inode_test_prepare_valid_raw_inode(ctx, 30, S_IFDIR | 0755); + raw = inode_test_raw_slot(ctx, 30, true); + raw->i_flags |= cpu_to_le32(EXT4_CASEFOLD_FL); + inode_test_stamp_raw_csum(ctx, 30, raw); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 30, EXT4_IGET_NORMAL)), + -EFSCORRUPTED); + + /* 14. EA_INODE opened without EXT4_IGET_EA_INODE: -ESTALE vs -EFSCORRUPTED */ + inode_test_prepare_valid_raw_inode(ctx, 31, S_IFREG | 0600); + raw = inode_test_raw_slot(ctx, 31, true); + raw->i_flags |= cpu_to_le32(EXT4_EA_INODE_FL); + inode_test_stamp_raw_csum(ctx, 31, raw); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 31, EXT4_IGET_HANDLE)), + -ESTALE); + + inode_test_prepare_valid_raw_inode(ctx, 31, S_IFREG | 0600); + raw = inode_test_raw_slot(ctx, 31, true); + raw->i_flags |= cpu_to_le32(EXT4_EA_INODE_FL); + inode_test_stamp_raw_csum(ctx, 31, raw); + KUNIT_EXPECT_EQ(test, PTR_ERR(ext4_iget(ctx->sb, 31, EXT4_IGET_NORMAL)), + -EFSCORRUPTED); +} + +/* ------------------------------------------------------------------------- + * 10. Fast Symlink Classification & ext4_can_truncate() Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_fast_symlink_and_can_truncate(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + + /* Fast symlink classification with/without external xattr & EA_INODE */ + inode_test_reset_mock_inode(ctx, S_IFLNK | 0777); + inode->i_size = 20; + inode->i_blocks = 0; + KUNIT_EXPECT_EQ(test, ext4_inode_is_fast_symlink(inode), 1); + + /* External xattr block accounts for 8 512B sectors when !EA_INODE */ + ctx->ei.i_file_acl = INODE_TEST_META_BLK0; + inode->i_blocks = 8; + KUNIT_EXPECT_EQ(test, ext4_inode_is_fast_symlink(inode), 1); + inode->i_blocks = 16; + KUNIT_EXPECT_EQ(test, ext4_inode_is_fast_symlink(inode), 0); + + /* With EA_INODE feature, fast symlink depends on 0 < i_size < 60 */ + ext4_set_feature_ea_inode(ctx->sb); + inode->i_size = 0; + KUNIT_EXPECT_EQ(test, ext4_inode_is_fast_symlink(inode), 0); + inode->i_size = 20; + KUNIT_EXPECT_EQ(test, ext4_inode_is_fast_symlink(inode), 1); + inode->i_size = EXT4_N_BLOCKS * 4; + KUNIT_EXPECT_EQ(test, ext4_inode_is_fast_symlink(inode), 0); + ext4_clear_feature_ea_inode(ctx->sb); + + /* Inline-data symlink is not classified as a legacy fast symlink */ + inode->i_size = 20; + inode->i_blocks = 8; + ext4_set_inode_flag(inode, EXT4_INODE_INLINE_DATA); + ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + ctx->ei.i_inline_off = 164; + KUNIT_EXPECT_EQ(test, ext4_inode_is_fast_symlink(inode), 0); + + /* ext4_can_truncate() across file types and fast vs slow symlinks */ + inode_test_reset_mock_inode(ctx, S_IFREG | 0644); + KUNIT_EXPECT_EQ(test, ext4_can_truncate(inode), 1); + + inode_test_reset_mock_inode(ctx, S_IFDIR | 0755); + KUNIT_EXPECT_EQ(test, ext4_can_truncate(inode), 1); + + inode_test_reset_mock_inode(ctx, S_IFIFO | 0600); + KUNIT_EXPECT_EQ(test, ext4_can_truncate(inode), 0); + + inode_test_reset_mock_inode(ctx, S_IFCHR | 0600); + KUNIT_EXPECT_EQ(test, ext4_can_truncate(inode), 0); + + inode_test_reset_mock_inode(ctx, S_IFLNK | 0777); + inode->i_blocks = 0; + KUNIT_EXPECT_EQ(test, ext4_can_truncate(inode), 0); + inode->i_blocks = 8; + KUNIT_EXPECT_EQ(test, ext4_can_truncate(inode), 1); +} + +/* ------------------------------------------------------------------------- + * 11. VFS Inode Flags, Address Space Ops, and Folio Order Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_flags_aops_mapping_order(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + const struct address_space_operations *da_aops, *nodelalloc_aops; + const struct address_space_operations *jdata_aops; + + /* 1. ext4_set_inode_flags() flag translation & S_DAX policy */ + inode_test_reset_mock_inode(ctx, S_IFREG | 0644); + ctx->ei.i_flags = EXT4_SYNC_FL | EXT4_APPEND_FL | EXT4_IMMUTABLE_FL | + EXT4_NOATIME_FL | EXT4_DIRSYNC_FL | EXT4_VERITY_FL; + ext4_set_inode_flags(inode, true); + KUNIT_EXPECT_EQ(test, + inode->i_flags & (S_SYNC | S_APPEND | S_IMMUTABLE | + S_NOATIME | S_DIRSYNC | S_VERITY), + (unsigned int)(S_SYNC | S_APPEND | S_IMMUTABLE | + S_NOATIME | S_DIRSYNC | S_VERITY)); + + ctx->ei.i_flags = 0; + ext4_set_inode_flags(inode, false); + KUNIT_EXPECT_EQ(test, + inode->i_flags & (S_SYNC | S_APPEND | S_IMMUTABLE | + S_NOATIME | S_DIRSYNC), 0U); + + /* S_DAX enabled when BDEV_IS_DAX + DAX_ALWAYS on regular extent file */ + set_bit(EXT4_FLAGS_BDEV_IS_DAX, &ctx->sbi.s_ext4_flags); + set_opt(ctx->sb, DAX_ALWAYS); + ext4_set_inode_flags(inode, true); + if (IS_ENABLED(CONFIG_FS_DAX)) + KUNIT_EXPECT_TRUE(test, IS_DAX(inode)); + + /* DAX_NEVER and JOURNAL_DATA both suppress S_DAX */ + clear_opt(ctx->sb, DAX_ALWAYS); + set_opt2(ctx->sb, DAX_NEVER); + inode->i_flags &= ~S_DAX; + ext4_set_inode_flags(inode, true); + KUNIT_EXPECT_FALSE(test, IS_DAX(inode)); + clear_opt2(ctx->sb, DAX_NEVER); + + clear_opt(ctx->sb, DELALLOC); + ctx->ei.i_flags = EXT4_DAX_FL | EXT4_JOURNAL_DATA_FL; + ctx->sbi.s_journal = (journal_t *)1; + ext4_set_inode_flags(inode, true); + ctx->sbi.s_journal = NULL; + set_opt(ctx->sb, DELALLOC); + KUNIT_EXPECT_FALSE(test, IS_DAX(inode)); + clear_bit(EXT4_FLAGS_BDEV_IS_DAX, &ctx->sbi.s_ext4_flags); + + /* 2. ext4_set_aops() dispatch across delalloc, ordered, journalled */ + inode_test_reset_mock_inode(ctx, S_IFREG | 0644); + set_opt(ctx->sb, DELALLOC); + ext4_set_aops(inode); + da_aops = inode->i_mapping->a_ops; + KUNIT_EXPECT_NOT_NULL(test, da_aops); + + clear_opt(ctx->sb, DELALLOC); + ext4_set_aops(inode); + nodelalloc_aops = inode->i_mapping->a_ops; + KUNIT_EXPECT_PTR_NE(test, da_aops, nodelalloc_aops); + + ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA); + ctx->sbi.s_journal = (journal_t *)1; + ext4_set_aops(inode); + ctx->sbi.s_journal = NULL; + jdata_aops = inode->i_mapping->a_ops; + KUNIT_EXPECT_PTR_NE(test, jdata_aops, da_aops); + KUNIT_EXPECT_PTR_NE(test, jdata_aops, nodelalloc_aops); + set_opt(ctx->sb, DELALLOC); + + /* 3. ext4_set_inode_mapping_order() clamping */ + inode_test_reset_mock_inode(ctx, S_IFREG | 0644); + ctx->sbi.s_min_folio_order = 0; + ctx->sbi.s_max_folio_order = 3; + ext4_set_inode_mapping_order(inode); + if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) { + KUNIT_EXPECT_EQ(test, + mapping_min_folio_order(inode->i_mapping), 0U); + KUNIT_EXPECT_EQ(test, + mapping_max_folio_order(inode->i_mapping), 3U); + + ctx->sbi.s_min_folio_order = 1; + ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA); + ext4_set_inode_mapping_order(inode); + KUNIT_EXPECT_EQ(test, + mapping_max_folio_order(inode->i_mapping), 1U); + } + ctx->sbi.s_min_folio_order = 0; + ctx->sbi.s_max_folio_order = 0; +} + +/* ------------------------------------------------------------------------- + * 12. Project ID, DIO Alignment, and getattr / file_getattr Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_projid_dio_and_getattr(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct path path = { .dentry = &ctx->root_dentry }; + struct kstat stat = {}; + kprojid_t projid = {}; + int err; + + /* ext4_get_projid(): -EOPNOTSUPP without feature, value with feature */ + ctx->ei.i_projid = make_kprojid(&init_user_ns, 314); + ext4_clear_feature_project(ctx->sb); + KUNIT_EXPECT_EQ(test, ext4_get_projid(inode, &projid), -EOPNOTSUPP); + ext4_set_feature_project(ctx->sb); + KUNIT_EXPECT_EQ(test, ext4_get_projid(inode, &projid), 0); + KUNIT_EXPECT_EQ(test, from_kprojid(&init_user_ns, projid), 314U); + + /* ext4_dio_alignment(): 1 default, blocksize encrypted, 0 jdata/inline */ + inode_test_reset_mock_inode(ctx, S_IFREG | 0644); + KUNIT_EXPECT_EQ(test, ext4_dio_alignment(inode), 1U); + + inode->i_flags |= S_ENCRYPTED; + KUNIT_EXPECT_EQ(test, ext4_dio_alignment(inode), + (u32)INODE_TEST_BLK_SIZE); + inode->i_flags &= ~S_ENCRYPTED; + + clear_opt(ctx->sb, DELALLOC); + ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA); + ctx->sbi.s_journal = (journal_t *)1; + KUNIT_EXPECT_EQ(test, ext4_dio_alignment(inode), 0U); + ctx->sbi.s_journal = NULL; + ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA); + set_opt(ctx->sb, DELALLOC); + + ext4_set_inode_flag(inode, EXT4_INODE_INLINE_DATA); + ctx->ei.i_inline_off = 164; + KUNIT_EXPECT_EQ(test, ext4_dio_alignment(inode), 0U); + ext4_clear_inode_flag(inode, EXT4_INODE_INLINE_DATA); + ctx->ei.i_inline_off = 0; + + /* ext4_getattr() omits delalloc; ext4_file_getattr() includes it */ + inode->i_size = 8192; + inode->i_blocks = 16; + ctx->ei.i_reserved_data_blocks = 2; + ctx->ei.i_crtime.tv_sec = 0x56781234LL; + ctx->ei.i_crtime.tv_nsec = 999L; + ctx->ei.i_flags |= EXT4_APPEND_FL | EXT4_IMMUTABLE_FL | EXT4_NODUMP_FL; + ctx->sbi.s_awu_min = 4096; + ctx->sbi.s_awu_max = 16384; + + err = ext4_getattr(&nop_mnt_idmap, &path, &stat, + STATX_BASIC_STATS | STATX_BTIME | + STATX_DIOALIGN | STATX_WRITE_ATOMIC, 0); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, stat.blocks, 16ULL); + + memset(&stat, 0, sizeof(stat)); + err = ext4_file_getattr(&nop_mnt_idmap, &path, &stat, + STATX_BASIC_STATS | STATX_BTIME | + STATX_DIOALIGN | STATX_WRITE_ATOMIC, 0); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, !!(stat.result_mask & STATX_BTIME)); + KUNIT_EXPECT_EQ(test, stat.btime.tv_sec, 0x56781234LL); + KUNIT_EXPECT_EQ(test, stat.btime.tv_nsec, 999L); + /* 16 on-disk sectors + 2 reserved 4K blocks (16 sectors) = 32 sectors */ + KUNIT_EXPECT_EQ(test, stat.blocks, 32ULL); + KUNIT_EXPECT_EQ(test, stat.attributes & (STATX_ATTR_APPEND | + STATX_ATTR_IMMUTABLE | + STATX_ATTR_NODUMP), + (u64)(STATX_ATTR_APPEND | STATX_ATTR_IMMUTABLE | + STATX_ATTR_NODUMP)); + KUNIT_EXPECT_EQ(test, stat.dio_mem_align, 512U); + KUNIT_EXPECT_EQ(test, stat.dio_offset_align, 512U); + KUNIT_EXPECT_EQ(test, stat.atomic_write_unit_min, 4096U); + KUNIT_EXPECT_EQ(test, stat.atomic_write_unit_max, 16384U); + + /* Inline-data file reports simulated 512B sectors from i_size */ + ctx->ei.i_reserved_data_blocks = 0; + inode->i_blocks = 0; + inode->i_size = 1200; + ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS); + ext4_set_inode_flag(inode, EXT4_INODE_INLINE_DATA); + ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + ctx->ei.i_inline_off = 164; + memset(&stat, 0, sizeof(stat)); + err = ext4_file_getattr(&nop_mnt_idmap, &path, &stat, + STATX_BASIC_STATS, 0); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, stat.blocks, 3ULL); + ctx->sbi.s_awu_min = 0; + ctx->sbi.s_awu_max = 0; +} + +/* ------------------------------------------------------------------------- + * 13. Delayed Allocation Reservation, Claim, Release & Nonda Switch Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_da_reserve_and_release(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + int err; + + percpu_counter_set(&ctx->sbi.s_freeclusters_counter, + max_t(s64, 100, EXT4_FREECLUSTERS_WATERMARK + 100)); + percpu_counter_set(&ctx->sbi.s_dirtyclusters_counter, 0); + + /* Reserve 5 clusters */ + err = ext4_da_reserve_space_test(inode, 5); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->ei.i_reserved_data_blocks, 5U); + KUNIT_EXPECT_EQ(test, + percpu_counter_sum(&ctx->sbi.s_dirtyclusters_counter), + 5LL); + + /* Claim 2 clusters via ext4_da_update_reserve_space() */ + ext4_da_update_reserve_space(inode, 2, 1); + KUNIT_EXPECT_EQ(test, ctx->ei.i_reserved_data_blocks, 3U); + KUNIT_EXPECT_EQ(test, + percpu_counter_sum(&ctx->sbi.s_dirtyclusters_counter), + 3LL); + + /* Release 2 clusters via ext4_da_release_space() */ + ext4_da_release_space(inode, 0); + KUNIT_EXPECT_EQ(test, ctx->ei.i_reserved_data_blocks, 3U); + ext4_da_release_space(inode, 2); + KUNIT_EXPECT_EQ(test, ctx->ei.i_reserved_data_blocks, 1U); + + /* Underflow in update_reserve_space clamps to 0 cleanly */ + kunit_warning_suppress(test) { + ext4_da_update_reserve_space(inode, 4, 0); + } + KUNIT_EXPECT_EQ(test, ctx->ei.i_reserved_data_blocks, 0U); + + /* Underflow in release_space clamps to 0 cleanly */ + err = ext4_da_reserve_space_test(inode, 1); + KUNIT_EXPECT_EQ(test, err, 0); + kunit_warning_suppress(test) { + ext4_da_release_space(inode, 3); + } + KUNIT_EXPECT_EQ(test, ctx->ei.i_reserved_data_blocks, 0U); + + /* Exhausted free clusters -> -ENOSPC & ext4_nonda_switch() */ + KUNIT_EXPECT_EQ(test, ext4_nonda_switch_test(ctx->sb), 0); + percpu_counter_set(&ctx->sbi.s_freeclusters_counter, 2); + percpu_counter_set(&ctx->sbi.s_dirtyclusters_counter, 4); + KUNIT_EXPECT_EQ(test, ext4_nonda_switch_test(ctx->sb), 1); + + percpu_counter_set(&ctx->sbi.s_freeclusters_counter, 0); + percpu_counter_set(&ctx->sbi.s_dirtyclusters_counter, 0); + KUNIT_EXPECT_EQ(test, ext4_da_reserve_space_test(inode, 1), -ENOSPC); +} + +/* ------------------------------------------------------------------------- + * 14. Bigalloc Delayed Allocation & Cluster Sharing Accounting Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_enable_bigalloc(struct inode_test_ctx *ctx, + unsigned int cluster_ratio) +{ + ext4_set_feature_bigalloc(ctx->sb); + ctx->sbi.s_cluster_ratio = cluster_ratio; + ctx->sbi.s_cluster_bits = ilog2(cluster_ratio); + ctx->sbi.s_clusters_per_group = + ctx->sbi.s_blocks_per_group / cluster_ratio; +} + +static void inode_test_insert_leaf_extent(struct inode *inode, ext4_lblk_t lblk, + u16 len, ext4_fsblk_t pblk, + bool unwritten) +{ + struct ext4_extent_header *eh = ext_inode_hdr(inode); + unsigned int idx = le16_to_cpu(eh->eh_entries); + struct ext4_extent *ex = EXT_FIRST_EXTENT(eh) + idx; + + ex->ee_block = cpu_to_le32(lblk); + ex->ee_len = cpu_to_le16(len); + if (unwritten) + ext4_ext_mark_unwritten(ex); + ext4_ext_store_pblock(ex, pblk); + eh->eh_entries = cpu_to_le16(idx + 1); + ext4_es_remove_extent(inode, lblk, len); +} + +static void inode_test_da_bigalloc_clusters(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct ext4_map_blocks map = {}; + struct buffer_head bh = {}; + int state_unalloc, state_delayed, state_mapped; + int err; + + inode_test_enable_bigalloc(ctx, 4); + inode_test_reset_mock_inode(ctx, S_IFREG | 0644); + /* Pre-populate written extent at lblk 4 (lclu 1) -> pblk 104 */ + inode_test_insert_leaf_extent(inode, 4, 1, INODE_TEST_DATA_BLK0 + 4, + false); + /* Pre-populate unwritten extent at lblk 8 (lclu 2) -> pblk 108 */ + inode_test_insert_leaf_extent(inode, 8, 2, 108, true); + + down_write(&ctx->ei.i_data_sem); + state_unalloc = ext4_clu_alloc_state_test(inode, 0); + state_mapped = ext4_clu_alloc_state_test(inode, 5); + up_write(&ctx->ei.i_data_sem); + KUNIT_EXPECT_EQ(test, state_unalloc, 0); + KUNIT_EXPECT_EQ(test, state_mapped, 2); + + /* 1. First block in unallocated cluster 0 reserves 1 cluster */ + memset(&bh, 0, sizeof(bh)); + bh.b_size = INODE_TEST_BLK_SIZE; + err = ext4_da_get_block_prep(inode, 0, &bh, 1); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, buffer_delay(&bh)); + KUNIT_EXPECT_TRUE(test, buffer_new(&bh)); + KUNIT_EXPECT_EQ(test, ctx->ei.i_reserved_data_blocks, 1U); + + down_write(&ctx->ei.i_data_sem); + state_delayed = ext4_clu_alloc_state_test(inode, 2); + up_write(&ctx->ei.i_data_sem); + KUNIT_EXPECT_EQ(test, state_delayed, 1); + + /* 2. Sibling block in cluster 0 shares existing delalloc reservation */ + memset(&bh, 0, sizeof(bh)); + bh.b_size = INODE_TEST_BLK_SIZE; + err = ext4_da_get_block_prep(inode, 1, &bh, 1); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, buffer_delay(&bh)); + KUNIT_EXPECT_EQ(test, ctx->ei.i_reserved_data_blocks, 1U); + + /* Multi-block ext4_da_map_blocks() across [lblk 2..3] in cluster 0 */ + map = (struct ext4_map_blocks){ .m_lblk = 2, .m_len = 2 }; + err = ext4_da_map_blocks_test(inode, &map); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, map.m_len, 2U); + KUNIT_EXPECT_TRUE(test, !!(map.m_flags & EXT4_MAP_DELAYED)); + KUNIT_EXPECT_EQ(test, ctx->ei.i_reserved_data_blocks, 1U); + + map = (struct ext4_map_blocks){ .m_lblk = 0, .m_len = 4 }; + err = ext4_da_map_blocks_test(inode, &map); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, map.m_len, 4U); + KUNIT_EXPECT_TRUE(test, !!(map.m_flags & EXT4_MAP_DELAYED)); + + /* + * 3. Delayed block in cluster 1 (sharing written lblk 4) reserves 0 new + * clusters and records a pending reservation on cluster 1! + */ + memset(&bh, 0, sizeof(bh)); + bh.b_size = INODE_TEST_BLK_SIZE; + err = ext4_da_get_block_prep(inode, 5, &bh, 1); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, buffer_delay(&bh)); + KUNIT_EXPECT_EQ(test, ctx->ei.i_reserved_data_blocks, 1U); + KUNIT_EXPECT_TRUE(test, ext4_is_pending(inode, 4)); + + /* 4. Already-written block 4 maps directly without BH_Delay */ + memset(&bh, 0, sizeof(bh)); + bh.b_size = INODE_TEST_BLK_SIZE; + err = ext4_da_get_block_prep(inode, 4, &bh, 1); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, buffer_mapped(&bh)); + KUNIT_EXPECT_FALSE(test, buffer_delay(&bh)); + KUNIT_EXPECT_EQ(test, (ext4_fsblk_t)bh.b_blocknr, + (ext4_fsblk_t)(INODE_TEST_DATA_BLK0 + 4)); + + /* + * 5. Unwritten block 8 sets BH_Unwritten | BH_New | BH_Mapped; + * delayed sibling hole block 10 in the same cluster 2 records a + * pending reservation without reserving an extra cluster. + */ + memset(&bh, 0, sizeof(bh)); + bh.b_size = INODE_TEST_BLK_SIZE; + err = ext4_da_get_block_prep(inode, 8, &bh, 1); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, buffer_unwritten(&bh)); + KUNIT_EXPECT_TRUE(test, buffer_new(&bh)); + KUNIT_EXPECT_TRUE(test, buffer_mapped(&bh)); + KUNIT_EXPECT_EQ(test, (ext4_fsblk_t)bh.b_blocknr, 108ULL); + KUNIT_EXPECT_FALSE(test, ext4_is_pending(inode, 8)); + + memset(&bh, 0, sizeof(bh)); + bh.b_size = INODE_TEST_BLK_SIZE; + err = ext4_da_get_block_prep(inode, 10, &bh, 1); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, buffer_delay(&bh)); + KUNIT_EXPECT_EQ(test, ctx->ei.i_reserved_data_blocks, 1U); + KUNIT_EXPECT_TRUE(test, ext4_is_pending(inode, 8)); + + /* Removing ES extents releases the 1 reserved cluster via da_release */ + down_write(&ctx->ei.i_data_sem); + ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS); + up_write(&ctx->ei.i_data_sem); + KUNIT_EXPECT_EQ(test, ctx->ei.i_reserved_data_blocks, 0U); +} + +/* ------------------------------------------------------------------------- + * 15. ext4_map_blocks() Lookup, Caching, Allocation, Zeroout & Validity Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_map_blocks_paths(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct ext4_map_blocks map = {}; + struct extent_status es = {}; + handle_t *handle; + int ret; + + /* 1. Out-of-range logical block -> -EFSCORRUPTED */ + map.m_lblk = EXT_MAX_BLOCKS; + map.m_len = 1; + KUNIT_EXPECT_EQ(test, ext4_map_blocks(NULL, inode, &map, 0), + -EFSCORRUPTED); + + /* 2. CACHED_NOWAIT miss returns 0 without querying extent tree */ + inode_test_insert_leaf_extent(inode, 0, 2, INODE_TEST_DATA_BLK0, false); + map = (struct ext4_map_blocks){ .m_lblk = 0, .m_len = 2 }; + ret = ext4_map_blocks(NULL, inode, &map, EXT4_GET_BLOCKS_CACHED_NOWAIT); + KUNIT_EXPECT_EQ(test, ret, 0); + + /* 3. ES miss queries extent tree, caches written extent; NOWAIT hits */ + map = (struct ext4_map_blocks){ .m_lblk = 0, .m_len = 2 }; + ret = ext4_map_blocks(NULL, inode, &map, 0); + KUNIT_EXPECT_EQ(test, ret, 2); + KUNIT_EXPECT_EQ(test, map.m_pblk, (ext4_fsblk_t)INODE_TEST_DATA_BLK0); + KUNIT_EXPECT_TRUE(test, !!(map.m_flags & EXT4_MAP_MAPPED)); + + map = (struct ext4_map_blocks){ .m_lblk = 1, .m_len = 1 }; + ret = ext4_map_blocks(NULL, inode, &map, EXT4_GET_BLOCKS_CACHED_NOWAIT); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, map.m_pblk, + (ext4_fsblk_t)(INODE_TEST_DATA_BLK0 + 1)); + + /* 4. ES delayed & hole hits */ + down_write(&ctx->ei.i_data_sem); + KUNIT_EXPECT_EQ(test, ext4_insert_delayed_blocks_test(inode, 4, 2), 0); + ext4_es_insert_extent(inode, 6, 2, ~0, EXTENT_STATUS_HOLE, 0); + up_write(&ctx->ei.i_data_sem); + + map = (struct ext4_map_blocks){ .m_lblk = 4, .m_len = 2 }; + ret = ext4_map_blocks(NULL, inode, &map, 0); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_TRUE(test, !!(map.m_flags & EXT4_MAP_DELAYED)); + + map = (struct ext4_map_blocks){ .m_lblk = 6, .m_len = 2 }; + ret = ext4_map_blocks(NULL, inode, &map, 0); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, map.m_flags, 0U); + + /* 5. Block allocation + EXT4_GET_BLOCKS_CREATE_ZERO & zeroout error */ + ctx->next_alloc_pblk = INODE_TEST_DATA_BLK0 + 2; + ctx->zeroout_calls = 0; + handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, 4); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + map = (struct ext4_map_blocks){ .m_lblk = 10, .m_len = 2 }; + ret = ext4_map_blocks(handle, inode, &map, EXT4_GET_BLOCKS_CREATE_ZERO); + ext4_journal_stop(handle); + + KUNIT_EXPECT_EQ(test, ret, 2); + KUNIT_EXPECT_EQ(test, map.m_pblk, + (ext4_fsblk_t)(INODE_TEST_DATA_BLK0 + 2)); + KUNIT_EXPECT_TRUE(test, !!(map.m_flags & EXT4_MAP_NEW)); + KUNIT_EXPECT_EQ(test, ctx->zeroout_calls, 1U); + KUNIT_EXPECT_EQ(test, ctx->last_zeroout_lblk, 10U); + KUNIT_EXPECT_EQ(test, ctx->last_zeroout_len, 2U); + + /* Failed zeroout returns error BEFORE caching written extent in ES */ + ctx->fail_zeroout_err = -EIO; + handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, 4); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + map = (struct ext4_map_blocks){ .m_lblk = 12, .m_len = 1 }; + ret = ext4_map_blocks(handle, inode, &map, EXT4_GET_BLOCKS_CREATE_ZERO); + ext4_journal_stop(handle); + ctx->fail_zeroout_err = 0; + + KUNIT_EXPECT_EQ(test, ret, -EIO); + KUNIT_EXPECT_EQ(test, ext4_es_lookup_extent(inode, 12, NULL, &es, NULL), + 1); + KUNIT_EXPECT_FALSE(test, ext4_es_is_written(&es)); + KUNIT_EXPECT_TRUE(test, ext4_es_is_hole(&es)); + + /* 6. check_block_validity() rejects out-of-bounds pblk in extent */ + inode_test_reset_mock_inode(ctx, S_IFREG | 0644); + inode_test_insert_leaf_extent(inode, 0, 1, INODE_TEST_TOTAL_BLKS + 50, + false); + map = (struct ext4_map_blocks){ .m_lblk = 0, .m_len = 1 }; + KUNIT_EXPECT_EQ(test, ext4_map_blocks(NULL, inode, &map, 0), + -EFSCORRUPTED); +} + +/* ------------------------------------------------------------------------- + * 16. ext4_get_block, getblk, bread, bread_batch & walk_page_buffers Tests + * ------------------------------------------------------------------------- + */ + +static int inode_test_walk_cb(handle_t *handle, struct inode *inode, + struct buffer_head *bh) +{ + int *visited = (int *)bh->b_private; + + (*visited)++; + if (*visited < 0) + return -EINVAL; + return 0; +} + +static void inode_test_get_block_bread_and_walk_buffers(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct inode_test_blk *dblk0 = inode_test_find_blk(ctx, + INODE_TEST_DATA_BLK0); + struct inode_test_blk *dblk1 = inode_test_find_blk(ctx, + INODE_TEST_DATA_BLK0 + 1); + struct buffer_head bh = {}; + struct buffer_head *res_bh; + struct buffer_head *batch[3] = {}; + struct buffer_head ring[4] = {}; + int visited[4] = { 0, 0, 0, 0 }; + int partial = 0; + handle_t *handle; + int i, err; + + /* 1. ext4_get_block() inline -ERANGE, hole lookup, mapped & create */ + ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS); + ext4_set_inode_flag(inode, EXT4_INODE_INLINE_DATA); + ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + ctx->ei.i_inline_off = 164; + bh.b_size = INODE_TEST_BLK_SIZE; + KUNIT_EXPECT_EQ(test, ext4_get_block(inode, 0, &bh, 0), -ERANGE); + ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + ext4_clear_inode_flag(inode, EXT4_INODE_INLINE_DATA); + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + ctx->ei.i_inline_off = 0; + + memset(&bh, 0, sizeof(bh)); + bh.b_size = INODE_TEST_BLK_SIZE; + KUNIT_EXPECT_EQ(test, ext4_get_block(inode, 0, &bh, 0), 0); + KUNIT_EXPECT_FALSE(test, buffer_mapped(&bh)); + + ctx->next_alloc_pblk = INODE_TEST_DATA_BLK0; + handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, 4); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + err = ext4_get_block_unwritten(inode, 0, &bh, 1); + ext4_journal_stop(handle); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, buffer_mapped(&bh)); + KUNIT_EXPECT_TRUE(test, buffer_unwritten(&bh)); + KUNIT_EXPECT_TRUE(test, buffer_new(&bh)); + + /* 2. ext4_getblk() hole -> NULL, CREATE new block zeroes & dirties bh */ + res_bh = ext4_getblk(NULL, inode, 5, 0); + KUNIT_EXPECT_NULL(test, res_bh); + + clear_buffer_uptodate(&dblk1->bh); + memset(dblk1->cache_buf, 0xcd, INODE_TEST_BLK_SIZE); + ctx->next_alloc_pblk = INODE_TEST_DATA_BLK0 + 1; + handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, 4); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + res_bh = ext4_getblk(handle, inode, 1, EXT4_GET_BLOCKS_CREATE); + ext4_journal_stop(handle); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(res_bh)); + KUNIT_EXPECT_TRUE(test, buffer_uptodate(res_bh)); + KUNIT_EXPECT_EQ(test, (u8)dblk1->cache_buf[0], 0); + brelse(res_bh); + + /* 3. ext4_bread() disk read & -EIO error cleanup */ + inode_test_reset_mock_inode(ctx, S_IFDIR | 0755); + inode_test_insert_leaf_extent(inode, 0, 1, INODE_TEST_DATA_BLK0, false); + inode_test_insert_leaf_extent(inode, 2, 1, INODE_TEST_DATA_BLK0 + 1, + false); + clear_buffer_uptodate(&dblk0->bh); + memset(dblk0->disk_buf, 0x3c, INODE_TEST_BLK_SIZE); + ctx->read_lock_calls = 0; + + res_bh = ext4_bread(NULL, inode, 0, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(res_bh)); + KUNIT_EXPECT_EQ(test, ctx->read_lock_calls, 1U); + KUNIT_EXPECT_EQ(test, (u8)res_bh->b_data[0], 0x3c); + brelse(res_bh); + + clear_buffer_uptodate(&dblk0->bh); + ctx->fail_read_eio = true; + res_bh = ext4_bread(NULL, inode, 0, 0); + ctx->fail_read_eio = false; + KUNIT_EXPECT_EQ(test, PTR_ERR(res_bh), -EIO); + KUNIT_EXPECT_EQ(test, atomic_read(&dblk0->bh.b_count), 1); + + /* 4. ext4_bread_batch() across [mapped, hole, mapped] & -EIO cleanup */ + clear_buffer_uptodate(&dblk0->bh); + clear_buffer_uptodate(&dblk1->bh); + memset(dblk1->disk_buf, 0x99, INODE_TEST_BLK_SIZE); + err = ext4_bread_batch(inode, 0, 3, true, batch); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_NOT_NULL(test, batch[0]); + KUNIT_EXPECT_NULL(test, batch[1]); + KUNIT_EXPECT_NOT_NULL(test, batch[2]); + KUNIT_EXPECT_EQ(test, (u8)batch[2]->b_data[0], 0x99); + for (i = 0; i < 3; i++) + brelse(batch[i]); + + memset(batch, 0, sizeof(batch)); + clear_buffer_uptodate(&dblk0->bh); + ctx->fail_read_eio = true; + err = ext4_bread_batch(inode, 0, 3, true, batch); + ctx->fail_read_eio = false; + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_EQ(test, atomic_read(&dblk0->bh.b_count), 1); + KUNIT_EXPECT_EQ(test, atomic_read(&dblk1->bh.b_count), 1); + + /* 5. ext4_walk_page_buffers() sub-page range, partial & error stop */ + for (i = 0; i < 4; i++) { + ring[i].b_size = 1024; + ring[i].b_this_page = &ring[(i + 1) % 4]; + ring[i].b_private = &visited[i]; + if (i != 3) + set_buffer_uptodate(&ring[i]); + } + err = ext4_walk_page_buffers(NULL, inode, &ring[0], 1024, 3072, + &partial, inode_test_walk_cb); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, visited[0], 0); + KUNIT_EXPECT_EQ(test, visited[1], 1); + KUNIT_EXPECT_EQ(test, visited[2], 1); + KUNIT_EXPECT_EQ(test, visited[3], 0); + KUNIT_EXPECT_EQ(test, partial, 1); + + set_buffer_uptodate(&ring[3]); + partial = 0; + err = ext4_walk_page_buffers(NULL, inode, &ring[0], 1024, 3072, + &partial, inode_test_walk_cb); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, partial, 0); + + visited[1] = -2; + err = ext4_walk_page_buffers(NULL, inode, &ring[0], 1024, 3072, + NULL, inode_test_walk_cb); + KUNIT_EXPECT_EQ(test, err, -EINVAL); + KUNIT_EXPECT_EQ(test, visited[2], 2); +} + +/* ------------------------------------------------------------------------- + * 17. ext4_iomap_begin, ext4_iomap_report_ops, and Atomic Writes Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_iomap_and_atomic_writes(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct iomap iomap = {}; + struct iomap srcmap = {}; + struct iomap_iter iter = {}; + int err; + + /* 1. Offset past EXT4_MAX_LOGICAL_BLOCK -> -EINVAL */ + err = ext4_iomap_begin(inode, + ((loff_t)EXT4_MAX_LOGICAL_BLOCK + 1) << 12, + 4096, 0, &iomap, &srcmap); + KUNIT_EXPECT_EQ(test, err, -EINVAL); + + /* 2. Inline-data: iomap_begin warns & returns -ERANGE; report works */ + ext4_set_inode_flag(inode, EXT4_INODE_INLINE_DATA); + ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS); + ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + ctx->ei.i_inline_off = 164; + ctx->ei.i_inline_size = 60; + inode->i_size = 24; + + kunit_warning_suppress(test) { + err = ext4_iomap_begin(inode, 0, 24, 0, &iomap, &srcmap); + } + KUNIT_EXPECT_EQ(test, err, -ERANGE); + + iter = (struct iomap_iter){ + .inode = inode, .pos = 0, .len = 24, .flags = IOMAP_REPORT, + }; + err = ext4_iomap_next_report(&iter, &iter.iomap, &iter.srcmap); + KUNIT_EXPECT_GT(test, err, 0); + KUNIT_EXPECT_EQ(test, iter.iomap.type, (u16)IOMAP_INLINE); + + iter = (struct iomap_iter){ + .inode = inode, .pos = 60, .len = 24, .flags = IOMAP_REPORT, + }; + err = ext4_iomap_next_report(&iter, &iter.iomap, &iter.srcmap); + KUNIT_EXPECT_EQ(test, err, -ENOENT); + + /* 3. Indirect report past s_bitmap_maxbytes returns IOMAP_HOLE */ + inode_test_reset_mock_inode(ctx, S_IFREG | 0644); + ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS); + memset(ctx->ei.i_data, 0, sizeof(ctx->ei.i_data)); + iter = (struct iomap_iter){ + .inode = inode, + .pos = ctx->sbi.s_bitmap_maxbytes, + .len = 4096, + .flags = IOMAP_REPORT, + }; + err = ext4_iomap_next_report(&iter, &iter.iomap, &iter.srcmap); + KUNIT_EXPECT_GT(test, err, 0); + KUNIT_EXPECT_EQ(test, iter.iomap.type, (u16)IOMAP_HOLE); + + /* Indirect DIO write to hole inside i_size returns -ENOTBLK */ + inode->i_size = 8192; + err = ext4_iomap_begin(inode, 0, 4096, IOMAP_WRITE | IOMAP_DIRECT, + &iomap, &srcmap); + KUNIT_EXPECT_EQ(test, err, -ENOTBLK); + + /* 4. Read mappings (MAPPED, UNWRITTEN, DELALLOC, HOLE, DAX offset) */ + inode_test_reset_mock_inode(ctx, S_IFREG | 0644); + inode->i_size = 16384; + ctx->sbi.s_dax_part_off = 0x200000ULL; + down_write(&ctx->ei.i_data_sem); + ext4_es_insert_extent(inode, 0, 1, INODE_TEST_DATA_BLK0, + EXTENT_STATUS_WRITTEN, 0); + ext4_es_insert_extent(inode, 1, 1, INODE_TEST_DATA_BLK0 + 1, + EXTENT_STATUS_UNWRITTEN, 0); + KUNIT_EXPECT_EQ(test, ext4_insert_delayed_blocks_test(inode, 2, 1), 0); + ext4_es_insert_extent(inode, 3, 1, ~0, EXTENT_STATUS_HOLE, 0); + up_write(&ctx->ei.i_data_sem); + + KUNIT_EXPECT_EQ(test, + ext4_iomap_begin(inode, 0, 4096, IOMAP_DAX, &iomap, + &srcmap), 0); + KUNIT_EXPECT_EQ(test, iomap.type, (u16)IOMAP_MAPPED); + KUNIT_EXPECT_EQ(test, iomap.addr, + ((u64)INODE_TEST_DATA_BLK0 << 12) + + (IS_ENABLED(CONFIG_FS_DAX) ? 0x200000ULL : 0ULL)); + ctx->sbi.s_dax_part_off = 0; + + KUNIT_EXPECT_EQ(test, + ext4_iomap_begin(inode, 4096, 4096, 0, &iomap, &srcmap), + 0); + KUNIT_EXPECT_EQ(test, iomap.type, (u16)IOMAP_UNWRITTEN); + + KUNIT_EXPECT_EQ(test, + ext4_iomap_begin(inode, 8192, 4096, 0, &iomap, &srcmap), + 0); + KUNIT_EXPECT_EQ(test, iomap.type, (u16)IOMAP_DELALLOC); + + KUNIT_EXPECT_EQ(test, + ext4_iomap_begin(inode, 12288, 4096, 0, &iomap, + &srcmap), 0); + KUNIT_EXPECT_EQ(test, iomap.type, (u16)IOMAP_HOLE); + + iter = (struct iomap_iter){ + .inode = inode, .pos = 0, .len = 4096, .flags = 0, + }; + err = ext4_iomap_next(&iter, &iter.iomap, &iter.srcmap); + KUNIT_EXPECT_GT(test, err, 0); + KUNIT_EXPECT_EQ(test, iter.iomap.type, (u16)IOMAP_MAPPED); + KUNIT_EXPECT_EQ(test, iter.iomap.addr, + (u64)INODE_TEST_DATA_BLK0 << 12); + + /* 5. DIO write: NOWAIT -> -EAGAIN, inside i_size -> UNWRITTEN */ + KUNIT_EXPECT_EQ(test, + ext4_iomap_begin(inode, 12288, 4096, + IOMAP_WRITE | IOMAP_DIRECT | + IOMAP_NOWAIT, &iomap, &srcmap), + -EAGAIN); + + ctx->next_alloc_pblk = INODE_TEST_DATA_BLK0 + 3; + KUNIT_EXPECT_EQ(test, + ext4_iomap_begin(inode, 12288, 4096, + IOMAP_WRITE | IOMAP_DIRECT, &iomap, + &srcmap), 0); + KUNIT_EXPECT_EQ(test, iomap.type, (u16)IOMAP_UNWRITTEN); + KUNIT_EXPECT_TRUE(test, !!(iomap.flags & IOMAP_F_NEW)); + + /* 6. Bigalloc multi-block atomic write across mixed [written + hole] */ + inode_test_enable_bigalloc(ctx, 4); + inode_test_reset_mock_inode(ctx, S_IFREG | 0644); + inode->i_size = 16384; + /* Pre-populate lblk 0..1 as written at pblk 100..101; lblk 2..3 hole */ + inode_test_insert_leaf_extent(inode, 0, 2, INODE_TEST_DATA_BLK0, false); + ctx->next_alloc_pblk = INODE_TEST_DATA_BLK0 + 2; + ctx->zeroout_calls = 0; + + err = ext4_iomap_begin(inode, 0, 16384, + IOMAP_WRITE | IOMAP_DIRECT | IOMAP_ATOMIC, + &iomap, &srcmap); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, iomap.type, (u16)IOMAP_MAPPED); + KUNIT_EXPECT_EQ(test, iomap.length, 16384ULL); + KUNIT_EXPECT_EQ(test, iomap.addr, (u64)INODE_TEST_DATA_BLK0 << 12); + KUNIT_EXPECT_TRUE(test, !!(iomap.flags & IOMAP_F_ATOMIC_BIO)); + KUNIT_EXPECT_GT(test, ctx->zeroout_calls, 0U); +} + +/* ------------------------------------------------------------------------- + * 18. Transaction Credits, Layout Breaking & Disksize Update Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_trans_credits_and_disksize(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + int ext_credits, ind_credits, chunk_ext, chunk_jdata; + int err; + + /* 1. ext4_meta_trans_blocks() & ext4_chunk_trans_*() */ + ctx->sbi.s_groups_count = 4; + ctx->sbi.s_gdb_count = 2; + ext_credits = ext4_meta_trans_blocks(inode, 8, 2, 1); + KUNIT_EXPECT_GT(test, ext_credits, 0); + + ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS); + ind_credits = ext4_meta_trans_blocks(inode, 8, 2, 1); + KUNIT_EXPECT_GT(test, ind_credits, 0); + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + ctx->sbi.s_groups_count = 1; + ctx->sbi.s_gdb_count = 1; + + chunk_ext = ext4_chunk_trans_extent(inode, 5); + KUNIT_EXPECT_EQ(test, ext4_chunk_trans_blocks(inode, 5), chunk_ext); + + clear_opt(ctx->sb, DELALLOC); + ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA); + ctx->sbi.s_journal = (journal_t *)1; + chunk_jdata = ext4_chunk_trans_extent(inode, 5); + ctx->sbi.s_journal = NULL; + ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA); + set_opt(ctx->sb, DELALLOC); + KUNIT_EXPECT_EQ(test, chunk_jdata, chunk_ext + 5); + + /* 2. ext4_break_layouts() requires invalidate_lock held */ + kunit_warning_suppress(test) { + err = ext4_break_layouts(inode); + } + KUNIT_EXPECT_EQ(test, err, -EINVAL); + + filemap_invalidate_lock(inode->i_mapping); + err = ext4_break_layouts(inode); + filemap_invalidate_unlock(inode->i_mapping); + KUNIT_EXPECT_EQ(test, err, 0); + + /* 3. ext4_update_disksize_before_punch() */ + inode->i_size = 12000; + ctx->ei.i_disksize = 4096; + + inode_lock(inode); + /* Punch past i_size is a no-op */ + KUNIT_EXPECT_EQ(test, + ext4_update_disksize_before_punch(inode, 16384, 4096), + 0); + KUNIT_EXPECT_EQ(test, ctx->ei.i_disksize, 4096LL); + + /* Punch within [0, 8192) advances i_disksize to 8192 */ + KUNIT_EXPECT_EQ(test, + ext4_update_disksize_before_punch(inode, 4096, 4096), + 0); + KUNIT_EXPECT_EQ(test, ctx->ei.i_disksize, 8192LL); + + /* Punch extending past i_size clamps i_disksize to i_size (12000) */ + KUNIT_EXPECT_EQ(test, + ext4_update_disksize_before_punch(inode, 8192, 8192), + 0); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ctx->ei.i_disksize, 12000LL); +} + +/* ------------------------------------------------------------------------- + * 19. Partial Block Zeroing, EOF Zeroing & Pagecache Truncate Range Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_zero_partial_and_eof(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct inode_test_blk *dblk0 = inode_test_find_blk(ctx, + INODE_TEST_DATA_BLK0); + struct inode_test_blk *dblk1 = inode_test_find_blk(ctx, + INODE_TEST_DATA_BLK0 + 1); + struct folio *folio; + unsigned int partial_zeroed = 0; + u8 *kaddr; + int err; + + /* + * Map lblk 0 -> pblk 100 (written), leave lblk 1 as a hole, and map + * lblk 2 -> pblk 101 (written). + */ + inode->i_size = 12288; + ctx->ei.i_disksize = 12288; + inode_test_insert_leaf_extent(inode, 0, 1, INODE_TEST_DATA_BLK0, false); + inode_test_insert_leaf_extent(inode, 2, 1, INODE_TEST_DATA_BLK0 + 1, + false); + memset(dblk0->disk_buf, 0x5a, INODE_TEST_BLK_SIZE); + memset(dblk1->disk_buf, 0xa5, INODE_TEST_BLK_SIZE); + + /* 1. Single-block interior zeroing [512, 1536) sets START | END */ + err = ext4_zero_partial_blocks(inode, 512, 1024, &partial_zeroed); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, partial_zeroed, + (unsigned int)(EXT4_PARTIAL_ZERO_START | + EXT4_PARTIAL_ZERO_END)); + + folio = filemap_get_folio(inode->i_mapping, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(folio)); + kaddr = kmap_local_folio(folio, 0); + KUNIT_EXPECT_EQ(test, kaddr[511], 0x5a); + KUNIT_EXPECT_EQ(test, kaddr[512], 0x00); + KUNIT_EXPECT_EQ(test, kaddr[1535], 0x00); + KUNIT_EXPECT_EQ(test, kaddr[1536], 0x5a); + kunmap_local(kaddr); + folio_put(folio); + + /* 2. Multi-block [3000, 5000): lblk 0 mapped, lblk 1 hole -> START */ + partial_zeroed = 0; + err = ext4_zero_partial_blocks(inode, 3000, 2000, &partial_zeroed); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, partial_zeroed, + (unsigned int)EXT4_PARTIAL_ZERO_START); + + /* Zero EOF tail [8500, 12288) in lblk 2 -> pblk 101 */ + KUNIT_EXPECT_EQ(test, ext4_block_zero_eof(inode, 8192, 12288), 0); + KUNIT_EXPECT_EQ(test, ext4_block_zero_eof(inode, 9000, 8500), 0); + + err = ext4_block_zero_eof(inode, 8500, 12288); + KUNIT_ASSERT_EQ(test, err, 0); + + folio = filemap_get_folio(inode->i_mapping, 8192 >> PAGE_SHIFT); + KUNIT_ASSERT_FALSE(test, IS_ERR(folio)); + kaddr = kmap_local_folio(folio, offset_in_folio(folio, 8192)); + KUNIT_EXPECT_EQ(test, kaddr[307], 0xa5); + KUNIT_EXPECT_EQ(test, kaddr[308], 0x00); + KUNIT_EXPECT_EQ(test, kaddr[4095], 0x00); + kunmap_local(kaddr); + folio_put(folio); + + /* 3. ext4_truncate_page_cache_block_range() evicts full folio 0 */ + err = ext4_truncate_page_cache_block_range(inode, 0, + INODE_TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, err, 0); + err = ext4_truncate_page_cache_block_range(inode, 0, + max_t(loff_t, PAGE_SIZE, INODE_TEST_BLK_SIZE)); + KUNIT_EXPECT_EQ(test, err, 0); + folio = filemap_get_folio(inode->i_mapping, 0); + KUNIT_EXPECT_TRUE(test, IS_ERR(folio)); + if (!IS_ERR(folio)) + folio_put(folio); +} + +/* ------------------------------------------------------------------------- + * 20. ext4_punch_hole() & ext4_truncate() End-to-End Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_punch_hole_and_truncate(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct file *dummy_file; + struct extent_status es = {}; + int err; + + dummy_file = kunit_kzalloc(test, sizeof(*dummy_file), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dummy_file); + dummy_file->f_inode = inode; + dummy_file->f_mapping = inode->i_mapping; + + /* Set up 4-block written extent [lblk 0..3 -> pblk 100..103] */ + inode->i_size = 4 * INODE_TEST_BLK_SIZE; + ctx->ei.i_disksize = inode->i_size; + inode->i_blocks = 32; + inode_test_insert_leaf_extent(inode, 0, 4, INODE_TEST_DATA_BLK0, false); + down_write(&ctx->ei.i_data_sem); + ext4_es_insert_extent(inode, 0, 4, INODE_TEST_DATA_BLK0, + EXTENT_STATUS_WRITTEN, 0); + up_write(&ctx->ei.i_data_sem); + + /* 1. Punch past i_size is a no-op */ + inode_lock(inode); + err = ext4_punch_hole(dummy_file, 5 * INODE_TEST_BLK_SIZE, + INODE_TEST_BLK_SIZE); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->total_freed_blocks, 0UL); + + /* 2. Punch middle 2 blocks [4096, 12288) -> frees pblk 101..102 */ + inode_lock(inode); + err = ext4_punch_hole(dummy_file, INODE_TEST_BLK_SIZE, + 2 * INODE_TEST_BLK_SIZE); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->total_freed_blocks, 2UL); + KUNIT_EXPECT_EQ(test, ext4_es_lookup_extent(inode, 1, NULL, &es, NULL), + 1); + KUNIT_EXPECT_TRUE(test, ext4_es_is_hole(&es)); + KUNIT_EXPECT_EQ(test, es.es_len, 2U); + + /* 3. Truncate down to 1 block (4096B) -> frees trailing pblk 103 */ + ctx->total_freed_blocks = 0; + ctx->orphan_add_calls = 0; + ctx->orphan_del_calls = 0; + inode->i_size = INODE_TEST_BLK_SIZE; + inode_lock(inode); + err = ext4_truncate(inode); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->orphan_add_calls, 1U); + KUNIT_EXPECT_EQ(test, ctx->orphan_del_calls, 1U); + KUNIT_EXPECT_EQ(test, ctx->total_freed_blocks, 1UL); + KUNIT_EXPECT_EQ(test, ctx->last_free_pblk, + (ext4_fsblk_t)(INODE_TEST_DATA_BLK0 + 3)); + + /* 4. Truncate to 0 sets EXT4_STATE_DA_ALLOC_CLOSE & frees pblk 100 */ + ctx->total_freed_blocks = 0; + inode->i_size = 0; + inode_lock(inode); + err = ext4_truncate(inode); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, + ext4_test_inode_state(inode, + EXT4_STATE_DA_ALLOC_CLOSE)); + KUNIT_EXPECT_EQ(test, ctx->total_freed_blocks, 1UL); + KUNIT_EXPECT_EQ(test, ctx->last_free_pblk, + (ext4_fsblk_t)INODE_TEST_DATA_BLK0); +} + +/* ------------------------------------------------------------------------- + * 21. ext4_inode_attach_jinode, ext4_write_inode & ext4_sync_inode_metadata + * ------------------------------------------------------------------------- + */ + +static void inode_test_write_and_sync_metadata(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct inode_test_blk *itable = inode_test_find_blk(ctx, + INODE_TEST_ITABLE_BLK0); + struct writeback_control wbc = { .sync_mode = WB_SYNC_ALL }; + struct ext4_inode *raw; + int err; + + /* 1. ext4_inode_attach_jinode(): no-op without journal, allocs with */ + KUNIT_EXPECT_EQ(test, ext4_inode_attach_jinode(inode), 0); + KUNIT_EXPECT_NULL(test, ctx->ei.jinode); + + ctx->sbi.s_journal = (journal_t *)1; + err = ext4_inode_attach_jinode(inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_NOT_NULL(test, ctx->ei.jinode); + /* Idempotent when jinode is already attached */ + KUNIT_EXPECT_EQ(test, ext4_inode_attach_jinode(inode), 0); + ctx->sbi.s_journal = NULL; + if (ctx->ei.jinode) { + jbd2_free_inode(ctx->ei.jinode); + ctx->ei.jinode = NULL; + } + + /* 2. ext4_write_inode(): 0 in nojournal, -EROFS in emergency state */ + KUNIT_EXPECT_EQ(test, ext4_write_inode(inode, &wbc), 0); + set_bit(EXT4_FLAGS_EMERGENCY_RO, &ctx->sbi.s_ext4_flags); + KUNIT_EXPECT_EQ(test, ext4_write_inode(inode, &wbc), -EROFS); + clear_bit(EXT4_FLAGS_EMERGENCY_RO, &ctx->sbi.s_ext4_flags); + + /* 3. ext4_sync_inode_metadata(): warns & fails if journal present */ + ctx->sbi.s_journal = (journal_t *)1; + kunit_warning_suppress(test) { + err = ext4_sync_inode_metadata(inode, &wbc); + } + ctx->sbi.s_journal = NULL; + KUNIT_EXPECT_EQ(test, err, -EFSCORRUPTED); + + /* Clean nojournal metadata sync flushes dirty raw inode & returns 0 */ + i_uid_write(inode, 0x7788); + ext4_dirty_inode(inode, I_DIRTY_SYNC); + clear_buffer_mapped(&itable->bh); + clear_buffer_write_io_error(&itable->bh); + err = ext4_sync_inode_metadata(inode, &wbc); + KUNIT_EXPECT_EQ(test, err, 0); + raw = inode_test_raw_slot(ctx, INODE_TEST_PRIMARY_INO, false); + KUNIT_EXPECT_EQ(test, le16_to_cpu(raw->i_uid_low), 0x7788); + + /* Simulated buffer write error returns -EIO */ + set_buffer_write_io_error(&itable->bh); + err = ext4_sync_inode_metadata(inode, &wbc); + clear_buffer_write_io_error(&itable->bh); + KUNIT_EXPECT_EQ(test, err, -EIO); +} + +/* ------------------------------------------------------------------------- + * 22. ext4_evict_inode() Live, Unlinked Regular & Fast Symlink Eviction Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_evict_inode_paths(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct ext4_inode *raw; + struct inode *ig; + + /* 1. Live inode (i_nlink == 1): evicts cleanly without freeing inode */ + inode_test_prepare_valid_raw_inode(ctx, 24, S_IFREG | 0644); + raw = inode_test_raw_slot(ctx, 24, true); + raw->i_size_lo = cpu_to_le32(4096); + inode_test_stamp_raw_csum(ctx, 24, raw); + ig = ext4_iget(ctx->sb, 24, EXT4_IGET_NORMAL); + KUNIT_ASSERT_FALSE(test, IS_ERR(ig)); + ctx->free_inode_calls = 0; + ctx->total_freed_blocks = 0; + iput(ig); + KUNIT_EXPECT_EQ(test, ctx->free_inode_calls, 0U); + KUNIT_EXPECT_EQ(test, ctx->total_freed_blocks, 0UL); + + /* + * 2. Unlinked regular file (i_nlink == 0) with 2 mapped blocks: + * truncates data blocks, sets i_dtime, updates raw inode, and calls + * ext4_free_inode(). + */ + { + u32 t_before, t_after, dtime; + + inode_test_prepare_valid_raw_inode(ctx, 25, S_IFREG | 0644); + raw = inode_test_raw_slot(ctx, 25, true); + raw->i_size_lo = cpu_to_le32(8192); + inode_test_stamp_raw_csum(ctx, 25, raw); + ig = ext4_iget(ctx->sb, 25, EXT4_IGET_NORMAL); + KUNIT_ASSERT_FALSE(test, IS_ERR(ig)); + inode_test_insert_leaf_extent(ig, 0, 2, INODE_TEST_DATA_BLK0, + false); + ig->i_blocks = 16; + clear_nlink(ig); + ctx->free_inode_calls = 0; + ctx->total_freed_blocks = 0; + raw = inode_test_raw_slot(ctx, 25, false); + raw->i_dtime = cpu_to_le32(0xdeadbeefU); + inode_test_stamp_raw_csum(ctx, 25, raw); + t_before = (__u32)ktime_get_real_seconds(); + iput(ig); + t_after = (__u32)ktime_get_real_seconds(); + KUNIT_EXPECT_EQ(test, ctx->total_freed_blocks, 2UL); + KUNIT_EXPECT_EQ(test, ctx->free_inode_calls, 1U); + raw = inode_test_raw_slot(ctx, 25, false); + dtime = le32_to_cpu(raw->i_dtime); + KUNIT_EXPECT_LE(test, (u32)(dtime - t_before), + (u32)(t_after - t_before)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(raw->i_size_lo), 0U); + } + + /* + * 3. Unlinked fast symlink (i_nlink == 0): clears inline i_data target + * without treating bytes as block pointers and frees the inode. + */ + inode_test_prepare_valid_raw_inode(ctx, 26, S_IFLNK | 0777); + raw = inode_test_raw_slot(ctx, 26, true); + raw->i_flags = 0; + raw->i_size_lo = cpu_to_le32(11); + memcpy(raw->i_block, "target/path", 11); + inode_test_stamp_raw_csum(ctx, 26, raw); + ig = ext4_iget(ctx->sb, 26, EXT4_IGET_NORMAL); + KUNIT_ASSERT_FALSE(test, IS_ERR(ig)); + KUNIT_EXPECT_EQ(test, ext4_inode_is_fast_symlink(ig), 1); + clear_nlink(ig); + ctx->free_inode_calls = 0; + ctx->total_freed_blocks = 0; + iput(ig); + KUNIT_EXPECT_EQ(test, ctx->total_freed_blocks, 0UL); + KUNIT_EXPECT_EQ(test, ctx->free_inode_calls, 1U); +} + +/* ------------------------------------------------------------------------- + * 23. Buffered Write (ext4_da_aops & ext4_aops) and Folio Operations Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_buffered_write_and_folio_ops(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct address_space *mapping = inode->i_mapping; + struct folio *folio = NULL; + void *fsdata = NULL; + u8 *kaddr; + int ret; + + /* + * 1. Delayed-allocation buffered write to hole [0, 128): + * reserves 1 delalloc block and updates i_size while deferring + * i_disksize update until writeback. + */ + inode_lock(inode); + ret = mapping->a_ops->write_begin(NULL, mapping, 0, 128, &folio, + &fsdata); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_ASSERT_NOT_NULL(test, folio); + kaddr = kmap_local_folio(folio, 0); + memset(kaddr, 0xab, 128); + kunmap_local(kaddr); + ret = mapping->a_ops->write_end(NULL, mapping, 0, 128, 128, folio, + fsdata); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ret, 128); + KUNIT_EXPECT_EQ(test, inode->i_size, 128LL); + KUNIT_EXPECT_EQ(test, ctx->ei.i_disksize, 0LL); + KUNIT_EXPECT_EQ(test, ctx->ei.i_reserved_data_blocks, 1U); + + /* + * 2. Delayed-allocation write into an already-written block past i_size + * (placed on folio index 1 regardless of PAGE_SIZE) updates both + * i_size and i_disksize immediately. + */ + { + loff_t wpos = max_t(loff_t, PAGE_SIZE, INODE_TEST_BLK_SIZE); + ext4_lblk_t wlblk = wpos >> INODE_TEST_BLK_BITS; + + inode_test_insert_leaf_extent(inode, wlblk, 1, + INODE_TEST_DATA_BLK0 + 1, false); + inode_lock(inode); + ret = mapping->a_ops->write_begin(NULL, mapping, wpos, 64, + &folio, &fsdata); + KUNIT_ASSERT_EQ(test, ret, 0); + kaddr = kmap_local_folio(folio, offset_in_folio(folio, wpos)); + memset(kaddr, 0xcd, 64); + kunmap_local(kaddr); + ret = mapping->a_ops->write_end(NULL, mapping, wpos, 64, 64, + folio, fsdata); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ret, 64); + KUNIT_EXPECT_EQ(test, inode->i_size, wpos + 64); + KUNIT_EXPECT_EQ(test, ctx->ei.i_disksize, wpos + 64); + + /* Full folio invalidation detaches buffers cleanly */ + folio = filemap_lock_folio(mapping, wpos >> PAGE_SHIFT); + KUNIT_ASSERT_FALSE(test, IS_ERR(folio)); + KUNIT_EXPECT_NOT_NULL(test, folio_buffers(folio)); + mapping->a_ops->invalidate_folio(folio, 0, folio_size(folio)); + KUNIT_EXPECT_NULL(test, folio_buffers(folio)); + folio_unlock(folio); + folio_put(folio); + } + + /* 3. Non-delalloc buffered write (ext4_aops) allocates pblk directly */ + inode_test_reset_mock_inode(ctx, S_IFREG | 0644); + clear_opt(ctx->sb, DELALLOC); + ext4_set_aops(inode); + ctx->next_alloc_pblk = INODE_TEST_DATA_BLK0; + ctx->alloc_calls = 0; + + inode_lock(inode); + ret = mapping->a_ops->write_begin(NULL, mapping, 0, 256, &folio, + &fsdata); + KUNIT_ASSERT_EQ(test, ret, 0); + kaddr = kmap_local_folio(folio, 0); + memset(kaddr, 0xef, 256); + kunmap_local(kaddr); + ret = mapping->a_ops->write_end(NULL, mapping, 0, 256, 256, folio, + fsdata); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, ret, 256); + KUNIT_EXPECT_EQ(test, ctx->alloc_calls, 1U); + KUNIT_EXPECT_EQ(test, inode->i_size, 256LL); + KUNIT_EXPECT_EQ(test, ctx->ei.i_disksize, 256LL); + + /* 4. a_ops->bmap, partial invalidate_folio & release_folio */ + KUNIT_EXPECT_EQ(test, (ext4_fsblk_t)mapping->a_ops->bmap(mapping, 0), + (ext4_fsblk_t)INODE_TEST_DATA_BLK0); + KUNIT_EXPECT_EQ(test, (ext4_fsblk_t)mapping->a_ops->bmap(mapping, 5), + 0ULL); + + folio = filemap_lock_folio(mapping, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(folio)); + folio_set_checked(folio); + KUNIT_EXPECT_FALSE(test, mapping->a_ops->release_folio(folio, + GFP_KERNEL)); + folio_clear_checked(folio); + /* Dirty buffer still pins folio buffers */ + KUNIT_EXPECT_FALSE(test, mapping->a_ops->release_folio(folio, + GFP_KERNEL)); + /* Partial invalidation preserves buffer ring */ + mapping->a_ops->invalidate_folio(folio, 128, 128); + KUNIT_EXPECT_NOT_NULL(test, folio_buffers(folio)); + + clear_buffer_dirty(folio_buffers(folio)); + folio_clear_dirty_for_io(folio); + KUNIT_EXPECT_TRUE(test, mapping->a_ops->release_folio(folio, + GFP_KERNEL)); + KUNIT_EXPECT_NULL(test, folio_buffers(folio)); + folio_unlock(folio); + folio_put(folio); + set_opt(ctx->sb, DELALLOC); +} + +/* ------------------------------------------------------------------------- + * 24. ext4_setattr() Permission, Mode, Extend & Shrink Truncate Tests + * ------------------------------------------------------------------------- + */ + +static void inode_test_setattr(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct inode_test_blk *dblk0 = inode_test_find_blk(ctx, + INODE_TEST_DATA_BLK0); + struct dentry dentry = { .d_sb = ctx->sb, .d_inode = inode }; + struct iattr attr = {}; + struct folio *folio; + u8 *kaddr; + u64 iv_before; + int err; + + /* 1. S_IMMUTABLE and S_APPEND permission rejections */ + inode->i_flags |= S_IMMUTABLE; + attr = (struct iattr){ .ia_valid = ATTR_MODE, .ia_mode = S_IFREG | 0600 }; + inode_lock(inode); + KUNIT_EXPECT_EQ(test, ext4_setattr(&nop_mnt_idmap, &dentry, &attr), + -EPERM); + inode_unlock(inode); + inode->i_flags &= ~S_IMMUTABLE; + + inode->i_flags |= S_APPEND; + inode_lock(inode); + KUNIT_EXPECT_EQ(test, ext4_setattr(&nop_mnt_idmap, &dentry, &attr), + -EPERM); + inode_unlock(inode); + inode->i_flags &= ~S_APPEND; + + /* 2. Directory ATTR_SIZE -> -EINVAL; indirect > maxbytes -> -EFBIG */ + inode->i_mode = S_IFDIR | 0755; + attr = (struct iattr){ .ia_valid = ATTR_SIZE, .ia_size = 0 }; + inode_lock(inode); + KUNIT_EXPECT_EQ(test, ext4_setattr(&nop_mnt_idmap, &dentry, &attr), + -EINVAL); + inode_unlock(inode); + + inode_test_reset_mock_inode(ctx, S_IFREG | 0644); + ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS); + memset(ctx->ei.i_data, 0, sizeof(ctx->ei.i_data)); + attr = (struct iattr){ + .ia_valid = ATTR_SIZE, + .ia_size = ctx->sbi.s_bitmap_maxbytes + 4096, + }; + inode_lock(inode); + KUNIT_EXPECT_EQ(test, ext4_setattr(&nop_mnt_idmap, &dentry, &attr), + -EFBIG); + inode_unlock(inode); + + /* 3. ATTR_MODE chmod updates mode & increments iversion */ + inode_test_reset_mock_inode(ctx, S_IFREG | 0644); + iv_before = inode_peek_iversion(inode); + attr = (struct iattr){ .ia_valid = ATTR_MODE, .ia_mode = S_IFREG | 0600 }; + inode_lock(inode); + err = ext4_setattr(&nop_mnt_idmap, &dentry, &attr); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, inode->i_mode & 0777, 0600); + KUNIT_EXPECT_GT(test, inode_peek_iversion(inode), iv_before); + + /* + * 4. ATTR_SIZE extend (2000 -> 8192) zeroes EOF tail [2000, 4096) in + * mapped block 0 and advances i_size and i_disksize. + */ + inode->i_size = 2000; + ctx->ei.i_disksize = 2000; + inode->i_blocks = 16; + inode_test_insert_leaf_extent(inode, 0, 2, INODE_TEST_DATA_BLK0, false); + memset(dblk0->disk_buf, 0x77, INODE_TEST_BLK_SIZE); + + attr = (struct iattr){ .ia_valid = ATTR_SIZE, .ia_size = 8192 }; + inode_lock(inode); + err = ext4_setattr(&nop_mnt_idmap, &dentry, &attr); + inode_unlock(inode); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, inode->i_size, 8192LL); + KUNIT_EXPECT_EQ(test, ctx->ei.i_disksize, 8192LL); + + folio = filemap_get_folio(inode->i_mapping, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(folio)); + kaddr = kmap_local_folio(folio, 0); + KUNIT_EXPECT_EQ(test, kaddr[1999], 0x77); + KUNIT_EXPECT_EQ(test, kaddr[2000], 0x00); + KUNIT_EXPECT_EQ(test, kaddr[4095], 0x00); + kunmap_local(kaddr); + folio_put(folio); + + /* 5. ATTR_SIZE shrink (8192 -> 4096) frees trailing block 1 */ + ctx->total_freed_blocks = 0; + attr = (struct iattr){ .ia_valid = ATTR_SIZE, .ia_size = 4096 }; + inode_lock(inode); + err = ext4_setattr(&nop_mnt_idmap, &dentry, &attr); + inode_unlock(inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, inode->i_size, 4096LL); + KUNIT_EXPECT_EQ(test, ctx->ei.i_disksize, 4096LL); + KUNIT_EXPECT_EQ(test, ctx->total_freed_blocks, 1UL); +} + +/* ------------------------------------------------------------------------- + * 25. ext4_page_mkwrite() Delalloc, Block-Alloc, Fast-Path & Truncate Tests + * ------------------------------------------------------------------------- + */ + +static vm_fault_t inode_test_call_page_mkwrite(struct vm_area_struct *vma, + struct folio *folio) +{ + struct vm_fault vmf = { + .vma = vma, + .page = folio_page(folio, 0), + }; + + return ext4_page_mkwrite(&vmf); +} + +static void inode_test_page_mkwrite(struct kunit *test) +{ + struct inode_test_ctx *ctx = inode_test_setup(test); + struct inode *inode = &ctx->ei.vfs_inode; + struct file *dummy_file; + struct vm_area_struct *vma; + struct folio *folio; + vm_fault_t ret; + + dummy_file = kunit_kzalloc(test, sizeof(*dummy_file), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dummy_file); + dummy_file->f_inode = inode; + dummy_file->f_mapping = inode->i_mapping; + dummy_file->f_mode = FMODE_NOCMTIME; + + vma = kunit_kzalloc(test, sizeof(*vma), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, vma); + vma->vm_file = dummy_file; + + inode->i_size = 4096; + ctx->ei.i_disksize = 4096; + folio = __filemap_get_folio(inode->i_mapping, 0, + FGP_CREAT | FGP_LOCK, GFP_KERNEL); + KUNIT_ASSERT_FALSE(test, IS_ERR(folio)); + folio_zero_segment(folio, 0, folio_size(folio)); + folio_mark_uptodate(folio); + folio_unlock(folio); + + /* 1. S_IMMUTABLE rejects write fault with VM_FAULT_SIGBUS */ + inode->i_flags |= S_IMMUTABLE; + KUNIT_EXPECT_TRUE(test, + inode_test_call_page_mkwrite(vma, folio) == + VM_FAULT_SIGBUS); + inode->i_flags &= ~S_IMMUTABLE; + + /* 2. Delalloc fault reserves 1 delayed block & returns LOCKED */ + ret = inode_test_call_page_mkwrite(vma, folio); + KUNIT_EXPECT_TRUE(test, ret == VM_FAULT_LOCKED); + if (ret & VM_FAULT_LOCKED) + folio_unlock(folio); + KUNIT_EXPECT_EQ(test, ctx->ei.i_reserved_data_blocks, 1U); + folio_put(folio); + + /* 3. Non-delalloc fault allocates pblk; repeat fault hits fast-path */ + inode_test_reset_mock_inode(ctx, S_IFREG | 0644); + clear_opt(ctx->sb, DELALLOC); + ext4_set_aops(inode); + inode->i_size = 4096; + ctx->ei.i_disksize = 4096; + ctx->next_alloc_pblk = INODE_TEST_DATA_BLK0; + ctx->alloc_calls = 0; + + folio = __filemap_get_folio(inode->i_mapping, 0, + FGP_CREAT | FGP_LOCK, GFP_KERNEL); + KUNIT_ASSERT_FALSE(test, IS_ERR(folio)); + folio_zero_segment(folio, 0, folio_size(folio)); + folio_mark_uptodate(folio); + folio_unlock(folio); + + ret = inode_test_call_page_mkwrite(vma, folio); + KUNIT_EXPECT_TRUE(test, ret == VM_FAULT_LOCKED); + if (ret & VM_FAULT_LOCKED) + folio_unlock(folio); + KUNIT_EXPECT_EQ(test, ctx->alloc_calls, 1U); + + /* Second fault sees all buffers mapped and skips journal_start/alloc */ + ret = inode_test_call_page_mkwrite(vma, folio); + KUNIT_EXPECT_TRUE(test, ret == VM_FAULT_LOCKED); + if (ret & VM_FAULT_LOCKED) + folio_unlock(folio); + KUNIT_EXPECT_EQ(test, ctx->alloc_calls, 1U); + + /* 4. Folio beyond truncated i_size returns VM_FAULT_NOPAGE */ + folio_put(folio); + folio = __filemap_get_folio(inode->i_mapping, 2, + FGP_CREAT | FGP_LOCK, GFP_KERNEL); + KUNIT_ASSERT_FALSE(test, IS_ERR(folio)); + folio_unlock(folio); + KUNIT_EXPECT_TRUE(test, + inode_test_call_page_mkwrite(vma, folio) == + VM_FAULT_NOPAGE); + folio_put(folio); + set_opt(ctx->sb, DELALLOC); +} + static struct kunit_case ext4_inode_test_cases[] = { KUNIT_CASE_PARAM(inode_test_xtimestamp_decoding, ext4_inode_gen_params), + KUNIT_CASE(inode_test_xtimestamp_encoding_roundtrip), + KUNIT_CASE(inode_test_csum_set_and_verify), + KUNIT_CASE(inode_test_blocks_encode_decode), + KUNIT_CASE(inode_test_fill_raw_inode), + KUNIT_CASE(inode_test_mark_dirty_and_update), + KUNIT_CASE(inode_test_expand_extra_isize), + KUNIT_CASE(inode_test_get_inode_loc_variants), + KUNIT_CASE(inode_test_iget_validation_and_modes), + KUNIT_CASE(inode_test_iget_corruptions), + KUNIT_CASE(inode_test_fast_symlink_and_can_truncate), + KUNIT_CASE(inode_test_flags_aops_mapping_order), + KUNIT_CASE(inode_test_projid_dio_and_getattr), + KUNIT_CASE(inode_test_da_reserve_and_release), + KUNIT_CASE(inode_test_da_bigalloc_clusters), + KUNIT_CASE(inode_test_map_blocks_paths), + KUNIT_CASE(inode_test_get_block_bread_and_walk_buffers), + KUNIT_CASE(inode_test_iomap_and_atomic_writes), + KUNIT_CASE(inode_test_trans_credits_and_disksize), + KUNIT_CASE(inode_test_zero_partial_and_eof), + KUNIT_CASE(inode_test_punch_hole_and_truncate), + KUNIT_CASE(inode_test_write_and_sync_metadata), + KUNIT_CASE(inode_test_evict_inode_paths), + KUNIT_CASE(inode_test_buffered_write_and_folio_ops), + KUNIT_CASE(inode_test_setattr), + KUNIT_CASE(inode_test_page_mkwrite), {} }; @@ -279,5 +3781,5 @@ static struct kunit_suite ext4_inode_test_suite = { kunit_test_suites(&ext4_inode_test_suite); -MODULE_DESCRIPTION("KUnit test of ext4 inode timestamp decoding"); +MODULE_DESCRIPTION("KUnit tests for ext4 inode operations"); MODULE_LICENSE("GPL v2"); diff --git a/fs/ext4/inode.c b/fs/ext4/inode.c index e3129353d4edbb..07a62d8569d311 100644 --- a/fs/ext4/inode.c +++ b/fs/ext4/inode.c @@ -57,6 +57,7 @@ static void ext4_journalled_zero_new_buffers(handle_t *handle, struct inode *inode, struct folio *folio, unsigned from, unsigned to); +static void ext4_wait_for_tail_page_commit(struct inode *inode); static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw, struct ext4_inode_info *ei) @@ -125,6 +126,7 @@ void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw, EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) raw->i_checksum_hi = cpu_to_le16(csum >> 16); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_csum_set); /* * Clear the disksize-grow-pending state and wake up all waiters. @@ -227,6 +229,7 @@ int ext4_inode_is_fast_symlink(struct inode *inode) return S_ISLNK(inode->i_mode) && inode->i_size && (inode->i_size < EXT4_N_BLOCKS * 4); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_is_fast_symlink); /* * Called at the last iput() if i_nlink is zero. @@ -394,6 +397,7 @@ void ext4_evict_inode(struct inode *inode) ext4_fc_mark_ineligible(inode->i_sb, EXT4_FC_REASON_NOMEM, NULL); ext4_clear_inode(inode); /* We must guarantee clearing of inode... */ } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_evict_inode); #ifdef CONFIG_QUOTA qsize_t *ext4_get_reserved_space(struct inode *inode) @@ -412,6 +416,9 @@ void ext4_da_update_reserve_space(struct inode *inode, struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); struct ext4_inode_info *ei = EXT4_I(inode); + KUNIT_STATIC_STUB_REDIRECT(ext4_da_update_reserve_space, + inode, used, quota_claim); + spin_lock(&ei->i_block_reservation_lock); trace_ext4_da_update_reserve_space(inode, used, quota_claim); if (unlikely(used > ei->i_reserved_data_blocks)) { @@ -470,23 +477,32 @@ static int __check_block_validity(struct inode *inode, const char *func, return 0; } -int ext4_issue_zeroout(struct inode *inode, ext4_lblk_t lblk, ext4_fsblk_t pblk, - ext4_lblk_t len) +/* + * The zeroes written here are file data. With a @handle the range is tracked + * for fast commit, because some callers zero out blocks outside the range that + * ext4_map_blocks() tracks and convert them to written. A caller without a + * handle must make sure that the conversion tracks the range. + */ +int ext4_issue_zeroout(handle_t *handle, struct inode *inode, ext4_lblk_t lblk, + ext4_fsblk_t pblk, ext4_lblk_t len) { int ret; - KUNIT_STATIC_STUB_REDIRECT(ext4_issue_zeroout, inode, lblk, pblk, len); + KUNIT_STATIC_STUB_REDIRECT(ext4_issue_zeroout, handle, inode, lblk, pblk, + len); if (IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode)) - return fscrypt_zeroout_range(inode, + ret = fscrypt_zeroout_range(inode, (loff_t)lblk << inode->i_blkbits, pblk << (inode->i_blkbits - SECTOR_SHIFT), (u64)len << inode->i_blkbits); - - ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS); + else + ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS); if (ret > 0) ret = 0; + if (!ret && handle) + ext4_fc_track_range(handle, inode, lblk, lblk + len - 1); return ret; } @@ -721,8 +737,8 @@ int ext4_map_create_blocks(handle_t *handle, struct inode *inode, */ if (flags & EXT4_GET_BLOCKS_ZERO && map->m_flags & EXT4_MAP_MAPPED && map->m_flags & EXT4_MAP_NEW) { - err = ext4_issue_zeroout(inode, map->m_lblk, map->m_pblk, - map->m_len); + err = ext4_issue_zeroout(handle, inode, map->m_lblk, + map->m_pblk, map->m_len); if (err) return err; } @@ -778,6 +794,8 @@ int ext4_map_blocks(handle_t *handle, struct inode *inode, memcpy(&orig_map, map, sizeof(*map)); #endif + KUNIT_STATIC_STUB_REDIRECT(ext4_map_blocks, handle, inode, map, flags); + map->m_flags = 0; ext_debug(inode, "flag 0x%x, max_blocks %u, logical block %lu\n", flags, map->m_len, (unsigned long) map->m_lblk); @@ -978,6 +996,7 @@ int ext4_map_blocks(handle_t *handle, struct inode *inode, return ret ? ret : retval; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_map_blocks); /* * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages @@ -1061,6 +1080,7 @@ int ext4_get_block(struct inode *inode, sector_t iblock, return _ext4_get_block(inode, iblock, bh, create ? EXT4_GET_BLOCKS_CREATE : 0); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_block); /* * Get block function used when preparing for buffered write if we require @@ -1087,10 +1107,42 @@ int ext4_get_block_unwritten(struct inode *inode, sector_t iblock, return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_block_unwritten); /* Maximum number of blocks we map for direct IO at once. */ #define DIO_MAX_BLOCKS 4096 +struct buffer_head *ext4_sb_getblk(struct super_block *sb, ext4_fsblk_t block) +{ + KUNIT_STATIC_STUB_REDIRECT(ext4_sb_getblk, sb, block); + return sb_getblk(sb, block); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sb_getblk); + +struct buffer_head *ext4_sb_find_get_block(struct super_block *sb, + ext4_fsblk_t block) +{ + KUNIT_STATIC_STUB_REDIRECT(ext4_sb_find_get_block, sb, block); + return sb_find_get_block(sb, block); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sb_find_get_block); + +struct buffer_head *ext4_sb_find_get_block_nonatomic(struct super_block *sb, + ext4_fsblk_t block) +{ + KUNIT_STATIC_STUB_REDIRECT(ext4_sb_find_get_block_nonatomic, sb, block); + return sb_find_get_block_nonatomic(sb, block); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sb_find_get_block_nonatomic); + +struct buffer_head *ext4_sb_getblk_unmovable(struct super_block *sb, + ext4_fsblk_t block) +{ + KUNIT_STATIC_STUB_REDIRECT(ext4_sb_getblk_unmovable, sb, block); + return getblk_unmovable(sb->s_bdev, block, sb->s_blocksize); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sb_getblk_unmovable); + /* * `handle' can be NULL if create is zero */ @@ -1103,6 +1155,9 @@ struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode, bool nowait = map_flags & EXT4_GET_BLOCKS_CACHED_NOWAIT; int err; + KUNIT_STATIC_STUB_REDIRECT(ext4_getblk, handle, inode, block, + map_flags); + ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY) || handle != NULL || create == 0); ASSERT(create == 0 || !nowait); @@ -1117,15 +1172,14 @@ struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode, return ERR_PTR(err); if (nowait) - return sb_find_get_block(inode->i_sb, map.m_pblk); + return ext4_sb_find_get_block(inode->i_sb, map.m_pblk); /* * Since bh could introduce extra ref count such as referred by * journal_head etc. Try to avoid using __GFP_MOVABLE here * as it may fail the migration when journal_head remains. */ - bh = getblk_unmovable(inode->i_sb->s_bdev, map.m_pblk, - inode->i_sb->s_blocksize); + bh = ext4_sb_getblk_unmovable(inode->i_sb, map.m_pblk); if (unlikely(!bh)) return ERR_PTR(-ENOMEM); @@ -1165,6 +1219,7 @@ struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode, brelse(bh); return ERR_PTR(err); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_getblk); struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode, ext4_lblk_t block, int map_flags) @@ -1185,6 +1240,7 @@ struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode, } return bh; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_bread); /* Read a contiguous batch of blocks. */ int ext4_bread_batch(struct inode *inode, ext4_lblk_t block, int bh_count, @@ -1228,6 +1284,7 @@ int ext4_bread_batch(struct inode *inode, ext4_lblk_t block, int bh_count, } return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_bread_batch); int ext4_walk_page_buffers(handle_t *handle, struct inode *inode, struct buffer_head *head, @@ -1259,6 +1316,7 @@ int ext4_walk_page_buffers(handle_t *handle, struct inode *inode, } return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_walk_page_buffers); /* * Helper for handling dirtying of journalled data. We also mark the folio as @@ -1573,15 +1631,18 @@ static int ext4_write_end(const struct kiocb *iocb, * it's important to update i_size while still holding folio lock: * page writeout could otherwise come in and zero beyond i_size. * + * If nothing was copied (e.g. the source buffer was unreadable), do + * not move i_size up to pos. + * * If FS_IOC_ENABLE_VERITY is running on this inode, then Merkle tree * blocks are being written past EOF, so skip the i_size update. */ - if (!verity) + if (copied && !verity) i_size_changed = ext4_update_inode_size(inode, pos + copied); folio_unlock(folio); folio_put(folio); - if (old_size < pos && !verity) + if (copied && old_size < pos && !verity) pagecache_isize_extended(inode, old_size, pos); /* @@ -1692,13 +1753,13 @@ static int ext4_journalled_write_end(const struct kiocb *iocb, if (!partial) folio_mark_uptodate(folio); } - if (!verity) + if (copied && !verity) size_changed = ext4_update_inode_size(inode, pos + copied); EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid; folio_unlock(folio); folio_put(folio); - if (old_size < pos && !verity) + if (copied && old_size < pos && !verity) pagecache_isize_extended(inode, old_size, pos); if (size_changed) { @@ -1718,6 +1779,7 @@ static int ext4_journalled_write_end(const struct kiocb *iocb, if (!ret) ret = ret2; if (pos + len > inode->i_size && !verity) { + ext4_wait_for_tail_page_commit(inode); ext4_truncate_failed_write(inode); /* * If truncate failed early the inode might still be @@ -1767,6 +1829,8 @@ void ext4_da_release_space(struct inode *inode, int to_free) struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); struct ext4_inode_info *ei = EXT4_I(inode); + KUNIT_STATIC_STUB_REDIRECT(ext4_da_release_space, inode, to_free); + if (!to_free) return; /* Nothing to release, exit */ @@ -2036,6 +2100,7 @@ static int ext4_da_map_blocks(struct inode *inode, struct ext4_map_blocks *map) #endif map->m_flags = 0; + map->m_pblk = 0; ext_debug(inode, "max_blocks %u, logical block %lu\n", map->m_len, (unsigned long) map->m_lblk); @@ -2139,6 +2204,9 @@ int ext4_da_get_block_prep(struct inode *inode, sector_t iblock, sector_t invalid_block = ~((sector_t) 0xffff); int ret = 0; + KUNIT_STATIC_STUB_REDIRECT(ext4_da_get_block_prep, inode, iblock, bh, + create); + BUG_ON(create == 0); BUG_ON(bh->b_size != inode->i_sb->s_blocksize); @@ -2284,7 +2352,7 @@ static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk, * @bh - buffer we should start processing from * @lblk - logical number of the block in the file corresponding to @bh * - * Walk through page buffers from @bh upto @head (exclusive) and either submit + * Walk through page buffers from @bh up to @head (exclusive) and either submit * the page for IO if all buffers in this page were mapped and there's no * accumulated extent of buffers to map or add buffers in the page to the * extent of buffers to map. The function returns 1 if the caller can continue @@ -2539,8 +2607,14 @@ static int mpage_submit_partial_folio(struct mpage_da_data *mpd) */ pos = ((loff_t)mpd->map.m_lblk) << inode->i_blkbits; if (WARN_ON_ONCE((folio_pos(folio) == pos) || - !folio_contains(folio, pos >> PAGE_SHIFT))) + !folio_contains(folio, pos >> PAGE_SHIFT))) { + /* + * Leave the folio locked so that the caller can invalidate + * and unlock it through mpage_release_unused_pages(). + */ + folio_put(folio); return -EINVAL; + } mpage_submit_folio(mpd, folio); /* @@ -2632,6 +2706,12 @@ static int mpage_map_and_submit_extent(handle_t *handle, ext4_print_free_blocks(inode); invalidate_dirty_pages: *give_up_on_write = true; + /* + * Record the error so that a subsequent fsync() + * / errseq check can observe the data loss that + * discarding these dirty pages implies. + */ + mapping_set_error(inode->i_mapping, err); return err; } progress = 1; @@ -2901,7 +2981,6 @@ static int ext4_do_writepages(struct mpage_da_data *mpd) int needed_blocks, rsv_blocks = 0, ret = 0; struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb); struct blk_plug plug; - bool give_up_on_write = false; trace_ext4_writepages(inode, wbc); @@ -3026,6 +3105,8 @@ static int ext4_do_writepages(struct mpage_da_data *mpd) goto unplug; while (!mpd->scanned_until_end && wbc->nr_to_write > 0) { + bool give_up_on_write = false; + /* For each extent of pages we use new io_end */ mpd->io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL); if (!mpd->io_submit.io_end) { @@ -3344,6 +3425,24 @@ static int ext4_da_should_update_i_disksize(struct folio *folio, return 1; } +/* + * Delalloc counterpart of ext4_truncate_failed_write(): ->write_begin() only + * reserved delayed blocks, so drop the page cache and the delayed extents + * beyond i_size and leave the blocks that are allocated there alone. + */ +static void ext4_da_truncate_failed_write(struct inode *inode) +{ + struct address_space *mapping = inode->i_mapping; + ext4_lblk_t lblk = EXT4_B_TO_LBLK(inode, inode->i_size); + + filemap_invalidate_lock(mapping); + truncate_inode_pages(mapping, inode->i_size); + down_write(&EXT4_I(inode)->i_data_sem); + ext4_es_remove_extent(inode, lblk, EXT_MAX_BLOCKS - lblk); + up_write(&EXT4_I(inode)->i_data_sem); + filemap_invalidate_unlock(mapping); +} + static int ext4_da_do_write_end(struct address_space *mapping, loff_t pos, unsigned len, unsigned copied, struct folio *folio) @@ -3381,12 +3480,12 @@ static int ext4_da_do_write_end(struct address_space *mapping, * checked, we need to update i_disksize here as certain * ext4_writepages() paths not allocating blocks and update i_disksize. */ - if (new_i_size > inode->i_size) { + if (copied && new_i_size > inode->i_size) { unsigned long end; i_size_write(inode, new_i_size); end = offset_in_folio(folio, new_i_size - 1); - if (copied && ext4_da_should_update_i_disksize(folio, end)) { + if (ext4_da_should_update_i_disksize(folio, end)) { ext4_update_i_disksize(inode, new_i_size); disksize_changed = true; } @@ -3395,9 +3494,13 @@ static int ext4_da_do_write_end(struct address_space *mapping, folio_unlock(folio); folio_put(folio); - if (pos > old_size) + if (copied && pos > old_size) pagecache_isize_extended(inode, old_size, pos); + /* Drop what ->write_begin() prepared beyond the resulting i_size. */ + if (pos + len > inode->i_size) + ext4_da_truncate_failed_write(inode); + if (!disksize_changed) return copied; @@ -3988,8 +4091,10 @@ int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length, return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_iomap_begin); DEFINE_IOMAP_ITER_NEXT(ext4_iomap_next, ext4_iomap_begin); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_iomap_next); static int ext4_iomap_begin_report(struct inode *inode, loff_t offset, loff_t length, unsigned int flags, @@ -4043,6 +4148,7 @@ static int ext4_iomap_begin_report(struct inode *inode, loff_t offset, } DEFINE_IOMAP_ITER_NEXT(ext4_iomap_next_report, ext4_iomap_begin_report); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_iomap_next_report); static int ext4_iomap_map_blocks(struct inode *inode, loff_t offset, loff_t length, struct ext4_map_blocks *map, @@ -4486,7 +4592,7 @@ static int ext4_iomap_writepages(struct address_space *mapping, */ if (!ext4_inode_buffered_iomap(inode)) { ext4_writepages_up_read(sb, alloc_ctx); - return ret; + return 0; } trace_ext4_writepages(inode, wbc); @@ -4625,6 +4731,7 @@ void ext4_set_aops(struct inode *inode) else inode->i_mapping->a_ops = &ext4_aops; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_set_aops); /* * Here we can't skip an unwritten buffer even though it usually reads zero @@ -5031,6 +5138,7 @@ int ext4_block_zero_eof(struct inode *inode, loff_t from, loff_t end) trace_ext4_block_zero_eof(inode, from, length, did_zero, zero_written); return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_block_zero_eof); /* * Zero out the unaligned head and tail of the [lstart, lstart+length) @@ -5091,6 +5199,7 @@ int ext4_zero_partial_blocks(struct inode *inode, loff_t lstart, loff_t length, } return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_zero_partial_blocks); int ext4_can_truncate(struct inode *inode) { @@ -5102,6 +5211,7 @@ int ext4_can_truncate(struct inode *inode) return !ext4_inode_is_fast_symlink(inode); return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_can_truncate); /* * We have to make sure i_disksize gets properly updated before we truncate @@ -5147,6 +5257,7 @@ int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset, return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_update_disksize_before_punch); static inline void ext4_truncate_folio(struct inode *inode, loff_t start, loff_t end) @@ -5209,6 +5320,7 @@ int ext4_truncate_page_cache_block_range(struct inode *inode, truncate_pagecache_range(inode, start, end - 1); return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_truncate_page_cache_block_range); static void ext4_wait_dax_page(struct inode *inode) { @@ -5224,6 +5336,7 @@ int ext4_break_layouts(struct inode *inode) return dax_break_layout_inode(inode, ext4_wait_dax_page); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_break_layouts); /* * ext4_punch_hole: punches a hole in a file by releasing the blocks @@ -5351,6 +5464,7 @@ int ext4_punch_hole(struct file *file, loff_t offset, loff_t length) ext4_journal_stop(handle); return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_punch_hole); int ext4_inode_attach_jinode(struct inode *inode) { @@ -5381,6 +5495,7 @@ int ext4_inode_attach_jinode(struct inode *inode) jbd2_free_inode(jinode); return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_attach_jinode); /* * ext4_truncate() @@ -5417,6 +5532,8 @@ int ext4_truncate(struct inode *inode) int err = 0, err2; handle_t *handle; + KUNIT_STATIC_STUB_REDIRECT(ext4_truncate, inode); + /* * There is a possibility that we're either freeing the inode * or it's a completely new inode. In those cases we might not @@ -5515,6 +5632,7 @@ int ext4_truncate(struct inode *inode) trace_ext4_truncate_exit(inode); return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_truncate); static inline u64 ext4_inode_peek_iversion(const struct inode *inode) { @@ -5706,7 +5824,7 @@ static int __ext4_get_inode_loc(struct super_block *sb, unsigned long ino, } block += (inode_offset / inodes_per_block); - bh = sb_getblk(sb, block); + bh = ext4_sb_getblk(sb, block); if (unlikely(!bh)) return -ENOMEM; if (ext4_buffer_uptodate(bh)) @@ -5730,8 +5848,13 @@ static int __ext4_get_inode_loc(struct super_block *sb, unsigned long ino, start = inode_offset & ~(inodes_per_block - 1); - /* Is the inode bitmap in cache? */ - bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp)); + /* + * Is the inode bitmap in cache? Non-blocking lookup: bh above + * is locked, and blocking here would folio_lock() against a + * block_read_full_folio() that locks bh the other way round. + */ + bitmap_bh = ext4_sb_find_get_block(sb, + ext4_inode_bitmap(sb, gdp)); if (unlikely(!bitmap_bh)) goto make_io; @@ -5834,6 +5957,8 @@ int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc) ext4_fsblk_t err_blk = 0; int ret; + KUNIT_STATIC_STUB_REDIRECT(ext4_get_inode_loc, inode, iloc); + ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, inode, iloc, &err_blk); @@ -5843,6 +5968,7 @@ int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc) return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_inode_loc); /* * ext4_get_inode_loc_noio() is a best-effort variant of ext4_get_inode_loc(). @@ -5859,6 +5985,8 @@ int ext4_get_inode_loc_noio(struct inode *inode, struct ext4_iloc *iloc) int inodes_per_block, inode_offset; unsigned long ino = inode->i_ino; + KUNIT_STATIC_STUB_REDIRECT(ext4_get_inode_loc_noio, inode, iloc); + iloc->bh = NULL; if (ino < EXT4_ROOT_INO || ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count)) @@ -5884,7 +6012,7 @@ int ext4_get_inode_loc_noio(struct inode *inode, struct ext4_iloc *iloc) } block += inode_offset / inodes_per_block; - bh = sb_find_get_block_nonatomic(sb, block); + bh = ext4_sb_find_get_block_nonatomic(sb, block); if (!bh) return -EAGAIN; if (!ext4_buffer_uptodate(bh)) { @@ -5900,6 +6028,8 @@ int ext4_get_inode_loc_noio(struct inode *inode, struct ext4_iloc *iloc) int ext4_get_fc_inode_loc(struct super_block *sb, unsigned long ino, struct ext4_iloc *iloc) { + KUNIT_STATIC_STUB_REDIRECT(ext4_get_fc_inode_loc, sb, ino, iloc); + return __ext4_get_inode_loc(sb, ino, NULL, iloc, NULL); } @@ -5961,6 +6091,7 @@ void ext4_set_inode_flags(struct inode *inode, bool init) S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX| S_ENCRYPTED|S_CASEFOLD|S_VERITY); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_set_inode_flags); static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode, struct ext4_inode_info *ei) @@ -6017,6 +6148,7 @@ int ext4_get_projid(struct inode *inode, kprojid_t *projid) *projid = EXT4_I(inode)->i_projid; return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_projid); /* * ext4 has self-managed i_version for ea inodes, it stores the lower 32bit of @@ -6169,6 +6301,7 @@ void ext4_set_inode_mapping_order(struct inode *inode) mapping_set_folio_order_range(inode->i_mapping, min_order, max_order); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_set_inode_mapping_order); static int ext4_iget_match(struct inode *inode, u64 ino, void *data) { @@ -6201,6 +6334,8 @@ struct inode *__ext4_iget(struct super_block *sb, unsigned long ino, gid_t i_gid; projid_t i_projid; + KUNIT_STATIC_STUB_REDIRECT(__ext4_iget, sb, ino, flags, function, line); + if ((!(flags & EXT4_IGET_SPECIAL) && is_special_ino(sb, ino)) || (ino < EXT4_ROOT_INO) || (ino > le32_to_cpu(es->s_inodes_count))) { @@ -6452,10 +6587,9 @@ struct inode *__ext4_iget(struct super_block *sb, unsigned long ino, goto bad_inode; } else if (!ext4_has_inline_data(inode)) { /* validate the block references in the inode */ - if (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY) && - (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) || - (S_ISLNK(inode->i_mode) && - !ext4_inode_is_fast_symlink(inode)))) { + if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) || + (S_ISLNK(inode->i_mode) && + !ext4_inode_is_fast_symlink(inode))) { if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) ret = ext4_ext_check_inode(inode); else @@ -6577,6 +6711,7 @@ struct inode *__ext4_iget(struct super_block *sb, unsigned long ino, iget_failed(inode); return ERR_PTR(ret); } +EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_iget); static void __ext4_update_other_inode_time(struct super_block *sb, unsigned long orig_ino, @@ -6781,6 +6916,7 @@ int ext4_write_inode(struct inode *inode, struct writeback_control *wbc) return ext4_fc_commit(EXT4_SB(inode->i_sb)->s_journal, EXT4_I(inode)->i_sync_tid); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_write_inode); int ext4_sync_inode_metadata(struct inode *inode, struct writeback_control *wbc) { @@ -6813,6 +6949,7 @@ int ext4_sync_inode_metadata(struct inode *inode, struct writeback_control *wbc) brelse(iloc.bh); return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sync_inode_metadata); /* * In data=journal mode ext4_journalled_invalidate_folio() may fail to invalidate @@ -7103,7 +7240,7 @@ int ext4_setattr(const struct mnt_idmap *idmap, struct dentry *dentry, attr->ia_size > EXT4_I(inode)->i_inline_size) { error = ext4_convert_inline_data(inode); if (error) - goto err_out; + return error; } if (shrink) { @@ -7163,6 +7300,7 @@ int ext4_setattr(const struct mnt_idmap *idmap, struct dentry *dentry, error = rc; return error; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_setattr); u32 ext4_dio_alignment(struct inode *inode) { @@ -7176,6 +7314,7 @@ u32 ext4_dio_alignment(struct inode *inode) return i_blocksize(inode); return 1; /* use the iomap defaults */ } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_dio_alignment); int ext4_getattr(const struct mnt_idmap *idmap, const struct path *path, struct kstat *stat, u32 request_mask, unsigned int query_flags) @@ -7218,7 +7357,8 @@ int ext4_getattr(const struct mnt_idmap *idmap, const struct path *path, awu_max = sbi->s_awu_max; } - generic_fill_statx_atomic_writes(stat, awu_min, awu_max, 0); + generic_fill_statx_atomic_writes(stat, awu_min, awu_max, + awu_max); } flags = ei->i_flags & EXT4_FL_USER_VISIBLE; @@ -7242,6 +7382,7 @@ int ext4_getattr(const struct mnt_idmap *idmap, const struct path *path, generic_fillattr(idmap, request_mask, inode, stat); return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_getattr); int ext4_file_getattr(const struct mnt_idmap *idmap, const struct path *path, struct kstat *stat, @@ -7276,6 +7417,7 @@ int ext4_file_getattr(const struct mnt_idmap *idmap, stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9); return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_file_getattr); static int ext4_index_trans_blocks(struct inode *inode, int lblocks, int pextents) @@ -7328,6 +7470,7 @@ int ext4_meta_trans_blocks(struct inode *inode, int lblocks, int pextents, return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_meta_trans_blocks); /* * Calculate the journal credits for modifying the number of blocks @@ -7345,6 +7488,7 @@ int ext4_chunk_trans_extent(struct inode *inode, int nrblocks) ret += nrblocks; return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_chunk_trans_extent); /* * Calculate the journal credits for a chunk of data modification. @@ -7359,6 +7503,7 @@ int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks) { return ext4_meta_trans_blocks(inode, nrblocks, 1, 1); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_chunk_trans_blocks); /* * The caller must have previously called ext4_reserve_inode_write(). @@ -7370,6 +7515,8 @@ int ext4_mark_iloc_dirty(handle_t *handle, struct super_block *sb = inode->i_sb; int err = 0; + KUNIT_STATIC_STUB_REDIRECT(ext4_mark_iloc_dirty, handle, inode, iloc); + err = ext4_emergency_state(sb); if (unlikely(err)) { put_bh(iloc->bh); @@ -7403,6 +7550,7 @@ int ext4_mark_iloc_dirty(handle_t *handle, } return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mark_iloc_dirty); /* * On success, We end up with an outstanding reference count against @@ -7433,6 +7581,7 @@ ext4_reserve_inode_write(handle_t *handle, struct inode *inode, ext4_std_error(inode->i_sb, err); return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_reserve_inode_write); static int __ext4_expand_extra_isize(struct inode *inode, unsigned int new_extra_isize, @@ -7590,6 +7739,7 @@ int ext4_expand_extra_isize(struct inode *inode, ext4_journal_stop(handle); return error; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_expand_extra_isize); /* * What we do here is to mark the in-core inode as clean with respect to inode @@ -7611,6 +7761,9 @@ int __ext4_mark_inode_dirty(handle_t *handle, struct inode *inode, struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); int err; + KUNIT_STATIC_STUB_REDIRECT(__ext4_mark_inode_dirty, handle, inode, + func, line); + might_sleep(); trace_ext4_mark_inode_dirty(inode, _RET_IP_); err = ext4_reserve_inode_write(handle, inode, &iloc); @@ -7653,6 +7806,7 @@ void ext4_dirty_inode(struct inode *inode, int flags) ext4_mark_inode_dirty(handle, inode); ext4_journal_stop(handle); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_dirty_inode); int ext4_change_inode_journal_flag(struct inode *inode, int val) { @@ -7914,3 +8068,91 @@ vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf) sb_end_pagefault(inode->i_sb); return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_page_mkwrite); + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +int ext4_inode_csum_verify_test(struct inode *inode, struct ext4_inode *raw, + struct ext4_inode_info *ei) +{ + return ext4_inode_csum_verify(inode, raw, ei); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_csum_verify_test); + +int ext4_inode_blocks_set_test(struct ext4_inode *raw_inode, + struct ext4_inode_info *ei) +{ + return ext4_inode_blocks_set(raw_inode, ei); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_blocks_set_test); + +blkcnt_t ext4_inode_blocks_test(struct ext4_inode *raw_inode, + struct ext4_inode_info *ei) +{ + return ext4_inode_blocks(raw_inode, ei); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_blocks_test); + +int ext4_fill_raw_inode_test(struct inode *inode, struct ext4_inode *raw_inode) +{ + return ext4_fill_raw_inode(inode, raw_inode); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fill_raw_inode_test); + +int ext4_expand_extra_isize_test(struct inode *inode, + unsigned int new_extra_isize, + struct ext4_iloc *iloc, + handle_t *handle, int *no_expand) +{ + return __ext4_expand_extra_isize(inode, new_extra_isize, iloc, + handle, no_expand); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_expand_extra_isize_test); + +int ext4_try_to_expand_extra_isize_test(struct inode *inode, + unsigned int new_extra_isize, + struct ext4_iloc *iloc, + handle_t *handle) +{ + return ext4_try_to_expand_extra_isize(inode, new_extra_isize, + *iloc, handle); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_try_to_expand_extra_isize_test); + +int ext4_da_reserve_space_test(struct inode *inode, int nr_resv) +{ + return ext4_da_reserve_space(inode, nr_resv); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_da_reserve_space_test); + +int ext4_clu_alloc_state_test(struct inode *inode, ext4_lblk_t lblk) +{ + return ext4_clu_alloc_state(inode, lblk); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_clu_alloc_state_test); + +int ext4_insert_delayed_blocks_test(struct inode *inode, ext4_lblk_t lblk, + ext4_lblk_t len) +{ + return ext4_insert_delayed_blocks(inode, lblk, len); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_insert_delayed_blocks_test); + +int ext4_da_map_blocks_test(struct inode *inode, struct ext4_map_blocks *map) +{ + return ext4_da_map_blocks(inode, map); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_da_map_blocks_test); + +int ext4_nonda_switch_test(struct super_block *sb) +{ + return ext4_nonda_switch(sb); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_nonda_switch_test); + +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_inode_loc_noio); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_fc_inode_loc); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_da_get_block_prep); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_da_update_reserve_space); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_da_release_space); +EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_mark_inode_dirty); +#endif diff --git a/fs/ext4/ioctl-test.c b/fs/ext4/ioctl-test.c new file mode 100644 index 00000000000000..8cdb4f7dd639be --- /dev/null +++ b/fs/ext4/ioctl-test.c @@ -0,0 +1,1198 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for fs/ext4/ioctl.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_jbd2.h" +#include "xattr.h" + +#define IOCTL_TEST_NGROUPS 8U +#define IOCTL_TEST_BLK_SIZE 1024U +#define IOCTL_TEST_BLK_BITS 10U +#define IOCTL_TEST_BLOCKS_PER_GRP 1024U +#define IOCTL_TEST_FIRST_DATA_BLK 1U +#define IOCTL_TEST_TOTAL_BLKS (IOCTL_TEST_FIRST_DATA_BLK + \ + IOCTL_TEST_NGROUPS * \ + IOCTL_TEST_BLOCKS_PER_GRP) +#define IOCTL_TEST_INODE_SIZE 256U +#define IOCTL_TEST_EXTRA_ISIZE 32U +#define IOCTL_TEST_INODES_PER_GRP 32U +#define IOCTL_TEST_TOTAL_INODES (IOCTL_TEST_NGROUPS * \ + IOCTL_TEST_INODES_PER_GRP) +#define IOCTL_TEST_FIRST_INO 11U + +struct ioctl_test_ctx { + struct super_block *sb; + struct ext4_sb_info sbi; + struct ext4_super_block *es; + struct blockgroup_lock bgl; + struct gendisk bdev_disk; + struct block_device bdev; + struct request_queue bdev_queue; + struct inode bd_inode; + struct folio *bh_folio; + struct buffer_head sb_bh; + u8 primary_sb_buf[IOCTL_TEST_BLK_SIZE]; + struct buffer_head backup_bhs[IOCTL_TEST_NGROUPS]; + u8 backup_sb_bufs[IOCTL_TEST_NGROUPS][IOCTL_TEST_BLK_SIZE]; + struct buffer_head iloc_bh; + u8 iloc_buf[IOCTL_TEST_BLK_SIZE]; + int sync_bh_calls; + int sync_bh_err; + bool es_shrinker_inited; +}; + +static struct kunit *active_ioctl_test; + +static struct inode *ioctl_test_alloc_inode(struct super_block *sb) +{ + struct ext4_inode_info *ei; + + ei = kzalloc_obj(*ei); + if (!ei) + return NULL; + + init_rwsem(&ei->i_data_sem); + inode_init_once(&ei->vfs_inode); + inode_set_iversion(&ei->vfs_inode, 1); + ei->i_prealloc_node = RB_ROOT; + rwlock_init(&ei->i_prealloc_lock); + ext4_es_init_tree(&ei->i_es_tree); + rwlock_init(&ei->i_es_lock); + INIT_LIST_HEAD(&ei->i_es_list); + spin_lock_init(&ei->i_raw_lock); + spin_lock_init(&ei->i_block_reservation_lock); + ext4_init_pending_tree(&ei->i_pending_tree); + init_rwsem(&ei->xattr_sem); + INIT_LIST_HEAD(&ei->i_rsv_conversion_list); + spin_lock_init(&ei->i_completed_io_lock); + INIT_LIST_HEAD(&ei->i_orphan); + ext4_fc_init_inode(&ei->vfs_inode); + spin_lock_init(&ei->i_fc_lock); + ei->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + ei->i_extra_isize = IOCTL_TEST_EXTRA_ISIZE; + ei->i_last_alloc_group = ~0U; + + return &ei->vfs_inode; +} + +static void ioctl_test_free_inode(struct inode *inode) +{ + kfree(EXT4_I(inode)); +} + +static void ioctl_test_evict_inode(struct inode *inode) +{ + truncate_inode_pages_final(&inode->i_data); + ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS); + clear_inode(inode); +} + +#ifdef CONFIG_QUOTA +static struct dquot __rcu **ioctl_test_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} +#endif + +static const struct super_operations ioctl_test_sops = { + .alloc_inode = ioctl_test_alloc_inode, + .free_inode = ioctl_test_free_inode, + .evict_inode = ioctl_test_evict_inode, +#ifdef CONFIG_QUOTA + .get_dquots = ioctl_test_get_dquots, +#endif +}; + +static void ioctl_test_sb_upd_work(struct work_struct *work) +{ +} + +static void ioctl_test_err_timer(struct timer_list *t) +{ +} + +static int ioctl_test_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static struct file_system_type ioctl_test_fs_type = { + .name = "ext4_ioctl_kunit", + .init_fs_context = ioctl_test_init_fs_context, + .kill_sb = kill_anon_super, +}; + +static struct buffer_head *ioctl_sb_bread_stub(struct super_block *sb, + sector_t block, + blk_opf_t op_flags) +{ + struct kunit *test = active_ioctl_test; + struct ioctl_test_ctx *ctx; + ext4_group_t g; + + if (!test) + return ERR_PTR(-EIO); + ctx = test->priv; + if (!ctx || sb != ctx->sb) + return ERR_PTR(-EIO); + + for (g = 0; g < IOCTL_TEST_NGROUPS; g++) { + ext4_fsblk_t grp_blk = ext4_group_first_block_no(sb, g); + + if ((ext4_fsblk_t)block == grp_blk) { + struct buffer_head *bh = &ctx->backup_bhs[g]; + + get_bh(bh); + return bh; + } + } + + return ERR_PTR(-ENOENT); +} + +static int ioctl_sync_bh_stub(struct buffer_head *bh) +{ + struct kunit *test = active_ioctl_test; + struct ioctl_test_ctx *ctx; + + if (!test) + return 0; + ctx = test->priv; + if (!ctx) + return 0; + + ctx->sync_bh_calls++; + return ctx->sync_bh_err; +} + +static int ioctl_get_inode_loc_stub(struct inode *inode, struct ext4_iloc *iloc) +{ + struct kunit *test = active_ioctl_test; + struct ioctl_test_ctx *ctx; + + if (!test) + return -EIO; + ctx = test->priv; + if (!ctx) + return -EIO; + + get_bh(&ctx->iloc_bh); + iloc->bh = &ctx->iloc_bh; + iloc->offset = 0; + iloc->block_group = 0; + return 0; +} + +static int ioctl_mark_iloc_dirty_stub(handle_t *handle, struct inode *inode, + struct ext4_iloc *iloc) +{ + brelse(iloc->bh); + iloc->bh = NULL; + return 0; +} + +static void ioctl_init_mock_bh(struct buffer_head *bh, + struct block_device *bdev, struct folio *folio, + u8 *data, size_t size, sector_t blocknr) +{ + memset(bh, 0, sizeof(*bh)); + bh->b_bdev = bdev; + bh->b_folio = folio; + bh->b_data = (char *)data; + bh->b_size = size; + bh->b_blocknr = blocknr; + atomic_set(&bh->b_count, 2); + set_buffer_uptodate(bh); +} + +static void ioctl_sync_backups_from_primary(struct ioctl_test_ctx *ctx) +{ + struct super_block *sb = ctx->sb; + ext4_group_t g; + + ext4_superblock_csum_set(sb); + for (g = 0; g < IOCTL_TEST_NGROUPS; g++) { + struct ext4_super_block *bes; + + bes = (struct ext4_super_block *)ctx->backup_sb_bufs[g]; + memcpy(bes, ctx->es, sizeof(*bes)); + bes->s_block_group_nr = cpu_to_le16(g); + if (ext4_has_feature_metadata_csum(sb)) + bes->s_checksum = ext4_superblock_csum(bes); + } +} + +static void ioctl_test_cleanup(struct ioctl_test_ctx *ctx) +{ + active_ioctl_test = NULL; + + cancel_work_sync(&ctx->sbi.s_sb_upd_work); + timer_delete_sync(&ctx->sbi.s_err_report); + + if (ctx->sb) { + deactivate_super(ctx->sb); + rcu_barrier(); + } + + if (ctx->es_shrinker_inited) { + ext4_es_unregister_shrinker(&ctx->sbi); + ext4_es_destroy_stats(&ctx->sbi); + } + + percpu_counter_destroy(&ctx->sbi.s_freeclusters_counter); + percpu_counter_destroy(&ctx->sbi.s_dirtyclusters_counter); + percpu_counter_destroy(&ctx->sbi.s_freeinodes_counter); + + if (ctx->bh_folio) + folio_put(ctx->bh_folio); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); +} + +KUNIT_DEFINE_ACTION_WRAPPER(ioctl_test_cleanup_action, ioctl_test_cleanup, + struct ioctl_test_ctx *); + +static int ioctl_test_init(struct kunit *test) +{ + struct ioctl_test_ctx *ctx; + struct fs_context *fc; + struct super_block *sb; + struct ext4_sb_info *sbi; + struct inode *root_inode; + ext4_group_t g; + int err; + + ctx = kzalloc_obj(*ctx); + KUNIT_ASSERT_NOT_NULL(test, ctx); + test->priv = ctx; + + ctx->bdev.bd_stats = alloc_percpu(struct disk_stats); + if (!ctx->bdev.bd_stats) { + kfree(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc bd_stats"); + } + + ctx->bh_folio = folio_alloc(GFP_KERNEL, 0); + if (!ctx->bh_folio) { + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc bh_folio"); + } + + fc = fs_context_for_mount(&ioctl_test_fs_type, 0); + if (IS_ERR(fc)) { + err = PTR_ERR(fc); + folio_put(ctx->bh_folio); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + sb = sget_fc(fc, NULL, set_anon_super_fc); + put_fs_context(fc); + if (IS_ERR(sb)) { + err = PTR_ERR(sb); + folio_put(ctx->bh_folio); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + ctx->sb = sb; + sbi = &ctx->sbi; + + INIT_WORK(&sbi->s_sb_upd_work, ioctl_test_sb_upd_work); + timer_setup(&sbi->s_err_report, ioctl_test_err_timer, 0); + + err = percpu_counter_init(&sbi->s_freeclusters_counter, 0, GFP_KERNEL); + if (err) { + up_write(&sb->s_umount); + ioctl_test_cleanup(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + err = percpu_counter_init(&sbi->s_dirtyclusters_counter, 0, GFP_KERNEL); + if (err) { + up_write(&sb->s_umount); + ioctl_test_cleanup(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + err = percpu_counter_init(&sbi->s_freeinodes_counter, 0, GFP_KERNEL); + if (err) { + up_write(&sb->s_umount); + ioctl_test_cleanup(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + + spin_lock_init(&sbi->s_error_lock); + spin_lock_init(&sbi->s_md_lock); + spin_lock_init(&sbi->s_bdev_wb_lock); + spin_lock_init(&sbi->s_es_lock); + INIT_LIST_HEAD(&sbi->s_es_list); + mutex_init(&sbi->s_fc_lock); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_STAGING]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_STAGING]); + ratelimit_state_init(&sbi->s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + + sbi->s_sb = sb; + sb->s_fs_info = sbi; + sb->s_op = &ioctl_test_sops; +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; +#endif + sb->s_flags |= SB_ACTIVE; + sb->s_blocksize = IOCTL_TEST_BLK_SIZE; + sb->s_blocksize_bits = IOCTL_TEST_BLK_BITS; + sb->s_maxbytes = MAX_LFS_FILESIZE; + sb->s_time_gran = 1; + sb->s_xattr = ext4_xattr_handlers; + strscpy(sb->s_id, "ext4_ioctl_kunit", sizeof(sb->s_id)); + + err = ext4_es_register_shrinker(sbi); + if (err) { + up_write(&sb->s_umount); + ioctl_test_cleanup(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + ctx->es_shrinker_inited = true; + + inode_init_once(&ctx->bd_inode); + ctx->bd_inode.i_sb = sb; + ctx->bd_inode.i_blkbits = IOCTL_TEST_BLK_BITS; + ctx->bd_inode.i_mapping = &ctx->bd_inode.i_data; + ctx->bd_inode.i_data.host = &ctx->bd_inode; + ctx->bdev_queue.limits.logical_block_size = 512; + ctx->bdev_queue.limits.dma_alignment = 511; + ctx->bdev_disk.part0 = &ctx->bdev; + ctx->bdev_disk.queue = &ctx->bdev_queue; + ctx->bdev.bd_disk = &ctx->bdev_disk; + ctx->bdev.bd_queue = &ctx->bdev_queue; + ctx->bdev.bd_mapping = &ctx->bd_inode.i_data; + bdev_clear_flag(&ctx->bdev, BD_READ_ONLY); + sb->s_bdev = &ctx->bdev; + + bgl_lock_init(&ctx->bgl); + sbi->s_blockgroup_lock = &ctx->bgl; + + ctx->es = (struct ext4_super_block *)ctx->primary_sb_buf; + ctx->es->s_magic = cpu_to_le16(EXT4_SUPER_MAGIC); + ctx->es->s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + ctx->es->s_first_ino = cpu_to_le32(IOCTL_TEST_FIRST_INO); + ctx->es->s_inode_size = cpu_to_le16(IOCTL_TEST_INODE_SIZE); + ctx->es->s_want_extra_isize = cpu_to_le16(IOCTL_TEST_EXTRA_ISIZE); + ctx->es->s_min_extra_isize = cpu_to_le16(IOCTL_TEST_EXTRA_ISIZE); + ctx->es->s_first_data_block = cpu_to_le32(IOCTL_TEST_FIRST_DATA_BLK); + ctx->es->s_blocks_per_group = cpu_to_le32(IOCTL_TEST_BLOCKS_PER_GRP); + ctx->es->s_clusters_per_group = cpu_to_le32(IOCTL_TEST_BLOCKS_PER_GRP); + ctx->es->s_inodes_per_group = cpu_to_le32(IOCTL_TEST_INODES_PER_GRP); + ctx->es->s_inodes_count = cpu_to_le32(IOCTL_TEST_TOTAL_INODES); + ext4_blocks_count_set(ctx->es, IOCTL_TEST_TOTAL_BLKS); + ctx->es->s_checksum_type = EXT4_CRC32C_CHKSUM; + ctx->es->s_feature_incompat = cpu_to_le32(EXT4_FEATURE_INCOMPAT_EXTENTS | + EXT4_FEATURE_INCOMPAT_64BIT); + ctx->es->s_feature_ro_compat = + cpu_to_le32(EXT4_FEATURE_RO_COMPAT_SPARSE_SUPER | + EXT4_FEATURE_RO_COMPAT_METADATA_CSUM | + EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE); + generate_random_uuid(ctx->es->s_uuid); + + ioctl_init_mock_bh(&ctx->sb_bh, &ctx->bdev, ctx->bh_folio, + ctx->primary_sb_buf, IOCTL_TEST_BLK_SIZE, + IOCTL_TEST_FIRST_DATA_BLK); + for (g = 0; g < IOCTL_TEST_NGROUPS; g++) { + ext4_fsblk_t blk = IOCTL_TEST_FIRST_DATA_BLK + + (ext4_fsblk_t)g * IOCTL_TEST_BLOCKS_PER_GRP; + + ioctl_init_mock_bh(&ctx->backup_bhs[g], &ctx->bdev, + ctx->bh_folio, ctx->backup_sb_bufs[g], + IOCTL_TEST_BLK_SIZE, blk); + } + ioctl_init_mock_bh(&ctx->iloc_bh, &ctx->bdev, ctx->bh_folio, + ctx->iloc_buf, IOCTL_TEST_BLK_SIZE, 20); + + sbi->s_es = ctx->es; + sbi->s_sbh = &ctx->sb_bh; + sbi->s_blocks_per_group = IOCTL_TEST_BLOCKS_PER_GRP; + sbi->s_clusters_per_group = IOCTL_TEST_BLOCKS_PER_GRP; + sbi->s_cluster_ratio = 1; + sbi->s_cluster_bits = 0; + sbi->s_inodes_per_group = IOCTL_TEST_INODES_PER_GRP; + sbi->s_groups_count = IOCTL_TEST_NGROUPS; + sbi->s_inode_size = IOCTL_TEST_INODE_SIZE; + sbi->s_first_ino = IOCTL_TEST_FIRST_INO; + sbi->s_want_extra_isize = IOCTL_TEST_EXTRA_ISIZE; + sbi->s_desc_size = EXT4_MIN_DESC_SIZE_64BIT; + sbi->s_csum_seed = ext4_chksum(~0, ctx->es->s_uuid, + sizeof(ctx->es->s_uuid)); + + ioctl_sync_backups_from_primary(ctx); + + root_inode = new_inode(sb); + if (!root_inode) { + up_write(&sb->s_umount); + ioctl_test_cleanup(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc root_inode"); + } + root_inode->i_ino = EXT4_ROOT_INO; + root_inode->i_mode = S_IFDIR | 0755; + root_inode->i_flags |= S_NOQUOTA; + root_inode->i_op = &simple_dir_inode_operations; + set_nlink(root_inode, 2); + sb->s_root = d_make_root(root_inode); + if (!sb->s_root) { + up_write(&sb->s_umount); + ioctl_test_cleanup(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc s_root"); + } + + up_write(&sb->s_umount); + + err = kunit_add_action_or_reset(test, ioctl_test_cleanup_action, ctx); + KUNIT_ASSERT_EQ(test, err, 0); + + active_ioctl_test = test; + + kunit_activate_static_stub(test, ext4_sb_bread, ioctl_sb_bread_stub); + kunit_activate_static_stub(test, ext4_ioctl_sync_bh, + ioctl_sync_bh_stub); + kunit_activate_static_stub(test, ext4_get_inode_loc, + ioctl_get_inode_loc_stub); + kunit_activate_static_stub(test, ext4_mark_iloc_dirty, + ioctl_mark_iloc_dirty_stub); + + return 0; +} + +/* + * Verify ext4_sb_setlabel, ext4_sb_setuuid, and ext4_sb_setparams across all + * superblock tuneable fields, split 64-bit / 32-bit fields, feature masks, + * and FORCE_FSCK state marking. + */ +static void test_sb_callbacks_and_setparams(struct kunit *test) +{ + struct ioctl_test_ctx *ctx = test->priv; + struct ext4_sb_info *sbi = &ctx->sbi; + struct ext4_super_block *es = ctx->es; + struct ext4_tune_sb_params params; + char label[EXT4_LABEL_MAX] = "ext4_kunit_lbl"; + u8 uuid[UUID_SIZE]; + int i; + + ext4_sb_setlabel_test(sbi, es, label); + KUNIT_EXPECT_MEMEQ(test, es->s_volume_name, label, EXT4_LABEL_MAX); + + for (i = 0; i < UUID_SIZE; i++) + uuid[i] = 0xa0 + i; + ext4_sb_setuuid_test(sbi, es, uuid); + KUNIT_EXPECT_MEMEQ(test, es->s_uuid, uuid, UUID_SIZE); + + memset(¶ms, 0, sizeof(params)); + sbi->s_def_hash_version = DX_HASH_TEA; + sbi->s_csum_seed = 0xdeadbeefU; + params.set_flags = EXT4_TUNE_FL_ERRORS_BEHAVIOR | + EXT4_TUNE_FL_MNT_COUNT | + EXT4_TUNE_FL_MAX_MNT_COUNT | + EXT4_TUNE_FL_CHECKINTRVAL | + EXT4_TUNE_FL_LAST_CHECK_TIME | + EXT4_TUNE_FL_RESERVED_BLOCKS | + EXT4_TUNE_FL_RESERVED_UID | + EXT4_TUNE_FL_RESERVED_GID | + EXT4_TUNE_FL_DEFAULT_MNT_OPTS | + EXT4_TUNE_FL_DEF_HASH_ALG | + EXT4_TUNE_FL_RAID_STRIDE | + EXT4_TUNE_FL_RAID_STRIPE_WIDTH | + EXT4_TUNE_FL_ENCODING | + EXT4_TUNE_FL_ENCODING_FLAGS | + EXT4_TUNE_FL_MOUNT_OPTS | + EXT4_TUNE_FL_EDIT_FEATURES | + EXT4_TUNE_FL_FORCE_FSCK; + params.errors_behavior = EXT4_ERRORS_RO; + params.mnt_count = 7; + params.max_mnt_count = 42; + params.checkinterval = 86400; + params.last_check_time = 1700000000ULL; + params.reserved_blocks = 0x100000055ULL; + params.reserved_uid = 0x12345678U; + params.reserved_gid = 0x87654321U; + params.default_mnt_opts = EXT4_DEFM_ACL | EXT4_DEFM_XATTR_USER; + params.def_hash_alg = DX_HASH_HALF_MD4; + params.raid_stride = 16; + params.raid_stripe_width = 128; + params.encoding = EXT4_ENC_UTF8_12_1; + params.encoding_flags = SB_ENC_STRICT_MODE_FL; + strscpy(params.mount_opts, "nodelalloc,noatime", + sizeof(params.mount_opts)); + params.set_feature_compat_mask = EXT4_FEATURE_COMPAT_DIR_INDEX; + params.set_feature_incompat_mask = EXT4_FEATURE_INCOMPAT_CSUM_SEED; + params.set_feature_ro_compat_mask = EXT4_FEATURE_RO_COMPAT_PROJECT; + + ext4_sb_setparams_test(sbi, es, ¶ms); + + KUNIT_EXPECT_EQ(test, le16_to_cpu(es->s_errors), EXT4_ERRORS_RO); + KUNIT_EXPECT_EQ(test, le16_to_cpu(es->s_mnt_count), 7); + KUNIT_EXPECT_EQ(test, le16_to_cpu(es->s_max_mnt_count), 42); + KUNIT_EXPECT_EQ(test, le32_to_cpu(es->s_checkinterval), 86400U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(es->s_lastcheck), 1700000000U); + KUNIT_EXPECT_EQ(test, ext4_r_blocks_count(es), 0x100000055ULL); + KUNIT_EXPECT_EQ(test, ext4_get_resuid(es), 0x12345678U); + KUNIT_EXPECT_EQ(test, ext4_get_resgid(es), 0x87654321U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(es->s_default_mount_opts), + (u32)(EXT4_DEFM_ACL | EXT4_DEFM_XATTR_USER)); + /* EDIT_FEATURES + DIR_INDEX overrides s_def_hash_version from sbi */ + KUNIT_EXPECT_EQ(test, es->s_def_hash_version, DX_HASH_TEA); + KUNIT_EXPECT_EQ(test, le16_to_cpu(es->s_raid_stride), 16); + KUNIT_EXPECT_EQ(test, le32_to_cpu(es->s_raid_stripe_width), 128U); + KUNIT_EXPECT_EQ(test, le16_to_cpu(es->s_encoding), EXT4_ENC_UTF8_12_1); + KUNIT_EXPECT_EQ(test, le16_to_cpu(es->s_encoding_flags), + SB_ENC_STRICT_MODE_FL); + KUNIT_EXPECT_STREQ(test, (char *)es->s_mount_opts, + "nodelalloc,noatime"); + KUNIT_EXPECT_NE(test, + le32_to_cpu(es->s_feature_compat) & + EXT4_FEATURE_COMPAT_DIR_INDEX, 0U); + KUNIT_EXPECT_NE(test, + le32_to_cpu(es->s_feature_incompat) & + EXT4_FEATURE_INCOMPAT_CSUM_SEED, 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(es->s_checksum_seed), 0xdeadbeefU); + KUNIT_EXPECT_NE(test, + le32_to_cpu(es->s_feature_ro_compat) & + EXT4_FEATURE_RO_COMPAT_PROJECT, 0U); + KUNIT_EXPECT_NE(test, le16_to_cpu(es->s_state) & EXT4_ERROR_FS, 0); +} + +/* + * Verify ext4_validate_tune_sb_params rejects malformed mount_opts, invalid + * flags, out-of-range parameters, unsupported feature edits, and standalone + * encoding updates, while normalizing DIR_INDEX and CASEFOLD enablement. + */ +static void test_validate_tune_sb_params(struct kunit *test) +{ + struct ioctl_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + struct ext4_super_block *es = ctx->es; + struct ext4_tune_sb_params params; + uuid_t uu; + + /* Unterminated mount_opts -> -E2BIG */ + memset(¶ms, 0, sizeof(params)); + memset(params.mount_opts, 'a', sizeof(params.mount_opts)); + KUNIT_EXPECT_EQ(test, ext4_validate_tune_sb_params_test(sb, ¶ms), + -E2BIG); + + /* Unknown set_flags bit -> -EOPNOTSUPP */ + memset(¶ms, 0, sizeof(params)); + params.set_flags = 0x80000000U; + KUNIT_EXPECT_EQ(test, ext4_validate_tune_sb_params_test(sb, ¶ms), + -EOPNOTSUPP); + + /* Invalid errors_behavior -> -EINVAL */ + memset(¶ms, 0, sizeof(params)); + params.set_flags = EXT4_TUNE_FL_ERRORS_BEHAVIOR; + params.errors_behavior = EXT4_ERRORS_PANIC + 1; + KUNIT_EXPECT_EQ(test, ext4_validate_tune_sb_params_test(sb, ¶ms), + -EINVAL); + + /* Reserved blocks > blocks_count / 2 -> -EINVAL, <= half -> 0 */ + memset(¶ms, 0, sizeof(params)); + params.set_flags = EXT4_TUNE_FL_RESERVED_BLOCKS; + params.reserved_blocks = ext4_blocks_count(es) / 2 + 1; + KUNIT_EXPECT_EQ(test, ext4_validate_tune_sb_params_test(sb, ¶ms), + -EINVAL); + params.reserved_blocks = ext4_blocks_count(es) / 2; + KUNIT_EXPECT_EQ(test, ext4_validate_tune_sb_params_test(sb, ¶ms), + 0); + + /* Hash algorithm validation: SIPHASH and > DX_HASH_LAST rejected */ + memset(¶ms, 0, sizeof(params)); + params.set_flags = EXT4_TUNE_FL_DEF_HASH_ALG; + params.def_hash_alg = DX_HASH_SIPHASH; + KUNIT_EXPECT_EQ(test, ext4_validate_tune_sb_params_test(sb, ¶ms), + -EINVAL); + params.def_hash_alg = DX_HASH_LAST + 1; + KUNIT_EXPECT_EQ(test, ext4_validate_tune_sb_params_test(sb, ¶ms), + -EINVAL); + params.def_hash_alg = DX_HASH_HALF_MD4; + KUNIT_EXPECT_EQ(test, ext4_validate_tune_sb_params_test(sb, ¶ms), + 0); + + /* Mutual exclusion of FEATURES and EDIT_FEATURES */ + memset(¶ms, 0, sizeof(params)); + params.set_flags = EXT4_TUNE_FL_FEATURES | EXT4_TUNE_FL_EDIT_FEATURES; + KUNIT_EXPECT_EQ(test, ext4_validate_tune_sb_params_test(sb, ¶ms), + -EINVAL); + + /* Clearing an existing feature via FEATURES -> -EOPNOTSUPP */ + memset(¶ms, 0, sizeof(params)); + params.set_flags = EXT4_TUNE_FL_FEATURES; + params.feature_compat = le32_to_cpu(es->s_feature_compat); + params.feature_incompat = 0; + params.feature_ro_compat = le32_to_cpu(es->s_feature_ro_compat); + KUNIT_EXPECT_EQ(test, ext4_validate_tune_sb_params_test(sb, ¶ms), + -EOPNOTSUPP); + + /* Enabling DIR_INDEX via FEATURES initializes hash seed & default alg */ + memset(sbi->s_hash_seed, 0, sizeof(sbi->s_hash_seed)); + sbi->s_def_hash_version = 0; + memset(¶ms, 0, sizeof(params)); + params.set_flags = EXT4_TUNE_FL_FEATURES; + params.feature_compat = le32_to_cpu(es->s_feature_compat) | + EXT4_FEATURE_COMPAT_DIR_INDEX; + params.feature_incompat = le32_to_cpu(es->s_feature_incompat); + params.feature_ro_compat = le32_to_cpu(es->s_feature_ro_compat) | + EXT4_FEATURE_RO_COMPAT_DIR_NLINK; + KUNIT_EXPECT_EQ(test, ext4_validate_tune_sb_params_test(sb, ¶ms), + 0); + KUNIT_EXPECT_NE(test, params.set_flags & EXT4_TUNE_FL_EDIT_FEATURES, + 0U); + KUNIT_EXPECT_EQ(test, params.set_feature_compat_mask, + (u32)EXT4_FEATURE_COMPAT_DIR_INDEX); + KUNIT_EXPECT_EQ(test, params.set_feature_ro_compat_mask, + (u32)EXT4_FEATURE_RO_COMPAT_DIR_NLINK); + memcpy(&uu, sbi->s_hash_seed, UUID_SIZE); + KUNIT_EXPECT_FALSE(test, uuid_is_null(&uu)); + KUNIT_EXPECT_EQ(test, sbi->s_def_hash_version, DX_HASH_HALF_MD4); + + /* Encoding without CASEFOLD -> -EINVAL; with CASEFOLD -> UTF8_12_1 */ + memset(¶ms, 0, sizeof(params)); + params.set_flags = EXT4_TUNE_FL_ENCODING; + params.encoding = EXT4_ENC_UTF8_12_1; + KUNIT_EXPECT_EQ(test, ext4_validate_tune_sb_params_test(sb, ¶ms), + -EINVAL); + + memset(¶ms, 0, sizeof(params)); + params.set_flags = EXT4_TUNE_FL_EDIT_FEATURES; + params.set_feature_incompat_mask = EXT4_FEATURE_INCOMPAT_CASEFOLD; + KUNIT_EXPECT_EQ(test, ext4_validate_tune_sb_params_test(sb, ¶ms), + 0); + KUNIT_EXPECT_EQ(test, params.encoding, EXT4_ENC_UTF8_12_1); + KUNIT_EXPECT_EQ(test, params.encoding_flags, 0); +} + +/* + * Verify ext4_update_backup_sb, ext4_update_superblocks_fn, and + * ext4_update_overhead across primary + 4 sparse_super backup groups (1, 3, + * 5, 7), covering both journaled (first 2 backups) and unjournaled (remaining + * backups) update paths, EXT4_FLAGS_RESIZING contention, and overhead skip + * conditions. + */ +static void test_update_superblocks_and_overhead(struct kunit *test) +{ + struct ioctl_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + static const ext4_group_t backup_grps[] = { 1, 3, 5, 7 }; + char new_label[EXT4_LABEL_MAX] = "updated_label"; + int i; + + /* Group 2 has no backup superblock under sparse_super */ + KUNIT_EXPECT_EQ(test, + ext4_update_backup_sb_test(sb, NULL, 2, + ext4_sb_setlabel_test, + new_label), + 0); + + /* Contention guard when EXT4_FLAGS_RESIZING is already set */ + set_bit(EXT4_FLAGS_RESIZING, &sbi->s_ext4_flags); + KUNIT_EXPECT_EQ(test, + ext4_update_superblocks_fn_test(sb, + ext4_sb_setlabel_test, + new_label), + -EBUSY); + clear_bit(EXT4_FLAGS_RESIZING, &sbi->s_ext4_flags); + + /* Full superblock update across primary (grp 0) + 4 backups */ + ctx->sync_bh_calls = 0; + KUNIT_EXPECT_EQ(test, + ext4_update_superblocks_fn_test(sb, + ext4_sb_setlabel_test, + new_label), + 0); + KUNIT_EXPECT_FALSE(test, + test_bit(EXT4_FLAGS_RESIZING, &sbi->s_ext4_flags)); + /* 1 primary + 4 backup superblocks synced */ + KUNIT_EXPECT_EQ(test, ctx->sync_bh_calls, 5); + KUNIT_EXPECT_MEMEQ(test, ctx->es->s_volume_name, new_label, + EXT4_LABEL_MAX); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es->s_checksum), + le32_to_cpu(ext4_superblock_csum(ctx->es))); + + for (i = 0; i < ARRAY_SIZE(backup_grps); i++) { + ext4_group_t g = backup_grps[i]; + struct ext4_super_block *bes; + + bes = (struct ext4_super_block *)ctx->backup_sb_bufs[g]; + KUNIT_EXPECT_MEMEQ(test, bes->s_volume_name, new_label, + EXT4_LABEL_MAX); + KUNIT_EXPECT_EQ(test, le32_to_cpu(bes->s_checksum), + le32_to_cpu(ext4_superblock_csum(bes))); + } + + /* ext4_update_overhead skip & force behavior */ + ctx->sync_bh_calls = 0; + sbi->s_overhead = 0; + KUNIT_EXPECT_EQ(test, ext4_update_overhead(sb, false), 0); + KUNIT_EXPECT_EQ(test, ctx->sync_bh_calls, 0); + + sbi->s_overhead = 77; + sb->s_flags |= SB_RDONLY; + KUNIT_EXPECT_EQ(test, ext4_update_overhead(sb, true), 0); + KUNIT_EXPECT_EQ(test, ctx->sync_bh_calls, 0); + sb->s_flags &= ~SB_RDONLY; + + set_bit(EXT4_FLAGS_SHUTDOWN, &sbi->s_ext4_flags); + KUNIT_EXPECT_EQ(test, ext4_update_overhead(sb, true), 0); + KUNIT_EXPECT_EQ(test, ctx->sync_bh_calls, 0); + clear_bit(EXT4_FLAGS_SHUTDOWN, &sbi->s_ext4_flags); + + KUNIT_EXPECT_EQ(test, ext4_update_overhead(sb, false), 0); + KUNIT_EXPECT_EQ(test, ctx->sync_bh_calls, 5); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es->s_overhead_clusters), 77U); + + /* Matching s_overhead skips when !force, updates when force == true */ + ctx->sync_bh_calls = 0; + KUNIT_EXPECT_EQ(test, ext4_update_overhead(sb, false), 0); + KUNIT_EXPECT_EQ(test, ctx->sync_bh_calls, 0); + KUNIT_EXPECT_EQ(test, ext4_update_overhead(sb, true), 0); + KUNIT_EXPECT_EQ(test, ctx->sync_bh_calls, 5); +} + +/* + * Verify swap_inode_data swaps i_data, i_disksize, i_size, i_version, + * atime/mtime, and EXT4_FL_SHOULD_SWAP flags while preserving non-swapped + * flags, clears both extent-status caches, and restores exact state when + * invoked a second time. Also verify ext4_reset_inode_seed. + */ +static void test_swap_inode_data_and_seed(struct kunit *test) +{ + struct ioctl_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct inode *inode1, *inode2; + struct ext4_inode_info *ei1, *ei2; + struct timespec64 at1 = { .tv_sec = 1000, .tv_nsec = 111 }; + struct timespec64 at2 = { .tv_sec = 2000, .tv_nsec = 222 }; + struct timespec64 mt1 = { .tv_sec = 3000, .tv_nsec = 333 }; + struct timespec64 mt2 = { .tv_sec = 4000, .tv_nsec = 444 }; + __le32 orig_data1[EXT4_N_BLOCKS]; + __le32 orig_data2[EXT4_N_BLOCKS]; + u32 seed1, seed2; + int i; + + inode1 = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, inode1); + inode2 = new_inode(sb); + if (!inode2) { + iput(inode1); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc inode2"); + } + ei1 = EXT4_I(inode1); + ei2 = EXT4_I(inode2); + + for (i = 0; i < EXT4_N_BLOCKS; i++) { + ei1->i_data[i] = cpu_to_le32(0x100 + i); + ei2->i_data[i] = cpu_to_le32(0x200 + i); + } + memcpy(orig_data1, ei1->i_data, sizeof(orig_data1)); + memcpy(orig_data2, ei2->i_data, sizeof(orig_data2)); + + ei1->i_flags = EXT4_EXTENTS_FL | EXT4_HUGE_FILE_FL | EXT4_IMMUTABLE_FL; + ei2->i_flags = EXT4_NOATIME_FL; + ei1->i_disksize = 0x11000; + ei2->i_disksize = 0x22000; + i_size_write(inode1, 0x10500); + i_size_write(inode2, 0x20500); + inode_set_iversion_raw(inode1, 10); + inode_set_iversion_raw(inode2, 20); + inode_set_atime_to_ts(inode1, at1); + inode_set_atime_to_ts(inode2, at2); + inode_set_mtime_to_ts(inode1, mt1); + inode_set_mtime_to_ts(inode2, mt2); + + ext4_es_insert_extent(inode1, 0, 4, 50, EXTENT_STATUS_WRITTEN, false); + ext4_es_insert_extent(inode2, 8, 2, 60, EXTENT_STATUS_WRITTEN, false); + KUNIT_EXPECT_EQ(test, ei1->i_es_all_nr, 1U); + KUNIT_EXPECT_EQ(test, ei2->i_es_all_nr, 1U); + + ext4_swap_inode_data_test(inode1, inode2); + + KUNIT_EXPECT_MEMEQ(test, ei1->i_data, orig_data2, sizeof(orig_data2)); + KUNIT_EXPECT_MEMEQ(test, ei2->i_data, orig_data1, sizeof(orig_data1)); + KUNIT_EXPECT_EQ(test, ei1->i_flags, (u32)EXT4_IMMUTABLE_FL); + KUNIT_EXPECT_EQ(test, ei2->i_flags, + (u32)(EXT4_NOATIME_FL | EXT4_EXTENTS_FL | + EXT4_HUGE_FILE_FL)); + KUNIT_EXPECT_EQ(test, ei1->i_disksize, (loff_t)0x22000); + KUNIT_EXPECT_EQ(test, ei2->i_disksize, (loff_t)0x11000); + KUNIT_EXPECT_EQ(test, i_size_read(inode1), (loff_t)0x20500); + KUNIT_EXPECT_EQ(test, i_size_read(inode2), (loff_t)0x10500); + KUNIT_EXPECT_EQ(test, inode_peek_iversion_raw(inode1), 20ULL); + KUNIT_EXPECT_EQ(test, inode_peek_iversion_raw(inode2), 10ULL); + KUNIT_EXPECT_EQ(test, inode_get_atime_sec(inode1), 2000LL); + KUNIT_EXPECT_EQ(test, inode_get_mtime_sec(inode1), 4000LL); + KUNIT_EXPECT_EQ(test, ei1->i_es_all_nr, 0U); + KUNIT_EXPECT_EQ(test, ei2->i_es_all_nr, 0U); + + /* Second swap restores exact pre-swap attributes */ + ext4_swap_inode_data_test(inode1, inode2); + KUNIT_EXPECT_MEMEQ(test, ei1->i_data, orig_data1, sizeof(orig_data1)); + KUNIT_EXPECT_MEMEQ(test, ei2->i_data, orig_data2, sizeof(orig_data2)); + KUNIT_EXPECT_EQ(test, ei1->i_flags, + (u32)(EXT4_EXTENTS_FL | EXT4_HUGE_FILE_FL | + EXT4_IMMUTABLE_FL)); + KUNIT_EXPECT_EQ(test, ei2->i_flags, (u32)EXT4_NOATIME_FL); + KUNIT_EXPECT_EQ(test, ei1->i_disksize, (loff_t)0x11000); + KUNIT_EXPECT_EQ(test, i_size_read(inode1), (loff_t)0x10500); + + /* ext4_reset_inode_seed with and without metadata_csum */ + inode1->i_ino = 42; + inode1->i_generation = 7; + ei1->i_csum_seed = 0; + ext4_reset_inode_seed(inode1); + seed1 = ei1->i_csum_seed; + KUNIT_EXPECT_NE(test, seed1, 0U); + + inode1->i_generation = 8; + ext4_reset_inode_seed(inode1); + seed2 = ei1->i_csum_seed; + KUNIT_EXPECT_NE(test, seed2, seed1); + + ext4_clear_feature_metadata_csum(sb); + ei1->i_csum_seed = 0x12345678U; + ext4_reset_inode_seed(inode1); + KUNIT_EXPECT_EQ(test, ei1->i_csum_seed, 0x12345678U); + + iput(inode1); + iput(inode2); +} + +/* + * Verify ext4_ioctl_check_immutable, dax_compatible, ext4_fileattr_get, and + * ext4_fileattr_set flag masking, mode checks, quota-file protection, and + * end-to-end VFS inode flag synchronization. + */ +static void test_immutable_dax_and_fileattr(struct kunit *test) +{ + struct ioctl_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct inode *reg_inode, *dir_inode; + struct dentry *reg_dentry, *dir_dentry; + struct ext4_inode_info *rei, *dei; + struct file_kattr fa; + + reg_inode = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, reg_inode); + dir_inode = new_inode(sb); + if (!dir_inode) { + iput(reg_inode); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc dir_inode"); + } + reg_inode->i_ino = 100; + reg_inode->i_mode = S_IFREG | 0644; + dir_inode->i_ino = 101; + dir_inode->i_mode = S_IFDIR | 0755; + rei = EXT4_I(reg_inode); + dei = EXT4_I(dir_inode); + + reg_dentry = d_alloc_anon(sb); + if (!reg_dentry) { + iput(dir_inode); + iput(reg_inode); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc reg_dentry"); + } + d_instantiate(reg_dentry, reg_inode); + dir_dentry = d_alloc_anon(sb); + if (!dir_dentry) { + dput(reg_dentry); + iput(dir_inode); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc dir_dentry"); + } + d_instantiate(dir_dentry, dir_inode); + + /* ext4_ioctl_check_immutable */ + ext4_set_feature_project(sb); + rei->i_projid = make_kprojid(&init_user_ns, 10); + rei->i_flags = EXT4_IMMUTABLE_FL | EXT4_NOATIME_FL; + KUNIT_EXPECT_EQ(test, + ext4_ioctl_check_immutable_test(reg_inode, 10, + EXT4_IMMUTABLE_FL | EXT4_NOATIME_FL), + 0); + /* Clearing IMMUTABLE_FL is allowed here (CAP_LINUX_IMMUTABLE checked in VFS) */ + KUNIT_EXPECT_EQ(test, + ext4_ioctl_check_immutable_test(reg_inode, 10, + EXT4_NOATIME_FL), + 0); + /* Changing other flags or projid while keeping IMMUTABLE_FL -> -EPERM */ + KUNIT_EXPECT_EQ(test, + ext4_ioctl_check_immutable_test(reg_inode, 10, + EXT4_IMMUTABLE_FL), + -EPERM); + KUNIT_EXPECT_EQ(test, + ext4_ioctl_check_immutable_test(reg_inode, 11, + EXT4_IMMUTABLE_FL | EXT4_NOATIME_FL), + -EPERM); + + /* dax_compatible */ + KUNIT_EXPECT_FALSE(test, + ext4_dax_compatible_test(reg_inode, EXT4_VERITY_FL, + EXT4_DAX_FL)); + KUNIT_EXPECT_FALSE(test, + ext4_dax_compatible_test(reg_inode, + EXT4_INLINE_DATA_FL, + EXT4_DAX_FL)); + KUNIT_EXPECT_FALSE(test, + ext4_dax_compatible_test(reg_inode, EXT4_DAX_FL, + EXT4_JOURNAL_DATA_FL)); + /* Inline directory MAY toggle DAX_FL */ + KUNIT_EXPECT_TRUE(test, + ext4_dax_compatible_test(dir_inode, + EXT4_INLINE_DATA_FL, + EXT4_INLINE_DATA_FL | + EXT4_DAX_FL)); + /* VERITY_IN_PROGRESS blocks enabling DAX_FL */ + ext4_set_inode_state(reg_inode, EXT4_STATE_VERITY_IN_PROGRESS); + KUNIT_EXPECT_FALSE(test, + ext4_dax_compatible_test(reg_inode, 0, EXT4_DAX_FL)); + ext4_clear_inode_state(reg_inode, EXT4_STATE_VERITY_IN_PROGRESS); + + /* ext4_fileattr_get: strips PROJINHERIT on reg file, keeps on dir */ + rei->i_flags = EXT4_NOATIME_FL | EXT4_PROJINHERIT_FL | EXT4_RESERVED_FL; + dei->i_flags = EXT4_NOATIME_FL | EXT4_PROJINHERIT_FL; + dei->i_projid = make_kprojid(&init_user_ns, 25); + + memset(&fa, 0, sizeof(fa)); + KUNIT_EXPECT_EQ(test, ext4_fileattr_get(reg_dentry, &fa), 0); + KUNIT_EXPECT_EQ(test, fa.flags, (u32)EXT4_NOATIME_FL); + KUNIT_EXPECT_EQ(test, fa.fsx_projid, 10U); + + memset(&fa, 0, sizeof(fa)); + KUNIT_EXPECT_EQ(test, ext4_fileattr_get(dir_dentry, &fa), 0); + KUNIT_EXPECT_EQ(test, fa.flags, + (u32)(EXT4_NOATIME_FL | EXT4_PROJINHERIT_FL)); + KUNIT_EXPECT_EQ(test, fa.fsx_projid, 25U); + + /* ext4_fileattr_set error paths and success path */ + ext4_clear_feature_project(sb); + rei->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + rei->i_flags = 0; + + /* Flag outside EXT4_FL_USER_VISIBLE -> -EOPNOTSUPP */ + memset(&fa, 0, sizeof(fa)); + fileattr_fill_flags(&fa, EXT4_RESERVED_FL); + KUNIT_EXPECT_EQ(test, + ext4_fileattr_set(&nop_mnt_idmap, reg_dentry, &fa), + -EOPNOTSUPP); + + /* Directory-only flag on regular file -> -EOPNOTSUPP */ + memset(&fa, 0, sizeof(fa)); + fileattr_fill_flags(&fa, EXT4_PROJINHERIT_FL); + KUNIT_EXPECT_EQ(test, + ext4_fileattr_set(&nop_mnt_idmap, reg_dentry, &fa), + -EOPNOTSUPP); + + /* Quota file cannot be modified -> -EPERM */ + reg_inode->i_flags |= S_NOQUOTA; + memset(&fa, 0, sizeof(fa)); + fileattr_fill_flags(&fa, EXT4_NOATIME_FL); + KUNIT_EXPECT_EQ(test, + ext4_fileattr_set(&nop_mnt_idmap, reg_dentry, &fa), + -EPERM); + reg_inode->i_flags &= ~S_NOQUOTA; + + /* CASEFOLD_FL without casefold feature -> -EOPNOTSUPP */ + memset(&fa, 0, sizeof(fa)); + fileattr_fill_flags(&fa, EXT4_CASEFOLD_FL); + KUNIT_EXPECT_EQ(test, + ext4_fileattr_set(&nop_mnt_idmap, dir_dentry, &fa), + -EOPNOTSUPP); + + /* End-to-end setflags on regular file updates ei->i_flags & VFS flags */ + memset(&fa, 0, sizeof(fa)); + fileattr_fill_flags(&fa, EXT4_NOATIME_FL | EXT4_SYNC_FL | + EXT4_NODUMP_FL); + KUNIT_EXPECT_EQ(test, + ext4_fileattr_set(&nop_mnt_idmap, reg_dentry, &fa), + 0); + KUNIT_EXPECT_EQ(test, + rei->i_flags & (EXT4_NOATIME_FL | EXT4_SYNC_FL | + EXT4_NODUMP_FL), + (u32)(EXT4_NOATIME_FL | EXT4_SYNC_FL | EXT4_NODUMP_FL)); + KUNIT_EXPECT_NE(test, reg_inode->i_flags & S_NOATIME, 0U); + KUNIT_EXPECT_NE(test, reg_inode->i_flags & S_SYNC, 0U); + + dput(reg_dentry); + dput(dir_dentry); +} + +/* + * Verify ext4_force_shutdown state transitions and ext4_ioctl / + * ext4_compat_ioctl command dispatch for unknown commands, feature-gated + * commands, mode checks, FITRIM preconditions, and EXT4_IOC_CLEAR_ES_CACHE. + */ +static void test_force_shutdown_and_ioctl_dispatch(struct kunit *test) +{ + struct ioctl_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct inode *inode; + struct dentry *dentry; + struct vfsmount mnt = { + .mnt_root = sb->s_root, + .mnt_sb = sb, + .mnt_idmap = &nop_mnt_idmap, + }; + + inode = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, inode); + inode->i_ino = 200; + inode->i_mode = S_IFREG | 0644; + dentry = d_alloc_anon(sb); + if (!dentry) { + iput(inode); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc dentry"); + } + d_instantiate(dentry, inode); + + { + struct file filp = { + .f_inode = inode, + .f_path = { + .mnt = &mnt, + .dentry = dentry, + }, + .f_mode = FMODE_READ | FMODE_WRITE, + }; + + /* Unknown command dispatch */ + KUNIT_EXPECT_EQ(test, ext4_ioctl(&filp, 0xffffffffU, 0), + -ENOTTY); +#ifdef CONFIG_COMPAT + KUNIT_EXPECT_EQ(test, ext4_compat_ioctl(&filp, 0xffffffffU, 0), + -ENOIOCTLCMD); +#endif + + /* Encryption and verity ioctls return -EOPNOTSUPP when off */ + KUNIT_EXPECT_EQ(test, + ext4_ioctl(&filp, FS_IOC_SET_ENCRYPTION_POLICY, + 0), + -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, + ext4_ioctl(&filp, FS_IOC_GET_ENCRYPTION_POLICY, + 0), + -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, + ext4_ioctl(&filp, FS_IOC_ENABLE_VERITY, 0), + -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, + ext4_ioctl(&filp, FS_IOC_MEASURE_VERITY, 0), + -EOPNOTSUPP); +#ifdef CONFIG_COMPAT + KUNIT_EXPECT_EQ(test, + ext4_compat_ioctl(&filp, FS_IOC_ENABLE_VERITY, + 0), + -EOPNOTSUPP); +#endif + + /* SETVERSION rejected with -ENOTTY when metadata_csum is on */ + KUNIT_EXPECT_EQ(test, ext4_ioctl(&filp, EXT4_IOC_SETVERSION, 0), + -ENOTTY); + + /* FITRIM: no discard -> -EOPNOTSUPP; NOLOAD+journal -> -EROFS */ + ctx->bdev_queue.limits.max_discard_sectors = 0; + KUNIT_EXPECT_EQ(test, ext4_ioctl(&filp, FITRIM, 0), + -EOPNOTSUPP); + + ctx->bdev_queue.limits.max_discard_sectors = 1024; + set_opt(sb, NOLOAD); + ext4_set_feature_journal(sb); + KUNIT_EXPECT_EQ(test, ext4_ioctl(&filp, FITRIM, 0), -EROFS); + clear_opt(sb, NOLOAD); + ext4_clear_feature_journal(sb); + + /* MOVE_EXT and SWAP_BOOT require FMODE_WRITE -> -EBADF on RO */ + filp.f_mode = FMODE_READ; + KUNIT_EXPECT_EQ(test, ext4_ioctl(&filp, EXT4_IOC_MOVE_EXT, 0), + -EBADF); + KUNIT_EXPECT_EQ(test, ext4_ioctl(&filp, EXT4_IOC_SWAP_BOOT, 0), + -EBADF); + filp.f_mode = FMODE_READ | FMODE_WRITE; + + /* EXT4_IOC_CLEAR_ES_CACHE empties inode extent status tree */ + ext4_es_insert_extent(inode, 0, 8, 120, EXTENT_STATUS_WRITTEN, + false); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_es_all_nr, 1U); + KUNIT_EXPECT_EQ(test, + ext4_ioctl(&filp, EXT4_IOC_CLEAR_ES_CACHE, 0), + 0); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_es_all_nr, 0U); + } + + /* ext4_force_shutdown validation, NOLOGFLUSH state, and idempotency */ + KUNIT_EXPECT_EQ(test, + ext4_force_shutdown(sb, EXT4_GOING_FLAGS_NOLOGFLUSH + 1), + -EINVAL); + set_opt(sb, DISCARD); + KUNIT_EXPECT_EQ(test, + ext4_force_shutdown(sb, EXT4_GOING_FLAGS_NOLOGFLUSH), + 0); + KUNIT_EXPECT_TRUE(test, ext4_forced_shutdown(sb)); + KUNIT_EXPECT_EQ(test, test_opt(sb, DISCARD), 0U); + /* Repeat shutdown call is a no-op returning 0 */ + KUNIT_EXPECT_EQ(test, + ext4_force_shutdown(sb, EXT4_GOING_FLAGS_DEFAULT), + 0); + + dput(dentry); +} + +static struct kunit_case ioctl_test_cases[] = { + KUNIT_CASE(test_sb_callbacks_and_setparams), + KUNIT_CASE(test_validate_tune_sb_params), + KUNIT_CASE(test_update_superblocks_and_overhead), + KUNIT_CASE(test_swap_inode_data_and_seed), + KUNIT_CASE(test_immutable_dax_and_fileattr), + KUNIT_CASE(test_force_shutdown_and_ioctl_dispatch), + {} +}; + +static struct kunit_suite ioctl_test_suite = { + .name = "ext4_ioctl_test", + .init = ioctl_test_init, + .test_cases = ioctl_test_cases, +}; + +kunit_test_suites(&ioctl_test_suite); + +MODULE_DESCRIPTION("KUnit tests for ext4 ioctl operations"); +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/ioctl.c b/fs/ext4/ioctl.c index e8e579498c9902..83630cd40712c8 100644 --- a/fs/ext4/ioctl.c +++ b/fs/ext4/ioctl.c @@ -27,6 +27,7 @@ #include "fsmap.h" #include #include +#include typedef void ext4_update_sb_callback(struct ext4_sb_info *sbi, struct ext4_super_block *es, @@ -55,6 +56,13 @@ static void ext4_sb_setuuid(struct ext4_sb_info *sbi, memcpy(es->s_uuid, (__u8 *)arg, UUID_SIZE); } +int ext4_ioctl_sync_bh(struct buffer_head *bh) +{ + KUNIT_STATIC_STUB_REDIRECT(ext4_ioctl_sync_bh, bh); + return sync_dirty_buffer(bh); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ioctl_sync_bh); + static int ext4_update_primary_sb(struct super_block *sb, handle_t *handle, ext4_update_sb_callback func, @@ -89,7 +97,7 @@ int ext4_update_primary_sb(struct super_block *sb, handle_t *handle, err = ext4_handle_dirty_metadata(handle, NULL, bh); if (err) goto out_err; - err = sync_dirty_buffer(bh); + err = ext4_ioctl_sync_bh(bh); out_err: ext4_std_error(sb, err); return err; @@ -167,7 +175,7 @@ static int ext4_update_backup_sb(struct super_block *sb, BUFFER_TRACE(bh, "marking dirty"); mark_buffer_dirty(bh); } - err = sync_dirty_buffer(bh); + err = ext4_ioctl_sync_bh(bh); out_bh: brelse(bh); @@ -361,6 +369,7 @@ void ext4_reset_inode_seed(struct inode *inode) csum = ext4_chksum(sbi->s_csum_seed, (__u8 *)&inum, sizeof(inum)); ei->i_csum_seed = ext4_chksum(csum, (__u8 *)&gen, sizeof(gen)); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_reset_inode_seed); /* * Swap the information from the given @inode and the inode @@ -854,6 +863,7 @@ int ext4_force_shutdown(struct super_block *sb, u32 flags) fserror_report_shutdown(sb, GFP_KERNEL); return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_force_shutdown); static int ext4_ioctl_shutdown(struct super_block *sb, unsigned long arg) { @@ -1007,6 +1017,7 @@ int ext4_fileattr_get(struct dentry *dentry, struct file_kattr *fa) return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fileattr_get); int ext4_fileattr_set(const struct mnt_idmap *idmap, struct dentry *dentry, struct file_kattr *fa) @@ -1037,6 +1048,7 @@ int ext4_fileattr_set(const struct mnt_idmap *idmap, out: return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fileattr_set); /* So that the fiemap access checks can't overflow on 32 bit machines. */ #define FIEMAP_MAX_EXTENTS (UINT_MAX / sizeof(struct fiemap_extent)) @@ -1384,81 +1396,74 @@ static void ext4_sb_setparams(struct ext4_sb_info *sbi, EXT4_FEATURE_INCOMPAT_CSUM_SEED) es->s_checksum_seed = cpu_to_le32(sbi->s_csum_seed); } - if (params->set_flags & EXT4_TUNE_FL_FORCE_FSCK) + if (params->set_flags & EXT4_TUNE_FL_FORCE_FSCK) { + sbi->s_mount_state |= EXT4_ERROR_FS; es->s_state |= cpu_to_le16(EXT4_ERROR_FS); + } } -static int ext4_ioctl_set_tune_sb(struct file *filp, - struct ext4_tune_sb_params __user *in) +static int ext4_validate_tune_sb_params(struct super_block *sb, + struct ext4_tune_sb_params *params) { - struct ext4_tune_sb_params params; - struct super_block *sb = file_inode(filp)->i_sb; struct ext4_sb_info *sbi = EXT4_SB(sb); struct ext4_super_block *es = sbi->s_es; int enabling_casefold = 0; - int ret; - if (!capable(CAP_SYS_ADMIN)) - return -EPERM; - - if (copy_from_user(¶ms, in, sizeof(params))) - return -EFAULT; - - if (strnlen(params.mount_opts, sizeof(params.mount_opts)) == - sizeof(params.mount_opts)) + if (strnlen(params->mount_opts, sizeof(params->mount_opts)) == + sizeof(params->mount_opts)) return -E2BIG; - if ((params.set_flags & ~TUNE_OPS_SUPPORTED) != 0) + if ((params->set_flags & ~TUNE_OPS_SUPPORTED) != 0) return -EOPNOTSUPP; - if ((params.set_flags & EXT4_TUNE_FL_ERRORS_BEHAVIOR) && - (params.errors_behavior > EXT4_ERRORS_PANIC)) + if ((params->set_flags & EXT4_TUNE_FL_ERRORS_BEHAVIOR) && + (params->errors_behavior > EXT4_ERRORS_PANIC)) return -EINVAL; - if ((params.set_flags & EXT4_TUNE_FL_RESERVED_BLOCKS) && - (params.reserved_blocks > ext4_blocks_count(sbi->s_es) / 2)) + if ((params->set_flags & EXT4_TUNE_FL_RESERVED_BLOCKS) && + (params->reserved_blocks > ext4_blocks_count(sbi->s_es) / 2)) return -EINVAL; - if ((params.set_flags & EXT4_TUNE_FL_DEF_HASH_ALG) && - ((params.def_hash_alg > DX_HASH_LAST) || - (params.def_hash_alg == DX_HASH_SIPHASH))) + if ((params->set_flags & EXT4_TUNE_FL_DEF_HASH_ALG) && + ((params->def_hash_alg > DX_HASH_LAST) || + (params->def_hash_alg == DX_HASH_SIPHASH))) return -EINVAL; - if ((params.set_flags & EXT4_TUNE_FL_FEATURES) && - (params.set_flags & EXT4_TUNE_FL_EDIT_FEATURES)) + if ((params->set_flags & EXT4_TUNE_FL_FEATURES) && + (params->set_flags & EXT4_TUNE_FL_EDIT_FEATURES)) return -EINVAL; - if (params.set_flags & EXT4_TUNE_FL_FEATURES) { - params.set_feature_compat_mask = - params.feature_compat & + if (params->set_flags & EXT4_TUNE_FL_FEATURES) { + params->set_feature_compat_mask = + params->feature_compat & ~le32_to_cpu(es->s_feature_compat); - params.set_feature_incompat_mask = - params.feature_incompat & + params->set_feature_incompat_mask = + params->feature_incompat & ~le32_to_cpu(es->s_feature_incompat); - params.set_feature_ro_compat_mask = - params.feature_ro_compat & + params->set_feature_ro_compat_mask = + params->feature_ro_compat & ~le32_to_cpu(es->s_feature_ro_compat); - params.clear_feature_compat_mask = - ~params.feature_compat & + params->clear_feature_compat_mask = + ~params->feature_compat & le32_to_cpu(es->s_feature_compat); - params.clear_feature_incompat_mask = - ~params.feature_incompat & + params->clear_feature_incompat_mask = + ~params->feature_incompat & le32_to_cpu(es->s_feature_incompat); - params.clear_feature_ro_compat_mask = - ~params.feature_ro_compat & + params->clear_feature_ro_compat_mask = + ~params->feature_ro_compat & le32_to_cpu(es->s_feature_ro_compat); - params.set_flags |= EXT4_TUNE_FL_EDIT_FEATURES; + params->set_flags |= EXT4_TUNE_FL_EDIT_FEATURES; } - if (params.set_flags & EXT4_TUNE_FL_EDIT_FEATURES) { - if ((params.set_feature_compat_mask & + if (params->set_flags & EXT4_TUNE_FL_EDIT_FEATURES) { + if ((params->set_feature_compat_mask & ~EXT4_TUNE_SET_COMPAT_SUPP) || - (params.set_feature_incompat_mask & + (params->set_feature_incompat_mask & ~EXT4_TUNE_SET_INCOMPAT_SUPP) || - (params.set_feature_ro_compat_mask & + (params->set_feature_ro_compat_mask & ~EXT4_TUNE_SET_RO_COMPAT_SUPP) || - (params.clear_feature_compat_mask & + (params->clear_feature_compat_mask & ~EXT4_TUNE_CLEAR_COMPAT_SUPP) || - (params.clear_feature_incompat_mask & + (params->clear_feature_incompat_mask & ~EXT4_TUNE_CLEAR_INCOMPAT_SUPP) || - (params.clear_feature_ro_compat_mask & + (params->clear_feature_ro_compat_mask & ~EXT4_TUNE_CLEAR_RO_COMPAT_SUPP)) return -EOPNOTSUPP; @@ -1466,34 +1471,35 @@ static int ext4_ioctl_set_tune_sb(struct file *filp, * Filter out the features that are already set from * the set_mask. */ - params.set_feature_compat_mask &= + params->set_feature_compat_mask &= ~le32_to_cpu(es->s_feature_compat); - params.set_feature_incompat_mask &= + params->set_feature_incompat_mask &= ~le32_to_cpu(es->s_feature_incompat); - params.set_feature_ro_compat_mask &= + params->set_feature_ro_compat_mask &= ~le32_to_cpu(es->s_feature_ro_compat); - if ((params.set_feature_incompat_mask & - EXT4_FEATURE_INCOMPAT_CASEFOLD)) { + if (params->set_feature_incompat_mask & + EXT4_FEATURE_INCOMPAT_CASEFOLD) { enabling_casefold = 1; - if (!(params.set_flags & EXT4_TUNE_FL_ENCODING)) { - params.encoding = EXT4_ENC_UTF8_12_1; - params.set_flags |= EXT4_TUNE_FL_ENCODING; + if (!(params->set_flags & EXT4_TUNE_FL_ENCODING)) { + params->encoding = EXT4_ENC_UTF8_12_1; + params->set_flags |= EXT4_TUNE_FL_ENCODING; } - if (!(params.set_flags & EXT4_TUNE_FL_ENCODING_FLAGS)) { - params.encoding_flags = 0; - params.set_flags |= EXT4_TUNE_FL_ENCODING_FLAGS; + if (!(params->set_flags & + EXT4_TUNE_FL_ENCODING_FLAGS)) { + params->encoding_flags = 0; + params->set_flags |= + EXT4_TUNE_FL_ENCODING_FLAGS; } } - if ((params.set_feature_compat_mask & - EXT4_FEATURE_COMPAT_DIR_INDEX)) { - uuid_t uu; + if (params->set_feature_compat_mask & + EXT4_FEATURE_COMPAT_DIR_INDEX) { + uuid_t uu; memcpy(&uu, sbi->s_hash_seed, UUID_SIZE); if (uuid_is_null(&uu)) - generate_random_uuid((char *) - &sbi->s_hash_seed); - if (params.set_flags & EXT4_TUNE_FL_DEF_HASH_ALG) - sbi->s_def_hash_version = params.def_hash_alg; + generate_random_uuid((char *)&sbi->s_hash_seed); + if (params->set_flags & EXT4_TUNE_FL_DEF_HASH_ALG) + sbi->s_def_hash_version = params->def_hash_alg; else if (sbi->s_def_hash_version == 0) sbi->s_def_hash_version = DX_HASH_HALF_MD4; if (!(es->s_flags & @@ -1508,21 +1514,42 @@ static int ext4_ioctl_set_tune_sb(struct file *filp, } } } - if (params.set_flags & EXT4_TUNE_FL_ENCODING) { + if (params->set_flags & EXT4_TUNE_FL_ENCODING) { if (!enabling_casefold) return -EINVAL; - if (params.encoding == 0) - params.encoding = EXT4_ENC_UTF8_12_1; - else if (params.encoding != EXT4_ENC_UTF8_12_1) + if (params->encoding == 0) + params->encoding = EXT4_ENC_UTF8_12_1; + else if (params->encoding != EXT4_ENC_UTF8_12_1) return -EINVAL; } - if (params.set_flags & EXT4_TUNE_FL_ENCODING_FLAGS) { + if (params->set_flags & EXT4_TUNE_FL_ENCODING_FLAGS) { if (!enabling_casefold) return -EINVAL; - if (params.encoding_flags & ~SB_ENC_SUPP_MASK) + if (params->encoding_flags & ~SB_ENC_SUPP_MASK) return -EINVAL; } + return 0; +} + +static int ext4_ioctl_set_tune_sb(struct file *filp, + struct ext4_tune_sb_params __user *in) +{ + struct ext4_tune_sb_params params; + struct super_block *sb = file_inode(filp)->i_sb; + struct ext4_sb_info *sbi = EXT4_SB(sb); + int ret; + + if (!capable(CAP_SYS_ADMIN)) + return -EPERM; + + if (copy_from_user(¶ms, in, sizeof(params))) + return -EFAULT; + + ret = ext4_validate_tune_sb_params(sb, ¶ms); + if (ret) + return ret; + ret = mnt_want_write_file(filp); if (ret) return ret; @@ -1675,10 +1702,10 @@ static long __ext4_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) } case EXT4_IOC_GROUP_ADD: { - struct ext4_new_group_data input; + struct ext4_new_group_input __user *uinput = (void __user *)arg; + struct ext4_new_group_data input = {}; - if (copy_from_user(&input, (struct ext4_new_group_input __user *)arg, - sizeof(input))) + if (copy_from_user(&input, uinput, sizeof(*uinput))) return -EFAULT; return ext4_ioctl_group_add(filp, &input); @@ -1931,6 +1958,7 @@ long ext4_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { return __ext4_ioctl(filp, cmd, arg); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ioctl); #ifdef CONFIG_COMPAT long ext4_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg) @@ -2007,6 +2035,7 @@ long ext4_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg) } return ext4_ioctl(file, cmd, (unsigned long) compat_ptr(arg)); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_compat_ioctl); #endif static void set_overhead(struct ext4_sb_info *sbi, @@ -2027,3 +2056,85 @@ int ext4_update_overhead(struct super_block *sb, bool force) return 0; return ext4_update_superblocks_fn(sb, set_overhead, &sbi->s_overhead); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_update_overhead); + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +void ext4_sb_setlabel_test(struct ext4_sb_info *sbi, + struct ext4_super_block *es, const void *arg) +{ + ext4_sb_setlabel(sbi, es, arg); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sb_setlabel_test); + +void ext4_sb_setuuid_test(struct ext4_sb_info *sbi, + struct ext4_super_block *es, const void *arg) +{ + ext4_sb_setuuid(sbi, es, arg); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sb_setuuid_test); + +void ext4_sb_setparams_test(struct ext4_sb_info *sbi, + struct ext4_super_block *es, const void *arg) +{ + ext4_sb_setparams(sbi, es, arg); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sb_setparams_test); + +int ext4_validate_tune_sb_params_test(struct super_block *sb, + struct ext4_tune_sb_params *params) +{ + return ext4_validate_tune_sb_params(sb, params); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_validate_tune_sb_params_test); + +int ext4_update_primary_sb_test(struct super_block *sb, handle_t *handle, + void (*func)(struct ext4_sb_info *, + struct ext4_super_block *, + const void *), + const void *arg) +{ + return ext4_update_primary_sb(sb, handle, func, arg); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_update_primary_sb_test); + +int ext4_update_backup_sb_test(struct super_block *sb, handle_t *handle, + ext4_group_t grp, + void (*func)(struct ext4_sb_info *, + struct ext4_super_block *, + const void *), + const void *arg) +{ + return ext4_update_backup_sb(sb, handle, grp, func, arg); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_update_backup_sb_test); + +int ext4_update_superblocks_fn_test(struct super_block *sb, + void (*func)(struct ext4_sb_info *, + struct ext4_super_block *, + const void *), + const void *arg) +{ + return ext4_update_superblocks_fn(sb, func, arg); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_update_superblocks_fn_test); + +void ext4_swap_inode_data_test(struct inode *inode1, struct inode *inode2) +{ + swap_inode_data(inode1, inode2); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_swap_inode_data_test); + +int ext4_ioctl_check_immutable_test(struct inode *inode, __u32 new_projid, + unsigned int flags) +{ + return ext4_ioctl_check_immutable(inode, new_projid, flags); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ioctl_check_immutable_test); + +bool ext4_dax_compatible_test(struct inode *inode, unsigned int oldflags, + unsigned int flags) +{ + return dax_compatible(inode, oldflags, flags); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_dax_compatible_test); +#endif diff --git a/fs/ext4/mballoc-test.c b/fs/ext4/mballoc-test.c index d31780075c21e5..bd5dabf74b6fba 100644 --- a/fs/ext4/mballoc-test.c +++ b/fs/ext4/mballoc-test.c @@ -5,8 +5,10 @@ #include #include +#include #include #include +#include #include "ext4.h" #include "mballoc.h" @@ -54,9 +56,19 @@ static void mbt_free_inode(struct inode *inode) kfree(EXT4_I(inode)); } +#ifdef CONFIG_QUOTA +static struct dquot __rcu **mbt_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} +#endif + static const struct super_operations mbt_sops = { .alloc_inode = mbt_alloc_inode, .free_inode = mbt_free_inode, +#ifdef CONFIG_QUOTA + .get_dquots = mbt_get_dquots, +#endif }; static int mbt_init_fs_context(struct fs_context *fc) @@ -79,6 +91,7 @@ static int mbt_mb_init(struct super_block *sb) sb->s_bdev = kzalloc_obj(*sb->s_bdev); if (sb->s_bdev == NULL) return -ENOMEM; + bdev_set_flag(sb->s_bdev, BD_READ_ONLY); sb->s_bdev->bd_queue = kzalloc_obj(struct request_queue); if (sb->s_bdev->bd_queue == NULL) { @@ -92,6 +105,9 @@ static int mbt_mb_init(struct super_block *sb) */ INIT_LIST_HEAD(&sb->s_inodes); sb->s_op = &mbt_sops; +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; +#endif ret = ext4_mb_init(sb); if (ret != 0) @@ -162,10 +178,15 @@ static struct super_block *mbt_ext4_alloc_super_block(void) goto out_deactivate; bgl_lock_init(sbi->s_blockgroup_lock); + spin_lock_init(&sbi->s_error_lock); + ratelimit_state_init(&sbi->s_err_ratelimit_state, 5 * HZ, 10); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, 5 * HZ, 10); + ratelimit_state_init(&sbi->s_msg_ratelimit_state, 5 * HZ, 10); sbi->s_es = &fsb->es; sbi->s_sb = sb; sb->s_fs_info = sbi; + set_opt(sb, ERRORS_CONT); up_write(&sb->s_umount); return sb; @@ -341,15 +362,75 @@ ext4_mb_mark_context_stub(handle_t *handle, struct super_block *sb, bool state, { struct mbt_grp_ctx *grp_ctx = MBT_GRP_CTX(sb, group); struct buffer_head *bitmap_bh = &grp_ctx->bitmap_bh; + struct ext4_group_desc *gdp = &grp_ctx->desc; + ext4_grpblk_t i, already = 0, changed = len; + __u32 free; + + for (i = 0; i < len; i++) { + if (mb_test_bit_test(blkoff + i, bitmap_bh->b_data) == state) + already++; + } + if (flags & 0x0001 /* EXT4_MB_BITMAP_MARKED_CHECK */) + changed = len - already; - if (state) + free = ext4_free_group_clusters(sb, gdp); + if (state) { mb_set_bits(bitmap_bh->b_data, blkoff, len); - else + if (free >= changed) + ext4_free_group_clusters_set(sb, gdp, free - changed); + } else { mb_clear_bits_test(bitmap_bh->b_data, blkoff, len); + ext4_free_group_clusters_set(sb, gdp, free + changed); + } + + if (ret_changed) + *ret_changed = changed; + + return 0; +} +static int +ext4_issue_discard_stub(struct super_block *sb, ext4_group_t block_group, + ext4_grpblk_t cluster, int count) +{ return 0; } +static struct inode *mbt_alloc_test_inode(struct kunit *test, + struct super_block *sb, + umode_t mode) +{ + struct ext4_inode_info *ei; + struct inode *inode; + + ei = kunit_kzalloc(test, sizeof(*ei), GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ei); + + INIT_LIST_HEAD(&ei->i_orphan); + init_rwsem(&ei->xattr_sem); + init_rwsem(&ei->i_data_sem); + ei->i_prealloc_node = RB_ROOT; + atomic_set(&ei->i_prealloc_active, 0); + rwlock_init(&ei->i_prealloc_lock); + spin_lock_init(&ei->i_block_reservation_lock); + spin_lock_init(&ei->i_raw_lock); + + inode = &ei->vfs_inode; + inode_init_once(inode); + spin_lock_init(&inode->i_lock); + init_rwsem(&inode->i_rwsem); + init_rwsem(&inode->i_data.invalidate_lock); + ext4_fc_init_inode(inode); + inode->i_sb = sb; + inode->i_ino = 12; + inode->i_mode = mode; + inode->i_flags |= S_NOQUOTA; + atomic_set(&inode->i_writecount, 1); + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + + return inode; +} + #define TEST_GOAL_GROUP 1 static int mbt_kunit_init(struct kunit *test) { @@ -382,6 +463,9 @@ static int mbt_kunit_init(struct kunit *test) kunit_activate_static_stub(test, ext4_mb_mark_context, ext4_mb_mark_context_stub); + kunit_activate_static_stub(test, + ext4_issue_discard, + ext4_issue_discard_stub); /* stub function will be called in mbt_mb_init->ext4_mb_init */ if (mbt_mb_init(sb) != 0) { @@ -402,7 +486,10 @@ static void mbt_kunit_exit(struct kunit *test) if (!sb) return; + if (sb->s_blocksize <= PAGE_SIZE) + ext4_mb_discard_preallocations_test(sb, 0); mbt_mb_release(sb); + rcu_barrier(); mbt_ctx_release(sb); mbt_ext4_free_super_block(sb); } @@ -417,11 +504,7 @@ static void test_new_blocks_simple(struct kunit *test) ext4_fsblk_t found; struct ext4_sb_info *sbi = EXT4_SB(sb); - inode = kunit_kzalloc(test, sizeof(*inode), GFP_KERNEL); - if (!inode) - return; - - inode->i_sb = sb; + inode = mbt_alloc_test_inode(test, sb, S_IFREG); ar.inode = inode; /* get block at goal */ @@ -527,10 +610,7 @@ test_free_blocks_simple_range(struct kunit *test, ext4_group_t goal_group, struct inode *inode; ext4_fsblk_t block; - inode = kunit_kzalloc(test, sizeof(*inode), GFP_KERNEL); - if (!inode) - return; - inode->i_sb = sb; + inode = mbt_alloc_test_inode(test, sb, S_IFREG); if (len == 0) return; @@ -601,10 +681,7 @@ static void test_mark_diskspace_used(struct kunit *test) mbt_generate_test_ranges(sb, ranges, TEST_RANGE_COUNT); - inode = kunit_kzalloc(test, sizeof(*inode), GFP_KERNEL); - if (!inode) - return; - inode->i_sb = sb; + inode = mbt_alloc_test_inode(test, sb, S_IFREG); ac.ac_status = AC_STATUS_FOUND; ac.ac_sb = sb; @@ -949,6 +1026,1814 @@ static void test_mb_mark_used_cost(struct kunit *test) ext4_mb_unload_buddy_test(&e4b); } +static void test_mb_bit_ops(struct kunit *test) +{ + u8 *buf; + void *unaligned; + int bit, i; + + buf = kunit_kzalloc(test, 128, GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, buf); + + /* + * Use an unaligned pointer (offset by 3 bytes) to exercise + * mb_correct_addr_and_bit() on 64-bit/32-bit architectures. + */ + unaligned = buf + 3; + + mb_set_bit_test(0, unaligned); + mb_set_bit_test(7, unaligned); + mb_set_bit_test(64, unaligned); + KUNIT_EXPECT_NE(test, mb_test_bit_test(0, unaligned), 0); + KUNIT_EXPECT_EQ(test, mb_test_bit_test(1, unaligned), 0); + KUNIT_EXPECT_NE(test, mb_test_bit_test(7, unaligned), 0); + KUNIT_EXPECT_NE(test, mb_test_bit_test(64, unaligned), 0); + + mb_clear_bit_test(7, unaligned); + KUNIT_EXPECT_EQ(test, mb_test_bit_test(7, unaligned), 0); + + bit = mb_find_next_bit_test(unaligned, 128, 1); + KUNIT_EXPECT_EQ(test, bit, 64); + + /* Clamping when no set bit exists before max */ + bit = mb_find_next_bit_test(unaligned, 60, 1); + KUNIT_EXPECT_EQ(test, bit, 60); + + /* Zero-length mb_set_bits / mb_clear_bits should be a no-op */ + memset(buf, 0, 128); + mb_set_bits(buf, 10, 0); + KUNIT_EXPECT_EQ(test, mb_find_next_bit_test(buf, 256, 0), 256); + + /* Multi-word range spanning head bits, 32-bit words, and tail */ + mb_set_bits(buf, 5, 75); + KUNIT_EXPECT_EQ(test, mb_find_next_bit_test(buf, 256, 0), 5); + KUNIT_EXPECT_EQ(test, mb_find_next_zero_bit_test(buf, 256, 5), 80); + /* Clamping when no zero bit exists before max */ + KUNIT_EXPECT_EQ(test, mb_find_next_zero_bit_test(buf, 50, 5), 50); + + /* Clear a sub-range across 32-bit boundaries */ + mb_clear_bits_test(buf, 13, 50); + for (i = 0; i < 100; i++) { + int expected = (i >= 5 && i < 13) || (i >= 63 && i < 80); + + KUNIT_EXPECT_EQ(test, !!mb_test_bit_test(i, buf), expected); + } +} + +static void test_mb_test_and_clear_bits(struct kunit *test) +{ + u8 *buf; + void *bm; + int ret, i; + + buf = kunit_kzalloc(test, 128, GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, buf); + bm = buf; + + /* Case 1: All bits in range [5, 85) are set -> returns -1 and clears all */ + memset(buf, 0xff, 128); + ret = mb_test_and_clear_bits_test(bm, 5, 80); + KUNIT_EXPECT_EQ(test, ret, -1); + KUNIT_EXPECT_NE(test, mb_test_bit_test(4, bm), 0); + for (i = 5; i < 85; i++) + KUNIT_EXPECT_EQ(test, mb_test_bit_test(i, bm), 0); + KUNIT_EXPECT_NE(test, mb_test_bit_test(85, bm), 0); + + /* Case 2: Zero bit in the unaligned head (bit 7) */ + memset(buf, 0xff, 128); + mb_clear_bit_test(7, bm); + ret = mb_test_and_clear_bits_test(bm, 5, 80); + KUNIT_EXPECT_EQ(test, ret, 7); + for (i = 5; i < 85; i++) + KUNIT_EXPECT_EQ(test, mb_test_bit_test(i, bm), 0); + + /* Case 3: Zero bit inside the 32-bit word fast-path region (bit 45) */ + memset(buf, 0xff, 128); + mb_clear_bit_test(45, bm); + ret = mb_test_and_clear_bits_test(bm, 5, 80); + KUNIT_EXPECT_EQ(test, ret, 45); + for (i = 5; i < 85; i++) + KUNIT_EXPECT_EQ(test, mb_test_bit_test(i, bm), 0); +} + +static void test_mb_find_buddy_and_order(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct ext4_buddy e4b; + struct ext4_free_extent ex; + void *bb; + int max = 0, ret; + int ord0, ord1, ord2, ord3; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + ret = ext4_mb_load_buddy_test(sb, TEST_GOAL_GROUP, &e4b); + KUNIT_ASSERT_EQ(test, ret, 0); + + /* Order 0 returns bitmap and bit count */ + bb = mb_find_buddy_test(&e4b, 0, &max); + KUNIT_EXPECT_PTR_EQ(test, bb, e4b.bd_bitmap); + KUNIT_EXPECT_EQ(test, max, (int)(sb->s_blocksize << 3)); + + /* Valid higher order returns buddy offset */ + bb = mb_find_buddy_test(&e4b, 1, &max); + KUNIT_EXPECT_PTR_EQ(test, bb, e4b.bd_buddy + sbi->s_mb_offsets[1]); + KUNIT_EXPECT_EQ(test, max, sbi->s_mb_maxs[1]); + + /* Out-of-bounds order (> bd_blkbits + 1) returns NULL and max = 0 */ + bb = mb_find_buddy_test(&e4b, MB_NUM_ORDERS(sb), &max); + KUNIT_EXPECT_NULL(test, bb); + KUNIT_EXPECT_EQ(test, max, 0); + + /* + * Mark cluster 0 used in group 1: this splits the group so that: + * - cluster 1 is free at order 0 + * - clusters [2, 4) are free at order 1 + * - clusters [4, 8) are free at order 2 + * - clusters [8, 16) are free at order 3 + */ + ex.fe_group = TEST_GOAL_GROUP; + ex.fe_start = 0; + ex.fe_len = 1; + ext4_lock_group(sb, TEST_GOAL_GROUP); + mb_mark_used_test(&e4b, &ex); + ord0 = mb_find_order_for_block_test(&e4b, 1); + ord1 = mb_find_order_for_block_test(&e4b, 2); + ord2 = mb_find_order_for_block_test(&e4b, 4); + ord3 = mb_find_order_for_block_test(&e4b, 8); + ext4_unlock_group(sb, TEST_GOAL_GROUP); + + KUNIT_EXPECT_EQ(test, ord0, 0); + KUNIT_EXPECT_EQ(test, ord1, 1); + KUNIT_EXPECT_EQ(test, ord2, 2); + KUNIT_EXPECT_EQ(test, ord3, 3); + + ext4_mb_unload_buddy_test(&e4b); +} + +static void test_mb_find_extent(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_buddy e4b; + struct ext4_free_extent ex, found_used, found_small, found_coalesced, found_unaligned; + int ret, len_used, len_small, len_coalesced, len_unaligned; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + ret = ext4_mb_load_buddy_test(sb, TEST_GOAL_GROUP, &e4b); + KUNIT_ASSERT_EQ(test, ret, 0); + + /* + * Leave only [10, 26) (16 clusters) free: + * [10, 12) order 1 (2) + [12, 16) order 2 (4) + + * [16, 24) order 3 (8) + [24, 26) order 1 (2). + */ + ext4_lock_group(sb, TEST_GOAL_GROUP); + ex.fe_group = TEST_GOAL_GROUP; + ex.fe_start = 0; + ex.fe_len = 10; + mb_mark_used_test(&e4b, &ex); + + ex.fe_start = 26; + ex.fe_len = EXT4_CLUSTERS_PER_GROUP(sb) - 26; + mb_mark_used_test(&e4b, &ex); + + len_used = mb_find_extent_test(&e4b, 5, 8, &found_used); + len_small = mb_find_extent_test(&e4b, 10, 1, &found_small); + len_coalesced = mb_find_extent_test(&e4b, 10, 20, &found_coalesced); + len_unaligned = mb_find_extent_test(&e4b, 11, 20, &found_unaligned); + ext4_unlock_group(sb, TEST_GOAL_GROUP); + + /* Used block returns 0 */ + KUNIT_EXPECT_EQ(test, len_used, 0); + KUNIT_EXPECT_EQ(test, found_used.fe_len, 0); + + /* Needed = 1 at block 10 returns the order-1 buddy [10, 12) */ + KUNIT_EXPECT_EQ(test, len_small, 2); + KUNIT_EXPECT_EQ(test, found_small.fe_start, 10); + KUNIT_EXPECT_EQ(test, found_small.fe_len, 2); + + /* Needed = 20 at block 10 coalesces across orders 1, 2, 3, 1 -> 16 clusters */ + KUNIT_EXPECT_EQ(test, len_coalesced, 16); + KUNIT_EXPECT_EQ(test, found_coalesced.fe_start, 10); + KUNIT_EXPECT_EQ(test, found_coalesced.fe_len, 16); + + /* Unaligned start at block 11 coalesces [11, 26) -> 15 clusters */ + KUNIT_EXPECT_EQ(test, len_unaligned, 15); + KUNIT_EXPECT_EQ(test, found_unaligned.fe_start, 11); + KUNIT_EXPECT_EQ(test, found_unaligned.fe_len, 15); + + ext4_mb_unload_buddy_test(&e4b); +} + +static void test_mb_generate_buddy_corrupt(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_group_info *grp; + void *bitmap, *buddy; + ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb); + bool is_corrupt; + ext4_grpblk_t corrected_free; + int i; + + bitmap = kunit_kzalloc(test, sb->s_blocksize, GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, bitmap); + buddy = kunit_kzalloc(test, sb->s_blocksize, GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, buddy); + + grp = ext4_get_group_info(sb, TEST_GOAL_GROUP); + KUNIT_ASSERT_NOT_NULL(test, grp); + + /* Mark 10 clusters used in bitmap, so actual free is max - 10 */ + mb_set_bits(bitmap, max, sb->s_blocksize * 8 - max); + mb_set_bits(bitmap, 0, 10); + + ext4_lock_group(sb, TEST_GOAL_GROUP); + for (i = 0; i < MB_NUM_ORDERS(sb); i++) + grp->bb_counters[i] = 0; + /* Intentionally set wrong bb_free = max (mismatch with max - 10) */ + grp->bb_free = max; + memset(buddy, 0xff, sb->s_blocksize); + ext4_mb_generate_buddy_test(sb, buddy, bitmap, TEST_GOAL_GROUP, grp); + is_corrupt = EXT4_MB_GRP_BBITMAP_CORRUPT(grp); + corrected_free = grp->bb_free; + ext4_unlock_group(sb, TEST_GOAL_GROUP); + + KUNIT_EXPECT_TRUE(test, is_corrupt); + KUNIT_EXPECT_EQ(test, corrected_free, max - 10); +} + +static void test_mb_free_blocks_double_free_and_fc_replay(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct ext4_buddy e4b; + struct ext4_free_extent ex; + bool corrupt_normal, corrupt_fc; + ext4_grpblk_t free_after_fc; + int ret; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + /* Part 1: Normal mode double-free marks group bitmap corrupt */ + ret = ext4_mb_load_buddy_test(sb, TEST_GOAL_GROUP, &e4b); + KUNIT_ASSERT_EQ(test, ret, 0); + + ext4_lock_group(sb, TEST_GOAL_GROUP); + /* Clusters [10, 14) are already free; freeing them again is a double free */ + mb_free_blocks_test(NULL, &e4b, 10, 4); + corrupt_normal = EXT4_MB_GRP_BBITMAP_CORRUPT(e4b.bd_info); + ext4_unlock_group(sb, TEST_GOAL_GROUP); + ext4_mb_unload_buddy_test(&e4b); + + KUNIT_EXPECT_TRUE(test, corrupt_normal); + + /* + * Part 2: In EXT4_FC_REPLAY mode, freeing an already-freed range + * triggers mb_regenerate_buddy() instead of marking the group corrupt. + */ + ret = ext4_mb_load_buddy_test(sb, 2, &e4b); + KUNIT_ASSERT_EQ(test, ret, 0); + + ext4_lock_group(sb, 2); + ex.fe_group = 2; + ex.fe_start = 10; + ex.fe_len = 10; + mb_mark_used_test(&e4b, &ex); + /* Free sub-range [12, 16) first so [12, 16) is already free */ + mb_free_blocks_test(NULL, &e4b, 12, 4); + + /* Re-freeing [12, 16) in EXT4_FC_REPLAY mode regenerates buddy cleanly */ + sbi->s_mount_state |= EXT4_FC_REPLAY; + mb_free_blocks_test(NULL, &e4b, 12, 4); + sbi->s_mount_state &= ~EXT4_FC_REPLAY; + + corrupt_fc = EXT4_MB_GRP_BBITMAP_CORRUPT(e4b.bd_info); + free_after_fc = e4b.bd_info->bb_free; + ext4_unlock_group(sb, 2); + ext4_mb_unload_buddy_test(&e4b); + + KUNIT_EXPECT_FALSE(test, corrupt_fc); + KUNIT_EXPECT_EQ(test, free_after_fc, EXT4_CLUSTERS_PER_GROUP(sb) - 6); +} + +static void test_mb_xarray_orders_and_frag_size(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct ext4_group_info *grp; + int ord_1, ord_4, ord_7, ord_8; + int old_lfo, new_lfo, new_afso; + void *xa_lfo_entry, *xa_afso_entry, *xa_old_entry; + int i; + + set_opt2(sb, MB_OPTIMIZE_SCAN); + + /* mb_avg_fragment_size_order computes clamp(fls(len) - 2, 0, MB_NUM_ORDERS - 1) */ + ord_1 = mb_avg_fragment_size_order_test(sb, 1); + ord_4 = mb_avg_fragment_size_order_test(sb, 4); + ord_7 = mb_avg_fragment_size_order_test(sb, 7); + ord_8 = mb_avg_fragment_size_order_test(sb, 8); + KUNIT_EXPECT_EQ(test, ord_1, 0); + KUNIT_EXPECT_EQ(test, ord_4, 1); + KUNIT_EXPECT_EQ(test, ord_7, 1); + KUNIT_EXPECT_EQ(test, ord_8, 2); + + grp = ext4_get_group_info(sb, TEST_GOAL_GROUP); + KUNIT_ASSERT_NOT_NULL(test, grp); + + ext4_lock_group(sb, TEST_GOAL_GROUP); + old_lfo = grp->bb_largest_free_order; + for (i = 0; i < MB_NUM_ORDERS(sb); i++) + grp->bb_counters[i] = 0; + grp->bb_counters[3] = 2; + grp->bb_free = 16; + grp->bb_fragments = 2; + + mb_set_largest_free_order_test(sb, grp); + mb_update_avg_fragment_size_test(sb, grp); + + new_lfo = grp->bb_largest_free_order; + new_afso = grp->bb_avg_fragment_size_order; + xa_lfo_entry = xa_load(&sbi->s_mb_largest_free_orders[3], TEST_GOAL_GROUP); + xa_afso_entry = xa_load(&sbi->s_mb_avg_fragment_size[2], TEST_GOAL_GROUP); + + /* Now mark group completely full and verify XArray entries are erased */ + grp->bb_counters[3] = 0; + grp->bb_free = 0; + grp->bb_fragments = 0; + mb_set_largest_free_order_test(sb, grp); + mb_update_avg_fragment_size_test(sb, grp); + xa_old_entry = xa_load(&sbi->s_mb_largest_free_orders[3], TEST_GOAL_GROUP); + ext4_unlock_group(sb, TEST_GOAL_GROUP); + + KUNIT_EXPECT_EQ(test, old_lfo, -1); + KUNIT_EXPECT_EQ(test, new_lfo, 3); + KUNIT_EXPECT_EQ(test, new_afso, 2); + KUNIT_EXPECT_PTR_EQ(test, xa_lfo_entry, grp); + KUNIT_EXPECT_PTR_EQ(test, xa_afso_entry, grp); + KUNIT_EXPECT_NULL(test, xa_old_entry); +} + +static void test_mb_good_group(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct ext4_buddy e4b; + struct ext4_allocation_context ac = {}; + struct ext4_group_info *grp1, *grp2; + int ret; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + /* Initialize group 1 buddy cache so bb_fragments and orders are populated */ + ret = ext4_mb_load_buddy_test(sb, TEST_GOAL_GROUP, &e4b); + KUNIT_ASSERT_EQ(test, ret, 0); + ext4_mb_unload_buddy_test(&e4b); + + grp1 = ext4_get_group_info(sb, TEST_GOAL_GROUP); + KUNIT_ASSERT_NOT_NULL(test, grp1); + + ac.ac_sb = sb; + ac.ac_2order = 3; + ac.ac_g_ex.fe_len = 8; + ac.ac_flags = EXT4_MB_HINT_DATA; + + /* Group 1 has all clusters free in 1 fragment -> eligible at all CRs */ + KUNIT_EXPECT_TRUE(test, ext4_mb_good_group_test(&ac, TEST_GOAL_GROUP, + CR_POWER2_ALIGNED)); + KUNIT_EXPECT_TRUE(test, ext4_mb_good_group_test(&ac, TEST_GOAL_GROUP, + CR_GOAL_LEN_FAST)); + KUNIT_EXPECT_TRUE(test, ext4_mb_good_group_test(&ac, TEST_GOAL_GROUP, + CR_BEST_AVAIL_LEN)); + KUNIT_EXPECT_TRUE(test, ext4_mb_good_group_test(&ac, TEST_GOAL_GROUP, + CR_GOAL_LEN_SLOW)); + KUNIT_EXPECT_TRUE(test, ext4_mb_good_group_test(&ac, TEST_GOAL_GROUP, + CR_ANY_FREE)); + + /* + * Simulate high fragmentation: free = 16, fragments = 8 (avg = 2 < 8), + * largest_free_order = 1 (< ac_2order = 3). + * CR_POWER2_ALIGNED, CR_GOAL_LEN_FAST, CR_BEST_AVAIL_LEN must reject, + * while CR_GOAL_LEN_SLOW (free 16 >= 8) and CR_ANY_FREE accept. + */ + ext4_lock_group(sb, TEST_GOAL_GROUP); + grp1->bb_free = 16; + grp1->bb_fragments = 8; + grp1->bb_largest_free_order = 1; + ext4_unlock_group(sb, TEST_GOAL_GROUP); + + KUNIT_EXPECT_FALSE(test, ext4_mb_good_group_test(&ac, TEST_GOAL_GROUP, + CR_POWER2_ALIGNED)); + KUNIT_EXPECT_FALSE(test, ext4_mb_good_group_test(&ac, TEST_GOAL_GROUP, + CR_GOAL_LEN_FAST)); + KUNIT_EXPECT_FALSE(test, ext4_mb_good_group_test(&ac, TEST_GOAL_GROUP, + CR_BEST_AVAIL_LEN)); + KUNIT_EXPECT_TRUE(test, ext4_mb_good_group_test(&ac, TEST_GOAL_GROUP, + CR_GOAL_LEN_SLOW)); + KUNIT_EXPECT_TRUE(test, ext4_mb_good_group_test(&ac, TEST_GOAL_GROUP, + CR_ANY_FREE)); + + /* When free = 4 < fe_len = 8, CR_GOAL_LEN_SLOW rejects, CR_ANY_FREE accepts */ + ext4_lock_group(sb, TEST_GOAL_GROUP); + grp1->bb_free = 4; + ext4_unlock_group(sb, TEST_GOAL_GROUP); + + KUNIT_EXPECT_FALSE(test, ext4_mb_good_group_test(&ac, TEST_GOAL_GROUP, + CR_GOAL_LEN_SLOW)); + KUNIT_EXPECT_TRUE(test, ext4_mb_good_group_test(&ac, TEST_GOAL_GROUP, + CR_ANY_FREE)); + + /* Flex_bg first group avoidance at CR_POWER2_ALIGNED for data */ + ret = ext4_mb_load_buddy_test(sb, 0, &e4b); + KUNIT_ASSERT_EQ(test, ret, 0); + ext4_mb_unload_buddy_test(&e4b); + sbi->s_log_groups_per_flex = 2; /* flex_size = 4 >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME */ + KUNIT_EXPECT_FALSE(test, ext4_mb_good_group_test(&ac, 0, CR_POWER2_ALIGNED)); + sbi->s_log_groups_per_flex = 0; + + /* + * Test ext4_mb_good_group_nolock on an uninitialized group on a + * separate buddy-cache folio: + * At inexpensive CR_POWER2_ALIGNED, it skips initializing the group + * and returns 0. At expensive CR_GOAL_LEN_SLOW (with STRICT_CHECK), + * it initializes the group and returns 1. + */ + { + ext4_group_t uninit_grp = max_t(ext4_group_t, 2, + DIV_ROUND_UP(PAGE_SIZE / sb->s_blocksize, 2)); + + if (uninit_grp < ext4_get_groups_count(sb)) { + grp2 = ext4_get_group_info(sb, uninit_grp); + KUNIT_ASSERT_NOT_NULL(test, grp2); + KUNIT_EXPECT_TRUE(test, EXT4_MB_GRP_NEED_INIT(grp2)); + + ac.ac_criteria = CR_POWER2_ALIGNED; + ret = ext4_mb_good_group_nolock_test(&ac, uninit_grp, + CR_POWER2_ALIGNED); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_TRUE(test, EXT4_MB_GRP_NEED_INIT(grp2)); + + ac.ac_flags |= EXT4_MB_STRICT_CHECK; + ac.ac_criteria = CR_GOAL_LEN_SLOW; + ret = ext4_mb_good_group_nolock_test(&ac, uninit_grp, + CR_GOAL_LEN_SLOW); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_FALSE(test, EXT4_MB_GRP_NEED_INIT(grp2)); + } + } +} + +static void test_mb_find_by_goal(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct ext4_buddy e4b; + struct ext4_allocation_context ac = {}; + struct inode *inode; + int ret; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + inode = mbt_alloc_test_inode(test, sb, S_IFREG); + + /* Mark [24, 32) used in group 1 so [20, 24) has only 4 free clusters */ + mbt_ctx_mark_used(sb, TEST_GOAL_GROUP, 24, 8); + ext4_get_group_info(sb, TEST_GOAL_GROUP)->bb_free -= 8; + + /* 1. Exact goal hit at [10, 14) */ + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status = AC_STATUS_CONTINUE; + ac.ac_flags = EXT4_MB_HINT_TRY_GOAL; + ac.ac_g_ex.fe_group = TEST_GOAL_GROUP; + ac.ac_g_ex.fe_start = 10; + ac.ac_g_ex.fe_len = 4; + ac.ac_o_ex = ac.ac_g_ex; + + ret = ext4_mb_find_by_goal_test(&ac, &e4b); + ext4_mb_release_context_test(&ac); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ac.ac_status, AC_STATUS_FOUND); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_group, TEST_GOAL_GROUP); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_start, 10); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_len, 4); + + /* 2. Partial goal at [20, 28) without HINT_MERGE fails to match */ + memset(&ac, 0, sizeof(ac)); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status = AC_STATUS_CONTINUE; + ac.ac_flags = EXT4_MB_HINT_TRY_GOAL; + ac.ac_g_ex.fe_group = TEST_GOAL_GROUP; + ac.ac_g_ex.fe_start = 20; + ac.ac_g_ex.fe_len = 8; + ac.ac_o_ex = ac.ac_g_ex; + + ret = ext4_mb_find_by_goal_test(&ac, &e4b); + ext4_mb_release_context_test(&ac); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ac.ac_status, AC_STATUS_CONTINUE); + + /* 3. Partial goal at [20, 28) WITH EXT4_MB_HINT_MERGE allocates [20, 24) */ + memset(&ac, 0, sizeof(ac)); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status = AC_STATUS_CONTINUE; + ac.ac_flags = EXT4_MB_HINT_TRY_GOAL | EXT4_MB_HINT_MERGE; + ac.ac_g_ex.fe_group = TEST_GOAL_GROUP; + ac.ac_g_ex.fe_start = 20; + ac.ac_g_ex.fe_len = 8; + ac.ac_o_ex = ac.ac_g_ex; + + ret = ext4_mb_find_by_goal_test(&ac, &e4b); + ext4_mb_release_context_test(&ac); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ac.ac_status, AC_STATUS_FOUND); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_start, 20); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_len, 4); + + /* + * 4. Stripe-aligned check: s_stripe = 8 clusters; unaligned start 36 + * rejected, aligned 40 accepted. + */ + sbi->s_stripe = EXT4_C2B(sbi, 8); + memset(&ac, 0, sizeof(ac)); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status = AC_STATUS_CONTINUE; + ac.ac_flags = EXT4_MB_HINT_TRY_GOAL; + ac.ac_g_ex.fe_group = TEST_GOAL_GROUP; + ac.ac_g_ex.fe_start = 36; + ac.ac_g_ex.fe_len = 8; + ac.ac_o_ex = ac.ac_g_ex; + + ret = ext4_mb_find_by_goal_test(&ac, &e4b); + ext4_mb_release_context_test(&ac); + KUNIT_EXPECT_EQ(test, ac.ac_status, AC_STATUS_CONTINUE); + + ac.ac_g_ex.fe_start = 40; + ac.ac_o_ex = ac.ac_g_ex; + ret = ext4_mb_find_by_goal_test(&ac, &e4b); + ext4_mb_release_context_test(&ac); + KUNIT_EXPECT_EQ(test, ac.ac_status, AC_STATUS_FOUND); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_start, 40); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_len, 8); + sbi->s_stripe = 0; +} + +static void test_mb_simple_and_aligned_scan(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct ext4_buddy e4b; + struct ext4_allocation_context ac = {}; + struct inode *inode; + int ret; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + inode = mbt_alloc_test_inode(test, sb, S_IFREG); + + /* + * Mark cluster 0 used in group 1 so: + * - order 3 buddy [8, 16) is the first order-3 buddy + * - first 16-cluster stripe [0, 16) is not completely free, so + * stripe-aligned scan must skip to cluster 16. + */ + mbt_ctx_mark_used(sb, TEST_GOAL_GROUP, 0, 1); + ext4_get_group_info(sb, TEST_GOAL_GROUP)->bb_free--; + + ret = ext4_mb_load_buddy_test(sb, TEST_GOAL_GROUP, &e4b); + KUNIT_ASSERT_EQ(test, ret, 0); + + /* 1. ext4_mb_simple_scan_group with ac_2order = 3 (8 clusters) */ + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status = AC_STATUS_CONTINUE; + ac.ac_criteria = CR_POWER2_ALIGNED; + ac.ac_2order = 3; + ac.ac_g_ex.fe_len = 8; + ac.ac_o_ex.fe_len = 8; + + ext4_lock_group(sb, TEST_GOAL_GROUP); + ext4_mb_simple_scan_group_test(&ac, &e4b); + ext4_unlock_group(sb, TEST_GOAL_GROUP); + ext4_mb_release_context_test(&ac); + + KUNIT_EXPECT_EQ(test, ac.ac_status, AC_STATUS_FOUND); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_group, TEST_GOAL_GROUP); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_start, 8); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_len, 8); + + /* 2. ext4_mb_scan_aligned with stripe = 16 clusters */ + sbi->s_stripe = EXT4_C2B(sbi, 16); + memset(&ac, 0, sizeof(ac)); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status = AC_STATUS_CONTINUE; + ac.ac_criteria = CR_GOAL_LEN_FAST; + ac.ac_g_ex.fe_len = 16; + ac.ac_o_ex.fe_len = 16; + + ext4_lock_group(sb, TEST_GOAL_GROUP); + ext4_mb_scan_aligned_test(&ac, &e4b); + ext4_unlock_group(sb, TEST_GOAL_GROUP); + ext4_mb_release_context_test(&ac); + + KUNIT_EXPECT_EQ(test, ac.ac_status, AC_STATUS_FOUND); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_group, TEST_GOAL_GROUP); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_start, 16); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_len, 16); + + sbi->s_stripe = 0; + ext4_mb_unload_buddy_test(&e4b); +} + +static void test_mb_complex_scan_and_measure(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct ext4_buddy e4b; + struct ext4_allocation_context ac = {}; + struct inode *inode; + ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb); + int ret; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + inode = mbt_alloc_test_inode(test, sb, S_IFREG); + + /* + * Create 3 power-of-2 aligned free extents in TEST_GOAL_GROUP: + * - [0, 4) len 4 (order 2 buddy) + * - [16, 32) len 16 (order 4 buddy) + * - [40, 48) len 8 (order 3 buddy) + * Mark everything else used (total free = 28 clusters). + */ + mbt_ctx_mark_used(sb, TEST_GOAL_GROUP, 4, 12); + mbt_ctx_mark_used(sb, TEST_GOAL_GROUP, 32, 8); + mbt_ctx_mark_used(sb, TEST_GOAL_GROUP, 48, max - 48); + ext4_get_group_info(sb, TEST_GOAL_GROUP)->bb_free = 28; + + ret = ext4_mb_load_buddy_test(sb, TEST_GOAL_GROUP, &e4b); + KUNIT_ASSERT_EQ(test, ret, 0); + + /* + * Case 1: Goal len = 5 at CR_GOAL_LEN_SLOW. + * Scans [0, 4) (len 4 < 5), [16, 32) (order 4 buddy -> len 16 > 5), + * and [40, 48) (order 3 buddy -> len 8 > 5, smaller than 16 so preferred!), + * then allocates 5 clusters from [40, 48) at finish_group. + */ + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status = AC_STATUS_CONTINUE; + ac.ac_criteria = CR_GOAL_LEN_SLOW; + ac.ac_g_ex.fe_len = 5; + ac.ac_o_ex.fe_len = 5; + + ext4_lock_group(sb, TEST_GOAL_GROUP); + ext4_mb_complex_scan_group_test(&ac, &e4b); + ext4_unlock_group(sb, TEST_GOAL_GROUP); + ext4_mb_release_context_test(&ac); + + KUNIT_EXPECT_EQ(test, ac.ac_status, AC_STATUS_FOUND); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_start, 40); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_len, 5); + + /* + * Case 2: Goal len = 32 (larger than any free extent) with s_mb_max_to_scan = 1. + * Scanning [0, 4) and [16, 32) increments ac_found to 2 > s_mb_max_to_scan, + * triggering AC_STATUS_BREAK with best smaller extent [16, 32) (len 16) + * recorded in ac_b_ex. Calling ext4_mb_try_best_found() then claims [16, 32). + */ + sbi->s_mb_max_to_scan = 1; + memset(&ac, 0, sizeof(ac)); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status = AC_STATUS_CONTINUE; + ac.ac_criteria = CR_ANY_FREE; + ac.ac_g_ex.fe_len = 32; + ac.ac_o_ex.fe_len = 32; + + ext4_lock_group(sb, TEST_GOAL_GROUP); + ext4_mb_complex_scan_group_test(&ac, &e4b); + ext4_unlock_group(sb, TEST_GOAL_GROUP); + + KUNIT_EXPECT_EQ(test, ac.ac_status, AC_STATUS_BREAK); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_start, 16); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_len, 16); + + ext4_mb_try_best_found_test(&ac, &e4b); + ext4_mb_release_context_test(&ac); + + KUNIT_EXPECT_EQ(test, ac.ac_status, AC_STATUS_FOUND); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_start, 16); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_len, 16); + + /* + * Case 3: EXT4_MB_HINT_FIRST immediately takes the first free extent [0, 4). + */ + sbi->s_mb_max_to_scan = 200; + memset(&ac, 0, sizeof(ac)); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status = AC_STATUS_CONTINUE; + ac.ac_criteria = CR_ANY_FREE; + ac.ac_flags = EXT4_MB_HINT_FIRST; + ac.ac_g_ex.fe_len = 4; + ac.ac_o_ex.fe_len = 4; + + ext4_lock_group(sb, TEST_GOAL_GROUP); + ext4_mb_complex_scan_group_test(&ac, &e4b); + ext4_unlock_group(sb, TEST_GOAL_GROUP); + ext4_mb_release_context_test(&ac); + + KUNIT_EXPECT_EQ(test, ac.ac_status, AC_STATUS_FOUND); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_start, 0); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_len, 4); + + ext4_mb_unload_buddy_test(&e4b); +} + +static void test_mb_regular_allocator(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct ext4_allocation_context ac = {}; + struct inode *inode; + int ret, hash; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + inode = mbt_alloc_test_inode(test, sb, S_IFREG); + + /* + * 1. EXT4_MB_HINT_GOAL_ONLY when goal block (group 0, cluster 0) is already + * marked used: must stop immediately without scanning other blocks. + */ + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status = AC_STATUS_CONTINUE; + ac.ac_flags = EXT4_MB_HINT_GOAL_ONLY; + ac.ac_g_ex.fe_group = 0; + ac.ac_g_ex.fe_start = 0; + ac.ac_g_ex.fe_len = 1; + ac.ac_o_ex = ac.ac_g_ex; + + ret = ext4_mb_regular_allocator_test(&ac); + ext4_mb_release_context_test(&ac); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ac.ac_status, AC_STATUS_CONTINUE); + + /* + * 2. Stream allocation (EXT4_MB_STREAM_ALLOC) with group 0 full: + * allocates in group 1 and updates s_mb_last_groups[hash] to 1. + */ + mbt_ctx_mark_used(sb, 0, 0, EXT4_CLUSTERS_PER_GROUP(sb)); + ext4_free_group_clusters_set(sb, &MBT_GRP_CTX(sb, 0)->desc, 0); + ext4_get_group_info(sb, 0)->bb_free = 0; + + memset(&ac, 0, sizeof(ac)); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status = AC_STATUS_CONTINUE; + ac.ac_flags = EXT4_MB_STREAM_ALLOC | EXT4_MB_HINT_DATA; + ac.ac_g_ex.fe_len = 8; + ac.ac_orig_goal_len = 8; + ac.ac_o_ex.fe_len = 8; + + ret = ext4_mb_regular_allocator_test(&ac); + ext4_mb_release_context_test(&ac); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ac.ac_status, AC_STATUS_FOUND); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_group, 1); + + hash = (unsigned int)inode->i_ino % sbi->s_mb_nr_global_goals; + KUNIT_EXPECT_EQ(test, READ_ONCE(sbi->s_mb_last_groups[hash]), 1); + + /* + * 3. MB_OPTIMIZE_SCAN with CR_BEST_AVAIL_LEN goal length trimming: + * Make group 2 the only group with free blocks, fragmented into two + * 8-cluster chunks [0, 8) and [16, 24) so largest_free_order = 3 + * and avg_fragment_size = 8. + * Note: group 2 may have already been prefetched during step 2, so + * mark its blocks used via mb_mark_used_test on the loaded buddy. + */ + set_opt2(sb, MB_OPTIMIZE_SCAN); + mbt_ctx_mark_used(sb, 1, 0, EXT4_CLUSTERS_PER_GROUP(sb)); + ext4_free_group_clusters_set(sb, &MBT_GRP_CTX(sb, 1)->desc, 0); + ext4_get_group_info(sb, 1)->bb_free = 0; + ext4_get_group_info(sb, 1)->bb_fragments = 0; + mb_set_largest_free_order_test(sb, ext4_get_group_info(sb, 1)); + mb_update_avg_fragment_size_test(sb, ext4_get_group_info(sb, 1)); + + mbt_ctx_mark_used(sb, 3, 0, EXT4_CLUSTERS_PER_GROUP(sb)); + ext4_free_group_clusters_set(sb, &MBT_GRP_CTX(sb, 3)->desc, 0); + ext4_get_group_info(sb, 3)->bb_free = 0; + ext4_get_group_info(sb, 3)->bb_fragments = 0; + mb_set_largest_free_order_test(sb, ext4_get_group_info(sb, 3)); + mb_update_avg_fragment_size_test(sb, ext4_get_group_info(sb, 3)); + + { + struct ext4_buddy e4b; + struct ext4_free_extent ex; + + ret = ext4_mb_load_buddy_test(sb, 2, &e4b); + KUNIT_ASSERT_EQ(test, ret, 0); + ext4_lock_group(sb, 2); + ex.fe_group = 2; + ex.fe_start = 8; + ex.fe_len = 8; + mb_mark_used_test(&e4b, &ex); + ex.fe_start = 24; + ex.fe_len = EXT4_CLUSTERS_PER_GROUP(sb) - 24; + mb_mark_used_test(&e4b, &ex); + ext4_unlock_group(sb, 2); + ext4_mb_unload_buddy_test(&e4b); + } + + memset(&ac, 0, sizeof(ac)); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status = AC_STATUS_CONTINUE; + ac.ac_flags = EXT4_MB_HINT_DATA; + ac.ac_g_ex.fe_group = 0; + ac.ac_g_ex.fe_len = 16; + ac.ac_orig_goal_len = 16; + ac.ac_o_ex.fe_len = 4; + + ret = ext4_mb_pa_alloc_test(&ac); + KUNIT_ASSERT_EQ(test, ret, 0); + + ret = ext4_mb_regular_allocator_test(&ac); + ext4_mb_release_context_test(&ac); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ac.ac_status, AC_STATUS_FOUND); + KUNIT_EXPECT_EQ(test, ac.ac_criteria, CR_BEST_AVAIL_LEN); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_group, 2); + KUNIT_EXPECT_EQ(test, ac.ac_f_ex.fe_len, 8); + KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_len, 4); + ext4_discard_preallocations(inode); +} + +static void test_mb_prefetch(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_group_info *grp0, *grp1, *grp2; + ext4_group_t next_grp, uninit_grp; + int ios = 0; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + uninit_grp = max_t(ext4_group_t, 2, + DIV_ROUND_UP(PAGE_SIZE / sb->s_blocksize, 2)); + + grp0 = ext4_get_group_info(sb, 0); + grp1 = ext4_get_group_info(sb, 1); + grp2 = ext4_get_group_info(sb, 2); + KUNIT_ASSERT_NOT_NULL(test, grp0); + KUNIT_ASSERT_NOT_NULL(test, grp1); + KUNIT_ASSERT_NOT_NULL(test, grp2); + + KUNIT_EXPECT_TRUE(test, EXT4_MB_GRP_NEED_INIT(grp0)); + KUNIT_EXPECT_TRUE(test, EXT4_MB_GRP_NEED_INIT(grp1)); + KUNIT_EXPECT_TRUE(test, EXT4_MB_GRP_NEED_INIT(grp2)); + + next_grp = ext4_mb_prefetch(sb, 0, 2, &ios); + KUNIT_EXPECT_EQ(test, next_grp, 2); + /* First prefetch of uninitialized buffers increments ios count */ + KUNIT_EXPECT_EQ(test, ios, 2); + + /* Repeated prefetch on the same groups does not re-read bitmaps */ + ios = 0; + ext4_mb_prefetch(sb, 0, 2, &ios); + KUNIT_EXPECT_EQ(test, ios, 0); + + /* ext4_mb_prefetch_fini initializes the prefetched groups [0, 2) */ + ext4_mb_prefetch_fini(sb, next_grp, 2); + KUNIT_EXPECT_FALSE(test, EXT4_MB_GRP_NEED_INIT(grp0)); + KUNIT_EXPECT_FALSE(test, EXT4_MB_GRP_NEED_INIT(grp1)); + if (uninit_grp < ext4_get_groups_count(sb)) { + grp2 = ext4_get_group_info(sb, uninit_grp); + KUNIT_ASSERT_NOT_NULL(test, grp2); + KUNIT_EXPECT_TRUE(test, EXT4_MB_GRP_NEED_INIT(grp2)); + } +} + +static void test_mb_initialize_context(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct ext4_allocation_context ac = {}; + struct ext4_allocation_request ar = {}; + struct inode *inode; + + inode = mbt_alloc_test_inode(test, sb, S_IFREG); + + /* 1. Small open file (<= s_mb_stream_request) uses locality group alloc */ + i_size_write(inode, sb->s_blocksize); + ar.inode = inode; + ar.logical = 0; + ar.len = 1; + ar.goal = ext4_group_first_block_no(sb, TEST_GOAL_GROUP); + ar.flags = EXT4_MB_HINT_DATA; + + ext4_mb_initialize_context_test(&ac, &ar); + ext4_mb_release_context_test(&ac); + KUNIT_EXPECT_NE(test, ac.ac_flags & EXT4_MB_HINT_GROUP_ALLOC, 0); + KUNIT_EXPECT_NOT_NULL(test, ac.ac_lg); + KUNIT_EXPECT_EQ(test, ac.ac_g_ex.fe_group, TEST_GOAL_GROUP); + + /* 2. Large open file (> s_mb_stream_request) uses stream alloc */ + memset(&ac, 0, sizeof(ac)); + i_size_write(inode, (loff_t)(sbi->s_mb_stream_request + 64) << sb->s_blocksize_bits); + ext4_mb_initialize_context_test(&ac, &ar); + ext4_mb_release_context_test(&ac); + KUNIT_EXPECT_NE(test, ac.ac_flags & EXT4_MB_STREAM_ALLOC, 0); + KUNIT_EXPECT_NULL(test, ac.ac_lg); + + /* + * 3. Closed file (i_writecount == 0) with size == isize and + * size > s_mb_stream_request sets EXT4_MB_HINT_NOPREALLOC. + */ + memset(&ac, 0, sizeof(ac)); + atomic_set(&inode->i_writecount, 0); + ar.logical = EXT4_LBLK_CMASK(sbi, sbi->s_mb_stream_request + EXT4_C2B(sbi, 2)); + ar.len = 1; + i_size_write(inode, (loff_t)(ar.logical + EXT4_C2B(sbi, 1)) << sb->s_blocksize_bits); + /* Also test out-of-range ar.goal fallback to group 0 */ + ar.goal = ext4_blocks_count(sbi->s_es) + 100; + ext4_mb_initialize_context_test(&ac, &ar); + ext4_mb_release_context_test(&ac); + KUNIT_EXPECT_NE(test, ac.ac_flags & EXT4_MB_HINT_NOPREALLOC, 0); + KUNIT_EXPECT_EQ(test, ac.ac_o_ex.fe_group, 0); + KUNIT_EXPECT_EQ(test, ac.ac_o_ex.fe_start, 0); +} + +static void test_mb_normalize_request(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct ext4_allocation_context ac = {}; + struct ext4_allocation_request ar = {}; + struct inode *inode; + struct ext4_inode_info *ei; + struct ext4_prealloc_space left_pa = {}, right_pa = {}; + int bsbits = sb->s_blocksize_bits; + + inode = mbt_alloc_test_inode(test, sb, S_IFREG); + ei = EXT4_I(inode); + + /* 1. Metadata request (no EXT4_MB_HINT_DATA) is not normalized */ + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_o_ex.fe_logical = 0; + ac.ac_o_ex.fe_len = 1; + ac.ac_g_ex = ac.ac_o_ex; + ext4_mb_normalize_request_test(&ac, &ar); + KUNIT_EXPECT_EQ(test, ac.ac_g_ex.fe_len, 1); + + /* 2. Locality group request normalizes fe_len to s_mb_group_prealloc */ + memset(&ac, 0, sizeof(ac)); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_flags = EXT4_MB_HINT_DATA | EXT4_MB_HINT_GROUP_ALLOC; + ac.ac_lg = raw_cpu_ptr(sbi->s_locality_groups); + ac.ac_o_ex.fe_len = 1; + ac.ac_g_ex = ac.ac_o_ex; + ext4_mb_normalize_request_test(&ac, &ar); + KUNIT_EXPECT_EQ(test, ac.ac_g_ex.fe_len, sbi->s_mb_group_prealloc); + + /* 3. Small file (<= 16KB) normalizes up to max(SZ_16K, cluster_size) */ + if ((SZ_16K >> bsbits) >= sbi->s_cluster_ratio) { + memset(&ac, 0, sizeof(ac)); + i_size_write(inode, 4096); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_flags = EXT4_MB_HINT_DATA; + ac.ac_o_ex.fe_logical = 0; + ac.ac_o_ex.fe_len = 1; + ac.ac_g_ex = ac.ac_o_ex; + ext4_mb_normalize_request_test(&ac, &ar); + KUNIT_EXPECT_EQ(test, ac.ac_g_ex.fe_len, + EXT4_NUM_B2C(sbi, SZ_16K >> bsbits)); + } + + /* 4. 200KB file normalizes up to next power of two (256KB) */ + if ((SZ_256K >> bsbits) >= sbi->s_cluster_ratio) { + memset(&ac, 0, sizeof(ac)); + i_size_write(inode, 200 * 1024); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_flags = EXT4_MB_HINT_DATA; + ac.ac_o_ex.fe_logical = 0; + ac.ac_o_ex.fe_len = 1; + ac.ac_g_ex = ac.ac_o_ex; + ext4_mb_normalize_request_test(&ac, &ar); + KUNIT_EXPECT_EQ(test, ac.ac_g_ex.fe_len, + EXT4_NUM_B2C(sbi, SZ_256K >> bsbits)); + } + + /* + * 5. Trimming against left/right allocated neighbors (ar.pleft / ar.pright) + * and against existing inode preallocations (ext4_mb_pa_adjust_overlap). + */ + if (((loff_t)EXT4_C2B(sbi, 16) << bsbits) <= SZ_1M) { + memset(&ac, 0, sizeof(ac)); + memset(&ar, 0, sizeof(ar)); + i_size_write(inode, (loff_t)EXT4_C2B(sbi, 16) << bsbits); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_flags = EXT4_MB_HINT_DATA; + ac.ac_o_ex.fe_logical = EXT4_C2B(sbi, 4); + ac.ac_o_ex.fe_len = 1; + ac.ac_g_ex = ac.ac_o_ex; + + /* Left neighbor ends at cluster 2 (logical block EXT4_C2B(sbi, 2) - 1) */ + ar.lleft = EXT4_C2B(sbi, 2) - 1; + ar.pleft = ext4_group_first_block_no(sb, TEST_GOAL_GROUP) + ar.lleft; + /* Right neighbor starts at cluster 10 */ + ar.lright = EXT4_C2B(sbi, 10); + ar.pright = ext4_group_first_block_no(sb, TEST_GOAL_GROUP) + ar.lright; + + /* + * Also insert a left PA covering clusters [2, 3) and a right PA covering + * clusters [8, 10) into ei->i_prealloc_node so ext4_mb_pa_adjust_overlap + * trims the range further to clusters [3, 8) (5 clusters). + */ + spin_lock_init(&left_pa.pa_lock); + left_pa.pa_lstart = EXT4_C2B(sbi, 2); + left_pa.pa_len = 1; + left_pa.pa_free = 1; + left_pa.pa_deleted = 0; + + spin_lock_init(&right_pa.pa_lock); + right_pa.pa_lstart = EXT4_C2B(sbi, 8); + right_pa.pa_len = 2; + right_pa.pa_free = 2; + right_pa.pa_deleted = 0; + + rb_link_node(&left_pa.pa_node.inode_node, NULL, + &ei->i_prealloc_node.rb_node); + rb_insert_color(&left_pa.pa_node.inode_node, &ei->i_prealloc_node); + rb_link_node(&right_pa.pa_node.inode_node, + &left_pa.pa_node.inode_node, + &left_pa.pa_node.inode_node.rb_right); + rb_insert_color(&right_pa.pa_node.inode_node, &ei->i_prealloc_node); + + ext4_mb_normalize_request_test(&ac, &ar); + ei->i_prealloc_node = RB_ROOT; + + KUNIT_EXPECT_EQ(test, ac.ac_g_ex.fe_logical, EXT4_C2B(sbi, 3)); + KUNIT_EXPECT_EQ(test, ac.ac_g_ex.fe_len, 5); + } +} + +static void test_mb_inode_pa_lifecycle(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct inode *inode; + struct ext4_inode_info *ei; + struct ext4_allocation_request ar = {}; + struct ext4_group_info *grp; + ext4_group_t pa_grp; + ext4_grpblk_t pa_off, free_before; + ext4_fsblk_t blk1, blk2; + void *pa_bitmap; + int err = 0; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + inode = mbt_alloc_test_inode(test, sb, S_IFREG); + ei = EXT4_I(inode); + /* Large file size (> s_mb_stream_request) so inode PA is used */ + i_size_write(inode, (loff_t)(sbi->s_mb_stream_request + 64) << sb->s_blocksize_bits); + + ar.inode = inode; + ar.logical = 0; + ar.len = 1; + ar.goal = ext4_group_first_block_no(sb, TEST_GOAL_GROUP); + ar.flags = EXT4_MB_HINT_DATA; + + blk1 = ext4_mb_new_blocks(NULL, &ar, &err); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_NE(test, blk1, 0ULL); + KUNIT_EXPECT_EQ(test, ar.len, 1); + KUNIT_EXPECT_EQ(test, atomic_read(&ei->i_prealloc_active), 1); + KUNIT_EXPECT_FALSE(test, RB_EMPTY_ROOT(&ei->i_prealloc_node)); + + ext4_get_group_no_and_offset(sb, blk1, &pa_grp, &pa_off); + grp = ext4_get_group_info(sb, pa_grp); + free_before = ext4_free_group_clusters(sb, &MBT_GRP_CTX(sb, pa_grp)->desc) + 1; + + /* Verify ext4_mb_generate_from_pa marks the PA's clusters in a bitmap */ + pa_bitmap = kunit_kzalloc(test, sb->s_blocksize, GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, pa_bitmap); + ext4_lock_group(sb, pa_grp); + ext4_mb_generate_from_pa_test(sb, pa_bitmap, pa_grp); + ext4_unlock_group(sb, pa_grp); + KUNIT_EXPECT_NE(test, mb_test_bit_test(pa_off, pa_bitmap), 0); + + /* Second sequential allocation is served directly from the inode PA */ + ar.logical = EXT4_C2B(sbi, 1); + ar.len = 1; + ar.goal = blk1 + EXT4_C2B(sbi, 1); + blk2 = ext4_mb_new_blocks(NULL, &ar, &err); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, blk2, blk1 + EXT4_C2B(sbi, 1)); + + /* Discard inode preallocations and verify cleanup */ + ext4_discard_preallocations(inode); + KUNIT_EXPECT_EQ(test, atomic_read(&ei->i_prealloc_active), 0); + KUNIT_EXPECT_TRUE(test, RB_EMPTY_ROOT(&ei->i_prealloc_node)); + /* Only the 2 allocated clusters should remain used in the group */ + KUNIT_EXPECT_EQ(test, grp->bb_free, free_before - 2); +} + +struct mbt_saved_affinity { + cpumask_var_t mask; +}; + +static void mbt_restore_cpu_affinity(void *data) +{ + struct mbt_saved_affinity *saved = data; + + set_cpus_allowed_ptr(current, saved->mask); + free_cpumask_var(saved->mask); + kfree(saved); +} + +static void mbt_pin_current_cpu(struct kunit *test) +{ + struct mbt_saved_affinity *saved; + int err; + + saved = kzalloc_obj(*saved); + KUNIT_ASSERT_NOT_NULL(test, saved); + if (!alloc_cpumask_var(&saved->mask, GFP_KERNEL)) { + kfree(saved); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc cpumask"); + } + cpumask_copy(saved->mask, current->cpus_ptr); + + err = set_cpus_allowed_ptr(current, + cpumask_of(raw_smp_processor_id())); + if (err) { + free_cpumask_var(saved->mask); + kfree(saved); + KUNIT_ASSERT_EQ(test, err, 0); + } + + err = kunit_add_action_or_reset(test, mbt_restore_cpu_affinity, saved); + KUNIT_ASSERT_EQ(test, err, 0); +} + +static void test_mb_group_pa_lifecycle(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct inode *inode1, *inode2; + struct ext4_allocation_request ar = {}; + struct ext4_group_info *grp; + ext4_fsblk_t blk1, blk2; + int err = 0, discarded; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + /* Pin to one CPU so both allocations hit the same locality group PA */ + mbt_pin_current_cpu(test); + + inode1 = mbt_alloc_test_inode(test, sb, S_IFREG); + inode2 = mbt_alloc_test_inode(test, sb, S_IFREG); + inode2->i_ino = 13; + + /* Small files (<= s_mb_stream_request) use locality group PA (MB_GROUP_PA) */ + i_size_write(inode1, sb->s_blocksize); + i_size_write(inode2, sb->s_blocksize); + + ar.inode = inode1; + ar.logical = 0; + ar.len = 1; + ar.goal = ext4_group_first_block_no(sb, TEST_GOAL_GROUP); + ar.flags = EXT4_MB_HINT_DATA; + + blk1 = ext4_mb_new_blocks(NULL, &ar, &err); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, blk1, ext4_group_first_block_no(sb, TEST_GOAL_GROUP)); + + /* Second small file allocation reuses the locality group PA */ + ar.inode = inode2; + ar.logical = 0; + ar.len = 1; + ar.goal = ext4_group_first_block_no(sb, TEST_GOAL_GROUP); + blk2 = ext4_mb_new_blocks(NULL, &ar, &err); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, blk2, blk1 + EXT4_C2B(sbi, 1)); + + /* Discard all group preallocations and verify free count is restored */ + discarded = ext4_mb_discard_preallocations_test(sb, 0); + rcu_barrier(); + KUNIT_EXPECT_EQ(test, discarded, (int)sbi->s_mb_group_prealloc - 2); + + grp = ext4_get_group_info(sb, TEST_GOAL_GROUP); + KUNIT_EXPECT_EQ(test, grp->bb_free, EXT4_CLUSTERS_PER_GROUP(sb) - 2); +} + +static void test_mb_lg_list_trim(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct ext4_locality_group *lg; + struct inode *inode; + struct ext4_buddy e4b; + struct ext4_prealloc_space *pa; + int i, ret, count = 0; + int order = fls(15) - 1; /* pa_free = 15 -> order 3 */ + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + inode = mbt_alloc_test_inode(test, sb, S_IFREG); + sbi->s_mb_group_prealloc = 16; + + ret = ext4_mb_load_buddy_test(sb, TEST_GOAL_GROUP, &e4b); + KUNIT_ASSERT_EQ(test, ret, 0); + + /* + * Create 9 locality-group PAs in bucket order 3 (each of length 16 with + * 1 cluster used -> pa_free = 15). When the 9th PA is added via + * ext4_mb_release_context -> ext4_mb_add_n_trim, lg_prealloc_count > 8 + * triggers ext4_mb_discard_lg_preallocations() to trim the list to 5! + * Capture one locality group pointer up front so CPU migration across + * iterations cannot split PAs across different per-CPU locality groups. + */ + lg = raw_cpu_ptr(sbi->s_locality_groups); + for (i = 0; i < 9; i++) { + struct ext4_allocation_context ac = {}; + struct ext4_free_extent ex = { + .fe_group = TEST_GOAL_GROUP, + .fe_start = i * 32, + .fe_len = 16, + }; + + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_flags = EXT4_MB_HINT_DATA | EXT4_MB_HINT_GROUP_ALLOC; + ac.ac_lg = lg; + mutex_lock(&ac.ac_lg->lg_mutex); + + ret = ext4_mb_pa_alloc_test(&ac); + if (ret) { + mutex_unlock(&ac.ac_lg->lg_mutex); + ext4_mb_unload_buddy_test(&e4b); + KUNIT_ASSERT_EQ(test, ret, 0); + } + + ext4_lock_group(sb, TEST_GOAL_GROUP); + mb_mark_used_test(&e4b, &ex); + ext4_unlock_group(sb, TEST_GOAL_GROUP); + + ac.ac_status = AC_STATUS_FOUND; + ac.ac_o_ex.fe_len = 1; + ac.ac_b_ex = ex; + ac.ac_f_ex = ex; + ext4_mb_new_preallocation_test(&ac); + /* Release context updates pa_free to 15 and runs ext4_mb_add_n_trim */ + ext4_mb_release_context_test(&ac); + } + + ext4_mb_unload_buddy_test(&e4b); + + spin_lock(&lg->lg_prealloc_lock); + list_for_each_entry(pa, &lg->lg_prealloc_list[order], pa_node.lg_list) + count++; + spin_unlock(&lg->lg_prealloc_lock); + + KUNIT_EXPECT_EQ(test, count, 5); +} + +static void test_mb_new_blocks_and_enospc_retry(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct inode *inode1, *inode2; + struct ext4_allocation_request ar = {}; + ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb); + ext4_fsblk_t blk; + int err = 0; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + inode1 = mbt_alloc_test_inode(test, sb, S_IFREG); + inode2 = mbt_alloc_test_inode(test, sb, S_IFREG); + inode2->i_ino = 14; + i_size_write(inode1, sb->s_blocksize); + + /* + * Leave only 16 free clusters in group 1 and mark groups 0, 2, 3 full. + * Set s_mb_group_prealloc = 16 so allocating 1 cluster for inode1 + * preallocates the remaining 15 clusters into a group PA (leaving + * 0 free clusters in buddy for all groups). + */ + mbt_ctx_mark_used(sb, 0, 0, max); + ext4_free_group_clusters_set(sb, &MBT_GRP_CTX(sb, 0)->desc, 0); + ext4_get_group_info(sb, 0)->bb_free = 0; + + mbt_ctx_mark_used(sb, 1, 16, max - 16); + ext4_free_group_clusters_set(sb, &MBT_GRP_CTX(sb, 1)->desc, 16); + ext4_get_group_info(sb, 1)->bb_free = 16; + + mbt_ctx_mark_used(sb, 2, 0, max); + ext4_free_group_clusters_set(sb, &MBT_GRP_CTX(sb, 2)->desc, 0); + ext4_get_group_info(sb, 2)->bb_free = 0; + + mbt_ctx_mark_used(sb, 3, 0, max); + ext4_free_group_clusters_set(sb, &MBT_GRP_CTX(sb, 3)->desc, 0); + ext4_get_group_info(sb, 3)->bb_free = 0; + + percpu_counter_set(&sbi->s_freeclusters_counter, 16); + sbi->s_mb_group_prealloc = 16; + + ar.inode = inode1; + ar.logical = 0; + ar.len = 1; + ar.goal = ext4_group_first_block_no(sb, 1); + ar.flags = EXT4_MB_HINT_DATA; + + blk = ext4_mb_new_blocks(NULL, &ar, &err); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ext4_get_group_info(sb, 1)->bb_free, 0); + + /* + * Now request 4 metadata clusters (no EXT4_MB_HINT_DATA so it cannot + * use the PA directly). First allocator pass finds 0 free clusters, + * then ext4_mb_discard_preallocations_should_retry() discards the PA + * (recovering 15 clusters) and retries, succeeding! + */ + memset(&ar, 0, sizeof(ar)); + ar.inode = inode2; + ar.len = 4; + ar.goal = ext4_group_first_block_no(sb, 1); + ar.flags = 0; + + blk = ext4_mb_new_blocks(NULL, &ar, &err); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_NE(test, blk, 0ULL); + KUNIT_EXPECT_EQ(test, ar.len, 4); + + /* + * The 4-cluster power-of-2 allocation claimed [4, 8), leaving two + * fragments [1, 4) (3 clusters) and [8, 16) (8 clusters). + * Requesting 11 clusters allocates the largest fragment (8 clusters), + * then requesting 3 clusters allocates [1, 4), and the next request + * returns -ENOSPC. + */ + ar.len = 11; + blk = ext4_mb_new_blocks(NULL, &ar, &err); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ar.len, 8); + + ar.len = 3; + blk = ext4_mb_new_blocks(NULL, &ar, &err); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ar.len, 3); + + ar.len = 1; + blk = ext4_mb_new_blocks(NULL, &ar, &err); + KUNIT_EXPECT_EQ(test, err, -ENOSPC); + KUNIT_EXPECT_EQ(test, blk, 0ULL); +} + +static int +ext4_handle_dirty_metadata_Updated_stub(const char *where, unsigned int line, + handle_t *handle, struct inode *inode, + struct buffer_head *bh) +{ + return 0; +} + +static void test_mb_mark_context_and_mark_bb(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct ext4_group_desc *gdp1, *gdp2; + ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb); + ext4_grpblk_t changed = 0; + ext4_fsblk_t boundary_blk; + __u32 free_before; + int ret; + + /* Test the real ext4_mb_mark_context implementation */ + kunit_deactivate_static_stub(test, ext4_mb_mark_context); + kunit_activate_static_stub(test, __ext4_handle_dirty_metadata, + ext4_handle_dirty_metadata_Updated_stub); + + gdp1 = ext4_get_group_desc(sb, 1, NULL); + gdp2 = ext4_get_group_desc(sb, 2, NULL); + KUNIT_ASSERT_NOT_NULL(test, gdp1); + KUNIT_ASSERT_NOT_NULL(test, gdp2); + free_before = ext4_free_group_clusters(sb, gdp1); + + /* 1. Mark [10, 20) used with EXT4_MB_BITMAP_MARKED_CHECK (0x1) */ + ret = ext4_mb_mark_context(NULL, sb, true, 1, 10, 10, 0x0001, &changed); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, changed, 10); + KUNIT_EXPECT_EQ(test, ext4_free_group_clusters(sb, gdp1), free_before - 10); + + /* 2. Mark overlapping [15, 25) used -> only 5 new clusters changed */ + ret = ext4_mb_mark_context(NULL, sb, true, 1, 15, 10, 0x0001, &changed); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, changed, 5); + KUNIT_EXPECT_EQ(test, ext4_free_group_clusters(sb, gdp1), free_before - 15); + + /* 3. Clear [10, 25) -> 15 clusters freed */ + ret = ext4_mb_mark_context(NULL, sb, false, 1, 10, 15, 0x0001, &changed); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, changed, 15); + KUNIT_EXPECT_EQ(test, ext4_free_group_clusters(sb, gdp1), free_before); + + /* + * 4. Test ext4_mb_mark_bb across the boundary between group 1 and group 2: + * 2 clusters at the end of group 1 + 3 clusters at the start of group 2. + */ + kunit_activate_static_stub(test, ext4_mb_mark_context, + ext4_mb_mark_context_stub); + boundary_blk = ext4_group_first_block_no(sb, 2) - EXT4_C2B(sbi, 2); + ext4_mb_mark_bb(sb, boundary_blk, EXT4_C2B(sbi, 5), true); + + KUNIT_EXPECT_NE(test, mb_test_bit_test(max - 2, mbt_ctx_bitmap(sb, 1)), 0); + KUNIT_EXPECT_NE(test, mb_test_bit_test(max - 1, mbt_ctx_bitmap(sb, 1)), 0); + KUNIT_EXPECT_NE(test, mb_test_bit_test(0, mbt_ctx_bitmap(sb, 2)), 0); + KUNIT_EXPECT_NE(test, mb_test_bit_test(2, mbt_ctx_bitmap(sb, 2)), 0); + KUNIT_EXPECT_EQ(test, mb_test_bit_test(3, mbt_ctx_bitmap(sb, 2)), 0); + + ext4_mb_mark_bb(sb, boundary_blk, EXT4_C2B(sbi, 5), false); + KUNIT_EXPECT_EQ(test, mb_test_bit_test(max - 2, mbt_ctx_bitmap(sb, 1)), 0); + KUNIT_EXPECT_EQ(test, mb_test_bit_test(0, mbt_ctx_bitmap(sb, 2)), 0); +} + +static void test_ext4_free_blocks_flags_and_cross_group(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct inode *inode; + struct ext4_buddy e4b; + ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb); + ext4_fsblk_t grp1_first = ext4_group_first_block_no(sb, 1); + ext4_fsblk_t grp2_first = ext4_group_first_block_no(sb, 2); + s64 free_before; + int ret; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + inode = mbt_alloc_test_inode(test, sb, S_IFREG); + + /* Mark clusters [10, 20) and [max - 2, max) in group 1, and [0, 3) in group 2 used */ + mbt_ctx_mark_used(sb, 1, 10, 10); + mbt_ctx_mark_used(sb, 1, max - 2, 2); + mbt_ctx_mark_used(sb, 2, 0, 3); + ext4_get_group_info(sb, 1)->bb_free -= 12; + ext4_get_group_info(sb, 2)->bb_free -= 3; + + ret = ext4_mb_load_buddy_test(sb, 1, &e4b); + KUNIT_ASSERT_EQ(test, ret, 0); + ext4_mb_unload_buddy_test(&e4b); + ret = ext4_mb_load_buddy_test(sb, 2, &e4b); + KUNIT_ASSERT_EQ(test, ret, 0); + ext4_mb_unload_buddy_test(&e4b); + + /* + * 1. EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER | EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER: + * Freeing from cluster 10 + 2 blocks through cluster 12 + 3 blocks + * skips partial clusters 10 and 12 and frees only full cluster 11! + */ + ext4_free_blocks(NULL, inode, NULL, + grp1_first + EXT4_C2B(sbi, 10) + 2, + EXT4_C2B(sbi, 2) - 2 + 3, + EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER | + EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER | + EXT4_FREE_BLOCKS_NO_QUOT_UPDATE); + + KUNIT_EXPECT_NE(test, mb_test_bit_test(10, mbt_ctx_bitmap(sb, 1)), 0); + KUNIT_EXPECT_EQ(test, mb_test_bit_test(11, mbt_ctx_bitmap(sb, 1)), 0); + KUNIT_EXPECT_NE(test, mb_test_bit_test(12, mbt_ctx_bitmap(sb, 1)), 0); + + /* + * 2. EXT4_FREE_BLOCKS_RERESERVE_CLUSTER: frees cluster 12 in bitmap & buddy + * without incrementing s_freeclusters_counter. + */ + free_before = percpu_counter_sum(&sbi->s_freeclusters_counter); + ext4_free_blocks(NULL, inode, NULL, + grp1_first + EXT4_C2B(sbi, 12), + EXT4_C2B(sbi, 1), + EXT4_FREE_BLOCKS_RERESERVE_CLUSTER | + EXT4_FREE_BLOCKS_NO_QUOT_UPDATE); + KUNIT_EXPECT_EQ(test, mb_test_bit_test(12, mbt_ctx_bitmap(sb, 1)), 0); + KUNIT_EXPECT_EQ(test, percpu_counter_sum(&sbi->s_freeclusters_counter), + free_before); + + /* + * 3. Cross-group boundary free: 2 clusters at end of group 1 + 3 clusters + * at start of group 2. + */ + ext4_free_blocks(NULL, inode, NULL, + grp2_first - EXT4_C2B(sbi, 2), + EXT4_C2B(sbi, 5), + EXT4_FREE_BLOCKS_NO_QUOT_UPDATE); + KUNIT_EXPECT_EQ(test, mb_test_bit_test(max - 2, mbt_ctx_bitmap(sb, 1)), 0); + KUNIT_EXPECT_EQ(test, mb_test_bit_test(max - 1, mbt_ctx_bitmap(sb, 1)), 0); + KUNIT_EXPECT_EQ(test, mb_test_bit_test(0, mbt_ctx_bitmap(sb, 2)), 0); + KUNIT_EXPECT_EQ(test, mb_test_bit_test(2, mbt_ctx_bitmap(sb, 2)), 0); +} + +static void test_mb_free_metadata_and_process_freed_data(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct inode *inode; + struct ext4_buddy e4b; + struct ext4_group_info *grp; + struct ext4_free_data *entry; + transaction_t trans = { .t_tid = 42 }; + handle_t handle = { .h_transaction = &trans }; + ext4_fsblk_t grp1_first = ext4_group_first_block_no(sb, TEST_GOAL_GROUP); + ext4_grpblk_t merged_start = 0, merged_count = 0; + int node_count = 0, ret; + struct rb_node *n; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + inode = mbt_alloc_test_inode(test, sb, S_IFREG); + + /* Mark clusters [20, 28) used in group 1 and load buddy */ + mbt_ctx_mark_used(sb, TEST_GOAL_GROUP, 20, 8); + grp = ext4_get_group_info(sb, TEST_GOAL_GROUP); + grp->bb_free -= 8; + + ret = ext4_mb_load_buddy_test(sb, TEST_GOAL_GROUP, &e4b); + KUNIT_ASSERT_EQ(test, ret, 0); + ext4_mb_unload_buddy_test(&e4b); + + /* + * Free [20, 22), then [25, 28), then the middle [22, 25) as metadata + * with a valid journal handle (tid = 42). + * This exercises rbtree insertion and both prev and next extent merging! + */ + ext4_free_blocks(&handle, inode, NULL, + grp1_first + EXT4_C2B(sbi, 20), EXT4_C2B(sbi, 2), + EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_NO_QUOT_UPDATE); + ext4_free_blocks(&handle, inode, NULL, + grp1_first + EXT4_C2B(sbi, 25), EXT4_C2B(sbi, 3), + EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_NO_QUOT_UPDATE); + ext4_free_blocks(&handle, inode, NULL, + grp1_first + EXT4_C2B(sbi, 22), EXT4_C2B(sbi, 3), + EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_NO_QUOT_UPDATE); + + KUNIT_EXPECT_EQ(test, atomic_read(&sbi->s_mb_free_pending), 8); + /* Blocks are not yet freed in buddy until transaction commit */ + KUNIT_EXPECT_EQ(test, grp->bb_free, EXT4_CLUSTERS_PER_GROUP(sb) - 8); + + ext4_lock_group(sb, TEST_GOAL_GROUP); + for (n = rb_first(&grp->bb_free_root); n; n = rb_next(n)) { + entry = rb_entry(n, struct ext4_free_data, efd_node); + merged_start = entry->efd_start_cluster; + merged_count = entry->efd_count; + node_count++; + } + ext4_unlock_group(sb, TEST_GOAL_GROUP); + + /* All 3 freed extents for tid 42 must have merged into a single node [20, 28) */ + KUNIT_EXPECT_EQ(test, node_count, 1); + KUNIT_EXPECT_EQ(test, merged_start, 20); + KUNIT_EXPECT_EQ(test, merged_count, 8); + + /* Commit tid 42 -> ext4_process_freed_data releases [20, 28) into buddy */ + ext4_process_freed_data(sb, 42); + KUNIT_EXPECT_EQ(test, atomic_read(&sbi->s_mb_free_pending), 0); + KUNIT_EXPECT_TRUE(test, RB_EMPTY_ROOT(&grp->bb_free_root)); + KUNIT_EXPECT_EQ(test, grp->bb_free, EXT4_CLUSTERS_PER_GROUP(sb)); +} + +static void test_ext4_group_add_blocks(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct ext4_buddy e4b; + struct ext4_group_info *grp; + ext4_fsblk_t grp1_first = ext4_group_first_block_no(sb, TEST_GOAL_GROUP); + s64 free_before; + int ret; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + /* Mark [50, 60) used in group 1 and initialize buddy */ + mbt_ctx_mark_used(sb, TEST_GOAL_GROUP, 50, 10); + grp = ext4_get_group_info(sb, TEST_GOAL_GROUP); + grp->bb_free -= 10; + + ret = ext4_mb_load_buddy_test(sb, TEST_GOAL_GROUP, &e4b); + KUNIT_ASSERT_EQ(test, ret, 0); + ext4_mb_unload_buddy_test(&e4b); + + free_before = percpu_counter_sum(&sbi->s_freeclusters_counter); + ret = ext4_group_add_blocks(NULL, sb, + grp1_first + EXT4_C2B(sbi, 50), + EXT4_C2B(sbi, 10)); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, grp->bb_free, EXT4_CLUSTERS_PER_GROUP(sb)); + KUNIT_EXPECT_EQ(test, percpu_counter_sum(&sbi->s_freeclusters_counter), + free_before + 10); + + /* Cross-group boundary addition must fail with -EINVAL */ + ret = ext4_group_add_blocks(NULL, sb, + grp1_first + EXT4_C2B(sbi, EXT4_CLUSTERS_PER_GROUP(sb) - 2), + EXT4_C2B(sbi, 5)); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + + /* System zone block (block 0) must fail with -EINVAL */ + ret = ext4_group_add_blocks(NULL, sb, 0, EXT4_C2B(sbi, 1)); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); +} + +static int mbt_discard_calls; +static int mbt_discard_clusters; + +static int +ext4_issue_discard_count_stub(struct super_block *sb, ext4_group_t block_group, + ext4_grpblk_t cluster, int count) +{ + mbt_discard_calls++; + mbt_discard_clusters += count; + return 0; +} + +static void test_ext4_trim_fs(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct fstrim_range range = {}; + struct ext4_group_info *grp1; + struct inode *inode; + ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb); + int ret; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + inode = mbt_alloc_test_inode(test, sb, S_IFREG); + kunit_activate_static_stub(test, ext4_issue_discard, + ext4_issue_discard_count_stub); + + /* + * Mark groups 0, 2, 3 completely used. + * In group 1, leave only [10, 14) (4 clusters) and [30, 50) (20 clusters) free. + */ + mbt_ctx_mark_used(sb, 0, 0, max); + ext4_get_group_info(sb, 0)->bb_free = 0; + mbt_ctx_mark_used(sb, 2, 0, max); + ext4_get_group_info(sb, 2)->bb_free = 0; + mbt_ctx_mark_used(sb, 3, 0, max); + ext4_get_group_info(sb, 3)->bb_free = 0; + + mbt_ctx_mark_used(sb, 1, 0, 10); + mbt_ctx_mark_used(sb, 1, 14, 16); + mbt_ctx_mark_used(sb, 1, 50, max - 50); + grp1 = ext4_get_group_info(sb, 1); + grp1->bb_free = 24; + + /* Invalid range checks */ + range.start = 0; + range.len = sb->s_blocksize - 1; + range.minlen = 0; + KUNIT_EXPECT_EQ(test, ext4_trim_fs(sb, &range), -EINVAL); + + /* Trim with minlen = 10 clusters: skips [10, 14) and trims only [30, 50) (20 clusters) */ + mbt_discard_calls = 0; + mbt_discard_clusters = 0; + range.start = 0; + range.len = (u64)ext4_blocks_count(sbi->s_es) << sb->s_blocksize_bits; + range.minlen = (u64)EXT4_C2B(sbi, 10) << sb->s_blocksize_bits; + + ret = ext4_trim_fs(sb, &range); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, mbt_discard_calls, 1); + KUNIT_EXPECT_EQ(test, mbt_discard_clusters, 20); + KUNIT_EXPECT_EQ(test, range.len, + (u64)EXT4_C2B(sbi, 20) << sb->s_blocksize_bits); + KUNIT_EXPECT_TRUE(test, EXT4_MB_GRP_WAS_TRIMMED(grp1)); + + /* Second trim with same minlen is skipped because WAS_TRIMMED is set */ + range.len = (u64)ext4_blocks_count(sbi->s_es) << sb->s_blocksize_bits; + ret = ext4_trim_fs(sb, &range); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, mbt_discard_calls, 1); + KUNIT_EXPECT_EQ(test, range.len, 0ULL); + + /* Freeing a block clears WAS_TRIMMED, allowing subsequent trim */ + ext4_free_blocks(NULL, inode, NULL, + ext4_group_first_block_no(sb, 1) + EXT4_C2B(sbi, 50), + EXT4_C2B(sbi, 1), EXT4_FREE_BLOCKS_NO_QUOT_UPDATE); + KUNIT_EXPECT_FALSE(test, EXT4_MB_GRP_WAS_TRIMMED(grp1)); +} + +struct mbt_query_ctx { + int meta_calls; + ext4_grpblk_t meta_start; + ext4_grpblk_t meta_len; + int free_calls; + ext4_grpblk_t free_starts[4]; + ext4_grpblk_t free_lens[4]; + int stop_after; +}; + +static int mbt_query_meta_cb(struct super_block *sb, ext4_group_t agno, + ext4_grpblk_t start, ext4_grpblk_t len, void *priv) +{ + struct mbt_query_ctx *q = priv; + + q->meta_calls++; + q->meta_start = start; + q->meta_len = len; + return 0; +} + +static int mbt_query_free_cb(struct super_block *sb, ext4_group_t agno, + ext4_grpblk_t start, ext4_grpblk_t len, void *priv) +{ + struct mbt_query_ctx *q = priv; + + if (q->free_calls < 4) { + q->free_starts[q->free_calls] = start; + q->free_lens[q->free_calls] = len; + } + q->free_calls++; + if (q->stop_after && q->free_calls >= q->stop_after) + return -ECANCELED; + return 0; +} + +static void test_ext4_mballoc_query_range(struct kunit *test) +{ + struct super_block *sb = (struct super_block *)test->priv; + struct mbt_query_ctx q = {}; + ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb); + int ret; + + if (sb->s_blocksize > PAGE_SIZE) + kunit_skip(test, "blocksize exceeds pagesize"); + + /* + * In group 1: + * [0, 10) used (before bb_first_free = 10 -> reported to meta_formatter) + * [10, 15) free (len 5) + * [15, 25) used + * [25, 32) free (len 7) + * [32, max) used + */ + mbt_ctx_mark_used(sb, TEST_GOAL_GROUP, 0, 10); + mbt_ctx_mark_used(sb, TEST_GOAL_GROUP, 15, 10); + mbt_ctx_mark_used(sb, TEST_GOAL_GROUP, 32, max - 32); + ext4_get_group_info(sb, TEST_GOAL_GROUP)->bb_free = 12; + + ret = ext4_mballoc_query_range(sb, TEST_GOAL_GROUP, 0, 100, + mbt_query_meta_cb, mbt_query_free_cb, &q); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, q.meta_calls, 1); + KUNIT_EXPECT_EQ(test, q.meta_start, 0); + KUNIT_EXPECT_EQ(test, q.meta_len, 10); + KUNIT_EXPECT_EQ(test, q.free_calls, 2); + KUNIT_EXPECT_EQ(test, q.free_starts[0], 10); + KUNIT_EXPECT_EQ(test, q.free_lens[0], 5); + KUNIT_EXPECT_EQ(test, q.free_starts[1], 25); + KUNIT_EXPECT_EQ(test, q.free_lens[1], 7); + + /* Early abort from formatter callback propagates error code */ + memset(&q, 0, sizeof(q)); + q.stop_after = 1; + ret = ext4_mballoc_query_range(sb, TEST_GOAL_GROUP, 0, 100, + NULL, mbt_query_free_cb, &q); + KUNIT_EXPECT_EQ(test, ret, -ECANCELED); + KUNIT_EXPECT_EQ(test, q.free_calls, 1); +} + static const struct mbt_ext4_block_layout mbt_test_layouts[] = { { .blocksize_bits = 10, @@ -991,6 +2876,31 @@ static struct kunit_case mbt_test_cases[] = { KUNIT_CASE_PARAM(test_mb_mark_used, mbt_layouts_gen_params), KUNIT_CASE_PARAM(test_mb_free_blocks, mbt_layouts_gen_params), KUNIT_CASE_PARAM(test_mark_diskspace_used, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_bit_ops, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_test_and_clear_bits, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_find_buddy_and_order, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_find_extent, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_generate_buddy_corrupt, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_free_blocks_double_free_and_fc_replay, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_xarray_orders_and_frag_size, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_good_group, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_find_by_goal, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_simple_and_aligned_scan, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_complex_scan_and_measure, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_regular_allocator, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_prefetch, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_initialize_context, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_normalize_request, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_inode_pa_lifecycle, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_group_pa_lifecycle, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_lg_list_trim, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_new_blocks_and_enospc_retry, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_mark_context_and_mark_bb, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_ext4_free_blocks_flags_and_cross_group, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_mb_free_metadata_and_process_freed_data, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_ext4_group_add_blocks, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_ext4_trim_fs, mbt_layouts_gen_params), + KUNIT_CASE_PARAM(test_ext4_mballoc_query_range, mbt_layouts_gen_params), KUNIT_CASE_PARAM_ATTR(test_mb_mark_used_cost, mbt_layouts_gen_params, { .speed = KUNIT_SPEED_SLOW }), {} diff --git a/fs/ext4/mballoc.c b/fs/ext4/mballoc.c index a15285224cdf6e..81a4f45906d337 100644 --- a/fs/ext4/mballoc.c +++ b/fs/ext4/mballoc.c @@ -234,7 +234,7 @@ * * there are two types of preallocations: * - inode - * assiged to specific inode and can be used for this inode only. + * assigned to specific inode and can be used for this inode only. * it describes part of inode's space preallocated to specific * physical blocks. any block from that preallocated can be used * independent. the descriptor just tracks number of blocks left @@ -2324,11 +2324,11 @@ static void ext4_mb_check_limits(struct ext4_allocation_context *ac, * stop the scan and use it immediately * * * If free extent found is smaller than goal, then keep retrying - * upto a max of sbi->s_mb_max_to_scan times (default 200). After + * up to a max of sbi->s_mb_max_to_scan times (default 200). After * that stop scanning and use whatever we have. * * * If free extent found is bigger than goal, then keep retrying - * upto a max of sbi->s_mb_min_to_scan times (default 10) before + * up to a max of sbi->s_mb_min_to_scan times (default 10) before * stopping the scan and using the extent. * * @@ -3027,7 +3027,7 @@ ext4_mb_regular_allocator(struct ext4_allocation_context *ac) * is greater than equal to the sbi_s_mb_order2_reqs * You can tune it via /sys/fs/ext4//mb_order2_req * We also support searching for power-of-two requests only for - * requests upto maximum buddy size we have constructed. + * requests up to maximum buddy size we have constructed. */ if (i >= sbi->s_mb_order2_reqs && i <= MB_NUM_ORDERS(sb)) { if (is_power_of_2(ac->ac_g_ex.fe_len)) @@ -3896,6 +3896,8 @@ void ext4_mb_release(struct super_block *sb) * wait the discard work to drain all of ext4_free_data */ flush_work(&sbi->s_discard_work); + /* Prevent the later journal teardown from requeueing discard work. */ + disable_work_sync(&sbi->s_discard_work); WARN_ON_ONCE(!list_empty(&sbi->s_discard_list)); group_info = rcu_access_pointer(sbi->s_group_info); @@ -3955,11 +3957,14 @@ void ext4_mb_release(struct super_block *sb) kfree(sbi->s_mb_last_groups); } -static inline int ext4_issue_discard(struct super_block *sb, +int ext4_issue_discard(struct super_block *sb, ext4_group_t block_group, ext4_grpblk_t cluster, int count) { ext4_fsblk_t discard_block; + KUNIT_STATIC_STUB_REDIRECT(ext4_issue_discard, sb, block_group, + cluster, count); + discard_block = (EXT4_C2B(EXT4_SB(sb), cluster) + ext4_group_first_block_no(sb, block_group)); count = EXT4_C2B(EXT4_SB(sb), count); @@ -4264,6 +4269,8 @@ void ext4_mb_mark_bb(struct super_block *sb, ext4_fsblk_t block, int err = 0; unsigned int clen, thisgrp_len; + KUNIT_STATIC_STUB_REDIRECT(ext4_mb_mark_bb, sb, block, len, state); + while (len > 0) { ext4_get_group_no_and_offset(sb, block, &group, &blkoff); @@ -6237,6 +6244,8 @@ ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle, int retries = 0; u64 seq; + KUNIT_STATIC_STUB_REDIRECT(ext4_mb_new_blocks, handle, ar, errp); + might_sleep(); sb = ar->inode->i_sb; sbi = EXT4_SB(sb); @@ -6695,6 +6704,9 @@ void ext4_free_blocks(handle_t *handle, struct inode *inode, unsigned int overflow; struct ext4_sb_info *sbi; + KUNIT_STATIC_STUB_REDIRECT(ext4_free_blocks, handle, inode, bh, block, + count, flags); + sbi = EXT4_SB(sb); if (bh) { @@ -7139,6 +7151,9 @@ ext4_mballoc_query_range( struct ext4_buddy e4b; int error; + KUNIT_STATIC_STUB_REDIRECT(ext4_mballoc_query_range, sb, group, first, + end, meta_formatter, formatter, priv); + error = ext4_mb_load_buddy(sb, group, &e4b); if (error) return error; @@ -7268,15 +7283,177 @@ void ext4_free_blocks_simple_test(struct inode *inode, ext4_fsblk_t block, } EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_free_blocks_simple_test); +void mb_set_bit_test(int bit, void *addr) +{ + mb_set_bit(bit, addr); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(mb_set_bit_test); + +int mb_test_and_clear_bits_test(void *bm, int cur, int len) +{ + return mb_test_and_clear_bits(bm, cur, len); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(mb_test_and_clear_bits_test); + +void *mb_find_buddy_test(struct ext4_buddy *e4b, int order, int *max) +{ + return mb_find_buddy(e4b, order, max); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(mb_find_buddy_test); + +int mb_find_order_for_block_test(struct ext4_buddy *e4b, int block) +{ + return mb_find_order_for_block(e4b, block); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(mb_find_order_for_block_test); + +int mb_find_extent_test(struct ext4_buddy *e4b, int block, int needed, + struct ext4_free_extent *ex) +{ + return mb_find_extent(e4b, block, needed, ex); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(mb_find_extent_test); + +int mb_avg_fragment_size_order_test(struct super_block *sb, ext4_grpblk_t len) +{ + return mb_avg_fragment_size_order(sb, len); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(mb_avg_fragment_size_order_test); + +void mb_update_avg_fragment_size_test(struct super_block *sb, + struct ext4_group_info *grp) +{ + mb_update_avg_fragment_size(sb, grp); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(mb_update_avg_fragment_size_test); + +void mb_set_largest_free_order_test(struct super_block *sb, + struct ext4_group_info *grp) +{ + mb_set_largest_free_order(sb, grp); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(mb_set_largest_free_order_test); + +bool ext4_mb_good_group_test(struct ext4_allocation_context *ac, + ext4_group_t group, enum criteria cr) +{ + return ext4_mb_good_group(ac, group, cr); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_good_group_test); + +int ext4_mb_good_group_nolock_test(struct ext4_allocation_context *ac, + ext4_group_t group, enum criteria cr) +{ + return ext4_mb_good_group_nolock(ac, group, cr); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_good_group_nolock_test); + +int ext4_mb_find_by_goal_test(struct ext4_allocation_context *ac, + struct ext4_buddy *e4b) +{ + return ext4_mb_find_by_goal(ac, e4b); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_find_by_goal_test); + +void ext4_mb_simple_scan_group_test(struct ext4_allocation_context *ac, + struct ext4_buddy *e4b) +{ + ext4_mb_simple_scan_group(ac, e4b); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_simple_scan_group_test); + +void ext4_mb_scan_aligned_test(struct ext4_allocation_context *ac, + struct ext4_buddy *e4b) +{ + ext4_mb_scan_aligned(ac, e4b); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_scan_aligned_test); + +void ext4_mb_complex_scan_group_test(struct ext4_allocation_context *ac, + struct ext4_buddy *e4b) +{ + ext4_mb_complex_scan_group(ac, e4b); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_complex_scan_group_test); + +void ext4_mb_try_best_found_test(struct ext4_allocation_context *ac, + struct ext4_buddy *e4b) +{ + ext4_mb_try_best_found(ac, e4b); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_try_best_found_test); + +int ext4_mb_regular_allocator_test(struct ext4_allocation_context *ac) +{ + return ext4_mb_regular_allocator(ac); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_regular_allocator_test); + +void ext4_mb_initialize_context_test(struct ext4_allocation_context *ac, + struct ext4_allocation_request *ar) +{ + ext4_mb_initialize_context(ac, ar); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_initialize_context_test); + +void ext4_mb_normalize_request_test(struct ext4_allocation_context *ac, + struct ext4_allocation_request *ar) +{ + ext4_mb_normalize_request(ac, ar); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_normalize_request_test); + +void ext4_mb_new_preallocation_test(struct ext4_allocation_context *ac) +{ + ext4_mb_new_preallocation(ac); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_new_preallocation_test); + +void ext4_mb_release_context_test(struct ext4_allocation_context *ac) +{ + ext4_mb_release_context(ac); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_release_context_test); + +int ext4_mb_pa_alloc_test(struct ext4_allocation_context *ac) +{ + return ext4_mb_pa_alloc(ac); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_pa_alloc_test); + +void ext4_mb_generate_from_pa_test(struct super_block *sb, void *bitmap, + ext4_group_t group) +{ + ext4_mb_generate_from_pa(sb, bitmap, group); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_generate_from_pa_test); + +int ext4_mb_discard_preallocations_test(struct super_block *sb, int needed) +{ + return ext4_mb_discard_preallocations(sb, needed); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_discard_preallocations_test); + EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_wait_block_bitmap); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_init); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_group_desc); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_count_free_clusters); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_group_info); -EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_free_group_clusters_set); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_group_no_and_offset); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_group_number); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_release); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_read_block_bitmap_nowait); EXPORT_SYMBOL_FOR_EXT4_TEST(mb_set_bits); -EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_init_inode); EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_mark_context); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_new_blocks); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_free_blocks); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_prefetch); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_prefetch_fini); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_discard_preallocations); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mb_mark_bb); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_process_freed_data); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_group_add_blocks); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_trim_fs); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mballoc_query_range); +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_issue_discard); #endif diff --git a/fs/ext4/mballoc.h b/fs/ext4/mballoc.h index 39333ce72cbd50..f332a23d66f866 100644 --- a/fs/ext4/mballoc.h +++ b/fs/ext4/mballoc.h @@ -86,9 +86,9 @@ #define MB_DEFAULT_LINEAR_SCAN_THRESHOLD 16 /* - * The maximum order upto which CR_BEST_AVAIL_LEN can trim a particular + * The maximum order up to which CR_BEST_AVAIL_LEN can trim a particular * allocation request. Example, if we have an order 7 request and max trim order - * of 3, we can trim this request upto order 4. + * of 3, we can trim this request up to order 4. */ #define MB_DEFAULT_BEST_AVAIL_TRIM_ORDER 3 @@ -275,6 +275,8 @@ extern int ext4_mb_mark_context(handle_t *handle, ext4_group_t group, ext4_grpblk_t blkoff, ext4_grpblk_t len, int flags, ext4_grpblk_t *ret_changed); +extern int ext4_issue_discard(struct super_block *sb, + ext4_group_t block_group, ext4_grpblk_t cluster, int count); #if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) extern void mb_clear_bits_test(void *bm, int cur, int len); extern ext4_fsblk_t @@ -283,7 +285,45 @@ ext4_mb_new_blocks_simple_test(struct ext4_allocation_request *ar, extern int mb_find_next_zero_bit_test(void *addr, int max, int start); extern int mb_find_next_bit_test(void *addr, int max, int start); extern void mb_clear_bit_test(int bit, void *addr); +extern void mb_set_bit_test(int bit, void *addr); extern int mb_test_bit_test(int bit, void *addr); +extern int mb_test_and_clear_bits_test(void *bm, int cur, int len); +extern void *mb_find_buddy_test(struct ext4_buddy *e4b, int order, int *max); +extern int mb_find_order_for_block_test(struct ext4_buddy *e4b, int block); +extern int mb_find_extent_test(struct ext4_buddy *e4b, int block, int needed, + struct ext4_free_extent *ex); +extern int mb_avg_fragment_size_order_test(struct super_block *sb, + ext4_grpblk_t len); +extern void mb_update_avg_fragment_size_test(struct super_block *sb, + struct ext4_group_info *grp); +extern void mb_set_largest_free_order_test(struct super_block *sb, + struct ext4_group_info *grp); +extern bool ext4_mb_good_group_test(struct ext4_allocation_context *ac, + ext4_group_t group, enum criteria cr); +extern int ext4_mb_good_group_nolock_test(struct ext4_allocation_context *ac, + ext4_group_t group, enum criteria cr); +extern int ext4_mb_find_by_goal_test(struct ext4_allocation_context *ac, + struct ext4_buddy *e4b); +extern void ext4_mb_simple_scan_group_test(struct ext4_allocation_context *ac, + struct ext4_buddy *e4b); +extern void ext4_mb_scan_aligned_test(struct ext4_allocation_context *ac, + struct ext4_buddy *e4b); +extern void ext4_mb_complex_scan_group_test(struct ext4_allocation_context *ac, + struct ext4_buddy *e4b); +extern void ext4_mb_try_best_found_test(struct ext4_allocation_context *ac, + struct ext4_buddy *e4b); +extern int ext4_mb_regular_allocator_test(struct ext4_allocation_context *ac); +extern void ext4_mb_initialize_context_test(struct ext4_allocation_context *ac, + struct ext4_allocation_request *ar); +extern void ext4_mb_normalize_request_test(struct ext4_allocation_context *ac, + struct ext4_allocation_request *ar); +extern void ext4_mb_new_preallocation_test(struct ext4_allocation_context *ac); +extern void ext4_mb_release_context_test(struct ext4_allocation_context *ac); +extern int ext4_mb_pa_alloc_test(struct ext4_allocation_context *ac); +extern void ext4_mb_generate_from_pa_test(struct super_block *sb, void *bitmap, + ext4_group_t group); +extern int ext4_mb_discard_preallocations_test(struct super_block *sb, + int needed); extern int ext4_mb_mark_diskspace_used_test(struct ext4_allocation_context *ac, handle_t *handle); diff --git a/fs/ext4/migrate-test.c b/fs/ext4/migrate-test.c new file mode 100644 index 00000000000000..5a616827e78c89 --- /dev/null +++ b/fs/ext4/migrate-test.c @@ -0,0 +1,1384 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for fs/ext4/migrate.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_extents.h" +#include "ext4_jbd2.h" + +#define MIGRATE_TEST_BLK_SIZE 1024U +#define MIGRATE_TEST_BLK_BITS 10U +#define MIGRATE_TEST_BLOCKS_PER_GRP 1024U +#define MIGRATE_TEST_NGROUPS 8U +#define MIGRATE_TEST_FIRST_DATA_BLK 1U +#define MIGRATE_TEST_TOTAL_BLKS (MIGRATE_TEST_FIRST_DATA_BLK + \ + MIGRATE_TEST_NGROUPS * \ + MIGRATE_TEST_BLOCKS_PER_GRP) +#define MIGRATE_TEST_INODE_SIZE 256U +#define MIGRATE_TEST_EXTRA_ISIZE 32U +#define MIGRATE_TEST_INODES_PER_GRP 32U +#define MIGRATE_MAX_FREED_REC 32U + +struct migrate_mock_blk { + struct list_head node; + ext4_fsblk_t blocknr; + struct buffer_head bh; + u8 *data; +}; + +struct migrate_test_ctx { + struct super_block *sb; + struct ext4_sb_info sbi; + struct ext4_super_block *es; + struct blockgroup_lock bgl; + struct gendisk bdev_disk; + struct block_device bdev; + struct request_queue bdev_queue; + struct inode bd_inode; + struct folio *bh_folio; + struct list_head blks; + ext4_fsblk_t device_blocks; + ext4_fsblk_t next_alloc_pblk; + int new_inode_err; + ext4_fsblk_t freed_blks[MIGRATE_MAX_FREED_REC]; + unsigned int freed_cnt; + unsigned int datasem_restarts; + struct inode *race_inode; + int mark_dirty_err; + struct inode *mark_dirty_err_inode; + int ensure_credits_err; + struct inode *ensure_credits_after_swap_inode; + bool evict_tmp_seen; + loff_t evict_tmp_isize; + blkcnt_t evict_tmp_iblocks; + u16 evict_tmp_eh_entries; + u16 evict_tmp_eh_depth; + __u32 evict_tmp_csum_seed; + bool rwsem_inited; + bool es_shrinker_inited; +}; + +static struct kunit *active_migrate_test; + +static struct inode *migrate_test_alloc_inode(struct super_block *sb) +{ + struct ext4_inode_info *ei; + + ei = kzalloc_obj(*ei); + if (!ei) + return NULL; + + init_rwsem(&ei->i_data_sem); + inode_init_once(&ei->vfs_inode); + inode_set_iversion(&ei->vfs_inode, 1); + ei->i_prealloc_node = RB_ROOT; + rwlock_init(&ei->i_prealloc_lock); + ext4_es_init_tree(&ei->i_es_tree); + rwlock_init(&ei->i_es_lock); + INIT_LIST_HEAD(&ei->i_es_list); + spin_lock_init(&ei->i_raw_lock); + spin_lock_init(&ei->i_block_reservation_lock); + ext4_init_pending_tree(&ei->i_pending_tree); + init_rwsem(&ei->xattr_sem); + INIT_LIST_HEAD(&ei->i_rsv_conversion_list); + spin_lock_init(&ei->i_completed_io_lock); + INIT_LIST_HEAD(&ei->i_orphan); + ext4_fc_init_inode(&ei->vfs_inode); + spin_lock_init(&ei->i_fc_lock); + ei->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + ei->i_extra_isize = MIGRATE_TEST_EXTRA_ISIZE; + ei->i_last_alloc_group = ~0U; + + return &ei->vfs_inode; +} + +static void migrate_test_free_inode(struct inode *inode) +{ + kfree(EXT4_I(inode)); +} + +static void migrate_test_evict_inode(struct inode *inode) +{ + struct kunit *test = active_migrate_test; + + if (test && test->priv && inode->i_ino == 99) { + struct migrate_test_ctx *ctx = test->priv; + struct ext4_extent_header *eh = ext_inode_hdr(inode); + + ctx->evict_tmp_seen = true; + ctx->evict_tmp_isize = i_size_read(inode); + ctx->evict_tmp_iblocks = inode->i_blocks; + ctx->evict_tmp_eh_entries = le16_to_cpu(eh->eh_entries); + ctx->evict_tmp_eh_depth = le16_to_cpu(eh->eh_depth); + ctx->evict_tmp_csum_seed = EXT4_I(inode)->i_csum_seed; + } + truncate_inode_pages_final(&inode->i_data); + ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS); + clear_inode(inode); +} + +#ifdef CONFIG_QUOTA +static struct dquot __rcu **migrate_test_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} +#endif + +static const struct super_operations migrate_test_sops = { + .alloc_inode = migrate_test_alloc_inode, + .free_inode = migrate_test_free_inode, + .evict_inode = migrate_test_evict_inode, +#ifdef CONFIG_QUOTA + .get_dquots = migrate_test_get_dquots, +#endif +}; + +static int migrate_test_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static void migrate_test_sb_upd_work(struct work_struct *work) +{ +} + +static void migrate_test_err_timer(struct timer_list *t) +{ +} + +static struct file_system_type migrate_test_fs_type = { + .name = "ext4_migrate_kunit", + .init_fs_context = migrate_test_init_fs_context, + .kill_sb = kill_anon_super, +}; + +static void migrate_init_mock_bh(struct buffer_head *bh, struct folio *folio, + u8 *data, size_t size, sector_t blocknr) +{ + memset(bh, 0, sizeof(*bh)); + bh->b_folio = folio; + bh->b_data = (char *)data; + bh->b_size = size; + bh->b_blocknr = blocknr; + atomic_set(&bh->b_count, 2); + set_buffer_uptodate(bh); + set_buffer_mapped(bh); +} + +static struct buffer_head *migrate_lookup_bh(struct migrate_test_ctx *ctx, + ext4_fsblk_t blocknr) +{ + struct migrate_mock_blk *blk; + + list_for_each_entry(blk, &ctx->blks, node) { + if (blk->blocknr == blocknr) + return &blk->bh; + } + return NULL; +} + +static struct buffer_head *migrate_get_or_create_bh(struct migrate_test_ctx *ctx, + ext4_fsblk_t blocknr) +{ + struct buffer_head *bh; + struct migrate_mock_blk *blk; + + bh = migrate_lookup_bh(ctx, blocknr); + if (bh) { + get_bh(bh); + return bh; + } + + blk = kzalloc_obj(*blk); + if (!blk) + return NULL; + blk->data = kzalloc(MIGRATE_TEST_BLK_SIZE, GFP_KERNEL); + if (!blk->data) { + kfree(blk); + return NULL; + } + blk->blocknr = blocknr; + migrate_init_mock_bh(&blk->bh, ctx->bh_folio, blk->data, + MIGRATE_TEST_BLK_SIZE, blocknr); + list_add_tail(&blk->node, &ctx->blks); + get_bh(&blk->bh); + return &blk->bh; +} + +static struct buffer_head *migrate_sb_bread_stub(struct super_block *sb, + sector_t block, + blk_opf_t op_flags) +{ + struct kunit *test = active_migrate_test; + struct migrate_test_ctx *ctx; + struct buffer_head *bh; + + if (!test) + return ERR_PTR(-EIO); + ctx = test->priv; + if (!ctx || sb != ctx->sb) + return ERR_PTR(-EIO); + if ((ext4_fsblk_t)block >= ctx->device_blocks) + return ERR_PTR(-EIO); + + bh = migrate_get_or_create_bh(ctx, block); + if (!bh) + return ERR_PTR(-ENOMEM); + return bh; +} + +static struct buffer_head *migrate_ext_getblk_stub(struct inode *inode, + ext4_fsblk_t pblk, + gfp_t gfp_flags) +{ + struct kunit *test = active_migrate_test; + struct migrate_test_ctx *ctx; + + if (!test) + return NULL; + ctx = test->priv; + if (!ctx) + return NULL; + + return migrate_get_or_create_bh(ctx, pblk); +} + +static int migrate_ext_dirty_stub(const char *where, unsigned int line, + handle_t *handle, struct inode *inode, + struct ext4_ext_path *path) +{ + if (path && path->p_bh) { + ext4_extent_block_csum_set_test(inode, + ext_block_hdr(path->p_bh)); + set_buffer_verified(path->p_bh); + } + return 0; +} + +static int migrate_handle_dirty_metadata_stub(const char *where, + unsigned int line, + handle_t *handle, + struct inode *inode, + struct buffer_head *bh) +{ + if (bh) + set_buffer_uptodate(bh); + return 0; +} + +static int migrate_mark_inode_dirty_stub(handle_t *handle, struct inode *inode, + const char *func, unsigned int line) +{ + struct kunit *test = active_migrate_test; + + if (test && test->priv) { + struct migrate_test_ctx *ctx = test->priv; + + if (ctx->mark_dirty_err && inode == ctx->mark_dirty_err_inode) + return ctx->mark_dirty_err; + } + return 0; +} + +static int migrate_ensure_credits_stub(handle_t *handle, int check_cred, + int extend_cred, int revoke_cred) +{ + struct kunit *test = active_migrate_test; + + if (test && test->priv) { + struct migrate_test_ctx *ctx = test->priv; + + if (ctx->ensure_credits_err && + ctx->ensure_credits_after_swap_inode && + ext4_test_inode_flag(ctx->ensure_credits_after_swap_inode, + EXT4_INODE_EXTENTS)) + return ctx->ensure_credits_err; + } + return 0; +} + +static struct inode *migrate_new_inode_stub(const struct mnt_idmap *idmap, + handle_t *handle, + struct inode *dir, umode_t mode, + const struct qstr *qstr, + __u32 goal, uid_t *owner, + __u32 i_flags, int handle_type, + unsigned int line_no, int nblocks) +{ + struct kunit *test = active_migrate_test; + struct migrate_test_ctx *ctx; + struct inode *inode; + + if (!test) + return ERR_PTR(-EIO); + ctx = test->priv; + if (!ctx) + return ERR_PTR(-EIO); + if (ctx->new_inode_err) + return ERR_PTR(ctx->new_inode_err); + + inode = new_inode(dir->i_sb); + if (!inode) + return ERR_PTR(-ENOMEM); + + inode->i_ino = 99; + inode->i_mode = mode; + inode->i_blkbits = dir->i_sb->s_blocksize_bits; + inode->i_flags |= S_NOQUOTA; + EXT4_I(inode)->i_flags = i_flags; + EXT4_I(inode)->i_csum_seed = 0xabcdef01U; + if (owner) { + i_uid_write(inode, owner[0]); + i_gid_write(inode, owner[1]); + } + inode_state_set_raw(inode, I_NEW); + return inode; +} + +static ext4_fsblk_t migrate_mb_new_blocks_stub(handle_t *handle, + struct ext4_allocation_request *ar, + int *errp) +{ + struct kunit *test = active_migrate_test; + struct migrate_test_ctx *ctx; + ext4_fsblk_t pblk; + + if (!test) { + *errp = -EIO; + return 0; + } + ctx = test->priv; + pblk = ctx->next_alloc_pblk; + ctx->next_alloc_pblk += ar->len; + ar->inode->i_blocks += (blkcnt_t)ar->len << + (ar->inode->i_blkbits - 9); + *errp = 0; + return pblk; +} + +static void migrate_free_blocks_stub(handle_t *handle, struct inode *inode, + struct buffer_head *bh, ext4_fsblk_t block, + unsigned long count, int flags) +{ + struct kunit *test = active_migrate_test; + struct migrate_test_ctx *ctx; + blkcnt_t sectors; + unsigned long i; + + if (!test) + return; + ctx = test->priv; + for (i = 0; i < count && ctx->freed_cnt < MIGRATE_MAX_FREED_REC; i++) + ctx->freed_blks[ctx->freed_cnt++] = block + i; + + sectors = (blkcnt_t)count << (inode->i_blkbits - 9); + if (inode->i_blocks >= sectors) + inode->i_blocks -= sectors; + if (bh) + brelse(bh); +} + +static bool migrate_was_freed(struct migrate_test_ctx *ctx, ext4_fsblk_t blk) +{ + unsigned int i; + + for (i = 0; i < ctx->freed_cnt; i++) { + if (ctx->freed_blks[i] == blk) + return true; + } + return false; +} + +/* + * Emulate ext4_datasem_ensure_credits() having to restart the transaction: + * i_data_sem is dropped and re-acquired and 1 is returned. + */ +static int migrate_datasem_restart_stub(handle_t *handle, struct inode *inode, + int check_cred, int restart_cred, + int revoke_cred) +{ + struct migrate_test_ctx *ctx = active_migrate_test->priv; + + up_write(&EXT4_I(inode)->i_data_sem); + down_write(&EXT4_I(inode)->i_data_sem); + ctx->datasem_restarts++; + return 1; +} + +/* + * Emulate a block allocation racing with the migration of + * ctx->race_inode, which clears EXT4_STATE_EXT_MIGRATE on it. + */ +static int migrate_datasem_race_stub(handle_t *handle, struct inode *inode, + int check_cred, int restart_cred, + int revoke_cred) +{ + struct migrate_test_ctx *ctx = active_migrate_test->priv; + + ext4_clear_inode_state(ctx->race_inode, EXT4_STATE_EXT_MIGRATE); + return 0; +} + +KUNIT_DEFINE_ACTION_WRAPPER(migrate_iput_action, iput, struct inode *); + +static struct inode *migrate_make_test_inode(struct kunit *test, unsigned long ino, + umode_t mode) +{ + struct migrate_test_ctx *ctx = test->priv; + struct inode *inode; + int ret; + + inode = new_inode(ctx->sb); + KUNIT_ASSERT_NOT_NULL(test, inode); + inode->i_ino = ino; + inode->i_mode = mode; + inode->i_blkbits = MIGRATE_TEST_BLK_BITS; + inode->i_flags |= S_NOQUOTA; + EXT4_I(inode)->i_csum_seed = 0x55aa55aaU; + ret = kunit_add_action_or_reset(test, migrate_iput_action, inode); + KUNIT_ASSERT_EQ(test, ret, 0); + return inode; +} + +static void migrate_test_cleanup(struct migrate_test_ctx *ctx) +{ + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + struct migrate_mock_blk *blk, *tmp; + + active_migrate_test = NULL; + + cancel_work_sync(&sbi->s_sb_upd_work); + timer_delete_sync(&sbi->s_err_report); + + if (sb) { + deactivate_super(sb); + ctx->sb = NULL; + } + rcu_barrier(); + + if (ctx->es_shrinker_inited) { + ext4_es_unregister_shrinker(sbi); + ext4_es_destroy_stats(sbi); + ctx->es_shrinker_inited = false; + } + + percpu_counter_destroy(&sbi->s_freeclusters_counter); + percpu_counter_destroy(&sbi->s_dirtyclusters_counter); + percpu_counter_destroy(&sbi->s_freeinodes_counter); + + if (ctx->rwsem_inited) { + percpu_free_rwsem(&sbi->s_writepages_rwsem); + ctx->rwsem_inited = false; + } + + list_for_each_entry_safe(blk, tmp, &ctx->blks, node) { + list_del(&blk->node); + kfree(blk->data); + kfree(blk); + } + + if (ctx->bh_folio) { + folio_put(ctx->bh_folio); + ctx->bh_folio = NULL; + } + + if (ctx->bdev.bd_stats) { + free_percpu(ctx->bdev.bd_stats); + ctx->bdev.bd_stats = NULL; + } +} + +KUNIT_DEFINE_ACTION_WRAPPER(migrate_test_cleanup_action, migrate_test_cleanup, + struct migrate_test_ctx *); + +static int migrate_test_set_super(struct super_block *sb, struct fs_context *fc) +{ + return set_anon_super_fc(sb, fc); +} + +static int migrate_test_init(struct kunit *test) +{ + struct migrate_test_ctx *ctx; + struct fs_context *fc; + struct super_block *sb; + struct ext4_sb_info *sbi; + struct buffer_head *sbh; + struct inode *root_inode; + int ret; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + INIT_LIST_HEAD(&ctx->blks); + ctx->device_blocks = MIGRATE_TEST_TOTAL_BLKS; + ctx->next_alloc_pblk = 900; + test->priv = ctx; + + ctx->bdev.bd_stats = alloc_percpu(struct disk_stats); + KUNIT_ASSERT_TRUE(test, ctx->bdev.bd_stats != NULL); + + ctx->bh_folio = folio_alloc(GFP_KERNEL, 0); + if (!ctx->bh_folio) { + free_percpu(ctx->bdev.bd_stats); + ctx->bdev.bd_stats = NULL; + KUNIT_FAIL_AND_ABORT(test, "folio_alloc failed"); + } + + fc = fs_context_for_mount(&migrate_test_fs_type, 0); + if (IS_ERR(fc)) { + folio_put(ctx->bh_folio); + ctx->bh_folio = NULL; + free_percpu(ctx->bdev.bd_stats); + ctx->bdev.bd_stats = NULL; + KUNIT_FAIL_AND_ABORT(test, "fs_context_for_mount failed: %ld", + PTR_ERR(fc)); + } + sb = sget_fc(fc, NULL, migrate_test_set_super); + put_fs_context(fc); + if (IS_ERR(sb)) { + folio_put(ctx->bh_folio); + ctx->bh_folio = NULL; + free_percpu(ctx->bdev.bd_stats); + ctx->bdev.bd_stats = NULL; + KUNIT_FAIL_AND_ABORT(test, "sget_fc failed: %ld", PTR_ERR(sb)); + } + ctx->sb = sb; + sbi = &ctx->sbi; + INIT_WORK(&sbi->s_sb_upd_work, migrate_test_sb_upd_work); + timer_setup(&sbi->s_err_report, migrate_test_err_timer, 0); + up_write(&sb->s_umount); + + ret = kunit_add_action_or_reset(test, migrate_test_cleanup_action, ctx); + KUNIT_ASSERT_EQ(test, ret, 0); + + sb->s_fs_info = sbi; + sb->s_op = &migrate_test_sops; + sb->s_blocksize = MIGRATE_TEST_BLK_SIZE; + sb->s_blocksize_bits = MIGRATE_TEST_BLK_BITS; + sb->s_magic = EXT4_SUPER_MAGIC; + sb->s_maxbytes = MAX_LFS_FILESIZE; + INIT_LIST_HEAD(&sb->s_inodes); +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; +#endif + + strscpy(sb->s_id, "ext4_migrate_kunit", sizeof(sb->s_id)); + inode_init_once(&ctx->bd_inode); + ctx->bd_inode.i_sb = sb; + ctx->bd_inode.i_blkbits = MIGRATE_TEST_BLK_BITS; + ctx->bd_inode.i_mapping = &ctx->bd_inode.i_data; + ctx->bd_inode.i_data.host = &ctx->bd_inode; + ctx->bdev_disk.part0 = &ctx->bdev; + ctx->bdev_disk.queue = &ctx->bdev_queue; + ctx->bdev.bd_disk = &ctx->bdev_disk; + ctx->bdev.bd_queue = &ctx->bdev_queue; + ctx->bdev.bd_mapping = &ctx->bd_inode.i_data; + bdev_clear_flag(&ctx->bdev, BD_READ_ONLY); + sb->s_bdev = &ctx->bdev; + + sbi->s_sb = sb; + sbi->s_blockgroup_lock = &ctx->bgl; + bgl_lock_init(&ctx->bgl); + spin_lock_init(&sbi->s_error_lock); + spin_lock_init(&sbi->s_md_lock); + spin_lock_init(&sbi->s_bdev_wb_lock); + spin_lock_init(&sbi->s_es_lock); + INIT_LIST_HEAD(&sbi->s_es_list); + mutex_init(&sbi->s_fc_lock); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_STAGING]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_STAGING]); + ratelimit_state_init(&sbi->s_err_ratelimit_state, 5 * HZ, 10); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, 5 * HZ, 10); + ratelimit_state_init(&sbi->s_msg_ratelimit_state, 5 * HZ, 10); + + ret = percpu_init_rwsem(&sbi->s_writepages_rwsem); + KUNIT_ASSERT_EQ(test, ret, 0); + ctx->rwsem_inited = true; + + ret = percpu_counter_init(&sbi->s_freeclusters_counter, 4096, + GFP_KERNEL); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = percpu_counter_init(&sbi->s_dirtyclusters_counter, 0, GFP_KERNEL); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = percpu_counter_init(&sbi->s_freeinodes_counter, 200, GFP_KERNEL); + KUNIT_ASSERT_EQ(test, ret, 0); + + ret = ext4_es_register_shrinker(sbi); + KUNIT_ASSERT_EQ(test, ret, 0); + ctx->es_shrinker_inited = true; + + sbi->s_blocks_per_group = MIGRATE_TEST_BLOCKS_PER_GRP; + sbi->s_clusters_per_group = MIGRATE_TEST_BLOCKS_PER_GRP; + sbi->s_cluster_ratio = 1; + sbi->s_cluster_bits = 0; + sbi->s_groups_count = MIGRATE_TEST_NGROUPS; + sbi->s_inodes_per_group = MIGRATE_TEST_INODES_PER_GRP; + sbi->s_inode_size = MIGRATE_TEST_INODE_SIZE; + sbi->s_inodes_per_block = MIGRATE_TEST_BLK_SIZE / + MIGRATE_TEST_INODE_SIZE; + sbi->s_first_ino = 11; + sbi->s_mount_state = EXT4_VALID_FS; + set_opt(sb, ERRORS_CONT); + + sbh = migrate_get_or_create_bh(ctx, MIGRATE_TEST_FIRST_DATA_BLK); + KUNIT_ASSERT_NOT_NULL(test, sbh); + brelse(sbh); + sbi->s_sbh = sbh; + ctx->es = (struct ext4_super_block *)sbh->b_data; + sbi->s_es = ctx->es; + + ctx->es->s_magic = cpu_to_le16(EXT4_SUPER_MAGIC); + ctx->es->s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + ctx->es->s_first_data_block = cpu_to_le32(MIGRATE_TEST_FIRST_DATA_BLK); + ctx->es->s_blocks_per_group = cpu_to_le32(MIGRATE_TEST_BLOCKS_PER_GRP); + ctx->es->s_clusters_per_group = + cpu_to_le32(MIGRATE_TEST_BLOCKS_PER_GRP); + ctx->es->s_inodes_per_group = cpu_to_le32(MIGRATE_TEST_INODES_PER_GRP); + ctx->es->s_inodes_count = cpu_to_le32(MIGRATE_TEST_NGROUPS * + MIGRATE_TEST_INODES_PER_GRP); + ctx->es->s_inode_size = cpu_to_le16(MIGRATE_TEST_INODE_SIZE); + ctx->es->s_checksum_type = EXT4_CRC32C_CHKSUM; + generate_random_uuid(ctx->es->s_uuid); + ext4_blocks_count_set(ctx->es, MIGRATE_TEST_TOTAL_BLKS); + ext4_set_feature_extents(sb); + ext4_set_feature_64bit(sb); + ext4_set_feature_metadata_csum(sb); + sbi->s_csum_seed = ext4_chksum(~0, ctx->es->s_uuid, + sizeof(ctx->es->s_uuid)); + ext4_superblock_csum_set(sb); + + root_inode = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, root_inode); + root_inode->i_ino = EXT4_ROOT_INO; + root_inode->i_mode = S_IFDIR | 0755; + root_inode->i_blkbits = MIGRATE_TEST_BLK_BITS; + root_inode->i_flags |= S_NOQUOTA; + root_inode->i_op = &simple_dir_inode_operations; + set_nlink(root_inode, 2); + sb->s_root = d_make_root(root_inode); + KUNIT_ASSERT_NOT_NULL(test, sb->s_root); + sb->s_flags |= SB_ACTIVE; + + active_migrate_test = test; + kunit_activate_static_stub(test, ext4_sb_bread, migrate_sb_bread_stub); + kunit_activate_static_stub(test, ext4_ext_getblk, + migrate_ext_getblk_stub); + kunit_activate_static_stub(test, __ext4_ext_dirty, + migrate_ext_dirty_stub); + kunit_activate_static_stub(test, __ext4_handle_dirty_metadata, + migrate_handle_dirty_metadata_stub); + kunit_activate_static_stub(test, __ext4_mark_inode_dirty, + migrate_mark_inode_dirty_stub); + kunit_activate_static_stub(test, __ext4_new_inode, + migrate_new_inode_stub); + kunit_activate_static_stub(test, ext4_mb_new_blocks, + migrate_mb_new_blocks_stub); + kunit_activate_static_stub(test, ext4_free_blocks, + migrate_free_blocks_stub); + + return 0; +} + +/* + * Test 1: ext4_ext_migrate() precondition guards, fast symlink no-op, and + * temporary inode allocation failure handling. + */ +static void test_ext_migrate_precondition_checks_and_fast_symlink(struct kunit *test) +{ + struct migrate_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct inode *inode, *symlink; + + inode = migrate_make_test_inode(test, 12, S_IFREG | 0644); + + /* 1. Filesystem lacks extents feature -> -EINVAL */ + ext4_clear_feature_extents(sb); + KUNIT_EXPECT_EQ(test, ext4_ext_migrate(inode), -EINVAL); + ext4_set_feature_extents(sb); + + /* 2. Inode already uses extents -> -EINVAL */ + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + KUNIT_EXPECT_EQ(test, ext4_ext_migrate(inode), -EINVAL); + ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS); + + /* 3. Inline-data inode -> -EINVAL */ + ext4_set_inode_flag(inode, EXT4_INODE_INLINE_DATA); + EXT4_I(inode)->i_inline_off = 164; + KUNIT_EXPECT_EQ(test, ext4_ext_migrate(inode), -EINVAL); + ext4_clear_inode_flag(inode, EXT4_INODE_INLINE_DATA); + EXT4_I(inode)->i_inline_off = 0; + + /* 4. Fast symlink (S_IFLNK && i_blocks == 0) is a clean no-op */ + symlink = migrate_make_test_inode(test, 13, S_IFLNK | 0777); + symlink->i_blocks = 0; + memcpy(EXT4_I(symlink)->i_data, "target/path", 11); + KUNIT_EXPECT_EQ(test, ext4_ext_migrate(symlink), 0); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_flag(symlink, EXT4_INODE_EXTENTS)); + KUNIT_EXPECT_MEMEQ(test, EXT4_I(symlink)->i_data, "target/path", 11); + + /* 5. Temporary inode allocation failure (-ENOSPC) propagates */ + ctx->new_inode_err = -ENOSPC; + KUNIT_EXPECT_EQ(test, ext4_ext_migrate(inode), -ENOSPC); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + ctx->new_inode_err = 0; +} + +/* + * Test 2: ext4_ext_migrate() coalesces contiguous direct + single-indirect + * runs across the EXT4_NDIR_BLOCKS boundary, preserves sparse holes, and + * frees the indirect metadata block. + */ +static void test_ext_migrate_direct_and_ind_coalescing_and_holes(struct kunit *test) +{ + struct migrate_test_ctx *ctx = test->priv; + struct inode *inode; + struct buffer_head *ind_bh; + __le32 *ind_data; + struct ext4_extent_header *eh; + struct ext4_extent *ex; + + inode = migrate_make_test_inode(test, 14, S_IFREG | 0644); + i_size_write(inode, 25 * MIGRATE_TEST_BLK_SIZE); + inode->i_blocks = 8 * (MIGRATE_TEST_BLK_SIZE >> 9); + + /* Direct [0..2] -> 100..102; hole [3..10]; Direct [11] -> 200 */ + EXT4_I(inode)->i_data[0] = cpu_to_le32(100); + EXT4_I(inode)->i_data[1] = cpu_to_le32(101); + EXT4_I(inode)->i_data[2] = cpu_to_le32(102); + EXT4_I(inode)->i_data[11] = cpu_to_le32(200); + + /* IND block 500: [0..1] (lblks 12..13) -> 201..202; [10] (lblk 22) -> 350 */ + EXT4_I(inode)->i_data[EXT4_IND_BLOCK] = cpu_to_le32(500); + ind_bh = migrate_get_or_create_bh(ctx, 500); + KUNIT_ASSERT_NOT_NULL(test, ind_bh); + ind_data = (__le32 *)ind_bh->b_data; + ind_data[0] = cpu_to_le32(201); + ind_data[1] = cpu_to_le32(202); + ind_data[10] = cpu_to_le32(350); + brelse(ind_bh); + + KUNIT_EXPECT_EQ(test, ext4_ext_migrate(inode), 0); + KUNIT_EXPECT_TRUE(test, + ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + + eh = ext_inode_hdr(inode); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_magic), + le16_to_cpu(EXT4_EXT_MAGIC)); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_depth), 0U); + KUNIT_ASSERT_EQ(test, le16_to_cpu(eh->eh_entries), 3U); + + ex = EXT_FIRST_EXTENT(eh); + /* Extent 0: lblk [0..2] -> pblk 100 */ + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[0].ee_block), 0U); + KUNIT_EXPECT_EQ(test, le16_to_cpu(ex[0].ee_len), 3U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex[0]), 100ULL); + + /* Extent 1: lblk [11..13] coalesced across DIRECT/IND -> pblk 200 */ + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[1].ee_block), 11U); + KUNIT_EXPECT_EQ(test, le16_to_cpu(ex[1].ee_len), 3U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex[1]), 200ULL); + + /* Extent 2: lblk [22..22] -> pblk 350 */ + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[2].ee_block), 22U); + KUNIT_EXPECT_EQ(test, le16_to_cpu(ex[2].ee_len), 1U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex[2]), 350ULL); + + /* Indirect metadata block 500 was freed */ + KUNIT_EXPECT_TRUE(test, migrate_was_freed(ctx, 500)); +} + +/* + * Test 3: ext4_ext_migrate() across DIRECT, IND, DIND, and TIND sparse blocks + * (> 4 discontiguous extents, growing a depth-1 extent tree) and freeing all + * indirect metadata blocks at every level. + */ +static void test_ext_migrate_dind_tind_and_multilevel_tree(struct kunit *test) +{ + struct migrate_test_ctx *ctx = test->priv; + struct inode *inode; + struct buffer_head *bh; + struct ext4_ext_path *path; + static const struct { + ext4_lblk_t lblk; + ext4_fsblk_t pblk; + } expected[] = { + { 0, 100 }, + { 5, 110 }, + { 15, 120 }, + { 780, 130 }, + { 131341, 140 }, + { 131345, 150 }, + }; + static const ext4_fsblk_t expected_freed_meta[] = { + 510, 520, 521, 530, 531, 532 + }; + unsigned int i; + + inode = migrate_make_test_inode(test, 15, S_IFREG | 0644); + i_size_write(inode, 140000ULL * MIGRATE_TEST_BLK_SIZE); + inode->i_blocks = 12 * (MIGRATE_TEST_BLK_SIZE >> 9); + + /* Direct: lblk 0 -> 100, lblk 5 -> 110 */ + EXT4_I(inode)->i_data[0] = cpu_to_le32(100); + EXT4_I(inode)->i_data[5] = cpu_to_le32(110); + + /* IND (510): entry 3 (lblk 12 + 3 = 15) -> 120 */ + EXT4_I(inode)->i_data[EXT4_IND_BLOCK] = cpu_to_le32(510); + bh = migrate_get_or_create_bh(ctx, 510); + KUNIT_ASSERT_NOT_NULL(test, bh); + ((__le32 *)bh->b_data)[3] = cpu_to_le32(120); + brelse(bh); + + /* DIND (520) -> [2] = 521 -> [0] (lblk 12 + 256 + 512 = 780) -> 130 */ + EXT4_I(inode)->i_data[EXT4_DIND_BLOCK] = cpu_to_le32(520); + bh = migrate_get_or_create_bh(ctx, 520); + KUNIT_ASSERT_NOT_NULL(test, bh); + ((__le32 *)bh->b_data)[2] = cpu_to_le32(521); + brelse(bh); + + bh = migrate_get_or_create_bh(ctx, 521); + KUNIT_ASSERT_NOT_NULL(test, bh); + ((__le32 *)bh->b_data)[0] = cpu_to_le32(130); + brelse(bh); + + /* + * TIND (530) -> [1] = 531 -> [0] = 532 -> [1] (lblk 12 + 256 + 65536 + + * 65536 + 1 = 131341 -> 140) and [5] (lblk 131345 -> 150). + */ + EXT4_I(inode)->i_data[EXT4_TIND_BLOCK] = cpu_to_le32(530); + bh = migrate_get_or_create_bh(ctx, 530); + KUNIT_ASSERT_NOT_NULL(test, bh); + ((__le32 *)bh->b_data)[1] = cpu_to_le32(531); + brelse(bh); + + bh = migrate_get_or_create_bh(ctx, 531); + KUNIT_ASSERT_NOT_NULL(test, bh); + ((__le32 *)bh->b_data)[0] = cpu_to_le32(532); + brelse(bh); + + bh = migrate_get_or_create_bh(ctx, 532); + KUNIT_ASSERT_NOT_NULL(test, bh); + ((__le32 *)bh->b_data)[1] = cpu_to_le32(140); + ((__le32 *)bh->b_data)[5] = cpu_to_le32(150); + brelse(bh); + + KUNIT_EXPECT_EQ(test, ext4_ext_migrate(inode), 0); + KUNIT_EXPECT_TRUE(test, + ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + KUNIT_EXPECT_EQ(test, le16_to_cpu(ext_inode_hdr(inode)->eh_depth), 1U); + + for (i = 0; i < ARRAY_SIZE(expected); i++) { + struct ext4_extent ex; + + path = ext4_find_extent(inode, expected[i].lblk, NULL, + EXT4_EX_FORCE_CACHE); + KUNIT_ASSERT_FALSE_MSG(test, IS_ERR(path), + "find_extent failed at idx %u", i); + if (!path[path->p_depth].p_ext) { + ext4_free_ext_path(path); + KUNIT_FAIL_AND_ABORT(test, + "missing extent at idx %u", i); + } + ex = *path[path->p_depth].p_ext; + ext4_free_ext_path(path); + KUNIT_EXPECT_EQ_MSG(test, le32_to_cpu(ex.ee_block), + expected[i].lblk, "lblk idx %u", i); + KUNIT_EXPECT_EQ_MSG(test, ext4_ext_pblock(&ex), + expected[i].pblk, "pblk idx %u", i); + } + + for (i = 0; i < ARRAY_SIZE(expected_freed_meta); i++) { + KUNIT_EXPECT_TRUE_MSG(test, + migrate_was_freed(ctx, + expected_freed_meta[i]), + "expected meta block %llu freed", + expected_freed_meta[i]); + } +} + +/* + * Test 4: When reading an indirect block fails midway after tmp_inode has + * already grown a depth-1 extent tree, free_ext_block() / free_ext_idx() + * frees the allocated temporary extent metadata block, leaves the original + * inode untouched, and ext4_ext_migrate() returns the error. + */ +static void test_ext_migrate_error_rollback_frees_tmp_extent_blocks(struct kunit *test) +{ + struct migrate_test_ctx *ctx = test->priv; + struct inode *inode; + ext4_fsblk_t expected_leaf_blk = ctx->next_alloc_pblk; + + inode = migrate_make_test_inode(test, 16, S_IFREG | 0644); + inode->i_blocks = 12; + + /* + * 6 discontiguous direct blocks flush 5 extents into tmp_inode + * (the 6th stays buffered in lb), growing tmp_inode past eh_max=4 + * to a depth-1 extent leaf block before EXT4_IND_BLOCK is read. + */ + EXT4_I(inode)->i_data[0] = cpu_to_le32(100); + EXT4_I(inode)->i_data[2] = cpu_to_le32(110); + EXT4_I(inode)->i_data[4] = cpu_to_le32(120); + EXT4_I(inode)->i_data[6] = cpu_to_le32(130); + EXT4_I(inode)->i_data[8] = cpu_to_le32(140); + EXT4_I(inode)->i_data[10] = cpu_to_le32(150); + /* Unreadable IND block beyond device_blocks triggers -EIO rollback */ + EXT4_I(inode)->i_data[EXT4_IND_BLOCK] = + cpu_to_le32(MIGRATE_TEST_TOTAL_BLKS + 50); + + /* The read error is reported to the caller, not swallowed */ + KUNIT_EXPECT_EQ(test, ext4_ext_migrate(inode), -EIO); + + /* Temporary extent leaf block allocated during build must be freed */ + KUNIT_EXPECT_TRUE(test, migrate_was_freed(ctx, expected_leaf_blk)); + /* Original inode remains indirect with intact direct pointers */ + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[0]), 100U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[8]), 140U); +} + +/* + * Test 5: ext4_ext_swap_inode_data() returns -EAGAIN without modifying the + * target inode or freeing its indirect blocks if EXT4_STATE_EXT_MIGRATE was + * cleared by a concurrent allocation. + */ +static void test_ext_swap_inode_data_detects_concurrent_allocation(struct kunit *test) +{ + struct migrate_test_ctx *ctx = test->priv; + struct inode *inode, *tmp_inode; + handle_t *handle; + int ret; + + inode = migrate_make_test_inode(test, 17, S_IFREG | 0644); + EXT4_I(inode)->i_data[0] = cpu_to_le32(210); + EXT4_I(inode)->i_data[EXT4_IND_BLOCK] = cpu_to_le32(550); + + tmp_inode = migrate_make_test_inode(test, 18, S_IFREG | 0644); + handle = ext4_journal_start(inode, EXT4_HT_MIGRATE, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ext4_ext_tree_init(handle, tmp_inode); + + /* EXT4_STATE_EXT_MIGRATE intentionally NOT set on inode */ + ret = ext4_ext_swap_inode_data_test(handle, inode, tmp_inode); + ext4_journal_stop(handle); + + KUNIT_EXPECT_EQ(test, ret, -EAGAIN); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[0]), 210U); + KUNIT_EXPECT_EQ(test, + le32_to_cpu(EXT4_I(inode)->i_data[EXT4_IND_BLOCK]), + 550U); + KUNIT_EXPECT_FALSE(test, migrate_was_freed(ctx, 550)); +} + +/* + * Test 6: ext4_ind_migrate() converts an empty 0-extent file and a 1-extent + * file with a leading sparse hole ([3..7] -> 200..204) to direct block mapping. + */ +static void test_ind_migrate_empty_and_single_direct_extent(struct kunit *test) +{ + struct inode *inode; + struct ext4_extent_header *eh; + struct ext4_extent *ex; + handle_t *handle; + unsigned int i; + + /* 1. Empty 0-extent file */ + inode = migrate_make_test_inode(test, 19, S_IFREG | 0644); + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + handle = ext4_journal_start(inode, EXT4_HT_MIGRATE, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ext4_ext_tree_init(handle, inode); + ext4_journal_stop(handle); + + KUNIT_EXPECT_EQ(test, ext4_ind_migrate(inode), 0); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + for (i = 0; i < EXT4_N_BLOCKS; i++) + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[i]), 0U); + + /* 2. Single extent covering logical blocks [3..7] -> physical 200..204 */ + inode = migrate_make_test_inode(test, 20, S_IFREG | 0644); + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + handle = ext4_journal_start(inode, EXT4_HT_MIGRATE, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ext4_ext_tree_init(handle, inode); + ext4_journal_stop(handle); + + eh = ext_inode_hdr(inode); + eh->eh_entries = cpu_to_le16(1); + ex = EXT_FIRST_EXTENT(eh); + ex->ee_block = cpu_to_le32(3); + ex->ee_len = cpu_to_le16(5); + ext4_ext_store_pblock(ex, 200); + + KUNIT_EXPECT_EQ(test, ext4_ind_migrate(inode), 0); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + for (i = 0; i < 3; i++) + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[i]), 0U); + for (i = 3; i <= 7; i++) + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[i]), + 200U + (i - 3)); + for (i = 8; i < EXT4_N_BLOCKS; i++) + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[i]), 0U); +} + +/* + * Test 7: ext4_ind_migrate() rejects non-extents, bigalloc, multi-extent, + * non-zero depth, >= EXT4_NDIR_BLOCKS logical range, and >32-bit filesystems. + */ +static void test_ind_migrate_rejections(struct kunit *test) +{ + struct migrate_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct inode *inode; + struct ext4_extent_header *eh; + struct ext4_extent *ex; + handle_t *handle; + + inode = migrate_make_test_inode(test, 21, S_IFREG | 0644); + + /* 1. Inode without EXT4_INODE_EXTENTS -> -EINVAL */ + KUNIT_EXPECT_EQ(test, ext4_ind_migrate(inode), -EINVAL); + + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + handle = ext4_journal_start(inode, EXT4_HT_MIGRATE, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(handle)); + ext4_ext_tree_init(handle, inode); + ext4_journal_stop(handle); + + /* 2. Filesystem without extents feature -> -EINVAL */ + ext4_clear_feature_extents(sb); + KUNIT_EXPECT_EQ(test, ext4_ind_migrate(inode), -EINVAL); + ext4_set_feature_extents(sb); + + /* 3. bigalloc enabled -> -EOPNOTSUPP */ + ext4_set_feature_bigalloc(sb); + KUNIT_EXPECT_EQ(test, ext4_ind_migrate(inode), -EOPNOTSUPP); + ext4_clear_feature_bigalloc(sb); + + /* 4. Extent reaching EXT4_NDIR_BLOCKS (end = 10 + 3 - 1 = 12) */ + eh = ext_inode_hdr(inode); + eh->eh_entries = cpu_to_le16(1); + ex = EXT_FIRST_EXTENT(eh); + ex[0].ee_block = cpu_to_le32(10); + ex[0].ee_len = cpu_to_le16(3); + ext4_ext_store_pblock(&ex[0], 200); + KUNIT_EXPECT_EQ(test, ext4_ind_migrate(inode), -EOPNOTSUPP); + KUNIT_EXPECT_TRUE(test, + ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + + /* 5. More than 1 extent (eh_entries == 2) -> -EOPNOTSUPP */ + ex[0].ee_block = cpu_to_le32(0); + ex[0].ee_len = cpu_to_le16(2); + ext4_ext_store_pblock(&ex[0], 200); + ex[1].ee_block = cpu_to_le32(4); + ex[1].ee_len = cpu_to_le16(2); + ext4_ext_store_pblock(&ex[1], 210); + eh->eh_entries = cpu_to_le16(2); + KUNIT_EXPECT_EQ(test, ext4_ind_migrate(inode), -EOPNOTSUPP); + + /* 6. Filesystem > EXT4_MAX_BLOCK_FILE_PHYS -> -EOPNOTSUPP */ + eh->eh_entries = cpu_to_le16(1); + ext4_blocks_count_set(ctx->es, (ext4_fsblk_t)EXT4_MAX_BLOCK_FILE_PHYS + + 100ULL); + KUNIT_EXPECT_EQ(test, ext4_ind_migrate(inode), -EOPNOTSUPP); + ext4_blocks_count_set(ctx->es, MIGRATE_TEST_TOTAL_BLKS); +} + +/* + * Test 8: ext4_ext_migrate() splits a physically and logically contiguous + * run longer than EXT_INIT_MAX_LEN into multiple initialized extents rather + * than encoding the raw length into ee_len, which would turn the extent + * into an unwritten one (or wrap ee_len) and lose the file data. + */ +static void test_ext_migrate_caps_long_run_at_init_max_len(struct kunit *test) +{ + struct migrate_test_ctx *ctx = test->priv; + const unsigned int per_blk = MIGRATE_TEST_BLK_SIZE / sizeof(__le32); + const unsigned int nr_ind = 128; + const ext4_fsblk_t data_pblk = 2000; + const ext4_fsblk_t ind_pblk = 600, dind_pblk = 700; + const ext4_lblk_t len = EXT4_NDIR_BLOCKS + per_blk + nr_ind * per_blk; + const int max_len = EXT_INIT_MAX_LEN; + struct ext4_extent_header *eh; + struct ext4_extent *ex; + struct buffer_head *bh; + struct inode *inode; + ext4_fsblk_t pblk = data_pblk; + unsigned int i, j; + + /* 12 + 256 + 128 * 256 = 33036 blocks > EXT_INIT_MAX_LEN */ + KUNIT_ASSERT_GT(test, len, (ext4_lblk_t)max_len); + ext4_blocks_count_set(ctx->es, data_pblk + len + 1024); + + inode = migrate_make_test_inode(test, 22, S_IFREG | 0644); + i_size_write(inode, (loff_t)len * MIGRATE_TEST_BLK_SIZE); + + for (i = 0; i < EXT4_NDIR_BLOCKS; i++) + EXT4_I(inode)->i_data[i] = cpu_to_le32(pblk++); + + EXT4_I(inode)->i_data[EXT4_IND_BLOCK] = cpu_to_le32(ind_pblk); + bh = migrate_get_or_create_bh(ctx, ind_pblk); + KUNIT_ASSERT_NOT_NULL(test, bh); + for (j = 0; j < per_blk; j++) + ((__le32 *)bh->b_data)[j] = cpu_to_le32(pblk++); + brelse(bh); + + EXT4_I(inode)->i_data[EXT4_DIND_BLOCK] = cpu_to_le32(dind_pblk); + bh = migrate_get_or_create_bh(ctx, dind_pblk); + KUNIT_ASSERT_NOT_NULL(test, bh); + for (i = 0; i < nr_ind; i++) + ((__le32 *)bh->b_data)[i] = cpu_to_le32(dind_pblk + 1 + i); + brelse(bh); + + for (i = 0; i < nr_ind; i++) { + bh = migrate_get_or_create_bh(ctx, dind_pblk + 1 + i); + KUNIT_ASSERT_NOT_NULL(test, bh); + for (j = 0; j < per_blk; j++) + ((__le32 *)bh->b_data)[j] = cpu_to_le32(pblk++); + brelse(bh); + } + inode->i_blocks = (blkcnt_t)(len + 2 + nr_ind) * + (MIGRATE_TEST_BLK_SIZE >> 9); + + KUNIT_EXPECT_EQ(test, ext4_ext_migrate(inode), 0); + KUNIT_EXPECT_TRUE(test, + ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + eh = ext_inode_hdr(inode); + if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS) || + !eh->eh_entries) + return; + + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_depth), 0U); + ex = EXT_FIRST_EXTENT(eh); + + /* Extent 0: lblk [0..32767] -> data_pblk, initialized */ + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[0].ee_block), 0U); + KUNIT_EXPECT_FALSE(test, ext4_ext_is_unwritten(&ex[0])); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[0]), max_len); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex[0]), data_pblk); + + /* Extent 1: remainder of the run, initialized */ + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 2U); + if (le16_to_cpu(eh->eh_entries) < 2) + return; + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[1].ee_block), (u32)max_len); + KUNIT_EXPECT_FALSE(test, ext4_ext_is_unwritten(&ex[1])); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[1]), + (int)len - max_len); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex[1]), data_pblk + max_len); + + /* Indirect metadata blocks were released */ + KUNIT_EXPECT_TRUE(test, migrate_was_freed(ctx, ind_pblk)); + KUNIT_EXPECT_TRUE(test, migrate_was_freed(ctx, dind_pblk + 1)); +} + +/* + * Test 9: A transaction restart while inserting an extent into tmp_inode + * (ext4_datasem_ensure_credits() returning 1) is not an error; migration + * still completes and builds every extent. + */ +static void test_ext_migrate_survives_handle_restart(struct kunit *test) +{ + struct migrate_test_ctx *ctx = test->priv; + struct ext4_extent_header *eh; + struct ext4_extent *ex; + struct inode *inode; + + kunit_activate_static_stub(test, ext4_datasem_ensure_credits, + migrate_datasem_restart_stub); + + inode = migrate_make_test_inode(test, 23, S_IFREG | 0644); + i_size_write(inode, 12 * MIGRATE_TEST_BLK_SIZE); + inode->i_blocks = 4 * (MIGRATE_TEST_BLK_SIZE >> 9); + + /* Three discontiguous runs: [0..1] -> 100, [4] -> 200, [8] -> 300 */ + EXT4_I(inode)->i_data[0] = cpu_to_le32(100); + EXT4_I(inode)->i_data[1] = cpu_to_le32(101); + EXT4_I(inode)->i_data[4] = cpu_to_le32(200); + EXT4_I(inode)->i_data[8] = cpu_to_le32(300); + + KUNIT_EXPECT_EQ(test, ext4_ext_migrate(inode), 0); + KUNIT_EXPECT_EQ(test, ctx->datasem_restarts, 3U); + KUNIT_EXPECT_TRUE(test, + ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) + return; + + eh = ext_inode_hdr(inode); + KUNIT_EXPECT_EQ(test, le16_to_cpu(eh->eh_entries), 3U); + if (le16_to_cpu(eh->eh_entries) != 3) + return; + ex = EXT_FIRST_EXTENT(eh); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[0].ee_block), 0U); + KUNIT_EXPECT_EQ(test, ext4_ext_get_actual_len(&ex[0]), 2); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex[0]), 100ULL); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[1].ee_block), 4U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex[1]), 200ULL); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ex[2].ee_block), 8U); + KUNIT_EXPECT_EQ(test, ext4_ext_pblock(&ex[2]), 300ULL); +} + +/* + * Test 10: If a concurrent block allocation invalidates the migration, + * ext4_ext_migrate() reports -EAGAIN instead of claiming success, and the + * inode keeps its indirect block map. + */ +static void test_ext_migrate_reports_concurrent_allocation(struct kunit *test) +{ + struct migrate_test_ctx *ctx = test->priv; + struct inode *inode; + + kunit_activate_static_stub(test, ext4_datasem_ensure_credits, + migrate_datasem_race_stub); + + inode = migrate_make_test_inode(test, 24, S_IFREG | 0644); + i_size_write(inode, 4 * MIGRATE_TEST_BLK_SIZE); + inode->i_blocks = 2 * (MIGRATE_TEST_BLK_SIZE >> 9); + EXT4_I(inode)->i_data[0] = cpu_to_le32(100); + EXT4_I(inode)->i_data[3] = cpu_to_le32(200); + ctx->race_inode = inode; + + KUNIT_EXPECT_EQ(test, ext4_ext_migrate(inode), -EAGAIN); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[0]), 100U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(inode)->i_data[3]), 200U); + + ctx->race_inode = NULL; +} + +/* + * Test 11: Verify ext4_ext_migrate() clears tmp_inode's in-memory extent + * header, i_size, i_blocks, and csum_seed even when ext4_journal_ensure_credits() + * fails after swap or when ext4_mark_inode_dirty() fails inside + * ext4_ext_swap_inode_data(), so neither free_ext_block() nor + * ext4_evict_inode() frees the migrated inode's live blocks. + */ +static void test_ext_migrate_credit_or_dirty_failure_keeps_live_blocks( + struct kunit *test) +{ + struct migrate_test_ctx *ctx = test->priv; + struct inode *inode; + ext4_fsblk_t ext_idx_pblk; + unsigned int i; + + /* + * 1. Six discontiguous direct blocks produce a depth-1 extent tree + * (exceeding the 4 inline root extents). Failing + * __ext4_journal_ensure_credits() with -EROFS after swapping must + * still leave tmp_inode empty when evicted. + */ + kunit_activate_static_stub(test, __ext4_journal_ensure_credits, + migrate_ensure_credits_stub); + inode = migrate_make_test_inode(test, 25, S_IFREG | 0644); + i_size_write(inode, 12 * MIGRATE_TEST_BLK_SIZE); + inode->i_blocks = 6 * (MIGRATE_TEST_BLK_SIZE >> 9); + for (i = 0; i < 6; i++) + EXT4_I(inode)->i_data[i * 2] = cpu_to_le32(100 + i * 10); + + ctx->evict_tmp_seen = false; + ctx->ensure_credits_after_swap_inode = inode; + ctx->ensure_credits_err = -EROFS; + KUNIT_EXPECT_EQ(test, ext4_ext_migrate(inode), -EROFS); + ctx->ensure_credits_err = 0; + ctx->ensure_credits_after_swap_inode = NULL; + + KUNIT_EXPECT_TRUE(test, + ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)); + KUNIT_EXPECT_EQ(test, le16_to_cpu(ext_inode_hdr(inode)->eh_depth), 1U); + KUNIT_ASSERT_TRUE(test, ctx->evict_tmp_seen); + KUNIT_EXPECT_EQ(test, ctx->evict_tmp_isize, 0LL); + KUNIT_EXPECT_EQ(test, ctx->evict_tmp_iblocks, (blkcnt_t)0); + KUNIT_EXPECT_EQ(test, ctx->evict_tmp_eh_entries, 0U); + KUNIT_EXPECT_EQ(test, ctx->evict_tmp_eh_depth, 0U); + KUNIT_EXPECT_EQ(test, ctx->evict_tmp_csum_seed, 0xabcdef01U); + + /* + * 2. Failing ext4_mark_inode_dirty() inside ext4_ext_swap_inode_data() + * after ownership moved to inode must NOT free inode's new extent index + * block via free_ext_block(handle, tmp_inode). + */ + inode = migrate_make_test_inode(test, 26, S_IFREG | 0644); + i_size_write(inode, 12 * MIGRATE_TEST_BLK_SIZE); + inode->i_blocks = 6 * (MIGRATE_TEST_BLK_SIZE >> 9); + for (i = 0; i < 6; i++) + EXT4_I(inode)->i_data[i * 2] = cpu_to_le32(200 + i * 10); + + ext_idx_pblk = ctx->next_alloc_pblk; + ctx->freed_cnt = 0; + ctx->evict_tmp_seen = false; + ctx->mark_dirty_err = -EIO; + ctx->mark_dirty_err_inode = inode; + KUNIT_EXPECT_EQ(test, ext4_ext_migrate(inode), -EIO); + ctx->mark_dirty_err = 0; + ctx->mark_dirty_err_inode = NULL; + + KUNIT_EXPECT_FALSE(test, migrate_was_freed(ctx, ext_idx_pblk)); + KUNIT_ASSERT_TRUE(test, ctx->evict_tmp_seen); + KUNIT_EXPECT_EQ(test, ctx->evict_tmp_isize, 0LL); + KUNIT_EXPECT_EQ(test, ctx->evict_tmp_iblocks, (blkcnt_t)0); + KUNIT_EXPECT_EQ(test, ctx->evict_tmp_eh_entries, 0U); + KUNIT_EXPECT_EQ(test, ctx->evict_tmp_eh_depth, 0U); + KUNIT_EXPECT_EQ(test, ctx->evict_tmp_csum_seed, 0xabcdef01U); +} + +static struct kunit_case ext4_migrate_test_cases[] = { + KUNIT_CASE(test_ext_migrate_precondition_checks_and_fast_symlink), + KUNIT_CASE(test_ext_migrate_direct_and_ind_coalescing_and_holes), + KUNIT_CASE(test_ext_migrate_dind_tind_and_multilevel_tree), + KUNIT_CASE(test_ext_migrate_error_rollback_frees_tmp_extent_blocks), + KUNIT_CASE(test_ext_swap_inode_data_detects_concurrent_allocation), + KUNIT_CASE(test_ind_migrate_empty_and_single_direct_extent), + KUNIT_CASE(test_ind_migrate_rejections), + KUNIT_CASE(test_ext_migrate_caps_long_run_at_init_max_len), + KUNIT_CASE(test_ext_migrate_survives_handle_restart), + KUNIT_CASE(test_ext_migrate_reports_concurrent_allocation), + KUNIT_CASE(test_ext_migrate_credit_or_dirty_failure_keeps_live_blocks), + {} +}; + +static struct kunit_suite ext4_migrate_test_suite = { + .name = "ext4_migrate_test", + .init = migrate_test_init, + .test_cases = ext4_migrate_test_cases, +}; + +kunit_test_suites(&ext4_migrate_test_suite); + +MODULE_DESCRIPTION("KUnit tests for ext4 indirect/extent inode migration"); +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/migrate.c b/fs/ext4/migrate.c index 09931d3ba2c6a8..807bd30341e689 100644 --- a/fs/ext4/migrate.c +++ b/fs/ext4/migrate.c @@ -14,7 +14,7 @@ * represented by a single extent */ struct migrate_struct { - ext4_lblk_t first_block, last_block, curr_block; + u64 first_block, last_block, curr_block; ext4_fsblk_t first_pblock, last_pblock; }; @@ -53,8 +53,7 @@ static int finish_range(handle_t *handle, struct inode *inode, if (retval < 0) goto err_out; path = ext4_ext_insert_extent(handle, inode, path, &newext, 0); - if (IS_ERR(path)) - retval = PTR_ERR(path); + retval = PTR_ERR_OR_ZERO(path); err_out: up_write((&EXT4_I(inode)->i_data_sem)); ext4_free_ext_path(path); @@ -66,12 +65,17 @@ static int update_extent_range(handle_t *handle, struct inode *inode, ext4_fsblk_t pblock, struct migrate_struct *lb) { int retval; + + if (lb->curr_block >= EXT_MAX_BLOCKS) + return -EOPNOTSUPP; + /* * See if we can add on to the existing range (if it exists) */ if (lb->first_pblock && (lb->last_pblock+1 == pblock) && - (lb->last_block+1 == lb->curr_block)) { + (lb->last_block+1 == lb->curr_block) && + (lb->last_block - lb->first_block + 1 < EXT_INIT_MAX_LEN)) { lb->last_pblock = pblock; lb->last_block = lb->curr_block; lb->curr_block++; @@ -322,6 +326,12 @@ static int ext4_ext_swap_inode_data(handle_t *handle, struct inode *inode, */ ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); memcpy(ei->i_data, tmp_ei->i_data, sizeof(ei->i_data)); + /* + * The extent tree belongs to the inode now. Make tmp_inode's extent + * tree empty, so that cleaning up tmp_inode can't free the tree + * blocks, if we fail to finish the migration. + */ + ext4_ext_init_root(tmp_inode); /* * Update i_blocks with the new blocks that got @@ -331,10 +341,13 @@ static int ext4_ext_swap_inode_data(handle_t *handle, struct inode *inode, * While converting to extents we need not * update the original inode i_blocks for extent blocks * via quota APIs. The quota update happened via tmp_inode already. + * Clear tmp_inode i_blocks to avoid truncating original data blocks + * in case we fail to finish the migration. */ spin_lock(&inode->i_lock); inode->i_blocks += tmp_inode->i_blocks; spin_unlock(&inode->i_lock); + tmp_inode->i_blocks = 0; up_write(&EXT4_I(inode)->i_data_sem); /* @@ -410,7 +423,7 @@ static int free_ext_block(handle_t *handle, struct inode *inode) int ext4_ext_migrate(struct inode *inode) { handle_t *handle; - int retval = 0, i; + int retval = 0, err, i; __le32 *i_data; struct ext4_inode_info *ei; struct inode *tmp_inode = NULL; @@ -558,18 +571,16 @@ int ext4_ext_migrate(struct inode *inode) free_ext_block(handle, tmp_inode); else { retval = ext4_ext_swap_inode_data(handle, inode, tmp_inode); - if (retval) + if (retval && !ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) /* * if we fail to swap inode data free the extent - * details of the tmp inode + * details of the tmp inode. If the tree was already + * moved to the original inode, the tmp_inode has an + * empty tree and there is nothing to free. */ free_ext_block(handle, tmp_inode); } - /* We mark the tmp_inode dirty via ext4_ext_tree_init. */ - retval = ext4_journal_ensure_credits(handle, 1, 0); - if (retval < 0) - goto out_stop; /* * Mark the tmp_inode as of size zero */ @@ -586,6 +597,13 @@ int ext4_ext_migrate(struct inode *inode) tmp_inode->i_blocks = 0; EXT4_I(tmp_inode)->i_csum_seed = tmp_csum_seed; + /* We mark the tmp_inode dirty via ext4_ext_tree_init. */ + err = ext4_journal_ensure_credits(handle, 1, 0); + if (err < 0) { + if (!retval) + retval = err; + goto out_stop; + } /* Reset the extent details */ ext4_ext_tree_init(handle, tmp_inode); out_stop: @@ -597,6 +615,7 @@ int ext4_ext_migrate(struct inode *inode) iput(tmp_inode); return retval; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_migrate); /* * Migrate a simple extent-based inode to use the i_blocks[] array @@ -685,3 +704,13 @@ int ext4_ind_migrate(struct inode *inode) ext4_writepages_up_write(inode->i_sb, alloc_ctx); return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ind_migrate); + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +int ext4_ext_swap_inode_data_test(handle_t *handle, struct inode *inode, + struct inode *tmp_inode) +{ + return ext4_ext_swap_inode_data(handle, inode, tmp_inode); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_swap_inode_data_test); +#endif diff --git a/fs/ext4/mmp-test.c b/fs/ext4/mmp-test.c new file mode 100644 index 00000000000000..e8496e8940f5ed --- /dev/null +++ b/fs/ext4/mmp-test.c @@ -0,0 +1,661 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for fs/ext4/mmp.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" + +#define MMP_TEST_BLK_SIZE 4096U +#define MMP_TEST_BLK_BITS 12U +#define MMP_TEST_FIRST_DATA_BLK 1ULL +#define MMP_TEST_TOTAL_BLKS 1024ULL +#define MMP_TEST_VALID_BLK 10ULL +#define MMP_MAX_WAITS 8U + +struct mmp_test_ctx { + struct super_block *sb; + struct ext4_sb_info sbi; + struct ext4_super_block *es; + struct gendisk bdev_disk; + struct block_device bdev; + struct request_queue bdev_queue; + struct address_space bdev_mapping; + struct buffer_head sbh; + u8 sbh_data[MMP_TEST_BLK_SIZE]; + + /* Simulated on-disk MMP block and in-memory buffer_head */ + u8 disk_buf[MMP_TEST_BLK_SIZE]; + struct buffer_head mmp_bh; + u8 bh_buf[MMP_TEST_BLK_SIZE]; + + /* Deterministic I/O, sleep, and kthread fault injection */ + int load_nomem; + int load_err_on_call; + unsigned int load_calls; + ext4_fsblk_t last_load_blk; + + int write_err_on_call; + unsigned int write_calls; + + unsigned int wait_calls; + long wait_timeouts[MMP_MAX_WAITS]; + long wait_ret_on_call; + unsigned int wait_ret_target_call; + unsigned int mutate_seq_on_wait_call; + u32 mutated_seq; + + int run_thread_err; + unsigned int run_thread_calls; +}; + +static struct kunit *active_mmp_test; + +static void mmp_noop_work(struct work_struct *work) +{ +} + +static void mmp_noop_timer(struct timer_list *t) +{ +} + +static const struct super_operations mmp_test_sops = {}; + +static int mmp_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static int mmp_set_super(struct super_block *sb, struct fs_context *fc) +{ + return set_anon_super_fc(sb, fc); +} + +static struct file_system_type mmp_test_fs_type = { + .name = "ext4_mmp_test", + .init_fs_context = mmp_init_fs_context, + .kill_sb = kill_anon_super, +}; + +static int mmp_dummy_kthread_fn(void *data) +{ + while (!kthread_should_stop()) { + set_current_state(TASK_INTERRUPTIBLE); + if (!kthread_should_stop()) + schedule(); + } + __set_current_state(TASK_RUNNING); + return 0; +} + +static int mmp_submit_write_stub(struct buffer_head *bh) +{ + struct kunit *test = active_mmp_test; + struct mmp_test_ctx *ctx; + + if (!test) + return -EIO; + ctx = test->priv; + ctx->write_calls++; + if (ctx->write_err_on_call && + ctx->write_calls == (unsigned int)ctx->write_err_on_call) { + clear_buffer_uptodate(bh); + return -EIO; + } + + memcpy(ctx->disk_buf, bh->b_data, MMP_TEST_BLK_SIZE); + set_buffer_uptodate(bh); + return 0; +} + +static int mmp_load_bh_stub(struct super_block *sb, struct buffer_head **bh, + ext4_fsblk_t mmp_block) +{ + struct kunit *test = active_mmp_test; + struct mmp_test_ctx *ctx; + + if (!test) + return -EIO; + ctx = test->priv; + ctx->load_calls++; + ctx->last_load_blk = mmp_block; + + if (ctx->load_nomem && !*bh) + return -ENOMEM; + + if (!*bh) { + *bh = &ctx->mmp_bh; + get_bh(*bh); + } + + if (ctx->load_err_on_call && + ctx->load_calls == (unsigned int)ctx->load_err_on_call) + return -EIO; + + memcpy((*bh)->b_data, ctx->disk_buf, MMP_TEST_BLK_SIZE); + set_buffer_uptodate(*bh); + return 0; +} + +static long mmp_wait_timeout_stub(long timeout) +{ + struct kunit *test = active_mmp_test; + struct mmp_test_ctx *ctx; + + if (!test) + return 1; + ctx = test->priv; + if (ctx->wait_calls < MMP_MAX_WAITS) + ctx->wait_timeouts[ctx->wait_calls] = timeout; + ctx->wait_calls++; + + if (ctx->mutate_seq_on_wait_call && + ctx->wait_calls == ctx->mutate_seq_on_wait_call) { + struct mmp_struct *disk_mmp = (struct mmp_struct *)ctx->disk_buf; + + disk_mmp->mmp_seq = cpu_to_le32(ctx->mutated_seq); + strscpy(disk_mmp->mmp_nodename, "other-node", + sizeof(disk_mmp->mmp_nodename)); + ext4_mmp_csum_set_test(ctx->sb, disk_mmp); + } + + if (ctx->wait_ret_target_call && + ctx->wait_calls == ctx->wait_ret_target_call) + return ctx->wait_ret_on_call; + + return 0; +} + +static struct task_struct *mmp_run_thread_stub(struct super_block *sb, + const char *bdevname, + int bdevname_len) +{ + struct kunit *test = active_mmp_test; + struct mmp_test_ctx *ctx; + + if (!test) + return ERR_PTR(-EINVAL); + ctx = test->priv; + ctx->run_thread_calls++; + if (ctx->run_thread_err) + return ERR_PTR(ctx->run_thread_err); + + return kthread_run(mmp_dummy_kthread_fn, NULL, "kunit-mmpd"); +} + +static void mmp_init_disk_block(struct mmp_test_ctx *ctx, u32 seq, + u16 check_interval) +{ + struct mmp_struct *mmp = (struct mmp_struct *)ctx->disk_buf; + + memset(ctx->disk_buf, 0, sizeof(ctx->disk_buf)); + mmp->mmp_magic = cpu_to_le32(EXT4_MMP_MAGIC); + mmp->mmp_seq = cpu_to_le32(seq); + mmp->mmp_time = cpu_to_le64(1700000000ULL); + strscpy(mmp->mmp_nodename, "init-node", sizeof(mmp->mmp_nodename)); + strscpy(mmp->mmp_bdevname, "init-bdev", sizeof(mmp->mmp_bdevname)); + mmp->mmp_check_interval = cpu_to_le16(check_interval); + ext4_mmp_csum_set_test(ctx->sb, mmp); +} + +static void mmp_reset_counters(struct mmp_test_ctx *ctx) +{ + ctx->load_nomem = 0; + ctx->load_err_on_call = 0; + ctx->load_calls = 0; + ctx->last_load_blk = 0; + ctx->write_err_on_call = 0; + ctx->write_calls = 0; + ctx->wait_calls = 0; + memset(ctx->wait_timeouts, 0, sizeof(ctx->wait_timeouts)); + ctx->wait_ret_on_call = 0; + ctx->wait_ret_target_call = 0; + ctx->mutate_seq_on_wait_call = 0; + ctx->mutated_seq = 0; + ctx->run_thread_err = 0; + ctx->run_thread_calls = 0; +} + +static void mmp_cleanup_ctx(void *data) +{ + struct mmp_test_ctx *ctx = data; + + active_mmp_test = NULL; + + if (ctx->sbi.s_mmp_tsk) + ext4_stop_mmpd(&ctx->sbi); + ctx->sbi.s_mmp_bh = NULL; + + cancel_work_sync(&ctx->sbi.s_sb_upd_work); + timer_delete_sync(&ctx->sbi.s_err_report); + + if (ctx->sb) { + ctx->sb->s_fs_info = NULL; + deactivate_super(ctx->sb); + ctx->sb = NULL; + } + if (ctx->bdev.bd_stats) { + free_percpu(ctx->bdev.bd_stats); + ctx->bdev.bd_stats = NULL; + } +} + +static struct mmp_test_ctx *mmp_setup_ctx(struct kunit *test) +{ + struct mmp_test_ctx *ctx; + struct fs_context *fc; + struct super_block *sb; + int err; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + ctx->es = kunit_kzalloc(test, sizeof(*ctx->es), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->es); + + fc = fs_context_for_mount(&mmp_test_fs_type, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(fc)); + sb = sget_fc(fc, NULL, mmp_set_super); + put_fs_context(fc); + KUNIT_ASSERT_FALSE(test, IS_ERR(sb)); + up_write(&sb->s_umount); + ctx->sb = sb; + + INIT_WORK(&ctx->sbi.s_sb_upd_work, mmp_noop_work); + timer_setup(&ctx->sbi.s_err_report, mmp_noop_timer, 0); + + err = kunit_add_action_or_reset(test, mmp_cleanup_ctx, ctx); + KUNIT_ASSERT_EQ(test, err, 0); + + ctx->bdev.bd_stats = alloc_percpu(struct disk_stats); + KUNIT_ASSERT_TRUE(test, ctx->bdev.bd_stats != NULL); + strscpy(ctx->bdev_disk.disk_name, "mmp_bdev", + sizeof(ctx->bdev_disk.disk_name)); + ctx->bdev_disk.queue = &ctx->bdev_queue; + ctx->bdev.bd_disk = &ctx->bdev_disk; + ctx->bdev.bd_queue = &ctx->bdev_queue; + ctx->bdev.bd_mapping = &ctx->bdev_mapping; + + sb->s_bdev = &ctx->bdev; + sb->s_blocksize = MMP_TEST_BLK_SIZE; + sb->s_blocksize_bits = MMP_TEST_BLK_BITS; + sb->s_magic = EXT4_SUPER_MAGIC; + sb->s_op = &mmp_test_sops; + sb->s_fs_info = &ctx->sbi; + strscpy(sb->s_id, "ext4_mmp_kunit", sizeof(sb->s_id)); + + ctx->sbh.b_data = ctx->sbh_data; + ctx->sbh.b_size = MMP_TEST_BLK_SIZE; + ctx->sbh.b_bdev = &ctx->bdev; + atomic_set(&ctx->sbh.b_count, 2); + set_buffer_uptodate(&ctx->sbh); + clear_buffer_mapped(&ctx->sbh); + + ctx->mmp_bh.b_data = ctx->bh_buf; + ctx->mmp_bh.b_size = MMP_TEST_BLK_SIZE; + ctx->mmp_bh.b_blocknr = MMP_TEST_VALID_BLK; + ctx->mmp_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->mmp_bh.b_count, 2); + set_buffer_mapped(&ctx->mmp_bh); + + ctx->es->s_magic = cpu_to_le16(EXT4_SUPER_MAGIC); + ctx->es->s_first_data_block = cpu_to_le32(MMP_TEST_FIRST_DATA_BLK); + ctx->es->s_mmp_block = cpu_to_le64(MMP_TEST_VALID_BLK); + ctx->es->s_mmp_update_interval = cpu_to_le16(EXT4_MMP_MIN_CHECK_INTERVAL); + ctx->es->s_feature_incompat = cpu_to_le32(EXT4_FEATURE_INCOMPAT_MMP); + ctx->es->s_feature_ro_compat = + cpu_to_le32(EXT4_FEATURE_RO_COMPAT_METADATA_CSUM); + ext4_blocks_count_set(ctx->es, MMP_TEST_TOTAL_BLKS); + + ctx->sbi.s_sb = sb; + ctx->sbi.s_es = ctx->es; + ctx->sbi.s_sbh = &ctx->sbh; + ctx->sbi.s_csum_seed = 0x9abcdef0U; + set_opt(sb, ERRORS_CONT); + spin_lock_init(&ctx->sbi.s_bdev_wb_lock); + spin_lock_init(&ctx->sbi.s_error_lock); + ratelimit_state_init(&ctx->sbi.s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, + DEFAULT_RATELIMIT_BURST); + ratelimit_state_init(&ctx->sbi.s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, + DEFAULT_RATELIMIT_BURST); + ratelimit_state_init(&ctx->sbi.s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, + DEFAULT_RATELIMIT_BURST); + + test->priv = ctx; + active_mmp_test = test; + + kunit_activate_static_stub(test, ext4_mmp_submit_write, + mmp_submit_write_stub); + kunit_activate_static_stub(test, ext4_mmp_load_bh, + mmp_load_bh_stub); + kunit_activate_static_stub(test, ext4_mmp_wait_timeout, + mmp_wait_timeout_stub); + kunit_activate_static_stub(test, ext4_mmp_run_thread, + mmp_run_thread_stub); + + return ctx; +} + +static void test_mmp_csum_set_and_verify(struct kunit *test) +{ + struct mmp_test_ctx *ctx = mmp_setup_ctx(test); + struct mmp_struct *mmp; + __le32 orig_csum; + + mmp = kunit_kzalloc(test, sizeof(*mmp), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, mmp); + + mmp->mmp_magic = cpu_to_le32(EXT4_MMP_MAGIC); + mmp->mmp_seq = cpu_to_le32(EXT4_MMP_SEQ_CLEAN); + strscpy(mmp->mmp_nodename, "node-a", sizeof(mmp->mmp_nodename)); + + /* Without METADATA_CSUM, set is a no-op and verify always returns 1 */ + ext4_clear_feature_metadata_csum(ctx->sb); + mmp->mmp_checksum = cpu_to_le32(0xdeadbeefU); + ext4_mmp_csum_set_test(ctx->sb, mmp); + KUNIT_EXPECT_EQ(test, le32_to_cpu(mmp->mmp_checksum), 0xdeadbeefU); + KUNIT_EXPECT_EQ(test, ext4_mmp_csum_verify_test(ctx->sb, mmp), 1); + + /* With METADATA_CSUM, set computes CRC32C and verify detects tampering */ + ext4_set_feature_metadata_csum(ctx->sb); + mmp->mmp_checksum = 0; + ext4_mmp_csum_set_test(ctx->sb, mmp); + orig_csum = mmp->mmp_checksum; + KUNIT_EXPECT_NE(test, le32_to_cpu(orig_csum), 0U); + KUNIT_EXPECT_EQ(test, ext4_mmp_csum_verify_test(ctx->sb, mmp), 1); + + /* Flipping payload field or csum seed invalidates verification */ + mmp->mmp_seq = cpu_to_le32(7); + KUNIT_EXPECT_EQ(test, ext4_mmp_csum_verify_test(ctx->sb, mmp), 0); + mmp->mmp_seq = cpu_to_le32(EXT4_MMP_SEQ_CLEAN); + KUNIT_EXPECT_EQ(test, ext4_mmp_csum_verify_test(ctx->sb, mmp), 1); + + ctx->sbi.s_csum_seed ^= 1U; + KUNIT_EXPECT_EQ(test, ext4_mmp_csum_verify_test(ctx->sb, mmp), 0); +} + +static void test_read_and_write_mmp_block(struct kunit *test) +{ + struct mmp_test_ctx *ctx = mmp_setup_ctx(test); + struct buffer_head *bh = NULL; + struct mmp_struct *mmp; + int base_ref; + int ret; + + /* Write populates checksum and persists block into disk_buf */ + mmp = (struct mmp_struct *)ctx->mmp_bh.b_data; + memset(ctx->mmp_bh.b_data, 0, MMP_TEST_BLK_SIZE); + mmp->mmp_magic = cpu_to_le32(EXT4_MMP_MAGIC); + mmp->mmp_seq = cpu_to_le32(19); + ret = ext4_write_mmp_block_test(ctx->sb, &ctx->mmp_bh); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ctx->write_calls, 1U); + KUNIT_EXPECT_EQ(test, + ext4_mmp_csum_verify_test(ctx->sb, + (struct mmp_struct *)ctx->disk_buf), 1); + + /* Simulated write I/O error returns -EIO */ + ctx->write_err_on_call = 2; + KUNIT_EXPECT_EQ(test, ext4_write_mmp_block_test(ctx->sb, &ctx->mmp_bh), + -EIO); + ctx->write_err_on_call = 0; + + /* Valid read allocates/populates bh and verifies magic + checksum */ + base_ref = atomic_read(&ctx->mmp_bh.b_count); + ret = ext4_read_mmp_block_test(ctx->sb, &bh, MMP_TEST_VALID_BLK); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_ASSERT_PTR_EQ(test, bh, &ctx->mmp_bh); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->mmp_bh.b_count), base_ref + 1); + + /* Re-reading with existing bh refreshes contents without leaking ref */ + ((struct mmp_struct *)ctx->disk_buf)->mmp_seq = cpu_to_le32(23); + ext4_mmp_csum_set_test(ctx->sb, (struct mmp_struct *)ctx->disk_buf); + ret = ext4_read_mmp_block_test(ctx->sb, &bh, MMP_TEST_VALID_BLK); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, + le32_to_cpu(((struct mmp_struct *)bh->b_data)->mmp_seq), + 23U); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->mmp_bh.b_count), base_ref + 1); + brelse(bh); + bh = NULL; + + /* -ENOMEM when bh allocation fails */ + ctx->load_nomem = 1; + KUNIT_EXPECT_EQ(test, + ext4_read_mmp_block_test(ctx->sb, &bh, + MMP_TEST_VALID_BLK), + -ENOMEM); + KUNIT_EXPECT_NULL(test, bh); + ctx->load_nomem = 0; + + /* -EIO read failure releases bh and resets *bh to NULL */ + mmp_reset_counters(ctx); + ctx->load_err_on_call = 1; + KUNIT_EXPECT_EQ(test, + ext4_read_mmp_block_test(ctx->sb, &bh, + MMP_TEST_VALID_BLK), + -EIO); + KUNIT_EXPECT_NULL(test, bh); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->mmp_bh.b_count), base_ref); + + /* Bad magic returns -EFSCORRUPTED and cleans up bh */ + mmp_reset_counters(ctx); + ((struct mmp_struct *)ctx->disk_buf)->mmp_magic = cpu_to_le32(0x1234U); + KUNIT_EXPECT_EQ(test, + ext4_read_mmp_block_test(ctx->sb, &bh, + MMP_TEST_VALID_BLK), + -EFSCORRUPTED); + KUNIT_EXPECT_NULL(test, bh); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->mmp_bh.b_count), base_ref); + + /* Bad checksum returns -EFSBADCRC and cleans up bh */ + mmp_init_disk_block(ctx, EXT4_MMP_SEQ_CLEAN, 5); + ((struct mmp_struct *)ctx->disk_buf)->mmp_checksum ^= cpu_to_le32(1U); + KUNIT_EXPECT_EQ(test, + ext4_read_mmp_block_test(ctx->sb, &bh, + MMP_TEST_VALID_BLK), + -EFSBADCRC); + KUNIT_EXPECT_NULL(test, bh); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->mmp_bh.b_count), base_ref); +} + +static void test_mmp_invalid_block_and_io_errors(struct kunit *test) +{ + struct mmp_test_ctx *ctx = mmp_setup_ctx(test); + + /* Block below s_first_data_block (1) or >= blocks_count (1024) */ + KUNIT_EXPECT_EQ(test, ext4_multi_mount_protect(ctx->sb, 0), -EINVAL); + KUNIT_EXPECT_EQ(test, + ext4_multi_mount_protect(ctx->sb, MMP_TEST_TOTAL_BLKS), + -EINVAL); + KUNIT_EXPECT_EQ(test, ctx->load_calls, 0U); + + /* Initial read failure propagates error */ + mmp_init_disk_block(ctx, EXT4_MMP_SEQ_CLEAN, 5); + mmp_reset_counters(ctx); + ctx->load_err_on_call = 1; + KUNIT_EXPECT_EQ(test, + ext4_multi_mount_protect(ctx->sb, MMP_TEST_VALID_BLK), + -EIO); + + /* Write failure when claiming MMP block */ + mmp_reset_counters(ctx); + ctx->write_err_on_call = 1; + KUNIT_EXPECT_EQ(test, + ext4_multi_mount_protect(ctx->sb, MMP_TEST_VALID_BLK), + -EIO); + + /* Post-write verification read failure */ + mmp_init_disk_block(ctx, EXT4_MMP_SEQ_CLEAN, 5); + mmp_reset_counters(ctx); + ctx->load_err_on_call = 2; + KUNIT_EXPECT_EQ(test, + ext4_multi_mount_protect(ctx->sb, MMP_TEST_VALID_BLK), + -EIO); +} + +static void test_mmp_clean_and_fsck_sequences(struct kunit *test) +{ + struct mmp_test_ctx *ctx = mmp_setup_ctx(test); + struct mmp_struct *disk_mmp = (struct mmp_struct *)ctx->disk_buf; + int base_ref; + int ret; + + /* EXT4_MMP_SEQ_FSCK fails immediately with -EBUSY without sleeping */ + mmp_init_disk_block(ctx, EXT4_MMP_SEQ_FSCK, 5); + mmp_reset_counters(ctx); + ret = ext4_multi_mount_protect(ctx->sb, MMP_TEST_VALID_BLK); + KUNIT_EXPECT_EQ(test, ret, -EBUSY); + KUNIT_EXPECT_EQ(test, ctx->wait_calls, 0U); + KUNIT_EXPECT_EQ(test, ctx->write_calls, 0U); + + /* + * EXT4_MMP_SEQ_CLEAN skips pre-claim wait, writes a valid sequence + * <= EXT4_MMP_SEQ_MAX, starts kmmpd, and ext4_stop_mmpd() cleans up. + */ + mmp_init_disk_block(ctx, EXT4_MMP_SEQ_CLEAN, 5); + mmp_reset_counters(ctx); + base_ref = atomic_read(&ctx->mmp_bh.b_count); + + ret = ext4_multi_mount_protect(ctx->sb, MMP_TEST_VALID_BLK); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ctx->wait_calls, 1U); + KUNIT_EXPECT_EQ(test, ctx->write_calls, 1U); + KUNIT_EXPECT_EQ(test, ctx->run_thread_calls, 1U); + KUNIT_EXPECT_LE(test, le32_to_cpu(disk_mmp->mmp_seq), EXT4_MMP_SEQ_MAX); + KUNIT_EXPECT_NOT_NULL(test, ctx->sbi.s_mmp_tsk); + KUNIT_EXPECT_PTR_EQ(test, ctx->sbi.s_mmp_bh, &ctx->mmp_bh); + KUNIT_EXPECT_STREQ(test, + ((struct mmp_struct *)ctx->mmp_bh.b_data)->mmp_bdevname, + "mmp_bdev"); + + ext4_stop_mmpd(&ctx->sbi); + KUNIT_EXPECT_NULL(test, ctx->sbi.s_mmp_tsk); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->mmp_bh.b_count), base_ref); + ctx->sbi.s_mmp_bh = NULL; +} + +static void test_mmp_active_seq_conflict_and_claim(struct kunit *test) +{ + struct mmp_test_ctx *ctx = mmp_setup_ctx(test); + int ret; + + /* + * Case 1: Active sequence on disk; s_mmp_update_interval = 3 (floored + * to 5), disk mmp_check_interval = 12 (overrides 5 -> wait_time = 25s). + * Remote node updates mmp_seq during wait #1 -> fails with -EBUSY. + */ + ctx->es->s_mmp_update_interval = cpu_to_le16(3); + mmp_init_disk_block(ctx, 100, 12); + mmp_reset_counters(ctx); + ctx->mutate_seq_on_wait_call = 1; + ctx->mutated_seq = 101; + + ret = ext4_multi_mount_protect(ctx->sb, MMP_TEST_VALID_BLK); + KUNIT_EXPECT_EQ(test, ret, -EBUSY); + KUNIT_EXPECT_EQ(test, ctx->wait_calls, 1U); + KUNIT_EXPECT_EQ(test, ctx->wait_timeouts[0], (long)(25 * HZ)); + KUNIT_EXPECT_EQ(test, ctx->write_calls, 0U); + + /* + * Case 2: Stale sequence unchanged on wait #1, but racing mounter + * overwrites mmp_seq during post-claim wait #2 -> fails with -EBUSY. + */ + mmp_init_disk_block(ctx, 100, 12); + mmp_reset_counters(ctx); + ctx->mutate_seq_on_wait_call = 2; + ctx->mutated_seq = 0x5555U; + + ret = ext4_multi_mount_protect(ctx->sb, MMP_TEST_VALID_BLK); + KUNIT_EXPECT_EQ(test, ret, -EBUSY); + KUNIT_EXPECT_EQ(test, ctx->wait_calls, 2U); + KUNIT_EXPECT_EQ(test, ctx->wait_timeouts[0], (long)(25 * HZ)); + KUNIT_EXPECT_EQ(test, ctx->wait_timeouts[1], (long)(25 * HZ)); + KUNIT_EXPECT_EQ(test, ctx->write_calls, 1U); + + /* + * Case 3: Stale sequence with large check_interval = 80 (wait_time + * capped to 80 + 60 = 140s via min(2*x+1, x+60)) succeeds cleanly. + */ + mmp_init_disk_block(ctx, 100, 80); + mmp_reset_counters(ctx); + + ret = ext4_multi_mount_protect(ctx->sb, MMP_TEST_VALID_BLK); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ctx->wait_calls, 2U); + KUNIT_EXPECT_EQ(test, ctx->wait_timeouts[0], (long)(140 * HZ)); + KUNIT_EXPECT_EQ(test, ctx->wait_timeouts[1], (long)(140 * HZ)); + + ext4_stop_mmpd(&ctx->sbi); + ctx->sbi.s_mmp_bh = NULL; +} + +static void test_mmp_interrupted_waits_and_kthread_failure(struct kunit *test) +{ + struct mmp_test_ctx *ctx = mmp_setup_ctx(test); + + /* Signal interruption on pre-claim wait returns -ETIMEDOUT */ + mmp_init_disk_block(ctx, 77, 5); + mmp_reset_counters(ctx); + ctx->wait_ret_target_call = 1; + ctx->wait_ret_on_call = 3 * HZ; + KUNIT_EXPECT_EQ(test, + ext4_multi_mount_protect(ctx->sb, MMP_TEST_VALID_BLK), + -ETIMEDOUT); + + /* Signal interruption on post-claim wait returns -ETIMEDOUT */ + mmp_init_disk_block(ctx, 77, 5); + mmp_reset_counters(ctx); + ctx->wait_ret_target_call = 2; + ctx->wait_ret_on_call = 2 * HZ; + KUNIT_EXPECT_EQ(test, + ext4_multi_mount_protect(ctx->sb, MMP_TEST_VALID_BLK), + -ETIMEDOUT); + + /* kthread creation failure returns -ENOMEM and leaves s_mmp_tsk NULL */ + mmp_init_disk_block(ctx, EXT4_MMP_SEQ_CLEAN, 5); + mmp_reset_counters(ctx); + ctx->run_thread_err = -ENOMEM; + KUNIT_EXPECT_EQ(test, + ext4_multi_mount_protect(ctx->sb, MMP_TEST_VALID_BLK), + -ENOMEM); + KUNIT_EXPECT_NULL(test, ctx->sbi.s_mmp_tsk); + ctx->sbi.s_mmp_bh = NULL; +} + +static struct kunit_case mmp_test_cases[] = { + KUNIT_CASE(test_mmp_csum_set_and_verify), + KUNIT_CASE(test_read_and_write_mmp_block), + KUNIT_CASE(test_mmp_invalid_block_and_io_errors), + KUNIT_CASE(test_mmp_clean_and_fsck_sequences), + KUNIT_CASE(test_mmp_active_seq_conflict_and_claim), + KUNIT_CASE(test_mmp_interrupted_waits_and_kthread_failure), + {} +}; + +static struct kunit_suite mmp_test_suite = { + .name = "ext4_mmp_test", + .test_cases = mmp_test_cases, +}; + +kunit_test_suites(&mmp_test_suite); + +MODULE_DESCRIPTION("KUnit tests for ext4 multi-mount protection (MMP)"); +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/mmp.c b/fs/ext4/mmp.c index 4b18ddef468d71..9e9eac6060afec 100644 --- a/fs/ext4/mmp.c +++ b/fs/ext4/mmp.c @@ -1,4 +1,5 @@ // SPDX-License-Identifier: GPL-2.0 +#include #include #include #include @@ -35,6 +36,20 @@ static void ext4_mmp_csum_set(struct super_block *sb, struct mmp_struct *mmp) mmp->mmp_checksum = ext4_mmp_csum(sb, mmp); } +int ext4_mmp_submit_write(struct buffer_head *bh) +{ + KUNIT_STATIC_STUB_REDIRECT(ext4_mmp_submit_write, bh); + + lock_buffer(bh); + bh_submit(bh, REQ_OP_WRITE | REQ_SYNC | REQ_META | REQ_PRIO, + bh_end_write); + wait_on_buffer(bh); + if (unlikely(buffer_write_io_error(bh))) + return -EIO; + return 0; +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mmp_submit_write); + /* * Write the MMP block using REQ_SYNC to try to get the block on-disk * faster. @@ -45,13 +60,7 @@ static int write_mmp_block_thawed(struct super_block *sb, struct mmp_struct *mmp = (struct mmp_struct *)(bh->b_data); ext4_mmp_csum_set(sb, mmp); - lock_buffer(bh); - bh_submit(bh, REQ_OP_WRITE | REQ_SYNC | REQ_META | REQ_PRIO, - bh_end_write); - wait_on_buffer(bh); - if (unlikely(buffer_write_io_error(bh))) - return -EIO; - return 0; + return ext4_mmp_submit_write(bh); } static int write_mmp_block(struct super_block *sb, struct buffer_head *bh) @@ -64,6 +73,35 @@ static int write_mmp_block(struct super_block *sb, struct buffer_head *bh) return write_mmp_block_thawed(sb, bh); } +int ext4_mmp_load_bh(struct super_block *sb, struct buffer_head **bh, + ext4_fsblk_t mmp_block) +{ + KUNIT_STATIC_STUB_REDIRECT(ext4_mmp_load_bh, sb, bh, mmp_block); + + /* + * This would be sb_bread(sb, mmp_block), except we need to be sure + * that the MD RAID device cache has been bypassed, and that the read + * is not blocked in the elevator. + */ + if (!*bh) { + *bh = sb_getblk(sb, mmp_block); + if (!*bh) + return -ENOMEM; + } + + lock_buffer(*bh); + return ext4_read_bh(*bh, REQ_META | REQ_PRIO, NULL, false); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mmp_load_bh); + +long ext4_mmp_wait_timeout(long timeout) +{ + KUNIT_STATIC_STUB_REDIRECT(ext4_mmp_wait_timeout, timeout); + + return schedule_timeout_interruptible(timeout); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mmp_wait_timeout); + /* * Read the MMP block. It _must_ be read from disk and hence we clear the * uptodate flag on the buffer. @@ -77,19 +115,7 @@ static int read_mmp_block(struct super_block *sb, struct buffer_head **bh, if (*bh) clear_buffer_uptodate(*bh); - /* This would be sb_bread(sb, mmp_block), except we need to be sure - * that the MD RAID device cache has been bypassed, and that the read - * is not blocked in the elevator. */ - if (!*bh) { - *bh = sb_getblk(sb, mmp_block); - if (!*bh) { - ret = -ENOMEM; - goto warn_exit; - } - } - - lock_buffer(*bh); - ret = ext4_read_bh(*bh, REQ_META | REQ_PRIO, NULL, false); + ret = ext4_mmp_load_bh(sb, bh, mmp_block); if (ret) goto warn_exit; @@ -185,8 +211,7 @@ static int kmmpd(void *data) diff = jiffies - last_update_time; if (diff < mmp_update_interval * HZ) - schedule_timeout_interruptible(mmp_update_interval * - HZ - diff); + ext4_mmp_wait_timeout(mmp_update_interval * HZ - diff); /* * We need to make sure that more than mmp_check_interval @@ -250,6 +275,16 @@ static int kmmpd(void *data) return retval; } +struct task_struct *ext4_mmp_run_thread(struct super_block *sb, + const char *bdevname, int bdevname_len) +{ + KUNIT_STATIC_STUB_REDIRECT(ext4_mmp_run_thread, sb, bdevname, + bdevname_len); + + return kthread_run(kmmpd, sb, "kmmpd-%.*s", bdevname_len, bdevname); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mmp_run_thread); + void ext4_stop_mmpd(struct ext4_sb_info *sbi) { if (sbi->s_mmp_tsk) { @@ -258,6 +293,7 @@ void ext4_stop_mmpd(struct ext4_sb_info *sbi) sbi->s_mmp_tsk = NULL; } } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_stop_mmpd); /* * Get a random new sequence number but make sure it is not greater than @@ -323,7 +359,7 @@ int ext4_multi_mount_protect(struct super_block *sb, ext4_warning(sb, "MMP interval %u higher than expected, please" " wait.\n", wait_time * 2); - if (schedule_timeout_interruptible(HZ * wait_time) != 0) { + if (ext4_mmp_wait_timeout(HZ * wait_time) != 0) { ext4_warning(sb, "MMP startup interrupted, failing mount\n"); retval = -ETIMEDOUT; goto failed; @@ -358,7 +394,7 @@ int ext4_multi_mount_protect(struct super_block *sb, /* * wait for MMP interval and check mmp_seq. */ - if (schedule_timeout_interruptible(HZ * wait_time) != 0) { + if (ext4_mmp_wait_timeout(HZ * wait_time) != 0) { ext4_warning(sb, "MMP startup interrupted, failing mount"); retval = -ETIMEDOUT; goto failed; @@ -384,9 +420,8 @@ int ext4_multi_mount_protect(struct super_block *sb, /* * Start a kernel thread to update the MMP block periodically. */ - EXT4_SB(sb)->s_mmp_tsk = kthread_run(kmmpd, sb, "kmmpd-%.*s", - (int)sizeof(mmp->mmp_bdevname), - mmp->mmp_bdevname); + EXT4_SB(sb)->s_mmp_tsk = ext4_mmp_run_thread(sb, mmp->mmp_bdevname, + (int)sizeof(mmp->mmp_bdevname)); if (IS_ERR(EXT4_SB(sb)->s_mmp_tsk)) { EXT4_SB(sb)->s_mmp_tsk = NULL; ext4_warning(sb, "Unable to create kmmpd thread for %s.", @@ -401,3 +436,31 @@ int ext4_multi_mount_protect(struct super_block *sb, brelse(bh); return retval; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_multi_mount_protect); + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +int ext4_mmp_csum_verify_test(struct super_block *sb, struct mmp_struct *mmp) +{ + return ext4_mmp_csum_verify(sb, mmp); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mmp_csum_verify_test); + +void ext4_mmp_csum_set_test(struct super_block *sb, struct mmp_struct *mmp) +{ + ext4_mmp_csum_set(sb, mmp); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mmp_csum_set_test); + +int ext4_read_mmp_block_test(struct super_block *sb, struct buffer_head **bh, + ext4_fsblk_t mmp_block) +{ + return read_mmp_block(sb, bh, mmp_block); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_read_mmp_block_test); + +int ext4_write_mmp_block_test(struct super_block *sb, struct buffer_head *bh) +{ + return write_mmp_block(sb, bh); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_write_mmp_block_test); +#endif diff --git a/fs/ext4/move_extent-test.c b/fs/ext4/move_extent-test.c new file mode 100644 index 00000000000000..a3e002f1410932 --- /dev/null +++ b/fs/ext4/move_extent-test.c @@ -0,0 +1,1023 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for fs/ext4/move_extent.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_extents.h" +#include "ext4_jbd2.h" + +#define MEXT_TEST_BLK_SIZE 4096U +#define MEXT_TEST_BLK_BITS 12U +#define MEXT_TEST_BLOCKS_PER_GRP 32768U +#define MEXT_TEST_NGROUPS 8U +#define MEXT_TEST_FIRST_DATA_BLK 1U +#define MEXT_TEST_TOTAL_BLKS (MEXT_TEST_FIRST_DATA_BLK + \ + MEXT_TEST_NGROUPS * \ + MEXT_TEST_BLOCKS_PER_GRP) +#define MEXT_MAX_META_BLKS 16U +#define MEXT_META_BASE_PBLK 1000U + +struct mext_meta_blk { + ext4_fsblk_t pblk; + struct buffer_head bh; + u8 data[MEXT_TEST_BLK_SIZE]; + bool in_use; +}; + +struct mext_test_ctx { + struct super_block *sb; + struct ext4_sb_info sbi; + struct ext4_super_block *es; + struct blockgroup_lock bgl; + struct gendisk bdev_disk; + struct block_device bdev; + struct request_queue bdev_queue; + struct address_space bdev_mapping; + struct buffer_head sbh; + u8 sbh_data[MEXT_TEST_BLK_SIZE]; + struct mext_meta_blk *meta_blks; + ext4_fsblk_t next_meta_pblk; + struct inode *orig_inode; + struct inode *donor_inode; + struct dentry orig_dentry; + struct dentry donor_dentry; + struct file orig_file; + struct file donor_file; + bool es_shrinker_inited; + bool counters_inited; +}; + +static struct kunit *active_mext_test; + +static void mext_noop_work(struct work_struct *work) +{ +} + +static void mext_noop_timer(struct timer_list *t) +{ +} + +static unsigned long mext_dummy_shrinker_count(struct shrinker *shrink, + struct shrink_control *sc) +{ + return 0; +} + +static unsigned long mext_dummy_shrinker_scan(struct shrinker *shrink, + struct shrink_control *sc) +{ + return SHRINK_STOP; +} + +static struct inode *mext_test_alloc_inode(struct super_block *sb) +{ + struct ext4_inode_info *ei; + + ei = kzalloc_obj(*ei); + if (!ei) + return NULL; + + init_rwsem(&ei->i_data_sem); + inode_init_once(&ei->vfs_inode); + inode_set_iversion(&ei->vfs_inode, 1); + ei->i_prealloc_node = RB_ROOT; + rwlock_init(&ei->i_prealloc_lock); + ext4_es_init_tree(&ei->i_es_tree); + rwlock_init(&ei->i_es_lock); + INIT_LIST_HEAD(&ei->i_es_list); + spin_lock_init(&ei->i_raw_lock); + spin_lock_init(&ei->i_block_reservation_lock); + ext4_init_pending_tree(&ei->i_pending_tree); + init_rwsem(&ei->xattr_sem); + INIT_LIST_HEAD(&ei->i_rsv_conversion_list); + spin_lock_init(&ei->i_completed_io_lock); + INIT_LIST_HEAD(&ei->i_orphan); + ext4_fc_init_inode(&ei->vfs_inode); + spin_lock_init(&ei->i_fc_lock); + ei->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + ei->i_extra_isize = sizeof(struct ext4_inode) - EXT4_GOOD_OLD_INODE_SIZE; + ei->i_last_alloc_group = ~0U; + + return &ei->vfs_inode; +} + +static void mext_test_free_inode(struct inode *inode) +{ + kfree(EXT4_I(inode)); +} + +static void mext_test_evict_inode(struct inode *inode) +{ + truncate_inode_pages_final(&inode->i_data); + ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS); + clear_inode(inode); +} + +#ifdef CONFIG_QUOTA +static struct dquot __rcu **mext_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} + +static qsize_t *mext_get_reserved_space(struct inode *inode) +{ + return &EXT4_I(inode)->i_reserved_quota; +} + +static const struct dquot_operations mext_dummy_qops = { + .get_reserved_space = mext_get_reserved_space, +}; +#endif + +static const struct super_operations mext_test_sops = { + .alloc_inode = mext_test_alloc_inode, + .free_inode = mext_test_free_inode, + .evict_inode = mext_test_evict_inode, +#ifdef CONFIG_QUOTA + .get_dquots = mext_get_dquots, +#endif +}; + +static int mext_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static int mext_set_super(struct super_block *sb, struct fs_context *fc) +{ + return set_anon_super_fc(sb, fc); +} + +static struct file_system_type mext_test_fs_type = { + .name = "ext4_move_extent_test", + .init_fs_context = mext_init_fs_context, + .kill_sb = kill_anon_super, +}; + +static int mext_ext_dirty_stub(const char *where, unsigned int line, + handle_t *handle, struct inode *inode, + struct ext4_ext_path *path) +{ + if (path && path->p_bh) { + ext4_extent_block_csum_set_test(inode, + ext_block_hdr(path->p_bh)); + set_buffer_verified(path->p_bh); + } + return 0; +} + +static int mext_handle_dirty_metadata_stub(const char *where, + unsigned int line, + handle_t *handle, + struct inode *inode, + struct buffer_head *bh) +{ + if (bh) + set_buffer_uptodate(bh); + return 0; +} + +static int mext_mark_inode_dirty_stub(handle_t *handle, struct inode *inode, + const char *func, unsigned int line) +{ + return 0; +} + +static struct buffer_head *mext_ext_getblk_stub(struct inode *inode, + ext4_fsblk_t pblk, + gfp_t gfp_flags) +{ + struct kunit *test = active_mext_test; + struct mext_test_ctx *ctx; + struct mext_meta_blk *slot = NULL; + unsigned int i; + + if (!test) + return NULL; + ctx = test->priv; + if (!ctx || !ctx->meta_blks) + return NULL; + + for (i = 0; i < MEXT_MAX_META_BLKS; i++) { + if (ctx->meta_blks[i].in_use && + ctx->meta_blks[i].pblk == pblk) { + slot = &ctx->meta_blks[i]; + break; + } + } + + if (!slot) { + for (i = 0; i < MEXT_MAX_META_BLKS; i++) { + if (!ctx->meta_blks[i].in_use) { + slot = &ctx->meta_blks[i]; + break; + } + } + if (!slot) + return NULL; + + memset(slot, 0, sizeof(*slot)); + slot->in_use = true; + slot->pblk = pblk; + slot->bh.b_data = slot->data; + slot->bh.b_size = inode->i_sb->s_blocksize; + slot->bh.b_blocknr = pblk; + slot->bh.b_bdev = inode->i_sb->s_bdev; + atomic_set(&slot->bh.b_count, 1); + set_buffer_uptodate(&slot->bh); + set_buffer_mapped(&slot->bh); + } + + get_bh(&slot->bh); + return &slot->bh; +} + +static ext4_fsblk_t mext_mb_new_blocks_stub(handle_t *handle, + struct ext4_allocation_request *ar, + int *errp) +{ + struct kunit *test = active_mext_test; + struct mext_test_ctx *ctx; + ext4_fsblk_t pblk; + + if (!test) { + *errp = -EIO; + return 0; + } + ctx = test->priv; + pblk = ctx->next_meta_pblk; + ctx->next_meta_pblk += ar->len; + *errp = 0; + return pblk; +} + +static void mext_free_blocks_stub(handle_t *handle, struct inode *inode, + struct buffer_head *bh, ext4_fsblk_t block, + unsigned long count, int flags) +{ +} + +static int mext_journal_data_mode_stub(struct inode *inode) +{ + return EXT4_INODE_JOURNAL_DATA_MODE; +} + +static void mext_init_mock_file(struct file *filp, struct dentry *dentry, + struct inode *inode) +{ + struct file tmp = { + .f_path = { .dentry = dentry }, + .f_inode = inode, + .f_mapping = inode->i_mapping, + .f_mode = FMODE_READ | FMODE_WRITE | FMODE_NOCMTIME, + }; + + memset(dentry, 0, sizeof(*dentry)); + dentry->d_inode = inode; + memcpy(filp, &tmp, sizeof(*filp)); +} + +static struct inode *mext_create_test_inode(struct kunit *test, + struct super_block *sb, + unsigned long ino, + ext4_lblk_t size_blks) +{ + struct ext4_extent_header *eh; + struct inode *inode; + + inode = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, inode); + + inode->i_ino = ino; + inode->i_mode = S_IFREG | 0644; + set_nlink(inode, 1); + inode->i_blkbits = sb->s_blocksize_bits; + /* + * Note: leave S_NOQUOTA clear so ext4_is_quota_file(inode) is false. + */ + inode->i_flags |= S_NOSEC; + inode_state_set_raw(inode, + I_DIRTY_SYNC | I_DIRTY_DATASYNC | I_DIRTY_PAGES); + mapping_set_gfp_mask(&inode->i_data, GFP_KERNEL); + + EXT4_I(inode)->i_csum_seed = 0x13572468U; + EXT4_I(inode)->i_disksize = (loff_t)size_blks << sb->s_blocksize_bits; + i_size_write(inode, EXT4_I(inode)->i_disksize); + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + ext4_set_aops(inode); + + eh = ext_inode_hdr(inode); + memset(EXT4_I(inode)->i_data, 0, sizeof(EXT4_I(inode)->i_data)); + eh->eh_magic = EXT4_EXT_MAGIC; + eh->eh_entries = 0; + eh->eh_max = cpu_to_le16(ext4_ext_space_root_idx_test(inode, 0)); + eh->eh_depth = 0; + + return inode; +} + +static void mext_insert_extent(struct kunit *test, struct inode *inode, + ext4_lblk_t lblk, u16 len, ext4_fsblk_t pblk, + bool unwritten) +{ + struct ext4_extent newex = {}; + struct ext4_ext_path *path; + + newex.ee_block = cpu_to_le32(lblk); + newex.ee_len = cpu_to_le16(len); + if (unwritten) + ext4_ext_mark_unwritten(&newex); + ext4_ext_store_pblock(&newex, pblk); + + inode_lock(inode); + down_write(&EXT4_I(inode)->i_data_sem); + path = ext4_find_extent(inode, lblk, NULL, 0); + if (!IS_ERR(path)) + path = ext4_ext_insert_extent(NULL, inode, path, &newex, 0); + up_write(&EXT4_I(inode)->i_data_sem); + inode_unlock(inode); + + KUNIT_ASSERT_FALSE(test, IS_ERR(path)); + ext4_free_ext_path(path); +} + +static void mext_populate_folio_block(struct kunit *test, struct inode *inode, + ext4_lblk_t lblk, u8 pattern) +{ + loff_t pos = (loff_t)lblk << inode->i_blkbits; + size_t bsize = i_blocksize(inode); + struct folio *folio; + u8 *addr; + + folio = __filemap_get_folio(inode->i_mapping, pos >> PAGE_SHIFT, + FGP_CREAT | FGP_LOCK, GFP_KERNEL); + KUNIT_ASSERT_FALSE(test, IS_ERR(folio)); + + addr = folio_address(folio); + memset(addr + offset_in_folio(folio, pos), pattern, bsize); + folio_mark_uptodate(folio); + folio_unlock(folio); + folio_put(folio); +} + +static void mext_assert_mapped_block(struct kunit *test, struct inode *inode, + ext4_lblk_t lblk, ext4_fsblk_t exp_pblk, + unsigned int exp_flag) +{ + struct ext4_map_blocks map = { + .m_lblk = lblk, + .m_len = 1, + }; + int ret; + + inode_lock(inode); + ret = ext4_map_blocks(NULL, inode, &map, 0); + inode_unlock(inode); + + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, map.m_pblk, exp_pblk); + KUNIT_EXPECT_TRUE(test, (map.m_flags & exp_flag) != 0); + if (exp_flag == EXT4_MAP_MAPPED) + KUNIT_EXPECT_EQ(test, map.m_flags & EXT4_MAP_UNWRITTEN, 0U); + else if (exp_flag == EXT4_MAP_UNWRITTEN) + KUNIT_EXPECT_EQ(test, map.m_flags & EXT4_MAP_MAPPED, 0U); +} + +static void mext_cleanup_ctx(void *data) +{ + struct mext_test_ctx *ctx = data; + + active_mext_test = NULL; + + cancel_work_sync(&ctx->sbi.s_sb_upd_work); + timer_delete_sync(&ctx->sbi.s_err_report); + + if (ctx->orig_inode) { + iput(ctx->orig_inode); + ctx->orig_inode = NULL; + } + if (ctx->donor_inode) { + iput(ctx->donor_inode); + ctx->donor_inode = NULL; + } + + if (ctx->sb) { + deactivate_super(ctx->sb); + ctx->sb = NULL; + } + rcu_barrier(); + + if (ctx->es_shrinker_inited) { + ext4_es_unregister_shrinker(&ctx->sbi); + ext4_es_destroy_stats(&ctx->sbi); + ctx->es_shrinker_inited = false; + } + if (ctx->counters_inited) { + percpu_counter_destroy(&ctx->sbi.s_freeclusters_counter); + percpu_counter_destroy(&ctx->sbi.s_dirtyclusters_counter); + ctx->counters_inited = false; + } + + if (ctx->bdev.bd_stats) { + free_percpu(ctx->bdev.bd_stats); + ctx->bdev.bd_stats = NULL; + } +} + +static struct mext_test_ctx *mext_setup_ctx(struct kunit *test) +{ + struct mext_test_ctx *ctx; + struct fs_context *fc; + struct super_block *sb; + int err; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + ctx->es = kunit_kzalloc(test, sizeof(*ctx->es), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->es); + ctx->meta_blks = kunit_kcalloc(test, MEXT_MAX_META_BLKS, + sizeof(*ctx->meta_blks), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->meta_blks); + ctx->next_meta_pblk = MEXT_META_BASE_PBLK; + + fc = fs_context_for_mount(&mext_test_fs_type, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(fc)); + sb = sget_fc(fc, NULL, mext_set_super); + put_fs_context(fc); + KUNIT_ASSERT_FALSE(test, IS_ERR(sb)); + up_write(&sb->s_umount); + ctx->sb = sb; + + INIT_WORK(&ctx->sbi.s_sb_upd_work, mext_noop_work); + timer_setup(&ctx->sbi.s_err_report, mext_noop_timer, 0); + + err = kunit_add_action_or_reset(test, mext_cleanup_ctx, ctx); + KUNIT_ASSERT_EQ(test, err, 0); + + ctx->bdev.bd_stats = alloc_percpu(struct disk_stats); + KUNIT_ASSERT_TRUE(test, ctx->bdev.bd_stats != NULL); + ctx->bdev_disk.queue = &ctx->bdev_queue; + ctx->bdev.bd_disk = &ctx->bdev_disk; + ctx->bdev.bd_queue = &ctx->bdev_queue; + ctx->bdev.bd_mapping = &ctx->bdev_mapping; + bdev_set_flag(&ctx->bdev, BD_READ_ONLY); + + sb->s_bdev = &ctx->bdev; + sb->s_blocksize = MEXT_TEST_BLK_SIZE; + sb->s_blocksize_bits = MEXT_TEST_BLK_BITS; + sb->s_maxbytes = MAX_LFS_FILESIZE; + sb->s_magic = EXT4_SUPER_MAGIC; + sb->s_op = &mext_test_sops; +#ifdef CONFIG_QUOTA + sb->dq_op = &mext_dummy_qops; +#endif +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; +#endif + sb->s_fs_info = &ctx->sbi; + strscpy(sb->s_id, "ext4_mext_kunit", sizeof(sb->s_id)); + + ctx->sbh.b_data = ctx->sbh_data; + ctx->sbh.b_size = MEXT_TEST_BLK_SIZE; + ctx->sbh.b_bdev = &ctx->bdev; + atomic_set(&ctx->sbh.b_count, 2); + set_buffer_uptodate(&ctx->sbh); + clear_buffer_mapped(&ctx->sbh); + + ctx->es->s_magic = cpu_to_le16(EXT4_SUPER_MAGIC); + ctx->es->s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + ctx->es->s_first_data_block = cpu_to_le32(MEXT_TEST_FIRST_DATA_BLK); + ctx->es->s_log_block_size = cpu_to_le32(2); + ctx->es->s_log_cluster_size = cpu_to_le32(2); + ctx->es->s_blocks_per_group = cpu_to_le32(MEXT_TEST_BLOCKS_PER_GRP); + ctx->es->s_clusters_per_group = cpu_to_le32(MEXT_TEST_BLOCKS_PER_GRP); + ctx->es->s_inodes_per_group = cpu_to_le32(8192); + ctx->es->s_inodes_count = cpu_to_le32(MEXT_TEST_NGROUPS * 8192); + ctx->es->s_feature_incompat = cpu_to_le32(EXT4_FEATURE_INCOMPAT_EXTENTS); + ext4_blocks_count_set(ctx->es, MEXT_TEST_TOTAL_BLKS); + + bgl_lock_init(&ctx->bgl); + ctx->sbi.s_sb = sb; + ctx->sbi.s_es = ctx->es; + ctx->sbi.s_sbh = &ctx->sbh; + ctx->sbi.s_blockgroup_lock = &ctx->bgl; + ctx->sbi.s_blocks_per_group = MEXT_TEST_BLOCKS_PER_GRP; + ctx->sbi.s_clusters_per_group = MEXT_TEST_BLOCKS_PER_GRP; + ctx->sbi.s_cluster_ratio = 1; + ctx->sbi.s_cluster_bits = 0; + ctx->sbi.s_groups_count = MEXT_TEST_NGROUPS; + ctx->sbi.s_desc_size = EXT4_MIN_DESC_SIZE; + ctx->sbi.s_desc_per_block = MEXT_TEST_BLK_SIZE / EXT4_MIN_DESC_SIZE; + ctx->sbi.s_inodes_per_group = 8192; + ctx->sbi.s_inode_size = sizeof(struct ext4_inode); + ctx->sbi.s_inodes_per_block = MEXT_TEST_BLK_SIZE / + sizeof(struct ext4_inode); + ctx->sbi.s_bitmap_maxbytes = MAX_LFS_FILESIZE; + set_opt(sb, ERRORS_CONT); + + mutex_init(&ctx->sbi.s_orphan_lock); + INIT_LIST_HEAD(&ctx->sbi.s_orphan); + spin_lock_init(&ctx->sbi.s_bdev_wb_lock); + spin_lock_init(&ctx->sbi.s_error_lock); + spin_lock_init(&ctx->sbi.s_md_lock); + INIT_LIST_HEAD(&ctx->sbi.s_fc_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&ctx->sbi.s_fc_q[FC_Q_STAGING]); + INIT_LIST_HEAD(&ctx->sbi.s_fc_dentry_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&ctx->sbi.s_fc_dentry_q[FC_Q_STAGING]); + mutex_init(&ctx->sbi.s_fc_lock); + ratelimit_state_init(&ctx->sbi.s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, + DEFAULT_RATELIMIT_BURST); + ratelimit_state_init(&ctx->sbi.s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, + DEFAULT_RATELIMIT_BURST); + ratelimit_state_init(&ctx->sbi.s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, + DEFAULT_RATELIMIT_BURST); + + err = percpu_counter_init(&ctx->sbi.s_freeclusters_counter, 65536, + GFP_KERNEL); + KUNIT_ASSERT_EQ(test, err, 0); + err = percpu_counter_init(&ctx->sbi.s_dirtyclusters_counter, 0, + GFP_KERNEL); + if (err) { + percpu_counter_destroy(&ctx->sbi.s_freeclusters_counter); + KUNIT_FAIL_AND_ABORT(test, "dirtyclusters counter init failed"); + } + ctx->counters_inited = true; + + err = ext4_es_register_shrinker(&ctx->sbi); + KUNIT_ASSERT_EQ(test, err, 0); + ctx->sbi.s_es_shrinker->count_objects = mext_dummy_shrinker_count; + ctx->sbi.s_es_shrinker->scan_objects = mext_dummy_shrinker_scan; + ctx->es_shrinker_inited = true; + + ctx->orig_inode = mext_create_test_inode(test, sb, 21, 16); + ctx->donor_inode = mext_create_test_inode(test, sb, 22, 16); + mext_init_mock_file(&ctx->orig_file, &ctx->orig_dentry, + ctx->orig_inode); + mext_init_mock_file(&ctx->donor_file, &ctx->donor_dentry, + ctx->donor_inode); + + test->priv = ctx; + active_mext_test = test; + + kunit_activate_static_stub(test, __ext4_ext_dirty, + mext_ext_dirty_stub); + kunit_activate_static_stub(test, __ext4_handle_dirty_metadata, + mext_handle_dirty_metadata_stub); + kunit_activate_static_stub(test, __ext4_mark_inode_dirty, + mext_mark_inode_dirty_stub); + kunit_activate_static_stub(test, ext4_ext_getblk, + mext_ext_getblk_stub); + kunit_activate_static_stub(test, ext4_mb_new_blocks, + mext_mb_new_blocks_stub); + kunit_activate_static_stub(test, ext4_free_blocks, + mext_free_blocks_stub); + + return ctx; +} + +static void test_double_data_sem_lock_order(struct kunit *test) +{ + struct mext_test_ctx *ctx = mext_setup_ctx(test); + struct inode *low = ctx->orig_inode; + struct inode *high = ctx->donor_inode; + + if (low > high) + swap(low, high); + + /* Acquire with first < second */ + ext4_double_down_write_data_sem(low, high); + KUNIT_EXPECT_TRUE(test, rwsem_is_locked(&EXT4_I(low)->i_data_sem)); + KUNIT_EXPECT_TRUE(test, rwsem_is_locked(&EXT4_I(high)->i_data_sem)); + ext4_double_up_write_data_sem(low, high); + KUNIT_EXPECT_FALSE(test, rwsem_is_locked(&EXT4_I(low)->i_data_sem)); + KUNIT_EXPECT_FALSE(test, rwsem_is_locked(&EXT4_I(high)->i_data_sem)); + + /* Acquire with first > second */ + ext4_double_down_write_data_sem(high, low); + KUNIT_EXPECT_TRUE(test, rwsem_is_locked(&EXT4_I(low)->i_data_sem)); + KUNIT_EXPECT_TRUE(test, rwsem_is_locked(&EXT4_I(high)->i_data_sem)); + ext4_double_up_write_data_sem(high, low); + KUNIT_EXPECT_FALSE(test, rwsem_is_locked(&EXT4_I(low)->i_data_sem)); + KUNIT_EXPECT_FALSE(test, rwsem_is_locked(&EXT4_I(high)->i_data_sem)); +} + +static void test_mext_check_validity_rejections(struct kunit *test) +{ + struct mext_test_ctx *ctx = mext_setup_ctx(test); + struct inode *orig = ctx->orig_inode; + struct inode *donor = ctx->donor_inode; + struct super_block *other_sb; + __u64 moved_len = 99; + int ret; + + /* Valid baseline */ + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), 0); + + /* Same inode rejected both directly and via ext4_move_extents() */ + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, orig), + -EINVAL); + ret = ext4_move_extents(&ctx->orig_file, &ctx->orig_file, 0, 0, 1, + &moved_len); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + KUNIT_EXPECT_EQ(test, moved_len, 0ULL); + + /* Cross-superblock rejected */ + other_sb = kunit_kzalloc(test, sizeof(*other_sb), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, other_sb); + donor->i_sb = other_sb; + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), + -EINVAL); + donor->i_sb = ctx->sb; + + /* Non-regular files rejected */ + orig->i_mode = S_IFIFO | 0644; + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), + -EINVAL); + ret = ext4_move_extents(&ctx->orig_file, &ctx->donor_file, 0, 0, 1, + &moved_len); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + orig->i_mode = S_IFREG | 0644; + + donor->i_mode = S_IFDIR | 0755; + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), + -EINVAL); + donor->i_mode = S_IFREG | 0644; + + /* Bigalloc feature rejected */ + ext4_set_feature_bigalloc(ctx->sb); + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), + -EOPNOTSUPP); + ext4_clear_feature_bigalloc(ctx->sb); + +#if IS_ENABLED(CONFIG_FS_DAX) + /* DAX inode rejected */ + orig->i_flags |= S_DAX; + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), + -EOPNOTSUPP); + orig->i_flags &= ~S_DAX; +#endif + + /* Data journaling mode rejected */ + kunit_activate_static_stub(test, ext4_inode_journal_mode, + mext_journal_data_mode_stub); + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), + -EOPNOTSUPP); + kunit_deactivate_static_stub(test, ext4_inode_journal_mode); + + /* Encrypted inode rejected */ + donor->i_flags |= S_ENCRYPTED; + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), + -EOPNOTSUPP); + donor->i_flags &= ~S_ENCRYPTED; + + /* Non-extent inode rejected */ + ext4_clear_inode_flag(orig, EXT4_INODE_EXTENTS); + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), + -EOPNOTSUPP); + ext4_set_inode_flag(orig, EXT4_INODE_EXTENTS); + + /* SUID / SGID on donor rejected */ + donor->i_mode |= S_ISUID; + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), + -EINVAL); + donor->i_mode = (donor->i_mode & ~S_ISUID) | S_ISGID; + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), + -EINVAL); + donor->i_mode &= ~S_ISGID; + + /* Immutable / append-only donor rejected with -EPERM */ + donor->i_flags |= S_IMMUTABLE; + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), + -EPERM); + donor->i_flags = (donor->i_flags & ~S_IMMUTABLE) | S_APPEND; + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), + -EPERM); + donor->i_flags &= ~S_APPEND; + + /* Swapfile rejected with -ETXTBSY */ + orig->i_flags |= S_SWAPFILE; + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), + -ETXTBSY); + orig->i_flags &= ~S_SWAPFILE; + + /* Quota file (S_NOQUOTA without EXT4_INODE_EA_INODE) rejected */ + orig->i_flags |= S_NOQUOTA; + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), + -EOPNOTSUPP); + ext4_set_inode_flag(orig, EXT4_INODE_EA_INODE); + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), 0); + ext4_clear_inode_flag(orig, EXT4_INODE_EA_INODE); + orig->i_flags &= ~S_NOQUOTA; + + /* Zero-byte file rejected with -EINVAL */ + i_size_write(donor, 0); + KUNIT_EXPECT_EQ(test, ext4_mext_check_validity_test(orig, donor), + -EINVAL); + i_size_write(donor, EXT4_I(donor)->i_disksize); +} + +static void test_mext_check_adjust_range(struct kunit *test) +{ + struct mext_test_ctx *ctx = mext_setup_ctx(test); + struct inode *orig = ctx->orig_inode; + struct inode *donor = ctx->donor_inode; + __u64 len; + int ret; + + /* Sub-page block alignment check when blocksize (1024) < PAGE_SIZE */ + orig->i_blkbits = 10; + donor->i_blkbits = 10; + i_size_write(orig, max_t(loff_t, 32 * 1024, 4 * PAGE_SIZE)); + i_size_write(donor, max_t(loff_t, 32 * 1024, 4 * PAGE_SIZE)); + + len = 4; + ret = ext4_mext_check_adjust_range_test(orig, donor, 1, 2, &len); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + + len = 4; + ret = ext4_mext_check_adjust_range_test(orig, donor, 1, + 1 + (PAGE_SIZE >> 10), &len); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, len, 4ULL); + + orig->i_blkbits = MEXT_TEST_BLK_BITS; + donor->i_blkbits = MEXT_TEST_BLK_BITS; + + /* EXT_MAX_BLOCKS boundary and sum-overflow checks */ + len = 1; + KUNIT_EXPECT_EQ(test, + ext4_mext_check_adjust_range_test(orig, donor, + EXT_MAX_BLOCKS, + EXT_MAX_BLOCKS, &len), + -EINVAL); + + len = (u64)EXT_MAX_BLOCKS + 1; + KUNIT_EXPECT_EQ(test, + ext4_mext_check_adjust_range_test(orig, donor, 0, 0, + &len), + -EINVAL); + + len = 4; + KUNIT_EXPECT_EQ(test, + ext4_mext_check_adjust_range_test(orig, donor, + EXT_MAX_BLOCKS - 4, + EXT_MAX_BLOCKS - 4, + &len), + -EINVAL); + + /* Clamping to shorter EOF (including partial trailing block i_size) */ + i_size_write(orig, 5 * MEXT_TEST_BLK_SIZE + 100); /* orig_eof = 6 */ + i_size_write(donor, 4 * MEXT_TEST_BLK_SIZE); /* donor_eof = 4 */ + + len = 12; + ret = ext4_mext_check_adjust_range_test(orig, donor, 1, 1, &len); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, len, 3ULL); + + /* Start at or beyond EOF clamps len to 0 and returns -EINVAL */ + len = 4; + ret = ext4_mext_check_adjust_range_test(orig, donor, 4, 4, &len); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + KUNIT_EXPECT_EQ(test, len, 0ULL); +} + +static void test_move_extents_holes_and_unwritten(struct kunit *test) +{ + struct mext_test_ctx *ctx = mext_setup_ctx(test); + struct inode *orig = ctx->orig_inode; + struct inode *donor = ctx->donor_inode; + __u64 moved_len = 0; + int ret; + + /* + * orig: [0, 2) hole, [2, 4) unwritten -> pblk 202..203, + * [4, 6) unwritten -> pblk 204..205 + * donor: [0, 2) unwritten -> pblk 300..301, [2, 4) hole, + * [4, 6) unwritten -> pblk 304..305 + * + * Expected across [0, 6) (clamped from requested len = 16 to EOF = 6): + * - [0, 2): skipped in ext4_move_extents() because orig is a hole + * - [2, 4): skipped via MEXT_SKIP_EXTENT because donor is a hole + * - [4, 6): swapped via MEXT_MOVE_EXTENT (both unwritten) + */ + i_size_write(orig, 6 * MEXT_TEST_BLK_SIZE); + EXT4_I(orig)->i_disksize = 6 * MEXT_TEST_BLK_SIZE; + i_size_write(donor, 6 * MEXT_TEST_BLK_SIZE); + EXT4_I(donor)->i_disksize = 6 * MEXT_TEST_BLK_SIZE; + + mext_insert_extent(test, orig, 2, 4, 202, true); + mext_insert_extent(test, donor, 0, 2, 300, true); + mext_insert_extent(test, donor, 4, 2, 304, true); + + ret = ext4_move_extents(&ctx->orig_file, &ctx->donor_file, 0, 0, 16, + &moved_len); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, moved_len, 2ULL); + + /* [2, 4) on orig remained on pblk 202..203; [4, 6) swapped to 304..305 */ + mext_assert_mapped_block(test, orig, 2, 202, EXT4_MAP_UNWRITTEN); + mext_assert_mapped_block(test, orig, 3, 203, EXT4_MAP_UNWRITTEN); + mext_assert_mapped_block(test, orig, 4, 304, EXT4_MAP_UNWRITTEN); + mext_assert_mapped_block(test, orig, 5, 305, EXT4_MAP_UNWRITTEN); + + /* [0, 2) on donor remained 300..301; [4, 6) received 204..205 */ + mext_assert_mapped_block(test, donor, 0, 300, EXT4_MAP_UNWRITTEN); + mext_assert_mapped_block(test, donor, 4, 204, EXT4_MAP_UNWRITTEN); + mext_assert_mapped_block(test, donor, 5, 205, EXT4_MAP_UNWRITTEN); +} + +static void test_move_extents_written_copy_data_and_split(struct kunit *test) +{ + struct mext_test_ctx *ctx = mext_setup_ctx(test); + struct inode *orig = ctx->orig_inode; + struct inode *donor = ctx->donor_inode; + ext4_lblk_t stride = max_t(ext4_lblk_t, 1, + PAGE_SIZE >> MEXT_TEST_BLK_BITS); + ext4_lblk_t ext1 = stride; + ext4_lblk_t ext2 = 3 * stride; + ext4_lblk_t total_blks = ext2 + 3; + ext4_lblk_t moved_lblks[] = { ext1, ext2, ext2 + 1 }; + ext4_lblk_t lblk; + __u64 moved_len = 0; + unsigned int i; + int ret; + + /* + * orig: [0, total_blks) written -> pblk 400.., uptodate folios + * donor: [ext1, ext1 + 1) written -> pblk 501, + * [ext1 + 1, ext2) hole, + * [ext2, ext2 + 2) unwritten -> pblk 503..504 + * + * Spacing donor extents by @stride ensures distinct pagecache folios on + * 16K/64K PAGE_SIZE kernels so dirtying ext1's folio does not make + * ext2's folio unreleasable (-EBUSY). + * + * Moving [ext1, ext2 + 2) exercises MEXT_COPY_DATA, left/right extent + * splits on orig, donor hole skipping, written preservation on orig, + * mark_unwritten=1 on donor, and page cache data preservation. + */ + i_size_write(orig, (loff_t)total_blks * MEXT_TEST_BLK_SIZE); + EXT4_I(orig)->i_disksize = (loff_t)total_blks * MEXT_TEST_BLK_SIZE; + i_size_write(donor, (loff_t)total_blks * MEXT_TEST_BLK_SIZE); + EXT4_I(donor)->i_disksize = (loff_t)total_blks * MEXT_TEST_BLK_SIZE; + + mext_insert_extent(test, orig, 0, total_blks, 400, false); + mext_insert_extent(test, donor, ext1, 1, 501, false); + mext_insert_extent(test, donor, ext2, 2, 503, true); + + for (lblk = 0; lblk < total_blks; lblk++) + mext_populate_folio_block(test, orig, lblk, 0xA0 + lblk); + + ret = ext4_move_extents(&ctx->orig_file, &ctx->donor_file, ext1, ext1, + ext2 + 2 - ext1, &moved_len); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, moved_len, 3ULL); + + /* Verify orig mappings: leading/hole/trailing unchanged; moved swapped */ + mext_assert_mapped_block(test, orig, 0, 400, EXT4_MAP_MAPPED); + mext_assert_mapped_block(test, orig, ext1, 501, EXT4_MAP_MAPPED); + mext_assert_mapped_block(test, orig, ext1 + 1, 400 + ext1 + 1, + EXT4_MAP_MAPPED); + mext_assert_mapped_block(test, orig, ext2, 503, EXT4_MAP_MAPPED); + mext_assert_mapped_block(test, orig, ext2 + 1, 504, EXT4_MAP_MAPPED); + mext_assert_mapped_block(test, orig, ext2 + 2, 400 + ext2 + 2, + EXT4_MAP_MAPPED); + + /* Donor's swapped extents are marked unwritten to avoid leaking data */ + mext_assert_mapped_block(test, donor, ext1, 400 + ext1, + EXT4_MAP_UNWRITTEN); + mext_assert_mapped_block(test, donor, ext2, 400 + ext2, + EXT4_MAP_UNWRITTEN); + mext_assert_mapped_block(test, donor, ext2 + 1, 400 + ext2 + 1, + EXT4_MAP_UNWRITTEN); + + /* Verify cached bytes in orig's moved folios were preserved & dirtied */ + for (i = 0; i < ARRAY_SIZE(moved_lblks); i++) { + loff_t pos; + struct folio *folio; + u8 *addr; + + lblk = moved_lblks[i]; + pos = (loff_t)lblk << orig->i_blkbits; + folio = filemap_get_folio(orig->i_mapping, pos >> PAGE_SHIFT); + KUNIT_ASSERT_FALSE(test, IS_ERR(folio)); + KUNIT_EXPECT_TRUE(test, folio_test_uptodate(folio)); + KUNIT_EXPECT_TRUE(test, folio_test_dirty(folio)); + addr = folio_address(folio); + KUNIT_EXPECT_EQ(test, addr[offset_in_folio(folio, pos)], + (u8)(0xA0 + lblk)); + folio_put(folio); + } +} + +static void test_move_extents_unwritten_orig_and_ebusy(struct kunit *test) +{ + struct mext_test_ctx *ctx = mext_setup_ctx(test); + struct inode *orig = ctx->orig_inode; + struct inode *donor = ctx->donor_inode; + ext4_lblk_t stride = max_t(ext4_lblk_t, 1, + PAGE_SIZE >> MEXT_TEST_BLK_BITS); + ext4_lblk_t ebusy_lblk = max_t(ext4_lblk_t, 2, stride); + ext4_lblk_t total_blks = ebusy_lblk + 2; + struct folio *donor_folio; + __u64 moved_len = 0; + int ret; + + /* + * Part 1: orig unwritten [0, 2) -> 600..601 (no pre-populated folios), + * donor written [0, 2) -> 700..701. Exercises MEXT_COPY_DATA through + * mext_folio_mkuptodate()'s non-uptodate unwritten buffer zeroing path. + */ + i_size_write(orig, (loff_t)total_blks * MEXT_TEST_BLK_SIZE); + EXT4_I(orig)->i_disksize = (loff_t)total_blks * MEXT_TEST_BLK_SIZE; + i_size_write(donor, (loff_t)total_blks * MEXT_TEST_BLK_SIZE); + EXT4_I(donor)->i_disksize = (loff_t)total_blks * MEXT_TEST_BLK_SIZE; + + mext_insert_extent(test, orig, 0, 2, 600, true); + mext_insert_extent(test, donor, 0, 2, 700, false); + + ret = ext4_move_extents(&ctx->orig_file, &ctx->donor_file, 0, 0, 2, + &moved_len); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, moved_len, 2ULL); + + mext_assert_mapped_block(test, orig, 0, 700, EXT4_MAP_UNWRITTEN); + mext_assert_mapped_block(test, orig, 1, 701, EXT4_MAP_UNWRITTEN); + mext_assert_mapped_block(test, donor, 0, 600, EXT4_MAP_UNWRITTEN); + mext_assert_mapped_block(test, donor, 1, 601, EXT4_MAP_UNWRITTEN); + + /* + * Part 2: non-releasable folio on donor triggers -EBUSY from + * filemap_release_folio() without altering extent mappings. + */ + mext_insert_extent(test, orig, ebusy_lblk, 1, 602, true); + mext_insert_extent(test, donor, ebusy_lblk, 1, 702, true); + + donor_folio = __filemap_get_folio(donor->i_mapping, + ((loff_t)ebusy_lblk << + donor->i_blkbits) >> PAGE_SHIFT, + FGP_CREAT | FGP_LOCK, GFP_KERNEL); + KUNIT_ASSERT_FALSE(test, IS_ERR(donor_folio)); + if (!folio_buffers(donor_folio)) + create_empty_buffers(donor_folio, MEXT_TEST_BLK_SIZE, 0); + folio_set_checked(donor_folio); + folio_unlock(donor_folio); + + ret = ext4_move_extents(&ctx->orig_file, &ctx->donor_file, + ebusy_lblk, ebusy_lblk, 1, &moved_len); + folio_clear_checked(donor_folio); + folio_put(donor_folio); + + KUNIT_EXPECT_EQ(test, ret, -EBUSY); + KUNIT_EXPECT_EQ(test, moved_len, 0ULL); + mext_assert_mapped_block(test, orig, ebusy_lblk, 602, + EXT4_MAP_UNWRITTEN); + mext_assert_mapped_block(test, donor, ebusy_lblk, 702, + EXT4_MAP_UNWRITTEN); +} + +static struct kunit_case move_extent_test_cases[] = { + KUNIT_CASE(test_double_data_sem_lock_order), + KUNIT_CASE(test_mext_check_validity_rejections), + KUNIT_CASE(test_mext_check_adjust_range), + KUNIT_CASE(test_move_extents_holes_and_unwritten), + KUNIT_CASE(test_move_extents_written_copy_data_and_split), + KUNIT_CASE(test_move_extents_unwritten_orig_and_ebusy), + {} +}; + +static struct kunit_suite move_extent_test_suite = { + .name = "ext4_move_extent_test", + .test_cases = move_extent_test_cases, +}; + +kunit_test_suites(&move_extent_test_suite); + +MODULE_DESCRIPTION("KUnit tests for ext4 move_extent"); +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/move_extent.c b/fs/ext4/move_extent.c index 948ef3f44df5eb..15f4126c5c5129 100644 --- a/fs/ext4/move_extent.c +++ b/fs/ext4/move_extent.c @@ -40,6 +40,7 @@ ext4_double_down_write_data_sem(struct inode *first, struct inode *second) down_write_nested(&EXT4_I(first)->i_data_sem, I_DATA_SEM_OTHER); } } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_double_down_write_data_sem); /** * ext4_double_up_write_data_sem - Release two inodes' write lock of i_data_sem @@ -55,6 +56,7 @@ ext4_double_up_write_data_sem(struct inode *orig_inode, up_write(&EXT4_I(orig_inode)->i_data_sem); up_write(&EXT4_I(donor_inode)->i_data_sem); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_double_up_write_data_sem); /* Grab and lock folio on both @inode1 and @inode2 by inode order. */ static int mext_folio_double_lock(struct inode *inode1, struct inode *inode2, @@ -667,3 +669,23 @@ int ext4_move_extents(struct file *o_filp, struct file *d_filp, __u64 orig_blk, unlock_two_nondirectories(orig_inode, donor_inode); return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_move_extents); + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +int ext4_mext_check_validity_test(struct inode *orig_inode, + struct inode *donor_inode) +{ + return mext_check_validity(orig_inode, donor_inode); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mext_check_validity_test); + +int ext4_mext_check_adjust_range_test(struct inode *orig_inode, + struct inode *donor_inode, + __u64 orig_start, __u64 donor_start, + __u64 *len) +{ + return mext_check_adjust_range(orig_inode, donor_inode, orig_start, + donor_start, len); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mext_check_adjust_range_test); +#endif diff --git a/fs/ext4/namei-test.c b/fs/ext4/namei-test.c new file mode 100644 index 00000000000000..f0192135fcf223 --- /dev/null +++ b/fs/ext4/namei-test.c @@ -0,0 +1,2349 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for ext4 directory lookup, HTree indexing, and namespace + * operations (fs/ext4/namei.c). + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_jbd2.h" +#include "xattr.h" +#include "namei.h" + +#define TEST_BLK_SIZE 1024 +#define TEST_BLK_BITS 10 +#define TEST_INODE_SIZE 256 +#define TEST_EXTRA_ISIZE (sizeof(struct ext4_inode) - \ + EXT4_GOOD_OLD_INODE_SIZE) +#define TEST_FIRST_PBLK 100 +#define TEST_MAX_BLOCKS 64 +#define TEST_MAX_LBLOCKS 16 +#define TEST_MAX_INODES 8 + +#define TEST_ROOT_INO EXT4_ROOT_INO +#define TEST_DIR_INO 12 +#define TEST_DIR2_INO 13 +#define TEST_SUBDIR_INO 14 +#define TEST_FILE1_INO 15 +#define TEST_FILE2_INO 16 +#define TEST_FILE3_INO 17 +#define TEST_CSUM_SEED 0x12345678U + +struct mock_block { + bool in_use; + struct buffer_head bh; + char data[TEST_BLK_SIZE] __aligned(8); +}; + +struct mock_inode_slot { + bool allocated; + struct ext4_inode_info ei; + struct buffer_head iloc_bh; + char raw_buf[TEST_INODE_SIZE] __aligned(8); + ext4_fsblk_t lblk_to_pblk[TEST_MAX_LBLOCKS]; +}; + +struct namei_test_ctx { + struct super_block sb; + struct ext4_sb_info sbi; + struct ext4_super_block es; + struct block_device bdev; + struct address_space bd_mapping; + struct buffer_head sb_bh; + + struct mock_inode_slot inodes[TEST_MAX_INODES]; + struct mock_block blocks[TEST_MAX_BLOCKS]; + + int fail_map_blocks; + int force_map_blocks_ret; + int fail_getblk; + int fail_get_inode_loc; + int fail_mark_iloc_dirty; + int fail_dirty_metadata; + int fail_iget; + + unsigned long last_iget_ino; + unsigned int orphan_add_calls; + unsigned long last_orphan_add_ino; + unsigned int orphan_del_calls; + unsigned long last_orphan_del_ino; + unsigned int dirty_metadata_calls; + unsigned int mark_inode_dirty_calls; +}; + +#ifdef CONFIG_QUOTA +static struct dquot __rcu **namei_test_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} + +static qsize_t *namei_test_get_reserved_space(struct inode *inode) +{ + return &EXT4_I(inode)->i_reserved_quota; +} + +static const struct dquot_operations namei_test_qops = { + .get_reserved_space = namei_test_get_reserved_space, +}; +#endif + +static const struct super_operations namei_test_sops = { +#ifdef CONFIG_QUOTA + .get_dquots = namei_test_get_dquots, +#endif +}; + +static void init_mock_inode_slot(struct namei_test_ctx *ctx, + struct mock_inode_slot *slot, + unsigned long ino, umode_t mode) +{ + struct inode *inode = &slot->ei.vfs_inode; + struct ext4_inode *raw_inode; + + memset(slot, 0, sizeof(*slot)); + slot->allocated = true; + + inode->i_sb = &ctx->sb; + inode->i_ino = ino; + inode->i_mode = mode; + inode->i_blkbits = TEST_BLK_BITS; + inode->i_mapping = &inode->i_data; + set_nlink(inode, S_ISDIR(mode) ? 2 : 1); + atomic_set(&inode->i_count, 1); + + spin_lock_init(&inode->i_lock); + init_rwsem(&inode->i_rwsem); + INIT_LIST_HEAD(&inode->i_io_list); + INIT_LIST_HEAD(&inode->i_wb_list); + INIT_LIST_HEAD(&inode->i_lru); + INIT_HLIST_NODE(&inode->i_hash); + /* + * Pre-set all I_DIRTY flags so mark_inode_dirty() is a fastpath + * no-op that does not touch superblock/bdi writeback lists. + */ + inode_state_set_raw(inode, I_DIRTY); + + init_rwsem(&slot->ei.xattr_sem); + init_rwsem(&slot->ei.i_data_sem); + INIT_LIST_HEAD(&slot->ei.i_orphan); + INIT_LIST_HEAD(&slot->ei.i_fc_list); + spin_lock_init(&slot->ei.i_fc_lock); + spin_lock_init(&slot->ei.i_raw_lock); + + slot->ei.i_extra_isize = TEST_EXTRA_ISIZE; + slot->ei.i_csum_seed = TEST_CSUM_SEED ^ (u32)ino; + slot->ei.i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + + slot->iloc_bh.b_data = slot->raw_buf; + slot->iloc_bh.b_size = TEST_INODE_SIZE; + slot->iloc_bh.b_blocknr = 10 + ino; + atomic_set(&slot->iloc_bh.b_count, 1); + set_buffer_uptodate(&slot->iloc_bh); + + raw_inode = (struct ext4_inode *)slot->raw_buf; + raw_inode->i_extra_isize = cpu_to_le16(TEST_EXTRA_ISIZE); +} + +static struct mock_inode_slot *find_inode_slot_by_ino(struct namei_test_ctx *ctx, + unsigned long ino) +{ + int i; + + for (i = 0; i < TEST_MAX_INODES; i++) { + if (ctx->inodes[i].allocated && + ctx->inodes[i].ei.vfs_inode.i_ino == ino) + return &ctx->inodes[i]; + } + return NULL; +} + +static struct mock_inode_slot *find_inode_slot(struct namei_test_ctx *ctx, + struct inode *inode) +{ + return find_inode_slot_by_ino(ctx, inode->i_ino); +} + +static struct inode *get_mock_inode(struct namei_test_ctx *ctx, + unsigned long ino) +{ + struct mock_inode_slot *slot = find_inode_slot_by_ino(ctx, ino); + + return slot ? &slot->ei.vfs_inode : NULL; +} + +static struct mock_block *get_mock_block(struct namei_test_ctx *ctx, + ext4_fsblk_t pblk) +{ + unsigned long idx; + + if (pblk < TEST_FIRST_PBLK) + return NULL; + idx = pblk - TEST_FIRST_PBLK; + if (idx >= TEST_MAX_BLOCKS) + return NULL; + return &ctx->blocks[idx]; +} + +static ext4_fsblk_t alloc_mock_pblk(struct namei_test_ctx *ctx) +{ + int i; + + for (i = 0; i < TEST_MAX_BLOCKS; i++) { + if (!ctx->blocks[i].in_use) { + ctx->blocks[i].in_use = true; + memset(ctx->blocks[i].data, 0, TEST_BLK_SIZE); + set_buffer_uptodate(&ctx->blocks[i].bh); + clear_buffer_verified(&ctx->blocks[i].bh); + return TEST_FIRST_PBLK + i; + } + } + return 0; +} + +static struct buffer_head *map_and_get_dir_bh(struct namei_test_ctx *ctx, + struct inode *inode, + ext4_lblk_t lblk) +{ + struct mock_inode_slot *slot = find_inode_slot(ctx, inode); + struct mock_block *blk; + ext4_fsblk_t pblk; + + if (!slot || lblk >= TEST_MAX_LBLOCKS) + return NULL; + pblk = slot->lblk_to_pblk[lblk]; + if (!pblk) { + pblk = alloc_mock_pblk(ctx); + if (!pblk) + return NULL; + slot->lblk_to_pblk[lblk] = pblk; + } + blk = get_mock_block(ctx, pblk); + return blk ? &blk->bh : NULL; +} + +static void init_mock_dentry(struct dentry *dentry, struct dentry *parent, + const char *name, struct inode *inode, + struct super_block *sb) +{ + memset(dentry, 0, sizeof(*dentry)); + spin_lock_init(&dentry->d_lock); + seqcount_spinlock_init(&dentry->d_seq, &dentry->d_lock); + INIT_HLIST_NODE(&dentry->d_sib); + INIT_HLIST_HEAD(&dentry->d_children); + INIT_HLIST_BL_NODE(&dentry->d_hash); + dentry->d_parent = parent ? parent : dentry; + dentry->d_sb = sb; + dentry->__d_name.name = (const unsigned char *)name; + dentry->__d_name.len = strlen(name); + if (inode) { + dentry->d_inode = inode; + dentry->d_flags = S_ISDIR(inode->i_mode) ? + DCACHE_DIRECTORY_TYPE : DCACHE_REGULAR_TYPE; + } else { + dentry->d_flags = DCACHE_MISS_TYPE; + } +} + +/* --- KUnit Static Stubs --- */ + +static int ext4_map_blocks_stub(handle_t *handle, struct inode *inode, + struct ext4_map_blocks *map, int flags) +{ + struct kunit *test = kunit_get_current_test(); + struct namei_test_ctx *ctx = test->priv; + struct mock_inode_slot *slot; + ext4_fsblk_t pblk; + + if (ctx->fail_map_blocks) + return ctx->fail_map_blocks; + if (ctx->force_map_blocks_ret) + return ctx->force_map_blocks_ret; + + slot = find_inode_slot(ctx, inode); + if (!slot || map->m_lblk >= TEST_MAX_LBLOCKS) + return -EFSCORRUPTED; + + pblk = slot->lblk_to_pblk[map->m_lblk]; + if (pblk) { + map->m_pblk = pblk; + map->m_len = 1; + map->m_flags = EXT4_MAP_MAPPED; + return 1; + } + + if (!(flags & EXT4_GET_BLOCKS_CREATE)) { + map->m_pblk = 0; + map->m_flags = 0; + return 0; + } + + pblk = alloc_mock_pblk(ctx); + if (!pblk) + return -ENOSPC; + + slot->lblk_to_pblk[map->m_lblk] = pblk; + map->m_pblk = pblk; + map->m_len = 1; + map->m_flags = EXT4_MAP_MAPPED | EXT4_MAP_NEW; + return 1; +} + +static struct buffer_head *ext4_getblk_stub(handle_t *handle, + struct inode *inode, + ext4_lblk_t block, int map_flags) +{ + struct kunit *test = kunit_get_current_test(); + struct namei_test_ctx *ctx = test->priv; + struct mock_inode_slot *slot; + struct mock_block *blk; + ext4_fsblk_t pblk; + + if (ctx->fail_getblk) + return ERR_PTR(ctx->fail_getblk); + + slot = find_inode_slot(ctx, inode); + if (!slot || block >= TEST_MAX_LBLOCKS) + return ERR_PTR(-EFSCORRUPTED); + + pblk = slot->lblk_to_pblk[block]; + if (!pblk) { + if (!(map_flags & EXT4_GET_BLOCKS_CREATE)) + return NULL; + pblk = alloc_mock_pblk(ctx); + if (!pblk) + return ERR_PTR(-ENOSPC); + slot->lblk_to_pblk[block] = pblk; + } + + blk = get_mock_block(ctx, pblk); + if (!blk) + return ERR_PTR(-EFSCORRUPTED); + + get_bh(&blk->bh); + return &blk->bh; +} + +static int ext4_get_inode_loc_stub(struct inode *inode, struct ext4_iloc *iloc) +{ + struct kunit *test = kunit_get_current_test(); + struct namei_test_ctx *ctx = test->priv; + struct mock_inode_slot *slot; + + if (ctx->fail_get_inode_loc) + return ctx->fail_get_inode_loc; + + slot = find_inode_slot(ctx, inode); + if (!slot) + return -ENOENT; + + get_bh(&slot->iloc_bh); + iloc->bh = &slot->iloc_bh; + iloc->offset = 0; + iloc->block_group = 0; + return 0; +} + +static int ext4_mark_iloc_dirty_stub(handle_t *handle, struct inode *inode, + struct ext4_iloc *iloc) +{ + struct kunit *test = kunit_get_current_test(); + struct namei_test_ctx *ctx = test->priv; + + brelse(iloc->bh); + iloc->bh = NULL; + if (ctx->fail_mark_iloc_dirty) + return ctx->fail_mark_iloc_dirty; + return 0; +} + +static int ext4_mark_inode_dirty_stub(handle_t *handle, struct inode *inode, + const char *func, unsigned int line) +{ + struct kunit *test = kunit_get_current_test(); + struct namei_test_ctx *ctx = test->priv; + + ctx->mark_inode_dirty_calls++; + if (ctx->fail_mark_iloc_dirty) + return ctx->fail_mark_iloc_dirty; + return 0; +} + +static int ext4_handle_dirty_metadata_stub(const char *where, unsigned int line, + handle_t *handle, + struct inode *inode, + struct buffer_head *bh) +{ + struct kunit *test = kunit_get_current_test(); + struct namei_test_ctx *ctx = test->priv; + + ctx->dirty_metadata_calls++; + if (ctx->fail_dirty_metadata) + return ctx->fail_dirty_metadata; + return 0; +} + +static struct inode *ext4_iget_stub(struct super_block *sb, unsigned long ino, + ext4_iget_flags flags, + const char *function, unsigned int line) +{ + struct kunit *test = kunit_get_current_test(); + struct namei_test_ctx *ctx = test->priv; + + ctx->last_iget_ino = ino; + if (ctx->fail_iget) + return ERR_PTR(ctx->fail_iget); + return ERR_PTR(-ENOENT); +} + +static int ext4_orphan_add_stub(handle_t *handle, struct inode *inode) +{ + struct kunit *test = kunit_get_current_test(); + struct namei_test_ctx *ctx = test->priv; + + ctx->orphan_add_calls++; + ctx->last_orphan_add_ino = inode->i_ino; + if (list_empty(&EXT4_I(inode)->i_orphan)) + list_add(&EXT4_I(inode)->i_orphan, &ctx->sbi.s_orphan); + return 0; +} + +static int ext4_orphan_del_stub(handle_t *handle, struct inode *inode) +{ + struct kunit *test = kunit_get_current_test(); + struct namei_test_ctx *ctx = test->priv; + + ctx->orphan_del_calls++; + ctx->last_orphan_del_ino = inode->i_ino; + list_del_init(&EXT4_I(inode)->i_orphan); + return 0; +} + +static int namei_test_init(struct kunit *test) +{ + struct namei_test_ctx *ctx; + int i; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx); + test->priv = ctx; + + ctx->sb.s_blocksize = TEST_BLK_SIZE; + ctx->sb.s_blocksize_bits = TEST_BLK_BITS; + ctx->sb.s_magic = EXT4_SUPER_MAGIC; + ctx->sb.s_maxbytes = MAX_LFS_FILESIZE; + ctx->sb.s_time_gran = 1; + ctx->sb.s_op = &namei_test_sops; + ctx->sb.s_fs_info = &ctx->sbi; + ctx->sb.s_user_ns = &init_user_ns; + ctx->sb.s_bdev = &ctx->bdev; +#ifdef CONFIG_FS_ENCRYPTION + ctx->sb.s_cop = &ext4_cryptops; +#endif +#ifdef CONFIG_QUOTA + ctx->sb.dq_op = &namei_test_qops; +#endif + ctx->bdev.bd_mapping = &ctx->bd_mapping; + bdev_set_flag(&ctx->bdev, BD_READ_ONLY); + init_rwsem(&ctx->sb.s_umount); + strscpy(ctx->sb.s_id, "ext4_namei_kunit", sizeof(ctx->sb.s_id)); + + ctx->sbi.s_sb = &ctx->sb; + ctx->sbi.s_es = &ctx->es; + ctx->sbi.s_sbh = &ctx->sb_bh; + ctx->sbi.s_inode_size = TEST_INODE_SIZE; + ctx->sbi.s_first_ino = EXT4_GOOD_OLD_FIRST_INO; + ctx->sbi.s_want_extra_isize = TEST_EXTRA_ISIZE; + ctx->sbi.s_def_hash_version = DX_HASH_HALF_MD4; + ctx->sbi.s_hash_unsigned = 3; + ctx->sbi.s_hash_seed[0] = 0x11223344U; + ctx->sbi.s_hash_seed[1] = 0x55667788U; + ctx->sbi.s_hash_seed[2] = 0x99aabbccU; + ctx->sbi.s_hash_seed[3] = 0xddeeff00U; + ctx->sbi.s_csum_seed = TEST_CSUM_SEED; + set_opt(&ctx->sb, ERRORS_CONT); + spin_lock_init(&ctx->sbi.s_bdev_wb_lock); + spin_lock_init(&ctx->sbi.s_error_lock); + spin_lock_init(&ctx->sbi.s_md_lock); + mutex_init(&ctx->sbi.s_orphan_lock); + INIT_LIST_HEAD(&ctx->sbi.s_orphan); + ratelimit_state_init(&ctx->sbi.s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&ctx->sbi.s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&ctx->sbi.s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + + ctx->es.s_inodes_count = cpu_to_le32(1024); + ctx->es.s_first_ino = cpu_to_le32(EXT4_GOOD_OLD_FIRST_INO); + ctx->es.s_inode_size = cpu_to_le16(TEST_INODE_SIZE); + ctx->es.s_min_extra_isize = cpu_to_le16(TEST_EXTRA_ISIZE); + ctx->es.s_want_extra_isize = cpu_to_le16(TEST_EXTRA_ISIZE); + ctx->es.s_feature_incompat = cpu_to_le32(EXT4_FEATURE_INCOMPAT_FILETYPE); + ctx->es.s_feature_compat = cpu_to_le32(EXT4_FEATURE_COMPAT_DIR_INDEX); + + ctx->sb_bh.b_data = (char *)&ctx->es; + ctx->sb_bh.b_size = TEST_BLK_SIZE; + ctx->sb_bh.b_blocknr = 1; + atomic_set(&ctx->sb_bh.b_count, 1); + set_buffer_uptodate(&ctx->sb_bh); + + for (i = 0; i < TEST_MAX_BLOCKS; i++) { + struct buffer_head *bh = &ctx->blocks[i].bh; + + bh->b_data = ctx->blocks[i].data; + bh->b_size = TEST_BLK_SIZE; + bh->b_blocknr = TEST_FIRST_PBLK + i; + atomic_set(&bh->b_count, 1); + set_buffer_uptodate(bh); + } + + init_mock_inode_slot(ctx, &ctx->inodes[0], TEST_ROOT_INO, + S_IFDIR | 0755); + init_mock_inode_slot(ctx, &ctx->inodes[1], TEST_DIR_INO, + S_IFDIR | 0755); + init_mock_inode_slot(ctx, &ctx->inodes[2], TEST_DIR2_INO, + S_IFDIR | 0755); + init_mock_inode_slot(ctx, &ctx->inodes[3], TEST_SUBDIR_INO, + S_IFDIR | 0755); + init_mock_inode_slot(ctx, &ctx->inodes[4], TEST_FILE1_INO, + S_IFREG | 0644); + init_mock_inode_slot(ctx, &ctx->inodes[5], TEST_FILE2_INO, + S_IFREG | 0644); + init_mock_inode_slot(ctx, &ctx->inodes[6], TEST_FILE3_INO, + S_IFLNK | 0777); + + kunit_activate_static_stub(test, ext4_map_blocks, ext4_map_blocks_stub); + kunit_activate_static_stub(test, ext4_getblk, ext4_getblk_stub); + kunit_activate_static_stub(test, ext4_get_inode_loc, + ext4_get_inode_loc_stub); + kunit_activate_static_stub(test, ext4_mark_iloc_dirty, + ext4_mark_iloc_dirty_stub); + kunit_activate_static_stub(test, __ext4_mark_inode_dirty, + ext4_mark_inode_dirty_stub); + kunit_activate_static_stub(test, __ext4_handle_dirty_metadata, + ext4_handle_dirty_metadata_stub); + kunit_activate_static_stub(test, __ext4_iget, ext4_iget_stub); + kunit_activate_static_stub(test, ext4_orphan_add, ext4_orphan_add_stub); + kunit_activate_static_stub(test, ext4_orphan_del, ext4_orphan_del_stub); + + return 0; +} + +static void namei_test_exit(struct kunit *test) +{ + struct namei_test_ctx *ctx = test->priv; + + if (!ctx) + return; +#if IS_ENABLED(CONFIG_UNICODE) + utf8_unload(ctx->sb.s_encoding); + ctx->sb.s_encoding = NULL; +#endif +} + +/* + * Test 1: Directory leaf tail initialization, checksum computation, and + * verification (ext4_initialize_dirent_tail, ext4_dirblock_csum_verify, + * ext4_handle_dirty_dirblock). + */ +static void test_namei_dirent_tail_and_csum(struct kunit *test) +{ + struct namei_test_ctx *ctx = test->priv; + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct buffer_head *bh; + struct ext4_dir_entry_tail *t; + int err; + + bh = map_and_get_dir_bh(ctx, dir, 0); + KUNIT_ASSERT_NOT_NULL(test, bh); + + /* Without METADATA_CSUM, verification always succeeds */ + KUNIT_EXPECT_EQ(test, ext4_dirblock_csum_verify(dir, bh), 1); + + /* Enable METADATA_CSUM */ + ctx->es.s_feature_ro_compat |= + cpu_to_le32(EXT4_FEATURE_RO_COMPAT_METADATA_CSUM); + + /* Uninitialized tail fails verification */ + KUNIT_EXPECT_EQ(test, ext4_dirblock_csum_verify(dir, bh), 0); + + /* Initialize directory block and tail, then compute csum */ + err = ext4_init_dirblock(NULL, dir, bh, TEST_ROOT_INO, NULL, 0); + KUNIT_ASSERT_EQ(test, err, 0); + + t = EXT4_DIRENT_TAIL(bh->b_data, TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, le32_to_cpu(t->det_reserved_zero1), 0U); + KUNIT_EXPECT_EQ(test, le16_to_cpu(t->det_rec_len), + sizeof(struct ext4_dir_entry_tail)); + KUNIT_EXPECT_EQ(test, t->det_reserved_zero2, 0); + KUNIT_EXPECT_EQ(test, t->det_reserved_ft, EXT4_FT_DIR_CSUM); + KUNIT_EXPECT_EQ(test, ext4_dirblock_csum_verify(dir, bh), 1); + + /* Flip a bit in the directory data -> checksum mismatch */ + bh->b_data[0] ^= 0x01; + KUNIT_EXPECT_EQ(test, ext4_dirblock_csum_verify(dir, bh), 0); + bh->b_data[0] ^= 0x01; + KUNIT_EXPECT_EQ(test, ext4_dirblock_csum_verify(dir, bh), 1); + + /* Corrupt tail reserved_ft -> get_dirent_tail() rejects it */ + t->det_reserved_ft = EXT4_FT_REG_FILE; + KUNIT_EXPECT_EQ(test, ext4_dirblock_csum_verify(dir, bh), 0); + ext4_initialize_dirent_tail(bh, TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, ext4_handle_dirty_dirblock(NULL, dir, bh), 0); + KUNIT_EXPECT_EQ(test, ext4_dirblock_csum_verify(dir, bh), 1); +} + +/* + * Test 2: HTree dx_entry accessors, dx_root_limit / dx_node_limit, and + * dx_root / dx_node metadata checksum verification (ext4_dx_csum_set_test, + * ext4_dx_csum_verify_test). + */ +static void test_namei_dx_helpers_and_csum(struct kunit *test) +{ + struct namei_test_ctx *ctx = test->priv; + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct buffer_head *root_bh, *node_bh; + struct dx_root *root; + struct dx_node *node; + struct dx_entry *entries; + + root_bh = map_and_get_dir_bh(ctx, dir, 0); + node_bh = map_and_get_dir_bh(ctx, dir, 1); + KUNIT_ASSERT_NOT_NULL(test, root_bh); + KUNIT_ASSERT_NOT_NULL(test, node_bh); + + /* Check limits without METADATA_CSUM (1024B block) */ + /* Root: (1024 - 12 - 12 - 8) / 8 = 124 */ + KUNIT_EXPECT_EQ(test, + dx_root_limit(dir, sizeof(struct dx_root_info)), 124U); + /* Node: (1024 - 8) / 8 = 127 */ + KUNIT_EXPECT_EQ(test, dx_node_limit(dir), 127U); + + /* Enable METADATA_CSUM -> 1 fewer entry for 8-byte dx_tail */ + ctx->es.s_feature_ro_compat |= + cpu_to_le32(EXT4_FEATURE_RO_COMPAT_METADATA_CSUM); + KUNIT_EXPECT_EQ(test, + dx_root_limit(dir, sizeof(struct dx_root_info)), 123U); + KUNIT_EXPECT_EQ(test, dx_node_limit(dir), 126U); + + /* Set up a valid dx_root in root_bh */ + root = (struct dx_root *)root_bh->b_data; + root->dot.inode = cpu_to_le32(dir->i_ino); + root->dot.rec_len = ext4_rec_len_to_disk(12, TEST_BLK_SIZE); + root->dot.name_len = 1; + root->dot.file_type = EXT4_FT_DIR; + strscpy(root->dot_name, ".", sizeof(root->dot_name)); + + root->dotdot.inode = cpu_to_le32(TEST_ROOT_INO); + root->dotdot.rec_len = ext4_rec_len_to_disk(TEST_BLK_SIZE - 12, + TEST_BLK_SIZE); + root->dotdot.name_len = 2; + root->dotdot.file_type = EXT4_FT_DIR; + strscpy(root->dotdot_name, "..", sizeof(root->dotdot_name)); + + root->info.info_length = sizeof(struct dx_root_info); + root->info.hash_version = DX_HASH_HALF_MD4; + entries = root->entries; + dx_set_limit(entries, dx_root_limit(dir, sizeof(struct dx_root_info))); + dx_set_count(entries, 2); + dx_set_block(entries + 0, 0xf0000001U); /* high 4 bits masked */ + dx_set_hash(entries + 1, 0x80001234U); + dx_set_block(entries + 1, 2); + + KUNIT_EXPECT_EQ(test, dx_get_limit(entries), 123U); + KUNIT_EXPECT_EQ(test, dx_get_count(entries), 2U); + KUNIT_EXPECT_EQ(test, dx_get_block(entries + 0), 1U); + KUNIT_EXPECT_EQ(test, dx_get_hash(entries + 1), 0x80001234U); + KUNIT_EXPECT_EQ(test, dx_get_block(entries + 1), 2U); + + ext4_dx_csum_set_test(dir, (struct ext4_dir_entry *)root_bh->b_data); + KUNIT_EXPECT_EQ(test, + ext4_dx_csum_verify_test(dir, + (struct ext4_dir_entry *)root_bh->b_data), 1); + + /* Corrupt hash -> csum verify fails */ + dx_set_hash(entries + 1, 0x80001235U); + KUNIT_EXPECT_EQ(test, + ext4_dx_csum_verify_test(dir, + (struct ext4_dir_entry *)root_bh->b_data), 0); + dx_set_hash(entries + 1, 0x80001234U); + KUNIT_EXPECT_EQ(test, + ext4_dx_csum_verify_test(dir, + (struct ext4_dir_entry *)root_bh->b_data), 1); + + /* Overflow limit -> no space for csum fails */ + dx_set_limit(entries, 200); + KUNIT_EXPECT_EQ(test, + ext4_dx_csum_verify_test(dir, + (struct ext4_dir_entry *)root_bh->b_data), 0); + + /* Set up a valid dx_node in node_bh */ + node = (struct dx_node *)node_bh->b_data; + node->fake.rec_len = ext4_rec_len_to_disk(TEST_BLK_SIZE, TEST_BLK_SIZE); + dx_set_limit(node->entries, dx_node_limit(dir)); + dx_set_count(node->entries, 2); + dx_set_block(node->entries + 0, 3); + dx_set_hash(node->entries + 1, 0x40000000U); + dx_set_block(node->entries + 1, 4); + + ext4_dx_csum_set_test(dir, (struct ext4_dir_entry *)node_bh->b_data); + KUNIT_EXPECT_EQ(test, + ext4_dx_csum_verify_test(dir, + (struct ext4_dir_entry *)node_bh->b_data), 1); + + /* Corrupt fake.rec_len -> get_dx_countlimit returns NULL */ + node->fake.rec_len = ext4_rec_len_to_disk(12, TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, + ext4_dx_csum_verify_test(dir, + (struct ext4_dir_entry *)node_bh->b_data), 0); +} + +/* + * Test 3: Parameterized tests for __ext4_read_dirblock (ext4_read_dirblock_test). + */ +enum read_dirblock_case_id { + RDB_VALID_LEAF, + RDB_VALID_INDEX, + RDB_HOLE_ALLOWED_EITHER, + RDB_PAST_ISIZE, + RDB_BREAD_EIO, + RDB_HOLE_AT_BLOCK0, + RDB_HOLE_FOR_HTREE_LEAF, + RDB_LEAF_INSTEAD_OF_INDEX, + RDB_BAD_LEAF_CSUM, + RDB_BAD_INDEX_CSUM, +}; + +struct read_dirblock_param { + const char *desc; + enum read_dirblock_case_id id; + ext4_lblk_t block; + enum dirblock_type type; + int expected_err; + bool expect_null; +}; + +static const struct read_dirblock_param read_dirblock_params[] = { + { + .desc = "valid leaf block with metadata_csum", + .id = RDB_VALID_LEAF, + .block = 0, + .type = DIRENT, + .expected_err = 0, + }, + { + .desc = "valid dx_root index block with metadata_csum", + .id = RDB_VALID_INDEX, + .block = 0, + .type = INDEX, + .expected_err = 0, + }, + { + .desc = "hole at block > 0 with EITHER returns NULL", + .id = RDB_HOLE_ALLOWED_EITHER, + .block = 1, + .type = EITHER, + .expected_err = 0, + .expect_null = true, + }, + { + .desc = "reading block past i_size returns -EFSCORRUPTED", + .id = RDB_PAST_ISIZE, + .block = 2, + .type = EITHER, + .expected_err = -EFSCORRUPTED, + }, + { + .desc = "ext4_bread -EIO error propagates", + .id = RDB_BREAD_EIO, + .block = 0, + .type = DIRENT, + .expected_err = -EIO, + }, + { + .desc = "hole at block 0 returns -EFSCORRUPTED", + .id = RDB_HOLE_AT_BLOCK0, + .block = 0, + .type = EITHER, + .expected_err = -EFSCORRUPTED, + }, + { + .desc = "hole for DIRENT_HTREE returns -EFSCORRUPTED", + .id = RDB_HOLE_FOR_HTREE_LEAF, + .block = 1, + .type = DIRENT_HTREE, + .expected_err = -EFSCORRUPTED, + }, + { + .desc = "leaf block found when expecting INDEX returns -EFSCORRUPTED", + .id = RDB_LEAF_INSTEAD_OF_INDEX, + .block = 1, + .type = INDEX, + .expected_err = -EFSCORRUPTED, + }, + { + .desc = "corrupted leaf checksum returns -EFSBADCRC", + .id = RDB_BAD_LEAF_CSUM, + .block = 0, + .type = DIRENT, + .expected_err = -EFSBADCRC, + }, + { + .desc = "corrupted index checksum returns -EFSBADCRC", + .id = RDB_BAD_INDEX_CSUM, + .block = 0, + .type = INDEX, + .expected_err = -EFSBADCRC, + }, +}; + +static void read_dirblock_get_desc(const struct read_dirblock_param *p, + char *desc) +{ + strscpy(desc, p->desc, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(read_dirblock, read_dirblock_params, read_dirblock_get_desc); + +static void test_namei_read_dirblock(struct kunit *test) +{ + const struct read_dirblock_param *p = test->param_value; + struct namei_test_ctx *ctx = test->priv; + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct buffer_head *bh, *res; + struct dx_root *root; + + ctx->es.s_feature_ro_compat |= + cpu_to_le32(EXT4_FEATURE_RO_COMPAT_METADATA_CSUM); + dir->i_size = 2 * TEST_BLK_SIZE; + + switch (p->id) { + case RDB_VALID_LEAF: + bh = map_and_get_dir_bh(ctx, dir, 0); + KUNIT_ASSERT_NOT_NULL(test, bh); + KUNIT_ASSERT_EQ(test, + ext4_init_dirblock(NULL, dir, bh, TEST_ROOT_INO, + NULL, 0), 0); + clear_buffer_verified(bh); + break; + case RDB_VALID_INDEX: + case RDB_BAD_INDEX_CSUM: + ext4_set_inode_flag(dir, EXT4_INODE_INDEX); + bh = map_and_get_dir_bh(ctx, dir, 0); + KUNIT_ASSERT_NOT_NULL(test, bh); + root = (struct dx_root *)bh->b_data; + root->dot.inode = cpu_to_le32(dir->i_ino); + root->dot.rec_len = ext4_rec_len_to_disk(12, TEST_BLK_SIZE); + root->dot.name_len = 1; + strscpy(root->dot_name, ".", sizeof(root->dot_name)); + root->dotdot.inode = cpu_to_le32(TEST_ROOT_INO); + root->dotdot.rec_len = ext4_rec_len_to_disk(TEST_BLK_SIZE - 12, + TEST_BLK_SIZE); + root->dotdot.name_len = 2; + strscpy(root->dotdot_name, "..", sizeof(root->dotdot_name)); + root->info.info_length = sizeof(struct dx_root_info); + root->info.hash_version = DX_HASH_HALF_MD4; + dx_set_limit(root->entries, + dx_root_limit(dir, sizeof(struct dx_root_info))); + dx_set_count(root->entries, 1); + dx_set_block(root->entries, 1); + ext4_dx_csum_set_test(dir, (struct ext4_dir_entry *)bh->b_data); + if (p->id == RDB_BAD_INDEX_CSUM) + dx_set_block(root->entries, 99); + clear_buffer_verified(bh); + break; + case RDB_HOLE_ALLOWED_EITHER: + case RDB_PAST_ISIZE: + case RDB_HOLE_AT_BLOCK0: + case RDB_HOLE_FOR_HTREE_LEAF: + break; + case RDB_BREAD_EIO: + ctx->fail_getblk = -EIO; + break; + case RDB_LEAF_INSTEAD_OF_INDEX: + ext4_set_inode_flag(dir, EXT4_INODE_INDEX); + bh = map_and_get_dir_bh(ctx, dir, 1); + KUNIT_ASSERT_NOT_NULL(test, bh); + KUNIT_ASSERT_EQ(test, + ext4_init_dirblock(NULL, dir, bh, TEST_ROOT_INO, + NULL, 0), 0); + clear_buffer_verified(bh); + break; + case RDB_BAD_LEAF_CSUM: + bh = map_and_get_dir_bh(ctx, dir, 0); + KUNIT_ASSERT_NOT_NULL(test, bh); + KUNIT_ASSERT_EQ(test, + ext4_init_dirblock(NULL, dir, bh, TEST_ROOT_INO, + NULL, 0), 0); + bh->b_data[0] ^= 0xff; + clear_buffer_verified(bh); + break; + } + + res = ext4_read_dirblock_test(dir, p->block, p->type); + if (p->expected_err) { + KUNIT_EXPECT_TRUE(test, IS_ERR(res)); + KUNIT_EXPECT_EQ(test, PTR_ERR(res), p->expected_err); + } else if (p->expect_null) { + KUNIT_EXPECT_NULL(test, res); + } else { + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(res)); + KUNIT_EXPECT_TRUE(test, buffer_verified(res)); + brelse(res); + } +} + +/* + * Test 4: Directory initialization and block appending (ext4_init_new_dir, + * ext4_append_test, s_max_dir_size_kb limit, already-allocated block check, + * and ext4_init_dirblock with inline_buf conversion data). + */ +static void test_namei_append_and_init_dir(struct kunit *test) +{ + struct namei_test_ctx *ctx = test->priv; + struct inode *root_dir = get_mock_inode(ctx, TEST_ROOT_INO); + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct buffer_head *bh; + struct ext4_dir_entry_2 *de; + char inline_entries[64]; + ext4_lblk_t lblk = 0; + int err; + + ctx->es.s_feature_ro_compat |= + cpu_to_le32(EXT4_FEATURE_RO_COMPAT_METADATA_CSUM); + + err = ext4_init_new_dir(NULL, root_dir, dir); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, dir->i_nlink, 2U); + KUNIT_EXPECT_EQ(test, dir->i_size, (loff_t)TEST_BLK_SIZE); + + /* Append a second block (lblk 1) */ + bh = ext4_append_test(NULL, dir, &lblk); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(bh)); + KUNIT_EXPECT_EQ(test, lblk, 1U); + KUNIT_EXPECT_EQ(test, dir->i_size, (loff_t)(2 * TEST_BLK_SIZE)); + brelse(bh); + + /* Enforce s_max_dir_size_kb limit -> -ENOSPC */ + ctx->sbi.s_max_dir_size_kb = 2; + bh = ext4_append_test(NULL, dir, &lblk); + KUNIT_EXPECT_TRUE(test, IS_ERR(bh)); + KUNIT_EXPECT_EQ(test, PTR_ERR(bh), -ENOSPC); + ctx->sbi.s_max_dir_size_kb = 0; + + /* Pre-allocated logical block at append target -> -EFSCORRUPTED */ + ctx->force_map_blocks_ret = 1; + bh = ext4_append_test(NULL, dir, &lblk); + KUNIT_EXPECT_TRUE(test, IS_ERR(bh)); + KUNIT_EXPECT_EQ(test, PTR_ERR(bh), -EFSCORRUPTED); + ctx->force_map_blocks_ret = 0; + + /* Test ext4_init_dirblock with non-NULL inline_buf */ + memset(inline_entries, 0, sizeof(inline_entries)); + de = (struct ext4_dir_entry_2 *)inline_entries; + de->inode = cpu_to_le32(TEST_FILE1_INO); + de->name_len = 3; + de->file_type = EXT4_FT_REG_FILE; + memcpy(de->name, "foo", 3); + de->rec_len = ext4_rec_len_to_disk(sizeof(inline_entries), + TEST_BLK_SIZE); + + bh = map_and_get_dir_bh(ctx, dir, 1); + KUNIT_ASSERT_NOT_NULL(test, bh); + err = ext4_init_dirblock(NULL, dir, bh, TEST_ROOT_INO, + inline_entries, sizeof(inline_entries)); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ext4_dirblock_csum_verify(dir, bh), 1); + + /* Verify '.', '..', and 'foo' in the initialized block */ + de = (struct ext4_dir_entry_2 *)bh->b_data; + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), dir->i_ino); + de = ext4_next_entry(de, TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), TEST_ROOT_INO); + de = ext4_next_entry(de, TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), TEST_FILE1_INO); + KUNIT_EXPECT_EQ(test, de->name_len, 3); + KUNIT_EXPECT_MEMEQ(test, de->name, "foo", 3); + KUNIT_EXPECT_EQ(test, ext4_rec_len_from_disk(de->rec_len, TEST_BLK_SIZE), + TEST_BLK_SIZE - 24 - + (int)sizeof(struct ext4_dir_entry_tail)); +} + +/* + * Test 5: Directory entry destination search, insertion, linear lookup, and + * deletion (ext4_find_dest_de, ext4_insert_dentry, ext4_search_dir, + * ext4_delete_entry_test, ext4_generic_delete_entry). + */ +static void test_namei_search_insert_delete_dentry(struct kunit *test) +{ + struct namei_test_ctx *ctx = test->priv; + struct inode *root_dir = get_mock_inode(ctx, TEST_ROOT_INO); + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct inode *file2 = get_mock_inode(ctx, TEST_FILE2_INO); + struct buffer_head *bh; + struct ext4_dir_entry_2 *de = NULL, *res_de = NULL; + struct ext4_filename fname1, fname2; + struct qstr q1 = QSTR_INIT("alpha.txt", 9); + struct qstr q2 = QSTR_INIT("beta.txt", 8); + int csum_size = sizeof(struct ext4_dir_entry_tail); + int buf_size = TEST_BLK_SIZE - csum_size; + int err; + + ctx->es.s_feature_ro_compat |= + cpu_to_le32(EXT4_FEATURE_RO_COMPAT_METADATA_CSUM); + + KUNIT_ASSERT_EQ(test, ext4_init_new_dir(NULL, root_dir, dir), 0); + bh = map_and_get_dir_bh(ctx, dir, 0); + KUNIT_ASSERT_NOT_NULL(test, bh); + + KUNIT_ASSERT_EQ(test, ext4_fname_setup_filename(dir, &q1, 0, &fname1), 0); + KUNIT_ASSERT_EQ(test, ext4_fname_setup_filename(dir, &q2, 0, &fname2), 0); + + /* Find space and insert alpha.txt */ + err = ext4_find_dest_de(dir, bh, bh->b_data, buf_size, &fname1, &de); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_ASSERT_NOT_NULL(test, de); + ext4_insert_dentry(dir, file1, de, TEST_BLK_SIZE, &fname1); + KUNIT_ASSERT_EQ(test, ext4_handle_dirty_dirblock(NULL, dir, bh), 0); + + /* Duplicate insert of alpha.txt must return -EEXIST */ + err = ext4_find_dest_de(dir, bh, bh->b_data, buf_size, &fname1, &de); + KUNIT_EXPECT_EQ(test, err, -EEXIST); + + /* Insert beta.txt */ + err = ext4_find_dest_de(dir, bh, bh->b_data, buf_size, &fname2, &de); + KUNIT_ASSERT_EQ(test, err, 0); + ext4_insert_dentry(dir, file2, de, TEST_BLK_SIZE, &fname2); + KUNIT_ASSERT_EQ(test, ext4_handle_dirty_dirblock(NULL, dir, bh), 0); + + /* Search for both entries via ext4_search_dir */ + err = ext4_search_dir(bh, bh->b_data, buf_size, dir, &fname1, 0, + &res_de); + KUNIT_ASSERT_EQ(test, err, 1); + KUNIT_EXPECT_EQ(test, le32_to_cpu(res_de->inode), TEST_FILE1_INO); + KUNIT_EXPECT_EQ(test, res_de->file_type, EXT4_FT_REG_FILE); + + /* Delete alpha.txt via ext4_delete_entry_test (merges into '..') */ + err = ext4_delete_entry_test(NULL, dir, res_de, bh); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ext4_dirblock_csum_verify(dir, bh), 1); + + /* alpha.txt is gone, beta.txt is still present */ + KUNIT_EXPECT_EQ(test, + ext4_search_dir(bh, bh->b_data, buf_size, dir, &fname1, 0, + &res_de), 0); + KUNIT_EXPECT_EQ(test, + ext4_search_dir(bh, bh->b_data, buf_size, dir, &fname2, 0, + &res_de), 1); + + /* + * Test deleting the very first entry in a buffer (pde == NULL), + * which zeroes de->inode while preserving rec_len. + */ + de = (struct ext4_dir_entry_2 *)bh->b_data; + err = ext4_generic_delete_entry(dir, de, bh, bh->b_data, + TEST_BLK_SIZE, csum_size); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), 0U); + KUNIT_EXPECT_EQ(test, ext4_rec_len_from_disk(de->rec_len, TEST_BLK_SIZE), + 12); + + /* Deleting a pointer not in the buffer returns -ENOENT */ + err = ext4_generic_delete_entry(dir, + (struct ext4_dir_entry_2 *)(bh->b_data + 500), + bh, bh->b_data, TEST_BLK_SIZE, csum_size); + KUNIT_EXPECT_EQ(test, err, -ENOENT); + + ext4_fname_free_filename(&fname1); + ext4_fname_free_filename(&fname2); +} + +/* + * Test 6: Directory emptiness validation (ext4_empty_dir) across fresh, + * non-empty, deleted, corrupt, and multi-block directories. + */ +static void test_namei_empty_dir(struct kunit *test) +{ + struct namei_test_ctx *ctx = test->priv; + struct inode *root_dir = get_mock_inode(ctx, TEST_ROOT_INO); + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct dentry parent_dentry, file_dentry; + struct buffer_head *bh, *bh1; + struct ext4_dir_entry_2 *de = NULL; + ext4_lblk_t lblk; + + init_mock_dentry(&parent_dentry, NULL, "dir", dir, &ctx->sb); + init_mock_dentry(&file_dentry, &parent_dentry, "item", file1, &ctx->sb); + + /* Freshly initialized directory is empty */ + KUNIT_ASSERT_EQ(test, ext4_init_new_dir(NULL, root_dir, dir), 0); + KUNIT_EXPECT_TRUE(test, ext4_empty_dir(dir)); + + /* Truncated i_size < 24 bytes is rejected as non-empty (corrupt) */ + dir->i_size = 12; + KUNIT_EXPECT_FALSE(test, ext4_empty_dir(dir)); + dir->i_size = TEST_BLK_SIZE; + + /* Add an entry -> not empty */ + KUNIT_ASSERT_EQ(test, ext4_add_entry_test(NULL, &file_dentry, file1), 0); + KUNIT_EXPECT_FALSE(test, ext4_empty_dir(dir)); + + /* Delete the entry -> empty again */ + bh = ext4_find_entry_test(dir, &file_dentry.d_name, &de, NULL); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(bh)); + KUNIT_ASSERT_EQ(test, ext4_delete_entry_test(NULL, dir, de, bh), 0); + brelse(bh); + KUNIT_EXPECT_TRUE(test, ext4_empty_dir(dir)); + + /* Multi-block directory with a hole at block 1 and an empty block 2 */ + dir->i_size = 2 * TEST_BLK_SIZE; /* block 1 is unmapped (hole) */ + bh1 = ext4_append_test(NULL, dir, &lblk); /* appends block 2 */ + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(bh1)); + KUNIT_EXPECT_EQ(test, lblk, 2U); + de = (struct ext4_dir_entry_2 *)bh1->b_data; + de->inode = 0; + de->rec_len = ext4_rec_len_to_disk(TEST_BLK_SIZE, TEST_BLK_SIZE); + KUNIT_EXPECT_TRUE(test, ext4_empty_dir(dir)); + + /* Active entry in block 2 makes directory non-empty */ + de->inode = cpu_to_le32(TEST_FILE1_INO); + de->name_len = 1; + de->name[0] = 'x'; + KUNIT_EXPECT_FALSE(test, ext4_empty_dir(dir)); + de->inode = 0; + brelse(bh1); + + /* Corrupt '..' name in block 0 -> returns false */ + bh = map_and_get_dir_bh(ctx, dir, 0); + de = ext4_next_entry((struct ext4_dir_entry_2 *)bh->b_data, + TEST_BLK_SIZE); + de->name[1] = 'x'; + KUNIT_EXPECT_FALSE(test, ext4_empty_dir(dir)); + de->name[1] = '.'; + + /* Corrupt '.' inode number in block 0 -> returns false */ + de = (struct ext4_dir_entry_2 *)bh->b_data; + de->inode = cpu_to_le32(999); + KUNIT_EXPECT_FALSE(test, ext4_empty_dir(dir)); +} + +/* + * Test 7: HTree leaf splitting helpers: dx_make_map_test, dx_sort_map_test + * (exercising both combsort and bubble sort phases), dx_move_dirents_test, + * dx_pack_dirents_test, and dx_insert_block_test. + */ +static void test_namei_dx_map_pack_and_move(struct kunit *test) +{ + struct namei_test_ctx *ctx = test->priv; + struct inode *root_dir = get_mock_inode(ctx, TEST_ROOT_INO); + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct buffer_head *bh, *bh2; + struct dx_hash_info hinfo = {}; + struct dx_map_entry *map; + struct ext4_dir_entry_2 *de, *last_de; + struct dx_frame frame; + struct dx_entry entries[8]; + int i, count; + + KUNIT_ASSERT_EQ(test, ext4_init_new_dir(NULL, root_dir, dir), 0); + bh = map_and_get_dir_bh(ctx, dir, 0); + bh2 = map_and_get_dir_bh(ctx, dir, 1); + KUNIT_ASSERT_NOT_NULL(test, bh); + KUNIT_ASSERT_NOT_NULL(test, bh2); + + /* Insert 16 entries into block 0 so count >= 18 (triggers combsort) */ + for (i = 0; i < 16; i++) { + char name[16]; + struct qstr q; + struct ext4_filename fname; + + snprintf(name, sizeof(name), "entry_%02d", i); + q.name = (const unsigned char *)name; + q.len = strlen(name); + KUNIT_ASSERT_EQ(test, + ext4_fname_setup_filename(dir, &q, 0, &fname), 0); + KUNIT_ASSERT_EQ(test, + ext4_find_dest_de(dir, bh, bh->b_data, TEST_BLK_SIZE, + &fname, &de), 0); + ext4_insert_dentry(dir, file1, de, TEST_BLK_SIZE, &fname); + ext4_fname_free_filename(&fname); + } + + hinfo.hash_version = DX_HASH_HALF_MD4 + ctx->sbi.s_hash_unsigned; + hinfo.seed = ctx->sbi.s_hash_seed; + + map = (struct dx_map_entry *)(bh2->b_data + TEST_BLK_SIZE); + count = dx_make_map_test(dir, bh, &hinfo, map); + /* 2 ('.' and '..') + 16 = 18 entries */ + KUNIT_ASSERT_EQ(test, count, 18); + + map -= count; + dx_sort_map_test(map, count); + for (i = 1; i < count; i++) + KUNIT_EXPECT_LE(test, map[i - 1].hash, map[i].hash); + + /* Move the second half (9 entries) to bh2 and pack the first half */ + last_de = dx_move_dirents_test(dir, bh->b_data, bh2->b_data, + map + 9, 9, TEST_BLK_SIZE); + KUNIT_ASSERT_NOT_NULL(test, last_de); + last_de->rec_len = ext4_rec_len_to_disk( + bh2->b_data + TEST_BLK_SIZE - (char *)last_de, TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, + ext4_check_all_de(dir, bh2, bh2->b_data, TEST_BLK_SIZE), 0); + + last_de = dx_pack_dirents_test(dir, bh->b_data, TEST_BLK_SIZE); + KUNIT_ASSERT_NOT_NULL(test, last_de); + last_de->rec_len = ext4_rec_len_to_disk( + bh->b_data + TEST_BLK_SIZE - (char *)last_de, TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, + ext4_check_all_de(dir, bh, bh->b_data, TEST_BLK_SIZE), 0); + + /* Test dx_insert_block_test shifting entries in a dx_frame */ + memset(entries, 0, sizeof(entries)); + dx_set_limit(entries, 8); + dx_set_count(entries, 2); + dx_set_block(entries + 0, 1); + dx_set_hash(entries + 1, 0x80000000U); + dx_set_block(entries + 1, 2); + + frame.entries = entries; + frame.at = entries + 0; + dx_insert_block_test(&frame, 0x40000000U, 3); + KUNIT_EXPECT_EQ(test, dx_get_count(entries), 3U); + KUNIT_EXPECT_EQ(test, dx_get_hash(entries + 1), 0x40000000U); + KUNIT_EXPECT_EQ(test, dx_get_block(entries + 1), 3U); + KUNIT_EXPECT_EQ(test, dx_get_hash(entries + 2), 0x80000000U); + KUNIT_EXPECT_EQ(test, dx_get_block(entries + 2), 2U); +} + +/* + * Test 8: Parameterized tests for ext4_check_dx_root_test, dx_probe_test, and + * ext4_htree_next_block_test across valid 1-level / 2-level trees and 10 + * on-disk corruption cases. + */ +enum dx_probe_case_id { + DXP_VALID_1LEVEL, + DXP_VALID_2LEVEL_AND_NEXT, + DXP_DOT_BAD_NAMELEN, + DXP_DOT_BAD_NAME, + DXP_DOT_BAD_RECLEN, + DXP_DOTDOT_BAD_NAMELEN, + DXP_DOTDOT_BAD_NAME, + DXP_BAD_HASH_VERSION, + DXP_SIPHASH_WITHOUT_IN_DIRENT, + DXP_UNUSED_FLAGS_SET, + DXP_INDIRECT_LEVEL_TOO_DEEP, + DXP_BAD_ROOT_LIMIT, + DXP_ZERO_COUNT, + DXP_TREE_CYCLE, +}; + +struct dx_probe_param { + const char *desc; + enum dx_probe_case_id id; + bool check_dx_root_only; + bool expect_ok; +}; + +static const struct dx_probe_param dx_probe_params[] = { + { + .desc = "valid 1-level dx_root binary search probe", + .id = DXP_VALID_1LEVEL, + .expect_ok = true, + }, + { + .desc = "valid 2-level htree probe and ext4_htree_next_block", + .id = DXP_VALID_2LEVEL_AND_NEXT, + .expect_ok = true, + }, + { + .desc = "ext4_check_dx_root rejects dot name_len != 1", + .id = DXP_DOT_BAD_NAMELEN, + .check_dx_root_only = true, + .expect_ok = false, + }, + { + .desc = "ext4_check_dx_root rejects dot name != '.'", + .id = DXP_DOT_BAD_NAME, + .check_dx_root_only = true, + .expect_ok = false, + }, + { + .desc = "ext4_check_dx_root rejects dot rec_len >= blocksize", + .id = DXP_DOT_BAD_RECLEN, + .check_dx_root_only = true, + .expect_ok = false, + }, + { + .desc = "ext4_check_dx_root rejects dotdot name_len != 2", + .id = DXP_DOTDOT_BAD_NAMELEN, + .check_dx_root_only = true, + .expect_ok = false, + }, + { + .desc = "ext4_check_dx_root rejects dotdot name != '..'", + .id = DXP_DOTDOT_BAD_NAME, + .check_dx_root_only = true, + .expect_ok = false, + }, + { + .desc = "dx_probe rejects unrecognized hash_version", + .id = DXP_BAD_HASH_VERSION, + .expect_ok = false, + }, + { + .desc = "dx_probe rejects DX_HASH_SIPHASH when not hash_in_dirent", + .id = DXP_SIPHASH_WITHOUT_IN_DIRENT, + .expect_ok = false, + }, + { + .desc = "dx_probe rejects non-zero unused_flags & 1", + .id = DXP_UNUSED_FLAGS_SET, + .expect_ok = false, + }, + { + .desc = "dx_probe rejects indirect_levels >= ext4_dir_htree_level", + .id = DXP_INDIRECT_LEVEL_TOO_DEEP, + .expect_ok = false, + }, + { + .desc = "dx_probe rejects root limit mismatch", + .id = DXP_BAD_ROOT_LIMIT, + .expect_ok = false, + }, + { + .desc = "dx_probe rejects count == 0", + .id = DXP_ZERO_COUNT, + .expect_ok = false, + }, + { + .desc = "dx_probe detects tree cycle pointing back to block 0", + .id = DXP_TREE_CYCLE, + .expect_ok = false, + }, +}; + +static void dx_probe_get_desc(const struct dx_probe_param *p, char *desc) +{ + strscpy(desc, p->desc, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(dx_probe, dx_probe_params, dx_probe_get_desc); + +static void setup_valid_dx_root(struct inode *dir, struct buffer_head *bh) +{ + struct dx_root *root = (struct dx_root *)bh->b_data; + + memset(root, 0, TEST_BLK_SIZE); + root->dot.inode = cpu_to_le32(dir->i_ino); + root->dot.rec_len = ext4_rec_len_to_disk(12, TEST_BLK_SIZE); + root->dot.name_len = 1; + root->dot.file_type = EXT4_FT_DIR; + strscpy(root->dot_name, ".", sizeof(root->dot_name)); + + root->dotdot.inode = cpu_to_le32(TEST_ROOT_INO); + root->dotdot.rec_len = ext4_rec_len_to_disk(TEST_BLK_SIZE - 12, + TEST_BLK_SIZE); + root->dotdot.name_len = 2; + root->dotdot.file_type = EXT4_FT_DIR; + strscpy(root->dotdot_name, "..", sizeof(root->dotdot_name)); + + root->info.info_length = sizeof(struct dx_root_info); + root->info.hash_version = DX_HASH_HALF_MD4; + dx_set_limit(root->entries, + dx_root_limit(dir, sizeof(struct dx_root_info))); + dx_set_count(root->entries, 2); + dx_set_block(root->entries + 0, 1); + dx_set_hash(root->entries + 1, 0x80000000U); + dx_set_block(root->entries + 1, 2); +} + +static void test_namei_check_dx_root_and_probe(struct kunit *test) +{ + const struct dx_probe_param *p = test->param_value; + struct namei_test_ctx *ctx = test->priv; + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct buffer_head *bh0, *bh1; + struct dx_root *root; + struct dx_node *node; + struct dx_frame frames[EXT4_HTREE_LEVEL], *frame; + struct dx_hash_info hinfo = {}; + __u32 start_hash = 0; + + ext4_set_inode_flag(dir, EXT4_INODE_INDEX); + dir->i_size = 4 * TEST_BLK_SIZE; + bh0 = map_and_get_dir_bh(ctx, dir, 0); + KUNIT_ASSERT_NOT_NULL(test, bh0); + setup_valid_dx_root(dir, bh0); + root = (struct dx_root *)bh0->b_data; + + switch (p->id) { + case DXP_VALID_1LEVEL: + root->dotdot.rec_len = ext4_rec_len_to_disk(12, TEST_BLK_SIZE); + KUNIT_EXPECT_TRUE(test, ext4_check_dx_root_test(dir, root)); + root->dotdot.rec_len = ext4_rec_len_to_disk(TEST_BLK_SIZE - 12, + TEST_BLK_SIZE); + break; + case DXP_VALID_2LEVEL_AND_NEXT: + root->info.indirect_levels = 1; + bh1 = map_and_get_dir_bh(ctx, dir, 1); + KUNIT_ASSERT_NOT_NULL(test, bh1); + node = (struct dx_node *)bh1->b_data; + node->fake.rec_len = ext4_rec_len_to_disk(TEST_BLK_SIZE, + TEST_BLK_SIZE); + dx_set_limit(node->entries, dx_node_limit(dir)); + dx_set_count(node->entries, 2); + dx_set_block(node->entries + 0, 2); + /* Continuation hash (low bit 1) matching 0x40000000 */ + dx_set_hash(node->entries + 1, 0x40000001U); + dx_set_block(node->entries + 1, 3); + break; + case DXP_DOT_BAD_NAMELEN: + root->dotdot.rec_len = ext4_rec_len_to_disk(12, TEST_BLK_SIZE); + root->dot.name_len = 2; + break; + case DXP_DOT_BAD_NAME: + root->dotdot.rec_len = ext4_rec_len_to_disk(12, TEST_BLK_SIZE); + root->dot_name[0] = 'x'; + break; + case DXP_DOT_BAD_RECLEN: + root->dotdot.rec_len = ext4_rec_len_to_disk(12, TEST_BLK_SIZE); + root->dot.rec_len = ext4_rec_len_to_disk(TEST_BLK_SIZE, + TEST_BLK_SIZE); + break; + case DXP_DOTDOT_BAD_NAMELEN: + root->dotdot.rec_len = ext4_rec_len_to_disk(12, TEST_BLK_SIZE); + root->dotdot.name_len = 1; + break; + case DXP_DOTDOT_BAD_NAME: + root->dotdot.rec_len = ext4_rec_len_to_disk(12, TEST_BLK_SIZE); + root->dotdot_name[1] = 'x'; + break; + case DXP_BAD_HASH_VERSION: + root->info.hash_version = 99; + break; + case DXP_SIPHASH_WITHOUT_IN_DIRENT: + root->info.hash_version = DX_HASH_SIPHASH; + break; + case DXP_UNUSED_FLAGS_SET: + root->info.unused_flags = 1; + break; + case DXP_INDIRECT_LEVEL_TOO_DEEP: + root->info.indirect_levels = EXT4_HTREE_LEVEL_COMPAT; + break; + case DXP_BAD_ROOT_LIMIT: + dx_set_limit(root->entries, 50); + break; + case DXP_ZERO_COUNT: + dx_set_count(root->entries, 0); + break; + case DXP_TREE_CYCLE: + dx_set_block(root->entries + 0, 0); + break; + } + + if (p->check_dx_root_only) { + KUNIT_EXPECT_EQ(test, ext4_check_dx_root_test(dir, root), + p->expect_ok); + return; + } + + hinfo.hash = 0x40000000U; + frame = dx_probe_test(NULL, dir, &hinfo, frames); + if (!p->expect_ok) { + KUNIT_EXPECT_TRUE(test, IS_ERR(frame)); + KUNIT_EXPECT_EQ(test, PTR_ERR(frame), ERR_BAD_DX_DIR); + return; + } + + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(frame)); + if (p->id == DXP_VALID_1LEVEL) { + KUNIT_EXPECT_PTR_EQ(test, frame, &frames[0]); + KUNIT_EXPECT_EQ(test, dx_get_block(frame->at), 1U); + } else if (p->id == DXP_VALID_2LEVEL_AND_NEXT) { + KUNIT_EXPECT_PTR_EQ(test, frame, &frames[1]); + KUNIT_EXPECT_EQ(test, dx_get_block(frame->at), 2U); + + /* Advance to next leaf block matching continuation hash */ + KUNIT_EXPECT_EQ(test, + ext4_htree_next_block_test(dir, 0x40000000U, frame, + frames, &start_hash), 1); + KUNIT_EXPECT_EQ(test, start_hash, 0x40000001U); + KUNIT_EXPECT_EQ(test, dx_get_block(frame->at), 3U); + + /* Non-matching even hash stops traversal */ + KUNIT_EXPECT_EQ(test, + ext4_htree_next_block_test(dir, 0x40000000U, frame, + frames, NULL), 0); + } + dx_release_test(frames); +} + +/* + * Test 9: End-to-end HTree directory conversion (make_indexed_dir), multiple + * leaf splits (ext4_dx_add_entry / do_split), indexed lookup + * (ext4_dx_find_entry), and rb-tree population (ext4_htree_fill_tree). + */ +static void test_namei_add_find_and_htree_split(struct kunit *test) +{ + struct namei_test_ctx *ctx = test->priv; + struct inode *root_dir = get_mock_inode(ctx, TEST_ROOT_INO); + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct dentry *dentries; + struct dentry *parent_dentry, *child_dentry; + struct dir_private_info *dir_info; + struct file *dir_file; + __u32 curr_hash = 0, next_hash = 0; + int i, err, total_loaded = 0; + + dentries = kunit_kcalloc(test, 2, sizeof(*dentries), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dentries); + parent_dentry = &dentries[0]; + child_dentry = &dentries[1]; + dir_file = kunit_kzalloc(test, sizeof(*dir_file), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dir_file); + + ctx->es.s_feature_ro_compat |= + cpu_to_le32(EXT4_FEATURE_RO_COMPAT_METADATA_CSUM); + + KUNIT_ASSERT_EQ(test, ext4_init_new_dir(NULL, root_dir, dir), 0); + init_mock_dentry(parent_dentry, NULL, "dir", dir, &ctx->sb); + + /* + * Insert 60 entries into a 1024-byte block directory. + * Each entry takes 20 bytes (name_len = 10 -> rec_len = 20), so ~48 + * entries fit in block 0 before make_indexed_dir converts it into an + * HTree and subsequent insertions split leaves via ext4_dx_add_entry. + */ + for (i = 0; i < 60; i++) { + char name[16]; + + snprintf(name, sizeof(name), "file_%05d", i); + init_mock_dentry(child_dentry, parent_dentry, name, file1, + &ctx->sb); + err = ext4_add_entry_test(NULL, child_dentry, file1); + KUNIT_ASSERT_EQ_MSG(test, err, 0, "failed at entry %d", i); + } + + /* Verify the directory was converted to an HTree index */ + KUNIT_EXPECT_TRUE(test, ext4_test_inode_flag(dir, EXT4_INODE_INDEX)); + KUNIT_EXPECT_GE(test, dir->i_size, (loff_t)(3 * TEST_BLK_SIZE)); + + /* Adding a duplicate entry must return -EEXIST */ + init_mock_dentry(child_dentry, parent_dentry, "file_00025", file1, + &ctx->sb); + KUNIT_EXPECT_EQ(test, + ext4_add_entry_test(NULL, child_dentry, file1), + -EEXIST); + + /* Look up all 60 entries via ext4_find_entry_test (ext4_dx_find_entry) */ + for (i = 0; i < 60; i++) { + char name[16]; + struct qstr q; + struct ext4_dir_entry_2 *de = NULL; + struct buffer_head *bh; + + snprintf(name, sizeof(name), "file_%05d", i); + q.name = (const unsigned char *)name; + q.len = strlen(name); + bh = ext4_find_entry_test(dir, &q, &de, NULL); + KUNIT_ASSERT_FALSE_MSG(test, IS_ERR_OR_NULL(bh), + "missing entry %s", name); + KUNIT_ASSERT_NOT_NULL(test, de); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), TEST_FILE1_INO); + brelse(bh); + } + + /* Populate readdir rb-tree via ext4_htree_fill_tree */ + dir_file->f_inode = dir; + while (1) { + int cnt; + + dir_info = kzalloc_obj(*dir_info); + KUNIT_ASSERT_NOT_NULL(test, dir_info); + dir_file->private_data = dir_info; + cnt = ext4_htree_fill_tree(dir_file, curr_hash, 0, &next_hash); + KUNIT_ASSERT_GE(test, cnt, 0); + total_loaded += cnt; + ext4_htree_free_dir_info(dir_info); + if (next_hash == ~0U) + break; + curr_hash = next_hash; + } + /* 60 files + '.' + '..' = 62 total entries */ + KUNIT_EXPECT_EQ(test, total_loaded, 62); +} + +/* + * Test 10: HTree index level growth (splitting full dx_root into a 2-level + * tree with indirect_levels == 1), max htree level -ENOSPC enforcement, and + * corrupted dx_root fallback in __ext4_find_entry and __ext4_add_entry. + */ +static void test_namei_dx_index_level_growth_and_fallback(struct kunit *test) +{ + struct namei_test_ctx *ctx = test->priv; + struct inode *root_dir = get_mock_inode(ctx, TEST_ROOT_INO); + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct dentry parent_dentry, child_dentry; + struct buffer_head *bh0, *bh1, *found_bh; + struct dx_root *root; + struct ext4_dir_entry_2 *de = NULL; + unsigned int root_limit; + int i, err; + + ctx->es.s_feature_ro_compat |= + cpu_to_le32(EXT4_FEATURE_RO_COMPAT_METADATA_CSUM); + + KUNIT_ASSERT_EQ(test, ext4_init_new_dir(NULL, root_dir, dir), 0); + init_mock_dentry(&parent_dentry, NULL, "dir", dir, &ctx->sb); + + /* Set up a 1-level HTree where root->entries is completely full */ + ext4_set_inode_flag(dir, EXT4_INODE_INDEX); + dir->i_size = 2 * TEST_BLK_SIZE; + bh0 = map_and_get_dir_bh(ctx, dir, 0); + bh1 = map_and_get_dir_bh(ctx, dir, 1); + KUNIT_ASSERT_NOT_NULL(test, bh0); + KUNIT_ASSERT_NOT_NULL(test, bh1); + + setup_valid_dx_root(dir, bh0); + root = (struct dx_root *)bh0->b_data; + root_limit = dx_root_limit(dir, sizeof(struct dx_root_info)); + dx_set_limit(root->entries, root_limit); + dx_set_count(root->entries, root_limit); + /* Point every index entry at leaf block 1 in ascending hash order */ + for (i = 0; i < root_limit; i++) { + if (i > 0) + dx_set_hash(root->entries + i, (u32)i * 0x02000000U); + dx_set_block(root->entries + i, 1); + } + ext4_dx_csum_set_test(dir, (struct ext4_dir_entry *)bh0->b_data); + + /* Fill leaf block 1 completely so adding one more entry splits it */ + KUNIT_ASSERT_EQ(test, + ext4_init_dirblock(NULL, dir, bh1, TEST_ROOT_INO, NULL, 0), 0); + for (i = 0; i < 60; i++) { + char name[16]; + struct qstr q; + struct ext4_filename fname; + + snprintf(name, sizeof(name), "leaf_%05d", i); + q.name = (const unsigned char *)name; + q.len = strlen(name); + KUNIT_ASSERT_EQ(test, + ext4_fname_setup_filename(dir, &q, 0, &fname), 0); + err = ext4_find_dest_de(dir, bh1, bh1->b_data, + TEST_BLK_SIZE - + sizeof(struct ext4_dir_entry_tail), + &fname, &de); + if (err == 0) + ext4_insert_dentry(dir, file1, de, TEST_BLK_SIZE, + &fname); + ext4_fname_free_filename(&fname); + if (err == -ENOSPC) + break; + } + KUNIT_ASSERT_EQ(test, ext4_handle_dirty_dirblock(NULL, dir, bh1), 0); + + /* + * Adding "trigger_split_entry" finds leaf block 1 full and root index + * full (count == limit), triggering the add_level branch in + * ext4_dx_add_entry (indirect_levels: 0 -> 1). + */ + init_mock_dentry(&child_dentry, &parent_dentry, "trigger_split_entry", + file1, &ctx->sb); + err = ext4_add_entry_test(NULL, &child_dentry, file1); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, root->info.indirect_levels, 1); + KUNIT_EXPECT_EQ(test, dx_get_count(root->entries), 1U); + + /* Verify the newly inserted entry can be found in the 2-level tree */ + found_bh = ext4_find_entry_test(dir, &child_dentry.d_name, &de, NULL); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(found_bh)); + brelse(found_bh); + + /* + * Test interior dx_node split (!add_level in ext4_dx_add_entry) and + * max htree level (-ENOSPC when levels == ext4_dir_htree_level(sb)): + * Block 2 is the new interior dx_node created by the root split above. + * Point all node_limit entries in block 2 to leaf block 1 and refill + * leaf block 1 so the next insertion splits the interior dx_node. + */ + { + struct buffer_head *bh2 = map_and_get_dir_bh(ctx, dir, 2); + struct dx_node *node; + unsigned int node_limit = dx_node_limit(dir); + + KUNIT_ASSERT_NOT_NULL(test, bh2); + node = (struct dx_node *)bh2->b_data; + dx_set_limit(node->entries, node_limit); + dx_set_count(node->entries, node_limit); + for (i = 0; i < node_limit; i++) { + if (i > 0) + dx_set_hash(node->entries + i, + (u32)i * 0x01000000U); + dx_set_block(node->entries + i, 1); + } + ext4_dx_csum_set_test(dir, + (struct ext4_dir_entry *)bh2->b_data); + + /* Refill leaf block 1 to capacity */ + for (i = 60; i < 120; i++) { + char name[16]; + struct qstr q; + struct ext4_filename fname; + + snprintf(name, sizeof(name), "leaf_%05d", i); + q.name = (const unsigned char *)name; + q.len = strlen(name); + KUNIT_ASSERT_EQ(test, + ext4_fname_setup_filename(dir, &q, 0, &fname), + 0); + err = ext4_find_dest_de(dir, bh1, bh1->b_data, + TEST_BLK_SIZE - + sizeof(struct ext4_dir_entry_tail), + &fname, &de); + if (err == 0) + ext4_insert_dentry(dir, file1, de, + TEST_BLK_SIZE, &fname); + ext4_fname_free_filename(&fname); + if (err == -ENOSPC) + break; + } + KUNIT_ASSERT_EQ(test, + ext4_handle_dirty_dirblock(NULL, dir, bh1), 0); + + /* + * First test max htree level check: if both root (level 0) and + * interior node (level 1) are full when LARGEDIR is disabled + * (max level 2), ext4_dx_add_entry returns -ENOSPC. + */ + dx_set_count(root->entries, root_limit); + for (i = 0; i < root_limit; i++) { + if (i > 0) + dx_set_hash(root->entries + i, + (u32)i * 0x02000000U); + dx_set_block(root->entries + i, 2); + } + ext4_dx_csum_set_test(dir, + (struct ext4_dir_entry *)bh0->b_data); + init_mock_dentry(&child_dentry, &parent_dentry, + "max_level_enospc", file1, &ctx->sb); + KUNIT_EXPECT_EQ(test, + ext4_add_entry_test(NULL, &child_dentry, file1), + -ENOSPC); + + /* + * Restore root count to 1 and insert again: now root has room + * while interior node at block 2 is full, exercising the + * !add_level interior node split in ext4_dx_add_entry. + */ + dx_set_count(root->entries, 1); + dx_set_block(root->entries + 0, 2); + ext4_dx_csum_set_test(dir, + (struct ext4_dir_entry *)bh0->b_data); + init_mock_dentry(&child_dentry, &parent_dentry, + "interior_node_split", file1, &ctx->sb); + KUNIT_ASSERT_EQ(test, + ext4_add_entry_test(NULL, &child_dentry, file1), + 0); + KUNIT_EXPECT_EQ(test, root->info.indirect_levels, 1); + KUNIT_EXPECT_EQ(test, dx_get_count(root->entries), 2U); + } + + /* + * Now test corrupted dx_root handling: + * 1) With METADATA_CSUM enabled, __ext4_add_entry refuses to clear + * EXT4_INODE_INDEX and returns -EFSCORRUPTED. + */ + root->info.hash_version = 99; + ext4_dx_csum_set_test(dir, (struct ext4_dir_entry *)bh0->b_data); + init_mock_dentry(&child_dentry, &parent_dentry, "after_corrupt", + file1, &ctx->sb); + KUNIT_EXPECT_EQ(test, + ext4_add_entry_test(NULL, &child_dentry, file1), + -EFSCORRUPTED); + + /* + * 2) __ext4_find_entry falls back to linear block scan on + * ERR_BAD_DX_DIR and still finds "leaf_00000" in block 1! + */ + init_mock_dentry(&child_dentry, &parent_dentry, "leaf_00000", + file1, &ctx->sb); + found_bh = ext4_find_entry_test(dir, &child_dentry.d_name, &de, NULL); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(found_bh)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), TEST_FILE1_INO); + brelse(found_bh); + + /* + * 3) Without METADATA_CSUM, __ext4_add_entry clears EXT4_INODE_INDEX + * on ERR_BAD_DX_DIR and falls back to linear append. + */ + ctx->es.s_feature_ro_compat &= + ~cpu_to_le32(EXT4_FEATURE_RO_COMPAT_METADATA_CSUM); + init_mock_dentry(&child_dentry, &parent_dentry, "fallback_new_entry", + file1, &ctx->sb); + KUNIT_EXPECT_EQ(test, + ext4_add_entry_test(NULL, &child_dentry, file1), 0); + KUNIT_EXPECT_FALSE(test, ext4_test_inode_flag(dir, EXT4_INODE_INDEX)); +} + +/* + * Test 11: Inline directory lifecycle through namei.c entry points + * (ext4_init_new_dir, ext4_empty_dir, ext4_add_entry_test, + * ext4_find_entry_test, ext4_delete_entry_test, ext4_htree_fill_tree). + */ +static void test_namei_inline_dir_lifecycle(struct kunit *test) +{ + struct namei_test_ctx *ctx = test->priv; + struct inode *root_dir = get_mock_inode(ctx, TEST_ROOT_INO); + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct dentry parent_dentry, child_dentry; + struct buffer_head *bh; + struct ext4_dir_entry_2 *de = NULL; + struct dir_private_info *dir_info; + struct file dir_file = {}; + __u32 next_hash = 0; + int inlined = 0; + + ctx->es.s_feature_incompat |= + cpu_to_le32(EXT4_FEATURE_INCOMPAT_INLINE_DATA); + ext4_set_inode_state(dir, EXT4_STATE_MAY_INLINE_DATA); + + KUNIT_ASSERT_EQ(test, ext4_init_new_dir(NULL, root_dir, dir), 0); + KUNIT_EXPECT_TRUE(test, ext4_has_inline_data(dir)); + KUNIT_EXPECT_TRUE(test, ext4_empty_dir(dir)); + + init_mock_dentry(&parent_dentry, NULL, "idir", dir, &ctx->sb); + init_mock_dentry(&child_dentry, &parent_dentry, "tiny", file1, + &ctx->sb); + + /* Add an entry into the inline directory */ + KUNIT_ASSERT_EQ(test, + ext4_add_entry_test(NULL, &child_dentry, file1), 0); + KUNIT_EXPECT_TRUE(test, ext4_has_inline_data(dir)); + KUNIT_EXPECT_FALSE(test, ext4_empty_dir(dir)); + + /* Find the inline entry */ + bh = ext4_find_entry_test(dir, &child_dentry.d_name, &de, &inlined); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(bh)); + KUNIT_EXPECT_EQ(test, inlined, 1); + KUNIT_ASSERT_NOT_NULL(test, de); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), TEST_FILE1_INO); + brelse(bh); + + /* Load inline directory into rb-tree via ext4_htree_fill_tree */ + dir_info = kzalloc_obj(*dir_info); + KUNIT_ASSERT_NOT_NULL(test, dir_info); + dir_file.f_inode = dir; + dir_file.private_data = dir_info; + KUNIT_EXPECT_EQ(test, + ext4_htree_fill_tree(&dir_file, 0, 0, &next_hash), 3); + KUNIT_EXPECT_EQ(test, next_hash, ~0U); + ext4_htree_free_dir_info(dir_info); + + /* Delete the inline entry -> directory becomes empty again */ + bh = ext4_find_entry_test(dir, &child_dentry.d_name, &de, &inlined); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(bh)); + KUNIT_ASSERT_EQ(test, ext4_delete_entry_test(NULL, dir, de, bh), 0); + brelse(bh); + KUNIT_EXPECT_TRUE(test, ext4_empty_dir(dir)); +} + +/* + * Test 12: Directory link count helpers (ext4_inc_count_test, + * ext4_dec_count_test) and VFS lookup / parent resolution (ext4_lookup, + * ext4_get_parent). + */ +static void test_namei_nlink_and_lookup_parent(struct kunit *test) +{ + struct namei_test_ctx *ctx = test->priv; + struct inode *root_dir = get_mock_inode(ctx, TEST_ROOT_INO); + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct dentry *dentries; + struct dentry *parent_dentry, *lookup_dentry, *res_dentry; + struct buffer_head *bh; + struct ext4_dir_entry_2 *de = NULL; + char *long_name; + + dentries = kunit_kcalloc(test, 2, sizeof(*dentries), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dentries); + parent_dentry = &dentries[0]; + lookup_dentry = &dentries[1]; + long_name = kunit_kzalloc(test, EXT4_NAME_LEN + 2, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, long_name); + + /* Test ext4_inc_count_test and ext4_dec_count_test on indexed dir */ + ext4_set_inode_flag(dir, EXT4_INODE_INDEX); + set_nlink(dir, 2); + ext4_inc_count_test(dir); + KUNIT_EXPECT_EQ(test, dir->i_nlink, 3U); + ext4_dec_count_test(dir); + KUNIT_EXPECT_EQ(test, dir->i_nlink, 2U); + + /* Overflow past EXT4_LINK_MAX wraps nlink to 1 and keeps it at 1 */ + set_nlink(dir, EXT4_LINK_MAX); + ext4_inc_count_test(dir); + KUNIT_EXPECT_EQ(test, dir->i_nlink, 1U); + ext4_inc_count_test(dir); + KUNIT_EXPECT_EQ(test, dir->i_nlink, 1U); + ext4_dec_count_test(dir); + KUNIT_EXPECT_EQ(test, dir->i_nlink, 1U); + ext4_clear_inode_flag(dir, EXT4_INODE_INDEX); + + /* Initialize directory for lookup and get_parent tests */ + KUNIT_ASSERT_EQ(test, ext4_init_new_dir(NULL, root_dir, dir), 0); + init_mock_dentry(parent_dentry, NULL, "dir", dir, &ctx->sb); + + /* 1) Name longer than EXT4_NAME_LEN -> -ENAMETOOLONG */ + memset(long_name, 'a', EXT4_NAME_LEN + 1); + long_name[EXT4_NAME_LEN + 1] = '\0'; + init_mock_dentry(lookup_dentry, parent_dentry, long_name, NULL, + &ctx->sb); + res_dentry = ext4_dir_inode_operations.lookup(dir, lookup_dentry, 0); + KUNIT_EXPECT_PTR_EQ(test, res_dentry, ERR_PTR(-ENAMETOOLONG)); + + /* 2) Negative lookup returns NULL without calling ext4_iget */ + ctx->last_iget_ino = 0; + init_mock_dentry(lookup_dentry, parent_dentry, "nonexistent", NULL, + &ctx->sb); + res_dentry = ext4_dir_inode_operations.lookup(dir, lookup_dentry, 0); + /* + * ext4_lookup() hashes negative dentries via d_splice_alias(); unhash + * it and wait for RCU readers before reusing or freeing memory. + */ + d_drop(lookup_dentry); + synchronize_rcu(); + KUNIT_EXPECT_NULL(test, res_dentry); + KUNIT_EXPECT_EQ(test, ctx->last_iget_ino, 0UL); + + /* 3) Positive lookup invokes ext4_iget with target inode number */ + init_mock_dentry(lookup_dentry, parent_dentry, "target", file1, + &ctx->sb); + KUNIT_ASSERT_EQ(test, + ext4_add_entry_test(NULL, lookup_dentry, file1), 0); + ctx->fail_iget = -ESTALE; + /* -ESTALE from ext4_iget is translated to -EFSCORRUPTED */ + res_dentry = ext4_dir_inode_operations.lookup(dir, lookup_dentry, 0); + KUNIT_EXPECT_PTR_EQ(test, res_dentry, ERR_PTR(-EFSCORRUPTED)); + KUNIT_EXPECT_EQ(test, ctx->last_iget_ino, TEST_FILE1_INO); + + /* 4) Self-linked directory entry (de->inode == dir->i_ino) -> -EFSCORRUPTED */ + bh = ext4_find_entry_test(dir, &lookup_dentry->d_name, &de, NULL); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(bh)); + de->inode = cpu_to_le32(dir->i_ino); + brelse(bh); + res_dentry = ext4_dir_inode_operations.lookup(dir, lookup_dentry, 0); + KUNIT_EXPECT_PTR_EQ(test, res_dentry, ERR_PTR(-EFSCORRUPTED)); + + /* 5) Invalid inode number (e.g. reserved ino 5) -> -EFSCORRUPTED */ + de->inode = cpu_to_le32(5); + res_dentry = ext4_dir_inode_operations.lookup(dir, lookup_dentry, 0); + KUNIT_EXPECT_PTR_EQ(test, res_dentry, ERR_PTR(-EFSCORRUPTED)); + + /* 6) ext4_get_parent looks up ".." and calls ext4_iget(TEST_ROOT_INO) */ + ctx->fail_iget = -EUCLEAN; + ctx->last_iget_ino = 0; + res_dentry = ext4_get_parent(parent_dentry); + KUNIT_EXPECT_PTR_EQ(test, res_dentry, ERR_PTR(-EUCLEAN)); + KUNIT_EXPECT_EQ(test, ctx->last_iget_ino, (unsigned long)TEST_ROOT_INO); + + /* Corrupt '..' inode to invalid ino 5 -> ext4_get_parent returns -EFSCORRUPTED */ + bh = map_and_get_dir_bh(ctx, dir, 0); + de = ext4_next_entry((struct ext4_dir_entry_2 *)bh->b_data, + TEST_BLK_SIZE); + de->inode = cpu_to_le32(5); + res_dentry = ext4_get_parent(parent_dentry); + KUNIT_EXPECT_PTR_EQ(test, res_dentry, ERR_PTR(-EFSCORRUPTED)); +} + +/* + * Test 13: Hard link, unlink, and rmdir operations (__ext4_link, + * ext4_dir_inode_operations.link, __ext4_unlink, + * ext4_dir_inode_operations.unlink, ext4_dir_inode_operations.rmdir). + */ +static void test_namei_link_unlink_and_rmdir(struct kunit *test) +{ + struct namei_test_ctx *ctx = test->priv; + struct inode *root_dir = get_mock_inode(ctx, TEST_ROOT_INO); + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct inode *subdir = get_mock_inode(ctx, TEST_SUBDIR_INO); + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct dentry *dentries; + struct dentry *dir_dentry, *f1_dentry, *f1_link_dentry, *sub_dentry; + int err; + + dentries = kunit_kcalloc(test, 4, sizeof(*dentries), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dentries); + dir_dentry = &dentries[0]; + f1_dentry = &dentries[1]; + f1_link_dentry = &dentries[2]; + sub_dentry = &dentries[3]; + + ctx->es.s_feature_ro_compat |= + cpu_to_le32(EXT4_FEATURE_RO_COMPAT_METADATA_CSUM); + + KUNIT_ASSERT_EQ(test, ext4_init_new_dir(NULL, root_dir, dir), 0); + KUNIT_ASSERT_EQ(test, ext4_init_new_dir(NULL, dir, subdir), 0); + ext4_inc_count_test(dir); + + init_mock_dentry(dir_dentry, NULL, "dir", dir, &ctx->sb); + init_mock_dentry(f1_dentry, dir_dentry, "orig", file1, &ctx->sb); + init_mock_dentry(f1_link_dentry, dir_dentry, "hardlink", file1, + &ctx->sb); + init_mock_dentry(sub_dentry, dir_dentry, "subdir", subdir, &ctx->sb); + + /* Link a 0-nlink tmpfile -> nlink becomes 1 and ext4_orphan_del runs */ + set_nlink(file1, 0); + inode_state_set_raw(file1, I_DIRTY | I_LINKABLE); + ctx->orphan_del_calls = 0; + err = __ext4_link(dir, file1, &f1_dentry->d_name, f1_dentry); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, file1->i_nlink, 1U); + KUNIT_EXPECT_EQ(test, ctx->orphan_del_calls, 1U); + KUNIT_EXPECT_EQ(test, ctx->last_orphan_del_ino, TEST_FILE1_INO); + + /* Create a second hard link via __ext4_link */ + err = __ext4_link(dir, file1, &f1_link_dentry->d_name, f1_link_dentry); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, file1->i_nlink, 2U); + + /* Cross-project link with EXT4_INODE_PROJINHERIT returns -EXDEV */ + ext4_set_inode_flag(dir, EXT4_INODE_PROJINHERIT); + EXT4_I(file1)->i_projid = make_kprojid(&init_user_ns, 42); + KUNIT_EXPECT_EQ(test, + ext4_dir_inode_operations.link(f1_dentry, dir, + f1_link_dentry), -EXDEV); + EXT4_I(file1)->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + + /* Max link count check returns -EMLINK */ + set_nlink(file1, EXT4_LINK_MAX); + KUNIT_EXPECT_EQ(test, + ext4_dir_inode_operations.link(f1_dentry, dir, + f1_link_dentry), -EMLINK); + set_nlink(file1, 2); + + /* Unlink first link -> nlink drops to 1, not orphaned yet */ + ctx->orphan_add_calls = 0; + err = ext4_dir_inode_operations.unlink(dir, f1_dentry); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, file1->i_nlink, 1U); + KUNIT_EXPECT_EQ(test, ctx->orphan_add_calls, 0U); + + /* Unlink last link -> nlink drops to 0 and inode is added to orphans */ + err = ext4_dir_inode_operations.unlink(dir, f1_link_dentry); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, file1->i_nlink, 0U); + KUNIT_EXPECT_EQ(test, ctx->orphan_add_calls, 1U); + KUNIT_EXPECT_EQ(test, ctx->last_orphan_add_ino, TEST_FILE1_INO); + + /* Unlinking missing entry returns -ENOENT */ + KUNIT_EXPECT_EQ(test, + ext4_dir_inode_operations.unlink(dir, f1_link_dentry), + -ENOENT); + + /* + * Test __ext4_unlink when directory entry points to a different inode: + * normally rejected with -ENOENT, but permitted during EXT4_FC_REPLAY. + */ + { + struct inode *file2 = get_mock_inode(ctx, TEST_FILE2_INO); + + set_nlink(file1, 1); + set_nlink(file2, 1); + KUNIT_ASSERT_EQ(test, + ext4_add_entry_test(NULL, f1_dentry, file1), 0); + KUNIT_EXPECT_EQ(test, + __ext4_unlink(dir, &f1_dentry->d_name, file2, + f1_dentry), -ENOENT); + ctx->sbi.s_mount_state |= EXT4_FC_REPLAY; + KUNIT_EXPECT_EQ(test, + __ext4_unlink(dir, &f1_dentry->d_name, file2, + f1_dentry), 0); + ctx->sbi.s_mount_state &= ~EXT4_FC_REPLAY; + } + + /* Add subdir to dir and test rmdir */ + KUNIT_ASSERT_EQ(test, + ext4_add_entry_test(NULL, sub_dentry, subdir), 0); + + /* Non-empty subdir cannot be removed (-ENOTEMPTY) */ + init_mock_dentry(f1_dentry, sub_dentry, "inside", file1, &ctx->sb); + set_nlink(file1, 1); + KUNIT_ASSERT_EQ(test, + ext4_add_entry_test(NULL, f1_dentry, file1), 0); + KUNIT_EXPECT_EQ(test, + ext4_dir_inode_operations.rmdir(dir, sub_dentry), -ENOTEMPTY); + + /* Unlink file inside subdir, then rmdir subdir succeeds */ + KUNIT_ASSERT_EQ(test, + ext4_dir_inode_operations.unlink(subdir, f1_dentry), 0); + KUNIT_ASSERT_EQ(test, + ext4_dir_inode_operations.rmdir(dir, sub_dentry), 0); + KUNIT_EXPECT_EQ(test, subdir->i_nlink, 0U); + KUNIT_EXPECT_EQ(test, subdir->i_size, 0LL); + KUNIT_EXPECT_EQ(test, dir->i_nlink, 2U); + KUNIT_EXPECT_EQ(test, ctx->last_orphan_add_ino, TEST_SUBDIR_INO); +} + +/* + * Test 14: Rename, overwrite rename, cross-directory subdirectory rename, + * RENAME_EXCHANGE (ext4_cross_rename), and slow symlink block initialization + * (ext4_init_symlink_block_test). + */ +static void test_namei_rename_and_exchange(struct kunit *test) +{ + struct namei_test_ctx *ctx = test->priv; + struct inode *root_dir = get_mock_inode(ctx, TEST_ROOT_INO); + struct inode *dir1 = get_mock_inode(ctx, TEST_DIR_INO); + struct inode *dir2 = get_mock_inode(ctx, TEST_DIR2_INO); + struct inode *subdir = get_mock_inode(ctx, TEST_SUBDIR_INO); + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct inode *file2 = get_mock_inode(ctx, TEST_FILE2_INO); + struct inode *symlink_inode = get_mock_inode(ctx, TEST_FILE3_INO); + struct dentry *dentries; + struct dentry *d1_dentry, *d2_dentry; + struct dentry *old_dentry, *new_dentry, *sub_dentry; + struct buffer_head *bh; + struct ext4_dir_entry_2 *de = NULL; + const char *sym_target = "/very/long/symlink/target/path/for/ext4/test"; + struct fscrypt_str disk_link = { + .name = (unsigned char *)sym_target, + .len = strlen(sym_target) + 1, + }; + int err; + + dentries = kunit_kcalloc(test, 5, sizeof(*dentries), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dentries); + d1_dentry = &dentries[0]; + d2_dentry = &dentries[1]; + old_dentry = &dentries[2]; + new_dentry = &dentries[3]; + sub_dentry = &dentries[4]; + + ctx->es.s_feature_ro_compat |= + cpu_to_le32(EXT4_FEATURE_RO_COMPAT_METADATA_CSUM); + + KUNIT_ASSERT_EQ(test, ext4_init_new_dir(NULL, root_dir, dir1), 0); + KUNIT_ASSERT_EQ(test, ext4_init_new_dir(NULL, root_dir, dir2), 0); + KUNIT_ASSERT_EQ(test, ext4_init_new_dir(NULL, dir1, subdir), 0); + set_nlink(dir1, 3); /* '.', '..', and subdir */ + set_nlink(dir2, 2); + + init_mock_dentry(d1_dentry, NULL, "dir1", dir1, &ctx->sb); + init_mock_dentry(d2_dentry, NULL, "dir2", dir2, &ctx->sb); + + /* Invalid rename flags are rejected with -EINVAL */ + init_mock_dentry(old_dentry, d1_dentry, "f1", file1, &ctx->sb); + init_mock_dentry(new_dentry, d1_dentry, "f1_new", NULL, &ctx->sb); + KUNIT_EXPECT_EQ(test, + ext4_dir_inode_operations.rename(&nop_mnt_idmap, dir1, + old_dentry, dir1, new_dentry, ~0U), -EINVAL); + + /* Add f1 and f2 in dir1, and subdir in dir1 */ + KUNIT_ASSERT_EQ(test, + ext4_add_entry_test(NULL, old_dentry, file1), 0); + init_mock_dentry(sub_dentry, d1_dentry, "sub", subdir, &ctx->sb); + KUNIT_ASSERT_EQ(test, + ext4_add_entry_test(NULL, sub_dentry, subdir), 0); + + /* 1) Same-directory rename: f1 -> f1_renamed */ + err = ext4_dir_inode_operations.rename(&nop_mnt_idmap, dir1, + old_dentry, dir1, new_dentry, + 0); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_NULL(test, + ext4_find_entry_test(dir1, &old_dentry->d_name, &de, NULL)); + bh = ext4_find_entry_test(dir1, &new_dentry->d_name, &de, NULL); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(bh)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), TEST_FILE1_INO); + brelse(bh); + + /* 2) Overwrite rename: f1_renamed overwrites existing f2 in dir1 */ + init_mock_dentry(old_dentry, d1_dentry, "f1_new", file1, &ctx->sb); + init_mock_dentry(new_dentry, d1_dentry, "f2", file2, &ctx->sb); + KUNIT_ASSERT_EQ(test, + ext4_add_entry_test(NULL, new_dentry, file2), 0); + ctx->orphan_add_calls = 0; + err = ext4_dir_inode_operations.rename(&nop_mnt_idmap, dir1, + old_dentry, dir1, new_dentry, + 0); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, file2->i_nlink, 0U); + KUNIT_EXPECT_EQ(test, ctx->orphan_add_calls, 1U); + KUNIT_EXPECT_EQ(test, ctx->last_orphan_add_ino, TEST_FILE2_INO); + + /* 3) Cross-directory subdir move: dir1/sub -> dir2/sub_moved */ + init_mock_dentry(new_dentry, d2_dentry, "sub_moved", NULL, &ctx->sb); + err = ext4_dir_inode_operations.rename(&nop_mnt_idmap, dir1, + sub_dentry, dir2, new_dentry, + 0); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, dir1->i_nlink, 2U); + KUNIT_EXPECT_EQ(test, dir2->i_nlink, 3U); + + /* Verify subdir's '..' now points to dir2 */ + bh = map_and_get_dir_bh(ctx, subdir, 0); + de = ext4_next_entry((struct ext4_dir_entry_2 *)bh->b_data, + TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), TEST_DIR2_INO); + + /* + * 4) RENAME_EXCHANGE (ext4_cross_rename): exchange regular file + * dir1/f2 with directory dir2/sub_moved across parents! + */ + init_mock_dentry(old_dentry, d1_dentry, "f2", file1, &ctx->sb); + init_mock_dentry(new_dentry, d2_dentry, "sub_moved", subdir, + &ctx->sb); + + /* Cross-project RENAME_EXCHANGE and normal rename return -EXDEV */ + ext4_set_inode_flag(dir2, EXT4_INODE_PROJINHERIT); + EXT4_I(dir2)->i_projid = make_kprojid(&init_user_ns, 77); + KUNIT_EXPECT_EQ(test, + ext4_dir_inode_operations.rename(&nop_mnt_idmap, dir1, + old_dentry, dir2, new_dentry, RENAME_EXCHANGE), + -EXDEV); + KUNIT_EXPECT_EQ(test, + ext4_dir_inode_operations.rename(&nop_mnt_idmap, dir1, + old_dentry, dir2, new_dentry, 0), + -EXDEV); + ext4_clear_inode_flag(dir2, EXT4_INODE_PROJINHERIT); + EXT4_I(dir2)->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + + err = ext4_dir_inode_operations.rename(&nop_mnt_idmap, dir1, + old_dentry, dir2, new_dentry, + RENAME_EXCHANGE); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, dir1->i_nlink, 3U); + KUNIT_EXPECT_EQ(test, dir2->i_nlink, 2U); + de = ext4_next_entry((struct ext4_dir_entry_2 *)bh->b_data, + TEST_BLK_SIZE); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), TEST_DIR_INO); + + /* + * Overwriting a target inode whose i_nlink == 0 returns -EFSCORRUPTED + * (in dir2, "sub_moved" now points to file1 after the exchange). + */ + init_mock_dentry(old_dentry, d1_dentry, "f2", subdir, &ctx->sb); + init_mock_dentry(new_dentry, d2_dentry, "sub_moved", file1, &ctx->sb); + set_nlink(file1, 0); + KUNIT_EXPECT_EQ(test, + ext4_dir_inode_operations.rename(&nop_mnt_idmap, dir2, + new_dentry, dir2, new_dentry, 0), + -EFSCORRUPTED); + set_nlink(file1, 1); + + /* 5) Test ext4_init_symlink_block_test */ + err = ext4_init_symlink_block_test(NULL, symlink_inode, &disk_link); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, symlink_inode->i_size, + (loff_t)strlen(sym_target)); + bh = map_and_get_dir_bh(ctx, symlink_inode, 0); + KUNIT_ASSERT_NOT_NULL(test, bh); + KUNIT_EXPECT_STREQ(test, bh->b_data, sym_target); +} + +#if IS_ENABLED(CONFIG_UNICODE) +/* + * Test 15: Case-insensitive (EXT4_INODE_CASEFOLD) filename setup, directory + * lookup, and strict UTF-8 validation. + */ +static void test_namei_casefold_lookup_and_strict(struct kunit *test) +{ + struct namei_test_ctx *ctx = test->priv; + struct inode *root_dir = get_mock_inode(ctx, TEST_ROOT_INO); + struct inode *dir = get_mock_inode(ctx, TEST_DIR_INO); + struct inode *file1 = get_mock_inode(ctx, TEST_FILE1_INO); + struct unicode_map *um; + struct dentry parent_dentry, add_dentry; + struct qstr upper_q = QSTR_INIT(" readme.md ", 11); + struct qstr bad_utf8 = QSTR_INIT("\xff\xfe", 2); + struct buffer_head *bh; + struct ext4_dir_entry_2 *de = NULL; + + um = utf8_load(UNICODE_AGE(12, 1, 0)); + if (IS_ERR(um)) + kunit_skip(test, "utf8data module not available"); + + ctx->sb.s_encoding = um; + ctx->es.s_feature_incompat |= + cpu_to_le32(EXT4_FEATURE_INCOMPAT_CASEFOLD); + ext4_set_inode_flag(dir, EXT4_INODE_CASEFOLD); + ext4_set_inode_flags(dir, true); + + KUNIT_ASSERT_EQ(test, ext4_init_new_dir(NULL, root_dir, dir), 0); + init_mock_dentry(&parent_dentry, NULL, "cfdir", dir, &ctx->sb); + init_mock_dentry(&add_dentry, &parent_dentry, " ReadMe.MD ", file1, + &ctx->sb); + + KUNIT_ASSERT_EQ(test, + ext4_add_entry_test(NULL, &add_dentry, file1), 0); + + /* Case-insensitive lookup with different case finds the entry */ + bh = ext4_find_entry_test(dir, &upper_q, &de, NULL); + KUNIT_ASSERT_FALSE(test, IS_ERR_OR_NULL(bh)); + KUNIT_ASSERT_NOT_NULL(test, de); + KUNIT_EXPECT_EQ(test, le32_to_cpu(de->inode), TEST_FILE1_INO); + brelse(bh); + + /* Enable SB_ENC_STRICT_MODE_FL -> invalid UTF-8 sequence is rejected */ + ctx->sb.s_encoding_flags |= SB_ENC_STRICT_MODE_FL; + add_dentry.__d_name = bad_utf8; + KUNIT_EXPECT_EQ(test, + ext4_add_entry_test(NULL, &add_dentry, file1), + -EINVAL); +} +#endif /* CONFIG_UNICODE */ + +static struct kunit_case namei_test_cases[] = { + KUNIT_CASE(test_namei_dirent_tail_and_csum), + KUNIT_CASE(test_namei_dx_helpers_and_csum), + KUNIT_CASE_PARAM(test_namei_read_dirblock, read_dirblock_gen_params), + KUNIT_CASE(test_namei_append_and_init_dir), + KUNIT_CASE(test_namei_search_insert_delete_dentry), + KUNIT_CASE(test_namei_empty_dir), + KUNIT_CASE(test_namei_dx_map_pack_and_move), + KUNIT_CASE_PARAM(test_namei_check_dx_root_and_probe, + dx_probe_gen_params), + KUNIT_CASE(test_namei_add_find_and_htree_split), + KUNIT_CASE(test_namei_dx_index_level_growth_and_fallback), + KUNIT_CASE(test_namei_inline_dir_lifecycle), + KUNIT_CASE(test_namei_nlink_and_lookup_parent), + KUNIT_CASE(test_namei_link_unlink_and_rmdir), + KUNIT_CASE(test_namei_rename_and_exchange), +#if IS_ENABLED(CONFIG_UNICODE) + KUNIT_CASE(test_namei_casefold_lookup_and_strict), +#endif + {} +}; + +static struct kunit_suite namei_test_suite = { + .name = "ext4_namei_test", + .init = namei_test_init, + .exit = namei_test_exit, + .test_cases = namei_test_cases, +}; + +kunit_test_suites(&namei_test_suite); + +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/namei.c b/fs/ext4/namei.c index 354fc2d22df1aa..b2753daad49f4a 100644 --- a/fs/ext4/namei.c +++ b/fs/ext4/namei.c @@ -36,11 +36,13 @@ #include #include #include +#include #include "ext4.h" #include "ext4_jbd2.h" #include "xattr.h" #include "acl.h" +#include "namei.h" #include /* @@ -104,26 +106,12 @@ static struct buffer_head *ext4_append(handle_t *handle, static int ext4_dx_csum_verify(struct inode *inode, struct ext4_dir_entry *dirent); -/* - * Hints to ext4_read_dirblock regarding whether we expect a directory - * block being read to be an index block, or a block containing - * directory entries (and if the latter, whether it was found via a - * logical block in an htree index block). This is used to control - * what sort of sanity checkinig ext4_read_dirblock() will do on the - * directory block read from the storage device. EITHER will means - * the caller doesn't know what kind of directory block will be read, - * so no specific verification will be done. - */ -typedef enum { - EITHER, INDEX, DIRENT, DIRENT_HTREE -} dirblock_type_t; - #define ext4_read_dirblock(inode, block, type) \ __ext4_read_dirblock((inode), (block), (type), __func__, __LINE__) static struct buffer_head *__ext4_read_dirblock(struct inode *inode, ext4_lblk_t block, - dirblock_type_t type, + enum dirblock_type type, const char *func, unsigned int line) { @@ -218,79 +206,6 @@ static struct buffer_head *__ext4_read_dirblock(struct inode *inode, #define dxtrace(command) #endif -struct fake_dirent -{ - __le32 inode; - __le16 rec_len; - u8 name_len; - u8 file_type; -}; - -struct dx_countlimit -{ - __le16 limit; - __le16 count; -}; - -struct dx_entry -{ - __le32 hash; - __le32 block; -}; - -/* - * dx_root_info is laid out so that if it should somehow get overlaid by a - * dirent the two low bits of the hash version will be zero. Therefore, the - * hash version mod 4 should never be 0. Sincerely, the paranoia department. - */ - -struct dx_root -{ - struct fake_dirent dot; - char dot_name[4]; - struct fake_dirent dotdot; - char dotdot_name[4]; - struct dx_root_info - { - __le32 reserved_zero; - u8 hash_version; - u8 info_length; /* 8 */ - u8 indirect_levels; - u8 unused_flags; - } - info; - struct dx_entry entries[]; -}; - -struct dx_node -{ - struct fake_dirent fake; - struct dx_entry entries[]; -}; - - -struct dx_frame -{ - struct buffer_head *bh; - struct dx_entry *entries; - struct dx_entry *at; -}; - -struct dx_map_entry -{ - u32 hash; - u16 offs; - u16 size; -}; - -/* - * This goes at the end of each htree block. - */ -struct dx_tail { - u32 dt_reserved; - __le32 dt_checksum; /* crc32c(uuid+inum+dirblock) */ -}; - static struct buffer_head * ext4_dx_find_entry(struct inode *dir, struct ext4_filename *fname, struct ext4_dir_entry_2 **res_dir); @@ -308,6 +223,7 @@ void ext4_initialize_dirent_tail(struct buffer_head *bh, sizeof(struct ext4_dir_entry_tail), blocksize); t->det_reserved_ft = EXT4_FT_DIR_CSUM; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_initialize_dirent_tail); /* Walk through a dirent block to find a checksum "dirent" at the tail */ static struct ext4_dir_entry_tail *get_dirent_tail(struct inode *inode, @@ -382,6 +298,7 @@ int ext4_dirblock_csum_verify(struct inode *inode, struct buffer_head *bh) return 1; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_dirblock_csum_verify); static void ext4_dirblock_csum_set(struct inode *inode, struct buffer_head *bh) @@ -408,6 +325,7 @@ int ext4_handle_dirty_dirblock(handle_t *handle, ext4_dirblock_csum_set(inode, bh); return ext4_handle_dirty_metadata(handle, inode, bh); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_handle_dirty_dirblock); static struct dx_countlimit *get_dx_countlimit(struct inode *inode, struct ext4_dir_entry *dirent, @@ -519,82 +437,6 @@ static inline int ext4_handle_dirty_dx_node(handle_t *handle, return ext4_handle_dirty_metadata(handle, inode, bh); } -/* - * p is at least 6 bytes before the end of page - */ -static inline struct ext4_dir_entry_2 * -ext4_next_entry(struct ext4_dir_entry_2 *p, unsigned long blocksize) -{ - return (struct ext4_dir_entry_2 *)((char *)p + - ext4_rec_len_from_disk(p->rec_len, blocksize)); -} - -/* - * Future: use high four bits of block for coalesce-on-delete flags - * Mask them off for now. - */ - -static inline ext4_lblk_t dx_get_block(struct dx_entry *entry) -{ - return le32_to_cpu(entry->block) & 0x0fffffff; -} - -static inline void dx_set_block(struct dx_entry *entry, ext4_lblk_t value) -{ - entry->block = cpu_to_le32(value); -} - -static inline unsigned dx_get_hash(struct dx_entry *entry) -{ - return le32_to_cpu(entry->hash); -} - -static inline void dx_set_hash(struct dx_entry *entry, unsigned value) -{ - entry->hash = cpu_to_le32(value); -} - -static inline unsigned dx_get_count(struct dx_entry *entries) -{ - return le16_to_cpu(((struct dx_countlimit *) entries)->count); -} - -static inline unsigned dx_get_limit(struct dx_entry *entries) -{ - return le16_to_cpu(((struct dx_countlimit *) entries)->limit); -} - -static inline void dx_set_count(struct dx_entry *entries, unsigned value) -{ - ((struct dx_countlimit *) entries)->count = cpu_to_le16(value); -} - -static inline void dx_set_limit(struct dx_entry *entries, unsigned value) -{ - ((struct dx_countlimit *) entries)->limit = cpu_to_le16(value); -} - -static inline unsigned dx_root_limit(struct inode *dir, unsigned infosize) -{ - unsigned int entry_space = dir->i_sb->s_blocksize - - ext4_dir_rec_len(1, NULL) - - ext4_dir_rec_len(2, NULL) - infosize; - - if (ext4_has_feature_metadata_csum(dir->i_sb)) - entry_space -= sizeof(struct dx_tail); - return entry_space / sizeof(struct dx_entry); -} - -static inline unsigned dx_node_limit(struct inode *dir) -{ - unsigned int entry_space = dir->i_sb->s_blocksize - - ext4_dir_rec_len(0, dir); - - if (ext4_has_feature_metadata_csum(dir->i_sb)) - entry_space -= sizeof(struct dx_tail); - return entry_space / sizeof(struct dx_entry); -} - /* * Debug */ @@ -1161,6 +1003,9 @@ int ext4_htree_fill_tree(struct file *dir_file, __u32 start_hash, __u32 hashval; struct fscrypt_str tmp_str; + KUNIT_STATIC_STUB_REDIRECT(ext4_htree_fill_tree, dir_file, start_hash, + start_minor_hash, next_hash); + dxtrace(printk(KERN_DEBUG "In htree_fill_tree, start hash: %x:%x\n", start_hash, start_minor_hash)); dir = file_inode(dir_file); @@ -1258,6 +1103,7 @@ int ext4_htree_fill_tree(struct file *dir_file, __u32 start_hash, dx_release(frames); return (err); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_htree_fill_tree); static inline int search_dirblock(struct buffer_head *bh, struct inode *dir, @@ -1395,6 +1241,7 @@ int ext4_fname_setup_ci_filename(struct inode *dir, const struct qstr *iname, else return ext4fs_dirhash(dir, iname->name, iname->len, hinfo); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fname_setup_ci_filename); #endif /* @@ -1488,6 +1335,7 @@ int ext4_search_dir(struct buffer_head *bh, char *search_buf, int buf_size, } return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_search_dir); static int is_dx_internal_node(struct inode *dir, ext4_lblk_t block, struct ext4_dir_entry *de) @@ -1837,6 +1685,7 @@ struct dentry *ext4_get_parent(struct dentry *child) return d_obtain_alias(ext4_iget(child->d_sb, ino, EXT4_IGET_NORMAL)); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_parent); /* * Move count entries from end of map between two memory locations. @@ -2066,6 +1915,7 @@ int ext4_find_dest_de(struct inode *dir, struct buffer_head *bh, *dest_de = de; return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_find_dest_de); void ext4_insert_dentry(struct inode *dir, struct inode *inode, @@ -2098,6 +1948,7 @@ void ext4_insert_dentry(struct inode *dir, cpu_to_le32(hinfo->minor_hash); } } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_insert_dentry); /* * Add a new entry into a directory (leaf) block. If de is non-NULL, @@ -2705,6 +2556,7 @@ int ext4_generic_delete_entry(struct inode *dir, } return -ENOENT; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_generic_delete_entry); static int ext4_delete_entry(handle_t *handle, struct inode *dir, @@ -2967,6 +2819,7 @@ int ext4_init_dirblock(handle_t *handle, struct inode *inode, set_buffer_verified(bh); return ext4_handle_dirty_dirblock(handle, inode, bh); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_init_dirblock); int ext4_init_new_dir(handle_t *handle, struct inode *dir, struct inode *inode) @@ -2993,6 +2846,7 @@ int ext4_init_new_dir(handle_t *handle, struct inode *dir, brelse(dir_block); return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_init_new_dir); static struct dentry *ext4_mkdir(const struct mnt_idmap *idmap, struct inode *dir, struct dentry *dentry, umode_t mode) @@ -3134,6 +2988,7 @@ bool ext4_empty_dir(struct inode *inode) brelse(bh); return true; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_empty_dir); static int ext4_rmdir(struct inode *dir, struct dentry *dentry) { @@ -3298,6 +3153,7 @@ int __ext4_unlink(struct inode *dir, const struct qstr *d_name, brelse(bh); return retval; } +EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_unlink); static int ext4_unlink(struct inode *dir, struct dentry *dentry) { @@ -3491,6 +3347,7 @@ int __ext4_link(struct inode *dir, struct inode *inode, goto retry; return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_link); static int ext4_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry) @@ -4242,6 +4099,7 @@ const struct inode_operations ext4_dir_inode_operations = { .fileattr_get = ext4_fileattr_get, .fileattr_set = ext4_fileattr_set, }; +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_dir_inode_operations); const struct inode_operations ext4_special_inode_operations = { .setattr = ext4_setattr, @@ -4250,3 +4108,159 @@ const struct inode_operations ext4_special_inode_operations = { .get_inode_acl = ext4_get_acl, .set_acl = ext4_set_acl, }; +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_special_inode_operations); + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +struct buffer_head *ext4_append_test(handle_t *handle, struct inode *inode, + ext4_lblk_t *block) +{ + return ext4_append(handle, inode, block); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_append_test); + +struct buffer_head *ext4_read_dirblock_test(struct inode *inode, + ext4_lblk_t block, + enum dirblock_type type) +{ + return ext4_read_dirblock(inode, block, type); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_read_dirblock_test); + +void ext4_dx_csum_set_test(struct inode *inode, struct ext4_dir_entry *dirent) +{ + ext4_dx_csum_set(inode, dirent); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_dx_csum_set_test); + +int ext4_dx_csum_verify_test(struct inode *inode, + struct ext4_dir_entry *dirent) +{ + return ext4_dx_csum_verify(inode, dirent); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_dx_csum_verify_test); + +struct dx_frame *dx_probe_test(struct ext4_filename *fname, struct inode *dir, + struct dx_hash_info *hinfo, + struct dx_frame *frame_in) +{ + return dx_probe(fname, dir, hinfo, frame_in); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(dx_probe_test); + +void dx_release_test(struct dx_frame *frames) +{ + dx_release(frames); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(dx_release_test); + +int ext4_htree_next_block_test(struct inode *dir, __u32 hash, + struct dx_frame *frame, + struct dx_frame *frames, __u32 *start_hash) +{ + return ext4_htree_next_block(dir, hash, frame, frames, start_hash); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_htree_next_block_test); + +int dx_make_map_test(struct inode *dir, struct buffer_head *bh, + struct dx_hash_info *hinfo, + struct dx_map_entry *map_tail) +{ + return dx_make_map(dir, bh, hinfo, map_tail); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(dx_make_map_test); + +void dx_sort_map_test(struct dx_map_entry *map, unsigned int count) +{ + dx_sort_map(map, count); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(dx_sort_map_test); + +void dx_insert_block_test(struct dx_frame *frame, u32 hash, ext4_lblk_t block) +{ + dx_insert_block(frame, hash, block); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(dx_insert_block_test); + +struct ext4_dir_entry_2 *dx_move_dirents_test(struct inode *dir, char *from, + char *to, + struct dx_map_entry *map, + int count, + unsigned int blocksize) +{ + return dx_move_dirents(dir, from, to, map, count, blocksize); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(dx_move_dirents_test); + +struct ext4_dir_entry_2 *dx_pack_dirents_test(struct inode *dir, char *base, + unsigned int blocksize) +{ + return dx_pack_dirents(dir, base, blocksize); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(dx_pack_dirents_test); + +struct ext4_dir_entry_2 *do_split_test(handle_t *handle, struct inode *dir, + struct buffer_head **bh, + struct dx_frame *frame, + struct dx_hash_info *hinfo) +{ + return do_split(handle, dir, bh, frame, hinfo); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(do_split_test); + +bool ext4_check_dx_root_test(struct inode *dir, struct dx_root *root) +{ + return ext4_check_dx_root(dir, root); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_check_dx_root_test); + +struct buffer_head *ext4_find_entry_test(struct inode *dir, + const struct qstr *d_name, + struct ext4_dir_entry_2 **res_dir, + int *inlined) +{ + return ext4_find_entry(dir, d_name, res_dir, inlined); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_find_entry_test); + +struct buffer_head *ext4_lookup_entry_test(struct inode *dir, + struct dentry *dentry, + struct ext4_dir_entry_2 **res_dir) +{ + return ext4_lookup_entry(dir, dentry, res_dir); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_lookup_entry_test); + +int ext4_add_entry_test(handle_t *handle, struct dentry *dentry, + struct inode *inode) +{ + return ext4_add_entry(handle, dentry, inode); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_add_entry_test); + +int ext4_delete_entry_test(handle_t *handle, struct inode *dir, + struct ext4_dir_entry_2 *de_del, + struct buffer_head *bh) +{ + return ext4_delete_entry(handle, dir, de_del, bh); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_delete_entry_test); + +void ext4_inc_count_test(struct inode *inode) +{ + ext4_inc_count(inode); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inc_count_test); + +void ext4_dec_count_test(struct inode *inode) +{ + ext4_dec_count(inode); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_dec_count_test); + +int ext4_init_symlink_block_test(handle_t *handle, struct inode *inode, + struct fscrypt_str *disk_link) +{ + return ext4_init_symlink_block(handle, inode, disk_link); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_init_symlink_block_test); +#endif diff --git a/fs/ext4/namei.h b/fs/ext4/namei.h new file mode 100644 index 00000000000000..2539ed588966ba --- /dev/null +++ b/fs/ext4/namei.h @@ -0,0 +1,213 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* + * Internal definitions and helpers for fs/ext4/namei.c + */ + +#ifndef _EXT4_NAMEI_H +#define _EXT4_NAMEI_H + +#include "ext4.h" + +/* + * Hints to ext4_read_dirblock regarding whether we expect a directory + * block being read to be an index block, or a block containing + * directory entries (and if the latter, whether it was found via a + * logical block in an htree index block). This is used to control + * what sort of sanity checkinig ext4_read_dirblock() will do on the + * directory block read from the storage device. EITHER will means + * the caller doesn't know what kind of directory block will be read, + * so no specific verification will be done. + */ +enum dirblock_type { + EITHER, INDEX, DIRENT, DIRENT_HTREE +}; + +struct fake_dirent { + __le32 inode; + __le16 rec_len; + u8 name_len; + u8 file_type; +}; + +struct dx_countlimit { + __le16 limit; + __le16 count; +}; + +struct dx_entry { + __le32 hash; + __le32 block; +}; + +/* + * dx_root_info is laid out so that if it should somehow get overlaid by a + * dirent the two low bits of the hash version will be zero. Therefore, the + * hash version mod 4 should never be 0. Sincerely, the paranoia department. + */ +struct dx_root { + struct fake_dirent dot; + char dot_name[4]; + struct fake_dirent dotdot; + char dotdot_name[4]; + struct dx_root_info { + __le32 reserved_zero; + u8 hash_version; + u8 info_length; /* 8 */ + u8 indirect_levels; + u8 unused_flags; + } info; + struct dx_entry entries[]; +}; + +struct dx_node { + struct fake_dirent fake; + struct dx_entry entries[]; +}; + +struct dx_frame { + struct buffer_head *bh; + struct dx_entry *entries; + struct dx_entry *at; +}; + +struct dx_map_entry { + u32 hash; + u16 offs; + u16 size; +}; + +/* + * This goes at the end of each htree block. + */ +struct dx_tail { + u32 dt_reserved; + __le32 dt_checksum; /* crc32c(uuid+inum+dirblock) */ +}; + +/* + * p is at least 6 bytes before the end of page + */ +static inline struct ext4_dir_entry_2 * +ext4_next_entry(struct ext4_dir_entry_2 *p, unsigned long blocksize) +{ + return (struct ext4_dir_entry_2 *)((char *)p + + ext4_rec_len_from_disk(p->rec_len, blocksize)); +} + +/* + * Future: use high four bits of block for coalesce-on-delete flags + * Mask them off for now. + */ +static inline ext4_lblk_t dx_get_block(struct dx_entry *entry) +{ + return le32_to_cpu(entry->block) & 0x0fffffff; +} + +static inline void dx_set_block(struct dx_entry *entry, ext4_lblk_t value) +{ + entry->block = cpu_to_le32(value); +} + +static inline unsigned int dx_get_hash(struct dx_entry *entry) +{ + return le32_to_cpu(entry->hash); +} + +static inline void dx_set_hash(struct dx_entry *entry, unsigned int value) +{ + entry->hash = cpu_to_le32(value); +} + +static inline unsigned int dx_get_count(struct dx_entry *entries) +{ + return le16_to_cpu(((struct dx_countlimit *)entries)->count); +} + +static inline unsigned int dx_get_limit(struct dx_entry *entries) +{ + return le16_to_cpu(((struct dx_countlimit *)entries)->limit); +} + +static inline void dx_set_count(struct dx_entry *entries, unsigned int value) +{ + ((struct dx_countlimit *)entries)->count = cpu_to_le16(value); +} + +static inline void dx_set_limit(struct dx_entry *entries, unsigned int value) +{ + ((struct dx_countlimit *)entries)->limit = cpu_to_le16(value); +} + +static inline unsigned int dx_root_limit(struct inode *dir, unsigned int infosize) +{ + unsigned int entry_space = dir->i_sb->s_blocksize - + ext4_dir_rec_len(1, NULL) - + ext4_dir_rec_len(2, NULL) - infosize; + + if (ext4_has_feature_metadata_csum(dir->i_sb)) + entry_space -= sizeof(struct dx_tail); + return entry_space / sizeof(struct dx_entry); +} + +static inline unsigned int dx_node_limit(struct inode *dir) +{ + unsigned int entry_space = dir->i_sb->s_blocksize - + ext4_dir_rec_len(0, dir); + + if (ext4_has_feature_metadata_csum(dir->i_sb)) + entry_space -= sizeof(struct dx_tail); + return entry_space / sizeof(struct dx_entry); +} + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +struct buffer_head *ext4_append_test(handle_t *handle, struct inode *inode, + ext4_lblk_t *block); +struct buffer_head *ext4_read_dirblock_test(struct inode *inode, + ext4_lblk_t block, + enum dirblock_type type); +void ext4_dx_csum_set_test(struct inode *inode, struct ext4_dir_entry *dirent); +int ext4_dx_csum_verify_test(struct inode *inode, + struct ext4_dir_entry *dirent); +struct dx_frame *dx_probe_test(struct ext4_filename *fname, struct inode *dir, + struct dx_hash_info *hinfo, + struct dx_frame *frame_in); +void dx_release_test(struct dx_frame *frames); +int ext4_htree_next_block_test(struct inode *dir, __u32 hash, + struct dx_frame *frame, + struct dx_frame *frames, __u32 *start_hash); +int dx_make_map_test(struct inode *dir, struct buffer_head *bh, + struct dx_hash_info *hinfo, + struct dx_map_entry *map_tail); +void dx_sort_map_test(struct dx_map_entry *map, unsigned int count); +void dx_insert_block_test(struct dx_frame *frame, u32 hash, ext4_lblk_t block); +struct ext4_dir_entry_2 *dx_move_dirents_test(struct inode *dir, char *from, + char *to, + struct dx_map_entry *map, + int count, + unsigned int blocksize); +struct ext4_dir_entry_2 *dx_pack_dirents_test(struct inode *dir, char *base, + unsigned int blocksize); +struct ext4_dir_entry_2 *do_split_test(handle_t *handle, struct inode *dir, + struct buffer_head **bh, + struct dx_frame *frame, + struct dx_hash_info *hinfo); +bool ext4_check_dx_root_test(struct inode *dir, struct dx_root *root); +struct buffer_head *ext4_find_entry_test(struct inode *dir, + const struct qstr *d_name, + struct ext4_dir_entry_2 **res_dir, + int *inlined); +struct buffer_head *ext4_lookup_entry_test(struct inode *dir, + struct dentry *dentry, + struct ext4_dir_entry_2 **res_dir); +int ext4_add_entry_test(handle_t *handle, struct dentry *dentry, + struct inode *inode); +int ext4_delete_entry_test(handle_t *handle, struct inode *dir, + struct ext4_dir_entry_2 *de_del, + struct buffer_head *bh); +void ext4_inc_count_test(struct inode *inode); +void ext4_dec_count_test(struct inode *inode); +int ext4_init_symlink_block_test(handle_t *handle, struct inode *inode, + struct fscrypt_str *disk_link); +#endif /* CONFIG_EXT4_KUNIT_TESTS */ + +#endif /* _EXT4_NAMEI_H */ diff --git a/fs/ext4/orphan-test.c b/fs/ext4/orphan-test.c new file mode 100644 index 00000000000000..bd60976a840d2f --- /dev/null +++ b/fs/ext4/orphan-test.c @@ -0,0 +1,2372 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for fs/ext4/orphan.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_jbd2.h" +#include "ext4_extents.h" +#include "xattr.h" + +/* + * Mock filesystem geometry: + * - 2 block groups, 1024-byte blocks (254 orphan entries per orphan block) + * - 64 inodes per group (128 total inodes), 256-byte inodes + * - s_first_ino = 11, s_orphan_file_inum = 12 + */ +#define ORPHAN_TEST_NGROUPS 2U +#define ORPHAN_TEST_BLK_SIZE 1024U +#define ORPHAN_TEST_BLK_BITS 10U +#define ORPHAN_TEST_BLOCKS_PER_GRP 1024U +#define ORPHAN_TEST_FIRST_DATA_BLK 1U +#define ORPHAN_TEST_TOTAL_BLKS (ORPHAN_TEST_FIRST_DATA_BLK + \ + ORPHAN_TEST_NGROUPS * \ + ORPHAN_TEST_BLOCKS_PER_GRP) +#define ORPHAN_TEST_INODE_SIZE 256U +#define ORPHAN_TEST_EXTRA_ISIZE 32U +#define ORPHAN_TEST_INODES_PER_BLK (ORPHAN_TEST_BLK_SIZE / \ + ORPHAN_TEST_INODE_SIZE) +#define ORPHAN_TEST_INODES_PER_GRP 64U +#define ORPHAN_TEST_ITB_PER_GRP (ORPHAN_TEST_INODES_PER_GRP / \ + ORPHAN_TEST_INODES_PER_BLK) +#define ORPHAN_TEST_TOTAL_INODES (ORPHAN_TEST_NGROUPS * \ + ORPHAN_TEST_INODES_PER_GRP) +#define ORPHAN_TEST_FIRST_INO 11U +#define ORPHAN_TEST_ORPHAN_INO 12U +#define ORPHAN_TEST_CSUM_SEED 0x4d7a19c5U +#define ORPHAN_TEST_OF_CSUM_SEED 0x91e23b77U +#define ORPHAN_TEST_INODES_PER_OB 254U + +#define ORPHAN_TEST_GDESC_BLK 2ULL +#define ORPHAN_TEST_OB_BASE_BLK 500ULL +#define ORPHAN_TEST_MAX_OB_BLKS 4U +#define ORPHAN_TEST_MAX_SLOTS 16U + +struct orphan_test_ibitmap { + struct buffer_head bh; + char buf[ORPHAN_TEST_BLK_SIZE] __aligned(8); +}; + +struct orphan_test_ob_blk { + bool present; + int bread_err; + bool return_hole; + struct buffer_head bh; + char buf[ORPHAN_TEST_BLK_SIZE] __aligned(8); +}; + +struct orphan_test_inode_slot { + bool in_use; + unsigned long ino; + bool handoff_to_iget; + struct inode *inode; + struct buffer_head iloc_bh; + char raw_buf[ORPHAN_TEST_BLK_SIZE] __aligned(8); +}; + +struct orphan_test_ctx { + struct super_block *sb; + struct ext4_sb_info sbi; + struct ext4_super_block es; + struct blockgroup_lock bgl; + struct gendisk bdev_disk; + struct block_device bdev; + struct request_queue bdev_queue; + struct inode bd_inode; + struct buffer_head sb_bh; + struct buffer_head gdesc_bh; + char gdesc_buf[ORPHAN_TEST_BLK_SIZE] __aligned(8); + + struct ext4_group_desc gdps[ORPHAN_TEST_NGROUPS]; + struct ext4_group_info *grp_infos[ORPHAN_TEST_NGROUPS]; + struct ext4_group_info *grp_info_ptrs[16]; + struct ext4_group_info **grp_info_slice[1]; + struct orphan_test_ibitmap ibitmaps[ORPHAN_TEST_NGROUPS]; + + journal_t mock_journal; + handle_t mock_handle; + + struct orphan_test_ob_blk ob_pool[ORPHAN_TEST_MAX_OB_BLKS]; + struct ext4_orphan_block static_binfo[ORPHAN_TEST_MAX_OB_BLKS]; + + /* Shared read-only block used for 512-block max-size boundary test */ + bool use_boundary_bh; + struct buffer_head boundary_bh; + char boundary_buf[ORPHAN_TEST_BLK_SIZE] __aligned(8); + char frozen_buf[ORPHAN_TEST_BLK_SIZE] __aligned(8); +#ifdef CONFIG_QUOTA + char qf_name[16]; +#endif + + struct orphan_test_inode_slot slots[ORPHAN_TEST_MAX_SLOTS]; + bool orphan_info_allocated; + bool enable_real_evict; + + /* Fault injection controls */ + int fail_write_access_err; + int fail_write_access_on_call; + int fail_dirty_metadata_err; + int fail_dirty_metadata_on_call; + int fail_get_iloc_err; + int fail_get_iloc_on_call; + int fail_mark_iloc_err; + int fail_mark_iloc_on_call; + int fail_mark_inode_dirty_err; + int fail_iget_err; + unsigned long fail_iget_ino; + int stub_truncate_err; + + /* Call tracking & verification state */ + unsigned int write_access_calls; + enum ext4_journal_trigger_type last_trigger_type; + unsigned int dirty_metadata_calls; + unsigned int get_iloc_calls; + unsigned int mark_iloc_calls; + unsigned int iget_calls; + unsigned int truncate_calls; + bool saw_rw_during_cleanup; + + unsigned long freed_inos[ORPHAN_TEST_MAX_SLOTS]; + unsigned int nr_freed_inos; + ext4_fsblk_t last_freed_blk; + unsigned long total_freed_blks; +}; + +static inline ext4_fsblk_t orphan_test_ibitmap_blk(ext4_group_t g) +{ + return ORPHAN_TEST_FIRST_DATA_BLK + + (ext4_fsblk_t)g * ORPHAN_TEST_BLOCKS_PER_GRP + 3ULL; +} + +static inline ext4_fsblk_t orphan_test_bbitmap_blk(ext4_group_t g) +{ + return ORPHAN_TEST_FIRST_DATA_BLK + + (ext4_fsblk_t)g * ORPHAN_TEST_BLOCKS_PER_GRP + 2ULL; +} + +static inline ext4_fsblk_t orphan_test_itable_blk(ext4_group_t g) +{ + return ORPHAN_TEST_FIRST_DATA_BLK + + (ext4_fsblk_t)g * ORPHAN_TEST_BLOCKS_PER_GRP + 4ULL; +} + +static void orphan_test_sb_upd_work(struct work_struct *work) +{ +} + +static void orphan_test_err_timer(struct timer_list *t) +{ +} + +static void orphan_test_init_ei_fields(struct ext4_inode_info *ei) +{ + inode_set_iversion(&ei->vfs_inode, 1); + ei->i_flags = 0; + ext4_clear_state_flags(ei); + spin_lock_init(&ei->i_raw_lock); + ei->i_prealloc_node = RB_ROOT; + atomic_set(&ei->i_prealloc_active, 0); + rwlock_init(&ei->i_prealloc_lock); + ext4_es_init_tree(&ei->i_es_tree); + rwlock_init(&ei->i_es_lock); + INIT_LIST_HEAD(&ei->i_es_list); + ei->i_es_all_nr = 0; + ei->i_es_shk_nr = 0; + ei->i_es_shrink_lblk = 0; + ei->i_es_seq = 0; + ei->i_reserved_data_blocks = 0; + spin_lock_init(&ei->i_block_reservation_lock); + ext4_init_pending_tree(&ei->i_pending_tree); +#ifdef CONFIG_QUOTA + ei->i_reserved_quota = 0; + memset(&ei->i_dquot, 0, sizeof(ei->i_dquot)); +#endif +#ifdef CONFIG_FS_ENCRYPTION + ei->i_crypt_info = NULL; +#endif + ei->jinode = NULL; + init_rwsem(&ei->xattr_sem); + INIT_LIST_HEAD(&ei->i_rsv_conversion_list); + spin_lock_init(&ei->i_completed_io_lock); + ei->i_sync_tid = 0; + ei->i_datasync_tid = 0; + INIT_LIST_HEAD(&ei->i_orphan); + ext4_fc_init_inode(&ei->vfs_inode); + spin_lock_init(&ei->i_fc_lock); + ei->i_metadata_bhs = NULL; + ei->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + ei->i_extra_isize = ORPHAN_TEST_EXTRA_ISIZE; + ei->i_csum_seed = ORPHAN_TEST_OF_CSUM_SEED; + ei->i_last_alloc_group = ~0U; +} + +static struct inode *orphan_test_alloc_inode(struct super_block *sb) +{ + struct ext4_inode_info *ei; + + ei = kzalloc_obj(*ei); + if (!ei) + return NULL; + + init_rwsem(&ei->i_data_sem); + inode_init_once(&ei->vfs_inode); + orphan_test_init_ei_fields(ei); + return &ei->vfs_inode; +} + +static void orphan_test_evict_inode(struct inode *inode) +{ + struct kunit *test = kunit_get_current_test(); + struct orphan_test_ctx *ctx = test ? test->priv : NULL; + + if (ctx && ctx->enable_real_evict) { + ext4_evict_inode(inode); + return; + } + truncate_inode_pages_final(&inode->i_data); + ext4_clear_inode(inode); +} + +static void orphan_test_destroy_inode(struct inode *inode) +{ + kfree(ext4_i_metadata_bhs(inode)); + EXT4_I(inode)->i_metadata_bhs = NULL; +} + +static void orphan_test_free_inode_mem(struct inode *inode) +{ + kfree(EXT4_I(inode)); +} + +#ifdef CONFIG_QUOTA +static struct dquot __rcu **orphan_test_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} + +static qsize_t *orphan_test_get_reserved_space(struct inode *inode) +{ + return &EXT4_I(inode)->i_reserved_quota; +} + +static const struct dquot_operations orphan_test_qops = { + .get_reserved_space = orphan_test_get_reserved_space, + .alloc_dquot = dquot_alloc, + .destroy_dquot = dquot_destroy, + .get_next_id = dquot_get_next_id, +}; +#endif + +static const struct super_operations orphan_test_sops = { + .alloc_inode = orphan_test_alloc_inode, + .evict_inode = orphan_test_evict_inode, + .destroy_inode = orphan_test_destroy_inode, + .free_inode = orphan_test_free_inode_mem, + .drop_inode = inode_just_drop, +#ifdef CONFIG_QUOTA + .get_dquots = orphan_test_get_dquots, +#endif +}; + +static int orphan_test_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static struct file_system_type orphan_test_fs_type = { + .name = "ext4_orphan_kunit", + .init_fs_context = orphan_test_init_fs_context, + .kill_sb = kill_anon_super, +}; + +/* --- Slot & Orphan Block Helpers --- */ + +static struct orphan_test_inode_slot * +orphan_test_find_slot(struct orphan_test_ctx *ctx, unsigned long ino) +{ + unsigned int i; + + for (i = 0; i < ORPHAN_TEST_MAX_SLOTS; i++) { + if (ctx->slots[i].in_use && ctx->slots[i].ino == ino) + return &ctx->slots[i]; + } + return NULL; +} + +static void orphan_test_set_ibitmap_bit(struct orphan_test_ctx *ctx, + unsigned long ino, bool set) +{ + ext4_group_t g = (ino - 1) / ORPHAN_TEST_INODES_PER_GRP; + unsigned int bit = (ino - 1) % ORPHAN_TEST_INODES_PER_GRP; + + if (g >= ORPHAN_TEST_NGROUPS) + return; + if (set) + ext4_set_bit(bit, ctx->ibitmaps[g].buf); + else + ext4_clear_bit(bit, ctx->ibitmaps[g].buf); +} + +static struct orphan_test_inode_slot * +orphan_test_create_inode(struct kunit *test, struct orphan_test_ctx *ctx, + unsigned long ino, umode_t mode, unsigned int nlink) +{ + struct orphan_test_inode_slot *slot = NULL; + struct ext4_extent_header *eh; + struct inode *inode; + unsigned int i; + + for (i = 0; i < ORPHAN_TEST_MAX_SLOTS; i++) { + if (!ctx->slots[i].in_use) { + slot = &ctx->slots[i]; + break; + } + } + KUNIT_ASSERT_NOT_NULL(test, slot); + + inode = new_inode(ctx->sb); + KUNIT_ASSERT_NOT_NULL(test, inode); + + memset(slot, 0, sizeof(*slot)); + slot->in_use = true; + slot->ino = ino; + slot->inode = inode; + slot->iloc_bh.b_data = slot->raw_buf; + slot->iloc_bh.b_size = ORPHAN_TEST_BLK_SIZE; + slot->iloc_bh.b_bdev = &ctx->bdev; + slot->iloc_bh.b_blocknr = orphan_test_itable_blk(0) + i; + atomic_set(&slot->iloc_bh.b_count, 1); + set_buffer_uptodate(&slot->iloc_bh); + + inode->i_ino = ino; + inode->i_mode = mode; + inode->i_blkbits = ctx->sb->s_blocksize_bits; + inode->i_flags |= S_NOQUOTA; + set_nlink(inode, nlink); + EXT4_I(inode)->i_block_group = (ino - 1) / ORPHAN_TEST_INODES_PER_GRP; + + if (S_ISREG(mode) || S_ISDIR(mode)) { + ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS); + eh = ext_inode_hdr(inode); + memset(eh, 0, sizeof(EXT4_I(inode)->i_data)); + eh->eh_magic = EXT4_EXT_MAGIC; + eh->eh_entries = 0; + eh->eh_max = cpu_to_le16((sizeof(EXT4_I(inode)->i_data) - + sizeof(*eh)) / + sizeof(struct ext4_extent)); + eh->eh_depth = 0; + } + + orphan_test_set_ibitmap_bit(ctx, ino, true); + return slot; +} + +static void orphan_test_add_single_extent(struct inode *inode, + ext4_lblk_t lblk, ext4_fsblk_t pblk, + unsigned short len) +{ + struct ext4_extent_header *eh = ext_inode_hdr(inode); + struct ext4_extent *ex = EXT_FIRST_EXTENT(eh); + + eh->eh_entries = cpu_to_le16(1); + ex->ee_block = cpu_to_le32(lblk); + ex->ee_len = cpu_to_le16(len); + ext4_ext_store_pblock(ex, pblk); + inode->i_blocks = (blkcnt_t)len << (inode->i_blkbits - 9); +} + +static __u32 orphan_test_calc_ob_csum(struct super_block *sb, __u32 seed, + ext4_fsblk_t blocknr, const void *data) +{ + __le64 dsk_block_nr = cpu_to_le64(blocknr); + size_t payload_bytes = sb->s_blocksize - + sizeof(struct ext4_orphan_block_tail); + __u32 csum; + + csum = crc32c(seed, &dsk_block_nr, sizeof(dsk_block_nr)); + return crc32c(csum, data, payload_bytes); +} + +static void orphan_test_seal_ob_bh(struct super_block *sb, __u32 seed, + struct buffer_head *bh, __u32 magic) +{ + struct ext4_orphan_block_tail *ot; + __u32 csum; + + ot = (struct ext4_orphan_block_tail *)(bh->b_data + sb->s_blocksize - + sizeof(*ot)); + ot->ob_magic = cpu_to_le32(magic); + csum = orphan_test_calc_ob_csum(sb, seed, bh->b_blocknr, bh->b_data); + ot->ob_checksum = cpu_to_le32(csum); +} + +static void orphan_test_setup_static_orphan_file(struct orphan_test_ctx *ctx, + int num_blocks) +{ + struct super_block *sb = ctx->sb; + struct ext4_orphan_info *oi = &ctx->sbi.s_orphan_info; + int i; + + ext4_set_feature_orphan_file(sb); + oi->of_blocks = num_blocks; + oi->of_csum_seed = ORPHAN_TEST_OF_CSUM_SEED; + oi->of_binfo = ctx->static_binfo; + ctx->orphan_info_allocated = false; + + for (i = 0; i < num_blocks; i++) { + struct orphan_test_ob_blk *oblk = &ctx->ob_pool[i]; + + memset(oblk, 0, sizeof(*oblk)); + oblk->present = true; + oblk->bh.b_data = oblk->buf; + oblk->bh.b_size = sb->s_blocksize; + oblk->bh.b_bdev = &ctx->bdev; + oblk->bh.b_blocknr = ORPHAN_TEST_OB_BASE_BLK + i; + atomic_set(&oblk->bh.b_count, 1); + set_buffer_uptodate(&oblk->bh); + orphan_test_seal_ob_bh(sb, oi->of_csum_seed, &oblk->bh, + EXT4_ORPHAN_BLOCK_MAGIC); + + ctx->static_binfo[i].ob_bh = &oblk->bh; + atomic_set(&ctx->static_binfo[i].ob_free_entries, + ORPHAN_TEST_INODES_PER_OB); + } +} + +static void orphan_test_reset_faults(struct orphan_test_ctx *ctx) +{ + ctx->fail_write_access_err = 0; + ctx->fail_write_access_on_call = 0; + ctx->fail_dirty_metadata_err = 0; + ctx->fail_dirty_metadata_on_call = 0; + ctx->fail_get_iloc_err = 0; + ctx->fail_get_iloc_on_call = 0; + ctx->fail_mark_iloc_err = 0; + ctx->fail_mark_iloc_on_call = 0; + ctx->fail_mark_inode_dirty_err = 0; + ctx->fail_iget_err = 0; + ctx->fail_iget_ino = 0; + ctx->stub_truncate_err = 0; + + ctx->write_access_calls = 0; + ctx->last_trigger_type = EXT4_JTR_NONE; + ctx->dirty_metadata_calls = 0; + ctx->get_iloc_calls = 0; + ctx->mark_iloc_calls = 0; + ctx->iget_calls = 0; + ctx->truncate_calls = 0; + ctx->saw_rw_during_cleanup = false; + ctx->nr_freed_inos = 0; + ctx->last_freed_blk = 0; + ctx->total_freed_blks = 0; + ctx->sbi.s_mount_state &= ~EXT4_ERROR_FS; +} + +static bool orphan_test_was_ino_freed(const struct orphan_test_ctx *ctx, + unsigned long ino) +{ + unsigned int i; + + for (i = 0; i < ctx->nr_freed_inos; i++) { + if (ctx->freed_inos[i] == ino) + return true; + } + return false; +} + +static int orphan_test_call_add(handle_t *handle, struct inode *inode) +{ + int err; + + inode_lock(inode); + err = ext4_orphan_add(handle, inode); + inode_unlock(inode); + return err; +} + +static int orphan_test_call_del(handle_t *handle, struct inode *inode) +{ + int err; + + inode_lock(inode); + err = ext4_orphan_del(handle, inode); + inode_unlock(inode); + return err; +} + +/* --- KUnit Static Stubs --- */ + +static int +orphan_test_get_write_access_stub(const char *where, unsigned int line, + handle_t *handle, struct super_block *sb, + struct buffer_head *bh, + enum ext4_journal_trigger_type trigger_type) +{ + struct kunit *test = kunit_get_current_test(); + struct orphan_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) + return 0; + + ctx->write_access_calls++; + ctx->last_trigger_type = trigger_type; + if (ctx->fail_write_access_err && + (!ctx->fail_write_access_on_call || + ctx->write_access_calls == (unsigned int)ctx->fail_write_access_on_call)) + return ctx->fail_write_access_err; + return 0; +} + +static int orphan_test_dirty_metadata_stub(const char *where, unsigned int line, + handle_t *handle, + struct inode *inode, + struct buffer_head *bh) +{ + struct kunit *test = kunit_get_current_test(); + struct orphan_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) + return 0; + + ctx->dirty_metadata_calls++; + if (ctx->fail_dirty_metadata_err && + (!ctx->fail_dirty_metadata_on_call || + ctx->dirty_metadata_calls == (unsigned int)ctx->fail_dirty_metadata_on_call)) + return ctx->fail_dirty_metadata_err; + + if (bh) { + set_buffer_uptodate(bh); + clear_buffer_dirty(bh); + } + return 0; +} + +static int orphan_test_get_inode_loc_stub(struct inode *inode, + struct ext4_iloc *iloc) +{ + struct kunit *test = kunit_get_current_test(); + struct orphan_test_ctx *ctx = test ? test->priv : NULL; + struct orphan_test_inode_slot *slot; + + if (!ctx) + return -EIO; + + ctx->get_iloc_calls++; + if (ctx->fail_get_iloc_err && + (!ctx->fail_get_iloc_on_call || + ctx->get_iloc_calls == (unsigned int)ctx->fail_get_iloc_on_call)) + return ctx->fail_get_iloc_err; + + slot = orphan_test_find_slot(ctx, inode->i_ino); + if (!slot) + return -ENOENT; + + get_bh(&slot->iloc_bh); + iloc->bh = &slot->iloc_bh; + iloc->offset = 0; + iloc->block_group = EXT4_I(inode)->i_block_group; + return 0; +} + +static int orphan_test_mark_iloc_dirty_stub(handle_t *handle, + struct inode *inode, + struct ext4_iloc *iloc) +{ + struct kunit *test = kunit_get_current_test(); + struct orphan_test_ctx *ctx = test ? test->priv : NULL; + int err = 0; + + if (ctx) { + ctx->mark_iloc_calls++; + if (ctx->fail_mark_iloc_err && + (!ctx->fail_mark_iloc_on_call || + ctx->mark_iloc_calls == (unsigned int)ctx->fail_mark_iloc_on_call)) + err = ctx->fail_mark_iloc_err; + } + + /* Real ext4_mark_iloc_dirty() always drops iloc->bh */ + brelse(iloc->bh); + iloc->bh = NULL; + return err; +} + +static int orphan_test_mark_inode_dirty_stub(handle_t *handle, + struct inode *inode, + const char *func, + unsigned int line) +{ + struct kunit *test = kunit_get_current_test(); + struct orphan_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) + return 0; + return ctx->fail_mark_inode_dirty_err; +} + +static struct inode *orphan_test_iget_stub(struct super_block *sb, + unsigned long ino, + ext4_iget_flags flags, + const char *function, + unsigned int line) +{ + struct kunit *test = kunit_get_current_test(); + struct orphan_test_ctx *ctx = test ? test->priv : NULL; + struct orphan_test_inode_slot *slot; + struct inode *inode; + + if (!ctx) + return ERR_PTR(-EIO); + + ctx->iget_calls++; + if (ctx->fail_iget_err && + (!ctx->fail_iget_ino || ctx->fail_iget_ino == ino)) + return ERR_PTR(ctx->fail_iget_err); + + slot = orphan_test_find_slot(ctx, ino); + if (!slot || !slot->inode) + return ERR_PTR(-ENOENT); + + inode = slot->inode; + if (slot->handoff_to_iget) + slot->inode = NULL; + else + ihold(inode); + return inode; +} + +static struct buffer_head *orphan_test_getblk_stub(handle_t *handle, + struct inode *inode, + ext4_lblk_t block, + int map_flags) +{ + struct kunit *test = kunit_get_current_test(); + struct orphan_test_ctx *ctx = test ? test->priv : NULL; + struct orphan_test_ob_blk *oblk; + + if (!ctx) + return ERR_PTR(-EIO); + + if (ctx->use_boundary_bh) { + get_bh(&ctx->boundary_bh); + return &ctx->boundary_bh; + } + + if (block >= ORPHAN_TEST_MAX_OB_BLKS) + return ERR_PTR(-EFSCORRUPTED); + + oblk = &ctx->ob_pool[block]; + if (oblk->bread_err) + return ERR_PTR(oblk->bread_err); + if (oblk->return_hole || !oblk->present) + return NULL; + + get_bh(&oblk->bh); + return &oblk->bh; +} + +static struct ext4_group_desc * +orphan_test_get_group_desc_stub(struct super_block *sb, + ext4_group_t block_group, + struct buffer_head **bh) +{ + struct kunit *test = kunit_get_current_test(); + struct orphan_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx || block_group >= ORPHAN_TEST_NGROUPS) + return NULL; + if (bh) + *bh = &ctx->gdesc_bh; + return &ctx->gdps[block_group]; +} + +static struct buffer_head *orphan_test_sb_getblk_stub(struct super_block *sb, + ext4_fsblk_t block) +{ + struct kunit *test = kunit_get_current_test(); + struct orphan_test_ctx *ctx = test ? test->priv : NULL; + ext4_group_t g; + + if (!ctx) + return NULL; + + for (g = 0; g < ORPHAN_TEST_NGROUPS; g++) { + if (block == orphan_test_ibitmap_blk(g)) { + get_bh(&ctx->ibitmaps[g].bh); + return &ctx->ibitmaps[g].bh; + } + } + return NULL; +} + +static void orphan_test_free_inode_stub(handle_t *handle, struct inode *inode) +{ + struct kunit *test = kunit_get_current_test(); + struct orphan_test_ctx *ctx = test ? test->priv : NULL; + + if (ctx) { + if (!sb_rdonly(inode->i_sb)) + ctx->saw_rw_during_cleanup = true; + if (ctx->nr_freed_inos < ORPHAN_TEST_MAX_SLOTS) + ctx->freed_inos[ctx->nr_freed_inos++] = inode->i_ino; + orphan_test_set_ibitmap_bit(ctx, inode->i_ino, false); + } + ext4_clear_inode(inode); +} + +static void orphan_test_free_blocks_stub(handle_t *handle, struct inode *inode, + struct buffer_head *bh, + ext4_fsblk_t block, + unsigned long count, int flags) +{ + struct kunit *test = kunit_get_current_test(); + struct orphan_test_ctx *ctx = test ? test->priv : NULL; + + if (bh) + brelse(bh); + if (!ctx) + return; + ctx->last_freed_blk = block; + ctx->total_freed_blks += count; +} + +static int orphan_test_truncate_stub(struct inode *inode) +{ + struct kunit *test = kunit_get_current_test(); + struct orphan_test_ctx *ctx = test ? test->priv : NULL; + + if (!ctx) + return 0; + + ctx->truncate_calls++; + if (!sb_rdonly(inode->i_sb)) + ctx->saw_rw_during_cleanup = true; + return ctx->stub_truncate_err; +} + +/* --- Fixture Setup & Teardown --- */ + +static void orphan_test_cleanup(struct orphan_test_ctx *ctx) +{ + handle_t *handle; + unsigned int i; + + ctx->enable_real_evict = false; + ctx->sbi.s_journal = NULL; + ctx->sbi.s_mount_state &= ~EXT4_ORPHAN_FS; + + while ((handle = ext4_journal_current_handle()) != NULL) + ext4_journal_stop(handle); + + if (ctx->orphan_info_allocated) { + ext4_release_orphan_info(ctx->sb); + ctx->orphan_info_allocated = false; + } + memset(&ctx->sbi.s_orphan_info, 0, sizeof(ctx->sbi.s_orphan_info)); + INIT_LIST_HEAD(&ctx->sbi.s_orphan); + + for (i = 0; i < ORPHAN_TEST_MAX_SLOTS; i++) { + struct inode *inode = ctx->slots[i].inode; + + if (!inode) + continue; + INIT_LIST_HEAD(&EXT4_I(inode)->i_orphan); + ext4_clear_inode_state(inode, EXT4_STATE_ORPHAN_FILE); + spin_lock(&inode->i_lock); + inode_state_clear(inode, I_DIRTY_TIME | I_NEW); + spin_unlock(&inode->i_lock); + set_nlink(inode, 1); + iput(inode); + ctx->slots[i].inode = NULL; + } + + deactivate_super(ctx->sb); + rcu_barrier(); + + cancel_work_sync(&ctx->sbi.s_sb_upd_work); + timer_delete_sync(&ctx->sbi.s_err_report); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); +} + +KUNIT_DEFINE_ACTION_WRAPPER(orphan_test_cleanup_action, orphan_test_cleanup, + struct orphan_test_ctx *); + +static int orphan_test_init(struct kunit *test) +{ + struct orphan_test_ctx *ctx; + struct fs_context *fc; + struct super_block *sb; + struct ext4_sb_info *sbi; + struct inode *root_inode; + ext4_group_t g; + unsigned int bit; + int err; + + ctx = kzalloc_obj(*ctx); + KUNIT_ASSERT_NOT_NULL(test, ctx); + test->priv = ctx; + + ctx->bdev.bd_stats = alloc_percpu(struct disk_stats); + if (!ctx->bdev.bd_stats) { + kfree(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc bd_stats"); + } + + fc = fs_context_for_mount(&orphan_test_fs_type, 0); + if (IS_ERR(fc)) { + err = PTR_ERR(fc); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + sb = sget_fc(fc, NULL, set_anon_super_fc); + put_fs_context(fc); + if (IS_ERR(sb)) { + err = PTR_ERR(sb); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + ctx->sb = sb; + sbi = &ctx->sbi; + + sbi->s_sb = sb; + sb->s_fs_info = sbi; + sb->s_op = &orphan_test_sops; +#ifdef CONFIG_QUOTA + sb->dq_op = &orphan_test_qops; +#endif +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; +#endif + sb->s_flags |= SB_ACTIVE; + sb->s_blocksize = ORPHAN_TEST_BLK_SIZE; + sb->s_blocksize_bits = ORPHAN_TEST_BLK_BITS; + sb->s_maxbytes = MAX_LFS_FILESIZE; + sb->s_time_gran = 1; + sb->s_xattr = ext4_xattr_handlers; + strscpy(sb->s_id, "ext4_orphan_kunit", sizeof(sb->s_id)); + + inode_init_once(&ctx->bd_inode); + ctx->bd_inode.i_sb = sb; + ctx->bd_inode.i_blkbits = ORPHAN_TEST_BLK_BITS; + ctx->bd_inode.i_mapping = &ctx->bd_inode.i_data; + ctx->bd_inode.i_data.host = &ctx->bd_inode; + ctx->bdev_queue.limits.logical_block_size = 512; + ctx->bdev_queue.limits.dma_alignment = 511; + ctx->bdev_disk.part0 = &ctx->bdev; + ctx->bdev_disk.queue = &ctx->bdev_queue; + ctx->bdev.bd_disk = &ctx->bdev_disk; + ctx->bdev.bd_queue = &ctx->bdev_queue; + ctx->bdev.bd_mapping = &ctx->bd_inode.i_data; + /* Writable bdev by default so ext4_orphan_cleanup can proceed */ + bdev_clear_flag(&ctx->bdev, BD_READ_ONLY); + sb->s_bdev = &ctx->bdev; + + bgl_lock_init(&ctx->bgl); + sbi->s_blockgroup_lock = &ctx->bgl; + + sbi->s_es = &ctx->es; + ctx->es.s_magic = cpu_to_le16(EXT4_SUPER_MAGIC); + ctx->es.s_first_data_block = cpu_to_le32(ORPHAN_TEST_FIRST_DATA_BLK); + ctx->es.s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + ctx->es.s_creator_os = cpu_to_le32(EXT4_OS_LINUX); + ctx->es.s_inodes_count = cpu_to_le32(ORPHAN_TEST_TOTAL_INODES); + ctx->es.s_inodes_per_group = cpu_to_le32(ORPHAN_TEST_INODES_PER_GRP); + ctx->es.s_blocks_per_group = cpu_to_le32(ORPHAN_TEST_BLOCKS_PER_GRP); + ctx->es.s_clusters_per_group = cpu_to_le32(ORPHAN_TEST_BLOCKS_PER_GRP); + ctx->es.s_first_ino = cpu_to_le32(ORPHAN_TEST_FIRST_INO); + ctx->es.s_orphan_file_inum = cpu_to_le32(ORPHAN_TEST_ORPHAN_INO); + ctx->es.s_inode_size = cpu_to_le16(ORPHAN_TEST_INODE_SIZE); + ctx->es.s_min_extra_isize = cpu_to_le16(ORPHAN_TEST_EXTRA_ISIZE); + ctx->es.s_want_extra_isize = cpu_to_le16(ORPHAN_TEST_EXTRA_ISIZE); + ctx->es.s_checksum_type = EXT4_CRC32C_CHKSUM; + ext4_blocks_count_set(&ctx->es, ORPHAN_TEST_TOTAL_BLKS); + + ext4_set_feature_sparse_super(sb); + ext4_set_feature_extents(sb); + ext4_set_feature_extra_isize(sb); + ext4_set_feature_metadata_csum(sb); + ext4_set_feature_64bit(sb); + + /* Keep sb_bh unmapped so ext4_commit_super() skips bh_submit I/O */ + ctx->sb_bh.b_data = (char *)&ctx->es; + ctx->sb_bh.b_size = sizeof(ctx->es); + ctx->sb_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->sb_bh.b_count, 1); + set_buffer_uptodate(&ctx->sb_bh); + sbi->s_sbh = &ctx->sb_bh; + ext4_superblock_csum_set(sb); + + ctx->gdesc_bh.b_data = ctx->gdesc_buf; + ctx->gdesc_bh.b_size = ORPHAN_TEST_BLK_SIZE; + ctx->gdesc_bh.b_blocknr = ORPHAN_TEST_GDESC_BLK; + ctx->gdesc_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->gdesc_bh.b_count, 1); + set_buffer_uptodate(&ctx->gdesc_bh); + + sbi->s_inode_size = ORPHAN_TEST_INODE_SIZE; + sbi->s_inodes_per_block = ORPHAN_TEST_INODES_PER_BLK; + sbi->s_inodes_per_group = ORPHAN_TEST_INODES_PER_GRP; + sbi->s_itb_per_group = ORPHAN_TEST_ITB_PER_GRP; + sbi->s_first_ino = ORPHAN_TEST_FIRST_INO; + sbi->s_want_extra_isize = ORPHAN_TEST_EXTRA_ISIZE; + sbi->s_blocks_per_group = ORPHAN_TEST_BLOCKS_PER_GRP; + sbi->s_clusters_per_group = ORPHAN_TEST_BLOCKS_PER_GRP; + sbi->s_cluster_ratio = 1; + sbi->s_cluster_bits = 0; + sbi->s_groups_count = ORPHAN_TEST_NGROUPS; + sbi->s_gdb_count = 1; + sbi->s_desc_size = EXT4_MIN_DESC_SIZE_64BIT; + sbi->s_desc_per_block = ORPHAN_TEST_BLK_SIZE / EXT4_MIN_DESC_SIZE_64BIT; + sbi->s_desc_per_block_bits = ilog2(sbi->s_desc_per_block); + sbi->s_bitmap_maxbytes = 0x1ff7ffff000ULL; + sbi->s_csum_seed = ORPHAN_TEST_CSUM_SEED; + + mutex_init(&sbi->s_orphan_lock); + INIT_LIST_HEAD(&sbi->s_orphan); + sbi->s_journal = &ctx->mock_journal; + sbi->s_journal_triggers[EXT4_JTR_ORPHAN_FILE].sb = sb; + sbi->s_journal_triggers[EXT4_JTR_ORPHAN_FILE].tr_triggers.t_frozen = + ext4_orphan_file_block_trigger; + + set_opt(sb, ERRORS_CONT); + set_opt(sb, ORDERED_DATA); + spin_lock_init(&sbi->s_bdev_wb_lock); + spin_lock_init(&sbi->s_error_lock); + spin_lock_init(&sbi->s_md_lock); + INIT_WORK(&sbi->s_sb_upd_work, orphan_test_sb_upd_work); + timer_setup(&sbi->s_err_report, orphan_test_err_timer, 0); + mutex_init(&sbi->s_fc_lock); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_STAGING]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_STAGING]); + + ratelimit_state_init(&sbi->s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + + for (g = 0; g < ORPHAN_TEST_NGROUPS; g++) { + struct orphan_test_ibitmap *ibm = &ctx->ibitmaps[g]; + + ctx->grp_infos[g] = kunit_kzalloc(test, + sizeof(*ctx->grp_infos[g]), + GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->grp_infos[g]); + init_rwsem(&ctx->grp_infos[g]->alloc_sem); + ctx->grp_infos[g]->bb_state = 0; + ctx->grp_info_ptrs[g] = ctx->grp_infos[g]; + + ext4_block_bitmap_set(sb, &ctx->gdps[g], + orphan_test_bbitmap_blk(g)); + ext4_inode_bitmap_set(sb, &ctx->gdps[g], + orphan_test_ibitmap_blk(g)); + ext4_inode_table_set(sb, &ctx->gdps[g], + orphan_test_itable_blk(g)); + + ibm->bh.b_data = ibm->buf; + ibm->bh.b_size = ORPHAN_TEST_BLK_SIZE; + ibm->bh.b_bdev = &ctx->bdev; + ibm->bh.b_blocknr = orphan_test_ibitmap_blk(g); + atomic_set(&ibm->bh.b_count, 1); + if (g == 0) { + for (bit = 0; bit < ORPHAN_TEST_FIRST_INO - 1; bit++) + ext4_set_bit(bit, ibm->buf); + } + ext4_mark_bitmap_end(ORPHAN_TEST_INODES_PER_GRP, + ORPHAN_TEST_BLK_SIZE * 8, ibm->buf); + set_buffer_uptodate(&ibm->bh); + set_bitmap_uptodate(&ibm->bh); + set_buffer_verified(&ibm->bh); + } + ctx->grp_info_slice[0] = ctx->grp_info_ptrs; + rcu_assign_pointer(sbi->s_group_info, ctx->grp_info_slice); + + root_inode = new_inode(sb); + if (!root_inode) { + deactivate_locked_super(sb); + rcu_barrier(); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc root_inode"); + } + root_inode->i_ino = EXT4_ROOT_INO; + root_inode->i_mode = S_IFDIR | 0755; + root_inode->i_op = &simple_dir_inode_operations; + set_nlink(root_inode, 2); + sb->s_root = d_make_root(root_inode); + if (!sb->s_root) { + deactivate_locked_super(sb); + rcu_barrier(); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to create s_root"); + } + + up_write(&sb->s_umount); + + kunit_activate_static_stub(test, __ext4_journal_get_write_access, + orphan_test_get_write_access_stub); + kunit_activate_static_stub(test, __ext4_handle_dirty_metadata, + orphan_test_dirty_metadata_stub); + kunit_activate_static_stub(test, ext4_get_inode_loc, + orphan_test_get_inode_loc_stub); + kunit_activate_static_stub(test, ext4_mark_iloc_dirty, + orphan_test_mark_iloc_dirty_stub); + kunit_activate_static_stub(test, __ext4_mark_inode_dirty, + orphan_test_mark_inode_dirty_stub); + kunit_activate_static_stub(test, __ext4_iget, + orphan_test_iget_stub); + kunit_activate_static_stub(test, ext4_getblk, + orphan_test_getblk_stub); + kunit_activate_static_stub(test, ext4_get_group_desc, + orphan_test_get_group_desc_stub); + kunit_activate_static_stub(test, ext4_sb_getblk, + orphan_test_sb_getblk_stub); + kunit_activate_static_stub(test, ext4_free_inode, + orphan_test_free_inode_stub); + kunit_activate_static_stub(test, ext4_free_blocks, + orphan_test_free_blocks_stub); + + err = kunit_add_action_or_reset(test, orphan_test_cleanup_action, ctx); + KUNIT_ASSERT_EQ(test, err, 0); + ctx->enable_real_evict = true; + return 0; +} + +/* ========================================================================= + * 1. Geometry & Empty-State Helpers + * ========================================================================= + */ + +struct orphan_blksize_param { + const char *desc; + unsigned long blocksize; + unsigned char blocksize_bits; + int expected_inodes_per_ob; +}; + +static const struct orphan_blksize_param orphan_blksize_params[] = { + { "1K_blocksize", 1024, 10, 254 }, + { "2K_blocksize", 2048, 11, 510 }, + { "4K_blocksize", 4096, 12, 1022 }, + { "64K_blocksize", 65536, 16, 16382 }, +}; + +KUNIT_ARRAY_PARAM_DESC(orphan_blksize, orphan_blksize_params, desc); + +static void test_inodes_per_orphan_block_param(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + const struct orphan_blksize_param *p = test->param_value; + + ctx->sb->s_blocksize = p->blocksize; + ctx->sb->s_blocksize_bits = p->blocksize_bits; + + KUNIT_EXPECT_EQ(test, ext4_inodes_per_orphan_block(ctx->sb), + p->expected_inodes_per_ob); +} + +static void test_orphan_file_empty(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + + /* 1. Feature disabled returns 1 regardless of s_orphan_info */ + ext4_clear_feature_orphan_file(sb); + KUNIT_EXPECT_EQ(test, ext4_orphan_file_empty(sb), 1); + + /* 2. Feature enabled with 0 blocks returns 1 */ + ext4_set_feature_orphan_file(sb); + ctx->sbi.s_orphan_info.of_blocks = 0; + KUNIT_EXPECT_EQ(test, ext4_orphan_file_empty(sb), 1); + + /* 3. Multi-block orphan file with all slots free returns 1 */ + orphan_test_setup_static_orphan_file(ctx, 3); + KUNIT_EXPECT_EQ(test, ext4_orphan_file_empty(sb), 1); + + /* 4. Occupied entry in a non-first block makes file non-empty (0) */ + atomic_set(&ctx->static_binfo[2].ob_free_entries, + ORPHAN_TEST_INODES_PER_OB - 1); + KUNIT_EXPECT_EQ(test, ext4_orphan_file_empty(sb), 0); + + /* 5. Restoring free count returns 1 again */ + atomic_set(&ctx->static_binfo[2].ob_free_entries, + ORPHAN_TEST_INODES_PER_OB); + KUNIT_EXPECT_EQ(test, ext4_orphan_file_empty(sb), 1); +} + +/* ========================================================================= + * 2. Superblock Linked-List ext4_orphan_add() + * ========================================================================= + */ + +static void test_orphan_add_early_exits_and_idempotency(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct orphan_test_inode_slot *s1, *s2, *s3, *s4; + int err; + + s1 = orphan_test_create_inode(test, ctx, 15, S_IFREG | 0644, 0); + s2 = orphan_test_create_inode(test, ctx, 16, S_IFREG | 0644, 0); + s3 = orphan_test_create_inode(test, ctx, 17, S_IFREG | 0644, 0); + s4 = orphan_test_create_inode(test, ctx, 18, S_IFREG | 0644, 0); + + /* 1. !sbi->s_journal -> no-op returning 0 */ + ctx->sbi.s_journal = NULL; + err = orphan_test_call_add(&ctx->mock_handle, s1->inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, list_empty(&EXT4_I(s1->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 0U); + KUNIT_EXPECT_EQ(test, ctx->write_access_calls, 0U); + ctx->sbi.s_journal = &ctx->mock_journal; + + /* 2. is_bad_inode(inode) -> no-op returning 0 */ + make_bad_inode(s2->inode); + err = orphan_test_call_add(&ctx->mock_handle, s2->inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, list_empty(&EXT4_I(s2->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, ctx->write_access_calls, 0U); + + /* 3. Idempotent when already on sbi->s_orphan list */ + err = orphan_test_call_add(&ctx->mock_handle, s1->inode); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 15U); + + orphan_test_reset_faults(ctx); + err = orphan_test_call_add(&ctx->mock_handle, s1->inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->write_access_calls, 0U); + KUNIT_EXPECT_EQ(test, ctx->dirty_metadata_calls, 0U); + + /* 4. Idempotent when already tracked via EXT4_STATE_ORPHAN_FILE */ + ext4_set_inode_state(s3->inode, EXT4_STATE_ORPHAN_FILE); + EXT4_I(s3->inode)->i_orphan_idx = 0; + err = orphan_test_call_add(&ctx->mock_handle, s3->inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->write_access_calls, 0U); + + /* 5. I_NEW inode can be added & deleted without holding i_rwsem */ + spin_lock(&s4->inode->i_lock); + inode_state_set(s4->inode, I_NEW); + spin_unlock(&s4->inode->i_lock); + + err = ext4_orphan_add(&ctx->mock_handle, s4->inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 18U); + + err = ext4_orphan_del(&ctx->mock_handle, s4->inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 15U); + + spin_lock(&s4->inode->i_lock); + inode_state_clear(s4->inode, I_NEW); + spin_unlock(&s4->inode->i_lock); +} + +static void test_orphan_add_list_chaining_and_csum(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct orphan_test_inode_slot *s1, *s2, *s3; + __le32 csum_before; + int err; + + s1 = orphan_test_create_inode(test, ctx, 15, S_IFREG | 0644, 0); + s2 = orphan_test_create_inode(test, ctx, 20, S_IFDIR | 0755, 0); + s3 = orphan_test_create_inode(test, ctx, 25, S_IFLNK | 0777, 0); + + /* Corrupt s_checksum first so we verify ext4_superblock_csum_set() */ + ctx->es.s_checksum = 0; + csum_before = ctx->es.s_checksum; + + err = orphan_test_call_add(&ctx->mock_handle, s1->inode); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 15U); + KUNIT_EXPECT_EQ(test, NEXT_ORPHAN(s1->inode), 0U); + KUNIT_EXPECT_NE(test, le32_to_cpu(ctx->es.s_checksum), + le32_to_cpu(csum_before)); + KUNIT_EXPECT_EQ(test, atomic_read(&s1->iloc_bh.b_count), 1); + + err = orphan_test_call_add(&ctx->mock_handle, s2->inode); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 20U); + KUNIT_EXPECT_EQ(test, NEXT_ORPHAN(s2->inode), 15U); + + err = orphan_test_call_add(&ctx->mock_handle, s3->inode); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 25U); + KUNIT_EXPECT_EQ(test, NEXT_ORPHAN(s3->inode), 20U); + + /* In-memory list head order must match LIFO insertion: s3 -> s2 -> s1 */ + KUNIT_EXPECT_PTR_EQ(test, ctx->sbi.s_orphan.next, + &EXT4_I(s3->inode)->i_orphan); + KUNIT_EXPECT_PTR_EQ(test, EXT4_I(s3->inode)->i_orphan.next, + &EXT4_I(s2->inode)->i_orphan); + KUNIT_EXPECT_PTR_EQ(test, EXT4_I(s2->inode)->i_orphan.next, + &EXT4_I(s1->inode)->i_orphan); +} + +static void test_orphan_add_next_orphan_bounds(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct orphan_test_inode_slot *s_valid, *s_oob; + int err; + + s_valid = orphan_test_create_inode(test, ctx, 18, S_IFREG | 0644, 0); + s_oob = orphan_test_create_inode(test, ctx, 19, S_IFREG | 0644, 0); + + /* + * 1. NEXT_ORPHAN == s_inodes_count (valid upper boundary): + * inode is treated as already on-disk; skip on-disk modification, + * link into in-memory s_orphan, and brelse(iloc.bh). + */ + NEXT_ORPHAN(s_valid->inode) = ORPHAN_TEST_TOTAL_INODES; + ctx->es.s_last_orphan = cpu_to_le32(15); + orphan_test_reset_faults(ctx); + + err = orphan_test_call_add(&ctx->mock_handle, s_valid->inode); + + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_FALSE(test, list_empty(&EXT4_I(s_valid->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 15U); + KUNIT_EXPECT_EQ(test, NEXT_ORPHAN(s_valid->inode), + ORPHAN_TEST_TOTAL_INODES); + KUNIT_EXPECT_EQ(test, ctx->dirty_metadata_calls, 0U); + KUNIT_EXPECT_EQ(test, ctx->mark_iloc_calls, 0U); + KUNIT_EXPECT_EQ(test, atomic_read(&s_valid->iloc_bh.b_count), 1); + + /* + * 2. NEXT_ORPHAN == s_inodes_count + 1 (invalid / garbage): + * must overwrite NEXT_ORPHAN with old s_last_orphan (15), update + * s_last_orphan to 19, and dirty both sb and iloc. + */ + NEXT_ORPHAN(s_oob->inode) = ORPHAN_TEST_TOTAL_INODES + 1; + orphan_test_reset_faults(ctx); + + err = orphan_test_call_add(&ctx->mock_handle, s_oob->inode); + + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_FALSE(test, list_empty(&EXT4_I(s_oob->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 19U); + KUNIT_EXPECT_EQ(test, NEXT_ORPHAN(s_oob->inode), 15U); + KUNIT_EXPECT_EQ(test, ctx->dirty_metadata_calls, 1U); + KUNIT_EXPECT_EQ(test, ctx->mark_iloc_calls, 1U); + KUNIT_EXPECT_EQ(test, atomic_read(&s_oob->iloc_bh.b_count), 1); +} + +static void test_orphan_add_list_error_paths(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct orphan_test_inode_slot *s1, *s2; + int err; + + s1 = orphan_test_create_inode(test, ctx, 21, S_IFREG | 0644, 0); + s2 = orphan_test_create_inode(test, ctx, 22, S_IFREG | 0644, 0); + + /* 1. ext4_journal_get_write_access(s_sbh) fails */ + orphan_test_reset_faults(ctx); + ctx->fail_write_access_err = -EIO; + ctx->fail_write_access_on_call = 1; + err = orphan_test_call_add(&ctx->mock_handle, s1->inode); + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_TRUE(test, list_empty(&EXT4_I(s1->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 0U); + KUNIT_EXPECT_NE(test, ctx->sbi.s_mount_state & EXT4_ERROR_FS, 0); + + /* 2. ext4_reserve_inode_write (ext4_get_inode_loc) fails */ + orphan_test_reset_faults(ctx); + ctx->fail_get_iloc_err = -EIO; + err = orphan_test_call_add(&ctx->mock_handle, s1->inode); + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_TRUE(test, list_empty(&EXT4_I(s1->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, atomic_read(&s1->iloc_bh.b_count), 1); + + /* + * 3. ext4_handle_dirty_metadata(s_sbh) fails while ext4_mark_iloc_dirty + * succeeds: must still consume iloc.bh and unlink from s_orphan! + */ + orphan_test_reset_faults(ctx); + ctx->fail_dirty_metadata_err = -EIO; + err = orphan_test_call_add(&ctx->mock_handle, s1->inode); + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_EQ(test, ctx->mark_iloc_calls, 1U); + KUNIT_EXPECT_TRUE(test, list_empty(&EXT4_I(s1->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, atomic_read(&s1->iloc_bh.b_count), 1); + + /* + * 4. ext4_handle_dirty_metadata(s_sbh) succeeds while + * ext4_mark_iloc_dirty fails: err = rc and rollback from s_orphan. + */ + orphan_test_reset_faults(ctx); + ctx->es.s_last_orphan = 0; + ctx->fail_mark_iloc_err = -ENOSPC; + err = orphan_test_call_add(&ctx->mock_handle, s2->inode); + KUNIT_EXPECT_EQ(test, err, -ENOSPC); + KUNIT_EXPECT_TRUE(test, list_empty(&EXT4_I(s2->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, atomic_read(&s2->iloc_bh.b_count), 1); +} + +/* ========================================================================= + * 3. Superblock Linked-List ext4_orphan_del() + * ========================================================================= + */ + +static void test_orphan_del_early_exits(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct orphan_test_inode_slot *s1, *s_untracked; + int err; + + s1 = orphan_test_create_inode(test, ctx, 15, S_IFREG | 0644, 0); + s_untracked = orphan_test_create_inode(test, ctx, 16, S_IFREG | 0644, 0); + + /* 1. Untracked inode is a fast no-op */ + orphan_test_reset_faults(ctx); + err = orphan_test_call_del(&ctx->mock_handle, s_untracked->inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, ctx->get_iloc_calls, 0U); + + /* Add s1 to orphan list */ + err = orphan_test_call_add(&ctx->mock_handle, s1->inode); + KUNIT_ASSERT_EQ(test, err, 0); + + /* 2. !s_journal && !(s_mount_state & EXT4_ORPHAN_FS) -> early return 0 */ + ctx->sbi.s_journal = NULL; + ctx->sbi.s_mount_state &= ~EXT4_ORPHAN_FS; + err = orphan_test_call_del(&ctx->mock_handle, s1->inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_FALSE(test, list_empty(&EXT4_I(s1->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 15U); + + /* 3. !s_journal WITH EXT4_ORPHAN_FS proceeds with full deletion */ + ctx->sbi.s_mount_state |= EXT4_ORPHAN_FS; + err = orphan_test_call_del(&ctx->mock_handle, s1->inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, list_empty(&EXT4_I(s1->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 0U); +} + +static void test_orphan_del_list_positions_and_null_handle(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct orphan_test_inode_slot *s1, *s2, *s3; + int err; + + s1 = orphan_test_create_inode(test, ctx, 15, S_IFREG | 0644, 0); + s2 = orphan_test_create_inode(test, ctx, 20, S_IFREG | 0644, 0); + s3 = orphan_test_create_inode(test, ctx, 25, S_IFREG | 0644, 0); + + /* Build chain: s_last_orphan -> 25 (s3) -> 20 (s2) -> 15 (s1) -> 0 */ + KUNIT_ASSERT_EQ(test, orphan_test_call_add(&ctx->mock_handle, s1->inode), + 0); + KUNIT_ASSERT_EQ(test, orphan_test_call_add(&ctx->mock_handle, s2->inode), + 0); + KUNIT_ASSERT_EQ(test, orphan_test_call_add(&ctx->mock_handle, s3->inode), + 0); + + /* 1. Delete middle entry (s2 = 20): s3->NEXT_ORPHAN becomes 15 */ + err = orphan_test_call_del(&ctx->mock_handle, s2->inode); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, list_empty(&EXT4_I(s2->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, NEXT_ORPHAN(s2->inode), 0U); + KUNIT_EXPECT_EQ(test, NEXT_ORPHAN(s3->inode), 15U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 25U); + + /* 2. Delete tail entry (s1 = 15): s3->NEXT_ORPHAN becomes 0 */ + err = orphan_test_call_del(&ctx->mock_handle, s1->inode); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, list_empty(&EXT4_I(s1->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, NEXT_ORPHAN(s1->inode), 0U); + KUNIT_EXPECT_EQ(test, NEXT_ORPHAN(s3->inode), 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 25U); + + /* 3. Delete head entry (s3 = 25): s_last_orphan becomes 0 */ + err = orphan_test_call_del(&ctx->mock_handle, s3->inode); + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, list_empty(&ctx->sbi.s_orphan)); + KUNIT_EXPECT_EQ(test, NEXT_ORPHAN(s3->inode), 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 0U); + + /* 4. handle == NULL removes in-core entry without on-disk updates */ + KUNIT_ASSERT_EQ(test, orphan_test_call_add(&ctx->mock_handle, s1->inode), + 0); + orphan_test_reset_faults(ctx); + + err = orphan_test_call_del(NULL, s1->inode); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, list_empty(&EXT4_I(s1->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 15U); + KUNIT_EXPECT_EQ(test, ctx->get_iloc_calls, 0U); + KUNIT_EXPECT_EQ(test, ctx->write_access_calls, 0U); +} + +static void test_orphan_del_list_error_paths(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct orphan_test_inode_slot *s1, *s2; + int err; + + s1 = orphan_test_create_inode(test, ctx, 15, S_IFREG | 0644, 0); + s2 = orphan_test_create_inode(test, ctx, 20, S_IFREG | 0644, 0); + + /* 1. Initial ext4_reserve_inode_write fails -> still unlinks in-core */ + KUNIT_ASSERT_EQ(test, orphan_test_call_add(&ctx->mock_handle, s1->inode), + 0); + orphan_test_reset_faults(ctx); + ctx->fail_get_iloc_err = -EIO; + ctx->fail_get_iloc_on_call = 1; + err = orphan_test_call_del(&ctx->mock_handle, s1->inode); + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_TRUE(test, list_empty(&EXT4_I(s1->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, atomic_read(&s1->iloc_bh.b_count), 1); + + /* 2. Head delete: ext4_journal_get_write_access(s_sbh) fails */ + ctx->es.s_last_orphan = 0; + NEXT_ORPHAN(s1->inode) = 0; + orphan_test_reset_faults(ctx); + KUNIT_ASSERT_EQ(test, orphan_test_call_add(&ctx->mock_handle, s1->inode), + 0); + orphan_test_reset_faults(ctx); + /* Call 1 is reserve_inode_write(s1); call 2 is get_write_access(s_sbh) */ + ctx->fail_write_access_err = -EIO; + ctx->fail_write_access_on_call = 2; + err = orphan_test_call_del(&ctx->mock_handle, s1->inode); + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 15U); + KUNIT_EXPECT_EQ(test, atomic_read(&s1->iloc_bh.b_count), 1); + + /* 3. Head delete: ext4_handle_dirty_metadata(s_sbh) fails */ + ctx->es.s_last_orphan = 0; + NEXT_ORPHAN(s1->inode) = 0; + orphan_test_reset_faults(ctx); + KUNIT_ASSERT_EQ(test, orphan_test_call_add(&ctx->mock_handle, s1->inode), + 0); + orphan_test_reset_faults(ctx); + ctx->fail_dirty_metadata_err = -EIO; + ctx->fail_dirty_metadata_on_call = 1; + err = orphan_test_call_del(&ctx->mock_handle, s1->inode); + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_EQ(test, atomic_read(&s1->iloc_bh.b_count), 1); + + /* 4. Non-head delete: ext4_reserve_inode_write(i_prev) fails */ + ctx->es.s_last_orphan = 0; + NEXT_ORPHAN(s1->inode) = 0; + NEXT_ORPHAN(s2->inode) = 0; + orphan_test_reset_faults(ctx); + KUNIT_ASSERT_EQ(test, orphan_test_call_add(&ctx->mock_handle, s1->inode), + 0); + KUNIT_ASSERT_EQ(test, orphan_test_call_add(&ctx->mock_handle, s2->inode), + 0); + + orphan_test_reset_faults(ctx); + /* Call 1 is s1 iloc; call 2 is i_prev (s2) iloc */ + ctx->fail_get_iloc_err = -EIO; + ctx->fail_get_iloc_on_call = 2; + err = orphan_test_call_del(&ctx->mock_handle, s1->inode); + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_EQ(test, NEXT_ORPHAN(s2->inode), 15U); + KUNIT_EXPECT_EQ(test, atomic_read(&s1->iloc_bh.b_count), 1); + KUNIT_EXPECT_EQ(test, atomic_read(&s2->iloc_bh.b_count), 1); + + /* 5. Non-head delete: ext4_mark_iloc_dirty(i_prev) fails */ + list_add(&EXT4_I(s1->inode)->i_orphan, &EXT4_I(s2->inode)->i_orphan); + orphan_test_reset_faults(ctx); + ctx->fail_mark_iloc_err = -EIO; + ctx->fail_mark_iloc_on_call = 1; + err = orphan_test_call_del(&ctx->mock_handle, s1->inode); + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_EQ(test, atomic_read(&s1->iloc_bh.b_count), 1); + KUNIT_EXPECT_EQ(test, atomic_read(&s2->iloc_bh.b_count), 1); + + /* 6. Final ext4_mark_iloc_dirty(inode) fails on head delete */ + orphan_test_reset_faults(ctx); + ctx->fail_mark_iloc_err = -ENOSPC; + ctx->fail_mark_iloc_on_call = 1; + err = orphan_test_call_del(&ctx->mock_handle, s2->inode); + KUNIT_EXPECT_EQ(test, err, -ENOSPC); + KUNIT_EXPECT_EQ(test, NEXT_ORPHAN(s2->inode), 0U); + KUNIT_EXPECT_EQ(test, atomic_read(&s2->iloc_bh.b_count), 1); +} + +/* ========================================================================= + * 4. Orphan-File ext4_orphan_add() & ext4_orphan_del() + * ========================================================================= + */ + +static void test_orphan_file_add_and_del_basic(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct orphan_test_inode_slot *s1; + unsigned int blk, off; + __le32 *bdata; + int err; + + orphan_test_setup_static_orphan_file(ctx, 2); + s1 = orphan_test_create_inode(test, ctx, 24, S_IFREG | 0644, 0); + + err = orphan_test_call_add(&ctx->mock_handle, s1->inode); + + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_TRUE(test, + ext4_test_inode_state(s1->inode, EXT4_STATE_ORPHAN_FILE)); + KUNIT_EXPECT_TRUE(test, ext4_inode_orphan_tracked(s1->inode)); + KUNIT_EXPECT_EQ(test, ctx->last_trigger_type, EXT4_JTR_ORPHAN_FILE); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 0U); + KUNIT_EXPECT_EQ(test, ext4_orphan_file_empty(sb), 0); + + blk = EXT4_I(s1->inode)->i_orphan_idx / ORPHAN_TEST_INODES_PER_OB; + off = EXT4_I(s1->inode)->i_orphan_idx % ORPHAN_TEST_INODES_PER_OB; + KUNIT_ASSERT_LT(test, blk, 2U); + KUNIT_EXPECT_EQ(test, off, 0U); + bdata = (__le32 *)ctx->static_binfo[blk].ob_bh->b_data; + KUNIT_EXPECT_EQ(test, le32_to_cpu(bdata[off]), 24U); + KUNIT_EXPECT_EQ(test, + atomic_read(&ctx->static_binfo[blk].ob_free_entries), + (int)(ORPHAN_TEST_INODES_PER_OB - 1)); + + /* Delete from orphan file and verify slot & state restoration */ + orphan_test_reset_faults(ctx); + err = orphan_test_call_del(&ctx->mock_handle, s1->inode); + + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(s1->inode, EXT4_STATE_ORPHAN_FILE)); + KUNIT_EXPECT_FALSE(test, ext4_inode_orphan_tracked(s1->inode)); + KUNIT_EXPECT_EQ(test, ctx->last_trigger_type, EXT4_JTR_ORPHAN_FILE); + KUNIT_EXPECT_EQ(test, le32_to_cpu(bdata[off]), 0U); + KUNIT_EXPECT_EQ(test, + atomic_read(&ctx->static_binfo[blk].ob_free_entries), + (int)ORPHAN_TEST_INODES_PER_OB); + KUNIT_EXPECT_EQ(test, ext4_orphan_file_empty(sb), 1); +} + +static void test_orphan_file_add_block_wraparound_and_last_slot(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct orphan_test_inode_slot *s1, *s2; + __le32 *bdata; + unsigned int j; + int b, err; + + orphan_test_setup_static_orphan_file(ctx, 3); + s1 = orphan_test_create_inode(test, ctx, 30, S_IFREG | 0644, 0); + s2 = orphan_test_create_inode(test, ctx, 31, S_IFREG | 0644, 0); + + /* + * Mark blocks 0 and 1 full (0 free), and leave ONLY the very last slot + * (ORPHAN_TEST_INODES_PER_OB - 1 = 253) free in block 2. Then test a + * second add when only block 0 has 1 slot free, guaranteeing + * wrap-around across the circular block ring regardless of CPU id. + */ + atomic_set(&ctx->static_binfo[0].ob_free_entries, 0); + atomic_set(&ctx->static_binfo[1].ob_free_entries, 0); + atomic_set(&ctx->static_binfo[2].ob_free_entries, 1); + bdata = (__le32 *)ctx->static_binfo[2].ob_bh->b_data; + for (j = 0; j < ORPHAN_TEST_INODES_PER_OB - 1; j++) + bdata[j] = cpu_to_le32(100 + j); + bdata[ORPHAN_TEST_INODES_PER_OB - 1] = 0; + + err = orphan_test_call_add(&ctx->mock_handle, s1->inode); + + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, EXT4_I(s1->inode)->i_orphan_idx, + 2 * ORPHAN_TEST_INODES_PER_OB + + (ORPHAN_TEST_INODES_PER_OB - 1)); + KUNIT_EXPECT_EQ(test, + le32_to_cpu(bdata[ORPHAN_TEST_INODES_PER_OB - 1]), 30U); + KUNIT_EXPECT_EQ(test, + atomic_read(&ctx->static_binfo[2].ob_free_entries), 0); + + /* Now make only block 0 slot (ORPHAN_TEST_INODES_PER_OB - 1) free */ + for (b = 0; b < 3; b++) + atomic_set(&ctx->static_binfo[b].ob_free_entries, 0); + atomic_set(&ctx->static_binfo[0].ob_free_entries, 1); + bdata = (__le32 *)ctx->static_binfo[0].ob_bh->b_data; + for (j = 0; j < ORPHAN_TEST_INODES_PER_OB - 1; j++) + bdata[j] = cpu_to_le32(100 + j); + bdata[ORPHAN_TEST_INODES_PER_OB - 1] = 0; + + err = orphan_test_call_add(&ctx->mock_handle, s2->inode); + + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, EXT4_I(s2->inode)->i_orphan_idx, + ORPHAN_TEST_INODES_PER_OB - 1); + KUNIT_EXPECT_EQ(test, + le32_to_cpu(bdata[ORPHAN_TEST_INODES_PER_OB - 1]), 31U); +} + +static void test_orphan_file_add_enospc_fallback_and_write_err(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct orphan_test_inode_slot *s_fb, *s_err, *s_dirty_err; + int err; + + orphan_test_setup_static_orphan_file(ctx, 2); + s_fb = orphan_test_create_inode(test, ctx, 32, S_IFREG | 0644, 0); + s_err = orphan_test_create_inode(test, ctx, 33, S_IFREG | 0644, 0); + s_dirty_err = orphan_test_create_inode(test, ctx, 34, S_IFREG | 0644, 0); + + /* + * 1. Full orphan file (all ob_free_entries == 0): + * ext4_orphan_file_add() returns -ENOSPC, and ext4_orphan_add() + * falls back to the superblock linked list! + */ + atomic_set(&ctx->static_binfo[0].ob_free_entries, 0); + atomic_set(&ctx->static_binfo[1].ob_free_entries, 0); + + err = orphan_test_call_add(&ctx->mock_handle, s_fb->inode); + + KUNIT_ASSERT_EQ(test, err, 0); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(s_fb->inode, + EXT4_STATE_ORPHAN_FILE)); + KUNIT_EXPECT_FALSE(test, list_empty(&EXT4_I(s_fb->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 32U); + + /* + * 2. Non-ENOSPC error (-EIO from ext4_journal_get_write_access): + * must restore ob_free_entries via atomic_inc and return -EIO + * directly WITHOUT falling back to the superblock linked list! + */ + atomic_set(&ctx->static_binfo[0].ob_free_entries, 5); + atomic_set(&ctx->static_binfo[1].ob_free_entries, 0); + orphan_test_reset_faults(ctx); + ctx->fail_write_access_err = -EIO; + ctx->fail_write_access_on_call = 1; + + err = orphan_test_call_add(&ctx->mock_handle, s_err->inode); + + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_EQ(test, + atomic_read(&ctx->static_binfo[0].ob_free_entries), 5); + KUNIT_EXPECT_FALSE(test, ext4_inode_orphan_tracked(s_err->inode)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 32U); + + /* + * 3. Non-ENOSPC error (-EIO from ext4_handle_dirty_metadata): + * propagates -EIO directly without falling back to s_last_orphan. + */ + orphan_test_reset_faults(ctx); + ctx->fail_dirty_metadata_err = -EIO; + ctx->fail_dirty_metadata_on_call = 1; + + err = orphan_test_call_add(&ctx->mock_handle, s_dirty_err->inode); + + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_TRUE(test, + ext4_test_inode_state(s_dirty_err->inode, + EXT4_STATE_ORPHAN_FILE)); + KUNIT_EXPECT_PTR_EQ(test, ctx->sbi.s_orphan.next, + &EXT4_I(s_fb->inode)->i_orphan); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 32U); +} + +static void test_orphan_file_del_edge_and_error_paths(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct orphan_test_inode_slot *s1; + __le32 *bdata; + int err; + + orphan_test_setup_static_orphan_file(ctx, 2); + s1 = orphan_test_create_inode(test, ctx, 35, S_IFREG | 0644, 0); + bdata = (__le32 *)ctx->static_binfo[1].ob_bh->b_data; + + /* 1. handle == NULL clears in-core state without touching orphan block */ + bdata[4] = cpu_to_le32(35); + atomic_set(&ctx->static_binfo[1].ob_free_entries, + ORPHAN_TEST_INODES_PER_OB - 1); + EXT4_I(s1->inode)->i_orphan_idx = 1 * ORPHAN_TEST_INODES_PER_OB + 4; + ext4_set_inode_state(s1->inode, EXT4_STATE_ORPHAN_FILE); + + err = orphan_test_call_del(NULL, s1->inode); + + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(s1->inode, EXT4_STATE_ORPHAN_FILE)); + KUNIT_EXPECT_TRUE(test, list_empty(&EXT4_I(s1->inode)->i_orphan)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(bdata[4]), 35U); + KUNIT_EXPECT_EQ(test, + atomic_read(&ctx->static_binfo[1].ob_free_entries), + (int)(ORPHAN_TEST_INODES_PER_OB - 1)); + + /* 2. Out-of-range blk >= oi->of_blocks hits WARN_ON_ONCE guard safely */ + EXT4_I(s1->inode)->i_orphan_idx = 2 * ORPHAN_TEST_INODES_PER_OB; + ext4_set_inode_state(s1->inode, EXT4_STATE_ORPHAN_FILE); + orphan_test_reset_faults(ctx); + + kunit_warning_suppress(test) { + err = orphan_test_call_del(&ctx->mock_handle, s1->inode); + } + + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(s1->inode, EXT4_STATE_ORPHAN_FILE)); + KUNIT_EXPECT_EQ(test, ctx->write_access_calls, 0U); + + /* 3. ext4_journal_get_write_access error leaves bdata[off] intact */ + EXT4_I(s1->inode)->i_orphan_idx = 1 * ORPHAN_TEST_INODES_PER_OB + 4; + ext4_set_inode_state(s1->inode, EXT4_STATE_ORPHAN_FILE); + orphan_test_reset_faults(ctx); + ctx->fail_write_access_err = -EIO; + + err = orphan_test_call_del(&ctx->mock_handle, s1->inode); + + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(s1->inode, EXT4_STATE_ORPHAN_FILE)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(bdata[4]), 35U); + KUNIT_EXPECT_EQ(test, + atomic_read(&ctx->static_binfo[1].ob_free_entries), + (int)(ORPHAN_TEST_INODES_PER_OB - 1)); + + /* 4. ext4_handle_dirty_metadata error propagates after clearing slot */ + EXT4_I(s1->inode)->i_orphan_idx = 1 * ORPHAN_TEST_INODES_PER_OB + 4; + ext4_set_inode_state(s1->inode, EXT4_STATE_ORPHAN_FILE); + orphan_test_reset_faults(ctx); + ctx->fail_dirty_metadata_err = -ENOSPC; + + err = orphan_test_call_del(&ctx->mock_handle, s1->inode); + + KUNIT_EXPECT_EQ(test, err, -ENOSPC); + KUNIT_EXPECT_FALSE(test, + ext4_test_inode_state(s1->inode, EXT4_STATE_ORPHAN_FILE)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(bdata[4]), 0U); + KUNIT_EXPECT_EQ(test, + atomic_read(&ctx->static_binfo[1].ob_free_entries), + (int)ORPHAN_TEST_INODES_PER_OB); +} + +/* ========================================================================= + * 5. Trigger, Init & Release of Orphan File Info + * ========================================================================= + */ + +static void test_orphan_file_block_trigger_and_frozen_data(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct jbd2_buffer_trigger_type *triggers = + &ctx->sbi.s_journal_triggers[EXT4_JTR_ORPHAN_FILE].tr_triggers; + struct buffer_head *bh; + struct ext4_orphan_block_tail *ot; + __le32 *bdata, *fdata; + __u32 expected_csum; + + orphan_test_setup_static_orphan_file(ctx, 1); + bh = ctx->static_binfo[0].ob_bh; + ot = (struct ext4_orphan_block_tail *)(bh->b_data + sb->s_blocksize - + sizeof(*ot)); + bdata = (__le32 *)bh->b_data; + bdata[0] = cpu_to_le32(42); + ot->ob_checksum = 0; + + /* 1. Trigger with data == bh->b_data computes valid block checksum */ + ext4_orphan_file_block_trigger(triggers, bh, bh->b_data, bh->b_size); + expected_csum = orphan_test_calc_ob_csum(sb, ORPHAN_TEST_OF_CSUM_SEED, + bh->b_blocknr, bh->b_data); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ot->ob_checksum), expected_csum); + + /* 2. Trigger with separate JBD2 frozen buffer hashes @data, not bh */ + memset(ctx->frozen_buf, 0, sizeof(ctx->frozen_buf)); + fdata = (__le32 *)ctx->frozen_buf; + fdata[0] = cpu_to_le32(99); + fdata[10] = cpu_to_le32(105); + + ext4_orphan_file_block_trigger(triggers, bh, ctx->frozen_buf, + bh->b_size); + expected_csum = orphan_test_calc_ob_csum(sb, ORPHAN_TEST_OF_CSUM_SEED, + bh->b_blocknr, + ctx->frozen_buf); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ot->ob_checksum), expected_csum); +} + +static void test_init_and_release_orphan_info_lifecycle(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_orphan_info *oi = &ctx->sbi.s_orphan_info; + struct orphan_test_inode_slot *of_slot; + struct ext4_orphan_block_tail *ot; + __le32 *bdata; + int i, err; + + /* 1. Feature disabled: init and release are clean no-ops */ + ext4_clear_feature_orphan_file(sb); + err = ext4_init_orphan_info(sb); + KUNIT_EXPECT_EQ(test, err, 0); + KUNIT_EXPECT_EQ(test, oi->of_blocks, 0); + KUNIT_EXPECT_NULL(test, oi->of_binfo); + ext4_release_orphan_info(sb); + + /* 2. Valid 2-block orphan file load and release */ + ext4_set_feature_orphan_file(sb); + of_slot = orphan_test_create_inode(test, ctx, ORPHAN_TEST_ORPHAN_INO, + S_IFREG | 0600, 1); + of_slot->inode->i_size = 2 * ORPHAN_TEST_BLK_SIZE; + EXT4_I(of_slot->inode)->i_csum_seed = ORPHAN_TEST_OF_CSUM_SEED; + + for (i = 0; i < 2; i++) { + struct orphan_test_ob_blk *oblk = &ctx->ob_pool[i]; + + memset(oblk, 0, sizeof(*oblk)); + oblk->present = true; + oblk->bh.b_data = oblk->buf; + oblk->bh.b_size = sb->s_blocksize; + oblk->bh.b_bdev = &ctx->bdev; + oblk->bh.b_blocknr = ORPHAN_TEST_OB_BASE_BLK + i; + atomic_set(&oblk->bh.b_count, 1); + set_buffer_uptodate(&oblk->bh); + } + /* Populate 3 active entries in block 0, 0 entries in block 1 */ + bdata = (__le32 *)ctx->ob_pool[0].buf; + bdata[0] = cpu_to_le32(20); + bdata[5] = cpu_to_le32(21); + bdata[253] = cpu_to_le32(22); + orphan_test_seal_ob_bh(sb, ORPHAN_TEST_OF_CSUM_SEED, + &ctx->ob_pool[0].bh, EXT4_ORPHAN_BLOCK_MAGIC); + orphan_test_seal_ob_bh(sb, ORPHAN_TEST_OF_CSUM_SEED, + &ctx->ob_pool[1].bh, EXT4_ORPHAN_BLOCK_MAGIC); + + err = ext4_init_orphan_info(sb); + KUNIT_ASSERT_EQ(test, err, 0); + ctx->orphan_info_allocated = true; + + KUNIT_EXPECT_EQ(test, oi->of_blocks, 2); + KUNIT_EXPECT_EQ(test, oi->of_csum_seed, ORPHAN_TEST_OF_CSUM_SEED); + KUNIT_ASSERT_NOT_NULL(test, oi->of_binfo); + KUNIT_EXPECT_EQ(test, atomic_read(&oi->of_binfo[0].ob_free_entries), + (int)(ORPHAN_TEST_INODES_PER_OB - 3)); + KUNIT_EXPECT_EQ(test, atomic_read(&oi->of_binfo[1].ob_free_entries), + (int)ORPHAN_TEST_INODES_PER_OB); + KUNIT_EXPECT_EQ(test, ext4_orphan_file_empty(sb), 0); + KUNIT_EXPECT_EQ(test, atomic_read(&of_slot->inode->i_count), 1); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->ob_pool[0].bh.b_count), 2); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->ob_pool[1].bh.b_count), 2); + + /* Release drops every block bh reference and frees of_binfo */ + ext4_release_orphan_info(sb); + ctx->orphan_info_allocated = false; + memset(oi, 0, sizeof(*oi)); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->ob_pool[0].bh.b_count), 1); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->ob_pool[1].bh.b_count), 1); + + /* + * 3. With metadata_csum disabled, ext4_orphan_file_block_csum_verify() + * returns 1 even if ob_checksum does not match. + */ + ext4_clear_feature_metadata_csum(sb); + of_slot->inode->i_size = ORPHAN_TEST_BLK_SIZE; + ot = (struct ext4_orphan_block_tail *)(ctx->ob_pool[0].buf + + sb->s_blocksize - sizeof(*ot)); + ot->ob_checksum = cpu_to_le32(0xdeadbeefU); + + err = ext4_init_orphan_info(sb); + KUNIT_ASSERT_EQ(test, err, 0); + ctx->orphan_info_allocated = true; + + ext4_release_orphan_info(sb); + ctx->orphan_info_allocated = false; + memset(oi, 0, sizeof(*oi)); +} + +static void test_init_orphan_info_max_blocks_boundary(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_orphan_info *oi = &ctx->sbi.s_orphan_info; + struct orphan_test_inode_slot *of_slot; + int err; + + ext4_set_feature_orphan_file(sb); + of_slot = orphan_test_create_inode(test, ctx, ORPHAN_TEST_ORPHAN_INO, + S_IFREG | 0600, 1); + EXT4_I(of_slot->inode)->i_csum_seed = ORPHAN_TEST_OF_CSUM_SEED; + + /* + * 1. Size 1 byte over max(EXT4_MAX_ORPHAN_FILE_BLOCKS << blkbits, 2M) + * (2 MiB = 2048 1 KiB blocks) fails with -EFSCORRUPTED. + */ + of_slot->inode->i_size = (2LL << 20) + 1; + err = ext4_init_orphan_info(sb); + KUNIT_EXPECT_EQ(test, err, -EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, atomic_read(&of_slot->inode->i_count), 1); + + /* 2. Exact 2 MiB (2048-block) limit succeeds and releases all bh refs */ + memset(ctx->boundary_buf, 0, sizeof(ctx->boundary_buf)); + ctx->boundary_bh.b_data = ctx->boundary_buf; + ctx->boundary_bh.b_size = sb->s_blocksize; + ctx->boundary_bh.b_bdev = &ctx->bdev; + ctx->boundary_bh.b_blocknr = ORPHAN_TEST_OB_BASE_BLK; + atomic_set(&ctx->boundary_bh.b_count, 1); + set_buffer_uptodate(&ctx->boundary_bh); + orphan_test_seal_ob_bh(sb, ORPHAN_TEST_OF_CSUM_SEED, + &ctx->boundary_bh, EXT4_ORPHAN_BLOCK_MAGIC); + + ctx->use_boundary_bh = true; + of_slot->inode->i_size = 2LL << 20; + + err = ext4_init_orphan_info(sb); + KUNIT_ASSERT_EQ(test, err, 0); + ctx->orphan_info_allocated = true; + KUNIT_EXPECT_EQ(test, oi->of_blocks, 2048); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->boundary_bh.b_count), 2049); + + ext4_release_orphan_info(sb); + ctx->orphan_info_allocated = false; + memset(oi, 0, sizeof(*oi)); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->boundary_bh.b_count), 1); +} + +static void test_init_orphan_info_error_paths_and_cleanup(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_orphan_info *oi = &ctx->sbi.s_orphan_info; + struct orphan_test_inode_slot *of_slot; + struct ext4_orphan_block_tail *ot; + int i, err; + + ext4_set_feature_orphan_file(sb); + + /* 1. ext4_iget failure returns error immediately */ + ctx->fail_iget_err = -ENOENT; + err = ext4_init_orphan_info(sb); + KUNIT_EXPECT_EQ(test, err, -ENOENT); + orphan_test_reset_faults(ctx); + + /* Prepare 2-block orphan inode where block 0 loads cleanly */ + of_slot = orphan_test_create_inode(test, ctx, ORPHAN_TEST_ORPHAN_INO, + S_IFREG | 0600, 1); + of_slot->inode->i_size = 2 * ORPHAN_TEST_BLK_SIZE; + EXT4_I(of_slot->inode)->i_csum_seed = ORPHAN_TEST_OF_CSUM_SEED; + + for (i = 0; i < 2; i++) { + struct orphan_test_ob_blk *oblk = &ctx->ob_pool[i]; + + memset(oblk, 0, sizeof(*oblk)); + oblk->present = true; + oblk->bh.b_data = oblk->buf; + oblk->bh.b_size = sb->s_blocksize; + oblk->bh.b_bdev = &ctx->bdev; + oblk->bh.b_blocknr = ORPHAN_TEST_OB_BASE_BLK + i; + atomic_set(&oblk->bh.b_count, 1); + set_buffer_uptodate(&oblk->bh); + orphan_test_seal_ob_bh(sb, ORPHAN_TEST_OF_CSUM_SEED, &oblk->bh, + EXT4_ORPHAN_BLOCK_MAGIC); + } + + /* 2. Block 1 ext4_bread returns ERR_PTR(-EIO) -> block 0 brelse'd */ + ctx->ob_pool[1].bread_err = -EIO; + err = ext4_init_orphan_info(sb); + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->ob_pool[0].bh.b_count), 1); + KUNIT_EXPECT_EQ(test, atomic_read(&of_slot->inode->i_count), 1); + memset(oi, 0, sizeof(*oi)); + ctx->ob_pool[1].bread_err = 0; + + /* 3. Block 1 ext4_bread returns NULL (unmapped hole) -> -EIO */ + ctx->ob_pool[1].return_hole = true; + err = ext4_init_orphan_info(sb); + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->ob_pool[0].bh.b_count), 1); + memset(oi, 0, sizeof(*oi)); + ctx->ob_pool[1].return_hole = false; + + /* 4. Block 1 has invalid ob_magic -> ext4_error + -EIO + brelse */ + orphan_test_seal_ob_bh(sb, ORPHAN_TEST_OF_CSUM_SEED, + &ctx->ob_pool[1].bh, 0xbad0bad0U); + orphan_test_reset_faults(ctx); + err = ext4_init_orphan_info(sb); + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_NE(test, ctx->sbi.s_mount_state & EXT4_ERROR_FS, 0); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->ob_pool[0].bh.b_count), 1); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->ob_pool[1].bh.b_count), 1); + memset(oi, 0, sizeof(*oi)); + + /* 5. Block 1 has valid magic but corrupted ob_checksum -> -EIO */ + orphan_test_seal_ob_bh(sb, ORPHAN_TEST_OF_CSUM_SEED, + &ctx->ob_pool[1].bh, EXT4_ORPHAN_BLOCK_MAGIC); + ot = (struct ext4_orphan_block_tail *)(ctx->ob_pool[1].buf + + sb->s_blocksize - sizeof(*ot)); + ot->ob_checksum = cpu_to_le32(le32_to_cpu(ot->ob_checksum) ^ 0x1U); + orphan_test_reset_faults(ctx); + + err = ext4_init_orphan_info(sb); + KUNIT_EXPECT_EQ(test, err, -EIO); + KUNIT_EXPECT_NE(test, ctx->sbi.s_mount_state & EXT4_ERROR_FS, 0); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->ob_pool[0].bh.b_count), 1); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->ob_pool[1].bh.b_count), 1); + memset(oi, 0, sizeof(*oi)); +} + +/* ========================================================================= + * 6. End-to-End Orphan Recovery: ext4_orphan_cleanup() & ext4_process_orphan() + * ========================================================================= + */ + +static void test_orphan_cleanup_skip_guards(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + __le32 saved_ro_compat; + + /* 1. Empty s_last_orphan and empty orphan file -> fast return */ + ctx->es.s_last_orphan = 0; + ext4_orphan_cleanup(sb, &ctx->es); + KUNIT_EXPECT_EQ(test, ctx->iget_calls, 0U); + + /* 2. Read-only block device skips orphan cleanup */ + ctx->es.s_last_orphan = cpu_to_le32(15); + bdev_set_flag(&ctx->bdev, BD_READ_ONLY); + ext4_orphan_cleanup(sb, &ctx->es); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 15U); + KUNIT_EXPECT_EQ(test, ctx->iget_calls, 0U); + bdev_clear_flag(&ctx->bdev, BD_READ_ONLY); + + /* 3. Unknown ROCOMPAT feature fails ext4_feature_set_ok(sb, 0) */ + saved_ro_compat = ctx->es.s_feature_ro_compat; + ctx->es.s_feature_ro_compat |= cpu_to_le32(0x80000000U); + ext4_orphan_cleanup(sb, &ctx->es); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 15U); + KUNIT_EXPECT_EQ(test, ctx->iget_calls, 0U); + ctx->es.s_feature_ro_compat = saved_ro_compat; + + /* 4a. EXT4_ERROR_FS on SB_RDONLY mount preserves s_last_orphan */ + ctx->sbi.s_mount_state |= EXT4_ERROR_FS; + sb->s_flags |= SB_RDONLY; + ext4_orphan_cleanup(sb, &ctx->es); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 15U); + sb->s_flags &= ~SB_RDONLY; + + /* 4b. EXT4_ERROR_FS on R/W mount clears s_last_orphan to 0 */ + ext4_orphan_cleanup(sb, &ctx->es); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 0U); + ctx->sbi.s_mount_state &= ~EXT4_ERROR_FS; +} + +static void +test_orphan_cleanup_linked_list_unlinked_and_truncated(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct orphan_test_inode_slot *s_unlinked, *s_trunc, *s_symlink; + + /* + * Match ext4_fill_super() no-journal recovery state: + * s_journal = NULL, s_mount_state |= EXT4_ORPHAN_FS. + */ + ctx->sbi.s_journal = NULL; + ctx->sbi.s_mount_state |= EXT4_ORPHAN_FS; + set_opt(sb, DEBUG); + + /* + * Build on-disk orphan chain: + * s_last_orphan -> 15 (unlinked reg w/ extent) -> 16 (linked truncate + * w/ extent) -> 17 (unlinked fast symlink) -> 0 + */ + s_unlinked = orphan_test_create_inode(test, ctx, 15, S_IFREG | 0644, 0); + s_unlinked->handoff_to_iget = true; + orphan_test_add_single_extent(s_unlinked->inode, 0, 200ULL, 2); + NEXT_ORPHAN(s_unlinked->inode) = 16; + + s_trunc = orphan_test_create_inode(test, ctx, 16, S_IFREG | 0644, 1); + s_trunc->handoff_to_iget = true; + s_trunc->inode->i_size = 0; + EXT4_I(s_trunc->inode)->i_disksize = 2 * ORPHAN_TEST_BLK_SIZE; + orphan_test_add_single_extent(s_trunc->inode, 0, 300ULL, 2); + NEXT_ORPHAN(s_trunc->inode) = 17; + + s_symlink = orphan_test_create_inode(test, ctx, 17, S_IFLNK | 0777, 0); + s_symlink->handoff_to_iget = true; + s_symlink->inode->i_size = 8; + memcpy(EXT4_I(s_symlink->inode)->i_data, "target12", 8); + NEXT_ORPHAN(s_symlink->inode) = 0; + + ctx->es.s_last_orphan = cpu_to_le32(15); + + ext4_orphan_cleanup(sb, &ctx->es); + + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 0U); + KUNIT_EXPECT_TRUE(test, list_empty(&ctx->sbi.s_orphan)); + KUNIT_EXPECT_EQ(test, ctx->nr_freed_inos, 2U); + KUNIT_EXPECT_TRUE(test, orphan_test_was_ino_freed(ctx, 15)); + KUNIT_EXPECT_FALSE(test, orphan_test_was_ino_freed(ctx, 16)); + KUNIT_EXPECT_TRUE(test, orphan_test_was_ino_freed(ctx, 17)); + /* Both s_unlinked (2 blks) and s_trunc (2 blks) freed their extents */ + KUNIT_EXPECT_EQ(test, ctx->total_freed_blks, 4UL); +} + +static void +test_orphan_cleanup_orphan_file_and_rdonly_restore(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct orphan_test_inode_slot *s_list, *s_of_del, *s_of_trunc, *s_of_only; + __le32 *bdata0, *bdata1; + + ctx->sbi.s_journal = NULL; + ctx->sbi.s_mount_state |= EXT4_ORPHAN_FS; + sb->s_flags |= SB_RDONLY; + + orphan_test_setup_static_orphan_file(ctx, 2); + bdata0 = (__le32 *)ctx->static_binfo[0].ob_bh->b_data; + bdata1 = (__le32 *)ctx->static_binfo[1].ob_bh->b_data; + + /* 1. Linked-list unlinked orphan (ino 15) */ + s_list = orphan_test_create_inode(test, ctx, 15, S_IFREG | 0644, 0); + s_list->handoff_to_iget = true; + NEXT_ORPHAN(s_list->inode) = 0; + ctx->es.s_last_orphan = cpu_to_le32(15); + + /* + * 2. Orphan file entries: + * - Block 0 slot 2: valid unlinked orphan (ino 16) + * - Block 0 slot 10: unallocated ino 99 -> ext4_orphan_get() fails, + * loop must continue to remaining entries! + * - Block 1 slot 5: valid linked truncate orphan (ino 18) + */ + s_of_del = orphan_test_create_inode(test, ctx, 16, S_IFREG | 0644, 0); + s_of_del->handoff_to_iget = true; + bdata0[2] = cpu_to_le32(16); + bdata0[10] = cpu_to_le32(99); + atomic_set(&ctx->static_binfo[0].ob_free_entries, + ORPHAN_TEST_INODES_PER_OB - 2); + + s_of_trunc = orphan_test_create_inode(test, ctx, 18, S_IFREG | 0644, 1); + s_of_trunc->handoff_to_iget = true; + s_of_trunc->inode->i_size = 0; + orphan_test_add_single_extent(s_of_trunc->inode, 0, 400ULL, 1); + bdata1[5] = cpu_to_le32(18); + atomic_set(&ctx->static_binfo[1].ob_free_entries, + ORPHAN_TEST_INODES_PER_OB - 1); + + ext4_orphan_cleanup(sb, &ctx->es); + + /* SB_RDONLY was cleared during cleanup and restored upon return */ + KUNIT_EXPECT_TRUE(test, ctx->saw_rw_during_cleanup); + KUNIT_EXPECT_NE(test, sb->s_flags & SB_RDONLY, 0UL); + + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 0U); + KUNIT_EXPECT_TRUE(test, orphan_test_was_ino_freed(ctx, 15)); + KUNIT_EXPECT_TRUE(test, orphan_test_was_ino_freed(ctx, 16)); + KUNIT_EXPECT_FALSE(test, orphan_test_was_ino_freed(ctx, 18)); + KUNIT_EXPECT_EQ(test, ctx->total_freed_blks, 1UL); + + /* Valid orphan-file slots were cleared; bad slot 10 was skipped */ + KUNIT_EXPECT_EQ(test, le32_to_cpu(bdata0[2]), 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(bdata0[10]), 99U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(bdata1[5]), 0U); + KUNIT_EXPECT_EQ(test, + atomic_read(&ctx->static_binfo[0].ob_free_entries), + (int)(ORPHAN_TEST_INODES_PER_OB - 1)); + KUNIT_EXPECT_EQ(test, + atomic_read(&ctx->static_binfo[1].ob_free_entries), + (int)ORPHAN_TEST_INODES_PER_OB); + + /* + * 3. s_last_orphan == 0 with non-empty orphan file: + * must NOT early-return at (!es->s_last_orphan && orphan_file_empty). + */ + bdata0[10] = 0; + atomic_set(&ctx->static_binfo[0].ob_free_entries, + ORPHAN_TEST_INODES_PER_OB); + s_of_only = orphan_test_create_inode(test, ctx, 19, S_IFREG | 0644, 0); + s_of_only->handoff_to_iget = true; + bdata1[8] = cpu_to_le32(19); + atomic_set(&ctx->static_binfo[1].ob_free_entries, + ORPHAN_TEST_INODES_PER_OB - 1); + orphan_test_reset_faults(ctx); + + ext4_orphan_cleanup(sb, &ctx->es); + + KUNIT_EXPECT_TRUE(test, orphan_test_was_ino_freed(ctx, 19)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(bdata1[8]), 0U); + KUNIT_EXPECT_EQ(test, ext4_orphan_file_empty(sb), 1); +} + +static void +test_orphan_cleanup_list_errors_and_truncate_fail(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct orphan_test_inode_slot *s1, *s2; + + ctx->sbi.s_journal = NULL; + ctx->sbi.s_mount_state |= EXT4_ORPHAN_FS; + + /* + * 1. Reserved / invalid orphan ino (< EXT4_FIRST_INO) on s_last_orphan: + * ext4_orphan_get() returns -EFSCORRUPTED, loop clears s_last_orphan + * and breaks cleanly. + */ + ctx->es.s_last_orphan = cpu_to_le32(5); + ext4_orphan_cleanup(sb, &ctx->es); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 0U); + + /* + * 2. ext4_truncate() fails (-EIO) on linked orphan s1 (20), which + * points to s2 (21): + * - ext4_process_orphan() removes s1 from in-core s_orphan via + * ext4_orphan_del(NULL, s1) and sets EXT4_ERROR_FS via + * ext4_std_error(). + * - Next loop iteration detects EXT4_ERROR_FS, clears s_last_orphan, + * and aborts recovery before touching s2 (21). + */ + orphan_test_reset_faults(ctx); + kunit_activate_static_stub(test, ext4_truncate, + orphan_test_truncate_stub); + ctx->stub_truncate_err = -EIO; + + s1 = orphan_test_create_inode(test, ctx, 20, S_IFREG | 0644, 1); + s1->handoff_to_iget = true; + NEXT_ORPHAN(s1->inode) = 21; + + s2 = orphan_test_create_inode(test, ctx, 21, S_IFREG | 0644, 0); + s2->handoff_to_iget = true; + NEXT_ORPHAN(s2->inode) = 0; + + ctx->es.s_last_orphan = cpu_to_le32(20); + + ext4_orphan_cleanup(sb, &ctx->es); + kunit_deactivate_static_stub(test, ext4_truncate); + + KUNIT_EXPECT_EQ(test, ctx->truncate_calls, 1U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 0U); + KUNIT_EXPECT_TRUE(test, list_empty(&ctx->sbi.s_orphan)); + KUNIT_EXPECT_FALSE(test, orphan_test_was_ino_freed(ctx, 21)); + KUNIT_EXPECT_NOT_NULL(test, s2->inode); +} + +#ifdef CONFIG_QUOTA +static void test_orphan_cleanup_quota_paths(struct kunit *test) +{ + struct orphan_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct orphan_test_inode_slot *s1, *s2; + + ctx->sbi.s_journal = NULL; + ctx->sbi.s_mount_state |= EXT4_ORPHAN_FS; + sb->s_flags |= SB_RDONLY; + strscpy(ctx->qf_name, "aquota.user", sizeof(ctx->qf_name)); + + /* + * 1. Exercise journaled quota mount hook (ext4_quota_on_mount) and, + * when CONFIG_QFMT_V2 is also enabled, ext4_enable_quotas() success + * (s_usr_quota_inum == 0 -> quota_update = 1) on SB_RDONLY orphan + * recovery. Hold s_umount to satisfy lockdep in s_qf_names RCU + * dereference (matching mount-time ext4_fill_super context). + */ + rcu_assign_pointer(ctx->sbi.s_qf_names[USRQUOTA], ctx->qf_name); +#if IS_ENABLED(CONFIG_QFMT_V2) + ext4_set_feature_quota(sb); + ctx->es.s_usr_quota_inum = 0; +#endif + + s1 = orphan_test_create_inode(test, ctx, 28, S_IFREG | 0644, 0); + s1->handoff_to_iget = true; + NEXT_ORPHAN(s1->inode) = 0; + ctx->es.s_last_orphan = cpu_to_le32(28); + + down_write(&sb->s_umount); + ext4_orphan_cleanup(sb, &ctx->es); + rcu_assign_pointer(ctx->sbi.s_qf_names[USRQUOTA], NULL); + up_write(&sb->s_umount); + + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 0U); + KUNIT_EXPECT_TRUE(test, orphan_test_was_ino_freed(ctx, 28)); + KUNIT_EXPECT_NE(test, sb->s_flags & SB_RDONLY, 0UL); + +#if IS_ENABLED(CONFIG_QFMT_V2) + /* + * 2. Exercise ext4_enable_quotas() failure path: missing quota inode 3 + * triggers ext4_error() (setting EXT4_ERROR_FS), logs the quota + * turn-on error, aborts s_last_orphan recovery while clearing + * s_last_orphan to 0, and still restores SB_RDONLY. + */ + orphan_test_reset_faults(ctx); + ctx->es.s_usr_quota_inum = cpu_to_le32(EXT4_USR_QUOTA_INO); + s2 = orphan_test_create_inode(test, ctx, 29, S_IFREG | 0644, 0); + s2->handoff_to_iget = true; + NEXT_ORPHAN(s2->inode) = 0; + ctx->es.s_last_orphan = cpu_to_le32(29); + + down_write(&sb->s_umount); + ext4_orphan_cleanup(sb, &ctx->es); + up_write(&sb->s_umount); + + KUNIT_EXPECT_NE(test, ctx->sbi.s_mount_state & EXT4_ERROR_FS, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es.s_last_orphan), 0U); + KUNIT_EXPECT_FALSE(test, orphan_test_was_ino_freed(ctx, 29)); + KUNIT_EXPECT_NE(test, sb->s_flags & SB_RDONLY, 0UL); +#else + (void)s2; +#endif +} +#endif + +static struct kunit_case orphan_test_cases[] = { + KUNIT_CASE_PARAM(test_inodes_per_orphan_block_param, + orphan_blksize_gen_params), + KUNIT_CASE(test_orphan_file_empty), + KUNIT_CASE(test_orphan_add_early_exits_and_idempotency), + KUNIT_CASE(test_orphan_add_list_chaining_and_csum), + KUNIT_CASE(test_orphan_add_next_orphan_bounds), + KUNIT_CASE(test_orphan_add_list_error_paths), + KUNIT_CASE(test_orphan_del_early_exits), + KUNIT_CASE(test_orphan_del_list_positions_and_null_handle), + KUNIT_CASE(test_orphan_del_list_error_paths), + KUNIT_CASE(test_orphan_file_add_and_del_basic), + KUNIT_CASE(test_orphan_file_add_block_wraparound_and_last_slot), + KUNIT_CASE(test_orphan_file_add_enospc_fallback_and_write_err), + KUNIT_CASE(test_orphan_file_del_edge_and_error_paths), + KUNIT_CASE(test_orphan_file_block_trigger_and_frozen_data), + KUNIT_CASE(test_init_and_release_orphan_info_lifecycle), + KUNIT_CASE(test_init_orphan_info_max_blocks_boundary), + KUNIT_CASE(test_init_orphan_info_error_paths_and_cleanup), + KUNIT_CASE(test_orphan_cleanup_skip_guards), + KUNIT_CASE(test_orphan_cleanup_linked_list_unlinked_and_truncated), + KUNIT_CASE(test_orphan_cleanup_orphan_file_and_rdonly_restore), + KUNIT_CASE(test_orphan_cleanup_list_errors_and_truncate_fail), +#ifdef CONFIG_QUOTA + KUNIT_CASE(test_orphan_cleanup_quota_paths), +#endif + {} +}; + +static struct kunit_suite orphan_test_suite = { + .name = "ext4_orphan_test", + .init = orphan_test_init, + .test_cases = orphan_test_cases, +}; + +kunit_test_suites(&orphan_test_suite); + +MODULE_DESCRIPTION("KUnit tests for ext4 orphan inode handling"); +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/orphan.c b/fs/ext4/orphan.c index b4675aa7ea965f..847eca2d866a1e 100644 --- a/fs/ext4/orphan.c +++ b/fs/ext4/orphan.c @@ -5,6 +5,7 @@ #include #include #include +#include #include "ext4.h" #include "ext4_jbd2.h" @@ -107,6 +108,8 @@ int ext4_orphan_add(handle_t *handle, struct inode *inode) int err = 0, rc; bool dirty = false; + KUNIT_STATIC_STUB_REDIRECT(ext4_orphan_add, handle, inode); + if (!sbi->s_journal || is_bad_inode(inode)) return 0; @@ -187,6 +190,7 @@ int ext4_orphan_add(handle_t *handle, struct inode *inode) ext4_std_error(sb, err); return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_orphan_add); static int ext4_orphan_file_del(handle_t *handle, struct inode *inode) { @@ -232,6 +236,8 @@ int ext4_orphan_del(handle_t *handle, struct inode *inode) struct ext4_iloc iloc; int err = 0; + KUNIT_STATIC_STUB_REDIRECT(ext4_orphan_del, handle, inode); + if (!sbi->s_journal && !(sbi->s_mount_state & EXT4_ORPHAN_FS)) return 0; @@ -308,6 +314,7 @@ int ext4_orphan_del(handle_t *handle, struct inode *inode) brelse(iloc.bh); goto out_err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_orphan_del); #ifdef CONFIG_QUOTA static int ext4_quota_on_mount(struct super_block *sb, int type) @@ -504,6 +511,7 @@ void ext4_orphan_cleanup(struct super_block *sb, struct ext4_super_block *es) #endif sb->s_flags = s_flags; /* Restore SB_RDONLY status */ } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_orphan_cleanup); void ext4_release_orphan_info(struct super_block *sb) { @@ -516,6 +524,7 @@ void ext4_release_orphan_info(struct super_block *sb) brelse(oi->of_binfo[i].ob_bh); kvfree(oi->of_binfo); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_release_orphan_info); static struct ext4_orphan_block_tail *ext4_orphan_block_tail( struct super_block *sb, @@ -563,6 +572,7 @@ void ext4_orphan_file_block_trigger(struct jbd2_buffer_trigger_type *triggers, ot = ext4_orphan_block_tail(sb, bh); ot->ob_checksum = cpu_to_le32(csum); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_orphan_file_block_trigger); int ext4_init_orphan_info(struct super_block *sb) { @@ -576,6 +586,7 @@ int ext4_init_orphan_info(struct super_block *sb) int inodes_per_ob = ext4_inodes_per_orphan_block(sb); struct ext4_orphan_block_tail *ot; ino_t orphan_ino = le32_to_cpu(EXT4_SB(sb)->s_es->s_orphan_file_inum); + loff_t max_size; if (!ext4_has_feature_orphan_file(sb)) return 0; @@ -589,8 +600,13 @@ int ext4_init_orphan_info(struct super_block *sb) * This is just an artificial limit to prevent corrupted fs from * consuming absurd amounts of memory when pinning blocks of orphan * file in memory. + * + * e2fsprogs 1.47.4 produces 2MB orphan files by default regardless + * of the number of blocks so that's where the second limit comes from. */ - if (inode->i_size > (EXT4_MAX_ORPHAN_FILE_BLOCKS << inode->i_blkbits)) { + max_size = max(EXT4_MAX_ORPHAN_FILE_BLOCKS << inode->i_blkbits, + 2 << 20); + if (inode->i_size > max_size) { ext4_msg(sb, KERN_ERR, "orphan file too big: %llu", (unsigned long long)inode->i_size); ret = -EFSCORRUPTED; @@ -645,6 +661,7 @@ int ext4_init_orphan_info(struct super_block *sb) iput(inode); return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_init_orphan_info); int ext4_orphan_file_empty(struct super_block *sb) { @@ -660,3 +677,4 @@ int ext4_orphan_file_empty(struct super_block *sb) return 0; return 1; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_orphan_file_empty); diff --git a/fs/ext4/page-io.c b/fs/ext4/page-io.c index 734d856a6d4784..059827b961ec83 100644 --- a/fs/ext4/page-io.c +++ b/fs/ext4/page-io.c @@ -192,6 +192,8 @@ static int ext4_end_io_end(ext4_io_end_t *io_end) jbd2_journal_abort(EXT4_SB(sb)->s_journal, ret); } else { ret = ext4_convert_unwritten_io_end_vec(handle, io_end); + if (ret < 0) + mapping_set_error(inode->i_mapping, ret); } if (ret < 0 && !ext4_emergency_state(sb) && io_end->flag & EXT4_IO_END_UNWRITTEN) { @@ -299,6 +301,7 @@ void ext4_end_io_rsv_work(struct work_struct *work) i_rsv_conversion_work); ext4_do_flush_completed_IO(&ei->vfs_inode, &ei->i_rsv_conversion_list); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_end_io_rsv_work); ext4_io_end_t *ext4_init_io_end(struct inode *inode, gfp_t flags) { @@ -458,6 +461,16 @@ static void io_submit_add_bh(struct ext4_io_submit *io, io_submit_init_bio(io, inode, folio, bh); if (!bio_add_folio(io->io_bio, folio, bh->b_size, bh_offset(bh))) goto submit_and_retry; + + /* + * Dropbehind folios can only be invalidated in task context. An + * io_end with unwritten extents is completed from ext4's workqueue + * anyway, so only ask the block layer to defer the others. + */ + if (folio_test_dropbehind(folio) && + !(io->io_end->flag & EXT4_IO_END_UNWRITTEN)) + bio_set_flag(io->io_bio, BIO_COMPLETE_IN_TASK); + wbc_account_cgroup_owner(io->io_wbc, folio, bh->b_size); io->io_next_block++; } diff --git a/fs/ext4/resize-test.c b/fs/ext4/resize-test.c new file mode 100644 index 00000000000000..81c9fd96816c6a --- /dev/null +++ b/fs/ext4/resize-test.c @@ -0,0 +1,1336 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for fs/ext4/resize.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_jbd2.h" +#include "mballoc.h" + +#define RESIZE_TEST_BLK_SIZE 1024U +#define RESIZE_TEST_BLK_BITS 10U +#define RESIZE_TEST_BLOCKS_PER_GRP 1024U +#define RESIZE_TEST_FIRST_DATA_BLK 1U +#define RESIZE_TEST_INODE_SIZE 256U +#define RESIZE_TEST_EXTRA_ISIZE 32U +#define RESIZE_TEST_INODES_PER_GRP 32U +#define RESIZE_TEST_ITB_PER_GRP 8U +#define RESIZE_TEST_DESC_SIZE 64U +#define RESIZE_TEST_DESC_PER_BLK 16U +#define RESIZE_TEST_DESC_PER_BLK_BITS 4U + +struct resize_mock_blk { + struct list_head node; + ext4_fsblk_t blocknr; + struct buffer_head bh; + u8 *data; +}; + +struct resize_test_ctx { + struct super_block *sb; + struct ext4_sb_info sbi; + struct ext4_super_block *es; + struct blockgroup_lock bgl; + struct gendisk bdev_disk; + struct block_device bdev; + struct request_queue bdev_queue; + struct inode bd_inode; + struct folio *bh_folio; + struct list_head blks; + struct buffer_head iloc_bh; + u8 iloc_buf[RESIZE_TEST_BLK_SIZE]; + struct inode *resize_inode; + ext4_fsblk_t device_blocks; + ext4_fsblk_t last_freed_blk; + unsigned long last_freed_count; + int zeroout_calls; + sector_t zeroout_blks; + int zeroout_err; + bool sb_getblk_fail; + bool mb_inited; +}; + +static struct kunit *active_resize_test; + +static struct inode *resize_test_alloc_inode(struct super_block *sb) +{ + struct ext4_inode_info *ei; + + ei = kzalloc_obj(*ei); + if (!ei) + return NULL; + + init_rwsem(&ei->i_data_sem); + inode_init_once(&ei->vfs_inode); + inode_set_iversion(&ei->vfs_inode, 1); + ei->i_prealloc_node = RB_ROOT; + rwlock_init(&ei->i_prealloc_lock); + ext4_es_init_tree(&ei->i_es_tree); + rwlock_init(&ei->i_es_lock); + INIT_LIST_HEAD(&ei->i_es_list); + spin_lock_init(&ei->i_raw_lock); + spin_lock_init(&ei->i_block_reservation_lock); + ext4_init_pending_tree(&ei->i_pending_tree); + init_rwsem(&ei->xattr_sem); + INIT_LIST_HEAD(&ei->i_rsv_conversion_list); + spin_lock_init(&ei->i_completed_io_lock); + INIT_LIST_HEAD(&ei->i_orphan); + ext4_fc_init_inode(&ei->vfs_inode); + spin_lock_init(&ei->i_fc_lock); + ei->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + ei->i_extra_isize = RESIZE_TEST_EXTRA_ISIZE; + ei->i_last_alloc_group = ~0U; + + return &ei->vfs_inode; +} + +static void resize_test_free_inode(struct inode *inode) +{ + kfree(EXT4_I(inode)); +} + +static void resize_test_evict_inode(struct inode *inode) +{ + truncate_inode_pages_final(&inode->i_data); + ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS); + clear_inode(inode); +} + +#ifdef CONFIG_QUOTA +static struct dquot __rcu **resize_test_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} +#endif + +static const struct super_operations resize_test_sops = { + .alloc_inode = resize_test_alloc_inode, + .free_inode = resize_test_free_inode, + .evict_inode = resize_test_evict_inode, +#ifdef CONFIG_QUOTA + .get_dquots = resize_test_get_dquots, +#endif +}; + +static int resize_test_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static void resize_test_sb_upd_work(struct work_struct *work) +{ +} + +static void resize_test_err_timer(struct timer_list *t) +{ +} + +static struct file_system_type resize_test_fs_type = { + .name = "ext4_resize_kunit", + .init_fs_context = resize_test_init_fs_context, + .kill_sb = kill_anon_super, +}; + +static void resize_init_mock_bh(struct buffer_head *bh, struct folio *folio, + u8 *data, size_t size, sector_t blocknr) +{ + memset(bh, 0, sizeof(*bh)); + bh->b_folio = folio; + bh->b_data = (char *)data; + bh->b_size = size; + bh->b_blocknr = blocknr; + atomic_set(&bh->b_count, 2); + set_buffer_uptodate(bh); +} + +static struct buffer_head *resize_lookup_bh(struct resize_test_ctx *ctx, + ext4_fsblk_t blocknr) +{ + struct resize_mock_blk *blk; + + list_for_each_entry(blk, &ctx->blks, node) { + if (blk->blocknr == blocknr) + return &blk->bh; + } + return NULL; +} + +static struct buffer_head *resize_get_or_create_bh(struct resize_test_ctx *ctx, + ext4_fsblk_t blocknr) +{ + struct buffer_head *bh; + struct resize_mock_blk *blk; + + bh = resize_lookup_bh(ctx, blocknr); + if (bh) { + get_bh(bh); + return bh; + } + + blk = kzalloc_obj(*blk); + if (!blk) + return NULL; + blk->data = kzalloc(RESIZE_TEST_BLK_SIZE, GFP_KERNEL); + if (!blk->data) { + kfree(blk); + return NULL; + } + blk->blocknr = blocknr; + resize_init_mock_bh(&blk->bh, ctx->bh_folio, blk->data, + RESIZE_TEST_BLK_SIZE, blocknr); + list_add_tail(&blk->node, &ctx->blks); + get_bh(&blk->bh); + return &blk->bh; +} + +static struct buffer_head *resize_sb_getblk_stub(struct super_block *sb, + ext4_fsblk_t block) +{ + struct kunit *test = active_resize_test; + struct resize_test_ctx *ctx; + + if (!test) + return NULL; + ctx = test->priv; + if (!ctx || sb != ctx->sb || ctx->sb_getblk_fail) + return NULL; + + return resize_get_or_create_bh(ctx, block); +} + +static struct buffer_head *resize_sb_bread_stub(struct super_block *sb, + sector_t block, + blk_opf_t op_flags) +{ + struct kunit *test = active_resize_test; + struct resize_test_ctx *ctx; + struct buffer_head *bh; + + if (!test) + return ERR_PTR(-EIO); + ctx = test->priv; + if (!ctx || sb != ctx->sb) + return ERR_PTR(-EIO); + if ((ext4_fsblk_t)block >= ctx->device_blocks) + return ERR_PTR(-EIO); + + bh = resize_get_or_create_bh(ctx, block); + if (!bh) + return ERR_PTR(-ENOMEM); + return bh; +} + +static int resize_zeroout_stub(struct super_block *sb, sector_t blk, + sector_t nr_blks, gfp_t gfp_mask) +{ + struct kunit *test = active_resize_test; + struct resize_test_ctx *ctx; + sector_t i; + + if (!test) + return 0; + ctx = test->priv; + if (!ctx) + return 0; + if (ctx->zeroout_err) + return ctx->zeroout_err; + + ctx->zeroout_calls++; + ctx->zeroout_blks += nr_blks; + for (i = 0; i < nr_blks; i++) { + struct buffer_head *bh = resize_lookup_bh(ctx, blk + i); + + if (bh) + memset(bh->b_data, 0, bh->b_size); + } + return 0; +} + +static struct inode *resize_iget_stub(struct super_block *sb, unsigned long ino, + ext4_iget_flags flags, + const char *function, unsigned int line) +{ + struct kunit *test = active_resize_test; + struct resize_test_ctx *ctx; + + if (!test) + return ERR_PTR(-ENOENT); + ctx = test->priv; + if (!ctx || sb != ctx->sb) + return ERR_PTR(-ENOENT); + if (ino == EXT4_RESIZE_INO && ctx->resize_inode) { + ihold(ctx->resize_inode); + return ctx->resize_inode; + } + return ERR_PTR(-ENOENT); +} + +static int resize_get_inode_loc_stub(struct inode *inode, + struct ext4_iloc *iloc) +{ + struct kunit *test = active_resize_test; + struct resize_test_ctx *ctx; + + if (!test) + return -EIO; + ctx = test->priv; + if (!ctx) + return -EIO; + + get_bh(&ctx->iloc_bh); + iloc->bh = &ctx->iloc_bh; + iloc->offset = 0; + iloc->block_group = 0; + return 0; +} + +static int resize_mark_iloc_dirty_stub(handle_t *handle, struct inode *inode, + struct ext4_iloc *iloc) +{ + brelse(iloc->bh); + iloc->bh = NULL; + return 0; +} + +static int resize_mark_inode_dirty_stub(handle_t *handle, struct inode *inode, + const char *func, unsigned int line) +{ + return 0; +} + +static void resize_free_blocks_stub(handle_t *handle, struct inode *inode, + struct buffer_head *bh, ext4_fsblk_t block, + unsigned long count, int flags) +{ + struct kunit *test = active_resize_test; + struct resize_test_ctx *ctx; + + if (!test) + return; + ctx = test->priv; + if (!ctx) + return; + + ctx->last_freed_blk = block; + ctx->last_freed_count = count; + if (bh) + brelse(bh); +} + +static void resize_test_cleanup(struct resize_test_ctx *ctx) +{ + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + struct flex_groups **flex_groups; + struct resize_mock_blk *blk, *tmp; + unsigned int i; + + active_resize_test = NULL; + + cancel_work_sync(&sbi->s_sb_upd_work); + timer_delete_sync(&sbi->s_err_report); + + if (ctx->resize_inode) { + iput(ctx->resize_inode); + ctx->resize_inode = NULL; + } + + if (ctx->mb_inited && sb) { + ext4_mb_release(sb); + ctx->mb_inited = false; + } + + if (sb) { + deactivate_super(sb); + ctx->sb = NULL; + } + rcu_barrier(); + + percpu_counter_destroy(&sbi->s_freeclusters_counter); + percpu_counter_destroy(&sbi->s_dirtyclusters_counter); + percpu_counter_destroy(&sbi->s_freeinodes_counter); + + flex_groups = rcu_access_pointer(sbi->s_flex_groups); + if (flex_groups) { + for (i = 0; i < sbi->s_flex_groups_allocated; i++) + kvfree(flex_groups[i]); + kvfree(flex_groups); + rcu_assign_pointer(sbi->s_flex_groups, NULL); + sbi->s_flex_groups_allocated = 0; + } + + kvfree(rcu_access_pointer(sbi->s_group_desc)); + rcu_assign_pointer(sbi->s_group_desc, NULL); + + list_for_each_entry_safe(blk, tmp, &ctx->blks, node) { + list_del(&blk->node); + kfree(blk->data); + kfree(blk); + } + + if (ctx->bh_folio) { + folio_put(ctx->bh_folio); + ctx->bh_folio = NULL; + } + + if (ctx->bdev.bd_stats) { + free_percpu(ctx->bdev.bd_stats); + ctx->bdev.bd_stats = NULL; + } +} + +KUNIT_DEFINE_ACTION_WRAPPER(resize_test_cleanup_action, resize_test_cleanup, + struct resize_test_ctx *); + +static int resize_test_set_super(struct super_block *sb, struct fs_context *fc) +{ + return set_anon_super_fc(sb, fc); +} + +/* + * Configure an in-memory ext4 filesystem with @ngroups initial groups, + * optional @reserved_gdb reserved GDT blocks (enabling RESIZE_INODE and + * populating the resize inode's DIND + reserved GDT blocks), optional + * flex_bg (@log_flex > 0), and @last_grp_blks blocks in the final group. + */ +static void resize_configure_fs(struct kunit *test, ext4_group_t ngroups, + u16 reserved_gdb, u8 log_flex, + u32 last_grp_blks) +{ + struct resize_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + struct ext4_super_block *es = ctx->es; + struct buffer_head **group_desc; + unsigned long gdb_count; + ext4_fsblk_t total_blks = RESIZE_TEST_FIRST_DATA_BLK; + ext4_fsblk_t total_free_blks = 0; + u32 total_inodes = ngroups * RESIZE_TEST_INODES_PER_GRP; + ext4_group_t g; + int ret; + + KUNIT_ASSERT_GT(test, ngroups, 0U); + KUNIT_ASSERT_LE(test, last_grp_blks, RESIZE_TEST_BLOCKS_PER_GRP); + + es->s_magic = cpu_to_le16(EXT4_SUPER_MAGIC); + es->s_log_block_size = cpu_to_le32(0); + es->s_log_cluster_size = cpu_to_le32(0); + es->s_first_data_block = cpu_to_le32(RESIZE_TEST_FIRST_DATA_BLK); + es->s_blocks_per_group = cpu_to_le32(RESIZE_TEST_BLOCKS_PER_GRP); + es->s_clusters_per_group = cpu_to_le32(RESIZE_TEST_BLOCKS_PER_GRP); + es->s_inodes_per_group = cpu_to_le32(RESIZE_TEST_INODES_PER_GRP); + es->s_inodes_count = cpu_to_le32(total_inodes); + es->s_free_inodes_count = cpu_to_le32(total_inodes - 10); + es->s_first_ino = cpu_to_le32(11); + es->s_inode_size = cpu_to_le16(RESIZE_TEST_INODE_SIZE); + es->s_desc_size = cpu_to_le16(RESIZE_TEST_DESC_SIZE); + es->s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + es->s_state = cpu_to_le16(EXT4_VALID_FS); + es->s_errors = cpu_to_le16(EXT4_ERRORS_CONTINUE); + es->s_checksum_type = EXT4_CRC32C_CHKSUM; + es->s_reserved_gdt_blocks = cpu_to_le16(reserved_gdb); + generate_random_uuid(es->s_uuid); + + ext4_set_feature_extents(sb); + ext4_set_feature_64bit(sb); + ext4_set_feature_filetype(sb); + ext4_set_feature_sparse_super(sb); + ext4_set_feature_metadata_csum(sb); + if (reserved_gdb > 0) + ext4_set_feature_resize_inode(sb); + if (log_flex > 0) { + ext4_set_feature_flex_bg(sb); + es->s_log_groups_per_flex = log_flex; + sbi->s_log_groups_per_flex = log_flex; + } + + sbi->s_csum_seed = ext4_chksum(~0, es->s_uuid, sizeof(es->s_uuid)); + sbi->s_groups_count = ngroups; + gdb_count = DIV_ROUND_UP(ngroups, RESIZE_TEST_DESC_PER_BLK); + sbi->s_gdb_count = gdb_count; + + group_desc = kvcalloc(gdb_count, sizeof(*group_desc), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, group_desc); + rcu_assign_pointer(sbi->s_group_desc, group_desc); + for (g = 0; g < gdb_count; g++) { + struct buffer_head *bh; + + bh = resize_get_or_create_bh(ctx, + RESIZE_TEST_FIRST_DATA_BLK + 1 + g); + KUNIT_ASSERT_NOT_NULL(test, bh); + brelse(bh); + group_desc[g] = bh; + } + + for (g = 0; g < ngroups; g++) { + u32 grp_blks = (g == ngroups - 1) ? + last_grp_blks : RESIZE_TEST_BLOCKS_PER_GRP; + ext4_fsblk_t start = ext4_group_first_block_no(sb, g); + unsigned int overhead = ext4_bg_num_gdb(sb, g); + unsigned int used_meta; + ext4_fsblk_t bb_blk, ib_blk, it_blk; + struct buffer_head *bb_bh, *ib_bh; + struct ext4_group_desc *gdp; + u32 free_blks; + + if (ext4_bg_has_super(sb, g)) + overhead += 1 + reserved_gdb; + + bb_blk = start + overhead; + ib_blk = bb_blk + 1; + it_blk = ib_blk + 1; + used_meta = overhead + 2 + RESIZE_TEST_ITB_PER_GRP; + if (g == 0 && reserved_gdb > 0) + used_meta++; + + bb_bh = resize_get_or_create_bh(ctx, bb_blk); + ib_bh = resize_get_or_create_bh(ctx, ib_blk); + KUNIT_ASSERT_NOT_NULL(test, bb_bh); + KUNIT_ASSERT_NOT_NULL(test, ib_bh); + + mb_set_bits(bb_bh->b_data, 0, used_meta); + ext4_mark_bitmap_end(grp_blks, sb->s_blocksize * 8, + bb_bh->b_data); + ext4_mark_bitmap_end(RESIZE_TEST_INODES_PER_GRP, + sb->s_blocksize * 8, ib_bh->b_data); + + gdp = ext4_get_group_desc(sb, g, NULL); + KUNIT_ASSERT_NOT_NULL(test, gdp); + memset(gdp, 0, RESIZE_TEST_DESC_SIZE); + ext4_block_bitmap_set(sb, gdp, bb_blk); + ext4_inode_bitmap_set(sb, gdp, ib_blk); + ext4_inode_table_set(sb, gdp, it_blk); + free_blks = grp_blks - used_meta; + ext4_free_group_clusters_set(sb, gdp, free_blks); + ext4_free_inodes_set(sb, gdp, RESIZE_TEST_INODES_PER_GRP); + ext4_itable_unused_set(sb, gdp, RESIZE_TEST_INODES_PER_GRP); + gdp->bg_flags = cpu_to_le16(EXT4_BG_INODE_ZEROED); + ext4_block_bitmap_csum_set(sb, gdp, bb_bh); + ext4_inode_bitmap_csum_set(sb, gdp, ib_bh); + ext4_group_desc_csum_set(sb, g, gdp); + + brelse(bb_bh); + brelse(ib_bh); + + total_blks += grp_blks; + total_free_blks += free_blks; + } + + ext4_blocks_count_set(es, total_blks); + ext4_free_blocks_count_set(es, total_free_blks); + ext4_r_blocks_count_set(es, div_u64(total_blks, 20)); + sbi->s_blockfile_groups = ngroups; + + if (reserved_gdb > 0) { + ext4_fsblk_t dind_blk; + struct buffer_head *dind_bh; + __le32 *dind_data; + unsigned int res; + unsigned int total_rsv_blks = 1; + + dind_blk = ext4_group_first_block_no(sb, 0) + 1 + gdb_count + + reserved_gdb + 2 + RESIZE_TEST_ITB_PER_GRP; + dind_bh = resize_get_or_create_bh(ctx, dind_blk); + KUNIT_ASSERT_NOT_NULL(test, dind_bh); + dind_data = (__le32 *)dind_bh->b_data; + + for (res = 0; res < reserved_gdb; res++) { + ext4_fsblk_t pri_blk = RESIZE_TEST_FIRST_DATA_BLK + 1 + + gdb_count + res; + struct buffer_head *pri_bh; + __le32 *pri_data; + unsigned int three = 1, five = 5, seven = 7; + unsigned int bgrp, idx = 0; + + dind_data[(gdb_count + res) % + EXT4_ADDR_PER_BLOCK(sb)] = + cpu_to_le32(pri_blk); + pri_bh = resize_get_or_create_bh(ctx, pri_blk); + KUNIT_ASSERT_NOT_NULL(test, pri_bh); + pri_data = (__le32 *)pri_bh->b_data; + + while ((bgrp = ext4_list_backups(sb, &three, &five, + &seven)) < ngroups) { + pri_data[idx++] = cpu_to_le32( + bgrp * RESIZE_TEST_BLOCKS_PER_GRP + + pri_blk); + } + total_rsv_blks += 1 + idx; + brelse(pri_bh); + } + brelse(dind_bh); + + ctx->resize_inode = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, ctx->resize_inode); + ctx->resize_inode->i_ino = EXT4_RESIZE_INO; + ctx->resize_inode->i_mode = S_IFREG | 0600; + ctx->resize_inode->i_blkbits = RESIZE_TEST_BLK_BITS; + ctx->resize_inode->i_blocks = total_rsv_blks * + (RESIZE_TEST_BLK_SIZE >> 9); + EXT4_I(ctx->resize_inode)->i_data[EXT4_DIND_BLOCK] = + cpu_to_le32(dind_blk); + } + + if (log_flex > 0) { + ret = ext4_fill_flex_info_test(sb); + KUNIT_ASSERT_EQ(test, ret, 1); + } + + ret = ext4_mb_init(sb); + KUNIT_ASSERT_EQ(test, ret, 0); + ctx->mb_inited = true; + + ret = percpu_counter_init(&sbi->s_freeclusters_counter, + total_free_blks, GFP_KERNEL); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = percpu_counter_init(&sbi->s_dirtyclusters_counter, 0, GFP_KERNEL); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = percpu_counter_init(&sbi->s_freeinodes_counter, + total_inodes - 10, GFP_KERNEL); + KUNIT_ASSERT_EQ(test, ret, 0); + + ext4_calculate_overhead(sb); + es->s_overhead_clusters = cpu_to_le32(sbi->s_overhead); + ext4_superblock_csum_set(sb); +} + +static int resize_test_init(struct kunit *test) +{ + struct resize_test_ctx *ctx; + struct fs_context *fc; + struct super_block *sb; + struct ext4_sb_info *sbi; + struct buffer_head *sbh; + int ret; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + INIT_LIST_HEAD(&ctx->blks); + ctx->device_blocks = 1 + 64 * RESIZE_TEST_BLOCKS_PER_GRP; + test->priv = ctx; + + ctx->bdev.bd_stats = alloc_percpu(struct disk_stats); + KUNIT_ASSERT_TRUE(test, ctx->bdev.bd_stats != NULL); + + ctx->bh_folio = folio_alloc(GFP_KERNEL, 0); + if (!ctx->bh_folio) { + free_percpu(ctx->bdev.bd_stats); + ctx->bdev.bd_stats = NULL; + KUNIT_FAIL_AND_ABORT(test, "folio_alloc failed"); + } + + fc = fs_context_for_mount(&resize_test_fs_type, 0); + if (IS_ERR(fc)) { + folio_put(ctx->bh_folio); + ctx->bh_folio = NULL; + free_percpu(ctx->bdev.bd_stats); + ctx->bdev.bd_stats = NULL; + KUNIT_FAIL_AND_ABORT(test, "fs_context_for_mount failed: %ld", + PTR_ERR(fc)); + } + sb = sget_fc(fc, NULL, resize_test_set_super); + put_fs_context(fc); + if (IS_ERR(sb)) { + folio_put(ctx->bh_folio); + ctx->bh_folio = NULL; + free_percpu(ctx->bdev.bd_stats); + ctx->bdev.bd_stats = NULL; + KUNIT_FAIL_AND_ABORT(test, "sget_fc failed: %ld", PTR_ERR(sb)); + } + ctx->sb = sb; + sbi = &ctx->sbi; + INIT_WORK(&sbi->s_sb_upd_work, resize_test_sb_upd_work); + timer_setup(&sbi->s_err_report, resize_test_err_timer, 0); + up_write(&sb->s_umount); + + ret = kunit_add_action_or_reset(test, resize_test_cleanup_action, ctx); + KUNIT_ASSERT_EQ(test, ret, 0); + + sb->s_fs_info = sbi; + sb->s_op = &resize_test_sops; + sb->s_blocksize = RESIZE_TEST_BLK_SIZE; + sb->s_blocksize_bits = RESIZE_TEST_BLK_BITS; + sb->s_magic = EXT4_SUPER_MAGIC; + sb->s_maxbytes = MAX_LFS_FILESIZE; + INIT_LIST_HEAD(&sb->s_inodes); +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; +#endif + + strscpy(sb->s_id, "ext4_resize_kunit", sizeof(sb->s_id)); + inode_init_once(&ctx->bd_inode); + ctx->bd_inode.i_sb = sb; + ctx->bd_inode.i_blkbits = RESIZE_TEST_BLK_BITS; + ctx->bd_inode.i_mapping = &ctx->bd_inode.i_data; + ctx->bd_inode.i_data.host = &ctx->bd_inode; + ctx->bdev_disk.part0 = &ctx->bdev; + ctx->bdev_disk.queue = &ctx->bdev_queue; + ctx->bdev.bd_disk = &ctx->bdev_disk; + ctx->bdev.bd_queue = &ctx->bdev_queue; + ctx->bdev.bd_mapping = &ctx->bd_inode.i_data; + bdev_clear_flag(&ctx->bdev, BD_READ_ONLY); + sb->s_bdev = &ctx->bdev; + + sbi->s_sb = sb; + sbi->s_blockgroup_lock = &ctx->bgl; + bgl_lock_init(&ctx->bgl); + spin_lock_init(&sbi->s_error_lock); + spin_lock_init(&sbi->s_md_lock); + spin_lock_init(&sbi->s_bdev_wb_lock); + spin_lock_init(&sbi->s_es_lock); + INIT_LIST_HEAD(&sbi->s_es_list); + mutex_init(&sbi->s_fc_lock); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_STAGING]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_MAIN]); + INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_STAGING]); + ratelimit_state_init(&sbi->s_err_ratelimit_state, 5 * HZ, 10); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, 5 * HZ, 10); + ratelimit_state_init(&sbi->s_msg_ratelimit_state, 5 * HZ, 10); + + sbi->s_blocks_per_group = RESIZE_TEST_BLOCKS_PER_GRP; + sbi->s_clusters_per_group = RESIZE_TEST_BLOCKS_PER_GRP; + sbi->s_cluster_ratio = 1; + sbi->s_cluster_bits = 0; + sbi->s_inodes_per_group = RESIZE_TEST_INODES_PER_GRP; + sbi->s_inode_size = RESIZE_TEST_INODE_SIZE; + sbi->s_inodes_per_block = RESIZE_TEST_BLK_SIZE / RESIZE_TEST_INODE_SIZE; + sbi->s_itb_per_group = RESIZE_TEST_ITB_PER_GRP; + sbi->s_desc_size = RESIZE_TEST_DESC_SIZE; + sbi->s_desc_per_block = RESIZE_TEST_DESC_PER_BLK; + sbi->s_desc_per_block_bits = RESIZE_TEST_DESC_PER_BLK_BITS; + sbi->s_first_ino = 11; + sbi->s_mount_state = EXT4_VALID_FS; + set_opt(sb, ERRORS_CONT); + + sbh = resize_get_or_create_bh(ctx, RESIZE_TEST_FIRST_DATA_BLK); + KUNIT_ASSERT_NOT_NULL(test, sbh); + brelse(sbh); + sbi->s_sbh = sbh; + ctx->es = (struct ext4_super_block *)sbh->b_data; + sbi->s_es = ctx->es; + + resize_init_mock_bh(&ctx->iloc_bh, ctx->bh_folio, ctx->iloc_buf, + RESIZE_TEST_BLK_SIZE, 99); + + active_resize_test = test; + kunit_activate_static_stub(test, ext4_sb_getblk, resize_sb_getblk_stub); + kunit_activate_static_stub(test, ext4_sb_bread, resize_sb_bread_stub); + kunit_activate_static_stub(test, ext4_resize_issue_zeroout, + resize_zeroout_stub); + kunit_activate_static_stub(test, __ext4_iget, resize_iget_stub); + kunit_activate_static_stub(test, ext4_get_inode_loc, + resize_get_inode_loc_stub); + kunit_activate_static_stub(test, ext4_mark_iloc_dirty, + resize_mark_iloc_dirty_stub); + kunit_activate_static_stub(test, __ext4_mark_inode_dirty, + resize_mark_inode_dirty_stub); + kunit_activate_static_stub(test, ext4_free_blocks, + resize_free_blocks_stub); + + return 0; +} + +/* + * Test 1: ext4_resize_begin() precondition checks and EXT4_FLAGS_RESIZING + * mutual exclusion with ext4_resize_end(). + */ +static void test_resize_begin_and_end_guards(struct kunit *test) +{ + struct resize_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + + resize_configure_fs(test, 2, 0, 0, RESIZE_TEST_BLOCKS_PER_GRP); + + /* Non-zero s_reserved_gdt_blocks without resize_inode -> -EFSCORRUPTED */ + ctx->es->s_reserved_gdt_blocks = cpu_to_le16(2); + KUNIT_EXPECT_EQ(test, ext4_resize_begin(sb), -EFSCORRUPTED); + ctx->es->s_reserved_gdt_blocks = 0; + ctx->sbi.s_mount_state &= ~EXT4_ERROR_FS; + + /* Mounted from backup superblock -> -EPERM */ + ctx->sbi.s_sbh->b_blocknr = 1025; + KUNIT_EXPECT_EQ(test, ext4_resize_begin(sb), -EPERM); + ctx->sbi.s_sbh->b_blocknr = RESIZE_TEST_FIRST_DATA_BLK; + + /* Filesystem has recorded errors -> -EPERM */ + ctx->sbi.s_mount_state |= EXT4_ERROR_FS; + KUNIT_EXPECT_EQ(test, ext4_resize_begin(sb), -EPERM); + ctx->sbi.s_mount_state &= ~EXT4_ERROR_FS; + + /* sparse_super2 online resize unsupported -> -EOPNOTSUPP */ + ext4_set_feature_sparse_super2(sb); + KUNIT_EXPECT_EQ(test, ext4_resize_begin(sb), -EOPNOTSUPP); + ext4_clear_feature_sparse_super2(sb); + + /* Valid begin acquires EXT4_FLAGS_RESIZING; second call gets -EBUSY */ + KUNIT_EXPECT_EQ(test, ext4_resize_begin(sb), 0); + KUNIT_EXPECT_TRUE(test, test_bit(EXT4_FLAGS_RESIZING, + &ctx->sbi.s_ext4_flags)); + KUNIT_EXPECT_EQ(test, ext4_resize_begin(sb), -EBUSY); + + /* ext4_resize_end releases lock so subsequent begin succeeds */ + KUNIT_EXPECT_EQ(test, ext4_resize_end(sb, false), 0); + KUNIT_EXPECT_FALSE(test, test_bit(EXT4_FLAGS_RESIZING, + &ctx->sbi.s_ext4_flags)); + KUNIT_EXPECT_EQ(test, ext4_resize_begin(sb), 0); + KUNIT_EXPECT_EQ(test, ext4_resize_end(sb, false), 0); +} + +/* + * Test 2: ext4_list_backups() sequence generation (sparse_super, dense, and + * sparse_super2) and verify_reserved_gdb() validation. + */ +static void test_list_backups_and_verify_reserved_gdb(struct kunit *test) +{ + struct resize_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + static const unsigned int expected_sparse[] = { + 1, 3, 5, 7, 9, 25, 27, 49, 81 + }; + unsigned int three, five, seven; + struct buffer_head *pri_bh; + __le32 *pri_data; + unsigned int i; + + resize_configure_fs(test, 4, 0, 0, RESIZE_TEST_BLOCKS_PER_GRP); + + /* 1. sparse_super yields sorted powers of 3, 5, and 7 */ + three = 1; + five = 5; + seven = 7; + for (i = 0; i < ARRAY_SIZE(expected_sparse); i++) { + KUNIT_EXPECT_EQ_MSG(test, + ext4_list_backups(sb, &three, &five, &seven), + expected_sparse[i], "sparse index %u", i); + } + + /* 2. Without sparse_super: every consecutive group 1, 2, 3, 4 */ + ext4_clear_feature_sparse_super(sb); + three = 1; + five = 5; + seven = 7; + for (i = 1; i <= 4; i++) + KUNIT_EXPECT_EQ(test, + ext4_list_backups(sb, &three, &five, &seven), + i); + ext4_set_feature_sparse_super(sb); + + /* 3. sparse_super2: reads s_backup_bgs[0..1], skipping 0, then UINT_MAX */ + ext4_set_feature_sparse_super2(sb); + ctx->es->s_backup_bgs[0] = 0; + ctx->es->s_backup_bgs[1] = cpu_to_le32(12); + three = 1; + five = 5; + seven = 7; + KUNIT_EXPECT_EQ(test, ext4_list_backups(sb, &three, &five, &seven), 12U); + KUNIT_EXPECT_EQ(test, ext4_list_backups(sb, &three, &five, &seven), + UINT_MAX); + ext4_clear_feature_sparse_super2(sb); + + /* 4. verify_reserved_gdb: valid backup list for groups < 10 (5 backups) */ + pri_bh = resize_get_or_create_bh(ctx, 3); + KUNIT_ASSERT_NOT_NULL(test, pri_bh); + pri_data = (__le32 *)pri_bh->b_data; + for (i = 0; i < 5; i++) + pri_data[i] = cpu_to_le32(expected_sparse[i] * + RESIZE_TEST_BLOCKS_PER_GRP + 3); + KUNIT_EXPECT_EQ(test, ext4_verify_reserved_gdb_test(sb, 10, pri_bh), 5); + + /* Corrupted backup block entry -> -EINVAL */ + pri_data[2] = cpu_to_le32(99999); + KUNIT_EXPECT_EQ(test, ext4_verify_reserved_gdb_test(sb, 10, pri_bh), + -EINVAL); + + /* Exceeding EXT4_ADDR_PER_BLOCK (256 on 1K blocks) -> -EFBIG */ + ext4_clear_feature_sparse_super(sb); + for (i = 0; i <= 257 && i < RESIZE_TEST_BLK_SIZE / sizeof(__le32); i++) + pri_data[i] = cpu_to_le32((i + 1) * RESIZE_TEST_BLOCKS_PER_GRP + + 3); + /* + * Allocate an oversized buffer temporarily so 257 entries can match + * before hitting ++gdbackups > EXT4_ADDR_PER_BLOCK(sb) (256). + */ + { + __le32 *big_buf = kunit_kcalloc(test, 260, sizeof(__le32), + GFP_KERNEL); + u8 *orig_data = (u8 *)pri_bh->b_data; + + KUNIT_ASSERT_NOT_NULL(test, big_buf); + for (i = 0; i < 258; i++) + big_buf[i] = cpu_to_le32((i + 1) * + RESIZE_TEST_BLOCKS_PER_GRP + + 3); + pri_bh->b_data = (char *)big_buf; + KUNIT_EXPECT_EQ(test, + ext4_verify_reserved_gdb_test(sb, 259, pri_bh), + -EFBIG); + pri_bh->b_data = (char *)orig_data; + } + brelse(pri_bh); +} + +/* + * Test 3: verify_group_input() boundary and overlap checks when adding sparse + * backup group 3 (which carries superblock + GDT overhead at group start). + */ +static void test_verify_group_input_rejections_and_acceptance(struct kunit *test) +{ + struct resize_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_new_group_data input; + ext4_fsblk_t start; + unsigned int overhead; + + /* Configure 3 full groups (0..2); next group to add is sparse group 3 */ + resize_configure_fs(test, 3, 1, 0, RESIZE_TEST_BLOCKS_PER_GRP); + start = ext4_blocks_count(ctx->es); + /* Group 3 has backup super (1) + 1 GDT + 1 reserved GDT = 3 blocks */ + overhead = 3; + + memset(&input, 0, sizeof(input)); + input.group = 3; + input.blocks_count = RESIZE_TEST_BLOCKS_PER_GRP; + input.reserved_blocks = 50; + input.block_bitmap = start + overhead; + input.inode_bitmap = start + overhead + 1; + input.inode_table = start + overhead + 2; + + /* 1. Wrong group number */ + input.group = 4; + KUNIT_EXPECT_EQ(test, ext4_verify_group_input_test(sb, &input), + -EINVAL); + input.group = 3; + + /* 2. Previous last group not full */ + ext4_blocks_count_set(ctx->es, start - 10); + KUNIT_EXPECT_EQ(test, ext4_verify_group_input_test(sb, &input), + -EINVAL); + ext4_blocks_count_set(ctx->es, start); + + /* 3. reserved_blocks > blocks_count / 5 */ + input.reserved_blocks = 205; + KUNIT_EXPECT_EQ(test, ext4_verify_group_input_test(sb, &input), + -EINVAL); + input.reserved_blocks = 50; + + /* 4. blocks_count smaller than metadata (free_blocks_count < 0) */ + input.blocks_count = 10; + KUNIT_EXPECT_EQ(test, ext4_verify_group_input_test(sb, &input), + -EINVAL); + input.blocks_count = RESIZE_TEST_BLOCKS_PER_GRP; + + /* 5. Last block beyond underlying device -> -EIO */ + ctx->device_blocks = start + 100; + KUNIT_EXPECT_EQ(test, ext4_verify_group_input_test(sb, &input), -EIO); + ctx->device_blocks = 1 + 64 * RESIZE_TEST_BLOCKS_PER_GRP; + + /* 6. Bitmaps or inode table outside [start, end) */ + input.block_bitmap = start - 1; + KUNIT_EXPECT_EQ(test, ext4_verify_group_input_test(sb, &input), + -EINVAL); + input.block_bitmap = start + overhead; + + input.inode_bitmap = start + RESIZE_TEST_BLOCKS_PER_GRP; + KUNIT_EXPECT_EQ(test, ext4_verify_group_input_test(sb, &input), + -EINVAL); + input.inode_bitmap = start + overhead + 1; + + input.inode_table = start + RESIZE_TEST_BLOCKS_PER_GRP - + RESIZE_TEST_ITB_PER_GRP + 1; + KUNIT_EXPECT_EQ(test, ext4_verify_group_input_test(sb, &input), + -EINVAL); + input.inode_table = start + overhead + 2; + + /* 7. Bitmap collision and bitmap inside inode table */ + input.inode_bitmap = input.block_bitmap; + KUNIT_EXPECT_EQ(test, ext4_verify_group_input_test(sb, &input), + -EINVAL); + input.inode_bitmap = input.inode_table + 3; + KUNIT_EXPECT_EQ(test, ext4_verify_group_input_test(sb, &input), + -EINVAL); + input.inode_bitmap = start + overhead + 1; + + input.block_bitmap = input.inode_table; + KUNIT_EXPECT_EQ(test, ext4_verify_group_input_test(sb, &input), + -EINVAL); + input.block_bitmap = start + overhead; + + /* 8. Bitmaps or inode table overlapping superblock/GDT overhead */ + input.block_bitmap = start + overhead - 1; + KUNIT_EXPECT_EQ(test, ext4_verify_group_input_test(sb, &input), + -EINVAL); + input.block_bitmap = start + overhead; + + input.inode_bitmap = start; + KUNIT_EXPECT_EQ(test, ext4_verify_group_input_test(sb, &input), + -EINVAL); + input.inode_bitmap = start + overhead + 1; + + input.inode_table = start + 1; + KUNIT_EXPECT_EQ(test, ext4_verify_group_input_test(sb, &input), + -EINVAL); + input.inode_table = start + overhead + 2; + + /* 9. Valid group input accepted with exact free_clusters_count */ + KUNIT_EXPECT_EQ(test, ext4_verify_group_input_test(sb, &input), 0); + /* 1024 - 2 (bitmaps) - 3 (overhead) - 8 (itable) = 1011 */ + KUNIT_EXPECT_EQ(test, input.free_clusters_count, 1011U); +} + +/* + * Test 4: alloc_flex_gd(), ext4_setup_next_flex_gd(), and + * ext4_alloc_group_tables() packed flex_bg layout and -ENOSPC handling. + */ +static void test_alloc_setup_flex_gd_and_group_tables(struct kunit *test) +{ + struct resize_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_new_flex_group_data *flex_gd; + ext4_fsblk_t g4_start; + + /* 4 initial groups (1 flex_bg of size 4, log_flex = 2), meta_bg mode */ + resize_configure_fs(test, 4, 0, 2, RESIZE_TEST_BLOCKS_PER_GRP); + ext4_set_feature_meta_bg(sb); + ctx->es->s_first_meta_bg = 0; + + /* 1. alloc_flex_gd shrinks allocation when adding only 1 group (4..4) */ + flex_gd = ext4_alloc_flex_gd_test(16, 4, 4); + KUNIT_ASSERT_NOT_NULL(test, flex_gd); + KUNIT_EXPECT_EQ(test, flex_gd->resize_bg, 1U); + ext4_free_flex_gd_test(flex_gd); + + /* 2. Full flex_bg batch (groups 4..7, with group 7 partial = 500 blks) */ + flex_gd = ext4_alloc_flex_gd_test(4, 3, 7); + KUNIT_ASSERT_NOT_NULL(test, flex_gd); + KUNIT_EXPECT_EQ(test, flex_gd->resize_bg, 4U); + + /* No-op when target equals current blocks_count */ + KUNIT_EXPECT_EQ(test, + ext4_setup_next_flex_gd_test(sb, flex_gd, + ext4_blocks_count(ctx->es)), + 0); + + /* Setup groups 4, 5, 6 (1024 blks each) + group 7 (500 blks) */ + KUNIT_EXPECT_EQ(test, + ext4_setup_next_flex_gd_test(sb, flex_gd, + 1 + 7 * 1024 + 500), + 1); + KUNIT_EXPECT_EQ(test, flex_gd->count, 4U); + KUNIT_EXPECT_EQ(test, flex_gd->groups[0].group, 4U); + KUNIT_EXPECT_EQ(test, flex_gd->groups[3].group, 7U); + KUNIT_EXPECT_EQ(test, flex_gd->groups[3].blocks_count, 500U); + /* Final group clears BG_BLOCK_UNINIT under group_desc_csum */ + KUNIT_EXPECT_NE(test, flex_gd->bg_flags[0] & EXT4_BG_BLOCK_UNINIT, 0); + KUNIT_EXPECT_EQ(test, flex_gd->bg_flags[3] & EXT4_BG_BLOCK_UNINIT, 0); + + /* + * 3. ext4_alloc_group_tables: group 4 has no super/meta_bg overhead + * (group 5 has sparse backup super -> overhead=1, stopping contiguous + * span at end of group 4). All 4 block bitmaps, 4 inode bitmaps, and + * 4*8=32 inode table blocks (40 blocks total) pack into group 4! + */ + g4_start = ext4_group_first_block_no(sb, 4); + KUNIT_EXPECT_EQ(test, ext4_alloc_group_tables_test(sb, flex_gd, 4), 0); + KUNIT_EXPECT_EQ(test, flex_gd->groups[0].block_bitmap, g4_start); + KUNIT_EXPECT_EQ(test, flex_gd->groups[3].block_bitmap, g4_start + 3); + KUNIT_EXPECT_EQ(test, flex_gd->groups[0].inode_bitmap, g4_start + 4); + KUNIT_EXPECT_EQ(test, flex_gd->groups[3].inode_bitmap, g4_start + 7); + KUNIT_EXPECT_EQ(test, flex_gd->groups[0].inode_table, g4_start + 8); + KUNIT_EXPECT_EQ(test, flex_gd->groups[3].inode_table, g4_start + 32); + /* Group 4 hosts all 40 metadata blocks -> BG_BLOCK_UNINIT cleared */ + KUNIT_EXPECT_EQ(test, flex_gd->bg_flags[0] & EXT4_BG_BLOCK_UNINIT, 0); + KUNIT_EXPECT_EQ(test, flex_gd->groups[0].free_clusters_count, + 1024U - 40U); + + /* 4. Insufficient space in flex_gd returns -ENOSPC */ + flex_gd->count = 1; + flex_gd->groups[0].group = 4; + flex_gd->groups[0].blocks_count = 5; + flex_gd->groups[0].mdata_blocks = 0; + KUNIT_EXPECT_EQ(test, ext4_alloc_group_tables_test(sb, flex_gd, 4), + -ENOSPC); + + ext4_free_flex_gd_test(flex_gd); +} + +/* + * Test 5: ext4_group_extend() validation and partial-last-group online + * extension updating superblock, block bitmap, buddy cache, and backup SB. + */ +static void test_group_extend_partial_last_group(struct kunit *test) +{ + struct resize_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_super_block *es = ctx->es; + struct ext4_super_block *backup_es; + struct buffer_head *b1_bh; + ext4_fsblk_t o_blks, o_free; + s64 free_before; + + /* 2 groups: group 0 full (1024 blks), group 1 partial (600 blks) */ + resize_configure_fs(test, 2, 0, 0, 600); + o_blks = ext4_blocks_count(es); + o_free = ext4_free_blocks_count(es); + KUNIT_ASSERT_EQ(test, o_blks, 1ULL + 1024ULL + 600ULL); + + /* No-op for 0 and o_blocks_count */ + KUNIT_EXPECT_EQ(test, ext4_group_extend(sb, es, 0), 0); + KUNIT_EXPECT_EQ(test, ext4_group_extend(sb, es, o_blks), 0); + + /* Shrink attempt -> -EINVAL */ + KUNIT_EXPECT_EQ(test, ext4_group_extend(sb, es, o_blks - 10), -EINVAL); + + /* Target beyond underlying device -> -ENOSPC */ + ctx->device_blocks = o_blks + 100; + KUNIT_EXPECT_EQ(test, ext4_group_extend(sb, es, o_blks + 200), -ENOSPC); + ctx->device_blocks = 1 + 64 * RESIZE_TEST_BLOCKS_PER_GRP; + + /* Extend group 1 by 300 blocks (from 600 to 900 blocks) */ + free_before = percpu_counter_sum(&ctx->sbi.s_freeclusters_counter); + KUNIT_EXPECT_EQ(test, ext4_group_extend(sb, es, o_blks + 300), 0); + KUNIT_EXPECT_EQ(test, ext4_blocks_count(es), o_blks + 300); + KUNIT_EXPECT_EQ(test, ext4_free_blocks_count(es), o_free + 300); + KUNIT_EXPECT_EQ(test, + percpu_counter_sum(&ctx->sbi.s_freeclusters_counter), + free_before + 300); + + /* Extend past group 1 boundary clamps to end of group 1 (+124 blocks) */ + KUNIT_EXPECT_EQ(test, ext4_group_extend(sb, es, o_blks + 800), 0); + KUNIT_EXPECT_EQ(test, ext4_blocks_count(es), 1ULL + 2048ULL); + + /* Once group 1 is full, further ext4_group_extend returns -EPERM */ + KUNIT_EXPECT_EQ(test, ext4_group_extend(sb, es, 1ULL + 2200ULL), + -EPERM); + + /* Backup superblock in group 1 (block 1025) reflects new size */ + b1_bh = resize_lookup_bh(ctx, ext4_group_first_block_no(sb, 1)); + KUNIT_ASSERT_NOT_NULL(test, b1_bh); + backup_es = (struct ext4_super_block *)b1_bh->b_data; + KUNIT_EXPECT_EQ(test, ext4_blocks_count(backup_es), 1ULL + 2048ULL); + KUNIT_EXPECT_EQ(test, le16_to_cpu(backup_es->s_block_group_nr), 1U); +} + +/* + * Test 6: ext4_group_add() error guards and adding non-sparse group 2 plus + * sparse backup group 3 (exercising reserve_backup_gdb() on resize_inode). + */ +static void test_group_add_with_resize_inode_and_backup_gdb(struct kunit *test) +{ + struct resize_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_new_group_data input; + struct buffer_head *pri_bh; + __le32 *pri_data; + blkcnt_t rsv_iblocks_before; + ext4_fsblk_t start; + + /* 2 initial groups, 1 reserved GDT block (at block 3) */ + resize_configure_fs(test, 2, 1, 0, RESIZE_TEST_BLOCKS_PER_GRP); + + /* 1. Overflow guards on blocks_count and s_inodes_count */ + memset(&input, 0, sizeof(input)); + input.group = 2; + input.blocks_count = 1024; + ext4_blocks_count_set(ctx->es, ~0ULL - 100); + KUNIT_EXPECT_EQ(test, ext4_group_add(sb, &input), -EINVAL); + ext4_blocks_count_set(ctx->es, 1 + 2 * RESIZE_TEST_BLOCKS_PER_GRP); + + ctx->es->s_inodes_count = cpu_to_le32(~0U - 10); + KUNIT_EXPECT_EQ(test, ext4_group_add(sb, &input), -EINVAL); + ctx->es->s_inodes_count = cpu_to_le32(2 * RESIZE_TEST_INODES_PER_GRP); + + /* 2. Add group 2 (no backup super, overhead = 0) */ + start = ext4_blocks_count(ctx->es); + memset(&input, 0, sizeof(input)); + input.group = 2; + input.blocks_count = RESIZE_TEST_BLOCKS_PER_GRP; + input.block_bitmap = start; + input.inode_bitmap = start + 1; + input.inode_table = start + 2; + + KUNIT_EXPECT_EQ(test, ext4_group_add(sb, &input), 0); + KUNIT_EXPECT_EQ(test, ctx->sbi.s_groups_count, 3U); + + /* 3. Add group 3 (sparse backup super -> overhead = 3, reserves backup) */ + start = ext4_blocks_count(ctx->es); + memset(&input, 0, sizeof(input)); + input.group = 3; + input.blocks_count = RESIZE_TEST_BLOCKS_PER_GRP; + input.block_bitmap = start + 3; + input.inode_bitmap = start + 4; + input.inode_table = start + 5; + + /* Without resize_inode feature -> -EPERM */ + ext4_clear_feature_resize_inode(sb); + KUNIT_EXPECT_EQ(test, ext4_group_add(sb, &input), -EPERM); + ext4_set_feature_resize_inode(sb); + + rsv_iblocks_before = ctx->resize_inode->i_blocks; + KUNIT_EXPECT_EQ(test, ext4_group_add(sb, &input), 0); + KUNIT_EXPECT_EQ(test, ctx->sbi.s_groups_count, 4U); + + /* + * reserve_backup_gdb() must append group 3's reserved GDT block + * (3 * 1024 + 3 = 3075) at index 1 (after group 1's backup) in + * primary reserved GDT block 3 and increment resize_inode->i_blocks. + */ + pri_bh = resize_lookup_bh(ctx, 3); + KUNIT_ASSERT_NOT_NULL(test, pri_bh); + pri_data = (__le32 *)pri_bh->b_data; + KUNIT_EXPECT_EQ(test, le32_to_cpu(pri_data[1]), 3U * 1024U + 3U); + KUNIT_EXPECT_EQ(test, ctx->resize_inode->i_blocks, + rsv_iblocks_before + (RESIZE_TEST_BLK_SIZE >> 9)); +} + +/* + * Test 7: ext4_convert_meta_bg() sanity validation of resize_inode and + * conversion from resize_inode to meta_bg. + */ +static void test_convert_meta_bg_validation_and_conversion(struct kunit *test) +{ + struct resize_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct inode *rinode; + ext4_fsblk_t dind_blk = 42; + + resize_configure_fs(test, 16, 0, 0, RESIZE_TEST_BLOCKS_PER_GRP); + ext4_set_feature_resize_inode(sb); + + rinode = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, rinode); + rinode->i_blkbits = RESIZE_TEST_BLK_BITS; + rinode->i_blocks = RESIZE_TEST_BLK_SIZE >> 9; + EXT4_I(rinode)->i_data[EXT4_DIND_BLOCK] = cpu_to_le32(dind_blk); + + /* 1. Non-zero s_reserved_gdt_blocks -> -EPERM */ + ctx->es->s_reserved_gdt_blocks = cpu_to_le16(1); + KUNIT_EXPECT_EQ(test, ext4_convert_meta_bg_test(sb, rinode), -EPERM); + ctx->es->s_reserved_gdt_blocks = 0; + + /* 2. Wrong i_blocks on resize_inode -> -EINVAL */ + rinode->i_blocks = 8; + KUNIT_EXPECT_EQ(test, ext4_convert_meta_bg_test(sb, rinode), -EINVAL); + rinode->i_blocks = RESIZE_TEST_BLK_SIZE >> 9; + + /* 3. Unexpected direct block pointer or missing DIND -> -EINVAL */ + EXT4_I(rinode)->i_data[0] = cpu_to_le32(10); + KUNIT_EXPECT_EQ(test, ext4_convert_meta_bg_test(sb, rinode), -EINVAL); + EXT4_I(rinode)->i_data[0] = 0; + + EXT4_I(rinode)->i_data[EXT4_DIND_BLOCK] = 0; + KUNIT_EXPECT_EQ(test, ext4_convert_meta_bg_test(sb, rinode), -EINVAL); + EXT4_I(rinode)->i_data[EXT4_DIND_BLOCK] = cpu_to_le32(dind_blk); + ctx->sbi.s_mount_state &= ~EXT4_ERROR_FS; + + /* 4. Valid conversion clears RESIZE_INODE, sets META_BG, frees DIND */ + KUNIT_EXPECT_EQ(test, ext4_convert_meta_bg_test(sb, rinode), 0); + KUNIT_EXPECT_FALSE(test, ext4_has_feature_resize_inode(sb)); + KUNIT_EXPECT_TRUE(test, ext4_has_feature_meta_bg(sb)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es->s_first_meta_bg), 1U); + KUNIT_EXPECT_EQ(test, ctx->last_freed_blk, dind_blk); + KUNIT_EXPECT_EQ(test, ctx->last_freed_count, 1UL); + KUNIT_EXPECT_EQ(test, rinode->i_blocks, 0ULL); + KUNIT_EXPECT_EQ(test, le32_to_cpu(EXT4_I(rinode)->i_data[EXT4_DIND_BLOCK]), + 0U); + + iput(rinode); +} + +/* + * Test 8: End-to-end ext4_resize_fs() across error guards, bigalloc cluster + * rounding, consuming reserved GDT blocks (16 -> 32 groups via add_new_gdb), + * converting resize_inode -> meta_bg, and growing into meta_bg (32 -> 34 + * groups via add_new_gdb_meta_bg). + */ +static void test_resize_fs_across_resize_inode_to_meta_bg(struct kunit *test) +{ + struct resize_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + ext4_fsblk_t o_blks, target_blks, dind_blk; + + /* + * Start with 16 groups (1 full 64-byte GDT block), 1 reserved GDT + * block (allowing growth to 32 groups before meta_bg conversion), and + * flex_bg of 4 groups (log_flex = 2). + */ + resize_configure_fs(test, 16, 1, 2, RESIZE_TEST_BLOCKS_PER_GRP); + o_blks = ext4_blocks_count(ctx->es); + dind_blk = le32_to_cpu( + EXT4_I(ctx->resize_inode)->i_data[EXT4_DIND_BLOCK]); + + /* 1. Beyond device -> -ENOSPC; shrink -> -EINVAL; same size -> 0 */ + KUNIT_EXPECT_EQ(test, ext4_resize_fs(sb, ctx->device_blocks + 100), + -ENOSPC); + KUNIT_EXPECT_EQ(test, ext4_resize_fs(sb, o_blks - 100), -EINVAL); + KUNIT_EXPECT_EQ(test, ext4_resize_fs(sb, o_blks), 0); + + /* 2. Simultaneous resize_inode + meta_bg -> -EINVAL */ + ext4_set_feature_meta_bg(sb); + KUNIT_EXPECT_EQ(test, ext4_resize_fs(sb, o_blks + 1024), -EINVAL); + ext4_clear_feature_meta_bg(sb); + ctx->sbi.s_mount_state &= ~EXT4_ERROR_FS; + + /* 3. Grow from 16 groups to 34 groups across GDT & meta_bg boundary */ + target_blks = RESIZE_TEST_FIRST_DATA_BLK + + 34ULL * RESIZE_TEST_BLOCKS_PER_GRP; + KUNIT_EXPECT_EQ(test, ext4_resize_fs(sb, target_blks), 0); + + KUNIT_EXPECT_EQ(test, ctx->sbi.s_groups_count, 34U); + KUNIT_EXPECT_EQ(test, ctx->sbi.s_gdb_count, 3UL); + KUNIT_EXPECT_EQ(test, ext4_blocks_count(ctx->es), target_blks); + KUNIT_EXPECT_EQ(test, le16_to_cpu(ctx->es->s_reserved_gdt_blocks), 0U); + KUNIT_EXPECT_FALSE(test, ext4_has_feature_resize_inode(sb)); + KUNIT_EXPECT_TRUE(test, ext4_has_feature_meta_bg(sb)); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es->s_first_meta_bg), 2U); + KUNIT_EXPECT_EQ(test, ctx->last_freed_blk, dind_blk); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->es->s_inodes_count), + 34U * RESIZE_TEST_INODES_PER_GRP); +} + +static struct kunit_case ext4_resize_test_cases[] = { + KUNIT_CASE(test_resize_begin_and_end_guards), + KUNIT_CASE(test_list_backups_and_verify_reserved_gdb), + KUNIT_CASE(test_verify_group_input_rejections_and_acceptance), + KUNIT_CASE(test_alloc_setup_flex_gd_and_group_tables), + KUNIT_CASE(test_group_extend_partial_last_group), + KUNIT_CASE(test_group_add_with_resize_inode_and_backup_gdb), + KUNIT_CASE(test_convert_meta_bg_validation_and_conversion), + KUNIT_CASE(test_resize_fs_across_resize_inode_to_meta_bg), + {} +}; + +static struct kunit_suite ext4_resize_test_suite = { + .name = "ext4_resize_test", + .init = resize_test_init, + .test_cases = ext4_resize_test_cases, +}; + +kunit_test_suites(&ext4_resize_test_suite); + +MODULE_DESCRIPTION("KUnit tests for ext4 online filesystem resizing"); +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/resize.c b/fs/ext4/resize.c index 041ab212c3a6c3..8bc79819ef1607 100644 --- a/fs/ext4/resize.c +++ b/fs/ext4/resize.c @@ -13,6 +13,7 @@ #include #include #include +#include #include "ext4_jbd2.h" @@ -42,6 +43,16 @@ void ext4_kvfree_array_rcu(void *to_free) synchronize_rcu(); kvfree(to_free); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_kvfree_array_rcu); + +int ext4_resize_issue_zeroout(struct super_block *sb, sector_t blk, + sector_t nr_blks, gfp_t gfp_mask) +{ + KUNIT_STATIC_STUB_REDIRECT(ext4_resize_issue_zeroout, sb, blk, + nr_blks, gfp_mask); + return sb_issue_zeroout(sb, blk, nr_blks, gfp_mask); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_resize_issue_zeroout); int ext4_resize_begin(struct super_block *sb) { @@ -94,6 +105,7 @@ int ext4_resize_begin(struct super_block *sb) return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_resize_begin); int ext4_resize_end(struct super_block *sb, bool update_backups) { @@ -103,6 +115,7 @@ int ext4_resize_end(struct super_block *sb, bool update_backups) return ext4_update_overhead(sb, true); return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_resize_end); static ext4_grpblk_t ext4_group_overhead_blocks(struct super_block *sb, ext4_group_t group) { @@ -209,21 +222,6 @@ static int verify_group_input(struct super_block *sb, return err; } -/* - * ext4_new_flex_group_data is used by 64bit-resize interface to add a flex - * group each time. - */ -struct ext4_new_flex_group_data { - struct ext4_new_group_data *groups; /* new_group_data for groups - in the flex group */ - __u16 *bg_flags; /* block group flags of groups - in @groups */ - ext4_group_t resize_bg; /* number of allocated - new_group_data */ - ext4_group_t count; /* number of groups in @groups - */ -}; - /* * Avoiding memory allocation failures due to too many groups added each time. */ @@ -424,7 +422,7 @@ static struct buffer_head *bclean(handle_t *handle, struct super_block *sb, struct buffer_head *bh; int err; - bh = sb_getblk(sb, blk); + bh = ext4_sb_getblk(sb, blk); if (unlikely(!bh)) return ERR_PTR(-ENOMEM); BUFFER_TRACE(bh, "get_write_access"); @@ -488,7 +486,7 @@ static int set_flexbg_block_bitmap(struct super_block *sb, handle_t *handle, if (err < 0) return err; - bh = sb_getblk(sb, flex_gd->groups[group].block_bitmap); + bh = ext4_sb_getblk(sb, flex_gd->groups[group].block_bitmap); if (unlikely(!bh)) return -ENOMEM; @@ -577,7 +575,7 @@ static int setup_new_flex_group_blocks(struct super_block *sb, if (err < 0) goto out; - gdb = sb_getblk(sb, block); + gdb = ext4_sb_getblk(sb, block); if (unlikely(!gdb)) { err = -ENOMEM; goto out; @@ -606,8 +604,8 @@ static int setup_new_flex_group_blocks(struct super_block *sb, * table blocks */ if (ext4_bg_has_super(sb, group)) { - err = sb_issue_zeroout(sb, gdblocks + start + 1, - reserved_gdb, GFP_NOFS); + err = ext4_resize_issue_zeroout(sb, gdblocks + start + 1, + reserved_gdb, GFP_NOFS); if (err) goto out; } @@ -621,8 +619,8 @@ static int setup_new_flex_group_blocks(struct super_block *sb, block = group_data[i].inode_table; ext4_debug("clear inode table blocks %#04llx -> %#04lx\n", block, sbi->s_itb_per_group); - err = sb_issue_zeroout(sb, block, sbi->s_itb_per_group, - GFP_NOFS); + err = ext4_resize_issue_zeroout(sb, block, sbi->s_itb_per_group, + GFP_NOFS); if (err) goto out; @@ -766,6 +764,7 @@ unsigned int ext4_list_backups(struct super_block *sb, unsigned int *three, return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_list_backups); /* * Check that all of the backup GDT blocks are held in the primary GDT block. @@ -795,7 +794,7 @@ static int verify_reserved_gdb(struct super_block *sb, blk); return -EINVAL; } - if (++gdbackups > EXT4_ADDR_PER_BLOCK(sb)) + if (++gdbackups >= EXT4_ADDR_PER_BLOCK(sb)) return -EFBIG; } @@ -1181,7 +1180,7 @@ static void update_backups(struct super_block *sb, sector_t blk_off, char *data, else backup_block = first_block + has_super; - bh = sb_getblk(sb, backup_block); + bh = ext4_sb_getblk(sb, backup_block); if (unlikely(!bh)) { err = -ENOMEM; break; @@ -1294,7 +1293,7 @@ static int ext4_add_new_descs(handle_t *handle, struct super_block *sb, static struct buffer_head *ext4_get_bitmap(struct super_block *sb, __u64 block) { - struct buffer_head *bh = sb_getblk(sb, block); + struct buffer_head *bh = ext4_sb_getblk(sb, block); if (unlikely(!bh)) return NULL; if (!bh_uptodate_or_lock(bh)) { @@ -1765,6 +1764,7 @@ int ext4_group_add(struct super_block *sb, struct ext4_new_group_data *input) iput(inode); return err; } /* ext4_group_add */ +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_group_add); /* * extend a group without checking assuming that checking has been done. @@ -1896,6 +1896,7 @@ int ext4_group_extend(struct super_block *sb, struct ext4_super_block *es, return ext4_group_extend_no_check(sb, o_blocks_count, add); } /* ext4_group_extend */ +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_group_extend); static int num_desc_blocks(struct super_block *sb, ext4_group_t groups) @@ -2192,3 +2193,56 @@ int ext4_resize_fs(struct super_block *sb, ext4_fsblk_t n_blocks_count) ext4_blocks_count(es)); return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_resize_fs); + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +int ext4_verify_group_input_test(struct super_block *sb, + struct ext4_new_group_data *input) +{ + return verify_group_input(sb, input); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_verify_group_input_test); + +struct ext4_new_flex_group_data * +ext4_alloc_flex_gd_test(unsigned int flexbg_size, ext4_group_t o_group, + ext4_group_t n_group) +{ + return alloc_flex_gd(flexbg_size, o_group, n_group); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_alloc_flex_gd_test); + +void ext4_free_flex_gd_test(struct ext4_new_flex_group_data *flex_gd) +{ + free_flex_gd(flex_gd); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_free_flex_gd_test); + +int ext4_alloc_group_tables_test(struct super_block *sb, + struct ext4_new_flex_group_data *flex_gd, + unsigned int flexbg_size) +{ + return ext4_alloc_group_tables(sb, flex_gd, flexbg_size); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_alloc_group_tables_test); + +int ext4_verify_reserved_gdb_test(struct super_block *sb, ext4_group_t end, + struct buffer_head *primary) +{ + return verify_reserved_gdb(sb, end, primary); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_verify_reserved_gdb_test); + +int ext4_setup_next_flex_gd_test(struct super_block *sb, + struct ext4_new_flex_group_data *flex_gd, + ext4_fsblk_t n_blocks_count) +{ + return ext4_setup_next_flex_gd(sb, flex_gd, n_blocks_count); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_setup_next_flex_gd_test); + +int ext4_convert_meta_bg_test(struct super_block *sb, struct inode *inode) +{ + return ext4_convert_meta_bg(sb, inode); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_convert_meta_bg_test); +#endif diff --git a/fs/ext4/super-test.c b/fs/ext4/super-test.c new file mode 100644 index 00000000000000..606798ef0258cc --- /dev/null +++ b/fs/ext4/super-test.c @@ -0,0 +1,1345 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for fs/ext4/super.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_jbd2.h" +#include "xattr.h" + +#define SUPER_TEST_NGROUPS 4U +#define SUPER_TEST_BLK_SIZE 1024U +#define SUPER_TEST_BLK_BITS 10U +#define SUPER_TEST_BLOCKS_PER_GRP 1024U +#define SUPER_TEST_FIRST_DATA_BLK 1U +#define SUPER_TEST_TOTAL_BLKS (SUPER_TEST_FIRST_DATA_BLK + \ + SUPER_TEST_NGROUPS * \ + SUPER_TEST_BLOCKS_PER_GRP) +#define SUPER_TEST_INODE_SIZE 256U +#define SUPER_TEST_EXTRA_ISIZE 32U +#define SUPER_TEST_INODES_PER_BLK (SUPER_TEST_BLK_SIZE / \ + SUPER_TEST_INODE_SIZE) +#define SUPER_TEST_INODES_PER_GRP 32U +#define SUPER_TEST_ITB_PER_GRP (SUPER_TEST_INODES_PER_GRP / \ + SUPER_TEST_INODES_PER_BLK) +#define SUPER_TEST_TOTAL_INODES (SUPER_TEST_NGROUPS * \ + SUPER_TEST_INODES_PER_GRP) +#define SUPER_TEST_FIRST_INO 11U +#define SUPER_TEST_GDB_COUNT 1U +#define SUPER_TEST_RSV_GDT_BLKS 2U + +struct super_test_ctx { + struct super_block *sb; + struct ext4_sb_info sbi; + struct ext4_super_block es; + struct blockgroup_lock bgl; + struct gendisk bdev_disk; + struct block_device bdev; + struct request_queue bdev_queue; + struct inode bd_inode; + struct buffer_head sb_bh; + struct ext4_group_desc gdps[8]; + journal_t mock_journal; + struct inode *journal_inode; + bool counters_inited; +}; + +static struct kunit *active_super_test; + +static struct inode *super_test_alloc_inode(struct super_block *sb) +{ + struct ext4_inode_info *ei; + + ei = kzalloc_obj(*ei); + if (!ei) + return NULL; + + init_rwsem(&ei->i_data_sem); + inode_init_once(&ei->vfs_inode); + inode_set_iversion(&ei->vfs_inode, 1); + ei->i_prealloc_node = RB_ROOT; + rwlock_init(&ei->i_prealloc_lock); + ext4_es_init_tree(&ei->i_es_tree); + rwlock_init(&ei->i_es_lock); + INIT_LIST_HEAD(&ei->i_es_list); + spin_lock_init(&ei->i_raw_lock); + spin_lock_init(&ei->i_block_reservation_lock); + ext4_init_pending_tree(&ei->i_pending_tree); + init_rwsem(&ei->xattr_sem); + INIT_LIST_HEAD(&ei->i_rsv_conversion_list); + spin_lock_init(&ei->i_completed_io_lock); + INIT_LIST_HEAD(&ei->i_orphan); + ext4_fc_init_inode(&ei->vfs_inode); + spin_lock_init(&ei->i_fc_lock); + ei->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + ei->i_extra_isize = SUPER_TEST_EXTRA_ISIZE; + ei->i_last_alloc_group = ~0U; + + return &ei->vfs_inode; +} + +static void super_test_free_inode(struct inode *inode) +{ + kfree(EXT4_I(inode)); +} + +static void super_test_evict_inode(struct inode *inode) +{ + truncate_inode_pages_final(&inode->i_data); + clear_inode(inode); +} + +#ifdef CONFIG_QUOTA +static struct dquot __rcu **super_test_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} +#endif + +static const struct super_operations super_test_sops = { + .alloc_inode = super_test_alloc_inode, + .free_inode = super_test_free_inode, + .evict_inode = super_test_evict_inode, +#ifdef CONFIG_QUOTA + .get_dquots = super_test_get_dquots, +#endif +}; + +static void super_test_sb_upd_work(struct work_struct *work) +{ +} + +static void super_test_err_timer(struct timer_list *t) +{ +} + +static int super_test_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static struct file_system_type super_test_fs_type = { + .name = "ext4_super_kunit", + .init_fs_context = super_test_init_fs_context, + .kill_sb = kill_anon_super, +}; + +static inline ext4_fsblk_t super_group_first_blk(ext4_group_t g) +{ + return SUPER_TEST_FIRST_DATA_BLK + + (ext4_fsblk_t)g * SUPER_TEST_BLOCKS_PER_GRP; +} + +static inline unsigned int super_default_base_meta(ext4_group_t g) +{ + if (g == 2) + return 0; + return 1U + SUPER_TEST_GDB_COUNT + SUPER_TEST_RSV_GDT_BLKS; +} + +static void super_setup_default_groups(struct super_test_ctx *ctx) +{ + struct super_block *sb = ctx->sb; + ext4_group_t g; + + memset(ctx->gdps, 0, sizeof(ctx->gdps)); + for (g = 0; g < SUPER_TEST_NGROUPS; g++) { + ext4_fsblk_t base = super_group_first_blk(g) + + super_default_base_meta(g); + + ext4_block_bitmap_set(sb, &ctx->gdps[g], base); + ext4_inode_bitmap_set(sb, &ctx->gdps[g], base + 1); + ext4_inode_table_set(sb, &ctx->gdps[g], base + 2); + ctx->gdps[g].bg_flags = cpu_to_le16(EXT4_BG_INODE_ZEROED); + ext4_group_desc_csum_set(sb, g, &ctx->gdps[g]); + } +} + +static struct ext4_group_desc * +super_get_group_desc_stub(struct super_block *sb, ext4_group_t block_group, + struct buffer_head **bh) +{ + struct kunit *test = active_super_test; + struct super_test_ctx *ctx; + + if (!test) + return NULL; + ctx = test->priv; + if (!ctx || sb != ctx->sb || block_group >= ARRAY_SIZE(ctx->gdps)) + return NULL; + if (bh) + *bh = NULL; + return &ctx->gdps[block_group]; +} + +static struct inode *super_iget_stub(struct super_block *sb, unsigned long ino, + ext4_iget_flags flags, + const char *function, unsigned int line) +{ + struct kunit *test = active_super_test; + struct super_test_ctx *ctx; + + if (!test) + return ERR_PTR(-EIO); + ctx = test->priv; + if (!ctx || sb != ctx->sb || !ctx->journal_inode || + ctx->journal_inode->i_ino != ino) + return ERR_PTR(-ENOENT); + + ihold(ctx->journal_inode); + return ctx->journal_inode; +} + +static void super_test_cleanup(struct super_test_ctx *ctx) +{ +#ifdef CONFIG_QUOTA + int i; +#endif + + active_super_test = NULL; + ctx->sbi.s_journal = NULL; + + if (ctx->journal_inode) { + iput(ctx->journal_inode); + ctx->journal_inode = NULL; + } + + ext4_flex_groups_free_test(&ctx->sbi); + +#ifdef CONFIG_QUOTA + for (i = 0; i < EXT4_MAXQUOTAS; i++) { + kfree(rcu_access_pointer(ctx->sbi.s_qf_names[i])); + rcu_assign_pointer(ctx->sbi.s_qf_names[i], NULL); + } +#endif + fscrypt_free_dummy_policy(&ctx->sbi.s_dummy_enc_policy); + + deactivate_super(ctx->sb); + rcu_barrier(); + + cancel_work_sync(&ctx->sbi.s_sb_upd_work); + timer_delete_sync(&ctx->sbi.s_err_report); + + if (ctx->counters_inited) { + percpu_counter_destroy(&ctx->sbi.s_freeclusters_counter); + percpu_counter_destroy(&ctx->sbi.s_dirtyclusters_counter); + percpu_counter_destroy(&ctx->sbi.s_freeinodes_counter); + } + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); +} + +KUNIT_DEFINE_ACTION_WRAPPER(super_test_cleanup_action, super_test_cleanup, + struct super_test_ctx *); + +static int super_test_init(struct kunit *test) +{ + struct super_test_ctx *ctx; + struct fs_context *fc; + struct super_block *sb; + struct ext4_sb_info *sbi; + struct inode *root_inode; + int err; + + ctx = kzalloc_obj(*ctx); + KUNIT_ASSERT_NOT_NULL(test, ctx); + test->priv = ctx; + active_super_test = test; + + ctx->bdev.bd_stats = alloc_percpu(struct disk_stats); + if (!ctx->bdev.bd_stats) { + kfree(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc bd_stats"); + } + + fc = fs_context_for_mount(&super_test_fs_type, 0); + if (IS_ERR(fc)) { + err = PTR_ERR(fc); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + sb = sget_fc(fc, NULL, set_anon_super_fc); + put_fs_context(fc); + if (IS_ERR(sb)) { + err = PTR_ERR(sb); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + ctx->sb = sb; + sbi = &ctx->sbi; + + err = percpu_counter_init(&sbi->s_freeclusters_counter, 0, GFP_KERNEL); + if (err) + goto err_sb; + err = percpu_counter_init(&sbi->s_dirtyclusters_counter, 0, GFP_KERNEL); + if (err) { + percpu_counter_destroy(&sbi->s_freeclusters_counter); + goto err_sb; + } + err = percpu_counter_init(&sbi->s_freeinodes_counter, 0, GFP_KERNEL); + if (err) { + percpu_counter_destroy(&sbi->s_dirtyclusters_counter); + percpu_counter_destroy(&sbi->s_freeclusters_counter); + goto err_sb; + } + ctx->counters_inited = true; + + sbi->s_sb = sb; + sb->s_fs_info = sbi; + sb->s_op = &super_test_sops; +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; +#endif + sb->s_flags |= SB_ACTIVE; + sb->s_blocksize = SUPER_TEST_BLK_SIZE; + sb->s_blocksize_bits = SUPER_TEST_BLK_BITS; + sb->s_maxbytes = MAX_LFS_FILESIZE; + sb->s_time_gran = 1; + sb->s_xattr = ext4_xattr_handlers; + strscpy(sb->s_id, "ext4_super_kunit", sizeof(sb->s_id)); + + inode_init_once(&ctx->bd_inode); + ctx->bd_inode.i_sb = sb; + ctx->bd_inode.i_blkbits = SUPER_TEST_BLK_BITS; + ctx->bd_inode.i_mapping = &ctx->bd_inode.i_data; + ctx->bd_inode.i_data.host = &ctx->bd_inode; + ctx->bdev_queue.limits.logical_block_size = 512; + ctx->bdev_queue.limits.dma_alignment = 511; + ctx->bdev_disk.part0 = &ctx->bdev; + ctx->bdev_disk.queue = &ctx->bdev_queue; + ctx->bdev.bd_disk = &ctx->bdev_disk; + ctx->bdev.bd_queue = &ctx->bdev_queue; + ctx->bdev.bd_mapping = &ctx->bd_inode.i_data; + bdev_clear_flag(&ctx->bdev, BD_READ_ONLY); + sb->s_bdev = &ctx->bdev; + + bgl_lock_init(&ctx->bgl); + sbi->s_blockgroup_lock = &ctx->bgl; + + sbi->s_es = &ctx->es; + ctx->es.s_magic = cpu_to_le16(EXT4_SUPER_MAGIC); + ctx->es.s_first_data_block = cpu_to_le32(SUPER_TEST_FIRST_DATA_BLK); + ctx->es.s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + ctx->es.s_creator_os = cpu_to_le32(EXT4_OS_LINUX); + ctx->es.s_inodes_count = cpu_to_le32(SUPER_TEST_TOTAL_INODES); + ctx->es.s_inodes_per_group = cpu_to_le32(SUPER_TEST_INODES_PER_GRP); + ctx->es.s_blocks_per_group = cpu_to_le32(SUPER_TEST_BLOCKS_PER_GRP); + ctx->es.s_clusters_per_group = cpu_to_le32(SUPER_TEST_BLOCKS_PER_GRP); + ctx->es.s_first_ino = cpu_to_le32(SUPER_TEST_FIRST_INO); + ctx->es.s_inode_size = cpu_to_le16(SUPER_TEST_INODE_SIZE); + ctx->es.s_min_extra_isize = cpu_to_le16(SUPER_TEST_EXTRA_ISIZE); + ctx->es.s_want_extra_isize = cpu_to_le16(SUPER_TEST_EXTRA_ISIZE); + ctx->es.s_desc_size = cpu_to_le16(EXT4_MIN_DESC_SIZE_64BIT); + ctx->es.s_reserved_gdt_blocks = cpu_to_le16(SUPER_TEST_RSV_GDT_BLKS); + ctx->es.s_errors = cpu_to_le16(EXT4_ERRORS_RO); + ctx->es.s_checksum_type = EXT4_CRC32C_CHKSUM; + generate_random_uuid(ctx->es.s_uuid); + ext4_blocks_count_set(&ctx->es, SUPER_TEST_TOTAL_BLKS); + + ext4_set_feature_sparse_super(sb); + ext4_set_feature_extents(sb); + ext4_set_feature_extra_isize(sb); + ext4_set_feature_metadata_csum(sb); + ext4_set_feature_64bit(sb); + sbi->s_csum_seed = ext4_chksum(~0, ctx->es.s_uuid, + sizeof(ctx->es.s_uuid)); + ext4_superblock_csum_set(sb); + + ctx->sb_bh.b_data = (char *)&ctx->es; + ctx->sb_bh.b_size = sizeof(ctx->es); + ctx->sb_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->sb_bh.b_count, 1); + set_buffer_uptodate(&ctx->sb_bh); + sbi->s_sbh = &ctx->sb_bh; + + sbi->s_sb_block = 1; + sbi->s_inode_size = SUPER_TEST_INODE_SIZE; + sbi->s_inodes_per_block = SUPER_TEST_INODES_PER_BLK; + sbi->s_inodes_per_group = SUPER_TEST_INODES_PER_GRP; + sbi->s_itb_per_group = SUPER_TEST_ITB_PER_GRP; + sbi->s_first_ino = SUPER_TEST_FIRST_INO; + sbi->s_want_extra_isize = SUPER_TEST_EXTRA_ISIZE; + sbi->s_blocks_per_group = SUPER_TEST_BLOCKS_PER_GRP; + sbi->s_clusters_per_group = SUPER_TEST_BLOCKS_PER_GRP; + sbi->s_cluster_ratio = 1; + sbi->s_cluster_bits = 0; + sbi->s_groups_count = SUPER_TEST_NGROUPS; + sbi->s_gdb_count = SUPER_TEST_GDB_COUNT; + sbi->s_desc_size = EXT4_MIN_DESC_SIZE_64BIT; + sbi->s_desc_per_block = SUPER_TEST_BLK_SIZE / EXT4_MIN_DESC_SIZE_64BIT; + sbi->s_desc_per_block_bits = ilog2(sbi->s_desc_per_block); + sbi->s_resuid = make_kuid(&init_user_ns, EXT4_DEF_RESUID); + sbi->s_resgid = make_kgid(&init_user_ns, EXT4_DEF_RESGID); + sbi->s_commit_interval = JBD2_DEFAULT_MAX_COMMIT_AGE * HZ; + sbi->s_min_batch_time = EXT4_DEF_MIN_BATCH_TIME; + sbi->s_max_batch_time = EXT4_DEF_MAX_BATCH_TIME; + sbi->s_inode_readahead_blks = EXT4_DEF_INODE_READAHEAD_BLKS; + sbi->s_li_wait_mult = EXT4_DEF_LI_WAIT_MULT; + sbi->s_err_report_sec = 86400; + + spin_lock_init(&sbi->s_bdev_wb_lock); + spin_lock_init(&sbi->s_error_lock); + spin_lock_init(&sbi->s_md_lock); + INIT_WORK(&sbi->s_sb_upd_work, super_test_sb_upd_work); + timer_setup(&sbi->s_err_report, super_test_err_timer, 0); + + ratelimit_state_init(&sbi->s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + + super_setup_default_groups(ctx); + + root_inode = new_inode(sb); + if (!root_inode) { + err = -ENOMEM; + goto err_counters; + } + root_inode->i_ino = EXT4_ROOT_INO; + root_inode->i_mode = S_IFDIR | 0755; + root_inode->i_flags |= S_NOQUOTA; + root_inode->i_op = &simple_dir_inode_operations; + set_nlink(root_inode, 2); + sb->s_root = d_make_root(root_inode); + if (!sb->s_root) { + err = -ENOMEM; + goto err_counters; + } + + up_write(&sb->s_umount); + + kunit_activate_static_stub(test, ext4_get_group_desc, + super_get_group_desc_stub); + kunit_activate_static_stub(test, __ext4_iget, super_iget_stub); + + err = kunit_add_action_or_reset(test, super_test_cleanup_action, ctx); + KUNIT_ASSERT_EQ(test, err, 0); + return 0; + +err_counters: + percpu_counter_destroy(&sbi->s_freeinodes_counter); + percpu_counter_destroy(&sbi->s_dirtyclusters_counter); + percpu_counter_destroy(&sbi->s_freeclusters_counter); +err_sb: + active_super_test = NULL; + deactivate_locked_super(sb); + rcu_barrier(); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + return err; +} + +static void test_feature_set_and_compatibility(struct kunit *test) +{ + struct super_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_super_block *es = &ctx->es; + __le32 orig_incompat = es->s_feature_incompat; + __le32 orig_ro_compat = es->s_feature_ro_compat; + + KUNIT_EXPECT_EQ(test, ext4_feature_set_ok(sb, 0), 1); + KUNIT_EXPECT_EQ(test, ext4_check_feature_compatibility_test(sb, es, 0), + 0); + + /* Unknown incompat flag must fail on both RW and RO */ + es->s_feature_incompat = orig_incompat | cpu_to_le32(0x80000000U); + KUNIT_EXPECT_EQ(test, ext4_feature_set_ok(sb, 0), 0); + KUNIT_EXPECT_EQ(test, ext4_feature_set_ok(sb, 1), 0); + KUNIT_EXPECT_EQ(test, ext4_check_feature_compatibility_test(sb, es, 0), + -EINVAL); + es->s_feature_incompat = orig_incompat; + + /* Unknown ro_compat flag fails RW, succeeds RO */ + es->s_feature_ro_compat = orig_ro_compat | cpu_to_le32(0x80000000U); + KUNIT_EXPECT_EQ(test, ext4_feature_set_ok(sb, 0), 0); + KUNIT_EXPECT_EQ(test, ext4_feature_set_ok(sb, 1), 1); + es->s_feature_ro_compat = orig_ro_compat; + + /* RO_COMPAT_READONLY forces SB_RDONLY on RW mount request */ + ext4_set_feature_readonly(sb); + sb->s_flags &= ~SB_RDONLY; + KUNIT_EXPECT_EQ(test, ext4_feature_set_ok(sb, 0), 1); + KUNIT_EXPECT_TRUE(test, sb_rdonly(sb)); + sb->s_flags &= ~SB_RDONLY; + es->s_feature_ro_compat = orig_ro_compat; + + /* bigalloc requires extents and s_first_data_block == 0 on RW */ + ext4_set_feature_bigalloc(sb); + ext4_clear_feature_extents(sb); + es->s_first_data_block = 0; + KUNIT_EXPECT_EQ(test, ext4_feature_set_ok(sb, 0), 0); + KUNIT_EXPECT_EQ(test, ext4_feature_set_ok(sb, 1), 1); + + ext4_set_feature_extents(sb); + es->s_first_data_block = cpu_to_le32(1); + KUNIT_EXPECT_EQ(test, ext4_feature_set_ok(sb, 0), 0); + es->s_first_data_block = 0; + KUNIT_EXPECT_EQ(test, ext4_feature_set_ok(sb, 0), 1); + es->s_first_data_block = cpu_to_le32(SUPER_TEST_FIRST_DATA_BLK); + es->s_feature_ro_compat = orig_ro_compat; + es->s_feature_incompat = orig_incompat; + + /* Hurd creator OS sets HURD_COMPAT and rejects 64bit and ea_inode */ + es->s_creator_os = cpu_to_le32(EXT4_OS_HURD); + KUNIT_EXPECT_EQ(test, ext4_check_feature_compatibility_test(sb, es, 0), + -EINVAL); + KUNIT_EXPECT_NE(test, test_opt2(sb, HURD_COMPAT), 0); + + ext4_clear_feature_64bit(sb); + ext4_set_feature_ea_inode(sb); + KUNIT_EXPECT_EQ(test, ext4_check_feature_compatibility_test(sb, es, 0), + -EINVAL); + + ext4_clear_feature_ea_inode(sb); + KUNIT_EXPECT_EQ(test, ext4_check_feature_compatibility_test(sb, es, 0), + 0); + clear_opt2(sb, HURD_COMPAT); + es->s_creator_os = cpu_to_le32(EXT4_OS_LINUX); + es->s_feature_incompat = orig_incompat; + +#ifdef CONFIG_FS_DAX + /* DAX_ALWAYS rejects inline_data and non-DAX block devices */ + set_opt(sb, DAX_ALWAYS); + ext4_set_feature_inline_data(sb); + set_bit(EXT4_FLAGS_BDEV_IS_DAX, &ctx->sbi.s_ext4_flags); + KUNIT_EXPECT_EQ(test, ext4_check_feature_compatibility_test(sb, es, 0), + -EINVAL); + + ext4_clear_feature_inline_data(sb); + clear_bit(EXT4_FLAGS_BDEV_IS_DAX, &ctx->sbi.s_ext4_flags); + KUNIT_EXPECT_EQ(test, ext4_check_feature_compatibility_test(sb, es, 0), + -EINVAL); + + set_bit(EXT4_FLAGS_BDEV_IS_DAX, &ctx->sbi.s_ext4_flags); + KUNIT_EXPECT_EQ(test, ext4_check_feature_compatibility_test(sb, es, 0), + 0); + clear_bit(EXT4_FLAGS_BDEV_IS_DAX, &ctx->sbi.s_ext4_flags); + clear_opt(sb, DAX_ALWAYS); +#endif + + /* Non-zero s_encryption_level with encrypt feature is rejected */ + ext4_set_feature_encrypt(sb); + es->s_encryption_level = 1; + KUNIT_EXPECT_EQ(test, ext4_check_feature_compatibility_test(sb, es, 0), + -EINVAL); + es->s_encryption_level = 0; + KUNIT_EXPECT_EQ(test, ext4_check_feature_compatibility_test(sb, es, 0), + 0); + ext4_clear_feature_encrypt(sb); +} + +static void test_inode_info_init(struct kunit *test) +{ + struct super_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + struct ext4_super_block *es = &ctx->es; + + /* EXT4_GOOD_OLD_REV forces 128-byte inodes and first_ino == 11 */ + es->s_rev_level = cpu_to_le32(EXT4_GOOD_OLD_REV); + es->s_inode_size = cpu_to_le16(512); + es->s_first_ino = cpu_to_le32(99); + KUNIT_EXPECT_EQ(test, ext4_inode_info_init_test(sb, es), 0); + KUNIT_EXPECT_EQ(test, sbi->s_inode_size, EXT4_GOOD_OLD_INODE_SIZE); + KUNIT_EXPECT_EQ(test, sbi->s_first_ino, + (unsigned int)EXT4_GOOD_OLD_FIRST_INO); + + /* EXT4_DYNAMIC_REV validation of s_first_ino and s_inode_size */ + es->s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + es->s_first_ino = cpu_to_le32(10); + es->s_inode_size = cpu_to_le16(256); + KUNIT_EXPECT_EQ(test, ext4_inode_info_init_test(sb, es), -EINVAL); + + es->s_first_ino = cpu_to_le32(11); + es->s_inode_size = cpu_to_le16(64); + KUNIT_EXPECT_EQ(test, ext4_inode_info_init_test(sb, es), -EINVAL); + + es->s_inode_size = cpu_to_le16(192); + KUNIT_EXPECT_EQ(test, ext4_inode_info_init_test(sb, es), -EINVAL); + + es->s_inode_size = cpu_to_le16(2048); + KUNIT_EXPECT_EQ(test, ext4_inode_info_init_test(sb, es), -EINVAL); + + /* 128-byte inode uses 1-second timestamp granularity */ + es->s_inode_size = cpu_to_le16(128); + KUNIT_EXPECT_EQ(test, ext4_inode_info_init_test(sb, es), 0); + KUNIT_EXPECT_EQ(test, sb->s_time_gran, (u32)NSEC_PER_SEC); + KUNIT_EXPECT_EQ(test, sb->s_time_max, EXT4_NON_EXTRA_TIMESTAMP_MAX); + KUNIT_EXPECT_EQ(test, sb->s_time_min, EXT4_TIMESTAMP_MIN); + + /* 256-byte inode enables nanosecond extra timestamps and extra_isize */ + es->s_inode_size = cpu_to_le16(256); + es->s_want_extra_isize = cpu_to_le16(200); + KUNIT_EXPECT_EQ(test, ext4_inode_info_init_test(sb, es), -EINVAL); + + es->s_want_extra_isize = cpu_to_le16(32); + es->s_min_extra_isize = cpu_to_le16(200); + KUNIT_EXPECT_EQ(test, ext4_inode_info_init_test(sb, es), -EINVAL); + + es->s_min_extra_isize = cpu_to_le16(64); + KUNIT_EXPECT_EQ(test, ext4_inode_info_init_test(sb, es), 0); + KUNIT_EXPECT_EQ(test, sb->s_time_gran, 1U); + KUNIT_EXPECT_EQ(test, sb->s_time_max, EXT4_EXTRA_TIMESTAMP_MAX); + KUNIT_EXPECT_EQ(test, sbi->s_want_extra_isize, 64U); +} + +static void test_block_group_meta_and_clustersize(struct kunit *test) +{ + struct super_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + struct ext4_super_block *es = &ctx->es; + + /* Without 64bit, descriptor size is forced to 32 bytes */ + ext4_clear_feature_64bit(sb); + es->s_desc_size = cpu_to_le16(128); + es->s_state = cpu_to_le16(EXT4_VALID_FS | EXT4_FC_REPLAY); + KUNIT_EXPECT_EQ(test, ext4_block_group_meta_init_test(sb, 1), 0); + KUNIT_EXPECT_EQ(test, sbi->s_desc_size, + (unsigned long)EXT4_MIN_DESC_SIZE); + KUNIT_EXPECT_EQ(test, sbi->s_mount_state, + (unsigned short)EXT4_VALID_FS); + + /* With 64bit, s_desc_size must be a power of 2 in [64, 1024] */ + ext4_set_feature_64bit(sb); + es->s_desc_size = cpu_to_le16(32); + KUNIT_EXPECT_EQ(test, ext4_block_group_meta_init_test(sb, 1), -EINVAL); + es->s_desc_size = cpu_to_le16(96); + KUNIT_EXPECT_EQ(test, ext4_block_group_meta_init_test(sb, 1), -EINVAL); + es->s_desc_size = cpu_to_le16(2048); + KUNIT_EXPECT_EQ(test, ext4_block_group_meta_init_test(sb, 1), -EINVAL); + + es->s_desc_size = cpu_to_le16(64); + es->s_blocks_per_group = 0; + KUNIT_EXPECT_EQ(test, ext4_block_group_meta_init_test(sb, 1), -EINVAL); + es->s_blocks_per_group = cpu_to_le32(SUPER_TEST_BLOCKS_PER_GRP); + + /* Invalid s_inodes_per_group bounds and alignment */ + es->s_inodes_per_group = cpu_to_le32(2); + KUNIT_EXPECT_EQ(test, ext4_block_group_meta_init_test(sb, 1), -EINVAL); + es->s_inodes_per_group = cpu_to_le32(SUPER_TEST_BLK_SIZE * 8 + 8); + KUNIT_EXPECT_EQ(test, ext4_block_group_meta_init_test(sb, 1), -EINVAL); + es->s_inodes_per_group = cpu_to_le32(36); + KUNIT_EXPECT_EQ(test, ext4_block_group_meta_init_test(sb, 1), -EINVAL); + + es->s_inodes_per_group = cpu_to_le32(SUPER_TEST_INODES_PER_GRP); + KUNIT_EXPECT_EQ(test, ext4_block_group_meta_init_test(sb, 1), 0); + KUNIT_EXPECT_EQ(test, sbi->s_itb_per_group, + (unsigned long)SUPER_TEST_ITB_PER_GRP); + KUNIT_EXPECT_EQ(test, sbi->s_desc_per_block, 16UL); + + /* Non-bigalloc clustersize checks */ + es->s_log_block_size = 0; + es->s_log_cluster_size = cpu_to_le32(1); + KUNIT_EXPECT_EQ(test, ext4_handle_clustersize_test(sb), -EINVAL); + + es->s_log_cluster_size = 0; + sbi->s_blocks_per_group = SUPER_TEST_BLK_SIZE * 8 + 8; + KUNIT_EXPECT_EQ(test, ext4_handle_clustersize_test(sb), -EINVAL); + + sbi->s_blocks_per_group = SUPER_TEST_BLK_SIZE * 8; + es->s_clusters_per_group = cpu_to_le32(SUPER_TEST_BLK_SIZE * 8 - 4); + KUNIT_EXPECT_EQ(test, ext4_handle_clustersize_test(sb), -EINVAL); + + es->s_clusters_per_group = cpu_to_le32(SUPER_TEST_BLK_SIZE * 4); + KUNIT_EXPECT_EQ(test, ext4_handle_clustersize_test(sb), -EINVAL); + + clear_opt2(sb, STD_GROUP_SIZE); + es->s_clusters_per_group = cpu_to_le32(SUPER_TEST_BLK_SIZE * 8); + KUNIT_EXPECT_EQ(test, ext4_handle_clustersize_test(sb), 0); + KUNIT_EXPECT_EQ(test, sbi->s_cluster_ratio, 1); + KUNIT_EXPECT_EQ(test, sbi->s_cluster_bits, 0); + KUNIT_EXPECT_NE(test, test_opt2(sb, STD_GROUP_SIZE), 0); + + /* Bigalloc clustersize checks: 4K blocks, 16K clusters (ratio 4) */ + ext4_set_feature_bigalloc(sb); + sb->s_blocksize = 4096; + sb->s_blocksize_bits = 12; + es->s_log_block_size = cpu_to_le32(2); + es->s_log_cluster_size = cpu_to_le32(1); + KUNIT_EXPECT_EQ(test, ext4_handle_clustersize_test(sb), -EINVAL); + + es->s_log_cluster_size = cpu_to_le32(4); + sbi->s_blocks_per_group = 4096; + es->s_clusters_per_group = cpu_to_le32(512); + KUNIT_EXPECT_EQ(test, ext4_handle_clustersize_test(sb), -EINVAL); + + es->s_clusters_per_group = cpu_to_le32(1024); + KUNIT_EXPECT_EQ(test, ext4_handle_clustersize_test(sb), 0); + KUNIT_EXPECT_EQ(test, sbi->s_cluster_bits, 2); + KUNIT_EXPECT_EQ(test, sbi->s_cluster_ratio, 4); +} + +static void test_hash_info_init(struct kunit *test) +{ + struct super_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + struct ext4_super_block *es = &ctx->es; + + es->s_def_hash_version = DX_HASH_LAST + 1; + KUNIT_EXPECT_EQ(test, ext4_hash_info_init_test(sb), -EINVAL); + + es->s_def_hash_version = DX_HASH_SIPHASH; + KUNIT_EXPECT_EQ(test, ext4_hash_info_init_test(sb), -EINVAL); + + es->s_def_hash_version = DX_HASH_HALF_MD4; + es->s_hash_seed[0] = cpu_to_le32(0x11223344U); + es->s_hash_seed[1] = cpu_to_le32(0x55667788U); + es->s_hash_seed[2] = cpu_to_le32(0x99aabbccU); + es->s_hash_seed[3] = cpu_to_le32(0xddeeff00U); + ext4_set_feature_dir_index(sb); + es->s_flags = cpu_to_le32(EXT2_FLAGS_UNSIGNED_HASH); + sbi->s_hash_unsigned = 0; + + KUNIT_EXPECT_EQ(test, ext4_hash_info_init_test(sb), 0); + KUNIT_EXPECT_EQ(test, sbi->s_def_hash_version, + (unsigned char)DX_HASH_HALF_MD4); + KUNIT_EXPECT_EQ(test, sbi->s_hash_seed[0], 0x11223344U); + KUNIT_EXPECT_EQ(test, sbi->s_hash_seed[1], 0x55667788U); + KUNIT_EXPECT_EQ(test, sbi->s_hash_seed[2], 0x99aabbccU); + KUNIT_EXPECT_EQ(test, sbi->s_hash_seed[3], 0xddeeff00U); + KUNIT_EXPECT_EQ(test, sbi->s_hash_unsigned, 3); + + /* Unflagged dir_index superblock gets native hash signedness flag */ + es->s_flags = 0; + sbi->s_hash_unsigned = 0; + KUNIT_EXPECT_EQ(test, ext4_hash_info_init_test(sb), 0); + KUNIT_EXPECT_NE(test, le32_to_cpu(es->s_flags) & + (EXT2_FLAGS_SIGNED_HASH | EXT2_FLAGS_UNSIGNED_HASH), + 0U); +} + +static void test_check_geometry(struct kunit *test) +{ + struct super_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + struct ext4_super_block *es = &ctx->es; + + /* Excessive s_reserved_gdt_blocks (> blocksize / 4) */ + es->s_reserved_gdt_blocks = cpu_to_le16(SUPER_TEST_BLK_SIZE / 4 + 1); + KUNIT_EXPECT_EQ(test, ext4_check_geometry_test(sb, es), -EINVAL); + es->s_reserved_gdt_blocks = cpu_to_le16(SUPER_TEST_RSV_GDT_BLKS); + + /* Filesystem block count exceeding device capacity */ + ctx->bdev.bd_nr_sectors = 1000; + KUNIT_EXPECT_EQ(test, ext4_check_geometry_test(sb, es), -EINVAL); + ctx->bdev.bd_nr_sectors = 0; + + /* s_first_data_block >= blocks_count */ + es->s_first_data_block = cpu_to_le32(SUPER_TEST_TOTAL_BLKS); + KUNIT_EXPECT_EQ(test, ext4_check_geometry_test(sb, es), -EINVAL); + + /* s_first_data_block == 0 on 1K blocksize without bigalloc */ + es->s_first_data_block = 0; + es->s_log_block_size = 0; + sbi->s_cluster_ratio = 1; + KUNIT_EXPECT_EQ(test, ext4_check_geometry_test(sb, es), -EINVAL); + es->s_first_data_block = cpu_to_le32(SUPER_TEST_FIRST_DATA_BLK); + + /* Inode count mismatch against groups_count * inodes_per_group */ + es->s_inodes_count = cpu_to_le32(SUPER_TEST_TOTAL_INODES + 1); + KUNIT_EXPECT_EQ(test, ext4_check_geometry_test(sb, es), -EINVAL); + + /* Valid 5-group geometry with partial final group */ + ext4_blocks_count_set(es, SUPER_TEST_FIRST_DATA_BLK + + 4 * SUPER_TEST_BLOCKS_PER_GRP + 200); + es->s_inodes_count = cpu_to_le32(5 * SUPER_TEST_INODES_PER_GRP); + KUNIT_EXPECT_EQ(test, ext4_check_geometry_test(sb, es), 0); + KUNIT_EXPECT_EQ(test, sbi->s_groups_count, 5U); +} + +static void test_descriptor_loc(struct kunit *test) +{ + struct super_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_super_block *es = &ctx->es; + + /* Non-meta_bg places descriptor blocks linearly after superblock */ + ext4_clear_feature_meta_bg(sb); + KUNIT_EXPECT_EQ(test, ext4_descriptor_loc_test(sb, 1, 0), 2ULL); + KUNIT_EXPECT_EQ(test, ext4_descriptor_loc_test(sb, 1, 2), 4ULL); + + /* + * With meta_bg and s_desc_per_block == 16 on 1K blocks: + * - nr == 0 -> bg 0 (has_super): block 2 for both first_data_block + * 1 and 0 (compensated) + * - nr == 1 -> bg 16 (no backup super under sparse_super): first + * block of group 16 + * - nr == 2 -> bg 32 ( still no backup super; 32 is power of 2): + * first block of group 32 + */ + ext4_set_feature_meta_bg(sb); + es->s_first_meta_bg = 0; + es->s_first_data_block = cpu_to_le32(1); + KUNIT_EXPECT_EQ(test, ext4_descriptor_loc_test(sb, 1, 0), 2ULL); + KUNIT_EXPECT_EQ(test, ext4_descriptor_loc_test(sb, 1, 1), + ext4_group_first_block_no(sb, 16)); + + es->s_first_data_block = 0; + KUNIT_EXPECT_EQ(test, ext4_descriptor_loc_test(sb, 0, 0), 2ULL); + + /* Hybrid s_first_meta_bg == 2 uses linear layout for nr < 2 */ + es->s_first_data_block = cpu_to_le32(1); + es->s_first_meta_bg = cpu_to_le32(2); + KUNIT_EXPECT_EQ(test, ext4_descriptor_loc_test(sb, 1, 0), 2ULL); + KUNIT_EXPECT_EQ(test, ext4_descriptor_loc_test(sb, 1, 1), 3ULL); + KUNIT_EXPECT_EQ(test, ext4_descriptor_loc_test(sb, 1, 2), + ext4_group_first_block_no(sb, 32)); +} + +static void test_superblock_and_group_desc_csum(struct kunit *test) +{ + struct super_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + struct ext4_super_block *es = &ctx->es; + struct ext4_group_desc gdp = {}; + + /* Superblock checksum type, verification, and seed derivation */ + es->s_checksum_type = 99; + KUNIT_EXPECT_EQ(test, ext4_init_metadata_csum_test(sb, es), -EINVAL); + + es->s_checksum_type = EXT4_CRC32C_CHKSUM; + ext4_superblock_csum_set(sb); + es->s_checksum ^= cpu_to_le32(1); + KUNIT_EXPECT_EQ(test, ext4_init_metadata_csum_test(sb, es), -EFSBADCRC); + + ext4_clear_feature_csum_seed(sb); + ext4_superblock_csum_set(sb); + sbi->s_csum_seed = 0; + KUNIT_EXPECT_EQ(test, ext4_init_metadata_csum_test(sb, es), 0); + KUNIT_EXPECT_EQ(test, sbi->s_csum_seed, + ext4_chksum(~0, es->s_uuid, sizeof(es->s_uuid))); + + ext4_set_feature_csum_seed(sb); + es->s_checksum_seed = cpu_to_le32(0xdeadbeefU); + ext4_superblock_csum_set(sb); + KUNIT_EXPECT_EQ(test, ext4_init_metadata_csum_test(sb, es), 0); + KUNIT_EXPECT_EQ(test, sbi->s_csum_seed, 0xdeadbeefU); + + /* 32-byte vs 64-byte free_group_clusters accessor/mutator */ + sbi->s_desc_size = EXT4_MIN_DESC_SIZE; + ext4_free_group_clusters_set(sb, &gdp, 0x12345678U); + KUNIT_EXPECT_EQ(test, ext4_free_group_clusters(sb, &gdp), 0x5678U); + + sbi->s_desc_size = EXT4_MIN_DESC_SIZE_64BIT; + ext4_free_group_clusters_set(sb, &gdp, 0x12345678U); + KUNIT_EXPECT_EQ(test, ext4_free_group_clusters(sb, &gdp), 0x12345678U); + + /* metadata_csum (CRC32C) group descriptor verification */ + ext4_group_desc_csum_set(sb, 3, &gdp); + KUNIT_EXPECT_EQ(test, ext4_group_desc_csum_verify(sb, 3, &gdp), 1); + KUNIT_EXPECT_EQ(test, ext4_group_desc_csum_verify(sb, 2, &gdp), 0); + gdp.bg_block_bitmap_hi = cpu_to_le32(1); + KUNIT_EXPECT_EQ(test, ext4_group_desc_csum_verify(sb, 3, &gdp), 0); + + /* Legacy gdt_csum (CRC16) verification across 64-byte descriptor */ + ext4_clear_feature_metadata_csum(sb); + ext4_set_feature_gdt_csum(sb); + ext4_group_desc_csum_set(sb, 1, &gdp); + KUNIT_EXPECT_EQ(test, ext4_group_desc_csum_verify(sb, 1, &gdp), 1); + gdp.bg_free_blocks_count_hi ^= cpu_to_le16(1); + KUNIT_EXPECT_EQ(test, ext4_group_desc_csum_verify(sb, 1, &gdp), 0); + + /* No checksum features enabled -> verify always succeeds */ + ext4_clear_feature_gdt_csum(sb); + KUNIT_EXPECT_EQ(test, ext4_group_desc_csum_verify(sb, 1, &gdp), 1); +} + +static void test_check_descriptors_and_flex_info(struct kunit *test) +{ + struct super_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + struct flex_groups *fg0, *fg1; + ext4_group_t first_not_zeroed = 0; + + ctx->gdps[2].bg_flags = 0; + ext4_group_desc_csum_set(sb, 2, &ctx->gdps[2]); + KUNIT_EXPECT_EQ(test, + ext4_check_descriptors_test(sb, 1, &first_not_zeroed), + 1); + KUNIT_EXPECT_EQ(test, first_not_zeroed, 2U); + + /* Block bitmap overlapping superblock fails RW, tolerated on RO */ + ext4_block_bitmap_set(sb, &ctx->gdps[0], 1); + ext4_group_desc_csum_set(sb, 0, &ctx->gdps[0]); + KUNIT_EXPECT_EQ(test, ext4_check_descriptors_test(sb, 1, NULL), 0); + sb->s_flags |= SB_RDONLY; + KUNIT_EXPECT_EQ(test, ext4_check_descriptors_test(sb, 1, NULL), 1); + sb->s_flags &= ~SB_RDONLY; + + /* Inode table overlapping GDT block (block 2) fails RW */ + super_setup_default_groups(ctx); + ext4_inode_table_set(sb, &ctx->gdps[0], 2); + ext4_group_desc_csum_set(sb, 0, &ctx->gdps[0]); + KUNIT_EXPECT_EQ(test, ext4_check_descriptors_test(sb, 1, NULL), 0); + + /* Out-of-group bitmap fails without flex_bg, succeeds with flex_bg */ + super_setup_default_groups(ctx); + ext4_block_bitmap_set(sb, &ctx->gdps[1], 20); + ext4_group_desc_csum_set(sb, 1, &ctx->gdps[1]); + sb->s_flags |= SB_RDONLY; + KUNIT_EXPECT_EQ(test, ext4_check_descriptors_test(sb, 1, NULL), 0); + sb->s_flags &= ~SB_RDONLY; + + ext4_set_feature_flex_bg(sb); + KUNIT_EXPECT_EQ(test, ext4_check_descriptors_test(sb, 1, NULL), 1); + + /* Bad group descriptor checksum fails RW, tolerated on RO */ + ctx->gdps[1].bg_checksum ^= cpu_to_le16(0xffff); + KUNIT_EXPECT_EQ(test, ext4_check_descriptors_test(sb, 1, NULL), 0); + sb->s_flags |= SB_RDONLY; + KUNIT_EXPECT_EQ(test, ext4_check_descriptors_test(sb, 1, NULL), 1); + sb->s_flags &= ~SB_RDONLY; + + /* Flex-bg allocation and per-flex-group counter aggregation */ + super_setup_default_groups(ctx); + ctx->es.s_log_groups_per_flex = 32; + KUNIT_EXPECT_EQ(test, ext4_fill_flex_info_test(sb), 1); + KUNIT_EXPECT_EQ(test, sbi->s_log_groups_per_flex, 0U); + + ext4_free_group_clusters_set(sb, &ctx->gdps[0], 100); + ext4_free_inodes_set(sb, &ctx->gdps[0], 10); + ext4_used_dirs_set(sb, &ctx->gdps[0], 2); + ext4_free_group_clusters_set(sb, &ctx->gdps[1], 150); + ext4_free_inodes_set(sb, &ctx->gdps[1], 12); + ext4_used_dirs_set(sb, &ctx->gdps[1], 3); + ext4_free_group_clusters_set(sb, &ctx->gdps[2], 200); + ext4_free_inodes_set(sb, &ctx->gdps[2], 14); + ext4_used_dirs_set(sb, &ctx->gdps[2], 1); + ext4_free_group_clusters_set(sb, &ctx->gdps[3], 250); + ext4_free_inodes_set(sb, &ctx->gdps[3], 16); + ext4_used_dirs_set(sb, &ctx->gdps[3], 4); + + ctx->es.s_log_groups_per_flex = 1; + KUNIT_EXPECT_EQ(test, ext4_fill_flex_info_test(sb), 1); + KUNIT_EXPECT_EQ(test, sbi->s_flex_groups_allocated, 2); + + fg0 = sbi_array_rcu_deref(sbi, s_flex_groups, 0); + fg1 = sbi_array_rcu_deref(sbi, s_flex_groups, 1); + KUNIT_EXPECT_EQ(test, atomic64_read(&fg0->free_clusters), 250LL); + KUNIT_EXPECT_EQ(test, atomic_read(&fg0->free_inodes), 22); + KUNIT_EXPECT_EQ(test, atomic_read(&fg0->used_dirs), 5); + KUNIT_EXPECT_EQ(test, atomic64_read(&fg1->free_clusters), 450LL); + KUNIT_EXPECT_EQ(test, atomic_read(&fg1->free_inodes), 30); + KUNIT_EXPECT_EQ(test, atomic_read(&fg1->used_dirs), 5); + + /* Growing the flex_bg array preserves populated entries */ + KUNIT_EXPECT_EQ(test, ext4_alloc_flex_bg_array(sb, 8), 0); + KUNIT_EXPECT_EQ(test, sbi->s_flex_groups_allocated, 4); + fg0 = sbi_array_rcu_deref(sbi, s_flex_groups, 0); + KUNIT_EXPECT_EQ(test, atomic64_read(&fg0->free_clusters), 250LL); +} + +static void test_max_sizes_stripe_and_resv_clusters(struct kunit *test) +{ + struct super_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + + /* Without huge_file, 2^32 - 1 512B sectors caps max extent file size */ + KUNIT_EXPECT_EQ(test, ext4_max_size_test(10, 0), + (((1LL << 32) - 1) >> 1) << 10); + KUNIT_EXPECT_EQ(test, ext4_max_size_test(12, 0), + (((1LL << 32) - 1) >> 3) << 12); + + /* With huge_file, 32-bit ee_block caps max size at (2^32 - 1) blocks */ + KUNIT_EXPECT_EQ(test, ext4_max_size_test(10, 1), + ((1LL << 32) - 1) << 10); + KUNIT_EXPECT_EQ(test, ext4_max_size_test(12, 1), + min_t(loff_t, ((1LL << 32) - 1) << 12, + MAX_LFS_FILESIZE)); + + /* Indirect bitmap max size is strictly smaller with !huge_file on 4K */ + KUNIT_EXPECT_LT(test, ext4_max_bitmap_size_test(12, 0), + ext4_max_bitmap_size_test(12, 1)); + KUNIT_EXPECT_EQ(test, ext4_max_bitmap_size_test(10, 1), + (12LL + 256 + 65536 + 16777216) << 10); + + /* Stripe priority: mount s_stripe -> raid_stripe_width -> stride */ + sbi->s_blocks_per_group = 1024; + sbi->s_stripe = 64; + ctx->es.s_raid_stripe_width = cpu_to_le32(128); + ctx->es.s_raid_stride = cpu_to_le16(16); + KUNIT_EXPECT_EQ(test, ext4_get_stripe_size_test(sbi), 64UL); + + sbi->s_stripe = 2048; + KUNIT_EXPECT_EQ(test, ext4_get_stripe_size_test(sbi), 128UL); + + ctx->es.s_raid_stripe_width = cpu_to_le32(2048); + KUNIT_EXPECT_EQ(test, ext4_get_stripe_size_test(sbi), 16UL); + + ctx->es.s_raid_stride = cpu_to_le16(1); + KUNIT_EXPECT_EQ(test, ext4_get_stripe_size_test(sbi), 0UL); + + /* Reserved clusters: skipped without extents, 2% up to 4096 cap */ + atomic64_set(&sbi->s_resv_clusters, 7); + ext4_clear_feature_extents(sb); + ext4_blocks_count_set(&ctx->es, 5000); + ext4_set_resv_clusters_test(sb); + KUNIT_EXPECT_EQ(test, atomic64_read(&sbi->s_resv_clusters), 7LL); + + ext4_set_feature_extents(sb); + ext4_set_resv_clusters_test(sb); + KUNIT_EXPECT_EQ(test, atomic64_read(&sbi->s_resv_clusters), 100LL); + + ext4_blocks_count_set(&ctx->es, 500000); + ext4_set_resv_clusters_test(sb); + KUNIT_EXPECT_EQ(test, atomic64_read(&sbi->s_resv_clusters), 4096LL); +} + +static void test_overhead_and_statfs(struct kunit *test) +{ + struct super_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + struct kstatfs st = {}; + char *buf; + + buf = kunit_kzalloc(test, SUPER_TEST_BLK_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, buf); + + /* + * Non-bigalloc per-group overhead: + * - groups 0, 1, 3: 1 (super) + 1 (gdb) + 2 (rsv_gdt) + 8 (itb) + 2 + * = 14 + * - group 2 (sparse_super): 0 + 0 + 0 + 8 (itb) + 2 = 10 + * Total with s_first_data_block == 1: 1 + 14 + 14 + 10 + 14 = 53 + */ + KUNIT_EXPECT_EQ(test, ext4_count_overhead_test(sb, 0, buf), 14); + KUNIT_EXPECT_EQ(test, ext4_count_overhead_test(sb, 2, buf), 10); + KUNIT_EXPECT_EQ(test, ext4_calculate_overhead(sb), 0); + KUNIT_EXPECT_EQ(test, sbi->s_overhead, 53UL); + + /* Loaded internal journal adds j_total_len clusters */ + ctx->mock_journal.j_total_len = 64; + sbi->s_journal = &ctx->mock_journal; + KUNIT_EXPECT_EQ(test, ext4_calculate_overhead(sb), 0); + KUNIT_EXPECT_EQ(test, sbi->s_overhead, 117UL); + sbi->s_journal = NULL; + + /* Unloaded internal journal falls back to ext4_get_journal_inode() */ + ctx->journal_inode = new_inode(sb); + KUNIT_ASSERT_NOT_NULL(test, ctx->journal_inode); + ctx->journal_inode->i_ino = EXT4_JOURNAL_INO; + ctx->journal_inode->i_mode = S_IFREG | 0600; + ctx->journal_inode->i_flags |= S_NOQUOTA; + set_nlink(ctx->journal_inode, 1); + i_size_write(ctx->journal_inode, 32 * SUPER_TEST_BLK_SIZE); + ext4_set_feature_journal(sb); + ctx->es.s_journal_inum = cpu_to_le32(EXT4_JOURNAL_INO); + KUNIT_EXPECT_EQ(test, ext4_calculate_overhead(sb), 0); + KUNIT_EXPECT_EQ(test, sbi->s_overhead, 85UL); + ext4_clear_feature_journal(sb); + ctx->es.s_journal_inum = 0; + + /* Bigalloc deduplicates metadata blocks sharing the same cluster */ + ext4_set_feature_bigalloc(sb); + ctx->es.s_first_data_block = 0; + sbi->s_cluster_bits = 2; + sbi->s_cluster_ratio = 4; + sbi->s_clusters_per_group = SUPER_TEST_BLOCKS_PER_GRP / 4; + sbi->s_groups_count = 1; + ext4_block_bitmap_set(sb, &ctx->gdps[0], 2); + ext4_inode_bitmap_set(sb, &ctx->gdps[0], 3); + ext4_inode_table_set(sb, &ctx->gdps[0], 4); + memset(buf, 0, SUPER_TEST_BLK_SIZE); + /* Cluster 0 holds super+gdb+bbitmap+ibitmap; clusters 1..2 hold itb */ + KUNIT_EXPECT_EQ(test, ext4_count_overhead_test(sb, 0, buf), 3); + + /* Restore 1:1 geometry and verify ext4_statfs accounting & clamping */ + ext4_clear_feature_bigalloc(sb); + ctx->es.s_first_data_block = cpu_to_le32(SUPER_TEST_FIRST_DATA_BLK); + sbi->s_cluster_bits = 0; + sbi->s_cluster_ratio = 1; + sbi->s_clusters_per_group = SUPER_TEST_BLOCKS_PER_GRP; + sbi->s_groups_count = SUPER_TEST_NGROUPS; + sbi->s_overhead = 53; + ext4_r_blocks_count_set(&ctx->es, 100); + atomic64_set(&sbi->s_resv_clusters, 20); + percpu_counter_set(&sbi->s_freeclusters_counter, 500); + percpu_counter_set(&sbi->s_dirtyclusters_counter, 50); + percpu_counter_set(&sbi->s_freeinodes_counter, 90); + + KUNIT_EXPECT_EQ(test, ext4_statfs_test(sb->s_root, &st), 0); + KUNIT_EXPECT_EQ(test, st.f_type, (long)EXT4_SUPER_MAGIC); + KUNIT_EXPECT_EQ(test, st.f_blocks, (u64)(SUPER_TEST_TOTAL_BLKS - 53)); + KUNIT_EXPECT_EQ(test, st.f_bfree, 450ULL); + KUNIT_EXPECT_EQ(test, st.f_bavail, 330ULL); + KUNIT_EXPECT_EQ(test, st.f_files, (u64)SUPER_TEST_TOTAL_INODES); + KUNIT_EXPECT_EQ(test, st.f_ffree, 90ULL); + KUNIT_EXPECT_EQ(test, st.f_namelen, (long)EXT4_NAME_LEN); + + /* MINIX_DF omits s_overhead; dirty > free clamps f_bfree/f_bavail */ + set_opt(sb, MINIX_DF); + percpu_counter_set(&sbi->s_freeclusters_counter, 30); + percpu_counter_set(&sbi->s_dirtyclusters_counter, 80); + KUNIT_EXPECT_EQ(test, ext4_statfs_test(sb->s_root, &st), 0); + KUNIT_EXPECT_EQ(test, st.f_blocks, (u64)SUPER_TEST_TOTAL_BLKS); + KUNIT_EXPECT_EQ(test, st.f_bfree, 0ULL); + KUNIT_EXPECT_EQ(test, st.f_bavail, 0ULL); +} + +static void test_mount_options_and_show_options(struct kunit *test) +{ + struct super_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + struct ext4_super_block *es = &ctx->es; + unsigned int ioprio = 0; + struct seq_file seq = {}; + char *out; + + out = kunit_kzalloc(test, 1024, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, out); + + /* Superblock default mount options */ + sbi->s_mount_opt = 0; + sbi->s_mount_opt2 = 0; + es->s_default_mount_opts = cpu_to_le32(EXT4_DEFM_DISCARD | + EXT4_DEFM_NOBARRIER | + EXT4_DEFM_JMODE_WBACK); + es->s_errors = cpu_to_le16(EXT4_ERRORS_CONTINUE); + ext4_set_feature_fast_commit(sb); + ext4_set_def_opts_test(sb, es); + + KUNIT_EXPECT_NE(test, test_opt(sb, DISCARD), 0); + KUNIT_EXPECT_EQ(test, test_opt(sb, BARRIER), 0); + KUNIT_EXPECT_EQ(test, test_opt(sb, DATA_FLAGS), + EXT4_MOUNT_WRITEBACK_DATA); + KUNIT_EXPECT_NE(test, test_opt(sb, ERRORS_CONT), 0); + KUNIT_EXPECT_NE(test, test_opt(sb, JOURNAL_CHECKSUM), 0); + KUNIT_EXPECT_NE(test, test_opt2(sb, JOURNAL_FAST_COMMIT), 0); + sbi->s_def_mount_opt = sbi->s_mount_opt; + sbi->s_def_mount_opt2 = sbi->s_mount_opt2; + + /* Valid option string parsing and application */ + KUNIT_EXPECT_EQ(test, + ext4_parse_and_apply_options_test(sb, + "nodelalloc,minixdf,commit=15,stripe=32,errors=panic", + false), + 0); + KUNIT_EXPECT_EQ(test, + ext4_parse_and_apply_options_test(sb, + "resuid=1000,resgid=2000,inode_readahead_blks=64", + false), + 0); + KUNIT_EXPECT_EQ(test, + ext4_parse_and_apply_options_test(sb, + "max_dir_size_kb=512", false), + 0); + KUNIT_EXPECT_EQ(test, test_opt(sb, DELALLOC), 0); + KUNIT_EXPECT_NE(test, test_opt(sb, MINIX_DF), 0); + KUNIT_EXPECT_EQ(test, sbi->s_commit_interval, 15UL * HZ); + KUNIT_EXPECT_EQ(test, sbi->s_stripe, 32UL); + KUNIT_EXPECT_EQ(test, from_kuid(&init_user_ns, sbi->s_resuid), 1000U); + KUNIT_EXPECT_EQ(test, from_kgid(&init_user_ns, sbi->s_resgid), 2000U); + KUNIT_EXPECT_EQ(test, sbi->s_inode_readahead_blks, 64U); + KUNIT_EXPECT_EQ(test, sbi->s_max_dir_size_kb, 512U); + KUNIT_EXPECT_NE(test, test_opt(sb, ERRORS_PANIC), 0); + + /* Invalid parameter values and consistency rejections */ + KUNIT_EXPECT_EQ(test, + ext4_parse_and_apply_options_test(sb, + "inode_readahead_blks=3", false), + -EINVAL); + KUNIT_EXPECT_EQ(test, + ext4_parse_and_apply_options_test(sb, + "mb_optimize_scan=2", false), + -EINVAL); + KUNIT_EXPECT_EQ(test, + ext4_parse_and_apply_options_test(sb, + "debug_want_extra_isize=200", false), + -EINVAL); + KUNIT_EXPECT_EQ(test, + ext4_parse_and_apply_options_test(sb, + "debug_want_extra_isize=5", false), + -EINVAL); +#ifdef CONFIG_QUOTA + KUNIT_EXPECT_EQ(test, + ext4_parse_and_apply_options_test(sb, + "prjquota", false), + -EINVAL); + KUNIT_EXPECT_EQ(test, + ext4_parse_and_apply_options_test(sb, + "usrjquota=aquota.user", false), + -EINVAL); +#endif + KUNIT_EXPECT_EQ(test, + ext4_parse_and_apply_options_test(sb, + "test_dummy_encryption", false), + -EINVAL); + + /* Remount restrictions on data= mode changes */ + sbi->s_journal = &ctx->mock_journal; + KUNIT_EXPECT_EQ(test, + ext4_parse_and_apply_options_test(sb, + "data=ordered", true), + -EINVAL); +#ifdef CONFIG_FS_DAX + KUNIT_EXPECT_EQ(test, + ext4_parse_and_apply_options_test(sb, + "dax=never", false), + 0); + KUNIT_EXPECT_EQ(test, + ext4_parse_and_apply_options_test(sb, + "dax=always", true), + -EINVAL); +#else + KUNIT_EXPECT_EQ(test, + ext4_parse_and_apply_options_test(sb, + "dax=never", false), + -EINVAL); +#endif + sbi->s_journal = NULL; + + /* On-disk es->s_mount_opts parsing and malformed fallback */ + strscpy_pad(es->s_mount_opts, "nodiscard,commit=25,journal_ioprio=5"); + KUNIT_EXPECT_EQ(test, + ext4_parse_sb_mount_options_test(sb, NULL, &ioprio), + 0); + KUNIT_EXPECT_EQ(test, test_opt(sb, DISCARD), 0); + KUNIT_EXPECT_EQ(test, sbi->s_commit_interval, 25UL * HZ); + KUNIT_EXPECT_EQ(test, IOPRIO_PRIO_DATA(ioprio), 5UL); + + strscpy_pad(es->s_mount_opts, "nonexistent_opt=1"); + KUNIT_EXPECT_EQ(test, + ext4_parse_sb_mount_options_test(sb, NULL, NULL), 0); + + /* _ext4_show_options and ext4_seq_options_show formatting */ + seq.buf = out; + seq.size = 1023; + seq.private = sb; + KUNIT_EXPECT_EQ(test, ext4_show_options_test(&seq, sb, 0), 0); + out[seq.count] = '\0'; + KUNIT_EXPECT_NOT_NULL(test, strstr(out, ",minixdf")); + KUNIT_EXPECT_NOT_NULL(test, strstr(out, ",commit=25")); + KUNIT_EXPECT_NOT_NULL(test, strstr(out, ",stripe=32")); + KUNIT_EXPECT_NOT_NULL(test, strstr(out, ",errors=panic")); + + memset(out, 0, 1024); + seq.count = 0; + KUNIT_EXPECT_EQ(test, ext4_seq_options_show(&seq, NULL), 0); + out[seq.count] = '\0'; + KUNIT_EXPECT_TRUE(test, str_has_prefix(out, "rw\n")); + KUNIT_EXPECT_NOT_NULL(test, strstr(out, "\nresuid=1000\n")); +} + +static void test_error_recording_and_update_super(struct kunit *test) +{ + struct super_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + struct ext4_super_block *es = &ctx->es; + __le32 saved_wtime; + + KUNIT_EXPECT_EQ(test, ext4_errno_to_code_test(EIO), EXT4_ERR_EIO); + KUNIT_EXPECT_EQ(test, ext4_errno_to_code_test(ENOMEM), EXT4_ERR_ENOMEM); + KUNIT_EXPECT_EQ(test, ext4_errno_to_code_test(EFSCORRUPTED), + EXT4_ERR_EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, ext4_errno_to_code_test(ENOSPC), EXT4_ERR_ENOSPC); + KUNIT_EXPECT_EQ(test, ext4_errno_to_code_test(999), EXT4_ERR_UNKNOWN); + + /* First error defaults 0 -> EFSCORRUPTED; second updates last only */ + ext4_save_error_info_test(sb, 0, 17, 1024, "first_fn", 111); + ext4_save_error_info_test(sb, EIO, 29, 2048, "second_fn", 222); + + KUNIT_EXPECT_EQ(test, sbi->s_add_error_count, 2U); + KUNIT_EXPECT_EQ(test, sbi->s_first_error_code, EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, sbi->s_last_error_code, EIO); + + sbi->s_kbytes_written = 100; + percpu_counter_set(&sbi->s_freeclusters_counter, 321); + percpu_counter_set(&sbi->s_freeinodes_counter, 45); + + ext4_update_super_test(sb); + + KUNIT_EXPECT_EQ(test, sbi->s_add_error_count, 0U); + KUNIT_EXPECT_NE(test, le16_to_cpu(es->s_state) & EXT4_ERROR_FS, 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(es->s_error_count), 2U); + KUNIT_EXPECT_EQ(test, es->s_first_error_errcode, + (u8)EXT4_ERR_EFSCORRUPTED); + KUNIT_EXPECT_EQ(test, le32_to_cpu(es->s_first_error_ino), 17U); + KUNIT_EXPECT_EQ(test, le64_to_cpu(es->s_first_error_block), 1024ULL); + KUNIT_EXPECT_EQ(test, le32_to_cpu(es->s_first_error_line), 111U); + KUNIT_EXPECT_STREQ(test, (char *)es->s_first_error_func, "first_fn"); + + KUNIT_EXPECT_EQ(test, es->s_last_error_errcode, (u8)EXT4_ERR_EIO); + KUNIT_EXPECT_EQ(test, le32_to_cpu(es->s_last_error_ino), 29U); + KUNIT_EXPECT_EQ(test, le64_to_cpu(es->s_last_error_block), 2048ULL); + KUNIT_EXPECT_EQ(test, le32_to_cpu(es->s_last_error_line), 222U); + KUNIT_EXPECT_STREQ(test, (char *)es->s_last_error_func, "second_fn"); + + KUNIT_EXPECT_EQ(test, ext4_free_blocks_count(es), 321ULL); + KUNIT_EXPECT_EQ(test, le32_to_cpu(es->s_free_inodes_count), 45U); + KUNIT_EXPECT_EQ(test, le64_to_cpu(es->s_kbytes_written), 100ULL); + KUNIT_EXPECT_EQ(test, le32_to_cpu(es->s_checksum), + le32_to_cpu(ext4_superblock_csum(es))); + + /* Read-only superblock update must not touch s_wtime */ + es->s_wtime = cpu_to_le32(123456U); + saved_wtime = es->s_wtime; + sb->s_flags |= SB_RDONLY; + ext4_update_super_test(sb); + KUNIT_EXPECT_EQ(test, le32_to_cpu(es->s_wtime), + le32_to_cpu(saved_wtime)); +} + +static struct kunit_case ext4_super_test_cases[] = { + KUNIT_CASE(test_feature_set_and_compatibility), + KUNIT_CASE(test_inode_info_init), + KUNIT_CASE(test_block_group_meta_and_clustersize), + KUNIT_CASE(test_hash_info_init), + KUNIT_CASE(test_check_geometry), + KUNIT_CASE(test_descriptor_loc), + KUNIT_CASE(test_superblock_and_group_desc_csum), + KUNIT_CASE(test_check_descriptors_and_flex_info), + KUNIT_CASE(test_max_sizes_stripe_and_resv_clusters), + KUNIT_CASE(test_overhead_and_statfs), + KUNIT_CASE(test_mount_options_and_show_options), + KUNIT_CASE(test_error_recording_and_update_super), + {} +}; + +static struct kunit_suite ext4_super_test_suite = { + .name = "ext4_super_test", + .init = super_test_init, + .test_cases = ext4_super_test_cases, +}; + +kunit_test_suites(&ext4_super_test_suite); + +MODULE_DESCRIPTION("KUnit tests for ext4 superblock validation and options"); +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/super.c b/fs/ext4/super.c index 9cae52471dee95..880f664d6c04b0 100644 --- a/fs/ext4/super.c +++ b/fs/ext4/super.c @@ -49,6 +49,7 @@ #include #include #include +#include #include "ext4.h" #include "ext4_extents.h" /* Needed for trace points definition */ @@ -195,6 +196,9 @@ static inline void __ext4_read_bh(struct buffer_head *bh, blk_opf_t op_flags, void ext4_read_bh_nowait(struct buffer_head *bh, blk_opf_t op_flags, bio_end_io_t end_io, bool simu_fail) { + KUNIT_STATIC_STUB_REDIRECT(ext4_read_bh_nowait, bh, op_flags, + end_io, simu_fail); + BUG_ON(!buffer_locked(bh)); if (ext4_buffer_uptodate(bh)) { @@ -203,10 +207,14 @@ void ext4_read_bh_nowait(struct buffer_head *bh, blk_opf_t op_flags, } __ext4_read_bh(bh, op_flags, end_io, simu_fail); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_read_bh_nowait); int ext4_read_bh(struct buffer_head *bh, blk_opf_t op_flags, bio_end_io_t end_io, bool simu_fail) { + KUNIT_STATIC_STUB_REDIRECT(ext4_read_bh, bh, op_flags, + end_io, simu_fail); + BUG_ON(!buffer_locked(bh)); if (ext4_buffer_uptodate(bh)) { @@ -221,9 +229,12 @@ int ext4_read_bh(struct buffer_head *bh, blk_opf_t op_flags, return 0; return -EIO; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_read_bh); int ext4_read_bh_lock(struct buffer_head *bh, blk_opf_t op_flags, bool wait) { + KUNIT_STATIC_STUB_REDIRECT(ext4_read_bh_lock, bh, op_flags, wait); + lock_buffer(bh); if (!wait) { ext4_read_bh_nowait(bh, op_flags, NULL, false); @@ -231,6 +242,7 @@ int ext4_read_bh_lock(struct buffer_head *bh, blk_opf_t op_flags, bool wait) } return ext4_read_bh(bh, op_flags, NULL, false); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_read_bh_lock); /* * This works like __bread_gfp() except it uses ERR_PTR for error @@ -262,7 +274,11 @@ static struct buffer_head *__ext4_sb_bread_gfp(struct super_block *sb, struct buffer_head *ext4_sb_bread(struct super_block *sb, sector_t block, blk_opf_t op_flags) { - gfp_t gfp = mapping_gfp_constraint(sb->s_bdev->bd_mapping, + gfp_t gfp; + + KUNIT_STATIC_STUB_REDIRECT(ext4_sb_bread, sb, block, op_flags); + + gfp = mapping_gfp_constraint(sb->s_bdev->bd_mapping, ~__GFP_FS) | __GFP_MOVABLE; return __ext4_sb_bread_gfp(sb, block, op_flags, gfp); @@ -280,16 +296,24 @@ struct buffer_head *ext4_sb_bread_unmovable(struct super_block *sb, struct buffer_head *ext4_sb_bread_nofail(struct super_block *sb, sector_t block) { - gfp_t gfp = mapping_gfp_constraint(sb->s_bdev->bd_mapping, + gfp_t gfp; + + KUNIT_STATIC_STUB_REDIRECT(ext4_sb_bread_nofail, sb, block); + + gfp = mapping_gfp_constraint(sb->s_bdev->bd_mapping, ~__GFP_FS) | __GFP_MOVABLE | __GFP_NOFAIL; return __ext4_sb_bread_gfp(sb, block, 0, gfp); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sb_bread_nofail); void ext4_sb_breadahead_unmovable(struct super_block *sb, sector_t block) { - struct buffer_head *bh = bdev_getblk(sb->s_bdev, block, - sb->s_blocksize, GFP_NOWAIT); + struct buffer_head *bh; + + KUNIT_STATIC_STUB_REDIRECT(ext4_sb_breadahead_unmovable, sb, block); + + bh = bdev_getblk(sb->s_bdev, block, sb->s_blocksize, GFP_NOWAIT); if (likely(bh)) { if (trylock_buffer(bh)) @@ -297,6 +321,7 @@ void ext4_sb_breadahead_unmovable(struct super_block *sb, sector_t block) brelse(bh); } } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sb_breadahead_unmovable); static int ext4_verify_csum_type(struct super_block *sb, struct ext4_super_block *es) @@ -316,6 +341,7 @@ __le32 ext4_superblock_csum(struct ext4_super_block *es) return cpu_to_le32(csum); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_superblock_csum); static int ext4_superblock_csum_verify(struct super_block *sb, struct ext4_super_block *es) @@ -335,6 +361,7 @@ void ext4_superblock_csum_set(struct super_block *sb) es->s_checksum = ext4_superblock_csum(es); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_superblock_csum_set); ext4_fsblk_t ext4_block_bitmap(struct super_block *sb, struct ext4_group_desc *bg) @@ -343,6 +370,7 @@ ext4_fsblk_t ext4_block_bitmap(struct super_block *sb, (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ? (ext4_fsblk_t)le32_to_cpu(bg->bg_block_bitmap_hi) << 32 : 0); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_block_bitmap); ext4_fsblk_t ext4_inode_bitmap(struct super_block *sb, struct ext4_group_desc *bg) @@ -351,6 +379,7 @@ ext4_fsblk_t ext4_inode_bitmap(struct super_block *sb, (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ? (ext4_fsblk_t)le32_to_cpu(bg->bg_inode_bitmap_hi) << 32 : 0); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_bitmap); ext4_fsblk_t ext4_inode_table(struct super_block *sb, struct ext4_group_desc *bg) @@ -359,6 +388,7 @@ ext4_fsblk_t ext4_inode_table(struct super_block *sb, (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ? (ext4_fsblk_t)le32_to_cpu(bg->bg_inode_table_hi) << 32 : 0); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_table); __u32 ext4_free_group_clusters(struct super_block *sb, struct ext4_group_desc *bg) @@ -367,6 +397,7 @@ __u32 ext4_free_group_clusters(struct super_block *sb, (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ? (__u32)le16_to_cpu(bg->bg_free_blocks_count_hi) << 16 : 0); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_free_group_clusters); __u32 ext4_free_inodes_count(struct super_block *sb, struct ext4_group_desc *bg) @@ -375,6 +406,7 @@ __u32 ext4_free_inodes_count(struct super_block *sb, (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ? (__u32)le16_to_cpu(READ_ONCE(bg->bg_free_inodes_count_hi)) << 16 : 0); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_free_inodes_count); __u32 ext4_used_dirs_count(struct super_block *sb, struct ext4_group_desc *bg) @@ -383,6 +415,7 @@ __u32 ext4_used_dirs_count(struct super_block *sb, (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ? (__u32)le16_to_cpu(bg->bg_used_dirs_count_hi) << 16 : 0); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_used_dirs_count); __u32 ext4_itable_unused_count(struct super_block *sb, struct ext4_group_desc *bg) @@ -391,6 +424,7 @@ __u32 ext4_itable_unused_count(struct super_block *sb, (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ? (__u32)le16_to_cpu(bg->bg_itable_unused_hi) << 16 : 0); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_itable_unused_count); void ext4_block_bitmap_set(struct super_block *sb, struct ext4_group_desc *bg, ext4_fsblk_t blk) @@ -399,6 +433,7 @@ void ext4_block_bitmap_set(struct super_block *sb, if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT) bg->bg_block_bitmap_hi = cpu_to_le32(blk >> 32); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_block_bitmap_set); void ext4_inode_bitmap_set(struct super_block *sb, struct ext4_group_desc *bg, ext4_fsblk_t blk) @@ -407,6 +442,7 @@ void ext4_inode_bitmap_set(struct super_block *sb, if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT) bg->bg_inode_bitmap_hi = cpu_to_le32(blk >> 32); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_bitmap_set); void ext4_inode_table_set(struct super_block *sb, struct ext4_group_desc *bg, ext4_fsblk_t blk) @@ -415,6 +451,7 @@ void ext4_inode_table_set(struct super_block *sb, if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT) bg->bg_inode_table_hi = cpu_to_le32(blk >> 32); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_table_set); void ext4_free_group_clusters_set(struct super_block *sb, struct ext4_group_desc *bg, __u32 count) @@ -423,6 +460,7 @@ void ext4_free_group_clusters_set(struct super_block *sb, if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT) bg->bg_free_blocks_count_hi = cpu_to_le16(count >> 16); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_free_group_clusters_set); void ext4_free_inodes_set(struct super_block *sb, struct ext4_group_desc *bg, __u32 count) @@ -431,6 +469,7 @@ void ext4_free_inodes_set(struct super_block *sb, if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT) WRITE_ONCE(bg->bg_free_inodes_count_hi, cpu_to_le16(count >> 16)); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_free_inodes_set); void ext4_used_dirs_set(struct super_block *sb, struct ext4_group_desc *bg, __u32 count) @@ -439,6 +478,7 @@ void ext4_used_dirs_set(struct super_block *sb, if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT) bg->bg_used_dirs_count_hi = cpu_to_le16(count >> 16); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_used_dirs_set); void ext4_itable_unused_set(struct super_block *sb, struct ext4_group_desc *bg, __u32 count) @@ -447,6 +487,7 @@ void ext4_itable_unused_set(struct super_block *sb, if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT) bg->bg_itable_unused_hi = cpu_to_le16(count >> 16); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_itable_unused_set); static void __ext4_update_tstamp(__le32 *lo, __u8 *hi, time64_t now) { @@ -1145,6 +1186,7 @@ void ext4_mark_group_bitmap_corrupted(struct super_block *sb, } } } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mark_group_bitmap_corrupted); void ext4_update_dynamic_rev(struct super_block *sb) { @@ -1170,6 +1212,7 @@ void ext4_update_dynamic_rev(struct super_block *sb) * can leave it up to e2fsck to clean up any inconsistencies there. */ } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_update_dynamic_rev); static inline struct inode *orphan_list_entry(struct list_head *l) { @@ -1603,6 +1646,7 @@ void ext4_clear_inode(struct inode *inode) } fscrypt_put_encryption_info(inode); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_clear_inode); static struct inode *ext4_nfs_get_inode(struct super_block *sb, u64 ino, u32 generation) @@ -3161,6 +3205,7 @@ int ext4_seq_options_show(struct seq_file *seq, void *offset) seq_putc(seq, '\n'); return rc; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_seq_options_show); static int ext4_setup_super(struct super_block *sb, struct ext4_super_block *es, int read_only) @@ -3266,6 +3311,7 @@ int ext4_alloc_flex_bg_array(struct super_block *sb, ext4_group_t ngroup) ext4_kvfree_array_rcu(old_groups); return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_alloc_flex_bg_array); static int ext4_fill_flex_info(struct super_block *sb) { @@ -3354,6 +3400,7 @@ int ext4_group_desc_csum_verify(struct super_block *sb, __u32 block_group, return 1; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_group_desc_csum_verify); void ext4_group_desc_csum_set(struct super_block *sb, __u32 block_group, struct ext4_group_desc *gdp) @@ -3362,6 +3409,7 @@ void ext4_group_desc_csum_set(struct super_block *sb, __u32 block_group, return; gdp->bg_checksum = ext4_group_desc_csum(sb, block_group, gdp); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_group_desc_csum_set); /* Called at mount-time, super-block is locked */ static int ext4_check_descriptors(struct super_block *sb, @@ -3737,6 +3785,7 @@ int ext4_feature_set_ok(struct super_block *sb, int readonly) #endif /* CONFIG_QUOTA */ return 1; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_feature_set_ok); /* * This function is called once a day by default if we have errors logged @@ -3835,7 +3884,8 @@ static int ext4_run_li_request(struct ext4_li_request *elr) if (!ret) { start_time = ktime_get_ns(); ret = ext4_init_inode_table(sb, group, - elr->lr_timeout ? 0 : 1); + !elr->lr_timeout && + test_opt(sb, BARRIER)); trace_ext4_lazy_itable_init(sb, group); if (elr->lr_timeout == 0) { elr->lr_timeout = nsecs_to_jiffies((ktime_get_ns() - start_time) * @@ -4347,6 +4397,7 @@ int ext4_calculate_overhead(struct super_block *sb) kvfree(buf); return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_calculate_overhead); static void ext4_set_resv_clusters(struct super_block *sb) { @@ -5819,6 +5870,12 @@ failed_mount8: __maybe_unused failed_mount7: ext4_unregister_li_request(sb); failed_mount6: + /* + * We can have a running transaction from orphan replay or quota + * setup. Commit it so that discard work after commit runs before + * we shutdown mballoc. + */ + ext4_force_commit(sb); ext4_mb_release(sb); ext4_flex_groups_free(sbi); failed_mount5: @@ -5847,6 +5904,7 @@ failed_mount8: __maybe_unused failed_mount3a: /* Drain deferred EA inode iputs from journal replay */ flush_delayed_work(&sbi->s_ea_inode_work); + ext4_fc_replay_cleanup(sb); ext4_es_unregister_shrinker(sbi); ext4_es_destroy_stats(sbi); failed_mount3: @@ -6010,7 +6068,9 @@ static int ext4_journal_bmap(journal_t *journal, sector_t *block) ext4_msg(journal->j_inode->i_sb, KERN_CRIT, "journal bmap failed: block %llu ret %d\n", *block, ret); - jbd2_journal_abort(journal, ret ? ret : -EFSCORRUPTED); + if (!ret) + ret = -EFSCORRUPTED; + jbd2_journal_abort(journal, ret); return ret; } *block = map.m_pblk; @@ -7690,3 +7750,221 @@ MODULE_DESCRIPTION("Fourth Extended Filesystem"); MODULE_LICENSE("GPL"); module_init(ext4_init_fs) module_exit(ext4_exit_fs) + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sb_bread); + +int ext4_errno_to_code_test(int err) +{ + return ext4_errno_to_code(err); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_errno_to_code_test); + +void ext4_save_error_info_test(struct super_block *sb, int error, + __u32 ino, __u64 block, + const char *func, unsigned int line) +{ + save_error_info(sb, error, ino, block, func, line); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_save_error_info_test); + +void ext4_update_super_test(struct super_block *sb) +{ + ext4_update_super(sb); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_update_super_test); + +int ext4_check_descriptors_test(struct super_block *sb, + ext4_fsblk_t sb_block, + ext4_group_t *first_not_zeroed) +{ + return ext4_check_descriptors(sb, sb_block, first_not_zeroed); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_check_descriptors_test); + +loff_t ext4_max_size_test(int blkbits, int has_huge_files) +{ + return ext4_max_size(blkbits, has_huge_files); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_max_size_test); + +loff_t ext4_max_bitmap_size_test(int bits, int has_huge_files) +{ + return ext4_max_bitmap_size(bits, has_huge_files); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_max_bitmap_size_test); + +ext4_fsblk_t ext4_descriptor_loc_test(struct super_block *sb, + ext4_fsblk_t logical_sb_block, int nr) +{ + return descriptor_loc(sb, logical_sb_block, nr); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_descriptor_loc_test); + +unsigned long ext4_get_stripe_size_test(struct ext4_sb_info *sbi) +{ + return ext4_get_stripe_size(sbi); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_stripe_size_test); + +int ext4_count_overhead_test(struct super_block *sb, ext4_group_t grp, + char *buf) +{ + return count_overhead(sb, grp, buf); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_count_overhead_test); + +void ext4_set_resv_clusters_test(struct super_block *sb) +{ + ext4_set_resv_clusters(sb); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_set_resv_clusters_test); + +void ext4_set_def_opts_test(struct super_block *sb, + struct ext4_super_block *es) +{ + ext4_set_def_opts(sb, es); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_set_def_opts_test); + +int ext4_handle_clustersize_test(struct super_block *sb) +{ + return ext4_handle_clustersize(sb); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_handle_clustersize_test); + +int ext4_inode_info_init_test(struct super_block *sb, + struct ext4_super_block *es) +{ + return ext4_inode_info_init(sb, es); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_info_init_test); + +int ext4_init_metadata_csum_test(struct super_block *sb, + struct ext4_super_block *es) +{ + return ext4_init_metadata_csum(sb, es); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_init_metadata_csum_test); + +int ext4_check_feature_compatibility_test(struct super_block *sb, + struct ext4_super_block *es, + int silent) +{ + return ext4_check_feature_compatibility(sb, es, silent); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_check_feature_compatibility_test); + +int ext4_check_geometry_test(struct super_block *sb, + struct ext4_super_block *es) +{ + return ext4_check_geometry(sb, es); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_check_geometry_test); + +int ext4_hash_info_init_test(struct super_block *sb) +{ + return ext4_hash_info_init(sb); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_hash_info_init_test); + +int ext4_block_group_meta_init_test(struct super_block *sb, int silent) +{ + return ext4_block_group_meta_init(sb, silent); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_block_group_meta_init_test); + +int ext4_fill_flex_info_test(struct super_block *sb) +{ + return ext4_fill_flex_info(sb); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fill_flex_info_test); + +void ext4_flex_groups_free_test(struct ext4_sb_info *sbi) +{ + ext4_flex_groups_free(sbi); + rcu_assign_pointer(sbi->s_flex_groups, NULL); + sbi->s_flex_groups_allocated = 0; +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_flex_groups_free_test); + +int ext4_show_options_test(struct seq_file *seq, struct super_block *sb, + int nodefs) +{ + return _ext4_show_options(seq, sb, nodefs); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_show_options_test); + +int ext4_statfs_test(struct dentry *dentry, struct kstatfs *buf) +{ + return ext4_statfs(dentry, buf); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_statfs_test); + +int ext4_parse_and_apply_options_test(struct super_block *sb, + const char *options, bool is_remount) +{ + struct ext4_fs_context *ctx; + struct fs_context *fc; + char *opts_copy = NULL; + int ret; + + if (options) { + opts_copy = kstrdup(options, GFP_KERNEL); + if (!opts_copy) + return -ENOMEM; + } + + fc = kzalloc_obj(*fc); + if (!fc) { + kfree(opts_copy); + return -ENOMEM; + } + + ctx = kzalloc_obj(*ctx); + if (!ctx) { + kfree(fc); + kfree(opts_copy); + return -ENOMEM; + } + + fc->fs_private = ctx; + fc->s_fs_info = EXT4_SB(sb); + fc->purpose = is_remount ? FS_CONTEXT_FOR_RECONFIGURE : + FS_CONTEXT_FOR_MOUNT; + + ret = parse_options(fc, opts_copy); + if (ret == 0) { + down_write(&sb->s_umount); + ret = ext4_check_opt_consistency(fc, sb); + if (ret == 0) + ext4_apply_options(fc, sb); + up_write(&sb->s_umount); + } + + kfree(opts_copy); + ext4_fc_free(fc); + kfree(fc); + return ret; +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_parse_and_apply_options_test); + +int ext4_parse_sb_mount_options_test(struct super_block *sb, + unsigned long *journal_devnum, + unsigned int *journal_ioprio) +{ + struct ext4_fs_context m_ctx = {}; + int ret; + + down_write(&sb->s_umount); + ret = parse_apply_sb_mount_options(sb, &m_ctx); + up_write(&sb->s_umount); + + if (journal_devnum) + *journal_devnum = m_ctx.journal_devnum; + if (journal_ioprio) + *journal_ioprio = m_ctx.journal_ioprio; + return ret; +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_parse_sb_mount_options_test); +#endif diff --git a/fs/ext4/sysfs-test.c b/fs/ext4/sysfs-test.c new file mode 100644 index 00000000000000..eca33ff625087e --- /dev/null +++ b/fs/ext4/sysfs-test.c @@ -0,0 +1,679 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for fs/ext4/sysfs.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_jbd2.h" +#include "xattr.h" + +#define SYSFS_TEST_BLK_SIZE 4096U +#define SYSFS_TEST_BLK_BITS 12U +#define SYSFS_TEST_TOTAL_BLKS 4096U +#define SYSFS_TEST_CLUSTERS_PER_GRP 256U + +struct sysfs_test_ctx { + struct super_block *sb; + struct ext4_sb_info sbi; + struct ext4_super_block es; + struct blockgroup_lock bgl; + struct gendisk bdev_disk; + struct block_device bdev; + struct request_queue bdev_queue; + struct inode bd_inode; + struct inode buddy_inode; + struct buffer_head sb_bh; + journal_t mock_journal; + bool counters_inited; +}; + +static struct inode *sysfs_test_alloc_inode(struct super_block *sb) +{ + struct ext4_inode_info *ei; + + ei = kzalloc_obj(*ei); + if (!ei) + return NULL; + + init_rwsem(&ei->i_data_sem); + inode_init_once(&ei->vfs_inode); + inode_set_iversion(&ei->vfs_inode, 1); + ei->i_prealloc_node = RB_ROOT; + rwlock_init(&ei->i_prealloc_lock); + ext4_es_init_tree(&ei->i_es_tree); + rwlock_init(&ei->i_es_lock); + INIT_LIST_HEAD(&ei->i_es_list); + spin_lock_init(&ei->i_raw_lock); + spin_lock_init(&ei->i_block_reservation_lock); + ext4_init_pending_tree(&ei->i_pending_tree); + init_rwsem(&ei->xattr_sem); + INIT_LIST_HEAD(&ei->i_rsv_conversion_list); + spin_lock_init(&ei->i_completed_io_lock); + INIT_LIST_HEAD(&ei->i_orphan); + ext4_fc_init_inode(&ei->vfs_inode); + spin_lock_init(&ei->i_fc_lock); + ei->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID); + ei->i_extra_isize = 32; + ei->i_last_alloc_group = ~0U; + + return &ei->vfs_inode; +} + +static void sysfs_test_free_inode(struct inode *inode) +{ + kfree(EXT4_I(inode)); +} + +static void sysfs_test_evict_inode(struct inode *inode) +{ + truncate_inode_pages_final(&inode->i_data); + clear_inode(inode); +} + +#ifdef CONFIG_QUOTA +static struct dquot __rcu **sysfs_test_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} +#endif + +static const struct super_operations sysfs_test_sops = { + .alloc_inode = sysfs_test_alloc_inode, + .free_inode = sysfs_test_free_inode, + .evict_inode = sysfs_test_evict_inode, +#ifdef CONFIG_QUOTA + .get_dquots = sysfs_test_get_dquots, +#endif +}; + +static void sysfs_test_sb_upd_work(struct work_struct *work) +{ +} + +static void sysfs_test_err_timer(struct timer_list *t) +{ +} + +static int sysfs_test_init_fs_context(struct fs_context *fc) +{ + return 0; +} + +static struct file_system_type sysfs_test_fs_type = { + .name = "ext4_sysfs_kunit", + .init_fs_context = sysfs_test_init_fs_context, + .kill_sb = kill_anon_super, +}; + +static void sysfs_test_cleanup(struct sysfs_test_ctx *ctx) +{ + ctx->sbi.s_journal = NULL; + + cancel_work_sync(&ctx->sbi.s_sb_upd_work); + timer_delete_sync(&ctx->sbi.s_err_report); + + deactivate_super(ctx->sb); + rcu_barrier(); + + if (ctx->counters_inited) { + percpu_counter_destroy(&ctx->sbi.s_dirtyclusters_counter); + percpu_counter_destroy(&ctx->sbi.s_sra_exceeded_retry_limit); + } + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); +} + +KUNIT_DEFINE_ACTION_WRAPPER(sysfs_test_cleanup_action, sysfs_test_cleanup, + struct sysfs_test_ctx *); + +static int sysfs_test_init(struct kunit *test) +{ + struct sysfs_test_ctx *ctx; + struct fs_context *fc; + struct super_block *sb; + struct ext4_sb_info *sbi; + struct inode *root_inode; + int err; + + ctx = kzalloc_obj(*ctx); + KUNIT_ASSERT_NOT_NULL(test, ctx); + test->priv = ctx; + + ctx->bdev.bd_stats = alloc_percpu(struct disk_stats); + if (!ctx->bdev.bd_stats) { + kfree(ctx); + KUNIT_FAIL_AND_ABORT(test, "failed to alloc bd_stats"); + } + + fc = fs_context_for_mount(&sysfs_test_fs_type, 0); + if (IS_ERR(fc)) { + err = PTR_ERR(fc); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + sb = sget_fc(fc, NULL, set_anon_super_fc); + put_fs_context(fc); + if (IS_ERR(sb)) { + err = PTR_ERR(sb); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + } + ctx->sb = sb; + sbi = &ctx->sbi; + + err = percpu_counter_init(&sbi->s_dirtyclusters_counter, 0, GFP_KERNEL); + if (err) + goto err_sb; + err = percpu_counter_init(&sbi->s_sra_exceeded_retry_limit, 0, + GFP_KERNEL); + if (err) { + percpu_counter_destroy(&sbi->s_dirtyclusters_counter); + goto err_sb; + } + ctx->counters_inited = true; + + sbi->s_sb = sb; + sb->s_fs_info = sbi; + sb->s_op = &sysfs_test_sops; +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; +#endif + sb->s_flags |= SB_ACTIVE; + sb->s_blocksize = SYSFS_TEST_BLK_SIZE; + sb->s_blocksize_bits = SYSFS_TEST_BLK_BITS; + strscpy(sb->s_id, "ext4_sysfs_kunit", sizeof(sb->s_id)); + + inode_init_once(&ctx->bd_inode); + ctx->bd_inode.i_sb = sb; + ctx->bd_inode.i_blkbits = SYSFS_TEST_BLK_BITS; + ctx->bd_inode.i_mapping = &ctx->bd_inode.i_data; + ctx->bd_inode.i_data.host = &ctx->bd_inode; + ctx->bdev_disk.part0 = &ctx->bdev; + ctx->bdev_disk.queue = &ctx->bdev_queue; + ctx->bdev.bd_disk = &ctx->bdev_disk; + ctx->bdev.bd_queue = &ctx->bdev_queue; + ctx->bdev.bd_mapping = &ctx->bd_inode.i_data; + bdev_clear_flag(&ctx->bdev, BD_READ_ONLY); + sb->s_bdev = &ctx->bdev; + + inode_init_once(&ctx->buddy_inode); + ctx->buddy_inode.i_sb = sb; + sbi->s_buddy_cache = &ctx->buddy_inode; + + bgl_lock_init(&ctx->bgl); + sbi->s_blockgroup_lock = &ctx->bgl; + + sbi->s_es = &ctx->es; + ctx->es.s_magic = cpu_to_le16(EXT4_SUPER_MAGIC); + ext4_blocks_count_set(&ctx->es, SYSFS_TEST_TOTAL_BLKS); + + ctx->sb_bh.b_data = (char *)&ctx->es; + ctx->sb_bh.b_size = sizeof(ctx->es); + ctx->sb_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->sb_bh.b_count, 1); + set_buffer_uptodate(&ctx->sb_bh); + sbi->s_sbh = &ctx->sb_bh; + + sbi->s_cluster_bits = 2; + sbi->s_cluster_ratio = 4; + sbi->s_clusters_per_group = SYSFS_TEST_CLUSTERS_PER_GRP; + set_opt(sb, ERRORS_CONT); + + mutex_init(&sbi->s_error_notify_mutex); + spin_lock_init(&sbi->s_error_lock); + spin_lock_init(&sbi->s_md_lock); + INIT_WORK(&sbi->s_sb_upd_work, sysfs_test_sb_upd_work); + timer_setup(&sbi->s_err_report, sysfs_test_err_timer, 0); + + ratelimit_state_init(&sbi->s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + + root_inode = new_inode(sb); + if (!root_inode) { + err = -ENOMEM; + goto err_counters; + } + root_inode->i_ino = EXT4_ROOT_INO; + root_inode->i_mode = S_IFDIR | 0755; + root_inode->i_flags |= S_NOQUOTA; + root_inode->i_op = &simple_dir_inode_operations; + set_nlink(root_inode, 2); + sb->s_root = d_make_root(root_inode); + if (!sb->s_root) { + err = -ENOMEM; + goto err_counters; + } + + up_write(&sb->s_umount); + + err = kunit_add_action_or_reset(test, sysfs_test_cleanup_action, ctx); + KUNIT_ASSERT_EQ(test, err, 0); + return 0; + +err_counters: + percpu_counter_destroy(&sbi->s_sra_exceeded_retry_limit); + percpu_counter_destroy(&sbi->s_dirtyclusters_counter); +err_sb: + deactivate_locked_super(sb); + rcu_barrier(); + free_percpu(ctx->bdev.bd_stats); + kfree(ctx); + KUNIT_ASSERT_EQ(test, err, 0); + return err; +} + +static void test_generic_pointer_attrs(struct kunit *test) +{ + struct sysfs_test_ctx *ctx = test->priv; + struct ext4_sb_info *sbi = &ctx->sbi; + struct ext4_super_block *es = &ctx->es; + char *buf; + + buf = kunit_kzalloc(test, PAGE_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, buf); + + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_show_test(sbi, "no_such_attr", buf), + (ssize_t)-ENOENT); + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "no_such_attr", + "1", 1), + (ssize_t)-ENOENT); + + /* Explicit pointer RO attr: max_writeback_mb_bump == 128 */ + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, + "max_writeback_mb_bump", buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "128\n"); + + /* RW sbi unsigned int (attr_pointer_ui) and unsigned long (ul) */ + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "inode_goal", + " 42\n", 5), + (ssize_t)5); + KUNIT_EXPECT_EQ(test, sbi->s_inode_goal, 42U); + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, "inode_goal", buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "42\n"); + + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "last_trim_minblks", + "1048576", 7), + (ssize_t)7); + KUNIT_EXPECT_EQ(test, sbi->s_last_trim_minblks, 1048576UL); + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, "last_trim_minblks", + buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "1048576\n"); + + /* RW positive int (attr_pointer_pi) rejects negative values */ + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "err_ratelimit_burst", + "-1", 2), + (ssize_t)-EINVAL); + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "err_ratelimit_burst", + "0x80000000", 10), + (ssize_t)-EINVAL); + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "err_ratelimit_burst", + "15", 2), + (ssize_t)2); + KUNIT_EXPECT_EQ(test, sbi->s_err_ratelimit_state.burst, 15); + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, "err_ratelimit_burst", + buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "15\n"); + + /* RO atomic_t on sbi */ + atomic_set(&sbi->s_warning_count, 9); + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, "warning_count", buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "9\n"); + + /* RO superblock LE32, U8, LE64, and fixed-size string attrs */ + es->s_error_count = cpu_to_le32(77); + es->s_first_error_errcode = EXT4_ERR_EIO; + es->s_first_error_block = cpu_to_le64(0x123456789abcULL); + memset(es->s_first_error_func, 'A', sizeof(es->s_first_error_func)); + + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, "errors_count", buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "77\n"); + + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, "first_error_errcode", + buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "2\n"); + + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, "first_error_block", + buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "20015998343868\n"); + + /* Non-NUL-terminated 32-byte s_first_error_func is bounded to 32 */ + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_show_test(sbi, "first_error_func", + buf), + (ssize_t)33); + KUNIT_EXPECT_EQ(test, buf[32], '\n'); +} + +static void test_validated_rw_attrs(struct kunit *test) +{ + struct sysfs_test_ctx *ctx = test->priv; + struct ext4_sb_info *sbi = &ctx->sbi; + char *buf; + + buf = kunit_kzalloc(test, PAGE_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, buf); + + /* inode_readahead_blks: 0 or power-of-2 <= 0x40000000 */ + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "inode_readahead_blks", + "0", 1), + (ssize_t)1); + KUNIT_EXPECT_EQ(test, sbi->s_inode_readahead_blks, 0U); + + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "inode_readahead_blks", + "0x40000000", 10), + (ssize_t)10); + KUNIT_EXPECT_EQ(test, sbi->s_inode_readahead_blks, 0x40000000U); + + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "inode_readahead_blks", + "3", 1), + (ssize_t)-EINVAL); + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "inode_readahead_blks", + "0x80000000", 10), + (ssize_t)-EINVAL); + + /* + * reserved_clusters: 4096 blocks >> 2 cluster_bits == 1024 clusters; + * valid range is [0, 1023]. + */ + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "reserved_clusters", + "1023", 4), + (ssize_t)4); + KUNIT_EXPECT_EQ(test, atomic64_read(&sbi->s_resv_clusters), 1023LL); + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, "reserved_clusters", + buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "1023\n"); + + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "reserved_clusters", + "1024", 4), + (ssize_t)-EINVAL); + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "reserved_clusters", + "0xffffffffffffffff", 18), + (ssize_t)-EINVAL); + + /* mb_best_avail_max_trim_order: [0, 64] */ + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, + "mb_best_avail_max_trim_order", "64", 2), + (ssize_t)2); + KUNIT_EXPECT_EQ(test, sbi->s_mb_best_avail_max_trim_order, 64U); + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, + "mb_best_avail_max_trim_order", "65", 2), + (ssize_t)-EINVAL); + + /* mb_group_prealloc: [0, s_clusters_per_group == 256] */ + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "mb_group_prealloc", + "256", 3), + (ssize_t)3); + KUNIT_EXPECT_EQ(test, sbi->s_mb_group_prealloc, 256U); + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "mb_group_prealloc", + "257", 3), + (ssize_t)-EINVAL); + + /* err_report_sec: <= 365 * 24 * 60 * 60 (31536000) */ + sbi->s_err_report_sec = 0; + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "err_report_sec", + "3600", 4), + (ssize_t)4); + KUNIT_EXPECT_EQ(test, sbi->s_err_report_sec, 3600UL); + + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "err_report_sec", + "31536000", 8), + (ssize_t)8); + KUNIT_EXPECT_EQ(test, sbi->s_err_report_sec, 31536000UL); + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, "err_report_sec", buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "31536000\n"); + + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "err_report_sec", + "31536001", 8), + (ssize_t)-EINVAL); +} + +static void test_computed_ro_and_error_time_attrs(struct kunit *test) +{ + struct sysfs_test_ctx *ctx = test->priv; + struct ext4_sb_info *sbi = &ctx->sbi; + struct ext4_super_block *es = &ctx->es; + char expected_pid[32]; + char *buf; + + buf = kunit_kzalloc(test, PAGE_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, buf); + + /* 7 dirty clusters * 4 blocks/cluster == 28 delayed allocation blks */ + percpu_counter_set(&sbi->s_dirtyclusters_counter, 7); + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, + "delayed_allocation_blocks", buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "28\n"); + + /* (50 - 10) sectors >> 1 == 20 KB session, + 100 == 120 KB lifetime */ + sbi->s_sectors_written_start = 10; + sbi->s_kbytes_written = 100; + part_stat_lock(); + part_stat_add(&ctx->bdev, sectors[STAT_WRITE], 50); + part_stat_unlock(); + + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, "session_write_kbytes", + buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "20\n"); + + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, "lifetime_write_kbytes", + buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "120\n"); + + /* sra_exceeded_retry_limit sums percpu counter */ + percpu_counter_set(&sbi->s_sra_exceeded_retry_limit, 13); + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, + "sra_exceeded_retry_limit", buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "13\n"); + + /* 40-bit timestamp formatting: (2 << 32) + 100 == 8589934692 */ + es->s_first_error_time = cpu_to_le32(100); + es->s_first_error_time_hi = 2; + es->s_last_error_time = cpu_to_le32(250); + es->s_last_error_time_hi = 0; + + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, "first_error_time", + buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "8589934692\n"); + + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, "last_error_time", buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "250\n"); + + /* journal_task emits "\n" without journal, or j_task PID */ + sbi->s_journal = NULL; + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, "journal_task", buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, "\n"); + + ctx->mock_journal.j_task = current; + sbi->s_journal = &ctx->mock_journal; + snprintf(expected_pid, sizeof(expected_pid), "%d\n", + task_pid_vnr(current)); + KUNIT_EXPECT_GT(test, + ext4_sysfs_attr_show_test(sbi, "journal_task", buf), + (ssize_t)0); + KUNIT_EXPECT_STREQ(test, buf, expected_pid); + sbi->s_journal = NULL; +} + +static void test_feature_attrs_and_trigger_error(struct kunit *test) +{ + struct sysfs_test_ctx *ctx = test->priv; + struct ext4_sb_info *sbi = &ctx->sbi; + static const char * const feat_names[] = { + "lazy_itable_init", + "batched_discard", + "meta_bg_resize", + "metadata_csum_seed", + "fast_commit", +#ifdef CONFIG_FS_ENCRYPTION + "encryption", + "test_dummy_encryption_v2", +#endif +#if IS_ENABLED(CONFIG_UNICODE) + "casefold", +#endif +#ifdef CONFIG_FS_VERITY + "verity", +#endif +#if IS_ENABLED(CONFIG_UNICODE) && defined(CONFIG_FS_ENCRYPTION) + "encrypted_casefold", +#endif + }; + char *buf; + size_t i; + + buf = kunit_kzalloc(test, PAGE_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, buf); + + for (i = 0; i < ARRAY_SIZE(feat_names); i++) { + KUNIT_EXPECT_GT_MSG(test, + ext4_sysfs_feat_show_test(feat_names[i], + buf), + (ssize_t)0, "feat=%s", feat_names[i]); + KUNIT_EXPECT_STREQ_MSG(test, buf, "supported\n", + "feat=%s", feat_names[i]); + } + KUNIT_EXPECT_EQ(test, ext4_sysfs_feat_show_test("unknown_feat", buf), + (ssize_t)-ENOENT); + + /* Empty newline write to trigger_fs_error is a no-op */ + sbi->s_journal = &ctx->mock_journal; + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "trigger_fs_error", + "\n", 1), + (ssize_t)1); + KUNIT_EXPECT_EQ(test, sbi->s_mount_state & EXT4_ERROR_FS, 0); + + /* Non-empty message records error state via ext4_error() */ + KUNIT_EXPECT_EQ(test, + ext4_sysfs_attr_store_test(sbi, "trigger_fs_error", + "kunit injected\n", 15), + (ssize_t)15); + KUNIT_EXPECT_NE(test, sbi->s_mount_state & EXT4_ERROR_FS, 0); + if (IS_ENABLED(CONFIG_PRINTK)) + KUNIT_EXPECT_STREQ(test, sbi->s_last_error_func, + "trigger_test_error"); + else + KUNIT_EXPECT_STREQ(test, sbi->s_last_error_func, ""); + sbi->s_journal = NULL; +} + +static void test_sysfs_register_notify_and_unregister(struct kunit *test) +{ + struct sysfs_test_ctx *ctx = test->priv; + struct super_block *sb = ctx->sb; + struct ext4_sb_info *sbi = &ctx->sbi; + + KUNIT_ASSERT_EQ(test, ext4_register_sysfs(sb), 0); + KUNIT_EXPECT_EQ(test, (int)sbi->s_kobj.state_in_sysfs, 1); + + ext4_notify_error_sysfs(sbi); + + ext4_unregister_sysfs(sb); + KUNIT_EXPECT_EQ(test, (int)sbi->s_kobj.state_in_sysfs, 0); + kobject_put(&sbi->s_kobj); + wait_for_completion(&sbi->s_kobj_unregister); +} + +static struct kunit_case ext4_sysfs_test_cases[] = { + KUNIT_CASE(test_generic_pointer_attrs), + KUNIT_CASE(test_validated_rw_attrs), + KUNIT_CASE(test_computed_ro_and_error_time_attrs), + KUNIT_CASE(test_feature_attrs_and_trigger_error), + KUNIT_CASE(test_sysfs_register_notify_and_unregister), + {} +}; + +static struct kunit_suite ext4_sysfs_test_suite = { + .name = "ext4_sysfs_test", + .init = sysfs_test_init, + .test_cases = ext4_sysfs_test_cases, +}; + +kunit_test_suites(&ext4_sysfs_test_suite); + +MODULE_DESCRIPTION("KUnit tests for ext4 sysfs and procfs interfaces"); +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/sysfs.c b/fs/ext4/sysfs.c index 923b375e017faa..faa76f02109919 100644 --- a/fs/ext4/sysfs.c +++ b/fs/ext4/sysfs.c @@ -602,6 +602,7 @@ void ext4_notify_error_sysfs(struct ext4_sb_info *sbi) sysfs_notify(&sbi->s_kobj, NULL, "errors_count"); mutex_unlock(&sbi->s_error_notify_mutex); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_notify_error_sysfs); static struct kobject *ext4_root; @@ -642,6 +643,7 @@ int ext4_register_sysfs(struct super_block *sb) } return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_register_sysfs); void ext4_unregister_sysfs(struct super_block *sb) { @@ -654,6 +656,7 @@ void ext4_unregister_sysfs(struct super_block *sb) kobject_del(&sbi->s_kobj); mutex_unlock(&sbi->s_error_notify_mutex); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_unregister_sysfs); int __init ext4_init_sysfs(void) { @@ -696,3 +699,55 @@ void ext4_exit_sysfs(void) ext4_proc_root = NULL; } +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +static struct attribute *ext4_find_attr_test(struct attribute **list, + const char *name) +{ + for (; *list; list++) { + if (strcmp((*list)->name, name) == 0) + return *list; + } + return NULL; +} + +ssize_t ext4_sysfs_attr_show_test(struct ext4_sb_info *sbi, const char *name, + char *buf) +{ + struct attribute *attr = ext4_find_attr_test(ext4_attrs, name); + + if (!attr) + return -ENOENT; + return ext4_attr_show(&sbi->s_kobj, attr, buf); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sysfs_attr_show_test); + +ssize_t ext4_sysfs_attr_store_test(struct ext4_sb_info *sbi, const char *name, + const char *buf, size_t len) +{ + struct attribute *attr = ext4_find_attr_test(ext4_attrs, name); + + if (!attr) + return -ENOENT; + return ext4_attr_store(&sbi->s_kobj, attr, buf, len); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sysfs_attr_store_test); + +ssize_t ext4_sysfs_feat_show_test(const char *name, char *buf) +{ + struct attribute *attr = ext4_find_attr_test(ext4_feat_attrs, name); + struct ext4_sb_info *dummy_sbi; + ssize_t ret; + + if (!attr) + return -ENOENT; + /* struct ext4_sb_info is too large to place on the stack */ + dummy_sbi = kzalloc_obj(*dummy_sbi); + if (!dummy_sbi) + return -ENOMEM; + ret = ext4_attr_show(&dummy_sbi->s_kobj, attr, buf); + kfree(dummy_sbi); + return ret; +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sysfs_feat_show_test); +#endif + diff --git a/fs/ext4/xattr-test.c b/fs/ext4/xattr-test.c new file mode 100644 index 00000000000000..480bb4ac19ad3c --- /dev/null +++ b/fs/ext4/xattr-test.c @@ -0,0 +1,1825 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for ext4 extended attributes (fs/ext4/xattr.c). + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ext4.h" +#include "ext4_jbd2.h" +#include "xattr.h" + +#define TEST_BLK_SIZE 1024 +#define TEST_BLK_BITS 10 +#define TEST_INODE_SIZE 256 +#define TEST_EXTRA_ISIZE (sizeof(struct ext4_inode) - \ + EXT4_GOOD_OLD_INODE_SIZE) +#define TEST_FIRST_PBLK 100 +#define TEST_MAX_BLOCKS 16 +#define TEST_MAX_EA_INODES 8 +#define TEST_PRIMARY_INO 12 +#define TEST_SECONDARY_INO 13 +#define TEST_FIRST_EA_INO 20 +#define TEST_CSUM_SEED 0x87654321U + +struct mock_block { + bool in_use; + struct buffer_head bh; + char data[TEST_BLK_SIZE] __aligned(8); +}; + +struct mock_inode_slot { + bool allocated; + struct ext4_inode_info ei; + struct buffer_head iloc_bh; + char raw_buf[TEST_INODE_SIZE] __aligned(8); + ext4_fsblk_t lblk_to_pblk[8]; +}; + +struct xattr_test_ctx { + struct super_block sb; + struct ext4_sb_info sbi; + struct ext4_super_block es; + struct block_device bdev; + struct address_space bd_mapping; + struct buffer_head sb_bh; + struct dentry root_dentry; + + struct mock_inode_slot primary; + struct mock_inode_slot secondary; + struct mock_inode_slot ea_inodes[TEST_MAX_EA_INODES]; + struct mock_block blocks[TEST_MAX_BLOCKS]; + + int fail_get_inode_loc; + int fail_mark_iloc_dirty; + int fail_dirty_metadata; + int fail_alloc_block; + int fail_sb_bread; + int fail_getblk; + int fail_iget; + int fail_new_inode; + bool fail_xattr_getblk; + + unsigned int alloc_block_calls; + unsigned int free_block_calls; + ext4_fsblk_t last_freed_block; + unsigned int mark_iloc_dirty_calls; + unsigned int mark_inode_dirty_calls; + unsigned int dirty_metadata_calls; +}; + +#ifdef CONFIG_QUOTA +static struct dquot __rcu **xattr_test_get_dquots(struct inode *inode) +{ + return EXT4_I(inode)->i_dquot; +} + +static qsize_t *xattr_test_get_reserved_space(struct inode *inode) +{ + return &EXT4_I(inode)->i_reserved_quota; +} + +static const struct dquot_operations xattr_test_qops = { + .get_reserved_space = xattr_test_get_reserved_space, +}; +#endif + +static const struct super_operations xattr_test_sops = { +#ifdef CONFIG_QUOTA + .get_dquots = xattr_test_get_dquots, +#endif +}; + +static void init_mock_inode_slot(struct xattr_test_ctx *ctx, + struct mock_inode_slot *slot, + unsigned long ino) +{ + struct inode *inode = &slot->ei.vfs_inode; + struct ext4_inode *raw_inode; + + memset(slot, 0, sizeof(*slot)); + slot->allocated = true; + + inode->i_sb = &ctx->sb; + inode->i_ino = ino; + inode->i_mode = S_IFREG | 0644; + inode->i_blkbits = TEST_BLK_BITS; + inode->i_mapping = &inode->i_data; + set_nlink(inode, 1); + atomic_set(&inode->i_count, 1); + + spin_lock_init(&inode->i_lock); + i_size_ordered_init(inode); + init_rwsem(&inode->i_rwsem); + INIT_LIST_HEAD(&inode->i_io_list); + INIT_LIST_HEAD(&inode->i_wb_list); + INIT_LIST_HEAD(&inode->i_lru); + INIT_HLIST_NODE(&inode->i_hash); + /* + * Pre-set all I_DIRTY flags so mark_inode_dirty() from quota helpers + * sees the flags already set and returns without touching global bdi + * writeback lists. + */ + inode_state_set_raw(inode, I_DIRTY); + + init_rwsem(&slot->ei.xattr_sem); + init_rwsem(&slot->ei.i_data_sem); + spin_lock_init(&slot->ei.i_raw_lock); + spin_lock_init(&slot->ei.i_block_reservation_lock); + INIT_LIST_HEAD(&slot->ei.i_orphan); + slot->ei.i_extra_isize = TEST_EXTRA_ISIZE; + slot->ei.i_csum_seed = TEST_CSUM_SEED ^ (u32)ino; + + slot->iloc_bh.b_data = slot->raw_buf; + slot->iloc_bh.b_size = TEST_INODE_SIZE; + slot->iloc_bh.b_blocknr = 10 + ino; + slot->iloc_bh.b_bdev = &ctx->bdev; + atomic_set(&slot->iloc_bh.b_count, 1); + set_buffer_uptodate(&slot->iloc_bh); + set_buffer_mapped(&slot->iloc_bh); + + raw_inode = (struct ext4_inode *)slot->raw_buf; + raw_inode->i_extra_isize = cpu_to_le16(slot->ei.i_extra_isize); +} + +static struct mock_block *alloc_mock_block(struct xattr_test_ctx *ctx) +{ + int i; + + for (i = 0; i < TEST_MAX_BLOCKS; i++) { + struct mock_block *blk = &ctx->blocks[i]; + + if (!blk->in_use) { + memset(blk, 0, sizeof(*blk)); + blk->in_use = true; + blk->bh.b_data = blk->data; + blk->bh.b_size = TEST_BLK_SIZE; + blk->bh.b_blocknr = TEST_FIRST_PBLK + i; + blk->bh.b_bdev = &ctx->bdev; + atomic_set(&blk->bh.b_count, 1); + set_buffer_uptodate(&blk->bh); + set_buffer_mapped(&blk->bh); + return blk; + } + } + return NULL; +} + +static struct mock_block *find_mock_block(struct xattr_test_ctx *ctx, + ext4_fsblk_t blocknr) +{ + int i; + + for (i = 0; i < TEST_MAX_BLOCKS; i++) { + if (ctx->blocks[i].in_use && + ctx->blocks[i].bh.b_blocknr == blocknr) + return &ctx->blocks[i]; + } + return NULL; +} + +static int ext4_get_inode_loc_stub(struct inode *inode, struct ext4_iloc *iloc) +{ + struct kunit *test = kunit_get_current_test(); + struct xattr_test_ctx *ctx = test->priv; + struct mock_inode_slot *slot; + + if (ctx->fail_get_inode_loc) + return ctx->fail_get_inode_loc; + + slot = container_of(EXT4_I(inode), struct mock_inode_slot, ei); + get_bh(&slot->iloc_bh); + iloc->bh = &slot->iloc_bh; + iloc->offset = 0; + iloc->block_group = 0; + return 0; +} + +static int ext4_mark_iloc_dirty_stub(handle_t *handle, struct inode *inode, + struct ext4_iloc *iloc) +{ + struct kunit *test = kunit_get_current_test(); + struct xattr_test_ctx *ctx = test->priv; + + brelse(iloc->bh); + ctx->mark_iloc_dirty_calls++; + if (ctx->fail_mark_iloc_dirty) + return ctx->fail_mark_iloc_dirty; + return 0; +} + +static int __ext4_mark_inode_dirty_stub(handle_t *handle, struct inode *inode, + const char *func, unsigned int line) +{ + struct kunit *test = kunit_get_current_test(); + struct xattr_test_ctx *ctx = test->priv; + + ctx->mark_inode_dirty_calls++; + return 0; +} + +static int __ext4_handle_dirty_metadata_stub(const char *where, + unsigned int line, + handle_t *handle, + struct inode *inode, + struct buffer_head *bh) +{ + struct kunit *test = kunit_get_current_test(); + struct xattr_test_ctx *ctx = test->priv; + + if (ctx->fail_dirty_metadata) + return ctx->fail_dirty_metadata; + if (bh) + set_buffer_uptodate(bh); + ctx->dirty_metadata_calls++; + return 0; +} + +static ext4_fsblk_t ext4_mb_new_blocks_stub(handle_t *handle, + struct ext4_allocation_request *ar, + int *errp) +{ + struct kunit *test = kunit_get_current_test(); + struct xattr_test_ctx *ctx = test->priv; + struct mock_block *blk; + + if (ctx->fail_alloc_block) { + *errp = ctx->fail_alloc_block; + return 0; + } + + blk = alloc_mock_block(ctx); + if (!blk) { + *errp = -ENOSPC; + return 0; + } + + ctx->alloc_block_calls++; + *errp = 0; + return blk->bh.b_blocknr; +} + +static void ext4_free_blocks_stub(handle_t *handle, struct inode *inode, + struct buffer_head *bh, ext4_fsblk_t block, + unsigned long count, int flags) +{ + struct kunit *test = kunit_get_current_test(); + struct xattr_test_ctx *ctx = test->priv; + struct mock_block *blk; + + if (bh) { + if (!block) + block = bh->b_blocknr; + if (flags & EXT4_FREE_BLOCKS_FORGET) + brelse(bh); + } + if (!(flags & EXT4_FREE_BLOCKS_NO_QUOT_UPDATE)) + dquot_free_block(inode, + EXT4_C2B(EXT4_SB(inode->i_sb), count)); + + blk = find_mock_block(ctx, block); + if (blk) + blk->in_use = false; + + ctx->free_block_calls++; + ctx->last_freed_block = block; +} + +static struct buffer_head *ext4_xattr_getblk_stub(struct super_block *sb, + ext4_fsblk_t block) +{ + struct kunit *test = kunit_get_current_test(); + struct xattr_test_ctx *ctx = test->priv; + struct mock_block *blk; + + if (ctx->fail_xattr_getblk) + return NULL; + + blk = find_mock_block(ctx, block); + if (!blk) + return NULL; + + get_bh(&blk->bh); + return &blk->bh; +} + +static struct buffer_head *ext4_sb_bread_stub(struct super_block *sb, + sector_t block, + blk_opf_t op_flags) +{ + struct kunit *test = kunit_get_current_test(); + struct xattr_test_ctx *ctx = test->priv; + struct mock_block *blk; + + if (ctx->fail_sb_bread) + return ERR_PTR(ctx->fail_sb_bread); + + blk = find_mock_block(ctx, block); + if (!blk) + return ERR_PTR(-EIO); + + get_bh(&blk->bh); + return &blk->bh; +} + +static int ext4_map_blocks_stub(handle_t *handle, struct inode *inode, + struct ext4_map_blocks *map, int flags) +{ + struct kunit *test = kunit_get_current_test(); + struct xattr_test_ctx *ctx = test->priv; + struct mock_inode_slot *slot; + struct mock_block *blk; + + slot = container_of(EXT4_I(inode), struct mock_inode_slot, ei); + if (map->m_lblk >= ARRAY_SIZE(slot->lblk_to_pblk)) + return -EFSCORRUPTED; + + if (!slot->lblk_to_pblk[map->m_lblk]) { + if (!(flags & EXT4_GET_BLOCKS_CREATE)) + return 0; + if (ctx->fail_alloc_block) + return ctx->fail_alloc_block; + blk = alloc_mock_block(ctx); + if (!blk) + return -ENOSPC; + slot->lblk_to_pblk[map->m_lblk] = blk->bh.b_blocknr; + inode->i_blocks += TEST_BLK_SIZE >> 9; + map->m_flags = EXT4_MAP_NEW | EXT4_MAP_MAPPED; + } else { + map->m_flags = EXT4_MAP_MAPPED; + } + + map->m_pblk = slot->lblk_to_pblk[map->m_lblk]; + map->m_len = 1; + return 1; +} + +static struct buffer_head *ext4_getblk_stub(handle_t *handle, + struct inode *inode, + ext4_lblk_t block, int map_flags) +{ + struct kunit *test = kunit_get_current_test(); + struct xattr_test_ctx *ctx = test->priv; + struct mock_inode_slot *slot; + struct mock_block *blk; + + if (ctx->fail_getblk) + return ERR_PTR(ctx->fail_getblk); + + slot = container_of(EXT4_I(inode), struct mock_inode_slot, ei); + if (block >= ARRAY_SIZE(slot->lblk_to_pblk)) + return ERR_PTR(-EFSCORRUPTED); + if (!slot->lblk_to_pblk[block]) { + if (!(map_flags & EXT4_GET_BLOCKS_CREATE)) + return NULL; + blk = alloc_mock_block(ctx); + if (!blk) + return ERR_PTR(-ENOSPC); + slot->lblk_to_pblk[block] = blk->bh.b_blocknr; + inode->i_blocks += TEST_BLK_SIZE >> 9; + } else { + blk = find_mock_block(ctx, slot->lblk_to_pblk[block]); + if (!blk) + return ERR_PTR(-EIO); + } + + get_bh(&blk->bh); + return &blk->bh; +} + +static struct inode *__ext4_new_inode_stub(const struct mnt_idmap *idmap, + handle_t *handle, + struct inode *dir, umode_t mode, + const struct qstr *qstr, + __u32 goal, uid_t *owner, + __u32 i_flags, int handle_type, + unsigned int line_no, int nblocks) +{ + struct kunit *test = kunit_get_current_test(); + struct xattr_test_ctx *ctx = test->priv; + int i; + + if (ctx->fail_new_inode) + return ERR_PTR(ctx->fail_new_inode); + + for (i = 0; i < TEST_MAX_EA_INODES; i++) { + struct mock_inode_slot *slot = &ctx->ea_inodes[i]; + struct inode *inode = &slot->ei.vfs_inode; + + if (!slot->allocated) { + init_mock_inode_slot(ctx, slot, TEST_FIRST_EA_INO + i); + inode->i_mode = mode; + slot->ei.i_flags = i_flags; + if (owner) { + i_uid_write(inode, owner[0]); + i_gid_write(inode, owner[1]); + } + /* + * Set I_NEW for unlock_new_inode() and give the mock + * inode an extra baseline reference (i_count = 2) so + * ext4_put_ea_inode()'s iput_if_not_last() decrements + * i_count to 1 and returns without entering VFS + * eviction. + */ + inode_state_set_raw(inode, I_DIRTY | I_NEW); + atomic_set(&inode->i_count, 2); + return inode; + } + } + return ERR_PTR(-ENOSPC); +} + +static struct inode *__ext4_iget_stub(struct super_block *sb, + unsigned long ino, + ext4_iget_flags flags, + const char *function, + unsigned int line) +{ + struct kunit *test = kunit_get_current_test(); + struct xattr_test_ctx *ctx = test->priv; + int i; + + if (ctx->fail_iget) + return ERR_PTR(ctx->fail_iget); + + for (i = 0; i < TEST_MAX_EA_INODES; i++) { + struct mock_inode_slot *slot = &ctx->ea_inodes[i]; + struct inode *inode = &slot->ei.vfs_inode; + + if (slot->allocated && inode->i_ino == ino) { + if ((flags & EXT4_IGET_EA_INODE) && + !(slot->ei.i_flags & EXT4_EA_INODE_FL)) + return ERR_PTR(-EFSCORRUPTED); + atomic_inc(&inode->i_count); + return inode; + } + } + return ERR_PTR(-ENOENT); +} + +static int xattr_test_init(struct kunit *test) +{ + struct xattr_test_ctx *ctx; + struct super_block *sb; + struct ext4_sb_info *sbi; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + test->priv = ctx; + + sb = &ctx->sb; + sbi = &ctx->sbi; + + sbi->s_sb = sb; + sb->s_fs_info = sbi; + sb->s_op = &xattr_test_sops; +#ifdef CONFIG_QUOTA + sb->dq_op = &xattr_test_qops; +#endif +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; +#endif + sb->s_blocksize = TEST_BLK_SIZE; + sb->s_blocksize_bits = TEST_BLK_BITS; + sb->s_maxbytes = MAX_LFS_FILESIZE; + sb->s_time_gran = 1; + sb->s_xattr = ext4_xattr_handlers; + /* i_uid_read()/i_gid_read() map through sb->s_user_ns */ + sb->s_user_ns = &init_user_ns; + strscpy(sb->s_id, "ext4_xattr_kunit", sizeof(sb->s_id)); + init_rwsem(&sb->s_umount); + + ctx->bdev.bd_mapping = &ctx->bd_mapping; + bdev_set_flag(&ctx->bdev, BD_READ_ONLY); + sb->s_bdev = &ctx->bdev; + + sbi->s_es = &ctx->es; + ctx->es.s_first_data_block = cpu_to_le32(1); + ctx->es.s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); + ctx->es.s_inodes_count = cpu_to_le32(1024); + ctx->es.s_first_ino = cpu_to_le32(11); + ctx->es.s_inode_size = cpu_to_le16(TEST_INODE_SIZE); + ext4_blocks_count_set(&ctx->es, 65536); + + ctx->sb_bh.b_data = (char *)&ctx->es; + ctx->sb_bh.b_size = sizeof(ctx->es); + ctx->sb_bh.b_bdev = &ctx->bdev; + atomic_set(&ctx->sb_bh.b_count, 1); + set_buffer_uptodate(&ctx->sb_bh); + sbi->s_sbh = &ctx->sb_bh; + + sbi->s_inode_size = TEST_INODE_SIZE; + sbi->s_first_ino = 11; + sbi->s_want_extra_isize = TEST_EXTRA_ISIZE; + ctx->es.s_min_extra_isize = cpu_to_le16(TEST_EXTRA_ISIZE); + sbi->s_blocks_per_group = 8192; + sbi->s_clusters_per_group = 8192; + sbi->s_cluster_ratio = 1; + sbi->s_cluster_bits = 0; + sbi->s_groups_count = 8; + sbi->s_csum_seed = TEST_CSUM_SEED; + + set_opt(sb, ERRORS_CONT); + set_opt(sb, XATTR_USER); + spin_lock_init(&sbi->s_bdev_wb_lock); + spin_lock_init(&sbi->s_error_lock); + spin_lock_init(&sbi->s_md_lock); + + /* + * Use burst = 0 so expected corruption-test error/warning messages + * are suppressed without setting EXT4_FLAGS_SHUTDOWN. + */ + ratelimit_state_init(&sbi->s_err_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_warning_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + ratelimit_state_init(&sbi->s_msg_ratelimit_state, + DEFAULT_RATELIMIT_INTERVAL, 0); + + init_mock_inode_slot(ctx, &ctx->primary, TEST_PRIMARY_INO); + init_mock_inode_slot(ctx, &ctx->secondary, TEST_SECONDARY_INO); + + ctx->root_dentry.d_sb = sb; + ctx->root_dentry.d_inode = &ctx->primary.ei.vfs_inode; + sb->s_root = &ctx->root_dentry; + + kunit_activate_static_stub(test, ext4_get_inode_loc, + ext4_get_inode_loc_stub); + kunit_activate_static_stub(test, ext4_mark_iloc_dirty, + ext4_mark_iloc_dirty_stub); + kunit_activate_static_stub(test, __ext4_mark_inode_dirty, + __ext4_mark_inode_dirty_stub); + kunit_activate_static_stub(test, __ext4_handle_dirty_metadata, + __ext4_handle_dirty_metadata_stub); + kunit_activate_static_stub(test, ext4_mb_new_blocks, + ext4_mb_new_blocks_stub); + kunit_activate_static_stub(test, ext4_free_blocks, + ext4_free_blocks_stub); + kunit_activate_static_stub(test, ext4_xattr_getblk, + ext4_xattr_getblk_stub); + kunit_activate_static_stub(test, ext4_sb_bread, + ext4_sb_bread_stub); + kunit_activate_static_stub(test, ext4_map_blocks, + ext4_map_blocks_stub); + kunit_activate_static_stub(test, ext4_getblk, + ext4_getblk_stub); + kunit_activate_static_stub(test, __ext4_new_inode, + __ext4_new_inode_stub); + kunit_activate_static_stub(test, __ext4_iget, + __ext4_iget_stub); + + return 0; +} + +static void xattr_test_exit(struct kunit *test) +{ + struct xattr_test_ctx *ctx = test->priv; + + if (!ctx) + return; + + ext4_xattr_destroy_cache(ctx->sbi.s_ea_block_cache); + ctx->sbi.s_ea_block_cache = NULL; + ext4_xattr_destroy_cache(ctx->sbi.s_ea_inode_cache); + ctx->sbi.s_ea_inode_cache = NULL; +} + +/* + * Test 1: Sizing macros, EXT4_INODE_HAS_XATTR_SPACE, and xattr_sem locking + * helpers. + */ +static void test_xattr_macros_and_locking(struct kunit *test) +{ + struct xattr_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->primary.ei.vfs_inode; + int save_outer = -1, save_inner = -1; + int locked; + + /* EXT4_XATTR_LEN rounds (sizeof(entry) + name_len) to 4-byte boundary */ + KUNIT_EXPECT_EQ(test, EXT4_XATTR_LEN(0), 16U); + KUNIT_EXPECT_EQ(test, EXT4_XATTR_LEN(1), 20U); + KUNIT_EXPECT_EQ(test, EXT4_XATTR_LEN(4), 20U); + KUNIT_EXPECT_EQ(test, EXT4_XATTR_LEN(5), 24U); + + /* EXT4_XATTR_SIZE rounds value size up to 4-byte boundary */ + KUNIT_EXPECT_EQ(test, EXT4_XATTR_SIZE(0), 0U); + KUNIT_EXPECT_EQ(test, EXT4_XATTR_SIZE(1), 4U); + KUNIT_EXPECT_EQ(test, EXT4_XATTR_SIZE(4), 4U); + KUNIT_EXPECT_EQ(test, EXT4_XATTR_SIZE(5), 8U); + + /* + * EXT4_XATTR_MIN_LARGE_EA_SIZE(b) is + * b - EXT4_XATTR_LEN(3) - sizeof(struct ext4_xattr_header) - 4. + */ + KUNIT_EXPECT_EQ(test, EXT4_XATTR_MIN_LARGE_EA_SIZE(1024), 968); + KUNIT_EXPECT_EQ(test, EXT4_XATTR_MIN_LARGE_EA_SIZE(4096), 4040); + + /* + * EXT4_INODE_HAS_XATTR_SPACE requires at least + * sizeof(ibody_header) + EXT4_XATTR_PAD = 8 bytes of space after + * EXT4_GOOD_OLD_INODE_SIZE + i_extra_isize. + */ + KUNIT_EXPECT_TRUE(test, EXT4_INODE_HAS_XATTR_SPACE(inode)); + + ctx->sbi.s_inode_size = EXT4_GOOD_OLD_INODE_SIZE; + KUNIT_EXPECT_FALSE(test, EXT4_INODE_HAS_XATTR_SPACE(inode)); + ctx->sbi.s_inode_size = TEST_INODE_SIZE; + + /* Exact boundary: 256 - 128 - 8 = 120 bytes of i_extra_isize fits */ + EXT4_I(inode)->i_extra_isize = 120; + KUNIT_EXPECT_TRUE(test, EXT4_INODE_HAS_XATTR_SPACE(inode)); + + /* 124 bytes leaves only 4 bytes (< 8 bytes required) */ + EXT4_I(inode)->i_extra_isize = 124; + KUNIT_EXPECT_FALSE(test, EXT4_INODE_HAS_XATTR_SPACE(inode)); + EXT4_I(inode)->i_extra_isize = TEST_EXTRA_ISIZE; + + /* Locking helpers and EXT4_STATE_NO_EXPAND state preservation */ + KUNIT_EXPECT_EQ(test, + ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND), 0); + + ext4_write_lock_xattr(inode, &save_outer); + locked = ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND); + ext4_write_unlock_xattr(inode, &save_outer); + + KUNIT_EXPECT_EQ(test, save_outer, 0); + KUNIT_EXPECT_NE(test, locked, 0); + KUNIT_EXPECT_EQ(test, + ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND), 0); + + /* When EXT4_STATE_NO_EXPAND is already set, unlock must preserve it */ + ext4_set_inode_state(inode, EXT4_STATE_NO_EXPAND); + locked = ext4_write_trylock_xattr(inode, &save_inner); + if (locked) + ext4_write_unlock_xattr(inode, &save_inner); + + KUNIT_EXPECT_EQ(test, locked, 1); + KUNIT_EXPECT_NE(test, save_inner, 0); + KUNIT_EXPECT_NE(test, + ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND), 0); + ext4_clear_inode_state(inode, EXT4_STATE_NO_EXPAND); +} + +/* + * Test 2: Parameterized xattr_check_inode() validation across valid and + * corrupted in-inode xattr layouts. + */ +enum xattr_check_case_id { + CHECK_VALID_EMPTY, + CHECK_VALID_TWO_ENTRIES, + CHECK_BAD_MAGIC, + CHECK_END_BEFORE_FIRST, + CHECK_ENTRY_HDR_OVERFLOW, + CHECK_ENTRY_NAME_OVERFLOW, + CHECK_UNTERMINATED_LIST, + CHECK_EA_INODE_WITHOUT_FEATURE, + CHECK_VALUE_SIZE_GT_TOTAL, + CHECK_VALUE_OFFS_OVERLAPS_ENTRY, + CHECK_VALUE_END_EXCEEDS_TOTAL, +}; + +struct xattr_check_param { + const char *desc; + enum xattr_check_case_id id; + int expected_err; +}; + +static const struct xattr_check_param xattr_check_params[] = { + { "valid_empty_ibody", CHECK_VALID_EMPTY, 0 }, + { "valid_two_entries", CHECK_VALID_TWO_ENTRIES, 0 }, + { "bad_magic", CHECK_BAD_MAGIC, -EFSCORRUPTED }, + { "end_before_first_entry", CHECK_END_BEFORE_FIRST, -EFSCORRUPTED }, + { "entry_header_overflows_end", CHECK_ENTRY_HDR_OVERFLOW, -EFSCORRUPTED }, + { "entry_name_overflows_end", CHECK_ENTRY_NAME_OVERFLOW, -EFSCORRUPTED }, + { "unterminated_entry_list", CHECK_UNTERMINATED_LIST, -EFSCORRUPTED }, + { "ea_inode_without_feature", CHECK_EA_INODE_WITHOUT_FEATURE, -EFSCORRUPTED }, + { "value_size_gt_total_size", CHECK_VALUE_SIZE_GT_TOTAL, -EFSCORRUPTED }, + { "value_offset_overlaps_entries", CHECK_VALUE_OFFS_OVERLAPS_ENTRY, -EFSCORRUPTED }, + { "value_end_exceeds_total_size", CHECK_VALUE_END_EXCEEDS_TOTAL, -EFSCORRUPTED }, +}; + +static void xattr_check_param_get_desc(const struct xattr_check_param *p, + char *desc) +{ + strscpy(desc, p->desc, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(xattr_check, xattr_check_params, xattr_check_param_get_desc); + +static void test_xattr_check_inode(struct kunit *test) +{ + const struct xattr_check_param *p = test->param_value; + struct xattr_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->primary.ei.vfs_inode; + struct ext4_inode *raw_inode = (struct ext4_inode *)ctx->primary.raw_buf; + struct ext4_xattr_ibody_header *hdr = IHDR(inode, raw_inode); + struct ext4_xattr_entry *e1, *e2; + void *end = ITAIL(inode, raw_inode); + size_t total_size = (char *)end - (char *)IFIRST(hdr); + int ret; + + memset(hdr, 0, (char *)end - (char *)hdr); + hdr->h_magic = cpu_to_le32(EXT4_XATTR_MAGIC); + e1 = IFIRST(hdr); + + switch (p->id) { + case CHECK_VALID_EMPTY: + break; + case CHECK_VALID_TWO_ENTRIES: + e1->e_name_len = 1; + e1->e_name_index = EXT4_XATTR_INDEX_USER; + e1->e_name[0] = 'a'; + e1->e_value_size = cpu_to_le32(4); + e1->e_value_offs = cpu_to_le16(total_size - 4); + + e2 = EXT4_XATTR_NEXT(e1); + e2->e_name_len = 1; + e2->e_name_index = EXT4_XATTR_INDEX_USER; + e2->e_name[0] = 'b'; + e2->e_value_size = cpu_to_le32(4); + e2->e_value_offs = cpu_to_le16(total_size - 8); + break; + case CHECK_BAD_MAGIC: + hdr->h_magic = cpu_to_le32(0xdeadbeef); + break; + case CHECK_END_BEFORE_FIRST: + end = (char *)IFIRST(hdr) + 2; + break; + case CHECK_ENTRY_HDR_OVERFLOW: + e1->e_name_len = 1; + e1->e_name[0] = 'a'; + end = (char *)IFIRST(hdr) + EXT4_XATTR_LEN(1) + 8; + e2 = EXT4_XATTR_NEXT(e1); + e2->e_name_len = 1; + break; + case CHECK_ENTRY_NAME_OVERFLOW: + e1->e_name_len = 100; + break; + case CHECK_UNTERMINATED_LIST: + e1->e_name_len = 1; + e1->e_name[0] = 'a'; + end = (char *)IFIRST(hdr) + EXT4_XATTR_LEN(1); + break; + case CHECK_EA_INODE_WITHOUT_FEATURE: + ext4_clear_feature_ea_inode(&ctx->sb); + e1->e_name_len = 1; + e1->e_name[0] = 'a'; + e1->e_value_inum = cpu_to_le32(20); + e1->e_value_size = cpu_to_le32(4); + break; + case CHECK_VALUE_SIZE_GT_TOTAL: + e1->e_name_len = 1; + e1->e_name[0] = 'a'; + e1->e_value_size = cpu_to_le32(total_size + 4); + e1->e_value_offs = cpu_to_le16(total_size - 4); + break; + case CHECK_VALUE_OFFS_OVERLAPS_ENTRY: + e1->e_name_len = 1; + e1->e_name[0] = 'a'; + e1->e_value_size = cpu_to_le32(4); + /* Offset points inside e1 + 4-byte terminator */ + e1->e_value_offs = cpu_to_le16(EXT4_XATTR_LEN(1)); + break; + case CHECK_VALUE_END_EXCEEDS_TOTAL: + e1->e_name_len = 1; + e1->e_name[0] = 'a'; + e1->e_value_size = cpu_to_le32(8); + e1->e_value_offs = cpu_to_le16(total_size - 4); + break; + } + + ret = xattr_check_inode(inode, hdr, end); + KUNIT_EXPECT_EQ_MSG(test, ret, p->expected_err, "case: %s", p->desc); +} + +/* + * Test 3: In-inode (ibody) get/set, flags validation, EXT4_STATE_NEW handling, + * superblock feature update, and identical-value fastpath. + */ +static void test_xattr_ibody_basic_and_flags(struct kunit *test) +{ + struct xattr_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->primary.ei.vfs_inode; + struct ext4_inode *raw_inode = (struct ext4_inode *)ctx->primary.raw_buf; + char long_name[260]; + char buf[32]; + unsigned int prev_dirty; + int ret; + + /* Fresh inode without EXT4_STATE_XATTR returns -ENODATA */ + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "missing", + buf, sizeof(buf)); + KUNIT_EXPECT_EQ(test, ret, -ENODATA); + + /* Parameter validation: NULL name -> -EINVAL, >255 name -> -ERANGE */ + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_USER, + NULL, "v", 1, 0); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + + memset(long_name, 'x', sizeof(long_name) - 1); + long_name[sizeof(long_name) - 1] = '\0'; + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_USER, + long_name, "v", 1, 0); + KUNIT_EXPECT_EQ(test, ret, -ERANGE); + + /* Forced shutdown check on get and set */ + set_bit(EXT4_FLAGS_SHUTDOWN, &ctx->sbi.s_ext4_flags); + KUNIT_EXPECT_EQ(test, + ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "k", + buf, sizeof(buf)), + -EIO); + KUNIT_EXPECT_EQ(test, + ext4_xattr_set_handle(NULL, inode, + EXT4_XATTR_INDEX_USER, "k", + "v", 1, 0), + -EIO); + clear_bit(EXT4_FLAGS_SHUTDOWN, &ctx->sbi.s_ext4_flags); + + /* XATTR_REPLACE on non-existent attribute returns -ENODATA */ + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_USER, + "no_such", "val", 3, XATTR_REPLACE); + KUNIT_EXPECT_EQ(test, ret, -ENODATA); + + /* Deleting non-existent attribute without XATTR_REPLACE succeeds (0) */ + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_USER, + "no_such", NULL, 0, 0); + KUNIT_EXPECT_EQ(test, ret, 0); + + /* + * Verify EXT4_STATE_NEW causes ext4_xattr_set_handle() to zero the raw + * inode and clear EXT4_STATE_NEW. + */ + memset(raw_inode, 0x5a, TEST_INODE_SIZE); + ext4_set_inode_state(inode, EXT4_STATE_NEW); + KUNIT_EXPECT_FALSE(test, + ext4_has_feature_xattr(&ctx->sb)); + + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_USER, + "key1", "hello", 5, XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, + ext4_test_inode_state(inode, EXT4_STATE_NEW), 0); + KUNIT_EXPECT_NE(test, + ext4_test_inode_state(inode, EXT4_STATE_XATTR), 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(IHDR(inode, raw_inode)->h_magic), + (u32)EXT4_XATTR_MAGIC); + /* Setting first xattr enables EXT4_FEATURE_COMPAT_EXT_ATTR on sb */ + KUNIT_EXPECT_TRUE(test, ext4_has_feature_xattr(&ctx->sb)); + + /* XATTR_CREATE on existing attribute returns -EEXIST */ + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_USER, + "key1", "other", 5, XATTR_CREATE); + KUNIT_EXPECT_EQ(test, ret, -EEXIST); + + /* Query length (NULL buffer), too small buffer (-ERANGE), and read */ + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "key1", NULL, 0); + KUNIT_EXPECT_EQ(test, ret, 5); + + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "key1", buf, 4); + KUNIT_EXPECT_EQ(test, ret, -ERANGE); + + memset(buf, 0, sizeof(buf)); + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "key1", + buf, sizeof(buf)); + KUNIT_EXPECT_EQ(test, ret, 5); + KUNIT_EXPECT_MEMEQ(test, buf, "hello", 5); + + /* Direct ext4_xattr_ibody_get() check */ + memset(buf, 0, sizeof(buf)); + ret = ext4_xattr_ibody_get(inode, EXT4_XATTR_INDEX_USER, "key1", + buf, sizeof(buf)); + KUNIT_EXPECT_EQ(test, ret, 5); + KUNIT_EXPECT_MEMEQ(test, buf, "hello", 5); + + /* + * Setting the exact same value triggers the ext4_xattr_value_same() + * fastpath and skips dirtying the inode location. + */ + prev_dirty = ctx->mark_iloc_dirty_calls; + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_USER, + "key1", "hello", 5, XATTR_REPLACE); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, ctx->mark_iloc_dirty_calls, prev_dirty); +} + +/* + * Test 4: In-inode (ibody) replacement (same padded size vs different size), + * zero-length values, entry removal, and i_inline_off adjustment. + */ +static void test_xattr_ibody_replace_and_remove(struct kunit *test) +{ + struct xattr_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->primary.ei.vfs_inode; + struct ext4_inode *raw_inode = (struct ext4_inode *)ctx->primary.raw_buf; + struct ext4_xattr_ibody_header *hdr = IHDR(inode, raw_inode); + struct ext4_xattr_entry *e; + char buf[32]; + u16 offs_before, offs_after; + int ret; + + /* Create two entries in ibody: "a" (7 bytes -> 8 padded) and "b" (4 bytes) */ + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_USER, + "a", "1234567", 7, XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_USER, + "b", "wxyz", 4, XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + + e = IFIRST(hdr); + offs_before = le16_to_cpu(e->e_value_offs); + + /* + * Replace "a" with a 5-byte value (still 8 bytes padded): hits the + * in-place overwrite fastpath without shifting offsets, and zeroes + * the last 3 padding bytes. + */ + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_USER, + "a", "ABCDE", 5, XATTR_REPLACE); + KUNIT_ASSERT_EQ(test, ret, 0); + + offs_after = le16_to_cpu(e->e_value_offs); + KUNIT_EXPECT_EQ(test, offs_after, offs_before); + KUNIT_EXPECT_MEMEQ(test, (char *)IFIRST(hdr) + offs_after, + "ABCDE\0\0\0", 8); + + /* + * Replace "a" with a 12-byte value (different padded size): shifts + * "b"'s value and updates offsets while preserving "b"'s content. + */ + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_USER, + "a", "0123456789ab", 12, XATTR_REPLACE); + KUNIT_ASSERT_EQ(test, ret, 0); + + KUNIT_EXPECT_EQ(test, + ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "a", + buf, sizeof(buf)), + 12); + KUNIT_EXPECT_MEMEQ(test, buf, "0123456789ab", 12); + KUNIT_EXPECT_EQ(test, + ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "b", + buf, sizeof(buf)), + 4); + KUNIT_EXPECT_MEMEQ(test, buf, "wxyz", 4); + + /* Replace "a" with a zero-length value ("", size = 0) */ + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_USER, + "a", "", 0, XATTR_REPLACE); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, + ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "a", + buf, sizeof(buf)), + 0); + + /* + * Add system.data (inline data entry) and verify removing an earlier + * entry ("a") shifts system.data's entry header left and updates + * EXT4_I(inode)->i_inline_off. + */ + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_SYSTEM, + "data", "inlinedata", 10, + XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = ext4_find_inline_data_nolock(inode); + KUNIT_ASSERT_EQ(test, ret, 0); + ext4_set_inode_flag(inode, EXT4_INODE_INLINE_DATA); + ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + offs_before = EXT4_I(inode)->i_inline_off; + KUNIT_EXPECT_GT(test, offs_before, (u16)0); + + /* Remove "a": system.data entry header moves left by EXT4_XATTR_LEN(1) */ + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_USER, + "a", NULL, 0, XATTR_REPLACE); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_inline_off, + (u16)(offs_before - EXT4_XATTR_LEN(1))); + + /* Remove "b" and "system.data": emptying ibody clears h_magic and state */ + ext4_clear_inode_flag(inode, EXT4_INODE_INLINE_DATA); + ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_USER, + "b", NULL, 0, XATTR_REPLACE); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_NE(test, + ext4_test_inode_state(inode, EXT4_STATE_XATTR), 0); + + ret = ext4_xattr_set_handle(NULL, inode, EXT4_XATTR_INDEX_SYSTEM, + "data", NULL, 0, + XATTR_REPLACE); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(hdr->h_magic), 0U); + KUNIT_EXPECT_EQ(test, + ext4_test_inode_state(inode, EXT4_STATE_XATTR), 0); +} + +/* + * Test 5: External xattr block allocation, entry sorting, migration between + * ibody and external block, EXT4_XATTR_BLOCK_RESERVE enforcement, and external + * block header/CRC32C checksum validation. + */ +static void test_xattr_external_block_and_check(struct kunit *test) +{ + struct xattr_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->primary.ei.vfs_inode; + struct mock_block *blk; + struct ext4_xattr_header *bhdr; + struct ext4_xattr_entry *e1, *e2, *e3; + char val100[100]; + char *val796; + char buf[128]; + int ret; + + ext4_set_feature_metadata_csum(&ctx->sb); + memset(val100, 'V', sizeof(val100)); + + /* + * Start with a small attribute in ibody ("migr", 4 bytes), then grow + * it to 100 bytes (> 88-byte ibody space) so it migrates from ibody + * to a newly allocated external block. + */ + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "migr", + "tiny", 4, XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_file_acl, 0ULL); + + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "migr", + val100, sizeof(val100), XATTR_REPLACE); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_NE(test, EXT4_I(inode)->i_file_acl, 0ULL); + KUNIT_EXPECT_EQ(test, + ext4_test_inode_state(inode, EXT4_STATE_XATTR), 0); + + /* + * Add two more entries into the external block (by temporarily setting + * s_inode_size = 128 so ibody is bypassed) and verify external block + * entries are kept sorted by (e_name_index, e_name_len, e_name). + */ + ctx->sbi.s_inode_size = EXT4_GOOD_OLD_INODE_SIZE; + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "z", + "1", 1, XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "a", + "2", 1, XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + ctx->sbi.s_inode_size = TEST_INODE_SIZE; + + blk = find_mock_block(ctx, EXT4_I(inode)->i_file_acl); + KUNIT_ASSERT_NOT_NULL(test, blk); + bhdr = BHDR(&blk->bh); + e1 = BFIRST(&blk->bh); + e2 = EXT4_XATTR_NEXT(e1); + e3 = EXT4_XATTR_NEXT(e2); + + /* Length 1 ("a", "z") precede length 4 ("migr") */ + KUNIT_EXPECT_EQ(test, e1->e_name_len, 1); + KUNIT_EXPECT_EQ(test, e1->e_name[0], 'a'); + KUNIT_EXPECT_EQ(test, e2->e_name_len, 1); + KUNIT_EXPECT_EQ(test, e2->e_name[0], 'z'); + KUNIT_EXPECT_EQ(test, e3->e_name_len, 4); + KUNIT_EXPECT_MEMEQ(test, e3->e_name, "migr", 4); + + /* + * Verify external block validation and buffer_verified caching: + * 1) Reading sets buffer_verified. + * 2) Corrupting h_checksum while buffer_verified is set still succeeds + * because ext4_xattr_check_block() trusts buffer_verified. + * 3) Clearing buffer_verified exposes the bad checksum (-EFSBADCRC). + * 4) Corrupting h_blocks or h_magic returns -EFSCORRUPTED. + */ + clear_buffer_verified(&blk->bh); + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "migr", + buf, sizeof(buf)); + KUNIT_EXPECT_EQ(test, ret, 100); + KUNIT_EXPECT_NE(test, buffer_verified(&blk->bh), 0); + + bhdr->h_checksum ^= cpu_to_le32(1); + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "a", + buf, sizeof(buf)); + KUNIT_EXPECT_EQ(test, ret, 1); + + clear_buffer_verified(&blk->bh); + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "a", + buf, sizeof(buf)); + KUNIT_EXPECT_EQ(test, ret, -EFSBADCRC); + bhdr->h_checksum ^= cpu_to_le32(1); + + bhdr->h_blocks = cpu_to_le32(2); + clear_buffer_verified(&blk->bh); + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "a", + buf, sizeof(buf)); + KUNIT_EXPECT_EQ(test, ret, -EFSCORRUPTED); + bhdr->h_blocks = cpu_to_le32(1); + + /* + * Verify EXT4_XATTR_BLOCK_RESERVE (128 bytes on 1024B block) when + * EXT4_FEATURE_INCOMPAT_EA_INODE is enabled: + * With "migr" (100B), "a" (4B), and "z" (4B) in the block, min_offs is + * 1024 - 108 = 916 and free space is 820 bytes. Adding "r1" with a + * 796-byte value (816B total <= 820B free) leaves min_offs - new_size + * = 916 - 796 = 120 < 128 (EXT4_XATTR_BLOCK_RESERVE), so with ea_inode + * enabled and EA inode creation disabled it fails with -ENOSPC, + * whereas with ea_inode disabled it fits inline in the block. + */ + val796 = kunit_kmalloc(test, 796, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, val796); + memset(val796, 'R', 796); + ctx->sbi.s_inode_size = EXT4_GOOD_OLD_INODE_SIZE; + ext4_set_feature_ea_inode(&ctx->sb); + ctx->fail_new_inode = -ENOSPC; + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "r1", + val796, 796, XATTR_CREATE); + ctx->fail_new_inode = 0; + KUNIT_EXPECT_EQ(test, ret, -ENOSPC); + + ext4_clear_feature_ea_inode(&ctx->sb); + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "r1", + val796, 796, XATTR_CREATE); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_ASSERT_EQ(test, + ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "r1", + NULL, 0, XATTR_REPLACE), + 0); + ctx->sbi.s_inode_size = TEST_INODE_SIZE; + + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "a", + NULL, 0, XATTR_REPLACE); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "z", + NULL, 0, XATTR_REPLACE); + KUNIT_ASSERT_EQ(test, ret, 0); + + /* + * Removing the last entry ("migr") from the external block frees the + * external xattr block and clears i_file_acl to 0. + */ + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "migr", + NULL, 0, XATTR_REPLACE); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_file_acl, 0ULL); +} + +/* + * Test 6: External xattr block mb_cache deduplication, copy-on-write cloning + * when modifying a shared block, and EXT4_XATTR_REFCOUNT_MAX handling. + */ +static void test_xattr_block_dedup_and_cow(struct kunit *test) +{ + struct xattr_test_ctx *ctx = test->priv; + struct inode *inode1 = &ctx->primary.ei.vfs_inode; + struct inode *inode2 = &ctx->secondary.ei.vfs_inode; + struct mock_block *blk; + struct mb_cache_entry *ce; + char val100[100]; + ext4_fsblk_t shared_blk; + u32 hash; + int ret; + + ctx->sbi.s_ea_block_cache = ext4_xattr_create_cache(); + KUNIT_ASSERT_NOT_NULL(test, ctx->sbi.s_ea_block_cache); + + memset(val100, 'D', sizeof(val100)); + ret = ext4_xattr_set(inode1, EXT4_XATTR_INDEX_USER, "shared", + val100, sizeof(val100), XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + shared_blk = EXT4_I(inode1)->i_file_acl; + KUNIT_ASSERT_NE(test, shared_blk, 0ULL); + + /* Setting identical xattr on inode2 reuses shared_blk from mb_cache */ + ret = ext4_xattr_set(inode2, EXT4_XATTR_INDEX_USER, "shared", + val100, sizeof(val100), XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, EXT4_I(inode2)->i_file_acl, shared_blk); + + blk = find_mock_block(ctx, shared_blk); + KUNIT_ASSERT_NOT_NULL(test, blk); + KUNIT_EXPECT_EQ(test, le32_to_cpu(BHDR(&blk->bh)->h_refcount), 2U); + + /* + * Modifying the xattr on inode2 triggers copy-on-write: inode2 gets a + * new block and shared_blk's refcount drops back to 1. + */ + val100[0] = 'M'; + ret = ext4_xattr_set(inode2, EXT4_XATTR_INDEX_USER, "shared", + val100, sizeof(val100), XATTR_REPLACE); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_NE(test, EXT4_I(inode2)->i_file_acl, shared_blk); + KUNIT_EXPECT_EQ(test, le32_to_cpu(BHDR(&blk->bh)->h_refcount), 1U); + + /* + * Test EXT4_XATTR_REFCOUNT_MAX (1024) limit: + * Bump shared_blk's h_refcount to EXT4_XATTR_REFCOUNT_MAX (1024), + * then set the same xattr on inode2. Cache lookup must see + * ref >= EXT4_XATTR_REFCOUNT_MAX, clear MBE_REUSABLE_B, and allocate + * a separate block instead of exceeding 1024. + */ + val100[0] = 'D'; + BHDR(&blk->bh)->h_refcount = cpu_to_le32(EXT4_XATTR_REFCOUNT_MAX); + hash = le32_to_cpu(BHDR(&blk->bh)->h_hash); + + ret = ext4_xattr_set(inode2, EXT4_XATTR_INDEX_USER, "shared", + val100, sizeof(val100), XATTR_REPLACE); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_NE(test, EXT4_I(inode2)->i_file_acl, shared_blk); + + ce = mb_cache_entry_get(ctx->sbi.s_ea_block_cache, hash, shared_blk); + KUNIT_ASSERT_NOT_NULL(test, ce); + KUNIT_EXPECT_FALSE(test, test_bit(MBE_REUSABLE_B, &ce->e_flags)); + mb_cache_entry_put(ctx->sbi.s_ea_block_cache, ce); + + /* + * Removing the attribute on inode1 releases one reference on + * shared_blk (1024 -> 1023 = EXT4_XATTR_REFCOUNT_MAX - 1), which + * re-enables MBE_REUSABLE_B on the mb_cache entry. + */ + ret = ext4_xattr_set(inode1, EXT4_XATTR_INDEX_USER, "shared", + NULL, 0, XATTR_REPLACE); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(BHDR(&blk->bh)->h_refcount), + EXT4_XATTR_REFCOUNT_MAX - 1); + + ce = mb_cache_entry_get(ctx->sbi.s_ea_block_cache, hash, shared_blk); + KUNIT_ASSERT_NOT_NULL(test, ce); + KUNIT_EXPECT_TRUE(test, test_bit(MBE_REUSABLE_B, &ce->e_flags)); + mb_cache_entry_put(ctx->sbi.s_ea_block_cache, ce); +} + +/* + * Test 7: ext4_listxattr() across ibody and external block, and user/hurd/ + * trusted handler prefix and mount-option filtering. + */ +static void test_xattr_list_and_handlers(struct kunit *test) +{ + struct xattr_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->primary.ei.vfs_inode; + struct dentry *dentry = &ctx->root_dentry; + char val100[100]; + char list_buf[128]; + char val_buf[16]; + ssize_t list_len; + int ret; + + /* Handler get/set/list via user, hurd, and trusted handlers */ + ret = ext4_xattr_user_handler.set(&ext4_xattr_user_handler, + &nop_mnt_idmap, dentry, inode, + "ukey", "uval", 4, XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = ext4_xattr_user_handler.get(&ext4_xattr_user_handler, + dentry, inode, "ukey", + val_buf, sizeof(val_buf)); + KUNIT_EXPECT_EQ(test, ret, 4); + + ret = ext4_xattr_hurd_handler.set(&ext4_xattr_hurd_handler, + &nop_mnt_idmap, dentry, inode, + "hkey", "hval", 4, XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = ext4_xattr_hurd_handler.get(&ext4_xattr_hurd_handler, + dentry, inode, "hkey", + val_buf, sizeof(val_buf)); + KUNIT_EXPECT_EQ(test, ret, 4); + + /* Add a large attribute in external block via trusted handler */ + memset(val100, 'T', sizeof(val100)); + ret = ext4_xattr_trusted_handler.set(&ext4_xattr_trusted_handler, + &nop_mnt_idmap, dentry, inode, + "tkey", val100, sizeof(val100), + XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + + /* + * With XATTR_USER set: "user.ukey\0" (10) + "gnu.hkey\0" (9) + + * (if CAP_SYS_ADMIN) "trusted.tkey\0" (13). + */ + list_len = ext4_listxattr(dentry, NULL, 0); + KUNIT_EXPECT_GE(test, list_len, (ssize_t)19); + + /* Buffer too small by 1 byte returns -ERANGE */ + KUNIT_EXPECT_EQ(test, + ext4_listxattr(dentry, list_buf, list_len - 1), + (ssize_t)-ERANGE); + + memset(list_buf, 0, sizeof(list_buf)); + KUNIT_EXPECT_EQ(test, + ext4_listxattr(dentry, list_buf, sizeof(list_buf)), + list_len); + KUNIT_EXPECT_MEMEQ(test, list_buf, "user.ukey\0gnu.hkey\0", 19); + + /* + * Clearing XATTR_USER mount option disables user and hurd handlers + * (-EOPNOTSUPP on get/set and filtered out of ext4_listxattr). + */ + clear_opt(&ctx->sb, XATTR_USER); + KUNIT_EXPECT_FALSE(test, ext4_xattr_user_handler.list(dentry)); + KUNIT_EXPECT_FALSE(test, ext4_xattr_hurd_handler.list(dentry)); + KUNIT_EXPECT_EQ(test, + ext4_xattr_user_handler.get(&ext4_xattr_user_handler, + dentry, inode, "ukey", + val_buf, sizeof(val_buf)), + -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, + ext4_xattr_user_handler.set(&ext4_xattr_user_handler, + &nop_mnt_idmap, dentry, + inode, "ukey", "x", 1, 0), + -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, + ext4_xattr_hurd_handler.get(&ext4_xattr_hurd_handler, + dentry, inode, "hkey", + val_buf, sizeof(val_buf)), + -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, + ext4_xattr_hurd_handler.set(&ext4_xattr_hurd_handler, + &nop_mnt_idmap, dentry, + inode, "hkey", "x", 1, 0), + -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, ext4_listxattr(dentry, NULL, 0), + capable(CAP_SYS_ADMIN) ? (ssize_t)13 : (ssize_t)0); + set_opt(&ctx->sb, XATTR_USER); +} + +/* + * Test 8: Large xattr inodes (ea_inode feature) multi-block write/read, + * 64-bit refcount & hash encoding, mb_cache deduplication across inodes, + * reference decrement to 0, and ext4_evict_ea_inode(). + */ +static void test_xattr_ea_inode_lifecycle_and_dedup(struct kunit *test) +{ + struct xattr_test_ctx *ctx = test->priv; + struct inode *inode1 = &ctx->primary.ei.vfs_inode; + struct inode *inode2 = &ctx->secondary.ei.vfs_inode; + struct inode *ea_inode; + struct ext4_inode *raw1 = (struct ext4_inode *)ctx->primary.raw_buf; + struct ext4_xattr_entry *e1; + char *large_val, *read_buf; + const size_t large_len = 1500; /* Spans 2 1024-byte blocks */ + unsigned int ea_ino; + u64 refcount; + int i, ret; + + ext4_set_feature_ea_inode(&ctx->sb); + ctx->sbi.s_ea_inode_cache = ext4_xattr_create_cache(); + KUNIT_ASSERT_NOT_NULL(test, ctx->sbi.s_ea_inode_cache); + ext4_init_ea_inode_work(&ctx->sbi); + + large_val = kunit_kmalloc(test, large_len, GFP_KERNEL); + read_buf = kunit_kzalloc(test, large_len, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, large_val); + KUNIT_ASSERT_NOT_NULL(test, read_buf); + for (i = 0; i < large_len; i++) + large_val[i] = (char)('A' + (i % 26)); + + /* Create 1500-byte xattr on inode1: stored in a new EA inode */ + ret = ext4_xattr_set(inode1, EXT4_XATTR_INDEX_USER, "big", + large_val, large_len, XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + + e1 = IFIRST(IHDR(inode1, raw1)); + ea_ino = le32_to_cpu(e1->e_value_inum); + KUNIT_ASSERT_EQ(test, ea_ino, (unsigned int)TEST_FIRST_EA_INO); + KUNIT_EXPECT_EQ(test, le16_to_cpu(e1->e_value_offs), 0U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(e1->e_value_size), + (u32)large_len); + + ea_inode = &ctx->ea_inodes[0].ei.vfs_inode; + refcount = ((u64)inode_get_ctime_sec(ea_inode) << 32) | + (u32)inode_peek_iversion_raw(ea_inode); + KUNIT_EXPECT_EQ(test, refcount, 1ULL); + KUNIT_EXPECT_EQ(test, ea_inode->i_nlink, 1U); + + /* Read back multi-block EA inode value via ext4_xattr_get() */ + ret = ext4_xattr_get(inode1, EXT4_XATTR_INDEX_USER, "big", + read_buf, large_len); + KUNIT_ASSERT_EQ(test, ret, (int)large_len); + KUNIT_EXPECT_MEMEQ(test, read_buf, large_val, large_len); + + /* + * Setting the identical 1500-byte value on inode2 deduplicates via + * s_ea_inode_cache and increments ea_inode's refcount to 2. + */ + ret = ext4_xattr_set(inode2, EXT4_XATTR_INDEX_USER, "big2", + large_val, large_len, XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + + refcount = ((u64)inode_get_ctime_sec(ea_inode) << 32) | + (u32)inode_peek_iversion_raw(ea_inode); + KUNIT_EXPECT_EQ(test, refcount, 2ULL); + + /* Removing from inode1 drops refcount to 1; i_nlink remains 1 */ + ret = ext4_xattr_set(inode1, EXT4_XATTR_INDEX_USER, "big", + NULL, 0, XATTR_REPLACE); + KUNIT_ASSERT_EQ(test, ret, 0); + refcount = ((u64)inode_get_ctime_sec(ea_inode) << 32) | + (u32)inode_peek_iversion_raw(ea_inode); + KUNIT_EXPECT_EQ(test, refcount, 1ULL); + KUNIT_EXPECT_EQ(test, ea_inode->i_nlink, 1U); + + /* + * Removing from inode2 drops refcount to 0 and clears i_nlink to 0. + * Also verify ext4_evict_ea_inode() removes it from s_ea_inode_cache. + */ + ret = ext4_xattr_set(inode2, EXT4_XATTR_INDEX_USER, "big2", + NULL, 0, XATTR_REPLACE); + KUNIT_ASSERT_EQ(test, ret, 0); + refcount = ((u64)inode_get_ctime_sec(ea_inode) << 32) | + (u32)inode_peek_iversion_raw(ea_inode); + KUNIT_EXPECT_EQ(test, refcount, 0ULL); + KUNIT_EXPECT_EQ(test, ea_inode->i_nlink, 0U); + + ext4_evict_ea_inode(ea_inode); +} + +/* + * Test 9: EA inode hash verification (including legacy signed-char name hash + * fallback), ext4_xattr_inode_iget() corruption checks, and Lustre-style + * EA inode compatibility. + */ +static void test_xattr_ea_inode_validation_and_compat(struct kunit *test) +{ + struct xattr_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->primary.ei.vfs_inode; + struct inode *ea_inode; + struct ext4_inode *raw = (struct ext4_inode *)ctx->primary.raw_buf; + struct ext4_xattr_entry *e; + static const char signed_name[] = "\x80\xfe"; + const size_t val_len = 1000; + char *val, *buf; + u32 val_hash, signed_e_hash = 0; + __le32 orig_e_hash; + int i, ret; + + ext4_set_feature_ea_inode(&ctx->sb); + val = kunit_kmalloc(test, val_len, GFP_KERNEL); + buf = kunit_kzalloc(test, val_len, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, val); + KUNIT_ASSERT_NOT_NULL(test, buf); + memset(val, 'S', val_len); + + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, signed_name, + val, val_len, XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + + e = IFIRST(IHDR(inode, raw)); + ea_inode = &ctx->ea_inodes[0].ei.vfs_inode; + orig_e_hash = e->e_hash; + + /* + * Compute the legacy signed-char entry hash for "\x80\xfe" and verify + * ext4_xattr_inode_verify_hashes() accepts it as a valid fallback. + */ + val_hash = (u32)inode_get_atime_sec(ea_inode); + for (i = 0; i < (int)strlen(signed_name); i++) { + signed_e_hash = (signed_e_hash << 5) ^ + (signed_e_hash >> 27) ^ + (signed char)signed_name[i]; + } + signed_e_hash = (signed_e_hash << 16) ^ + (signed_e_hash >> 16) ^ val_hash; + e->e_hash = cpu_to_le32(signed_e_hash); + + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, signed_name, + buf, val_len); + KUNIT_EXPECT_EQ(test, ret, (int)val_len); + + /* Truly corrupted entry hash is rejected with -EFSCORRUPTED */ + e->e_hash = cpu_to_le32(signed_e_hash ^ 0x12345678U); + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, signed_name, + buf, val_len); + KUNIT_EXPECT_EQ(test, ret, -EFSCORRUPTED); + e->e_hash = orig_e_hash; + + /* Corrupted value hash stored in ea_inode->i_atime is rejected */ + inode_set_atime(ea_inode, val_hash ^ 1, 0); + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, signed_name, + buf, val_len); + KUNIT_EXPECT_EQ(test, ret, -EFSCORRUPTED); + inode_set_atime(ea_inode, val_hash, 0); + + /* Size mismatch between ea_inode->i_size and entry->e_value_size */ + i_size_write(ea_inode, val_len - 1); + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, signed_name, + buf, val_len); + KUNIT_EXPECT_EQ(test, ret, -EFSCORRUPTED); + i_size_write(ea_inode, val_len); + + /* Invalid i_nlink (0 or 2) on active EA inode returns -EFSCORRUPTED */ + set_nlink(ea_inode, 2); + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, signed_name, + buf, val_len); + KUNIT_EXPECT_EQ(test, ret, -EFSCORRUPTED); + set_nlink(ea_inode, 1); + + /* Self-referencing e_value_inum == parent->i_ino returns -EFSCORRUPTED */ + e->e_value_inum = cpu_to_le32(inode->i_ino); + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, signed_name, + buf, val_len); + KUNIT_EXPECT_EQ(test, ret, -EFSCORRUPTED); + e->e_value_inum = cpu_to_le32(ea_inode->i_ino); + + /* + * Lustre-style old EA inode compatibility: when e_hash != ea_inode + * hash, but parent ino (stored in i_mtime) and generation (stored in + * i_generation) match parent, ext4_xattr_inode_iget() sets + * EXT4_STATE_LUSTRE_EA_INODE and forces ref_count = 1. + */ + e->e_hash = 0; + inode->i_generation = 42; + ea_inode->i_generation = 42; + inode_set_mtime(ea_inode, inode->i_ino, 0); + inode_set_ctime(ea_inode, 0, 0); + inode_set_iversion_raw(ea_inode, 0); + /* Even with initial ref_count = 0, Lustre compat sets ref = 1 */ + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, signed_name, + buf, val_len); + KUNIT_EXPECT_EQ(test, ret, (int)val_len); + KUNIT_EXPECT_NE(test, + ext4_test_inode_state(ea_inode, + EXT4_STATE_LUSTRE_EA_INODE), + 0); +} + +/* + * Test 10: ext4_get_inode_usage(), credit calculation, handle credit check, + * ext4_expand_extra_isize_ea(), and ext4_xattr_delete_inode(). + */ +static void test_xattr_credits_usage_expand_and_delete(struct kunit *test) +{ + struct xattr_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->primary.ei.vfs_inode; + struct ext4_inode *raw = (struct ext4_inode *)ctx->primary.raw_buf; + journal_t *fake_journal; + handle_t fake_handle = { + .h_reserved = 1, + .h_total_credits = 1, + }; + const size_t large_len = 1000; + char *large_val; + char val28[28]; + char buf[64]; + qsize_t usage = 0; + int credits_create, credits_replace, credits_out = -1; + int ret; + + fake_journal = kunit_kzalloc(test, sizeof(*fake_journal), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, fake_journal); + fake_journal->j_revoke_records_per_block = 64; + fake_handle.h_journal = fake_journal; + + large_val = kunit_kmalloc(test, large_len, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, large_val); + memset(large_val, 'L', large_len); + + /* + * 1. Credit calculation and insufficient handle credits check + */ + credits_create = __ext4_xattr_set_credits(&ctx->sb, inode, NULL, + 100, true); + KUNIT_EXPECT_GT(test, credits_create, 0); + + ext4_set_feature_ea_inode(&ctx->sb); + credits_create = __ext4_xattr_set_credits(&ctx->sb, inode, NULL, + 1500, true); + credits_replace = __ext4_xattr_set_credits(&ctx->sb, inode, NULL, + 1500, false); + KUNIT_EXPECT_GT(test, credits_replace, credits_create); + + /* Without a journal (s_journal == NULL), credits_out is 0 */ + ret = ext4_xattr_set_credits(inode, 1500, true, &credits_out); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, credits_out, 0); + + /* With s_journal set, ext4_xattr_set_credits() returns credits_create */ + ctx->sbi.s_journal = fake_journal; + ret = ext4_xattr_set_credits(inode, 1500, true, &credits_out); + ctx->sbi.s_journal = NULL; + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, credits_out, credits_create); + + /* Handle with only 1 buffer credit (< credits) fails with -ENOSPC */ + ret = ext4_xattr_set_handle(&fake_handle, inode, EXT4_XATTR_INDEX_USER, + "k", "v", 1, XATTR_CREATE); + KUNIT_EXPECT_EQ(test, ret, -ENOSPC); + + /* + * 2. ext4_expand_extra_isize_ea(): + * Put "keep" (4B -> 24B total) and "evict" (28B -> 52B total) in + * ibody (88B usable, leaving 12B free). + * First expand i_extra_isize from 32 -> 40 (8 bytes <= 12B free): + * shifts ibody entries in-place without allocating an external block. + * Then expand i_extra_isize from 40 -> 72 (32 bytes > 4B free): + * "keep" (24 + 4 = 28 < 32) is too small alone, so "evict" (52 + 4 >= 32) + * is moved to an external xattr block while "keep" stays in ibody! + */ + ext4_clear_feature_ea_inode(&ctx->sb); + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "keep", + "1234", 4, XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + memset(val28, 'E', sizeof(val28)); + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "evict", + val28, sizeof(val28), XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_file_acl, 0ULL); + + /* In-place ibody shift (32 -> 40) */ + ret = ext4_expand_extra_isize_ea(inode, 40, raw, NULL); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_extra_isize, (u16)40); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_file_acl, 0ULL); + + /* Eviction of "evict" to external block (40 -> 72) */ + ret = ext4_expand_extra_isize_ea(inode, 72, raw, NULL); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_extra_isize, (u16)72); + KUNIT_EXPECT_NE(test, EXT4_I(inode)->i_file_acl, 0ULL); + + /* Both "keep" (in ibody) and "evict" (in external block) remain readable */ + KUNIT_EXPECT_EQ(test, + ext4_xattr_ibody_get(inode, EXT4_XATTR_INDEX_USER, + "keep", buf, sizeof(buf)), + 4); + KUNIT_EXPECT_EQ(test, + ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, + "evict", buf, sizeof(buf)), + 28); + + /* + * 3. ext4_get_inode_usage() and ext4_xattr_delete_inode(): + * Add a 1000-byte EA inode attribute ("large_ea") and check that + * ext4_get_inode_usage() accounts for 1 (parent inode) + 1 (EA inode) + * = 2 inodes, and ext4_xattr_delete_inode() frees the external block + * and drops the EA inode reference to 0. + */ + ext4_set_feature_ea_inode(&ctx->sb); + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "large_ea", + large_val, large_len, XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + + down_read(&EXT4_I(inode)->xattr_sem); + ret = ext4_get_inode_usage(inode, &usage); + up_read(&EXT4_I(inode)->xattr_sem); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, usage, (qsize_t)2); + + ret = ext4_xattr_delete_inode(NULL, inode, 0); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_file_acl, 0ULL); + KUNIT_EXPECT_EQ(test, ctx->ea_inodes[0].ei.vfs_inode.i_nlink, 0U); +} + +/* + * Test 11: Error injection and rollback paths across inode location lookup, + * external block allocation/getblk/bread/dirty_metadata, and EA inode + * creation/write/lookup. + */ +static void test_xattr_error_injection(struct kunit *test) +{ + struct xattr_test_ctx *ctx = test->priv; + struct inode *inode = &ctx->primary.ei.vfs_inode; + const size_t large_len = 1000; + char *large_val; + char val100[100]; + char buf[128]; + unsigned int prev_free; + int ret; + + large_val = kunit_kmalloc(test, large_len, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, large_val); + memset(large_val, 'F', large_len); + memset(val100, 'B', sizeof(val100)); + + /* 1. ext4_get_inode_loc() failure on set and get */ + ctx->fail_get_inode_loc = -EIO; + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "k", + "v", 1, XATTR_CREATE); + KUNIT_EXPECT_EQ(test, ret, -EIO); + + ext4_set_inode_state(inode, EXT4_STATE_XATTR); + ret = ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "k", + buf, sizeof(buf)); + KUNIT_EXPECT_EQ(test, ret, -EIO); + ext4_clear_inode_state(inode, EXT4_STATE_XATTR); + ctx->fail_get_inode_loc = 0; + + /* 2. ext4_mark_iloc_dirty() failure on set */ + ctx->fail_mark_iloc_dirty = -EIO; + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "k", + "v", 1, XATTR_CREATE); + ctx->fail_mark_iloc_dirty = 0; + KUNIT_EXPECT_EQ(test, ret, -EIO); + /* Clean up the entry written to raw_buf before mark_iloc_dirty */ + KUNIT_ASSERT_EQ(test, + ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "k", + NULL, 0, XATTR_REPLACE), + 0); + + /* 3. External block allocation failure (-ENOSPC) */ + ctx->fail_alloc_block = -ENOSPC; + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "blk", + val100, sizeof(val100), XATTR_CREATE); + ctx->fail_alloc_block = 0; + KUNIT_EXPECT_EQ(test, ret, -ENOSPC); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_file_acl, 0ULL); + + /* + * 4. ext4_xattr_getblk() failure (-ENOMEM) after block allocation must + * free the newly allocated block via ext4_free_blocks(). + */ + prev_free = ctx->free_block_calls; + ctx->fail_xattr_getblk = true; + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "blk", + val100, sizeof(val100), XATTR_CREATE); + ctx->fail_xattr_getblk = false; + KUNIT_EXPECT_EQ(test, ret, -ENOMEM); + KUNIT_EXPECT_EQ(test, ctx->free_block_calls, prev_free + 1); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_file_acl, 0ULL); + + /* 5. ext4_handle_dirty_metadata() failure when creating external block */ + ctx->fail_dirty_metadata = -EIO; + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "blk", + val100, sizeof(val100), XATTR_CREATE); + ctx->fail_dirty_metadata = 0; + KUNIT_EXPECT_EQ(test, ret, -EIO); + KUNIT_EXPECT_EQ(test, EXT4_I(inode)->i_file_acl, 0ULL); + + /* Successfully create external block, then test ext4_sb_bread() failure */ + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "blk", + val100, sizeof(val100), XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + + ctx->fail_sb_bread = -EIO; + KUNIT_EXPECT_EQ(test, + ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "blk", + buf, sizeof(buf)), + -EIO); + KUNIT_EXPECT_EQ(test, + ext4_listxattr(&ctx->root_dentry, buf, sizeof(buf)), + (ssize_t)-EIO); + KUNIT_EXPECT_EQ(test, ext4_xattr_delete_inode(NULL, inode, 0), -EIO); + ctx->fail_sb_bread = 0; + + /* + * 6. EA inode block allocation failure in ext4_xattr_inode_write() + * must clean up the newly created EA inode (dropping its i_nlink to 0). + */ + ext4_set_feature_ea_inode(&ctx->sb); + ctx->fail_alloc_block = -ENOSPC; + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "big_err", + large_val, large_len, XATTR_CREATE); + ctx->fail_alloc_block = 0; + KUNIT_EXPECT_EQ(test, ret, -ENOSPC); + KUNIT_EXPECT_TRUE(test, ctx->ea_inodes[0].allocated); + KUNIT_EXPECT_EQ(test, ctx->ea_inodes[0].ei.vfs_inode.i_nlink, 0U); + + /* 7. Successfully create EA inode, then test __ext4_iget() and ext4_getblk() failure */ + ret = ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER, "big_ok", + large_val, large_len, XATTR_CREATE); + KUNIT_ASSERT_EQ(test, ret, 0); + + ctx->fail_iget = -EIO; + KUNIT_EXPECT_EQ(test, + ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "big_ok", + large_val, large_len), + -EIO); + ctx->fail_iget = 0; + + ctx->fail_getblk = -EIO; + KUNIT_EXPECT_EQ(test, + ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER, "big_ok", + large_val, large_len), + -EIO); + ctx->fail_getblk = 0; +} + +static struct kunit_case xattr_test_cases[] = { + KUNIT_CASE(test_xattr_macros_and_locking), + KUNIT_CASE_PARAM(test_xattr_check_inode, xattr_check_gen_params), + KUNIT_CASE(test_xattr_ibody_basic_and_flags), + KUNIT_CASE(test_xattr_ibody_replace_and_remove), + KUNIT_CASE(test_xattr_external_block_and_check), + KUNIT_CASE(test_xattr_block_dedup_and_cow), + KUNIT_CASE(test_xattr_list_and_handlers), + KUNIT_CASE(test_xattr_ea_inode_lifecycle_and_dedup), + KUNIT_CASE(test_xattr_ea_inode_validation_and_compat), + KUNIT_CASE(test_xattr_credits_usage_expand_and_delete), + KUNIT_CASE(test_xattr_error_injection), + {} +}; + +static struct kunit_suite xattr_test_suite = { + .name = "ext4_xattr_test", + .init = xattr_test_init, + .exit = xattr_test_exit, + .test_cases = xattr_test_cases, +}; + +kunit_test_suites(&xattr_test_suite); + +MODULE_LICENSE("GPL"); diff --git a/fs/ext4/xattr.c b/fs/ext4/xattr.c index 5c310747b96500..277731c424a091 100644 --- a/fs/ext4/xattr.c +++ b/fs/ext4/xattr.c @@ -57,6 +57,7 @@ #include #include #include +#include #include "ext4_jbd2.h" #include "ext4.h" #include "xattr.h" @@ -107,6 +108,7 @@ const struct xattr_handler * const ext4_xattr_handlers[] = { &ext4_xattr_hurd_handler, NULL }; +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_handlers); #define EA_BLOCK_CACHE(inode) (((struct ext4_sb_info *) \ inode->i_sb->s_fs_info)->s_ea_block_cache) @@ -169,6 +171,14 @@ static void ext4_xattr_block_csum_set(struct inode *inode, bh->b_blocknr, BHDR(bh)); } +struct buffer_head *ext4_xattr_getblk(struct super_block *sb, + ext4_fsblk_t block) +{ + KUNIT_STATIC_STUB_REDIRECT(ext4_xattr_getblk, sb, block); + return sb_getblk(sb, block); +} +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_getblk); + static inline const char *ext4_xattr_prefix(int name_index, struct dentry *dentry) { @@ -315,6 +325,7 @@ __xattr_check_inode(struct inode *inode, struct ext4_xattr_ibody_header *header, return check_xattrs(inode, NULL, IFIRST(header), end, IFIRST(header), function, line); } +EXPORT_SYMBOL_FOR_EXT4_TEST(__xattr_check_inode); static int xattr_find_entry(struct inode *inode, struct ext4_xattr_entry **pentry, @@ -493,6 +504,7 @@ void ext4_evict_ea_inode(struct inode *inode) mb_cache_entry_put(EA_INODE_CACHE(inode), oe); } } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_evict_ea_inode); static int ext4_xattr_inode_verify_hashes(struct inode *ea_inode, @@ -693,6 +705,7 @@ ext4_xattr_ibody_get(struct inode *inode, int name_index, const char *name, brelse(iloc.bh); return error; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_ibody_get); /* * ext4_xattr_get() @@ -725,6 +738,7 @@ ext4_xattr_get(struct inode *inode, int name_index, const char *name, up_read(&EXT4_I(inode)->xattr_sem); return error; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_get); static int ext4_xattr_list_entries(struct dentry *dentry, struct ext4_xattr_entry *entry, @@ -841,6 +855,7 @@ ext4_listxattr(struct dentry *dentry, char *buffer, size_t buffer_size) up_read(&EXT4_I(d_inode(dentry))->xattr_sem); return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_listxattr); /* * If the EXT4_FEATURE_COMPAT_EXT_ATTR feature of this file system is @@ -912,6 +927,7 @@ int ext4_get_inode_usage(struct inode *inode, qsize_t *usage) brelse(bh); return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_inode_usage); static inline size_t round_up_cluster(struct inode *inode, size_t length) { @@ -1029,6 +1045,7 @@ int __ext4_xattr_set_credits(struct super_block *sb, struct inode *inode, } return credits; } +EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_xattr_set_credits); static int ext4_xattr_inode_update_ref(handle_t *handle, struct inode *ea_inode, int ref_change) @@ -1712,6 +1729,18 @@ static int ext4_xattr_set_entry(struct ext4_xattr_info *i, } } + if (!s->not_found && here->e_value_size && !here->e_value_inum) { + size_t offs = le16_to_cpu(here->e_value_offs); + + if (offs < min_offs) { + EXT4_ERROR_INODE(inode, + "corrupted xattr: value offset %zu < min_offs %zu", + offs, min_offs); + ret = -EFSCORRUPTED; + goto out; + } + } + /* * Getting access to old and new ea inodes is subject to failures. * Finish that work before doing any modifications to the xattr data. @@ -2113,6 +2142,24 @@ ext4_xattr_block_set(handle_t *handle, struct inode *inode, mb_cache_entry_touch(ea_block_cache, ce); mb_cache_entry_put(ea_block_cache, ce); ce = NULL; + if (ea_inode && !(bs->bh && s->base == bs->bh->b_data)) { + /* + * The cached block already owns its EA inode + * references. For an in-place update the lookup + * reference belongs to the old block and is + * dropped when that block is released. + */ + error = ext4_xattr_inode_dec_ref(handle, + ea_inode); + if (error) { + EXT4_ERROR_INODE(inode, + "dec ref error=%d", + error); + ext4_put_ea_inode(ea_inode); + ea_inode = NULL; + goto cleanup; + } + } } else if (bs->bh && s->base == bs->bh->b_data) { /* We were modifying this block in-place. */ ea_bdebug(bs->bh, "keeping this block"); @@ -2136,7 +2183,7 @@ ext4_xattr_block_set(handle_t *handle, struct inode *inode, ea_idebug(inode, "creating block %llu", (unsigned long long)block); - new_bh = sb_getblk(sb, block); + new_bh = ext4_xattr_getblk(sb, block); if (unlikely(!new_bh)) { error = -ENOMEM; getblk_failed: @@ -2252,6 +2299,7 @@ int ext4_xattr_ibody_find(struct inode *inode, struct ext4_xattr_info *i, } return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_ibody_find); int ext4_xattr_ibody_set(handle_t *handle, struct inode *inode, struct ext4_xattr_info *i, @@ -2274,6 +2322,14 @@ int ext4_xattr_ibody_set(handle_t *handle, struct inode *inode, if (IS_ERR(ea_inode)) return PTR_ERR(ea_inode); } + + /* + * Make sure xattr space is properly initialized so that + * IS_LAST_ENTRY() returns true for its first entry + */ + if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR)) + *(__u32 *)s->first = 0; + error = ext4_xattr_set_entry(i, s, handle, inode, ea_inode, false /* is_block */); if (error) { @@ -2302,6 +2358,7 @@ int ext4_xattr_ibody_set(handle_t *handle, struct inode *inode, ext4_put_ea_inode(ea_inode); return 0; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_ibody_set); static int ext4_xattr_value_same(struct ext4_xattr_search *s, struct ext4_xattr_info *i) @@ -2499,6 +2556,7 @@ ext4_xattr_set_handle(handle_t *handle, struct inode *inode, int name_index, ext4_write_unlock_xattr(inode, &no_expand); return error; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_set_handle); int ext4_xattr_set_credits(struct inode *inode, size_t value_len, bool is_create, int *credits) @@ -2526,6 +2584,7 @@ int ext4_xattr_set_credits(struct inode *inode, size_t value_len, up_read(&EXT4_I(inode)->xattr_sem); return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_set_credits); /* * ext4_xattr_set() @@ -2574,6 +2633,7 @@ ext4_xattr_set(struct inode *inode, int name_index, const char *name, return error; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_set); /* * Shift the EA entries in the inode to create space for the increased @@ -2865,6 +2925,7 @@ int ext4_expand_extra_isize_ea(struct inode *inode, int new_extra_isize, } return error; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_expand_extra_isize_ea); /* * ext4_xattr_delete_inode() @@ -2973,6 +3034,7 @@ int ext4_xattr_delete_inode(handle_t *handle, struct inode *inode, brelse(bh); return error; } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_delete_inode); /* * Worker function for deferred EA inode iput. Processes all inodes queued @@ -3026,12 +3088,14 @@ void ext4_put_ea_inode(struct inode *inode) */ schedule_delayed_work(&EXT4_SB(inode->i_sb)->s_ea_inode_work, 1); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_put_ea_inode); void ext4_init_ea_inode_work(struct ext4_sb_info *sbi) { init_llist_head(&sbi->s_ea_inode_to_free); INIT_DELAYED_WORK(&sbi->s_ea_inode_work, ext4_ea_inode_work); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_init_ea_inode_work); /* * ext4_xattr_block_cache_insert() @@ -3229,10 +3293,12 @@ ext4_xattr_create_cache(void) { return mb_cache_create(HASH_BUCKET_BITS); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_create_cache); void ext4_xattr_destroy_cache(struct mb_cache *cache) { if (cache) mb_cache_destroy(cache); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_destroy_cache); diff --git a/fs/ext4/xattr.h b/fs/ext4/xattr.h index 821dc6a50e51e7..1a72e68cea0c78 100644 --- a/fs/ext4/xattr.h +++ b/fs/ext4/xattr.h @@ -229,3 +229,5 @@ static inline void ext4_xattr_inode_set_class(struct inode *ea_inode) { } #endif extern int ext4_get_inode_usage(struct inode *inode, qsize_t *usage); +extern struct buffer_head *ext4_xattr_getblk(struct super_block *sb, + ext4_fsblk_t block); diff --git a/fs/ext4/xattr_hurd.c b/fs/ext4/xattr_hurd.c index a3ecbff72b1015..9cd42f6546b5a1 100644 --- a/fs/ext4/xattr_hurd.c +++ b/fs/ext4/xattr_hurd.c @@ -50,3 +50,7 @@ const struct xattr_handler ext4_xattr_hurd_handler = { .get = ext4_xattr_hurd_get, .set = ext4_xattr_hurd_set, }; + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_hurd_handler); +#endif diff --git a/fs/ext4/xattr_security.c b/fs/ext4/xattr_security.c index af5b8a93fed13a..c3919643d64f27 100644 --- a/fs/ext4/xattr_security.c +++ b/fs/ext4/xattr_security.c @@ -4,6 +4,7 @@ * Handler for storing security labels as extended attributes. */ +#include #include #include #include @@ -55,9 +56,12 @@ int ext4_init_security(handle_t *handle, struct inode *inode, struct inode *dir, const struct qstr *qstr) { + KUNIT_STATIC_STUB_REDIRECT(ext4_init_security, + handle, inode, dir, qstr); return security_inode_init_security(inode, dir, qstr, &ext4_initxattrs, handle); } +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_init_security); const struct xattr_handler ext4_xattr_security_handler = { .prefix = XATTR_SECURITY_PREFIX, diff --git a/fs/ext4/xattr_trusted.c b/fs/ext4/xattr_trusted.c index 458e1982ef83a3..d5d033ba75949e 100644 --- a/fs/ext4/xattr_trusted.c +++ b/fs/ext4/xattr_trusted.c @@ -45,3 +45,7 @@ const struct xattr_handler ext4_xattr_trusted_handler = { .get = ext4_xattr_trusted_get, .set = ext4_xattr_trusted_set, }; + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_trusted_handler); +#endif diff --git a/fs/ext4/xattr_user.c b/fs/ext4/xattr_user.c index ad35215f66104c..26087e98677be6 100644 --- a/fs/ext4/xattr_user.c +++ b/fs/ext4/xattr_user.c @@ -48,3 +48,7 @@ const struct xattr_handler ext4_xattr_user_handler = { .get = ext4_xattr_user_get, .set = ext4_xattr_user_set, }; + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_xattr_user_handler); +#endif diff --git a/fs/fuse/dev.c b/fs/fuse/dev.c index a5c08a00cf83b0..b198cc729cbaee 100644 --- a/fs/fuse/dev.c +++ b/fs/fuse/dev.c @@ -80,6 +80,10 @@ void fuse_chan_set_initialized(struct fuse_chan *fch, struct fuse_chan_param *pa fuse_uring_conn_init(fch); } + /* An aborted channel is also marked initialized to wake waiters. */ + if (!param && fch->connected) + fch->conn_refused = true; + /* Pairs with smp_load_acquire() readers of fch->initialized */ smp_store_release(&fch->initialized, 1); wake_up_all(&fch->blocked_waitq); @@ -130,6 +134,10 @@ static struct fuse_req *fuse_get_req(struct fuse_chan *fch, bool for_background) if (!fch->connected) goto out; + err = -ECONNREFUSED; + if (fch->conn_refused) + goto out; + req = fuse_request_alloc(fch, GFP_KERNEL); err = -ENOMEM; if (!req) { @@ -1108,7 +1116,9 @@ static int fuse_ref_folio(struct fuse_copy_state *cs, struct folio *folio, if (cs->nr_segs >= cs->pipe->max_usage) return -EIO; - folio_get(folio); + if (!folio_get_checked(folio)) + return -EFAULT; + err = unlock_request(cs->req); if (err) { folio_put(folio); diff --git a/fs/fuse/dir.c b/fs/fuse/dir.c index da23ccd8685cfe..a04d93d5fc4473 100644 --- a/fs/fuse/dir.c +++ b/fs/fuse/dir.c @@ -644,13 +644,17 @@ static struct dentry *fuse_lookup(struct inode *dir, struct dentry *entry, if (inode && get_node_id(inode) == FUSE_ROOT_ID) goto out_iput; + /* Set before the dentry is visible, or a racing lookup invalidates it */ + fuse_dentry_set_epoch(entry, epoch); newent = d_splice_alias(inode, entry); err = PTR_ERR(newent); if (IS_ERR(newent)) goto out_err; - entry = newent ? newent : entry; - fuse_dentry_set_epoch(entry, epoch); + if (newent) { + entry = newent; + fuse_dentry_set_epoch(entry, epoch); + } if (outarg_valid) fuse_change_entry_timeout(entry, &outarg); else @@ -907,8 +911,8 @@ static int fuse_create_open(const struct mnt_idmap *idmap, struct inode *dir, goto out_err; } kfree(forget); - d_instantiate(entry, inode); fuse_dentry_set_epoch(entry, epoch); + d_instantiate(entry, inode); fuse_change_entry_timeout(entry, &outentry); fuse_dir_changed(dir); err = generic_file_open(inode, file); @@ -1030,6 +1034,7 @@ static struct dentry *create_new_entry(const struct mnt_idmap *idmap, struct fus fuse_chan_queue_forget(fm->fc->chan, forget, outarg.nodeid, 1); return ERR_PTR(-ENOMEM); } + fuse_dentry_set_epoch(entry, epoch); kfree(forget); d = d_splice_alias(inode, entry); @@ -1040,7 +1045,6 @@ static struct dentry *create_new_entry(const struct mnt_idmap *idmap, struct fus fuse_dentry_set_epoch(d, epoch); fuse_change_entry_timeout(d, &outarg); } else { - fuse_dentry_set_epoch(entry, epoch); fuse_change_entry_timeout(entry, &outarg); } fuse_dir_changed(dir); diff --git a/fs/fuse/file.c b/fs/fuse/file.c index 1dc517edfac861..993a1d2b31511d 100644 --- a/fs/fuse/file.c +++ b/fs/fuse/file.c @@ -320,7 +320,7 @@ static void fuse_prepare_release(struct fuse_inode *fi, struct fuse_file *ff, struct fuse_release_args *ra = &ff->args->release_args; if (fuse_is_passthrough(ff)) - fuse_passthrough_release(ff, fuse_inode_backing(fi)); + fuse_passthrough_release(ff, fi ? fuse_inode_backing(fi) : NULL); /* Inode is NULL on error path of fuse_create_open() */ if (likely(fi)) { @@ -845,8 +845,19 @@ static void fuse_read_update_size(struct inode *inode, loff_t size, spin_unlock(&fi->lock); } -static void fuse_short_read(struct inode *inode, u64 attr_ver, size_t num_read, - struct fuse_args_pages *ap) +/* + * Position of the first byte covered by the folios in @ap. + * + * The first folio may be read partially, so the descriptor offset is part of + * the position. + */ +static loff_t fuse_folios_pos(struct fuse_args_pages *ap) +{ + return folio_pos(ap->folios[0]) + ap->descs[0].offset; +} + +static void fuse_short_read(struct inode *inode, struct fuse_io_args *ia, + size_t num_read) { struct fuse_conn *fc = get_fuse_conn(inode); @@ -856,8 +867,13 @@ static void fuse_short_read(struct inode *inode, u64 attr_ver, size_t num_read, * reached the client fs yet. So the hole is not present there. */ if (!fc->writeback_cache) { - loff_t pos = folio_pos(ap->folios[0]) + num_read; - fuse_read_update_size(inode, pos, attr_ver); + /* + * Derive EOF from the offset the request was sent with, which + * is not necessarily the start of the first folio. + */ + loff_t pos = ia->read.in.offset + num_read; + + fuse_read_update_size(inode, pos, ia->read.attr_ver); } } @@ -866,7 +882,6 @@ static int fuse_do_readfolio(struct file *file, struct folio *folio, { struct inode *inode = folio->mapping->host; struct fuse_mount *fm = get_fuse_mount(inode); - loff_t pos = folio_pos(folio) + off; struct fuse_folio_desc desc = { .offset = off, .length = len, @@ -878,10 +893,10 @@ static int fuse_do_readfolio(struct file *file, struct folio *folio, .ap.folios = &folio, .ap.descs = &desc, }; + loff_t pos = fuse_folios_pos(&ia.ap); ssize_t res; - u64 attr_ver; - attr_ver = fuse_get_attr_version(fm->fc); + ia.read.attr_ver = fuse_get_attr_version(fm->fc); /* * Don't overflow end offset. @@ -906,7 +921,7 @@ static int fuse_do_readfolio(struct file *file, struct folio *folio, * Short read means EOF. If file size is larger, truncate it */ if (res < len) - fuse_short_read(inode, attr_ver, res, &ia.ap); + fuse_short_read(inode, &ia, res); return 0; } @@ -1065,7 +1080,7 @@ static void fuse_readpages_end(struct fuse_args *args, int err) * Short read means EOF. If file size is larger, truncate it */ if (!err && num_read < count) - fuse_short_read(inode, ia->read.attr_ver, num_read, ap); + fuse_short_read(inode, ia, num_read); fuse_invalidate_atime(inode); @@ -1086,7 +1101,7 @@ static void fuse_send_readpages(struct fuse_io_args *ia, struct file *file, struct fuse_file *ff = file->private_data; struct fuse_mount *fm = ff->fm; struct fuse_args_pages *ap = &ia->ap; - loff_t pos = folio_pos(ap->folios[0]); + loff_t pos = fuse_folios_pos(ap); ssize_t res; int err; @@ -1560,6 +1575,11 @@ static ssize_t fuse_cache_write_iter(struct kiocb *iocb, struct iov_iter *from) written = direct_write_fallback(iocb, from, written, fuse_perform_write(iocb, from)); } else if (writeback) { + loff_t old_size = i_size_read(inode); + + if (iocb->ki_pos > old_size) + truncate_pagecache_range(inode, old_size, iocb->ki_pos - 1); + /* * Use iomap so that we can do granular uptodate reads * and granular dirty tracking for large folios. @@ -2252,7 +2272,7 @@ static ssize_t fuse_iomap_writeback_range(struct iomap_writepage_ctx *wpc, { struct fuse_fill_wb_data *data = wpc->wb_ctx; struct fuse_writepage_args *wpa = data->wpa; - struct fuse_args_pages *ap = &wpa->ia.ap; + struct fuse_args_pages *ap = wpa ? &wpa->ia.ap : NULL; struct inode *inode = wpc->inode; struct fuse_inode *fi = get_fuse_inode(inode); struct fuse_conn *fc = get_fuse_conn(inode); @@ -2994,6 +3014,7 @@ static ssize_t __fuse_copy_file_range(struct file *file_in, loff_t pos_in, struct fuse_write_out outarg; struct fuse_copy_file_range_out outarg_64; u64 bytes_copied; + loff_t old_size; ssize_t err; /* mark unstable when write-back is not used, and file_out gets * extended */ @@ -3018,6 +3039,14 @@ static ssize_t __fuse_copy_file_range(struct file *file_in, loff_t pos_in, if (err) goto out; + /* + * Copying to an offset past EOF extends the file over a hole. Drop the + * cache over the newly exposed range before the new size is published. + */ + old_size = i_size_read(inode_out); + if (pos_out > old_size) + truncate_pagecache_range(inode_out, old_size, pos_out - 1); + /* * Write out dirty pages in the destination file before sending the COPY * request to userspace. After the request is completed, drop the diff --git a/fs/fuse/fuse_dev_i.h b/fs/fuse/fuse_dev_i.h index a90ce26ded3192..a8eba46a3e51db 100644 --- a/fs/fuse/fuse_dev_i.h +++ b/fs/fuse/fuse_dev_i.h @@ -245,6 +245,9 @@ struct fuse_chan { /** Is interrupt not implemented by fs? */ bool no_interrupt; + /** @conn_refused: INIT failed while the channel was still connected. */ + bool conn_refused; + /* Use io_uring for communication */ unsigned int io_uring; diff --git a/fs/fuse/fuse_i.h b/fs/fuse/fuse_i.h index ec5ccdf18a255b..e0992fcbcc554f 100644 --- a/fs/fuse/fuse_i.h +++ b/fs/fuse/fuse_i.h @@ -418,8 +418,10 @@ struct fuse_fs_context { bool destroy:1; bool no_control:1; bool no_force_umount:1; + bool no_req_timeout:1; bool legacy_opts_show:1; bool syncfs_capable:1; + bool is_virtiofs:1; enum fuse_vdax_mode vdax_mode; unsigned int max_read; unsigned int blksize; @@ -698,6 +700,15 @@ struct fuse_conn { /** @no_force_umount: Do not allow MNT_FORCE umount */ unsigned int no_force_umount:1; + /** + * @no_req_timeout: Do not enforce a request timeout + * + * Set by transports that cannot revoke a request once it has been + * handed to the server, since the timeout is implemented by aborting + * the connection. + */ + unsigned int no_req_timeout:1; + /** @auto_submounts: Auto-mount submounts announced by the server */ unsigned int auto_submounts:1; @@ -751,6 +762,9 @@ struct fuse_conn { /** @sync_init: Is synchronous FUSE_INIT allowed? */ unsigned int sync_init:1; + /** @is_virtiofs: Is this a virtio-fs connection? */ + unsigned int is_virtiofs:1; + /** @max_stack_depth: Maximum stack depth for passthrough backing files */ int max_stack_depth; @@ -1263,6 +1277,15 @@ void fuse_free_conn(struct fuse_conn *fc); /* dax.c */ +static inline bool fuse_conn_vdax(struct fuse_conn *fc) +{ +#ifdef CONFIG_FUSE_VDAX + return fc->vdax; +#else + return false; +#endif +} + static inline bool fuse_inode_vdax(struct inode *inode) { #ifdef CONFIG_FUSE_VDAX diff --git a/fs/fuse/inode.c b/fs/fuse/inode.c index 1341b681d0ed3a..af6d9e0af190b0 100644 --- a/fs/fuse/inode.c +++ b/fs/fuse/inode.c @@ -385,7 +385,7 @@ static void fuse_change_attributes_i(struct inode *inode, struct fuse_attr *attr invalidate_inode_pages2(inode->i_mapping); } - if (IS_ENABLED(CONFIG_FUSE_VDAX)) + if (fuse_conn_vdax(fc)) fuse_vdax_dontcache(inode, attr->flags); } @@ -418,7 +418,19 @@ static void fuse_init_inode(struct inode *inode, struct fuse_attr *attr, fuse_init_common(inode); fuse_init_file_inode(inode, attr->flags); - if ((attr->flags & FUSE_ATTR_DAX) && !fuse_inode_vdax(inode)) { + /* + * FUSE_ATTR_DAX means a passthrough extent map on a dax + * device, which only exists on a plain fuse connection. On + * virtiofs the same bit means per inode virtiofs DAX, which + * is handled by fuse_vdax_inode_init() instead. + * + * Without CONFIG_FS_DAX, S_DAX is zero and IS_DAX() is + * constant false, so all the checks that keep DAX inodes away + * from the page cache are compiled out. Don't install address + * space operations that have no ->read_folio in that case. + */ + if (IS_ENABLED(CONFIG_FS_DAX) && !fc->is_virtiofs && + (attr->flags & FUSE_ATTR_DAX)) { inode->i_flags |= S_DAX; inode->i_data.a_ops = &fuse_dax_aops; } @@ -1387,7 +1399,7 @@ static void process_init_reply(struct fuse_args *args, int error) !fuse_vdax_check_alignment(fc, arg->map_alignment)) { ok = false; } - if (flags & FUSE_HAS_INODE_DAX) + if (fuse_conn_vdax(fc) && (flags & FUSE_HAS_INODE_DAX)) fc->inode_vdax = 1; } if (flags & FUSE_HANDLE_KILLPRIV_V2) { @@ -1416,7 +1428,7 @@ static void process_init_reply(struct fuse_args *args, int error) * and FUSE_WRITEBACK_CACHE, current design doesn't handle * them together. */ - if (IS_ENABLED(CONFIG_FUSE_PASSTHROUGH) && + if (IS_ENABLED(CONFIG_FUSE_PASSTHROUGH) && !fm->fc->is_virtiofs && (flags & (FUSE_PASSTHROUGH | FUSE_PASSTHROUGH_V2)) && arg->max_stack_depth > 0 && arg->max_stack_depth <= FILESYSTEM_MAX_STACK_DEPTH && @@ -1451,7 +1463,8 @@ static void process_init_reply(struct fuse_args *args, int error) fc->no_flock = 1; } - fuse_init_server_timeout(fc->chan, timeout); + if (!fc->no_req_timeout) + fuse_init_server_timeout(fc->chan, timeout); fm->sb->s_bdi->ra_pages = min(fm->sb->s_bdi->ra_pages, ra_pages); @@ -1502,18 +1515,31 @@ static struct fuse_init_args *fuse_new_init(struct fuse_mount *fm) FUSE_HANDLE_KILLPRIV_V2 | FUSE_SETXATTR_EXT | FUSE_INIT_EXT | FUSE_SECURITY_CTX | FUSE_CREATE_SUPP_GROUP | FUSE_HAS_EXPIRE_ONLY | FUSE_DIRECT_IO_ALLOW_MMAP | - FUSE_NO_EXPORT_SUPPORT | FUSE_HAS_RESEND | FUSE_ALLOW_IDMAP | - FUSE_REQUEST_TIMEOUT; + FUSE_NO_EXPORT_SUPPORT | FUSE_HAS_RESEND | FUSE_ALLOW_IDMAP; + if (!fm->fc->no_req_timeout) + flags |= FUSE_REQUEST_TIMEOUT; #ifdef CONFIG_FUSE_VDAX if (fm->fc->vdax) flags |= FUSE_MAP_ALIGNMENT; - if (fuse_is_inode_vdax_mode(fm->fc->vdax_mode)) + if (fm->fc->vdax && fuse_is_inode_vdax_mode(fm->fc->vdax_mode)) flags |= FUSE_HAS_INODE_DAX; #endif if (fm->fc->auto_submounts) flags |= FUSE_SUBMOUNTS; - if (IS_ENABLED(CONFIG_FUSE_PASSTHROUGH)) + /* + * Passthrough requires a backing file registered with + * FUSE_DEV_IOC_BACKING_OPEN on the fuse device, which a virtiofs + * server has no way to do. + */ + if (IS_ENABLED(CONFIG_FUSE_PASSTHROUGH) && !fm->fc->is_virtiofs) { flags |= FUSE_PASSTHROUGH | FUSE_PASSTHROUGH_V2; + /* + * Per inode DAX needs a dax device opened as backing, which + * is unrelated to how virtiofs uses the same flag above. + */ + if (IS_REACHABLE(CONFIG_DEV_DAX_FSDEV)) + flags |= FUSE_HAS_INODE_DAX; + } /* Only offered to sufficiently privileged servers; see * fuse_syncfs_enable(). */ @@ -1820,6 +1846,8 @@ int fuse_fill_super_common(struct super_block *sb, struct fuse_fs_context *ctx) fc->destroy = ctx->destroy; fc->no_control = ctx->no_control; fc->no_force_umount = ctx->no_force_umount; + fc->no_req_timeout = ctx->no_req_timeout; + fc->is_virtiofs = ctx->is_virtiofs; err = -ENOMEM; root = fuse_get_root_inode(sb, ctx->rootmode); diff --git a/fs/fuse/readdir.c b/fs/fuse/readdir.c index 1f6cf565477f78..c1e2a8fd834e93 100644 --- a/fs/fuse/readdir.c +++ b/fs/fuse/readdir.c @@ -11,6 +11,7 @@ #include #include #include +#include static bool fuse_use_readdirplus(struct inode *dir, struct dir_context *ctx) { @@ -191,18 +192,17 @@ static int fuse_direntplus_link(struct file *file, return -EIO; if (fuse_invalid_attr(&o->attr)) return -EIO; + if (memchr(name.name, '\0', name.len)) + return -EIO; fc = get_fuse_conn(dir); epoch = atomic_read(&fc->epoch); - name.hash = full_name_hash(parent, name.name, name.len); - dentry = d_lookup(parent, &name); - if (!dentry) { retry: - dentry = d_alloc_parallel(parent, &name); - if (IS_ERR(dentry)) - return PTR_ERR(dentry); - } + dentry = d_alloc_trylock(parent, &name); + if (IS_ERR(dentry)) + return PTR_ERR(dentry); + if (!d_in_lookup(dentry)) { struct fuse_inode *fi; inode = d_inode(dentry); @@ -230,6 +230,7 @@ static int fuse_direntplus_link(struct file *file, fuse_change_attributes(inode, &o->attr, NULL, ATTR_TIMEOUT(o), attr_version); + fuse_dentry_set_epoch(dentry, epoch); /* * The other branch comes via fuse_iget() * which bumps nlookup inside @@ -238,9 +239,14 @@ static int fuse_direntplus_link(struct file *file, inode = fuse_iget(dir->i_sb, o->nodeid, o->generation, &o->attr, ATTR_TIMEOUT(o), attr_version, evict_ctr); - if (!inode) - inode = ERR_PTR(-ENOMEM); + if (!inode) { + d_lookup_done(dentry); + dput(dentry); + return -ENOMEM; + } + fuse_dentry_set_epoch(dentry, epoch); + ihold(inode); /* d_splice_alias() eats a reference */ alias = d_splice_alias(inode, dentry); d_lookup_done(dentry); if (alias) { @@ -248,19 +254,20 @@ static int fuse_direntplus_link(struct file *file, dentry = alias; } if (IS_ERR(dentry)) { - if (!IS_ERR(inode)) { - struct fuse_inode *fi = get_fuse_inode(inode); + struct fuse_inode *fi = get_fuse_inode(inode); - spin_lock(&fi->lock); - fi->nlookup--; - spin_unlock(&fi->lock); - } + spin_lock(&fi->lock); + fi->nlookup--; + spin_unlock(&fi->lock); + iput(inode); return PTR_ERR(dentry); } + if (alias) + fuse_dentry_set_epoch(dentry, epoch); + iput(inode); } if (fc->readdirplus_auto) set_bit(FUSE_I_INIT_RDPLUS, &get_fuse_inode(inode)->state); - fuse_dentry_set_epoch(dentry, epoch); fuse_change_entry_timeout(dentry, o); dput(dentry); diff --git a/fs/fuse/req.c b/fs/fuse/req.c index 6274a23af445c1..d96b947c61e6ad 100644 --- a/fs/fuse/req.c +++ b/fs/fuse/req.c @@ -49,20 +49,11 @@ static int fuse_fill_creds(struct fuse_mount *fm, struct fuse_args *args, return 0; } -static int fuse_req_prep(struct fuse_mount *fm, struct fuse_args *args, - const struct mnt_idmap *idmap) -{ - if (!args->force && fm->fc->conn_error) - return -ECONNREFUSED; - - return fuse_fill_creds(fm, args, idmap); -} - ssize_t __fuse_simple_request(const struct mnt_idmap *idmap, struct fuse_mount *fm, struct fuse_args *args) { struct fuse_conn *fc = fm->fc; - int err = fuse_req_prep(fm, args, idmap); + int err = fuse_fill_creds(fm, args, idmap); if (err) return err; @@ -77,7 +68,7 @@ int fuse_simple_background(struct fuse_mount *fm, struct fuse_args *args, gfp_t WARN_ON(args->force && !args->nocreds); - err = fuse_req_prep(fm, args, &invalid_mnt_idmap); + err = fuse_fill_creds(fm, args, &invalid_mnt_idmap); if (err) return err; @@ -92,7 +83,7 @@ int fuse_simple_notify_reply(struct fuse_mount *fm, struct fuse_args *args, u64 WARN_ON(args->force && !args->nocreds); - err = fuse_req_prep(fm, args, &invalid_mnt_idmap); + err = fuse_fill_creds(fm, args, &invalid_mnt_idmap); if (err) return err; diff --git a/fs/fuse/virtio_fs.c b/fs/fuse/virtio_fs.c index ff872c7c07628e..d247a02cdca93f 100644 --- a/fs/fuse/virtio_fs.c +++ b/fs/fuse/virtio_fs.c @@ -193,6 +193,7 @@ static void virtio_fs_ktype_release(struct kobject *kobj) { struct virtio_fs *vfs = container_of(kobj, struct virtio_fs, kobj); + kfree(vfs->tag); kfree(vfs->mq_map); kfree(vfs->vqs); kfree(vfs); @@ -489,7 +490,11 @@ static void virtio_fs_free_devs(struct virtio_fs *fs) } } -/* Read filesystem name from virtio config into fs->tag (must kfree()). */ +/* + * Read filesystem name from virtio config into fs->tag. Freed by + * virtio_fs_ktype_release() so that it stays valid for as long as the + * virtio_fs object itself, which may outlive the virtio device. + */ static int virtio_fs_read_tag(struct virtio_device *vdev, struct virtio_fs *fs) { char tag_buf[sizeof_field(struct virtio_fs_config, tag)]; @@ -505,7 +510,7 @@ static int virtio_fs_read_tag(struct virtio_device *vdev, struct virtio_fs *fs) end = &tag_buf[sizeof(tag_buf)]; len = end - tag_buf; - fs->tag = devm_kmalloc(&vdev->dev, len + 1, GFP_KERNEL); + fs->tag = kmalloc(len + 1, GFP_KERNEL); if (!fs->tag) return -ENOMEM; memcpy(fs->tag, tag_buf, len); @@ -696,15 +701,16 @@ static int copy_args_to_argbuf(struct fuse_req *req, gfp_t gfp) unsigned int offset = 0; unsigned int num_in; unsigned int num_out; - unsigned int len; + unsigned int in_len; + unsigned int out_len; unsigned int i; num_in = args->in_numargs - args->in_pages; num_out = args->out_numargs - args->out_pages; - len = fuse_len_args(num_in, (struct fuse_arg *) args->in_args) + - fuse_len_args(num_out, args->out_args); + in_len = fuse_len_args(num_in, (struct fuse_arg *) args->in_args); + out_len = fuse_len_args(num_out, args->out_args); - req->argbuf = kmalloc(len, gfp); + req->argbuf = kmalloc(in_len + out_len, gfp); if (!req->argbuf) return -ENOMEM; @@ -715,6 +721,14 @@ static int copy_args_to_argbuf(struct fuse_req *req, gfp_t gfp) offset += args->in_args[i].size; } + /* + * The server is not required to fill the reply region and the length + * it reports in the used ring cannot confirm that it did. Zero the + * region so that an unwritten reply yields zeroes rather than stale + * heap contents. + */ + memset(req->argbuf + in_len, 0, out_len); + return 0; } @@ -1588,6 +1602,13 @@ static inline void virtio_fs_ctx_set_defaults(struct fuse_fs_context *ctx) ctx->destroy = true; ctx->no_control = true; ctx->no_force_umount = true; + /* + * A request handed to the device stays referenced by the virtqueue + * until the device completes it. The request timeout works by + * aborting the connection, which ends and frees such requests behind + * the device's back, so it must not be enabled here. + */ + ctx->no_req_timeout = true; } static int virtio_fs_fill_super(struct super_block *sb, struct fs_context *fsc) @@ -1807,6 +1828,7 @@ static int virtio_fs_init_fs_context(struct fs_context *fsc) ctx = kzalloc_obj(struct fuse_fs_context); if (!ctx) return -ENOMEM; + ctx->is_virtiofs = true; fsc->fs_private = ctx; fsc->ops = &virtio_fs_context_ops; return 0; diff --git a/fs/fuse/xattr.c b/fs/fuse/xattr.c index 53e3c5e6fff0dd..02f780e7426d31 100644 --- a/fs/fuse/xattr.c +++ b/fs/fuse/xattr.c @@ -94,7 +94,7 @@ static int fuse_verify_xattr_list(char *list, size_t size) while (size) { size_t thislen = strnlen(list, size); - if (!thislen || thislen == size) + if (!thislen || thislen == size || thislen > XATTR_NAME_MAX) return -EIO; size -= thislen + 1; diff --git a/fs/hugetlbfs/inode.c b/fs/hugetlbfs/inode.c index 02e0a65d596d86..f83c85caf8741b 100644 --- a/fs/hugetlbfs/inode.c +++ b/fs/hugetlbfs/inode.c @@ -401,6 +401,16 @@ static void hugetlb_unmap_file_folio(struct hstate *h, if (!hugetlb_vma_maps_pfn(vma, v_start, pfn)) continue; + /* + * We only need additional VMA locking here for PMD table + * sharing, which synchronizes on the shareable lock. + */ + if (!__vma_shareable_lock(vma)) { + unmap_hugepage_range(vma, v_start, v_end, NULL, + ZAP_FLAG_DROP_MARKER); + continue; + } + if (!hugetlb_vma_trylock_write(vma)) { vma_lock = vma->vm_private_data; /* @@ -722,11 +732,13 @@ static long hugetlbfs_fallocate(struct file *file, int mode, loff_t offset, /* * Default preallocate case. - * For this range, start is rounded down and end is rounded up - * as well as being converted to page offsets. + * vfs_fallocate() guarantees that offset + len is positive and does + * not overflow. Avoid overflows when calculating the end huge page + * index: set it to one past the index of the huge page containing the + * last byte. */ start = offset >> hpage_shift; - end = (offset + len + hpage_size - 1) >> hpage_shift; + end = ((offset + len - 1) >> hpage_shift) + 1; inode_lock(inode); @@ -1187,12 +1199,12 @@ static struct inode *hugetlbfs_alloc_inode(struct super_block *sb) static void hugetlbfs_free_inode(struct inode *inode) { - trace_hugetlbfs_free_inode(inode); kmem_cache_free(hugetlbfs_inode_cachep, HUGETLBFS_I(inode)); } static void hugetlbfs_destroy_inode(struct inode *inode) { + trace_hugetlbfs_destroy_inode(inode); hugetlbfs_inc_free_inodes(HUGETLBFS_SB(inode->i_sb)); } diff --git a/fs/iomap/buffered-io.c b/fs/iomap/buffered-io.c index 6d843b168d5f7d..25915c0f5e1ccc 100644 --- a/fs/iomap/buffered-io.c +++ b/fs/iomap/buffered-io.c @@ -1495,9 +1495,34 @@ static void iomap_write_delalloc_scan(struct inode *inode, * mapping_seek_hole_data() will return it, and we will skip the punch because * the folio is dirty. THis is incorrect - we always need to punch out delalloc * beyond EOF in this case as writeback will never write back and covert that - * delalloc block beyond EOF. Hence we limit the cached data scan range to EOF, - * resulting in always punching out the range from the EOF to the end of the - * range the iomap spans. + * delalloc block beyond EOF. Hence we limit the cached data scan range, and + * always punch out the range from the end of the scan to the end of the range + * the iomap spans. + * + * The scan cannot simply end at EOF, because EOF is a byte offset and a + * delalloc reservation covers whole blocks. If EOF lies inside a block, it + * splits that block in two: + * + * [block start, EOF) File data. If it is dirty it will be written + * back, so the block must keep its delalloc + * backing. + * [EOF, block end) Beyond EOF. By the rule above, this would always + * be punched out. + * + * Both parts share one reservation, and it cannot be split: a punch of a part + * of a block takes away the reservation for the whole block. If the scan ended + * at EOF, we would skip the punch for the first part because it is dirty, and + * then punch the second part, which takes the reservation away from under the + * dirty data in the first part. On XFS, writeback that has lost a COW fork + * reservation like this writes in place, over a block that is shared with + * another file. + * + * Hence we treat the EOF block as a whole, and let the cached data over it + * decide: the scan range is rounded up to the end of the block that EOF lies + * in. If the data over the EOF block is dirty, the scan moves the punch start + * past the block. If it is clean, the block is punched like any other block in + * the range. Only blocks that start at or beyond EOF are punched + * unconditionally. If EOF is block aligned, the round up changes nothing. * * Intervals are of the form [start_byte, end_byte) (i.e. open ended) because it * matches the intervals returned by mapping_seek_hole_data(). i.e. SEEK_DATA @@ -1511,7 +1536,8 @@ void iomap_write_delalloc_release(struct inode *inode, loff_t start_byte, iomap_punch_t punch) { loff_t punch_start_byte = start_byte; - loff_t scan_end_byte = min(i_size_read(inode), end_byte); + loff_t scan_end_byte = min_t(u64, end_byte, + round_up((u64)i_size_read(inode), i_blocksize(inode))); /* * The caller must hold invalidate_lock to avoid races with page faults diff --git a/fs/jbd2/checkpoint.c b/fs/jbd2/checkpoint.c index 5132737120108c..9bbce4c8cadb68 100644 --- a/fs/jbd2/checkpoint.c +++ b/fs/jbd2/checkpoint.c @@ -346,8 +346,14 @@ int jbd2_cleanup_journal_tail(journal_t *journal) * need this to guarantee correctness. Fortunately * jbd2_cleanup_journal_tail() doesn't get called all that often. */ - if (journal->j_flags & JBD2_BARRIER) - blkdev_issue_flush(journal->j_fs_dev); + if (journal->j_flags & JBD2_BARRIER) { + int err = blkdev_issue_flush(journal->j_fs_dev); + + if (err) { + jbd2_journal_abort(journal, err); + return err; + } + } return __jbd2_update_log_tail(journal, first_tid, blocknr); } diff --git a/fs/jbd2/commit.c b/fs/jbd2/commit.c index ebf6ba58ff4d0c..00a5a6b369ed52 100644 --- a/fs/jbd2/commit.c +++ b/fs/jbd2/commit.c @@ -800,8 +800,12 @@ void jbd2_journal_commit_transaction(journal_t *journal) */ if ((commit_transaction->t_need_data_flush || update_tail) && (journal->j_fs_dev != journal->j_dev) && - (journal->j_flags & JBD2_BARRIER)) - blkdev_issue_flush(journal->j_fs_dev); + (journal->j_flags & JBD2_BARRIER)) { + err = blkdev_issue_flush(journal->j_fs_dev); + + if (err) + jbd2_journal_abort(journal, err); + } /* Done it all: now write the commit record asynchronously. */ if (jbd2_has_feature_async_commit(journal)) { @@ -908,7 +912,10 @@ void jbd2_journal_commit_transaction(journal_t *journal) stats.run.rs_blocks_logged++; if (jbd2_has_feature_async_commit(journal) && journal->j_flags & JBD2_BARRIER) { - blkdev_issue_flush(journal->j_dev); + int flush_err = blkdev_issue_flush(journal->j_dev); + + if (!err) + err = flush_err; } if (err) diff --git a/fs/jbd2/journal.c b/fs/jbd2/journal.c index 3a4f3f613ead8a..eb8e944f1f9e67 100644 --- a/fs/jbd2/journal.c +++ b/fs/jbd2/journal.c @@ -700,7 +700,8 @@ int jbd2_log_wait_commit(journal_t *journal, tid_t tid) * it to complete. Returns 0 if a new fast commit was started. Returns -EALREADY * if a fast commit is not needed, either because there's an already a commit * going on or this tid has already been committed. Returns -EINVAL if no jbd2 - * commit has yet been performed. + * commit has yet been performed, or none since the journal was last marked + * empty. */ int jbd2_fc_begin_commit(journal_t *journal, tid_t tid) { @@ -719,6 +720,16 @@ int jbd2_fc_begin_commit(journal_t *journal, tid_t tid) return -EALREADY; } + /* + * The log was emptied and the superblock on disk says so, which makes + * recovery skip the fast commit area as well. Only a full commit + * records the log tail again. + */ + if (journal->j_flags & JBD2_FLUSHED) { + write_unlock(&journal->j_state_lock); + return -EINVAL; + } + if (journal->j_flags & JBD2_FULL_COMMIT_ONGOING || (journal->j_flags & JBD2_FAST_COMMIT_ONGOING)) { DEFINE_WAIT(wait); @@ -1268,10 +1279,22 @@ static unsigned long jbd2_journal_shrink_scan(struct shrinker *shrink, trace_jbd2_shrink_scan_enter(journal, sc->nr_to_scan, count); nr_shrunk = jbd2_journal_shrink_checkpoint_list(journal, &nr_to_scan); + sc->nr_scanned = sc->nr_to_scan - nr_to_scan; count = percpu_counter_read_positive(&journal->j_checkpoint_jh_count); trace_jbd2_shrink_scan_exit(journal, nr_to_scan, nr_shrunk, count); + /* + * Key SHRINK_STOP off sc->nr_scanned (buffers actually examined), + * not nr_shrunk (buffers actually freed): a batch can find every + * buffer in its transactions busy and free none, while later + * transactions may still hold buffers whose writeback has + * completed. sc->nr_scanned only comes back 0 when the checkpoint + * list had nothing left to walk. + */ + if (sc->nr_scanned == 0) + return SHRINK_STOP; + return nr_shrunk; } @@ -2096,7 +2119,10 @@ int jbd2_journal_load(journal_t *journal) return err; } + /* kjournald2 is already running, see journal_reset(). */ + write_lock(&journal->j_state_lock); journal->j_flags |= JBD2_LOADED; + write_unlock(&journal->j_state_lock); return 0; } diff --git a/fs/nfsd/nfs3proc.c b/fs/nfsd/nfs3proc.c index 60cd01b6a37d24..0711e93c996350 100644 --- a/fs/nfsd/nfs3proc.c +++ b/fs/nfsd/nfs3proc.c @@ -334,7 +334,7 @@ nfsd3_create_file(struct svc_rqst *rqstp, struct svc_fh *fhp, struct svc_fh *resfhp, struct nfsd3_createargs *argp) { struct iattr *iap = &argp->attrs; - struct dentry *parent, *child; + struct dentry *parent, *child, *mnt_child; struct nfsd_attrs attrs = { .na_iattr = iap, }; @@ -378,21 +378,29 @@ nfsd3_create_file(struct svc_rqst *rqstp, struct svc_fh *fhp, } exp = exp_get(fhp->fh_export); + /* + * Cross on a separate reference: child must remain the dentry + * start_creating() returned so that end_creating() unlocks the + * right directory. + */ + mnt_child = dget(child); if (argp->createmode == NFS3_CREATE_UNCHECKED) { /* * If name is already in dcache we need to check for mountpoints */ if (d_is_reg(child) && unlikely(nfsd_mountpoint(child, exp))) { - status = nfsd_cross_mnt(rqstp, &child, &exp); + status = nfsd_cross_mnt(rqstp, &mnt_child, &exp); if (status != nfs_ok) { + dput(mnt_child); exp_put(exp); goto out; } } } - status = fh_compose(resfhp, exp, child, fhp); + status = fh_compose(resfhp, exp, mnt_child, fhp); + dput(mnt_child); exp_put(exp); if (status != nfs_ok) goto out; diff --git a/fs/nfsd/nfsproc.c b/fs/nfsd/nfsproc.c index 1f74008bc06ad8..2cecae4e0cdfa8 100644 --- a/fs/nfsd/nfsproc.c +++ b/fs/nfsd/nfsproc.c @@ -682,7 +682,7 @@ nfsd_create_file(struct svc_rqst *rqstp, struct svc_fh *fhp, .na_iattr = attr, }; struct svc_export *exp; - struct dentry *dchild; + struct dentry *dchild, *dmnt; struct inode *inode; int type, mode; __be32 status; @@ -705,20 +705,26 @@ nfsd_create_file(struct svc_rqst *rqstp, struct svc_fh *fhp, status = nfserrno(PTR_ERR(dchild)); goto out_drop_write; } + exp = exp_get(fhp->fh_export); /* - * If name exists we need to check for mountpoints + * If name exists we need to check for mountpoints. Cross on a + * separate reference: end_creating() unlocks the parent of the + * dentry it is given, and only dchild has the locked directory + * as its parent. */ - exp = exp_get(fhp->fh_export); + dmnt = dget(dchild); if (d_is_reg(dchild) && unlikely(nfsd_mountpoint(dchild, exp))) { - status = nfsd_cross_mnt(rqstp, &dchild, &exp); + status = nfsd_cross_mnt(rqstp, &dmnt, &exp); if (status != nfs_ok) { + dput(dmnt); exp_put(exp); goto out; } } - status = fh_compose(resfhp, exp, dchild, fhp); + status = fh_compose(resfhp, exp, dmnt, fhp); + dput(dmnt); exp_put(exp); if (!status && d_really_is_negative(dchild)) status = nfserr_noent; diff --git a/fs/ntfs/aops.c b/fs/ntfs/aops.c index cb3d5443ee1dd6..d0d1a8402bc4d9 100644 --- a/fs/ntfs/aops.c +++ b/fs/ntfs/aops.c @@ -7,6 +7,7 @@ * Copyright (c) 2025 LG Electronics Co., Ltd. */ +#include #include #include "attrib.h" @@ -304,6 +305,65 @@ static int ntfs_swap_activate(struct swap_info_struct *sis, ntfs_read_iomap_next); } +/** + * ntfs_read_metadata_folio - read a metadata folio, ignoring fatal signals + * @mapping: address space of the metadata inode or block device + * @index: page cache index to read + * + * Like read_mapping_folio(), but the wait for the read cannot be interrupted, + * so a fatal signal cannot fail a metadata read in the middle of an update. + * The caller must not hold the lock of the folio at @index. + * + * Return: the uptodate folio with a reference held, or an ERR_PTR(). + */ +struct folio *ntfs_read_metadata_folio(struct address_space *mapping, + pgoff_t index) +{ + struct folio *folio; + int err; + + folio = filemap_get_folio(mapping, index); + if (!IS_ERR(folio)) { + if (folio_test_uptodate(folio)) + goto out; + folio_put(folio); + } +repeat: + folio = __filemap_get_folio(mapping, index, FGP_LOCK | FGP_CREAT, + mapping_gfp_mask(mapping)); + if (IS_ERR(folio)) + return folio; + /* $MFT updates clear uptodate under the folio lock, so check it locked. */ + if (folio_test_uptodate(folio)) + goto unlock; + + /* ->read_folio() unlocks the folio when the read completes. */ + err = mapping->a_ops->read_folio(NULL, folio); + if (err) { + folio_put(folio); + if (err == AOP_TRUNCATED_PAGE) + goto repeat; + return ERR_PTR(err); + } + folio_lock(folio); + if (folio->mapping != mapping) { + /* Truncated while the read was in flight. */ + folio_unlock(folio); + folio_put(folio); + goto repeat; + } + if (!folio_test_uptodate(folio)) { + folio_unlock(folio); + folio_put(folio); + return ERR_PTR(-EIO); + } +unlock: + folio_unlock(folio); +out: + folio_mark_accessed(folio); + return folio; +} + const struct address_space_operations ntfs_aops = { .read_folio = ntfs_read_folio, .readahead = ntfs_readahead, diff --git a/fs/ntfs/attrib.c b/fs/ntfs/attrib.c index ce7c1b524180af..9266a3ea3b0f38 100644 --- a/fs/ntfs/attrib.c +++ b/fs/ntfs/attrib.c @@ -1975,7 +1975,21 @@ int ntfs_resident_attr_value_resize(struct mft_record *m, struct attr_record *a, * inode i_size is that this is not necessarily uptodate. This happens when * ntfs_attr_make_non_resident() is called in the ->truncate call path(s). */ +static int __ntfs_attr_make_non_resident(struct ntfs_inode *ni, const u32 data_size, + bool nowait); + int ntfs_attr_make_non_resident(struct ntfs_inode *ni, const u32 data_size) +{ + return __ntfs_attr_make_non_resident(ni, data_size, false); +} + +/* + * With @nowait the folio lock is only tried: a caller that holds mrec_lock + * must not wait for a folio lock, the read path takes them the other way + * round. Fails with -EAGAIN if the folio is locked. + */ +static int __ntfs_attr_make_non_resident(struct ntfs_inode *ni, const u32 data_size, + bool nowait) { s64 new_size; struct inode *vi = VFS_I(ni); @@ -2056,10 +2070,23 @@ int ntfs_attr_make_non_resident(struct ntfs_inode *ni, const u32 data_size) * outside all ntfs locks, we need to get the folio now. */ folio = __filemap_get_folio(vi->i_mapping, 0, - FGP_CREAT | FGP_LOCK, + FGP_CREAT | FGP_LOCK | + (nowait ? FGP_NOWAIT : 0), mapping_gfp_mask(vi->i_mapping)); if (IS_ERR(folio)) { err = -ENOMEM; + if (nowait) { + /* + * FGP_NOWAIT also fails when it can not + * allocate the folio. Only a folio that is + * there and locked means a busy folio. + */ + folio = filemap_get_folio(vi->i_mapping, 0); + if (!IS_ERR(folio)) { + folio_put(folio); + err = -EAGAIN; + } + } goto err_out; } @@ -2323,7 +2350,7 @@ int ntfs_attr_set(struct ntfs_inode *ni, s64 ofs, s64 cnt, const u8 val) index = ofs >> PAGE_SHIFT; while (cnt) { - folio = read_mapping_folio(mapping, index, NULL); + folio = ntfs_read_metadata_folio(mapping, index); if (IS_ERR(folio)) { ret = PTR_ERR(folio); ntfs_error(VFS_I(ni)->i_sb, "Failed to read a page %lu for attr %#x: %ld", @@ -4895,8 +4922,23 @@ static int ntfs_resident_attr_resize(struct ntfs_inode *attr_ni, const s64 newsi /* There is not enough space in the mft record to perform the resize. */ /* Make the attribute non-resident if possible. */ - err = ntfs_attr_make_non_resident(attr_ni, - le32_to_cpu(ctx->attr->data.resident.value_length)); + err = __ntfs_attr_make_non_resident(attr_ni, + le32_to_cpu(ctx->attr->data.resident.value_length), true); + /* + * A reader holding folio 0 waits for mrec_lock, which we hold. Do not + * wait for it and do not look for room elsewhere either: the reader + * keeps the folio until we drop the lock, so the attribute can neither + * be converted nor written without waiting for it, and the loop below + * would only convert other attributes for nothing. + */ + if (err == -EAGAIN) { + /* + * Not -EAGAIN, it would reach user space and index.c uses it + * for its own retry. Not -ENOSPC, the record is not full. + */ + err = -EBUSY; + goto put_err_out; + } if (!err) { mark_mft_record_dirty(ctx->ntfs_ino); ntfs_attr_put_search_ctx(ctx); @@ -4913,12 +4955,14 @@ static int ntfs_resident_attr_resize(struct ntfs_inode *attr_ni, const s64 newsi while (!(err = ntfs_attr_lookup(AT_UNUSED, NULL, 0, 0, 0, NULL, 0, ctx))) { struct inode *tvi; struct attr_record *a; + __le16 *name; u32 value_len; a = ctx->attr; if (a->non_resident || a->type == AT_ATTRIBUTE_LIST) continue; value_len = le32_to_cpu(a->data.resident.value_length); + name = (__le16 *)((u8 *)a + le16_to_cpu(a->name_offset)); if (ntfs_attr_can_be_non_resident(vol, a->type)) continue; @@ -4933,18 +4977,65 @@ static int ntfs_resident_attr_resize(struct ntfs_inode *attr_ni, const s64 newsi if (a->type == AT_DATA && !value_len) continue; - if (a->type == AT_DATA) - tvi = ntfs_iget(sb, base_ni->mft_no); - else - tvi = ntfs_attr_iget(VFS_I(base_ni), a->type, - (__le16 *)((u8 *)a + le16_to_cpu(a->name_offset)), + /* + * The attribute inode of an unlinked file is evicted on the + * last iput() together with its dirty folio. + */ + if (NInoBeingDeleted(base_ni) || !VFS_I(base_ni)->i_nlink) + continue; + + /* + * Not the attribute being resized. Its conversion was tried + * above and failed, for instance on a busy folio, and + * converting it here would leave the resize to go on with the + * resident layout of a non-resident record. + */ + if (a->type == attr_ni->type && + a->name_length == attr_ni->name_len && + (!a->name_length || + !memcmp(name, attr_ni->name, + a->name_length * sizeof(__le16)))) + continue; + + /* + * Not the unnamed data either. Only the resize of the unnamed + * data itself holds its i_rwsem, a writer of the file can be + * between its residency check and the mft record lock. + */ + if (a->type == AT_DATA && !a->name_length) + continue; + + /* + * A named $DATA stream is converted only if nobody has it open: + * an open one can be unlinked, being removed or in use. A WOF + * file reads its stream from the device, so the stream must + * stay resident. + */ + if (a->type == AT_DATA) { + if (NInoWofCompressed(base_ni)) + continue; + tvi = ntfs_attr_ilookup(VFS_I(base_ni), a->type, + name, a->name_length); + if (tvi) { + iput(tvi); + continue; + } + } + tvi = ntfs_attr_iget(VFS_I(base_ni), a->type, name, a->name_length); + /* the lookup ignores case for streams, ours does not */ + if (!IS_ERR(tvi) && a->type == AT_DATA && + memcmp(NTFS_I(tvi)->name, name, + a->name_length * sizeof(__le16))) { + iput(tvi); + continue; + } if (IS_ERR(tvi)) { ntfs_error(sb, "Couldn't open attribute"); continue; } - if (ntfs_attr_make_non_resident(NTFS_I(tvi), value_len)) { + if (__ntfs_attr_make_non_resident(NTFS_I(tvi), value_len, true)) { iput(tvi); continue; } diff --git a/fs/ntfs/bdev-io.c b/fs/ntfs/bdev-io.c index 4f27eed3b0723b..afb1d1df37e09e 100644 --- a/fs/ntfs/bdev-io.c +++ b/fs/ntfs/bdev-io.c @@ -99,7 +99,7 @@ int ntfs_bdev_write(struct super_block *sb, void *buf, loff_t start, size_t size for (; idx < idx_end; idx++, from = 0) { u32 len; - folio = read_mapping_folio(sb->s_bdev->bd_mapping, idx, NULL); + folio = ntfs_read_metadata_folio(sb->s_bdev->bd_mapping, idx); if (IS_ERR(folio)) { ntfs_error(sb, "Unable to read %ld page", idx); return PTR_ERR(folio); diff --git a/fs/ntfs/bitmap.c b/fs/ntfs/bitmap.c index af86fb1c199ba5..0ad80255d6222e 100644 --- a/fs/ntfs/bitmap.c +++ b/fs/ntfs/bitmap.c @@ -36,8 +36,7 @@ int ntfs_bitmap_check_used(struct ntfs_volume *vol, s64 start, s64 count, return -EROFS; while (count) { - folio = read_mapping_folio(mapping, - start >> (PAGE_SHIFT + 3), NULL); + folio = ntfs_read_metadata_folio(mapping, start >> (PAGE_SHIFT + 3)); if (IS_ERR(folio)) return PTR_ERR(folio); @@ -203,7 +202,7 @@ int __ntfs_bitmap_set_bits_in_run(struct inode *vi, const s64 start_bit, /* Get the page containing the first bit (@start_bit). */ mapping = vi->i_mapping; - folio = read_mapping_folio(mapping, index, NULL); + folio = ntfs_read_metadata_folio(mapping, index); if (IS_ERR(folio)) { if (!is_rollback) ntfs_error(vi->i_sb, @@ -267,7 +266,7 @@ int __ntfs_bitmap_set_bits_in_run(struct inode *vi, const s64 start_bit, folio_unlock(folio); kunmap_local(kaddr); folio_put(folio); - folio = read_mapping_folio(mapping, ++index, NULL); + folio = ntfs_read_metadata_folio(mapping, ++index); if (IS_ERR(folio)) { ntfs_error(vi->i_sb, "Failed to map subsequent page (error %li), aborting.", diff --git a/fs/ntfs/dir.c b/fs/ntfs/dir.c index 9fb5bb3d351205..ce87799a28e8e4 100644 --- a/fs/ntfs/dir.c +++ b/fs/ntfs/dir.c @@ -327,8 +327,8 @@ u64 ntfs_lookup_inode_by_name(struct ntfs_inode *dir_ni, const __le16 *uname, * of PAGE_SIZE and map the page cache page, reading it from * disk if necessary. */ - folio = read_mapping_folio(ia_mapping, vcn << - dir_ni->itype.index.vcn_size_bits >> PAGE_SHIFT, NULL); + folio = ntfs_read_metadata_folio(ia_mapping, vcn << + dir_ni->itype.index.vcn_size_bits >> PAGE_SHIFT); if (IS_ERR(folio)) { ntfs_error(sb, "Failed to map directory index page, error %ld.", -PTR_ERR(folio)); diff --git a/fs/ntfs/file.c b/fs/ntfs/file.c index 1861d0f07fef8a..5ab0e3437d671f 100644 --- a/fs/ntfs/file.c +++ b/fs/ntfs/file.c @@ -323,13 +323,6 @@ int ntfs_file_fsync(struct file *filp, loff_t start, loff_t end, ret = __ntfs_write_inode(vi, 1); write_inode_now(vi, !datasync); - /* - * file_write_and_wait_range() already flushed this stream mapping. - * A stream fsync does not need to flush sibling attribute mappings. - */ - if (stream) - goto sync_volume; - ctx = ntfs_attr_get_search_ctx(ni, NULL); if (!ctx) return -ENOMEM; @@ -340,6 +333,9 @@ int ntfs_file_fsync(struct file *filp, loff_t start, loff_t end, struct file_name_attr *fn = (struct file_name_attr *)((u8 *)ctx->attr + le16_to_cpu(ctx->attr->data.resident.value_offset)); + if (MREF_LE(fn->parent_directory) == ni->mft_no) + continue; + parent_vi = ntfs_iget(vi->i_sb, MREF_LE(fn->parent_directory)); if (IS_ERR(parent_vi)) continue; @@ -409,7 +405,6 @@ int ntfs_file_fsync(struct file *filp, loff_t start, loff_t end, if (err && !ret) ret = err; -sync_volume: write_inode_now(vol->mftbmp_ino, 1); down_write(&vol->lcnbmp_lock); write_inode_now(vol->lcnbmp_ino, 1); diff --git a/fs/ntfs/inode.c b/fs/ntfs/inode.c index b799e6668a6939..6a9f488e277509 100644 --- a/fs/ntfs/inode.c +++ b/fs/ntfs/inode.c @@ -287,6 +287,25 @@ struct inode *ntfs_attr_iget(struct inode *base_vi, __le32 type, return vi; } +/* + * ntfs_attr_ilookup - find an attribute inode that is already in the cache + * + * Like ntfs_attr_iget() but never reads anything. Returns the inode with an + * increased reference count, or NULL if it is not cached. + */ +struct inode *ntfs_attr_ilookup(struct inode *base_vi, __le32 type, + __le16 *name, u32 name_len) +{ + struct ntfs_attr na = { + .mft_no = base_vi->i_ino, + .type = type, + .name = name, + .name_len = name_len, + }; + + return ilookup5(base_vi->i_sb, na.mft_no, ntfs_test_inode, &na); +} + /* * ntfs_index_iget - obtain a struct inode corresponding to an index * @base_vi: vfs base inode containing the index related attributes @@ -3773,8 +3792,14 @@ s64 ntfs_inode_attr_pread(struct inode *vi, s64 pos, s64 count, u8 *buf) index = pos >> PAGE_SHIFT; do { - /* Update @index and get the next folio. */ - folio = read_mapping_folio(mapping, index, NULL); + /* + * Update @index and get the next folio. The contents of a named + * stream are user data, so a fatal signal may still stop that read. + */ + if (ntfs_inode_is_named_stream(ni)) + folio = read_mapping_folio(mapping, index, NULL); + else + folio = ntfs_read_metadata_folio(mapping, index); if (IS_ERR(folio)) { err = PTR_ERR(folio); break; @@ -3926,9 +3951,18 @@ static s64 __ntfs_inode_non_resident_attr_pwrite(struct inode *vi, break; } } else { - folio = read_mapping_folio(mapping, index, NULL); + /* + * Named stream contents are user data; keep that read + * killable, as in ntfs_inode_attr_pread(). + */ + if (ntfs_inode_is_named_stream(ni)) + folio = read_mapping_folio(mapping, index, NULL); + else + folio = ntfs_read_metadata_folio(mapping, index); if (IS_ERR(folio)) { ret = PTR_ERR(folio); + if (ret == -EINTR) + break; ntfs_error(vi->i_sb, "Failed to read a page %lu for attr %#x: %ld", index, ni->type, PTR_ERR(folio)); break; diff --git a/fs/ntfs/inode.h b/fs/ntfs/inode.h index a18cbcf1c6312e..7ea52c59c04b56 100644 --- a/fs/ntfs/inode.h +++ b/fs/ntfs/inode.h @@ -326,6 +326,8 @@ struct ntfs_attr { int ntfs_test_inode(struct inode *vi, void *data); int ntfs_test_inode_rcu(struct inode *vi, void *data); struct inode *ntfs_iget(struct super_block *sb, u64 mft_no); +struct inode *ntfs_attr_ilookup(struct inode *base_vi, __le32 type, + __le16 *name, u32 name_len); struct inode *ntfs_attr_iget(struct inode *base_vi, __le32 type, __le16 *name, u32 name_len); struct inode *ntfs_index_iget(struct inode *base_vi, __le16 *name, diff --git a/fs/ntfs/lcnalloc.c b/fs/ntfs/lcnalloc.c index 3ebcac4c286481..7e00016f42adee 100644 --- a/fs/ntfs/lcnalloc.c +++ b/fs/ntfs/lcnalloc.c @@ -340,7 +340,7 @@ struct runlist_element *ntfs_cluster_alloc(struct ntfs_volume *vol, const s64 st if (vol->lcn_empty_bits_per_page[index] == 0) goto next_bmp_pos; - folio = read_mapping_folio(mapping, index, NULL); + folio = ntfs_read_metadata_folio(mapping, index); if (IS_ERR(folio)) { err = PTR_ERR(folio); ntfs_error(vol->sb, "Failed to map page."); diff --git a/fs/ntfs/logfile.c b/fs/ntfs/logfile.c index 2f27ae7a3927f1..cdc951309d0ca8 100644 --- a/fs/ntfs/logfile.c +++ b/fs/ntfs/logfile.c @@ -367,7 +367,7 @@ static int ntfs_check_and_load_restart_page(struct inode *vi, to_read = le32_to_cpu(rp->system_page_size) - size; idx = (pos + size) >> PAGE_SHIFT; do { - folio = read_mapping_folio(vi->i_mapping, idx, NULL); + folio = ntfs_read_metadata_folio(vi->i_mapping, idx); if (IS_ERR(folio)) { ntfs_error(vi->i_sb, "Error mapping LogFile page (index %lu).", idx); @@ -514,7 +514,7 @@ bool ntfs_check_logfile(struct inode *log_vi, struct restart_page_header **rp) kunmap_local(kbase); folio_put(folio); } - folio = read_mapping_folio(mapping, idx, NULL); + folio = ntfs_read_metadata_folio(mapping, idx); if (IS_ERR(folio)) { ntfs_error(vol->sb, "Error mapping LogFile page (index %lu).", idx); diff --git a/fs/ntfs/mft.c b/fs/ntfs/mft.c index 60734500a40624..d2852fc68838c4 100644 --- a/fs/ntfs/mft.c +++ b/fs/ntfs/mft.c @@ -143,7 +143,7 @@ static inline struct mft_record *map_mft_record_folio(struct ntfs_inode *ni) } /* Read, map, and pin the folio. */ - folio = read_mapping_folio(mft_vi->i_mapping, index, NULL); + folio = ntfs_read_metadata_folio(mft_vi->i_mapping, index); if (!IS_ERR(folio)) { u8 *addr; @@ -549,8 +549,8 @@ static int ntfs_sync_mft_mirror_unit(struct ntfs_volume *vol, if (unit->folio_ofs + unit->len > folio_size(source)) return -EIO; - mirror = read_mapping_folio(vol->mftmirr_ino->i_mapping, - mirror_file_ofs >> PAGE_SHIFT, NULL); + mirror = ntfs_read_metadata_folio(vol->mftmirr_ino->i_mapping, + mirror_file_ofs >> PAGE_SHIFT); if (IS_ERR(mirror)) return PTR_ERR(mirror); @@ -1023,7 +1023,7 @@ static bool mft_reserved_is_free(struct ntfs_volume *vol, if (!m) return false; - folio = read_mapping_folio(vol->mft_ino->i_mapping, index, NULL); + folio = ntfs_read_metadata_folio(vol->mft_ino->i_mapping, index); if (IS_ERR(folio)) goto free_m; @@ -1199,8 +1199,8 @@ static s64 mft_bitmap_alloc_free_rec(struct ntfs_volume *vol, * for a zero bit. */ if (size) { - folio = read_mapping_folio(mftbmp_mapping, - ofs >> PAGE_SHIFT, NULL); + folio = ntfs_read_metadata_folio(mftbmp_mapping, + ofs >> PAGE_SHIFT); if (IS_ERR(folio)) { ntfs_error(vol->sb, "Failed to read mft bitmap, aborting."); return PTR_ERR(folio); @@ -1392,8 +1392,8 @@ static int ntfs_mft_bitmap_extend_allocation_nolock(struct ntfs_volume *vol) * to us. */ ll = lcn >> 3; - folio = read_mapping_folio(vol->lcnbmp_ino->i_mapping, - ll >> PAGE_SHIFT, NULL); + folio = ntfs_read_metadata_folio(vol->lcnbmp_ino->i_mapping, + ll >> PAGE_SHIFT); if (IS_ERR(folio)) { up_write(&mftbmp_ni->runlist.lock); ntfs_error(vol->sb, "Failed to read from lcn bitmap."); @@ -2207,7 +2207,7 @@ static int ntfs_mft_record_format(const struct ntfs_volume *vol, const s64 mft_n } /* Read, map, and pin the folio containing the mft record. */ - folio = read_mapping_folio(mft_vi->i_mapping, index, NULL); + folio = ntfs_read_metadata_folio(mft_vi->i_mapping, index); if (IS_ERR(folio)) { ntfs_error(vol->sb, "Failed to map page containing mft record to format 0x%llx.", (long long)mft_no); @@ -2725,7 +2725,7 @@ int ntfs_mft_record_alloc(struct ntfs_volume *vol, const int mode, index = NTFS_MFT_NR_TO_PIDX(vol, bit); ofs = NTFS_MFT_NR_TO_POFS(vol, bit); /* Read, map, and pin the folio containing the mft record. */ - folio = read_mapping_folio(vol->mft_ino->i_mapping, index, NULL); + folio = ntfs_read_metadata_folio(vol->mft_ino->i_mapping, index); if (IS_ERR(folio)) { ntfs_error(vol->sb, "Failed to map page containing allocated mft record 0x%llx.", bit); diff --git a/fs/ntfs/ntfs.h b/fs/ntfs/ntfs.h index fac72d40f5832b..f33df986f5eea8 100644 --- a/fs/ntfs/ntfs.h +++ b/fs/ntfs/ntfs.h @@ -294,6 +294,10 @@ static inline int ntfs_ffs(int x) return r; } +/* From fs/ntfs/aops.c */ +struct folio *ntfs_read_metadata_folio(struct address_space *mapping, + pgoff_t index); + /* From fs/ntfs/bdev-io.c */ int ntfs_bdev_read(struct block_device *bdev, char *data, loff_t start, size_t size); int ntfs_bdev_write(struct super_block *sb, void *buf, loff_t start, size_t size); diff --git a/fs/ntfs/super.c b/fs/ntfs/super.c index 891b5e0c384b19..103d2b1b630ba0 100644 --- a/fs/ntfs/super.c +++ b/fs/ntfs/super.c @@ -1187,8 +1187,8 @@ static bool check_mft_mirror(struct ntfs_volume *vol) folio_put(mft_folio); } /* Get the $MFT page. */ - mft_folio = read_mapping_folio(vol->mft_ino->i_mapping, - index, NULL); + mft_folio = ntfs_read_metadata_folio(vol->mft_ino->i_mapping, + index); if (IS_ERR(mft_folio)) { ntfs_error(sb, "Failed to read $MFT."); return false; @@ -1196,8 +1196,8 @@ static bool check_mft_mirror(struct ntfs_volume *vol) kmft_base = kmap_local_folio(mft_folio, 0); kmft = kmft_base; /* Get the $MFTMirr page. */ - mirr_folio = read_mapping_folio(vol->mftmirr_ino->i_mapping, - index, NULL); + mirr_folio = ntfs_read_metadata_folio(vol->mftmirr_ino->i_mapping, + index); if (IS_ERR(mirr_folio)) { ntfs_error(sb, "Failed to read $MFTMirr."); goto mft_unmap_out; @@ -1207,6 +1207,14 @@ static bool check_mft_mirror(struct ntfs_volume *vol) ++index; } + /* + * Windows 10 may leave mirror records beyond the system files + * stale. Read the full mirror to map its runlist, but only + * compare the system records, as ntfs-3g does. + */ + if (i >= FILE_first_user) + goto next_record; + /* Do not check the record if it is not in use. */ if (((struct mft_record *)kmft)->flags & MFT_RECORD_IN_USE) { /* Make sure the record is ok. */ @@ -1250,6 +1258,7 @@ static bool check_mft_mirror(struct ntfs_volume *vol) i); goto mm_unmap_out; } +next_record: kmft += vol->mft_record_size; kmirr += vol->mft_record_size; } while (++i < vol->mftmirr_size); @@ -1395,7 +1404,7 @@ static int check_windows_hibernation_status(struct ntfs_volume *vol) goto iput_out; } - folio = read_mapping_folio(vi->i_mapping, 0, NULL); + folio = ntfs_read_metadata_folio(vi->i_mapping, 0); if (IS_ERR(folio)) { ntfs_error(vol->sb, "Failed to read from hiberfil.sys."); ret = PTR_ERR(folio); @@ -1460,7 +1469,7 @@ static bool load_and_init_attrdef(struct ntfs_volume *vol) while (index < max_index) { /* Read the attrdef table and copy it into the linear buffer. */ read_partial_attrdef_page: - folio = read_mapping_folio(ino->i_mapping, index, NULL); + folio = ntfs_read_metadata_folio(ino->i_mapping, index); if (IS_ERR(folio)) goto free_iput_failed; addr = kmap_local_folio(folio, 0); @@ -1526,7 +1535,7 @@ static bool load_and_init_upcase(struct ntfs_volume *vol) while (index < max_index) { /* Read the upcase table and copy it into the linear buffer. */ read_partial_upcase_page: - folio = read_mapping_folio(ino->i_mapping, index, NULL); + folio = ntfs_read_metadata_folio(ino->i_mapping, index); if (IS_ERR(folio)) goto iput_upcase_failed; addr = kmap_local_folio(folio, 0); diff --git a/fs/ocfs2/dlmfs/userdlm.c b/fs/ocfs2/dlmfs/userdlm.c index 617c92e7b925d9..516e50a5728dac 100644 --- a/fs/ocfs2/dlmfs/userdlm.c +++ b/fs/ocfs2/dlmfs/userdlm.c @@ -162,7 +162,13 @@ static void user_dlm_unblock_lock(struct work_struct *work); static void __user_dlm_queue_lockres(struct user_lock_res *lockres) { + struct inode *inode = user_dlm_inode_from_user_lockres(lockres); + if (!(lockres->l_flags & USER_LOCK_QUEUED)) { + /* Pin the superblock through the worker's iput(). */ + if (!atomic_inc_not_zero(&inode->i_sb->s_active)) + return; + user_dlm_grab_inode_ref(lockres); INIT_WORK(&lockres->l_work, user_dlm_unblock_lock); @@ -275,9 +281,11 @@ static struct ocfs2_locking_protocol user_dlm_lproto = { static inline void user_dlm_drop_inode_ref(struct user_lock_res *lockres) { - struct inode *inode; - inode = user_dlm_inode_from_user_lockres(lockres); + struct inode *inode = user_dlm_inode_from_user_lockres(lockres); + struct super_block *sb = inode->i_sb; + iput(inode); + deactivate_super(sb); } static void user_dlm_unblock_lock(struct work_struct *work) diff --git a/fs/ocfs2/dlmglue.c b/fs/ocfs2/dlmglue.c index c281902e3becec..a4131d4dd95692 100644 --- a/fs/ocfs2/dlmglue.c +++ b/fs/ocfs2/dlmglue.c @@ -3094,9 +3094,17 @@ static void *ocfs2_dlm_seq_start(struct seq_file *m, loff_t *pos) { struct ocfs2_dlm_seq_priv *priv = m->private; struct ocfs2_lock_res *iter; + struct ocfs2_lock_res *dummy = &priv->p_iter_res; + + /* Continue or retry the snapshot left by ->next(). */ + if (*pos) + return priv->p_tmp_res.l_ops ? &priv->p_tmp_res : NULL; + /* Reads from zero and seek traversal start at the list head. */ spin_lock(&ocfs2_dlm_tracking_lock); - iter = ocfs2_dlm_next_res(&priv->p_iter_res, priv); + list_move(&dummy->l_debug_list, + &priv->p_dlm_debug->d_lockres_tracking); + iter = ocfs2_dlm_next_res(dummy, priv); if (iter) { /* Since lockres' have the lifetime of their container * (which can be inodes, ocfs2_supers, etc) we want to @@ -3105,8 +3113,11 @@ static void *ocfs2_dlm_seq_start(struct seq_file *m, loff_t *pos) * trust any pointers on the copy returned, but that's * ok as the information we want isn't typically held * in them. */ + list_move(&dummy->l_debug_list, &iter->l_debug_list); priv->p_tmp_res = *iter; iter = &priv->p_tmp_res; + } else { + priv->p_tmp_res.l_ops = NULL; } spin_unlock(&ocfs2_dlm_tracking_lock); @@ -3120,17 +3131,19 @@ static void ocfs2_dlm_seq_stop(struct seq_file *m, void *v) static void *ocfs2_dlm_seq_next(struct seq_file *m, void *v, loff_t *pos) { struct ocfs2_dlm_seq_priv *priv = m->private; - struct ocfs2_lock_res *iter = v; + struct ocfs2_lock_res *iter; struct ocfs2_lock_res *dummy = &priv->p_iter_res; (*pos)++; spin_lock(&ocfs2_dlm_tracking_lock); - iter = ocfs2_dlm_next_res(iter, priv); + iter = ocfs2_dlm_next_res(dummy, priv); list_del_init(&dummy->l_debug_list); if (iter) { list_add(&dummy->l_debug_list, &iter->l_debug_list); priv->p_tmp_res = *iter; iter = &priv->p_tmp_res; + } else { + priv->p_tmp_res.l_ops = NULL; } spin_unlock(&ocfs2_dlm_tracking_lock); diff --git a/fs/ocfs2/inode.c b/fs/ocfs2/inode.c index 80c36c60a8cef9..e225a96d375353 100644 --- a/fs/ocfs2/inode.c +++ b/fs/ocfs2/inode.c @@ -1318,15 +1318,16 @@ static void ocfs2_clear_inode(struct inode *inode) oi->ip_blkno = 0ULL; /* - * ip_jinode is used to track txns against this inode. We ensure that - * the journal is flushed before journal shutdown. Thus it is safe to - * have inodes get cleaned up after journal shutdown. + * ip_jinode is used to track txns against this inode. The journal is + * flushed before it is shut down, so an inode cleaned up after that + * has nothing left to release. Hold the shutdown lock so a journal + * found here stays allocated until the release has finished. */ - if (!osb->journal) - return; - - jbd2_journal_release_jbd_inode(osb->journal->j_journal, - &oi->ip_jinode); + down_read(&osb->journal_shutdown_sem); + if (osb->journal) + jbd2_journal_release_jbd_inode(osb->journal->j_journal, + &oi->ip_jinode); + up_read(&osb->journal_shutdown_sem); } void ocfs2_evict_inode(struct inode *inode) diff --git a/fs/ocfs2/journal.c b/fs/ocfs2/journal.c index cbb44e280d4bb5..9c4a48887c9a3a 100644 --- a/fs/ocfs2/journal.c +++ b/fs/ocfs2/journal.c @@ -352,7 +352,7 @@ static int ocfs2_commit_cache(struct ocfs2_super *osb) trace_ocfs2_commit_cache_end(journal->j_trans_id, flushed); ocfs2_wake_downconvert_thread(osb); - wake_up(&journal->j_checkpointed); + wake_up(&osb->checkpoint_event); finally: return status; } @@ -901,7 +901,6 @@ int ocfs2_journal_alloc(struct ocfs2_super *osb) atomic_set(&journal->j_num_trans, 0); init_rwsem(&journal->j_trans_barrier); - init_waitqueue_head(&journal->j_checkpointed); spin_lock_init(&journal->j_lock); journal->j_trans_id = 1UL; INIT_LIST_HEAD(&journal->j_la_cleanups); @@ -1073,12 +1072,14 @@ void ocfs2_journal_shutdown(struct ocfs2_super *osb) journal = osb->journal; if (!journal) - goto done; + return; inode = journal->j_inode; - if (journal->j_state != OCFS2_JOURNAL_LOADED) - goto done; + if (journal->j_state != OCFS2_JOURNAL_LOADED) { + down_write(&osb->journal_shutdown_sem); + goto free; + } /* need to inc inode use count - jbd2_journal_destroy will iput. */ if (!igrab(inode)) @@ -1114,6 +1115,12 @@ void ocfs2_journal_shutdown(struct ocfs2_super *osb) mlog_errno(status); } + /* + * Exclude the final JBD2 inode cleanup in ocfs2_clear_inode() while + * the journal is destroyed and freed. + */ + down_write(&osb->journal_shutdown_sem); + /* Shutdown the kernel journal system */ if (!jbd2_journal_destroy(journal->j_journal) && !status) { /* @@ -1136,10 +1143,17 @@ void ocfs2_journal_shutdown(struct ocfs2_super *osb) journal->j_state = OCFS2_JOURNAL_FREE; -done: - iput(inode); - kfree(journal); +free: + /* Serialize the removal with ocfs2_ci_fully_checkpointed(). */ + spin_lock(&trans_inc_lock); osb->journal = NULL; + spin_unlock(&trans_inc_lock); + wake_up(&osb->checkpoint_event); + kfree(journal); + up_write(&osb->journal_shutdown_sem); + + /* The journal inode's own cleanup takes the read side. */ + iput(inode); } static void ocfs2_clear_journal_error(struct super_block *sb, diff --git a/fs/ocfs2/journal.h b/fs/ocfs2/journal.h index 4b52bf7b0938e6..f6bfb5d05d3d9c 100644 --- a/fs/ocfs2/journal.h +++ b/fs/ocfs2/journal.h @@ -54,7 +54,6 @@ struct ocfs2_journal { spinlock_t j_lock; unsigned long j_trans_id; struct rw_semaphore j_trans_barrier; - wait_queue_head_t j_checkpointed; /* both fields protected by j_lock*/ struct list_head j_la_cleanups; @@ -91,11 +90,15 @@ static inline void ocfs2_set_ci_lock_trans(struct ocfs2_journal *journal, static inline int ocfs2_ci_fully_checkpointed(struct ocfs2_caching_info *ci) { int ret; - struct ocfs2_journal *journal = - OCFS2_SB(ocfs2_metadata_cache_get_super(ci))->journal; + struct ocfs2_super *osb = + OCFS2_SB(ocfs2_metadata_cache_get_super(ci)); + struct ocfs2_journal *journal; spin_lock(&trans_inc_lock); - ret = time_after(journal->j_trans_id, ci->ci_last_trans); + journal = osb->journal; + /* A NULL journal has already completed checkpointing. */ + ret = !journal || + time_after(journal->j_trans_id, ci->ci_last_trans); spin_unlock(&trans_inc_lock); return ret; } @@ -196,9 +199,6 @@ static inline void ocfs2_checkpoint_inode(struct inode *inode) if (ocfs2_mount_local(osb)) return; - if (!osb->journal) - return; - if (!ocfs2_ci_fully_checkpointed(INODE_CACHE(inode))) { /* WARNING: This only kicks off a single * checkpoint. If someone races you and adds more @@ -208,7 +208,8 @@ static inline void ocfs2_checkpoint_inode(struct inode *inode) * OK. */ ocfs2_start_checkpoint(osb); - wait_event(osb->journal->j_checkpointed, + /* The wait queue must outlive journal shutdown. */ + wait_event(osb->checkpoint_event, ocfs2_ci_fully_checkpointed(INODE_CACHE(inode))); } } diff --git a/fs/ocfs2/mmap.c b/fs/ocfs2/mmap.c index 6c570157caf16e..1c03f45e8965d0 100644 --- a/fs/ocfs2/mmap.c +++ b/fs/ocfs2/mmap.c @@ -103,7 +103,17 @@ static vm_fault_t __ocfs2_page_mkwrite(struct file *file, goto out; } err = ocfs2_write_end_nolock(mapping, pos, len, len, fsdata); - BUG_ON(err != len); + if (err != len) { + /* + * ocfs2_write_end_nolock() keeps the mmap folio locked so + * that it can be returned to the VM with VM_FAULT_LOCKED. + * On failure nobody else will unlock it, so do it here. + */ + folio_unlock(locked_folio); + mlog_errno(err); + ret = vmf_error(err); + goto out; + } ret = VM_FAULT_LOCKED; out: return ret; diff --git a/fs/ocfs2/ocfs2.h b/fs/ocfs2/ocfs2.h index e3bb3cc0b25a29..8bee145e488877 100644 --- a/fs/ocfs2/ocfs2.h +++ b/fs/ocfs2/ocfs2.h @@ -388,6 +388,7 @@ struct ocfs2_super enum ocfs2_recovery_state recovery_state; wait_queue_head_t checkpoint_event; struct ocfs2_journal *journal; + struct rw_semaphore journal_shutdown_sem; unsigned long osb_commit_interval; /* Journal triggers for checksum */ diff --git a/fs/ocfs2/super.c b/fs/ocfs2/super.c index 0781c5cbdb1199..d2021405d408d5 100644 --- a/fs/ocfs2/super.c +++ b/fs/ocfs2/super.c @@ -2048,6 +2048,7 @@ static int ocfs2_initialize_super(struct super_block *sb, } init_waitqueue_head(&osb->checkpoint_event); + init_rwsem(&osb->journal_shutdown_sem); osb->s_atime_quantum = OCFS2_DEFAULT_ATIME_QUANTUM; diff --git a/fs/smb/client/cifs_unicode.c b/fs/smb/client/cifs_unicode.c index 4a8a591f4bcac7..264595633b1e28 100644 --- a/fs/smb/client/cifs_unicode.c +++ b/fs/smb/client/cifs_unicode.c @@ -92,7 +92,7 @@ convert_sfm_char(const __u16 src_char, char *target) /* * cifs_mapchar - convert a host-endian char to proper char in codepage * @target - where converted character should be copied - * @src_char - 2 byte host-endian source character + * @from - 2 byte host-endian source character * @cp - codepage to which character should be converted * @map_type - How should the 7 NTFS/SMB reserved characters be mapped to UCS2? * @@ -126,7 +126,7 @@ cifs_mapchar(char *target, const __u16 *from, const struct nls_table *cp, /* convert SURROGATE_PAIR and IVS */ if (strcmp(cp->charset, "utf8")) goto unknown; - len = utf16s_to_utf8s(from, 3, UTF16_LITTLE_ENDIAN, target, 6); + len = utf16s_to_utf8s(from, 3, UTF16_HOST_ENDIAN, target, 6); if (len <= 0) goto unknown; return len; @@ -518,7 +518,7 @@ cifsConvertToUTF16(__le16 *target, const char *source, int srclen, } else goto unknown; ret = utf8s_to_utf16s(source + i, charlen, - UTF16_LITTLE_ENDIAN, + UTF16_HOST_ENDIAN, wchar_to, 6); if (ret < 0) goto unknown; diff --git a/fs/smb/client/cifsacl.c b/fs/smb/client/cifsacl.c index d8f30c35cbe5b4..b23cb226c4d3d6 100644 --- a/fs/smb/client/cifsacl.c +++ b/fs/smb/client/cifsacl.c @@ -1375,7 +1375,8 @@ static int parse_sec_desc(struct cifs_sb_info *cifs_sb, gsidoffset = le32_to_cpu(pntsd->gsidoffset); dacloffset = le32_to_cpu(pntsd->dacloffset); cifs_dbg(NOISY, "revision %d type 0x%x ooffset 0x%x goffset 0x%x sacloffset 0x%x dacloffset 0x%x\n", - pntsd->revision, pntsd->type, osidoffset, gsidoffset, + le16_to_cpu(pntsd->revision), le16_to_cpu(pntsd->type), + osidoffset, gsidoffset, le32_to_cpu(pntsd->sacloffset), dacloffset); fattr->cf_uid = cifs_sb->ctx->linux_uid; fattr->cf_gid = cifs_sb->ctx->linux_gid; diff --git a/fs/smb/client/cifsfs.c b/fs/smb/client/cifsfs.c index 8cff7857b45095..9faba158f8b6a3 100644 --- a/fs/smb/client/cifsfs.c +++ b/fs/smb/client/cifsfs.c @@ -418,11 +418,11 @@ static void cifs_kill_sb(struct super_block *sb) flush_workqueue(deferredclose_wq); /* - * Wait for all in-flight netfs I/O requests to finish their - * cleanup_work so that any cifsFileInfo final puts they queue - * to fileinfo_put_wq/serverclose_wq have been queued, then - * drain the workqueue so the cfile dentry refs are dropped to - * avoid the busy dentry warning. + * Wait for all in-flight netfs I/O requests and oplock breaks + * to finish so that any cifsFileInfo final puts they queue to + * fileinfo_put_wq/serverclose_wq have been queued, then drain + * the workqueue so the cfile dentry refs are dropped to avoid + * the busy dentry warning. */ wait_var_event(&cifs_sb->outstanding_rreq, !atomic_read(&cifs_sb->outstanding_rreq)); diff --git a/fs/smb/client/dfs.c b/fs/smb/client/dfs.c index 57c90a2512a3cb..f5d867ab623a17 100644 --- a/fs/smb/client/dfs.c +++ b/fs/smb/client/dfs.c @@ -23,9 +23,10 @@ int dfs_parse_target_referral(const char *full_path, const struct dfs_info3_param *ref, struct smb3_fs_context *ctx) { - int rc; const char *prepath = NULL; + char *node_name = NULL; char *path; + int rc; if (!full_path || !*full_path || !ref || !ctx) return -EINVAL; @@ -40,7 +41,12 @@ int dfs_parse_target_referral(const char *full_path, const struct dfs_info3_para prepath++; } - path = cifs_build_devname(ref->node_name, prepath); + node_name = dfs_cache_local_path(ref->node_name, ctx->local_nls); + if (IS_ERR(node_name)) + return PTR_ERR(node_name); + + path = cifs_build_devname(node_name, prepath); + kfree(node_name); if (IS_ERR(path)) return PTR_ERR(path); @@ -85,16 +91,87 @@ static void set_root_smb_session(struct cifs_mount_ctx *mnt_ctx) ctx->dfs_root_ses = ses; } +static bool dfs_is_delim(wchar_t c) +{ + return c == '/' || c == '\\'; +} + +/* + * @consumed counts bytes of the canonical (cache charset) path @cpath. + * Return the matching byte offset in @fpath, which holds the same path in + * the mount charset. Offsets are matched by path component, since the + * delimiters are ASCII in every charset and survive remapping. + */ +static int dfs_consumed_to_local(const struct nls_table *nls, + const char *cpath, const char *fpath, + int consumed) +{ + size_t clen = strlen(cpath), flen = strlen(fpath), off = 0; + int ndelims = 0, seen = 0, i; + bool ends_on_delim; + + if (consumed < 0) + return -EINVAL; + + /* Identical bytes in both strings: units already agree */ + if ((size_t)consumed <= min(clen, flen) && + !memcmp(cpath, fpath, consumed)) + return consumed; + + if ((size_t)consumed > clen) + consumed = clen; + + for (i = 0; i < consumed; i++) + if (dfs_is_delim(cpath[i])) + ndelims++; + ends_on_delim = consumed && dfs_is_delim(cpath[consumed - 1]); + + while (off < flen) { + wchar_t uni; + int len; + + len = nls->char2uni((const unsigned char *)fpath + off, + flen - off, &uni); + if (len <= 0) { + uni = (unsigned char)fpath[off]; + len = 1; + } + if (dfs_is_delim(uni)) { + /* check if start of next component */ + if (!ends_on_delim && seen == ndelims) + break; + seen++; + if (ends_on_delim && seen == ndelims) { + /* just past the last consumed delimiter */ + off += len; + break; + } + } + off += len; + } + return off; +} + static inline int parse_dfs_target(struct smb3_fs_context *ctx, struct dfs_ref_walk *rw, struct dfs_info3_param *tgt) { - int rc; const char *fpath = ref_walk_fpath(rw) + 1; + const char *cpath = ref_walk_path(rw) + 1; + int rc; rc = ref_walk_get_tgt(rw, tgt); - if (!rc) - rc = dfs_parse_target_referral(fpath, tgt, ctx); + if (!rc) { + struct dfs_info3_param local = *tgt; + int off; + + off = dfs_consumed_to_local(rw->mnt_ctx->cifs_sb->local_nls, + cpath, fpath, tgt->path_consumed); + if (off < 0) + return off; + local.path_consumed = off; + rc = dfs_parse_target_referral(fpath, &local, ctx); + } return rc; } @@ -333,6 +410,26 @@ static int target_share_matches_server(struct TCP_Server_Info *server, char *sha return rc; } + +/* + * @prefix is in the DFS cache charset, the superblock prefix in the mount + * charset. + */ +static int set_super_prepath(struct cifs_sb_info *cifs_sb, const char *prefix) +{ + char *lprefix = NULL; + int rc; + + if (prefix && *prefix) { + lprefix = dfs_cache_local_path(prefix, cifs_sb->local_nls); + if (IS_ERR(lprefix)) + return PTR_ERR(lprefix); + } + rc = cifs_update_super_prepath(cifs_sb, lprefix); + kfree(lprefix); + return rc; +} + static int tree_connect_dfs_target(const unsigned int xid, struct cifs_tcon *tcon, struct cifs_sb_info *cifs_sb, @@ -373,7 +470,7 @@ static int tree_connect_dfs_target(const unsigned int xid, rc = ops->tree_connect(xid, tcon->ses, tree, tcon); if (islink && !rc && cifs_sb) - rc = cifs_update_super_prepath(cifs_sb, prefix); + rc = set_super_prepath(cifs_sb, prefix); break; } diff --git a/fs/smb/client/dfs_cache.c b/fs/smb/client/dfs_cache.c index 02864f7acefc25..168f563d5ef64c 100644 --- a/fs/smb/client/dfs_cache.c +++ b/fs/smb/client/dfs_cache.c @@ -105,6 +105,37 @@ char *dfs_cache_canonical_path(const char *path, const struct nls_table *cp, int return npath; } +/** + * dfs_cache_local_path - convert a path from the DFS cache charset + * + * @path: path in the DFS cache charset + * @cp: codepage to convert to + * + * Return the converted path, which the caller must free, or an error pointer. + */ +char *dfs_cache_local_path(const char *path, const struct nls_table *cp) +{ + char *tmp, *npath; + int plen = 0; + + if (!path || !cp || unlikely(!cache_cp)) + return ERR_PTR(-EINVAL); + + if (!strcmp(cp->charset, cache_cp->charset)) { + npath = kstrdup(path, GFP_KERNEL); + return npath ?: ERR_PTR(-ENOMEM); + } + + tmp = (char *)cifs_strndup_to_utf16(path, strlen(path), &plen, + cache_cp, NO_MAP_UNI_RSVD); + if (!tmp) + return ERR_PTR(-ENOMEM); + + npath = cifs_strndup_from_utf16(tmp, plen, true, cp); + kfree(tmp); + return npath ?: ERR_PTR(-ENOMEM); +} + static inline bool cache_entry_expired(const struct cache_entry *ce) { struct timespec64 ts; diff --git a/fs/smb/client/dfs_cache.h b/fs/smb/client/dfs_cache.h index c99dc3546c700f..636eb15543114c 100644 --- a/fs/smb/client/dfs_cache.h +++ b/fs/smb/client/dfs_cache.h @@ -53,6 +53,7 @@ int dfs_cache_get_tgt_share(char *path, char **share, char **prefix); char *dfs_cache_canonical_path(const char *path, const struct nls_table *cp, int remap); +char *dfs_cache_local_path(const char *path, const struct nls_table *cp); int dfs_cache_remount_fs(struct cifs_sb_info *cifs_sb); void dfs_cache_refresh(struct work_struct *work); diff --git a/fs/smb/client/file.c b/fs/smb/client/file.c index f51653cb6432a7..d272320436b3b2 100644 --- a/fs/smb/client/file.c +++ b/fs/smb/client/file.c @@ -2044,6 +2044,7 @@ bool cifs_reopen_persistent_handles(struct cifs_tcon *tcon) { struct cifsFileInfo *open_file, *tmp; + struct cifs_sb_info *cifs_sb; LIST_HEAD(tmp_list); bool retry = false; int rc; @@ -2060,12 +2061,15 @@ cifs_reopen_persistent_handles(struct cifs_tcon *tcon) list_for_each_entry(open_file, &tcon->openFileList, tlist) { if (!open_file->invalidHandle) continue; + cifs_sb = CIFS_SB(open_file->dentry); cifsFileInfo_get(open_file); + atomic_inc(&cifs_sb->outstanding_rreq); list_add_tail(&open_file->rlist, &tmp_list); } spin_unlock(&tcon->open_file_lock); list_for_each_entry_safe(open_file, tmp, &tmp_list, rlist) { + cifs_sb = CIFS_SB(open_file->dentry); /* do not flush */ rc = cifs_reopen_file(open_file, false, CIFS_REOPEN_BOUND | CIFS_REOPEN_NOWAIT); @@ -2075,6 +2079,8 @@ cifs_reopen_persistent_handles(struct cifs_tcon *tcon) } list_del_init(&open_file->rlist); cifsFileInfo_put(open_file); + if (atomic_dec_and_test(&cifs_sb->outstanding_rreq)) + wake_up_var(&cifs_sb->outstanding_rreq); } return retry; } @@ -4023,6 +4029,8 @@ void cifs_oplock_break(struct work_struct *work) out: cifs_done_oplock_break(cinode); iput(inode); + if (atomic_dec_and_test(&cifs_sb->outstanding_rreq)) + wake_up_var(&cifs_sb->outstanding_rreq); } #ifdef CONFIG_SWAP diff --git a/fs/smb/client/misc.c b/fs/smb/client/misc.c index 4d0df73d15d7ac..a8f4c8644562fd 100644 --- a/fs/smb/client/misc.c +++ b/fs/smb/client/misc.c @@ -371,6 +371,8 @@ void cifs_put_writer(struct cifsInodeInfo *cinode) */ void cifs_queue_oplock_break(struct cifsFileInfo *cfile) { + struct cifs_sb_info *cifs_sb = CIFS_SB(cfile->dentry); + /* * Bump the handle refcount now while we hold the * open_file_lock to enforce the validity of it for the oplock @@ -379,8 +381,10 @@ void cifs_queue_oplock_break(struct cifsFileInfo *cfile) * * Only take a reference if the work is actually queued. */ - if (queue_work(cifsoplockd_wq, &cfile->oplock_break)) + if (queue_work(cifsoplockd_wq, &cfile->oplock_break)) { cifsFileInfo_get(cfile); + atomic_inc(&cifs_sb->outstanding_rreq); + } } void cifs_done_oplock_break(struct cifsInodeInfo *cinode) diff --git a/fs/smb/client/netmisc.c b/fs/smb/client/netmisc.c index cf737ede1ab33a..033ca8f7e15195 100644 --- a/fs/smb/client/netmisc.c +++ b/fs/smb/client/netmisc.c @@ -133,8 +133,7 @@ cifs_NTtimeToUnix(__le64 ntutc) if (t < 0) { abs_t = -t; ts.tv_nsec = (time64_t)(do_div(abs_t, 10000000) * 100); - ts.tv_nsec = -ts.tv_nsec; - ts.tv_sec = -abs_t; + set_normalized_timespec64(&ts, -abs_t, -ts.tv_nsec); } else { abs_t = t; ts.tv_nsec = (time64_t)do_div(abs_t, 10000000) * 100; diff --git a/fs/smb/client/readdir.c b/fs/smb/client/readdir.c index 525f9918148589..5d335f12eb2445 100644 --- a/fs/smb/client/readdir.c +++ b/fs/smb/client/readdir.c @@ -253,9 +253,10 @@ cifs_posix_to_fattr(struct cifs_fattr *fattr, struct smb2_posix_info *info, fattr->cf_bytes = le64_to_cpu(info->AllocationSize); fattr->cf_eof = le64_to_cpu(info->EndOfFile); + fattr->cf_createtime = le64_to_cpu(info->CreationTime); fattr->cf_atime = cifs_NTtimeToUnix(info->LastAccessTime); fattr->cf_mtime = cifs_NTtimeToUnix(info->LastWriteTime); - fattr->cf_ctime = cifs_NTtimeToUnix(info->CreationTime); + fattr->cf_ctime = cifs_NTtimeToUnix(info->ChangeTime); fattr->cf_nlink = le32_to_cpu(info->HardLinks); fattr->cf_cifsattrs = le32_to_cpu(info->DosAttributes); diff --git a/fs/smb/client/sess.c b/fs/smb/client/sess.c index fe006e9f2e1025..468bdeae2de61a 100644 --- a/fs/smb/client/sess.c +++ b/fs/smb/client/sess.c @@ -672,7 +672,7 @@ int decode_ntlmssp_challenge(char *bcc_ptr, int blob_len, } if (pblob->MessageType != NtLmChallenge) { cifs_dbg(VFS, "Incorrect message type %d\n", - pblob->MessageType); + le32_to_cpu(pblob->MessageType)); return -EINVAL; } diff --git a/fs/smb/client/smb1debug.c b/fs/smb/client/smb1debug.c index e2d013e751e54b..91b52243d67ad3 100644 --- a/fs/smb/client/smb1debug.c +++ b/fs/smb/client/smb1debug.c @@ -15,8 +15,9 @@ void cifs_dump_detail(void *buf, size_t buf_len, struct TCP_Server_Info *server) struct smb_hdr *smb = buf; cifs_dbg(VFS, "Cmd: %d Err: 0x%x Flags: 0x%x Flgs2: 0x%x Mid: %d Pid: %d Wct: %d\n", - smb->Command, smb->Status.CifsError, smb->Flags, - smb->Flags2, smb->Mid, smb->Pid, smb->WordCount); + smb->Command, le32_to_cpu(smb->Status.CifsError), + smb->Flags, le16_to_cpu(smb->Flags2), le16_to_cpu(smb->Mid), + le16_to_cpu(smb->Pid), smb->WordCount); if (!server->ops->check_message(buf, buf_len, server->total_read, server)) { cifs_dbg(VFS, "smb buf %p len %u\n", smb, server->ops->calc_smb_size(smb)); diff --git a/fs/smb/client/smb1misc.c b/fs/smb/client/smb1misc.c index cdfbbff24b72ad..ef6186b1c62f8d 100644 --- a/fs/smb/client/smb1misc.c +++ b/fs/smb/client/smb1misc.c @@ -95,14 +95,15 @@ is_valid_oplock_break(char *buffer, struct TCP_Server_Info *srv) pnotify = (struct file_notify_information *) ((char *)&pSMBr->hdr.Protocol + data_offset); cifs_dbg(FYI, "dnotify on %s Action: 0x%x\n", - pnotify->FileName, pnotify->Action); + pnotify->FileName, + le32_to_cpu(pnotify->Action)); /* cifs_dump_mem("Rcvd notify Data: ",buf, sizeof(struct smb_hdr)+60); */ return true; } if (pSMBr->hdr.Status.CifsError) { cifs_dbg(FYI, "notify err 0x%x\n", - pSMBr->hdr.Status.CifsError); + le32_to_cpu(pSMBr->hdr.Status.CifsError)); return true; } return false; diff --git a/fs/smb/client/smb2ops.c b/fs/smb/client/smb2ops.c index 298f549bd7ed37..9c16839576e907 100644 --- a/fs/smb/client/smb2ops.c +++ b/fs/smb/client/smb2ops.c @@ -454,8 +454,9 @@ smb2_dump_detail(void *buf, size_t buf_len, struct TCP_Server_Info *server) struct smb2_hdr *shdr = (struct smb2_hdr *)buf; cifs_server_dbg(VFS, "Cmd: %d Err: 0x%x Flags: 0x%x Mid: %llu Pid: %d\n", - shdr->Command, shdr->Status, shdr->Flags, shdr->MessageId, - shdr->Id.SyncId.ProcessId); + le16_to_cpu(shdr->Command), le32_to_cpu(shdr->Status), + le32_to_cpu(shdr->Flags), le64_to_cpu(shdr->MessageId), + le32_to_cpu(shdr->Id.SyncId.ProcessId)); if (!server->ops->check_message(buf, buf_len, server->total_read, server)) { cifs_server_dbg(VFS, "smb buf %p len %u\n", buf, server->ops->calc_smb_size(buf)); diff --git a/fs/smb/client/smb2pdu.c b/fs/smb/client/smb2pdu.c index b26bfb4bd91ae4..fd7499c7966490 100644 --- a/fs/smb/client/smb2pdu.c +++ b/fs/smb/client/smb2pdu.c @@ -278,7 +278,7 @@ smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon, if (smb2_command != SMB2_TREE_DISCONNECT) { spin_unlock(&tcon->tc_lock); cifs_tcon_dbg(FYI, "can not send cmd %d while umounting\n", - smb2_command); + le16_to_cpu(smb2_command)); return -ENODEV; } } @@ -1294,7 +1294,8 @@ SMB2_negotiate(const unsigned int xid, goto neg_exit; } - cifs_dbg(FYI, "mode 0x%x\n", rsp->SecurityMode); + cifs_dbg(FYI, "%s: security mode 0x%x\n", __func__, + le16_to_cpu(rsp->SecurityMode)); switch (dialect) { case SMB20_PROT_ID: @@ -4390,8 +4391,8 @@ void smb2_reconnect_server(struct work_struct *work) /* if the server is marked for termination, drop the ref count here */ if (server->terminate) { - cifs_put_tcp_session(server, true); mutex_unlock(&pserver->reconnect_mutex); + cifs_put_tcp_session(server, true); return; } @@ -4819,6 +4820,8 @@ smb2_readv_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid) rc); rdata->subreq.error = rc; rdata->result = rc; + /* the data can't be trusted, don't count it */ + rdata->got_bytes = 0; if (is_replayable_error(rc)) { trace_netfs_sreq(&rdata->subreq, netfs_sreq_trace_io_retry_needed); @@ -4898,9 +4901,8 @@ smb2_readv_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid) __set_bit(NETFS_SREQ_CLEAR_TAIL, &rdata->subreq.flags); } else { size_t trans = rdata->subreq.transferred + rdata->got_bytes; - if (trans < rdata->subreq.len && + if (!rdata->result && trans < rdata->subreq.len && rdata->subreq.start + trans >= netfs_read_remote_i_size(inode)) { - rdata->result = 0; if (rdata->subreq.start + trans >= i_size_read(inode)) __set_bit(NETFS_SREQ_HIT_EOF, &rdata->subreq.flags); else @@ -5181,14 +5183,23 @@ smb2_writev_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid) if (written > wdata->subreq.len) written &= 0xFFFF; + /* + * The server must not report more bytes than were sent. netfs + * uses the subrequest length to work out which folios this + * write has finished with, so it must not be changed here. + */ + if (written > wdata->subreq.len) { + result = smb_EIO2(smb_eio_trace_write_overlarge, + written, wdata->subreq.len); + break; + } + cifs_stats_bytes_written(tcon, written); - if (written < wdata->subreq.len) { + if (written < wdata->subreq.len) result = -ENOSPC; - } else if (written > 0) { - wdata->subreq.len = written; + else if (written > 0) __set_bit(NETFS_SREQ_MADE_PROGRESS, &wdata->subreq.flags); - } break; case MID_REQUEST_SUBMITTED: trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_req_submitted); diff --git a/fs/smb/client/smb2transport.c b/fs/smb/client/smb2transport.c index 080864b24a0c50..7c4b5faf9de65d 100644 --- a/fs/smb/client/smb2transport.c +++ b/fs/smb/client/smb2transport.c @@ -380,7 +380,7 @@ generate_smb3signingkey(struct cifs_ses *ses, */ cifs_dbg(VFS, "Session Id %*ph\n", (int)sizeof(ses->Suid), &ses->Suid); - cifs_dbg(VFS, "Cipher type %d\n", server->cipher_type); + cifs_dbg(VFS, "Cipher type %d\n", le16_to_cpu(server->cipher_type)); cifs_dbg(VFS, "Session Key %*ph\n", (int)ses->auth_key.len, ses->auth_key.response); cifs_dbg(VFS, "Signing Key %*ph\n", @@ -570,7 +570,7 @@ smb2_verify_signature(struct smb_rqst *rqst, struct TCP_Server_Info *server) /* Do not need to verify session setups with signature "BSRSPYL " */ if (memcmp(shdr->Signature, "BSRSPYL ", 8) == 0) cifs_dbg(FYI, "dummy signature received for smb command 0x%x\n", - shdr->Command); + le16_to_cpu(shdr->Command)); /* * Save off the original signature so we can modify the smb and check @@ -588,7 +588,8 @@ smb2_verify_signature(struct smb_rqst *rqst, struct TCP_Server_Info *server) if (crypto_memneq(server_response_sig, shdr->Signature, SMB2_SIGNATURE_SIZE)) { cifs_dbg(VFS, "sign fail cmd 0x%x message id 0x%llx\n", - shdr->Command, shdr->MessageId); + le16_to_cpu(shdr->Command), + le64_to_cpu(shdr->MessageId)); return -EACCES; } else return 0; @@ -711,9 +712,12 @@ smb2_check_receive(struct mid_q_entry *mid, struct TCP_Server_Info *server, int rc; rc = smb2_verify_signature(&rqst, server); - if (rc) + if (rc) { cifs_server_dbg(VFS, "SMB signature verification returned error = %d\n", - rc); + rc); + mid->mid_state = MID_RESPONSE_MALFORMED; + return rc; + } } return map_smb2_to_linux_error(mid->resp_buf, log_error); diff --git a/fs/smb/client/trace.h b/fs/smb/client/trace.h index 5331ce6dc8b36c..18760a81949c82 100644 --- a/fs/smb/client/trace.h +++ b/fs/smb/client/trace.h @@ -153,6 +153,7 @@ EM(smb_eio_trace_user_iter, "user_iter") \ EM(smb_eio_trace_write_bad_buf_type, "write_bad_buf_type") \ EM(smb_eio_trace_write_mid_state_unknown, "write_mid_state_unknown") \ + EM(smb_eio_trace_write_overlarge, "write_overlarge") \ EM(smb_eio_trace_write_rsp_malformed, "write_rsp_malformed") \ E_(smb_eio_trace_write_too_far, "write_too_far") diff --git a/fs/smb/client/transport.c b/fs/smb/client/transport.c index c51f99d7be4b31..ea1f4fe42ee5e0 100644 --- a/fs/smb/client/transport.c +++ b/fs/smb/client/transport.c @@ -101,7 +101,7 @@ void __release_mid(struct TCP_Server_Info *server, struct mid_q_entry *midEntry) midEntry->when_sent, midEntry->when_received); if (cifsFYI & CIFS_TIMER) { pr_debug("slow rsp: cmd %d mid %llu A: 0x%lx S: 0x%lx R: 0x%lx\n", - midEntry->command, midEntry->mid, + smb_cmd, midEntry->mid, now - midEntry->when_alloc, now - midEntry->when_sent, now - midEntry->when_received); @@ -1124,6 +1124,11 @@ compound_send_recv(const unsigned int xid, struct cifs_ses *ses, rc = server->ops->check_receive(mid[i], server, flags & CIFS_LOG_ERROR); + if (mid[i]->mid_state != MID_RESPONSE_READY) { + cifs_mark_compound_mids_cancelled(mid, i); + num_processed = 0; + goto out; + } num_processed = i + 1; } diff --git a/fs/smb/server/misc.c b/fs/smb/server/misc.c index 5037f37c9226e5..94781246b4d651 100644 --- a/fs/smb/server/misc.c +++ b/fs/smb/server/misc.c @@ -336,8 +336,7 @@ struct timespec64 ksmbd_NTtimeToUnix(__le64 ntutc) if (t < 0) { abs_t = -t; ts.tv_nsec = do_div(abs_t, 10000000) * 100; - ts.tv_nsec = -ts.tv_nsec; - ts.tv_sec = -abs_t; + set_normalized_timespec64(&ts, -abs_t, -ts.tv_nsec); } else { abs_t = t; ts.tv_nsec = do_div(abs_t, 10000000) * 100; diff --git a/fs/smb/server/smb2pdu.c b/fs/smb/server/smb2pdu.c index fe17d406123746..a5601d170d2328 100644 --- a/fs/smb/server/smb2pdu.c +++ b/fs/smb/server/smb2pdu.c @@ -699,7 +699,7 @@ bool is_chained_smb2_message(struct ksmbd_work *work) get_rfc1002_len(work->request_buf)) { pr_err("next command(%u) offset exceeds smb msg size\n", next_cmd); - return false; + goto last_rsp; } /* @@ -716,16 +716,21 @@ bool is_chained_smb2_message(struct ksmbd_work *work) 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; + goto last_rsp; } ksmbd_debug(SMB, "got SMB2 chained command\n"); init_chained_smb2_rsp(work); return true; - } else if (work->next_smb2_rcv_hdr_off) { + } + +last_rsp: + if (work->next_smb2_rcv_hdr_off) { /* - * This is last request in chained command, - * align response to 8 byte + * This is the last response of a compound, also when the + * compound ends early because the next command does not fit. + * Align it to 8 bytes and make it the current response, which + * is the one the caller signs. */ len = ALIGN(get_rfc1002_len(work->response_buf), 8); len = len - get_rfc1002_len(work->response_buf); @@ -1014,39 +1019,15 @@ int smb2_allocate_rsp_buf(struct ksmbd_work *work) return 0; } -static bool smb2_session_expired_cmd_allowed(struct ksmbd_work *work, - unsigned int cmd) +/* + * MS-SMB2 3.3.5.2.9 lets LOGOFF, CLOSE and LOCK proceed on an expired + * session. CANCEL is allowed too. For LOCK, smb2_lock() allows only + * unlocks, after the request has been validated. + */ +static bool smb2_session_expired_cmd_allowed(unsigned int cmd) { - struct smb2_lock_req *req; - unsigned int len, lock_count, i; - - if (cmd == SMB2_CANCEL_HE || cmd == SMB2_CLOSE_HE || - cmd == SMB2_LOGOFF_HE) - return true; - if (cmd != SMB2_LOCK_HE) - return false; - - req = ksmbd_req_buf_next(work); - if (req->hdr.NextCommand) - len = le32_to_cpu(req->hdr.NextCommand); - else { - len = get_rfc1002_len(work->request_buf); - if (len < work->next_smb2_rcv_hdr_off) - return false; - len -= work->next_smb2_rcv_hdr_off; - } - - lock_count = le16_to_cpu(req->LockCount); - if (!lock_count || len < offsetof(struct smb2_lock_req, locks) || - lock_count > (len - offsetof(struct smb2_lock_req, locks)) / - sizeof(struct smb2_lock_element)) - return false; - - for (i = 0; i < lock_count; i++) { - if (le32_to_cpu(req->locks[i].Flags) != SMB2_LOCKFLAG_UNLOCK) - return false; - } - return true; + return cmd == SMB2_CANCEL_HE || cmd == SMB2_CLOSE_HE || + cmd == SMB2_LOGOFF_HE || cmd == SMB2_LOCK_HE; } static bool smb2_session_kerberos_expired(struct ksmbd_session *sess) @@ -1124,7 +1105,7 @@ int smb2_check_user_session(struct ksmbd_work *work) pr_err("compound request on a non-valid session (state %d)\n", work->sess->state); if (smb2_session_kerberos_expired(work->sess) && - smb2_session_expired_cmd_allowed(work, cmd)) + smb2_session_expired_cmd_allowed(cmd)) return 1; return smb2_session_kerberos_expired(work->sess) ? -EKEYEXPIRED : -EINVAL; @@ -1136,7 +1117,7 @@ int smb2_check_user_session(struct ksmbd_work *work) work->sess = ksmbd_session_lookup_all_states(conn, sess_id); if (work->sess) { if (smb2_session_kerberos_expired(work->sess)) { - return smb2_session_expired_cmd_allowed(work, cmd) ? + return smb2_session_expired_cmd_allowed(cmd) ? 1 : -EKEYEXPIRED; } if (work->sess->state != SMB2_SESSION_VALID) { @@ -5296,7 +5277,8 @@ int smb2_open(struct ksmbd_work *work) if (IS_ERR(az_req)) { rc = PTR_ERR(az_req); goto err_out1; - } else if (az_req) { + } else if (az_req && + test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) { int err; if (le16_to_cpu(az_req->ccontext.DataOffset) + @@ -8866,6 +8848,7 @@ static int set_file_basic_info(struct ksmbd_file *fp, const struct mnt_idmap *idmap; __le32 attrs_mask = FILE_ATTRIBUTE_DIRECTORY_LE | FILE_ATTRIBUTE_COMPRESSED_LE; + s64 crtime, time; int rc = 0; if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE)) @@ -8881,21 +8864,25 @@ static int set_file_basic_info(struct ksmbd_file *fp, (file_info->Attributes & FILE_ATTRIBUTE_TEMPORARY_LE)) return -EINVAL; - if (file_info->CreationTime) - fp->create_time = le64_to_cpu(file_info->CreationTime); + crtime = (s64)le64_to_cpu(file_info->CreationTime); + if (crtime > 0) + fp->create_time = crtime; - if (file_info->LastAccessTime) { + time = (s64)le64_to_cpu(file_info->LastAccessTime); + if (time > 0) { attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime); attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET); } - if (file_info->ChangeTime) { - fp->change_time = le64_to_cpu(file_info->ChangeTime); + time = (s64)le64_to_cpu(file_info->ChangeTime); + if (time > 0) { + fp->change_time = time; inode_set_ctime_to_ts(inode, ksmbd_NTtimeToUnix(file_info->ChangeTime)); } - if (file_info->LastWriteTime) { + time = (s64)le64_to_cpu(file_info->LastWriteTime); + if (time > 0) { attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime); attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET | ATTR_CTIME); } @@ -8914,7 +8901,7 @@ static int set_file_basic_info(struct ksmbd_file *fp, } if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) && - (file_info->CreationTime || file_info->Attributes)) { + (crtime > 0 || file_info->Attributes)) { struct xattr_dos_attrib da = {0}; da.version = 4; @@ -10880,6 +10867,19 @@ int smb2_lock(struct ksmbd_work *work) if (smb2_compound_has_failed(work, &rsp->hdr)) return -EACCES; + /* An expired session may release byte-range locks, not take them. */ + if (work->sess && smb2_session_kerberos_expired(work->sess)) { + lock_count = le16_to_cpu(req->LockCount); + for (i = 0; i < lock_count; i++) { + if (le32_to_cpu(req->locks[i].Flags) != + SMB2_LOCKFLAG_UNLOCK) { + rsp->hdr.Status = STATUS_NETWORK_SESSION_EXPIRED; + err = -EKEYEXPIRED; + goto out2; + } + } + } + if (work->next_smb2_rcv_hdr_off && !has_file_id(req->VolatileFileId)) { ksmbd_debug(SMB, "Compound request set FID = %llu\n", diff --git a/fs/smb/server/vfs.c b/fs/smb/server/vfs.c index cb3f4f5fe9cf0b..0c95d466837032 100644 --- a/fs/smb/server/vfs.c +++ b/fs/smb/server/vfs.c @@ -1914,7 +1914,10 @@ int ksmbd_vfs_fill_dentry_attrs(struct ksmbd_work *work, if (rc) return rc; - time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime); + if (ksmbd_kstat->kstat->result_mask & STATX_BTIME) + time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->btime); + else + time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime); ksmbd_kstat->create_time = time; /* diff --git a/fs/xfs/scrub/stats.c b/fs/xfs/scrub/stats.c index 6934d76cfd156b..dfdac4e7b4ad34 100644 --- a/fs/xfs/scrub/stats.c +++ b/fs/xfs/scrub/stats.c @@ -143,7 +143,6 @@ STATIC size_t xchk_stats_estimate_bufsize( struct xchk_stats *cs) { - struct xchk_scrub_stats *css = &cs->cs_stats[0]; unsigned int i; size_t field_width; size_t ret = 0; @@ -157,7 +156,7 @@ xchk_stats_estimate_bufsize( offsetof(struct xchk_scrub_stats, checktime_us)) / sizeof(uint64_t)); - for (i = 0; i < XFS_SCRUB_TYPE_NR; i++, css++) { + for (i = 0; i < XFS_SCRUB_TYPE_NR; i++) { if (!name_map[i]) continue; diff --git a/fs/xfs/scrub/tempfile.c b/fs/xfs/scrub/tempfile.c index 59a9213a3c7ddf..6340afcc22cf7f 100644 --- a/fs/xfs/scrub/tempfile.c +++ b/fs/xfs/scrub/tempfile.c @@ -490,7 +490,6 @@ xrep_tempfile_copyin( struct xfs_buf *bp; xfs_fileoff_t flush_mask; xfs_fileoff_t end = off + len; - loff_t pos = XFS_FSB_TO_B(mp, off); int error = 0; ASSERT(S_ISREG(VFS_I(sc->tempip)->i_mode)); @@ -498,7 +497,7 @@ xrep_tempfile_copyin( /* Flush buffers to disk every 512K */ flush_mask = XFS_B_TO_FSBT(mp, (1U << 19)) - 1; - for (; off < end; off++, pos += mp->m_sb.sb_blocksize) { + for (; off < end; off++) { struct xfs_bmbt_irec map; int nmaps = 1; diff --git a/fs/xfs/xfs_bmap_util.c b/fs/xfs/xfs_bmap_util.c index 865aec3ae5ab32..73e7db3203c0b0 100644 --- a/fs/xfs/xfs_bmap_util.c +++ b/fs/xfs/xfs_bmap_util.c @@ -863,8 +863,21 @@ xfs_flush_unmap_range( error = filemap_write_and_wait_range(inode->i_mapping, start, end); if (error) return error; - truncate_pagecache_range(inode, start, end); - return 0; + + /* + * The callers go on to change the block map, so no folio may stay over + * the range. The holder of a GUP pin can mark a folio dirty again + * after the flush, with no lock of ours. A truncate drops such a folio + * if it lies inside the range. If it is a large folio that straddles + * the range, the truncate cannot split it, so it zeroes a part of the + * folio, keeps it, and reports nothing. The invalidation removes whole + * folios, changes no data, and fails on a dirty folio. + */ + error = invalidate_inode_pages2_range(inode->i_mapping, + start >> PAGE_SHIFT, end >> PAGE_SHIFT); + if (error == -EBUSY) + error = -EINVAL; + return error; } int @@ -980,7 +993,7 @@ xfs_prepare_shift( * Writeback and invalidate cache for the remainder of the file as we're * about to shift down every extent from offset to EOF. */ - error = xfs_flush_unmap_range(ip, offset, XFS_ISIZE(ip)); + error = xfs_flush_unmap_range(ip, offset, XFS_ISIZE(ip) - offset); if (error) return error; @@ -1257,6 +1270,7 @@ xfs_swap_extent_flush( { int error; + inode_dio_wait(VFS_I(ip)); error = filemap_write_and_wait(VFS_I(ip)->i_mapping); if (error) return error; @@ -1554,9 +1568,9 @@ xfs_swap_extents( * page cache safely. Once we have done this we can take the ilocks and * do the rest of the checks. */ - lock_two_nondirectories(VFS_I(ip), VFS_I(tip)); - filemap_invalidate_lock_two(VFS_I(ip)->i_mapping, - VFS_I(tip)->i_mapping); + error = xfs_ilock2_io_mmap(ip, tip); + if (error) + return error; /* Verify that both files have the same format */ if ((VFS_I(ip)->i_mode & S_IFMT) != (VFS_I(tip)->i_mode & S_IFMT)) { @@ -1762,9 +1776,7 @@ xfs_swap_extents( xfs_iunlock(ip, XFS_ILOCK_EXCL); xfs_iunlock(tip, XFS_ILOCK_EXCL); out_unlock: - filemap_invalidate_unlock_two(VFS_I(ip)->i_mapping, - VFS_I(tip)->i_mapping); - unlock_two_nondirectories(VFS_I(ip), VFS_I(tip)); + xfs_iunlock2_io_mmap(ip, tip); return error; out_trans_cancel: diff --git a/fs/xfs/xfs_file.c b/fs/xfs/xfs_file.c index d61ea8e2c8e40c..ad1ce4f99ad88c 100644 --- a/fs/xfs/xfs_file.c +++ b/fs/xfs/xfs_file.c @@ -441,6 +441,19 @@ xfs_file_write_checks( goto restart; } + /* + * Now that we are in the same IOLOCK critical section as the actual + * write, check that the inode still has the realtime flag in the state + * that the caller expects. If not, some deliberately cleared it while + * I/O is ongoing, so bail out. + */ + if (xfs_is_zoned_inode(XFS_I(inode)) != !!ac) { + xfs_warn_ratelimited(XFS_I(inode)->i_mount, + "RT flag modifying during write for inode 0x%llx.", + inode->i_ino); + return -EINVAL; + } + /* * If the offset is beyond the size of the file, we need to zero all * blocks that fall between the existing EOF and the start of this @@ -695,14 +708,6 @@ xfs_file_dio_write_aligned( unsigned int dio_flags = 0; ssize_t ret; - /* - * For always COW inodes, each bio must be aligned to the file system - * block size and not just the device sector size because we need to - * allocate a block-aligned amount of space for each write. - */ - if (xfs_is_always_cow_inode(ip)) - dio_flags |= IOMAP_DIO_FSBLOCK_ALIGNED; - ret = xfs_ilock_iocb_for_write(iocb, &iolock); if (ret) return ret; @@ -719,6 +724,15 @@ xfs_file_dio_write_aligned( xfs_ilock_demote(ip, XFS_IOLOCK_EXCL); iolock = XFS_IOLOCK_SHARED; } + + /* + * For always COW inodes, each bio must be aligned to the file system + * block size and not just the device sector size because we need to + * allocate a block-aligned amount of space for each write. The + * realtime flag can change until we hold the IOLOCK, so test only now. + */ + if (xfs_is_always_cow_inode(ip)) + dio_flags |= IOMAP_DIO_FSBLOCK_ALIGNED; if (mapping_stable_writes(iocb->ki_filp->f_mapping)) dio_flags |= IOMAP_DIO_BOUNCE; trace_xfs_file_direct_write(iocb, from); @@ -867,9 +881,15 @@ xfs_file_dio_write_unaligned( if (ret) return ret; + ret = xfs_file_write_checks(iocb, from, &iolock, NULL); + if (ret) + goto out_unlock; + /* * We can't properly handle unaligned direct I/O to reflink files yet, - * as we can't unshare a partial block. + * as we can't unshare a partial block. xfs_file_write_checks() can + * drop the iolock and take it again, and the file can be reflinked in + * between, so test for that only now. */ if (xfs_is_cow_inode(ip)) { trace_xfs_reflink_bounce_dio_write(iocb, from); @@ -877,10 +897,6 @@ xfs_file_dio_write_unaligned( goto out_unlock; } - ret = xfs_file_write_checks(iocb, from, &iolock, NULL); - if (ret) - goto out_unlock; - /* * If we are doing exclusive unaligned I/O, this must be the only I/O * in-flight. Otherwise we risk data corruption due to unwritten extent @@ -1202,6 +1218,22 @@ xfs_falloc_setsize( &iattr); } +/* + * Collapse and insert range change the file in several steps, and each step + * writes back and empties the part of the page cache that it needs. That can + * fail. Do it here for everything that is going to move, before the first + * step, so that a failure leaves the file as it was. xfs_prepare_shift() + * starts one allocation unit before the offset, so do the same. + */ +static int +xfs_falloc_flush_shift_range( + struct xfs_inode *ip, + loff_t offset) +{ + offset -= min_t(loff_t, offset, xfs_inode_alloc_unitsize(ip)); + return xfs_flush_unmap_range(ip, offset, XFS_ISIZE(ip) - offset); +} + static int xfs_falloc_collapse_range( struct file *file, @@ -1223,6 +1255,10 @@ xfs_falloc_collapse_range( if (offset + len >= i_size_read(inode)) return -EINVAL; + error = xfs_falloc_flush_shift_range(XFS_I(inode), offset); + if (error) + return error; + error = xfs_collapse_file_space(XFS_I(inode), offset, len, ac); if (error) return error; @@ -1264,9 +1300,10 @@ xfs_falloc_insert_range( * fork. This shifts back out beyond EOF, but creates an expectedly * written post-eof block. The insert is going to flush, unmap and * cancel prealloc across this whole range, so flush EOF now before we - * bump i_size to provide consistent behavior. + * bump i_size to provide consistent behavior. Flush and unmap the rest + * of the range as well, so that a failure to do so leaves i_size alone. */ - error = filemap_write_and_wait_range(inode->i_mapping, isize, isize); + error = xfs_falloc_flush_shift_range(XFS_I(inode), offset); if (error) return error; @@ -1500,6 +1537,21 @@ xfs_falloc_allocate_range( FALLOC_FL_ZERO_RANGE | FALLOC_FL_INSERT_RANGE | \ FALLOC_FL_UNSHARE_RANGE | FALLOC_FL_WRITE_ZEROES) +/* + * For zoned file systems, zeroing the first and last block of a hole punch + * requires allocating a new block to rewrite the remaining data and new zeroes + * out of place, which needs a space reservation. + */ +static inline bool +xfs_falloc_needs_zoned_resv( + struct xfs_inode *ip, + int mode) +{ + return xfs_is_zoned_inode(ip) && + (mode & (FALLOC_FL_PUNCH_HOLE | FALLOC_FL_ZERO_RANGE | + FALLOC_FL_COLLAPSE_RANGE)); +} + STATIC long __xfs_file_fallocate( struct file *file, @@ -1518,6 +1570,19 @@ __xfs_file_fallocate( if (error) goto out_unlock; + /* + * The caller looked at the realtime flag before we took the IOLOCK, to + * decide if it has to reserve space. Bail out if the flag has changed + * since. + */ + if (xfs_falloc_needs_zoned_resv(ip, mode) != !!ac) { + xfs_warn_ratelimited(ip->i_mount, + "RT flag modifying during fallocate for inode 0x%llx.", + inode->i_ino); + error = -EINVAL; + goto out_unlock; + } + /* * Must wait for all AIO to complete before we continue as AIO can * change the file size on completion without holding any locks we @@ -1613,16 +1678,11 @@ xfs_file_fallocate( return -EOPNOTSUPP; /* - * For zoned file systems, zeroing the first and last block of a hole - * punch requires allocating a new block to rewrite the remaining data - * and new zeroes out of place. Get a reservations for those before - * taking the iolock. Dip into the reserved pool because we are - * expected to be able to punch a hole even on a completely full - * file system. + * Get the reservation before taking the iolock. Dip into the reserved + * pool because we are expected to be able to punch a hole even on a + * completely full file system. */ - if (xfs_is_zoned_inode(XFS_I(inode)) && - (mode & (FALLOC_FL_PUNCH_HOLE | FALLOC_FL_ZERO_RANGE | - FALLOC_FL_COLLAPSE_RANGE))) + if (xfs_falloc_needs_zoned_resv(XFS_I(inode), mode)) return xfs_file_zoned_fallocate(file, mode, offset, len); return __xfs_file_fallocate(file, mode, offset, len, NULL); } @@ -1980,11 +2040,22 @@ __xfs_write_fault( lock_mode = XFS_MMAPLOCK_EXCL; } - if (IS_DAX(inode)) + /* + * The caller picked the zoned or the regular path with no lock held. + * The realtime flag cannot change under the MMAPLOCK, so look at it + * again, and start over if it has changed. + */ + if (xfs_is_zoned_inode(ip) != !!ac) { + xfs_warn_ratelimited(ip->i_mount, + "RT flag modifying during page fault for inode 0x%llx.", + inode->i_ino); + ret = VM_FAULT_NOPAGE; + } else if (IS_DAX(inode)) { ret = xfs_dax_fault_locked(vmf, order, true); - else + } else { ret = iomap_page_mkwrite(vmf, xfs_buffered_write_iomap_next, ac); + } xfs_iunlock(ip, lock_mode); sb_end_pagefault(inode->i_sb); diff --git a/fs/xfs/xfs_inode.c b/fs/xfs/xfs_inode.c index cb61305e4b80dc..0584ad11f92ba3 100644 --- a/fs/xfs/xfs_inode.c +++ b/fs/xfs/xfs_inode.c @@ -134,7 +134,8 @@ xfs_lock_flags_assert( * take both the i_rwsem and the invalidate_lock. These locks should *only* be * both taken in places where we need to invalidate the page cache in a race * free manner (e.g. truncate, hole punch and other extent manipulation - * functions). + * functions), or where we change inode attributes that both kinds of IO rely + * on (xfs_fileattr_set). */ void xfs_ilock( diff --git a/fs/xfs/xfs_ioctl.c b/fs/xfs/xfs_ioctl.c index f81b6e52ac403d..c76e36dadf952b 100644 --- a/fs/xfs/xfs_ioctl.c +++ b/fs/xfs/xfs_ioctl.c @@ -564,11 +564,13 @@ xfs_ioctl_setattr_xflags( /* * If S_DAX is enabled on this file, we can only switch the - * device if both support fsdax. We can't update S_DAX because - * there might be other threads walking down the access paths. + * device if both support fsdax, and the zoned code does not. + * We can't update S_DAX because there might be other threads + * walking down the access paths. */ if (IS_DAX(VFS_I(ip)) && - (mp->m_ddev_targp->bt_daxdev == NULL || + (xfs_has_zoned(mp) || + mp->m_ddev_targp->bt_daxdev == NULL || (mp->m_rtdev_targp && mp->m_rtdev_targp->bt_daxdev == NULL))) return -EINVAL; @@ -595,7 +597,7 @@ xfs_ioctl_setattr_xflags( * Make the stable writes flag match that of the device the inode * resides on when flipping the RT flag. */ - if (rtflag != XFS_IS_REALTIME_INODE(ip) && S_ISREG(VFS_I(ip)->i_mode)) + if (S_ISREG(VFS_I(ip)->i_mode)) xfs_update_stable_writes(ip); xfs_trans_ichgtime(tp, ip, XFS_ICHGTIME_CHG); @@ -757,6 +759,7 @@ xfs_fileattr_set( struct xfs_trans *tp; struct xfs_dquot *pdqp = NULL; struct xfs_dquot *olddquot = NULL; + bool isreg = S_ISREG(VFS_I(ip)->i_mode); int error; trace_xfs_ioctl_setattr(ip); @@ -804,10 +807,18 @@ xfs_fileattr_set( xfs_ioctl_setattr_prepare_dax(ip, fa); + /* + * A write fault only holds the MMAPLOCK, and it looks at the realtime + * flag and at the extent size hints more than once. Only regular files + * have write faults. + */ + if (isreg) + xfs_ilock(ip, XFS_MMAPLOCK_EXCL); + tp = xfs_ioctl_setattr_get_trans(ip, pdqp); if (IS_ERR(tp)) { error = PTR_ERR(tp); - goto error_free_dquots; + goto error_unlock; } error = xfs_ioctl_setattr_check_extsize(ip, fa); @@ -864,6 +875,8 @@ xfs_fileattr_set( skip_xattr: error = xfs_trans_commit(tp); + if (isreg) + xfs_iunlock(ip, XFS_MMAPLOCK_EXCL); /* * Release any dquot(s) the inode had kept before chown. @@ -875,7 +888,9 @@ xfs_fileattr_set( error_trans_cancel: xfs_trans_cancel(tp); -error_free_dquots: +error_unlock: + if (isreg) + xfs_iunlock(ip, XFS_MMAPLOCK_EXCL); xfs_qm_dqrele(pdqp); return error; } diff --git a/fs/xfs/xfs_iops.c b/fs/xfs/xfs_iops.c index 6c5633db30daea..e04b7d9d212d89 100644 --- a/fs/xfs/xfs_iops.c +++ b/fs/xfs/xfs_iops.c @@ -1373,6 +1373,10 @@ xfs_inode_supports_dax( if (mp->m_sb.sb_blocksize != PAGE_SIZE) return false; + /* The zoned code does not support DAX. */ + if (xfs_is_zoned_inode(ip)) + return false; + /* Device has to support DAX too. */ return xfs_inode_buftarg(ip)->bt_daxdev != NULL; } diff --git a/fs/xfs/xfs_pnfs.c b/fs/xfs/xfs_pnfs.c index 065875c8b7dab8..945f7a3e11ca71 100644 --- a/fs/xfs/xfs_pnfs.c +++ b/fs/xfs/xfs_pnfs.c @@ -147,21 +147,6 @@ xfs_fs_map_blocks( if (xfs_is_shutdown(mp)) return -EIO; - /* - * We can't export inodes residing on the realtime device. The realtime - * device doesn't have a UUID to identify it, so the client has no way - * to find it. - */ - if (XFS_IS_REALTIME_INODE(ip)) - return -ENXIO; - - /* - * The pNFS block layout spec actually supports reflink like - * functionality, but the Linux pNFS server doesn't implement it yet. - */ - if (xfs_is_reflink_inode(ip)) - return -ENXIO; - /* * Lock out any other I/O before we flush and invalidate the pagecache, * and then hand out a layout to the remote system. This is very @@ -174,6 +159,23 @@ xfs_fs_map_blocks( */ xfs_ilock(ip, XFS_IOLOCK_EXCL | XFS_MMAPLOCK_EXCL); + /* + * We can't export inodes residing on the realtime device. The realtime + * device doesn't have a UUID to identify it, so the client has no way + * to find it. The flag is set under the IOLOCK, so test only now. + */ + error = -ENXIO; + if (XFS_IS_REALTIME_INODE(ip)) + goto out_unlock; + + /* + * The pNFS block layout spec actually supports reflink like + * functionality, but the Linux pNFS server doesn't implement it yet. + * This flag is set under the IOLOCK as well. + */ + if (xfs_is_reflink_inode(ip)) + goto out_unlock; + error = -EINVAL; limit = mp->m_super->s_maxbytes; if (!write) diff --git a/fs/xfs/xfs_reflink.c b/fs/xfs/xfs_reflink.c index c5c796e2b83d18..466415a2fec1cd 100644 --- a/fs/xfs/xfs_reflink.c +++ b/fs/xfs/xfs_reflink.c @@ -1663,7 +1663,7 @@ xfs_reflink_zero_posteof( /* * Prepare two files for range cloning. Upon a successful return both inodes * will have the iolock and mmaplock held, the page cache of the out file will - * be truncated, and any leases on the out file will have been broken. This + * be invalidated, and any leases on the out file will have been broken. This * function borrows heavily from xfs_file_aio_write_checks. * * The VFS allows partial EOF blocks to "match" for dedupe even though it hasn't diff --git a/fs/xfs/xfs_rtalloc.c b/fs/xfs/xfs_rtalloc.c index 84efe5a8fb11d8..31d90828b4e9e2 100644 --- a/fs/xfs/xfs_rtalloc.c +++ b/fs/xfs/xfs_rtalloc.c @@ -1997,10 +1997,14 @@ xfs_rtallocate_rtg( if (error == -ENOSPC) { xfs_rtbuf_cache_relse(&args); error = 0; + start = 0; } } - if (!error) { + /* + * Global search, runs when the near search did not find space. + */ + if (!error && !start) { error = xfs_rtallocate_extent_size(&args, minlen, maxlen, &len, prod, &rtx); } diff --git a/fs/xfs/xfs_super.c b/fs/xfs/xfs_super.c index 5a06132aa38466..2f6999b6947e6b 100644 --- a/fs/xfs/xfs_super.c +++ b/fs/xfs/xfs_super.c @@ -916,7 +916,7 @@ xfs_statfs_data( xfs_sum_freecounter(mp, XC_FREE_BLOCKS); /* make sure st->f_bfree does not underflow */ - st->f_bfree = max(0LL, + st->f_bfree = max_t(int64_t, 0, fdblocks - xfs_freecounter_unavailable(mp, XC_FREE_BLOCKS)); /* @@ -2668,9 +2668,15 @@ init_xfs_fs(void) if (error) goto out_destroy_wq; + xfsstats.xs_stats = alloc_percpu(struct xfsstats); + if (!xfsstats.xs_stats) { + error = -ENOMEM; + goto out_mru_cache_uninit; + } + error = xfs_init_procfs(); if (error) - goto out_mru_cache_uninit; + goto out_free_stats; error = xfs_sysctl_register(); if (error) @@ -2686,16 +2692,10 @@ init_xfs_fs(void) xfsstats.xs_kobj.kobject.kset = xfs_kset; - xfsstats.xs_stats = alloc_percpu(struct xfsstats); - if (!xfsstats.xs_stats) { - error = -ENOMEM; - goto out_kset_unregister; - } - error = xfs_sysfs_init(&xfsstats.xs_kobj, &xfs_stats_ktype, NULL, "stats"); if (error) - goto out_free_stats; + goto out_kset_unregister; error = xchk_global_stats_setup(xfs_debugfs); if (error) @@ -2727,8 +2727,6 @@ init_xfs_fs(void) xchk_global_stats_teardown(); out_remove_stats_kobj: xfs_sysfs_del(&xfsstats.xs_kobj); - out_free_stats: - free_percpu(xfsstats.xs_stats); out_kset_unregister: kset_unregister(xfs_kset); out_debugfs_unregister: @@ -2736,6 +2734,8 @@ init_xfs_fs(void) xfs_sysctl_unregister(); out_cleanup_procfs: xfs_cleanup_procfs(); + out_free_stats: + free_percpu(xfsstats.xs_stats); out_mru_cache_uninit: xfs_mru_cache_uninit(); out_destroy_wq: @@ -2756,11 +2756,11 @@ exit_xfs_fs(void) #endif xchk_global_stats_teardown(); xfs_sysfs_del(&xfsstats.xs_kobj); - free_percpu(xfsstats.xs_stats); kset_unregister(xfs_kset); debugfs_remove(xfs_debugfs); xfs_sysctl_unregister(); xfs_cleanup_procfs(); + free_percpu(xfsstats.xs_stats); xfs_mru_cache_uninit(); xfs_destroy_workqueues(); xfs_destroy_caches(); diff --git a/fs/zonefs/file.c b/fs/zonefs/file.c index 319d9502ba5654..c9293e35d690c0 100644 --- a/fs/zonefs/file.c +++ b/fs/zonefs/file.c @@ -399,15 +399,16 @@ static loff_t zonefs_write_check_limits(struct file *file, loff_t pos, { struct inode *inode = file_inode(file); struct zonefs_zone *z = zonefs_inode_zone(inode); - loff_t limit = rlimit(RLIMIT_FSIZE); + u64 limit = rlimit(RLIMIT_FSIZE); loff_t max_size = z->z_capacity; - if (limit != RLIM_INFINITY) { - if (pos >= limit) { + /* No file position reaches a limit above LLONG_MAX. */ + if (limit != RLIM_INFINITY && limit <= LLONG_MAX) { + if (pos >= (loff_t)limit) { send_sig(SIGXFSZ, current, 0); return -EFBIG; } - count = min(count, limit - pos); + count = min(count, (loff_t)limit - pos); } if (!(file->f_flags & O_LARGEFILE)) diff --git a/fs/zonefs/super.c b/fs/zonefs/super.c index b97f1f2b8dda24..0fe2d277dcda07 100644 --- a/fs/zonefs/super.c +++ b/fs/zonefs/super.c @@ -615,10 +615,12 @@ static long zonefs_fname_to_fno(const struct qstr *fname) c = *rname; if (!isdigit(c)) return -ENOENT; - digit = (c - '0') * shift; + if (check_mul_overflow((long)(c - '0'), shift, &digit)) + return -ENOENT; if (check_add_overflow(fno, digit, &fno)) return -ENOENT; - shift *= 10; + if (i + 1 < len && check_mul_overflow(shift, 10L, &shift)) + return -ENOENT; } return fno; diff --git a/include/asm-generic/tlb.h b/include/asm-generic/tlb.h index 3f4a180b48f3c0..b318e3e9e66a8d 100644 --- a/include/asm-generic/tlb.h +++ b/include/asm-generic/tlb.h @@ -75,8 +75,8 @@ * - __tlb_remove_folio_pages_size() * * __tlb_remove_folio_pages_size() is the basic primitive that queues pages - * for freeing. It will return a boolean indicating if the queue is (now) - * full and a call to tlb_flush_mmu() is required. + * for freeing. It returns true when a call to tlb_flush_mmu() is required, + * either because the queue is full or a folio is near its refcount limit. * * tlb_remove_page() and tlb_remove_page_size() imply the call to * tlb_flush_mmu() when required and has no return value. @@ -249,26 +249,18 @@ extern bool __tlb_remove_page_size(struct mmu_gather *tlb, struct page *page, in bool __tlb_remove_folio_pages(struct mmu_gather *tlb, struct page *page, unsigned int nr_pages, bool delay_rmap); -#ifdef CONFIG_SMP -/* - * This both sets 'delayed_rmap', and returns true. It would be an inline - * function, except we define it before the 'struct mmu_gather'. - */ -#define tlb_delay_rmap(tlb) (((tlb)->delayed_rmap = 1), true) +#define tlb_can_delay_rmap() (true) extern void tlb_flush_rmaps(struct mmu_gather *tlb, struct vm_area_struct *vma); -#endif #endif /* * We have a no-op version of the rmap removal that doesn't * delay anything. That is used on S390, which flushes remote - * TLBs synchronously, and on UP, which doesn't have any - * remote TLBs to flush and is not preemptible due to this - * all happening under the page table lock. + * TLBs synchronously. */ -#ifndef tlb_delay_rmap -#define tlb_delay_rmap(tlb) (false) +#ifndef tlb_can_delay_rmap +#define tlb_can_delay_rmap() (false) static inline void tlb_flush_rmaps(struct mmu_gather *tlb, struct vm_area_struct *vma) { } #endif diff --git a/include/drm/drm_crtc.h b/include/drm/drm_crtc.h index be5dca538d87ed..46546006f361c8 100644 --- a/include/drm/drm_crtc.h +++ b/include/drm/drm_crtc.h @@ -908,6 +908,15 @@ struct drm_crtc_funcs { */ void (*disable_vblank)(struct drm_crtc *crtc); + /** + * @sync_vblank: + * + * Synchronizes vblank hardware and software state after switching off + * vblanks for the given CRTC. Called without holding vblank locks. Allows + * the driver to clean up vblank state outside of critical sections. + */ + void (*sync_vblank)(struct drm_crtc *crtc); + /** * @get_vblank_timestamp: * diff --git a/include/drm/drm_vblank.h b/include/drm/drm_vblank.h index 2fcef9c0f5b1ba..257b83d145ce74 100644 --- a/include/drm/drm_vblank.h +++ b/include/drm/drm_vblank.h @@ -319,6 +319,22 @@ void drm_crtc_set_max_vblank_count(struct drm_crtc *crtc, int drm_crtc_vblank_start_timer(struct drm_crtc *crtc); void drm_crtc_vblank_cancel_timer(struct drm_crtc *crtc); +void drm_crtc_vblank_stop_canceled_timer(struct drm_crtc *crtc); + +/** + * drm_crtc_vblank_stop_timer - Stops a CRTC's vblank timer + * @crtc: the CRTC + * + * Drivers should call this function to fully stop a CRTC's vblank timer. + * + * The function blocks until a running timer function has returned. + */ +static inline void drm_crtc_vblank_stop_timer(struct drm_crtc *crtc) +{ + drm_crtc_vblank_cancel_timer(crtc); + drm_crtc_vblank_stop_canceled_timer(crtc); +} + void drm_crtc_vblank_get_vblank_timeout(struct drm_crtc *crtc, ktime_t *vblank_time); /* diff --git a/include/drm/drm_vblank_helper.h b/include/drm/drm_vblank_helper.h index 28051f08d0f422..dd0029e045be44 100644 --- a/include/drm/drm_vblank_helper.h +++ b/include/drm/drm_vblank_helper.h @@ -37,6 +37,7 @@ void drm_crtc_vblank_atomic_disable(struct drm_crtc *crtc, int drm_crtc_vblank_helper_enable_vblank_timer(struct drm_crtc *crtc); void drm_crtc_vblank_helper_disable_vblank_timer(struct drm_crtc *crtc); +void drm_crtc_vblank_helper_sync_vblank_timer(struct drm_crtc *crtc); bool drm_crtc_vblank_helper_get_vblank_timestamp_from_timer(struct drm_crtc *crtc, int *max_error, ktime_t *vblank_time, @@ -51,6 +52,7 @@ bool drm_crtc_vblank_helper_get_vblank_timestamp_from_timer(struct drm_crtc *crt #define DRM_CRTC_VBLANK_TIMER_FUNCS \ .enable_vblank = drm_crtc_vblank_helper_enable_vblank_timer, \ .disable_vblank = drm_crtc_vblank_helper_disable_vblank_timer, \ + .sync_vblank = drm_crtc_vblank_helper_sync_vblank_timer, \ .get_vblank_timestamp = drm_crtc_vblank_helper_get_vblank_timestamp_from_timer #endif diff --git a/include/linux/arm-smccc.h b/include/linux/arm-smccc.h index 4de81848fe2eec..75f9d3f1723b58 100644 --- a/include/linux/arm-smccc.h +++ b/include/linux/arm-smccc.h @@ -324,6 +324,7 @@ enum arm_smccc_conduit { SMCCC_CONDUIT_HVC, }; +#ifdef CONFIG_HAVE_ARM_SMCCC_DISCOVERY /** * arm_smccc_1_1_get_conduit() * @@ -363,6 +364,12 @@ s32 arm_smccc_get_soc_id_version(void); * When ARM_SMCCC_ARCH_SOC_ID is not present, returns SMCCC_RET_NOT_SUPPORTED. */ s32 arm_smccc_get_soc_id_revision(void); +#else /* CONFIG_HAVE_ARM_SMCCC_DISCOVERY */ +#define arm_smccc_1_1_get_conduit() SMCCC_CONDUIT_NONE +#define arm_smccc_get_version() 0 +#define arm_smccc_get_soc_id_version() SMCCC_RET_NOT_SUPPORTED +#define arm_smccc_get_soc_id_revision() SMCCC_RET_NOT_SUPPORTED +#endif /* CONFIG_HAVE_ARM_SMCCC_DISCOVERY */ #ifndef __ASSEMBLY__ diff --git a/include/linux/assoc_array_priv.h b/include/linux/assoc_array_priv.h index dca733ef675038..37a9f76e1505b6 100644 --- a/include/linux/assoc_array_priv.h +++ b/include/linux/assoc_array_priv.h @@ -80,7 +80,7 @@ struct assoc_array_edit { struct assoc_array_ptr **leaf_p; struct assoc_array_ptr *dead_leaf; struct assoc_array_ptr *new_meta[3]; - struct assoc_array_ptr *excised_meta[1]; + struct assoc_array_ptr *excised_meta[2]; struct assoc_array_ptr *excised_subtree; struct assoc_array_ptr **set_backpointers[ASSOC_ARRAY_FAN_OUT]; struct assoc_array_ptr *set_backpointers_to; diff --git a/include/linux/bit_spinlock.h b/include/linux/bit_spinlock.h index 7869a6e59b6a6c..c31d4f4d09ee46 100644 --- a/include/linux/bit_spinlock.h +++ b/include/linux/bit_spinlock.h @@ -17,7 +17,7 @@ * static analysis can use. */ context_lock_struct(__context_bitlock) { }; -#define __bitlock(bitnum, addr) (struct __context_bitlock *)(bitnum + (addr)) +#define __bitlock(bitnum, addr) ((struct __context_bitlock *)((bitnum) + (addr))) /* * bit-based spin_lock() diff --git a/include/linux/blk-mq.h b/include/linux/blk-mq.h index 1a2f8d48adc4d7..3c9667854c4650 100644 --- a/include/linux/blk-mq.h +++ b/include/linux/blk-mq.h @@ -524,7 +524,8 @@ enum hctx_type { * @tag_list: List of the request queues that use this tag set. See also * request_queue.tag_set_list. * @quiesce_lock: Serializes blk_mq_[un]quiesce_tagset() against each other - * and against a request queue being added to @tag_list. + * and against a request queue being added to or removed from + * @tag_list. * @quiesce_depth: How often blk_mq_quiesce_tagset() has been called without * blk_mq_unquiesce_tagset(). * @srcu: Use as lock when type of the request queue is blocking diff --git a/include/linux/blk_types.h b/include/linux/blk_types.h index 0cc09b975d8ffb..1a5812fa405299 100644 --- a/include/linux/blk_types.h +++ b/include/linux/blk_types.h @@ -328,6 +328,7 @@ enum { BIO_ZONE_WRITE_PLUGGING, /* bio handled through zone write plugging */ BIO_EMULATES_ZONE_APPEND, /* bio emulates a zone append operation */ BIO_COMPLETE_IN_TASK, /* complete bi_end_io() in task context */ + BIO_ERROR_INJECTED, /* error injection rules already applied */ BIO_FLAG_LAST }; diff --git a/include/linux/bootconfig.h b/include/linux/bootconfig.h index 260a6f46042e12..f745068c07cdc0 100644 --- a/include/linux/bootconfig.h +++ b/include/linux/bootconfig.h @@ -63,6 +63,30 @@ struct xbc_node { #define XBC_VALUE (1 << 15) /* Maximum size of boot config is 32KB - 1 */ #define XBC_DATA_MAX (XBC_VALUE - 1) +/* Maximum size of padded boot config in initrd trailer */ +#define XBC_DATA_MAX_PADDED (XBC_DATA_MAX + BOOTCONFIG_ALIGN - 1) + +/** + * xbc_exclude_padding() - Exclude trailing null padding bytes from size + * @data: Bootconfig data (including padding). + * @size: The size of @data from the bootconfig footer. + * + * Exclude up to BOOTCONFIG_ALIGN - 1 trailing null padding bytes while + * keeping the terminal null byte of the bootconfig data, and return the + * unpadded bootconfig size. + */ +static inline __init uint32_t xbc_exclude_padding(const char *data, uint32_t size) +{ + int i; + + for (i = 0; i < BOOTCONFIG_ALIGN - 1; i++) { + if (size <= 1 || data[size - 1] != '\0' || data[size - 2] != '\0') + break; + size--; + } + + return size; +} #define XBC_NODE_MAX 8192 #define XBC_KEYLEN_MAX 256 diff --git a/include/linux/bpf-cgroup-defs.h b/include/linux/bpf-cgroup-defs.h index 0147b8bec97368..671f27ba6a620c 100644 --- a/include/linux/bpf-cgroup-defs.h +++ b/include/linux/bpf-cgroup-defs.h @@ -53,6 +53,7 @@ enum cgroup_bpf_attach_type { MAX_CGROUP_BPF_ATTACH_TYPE }; +/* Locking: see cgroup_bpf_mutex in kernel/bpf/cgroup.c */ struct cgroup_bpf { /* array of effective progs in this cgroup */ struct bpf_prog_array __rcu *effective[MAX_CGROUP_BPF_ATTACH_TYPE]; diff --git a/include/linux/bpf-cgroup.h b/include/linux/bpf-cgroup.h index 02ef7f899b3dee..dfa7a75507c965 100644 --- a/include/linux/bpf-cgroup.h +++ b/include/linux/bpf-cgroup.h @@ -421,6 +421,9 @@ static inline bool cgroup_bpf_sock_enabled(struct sock *sk, __ret; \ }) +/* Take cgroup_mutex first if you need both. See kernel/bpf/cgroup.c. */ +void cgroup_bpf_lock(void); +void cgroup_bpf_unlock(void); int cgroup_bpf_prog_attach(const union bpf_attr *attr, enum bpf_prog_type ptype, struct bpf_prog *prog); int cgroup_bpf_prog_detach(const union bpf_attr *attr, diff --git a/include/linux/bpf.h b/include/linux/bpf.h index fdbf638300fc51..a6976776e90b6a 100644 --- a/include/linux/bpf.h +++ b/include/linux/bpf.h @@ -70,6 +70,7 @@ extern spinlock_t btf_idr_lock; extern struct kobject *btf_kobj; extern struct bpf_mem_alloc bpf_global_ma, bpf_global_percpu_ma; extern bool bpf_global_ma_set; +extern struct workqueue_struct *bpf_prog_free_wq __ro_after_init; typedef u64 (*bpf_callback_t)(u64, u64, u64, u64, u64); typedef int (*bpf_iter_init_seq_priv_t)(void *private_data, @@ -299,7 +300,9 @@ struct bpf_map_owner { bool sleepable; u64 storage_cookie[MAX_BPF_CGROUP_STORAGE_TYPE]; const struct btf_type *attach_func_proto; + const struct bpf_struct_ops *st_ops; enum bpf_attach_type expected_attach_type; + u64 hook_key; }; struct bpf_map { @@ -563,7 +566,14 @@ static inline void bpf_obj_init(const struct btf_record *rec, void *obj) */ static inline void check_and_init_map_value(struct bpf_map *map, void *dst) { - bpf_obj_init(map->record, dst); + const struct btf_record *rec = map->record; + int i; + + if (IS_ERR_OR_NULL(rec)) + return; + /* Not bpf_obj_init(): an empty list_head has the address of 'dst' */ + for (i = 0; i < rec->cnt; i++) + memset(dst + rec->fields[i].offset, 0, rec->fields[i].size); } /* memcpy that is used with 8-byte aligned pointers, power-of-8 size and @@ -1416,6 +1426,7 @@ struct bpf_ksym { bool prog; u32 fp_start; u32 fp_end; + u32 fp_ret; /* a return in between, it has no frame */ }; enum bpf_tramp_prog_type { @@ -1460,7 +1471,7 @@ static inline void bpf_tramp_image_add_skip(struct bpf_tramp_image *im, struct b { struct bpf_tramp_skip *skip; - /* struct_ops trampolines and arch_bpf_trampoline_size() have no image */ + /* struct_ops trampolines and arch_bpf_trampoline_size() have none */ if (!im || !im->skips) return; skip = &im->skips[im->nr_skips++]; @@ -1838,6 +1849,7 @@ struct bpf_stream { struct llist_node *backlog_tail; /* tail of the list above */ wait_queue_head_t waitq; struct irq_work notify_work; + int refused; /* length of the last stage that did not fit */ bool notify_used; /* notify_work was queued at least once */ bool dead; }; @@ -1888,6 +1900,7 @@ struct bpf_prog_aux { struct mutex dst_mutex; /* protects dst_* pointers below, *after* prog becomes visible */ struct bpf_prog *dst_prog; struct bpf_trampoline *dst_trampoline; + enum bpf_prog_type saved_dst_ctx_type; enum bpf_prog_type saved_dst_prog_type; enum bpf_attach_type saved_dst_attach_type; bool verifier_zext; /* Zero extensions has been inserted by verifier. */ @@ -2388,7 +2401,7 @@ int bpf_struct_ops_prepare_trampoline(struct bpf_tramp_nodes *tnodes, const struct btf_func_model *model, void *stub_func, void **image, u32 *image_off, - bool allow_alloc); + bool allow_alloc, struct bpf_ksym *ksym); void bpf_struct_ops_image_free(void *image); static inline bool bpf_try_module_get(const void *data, struct module *owner) { @@ -2407,7 +2420,8 @@ static inline void bpf_module_put(const void *data, struct module *owner) int bpf_struct_ops_link_create(union bpf_attr *attr); int bpf_prog_assoc_struct_ops(struct bpf_prog *prog, struct bpf_map *map); void bpf_prog_disassoc_struct_ops(struct bpf_prog *prog); -void *bpf_prog_get_assoc_struct_ops(const struct bpf_prog_aux *aux); +void *bpf_prog_get_assoc_struct_ops(const struct bpf_prog_aux *aux, + const struct bpf_struct_ops *st_ops); u32 bpf_struct_ops_id(const void *kdata); int bpf_struct_ops_for_each_prog(const void *kdata, int (*cb)(struct bpf_prog *prog, void *data), @@ -2471,7 +2485,8 @@ static inline int bpf_prog_assoc_struct_ops(struct bpf_prog *prog, struct bpf_ma static inline void bpf_prog_disassoc_struct_ops(struct bpf_prog *prog) { } -static inline void *bpf_prog_get_assoc_struct_ops(const struct bpf_prog_aux *aux) +static inline void *bpf_prog_get_assoc_struct_ops(const struct bpf_prog_aux *aux, + const struct bpf_struct_ops *st_ops) { return NULL; } @@ -2516,6 +2531,9 @@ static inline int bpf_fsession_cnt(struct bpf_tramp_nodes *nodes) struct bpf_tramp_nodes fentries = nodes[BPF_TRAMP_FENTRY]; int cnt = 0; + if (is_struct_ops_tramp(&fentries)) + return 0; + for (int i = 0; i < nodes[BPF_TRAMP_FENTRY].nr_nodes; i++) { if (fentries.nodes[i]->link->prog->expected_attach_type == BPF_TRACE_FSESSION) cnt++; @@ -3422,6 +3440,14 @@ static inline bool has_current_bpf_ctx(void) return !!current->bpf_ctx; } +/* An async callback runs in no hook, and current is not the task that has armed it */ +extern struct bpf_run_ctx bpf_async_run_ctx; + +static inline bool bpf_in_async_cb(void) +{ + return current->bpf_ctx == &bpf_async_run_ctx; +} + void notrace bpf_prog_inc_misses_counter(struct bpf_prog *prog); void bpf_dynptr_init(struct bpf_dynptr_kern *ptr, void *data, @@ -3747,6 +3773,11 @@ static inline bool has_current_bpf_ctx(void) return false; } +static inline bool bpf_in_async_cb(void) +{ + return false; +} + static inline void bpf_prog_inc_misses_counter(struct bpf_prog *prog) { } @@ -4330,6 +4361,7 @@ int bpf_prog_stream_init(struct bpf_prog *prog, gfp_t gfp_extra_flags); 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, u32 len); int bpf_prog_stream_new_fd(struct bpf_prog *prog, enum bpf_stream_id stream_id, u32 flags); +bool bpf_stream_has_room(struct bpf_prog *prog, enum bpf_stream_id stream_id); void bpf_stream_stage_init(struct bpf_stream_stage *ss); void bpf_stream_stage_free(struct bpf_stream_stage *ss); __printf(2, 3) @@ -4344,7 +4376,8 @@ int bpf_stream_stage_dump_stack(struct bpf_stream_stage *ss); #define bpf_stream_stage(ss, prog, stream_id, expr) \ ({ \ bpf_stream_stage_init(&ss); \ - (expr); \ + if (bpf_stream_has_room(prog, stream_id)) \ + (expr); \ bpf_stream_stage_commit(&ss, prog, stream_id); \ bpf_stream_stage_free(&ss); \ }) diff --git a/include/linux/btf.h b/include/linux/btf.h index 87fad4076f0e9d..7bb3cc973c1f25 100644 --- a/include/linux/btf.h +++ b/include/linux/btf.h @@ -159,6 +159,7 @@ struct btf_struct_metas { extern const struct file_operations btf_fops; const char *btf_get_name(const struct btf *btf); +u64 btf_raw_tp_null_mask(const struct bpf_prog *prog); void btf_get(struct btf *btf); void btf_put(struct btf *btf); const struct btf_header *btf_header(const struct btf *btf); diff --git a/include/linux/cleanup.h b/include/linux/cleanup.h index 1fb8058b897d4a..1e09aead4b080e 100644 --- a/include/linux/cleanup.h +++ b/include/linux/cleanup.h @@ -207,8 +207,10 @@ * Without the NULL test it turns into a mess and the compiler can't help us. */ -#define DEFINE_FREE(_name, _type, _free) \ - static __always_inline void __free_##_name(void *p) { _type _T = *(_type *)p; _free; } +#define DEFINE_FREE(_name, _type, _free) \ + static __always_inline void __free_##_name(void *p) \ + __context_unsafe(/* _free may release a lock */) \ + { _type _T = *(_type *)p; _free; } #define __free(_name) __cleanup(__free_##_name) diff --git a/include/linux/dma-fence.h b/include/linux/dma-fence.h index dd07d128adc3b0..64330bf5256139 100644 --- a/include/linux/dma-fence.h +++ b/include/linux/dma-fence.h @@ -487,16 +487,23 @@ const char __rcu *dma_fence_timeline_name(struct dma_fence *fence); * with the fence in any way. The user must, therefore, ensure through other * means that fences get signaled eventually. * - * This function uses test_bit(), which is thread-safe. Naturally, this function - * should be used opportunistically; a fence could get signaled at any moment - * after the check is done. + * Naturally, this function should be used opportunistically; a fence could get + * signaled at any moment after the check is done. + * + * This function provides acquire ordering. This means that all stores + * preceding the signaling of a fence are visible in correct order to users of + * this function. * * Return: true if signaled, false otherwise. */ static inline bool dma_fence_test_signaled_flag(struct dma_fence *fence) { - return test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags); + /* + * The release counterpart is the test_and_set_bit() in + * dma_fence_signal_timestamp_locked(). + */ + return test_bit_acquire(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags); } /** diff --git a/include/linux/efi.h b/include/linux/efi.h index cc1df1577d5fb8..1bdb4639acef29 100644 --- a/include/linux/efi.h +++ b/include/linux/efi.h @@ -1355,10 +1355,13 @@ struct linux_efi_initrd { #define EFI_SECRET_TABLE_HEADER_GUID EFI_GUID(0x1e74f542, 0x71dd, 0x4d66, 0x96, 0x3e, 0xef, 0x42, 0x87, 0xff, 0x17, 0x3b) bool xen_efi_config_table_is_usable(const efi_guid_t *guid, unsigned long table); +bool x86_efi_config_table_is_usable(const efi_guid_t *guid, unsigned long table); static __always_inline bool efi_config_table_is_usable(const efi_guid_t *guid, unsigned long table) { + if (IS_ENABLED(CONFIG_X86) && !x86_efi_config_table_is_usable(guid, table)) + return false; if (!IS_ENABLED(CONFIG_XEN_EFI)) return true; return xen_efi_config_table_is_usable(guid, table); diff --git a/include/linux/filter.h b/include/linux/filter.h index 4f0cd67caccb80..84d770aea722b5 100644 --- a/include/linux/filter.h +++ b/include/linux/filter.h @@ -1055,6 +1055,15 @@ static inline void bpf_restore_data_end( cb->data_end = saved_data_end; } +/* + * If nothing has set the header, it points to headroom that was not written. + * The packet starts at skb->head when skb->data or the MAC header is there. + */ +static inline bool bpf_skb_has_network_header(const struct sk_buff *skb) +{ + return skb->network_header || !skb->mac_header || !skb_headroom(skb); +} + static inline u8 *bpf_skb_cb(const struct sk_buff *skb) { /* eBPF programs may read/write skb->cb[] area to transfer meta @@ -1334,6 +1343,7 @@ u64 bpf_arch_uaddress_limit(void); void arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp), void *cookie); u64 arch_bpf_timed_may_goto(void); u64 bpf_check_timed_may_goto(struct bpf_timed_may_goto *); +void bpf_timed_may_goto_check_time(const struct bpf_prog *prog); void bpf_timed_may_goto_save(const struct bpf_prog *prog, struct bpf_timed_may_goto *saved); void bpf_timed_may_goto_restore(const struct bpf_prog *prog, struct bpf_timed_may_goto *saved); bool bpf_helper_changes_pkt_data(enum bpf_func_id func_id); @@ -1948,13 +1958,14 @@ static __always_inline long __bpf_xdp_redirect_map(struct bpf_map *map, u64 inde u64 flags, const u64 flag_mask, void *lookup_elem(struct bpf_map *map, u32 key)) { - struct bpf_redirect_info *ri = bpf_net_ctx_get_ri(); const u64 action_mask = XDP_ABORTED | XDP_DROP | XDP_PASS | XDP_TX; + struct bpf_redirect_info *ri; /* Lower bits of the flags are used as return code on lookup failure */ - if (unlikely(flags & ~(action_mask | flag_mask))) + if (unlikely(!bpf_net_ctx_get() || flags & ~(action_mask | flag_mask))) return XDP_ABORTED; + ri = bpf_net_ctx_get_ri(); ri->tgt_value = lookup_elem(map, index); if (unlikely(!ri->tgt_value) && !(flags & BPF_F_BROADCAST)) { /* If the lookup fails we want to clear out the state in the diff --git a/include/linux/firmware/cirrus/cs_dsp.h b/include/linux/firmware/cirrus/cs_dsp.h index 6aa1e1b2b4a57f..b2492c55660cfa 100644 --- a/include/linux/firmware/cirrus/cs_dsp.h +++ b/include/linux/firmware/cirrus/cs_dsp.h @@ -80,36 +80,37 @@ struct cs_dsp_alg_region { * struct cs_dsp_coeff_ctl - Describes a coefficient control * @list: List node for internal use * @dsp: DSP instance associated with this control - * @cache: Cached value of the control * @fw_name: Name of the firmware * @subname: Name of the control parsed from the WMFW * @subname_len: Length of subname + * @type: One of the WMFW_CTL_TYPE_ control types defined in wmfw.h * @offset: Offset of control within alg_region in words * @len: Length of the cached value in bytes - * @type: One of the WMFW_CTL_TYPE_ control types defined in wmfw.h * @flags: Bitfield of WMFW_CTL_FLAG_ control flags defined in wmfw.h * @set: Flag indicating the value has been written by the user * @enabled: Flag indicating whether control is enabled * @alg_region: Logical region associated with this control * @priv: For use by the client + * @cache: Cached value of the control */ struct cs_dsp_coeff_ctl { struct list_head list; struct cs_dsp *dsp; - void *cache __counted_by_ptr(len); const char *fw_name; /* Subname is needed to match with firmware */ const char *subname; - unsigned int subname_len; + u16 subname_len; + u16 type; unsigned int offset; unsigned int len; - unsigned int type; - unsigned int flags; + u16 flags; unsigned int set:1; unsigned int enabled:1; struct cs_dsp_alg_region alg_region; void *priv; + + u8 cache[] __counted_by(len); }; struct cs_dsp_ops; diff --git a/include/linux/firmware/imx/sm.h b/include/linux/firmware/imx/sm.h index ba5d93bd6158f4..0aec7da0ae784d 100644 --- a/include/linux/firmware/imx/sm.h +++ b/include/linux/firmware/imx/sm.h @@ -29,6 +29,12 @@ #define SCMI_IMX952_CTRL_BYPASS_AUDMIX 8U /* WAKE AUDMIX */ #if IS_ENABLED(CONFIG_IMX_SCMI_MISC_DRV) +/** + * scmi_imx_misc_ctrl_get() - Read an i.MX MISC control + * @id: Control identifier + * @num: On entry, capacity of @val in words; on return, words read + * @val: Buffer for the control value + */ int scmi_imx_misc_ctrl_get(u32 id, u32 *num, u32 *val); int scmi_imx_misc_ctrl_set(u32 id, u32 val); #else diff --git a/include/linux/ftrace.h b/include/linux/ftrace.h index 1c2056a1a68b30..bdb6ee6bc3b9e5 100644 --- a/include/linux/ftrace.h +++ b/include/linux/ftrace.h @@ -270,7 +270,7 @@ ftrace_regs_get_kernel_stack_nth(struct ftrace_regs *fregs, unsigned int nth) stackp = (unsigned long *)ftrace_regs_get_stack_pointer(fregs); if (((unsigned long)(stackp + nth) & ~(THREAD_SIZE - 1)) == ((unsigned long)stackp & ~(THREAD_SIZE - 1))) - return *(stackp + nth); + return READ_ONCE_NOCHECK(*(stackp + nth)); return 0; } diff --git a/include/linux/iio/common/inv_sensors_timestamp.h b/include/linux/iio/common/inv_sensors_timestamp.h index 4f08204ede3b45..91690778ae88b8 100644 --- a/include/linux/iio/common/inv_sensors_timestamp.h +++ b/include/linux/iio/common/inv_sensors_timestamp.h @@ -66,6 +66,7 @@ struct inv_sensors_timestamp { u32 new_mult; u32 period; struct inv_sensors_timestamp_acc chip_period; + bool init; }; void inv_sensors_timestamp_init(struct inv_sensors_timestamp *ts, @@ -94,7 +95,7 @@ static inline void inv_sensors_timestamp_reset(struct inv_sensors_timestamp *ts) ts->it = interval_init; ts->delta = interval_init; ts->delta_counter = 0; - ts->timestamp = 0; + ts->init = false; } #endif diff --git a/include/linux/initrd.h b/include/linux/initrd.h index 7e5d26c8136f19..3086a462da764b 100644 --- a/include/linux/initrd.h +++ b/include/linux/initrd.h @@ -17,6 +17,8 @@ extern unsigned long initrd_start, initrd_end; extern void free_initrd_mem(unsigned long, unsigned long); #ifdef CONFIG_BLK_DEV_INITRD +/* initrd_end before trailing data (e.g. bootconfig) was trimmed off */ +extern unsigned long initrd_mem_end; extern void __init reserve_initrd_mem(void); extern void wait_for_initramfs(void); #else diff --git a/include/linux/input.h b/include/linux/input.h index 3381608127f72d..02047cc45d04c7 100644 --- a/include/linux/input.h +++ b/include/linux/input.h @@ -549,8 +549,6 @@ extern const struct class input_class; * @set_autocenter: Called to auto-center device * @destroy: called by input core when parent input device is being * destroyed - * @stop: called by input core when parent input device is being - * unregistered * @private: driver-specific data, will be freed automatically * @ffbit: bitmap of force feedback capabilities truly supported by * device (not emulated like ones in input_dev->ffbit) @@ -579,7 +577,6 @@ struct ff_device { void (*set_autocenter)(struct input_dev *dev, u16 magnitude); void (*destroy)(struct ff_device *); - void (*stop)(struct ff_device *); void *private; diff --git a/include/linux/io_uring_types.h b/include/linux/io_uring_types.h index 1468bcb028930b..7a835113eac3f7 100644 --- a/include/linux/io_uring_types.h +++ b/include/linux/io_uring_types.h @@ -517,6 +517,8 @@ struct io_ring_ctx { /* ctx exit and cancelation */ struct work_struct exit_work; + /* the ctx is freed after a grace period, see io_ring_exit_work() */ + struct rcu_work free_rwork; struct completion ref_comp; /* io-wq management, e.g. thread count */ diff --git a/include/linux/jbd2.h b/include/linux/jbd2.h index e3886963ba0040..69f12366a09a84 100644 --- a/include/linux/jbd2.h +++ b/include/linux/jbd2.h @@ -482,6 +482,7 @@ struct jbd2_revoke_table_s; * @h_sync: Flag for sync-on-close. * @h_reserved: Flag for handle for reserved credits. * @h_aborted: Flag indicating fatal error on handle. + * @h_invalid: Flag for a handle not attached to a journal (ext4 nojournal mode). * @h_type: For handle statistics. * @h_line_no: For handle statistics. * @h_start_jiffies: Handle Start time. diff --git a/include/linux/kasan.h b/include/linux/kasan.h index bf233bde68c7eb..c1ac7971601e05 100644 --- a/include/linux/kasan.h +++ b/include/linux/kasan.h @@ -180,10 +180,12 @@ static __always_inline void * __must_check kasan_init_slab_obj( } bool __kasan_slab_pre_free(struct kmem_cache *s, void *object, - unsigned long ip); + unsigned long ip, bool after_rcu_delay); /** * kasan_slab_pre_free - Check whether freeing a slab object is safe. + * @s: Cache the object belongs to. * @object: Object to be freed. + * @after_rcu_delay: Whether the free follows an RCU grace period. * * This function checks whether freeing the given object is safe. It may * check for double-free and invalid-free bugs and report them. @@ -193,10 +195,12 @@ bool __kasan_slab_pre_free(struct kmem_cache *s, void *object, * @Return true if freeing the object is unsafe; false otherwise. */ static __always_inline bool kasan_slab_pre_free(struct kmem_cache *s, - void *object) + void *object, + bool after_rcu_delay) { if (kasan_enabled()) - return __kasan_slab_pre_free(s, object, _RET_IP_); + return __kasan_slab_pre_free(s, object, _RET_IP_, + after_rcu_delay); return false; } @@ -424,7 +428,8 @@ static inline void *kasan_init_slab_obj(struct kmem_cache *cache, return (void *)object; } -static inline bool kasan_slab_pre_free(struct kmem_cache *s, void *object) +static inline bool kasan_slab_pre_free(struct kmem_cache *s, void *object, + bool after_rcu_delay) { return false; } @@ -495,6 +500,7 @@ void kasan_cache_create(struct kmem_cache *cache, unsigned int *size, void kasan_cache_shrink(struct kmem_cache *cache); void kasan_cache_shutdown(struct kmem_cache *cache); void kasan_record_aux_stack(void *ptr); +void kasan_mark_rcu_free_pending(void *ptr); #else /* CONFIG_KASAN_GENERIC */ @@ -512,6 +518,7 @@ static inline void kasan_cache_create(struct kmem_cache *cache, static inline void kasan_cache_shrink(struct kmem_cache *cache) {} static inline void kasan_cache_shutdown(struct kmem_cache *cache) {} static inline void kasan_record_aux_stack(void *ptr) {} +static inline void kasan_mark_rcu_free_pending(void *ptr) {} #endif /* CONFIG_KASAN_GENERIC */ diff --git a/include/linux/kvm_host.h b/include/linux/kvm_host.h index e7fc94e2910a86..fe300a22ab0f0a 100644 --- a/include/linux/kvm_host.h +++ b/include/linux/kvm_host.h @@ -1353,13 +1353,34 @@ int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc, int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc, gpa_t gpa, unsigned long len); +static __always_inline __must_check bool kvm_can_do_uaccess(struct kvm *kvm) +{ + return current->mm == kvm->mm; +} + +#define BUILD_KVM_COPY_USER_WRAPPER(fn, to_user, from_user) \ +static __always_inline __must_check unsigned long kvm_##fn(struct kvm *kvm, \ + void to_user *to, \ + const void from_user *from, \ + unsigned long n) \ +{ \ + if (!kvm_can_do_uaccess(kvm)) \ + return n; \ + \ + return __##fn(to, from, n); \ +} +BUILD_KVM_COPY_USER_WRAPPER(copy_from_user, , __user) +BUILD_KVM_COPY_USER_WRAPPER(copy_from_user_inatomic, , __user) +BUILD_KVM_COPY_USER_WRAPPER(copy_to_user, __user, ) +BUILD_KVM_COPY_USER_WRAPPER(copy_to_user_inatomic, __user, ) + #define __kvm_get_guest(kvm, gfn, offset, v) \ ({ \ unsigned long __addr = gfn_to_hva(kvm, gfn); \ typeof(v) __user *__uaddr = (typeof(__uaddr))(__addr + offset); \ int __ret = -EFAULT; \ \ - if (!kvm_is_error_hva(__addr)) \ + if (!kvm_is_error_hva(__addr) && kvm_can_do_uaccess(kvm)) \ __ret = get_user(v, __uaddr); \ __ret; \ }) @@ -1379,7 +1400,7 @@ int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc, typeof(v) __user *__uaddr = (typeof(__uaddr))(__addr + offset); \ int __ret = -EFAULT; \ \ - if (!kvm_is_error_hva(__addr)) \ + if (!kvm_is_error_hva(__addr) && kvm_can_do_uaccess(kvm)) \ __ret = put_user(v, __uaddr); \ if (!__ret) \ mark_page_dirty(kvm, gfn); \ @@ -1570,11 +1591,11 @@ void kvm_arch_vcpu_unblocking(struct kvm_vcpu *vcpu); bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu); #ifndef CONFIG_S390 -void __kvm_vcpu_kick(struct kvm_vcpu *vcpu, bool wait); +void __kvm_vcpu_kick(struct kvm_vcpu *vcpu, int request, bool force); static inline void kvm_vcpu_kick(struct kvm_vcpu *vcpu) { - __kvm_vcpu_kick(vcpu, false); + __kvm_vcpu_kick(vcpu, 0, false); } #endif @@ -1694,7 +1715,6 @@ void kvm_arch_disable_virtualization_cpu(void); bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu); int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu); bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu); -int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu); bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu); bool kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu); bool kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu *vcpu); @@ -2315,7 +2335,7 @@ static __always_inline void kvm_make_request(int req, struct kvm_vcpu *vcpu) static inline void kvm_make_request_and_kick(int req, struct kvm_vcpu *vcpu) { kvm_make_request(req, vcpu); - __kvm_vcpu_kick(vcpu, req & KVM_REQUEST_WAIT); + __kvm_vcpu_kick(vcpu, req, false); } #endif diff --git a/include/linux/list_lru.h b/include/linux/list_lru.h index a450fffe1550be..6ef5bc5396065a 100644 --- a/include/linux/list_lru.h +++ b/include/linux/list_lru.h @@ -38,6 +38,8 @@ struct list_lru_one { struct list_lru_memcg { struct rcu_head rcu; + /* owning memcg, only compared and never dereferenced */ + const void *memcg; /* array of per cgroup per node lists, indexed by node id */ struct list_lru_one node[]; }; diff --git a/include/linux/maple_tree.h b/include/linux/maple_tree.h index 691f6012daea37..3892201d7efd5f 100644 --- a/include/linux/maple_tree.h +++ b/include/linux/maple_tree.h @@ -684,7 +684,7 @@ void mt_cache_shrink(void); pr_info("Pass: %u Run:%u\n", \ atomic_read(&maple_tree_tests_passed), \ atomic_read(&maple_tree_tests_run)); \ - dump_stack(); \ + BUG_ON(1); \ } else { \ atomic_inc(&maple_tree_tests_passed); \ } \ @@ -700,7 +700,7 @@ void mt_cache_shrink(void); pr_info("Pass: %u Run:%u\n", \ atomic_read(&maple_tree_tests_passed), \ atomic_read(&maple_tree_tests_run)); \ - dump_stack(); \ + BUG_ON(1); \ } else { \ atomic_inc(&maple_tree_tests_passed); \ } \ @@ -717,7 +717,7 @@ void mt_cache_shrink(void); pr_info("Pass: %u Run:%u\n", \ atomic_read(&maple_tree_tests_passed), \ atomic_read(&maple_tree_tests_run)); \ - dump_stack(); \ + BUG_ON(1); \ } else { \ atomic_inc(&maple_tree_tests_passed); \ } \ @@ -726,16 +726,16 @@ void mt_cache_shrink(void); #define MT_WARN_ON(__tree, __x) ({ \ int ret = !!(__x); \ atomic_inc(&maple_tree_tests_run); \ - if (ret) { \ - pr_info("WARN at %s:%d (%u)\n", \ - __func__, __LINE__, __x); \ + if (!ret) { \ + atomic_inc(&maple_tree_tests_passed); \ + } else if (__ONCE_LITE_IF(ret)) { \ + pr_info("WARN at %s:%d\n", \ + __func__, __LINE__); \ mt_dump(__tree, mt_dump_hex); \ pr_info("Pass: %u Run:%u\n", \ atomic_read(&maple_tree_tests_passed), \ atomic_read(&maple_tree_tests_run)); \ - dump_stack(); \ - } else { \ - atomic_inc(&maple_tree_tests_passed); \ + WARN_ON(1); \ } \ unlikely(ret); \ }) @@ -743,17 +743,17 @@ void mt_cache_shrink(void); #define MAS_WARN_ON(__mas, __x) ({ \ int ret = !!(__x); \ atomic_inc(&maple_tree_tests_run); \ - if (ret) { \ - pr_info("WARN at %s:%d (%u)\n", \ - __func__, __LINE__, __x); \ + if (!ret) { \ + atomic_inc(&maple_tree_tests_passed); \ + } else if (__ONCE_LITE_IF(ret)) { \ + pr_info("WARN at %s:%d\n", \ + __func__, __LINE__); \ mas_dump(__mas); \ mt_dump((__mas)->tree, mt_dump_hex); \ pr_info("Pass: %u Run:%u\n", \ atomic_read(&maple_tree_tests_passed), \ atomic_read(&maple_tree_tests_run)); \ - dump_stack(); \ - } else { \ - atomic_inc(&maple_tree_tests_passed); \ + WARN_ON(1); \ } \ unlikely(ret); \ }) @@ -761,18 +761,18 @@ void mt_cache_shrink(void); #define MAS_WR_WARN_ON(__wrmas, __x) ({ \ int ret = !!(__x); \ atomic_inc(&maple_tree_tests_run); \ - if (ret) { \ - pr_info("WARN at %s:%d (%u)\n", \ - __func__, __LINE__, __x); \ + if (!ret) { \ + atomic_inc(&maple_tree_tests_passed); \ + } else if (__ONCE_LITE_IF(ret)) { \ + pr_info("WARN at %s:%d\n", \ + __func__, __LINE__); \ mas_wr_dump(__wrmas); \ mas_dump((__wrmas)->mas); \ mt_dump((__wrmas)->mas->tree, mt_dump_hex); \ pr_info("Pass: %u Run:%u\n", \ atomic_read(&maple_tree_tests_passed), \ atomic_read(&maple_tree_tests_run)); \ - dump_stack(); \ - } else { \ - atomic_inc(&maple_tree_tests_passed); \ + WARN_ON(1); \ } \ unlikely(ret); \ }) @@ -780,9 +780,9 @@ void mt_cache_shrink(void); #define MT_BUG_ON(__tree, __x) BUG_ON(__x) #define MAS_BUG_ON(__mas, __x) BUG_ON(__x) #define MAS_WR_BUG_ON(__mas, __x) BUG_ON(__x) -#define MT_WARN_ON(__tree, __x) WARN_ON(__x) -#define MAS_WARN_ON(__mas, __x) WARN_ON(__x) -#define MAS_WR_WARN_ON(__mas, __x) WARN_ON(__x) +#define MT_WARN_ON(__tree, __x) WARN_ON_ONCE(__x) +#define MAS_WARN_ON(__mas, __x) WARN_ON_ONCE(__x) +#define MAS_WR_WARN_ON(__mas, __x) WARN_ON_ONCE(__x) #endif /* CONFIG_DEBUG_MAPLE_TREE */ /** diff --git a/include/linux/mfd/arizona/pdata.h b/include/linux/mfd/arizona/pdata.h index d465dcd8c90aaf..96ef9c97d4cc26 100644 --- a/include/linux/mfd/arizona/pdata.h +++ b/include/linux/mfd/arizona/pdata.h @@ -11,6 +11,7 @@ #include #include #include +#include #define ARIZONA_GPN_DIR_MASK 0x8000 /* GPN_DIR */ #define ARIZONA_GPN_DIR_SHIFT 15 /* GPN_DIR */ @@ -100,7 +101,7 @@ struct arizona_pdata { * useful for systems where and I2S bus with multiple data * lines is mastered. */ - unsigned int max_channels_clocked[ARIZONA_MAX_AIF]; + u32 max_channels_clocked[ARIZONA_MAX_AIF]; /** GPIO5 is used for jack detection */ bool jd_gpio5; @@ -111,12 +112,6 @@ struct arizona_pdata { /** set to true if jackdet contact opens on insert */ bool jd_invert; - /** Use the headphone detect circuit to identify the accessory */ - bool hpdet_acc_id; - - /** Check for line output with HPDET method */ - bool hpdet_acc_id_line; - /** Channel to use for headphone detection */ unsigned int hpdet_channel; @@ -150,7 +145,7 @@ struct arizona_pdata { int num_micd_configs; /** Reference voltage for DMIC inputs */ - int dmic_ref[ARIZONA_MAX_INPUT]; + u32 dmic_ref[ARIZONA_MAX_INPUT]; /** MICBIAS configurations */ struct arizona_micbias micbias[ARIZONA_MAX_MICBIAS]; @@ -161,19 +156,19 @@ struct arizona_pdata { * wm5102/wm5110/wm8280/wm8997: [0]=IN1 [1]=IN2 [2]=IN3 [3]=IN4 * wm8998: [0]=IN1A [1]=IN2A [2]=IN1B [3]=IN2B */ - int inmode[ARIZONA_MAX_INPUT]; + u32 inmode[ARIZONA_MAX_INPUT]; /** Mode for outputs */ - int out_mono[ARIZONA_MAX_OUTPUT]; + bool out_mono[ARIZONA_MAX_OUTPUT]; /** Limit output volumes */ - unsigned int out_vol_limit[2 * ARIZONA_MAX_OUTPUT]; + u32 out_vol_limit[2 * ARIZONA_MAX_OUTPUT]; /** PDM speaker mute setting */ - unsigned int spk_mute[ARIZONA_MAX_PDM_SPK]; + u32 spk_mute[ARIZONA_MAX_PDM_SPK]; /** PDM speaker format */ - unsigned int spk_fmt[ARIZONA_MAX_PDM_SPK]; + u32 spk_fmt[ARIZONA_MAX_PDM_SPK]; /** Haptic actuator type */ unsigned int hap_act; diff --git a/include/linux/migrate.h b/include/linux/migrate.h index 78424b3824c294..c6cce7925b9bc8 100644 --- a/include/linux/migrate.h +++ b/include/linux/migrate.h @@ -136,6 +136,7 @@ static inline int migrate_misplaced_folio(struct folio *folio, int node) #define MIGRATE_PFN_MIGRATE (1UL << 1) #define MIGRATE_PFN_WRITE (1UL << 3) #define MIGRATE_PFN_COMPOUND (1UL << 4) +#define MIGRATE_PFN_ANON_RMAP (1UL << 5) /* mm internal */ #define MIGRATE_PFN_SHIFT 6 static inline struct page *migrate_pfn_to_page(unsigned long mpfn) diff --git a/include/linux/mlx5/mlx5_ifc.h b/include/linux/mlx5/mlx5_ifc.h index 697fc9387b73ae..37b6e47c909141 100644 --- a/include/linux/mlx5/mlx5_ifc.h +++ b/include/linux/mlx5/mlx5_ifc.h @@ -12453,8 +12453,8 @@ struct mlx5_ifc_lagc_bits { u8 reserved_at_18[0x5]; u8 lag_state[0x3]; - u8 reserved_at_20[0xc]; - u8 active_port[0x4]; + u8 reserved_at_20[0x8]; + u8 active_port[0x8]; u8 reserved_at_30[0x4]; u8 tx_remap_affinity_2[0x4]; u8 reserved_at_38[0x4]; diff --git a/include/linux/mm.h b/include/linux/mm.h index 6af3b7008f1ad1..040cff64381bf1 100644 --- a/include/linux/mm.h +++ b/include/linux/mm.h @@ -2249,9 +2249,54 @@ vm_fault_t finish_fault(struct vm_fault *vmf); * back into memory. */ -/* 127: arbitrary random number, small enough to assemble well */ -#define folio_ref_zero_or_close_to_overflow(folio) \ - ((unsigned int) folio_ref_count(folio) + 127u <= 127u) +/* Leave separate reserves for administrators and concurrent reference gains. */ +#define FOLIO_REF_COUNT_LIMIT (INT_MAX - (1U << 26)) +#define FOLIO_REF_COUNT_ADMIN_LIMIT (INT_MAX - (1U << 25)) +#define FOLIO_REF_COUNT_FLUSH_LIMIT (INT_MAX - (1U << 27)) + +bool folio_ref_count_over_limit_slowpath(const struct folio *folio, + unsigned int ref_count); + +/** + * __folio_ref_count_over_limit - Check whether to refuse more folio references. + * @folio: The folio. + * @ref_count: The sampled folio reference count. + * + * Check before adding page table mappings or other significant refcount users + * to pagecache folios (!hugetlb), either before acquiring references or + * afterwards with rollback if the operation is refused. + * + * Also required when pinning folios without a dedicated pincount that use + * GUP_PIN_COUNTING_BIAS. + * + * Checking other folios does no harm. + * + * This check is an approximation; we leave some headroom such that concurrent + * increments, batches, temporary references, or other bounded refcount + * consumers are not a problem. + * + * Return: True if the caller should refuse the operation, false otherwise. + */ +static inline bool __folio_ref_count_over_limit(const struct folio *folio, + unsigned int ref_count) +{ + if (likely(ref_count < FOLIO_REF_COUNT_LIMIT)) + return false; + return folio_ref_count_over_limit_slowpath(folio, ref_count); +} + +/** + * folio_ref_count_over_limit - Check whether to refuse more folio references. + * @folio: The folio. + * + * See __folio_ref_count_over_limit(). + * + * Return: True if the caller should refuse the operation, false otherwise. + */ +static inline bool folio_ref_count_over_limit(const struct folio *folio) +{ + return __folio_ref_count_over_limit(folio, folio_ref_count(folio)); +} /** * folio_get - Increment the reference count on a folio. @@ -2263,7 +2308,7 @@ vm_fault_t finish_fault(struct vm_fault *vmf); */ static inline void folio_get(struct folio *folio) { - VM_BUG_ON_FOLIO(folio_ref_zero_or_close_to_overflow(folio), folio); + VM_WARN_ON_FOLIO(folio_ref_count(folio) <= 0, folio); folio_ref_inc(folio); } @@ -2277,15 +2322,35 @@ static inline void get_page(struct page *page) folio_get(folio); } -static inline __must_check bool try_get_page(struct page *page) +/** + * folio_get_checked - Try to acquire a reference to a live folio. + * @folio: The folio. + * + * The caller must already hold a reference to @folio. Warn and fail on a + * non-positive refcount, and refuse additional references at the limit. + * + * Use folio_try_get() for speculative reference acquisition where the + * refcount can legitimately be zero. + * + * Return: True if the refcount was incremented, false otherwise. + */ +static inline __must_check bool folio_get_checked(struct folio *folio) { - page = compound_head(page); - if (WARN_ON_ONCE(page_ref_count(page) <= 0)) + const int ref_count = folio_ref_count(folio); + + if (WARN_ON_ONCE(ref_count <= 0)) + return false; + if (unlikely(__folio_ref_count_over_limit(folio, ref_count))) return false; - page_ref_inc(page); + folio_ref_inc(folio); return true; } +static inline __must_check bool try_get_page(struct page *page) +{ + return folio_get_checked(page_folio(page)); +} + /** * folio_put - Decrement the reference count on a folio. * @folio: The folio. @@ -2925,12 +2990,8 @@ static inline bool folio_maybe_dma_pinned(struct folio *folio) return atomic_read(&folio->_pincount) > 0; /* - * folio_ref_count() is signed. If that refcount overflows, then - * folio_ref_count() returns a negative value, and callers will avoid - * further incrementing the refcount. - * - * Here, for that overflow case, use the sign bit to count a little - * bit higher via unsigned math, and thus still get an accurate result. + * Use unsigned math so even an unexpected negative refcount is + * treated as possibly pinned. */ return ((unsigned int)folio_ref_count(folio)) >= GUP_PIN_COUNTING_BIAS; @@ -3971,23 +4032,6 @@ static inline void pagetable_free_kernel(struct ptdesc *pt) __pagetable_free(pt); } #endif -/** - * pagetable_free - Free pagetables - * @pt: The page table descriptor - * - * pagetable_free frees the memory of all page tables described by a page - * table descriptor and the memory for the descriptor itself. - */ -static inline void pagetable_free(struct ptdesc *pt) -{ - if (ptdesc_test_kernel(pt)) { - ptdesc_clear_kernel(pt); - pagetable_free_kernel(pt); - } else { - __pagetable_free(pt); - } -} - #if defined(CONFIG_SPLIT_PTE_PTLOCKS) #if ALLOC_SPLIT_PTLOCKS void __init ptlock_cache_init(void); @@ -4080,6 +4124,26 @@ static inline void pagetable_dtor(struct ptdesc *ptdesc) lruvec_stat_sub_folio(folio, NR_PAGETABLE); } +/** + * pagetable_free - Free pagetables + * @pt: The page table descriptor + * + * pagetable_free frees the memory of all page tables described by a page + * table descriptor and the memory for the descriptor itself. + */ +static inline void pagetable_free(struct ptdesc *pt) +{ + if (PageTable(ptdesc_page(pt))) + pagetable_dtor(pt); + + if (ptdesc_test_kernel(pt)) { + ptdesc_clear_kernel(pt); + pagetable_free_kernel(pt); + } else { + __pagetable_free(pt); + } +} + static inline void pagetable_dtor_free(struct ptdesc *ptdesc) { pagetable_dtor(ptdesc); @@ -4367,9 +4431,7 @@ anon_rmap_tree_iter_first(struct anon_vma *anon_vma, struct anon_vma_chain * anon_rmap_tree_iter_next(struct anon_vma_chain *avc, pgoff_t pgoff_start, pgoff_t pgoff_last); -#ifdef CONFIG_DEBUG_VM_RB void anon_rmap_tree_verify(struct anon_vma_chain *avc); -#endif #define anon_rmap_tree_foreach(avc, anon_vma, pgoff_start, pgoff_last) \ for (avc = anon_rmap_tree_iter_first(anon_vma, pgoff_start, pgoff_last); \ diff --git a/include/linux/nsc_gpio.h b/include/linux/nsc_gpio.h index d7a04a6e3783a1..342ce97975e8a8 100644 --- a/include/linux/nsc_gpio.h +++ b/include/linux/nsc_gpio.h @@ -1,5 +1,5 @@ /* SPDX-License-Identifier: GPL-2.0 */ -/** +/* nsc_gpio.c National Semiconductor GPIO common access methods. diff --git a/include/linux/pci.h b/include/linux/pci.h index aa3765a20a96c1..4c1b1e557a6076 100644 --- a/include/linux/pci.h +++ b/include/linux/pci.h @@ -363,6 +363,8 @@ struct pci_dev { struct pci_slot *slot; /* Physical slot this device is in */ unsigned int devfn; /* Encoded device & function index */ + /* Bridge secondary bus number at FW/OS handoff */ + unsigned char fw_sec_busnr; unsigned short vendor; unsigned short device; unsigned short subsystem_vendor; diff --git a/include/linux/perf_event.h b/include/linux/perf_event.h index e1e11500df097a..b52348eca6ef10 100644 --- a/include/linux/perf_event.h +++ b/include/linux/perf_event.h @@ -1236,6 +1236,7 @@ extern const struct perf_event_attr *perf_event_attrs(struct perf_event *event); extern void perf_event_print_debug(void); extern void perf_pmu_disable(struct pmu *pmu); extern void perf_pmu_enable(struct pmu *pmu); +extern bool perf_pmu_enabled(struct pmu *pmu); extern void perf_sched_cb_dec(struct pmu *pmu); extern void perf_sched_cb_inc(struct pmu *pmu); extern int perf_event_task_disable(void); diff --git a/include/linux/pgtable.h b/include/linux/pgtable.h index 780fe849ff8b7e..66d369870a740f 100644 --- a/include/linux/pgtable.h +++ b/include/linux/pgtable.h @@ -12,6 +12,7 @@ #ifdef CONFIG_MMU #include +#include #include #include #include @@ -1518,6 +1519,29 @@ static inline void arch_swap_restore(swp_entry_t entry, struct folio *folio) }) #endif +/** + * pte_table_clamped_end() - Limit a range to a single PTE table. + * @addr: Start address. + * @end: Exclusive end address. + * + * Only use pmd_addr_end() when traversing page tables, in a pattern like:: + * + * next = pmd_addr_end(addr, end); + * + * Higher levels already bound the range when PMDs are folded. Use this + * helper elsewhere to clamp the range regardless of PMD folding. + * + * Return: The exclusive end of the PTE table containing @addr, capped at @end. + */ +static inline unsigned long pte_table_clamped_end(unsigned long addr, + unsigned long end) +{ + const unsigned long pmd_end = (addr & PMD_MASK) + PMD_SIZE; + + /* Compare inclusive ends to avoid wraparounds. */ + return min(pmd_end - 1, end - 1) + 1; +} + /* * When walking page tables, we usually want to skip any p?d_none entries; * and any p?d_bad entries - reporting the error before resetting to none. diff --git a/include/linux/regmap.h b/include/linux/regmap.h index 7e888decc9fafd..ab43fb603c8070 100644 --- a/include/linux/regmap.h +++ b/include/linux/regmap.h @@ -212,6 +212,23 @@ struct reg_sequence { __ret ?: __tmp; \ }) +/** + * struct reg_field - Description of an register field + * + * @reg: Offset of the register within the regmap bank + * @lsb: lsb of the register field. + * @msb: msb of the register field. + * @id_size: port size if it has some ports + * @id_offset: address offset for each ports + */ +struct reg_field { + unsigned int reg; + unsigned int lsb; + unsigned int msb; + unsigned int id_size; + unsigned int id_offset; +}; + #ifdef CONFIG_REGMAP enum regmap_endian { @@ -581,7 +598,6 @@ typedef void (*regmap_hw_free_context)(void *context); * to perform locking. This field is ignored if custom lock/unlock * functions are used (see fields lock/unlock of * struct regmap_config). - * @free_on_exit: kfree this on exit of regmap * @write: Write operation. * @gather_write: Write operation with split register/value, return -ENOTSUPP * if not implemented on a given device. @@ -612,10 +628,13 @@ typedef void (*regmap_hw_free_context)(void *context); * DEFAULT, BIG is assumed. * @max_raw_read: Max raw read size that can be used on the bus. * @max_raw_write: Max raw write size that can be used on the bus. + * @init_limits: Optional callback to adjust the maximum raw read and write + * sizes for a device. Called with the bus context, the config and + * pointers to the limits during regmap initialization before the cache + * is initialized. */ struct regmap_bus { bool fast_io; - bool free_on_exit; regmap_hw_write write; regmap_hw_gather_write gather_write; regmap_hw_async_write async_write; @@ -632,6 +651,10 @@ struct regmap_bus { enum regmap_endian val_format_endian_default; size_t max_raw_read; size_t max_raw_write; + void (*init_limits)(void *context, + const struct regmap_config *config, + size_t *max_raw_read, + size_t *max_raw_write); }; /* @@ -1448,23 +1471,6 @@ static inline int regmap_assign_bits(struct regmap *map, unsigned int reg, int regmap_test_bits(struct regmap *map, unsigned int reg, unsigned int bits); -/** - * struct reg_field - Description of an register field - * - * @reg: Offset of the register within the regmap bank - * @lsb: lsb of the register field. - * @msb: msb of the register field. - * @id_size: port size if it has some ports - * @id_offset: address offset for each ports - */ -struct reg_field { - unsigned int reg; - unsigned int lsb; - unsigned int msb; - unsigned int id_size; - unsigned int id_offset; -}; - #define REG_FIELD(_reg, _lsb, _msb) ((struct reg_field){ \ .reg = _reg, \ .lsb = _lsb, \ @@ -1485,7 +1491,7 @@ struct regmap_field *regmap_field_alloc(struct regmap *regmap, struct reg_field reg_field); void regmap_field_free(struct regmap_field *field); -DEFINE_FREE(regmap_field, struct regmap_field *, if (_T) regmap_field_free(_T)) +DEFINE_FREE(regmap_field, struct regmap_field *, if (!IS_ERR_OR_NULL(_T)) regmap_field_free(_T)) struct regmap_field *devm_regmap_field_alloc(struct device *dev, struct regmap *regmap, struct reg_field reg_field); diff --git a/include/linux/rpmb.h b/include/linux/rpmb.h index ed3f8e431eff03..11a5d2646e385b 100644 --- a/include/linux/rpmb.h +++ b/include/linux/rpmb.h @@ -7,6 +7,7 @@ #define __RPMB_H__ #include +#include #include /** @@ -48,12 +49,14 @@ struct rpmb_descr { * struct rpmb_dev - device which can support RPMB partition * * @dev : device + * @lock : serialises requests and protects them against teardown * @id : device_id * @list_node : linked list node * @descr : RPMB description */ struct rpmb_dev { struct device dev; + struct mutex lock; int id; struct list_head list_node; struct rpmb_descr descr; diff --git a/include/linux/sched/isolation.h b/include/linux/sched/isolation.h index cf0fd03dd7a24e..ae5109450ac922 100644 --- a/include/linux/sched/isolation.h +++ b/include/linux/sched/isolation.h @@ -44,6 +44,7 @@ extern bool housekeeping_enabled(enum hk_type type); extern void housekeeping_affine(struct task_struct *t, enum hk_type type); extern bool housekeeping_test_cpu(int cpu, enum hk_type type); extern int housekeeping_update(struct cpumask *isol_mask); +extern void __init housekeeping_set_cpu(int cpu, enum hk_type type); extern void __init housekeeping_init(void); #else @@ -72,6 +73,7 @@ static inline bool housekeeping_test_cpu(int cpu, enum hk_type type) } static inline int housekeeping_update(struct cpumask *isol_mask) { return 0; } +static inline void housekeeping_set_cpu(int cpu, enum hk_type type) { } static inline void housekeeping_init(void) { } #endif /* CONFIG_CPU_ISOLATION */ diff --git a/include/linux/skbuff.h b/include/linux/skbuff.h index 6787fcf6ac3e43..cf6a8e64b40313 100644 --- a/include/linux/skbuff.h +++ b/include/linux/skbuff.h @@ -268,6 +268,7 @@ SKB_WITH_OVERHEAD((PAGE_SIZE << (ORDER)) - (X)) #define SKB_MAX_HEAD(X) (SKB_MAX_ORDER((X), 0)) #define SKB_MAX_ALLOC (SKB_MAX_ORDER(0, 2)) +#define SKB_MAX_RX_HEADROOM (U16_MAX / 2) /* return minimum truesize of one skb containing X bytes of data */ #define SKB_TRUESIZE(X) ((X) + \ @@ -3186,6 +3187,7 @@ static inline u32 skb_mac_header_len(const struct sk_buff *skb) static inline void skb_unset_mac_header(struct sk_buff *skb) { skb->mac_header = (typeof(skb->mac_header))~0U; + skb->mac_len = 0; } static inline void skb_reset_mac_header(struct sk_buff *skb) diff --git a/include/linux/skmsg.h b/include/linux/skmsg.h index d5e35f24738d5c..f0e27b4b929f10 100644 --- a/include/linux/skmsg.h +++ b/include/linux/skmsg.h @@ -196,6 +196,25 @@ static inline void sk_msg_init(struct sk_msg *msg) sg_init_marker(msg->sg.data, NR_MSG_FRAG_IDS); } +/* + * sk_msg_memcopy_from_iter() writes to byte sg.copybreak of element sg.curr, + * counted from the offset of that element. Point both past the last byte of + * the message, after something other than a copy has changed its elements. + */ +static inline void sk_msg_reset_curr(struct sk_msg *msg) +{ + if (!msg->sg.size) { + msg->sg.curr = msg->sg.start; + msg->sg.copybreak = 0; + } else { + u32 i = msg->sg.end; + + sk_msg_iter_var_prev(i); + msg->sg.curr = i; + msg->sg.copybreak = msg->sg.data[i].length; + } +} + static inline void sk_msg_xfer(struct sk_msg *dst, struct sk_msg *src, int which, u32 size) { diff --git a/include/linux/soundwire/sdw.h b/include/linux/soundwire/sdw.h index 9e71ae68e9d927..985b9c23557094 100644 --- a/include/linux/soundwire/sdw.h +++ b/include/linux/soundwire/sdw.h @@ -289,8 +289,8 @@ struct sdw_dp0_prop { * @ch_prep_timeout: Port-specific timeout value, in milliseconds * @imp_def_interrupts: If set, each bit corresponds to support for * implementation-defined interrupts - * @max_ch: Maximum channels supported - * @min_ch: Minimum channels supported + * @max_ch: Maximum Channel Number of this Audio Port + * @min_ch: Minimum Channel Number of this Audio Port * @num_channels: Number of discrete channels supported * @num_ch_combinations: Number of channel combinations supported * @channels: Discrete channels supported diff --git a/include/linux/srcu.h b/include/linux/srcu.h index d4dcaeb83e2b63..380b5964fcb499 100644 --- a/include/linux/srcu.h +++ b/include/linux/srcu.h @@ -280,6 +280,10 @@ static inline int srcu_read_lock_held(const struct srcu_struct *ssp) * with __guarded_by(ssp) as it would complicate annotations for writers, we * choose the following strategy: srcu_dereference_check() calls this helper * that checks that the passed ssp is held, and then fake-acquires 'RCU'. + * srcu_dereference_check() only calls this helper if @c is the compile-time + * constant 0 because otherwise its callers may satisfy the condition @c + * instead of holding ssp, e.g. on the update side. srcu_dereference_notrace() + * passes 1 as @c and hence calls this helper explicitly. */ static inline void __srcu_read_lock_must_hold(const struct srcu_struct *ssp) __must_hold_shared(ssp) { } @@ -297,7 +301,8 @@ static inline void __srcu_read_lock_must_hold(const struct srcu_struct *ssp) __m */ #define srcu_dereference_check(p, ssp, c) \ ({ \ - __srcu_read_lock_must_hold(ssp); \ + if (const_true(!(c))) \ + __srcu_read_lock_must_hold(ssp); \ __acquire_shared_ctx_lock(RCU); \ __auto_type __v = __rcu_dereference_check((p), __UNIQUE_ID(rcu), \ (c) || srcu_read_lock_held(ssp), __rcu); \ @@ -323,7 +328,11 @@ static inline void __srcu_read_lock_must_hold(const struct srcu_struct *ssp) __m * @ssp: pointer to the srcu_struct, which is used to check that we * really are in an SRCU read-side critical section. */ -#define srcu_dereference_notrace(p, ssp) srcu_dereference_check((p), (ssp), 1) +#define srcu_dereference_notrace(p, ssp) \ +({ \ + __srcu_read_lock_must_hold(ssp); \ + srcu_dereference_check((p), (ssp), 1); \ +}) /** * srcu_read_lock - register a new reader for an SRCU-protected structure. diff --git a/include/linux/tcp.h b/include/linux/tcp.h index e6b79cf4798f49..d4b07fbae2d5f1 100644 --- a/include/linux/tcp.h +++ b/include/linux/tcp.h @@ -516,6 +516,9 @@ struct tcp_sock { #if IS_ENABLED(CONFIG_MPTCP) bool is_mptcp; #endif +#if IS_ENABLED(CONFIG_AF_KCM) + bool kcm_attached; +#endif #if IS_ENABLED(CONFIG_SMC) bool syn_smc; /* SYN includes SMC */ bool (*smc_hs_congested)(const struct sock *sk); diff --git a/include/linux/trace_events.h b/include/linux/trace_events.h index 321f2f3a6c8e8f..7a0aa23825de45 100644 --- a/include/linux/trace_events.h +++ b/include/linux/trace_events.h @@ -764,7 +764,7 @@ bool __trace_trigger_soft_disabled(struct trace_event_file *file); static __always_inline bool trace_trigger_soft_disabled(struct trace_event_file *file) { - unsigned long eflags = file->flags; + unsigned long eflags = READ_ONCE(file->flags); if (likely(!(eflags & (EVENT_FILE_FL_TRIGGER_MODE | EVENT_FILE_FL_SOFT_DISABLED | diff --git a/include/linux/uprobes.h b/include/linux/uprobes.h index d34dbc0fbbfe1a..43b250bff16251 100644 --- a/include/linux/uprobes.h +++ b/include/linux/uprobes.h @@ -239,6 +239,7 @@ extern void uprobe_copy_from_page(struct page *page, unsigned long vaddr, void * extern void handle_syscall_uprobe(struct pt_regs *regs, unsigned long bp_vaddr); extern void arch_uprobe_optimize(struct arch_uprobe *auprobe, unsigned long vaddr); extern unsigned long arch_uprobe_get_xol_area(void); +extern bool arch_uprobe_regs_writable(int off, int size); #else /* !CONFIG_UPROBES */ struct uprobes_state { }; @@ -300,5 +301,9 @@ static inline void uprobe_copy_process(struct task_struct *t, u64 flags) static inline void uprobe_clear_state(struct mm_struct *mm) { } +static inline bool arch_uprobe_regs_writable(int off, int size) +{ + return false; +} #endif /* !CONFIG_UPROBES */ #endif /* _LINUX_UPROBES_H */ diff --git a/include/linux/user_events.h b/include/linux/user_events.h index 57d1ff0060901a..75f1841267275c 100644 --- a/include/linux/user_events.h +++ b/include/linux/user_events.h @@ -27,28 +27,26 @@ struct user_event_mm { struct rcu_work put_rwork; }; -extern void user_event_mm_dup(struct task_struct *t, - struct user_event_mm *old_mm); +int user_event_mm_dup(struct task_struct *t, struct user_event_mm *old_mm); extern void user_event_mm_remove(struct task_struct *t); -static inline void user_events_fork(struct task_struct *t, - u64 clone_flags) +static inline int user_events_fork(struct task_struct *t, u64 clone_flags) { struct user_event_mm *old_mm; if (!t || !current->user_event_mm) - return; + return 0; old_mm = current->user_event_mm; if (clone_flags & CLONE_VM) { t->user_event_mm = old_mm; refcount_inc(&old_mm->tasks); - return; + return 0; } - user_event_mm_dup(t, old_mm); + return user_event_mm_dup(t, old_mm); } static inline void user_events_execve(struct task_struct *t) @@ -67,9 +65,9 @@ static inline void user_events_exit(struct task_struct *t) user_event_mm_remove(t); } #else -static inline void user_events_fork(struct task_struct *t, - u64 clone_flags) +static inline int user_events_fork(struct task_struct *t, u64 clone_flags) { + return 0; } static inline void user_events_execve(struct task_struct *t) diff --git a/include/linux/userfaultfd_k.h b/include/linux/userfaultfd_k.h index dff9a5c9a0dfa4..5768a3902c7c60 100644 --- a/include/linux/userfaultfd_k.h +++ b/include/linux/userfaultfd_k.h @@ -277,6 +277,7 @@ extern int userfaultfd_unmap_prep(struct vm_area_struct *vma, unsigned long start, unsigned long end, struct list_head *uf); extern void userfaultfd_unmap_complete(struct mm_struct *mm, struct list_head *uf); +void userfaultfd_unmap_abort(struct list_head *uf); extern bool userfaultfd_wp_unpopulated(struct vm_area_struct *vma); extern bool userfaultfd_wp_async(struct vm_area_struct *vma); extern bool userfaultfd_rwp_async(struct vm_area_struct *vma); @@ -443,6 +444,10 @@ static inline void userfaultfd_unmap_complete(struct mm_struct *mm, { } +static inline void userfaultfd_unmap_abort(struct list_head *uf) +{ +} + static inline bool uffd_disable_fault_around(struct vm_area_struct *vma) { return false; diff --git a/include/linux/wait.h b/include/linux/wait.h index c2af98b0074dcb..09518f8ff10cd4 100644 --- a/include/linux/wait.h +++ b/include/linux/wait.h @@ -21,6 +21,7 @@ int default_wake_function(struct wait_queue_entry *wq_entry, unsigned mode, int #define WQ_FLAG_CUSTOM 0x04 #define WQ_FLAG_DONE 0x08 #define WQ_FLAG_PRIORITY 0x10 +#define WQ_FLAG_POLL_EXCLUSIVE 0x20 /* * A single wait-queue entry structure: @@ -299,13 +300,13 @@ extern void init_wait_entry(struct wait_queue_entry *wq_entry, int flags); * otherwise. */ -#define ___wait_event(wq_head, condition, state, exclusive, ret, cmd) \ +#define ___wait_event(wq_head, condition, state, wq_flag, ret, cmd) \ ({ \ __label__ __out; \ struct wait_queue_entry __wq_entry; \ long __ret = ret; /* explicit shadow */ \ \ - init_wait_entry(&__wq_entry, exclusive ? WQ_FLAG_EXCLUSIVE : 0); \ + init_wait_entry(&__wq_entry, wq_flag); \ for (;;) { \ long __int = prepare_to_wait_event(&wq_head, &__wq_entry, state);\ \ @@ -327,8 +328,7 @@ __out: __ret; \ }) #define __wait_event(wq_head, condition) \ - (void)___wait_event(wq_head, condition, TASK_UNINTERRUPTIBLE, 0, 0, \ - schedule()) + (void)__wait_event_state(wq_head, condition, TASK_UNINTERRUPTIBLE) /** * wait_event - sleep until a condition gets true @@ -366,8 +366,7 @@ do { \ } while (0) #define __wait_event_freezable(wq_head, condition) \ - ___wait_event(wq_head, condition, (TASK_INTERRUPTIBLE|TASK_FREEZABLE), \ - 0, 0, schedule()) + __wait_event_state(wq_head, condition, (TASK_INTERRUPTIBLE|TASK_FREEZABLE)) /** * wait_event_freezable - sleep (or freeze) until a condition gets true @@ -442,8 +441,8 @@ do { \ }) #define __wait_event_exclusive_cmd(wq_head, condition, cmd1, cmd2) \ - (void)___wait_event(wq_head, condition, TASK_UNINTERRUPTIBLE, 1, 0, \ - cmd1; schedule(); cmd2) + (void)___wait_event(wq_head, condition, TASK_UNINTERRUPTIBLE, \ + WQ_FLAG_EXCLUSIVE, 0, cmd1; schedule(); cmd2) /* * Just like wait_event_cmd(), except it sets exclusive flag */ @@ -480,8 +479,7 @@ do { \ } while (0) #define __wait_event_interruptible(wq_head, condition) \ - ___wait_event(wq_head, condition, TASK_INTERRUPTIBLE, 0, 0, \ - schedule()) + __wait_event_state(wq_head, condition, TASK_INTERRUPTIBLE) /** * wait_event_interruptible - sleep until a condition gets true @@ -620,8 +618,7 @@ do { \ }) #define __wait_event_interruptible_exclusive(wq, condition) \ - ___wait_event(wq, condition, TASK_INTERRUPTIBLE, 1, 0, \ - schedule()) + __wait_event_state_exclusive(wq, condition, TASK_INTERRUPTIBLE) #define wait_event_interruptible_exclusive(wq, condition) \ ({ \ @@ -633,8 +630,7 @@ do { \ }) #define __wait_event_killable_exclusive(wq, condition) \ - ___wait_event(wq, condition, TASK_KILLABLE, 1, 0, \ - schedule()) + __wait_event_state_exclusive(wq, condition, TASK_KILLABLE) #define wait_event_killable_exclusive(wq, condition) \ ({ \ @@ -647,8 +643,7 @@ do { \ #define __wait_event_freezable_exclusive(wq, condition) \ - ___wait_event(wq, condition, (TASK_INTERRUPTIBLE|TASK_FREEZABLE), 1, 0,\ - schedule()) + __wait_event_state_exclusive(wq, condition, (TASK_INTERRUPTIBLE|TASK_FREEZABLE)) #define wait_event_freezable_exclusive(wq, condition) \ ({ \ @@ -676,7 +671,7 @@ do { \ do { \ might_sleep(); \ if (!(condition)) \ - ___wait_event(wq_head, condition, TASK_IDLE, 0, 0, schedule()); \ + __wait_event_state(wq_head, condition, TASK_IDLE); \ } while (0) /** @@ -700,7 +695,7 @@ do { \ do { \ might_sleep(); \ if (!(condition)) \ - ___wait_event(wq_head, condition, TASK_IDLE, 1, 0, schedule()); \ + __wait_event_state_exclusive(wq_head, condition, TASK_IDLE); \ } while (0) #define __wait_event_idle_timeout(wq_head, condition, timeout) \ @@ -738,7 +733,7 @@ do { \ #define __wait_event_idle_exclusive_timeout(wq_head, condition, timeout) \ ___wait_event(wq_head, ___wait_cond_timeout(condition), \ - TASK_IDLE, 1, timeout, \ + TASK_IDLE, WQ_FLAG_EXCLUSIVE, timeout, \ __ret = schedule_timeout(__ret)) /** @@ -911,7 +906,7 @@ extern int do_wait_intr_irq(wait_queue_head_t *, wait_queue_entry_t *); #define __wait_event_killable(wq, condition) \ - ___wait_event(wq, condition, TASK_KILLABLE, 0, 0, schedule()) + __wait_event_state(wq, condition, TASK_KILLABLE) /** * wait_event_killable - sleep until a condition gets true @@ -981,7 +976,7 @@ extern int do_wait_intr_irq(wait_queue_head_t *, wait_queue_entry_t *); }) #define __wait_event_state_exclusive(wq, condition, state) \ - ___wait_event(wq, condition, state, 1, 0, schedule()) + ___wait_event(wq, condition, state, WQ_FLAG_EXCLUSIVE, 0, schedule()) #define wait_event_state_exclusive(wq, condition, state) \ ({ \ diff --git a/include/net/amt.h b/include/net/amt.h index 2846dde0cadce3..9ba09712731da9 100644 --- a/include/net/amt.h +++ b/include/net/amt.h @@ -240,12 +240,19 @@ struct amt_tunnel_list { u32 nr_sources; enum amt_status status; struct delayed_work gc_wq; + /* Last time a Membership Update refreshed this tunnel, under ->lock. + * gc_wq re-arms itself from this rather than being re-armed by the + * Update path, so the Update path cannot re-queue the work of a + * tunnel that amt_tunnel_expire() is freeing. + */ + unsigned long last_seen; + /* Set under amt->lock and tunnel->lock by whichever freer reaches the + * tunnel first; the other then leaves it alone, so the tunnel is freed + * exactly once. + */ + bool dead; __be16 source_port; __be32 ip4; - __be32 nonce; - siphash_key_t key; - u64 mac:48, - reserved:16; struct rcu_head rcu; struct hlist_head groups[]; }; @@ -275,6 +282,7 @@ enum amt_source_status { /* protected by gnode->lock */ struct amt_source_node { struct hlist_node node; + struct hlist_node gc_node; struct amt_group_node *gnode; struct delayed_work source_timer; union amt_addr source_addr; @@ -282,6 +290,8 @@ struct amt_source_node { #define AMT_SOURCE_OLD 0 #define AMT_SOURCE_NEW 1 u8 flags; + /* Protected by gnode->tunnel_list->lock. */ + bool dead; struct rcu_head rcu; }; @@ -295,7 +305,10 @@ struct amt_group_node { u32 nr_sources; struct amt_tunnel_list *tunnel_list; struct hlist_node node; + struct hlist_node gc_node; struct delayed_work group_timer; + /* Protected by tunnel_list->lock. */ + bool dead; struct rcu_head rcu; struct hlist_head sources[]; }; @@ -325,8 +338,12 @@ struct amt_dev { struct work_struct event_wq; /* AMT status */ enum amt_status status; - /* Generated key */ - siphash_key_t key; + /* Current key and three previous generations keep MACs valid for + * 180-240s, beyond the advertised QQIC (see amt_secret_work()). + */ + siphash_key_t key[4]; + /* For lockless readers of key; writers hold lock */ + seqcount_spinlock_t key_seq; struct sock __rcu *sk; u32 max_groups; u32 max_sources; @@ -370,6 +387,7 @@ struct amt_dev { #define AMT_IPHDR_OPTS 4 #define AMT_IP6HDR_OPTS 8 #define AMT_GC_INTERVAL (30 * 1000) +#define AMT_GC_KICK 2048 #define AMT_MAX_GROUP 32 #define AMT_MAX_SOURCE 128 #define AMT_HSIZE_SHIFT 8 @@ -383,6 +401,8 @@ struct amt_dev { #define AMT_SECRET_TIMEOUT 60000 #define IANA_AMT_UDP_PORT 2268 #define AMT_MAX_TUNNELS 128 +/* Upper bound of amt_max_tunnels_per_src(), the per-address tunnel cap */ +#define AMT_MAX_TUNNELS_PER_SRC 16 #define AMT_MAX_REQS 128 #define AMT_GW_HLEN (sizeof(struct iphdr) + \ sizeof(struct udphdr) + \ diff --git a/include/net/bluetooth/hci_core.h b/include/net/bluetooth/hci_core.h index 6fb713d5e4be98..7cf63bc0f46685 100644 --- a/include/net/bluetooth/hci_core.h +++ b/include/net/bluetooth/hci_core.h @@ -561,6 +561,8 @@ struct hci_dev { struct list_head accept_list; struct list_head uuids; struct list_head link_keys; + /* Serializes the writers of link_keys, see hci_add_link_key() */ + struct mutex link_keys_lock; struct list_head long_term_keys; struct list_head identity_resolving_keys; struct mutex remote_oob_lock; @@ -1921,6 +1923,10 @@ struct hci_conn_params *hci_pend_le_action_lookup(struct list_head *list, void hci_uuids_clear(struct hci_dev *hdev); void hci_link_keys_clear(struct hci_dev *hdev); +struct link_key *__hci_add_link_key(struct hci_dev *hdev, struct hci_conn *conn, + bdaddr_t *bdaddr, u8 *val, u8 type, + u8 pin_len, bool *persistent); +void hci_del_link_key(struct hci_dev *hdev, struct link_key *key); u8 *hci_conn_key_enc_size(struct hci_conn *conn); struct link_key *hci_find_link_key(struct hci_dev *hdev, bdaddr_t *bdaddr); struct link_key *hci_add_link_key(struct hci_dev *hdev, struct hci_conn *conn, @@ -1972,6 +1978,7 @@ struct adv_info *hci_add_per_instance(struct hci_dev *hdev, u8 instance, u8 sid, int hci_set_adv_instance_data(struct hci_dev *hdev, u8 instance, u16 adv_data_len, u8 *adv_data, u16 scan_rsp_len, u8 *scan_rsp_data); +void hci_free_adv_instance(struct hci_dev *hdev, struct adv_info *adv_instance); int hci_remove_adv_instance(struct hci_dev *hdev, u8 instance); void hci_adv_instances_set_rpa_expired(struct hci_dev *hdev, bool rpa_expired); u32 hci_adv_instance_flags(struct hci_dev *hdev, u8 instance); @@ -2512,6 +2519,7 @@ void mgmt_index_removed(struct hci_dev *hdev); void mgmt_set_powered_failed(struct hci_dev *hdev, int err); void mgmt_power_on(struct hci_dev *hdev, int err); void __mgmt_power_off(struct hci_dev *hdev); +void mgmt_mesh_flush(struct hci_dev *hdev); void mgmt_new_link_key(struct hci_dev *hdev, struct link_key *key, bool persistent); void mgmt_device_connected(struct hci_dev *hdev, struct hci_conn *conn, diff --git a/include/net/bluetooth/l2cap.h b/include/net/bluetooth/l2cap.h index 2a05bda8ab4321..9f18e70f09bb95 100644 --- a/include/net/bluetooth/l2cap.h +++ b/include/net/bluetooth/l2cap.h @@ -45,6 +45,11 @@ #define L2CAP_DEFAULT_ACC_LAT 0xFFFFFFFF #define L2CAP_BREDR_MAX_PAYLOAD 1019 /* 3-DH5 packet */ #define L2CAP_LE_MIN_MTU 23 + +/* Identifier used by L2CAP_LE_CREDITS, it has no response so it is not + * tracked in conn->tx_ida and is never allocated for any other command. + */ +#define L2CAP_IDENT_LE_CREDITS 255 #define L2CAP_ECRED_CONN_SCID_MAX 5 #define L2CAP_DISC_TIMEOUT msecs_to_jiffies(100) @@ -636,6 +641,7 @@ struct l2cap_conn { struct sk_buff_head pending_rx; struct work_struct pending_rx_work; + bool pending_rx_blocked __guarded_by(&lock); struct delayed_work id_addr_timer; diff --git a/include/net/dropreason-core.h b/include/net/dropreason-core.h index fa2fe89905573a..903d6a3a0ff198 100644 --- a/include/net/dropreason-core.h +++ b/include/net/dropreason-core.h @@ -128,6 +128,7 @@ FN(PSP_INPUT) \ FN(PSP_OUTPUT) \ FN(RECURSION_LIMIT) \ + FN(SKB_RX_HEADROOM) \ FNe(MAX) /** @@ -612,6 +613,11 @@ enum skb_drop_reason { * itself. */ SKB_DROP_REASON_RECURSION_LIMIT, + /** + * @SKB_DROP_REASON_SKB_RX_HEADROOM: accumulated receive headroom + * exceeds the header-offset budget. + */ + SKB_DROP_REASON_SKB_RX_HEADROOM, /** * @SKB_DROP_REASON_MAX: the maximum of core drop reasons, which * shouldn't be used as a real 'reason' - only for tracing code gen diff --git a/include/net/gso.h b/include/net/gso.h index 119fc4c170e164..6cf6a6dee234c3 100644 --- a/include/net/gso.h +++ b/include/net/gso.h @@ -3,6 +3,7 @@ #ifndef _NET_GSO_H #define _NET_GSO_H +#include #include /* Keeps track of mac header offset relative to skb->head. @@ -39,6 +40,38 @@ static inline int skb_tnl_header_len(const struct sk_buff *inner_skb) SKB_GSO_CB(inner_skb)->mac_offset; } +/** + * skb_gso_fraglist_ok - test whether skb_segment_list() can segment an skb + * @skb: SKB_GSO_FRAGLIST skb to segment + * @features: features for the output path + * @hdrlen: transport header length + * @proto: network protocol, for checksum offload + * + * Return: false if the skb must be passed to the more general skb_segment(). + */ +static inline bool skb_gso_fraglist_ok(const struct sk_buff *skb, + netdev_features_t features, + unsigned int hdrlen, __be16 proto) +{ + /* Geometry modified, e.g., by a pull from frag_list */ + if (skb_pagelen(skb) - hdrlen != skb_shinfo(skb)->gso_size) + return false; + + if (skb_shinfo(skb)->gso_type & SKB_GSO_DODGY) + return false; + + /* Tunnel headers and outer checksums are not rebuilt */ + if (skb->encapsulation || skb_tnl_header_len(skb)) + return false; + + /* Checksums are not resolved in software */ + if (skb->ip_summed == CHECKSUM_PARTIAL && + !can_checksum_protocol(features, proto)) + return false; + + return true; +} + static inline int gso_pskb_expand_head(struct sk_buff *skb, int extra) { int new_headroom, headroom; diff --git a/include/net/inet_connection_sock.h b/include/net/inet_connection_sock.h index 903499581db7e2..562e12033a5d3f 100644 --- a/include/net/inet_connection_sock.h +++ b/include/net/inet_connection_sock.h @@ -255,9 +255,10 @@ static inline unsigned long inet_csk_rto_backoff(const struct inet_connection_sock *icsk, unsigned long max_when) { - u64 when = (u64)icsk->icsk_rto << icsk->icsk_backoff; + u8 backoff = min_t(u8, 32U, icsk->icsk_backoff); + u64 when = (u64)icsk->icsk_rto << backoff; - return (unsigned long)min_t(u64, when, max_when); + return (unsigned long)min_t(u64, when, max_when); } struct sock *inet_csk_accept(struct sock *sk, struct proto_accept_arg *arg); diff --git a/include/net/inet_hashtables.h b/include/net/inet_hashtables.h index 6e2fe186d0dcb0..44b7e39a1245b0 100644 --- a/include/net/inet_hashtables.h +++ b/include/net/inet_hashtables.h @@ -87,6 +87,8 @@ struct inet_bind_bucket { __be32 fast_rcv_saddr; unsigned short fast_sk_family; bool fast_ipv6_only; + unsigned char fast_sk_reuse; + int fast_bound_dev_if; struct hlist_node node; struct hlist_head bhash2; struct rcu_head rcu; diff --git a/include/net/ip_vs.h b/include/net/ip_vs.h index 9a83bff32569da..8dc80d5d42dca3 100644 --- a/include/net/ip_vs.h +++ b/include/net/ip_vs.h @@ -1021,7 +1021,9 @@ struct ip_vs_dest { struct rcu_head rcu_head; struct list_head t_list; /* in dest_trash */ - unsigned int in_rs_table:1; /* we are in rs_table */ + unsigned long rcu_state; /* GP cookie on unlink (trash or rehash) */ + unsigned int in_rs_table:1, /* we are in rs_table */ + need_gp:1; /* Need GP on rehash */ }; /* The scheduler object */ @@ -1685,7 +1687,6 @@ static inline bool __ip_vs_conn_get(struct ip_vs_conn *cp) /* put back the conn without restarting its timer */ static inline void __ip_vs_conn_put(struct ip_vs_conn *cp) { - smp_mb__before_atomic(); refcount_dec(&cp->refcnt); } void ip_vs_conn_put(struct ip_vs_conn *cp); @@ -1923,7 +1924,7 @@ 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, bool overload); +void ip_vs_dest_update_overload(struct ip_vs_dest *dest); /* Check if dest is in overloaded state */ static inline bool ip_vs_dest_is_overloaded(const struct ip_vs_dest *dest) diff --git a/include/net/mana/gdma.h b/include/net/mana/gdma.h index 29d152e185967e..6191ddddc27f9a 100644 --- a/include/net/mana/gdma.h +++ b/include/net/mana/gdma.h @@ -776,6 +776,9 @@ enum { /* Driver supports handling throttled EQEs */ #define GDMA_DRV_CAP_FLAG_1_THROTTLED_EVENT_QUEUE BIT_ULL(32) +/* Enforce min 1 usec, 1 frames for Interrupt Moderation */ +#define GDMA_DRV_CAP_FLAG_1_SET_MIN_INTR_MOD_VALUE BIT_ULL(33) + /* 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 @@ -801,7 +804,8 @@ enum { 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_THROTTLED_EVENT_QUEUE) + GDMA_DRV_CAP_FLAG_1_THROTTLED_EVENT_QUEUE | \ + GDMA_DRV_CAP_FLAG_1_SET_MIN_INTR_MOD_VALUE) #define GDMA_DRV_CAP_FLAGS2 0 diff --git a/include/net/mana/mana.h b/include/net/mana/mana.h index 218d540bc99404..84afc4199e8768 100644 --- a/include/net/mana/mana.h +++ b/include/net/mana/mana.h @@ -74,9 +74,12 @@ enum mana_priv_flag_bits { /* 8-pkt mode packs up to 2 packets per PPI entry */ #define MANA_CQE_COAL_PKTS_8 8 -/* Default/max interrupt moderation settings */ -#define MANA_INTR_MODR_USEC_DEF 0 -#define MANA_INTR_MODR_COMP_DEF 0 +/* Default/min interrupt moderation settings */ +#define MANA_INTR_MODR_USEC_DEF 1 +#define MANA_INTR_MODR_COMP_DEF 1 + +#define MANA_INTR_MODR_USEC_MIN 1 +#define MANA_INTR_MODR_COMP_MIN 1 #define MANA_ADAPTIVE_RX_DEF true #define MANA_ADAPTIVE_TX_DEF true diff --git a/include/net/neighbour.h b/include/net/neighbour.h index 79a5a548a12912..d6d691fec124d2 100644 --- a/include/net/neighbour.h +++ b/include/net/neighbour.h @@ -394,7 +394,7 @@ struct pneigh_entry *pneigh_lookup(struct neigh_table *tbl, const void *key, struct net_device *dev); int pneigh_create(struct neigh_table *tbl, const void *key, struct net_device *dev, u32 flags, u8 protocol, - bool permanent); + bool permanent, bool update); int pneigh_delete(struct neigh_table *tbl, const void *key, struct net_device *dev); diff --git a/include/net/tcp.h b/include/net/tcp.h index 5c9203aae83417..869e780fcb482f 100644 --- a/include/net/tcp.h +++ b/include/net/tcp.h @@ -164,6 +164,13 @@ static_assert((1 << ATO_BITS) > TCP_DELACK_MAX); #define TCP_TIMEOUT_MIN_US (2*USEC_PER_MSEC) /* Min TCP timeout in microsecs */ +/* Max RTT sample for tcp_rtt_estimator(). srtt_us holds 8 times the RTT, and + * mdev_us and rttvar_us up to 4 times its deviation, all in u32, like the sum + * in __tcp_set_rto(). A larger sample could not raise the RTO, which + * TCP_RTO_MAX bounds. + */ +#define TCP_RTT_MAX_US (TCP_RTO_MAX_SEC * USEC_PER_SEC) + #define TCP_TIMEOUT_INIT ((unsigned)(1*HZ)) /* RFC6298 2.1 initial RTO value */ #define TCP_TIMEOUT_FALLBACK ((unsigned)(3*HZ)) /* RFC 1122 initial RTO value, now * used as a fallback RTO for the @@ -910,15 +917,23 @@ static inline void tcp_bound_rto(struct sock *sk) static inline u32 __tcp_set_rto(const struct tcp_sock *tp) { - return usecs_to_jiffies((tp->srtt_us >> 3) + tp->rttvar_us); + u32 rto = usecs_to_jiffies((tp->srtt_us >> 3) + tp->rttvar_us); + + return max(rto, 1U); } -static inline unsigned long tcp_reqsk_timeout(struct request_sock *req) +static inline unsigned long tcp_reqsk_timeout_sk(const struct sock *sk, + const struct request_sock *req) { - u64 timeout = (u64)req->timeout << req->num_timeout; + /* timeout << 32 is already above tcp_rto_max(). */ + u64 timeout = (u64)req->timeout << min_t(u8, req->num_timeout, 32); - return (unsigned long)min_t(u64, timeout, - tcp_rto_max(req->rsk_listener)); + return (unsigned long)min_t(u64, timeout, tcp_rto_max(sk)); +} + +static inline unsigned long tcp_reqsk_timeout(struct request_sock *req) +{ + return tcp_reqsk_timeout_sk(req->rsk_listener, req); } u32 tcp_delack_max(const struct sock *sk); @@ -930,7 +945,8 @@ static inline u32 tcp_rto_min(const struct sock *sk) u32 rto_min = READ_ONCE(inet_csk(sk)->icsk_rto_min); if (dst && dst_metric_locked(dst, RTAX_RTO_MIN)) - rto_min = dst_metric_rtt(dst, RTAX_RTO_MIN); + rto_min = clamp(dst_metric_rtt(dst, RTAX_RTO_MIN), + 1, TCP_RTO_MAX); return rto_min; } @@ -1854,6 +1870,12 @@ static inline void tcp_adjust_rcv_ssthresh(struct sock *sk) void tcp_cleanup_rbuf(struct sock *sk, int copied); void __tcp_cleanup_rbuf(struct sock *sk, int copied); +/* Is the socket in a state in which TCP may send an ACK? */ +static inline bool tcp_can_send_ack(const struct sock *sk) +{ + return !((1 << inet_sk_state_load(sk)) & + (TCPF_SYN_SENT | TCPF_SYN_RECV | TCPF_TIME_WAIT | TCPF_CLOSE | TCPF_LISTEN)); +} /* We provision sk_rcvbuf around 200% of sk_rcvlowat. * If 87.5 % (7/8) of the space has been consumed, we want to override @@ -2882,6 +2904,15 @@ void tcp_cleanup_ulp(struct sock *sk); void tcp_update_ulp(struct sock *sk, struct proto *p, void (*write_space)(struct sock *sk)); +static inline bool tcp_kcm_attached(const struct sock *sk) +{ +#if IS_ENABLED(CONFIG_AF_KCM) + return tcp_sk(sk)->kcm_attached; +#else + return false; +#endif +} + #define MODULE_ALIAS_TCP_ULP(name) \ MODULE_INFO(alias, name); \ MODULE_INFO(alias, "tcp-ulp-" name) diff --git a/include/scsi/scsi_proto.h b/include/scsi/scsi_proto.h index 9c7d31aa6bae59..0ee0cf3200d0ca 100644 --- a/include/scsi/scsi_proto.h +++ b/include/scsi/scsi_proto.h @@ -371,6 +371,9 @@ enum zbc_zone_reporting_options { #define ZBC_REPORT_ZONE_PARTIAL 0x80 +#define ZBC_REPORT_ZONES_HEADER_SIZE 64 +#define ZBC_ZONE_DESCRIPTOR_SIZE 64 + /* Zone types of REPORT ZONES zone descriptors */ enum zbc_zone_type { ZBC_ZONE_TYPE_CONV = 0x1, diff --git a/include/sound/aw88399.h b/include/sound/aw88399.h index d72c491ee86636..fa43e8068093ac 100644 --- a/include/sound/aw88399.h +++ b/include/sound/aw88399.h @@ -469,13 +469,13 @@ #define AW88399_DSP_VOL_MASK \ (~(((1<buffer_accessing)) + return -EBUSY; + return 0; +} + +static inline void snd_pcm_buffer_access_put(struct snd_pcm_runtime *runtime) +{ + atomic_dec(&runtime->buffer_accessing); +} + +/* auto-cleanup macros */ +DEFINE_GUARD(snd_pcm_buffer_access, struct snd_pcm_runtime *, + snd_pcm_buffer_access_get(_T), snd_pcm_buffer_access_put(_T)); +DEFINE_GUARD_COND(snd_pcm_buffer_access, _try, + snd_pcm_buffer_access_get(_T), _RET == 0); + +#define SND_PCM_BUFFER_ACQUIRE(runtime, var) \ + ACQUIRE(snd_pcm_buffer_access_try, var)(runtime) +#define SND_PCM_BUFFER_ACQUIRE_ERR(var) \ + ACQUIRE_ERR(snd_pcm_buffer_access_try, &(var)) + /** * snd_pcm_running - Check whether the substream is in a running state * @substream: substream to check @@ -1188,6 +1214,17 @@ snd_pcm_sframes_t __snd_pcm_lib_xfer(struct snd_pcm_substream *substream, void *buf, bool interleaved, snd_pcm_uframes_t frames, bool in_kernel); +static inline snd_pcm_sframes_t +snd_pcm_lib_get_and_xfer(struct snd_pcm_substream *substream, + void *buf, bool interleaved, + snd_pcm_uframes_t frames, bool in_kernel) +{ + SND_PCM_BUFFER_ACQUIRE(substream->runtime, lock); + if (SND_PCM_BUFFER_ACQUIRE_ERR(lock)) + return -EBUSY; + return __snd_pcm_lib_xfer(substream, buf, interleaved, frames, in_kernel); +} + static inline snd_pcm_sframes_t snd_pcm_lib_write(struct snd_pcm_substream *substream, const void __user *buf, snd_pcm_uframes_t frames) @@ -1220,28 +1257,28 @@ static inline snd_pcm_sframes_t snd_pcm_kernel_write(struct snd_pcm_substream *substream, const void *buf, snd_pcm_uframes_t frames) { - return __snd_pcm_lib_xfer(substream, (void *)buf, true, frames, true); + return snd_pcm_lib_get_and_xfer(substream, (void *)buf, true, frames, true); } static inline snd_pcm_sframes_t snd_pcm_kernel_read(struct snd_pcm_substream *substream, void *buf, snd_pcm_uframes_t frames) { - return __snd_pcm_lib_xfer(substream, buf, true, frames, true); + return snd_pcm_lib_get_and_xfer(substream, buf, true, frames, true); } static inline snd_pcm_sframes_t snd_pcm_kernel_writev(struct snd_pcm_substream *substream, void **bufs, snd_pcm_uframes_t frames) { - return __snd_pcm_lib_xfer(substream, bufs, false, frames, true); + return snd_pcm_lib_get_and_xfer(substream, bufs, false, frames, true); } static inline snd_pcm_sframes_t snd_pcm_kernel_readv(struct snd_pcm_substream *substream, void **bufs, snd_pcm_uframes_t frames) { - return __snd_pcm_lib_xfer(substream, bufs, false, frames, true); + return snd_pcm_lib_get_and_xfer(substream, bufs, false, frames, true); } int snd_pcm_hw_limit_rates(struct snd_pcm_hardware *hw); diff --git a/include/sound/sb.h b/include/sound/sb.h index 24970f36c38ae9..f133cfee378841 100644 --- a/include/sound/sb.h +++ b/include/sound/sb.h @@ -299,10 +299,6 @@ static inline void snd_sbmixer_resume(struct snd_sb *chip) {} int snd_sb8dsp_pcm(struct snd_sb *chip, int device); /* sb8.c */ irqreturn_t snd_sb8dsp_interrupt(struct snd_sb *chip); -int snd_sb8_playback_open(struct snd_pcm_substream *substream); -int snd_sb8_capture_open(struct snd_pcm_substream *substream); -int snd_sb8_playback_close(struct snd_pcm_substream *substream); -int snd_sb8_capture_close(struct snd_pcm_substream *substream); /* midi8.c */ irqreturn_t snd_sb8dsp_midi_interrupt(struct snd_sb *chip); int snd_sb8dsp_midi(struct snd_sb *chip, int device); diff --git a/include/sound/soc-component.h b/include/sound/soc-component.h index 73d66c97669440..8314a2e8df55fa 100644 --- a/include/sound/soc-component.h +++ b/include/sound/soc-component.h @@ -272,14 +272,30 @@ struct snd_soc_component { snd_soc_dai_to_list(dai) != &(component)->dai_list; \ dai = _dai, _dai = snd_soc_dai_from_list(snd_soc_dai_to_list(_dai)->next)) +struct device *snd_soc_component_to_dev(struct snd_soc_component *component); struct snd_soc_dapm_context *snd_soc_component_to_dapm(struct snd_soc_component *component); +const struct snd_soc_component_driver +*snd_soc_component_to_driver(struct snd_soc_component *component); +struct snd_soc_card *snd_soc_component_to_card(struct snd_soc_component *component); +struct dentry *snd_soc_component_to_debugfs_root(struct snd_soc_component *component); +struct regmap *snd_soc_component_to_regmap(struct snd_soc_component *component); struct snd_soc_component *snd_soc_component_new(struct device *dev, const char *name, const struct snd_soc_component_driver *driver); +void snd_soc_component_unregister(struct snd_soc_component *component); int snd_soc_component_register(struct snd_soc_component *component, struct snd_soc_dai_driver *dai_drv, int num_dai); +int snd_soc_register_component(struct device *dev, + const struct snd_soc_component_driver *component_driver, + struct snd_soc_dai_driver *dai_drv, int num_dai); + +int devm_snd_soc_register_component(struct device *dev, + const struct snd_soc_component_driver *component_driver, + struct snd_soc_dai_driver *dai_drv, int num_dai); +void snd_soc_unregister_component(struct device *dev); const char *snd_soc_component_name(struct snd_soc_component *component); +const char *snd_soc_component_name_prefix(struct snd_soc_component *component); void snd_soc_component_set_priv(struct snd_soc_component *component, void *priv); void *snd_soc_component_to_priv(struct snd_soc_component *component); @@ -333,14 +349,20 @@ int snd_soc_component_stream_event(struct snd_soc_component *component, int snd_soc_component_set_bias_level(struct snd_soc_component *component, enum snd_soc_bias_level level); -int snd_soc_component_regmap_val_bytes(struct snd_soc_component *component); -int snd_soc_component_regmap_cache_sync(struct snd_soc_component *component); -void snd_soc_component_regmap_async_complete(struct snd_soc_component *component); #ifdef CONFIG_REGMAP -void snd_soc_component_init_regmap(struct snd_soc_component *component, +void snd_soc_component_regmap_init(struct snd_soc_component *component, struct regmap *regmap); -void snd_soc_component_exit_regmap(struct snd_soc_component *component); +void snd_soc_component_regmap_exit(struct snd_soc_component *component); +int snd_soc_component_regmap_multi_reg_write_bypassed(struct snd_soc_component *component, + const struct reg_sequence *regs, + int num_regs); #endif +int snd_soc_component_regmap_get_val_bytes(struct snd_soc_component *component); +void snd_soc_component_regmap_async_complete(struct snd_soc_component *component); +int snd_soc_component_regcache_sync(struct snd_soc_component *component); +void snd_soc_component_regcache_mark_dirty(struct snd_soc_component *component); +void snd_soc_component_regcache_cache_only(struct snd_soc_component *component, bool enable); +void snd_soc_component_regcache_cache_bypass(struct snd_soc_component *component, bool enable); int snd_soc_component_fixup_controls(struct snd_soc_component *component); int snd_soc_component_add_controls(struct snd_soc_component *component, @@ -371,6 +393,7 @@ static inline void *snd_soc_component_get_drvdata(struct snd_soc_component *c) } unsigned int snd_soc_component_active(struct snd_soc_component *component); +int snd_soc_component_num_dai(struct snd_soc_component *component); /* component controls */ struct snd_kcontrol *snd_soc_component_get_kcontrol(struct snd_soc_component *component, @@ -392,6 +415,9 @@ int snd_soc_component_of_xlate_dai_id(struct snd_soc_component *component, int snd_soc_component_of_xlate_dai_name(struct snd_soc_component *component, const struct of_phandle_args *args, const char **dai_name); +int snd_soc_component_of_simple_xlate_dai_name(struct snd_soc_component *component, + const struct of_phandle_args *args, + const char **dai_name); int snd_soc_component_compr_open(struct snd_soc_component *component, struct snd_compr_stream *cstream); void snd_soc_component_compr_free(struct snd_soc_component *component, @@ -445,10 +471,14 @@ void snd_soc_pcm_component_delay(struct snd_pcm_substream *substream, snd_pcm_sframes_t *cpu_delay, snd_pcm_sframes_t *codec_delay); /* REMOVE ME */ -#define snd_soc_component_cache_sync snd_soc_component_regmap_cache_sync +#define snd_soc_component_init_regmap snd_soc_component_regmap_init +#define snd_soc_component_exit_regmap snd_soc_component_regmap_exit +#define snd_soc_component_cache_sync snd_soc_component_regcache_sync +#define snd_soc_component_regmap_val_bytes snd_soc_component_regmap_get_val_bytes #define snd_soc_component_async_complete snd_soc_component_regmap_async_complete #define snd_soc_lookup_component_nolocked snd_soc_component_lookup_nolock #define snd_soc_lookup_component snd_soc_component_lookup #define snd_soc_lookup_component_by_name snd_soc_component_lookup_by_name +#define snd_soc_of_xlate_dai_name snd_soc_component_of_simple_xlate_dai_name #endif /* __SOC_COMPONENT_H */ diff --git a/include/sound/soc.h b/include/sound/soc.h index 338662645b42fa..5abebfa329b522 100644 --- a/include/sound/soc.h +++ b/include/sound/soc.h @@ -447,17 +447,6 @@ static inline int snd_soc_resume(struct device *dev) } #endif int snd_soc_poweroff(struct device *dev); -int snd_soc_register_component(struct device *dev, - const struct snd_soc_component_driver *component_driver, - struct snd_soc_dai_driver *dai_drv, int num_dai); - -int devm_snd_soc_register_component(struct device *dev, - const struct snd_soc_component_driver *component_driver, - struct snd_soc_dai_driver *dai_drv, int num_dai); -#define snd_soc_unregister_component(dev) snd_soc_unregister_component_by_driver(dev, NULL) -void snd_soc_unregister_component_by_driver(struct device *dev, - const struct snd_soc_component_driver *component_driver); - int soc_new_pcm(struct snd_soc_pcm_runtime *rtd); #ifdef CONFIG_SND_SOC_COMPRESS int snd_soc_new_compress(struct snd_soc_pcm_runtime *rtd); @@ -1314,9 +1303,6 @@ int snd_soc_of_parse_tdm_slot(struct device_node *np, unsigned int *rx_mask, unsigned int *slots, unsigned int *slot_width); -int snd_soc_of_xlate_dai_name(struct snd_soc_component *component, - const struct of_phandle_args *args, - const char **dai_name); void snd_soc_of_parse_node_prefix(struct device_node *np, struct snd_soc_codec_conf *codec_conf, struct device_node *of_node, diff --git a/include/sound/tas2573-reg.h b/include/sound/tas2573-reg.h index 4fedc8a3329e8f..6f8411c695ebc4 100644 --- a/include/sound/tas2573-reg.h +++ b/include/sound/tas2573-reg.h @@ -59,6 +59,28 @@ struct tasdev_reg_map { /* YM955 */ #define TAS2573_SHORTCKT TASDEVICE_REG(0x00, 0x83, 0x6C) +/* Registers for the speaker calibration */ +static const __maybe_unused unsigned int fct_status_regs[] = { + TAS2573_FCT_INT_LATCH, + TAS2573_FCT_STATUS_CTRL, + TAS2573_FCT_STATUS_BINNING, + TAS2573_SILENCE_DETECTED, + TAS2573_OPEN_CIRCUIT, + TAS2573_SHORTCKT, + TAS2573_FCT_OUTPUT_R0, + TAS2573_FCT_OUTPUT_R0_LOW, + TAS2573_FCT_OUTPUT_INV_R0, + TAS2573_FCT_OUTPUT_POWERTOT, + TAS2573_FCT_OUTPUT_F0, + TAS2573_RE_OUT, +}; + +static const __maybe_unused struct tasdev_reg_map calib_status_map = { + .regs = fct_status_regs, + .nregs = ARRAY_SIZE(fct_status_regs), + .tag = "fct_status_regs", +}; + /* Registers for the realtime (RT) speaker protection data */ static const __maybe_unused unsigned int tas2573_rt_data_regs[] = { TAS2573_TDM_DET_REG, diff --git a/include/target/iscsi/iscsi_target_core.h b/include/target/iscsi/iscsi_target_core.h index 51ca80abacf7ba..5cc688b3f7d148 100644 --- a/include/target/iscsi/iscsi_target_core.h +++ b/include/target/iscsi/iscsi_target_core.h @@ -7,6 +7,7 @@ #include #include /* struct sockaddr_storage */ #include /* u8 */ +#include /* struct work_struct */ #include /* itt_t */ #include /* struct se_cmd */ @@ -682,6 +683,8 @@ struct iscsit_session { struct completion session_wait_comp; struct completion session_waiting_on_uc_comp; struct timer_list time2retain_timer; + struct work_struct time2retain_work; + atomic_t time2retain_fired; struct iscsi_sess_ops *sess_ops; struct se_session *se_sess; struct iscsi_portal_group *tpg; diff --git a/include/trace/events/hugetlbfs.h b/include/trace/events/hugetlbfs.h index 8ba72c1d4f4d8b..a7932e0db0f88c 100644 --- a/include/trace/events/hugetlbfs.h +++ b/include/trace/events/hugetlbfs.h @@ -72,7 +72,7 @@ DEFINE_EVENT(hugetlbfs__inode, hugetlbfs_evict_inode, TP_ARGS(inode) ); -DEFINE_EVENT(hugetlbfs__inode, hugetlbfs_free_inode, +DEFINE_EVENT(hugetlbfs__inode, hugetlbfs_destroy_inode, TP_PROTO(struct inode *inode), diff --git a/include/trace/events/landlock.h b/include/trace/events/landlock.h index b6fdc6e2eef871..09e90e4a9cd7bd 100644 --- a/include/trace/events/landlock.h +++ b/include/trace/events/landlock.h @@ -21,6 +21,7 @@ #include enum landlock_request_type; +struct cred; struct dentry; struct landlock_blockers; struct landlock_domain; @@ -30,13 +31,15 @@ struct landlock_ruleset; struct path; struct sock; struct task_struct; +struct user_namespace; static_assert(sizeof(access_mask_t) <= sizeof(u64)); TRACE_DEFINE_ENUM(LANDLOCK_REQUEST_FS_CHANGE_TOPOLOGY); TRACE_DEFINE_ENUM(LANDLOCK_REQUEST_FS_ACCESS); TRACE_DEFINE_ENUM(LANDLOCK_REQUEST_NET_ACCESS); -TRACE_DEFINE_ENUM(LANDLOCK_REQUEST_NAMESPACE); +TRACE_DEFINE_ENUM(LANDLOCK_REQUEST_NAMESPACE_CREATE); +TRACE_DEFINE_ENUM(LANDLOCK_REQUEST_NAMESPACE_ENTER); TRACE_DEFINE_ENUM(LANDLOCK_REQUEST_CAPABILITY); #ifdef CREATE_TRACE_POINTS @@ -990,7 +993,8 @@ TRACE_EVENT(landlock_deny_access_net, * @namespace_id: Namespace ID, not directly visible from user space when * creation was denied. * - * Emitted when a Landlock domain denies namespace use. + * Emitted when a Landlock domain denies namespace creation or entry. The + * namespace_op field distinguishes these operations. */ TRACE_EVENT(landlock_deny_permission_namespace, @@ -1021,13 +1025,18 @@ TRACE_EVENT(landlock_deny_permission_namespace, __entry->namespace_id = namespace_id; ), - TP_printk("domain=%llx same_exec=%d logged=%d blockers=%s namespace_type=0x%x namespace_id=%llu", - __entry->domain_id, __entry->same_exec, __entry->logged, - __entry->blockers_type == LANDLOCK_REQUEST_NAMESPACE ? - __print_flags(__entry->blockers_access, "|", - _LANDLOCK_PERMISSION_BLOCKER_NAMES) : - "unknown", - __entry->namespace_type, __entry->namespace_id) + TP_printk("domain=%llx same_exec=%d logged=%d blockers=%s namespace_op=%s namespace_type=0x%x namespace_id=%llu", + __entry->domain_id, __entry->same_exec, __entry->logged, + (__entry->blockers_type == LANDLOCK_REQUEST_NAMESPACE_CREATE || + __entry->blockers_type == LANDLOCK_REQUEST_NAMESPACE_ENTER) ? + __print_flags(__entry->blockers_access, "|", + _LANDLOCK_PERMISSION_BLOCKER_NAMES) : + "unknown", + __entry->blockers_type == LANDLOCK_REQUEST_NAMESPACE_CREATE ? + "create" : + __entry->blockers_type == LANDLOCK_REQUEST_NAMESPACE_ENTER ? + "enter" : "unknown", + __entry->namespace_type, __entry->namespace_id) ); /** @@ -1039,6 +1048,9 @@ TRACE_EVENT(landlock_deny_permission_namespace, * @logged: Whether this denial was selected for audit logging. * @blockers: Request type and final missing permission subset (never NULL). * @capability: CAP_* number that was denied. + * @cred: Credentials used by commoncap's capability check (never NULL). + * @user_ns: Target user namespace used by commoncap's capability check (never + * NULL). * * Emitted when a Landlock domain denies capability use, except for checks * made with CAP_OPT_NOAUDIT, which are denied without emitting this event. @@ -1047,9 +1059,11 @@ TRACE_EVENT(landlock_deny_permission_capability, TP_PROTO(const struct landlock_hierarchy *hierarchy, bool same_exec, bool logged, const struct landlock_blockers *blockers, - int capability), + int capability, const struct cred *cred, + const struct user_namespace *user_ns), - TP_ARGS(hierarchy, same_exec, logged, blockers, capability), + TP_ARGS(hierarchy, same_exec, logged, blockers, capability, cred, + user_ns), TP_STRUCT__entry( __field( u64, domain_id ) diff --git a/include/uapi/linux/bpf.h b/include/uapi/linux/bpf.h index 8d72288343054b..6840ca5b923bf1 100644 --- a/include/uapi/linux/bpf.h +++ b/include/uapi/linux/bpf.h @@ -934,6 +934,7 @@ union bpf_iter_link_info { * by *prog_fd*, and the stream is identified by the *stream_id*. * The data is copied to a buffer pointed to by *stream_buf*, and * filled less than or equal to *stream_buf_len* bytes. + * The caller needs **CAP_PERFMON**. * * Return * Number of bytes read from the stream on success, or -1 if an @@ -953,7 +954,7 @@ union bpf_iter_link_info { * Description * Open a file descriptor for one of the BPF streams associated * with the program identified by *prog_fd*. The stream is selected - * by *stream_id*. + * by *stream_id*. The caller needs **CAP_PERFMON**. * * The returned file descriptor supports **read**\ (2) and * **poll**\ (2). Reads block while the stream is empty unless diff --git a/include/uapi/linux/fuse.h b/include/uapi/linux/fuse.h index 616430a2973c6e..cb9e9554f0efc0 100644 --- a/include/uapi/linux/fuse.h +++ b/include/uapi/linux/fuse.h @@ -257,6 +257,7 @@ * - add backing_id_64 to fuse_open_out * - add FUSE_NOTIFY_BACKING_MAP, fuse_notify_backing_map_out, fuse_extent * - add FUSE_BACKING_MAP_CREATE, FUSE_BACKING_MAP_CYCLIC + * - extend the meaning of FUSE_HAS_INODE_DAX and FUSE_ATTR_DAX */ #ifndef _LINUX_FUSE_H @@ -460,7 +461,11 @@ struct fuse_file_lock { * FUSE_INIT_RESERVED: reserved, do not use * FUSE_SECURITY_CTX: add security context to create, mkdir, symlink, and * mknod - * FUSE_HAS_INODE_DAX: use per inode DAX + * FUSE_HAS_INODE_DAX: use per inode DAX. The meaning depends on the + * transport: on virtio-fs it indicates per-inode DAX + * support, while on /dev/fuse (where FUSE_PASSTHROUGH_V2 + * is also offered) it indicates support for passthrough + * extent maps on a DAX device. * FUSE_CREATE_SUPP_GROUP: add supplementary group info to create, mkdir, * symlink and mknod (single group that matches parent) * FUSE_HAS_EXPIRE_ONLY: kernel supports expiry-only entry invalidation @@ -612,7 +617,8 @@ struct fuse_file_lock { * fuse_attr flags * * FUSE_ATTR_SUBMOUNT: Object is a submount root - * FUSE_ATTR_DAX: Enable DAX for this file in per inode DAX mode + * FUSE_ATTR_DAX: Enable DAX for this file in per inode DAX mode and in + * extent mapping passthrough mode */ #define FUSE_ATTR_SUBMOUNT (1 << 0) #define FUSE_ATTR_DAX (1 << 1) diff --git a/include/uapi/linux/landlock.h b/include/uapi/linux/landlock.h index 24510e5d8479a0..8ce0406ba54360 100644 --- a/include/uapi/linux/landlock.h +++ b/include/uapi/linux/landlock.h @@ -22,10 +22,10 @@ * enacted. Vice versa, access rights that are not specifically listed here are * not going to be denied by this ruleset when it is enacted. * - * For historical reasons, the %LANDLOCK_ACCESS_FS_REFER right is always denied - * by default, even when its bit is not set in @handled_access_fs. In order to - * add new rules with this access right, the bit must still be set explicitly - * (cf. `Filesystem flags`_). + * For historical reasons, as soon as any filesystem access right is handled in + * @handled_access_fs, the %LANDLOCK_ACCESS_FS_REFER right is always denied as + * well. In order to add new rules with this access right, the bit must still + * be set explicitly (cf. `Filesystem flags`_). * * The explicit listing of *handled access rights* is required for backwards * compatibility reasons. In most use cases, processes that use Landlock will @@ -462,10 +462,11 @@ struct landlock_capability_attr { * This access right is available since the second version of the Landlock * ABI. * - * This is the only access right which is denied by default by any ruleset, - * even if the right is not specified as handled at ruleset creation time. - * The only way to make a ruleset grant this right is to explicitly allow it - * for a specific directory by adding a matching rule to the ruleset. + * This is the only access right which is denied by default by any ruleset + * that handles filesystem access rights, even if the right is not specified + * as handled at ruleset creation time. The only way to make a ruleset grant + * this right is to explicitly allow it for a specific directory by adding a + * matching rule to the ruleset. * * In particular, when using the first Landlock ABI version, Landlock will * always deny attempts to reparent files between different directories. @@ -622,10 +623,9 @@ struct landlock_capability_attr { * - %LANDLOCK_PERMISSION_CAPABILITY_USE: Restrict the use of specific Linux * capabilities. A process in a Landlock domain that handles this permission * is denied from exercising capabilities that are not explicitly allowed by a - * %LANDLOCK_RULE_CAPABILITY rule. This hook is purely restrictive: it can - * deny capabilities that the kernel would otherwise grant, but it can never - * grant capabilities that the kernel already denied. Support added in - * Landlock ABI version 12. + * %LANDLOCK_RULE_CAPABILITY rule. Landlock only reduces the capabilities + * that processes can use: it does not let them use capabilities that they + * would not have without Landlock. Support added in Landlock ABI version 12. */ #define LANDLOCK_PERMISSION_NAMESPACE_USE (1ULL << 0) #define LANDLOCK_PERMISSION_CAPABILITY_USE (1ULL << 1) diff --git a/init/initramfs.c b/init/initramfs.c index ebddde9c8f0d91..11030cc1f35df4 100644 --- a/init/initramfs.c +++ b/init/initramfs.c @@ -582,6 +582,7 @@ char * __init unpack_to_rootfs(char *buf, unsigned long len) } static int __initdata do_retain_initrd; +unsigned long initrd_mem_end __initdata; static int __init retain_initrd_param(char *str) { @@ -750,6 +751,15 @@ static void __init do_populate_rootfs(void *unused, async_cookie_t cookie) security_initramfs_populated(); } + /* + * The bootconfig loader trims the bootconfig off initrd_end. Restore + * it to free the memory used by the bootconfig too, unless the initrd + * is retained (which must not expose the bootconfig). + */ + if (!do_retain_initrd && initrd_start && initrd_end < initrd_mem_end) + initrd_end = initrd_mem_end; + initrd_mem_end = 0; + /* * If the initrd region is overlapped with crashkernel reserved region, * free only memory that is not part of crashkernel region. diff --git a/init/main.c b/init/main.c index 7b0c8c34e6a911..f1478034505130 100644 --- a/init/main.c +++ b/init/main.c @@ -268,7 +268,7 @@ early_param("loglevel", loglevel); #ifdef CONFIG_BLK_DEV_INITRD static void * __init get_boot_config_from_initrd(size_t *_size) { - u32 size, csum; + u32 size, raw_size, csum; char *data; u8 *hdr; int i; @@ -294,29 +294,42 @@ static void * __init get_boot_config_from_initrd(size_t *_size) if ((unsigned long)hdr < initrd_start) return NULL; - size = get_unaligned_le32(hdr); + raw_size = get_unaligned_le32(hdr); csum = get_unaligned_le32(hdr + 4); - if (size > XBC_DATA_MAX) { + if (raw_size > XBC_DATA_MAX_PADDED) { pr_err("bootconfig size %u is greater than max size %d\n", - size, XBC_DATA_MAX); + raw_size, XBC_DATA_MAX); return NULL; } - if (size > ((unsigned long)hdr - initrd_start)) { + if (raw_size > ((unsigned long)hdr - initrd_start)) { pr_err("bootconfig size %u is greater than initrd size %lu\n", - size, initrd_end - initrd_start); + raw_size, initrd_end - initrd_start); return NULL; } - data = ((void *)hdr) - size; + data = ((void *)hdr) - raw_size; + + size = xbc_exclude_padding(data, raw_size); + if (size > XBC_DATA_MAX) { + pr_err("bootconfig size %u is greater than max size %d\n", + size, XBC_DATA_MAX); + return NULL; + } - if (xbc_calc_checksum(data, size) != csum) { + if (xbc_calc_checksum(data, raw_size) != csum) { pr_err("bootconfig checksum failed\n"); return NULL; } - /* Remove bootconfig from initramfs/initrd */ + /* + * Remove bootconfig from initramfs/initrd. Since the initrd memory + * (including the bootconfig) is freed with initrd_end, save the + * original end to free the whole region later. + */ + if (!initrd_mem_end) + initrd_mem_end = initrd_end; initrd_end = (unsigned long)data; if (_size) *_size = size; diff --git a/io_uring/bpf-ops.c b/io_uring/bpf-ops.c index 6c2a587fb1bf65..dfa93144b090df 100644 --- a/io_uring/bpf-ops.c +++ b/io_uring/bpf-ops.c @@ -157,6 +157,13 @@ static int bpf_io_check_member(const struct btf_type *t, return 0; } +static int bpf_io_validate(void *kdata) +{ + const struct io_uring_bpf_ops *ops = kdata; + + return ops->loop_step ? 0 : -EINVAL; +} + static int bpf_io_init_member(const struct btf_type *t, const struct btf_member *member, void *kdata, const void *udata) @@ -269,6 +276,7 @@ static struct bpf_struct_ops bpf_ring_ops = { .check_member = bpf_io_check_member, .init_member = bpf_io_init_member, .init = bpf_io_init, + .validate = bpf_io_validate, .cfi_stubs = &io_bpf_ops_stubs, .name = "io_uring_bpf_ops", .owner = THIS_MODULE, diff --git a/io_uring/cancel.c b/io_uring/cancel.c index e3d9fe8fc982c6..5b57d27225acd8 100644 --- a/io_uring/cancel.c +++ b/io_uring/cancel.c @@ -438,6 +438,7 @@ static bool io_match_linked(struct io_kiocb *head) bool io_match_task_safe(struct io_kiocb *head, struct io_uring_task *tctx, bool cancel_all) { + struct io_ring_ctx *ctx = head->ctx; bool matched; if (tctx && head->tctx != tctx) @@ -445,16 +446,13 @@ bool io_match_task_safe(struct io_kiocb *head, struct io_uring_task *tctx, if (cancel_all) return true; - if (head->flags & REQ_F_LINK_TIMEOUT) { - struct io_ring_ctx *ctx = head->ctx; - - /* protect against races with linked timeouts */ - raw_spin_lock_irq(&ctx->timeout_lock); - matched = io_match_linked(head); - raw_spin_unlock_irq(&ctx->timeout_lock); - } else { - matched = io_match_linked(head); - } + /* + * Protect against races with linked timeouts. REQ_F_LINK_TIMEOUT can't + * tell if there is one: an io-wq worker may set it during the walk. + */ + raw_spin_lock_irq(&ctx->timeout_lock); + matched = io_match_linked(head); + raw_spin_unlock_irq(&ctx->timeout_lock); return matched; } diff --git a/io_uring/filetable.c b/io_uring/filetable.c index cb1838c9fc3776..f547ab1193b103 100644 --- a/io_uring/filetable.c +++ b/io_uring/filetable.c @@ -67,6 +67,9 @@ static int io_install_fixed_file(struct io_ring_ctx *ctx, struct file *file, if (io_is_uring_fops(file)) return -EBADF; + /* Registered files come from fget(), which refuses these too */ + if (file->f_mode & FMODE_PATH) + return -EBADF; if (!ctx->file_table.data.nr) return -ENXIO; if (slot_index >= ctx->file_table.data.nr) diff --git a/io_uring/futex.c b/io_uring/futex.c index 9e4e63ee7bc151..615eaa9104b143 100644 --- a/io_uring/futex.c +++ b/io_uring/futex.c @@ -107,6 +107,7 @@ static bool __io_futex_cancel(struct io_kiocb *req) } hlist_del_init(&req->hash_node); + req_set_fail(req); io_req_set_res(req, -ECANCELED, 0); io_req_task_work_add(req); return true; diff --git a/io_uring/io-wq.c b/io_uring/io-wq.c index 92df54c6f50ca5..9609ae50dbd7a4 100644 --- a/io_uring/io-wq.c +++ b/io_uring/io-wq.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -741,6 +742,34 @@ static bool io_worker_retire(struct io_wq_acct *acct, struct io_worker *worker) return false; } +/* + * The CPUs a worker of @wq runs on: those of the io-wq affinity that the + * worker's cpuset allows, or the cpuset if they have none in common, as the + * scheduler does with a task's requested affinity when its cpuset changes. + * Read the cpuset each time: it can change while the io-wq exists. + */ +static void io_wq_worker_cpus(struct io_wq *wq, struct task_struct *tsk, + struct cpumask *cpus) +{ + cpuset_cpus_allowed(tsk, cpus); + if (cpumask_intersects(cpus, wq->cpu_mask)) + cpumask_and(cpus, cpus, wq->cpu_mask); +} + +/* Is the current worker on a CPU that a new worker would not get? */ +static bool io_wq_worker_off_cpus(struct io_wq *wq) +{ + cpumask_var_t cpus; + bool off; + + if (!alloc_cpumask_var(&cpus, GFP_KERNEL)) + return false; + io_wq_worker_cpus(wq, current, cpus); + off = !cpumask_test_cpu(raw_smp_processor_id(), cpus); + free_cpumask_var(cpus); + return off; +} + static int io_wq_worker(void *data) { struct io_worker *worker = data; @@ -819,8 +848,7 @@ static int io_wq_worker(void *data) } if (!ret) { last_timeout = true; - exit_mask = !cpumask_test_cpu(raw_smp_processor_id(), - wq->cpu_mask); + exit_mask = io_wq_worker_off_cpus(wq); } } @@ -870,9 +898,16 @@ void io_wq_worker_sleeping(struct task_struct *tsk) static void io_init_new_worker(struct io_wq *wq, struct io_wq_acct *acct, struct io_worker *worker, struct task_struct *tsk) { + cpumask_var_t cpus; + tsk->worker_private = worker; worker->task = tsk; - set_cpus_allowed_ptr(tsk, wq->cpu_mask); + /* Without a mask, the worker keeps its creator's CPUs. */ + if (alloc_cpumask_var(&cpus, GFP_KERNEL)) { + io_wq_worker_cpus(wq, tsk, cpus); + set_cpus_allowed_ptr(tsk, cpus); + free_cpumask_var(cpus); + } raw_spin_lock(&acct->workers_lock); hlist_nulls_add_head_rcu(&worker->nulls_node, &acct->free_list); @@ -1369,7 +1404,7 @@ struct io_wq *io_wq_create(unsigned bounded, struct io_wq_data *data) if (!alloc_cpumask_var(&wq->cpu_mask, GFP_KERNEL)) goto err; - cpuset_cpus_allowed(data->task, wq->cpu_mask); + cpumask_copy(wq->cpu_mask, cpu_possible_mask); wq->acct[IO_WQ_ACCT_BOUND].max_workers = bounded; wq->acct[IO_WQ_ACCT_UNBOUND].max_workers = task_rlimit(current, RLIMIT_NPROC); @@ -1448,6 +1483,22 @@ static void io_wq_cancel_tw_create(struct io_wq *wq) } } +static bool io_wq_worker_show(struct io_worker *worker, void *data) +{ + sched_show_task(worker->task); + return false; +} + +/* The exit path is always the same, show what the workers are stuck on */ +static void io_wq_show_stuck_workers(struct io_wq *wq) +{ + pr_warn("io-wq: %s/%d stuck waiting for workers to exit\n", + current->comm, task_pid_nr(current)); + rcu_read_lock(); + io_wq_for_each_worker(wq, io_wq_worker_show, NULL); + rcu_read_unlock(); +} + static void io_wq_exit_workers(struct io_wq *wq) { unsigned long timeout, warn_timeout; @@ -1469,8 +1520,8 @@ static void io_wq_exit_workers(struct io_wq *wq) * * where completely overloading the system with tons of long running * io-wq items can easily trigger the hung task timeout. Only sleep - * uninterruptibly for half that time, and warn if we exceeded end - * up waiting more than IO_URING_EXIT_WAIT_MAX. + * uninterruptibly for half that time, and show the stuck workers if + * we end up waiting more than IO_URING_EXIT_WAIT_MAX. */ timeout = sysctl_hung_task_timeout_secs * HZ / 2; if (!timeout) @@ -1479,7 +1530,8 @@ static void io_wq_exit_workers(struct io_wq *wq) do { if (wait_for_completion_timeout(&wq->worker_done, timeout)) break; - WARN_ON_ONCE(time_after(jiffies, warn_timeout)); + if (time_after(jiffies, warn_timeout)) + DO_ONCE_LITE(io_wq_show_stuck_workers, wq); } while (1); spin_lock_irq(&wq->hash->wait.lock); @@ -1574,7 +1626,7 @@ int io_wq_cpu_affinity(struct io_uring_task *tctx, cpumask_var_t mask) else ret = -EINVAL; } else { - cpumask_copy(tctx->io_wq->cpu_mask, allowed_mask); + cpumask_copy(tctx->io_wq->cpu_mask, cpu_possible_mask); } rcu_read_unlock(); diff --git a/io_uring/io_uring.c b/io_uring/io_uring.c index 5db57bf675f0e7..d8491f86e48082 100644 --- a/io_uring/io_uring.c +++ b/io_uring/io_uring.c @@ -1537,9 +1537,11 @@ static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags) ret = __io_issue_sqe(req, issue_flags, def); if (ret == IOU_COMPLETE) { - /* not all handlers take care of the internal restart codes */ - if (unlikely(req->cqe.res <= -ERESTARTSYS)) - req->cqe.res = io_fixup_restart_res(req->cqe.res); + if (unlikely(req->cqe.res < 0)) { + if (req->cqe.res <= -ERESTARTSYS) + req->cqe.res = io_fixup_restart_res(req->cqe.res); + req_set_fail(req); + } if (issue_flags & IO_URING_F_COMPLETE_DEFER) io_req_complete_defer(req); else @@ -2369,6 +2371,14 @@ static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx) kfree(ctx); } +static __cold void io_ring_ctx_free_work(struct work_struct *work) +{ + struct io_ring_ctx *ctx = container_of(to_rcu_work(work), + struct io_ring_ctx, free_rwork); + + io_ring_ctx_free(ctx); +} + static __cold void io_activate_pollwq_cb(struct callback_head *cb) { struct io_ring_ctx *ctx = container_of(cb, struct io_ring_ctx, @@ -2550,6 +2560,10 @@ static __cold void io_ring_ctx_wait_inflight(struct io_ring_ctx *ctx) /* Only wait if this task has attached to the ring */ if (!tctx || !xa_load(&tctx->xa, (unsigned long)ctx)) return; + /* Requests may sit in local work that only exit work can run */ + if ((ctx->flags & IORING_SETUP_DEFER_TASKRUN) && + !io_local_work_cancel_allowed(ctx)) + return; if (atomic_read(&tctx->in_cancel)) return; @@ -2654,11 +2668,14 @@ static __cold void io_ring_exit_work(struct work_struct *work) spin_lock(&ctx->completion_lock); spin_unlock(&ctx->completion_lock); - /* pairs with the RCU read sections in the task_work add paths */ - if (ctx->flags & (IORING_SETUP_DEFER_TASKRUN | IORING_SETUP_SQPOLL)) - synchronize_rcu(); - - io_ring_ctx_free(ctx); + /* + * Free the ring after a grace period. This pairs with the RCU read + * sections in the task_work add paths, which look at the rings and + * the submitter task, and with the one in io_uring_del_tctx_node(), + * which may still be unlocking ->tctx_lock. + */ + INIT_RCU_WORK(&ctx->free_rwork, io_ring_ctx_free_work); + queue_rcu_work(iou_wq, &ctx->free_rwork); } static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx) @@ -2685,6 +2702,9 @@ static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx) if (!(current->flags & PF_IO_WORKER)) { io_ring_ctx_cancel(ctx); io_ring_ctx_wait_inflight(ctx); + /* exit is past the drop in io_uring_cancel_generic() */ + if (current->io_uring) + io_uring_drop_tctx_refs(current); } INIT_WORK(&ctx->exit_work, io_ring_exit_work); diff --git a/io_uring/kbuf.c b/io_uring/kbuf.c index abf44f5dba26a0..78d29008919aae 100644 --- a/io_uring/kbuf.c +++ b/io_uring/kbuf.c @@ -370,6 +370,7 @@ int io_buffers_select(struct io_kiocb *req, struct buf_sel_arg *arg, req->flags |= REQ_F_BUF_MORE; } } else { + arg->out_len = arg->max_len; ret = io_provided_buffers_select(req, &arg->out_len, sel->buf_list, arg->iovs); } out_unlock: @@ -427,6 +428,9 @@ unsigned int __io_put_kbufs(struct io_kiocb *req, struct io_buffer_list *bl, ret = IORING_CQE_F_BUFFER | (req->buf_index << IORING_CQE_BUFFER_SHIFT); + /* only covers the buffer(s) being put, not a later selection */ + req->flags &= ~REQ_F_BL_NO_RECYCLE; + if (unlikely(!(req->flags & REQ_F_BUFFER_RING))) { io_kbuf_drop_legacy(req); return ret; diff --git a/io_uring/net.c b/io_uring/net.c index 533afd335627a9..b0d508b772ceea 100644 --- a/io_uring/net.c +++ b/io_uring/net.c @@ -515,12 +515,10 @@ static inline bool io_send_finish(struct io_kiocb *req, bool bundle_finished = sel->val <= 0; unsigned int cflags; - if (!(sr->flags & IORING_RECVSEND_BUNDLE)) { - cflags = io_put_kbuf(req, sel->val, sel->buf_list); + /* Committed at selection time, so a bundle needs no buffer count */ + cflags = io_put_kbuf(req, sel->val, sel->buf_list); + if (!(sr->flags & IORING_RECVSEND_BUNDLE)) goto finish; - } - - cflags = io_put_kbufs(req, sel->val, sel->buf_list, io_bundle_nbufs(kmsg, sel->val)); /* * Don't start new bundles if the buffer list is empty, or if the @@ -1049,6 +1047,8 @@ int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags) int ret, min_ret = 0; bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK; bool mshot_finished = true; + void __user *control; + size_t controllen; int consumed = 0; size_t len; @@ -1086,6 +1086,8 @@ int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags) kmsg->msg.msg_get_inq = 1; kmsg->msg.msg_inq = -1; + control = kmsg->msg.msg_control_user; + controllen = kmsg->msg.msg_controllen; if (req->flags & REQ_F_APOLL_MULTISHOT) { ret = io_recvmsg_multishot(sock, sr, kmsg, flags, &mshot_finished); @@ -1110,12 +1112,20 @@ int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags) if (ret < min_ret) { if (ret == -EAGAIN && force_nonblock) { + /* + * Don't depend on the control buffer being untouched, a + * protocol may post a cmsg before it finds no data. + */ + kmsg->msg.msg_control_user = control; + kmsg->msg.msg_controllen = controllen; io_kbuf_recycle(req, sel.buf_list, issue_flags); return IOU_RETRY; } if (ret > 0 && io_net_retry(sock, flags) && io_net_kbuf_can_retry(req, sel.buf_list, kmsg)) { sr->done_io += ret; + /* msg_name and msg_namelen are filled in, leave them */ + kmsg->uaddr = NULL; return io_net_kbuf_recyle(req, sel.buf_list, kmsg, ret); } if (ret == -ERESTARTSYS) @@ -1501,7 +1511,12 @@ static int io_sg_from_iter(struct sk_buff *skb, struct bio_vec v = mp_bvec_iter_bvec(from->bvec, bi); copied += v.bv_len; - truesize += PAGE_ALIGN(v.bv_len + v.bv_offset); + /* + * bv_offset is relative to the folio for coalesced huge page + * registrations, so only the in-page part of it matters for + * how much memory this fragment ties up. + */ + truesize += PAGE_ALIGN(v.bv_len + offset_in_page(v.bv_offset)); __skb_fill_page_desc_noacc(shinfo, frag++, v.bv_page, v.bv_offset, v.bv_len); bvec_iter_advance_single(from->bvec, &bi, v.bv_len); diff --git a/io_uring/openclose.c b/io_uring/openclose.c index 24cf3ce2e2bc3a..29fe31f16a2b21 100644 --- a/io_uring/openclose.c +++ b/io_uring/openclose.c @@ -54,6 +54,7 @@ static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe { struct io_open *open = io_kiocb_to_cmd(req, struct io_open); const char __user *fname; + int uflags = 0; int ret; if (unlikely(sqe->buf_index)) @@ -67,7 +68,9 @@ static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe open->dfd = READ_ONCE(sqe->fd); fname = u64_to_user_ptr(READ_ONCE(sqe->addr)); - ret = delayed_getname(&open->filename, fname); + if (open->how.flags & O_EMPTYPATH) + uflags = AT_EMPTY_PATH; + ret = delayed_getname_uflags(&open->filename, fname, uflags); if (unlikely(ret)) return ret; req->flags |= REQ_F_NEED_CLEANUP; diff --git a/io_uring/poll.c b/io_uring/poll.c index fc1800c7097b53..67bf39575238b6 100644 --- a/io_uring/poll.c +++ b/io_uring/poll.c @@ -533,11 +533,9 @@ static void __io_queue_proc(struct io_poll *poll, struct io_poll_table *pt, poll->head = head; poll->wait.private = (void *) wqe_private; - if (poll->events & EPOLLEXCLUSIVE) { - add_wait_queue_exclusive(head, &poll->wait); - } else { - add_wait_queue(head, &poll->wait); - } + if (poll->events & EPOLLEXCLUSIVE) + poll->wait.flags |= WQ_FLAG_POLL_EXCLUSIVE; + add_wait_queue(head, &poll->wait); } static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head, diff --git a/io_uring/rsrc.c b/io_uring/rsrc.c index 8de5737d223e8b..0b811d3c9c0e9f 100644 --- a/io_uring/rsrc.c +++ b/io_uring/rsrc.c @@ -363,8 +363,6 @@ static int __io_sqe_files_update(struct io_ring_ctx *ctx, if (i >= ctx->file_table.data.nr) break; i = array_index_nospec(i, ctx->file_table.data.nr); - if (io_reset_rsrc_node(ctx, &ctx->file_table.data, i)) - io_file_bitmap_clear(&ctx->file_table, i); if (fd != -1) { struct file *file = fget(fd); @@ -388,11 +386,15 @@ static int __io_sqe_files_update(struct io_ring_ctx *ctx, fput(file); break; } + if (io_reset_rsrc_node(ctx, &ctx->file_table.data, i)) + io_file_bitmap_clear(&ctx->file_table, i); ctx->file_table.data.nodes[i] = node; if (tag) node->tag = tag; io_fixed_file_set(node, file); io_file_bitmap_set(&ctx->file_table, i); + } else if (io_reset_rsrc_node(ctx, &ctx->file_table.data, i)) { + io_file_bitmap_clear(&ctx->file_table, i); } } return done ? done : err; diff --git a/io_uring/rw.c b/io_uring/rw.c index 3a8559ff4dc662..cf20597ba6a814 100644 --- a/io_uring/rw.c +++ b/io_uring/rw.c @@ -606,8 +606,10 @@ static void io_complete_rw_iopoll(struct kiocb *kiocb, long res) if (res == -EAGAIN && io_rw_should_reissue(req)) req->flags |= REQ_F_REISSUE | REQ_F_BL_NO_RECYCLE; - else if (unlikely(final_res != req->cqe.res)) + else if (unlikely(final_res != req->cqe.res)) { + req_set_fail(req); req->cqe.res = final_res; + } /* order with io_iopoll_complete() checking ->iopoll_completed */ smp_store_release(&req->iopoll_completed, 1); diff --git a/io_uring/tctx.c b/io_uring/tctx.c index b4fecea3ea4797..508a72fdfc1b59 100644 --- a/io_uring/tctx.c +++ b/io_uring/tctx.c @@ -231,7 +231,10 @@ __cold void io_uring_del_tctx_node(unsigned long index) mutex_lock(&node->ctx->tctx_lock); list_del(&node->ctx_node); + /* keeps the ctx until the unlock is done, see io_ring_exit_work() */ + rcu_read_lock(); mutex_unlock(&node->ctx->tctx_lock); + rcu_read_unlock(); if (tctx->last == node->ctx) tctx->last = NULL; diff --git a/io_uring/timeout.c b/io_uring/timeout.c index fa7b0d9a81d695..46c01704b58fba 100644 --- a/io_uring/timeout.c +++ b/io_uring/timeout.c @@ -115,7 +115,8 @@ static void io_timeout_complete(struct io_tw_req tw_req, io_tw_token_t tw) struct io_ring_ctx *ctx = req->ctx; if (!io_timeout_finish(timeout, data)) { - if (io_req_post_cqe(req, -ETIME, IORING_CQE_F_MORE)) { + if (!tw.cancel && + io_req_post_cqe(req, -ETIME, IORING_CQE_F_MORE)) { /* re-arm timer */ raw_spin_lock_irq(&ctx->timeout_lock); list_add(&timeout->list, ctx->timeout_list.prev); @@ -391,11 +392,14 @@ static void io_req_task_link_timeout(struct io_tw_req tw_req, io_tw_token_t tw) if (prev) { /* * splice the linked timeout out of prev's chain if the regular - * completion path didn't already do it. + * completion path didn't already do it. io-wq cancellation + * walks the chain with only ->timeout_lock held. */ + raw_spin_lock_irq(&req->ctx->timeout_lock); if (prev->link == req) prev->link = req->link; req->link = NULL; + raw_spin_unlock_irq(&req->ctx->timeout_lock); if (!tw.cancel) { struct io_cancel_data cd = { diff --git a/io_uring/tw.c b/io_uring/tw.c index 0b5066f9722450..41b3b9422d41fb 100644 --- a/io_uring/tw.c +++ b/io_uring/tw.c @@ -184,7 +184,7 @@ void io_req_local_work_add(struct io_kiocb *req, unsigned flags) struct io_ring_ctx *ctx = req->ctx; int nr_wait; - /* pairs with synchronize_rcu() in io_ring_exit_work() */ + /* pairs with the grace period before the free in io_ring_exit_work() */ guard(rcu)(); /* @@ -286,10 +286,11 @@ void __cold io_cancel_local_task_work(struct io_ring_ctx *ctx) * The work list consumer side is serialized by ->uring_lock, see * __io_run_local_work(). Grab it to guard against racing with normal * task_work running, as the task may be exiting. The ring is going - * away, run the entries in cancel mode right here - the callers - * provide the same process context the per-ctx fallback work that - * they were previously punted to ran in. + * away, run the entries in cancel mode right here, if allowed. */ + if (!io_local_work_cancel_allowed(ctx)) + return; + guard(mutex)(&ctx->uring_lock); while (!mpscq_empty(&ctx->work_list)) { diff --git a/io_uring/tw.h b/io_uring/tw.h index 3ade5ad577fda5..6bc69a234f0531 100644 --- a/io_uring/tw.h +++ b/io_uring/tw.h @@ -88,6 +88,17 @@ static inline int io_run_task_work(void) return ret; } +/* + * Canceled local work may still copy to user memory. Only run it from a kthread, + * where such copies fail, or from a task that shares the mm of the submitter. + */ +static inline bool io_local_work_cancel_allowed(struct io_ring_ctx *ctx) +{ + struct task_struct *tsk = ctx->submitter_task; + + return !current->mm || (tsk && current->mm == READ_ONCE(tsk->mm)); +} + static inline bool io_local_work_pending(struct io_ring_ctx *ctx) { return !mpscq_empty(&ctx->work_list); diff --git a/kernel/bpf/arena.c b/kernel/bpf/arena.c index ec2bda1a6ebf60..70a49b1200a9b5 100644 --- a/kernel/bpf/arena.c +++ b/kernel/bpf/arena.c @@ -149,6 +149,8 @@ struct apply_range_data { struct bpf_arena *arena; struct llist_head *pages; int i; + bool can_flush; /* the caller can flush TLB of all cpus after it drops the lock */ + bool flush; }; struct clear_range_data { @@ -189,6 +191,12 @@ static int apply_range_set_cb(pte_t *pte, unsigned long addr, void *data) continue; if (WARN_ON_ONCE(pte_page(old) != d->arena->scratch_page)) return -EBUSY; +#ifndef flush_tlb_before_set + /* The scratch page is in TLB, and it takes an IPI to flush it */ + if (!d->can_flush) + return -EBUSY; + d->flush = true; +#endif ptep_get_and_clear(&init_mm, addr, pte); flush_tlb_before_set(addr); } @@ -571,6 +579,7 @@ static vm_fault_t arena_vm_fault(struct vm_fault *vmf) } llist_add(&new_page->pcp_llist, &pages); data.arena = arena; + data.can_flush = false; data.pages = &pages; data.i = 0; @@ -637,16 +646,13 @@ static unsigned long arena_get_unmapped_area(struct file *filp, unsigned long ad return -EINVAL; if (len > (u64)map->max_entries * PAGE_SIZE) return -E2BIG; + /* each page in the range tree needs an address */ + if (len < (u64)map->max_entries * PAGE_SIZE) + return -EINVAL; /* if user_vm_start was specified at arena creation time */ - if (arena->user_vm_start) { - if (len > arena->user_vm_end - arena->user_vm_start) - return -E2BIG; - if (len != arena->user_vm_end - arena->user_vm_start) - return -EINVAL; - if (addr != arena->user_vm_start) - return -EINVAL; - } + if (arena->user_vm_start && addr != arena->user_vm_start) + return -EINVAL; /* * Without MAP_FIXED the mm finds a free range. Ask for twice the @@ -806,6 +812,8 @@ static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt goto out_memcg; data.arena = arena; + data.can_flush = sleepable; + data.flush = false; data.pages = &pages; data.i = 0; @@ -836,17 +844,18 @@ static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt flush_vmap_cache(kern_vm_start + uaddr32, mapped << PAGE_SHIFT); raw_res_spin_unlock_irqrestore(&arena->spinlock, flags); + if (data.flush) + flush_tlb_kernel_range(kern_vm_start + uaddr32, + kern_vm_start + uaddr32 + (mapped << PAGE_SHIFT)); addr = clear_lo32(arena->user_vm_start) + uaddr32; goto out_memcg; out_unmap: - /* Error handling: Undo partial mappings. */ + /* Error handling: Undo partial mappings, unmap the scratch page. */ flush_vmap_cache(kern_vm_start + uaddr32, mapped << PAGE_SHIFT); - range_tree_set(&arena->rt, pgoff + mapped, page_cnt - mapped); raw_res_spin_unlock_irqrestore(&arena->spinlock, flags); - if (mapped) - arena_free_pages(arena, uaddr32, mapped, sleepable); + arena_free_pages(arena, uaddr32, page_cnt, sleepable); out_free_pages: /* Error handling: Free back any unmapped pages. */ @@ -1178,9 +1187,10 @@ __bpf_kfunc int bpf_arena_reserve_pages(void *p__map, void *ptr__ign, u32 page_c __bpf_kfunc_end_defs(); BTF_KFUNCS_START(arena_kfuncs) -BTF_ID_FLAGS(func, bpf_arena_alloc_pages, KF_ARENA_RET | KF_ARENA_ARG2 | KF_SPINLOCK_SAFE) -BTF_ID_FLAGS(func, bpf_arena_free_pages, KF_ARENA_ARG2 | KF_SPINLOCK_SAFE) -BTF_ID_FLAGS(func, bpf_arena_reserve_pages, KF_ARENA_ARG2 | KF_SPINLOCK_SAFE) +BTF_ID_FLAGS(func, bpf_arena_alloc_pages, + KF_ARENA_RET | KF_ARENA_ARG2 | KF_SPINLOCK_SAFE | KF_PERFMON) +BTF_ID_FLAGS(func, bpf_arena_free_pages, KF_ARENA_ARG2 | KF_SPINLOCK_SAFE | KF_PERFMON) +BTF_ID_FLAGS(func, bpf_arena_reserve_pages, KF_ARENA_ARG2 | KF_SPINLOCK_SAFE | KF_PERFMON) BTF_KFUNCS_END(arena_kfuncs) static const struct btf_kfunc_id_set common_kfunc_set = { diff --git a/kernel/bpf/bpf_lsm.c b/kernel/bpf/bpf_lsm.c index 468e63dbd922d0..ae23511fd811bf 100644 --- a/kernel/bpf/bpf_lsm.c +++ b/kernel/bpf/bpf_lsm.c @@ -411,6 +411,8 @@ BTF_ID(func, bpf_lsm_bpf_map_free) BTF_ID(func, bpf_lsm_bpf_prog_free) BTF_ID(func, bpf_lsm_file_alloc_security) BTF_ID(func, bpf_lsm_file_free_security) +BTF_ID(func, bpf_lsm_backing_file_alloc) +BTF_ID(func, bpf_lsm_backing_file_free) BTF_ID(func, bpf_lsm_namespace_init) BTF_ID(func, bpf_lsm_namespace_free) #ifdef CONFIG_SECURITY_NETWORK diff --git a/kernel/bpf/bpf_struct_ops.c b/kernel/bpf/bpf_struct_ops.c index 7c5cd6086e2735..5461e0ebab2b63 100644 --- a/kernel/bpf/bpf_struct_ops.c +++ b/kernel/bpf/bpf_struct_ops.c @@ -640,9 +640,10 @@ int bpf_struct_ops_prepare_trampoline(struct bpf_tramp_nodes *tnodes, const struct btf_func_model *model, void *stub_func, void **_image, u32 *_image_off, - bool allow_alloc) + bool allow_alloc, struct bpf_ksym *ksym) { u32 image_off = *_image_off, flags = BPF_TRAMP_F_INDIRECT; + struct bpf_tramp_image im = {}; void *image = *_image; int size; @@ -667,7 +668,7 @@ int bpf_struct_ops_prepare_trampoline(struct bpf_tramp_nodes *tnodes, image_off = 0; } - size = arch_prepare_bpf_trampoline(NULL, image + image_off, + size = arch_prepare_bpf_trampoline(&im, image + image_off, image + image_off + size, model, flags, tnodes, stub_func); if (size <= 0) { @@ -676,6 +677,10 @@ int bpf_struct_ops_prepare_trampoline(struct bpf_tramp_nodes *tnodes, return size ? : -EFAULT; } + if (ksym) { + ksym->fp_start = im.ksym.fp_start; + ksym->fp_end = im.ksym.fp_end; + } *_image = image; *_image_off = image_off + size; return 0; @@ -845,6 +850,7 @@ static long bpf_struct_ops_map_update_elem(struct bpf_map *map, void *key, } if (prog->type != BPF_PROG_TYPE_STRUCT_OPS || + prog->aux->attach_btf != st_map->btf || prog->aux->attach_btf_id != st_ops_desc->type_id || prog->expected_attach_type != i) { bpf_prog_put(prog); @@ -878,7 +884,8 @@ static long bpf_struct_ops_map_update_elem(struct bpf_map *map, void *key, &st_ops->func_models[i], *(void **)(st_ops->cfi_stubs + moff), &image, &image_off, - st_map->image_pages_cnt < MAX_TRAMP_IMAGE_PAGES); + st_map->image_pages_cnt < MAX_TRAMP_IMAGE_PAGES, + ksym); if (err) goto reset_unlock; @@ -1591,13 +1598,14 @@ void bpf_prog_disassoc_struct_ops(struct bpf_prog *prog) * Get a reference to the struct_ops struct (i.e., kdata) associated with a * program. Should only be called in BPF program context (e.g., in a kfunc). * - * If the returned pointer is not NULL, it must points to a valid struct_ops. + * If the returned pointer is not NULL, it must points to a valid @st_ops. * The struct_ops map is not guaranteed to be initialized nor attached. * Kernel struct_ops implementers are responsible for tracking and checking * the state of the struct_ops if the use case requires an initialized or * attached struct_ops. */ -void *bpf_prog_get_assoc_struct_ops(const struct bpf_prog_aux *aux) +void *bpf_prog_get_assoc_struct_ops(const struct bpf_prog_aux *aux, + const struct bpf_struct_ops *st_ops) { struct bpf_struct_ops_map *st_map; struct bpf_map *st_ops_assoc; @@ -1607,6 +1615,8 @@ void *bpf_prog_get_assoc_struct_ops(const struct bpf_prog_aux *aux) return NULL; st_map = (struct bpf_struct_ops_map *)st_ops_assoc; + if (st_map->st_ops_desc->st_ops != st_ops) + return NULL; return &st_map->kvalue.data; } diff --git a/kernel/bpf/btf.c b/kernel/bpf/btf.c index 7e866bf017b537..23e8977164e79d 100644 --- a/kernel/bpf/btf.c +++ b/kernel/bpf/btf.c @@ -4579,7 +4579,7 @@ static int btf_enum_check_kflag_member(struct btf_verifier_env *env, return -EINVAL; } - nr_bits = int_bitsize; + nr_bits = member_type->size * BITS_PER_BYTE; } else if (nr_bits > int_bitsize) { btf_verifier_log_member(env, struct_type, member, "Invalid member bitfield_size"); @@ -4662,12 +4662,30 @@ static void btf_enum_log(struct btf_verifier_env *env, btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t)); } +static s64 btf_enum_read(const struct btf_type *t, const void *data) +{ + bool sign = btf_type_kflag(t); + + switch (t->size) { + case 1: + return sign ? *(s8 *)data : *(u8 *)data; + case 2: + return sign ? *(s16 *)data : *(u16 *)data; + case 4: + return sign ? (s64)*(s32 *)data : *(u32 *)data; + default: + return *(s64 *)data; + } +} + static void btf_enum_show(const struct btf *btf, const struct btf_type *t, u32 type_id, void *data, u8 bits_offset, struct btf_show *show) { const struct btf_enum *enums = btf_type_enum(t); u32 i, nr_enums = btf_type_vlen(t); + /* Old compilers don't set the flag for negative values */ + u32 mask = t->size < 4 ? BIT(t->size * BITS_PER_BYTE) - 1 : U32_MAX; void *safe_data; int v; @@ -4675,10 +4693,10 @@ static void btf_enum_show(const struct btf *btf, const struct btf_type *t, if (!safe_data) return; - v = *(int *)safe_data; + v = btf_enum_read(t, safe_data); for (i = 0; i < nr_enums; i++) { - if (v != enums[i].val) + if ((v ^ enums[i].val) & mask) continue; btf_show_type_value(show, "%s", @@ -4778,7 +4796,7 @@ static void btf_enum64_show(const struct btf *btf, const struct btf_type *t, if (!safe_data) return; - v = *(u64 *)safe_data; + v = btf_enum_read(t, safe_data); for (i = 0; i < nr_enums; i++) { if (v != btf_enum64_value(enums + i)) @@ -7444,11 +7462,22 @@ static const struct bpf_raw_tp_null_args raw_tp_null_args[] = { /* iptfs */ { "iptfs_ingress_postq_event", 0x1000 }, /* neigh */ + { "neigh_create", 0x4000 }, { "neigh_update", 0x10 }, /* snd_firewire_lib */ { "amdtp_packet", 0x100 }, }; +u64 btf_raw_tp_null_mask(const struct bpf_prog *prog) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(raw_tp_null_args); i++) + if (!strcmp(prog->aux->attach_func_name, raw_tp_null_args[i].func)) + return raw_tp_null_args[i].mask; + return btf_is_module(prog->aux->attach_btf) ? U64_MAX : 0; +} + bool btf_ctx_access(int off, int size, enum bpf_access_type type, const struct bpf_prog *prog, struct bpf_insn_access_aux *info) @@ -7485,7 +7514,8 @@ bool btf_ctx_access(int off, int size, enum bpf_access_type type, nr_args--; } - if (arg > nr_args) { + /* expected_attach_type of struct_ops is the index of the member */ + if (arg > nr_args || (arg == nr_args && prog->type == BPF_PROG_TYPE_STRUCT_OPS)) { bpf_log(log, "func '%s' doesn't have %d-th argument\n", tname, arg + 1); return false; @@ -7622,7 +7652,7 @@ bool btf_ctx_access(int off, int size, enum bpf_access_type type, if (btf_param_match_suffix(btf, &args[arg], "__nullable")) info->reg_type |= PTR_MAYBE_NULL; - if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { + if (prog->aux->attach_btf_trace) { struct btf *btf = prog->aux->attach_btf; const struct btf_type *t; const char *tname; @@ -7645,6 +7675,9 @@ bool btf_ctx_access(int off, int size, enum bpf_access_type type, /* Is the current arg IS_ERR? */ if (raw_tp_null_args[i].mask & (0x2ULL << (arg * 4))) ptr_err_raw_tp = true; + /* It can be NULL, and programs that do not check it have to load */ + if (raw_tp_null_args[i].mask & (0x4ULL << (arg * 4))) + info->reg_type = PTR_TO_BTF_ID | PTR_UNTRUSTED; break; } /* If we don't know NULL-ness specification and the tracepoint @@ -8094,7 +8127,12 @@ int btf_struct_access(struct bpf_verifier_log *log, for (i = 0; i < rec->cnt; i++) { struct btf_field *field = &rec->fields[i]; u32 offset = field->offset; - if (off < offset + field->size && offset < off + size) { + /* An access at 'lo' or above ends after the start of the field. */ + s64 lo = max(min_off, (s64)offset - size + 1); + + /* Round up to min_off + k * step. The step is never 0. */ + lo += imod(min_off - lo, reg->step); + if (lo <= max_off && lo < offset + field->size) { bpf_log(log, "direct access to %s is disallowed\n", btf_field_type_name(field->type)); @@ -8122,6 +8160,10 @@ int btf_struct_access(struct bpf_verifier_log *log, */ *next_btf_id = id; *flag = tmp_flag; + /* nothing tells where a flexible array ends */ + t = btf_type_skip_modifiers(btf, reg->btf_id, NULL); + if (min_off + size > t->size) + *flag = (tmp_flag & ~MEM_RCU) | PTR_UNTRUSTED; ret = PTR_TO_BTF_ID; goto check_variable_offset; case WALK_PTR_UNTRUSTED: @@ -9661,6 +9703,9 @@ BPF_CALL_4(bpf_btf_find_by_name_kind, char *, name, int, name_sz, u32, kind, int if (name_sz <= 1 || name[name_sz - 1]) return -EINVAL; + if (bpf_in_async_cb()) + return -EPERM; + ret = bpf_find_btf_id(name, kind, &btf); if (ret > 0 && btf_is_module(btf)) { btf_obj_fd = __btf_new_fd(btf); diff --git a/kernel/bpf/cgroup.c b/kernel/bpf/cgroup.c index 57a785241d42fb..3bf3081bfa276b 100644 --- a/kernel/bpf/cgroup.c +++ b/kernel/bpf/cgroup.c @@ -206,13 +206,53 @@ unsigned int __cgroup_bpf_run_lsm_current(const void *ctx, return ret; } +/* + * cgroup_bpf_mutex protects the bpf state of all cgroups: prog lists, + * effective arrays, flags, revisions, storage lists, link->cgroup, + * link->map of struct_ops links and cgroup_lsm_atype[]. + * + * Take cgroup_mutex first if you need both. This mutex doesn't keep a + * cgroup alive or the hierarchy stable. Attach, detach and replace walk + * the descendants, so they take both. Everything else takes only this one. + * + * cgroup_bpf_inherit() runs at mkdir with only cgroup_mutex. That's safe: + * it writes the new cgroup, which no one else can see yet, and what it + * reads from the ancestors changes only under cgroup_mutex. The ancestors + * are online, and only rmdir, which needs cgroup_mutex, starts a release. + */ +static DEFINE_MUTEX(cgroup_bpf_mutex); + +#define cgroup_bpf_held() lockdep_is_held(&cgroup_bpf_mutex) + +void cgroup_bpf_lock(void) +{ + mutex_lock(&cgroup_bpf_mutex); +} + +void cgroup_bpf_unlock(void) +{ + mutex_unlock(&cgroup_bpf_mutex); +} + +static void cgroup_bpf_lock_hierarchy(void) +{ + cgroup_lock(); + mutex_lock(&cgroup_bpf_mutex); +} + +static void cgroup_bpf_unlock_hierarchy(void) +{ + mutex_unlock(&cgroup_bpf_mutex); + cgroup_unlock(); +} + #ifdef CONFIG_BPF_LSM static enum cgroup_bpf_attach_type bpf_cgroup_atype_find(enum bpf_attach_type attach_type, u32 attach_btf_id) { int i; - lockdep_assert_held(&cgroup_mutex); + lockdep_assert_held(&cgroup_bpf_mutex); if (attach_type != BPF_LSM_CGROUP) return to_cgroup_bpf_attach_type(attach_type); @@ -233,7 +273,7 @@ void bpf_cgroup_atype_get(u32 attach_btf_id, int cgroup_atype) { int i = cgroup_atype - CGROUP_LSM_START; - lockdep_assert_held(&cgroup_mutex); + lockdep_assert_held(&cgroup_bpf_mutex); if (!cgroup_lsm_atype[i].attach_btf_id) { cgroup_lsm_atype[i].attach_btf_id = attach_btf_id; @@ -249,13 +289,13 @@ void bpf_cgroup_atype_put(int cgroup_atype) { int i = cgroup_atype - CGROUP_LSM_START; - cgroup_lock(); + cgroup_bpf_lock(); if (--cgroup_lsm_atype[i].refcnt <= 0) { WRITE_ONCE(cgroup_lsm_atype[i].returns_errno, true); cgroup_lsm_atype[i].attach_btf_id = 0; } WARN_ON_ONCE(cgroup_lsm_atype[i].refcnt < 0); - cgroup_unlock(); + cgroup_bpf_unlock(); } #else static enum cgroup_bpf_attach_type @@ -359,7 +399,7 @@ static void bpf_cgroup_link_auto_detach(struct bpf_cgroup_link *link) return; } - if (link->link.prog->expected_attach_type == BPF_LSM_CGROUP) + if (link->link.prog->type == BPF_PROG_TYPE_LSM) bpf_trampoline_unlink_cgroup_shim(link->link.prog); cgroup_put(link->cgroup); link->cgroup = NULL; @@ -424,7 +464,7 @@ static int bpf_cgroup_array_copy_to_user(struct bpf_prog_array *array, return -EFAULT; i++; } - return item->prog ? -ENOSPC : 0; + return 0; } static int bpf_cgroup_array_delete_safe_at(struct bpf_prog_array *array, @@ -459,7 +499,7 @@ static void cgroup_bpf_release(struct work_struct *work) unsigned int atype; - cgroup_lock(); + cgroup_bpf_lock(); for (atype = 0; atype < ARRAY_SIZE(cgrp->bpf.progs); atype++) { struct hlist_head *progs = &cgrp->bpf.progs[atype]; @@ -469,7 +509,7 @@ static void cgroup_bpf_release(struct work_struct *work) hlist_for_each_entry_safe(pl, pltmp, progs, node) { hlist_del(&pl->node); if (pl->prog) { - if (pl->prog->expected_attach_type == BPF_LSM_CGROUP) + if (pl->prog->type == BPF_PROG_TYPE_LSM) bpf_trampoline_unlink_cgroup_shim(pl->prog); bpf_prog_put(pl->prog); } @@ -480,7 +520,7 @@ static void cgroup_bpf_release(struct work_struct *work) } old_array = rcu_dereference_protected( cgrp->bpf.effective[atype], - lockdep_is_held(&cgroup_mutex)); + cgroup_bpf_held()); bpf_cgroup_array_free(old_array, atype); } @@ -489,7 +529,7 @@ static void cgroup_bpf_release(struct work_struct *work) bpf_cgroup_storage_free(storage); } - cgroup_unlock(); + cgroup_bpf_unlock(); for (p = cgroup_parent(cgrp); p; p = cgroup_parent(p)) cgroup_bpf_put(p); @@ -665,7 +705,9 @@ static void activate_effective_progs(struct cgroup *cgrp, enum cgroup_bpf_attach_type atype, struct bpf_prog_array *old_array) { + /* cgroup_bpf_inherit() holds only cgroup_mutex, see cgroup_bpf_mutex */ old_array = rcu_replace_pointer(cgrp->bpf.effective[atype], old_array, + lockdep_is_held(&cgroup_bpf_mutex) || lockdep_is_held(&cgroup_mutex)); /* free prog array after grace period, since __cgroup_bpf_run_*() * might be still walking the array @@ -687,6 +729,9 @@ static int cgroup_bpf_inherit(struct cgroup *cgrp) struct cgroup *p; int ret, i; + /* See the comment above cgroup_bpf_mutex */ + lockdep_assert_held(&cgroup_mutex); + ret = percpu_ref_init(&cgrp->bpf.refcnt, cgroup_bpf_release_fn, 0, GFP_KERNEL); if (ret) @@ -747,6 +792,8 @@ static int update_effective_progs(struct cgroup *cgrp, struct cgroup_subsys_state *css; int err; + lockdep_assert_held(&cgroup_bpf_mutex); + /* allocate and recompute effective prog arrays */ css_for_each_descendant_pre(css, &cgrp->self) { struct cgroup *desc = container_of(css, struct cgroup, self); @@ -954,7 +1001,7 @@ static int insert_pl_to_hlist(struct bpf_prog_list *pl, struct hlist_head *progs * @revision: bpf_prog_list revision * * Exactly one of @prog or @link can be non-null. - * Must be called with cgroup_mutex held. + * Must be called with cgroup_mutex and cgroup_bpf_mutex held. */ static int __cgroup_bpf_attach(struct cgroup *cgrp, struct bpf_prog *prog, struct bpf_prog *replace_prog, @@ -988,6 +1035,13 @@ static int __cgroup_bpf_attach(struct cgroup *cgrp, /* replace_prog implies BPF_F_REPLACE, and vice versa */ return -EINVAL; + /* + * The cgroup may have been removed since the caller looked it up. + * Then its bpf state may be freed, and nothing would detach this. + */ + if (cgroup_is_dead(cgrp)) + return -ENOENT; + atype = bpf_cgroup_atype_find(type, new_prog->aux->attach_btf_id); if (atype < 0) return -EINVAL; @@ -1093,10 +1147,10 @@ static int cgroup_bpf_attach(struct cgroup *cgrp, { int ret; - cgroup_lock(); + cgroup_bpf_lock_hierarchy(); ret = __cgroup_bpf_attach(cgrp, prog, replace_prog, link, type, flags, id_or_fd, revision); - cgroup_unlock(); + cgroup_bpf_unlock_hierarchy(); return ret; } @@ -1174,7 +1228,7 @@ static void replace_effective_prog(struct cgroup *cgrp, progs = rcu_dereference_protected( desc->bpf.effective[atype], - lockdep_is_held(&cgroup_mutex)); + cgroup_bpf_held()); item = &progs->items[pos]; prog_list_replace_item(pl, item); } @@ -1194,6 +1248,24 @@ static bool cgroup_bpf_storages_compatible(struct bpf_prog *old_prog, return true; } +/* See bpf_prog_attach_check_attach_type() */ +static bool prog_is_for_attach_type(const struct bpf_prog *prog, enum bpf_attach_type type) +{ + switch (prog->type) { + case BPF_PROG_TYPE_CGROUP_SKB: + if (!prog->enforce_expected_attach_type) + return true; + fallthrough; + case BPF_PROG_TYPE_CGROUP_SOCK: + case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: + case BPF_PROG_TYPE_CGROUP_SOCKOPT: + case BPF_PROG_TYPE_LSM: + return prog->expected_attach_type == type; + default: + return true; + } +} + /** * __cgroup_bpf_replace() - Replace link's program and propagate the change * to descendants @@ -1202,7 +1274,7 @@ static bool cgroup_bpf_storages_compatible(struct bpf_prog *old_prog, * @new_prog: &struct bpf_prog for the target BPF program with its refcnt * incremented * - * Must be called with cgroup_mutex held. + * Must be called with cgroup_mutex and cgroup_bpf_mutex held. */ static int __cgroup_bpf_replace(struct cgroup *cgrp, struct bpf_cgroup_link *link, @@ -1220,7 +1292,8 @@ static int __cgroup_bpf_replace(struct cgroup *cgrp, progs = &cgrp->bpf.progs[atype]; - if (link->link.prog->type != new_prog->type) + if (link->link.prog->type != new_prog->type || + !prog_is_for_attach_type(new_prog, link->link.attach_type)) return -EINVAL; hlist_for_each_entry(pl, progs, node) { @@ -1250,7 +1323,7 @@ static int cgroup_bpf_replace(struct bpf_link *link, struct bpf_prog *new_prog, cg_link = container_of(link, struct bpf_cgroup_link, link); - cgroup_lock(); + cgroup_bpf_lock_hierarchy(); /* link might have been auto-released by dying cgroup, so fail */ if (!cg_link->cgroup) { ret = -ENOLINK; @@ -1262,7 +1335,7 @@ static int cgroup_bpf_replace(struct bpf_link *link, struct bpf_prog *new_prog, } ret = __cgroup_bpf_replace(cg_link->cgroup, cg_link, new_prog); out_unlock: - cgroup_unlock(); + cgroup_bpf_unlock_hierarchy(); return ret; } @@ -1333,7 +1406,7 @@ static void purge_effective_progs(struct cgroup *cgrp, struct bpf_prog_list *pl, progs = rcu_dereference_protected( desc->bpf.effective[atype], - lockdep_is_held(&cgroup_mutex)); + cgroup_bpf_held()); /* Remove the program from the array */ WARN_ONCE(bpf_cgroup_array_delete_safe_at(progs, pos, atype), @@ -1351,7 +1424,7 @@ static void purge_effective_progs(struct cgroup *cgrp, struct bpf_prog_list *pl, * @revision: bpf_prog_list revision * * At most one of @prog or @link can be non-NULL. - * Must be called with cgroup_mutex held. + * Must be called with cgroup_mutex and cgroup_bpf_mutex held. */ static int __cgroup_bpf_detach(struct cgroup *cgrp, struct bpf_prog *prog, struct bpf_cgroup_link *link, enum bpf_attach_type type, @@ -1421,13 +1494,13 @@ static int cgroup_bpf_detach(struct cgroup *cgrp, struct bpf_prog *prog, { int ret; - cgroup_lock(); + cgroup_bpf_lock_hierarchy(); ret = __cgroup_bpf_detach(cgrp, prog, NULL, type, revision); - cgroup_unlock(); + cgroup_bpf_unlock_hierarchy(); return ret; } -/* Must be called with cgroup_mutex held to avoid races. */ +/* Must be called with cgroup_bpf_mutex held. */ static int __cgroup_bpf_query(struct cgroup *cgrp, const union bpf_attr *attr, union bpf_attr __user *uattr, u32 uattr_size) { @@ -1446,6 +1519,14 @@ static int __cgroup_bpf_query(struct cgroup *cgrp, const union bpf_attr *attr, if (effective_query && prog_attach_flags) return -EINVAL; + /* + * cgroup_bpf_release() frees the effective arrays once the bpf + * refcount is zero. It takes this lock too, so a nonzero count means + * the arrays are still valid. + */ + if (percpu_ref_is_zero(&cgrp->bpf.refcnt)) + return -ENOENT; + if (type == BPF_STRUCT_OPS) { u32 type_id = attr->query.type_id; @@ -1473,7 +1554,7 @@ static int __cgroup_bpf_query(struct cgroup *cgrp, const union bpf_attr *attr, for (atype = from_atype; atype <= to_atype; atype++) { if (effective_query) { effective = rcu_dereference_protected(cgrp->bpf.effective[atype], - lockdep_is_held(&cgroup_mutex)); + cgroup_bpf_held()); total_cnt += bpf_cgroup_array_length(effective, atype); } else { total_cnt += prog_list_length(&cgrp->bpf.progs[atype], NULL); @@ -1503,9 +1584,10 @@ static int __cgroup_bpf_query(struct cgroup *cgrp, const union bpf_attr *attr, for (atype = from_atype; atype <= to_atype && total_cnt; atype++) { if (effective_query) { effective = rcu_dereference_protected(cgrp->bpf.effective[atype], - lockdep_is_held(&cgroup_mutex)); + cgroup_bpf_held()); cnt = min_t(int, bpf_cgroup_array_length(effective, atype), total_cnt); - ret = bpf_cgroup_array_copy_to_user(effective, prog_ids, cnt, atype); + if (bpf_cgroup_array_copy_to_user(effective, prog_ids, cnt, atype)) + return -EFAULT; } else { struct hlist_head *progs; struct bpf_prog_list *pl; @@ -1544,9 +1626,9 @@ static int cgroup_bpf_query(struct cgroup *cgrp, const union bpf_attr *attr, { int ret; - cgroup_lock(); + cgroup_bpf_lock(); ret = __cgroup_bpf_query(cgrp, attr, uattr, uattr_size); - cgroup_unlock(); + cgroup_bpf_unlock(); return ret; } @@ -1614,11 +1696,11 @@ static void bpf_cgroup_link_release(struct bpf_link *link) if (!cg_link->cgroup) return; - cgroup_lock(); + cgroup_bpf_lock_hierarchy(); /* re-check cgroup under lock again */ if (!cg_link->cgroup) { - cgroup_unlock(); + cgroup_bpf_unlock_hierarchy(); return; } @@ -1630,7 +1712,7 @@ static void bpf_cgroup_link_release(struct bpf_link *link) cg = cg_link->cgroup; cg_link->cgroup = NULL; - cgroup_unlock(); + cgroup_bpf_unlock_hierarchy(); cgroup_put(cg); } @@ -1657,10 +1739,10 @@ static void bpf_cgroup_link_show_fdinfo(const struct bpf_link *link, container_of(link, struct bpf_cgroup_link, link); u64 cg_id = 0; - cgroup_lock(); + cgroup_bpf_lock(); if (cg_link->cgroup) cg_id = cgroup_id(cg_link->cgroup); - cgroup_unlock(); + cgroup_bpf_unlock(); seq_printf(seq, "cgroup_id:\t%llu\n" @@ -1676,10 +1758,10 @@ static int bpf_cgroup_link_fill_link_info(const struct bpf_link *link, container_of(link, struct bpf_cgroup_link, link); u64 cg_id = 0; - cgroup_lock(); + cgroup_bpf_lock(); if (cg_link->cgroup) cg_id = cgroup_id(cg_link->cgroup); - cgroup_unlock(); + cgroup_bpf_unlock(); info->cgroup.cgroup_id = cg_id; info->cgroup.attach_type = link->attach_type; @@ -1928,6 +2010,10 @@ int __cgroup_bpf_run_filter_sock_addr(struct sock *sk, ctx.uaddrlen = 0; } else { ctx.uaddrlen = *uaddrlen; + /* Programs read the family and the port also of a short address. */ + if (ctx.uaddrlen < offsetofend(struct sockaddr_in, sin_port)) + memset((void *)uaddr + ctx.uaddrlen, 0, + offsetofend(struct sockaddr_in, sin_port) - ctx.uaddrlen); } cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data); @@ -2024,7 +2110,7 @@ BPF_CALL_0(bpf_get_retval) struct bpf_cg_run_ctx *ctx = container_of(current->bpf_ctx, struct bpf_cg_run_ctx, run_ctx); - return ctx->retval; + return bpf_in_async_cb() ? 0 : ctx->retval; } const struct bpf_func_proto bpf_get_retval_proto = { @@ -2038,6 +2124,8 @@ BPF_CALL_1(bpf_set_retval, int, retval) struct bpf_cg_run_ctx *ctx = container_of(current->bpf_ctx, struct bpf_cg_run_ctx, run_ctx); + if (bpf_in_async_cb()) + return -EOPNOTSUPP; ctx->retval = retval; return 0; } @@ -2956,11 +3044,11 @@ static int __cgroup_struct_ops_link_detach(struct bpf_link *link, bool wake_poll struct bpf_map *map; struct cgroup *cgrp; - cgroup_lock(); + cgroup_bpf_lock_hierarchy(); cgrp = cg_link->cgroup; if (!cgrp) { - cgroup_unlock(); + cgroup_bpf_unlock_hierarchy(); return 0; } @@ -2972,7 +3060,7 @@ static int __cgroup_struct_ops_link_detach(struct bpf_link *link, bool wake_poll break; } if (WARN_ON_ONCE(!pl)) { - cgroup_unlock(); + cgroup_bpf_unlock_hierarchy(); return -ENOENT; } @@ -2990,7 +3078,7 @@ static int __cgroup_struct_ops_link_detach(struct bpf_link *link, bool wake_poll kfree(pl); static_branch_dec(&cgroup_bpf_enabled_key[atype]); - cgroup_unlock(); + cgroup_bpf_unlock_hierarchy(); return 0; } @@ -3013,15 +3101,15 @@ static void cgroup_struct_ops_link_show_fdinfo(const struct bpf_link *link, stru struct bpf_cgroup_link *cg_link = container_of(link, struct bpf_cgroup_link, link); - cgroup_lock(); + cgroup_bpf_lock(); if (!cg_link->cgroup) { - cgroup_unlock(); + cgroup_bpf_unlock(); return; } seq_printf(seq, "map_id:\t%u\n", cg_link->map->id); seq_printf(seq, "cgroup_id:\t%llu\n", cgroup_id(cg_link->cgroup)); - cgroup_unlock(); + cgroup_bpf_unlock(); } static int cgroup_struct_ops_link_fill_link_info(const struct bpf_link *link, @@ -3029,15 +3117,15 @@ static int cgroup_struct_ops_link_fill_link_info(const struct bpf_link *link, { struct bpf_cgroup_link *cg_link = container_of(link, struct bpf_cgroup_link, link); - cgroup_lock(); + cgroup_bpf_lock(); if (!cg_link->cgroup) { - cgroup_unlock(); + cgroup_bpf_unlock(); return 0; } info->struct_ops.map_id = cg_link->map->id; info->struct_ops.cgroup_id = cgroup_id(cg_link->cgroup); - cgroup_unlock(); + cgroup_bpf_unlock(); return 0; } @@ -3055,7 +3143,7 @@ static int cgroup_struct_ops_link_update(struct bpf_link *link, struct bpf_map * if (!bpf_struct_ops_valid_to_reg(new_map)) return -EINVAL; - cgroup_lock(); + cgroup_bpf_lock_hierarchy(); cgrp = cg_link->cgroup; if (!cgrp) { @@ -3088,7 +3176,7 @@ static int cgroup_struct_ops_link_update(struct bpf_link *link, struct bpf_map * cgrp->bpf.revisions[atype]++; out: - cgroup_unlock(); + cgroup_bpf_unlock_hierarchy(); return err; } @@ -3160,7 +3248,13 @@ int cgroup_bpf_struct_ops_attach(struct bpf_map *map, const union bpf_attr *attr atype = bpf_struct_ops_map_cgroup_atype(map); progs = &cgrp->bpf.progs[atype]; - cgroup_lock(); + cgroup_bpf_lock_hierarchy(); + + /* See the cgroup_is_dead() check in __cgroup_bpf_attach() */ + if (cgroup_is_dead(cgrp)) { + err = -ENOENT; + goto unlock; + } if (attr->link_create.cgroup.expected_revision && attr->link_create.cgroup.expected_revision != cgrp->bpf.revisions[atype]) { @@ -3197,12 +3291,12 @@ int cgroup_bpf_struct_ops_attach(struct bpf_map *map, const union bpf_attr *attr cgrp->bpf.revisions[atype]++; static_branch_inc(&cgroup_bpf_enabled_key[atype]); - cgroup_unlock(); + cgroup_bpf_unlock_hierarchy(); return bpf_link_settle(&link_primer); unlock: - cgroup_unlock(); + cgroup_bpf_unlock_hierarchy(); cleanup: kfree(pl); diff --git a/kernel/bpf/core.c b/kernel/bpf/core.c index 0b8456f2dce9fb..6742f5be865860 100644 --- a/kernel/bpf/core.c +++ b/kernel/bpf/core.c @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -82,6 +83,8 @@ void *bpf_internal_load_pointer_neg_helper(const struct sk_buff *skb, int k, uns u8 *ptr = NULL; if (k >= SKF_NET_OFF) { + if (unlikely(!bpf_skb_has_network_header(skb))) + return NULL; ptr = skb_network_header(skb) + k - SKF_NET_OFF; } else if (k >= SKF_LL_OFF) { if (unlikely(!skb_mac_header_was_set(skb))) @@ -232,7 +235,8 @@ void bpf_prog_fill_jited_linfo(struct bpf_prog *prog, const struct bpf_line_info *linfo; void **jited_linfo; - if (!prog->aux->jited_linfo || prog->aux->func_idx > prog->aux->func_cnt) + if (!prog->aux->jited_linfo || + (prog->aux->func_idx && prog->aux->func_idx >= prog->aux->func_cnt)) /* Userspace did not provide linfo */ return; @@ -646,11 +650,10 @@ static struct latch_tree_root bpf_tree __cacheline_aligned; void bpf_ksym_add(struct bpf_ksym *ksym) { - spin_lock_bh(&bpf_lock); + guard(spinlock_irqsave)(&bpf_lock); WARN_ON_ONCE(!list_empty(&ksym->lnode)); list_add_tail_rcu(&ksym->lnode, &bpf_kallsyms); latch_tree_insert(&ksym->tnode, &bpf_tree, &bpf_tree_ops); - spin_unlock_bh(&bpf_lock); } static void __bpf_ksym_del(struct bpf_ksym *ksym) @@ -664,9 +667,8 @@ static void __bpf_ksym_del(struct bpf_ksym *ksym) void bpf_ksym_del(struct bpf_ksym *ksym) { - spin_lock_bh(&bpf_lock); + guard(spinlock_irqsave)(&bpf_lock); __bpf_ksym_del(ksym); - spin_unlock_bh(&bpf_lock); } static bool bpf_prog_kallsyms_candidate(const struct bpf_prog *fp) @@ -785,7 +787,7 @@ bool bpf_has_frame_pointer(unsigned long ip) offset = ip - ksym->start; - return offset >= ksym->fp_start && offset < ksym->fp_end; + return offset >= ksym->fp_start && offset < ksym->fp_end && offset != ksym->fp_ret; } const struct exception_table_entry *search_bpf_extables(unsigned long addr) @@ -2514,18 +2516,34 @@ static unsigned int __bpf_prog_ret0_warn(const void *ctx, return 0; } +/* What the verifier took from the hook, next to its prototype */ +static u64 bpf_prog_hook_key(const struct bpf_prog *fp) +{ + if (IS_ENABLED(CONFIG_BPF_SYSCALL) && fp->aux->attach_btf_trace) + return btf_raw_tp_null_mask(fp); + if (fp->type == BPF_PROG_TYPE_TRACING && fp->expected_attach_type != BPF_TRACE_ITER) + return fp->aux->saved_dst_ctx_type; + if (fp->type == BPF_PROG_TYPE_TRACING || fp->type == BPF_PROG_TYPE_LSM) + return fp->aux->attach_btf_id; + return 0; +} + static bool __bpf_prog_map_compatible(struct bpf_map *map, const struct bpf_prog *fp) { + enum bpf_attach_type attach_type = fp->expected_attach_type; enum bpf_prog_type prog_type = resolve_prog_type(fp); struct bpf_prog_aux *aux = fp->aux; enum bpf_cgroup_storage_type i; + u64 cookie, hook_key = bpf_prog_hook_key(fp); bool ret = false; - u64 cookie; if (fp->kprobe_override) return ret; + if (fp->type == BPF_PROG_TYPE_EXT) + attach_type = aux->saved_dst_attach_type; + spin_lock(&map->owner_lock); /* There's no owner yet where we could check for compatibility. */ if (!map->owner) { @@ -2536,8 +2554,10 @@ static bool __bpf_prog_map_compatible(struct bpf_map *map, map->owner->jited = fp->jited; map->owner->xdp_has_frags = aux->xdp_has_frags; map->owner->sleepable = fp->sleepable; - map->owner->expected_attach_type = fp->expected_attach_type; + map->owner->expected_attach_type = attach_type; map->owner->attach_func_proto = aux->attach_func_proto; + map->owner->st_ops = aux->st_ops; + map->owner->hook_key = hook_key; for_each_cgroup_storage_type(i) { map->owner->storage_cookie[i] = aux->cgroup_storage[i] ? @@ -2548,10 +2568,12 @@ static bool __bpf_prog_map_compatible(struct bpf_map *map, ret = map->owner->type == prog_type && map->owner->jited == fp->jited && map->owner->xdp_has_frags == aux->xdp_has_frags && - map->owner->sleepable == fp->sleepable; + map->owner->sleepable == fp->sleepable && + map->owner->st_ops == aux->st_ops && + map->owner->hook_key == hook_key; if (ret && map->map_type == BPF_MAP_TYPE_PROG_ARRAY && - map->owner->expected_attach_type != fp->expected_attach_type) + map->owner->expected_attach_type != attach_type) ret = false; for_each_cgroup_storage_type(i) { if (!ret) @@ -3143,6 +3165,17 @@ static void bpf_free_used_btfs(struct bpf_prog_aux *aux) kfree(aux->used_btfs); } +struct workqueue_struct *bpf_prog_free_wq __ro_after_init; + +static int __init bpf_prog_free_wq_init(void) +{ + bpf_prog_free_wq = alloc_workqueue("bpf_prog_free", WQ_PERCPU, 1); + if (!bpf_prog_free_wq) + panic("Failed to allocate BPF program free workqueue\n"); + return 0; +} +early_initcall(bpf_prog_free_wq_init); + static void bpf_prog_free_images(struct work_struct *work) { struct bpf_prog_aux *aux; @@ -3198,7 +3231,7 @@ static void bpf_prog_free_deferred(struct work_struct *work) /* 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); + queue_rcu_work(bpf_prog_free_wq, &aux->rwork); else bpf_prog_free_images(&aux->rwork.work); } @@ -3211,7 +3244,11 @@ void bpf_prog_free(struct bpf_prog *fp) bpf_prog_put(aux->dst_prog); bpf_token_put(aux->token); INIT_WORK(&aux->work, bpf_prog_free_deferred); - schedule_work(&aux->work); + /* + * Free BPF programs on a dedicated workqueue to avoid blocking or slowing + * down the system workqueue. + */ + queue_work(bpf_prog_free_wq, &aux->work); } /* RNG for unprivileged user space with separated state from prandom_u32(). */ @@ -3678,6 +3715,15 @@ void bpf_timed_may_goto_restore(const struct bpf_prog *prog, struct bpf_timed_ma *cur = *saved; } +/* A walk of the stack is too long for BPF_MAX_TIMED_LOOPS trips. The next one looks at the time. */ +void bpf_timed_may_goto_check_time(const struct bpf_prog *prog) +{ + struct bpf_timed_may_goto __percpu *tmg = prog->aux->main_prog_aux->timed_may_goto; + + if (tmg && this_cpu_read(tmg->count)) + this_cpu_write(tmg->count, 1); +} + /* for configs without MMU or 32-bit */ __weak const struct bpf_map_ops arena_map_ops; __weak u64 bpf_arena_get_user_vm_start(struct bpf_arena *arena) diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c index a656634fa9e468..8c3a17a05a4e19 100644 --- a/kernel/bpf/fixups.c +++ b/kernel/bpf/fixups.c @@ -911,6 +911,7 @@ int bpf_convert_ctx_accesses(struct bpf_verifier_env *env) const int insn_cnt = env->prog->len; struct bpf_insn *epilogue_buf = env->epilogue_buf; struct bpf_insn *insn_buf = env->insn_buf; + bool nospec, nospec_next = false; struct bpf_insn *insn; u32 target_size, size_default, off; struct bpf_prog *new_prog; @@ -994,8 +995,13 @@ int bpf_convert_ctx_accesses(struct bpf_verifier_env *env) enum bpf_reg_type ptr_type; u8 mode; - if (env->insn_aux_data[i + delta].nospec) { - WARN_ON_ONCE(env->insn_aux_data[i + delta].alu_state); + /* A call or an atomic gets its nospec in front of the next insn */ + nospec = env->insn_aux_data[i + delta].nospec; + WARN_ON_ONCE(nospec && env->insn_aux_data[i + delta].alu_state); + nospec |= nospec_next; + nospec_next = env->insn_aux_data[i + delta].nospec_result; + + if (nospec) { struct bpf_insn *patch = insn_buf; *patch++ = BPF_ST_NOSPEC(); @@ -1102,6 +1108,7 @@ int bpf_convert_ctx_accesses(struct bpf_verifier_env *env) delta += cnt - 1; env->prog = new_prog; insn = new_prog->insnsi + i + delta; + nospec_next = false; continue; } @@ -1572,6 +1579,9 @@ static int jit_subprogs(struct bpf_verifier_env *env) prog->jited_len = func[0]->jited_len; prog->aux->extable = func[0]->aux->extable; prog->aux->num_exentries = func[0]->aux->num_exentries; + prog->aux->ksym.fp_start = func[0]->aux->ksym.fp_start; + prog->aux->ksym.fp_end = func[0]->aux->ksym.fp_end; + prog->aux->ksym.fp_ret = func[0]->aux->ksym.fp_ret; prog->aux->func = func; prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; prog->aux->real_func_cnt = env->subprog_cnt; @@ -2254,6 +2264,10 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env) * the program array. */ prog->cb_access = 1; + prog->call_get_func_ip = 1; + if (prog_type == BPF_PROG_TYPE_TRACING && + (eatype == BPF_TRACE_FSESSION || eatype == BPF_TRACE_FSESSION_MULTI)) + prog->call_session_cookie = 1; if (!bpf_allow_tail_call_in_subprogs(env)) prog->aux->stack_depth = MAX_BPF_STACK; prog->aux->max_pkt_offset = MAX_PACKET_OFF; diff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c index 6788489a2608b3..cebf9d8dfe36db 100644 --- a/kernel/bpf/helpers.c +++ b/kernel/bpf/helpers.c @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -22,7 +23,7 @@ #include #include #include -#include +#include #include #include #include @@ -726,7 +727,7 @@ BPF_CALL_5(bpf_copy_from_user_task, void *, dst, u32, size, if (unlikely(!size)) return 0; - mm = get_task_mm(tsk); + mm = tsk ? get_task_mm(tsk) : NULL; if (!mm) { memset(dst, 0, size); return -EFAULT; @@ -1218,12 +1219,25 @@ static DEFINE_PER_CPU(struct bpf_hrtimer *, hrtimer_running); static void bpf_async_refcount_put(struct bpf_async_cb *cb); +struct bpf_run_ctx bpf_async_run_ctx; + +static void bpf_run_async_cb(struct bpf_prog *prog, bpf_callback_t callback_fn, + struct bpf_map *map, void *key, void *value) +{ + struct bpf_run_ctx *old_ctx = bpf_set_run_ctx(&bpf_async_run_ctx); + struct bpf_timed_may_goto saved; + + bpf_timed_may_goto_save(prog, &saved); + callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0); + bpf_timed_may_goto_restore(prog, &saved); + bpf_reset_run_ctx(old_ctx); +} + 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 = READ_ONCE(t->cb.map); struct bpf_prog *prog = READ_ONCE(t->cb.prog); - struct bpf_timed_may_goto saved; void *value = t->cb.value; bpf_callback_t callback_fn; void *key; @@ -1244,10 +1258,8 @@ static enum hrtimer_restart bpf_timer_cb(struct hrtimer *hrtimer) key = map_key_from_value(map, value, &idx); - bpf_timed_may_goto_save(prog, &saved); - callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0); /* The verifier checked that return value is zero. */ - bpf_timed_may_goto_restore(prog, &saved); + bpf_run_async_cb(prog, callback_fn, map, key, value); this_cpu_write(hrtimer_running, NULL); out: @@ -1258,7 +1270,6 @@ 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_timed_may_goto saved; struct bpf_prog *prog; struct bpf_map *map; bpf_callback_t callback_fn; @@ -1281,9 +1292,7 @@ static void bpf_wq_work(struct work_struct *work) migrate_disable(); - bpf_timed_may_goto_save(prog, &saved); - callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0); - bpf_timed_may_goto_restore(prog, &saved); + bpf_run_async_cb(prog, callback_fn, map, key, value); migrate_enable(); out: @@ -2185,10 +2194,6 @@ bpf_base_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog) return &bpf_spin_unlock_proto; case BPF_FUNC_jiffies64: return &bpf_jiffies64_proto; - case BPF_FUNC_per_cpu_ptr: - return &bpf_per_cpu_ptr_proto; - case BPF_FUNC_this_cpu_ptr: - return &bpf_this_cpu_ptr_proto; case BPF_FUNC_timer_init: return &bpf_timer_init_proto; case BPF_FUNC_timer_set_callback: @@ -2292,6 +2297,10 @@ bpf_base_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog) return &bpf_get_branch_snapshot_proto; case BPF_FUNC_find_vma: return &bpf_find_vma_proto; + case BPF_FUNC_per_cpu_ptr: + return &bpf_per_cpu_ptr_proto; + case BPF_FUNC_this_cpu_ptr: + return &bpf_this_cpu_ptr_proto; default: return NULL; } @@ -2302,6 +2311,7 @@ void bpf_list_head_free(const struct btf_field *field, void *list_head, struct bpf_spin_lock *spin_lock) { struct list_head *head = list_head, drain, *pos, *n; + unsigned long flags; BUILD_BUG_ON(sizeof(struct list_head) > sizeof(struct bpf_list_head)); BUILD_BUG_ON(__alignof__(struct list_head) > __alignof__(struct bpf_list_head)); @@ -2313,7 +2323,8 @@ void bpf_list_head_free(const struct btf_field *field, void *list_head, * section, and end up doing map ops that call bpf_list_head_free for * the same map value again. */ - __bpf_spin_lock_irqsave(spin_lock); + local_irq_save(flags); + __bpf_spin_lock(spin_lock); if (!head->next || list_empty(head)) goto unlock; list_for_each_safe(pos, n, head) { @@ -2325,7 +2336,8 @@ void bpf_list_head_free(const struct btf_field *field, void *list_head, } unlock: INIT_LIST_HEAD(head); - __bpf_spin_unlock_irqrestore(spin_lock); + __bpf_spin_unlock(spin_lock); + local_irq_restore(flags); while (!list_empty(&drain)) { struct bpf_list_node_kern *node; @@ -2362,19 +2374,22 @@ void bpf_rb_root_free(const struct btf_field *field, void *rb_root, struct rb_root_cached orig_root, *root = rb_root; struct bpf_rb_node_kern *node; struct rb_node *pos, *n; + unsigned long flags; void *obj; BUILD_BUG_ON(sizeof(struct rb_root_cached) > sizeof(struct bpf_rb_root)); BUILD_BUG_ON(__alignof__(struct rb_root_cached) > __alignof__(struct bpf_rb_root)); - __bpf_spin_lock_irqsave(spin_lock); + local_irq_save(flags); + __bpf_spin_lock(spin_lock); orig_root = *root; bpf_rbtree_postorder_for_each_entry_safe(pos, n, &orig_root.rb_root) { node = rb_entry(pos, struct bpf_rb_node_kern, rb_node); WRITE_ONCE(node->owner, BPF_PTR_POISON); } *root = RB_ROOT_CACHED; - __bpf_spin_unlock_irqrestore(spin_lock); + __bpf_spin_unlock(spin_lock); + local_irq_restore(flags); bpf_rbtree_postorder_for_each_entry_safe(pos, n, &orig_root.rb_root) { obj = pos; @@ -3138,7 +3153,8 @@ __bpf_kfunc void *bpf_dynptr_slice(const struct bpf_dynptr *p, u64 offset, if (!IS_ERR_OR_NULL(xdp_ptr)) return xdp_ptr; - if (!buffer__nullable) + /* the packet may be shorter than it was for bpf_dynptr_from_xdp() */ + if (!buffer__nullable || ptr->offset + offset + len > xdp_get_buff_len(ptr->data)) return NULL; bpf_xdp_copy_buf(ptr->data, ptr->offset + offset, buffer__nullable, len, false); return buffer__nullable; @@ -3457,7 +3473,8 @@ static bool bpf_stack_walker(void *cookie, u64 ip, u64 sp, u64 bp) return false; } -__bpf_kfunc void bpf_throw(u64 cookie) +/* It does not return. What a tracer keeps for the return would stay behind, redzones too. */ +__bpf_kfunc notrace __no_sanitize_address void bpf_throw(u64 cookie) { struct bpf_throw_ctx ctx = {}; @@ -3467,16 +3484,11 @@ __bpf_kfunc void bpf_throw(u64 cookie) WARN_ON_ONCE(!ctx.aux->exception_boundary); WARN_ON_ONCE(!ctx.bp); WARN_ON_ONCE(!ctx.cnt); - /* - * Prevent KASAN false positives for CONFIG_KASAN_STACK by unpoisoning - * deeper stack depths than ctx.sp as we do not return from bpf_throw, - * which skips compiler generated instrumentation to do the same. Some - * architectures cannot recover sp while unwinding, so fall back to bp. - */ - kasan_unpoison_task_stack_below((void *)(long)(ctx.sp ?: ctx.bp)); + /* arm64 drops one entry of the shadow call stack, don't move the call to a callee */ ctx.aux->bpf_exception_cb(cookie, ctx.sp + ctx.aux->stack_arg_sp_adjust, ctx.bp, 0, 0); WARN(1, "A call to BPF exception callback should never return\n"); } +NOKPROBE_SYMBOL(bpf_throw); __bpf_kfunc int bpf_wq_init(struct bpf_wq *wq, void *p__const_map, unsigned int flags) { @@ -4620,7 +4632,6 @@ static void bpf_task_work_cancel(struct bpf_task_work_ctx *ctx, static void bpf_task_work_callback(struct callback_head *cb) { struct bpf_task_work_ctx *ctx = container_of(cb, struct bpf_task_work_ctx, work); - struct bpf_timed_may_goto saved; enum bpf_task_work_state state; u32 idx; void *key; @@ -4642,10 +4653,7 @@ static void bpf_task_work_callback(struct callback_head *cb) key = (void *)map_key_from_value(ctx->map, ctx->map_val, &idx); migrate_disable(); - bpf_timed_may_goto_save(ctx->prog, &saved); - ctx->callback_fn((u64)(long)ctx->map, (u64)(long)key, - (u64)(long)ctx->map_val, 0, 0); - bpf_timed_may_goto_restore(ctx->prog, &saved); + bpf_run_async_cb(ctx->prog, ctx->callback_fn, ctx->map, key, ctx->map_val); migrate_enable(); bpf_task_work_ctx_reset(ctx); @@ -4800,6 +4808,9 @@ static int bpf_task_work_schedule(struct task_struct *task, struct bpf_task_work BTF_TYPE_EMIT(struct bpf_task_work); + if (task->flags & PF_KTHREAD) + return -EPERM; + prog = bpf_prog_inc_not_zero(aux->prog); if (IS_ERR(prog)) return -EBADF; @@ -4885,7 +4896,6 @@ static void bpf_rcu_run_callback(struct rcu_head *rcu) struct bpf_rcu_head_kern *rh = container_of(rcu, struct bpf_rcu_head_kern, rcu); bpf_callback_t callback_fn = rh->callback_fn; struct bpf_prog *prog = rh->prog; - struct bpf_timed_may_goto saved; struct bpf_map *map = rh->map; void *value, *key; u32 idx; @@ -4897,9 +4907,7 @@ static void bpf_rcu_run_callback(struct rcu_head *rcu) smp_store_release(&rh->armed, 0); rcu_read_lock_dont_migrate(); - bpf_timed_may_goto_save(prog, &saved); - callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0); - bpf_timed_may_goto_restore(prog, &saved); + bpf_run_async_cb(prog, callback_fn, map, key, value); rcu_read_unlock_migrate(); bpf_prog_put(prog); @@ -5155,7 +5163,7 @@ BTF_ID_FLAGS(func, bpf_task_from_pid, KF_ACQUIRE | KF_RET_NULL) BTF_ID_FLAGS(func, bpf_task_from_vpid, KF_ACQUIRE | KF_RET_NULL) BTF_ID_FLAGS(func, bpf_throw) #ifdef CONFIG_BPF_EVENTS -BTF_ID_FLAGS(func, bpf_send_signal_task) +BTF_ID_FLAGS(func, bpf_send_signal_task, KF_PERFMON) #endif #ifdef CONFIG_KEYS BTF_ID_FLAGS(func, bpf_lookup_user_key, KF_ACQUIRE | KF_RET_NULL | KF_SLEEPABLE) @@ -5271,8 +5279,8 @@ BTF_ID_FLAGS(func, bpf_cgroup_read_xattr, KF_RCU) #endif BTF_ID_FLAGS(func, bpf_stream_vprintk, KF_IMPLICIT_ARGS | KF_SPINLOCK_SAFE | KF_PERFMON) BTF_ID_FLAGS(func, bpf_stream_print_stack, KF_IMPLICIT_ARGS | KF_SPINLOCK_SAFE | KF_PERFMON) -BTF_ID_FLAGS(func, bpf_task_work_schedule_signal, KF_IMPLICIT_ARGS) -BTF_ID_FLAGS(func, bpf_task_work_schedule_resume, KF_IMPLICIT_ARGS) +BTF_ID_FLAGS(func, bpf_task_work_schedule_signal, KF_IMPLICIT_ARGS | KF_PERFMON) +BTF_ID_FLAGS(func, bpf_task_work_schedule_resume, KF_IMPLICIT_ARGS | KF_PERFMON) BTF_ID_FLAGS(func, bpf_call_rcu, KF_IMPLICIT_ARGS) BTF_ID_FLAGS(func, bpf_call_rcu_tasks_trace, KF_IMPLICIT_ARGS) BTF_ID_FLAGS(func, bpf_dynptr_from_file) diff --git a/kernel/bpf/inode.c b/kernel/bpf/inode.c index c6f328e4752e1d..eefd1da179c524 100644 --- a/kernel/bpf/inode.c +++ b/kernel/bpf/inode.c @@ -310,6 +310,11 @@ static int bpffs_map_open(struct inode *inode, struct file *file) struct seq_file *m; int err; + /* Special fields are printed as they are. Most have addresses. */ + if (btf_record_has_field(map->record, ~(BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) && + !perfmon_capable()) + return -EPERM; + iter = map_iter_alloc(map); if (!iter) return -ENOMEM; @@ -1055,7 +1060,7 @@ static int bpf_parse_param(struct fs_context *fc, struct fs_parameter *param) struct bpffs_btf_enums info; const struct btf_type *enum_t; const char *enum_pfx; - u64 *delegate_msk, msk = 0; + u64 *delegate_msk, msk = 0, num; char *p, *str; int val; @@ -1094,9 +1099,10 @@ static int bpf_parse_param(struct fs_context *fc, struct fs_parameter *param) } else if (find_btf_enum_const(info.btf, enum_t, enum_pfx, p, &val)) { msk |= 1ULL << val; } else { - err = kstrtou64(p, 0, &msk); + err = kstrtou64(p, 0, &num); if (err) return err; + msk |= num; } } diff --git a/kernel/bpf/local_storage.c b/kernel/bpf/local_storage.c index 83cd527a2542bd..2cfbddeb1c7e97 100644 --- a/kernel/bpf/local_storage.c +++ b/kernel/bpf/local_storage.c @@ -345,14 +345,18 @@ static void cgroup_storage_map_free(struct bpf_map *_map) struct list_head *storages = &map->list; struct bpf_cgroup_storage *storage, *stmp; - cgroup_lock(); + /* + * Attach and cgroup_bpf_release() change the same cgroup storage + * lists under other maps' locks, so take cgroup_bpf_mutex. + */ + cgroup_bpf_lock(); list_for_each_entry_safe(storage, stmp, storages, list_map) { bpf_cgroup_storage_unlink(storage); bpf_cgroup_storage_free(storage); } - cgroup_unlock(); + cgroup_bpf_unlock(); WARN_ON(!RB_EMPTY_ROOT(&map->root)); WARN_ON(!list_empty(&map->list)); diff --git a/kernel/bpf/map_iter.c b/kernel/bpf/map_iter.c index a58c148692e6c3..7a769e5f539724 100644 --- a/kernel/bpf/map_iter.c +++ b/kernel/bpf/map_iter.c @@ -99,8 +99,8 @@ static struct bpf_iter_reg bpf_map_reg_info = { /* * For an iterator that hands the live map value to the program as a writable - * buffer: the verifier knows nothing of the map, so the special fields of the - * value have to lie outside of what the program may write. + * buffer: the verifier knows nothing of the map, so read-only maps + * and special fields of the value have to be protected from writes. */ int bpf_iter_map_check_value_write(const struct bpf_prog *prog, const struct bpf_map *map) @@ -109,7 +109,13 @@ int bpf_iter_map_check_value_write(const struct bpf_prog *prog, const struct btf_field *field; u32 i; - if (IS_ERR_OR_NULL(rec) || !prog->aux->max_rdwr_write) + if (!prog->aux->max_rdwr_write) + return 0; + + if (map->map_flags & BPF_F_RDONLY_PROG) + return -EACCES; + + if (IS_ERR_OR_NULL(rec)) return 0; for (i = 0; i < rec->cnt; i++) { diff --git a/kernel/bpf/stackmap.c b/kernel/bpf/stackmap.c index a19126f5db0292..f25f5585e578c1 100644 --- a/kernel/bpf/stackmap.c +++ b/kernel/bpf/stackmap.c @@ -897,7 +897,7 @@ static long __bpf_get_task_stack(struct task_struct *task, void *buf, u32 size, struct pt_regs *regs; long res = -EINVAL; - if (!try_get_task_stack(task)) { + if (!task || !try_get_task_stack(task)) { memset(buf, 0, size); return -EFAULT; } diff --git a/kernel/bpf/stream.c b/kernel/bpf/stream.c index 83e803ea54ef24..53519a17bf261d 100644 --- a/kernel/bpf/stream.c +++ b/kernel/bpf/stream.c @@ -74,7 +74,9 @@ static int bpf_stream_consume_capacity(struct bpf_stream *stream, int len) static void bpf_stream_release_capacity(struct bpf_stream *stream, int len) { - atomic_sub(len, &stream->capacity); + if (atomic_sub_return(len, &stream->capacity) + READ_ONCE(stream->refused) < + BPF_STREAM_MAX_CAPACITY) + WRITE_ONCE(stream->refused, 0); } static void bpf_stream_notify(struct irq_work *work) @@ -266,6 +268,8 @@ int bpf_prog_stream_read(struct bpf_prog *prog, enum bpf_stream_id stream_id, vo { struct bpf_stream *stream; + if (!bpf_token_capable(prog->aux->token, CAP_PERFMON)) + return -EPERM; stream = bpf_stream_get(stream_id, prog->aux); if (!stream) return -ENOENT; @@ -366,6 +370,8 @@ int bpf_prog_stream_new_fd(struct bpf_prog *prog, enum bpf_stream_id stream_id, int fd_flags = O_RDONLY | O_CLOEXEC; int fd; + if (!bpf_token_capable(prog->aux->token, CAP_PERFMON)) + return -EPERM; stream = bpf_stream_get(stream_id, prog->aux); if (!stream) return -ENOENT; @@ -490,6 +496,15 @@ void bpf_prog_stream_free(struct bpf_prog *prog) } } +/* A dump of the stack is expensive, and a loop can ask for one on each trip */ +bool bpf_stream_has_room(struct bpf_prog *prog, enum bpf_stream_id stream_id) +{ + struct bpf_stream *stream = bpf_stream_get(stream_id, prog->aux); + + return stream && atomic_read(&stream->capacity) + READ_ONCE(stream->refused) < + BPF_STREAM_MAX_CAPACITY; +} + void bpf_stream_stage_init(struct bpf_stream_stage *ss) { init_llist_head(&ss->log); @@ -531,13 +546,19 @@ int bpf_stream_stage_commit(struct bpf_stream_stage *ss, struct bpf_prog *prog, struct bpf_stream *stream; int ret; + bpf_timed_may_goto_check_time(prog); + stream = bpf_stream_get(stream_id, prog->aux); if (!stream) return -EINVAL; + if (!ss->len) + return 0; ret = bpf_stream_consume_capacity(stream, ss->len); - if (ret) + if (ret) { + WRITE_ONCE(stream->refused, min(ss->len, BPF_STREAM_MAX_CAPACITY / 2)); return ret; + } list = llist_del_all(&ss->log); head = tail = list; diff --git a/kernel/bpf/syscall.c b/kernel/bpf/syscall.c index 60c4d84b9aba6f..91d078bb13d2d8 100644 --- a/kernel/bpf/syscall.c +++ b/kernel/bpf/syscall.c @@ -3025,7 +3025,8 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_at if (is_perfmon_prog_type(type) && !bpf_token_capable(token, CAP_PERFMON)) goto put_token; - multi_func = is_tracing_multi(attr->expected_attach_type); + multi_func = type != BPF_PROG_TYPE_STRUCT_OPS && + is_tracing_multi(attr->expected_attach_type); /* attach_prog_fd/attach_btf_obj_fd can specify fd of either bpf_prog * or btf, we need to check which one it is @@ -3090,6 +3091,7 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_at prog->aux->attach_btf_id = multi_func ? bpf_multi_func_btf_id[0] : attr->attach_btf_id; prog->aux->dst_prog = dst_prog; if (dst_prog) { + prog->aux->saved_dst_ctx_type = resolve_prog_type(dst_prog); prog->aux->saved_dst_prog_type = dst_prog->type; prog->aux->saved_dst_attach_type = dst_prog->expected_attach_type; } @@ -3177,6 +3179,9 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_at if (err < 0) goto free_used_maps; + /* bpf_throw() and faults look for the symbol. The prog can run once it has the id. */ + bpf_prog_kallsyms_add(prog); + err = bpf_prog_alloc_id(prog); if (err) goto free_used_maps; @@ -3195,7 +3200,6 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_at * Also, any failure handling from this point onwards must * be using bpf_prog_put() given the program is exposed. */ - bpf_prog_kallsyms_add(prog); perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_LOAD, 0); bpf_audit_prog(prog, BPF_AUDIT_LOAD); @@ -3846,6 +3850,24 @@ static int bpf_tracing_prog_attach(struct bpf_prog *prog, err = -EINVAL; goto out_unlock; } + /* Where the return can be overridden is checked for the target only */ + if (prog->type == BPF_PROG_TYPE_EXT && + prog->kprobe_override && !tgt_prog->kprobe_override) { + err = -EINVAL; + goto out_unlock; + } + /* bpf_prog_run_save_cb() and bpf_prog_run_clear_cb() look at the target only */ + if (prog->type == BPF_PROG_TYPE_EXT && + (tgt_prog->type == BPF_PROG_TYPE_SOCKET_FILTER || + tgt_prog->type == BPF_PROG_TYPE_CGROUP_SKB || + tgt_prog->type == BPF_PROG_TYPE_LWT_IN || + tgt_prog->type == BPF_PROG_TYPE_LWT_OUT || + tgt_prog->type == BPF_PROG_TYPE_LWT_XMIT || + tgt_prog->type == BPF_PROG_TYPE_LWT_SEG6LOCAL) && + prog->cb_access && !tgt_prog->cb_access) { + 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, @@ -5239,7 +5261,8 @@ static int bpf_prog_get_info_by_fd(struct file *file, struct bpf_insn *insns_sanitized; bool fault; - if (!prog->blinded || bpf_dump_raw_ok(file->f_cred)) { + /* The verifier puts addresses to ld_imm64 and mov insns */ + if (bpf_dump_raw_ok(file->f_cred) || (!prog->blinded && perfmon_capable())) { insns_sanitized = bpf_insn_prepare_dump(prog, file->f_cred); if (!insns_sanitized) return -ENOMEM; @@ -6595,6 +6618,9 @@ static bool syscall_prog_is_valid_access(int off, int size, BPF_CALL_3(bpf_sys_bpf, int, cmd, union bpf_attr *, attr, u32, attr_size) { + if (bpf_in_async_cb()) + return -EPERM; + switch (cmd) { case BPF_MAP_CREATE: case BPF_MAP_DELETE_ELEM: @@ -6684,7 +6710,7 @@ BPF_CALL_1(bpf_sys_close, u32, fd) * This helper is allowed in the following callchain only: * sys_bpf->prog_test_run->bpf_prog->bpf_sys_close */ - return close_fd(fd); + return bpf_in_async_cb() ? -EPERM : close_fd(fd); } static const struct bpf_func_proto bpf_sys_close_proto = { @@ -6704,7 +6730,7 @@ BPF_CALL_4(bpf_kallsyms_lookup_name, const char *, name, int, name_sz, int, flag if (name_sz <= 1 || name[name_sz - 1]) return -EINVAL; - if (!bpf_dump_raw_ok(current_cred())) + if (bpf_in_async_cb() || !bpf_dump_raw_ok(current_cred())) return -EPERM; *res = kallsyms_lookup_name(name); @@ -6725,10 +6751,12 @@ static const struct bpf_func_proto bpf_kallsyms_lookup_name_proto = { static const struct bpf_func_proto * syscall_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog) { + if (!bpf_token_capable(prog->aux->token, CAP_PERFMON)) + return bpf_base_func_proto(func_id, prog); + switch (func_id) { case BPF_FUNC_sys_bpf: - return !bpf_token_capable(prog->aux->token, CAP_PERFMON) - ? NULL : &bpf_sys_bpf_proto; + return &bpf_sys_bpf_proto; case BPF_FUNC_btf_find_by_name_kind: return &bpf_btf_find_by_name_kind_proto; case BPF_FUNC_sys_close: diff --git a/kernel/bpf/trampoline.c b/kernel/bpf/trampoline.c index 21d460866dfef8..b0052c7565d84a 100644 --- a/kernel/bpf/trampoline.c +++ b/kernel/bpf/trampoline.c @@ -584,7 +584,7 @@ static void __bpf_tramp_image_put_rcu(struct rcu_head *rcu) im = container_of(rcu, struct bpf_tramp_image, rcu); INIT_WORK(&im->work, __bpf_tramp_image_put_deferred); - schedule_work(&im->work); + queue_work(bpf_prog_free_wq, &im->work); } /* callback, fexit step 2. Called after percpu_ref_kill confirms. */ diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c index 5e4700fda66b9f..85fec1f389277c 100644 --- a/kernel/bpf/verifier.c +++ b/kernel/bpf/verifier.c @@ -32,6 +32,7 @@ #include #include #include +#include #include #include #include @@ -3825,7 +3826,7 @@ static bool __is_pointer_value(bool allow_ptr_leaks, if (allow_ptr_leaks) return false; - return is_pointer_regtype(reg->type); + return reg->type != SCALAR_VALUE; } static void assign_scalar_id_before_mov(struct bpf_verifier_env *env, @@ -6217,6 +6218,7 @@ static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) u64 top_smax_value, top_smin_value; u64 num_bits = size * 8; s64 limit = 1LL << (num_bits - 1); + struct cnum32 r32; /* If every value fits the signed N-bit range sign extension is a noop. */ if (reg_smin(reg) >= -limit && reg_smax(reg) < limit) @@ -6271,7 +6273,13 @@ static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) } out: + r32 = reg->r32; set_sext64_default_val(reg, size); + /* the low 32 bits fit, they do not change */ + if (cnum32_smin(r32) >= -limit && cnum32_smax(r32) < limit) { + reg->r32 = r32; + reg->r64 = cnum64_from_srange(cnum32_smin(r32), cnum32_smax(r32)); + } } static void set_sext32_default_val(struct bpf_reg_state *reg, int size) @@ -6379,13 +6387,13 @@ int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; break; case sizeof(u16): - *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; + *val = is_ldsx ? (s64)get_unaligned((s16 *)ptr) : (u64)get_unaligned((u16 *)ptr); break; case sizeof(u32): - *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; + *val = is_ldsx ? (s64)get_unaligned((s32 *)ptr) : (u64)get_unaligned((u32 *)ptr); break; case sizeof(u64): - *val = *(u64 *)ptr; + *val = get_unaligned((u64 *)ptr); break; default: return -EINVAL; @@ -7963,6 +7971,10 @@ static int check_helper_mem_access(struct bpf_verifier_env *env, struct bpf_reg_ return check_mem_region_access(env, reg, argno, 0, access_size, reg->map_ptr->key_size, false); case PTR_TO_MAP_VALUE: + if (reg->map_ptr->map_type == BPF_MAP_TYPE_INSN_ARRAY && !env->allow_ptr_leaks) { + verbose(env, "%s leaks addr from insn_array\n", reg_arg_name(env, argno)); + return -EACCES; + } if (check_map_access_type(env, reg, 0, access_size, access_type)) return -EACCES; return check_map_access(env, reg, argno, 0, access_size, @@ -10526,6 +10538,7 @@ static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) { enum bpf_attach_type eatype = env->prog->expected_attach_type; enum bpf_prog_type type = resolve_prog_type(env->prog); + const char *afname = env->prog->aux->attach_func_name; if (func_id != BPF_FUNC_map_update_elem && func_id != BPF_FUNC_map_delete_elem) @@ -10536,7 +10549,8 @@ static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) */ switch (type) { case BPF_PROG_TYPE_TRACING: - if (eatype == BPF_TRACE_ITER) + if (eatype == BPF_TRACE_ITER && + !strcmp(afname + strlen(BPF_ITER_FUNC_PREFIX), "sockmap")) return true; break; case BPF_PROG_TYPE_SOCK_OPS: @@ -11480,6 +11494,12 @@ static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *ins struct bpf_verifier_state *async_cb; /* there is no real recursion here. timer and workqueue callbacks are async */ + /* there is no cgroup to take the storage from */ + if (env->prog->aux->cgroup_storage[BPF_CGROUP_STORAGE_SHARED] || + env->prog->aux->cgroup_storage[BPF_CGROUP_STORAGE_PERCPU]) { + verbose(env, "async callback in a program with cgroup storage\n"); + return -EINVAL; + } env->subprog_info[subprog].is_async_cb = true; async_cb = push_async_cb(env, env->subprog_info[subprog].start, insn_idx, subprog, @@ -12303,6 +12323,10 @@ static int do_refine_retval_range(struct bpf_verifier_env *env, env->prog->expected_attach_type == BPF_CGROUP_GETSOCKOPT) break; + /* It is what the previous struct bpf_tcp_ops returned, any int */ + if (prog_type == BPF_PROG_TYPE_STRUCT_OPS) + break; + if (prog_type == BPF_PROG_TYPE_LSM && env->prog->expected_attach_type == BPF_LSM_CGROUP) { if (!env->prog->aux->attach_func_proto->type) @@ -15532,12 +15556,10 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, for (i = 0; i < CALLER_SAVED_REGS; i++) bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); + /* The kfunc returns int, the upper half of r0 is not known */ mark_reg_unknown(env, regs, BPF_REG_0); - err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1); - if (err) { - verbose(env, "failed to mark s32 range for retval in forked state for lock\n"); - return err; - } + reg_set_srange32(®s[BPF_REG_0], -MAX_ERRNO, -1); + reg_bounds_sync(®s[BPF_REG_0]); } else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) { verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n"); return -EFAULT; @@ -15840,6 +15862,12 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, return err; } else if (btf_type_is_void(ptr_type)) { /* kfunc returning 'void *' is equivalent to returning scalar */ + if (!env->allow_ptr_leaks) { + verbose(env, + "%s is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", + func_name); + return -EPERM; + } mark_reg_unknown(env, regs, BPF_REG_0); } else if (!__btf_type_is_struct(ptr_type)) { if (!meta.ret_mem.found) { @@ -19587,7 +19615,8 @@ static int check_return_code(struct bpf_verifier_env *env, int regno, const char * matches the operator's return type and is in its unmodified * form. A scalar zero (i.e., a null pointer) is also allowed. */ - reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL; + reg_type = base_type(reg->type) == PTR_TO_BTF_ID ? + btf_type_by_id(reg->btf, reg->btf_id) : NULL; ret_type = btf_type_resolve_ptr(prog->aux->attach_btf, prog->aux->attach_func_proto->type, NULL); @@ -19931,7 +19960,11 @@ static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env, env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1; else subprog->keep_fastcall_stack = 1; - subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off); + /* + * The upper end of the longest pattern: no slot of a pattern is above it. Code that never + * runs may have a pattern that ends above the frame pointer. + */ + subprog->fastcall_stack_off = max(subprog->fastcall_stack_off, min_t(s16, off, 0)); } static int mark_fastcall_patterns(struct bpf_verifier_env *env) @@ -19942,6 +19975,7 @@ static int mark_fastcall_patterns(struct bpf_verifier_env *env) int s, i; for (s = 0; s < env->subprog_cnt; ++s, ++subprog) { + subprog->fastcall_stack_off = S16_MIN; /* find lowest stack spill offset used in this subprog */ lowest_off = 0; for (i = subprog->start; i < (subprog + 1)->start; ++i) { @@ -20622,13 +20656,13 @@ static int do_check(struct bpf_verifier_env *env) for (;;) { struct bpf_insn *insn; struct bpf_insn_aux_data *insn_aux; - int err; + int err, ctx_field_size; + bool nospec_result; if (signal_pending(current)) return -EAGAIN; - if (need_resched()) - cond_resched(); + cond_resched_tasks_rcu_qs(); /* reset current history entry on each new instruction */ env->cur_hist_ent = NULL; @@ -20776,6 +20810,8 @@ static int do_check(struct bpf_verifier_env *env) if (state->speculative && insn_aux->nospec) goto process_bpf_exit; + nospec_result = insn_aux->nospec_result; + ctx_field_size = insn_aux->ctx_field_size; err = do_check_insn(env, &do_print_state); if (error_recoverable_with_nospec(err) && state->speculative) { /* Prevent this speculative path from ever reaching the @@ -20786,6 +20822,8 @@ static int do_check(struct bpf_verifier_env *env) * markings for alu sanitization. */ insn_aux->alu_state = 0; + insn_aux->nospec_result = nospec_result; + insn_aux->ctx_field_size = ctx_field_size; goto process_bpf_exit; } else if (err < 0) { return err; @@ -20968,6 +21006,12 @@ static int __check_pseudo_btf_id(struct bpf_verifier_env *env, } } + if (!percpu && !env->allow_ptr_leaks) { + verbose(env, "access to '%s' is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", + sym_name); + return -EPERM; + } + type = t->type; t = btf_type_skip_modifiers(btf, type, NULL); if (percpu) { @@ -21013,6 +21057,11 @@ static int check_pseudo_btf_id(struct bpf_verifier_env *env, verbose(env, "invalid module BTF object FD specified.\n"); return -EINVAL; } + if (!btf_is_kernel(btf)) { + verbose(env, "BTF fd for ksym is not a kernel BTF\n"); + btf_put(btf); + return -EINVAL; + } } else { if (!btf_vmlinux) { verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); @@ -22665,6 +22714,7 @@ int bpf_check_attach_target(struct bpf_verifier_log *log, } if (tgt_prog) { struct bpf_prog_aux *aux = tgt_prog->aux; + enum bpf_cgroup_storage_type stype; bool tgt_changes_pkt_data; bool tgt_might_sleep; bool tgt_can_unwind; @@ -22719,6 +22769,16 @@ int bpf_check_attach_target(struct bpf_verifier_log *log, "Extension programs should be JITed\n"); return -EINVAL; } + /* bpf_get_local_storage() returns the storage of the target */ + for_each_cgroup_storage_type(stype) { + struct bpf_map *storage = prog->aux->cgroup_storage[stype]; + + if (storage && storage != aux->cgroup_storage[stype]) { + bpf_log(log, + "Extension program has another cgroup storage than original\n"); + return -EINVAL; + } + } /* * How much of the buffer of the tracepoint is used * is checked for the program that is attached to it. @@ -22783,16 +22843,14 @@ int bpf_check_attach_target(struct bpf_verifier_log *log, bpf_log(log, "Cannot recursively attach\n"); return -EINVAL; } - if (tgt_prog->type == BPF_PROG_TYPE_TRACING && - prog_extension && - (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || - tgt_prog->expected_attach_type == BPF_TRACE_FEXIT || - tgt_prog->expected_attach_type == BPF_TRACE_FENTRY_MULTI || - tgt_prog->expected_attach_type == BPF_TRACE_FEXIT_MULTI || - tgt_prog->expected_attach_type == BPF_TRACE_FSESSION || - tgt_prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) { - /* Program extensions can extend all program types - * except fentry/fexit. The reason is the following. + if (prog_extension && + (tgt_prog->type == BPF_PROG_TYPE_TRACING || + tgt_prog->type == BPF_PROG_TYPE_LSM || + tgt_prog->type == BPF_PROG_TYPE_STRUCT_OPS)) { + /* + * These types are checked against the BTF of their hook, + * and an extension has the BTF of its target instead. + * There is one more reason for fentry/fexit. * The fentry/fexit programs are used for performance * analysis, stats and can be attached to any program * type. When extension program is replacing XDP function @@ -22805,7 +22863,7 @@ int bpf_check_attach_target(struct bpf_verifier_log *log, * beyond reasonable stack size. Hence extending fentry * is not allowed. */ - bpf_log(log, "Cannot extend fentry/fexit/fsession\n"); + bpf_log(log, "Cannot extend tracing, LSM and struct_ops programs\n"); return -EINVAL; } } else { @@ -23153,10 +23211,13 @@ static int check_attach_btf_id(struct bpf_verifier_env *env) prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; } - if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { + /* An extension has expected_attach_type of its target, it can be any value */ + if (prog->type != BPF_PROG_TYPE_EXT && + prog->expected_attach_type == BPF_TRACE_RAW_TP) { prog->aux->attach_btf_trace = true; return 0; - } else if (prog->expected_attach_type == BPF_TRACE_ITER) { + } else if (prog->type != BPF_PROG_TYPE_EXT && + prog->expected_attach_type == BPF_TRACE_ITER) { return bpf_iter_prog_supported(prog); } @@ -23828,6 +23889,13 @@ static int bpf_prog_verify_signature(struct bpf_verifier_env *env, err = -EPERM; goto out; } + /* The freeze is not final for it, see bpf_map_mmap() */ + if ((map->map_flags & BPF_F_MMAPABLE) && !(map->map_flags & BPF_F_RDONLY_PROG)) { + verbose(env, "signed program metadata map '%s' must not be mmapable\n", + map->name); + err = -EPERM; + goto out; + } data_sz += map->value_size; } if (bpf_dynptr_check_size(data_sz)) { diff --git a/kernel/cgroup/rstat.c b/kernel/cgroup/rstat.c index de816a43db9f0a..d72fe721cea057 100644 --- a/kernel/cgroup/rstat.c +++ b/kernel/cgroup/rstat.c @@ -131,6 +131,7 @@ __bpf_kfunc void css_rstat_updated(struct cgroup_subsys_state *css, int cpu) if (unlikely(cpu < 0 || cpu >= nr_cpu_ids || !cpu_possible(cpu))) return; + guard(preempt)(); __css_rstat_updated(css, cpu); } diff --git a/kernel/dma/coherent.c b/kernel/dma/coherent.c index 4d0266893bcc99..ac62b6bd3d0d0e 100644 --- a/kernel/dma/coherent.c +++ b/kernel/dma/coherent.c @@ -7,6 +7,7 @@ #include #include #include +#include #include #include @@ -335,10 +336,18 @@ static phys_addr_t dma_reserved_default_memory_base __initdata; static phys_addr_t dma_reserved_default_memory_size __initdata; #endif +static DEFINE_MUTEX(rmem_dma_mutex); + static int rmem_dma_device_init(struct reserved_mem *rmem, struct device *dev) { - struct dma_coherent_mem *mem = rmem->priv; + struct dma_coherent_mem *mem; + /* + * Multiple devices can share the same pool and may be probed + * concurrently, so serialize the initialization of rmem->priv. + */ + guard(mutex)(&rmem_dma_mutex); + mem = rmem->priv; if (!mem) { mem = dma_init_coherent_memory(rmem->base, rmem->base, rmem->size, true); diff --git a/kernel/dma/pool.c b/kernel/dma/pool.c index 00f422a1e89666..5e8cf12e822292 100644 --- a/kernel/dma/pool.c +++ b/kernel/dma/pool.c @@ -106,6 +106,22 @@ static int atomic_pool_expand(struct dma_gen_pool *dma_pool, size_t pool_size, if (!page) goto out; + /* + * Memory in the atomic DMA pools must be unencrypted, the pools do not + * shrink so no re-encryption occurs in dma_direct_free(). + */ + if (dma_pool->cc_shared) { + ret = set_memory_decrypted((unsigned long)page_to_virt(page), + 1 << order); + /* + * On failure the encryption state of the pages is unknown, + * so they must not be returned to the page allocator or CMA. + * Leak them intentionally. + */ + if (ret) + goto out; + } + arch_dma_prep_coherent(page, pool_size); #ifdef CONFIG_DMA_DIRECT_REMAP @@ -116,43 +132,32 @@ static int atomic_pool_expand(struct dma_gen_pool *dma_pool, size_t pool_size, addr = dma_common_contiguous_remap(page, pool_size, prot, __builtin_return_address(0)); - if (!addr) - goto free_page; + if (!addr) { + ret = -ENOMEM; + goto encrypt_pages; + } #else addr = page_to_virt(page); #endif - /* - * Memory in the atomic DMA pools must be unencrypted, the pools do not - * shrink so no re-encryption occurs in dma_direct_free(). - */ - if (dma_pool->cc_shared) { - ret = set_memory_decrypted((unsigned long)page_to_virt(page), - 1 << order); - if (ret) { - leak_pages = true; - goto remove_mapping; - } - } - ret = gen_pool_add_virt(dma_pool->pool, (unsigned long)addr, page_to_phys(page), pool_size, NUMA_NO_NODE); if (ret) - goto encrypt_mapping; + goto remove_mapping; dma_atomic_pool_size_add(gfp, pool_size); return 0; -encrypt_mapping: - if (dma_pool->cc_shared && - set_memory_encrypted((unsigned long)page_to_virt(page), 1 << order)) - leak_pages = true; - remove_mapping: #ifdef CONFIG_DMA_DIRECT_REMAP dma_common_free_remap(addr, pool_size); -free_page: +encrypt_pages: #endif - if (!leak_pages) + if (dma_pool->cc_shared && + set_memory_encrypted((unsigned long)page_to_virt(page), 1 << order)) + leak_pages = true; + + if (!leak_pages && + !dma_release_from_contiguous(NULL, page, 1 << order)) __free_pages(page, order); out: return ret; diff --git a/kernel/dma/swiotlb.c b/kernel/dma/swiotlb.c index 2c57b49ac7c063..786954bc5e6a65 100644 --- a/kernel/dma/swiotlb.c +++ b/kernel/dma/swiotlb.c @@ -35,6 +35,7 @@ #include #include #include +#include #include #include #include @@ -664,6 +665,17 @@ void __init swiotlb_exit(void) return; pr_info("tearing down default memory pool\n"); +#ifdef CONFIG_SWIOTLB_DYNAMIC + io_tlb_default_mem.can_grow = false; + cancel_work_sync(&io_tlb_default_mem.dyn_alloc); + spin_lock(&io_tlb_default_mem.lock); + list_del_rcu(&mem->node); + io_tlb_default_mem.nslabs -= mem->nslabs; + spin_unlock(&io_tlb_default_mem.lock); + synchronize_rcu(); +#else + io_tlb_default_mem.nslabs = 0; +#endif tbl_vaddr = (unsigned long)phys_to_virt(mem->start); tbl_size = PAGE_ALIGN(mem->end - mem->start); slots_size = PAGE_ALIGN(array_size(sizeof(*mem->slots), mem->nslabs)); @@ -1986,10 +1998,12 @@ void swiotlb_free_from_pool(struct device *dev, swiotlb_release_slots(dev, tlb_addr, pool); } +static DEFINE_MUTEX(rmem_swiotlb_mutex); + static int rmem_swiotlb_device_init(struct reserved_mem *rmem, struct device *dev) { - struct io_tlb_mem *mem = rmem->priv; + struct io_tlb_mem *mem; unsigned long nslabs = rmem->size >> IO_TLB_SHIFT; /* Set Per-device io tlb area to one */ @@ -2003,10 +2017,25 @@ static int rmem_swiotlb_device_init(struct reserved_mem *rmem, /* * Since multiple devices can share the same pool, the private data, * io_tlb_mem struct, will be initialized by the first device attached - * to it. + * to it. Serialize this, as devices may be probed concurrently. */ + guard(mutex)(&rmem_swiotlb_mutex); + mem = rmem->priv; if (!mem) { struct io_tlb_pool *pool; + unsigned long aligned_nslabs = ALIGN_DOWN(nslabs, IO_TLB_SEGSIZE); + + if (aligned_nslabs != nslabs) { + dev_warn(dev, "Restricted DMA pool size %zu is not a multiple of %lu, rounding down to %lu bytes\n", + (size_t)rmem->size, + (unsigned long)IO_TLB_SEGSIZE << IO_TLB_SHIFT, + aligned_nslabs << IO_TLB_SHIFT); + nslabs = aligned_nslabs; + } + if (!nslabs) { + dev_err(dev, "Restricted DMA pool is too small\n"); + return -EINVAL; + } mem = kzalloc_obj(*mem); if (!mem) @@ -2034,7 +2063,7 @@ static int rmem_swiotlb_device_init(struct reserved_mem *rmem, mem->cc_shared = true; ret = set_memory_decrypted((unsigned long)phys_to_virt(rmem->base), - rmem->size >> PAGE_SHIFT); + (nslabs << IO_TLB_SHIFT) >> PAGE_SHIFT); if (ret) { dev_err(dev, "Failed to decrypt restricted DMA pool\n"); kfree(pool->areas); diff --git a/kernel/events/core.c b/kernel/events/core.c index e870f12c3ad812..4ab3919ac78e90 100644 --- a/kernel/events/core.c +++ b/kernel/events/core.c @@ -1366,6 +1366,12 @@ void perf_pmu_enable(struct pmu *pmu) pmu->pmu_enable(pmu); } +bool perf_pmu_enabled(struct pmu *pmu) +{ + int *count = &this_cpc(pmu)->pmu_disable_count; + return *count == 0; +} + static void perf_assert_pmu_disabled(struct pmu *pmu) { int *count = &this_cpc(pmu)->pmu_disable_count; @@ -7776,9 +7782,15 @@ static void perf_pending_task(struct callback_head *head) rctx = perf_swevent_get_recursion_context(); if (event->pending_work) { - event->pending_work = 0; perf_sigtrap(event); local_dec(&event->ctx->nr_no_switch_fast); + /* + * event->pending_work also acts as a 'lock' for + * event->{pending_addr, orig_type, attr.sig_data}. As such we + * must clear after perf_sigtrap is complete. + */ + barrier(); + event->pending_work = 0; } put_event(event); @@ -10747,8 +10759,15 @@ void perf_report_aux_output_id(struct perf_event *event, u64 hw_id) } EXPORT_SYMBOL_GPL(perf_report_aux_output_id); +/* + * @period is the period of the interval that just ended. PMU drivers + * re-arm the counter before calling perf_event_overflow(), which sets + * hwc->last_period to the period of the next interval, so the overflow + * path passes the sample's period instead. + */ static int -__perf_event_account_interrupt(struct perf_event *event, int throttle) +__perf_event_account_interrupt(struct perf_event *event, int throttle, + u64 period) { struct hw_perf_event *hwc = &event->hw; int ret = 0; @@ -10776,7 +10795,7 @@ __perf_event_account_interrupt(struct perf_event *event, int throttle) hwc->freq_time_stamp = now; if (delta > 0 && delta < 2*TICK_NSEC) - perf_adjust_period(event, delta, hwc->last_period, true); + perf_adjust_period(event, delta, period, true); } return ret; @@ -10784,7 +10803,7 @@ __perf_event_account_interrupt(struct perf_event *event, int throttle) int perf_event_account_interrupt(struct perf_event *event) { - return __perf_event_account_interrupt(event, 1); + return __perf_event_account_interrupt(event, 1, event->hw.last_period); } static inline bool sample_is_allowed(struct perf_event *event, struct pt_regs *regs) @@ -10819,6 +10838,9 @@ static int bpf_overflow_handler(struct perf_event *event, prog = READ_ONCE(event->prog); if (prog) { perf_prepare_sample(data, event, regs); + /* bpf_perf_event_data::addr is readable without PERF_SAMPLE_ADDR */ + if (!(data->sample_flags & PERF_SAMPLE_ADDR)) + data->addr = 0; ret = bpf_prog_run(prog, &ctx); } rcu_read_unlock(); @@ -10912,7 +10934,7 @@ static int __perf_event_overflow(struct perf_event *event, if (unlikely(!is_sampling_event(event))) return 0; - ret = __perf_event_account_interrupt(event, throttle); + ret = __perf_event_account_interrupt(event, throttle, data->period); if (event->attr.aux_pause) perf_event_aux_pause(event->aux_event, true); @@ -10950,16 +10972,22 @@ static int __perf_event_overflow(struct perf_event *event, notify_mode = in_nmi() ? TWA_NMI_CURRENT : TWA_RESUME; - if (!event->pending_work && - !task_work_add(current, &event->pending_task, notify_mode)) { - event->pending_work = pending_id; - local_inc(&event->ctx->nr_no_switch_fast); - WARN_ON_ONCE(!atomic_long_inc_not_zero(&event->refcount)); - - event->pending_addr = 0; - if (valid_sample && (data->sample_flags & PERF_SAMPLE_ADDR)) - event->pending_addr = data->addr; - + /* + * Software events can nest and attempt this recursively; + * claim the pending_work before task_work_add() recurses. + */ + if (cmpxchg_local(&event->pending_work, 0, 1) == 0) { + if (!task_work_add(event->ctx->task, &event->pending_task, notify_mode)) { + event->pending_work = pending_id; + local_inc(&event->ctx->nr_no_switch_fast); + WARN_ON_ONCE(!atomic_long_inc_not_zero(&event->refcount)); + + event->pending_addr = 0; + if (valid_sample && (data->sample_flags & PERF_SAMPLE_ADDR)) + event->pending_addr = data->addr; + } else { + event->pending_work = 0; + } } else if (event->attr.exclude_kernel && valid_sample) { /* * Should not be able to return to user space without @@ -11142,9 +11170,11 @@ int perf_exclude_event(struct perf_event *event, struct pt_regs *regs) static int perf_swevent_match(struct perf_event *event, enum perf_type_id type, u32 event_id, - struct perf_sample_data *data, struct pt_regs *regs) { + if (!perf_pmu_enabled(event->pmu)) + return 0; + if (event->attr.type != type) return 0; @@ -11207,11 +11237,10 @@ find_swevent_head(struct swevent_htable *swhash, struct perf_event *event) } static void do_perf_sw_event(enum perf_type_id type, u32 event_id, - u64 nr, - struct perf_sample_data *data, - struct pt_regs *regs) + u64 nr, struct pt_regs *regs, u64 addr) { struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable); + struct perf_sample_data data; struct perf_event *event; struct hlist_head *head; @@ -11221,8 +11250,10 @@ static void do_perf_sw_event(enum perf_type_id type, u32 event_id, goto end; hlist_for_each_entry_rcu(event, head, hlist_entry) { - if (perf_swevent_match(event, type, event_id, data, regs)) - perf_swevent_event(event, nr, data, regs); + if (perf_swevent_match(event, type, event_id, regs)) { + perf_sample_data_init(&data, addr, 0); + perf_swevent_event(event, nr, &data, regs); + } } end: rcu_read_unlock(); @@ -11243,13 +11274,10 @@ void perf_swevent_put_recursion_context(int rctx) void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr) { - struct perf_sample_data data; - if (WARN_ON_ONCE(!regs)) return; - perf_sample_data_init(&data, addr, 0); - do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs); + do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, regs, addr); } void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr) @@ -11525,6 +11553,9 @@ static int perf_tp_event_match(struct perf_event *event, struct perf_raw_record *raw, struct pt_regs *regs) { + if (!perf_pmu_enabled(event->pmu)) + return 0; + if (event->hw.state & PERF_HES_STOPPED) return 0; /* @@ -12968,6 +12999,7 @@ static void perf_pmu_free(struct pmu *pmu) struct perf_cpu_pmu_context *cpc; cpc = *per_cpu_ptr(pmu->cpu_pmu_context, cpu); + hrtimer_cancel(&cpc->hrtimer); if (!cpc) continue; if (cpc->epc.embedded) { @@ -13011,12 +13043,6 @@ int perf_pmu_register(struct pmu *_pmu, const char *name, int type) pmu->type = pmu_type.id; atomic_set(&pmu->exclusive_cnt, 0); - if (pmu_bus_running && !pmu->dev) { - int ret = pmu_dev_alloc(pmu); - if (ret) - return ret; - } - pmu->cpu_pmu_context = alloc_percpu(struct perf_cpu_pmu_context *); if (!pmu->cpu_pmu_context) return -ENOMEM; @@ -13035,6 +13061,12 @@ int perf_pmu_register(struct pmu *_pmu, const char *name, int type) __perf_mux_hrtimer_init(cpc, cpu); } + if (pmu_bus_running && !pmu->dev) { + int ret = pmu_dev_alloc(pmu); + if (ret) + return ret; + } + if (!pmu->start_txn) { if (pmu->pmu_enable) { /* @@ -14419,15 +14451,22 @@ SYSCALL_DEFINE5(perf_event_open, mutex_unlock(&ctx->mutex); + /* + * Publish the event on the owner's list before dropping + * exec_update_lock. Otherwise a concurrent exec() can run + * perf_event_remove_on_exec() and clear event->owner before + * owner_entry is linked, leaving an ownerless event on + * current->perf_event_list that perf_release() won't unlink. + */ + mutex_lock(¤t->perf_event_mutex); + list_add_tail(&event->owner_entry, ¤t->perf_event_list); + mutex_unlock(¤t->perf_event_mutex); + if (task) { up_read(&task->signal->exec_update_lock); put_task_struct(task); } - mutex_lock(¤t->perf_event_mutex); - list_add_tail(&event->owner_entry, ¤t->perf_event_list); - mutex_unlock(¤t->perf_event_mutex); - /* * File reference in group guarantees that group_leader has been * kept alive until we place the new event on the sibling_list. diff --git a/kernel/events/uprobes.c b/kernel/events/uprobes.c index caf444762a274b..c47b1ee266d515 100644 --- a/kernel/events/uprobes.c +++ b/kernel/events/uprobes.c @@ -2703,6 +2703,15 @@ void __weak arch_uprobe_optimize(struct arch_uprobe *auprobe, unsigned long vadd { } +/* + * Can a bpf prog write these bytes of pt_regs? An arch opts in and lists the + * registers that ptrace can set to any value. + */ +bool __weak arch_uprobe_regs_writable(int off, int size) +{ + return false; +} + /* * Run handler and ask thread to singlestep. * Ensure all non-fatal signals cannot interrupt thread while it singlesteps. diff --git a/kernel/fork.c b/kernel/fork.c index 5efceb8d58a78b..d55a7d21a8fb23 100644 --- a/kernel/fork.c +++ b/kernel/fork.c @@ -2328,9 +2328,12 @@ __latent_entropy struct task_struct *copy_process( retval = copy_mm(clone_flags, p); if (retval) goto bad_fork_cleanup_signal; - retval = copy_namespaces(clone_flags, p); + retval = user_events_fork(p, clone_flags); if (retval) goto bad_fork_cleanup_mm; + retval = copy_namespaces(clone_flags, p); + if (retval) + goto bad_fork_cleanup_user_events; retval = copy_io(clone_flags, p); if (retval) goto bad_fork_cleanup_namespaces; @@ -2598,7 +2601,6 @@ __latent_entropy struct task_struct *copy_process( trace_task_newtask(p, clone_flags); uprobe_copy_process(p, clone_flags); - user_events_fork(p, clone_flags); copy_oom_score_adj(clone_flags, p); @@ -2625,11 +2627,19 @@ __latent_entropy struct task_struct *copy_process( exit_io_context(p); bad_fork_cleanup_namespaces: exit_nsproxy_namespaces(p); +bad_fork_cleanup_user_events: + user_events_exit(p); bad_fork_cleanup_mm: sched_cache_fork_cleanup(p); if (p->mm) { - mm_clear_owner(p->mm, p); - mmput(p->mm); + struct mm_struct *mm = p->mm; + + /* Perf events and BPF programs can still reach p. */ + task_lock(p); + p->mm = NULL; + task_unlock(p); + mm_clear_owner(mm, p); + mmput(mm); } bad_fork_cleanup_signal: if (!(clone_flags & CLONE_THREAD)) @@ -2663,6 +2673,11 @@ __latent_entropy struct task_struct *copy_process( exit_cred_namespaces(p); exit_creds(p); bad_fork_free: + /* + * If set, p->mm points at the parent's mm without a reference. Nobody + * can access it concurrently anymore, but prevent later access. + */ + p->mm = NULL; WRITE_ONCE(p->__state, TASK_DEAD); exit_task_stack_account(p); put_task_stack(p); diff --git a/kernel/liveupdate/kexec_handover_debugfs.c b/kernel/liveupdate/kexec_handover_debugfs.c index 7d74477da0b799..3a91c47ad7a6d1 100644 --- a/kernel/liveupdate/kexec_handover_debugfs.c +++ b/kernel/liveupdate/kexec_handover_debugfs.c @@ -10,7 +10,6 @@ #define pr_fmt(fmt) "KHO: " fmt #include -#include #include #include #include @@ -97,8 +96,8 @@ DEFINE_SHOW_ATTRIBUTE(bootmem_len); __init void kho_in_debugfs_init(struct kho_debugfs *dbg, const void *fdt) { - struct dentry *dir, *sub_fdt_dir; - int err, child; + struct dentry *dir; + int err; INIT_LIST_HEAD(&dbg->fdt_list); @@ -108,54 +107,12 @@ __init void kho_in_debugfs_init(struct kho_debugfs *dbg, const void *fdt) goto err_out; } - sub_fdt_dir = debugfs_create_dir("sub_fdts", dir); - if (IS_ERR(sub_fdt_dir)) { - err = PTR_ERR(sub_fdt_dir); - goto err_rmdir; - } - err = __kho_debugfs_blob_add(&dbg->fdt_list, dir, "fdt", fdt, fdt_totalsize(fdt)); if (err) goto err_rmdir; - fdt_for_each_subnode(child, fdt, 0) { - int len = 0; - const char *name = fdt_get_name(fdt, child, NULL); - const u64 *blob_phys; - const u64 *blob_size; - void *blob; - - blob_phys = fdt_getprop(fdt, child, - KHO_SUB_TREE_PROP_NAME, &len); - if (!blob_phys) - continue; - if (len != sizeof(*blob_phys)) { - pr_warn("node %s prop %s has invalid length: %d\n", - name, KHO_SUB_TREE_PROP_NAME, len); - continue; - } - - blob_size = fdt_getprop(fdt, child, - KHO_SUB_TREE_SIZE_PROP_NAME, &len); - if (!blob_size || len != sizeof(*blob_size)) { - pr_warn("node %s missing or invalid %s property\n", - name, KHO_SUB_TREE_SIZE_PROP_NAME); - continue; - } - - blob = phys_to_virt(*blob_phys); - err = __kho_debugfs_blob_add(&dbg->fdt_list, sub_fdt_dir, name, - blob, *blob_size); - if (err) { - pr_warn("failed to add blob %s to debugfs: %pe\n", - name, ERR_PTR(err)); - continue; - } - } - dbg->dir = dir; - dbg->sub_fdt_dir = sub_fdt_dir; return; err_rmdir: diff --git a/kernel/rcu/tasks.h b/kernel/rcu/tasks.h index fcac7361ec51ec..743f777b4c18fe 100644 --- a/kernel/rcu/tasks.h +++ b/kernel/rcu/tasks.h @@ -178,8 +178,6 @@ static int rcu_task_contend_lim __read_mostly = 100; module_param(rcu_task_contend_lim, int, 0444); static int rcu_task_collapse_lim __read_mostly = 10; module_param(rcu_task_collapse_lim, int, 0444); -static bool rcu_task_collapse_debug __read_mostly; -module_param(rcu_task_collapse_debug, bool, 0644); static int rcu_task_lazy_lim __read_mostly = 32; module_param(rcu_task_lazy_lim, int, 0444); @@ -392,8 +390,7 @@ static void call_rcu_tasks_generic(struct rcu_head *rhp, rcu_callback_t func, WRITE_ONCE(rtp->percpu_enqueue_shift, 0); WRITE_ONCE(rtp->percpu_dequeue_lim, rcu_task_cpu_ids); smp_store_release(&rtp->percpu_enqueue_lim, rcu_task_cpu_ids); - if (data_race(rcu_task_collapse_debug)) - pr_info("Switching %s to per-CPU callback queuing.\n", rtp->name); + pr_debug("Switching %s to per-CPU callback queuing.\n", rtp->name); } raw_spin_unlock_irqrestore(&rtp->cbs_gbl_lock, flags); } @@ -514,9 +511,7 @@ static int rcu_tasks_need_gpcb(struct rcu_tasks *rtp) smp_store_release(&rtp->percpu_enqueue_lim, 1); rtp->percpu_dequeue_gpseq = get_state_synchronize_rcu(); gpdone = false; - if (data_race(rcu_task_collapse_debug)) - pr_info("Starting switch %s to CPU-0 callback queuing.\n", - rtp->name); + pr_debug("Starting switch %s to CPU-0 callback queuing.\n", rtp->name); } raw_spin_unlock_irqrestore(&rtp->cbs_gbl_lock, flags); } @@ -524,9 +519,7 @@ static int rcu_tasks_need_gpcb(struct rcu_tasks *rtp) raw_spin_lock_irqsave(&rtp->cbs_gbl_lock, flags); if (rtp->percpu_enqueue_lim < rtp->percpu_dequeue_lim) { WRITE_ONCE(rtp->percpu_dequeue_lim, 1); - if (data_race(rcu_task_collapse_debug)) - pr_info("Completing switch %s to CPU-0 callback queuing.\n", - rtp->name); + pr_debug("Completing switch %s to CPU-0 callback queuing.\n", rtp->name); } if (rtp->percpu_dequeue_lim == 1) { for (cpu = rtp->percpu_dequeue_lim; cpu < rcu_task_cpu_ids; cpu++) { @@ -711,8 +704,6 @@ static void __init rcu_tasks_bootup_oddness(void) pr_info("\tTasks-RCU CPU stall info multiplier clamped to %d (rcu_task_stall_info_mult).\n", rtsimc); rcu_task_stall_info_mult = rtsimc; } - if (rcu_task_collapse_debug) - pr_info("\tTasks-RCU callback contend/collapse debug enabled.\n"); #endif /* #ifdef CONFIG_TASKS_RCU */ #ifdef CONFIG_TASKS_RCU pr_info("\tTrampoline variant of Tasks RCU enabled.\n"); diff --git a/kernel/rcu/tree_nocb.h b/kernel/rcu/tree_nocb.h index b6cfee4e503997..8448a7c578e84c 100644 --- a/kernel/rcu/tree_nocb.h +++ b/kernel/rcu/tree_nocb.h @@ -1618,6 +1618,7 @@ static void show_rcu_nocb_state(struct rcu_data *rdp) struct rcu_segcblist *rsclp = &rdp->cblist; bool waslocked; bool wassleep; + unsigned long j; if (rdp->nocb_gp_rdp == rdp) show_rcu_nocb_gp_state(rdp); @@ -1639,6 +1640,7 @@ static void show_rcu_nocb_state(struct rcu_data *rdp) rsclp->gp_seq[RCU_NEXT_READY_TAIL].exp); sprintf(bufn, "%ld", rsclp->seglen[RCU_NEXT_TAIL]); sprintf(bufb, "%ld", rcu_cblist_n_cbs(&rdp->nocb_bypass)); + j = jiffies; pr_info(" CB %d^%d->%d %c%c%c%c%c F%ld L%ld C%d %c%s%c%s%c%s%c%s%c%s q%ld %c CPU %d%s\n", rdp->cpu, rdp->nocb_gp_rdp->cpu, nocb_next_rdp ? nocb_next_rdp->cpu : -1, @@ -1647,8 +1649,8 @@ static void show_rcu_nocb_state(struct rcu_data *rdp) "lL"[raw_spin_is_locked(&rdp->nocb_lock)], "sS"[!!rdp->nocb_cb_sleep], ".W"[swait_active(&rdp->nocb_cb_wq)], - jiffies - rdp->nocb_bypass_first, - jiffies - rdp->nocb_nobypass_last, + j - rdp->nocb_bypass_first, + j - rdp->nocb_nobypass_last, rdp->nocb_nobypass_count, ".D"[rcu_segcblist_ready_cbs(rsclp)], rcu_segcblist_segempty(rsclp, RCU_DONE_TAIL) ? "" : bufd, diff --git a/kernel/sched/core.c b/kernel/sched/core.c index 5ed660f099a55a..8f5e15af3c4e13 100644 --- a/kernel/sched/core.c +++ b/kernel/sched/core.c @@ -196,12 +196,13 @@ __read_mostly int scheduler_running; DEFINE_STATIC_KEY_FALSE(__sched_core_enabled); /* kernel prio, less is more */ -static inline int __task_prio(const struct task_struct *p) +static inline int __task_prio(const struct task_struct *p, + const struct sched_dl_entity *dl_server) { if (p->sched_class == &stop_sched_class) /* trumps deadline */ return -2; - if (p->dl_server) + if (dl_server) return -1; /* deadline */ if (rt_or_dl_prio(p->prio)) @@ -223,12 +224,19 @@ static inline int __task_prio(const struct task_struct *p) * ge(a,b) := !l(a,b) */ -/* real prio, less is less */ -static inline bool prio_less(const struct task_struct *a, - const struct task_struct *b, bool in_fi) +/* + * real prio, less is less + * + * @a_dl_server and @b_dl_server are the DL servers @a and @b run on + * behalf of, if any. + */ +static inline bool __prio_less(const struct task_struct *a, + const struct sched_dl_entity *a_dl_server, + const struct task_struct *b, + const struct sched_dl_entity *b_dl_server, + bool in_fi) { - - int pa = __task_prio(a), pb = __task_prio(b); + int pa = __task_prio(a, a_dl_server), pb = __task_prio(b, b_dl_server); if (-pa < -pb) return true; @@ -239,18 +247,13 @@ static inline bool prio_less(const struct task_struct *a, if (pa == -1) { /* dl_prio() doesn't work because of stop_class above */ const struct sched_dl_entity *a_dl, *b_dl; - a_dl = &a->dl; /* - * Since,'a' and 'b' can be CFS tasks served by DL server, + * Since 'a' and 'b' can be tasks served by a DL server, * __task_prio() can return -1 (for DL) even for those. In that * case, get to the dl_server's DL entity. */ - if (a->dl_server) - a_dl = a->dl_server; - - b_dl = &b->dl; - if (b->dl_server) - b_dl = b->dl_server; + a_dl = a_dl_server ?: &a->dl; + b_dl = b_dl_server ?: &b->dl; return !dl_time_before(a_dl->deadline, b_dl->deadline); } @@ -266,6 +269,12 @@ static inline bool prio_less(const struct task_struct *a, return false; } +static inline bool prio_less(const struct task_struct *a, + const struct task_struct *b, bool in_fi) +{ + return __prio_less(a, a->dl_server, b, b->dl_server, in_fi); +} + static inline bool __sched_core_less(const struct task_struct *a, const struct task_struct *b) { @@ -328,6 +337,15 @@ void sched_core_dequeue(struct rq *rq, struct task_struct *p, int flags) RB_CLEAR_NODE(&p->core_node); } + /* + * @p left this rq, so it can no longer be the pick a sibling made. + * This also avoids forced idle accounting charging it once it is gone. + */ + if (rq->core_pick == p) { + rq->core_pick = NULL; + rq->core_dl_server = NULL; + } + /* * Migrating the last task off the cpu, with the cpu in forced idle * state. Reschedule to create an accounting edge for forced idle, @@ -338,6 +356,15 @@ void sched_core_dequeue(struct rq *rq, struct task_struct *p, int flags) resched_curr(rq); } +/* + * An idle CPU with an empty runqueue must still call pick_next_task() while + * the core is forced idle. Only that pick ends or re-examines the forced idle. + */ +static inline bool sched_core_idle_needs_pick(struct rq *rq) +{ + return sched_core_enabled(rq) && rq->core->core_forceidle_count; +} + static int sched_task_is_throttled(struct task_struct *p, int cpu) { if (p->sched_class->task_is_throttled) @@ -541,6 +568,7 @@ void sched_core_put(void) static inline void sched_core_enqueue(struct rq *rq, struct task_struct *p) { } static inline void sched_core_dequeue(struct rq *rq, struct task_struct *p, int flags) { } +static inline bool sched_core_idle_needs_pick(struct rq *rq) { return false; } #endif /* !CONFIG_SCHED_CORE */ @@ -5017,6 +5045,7 @@ void wake_up_new_task(struct task_struct *p) struct rq_flags rf; struct rq *rq; int wake_flags = WF_FORK; + int en_flags = ENQUEUE_NOCLOCK | ENQUEUE_INITIAL; raw_spin_lock_irqsave(&p->pi_lock, rf.flags); WRITE_ONCE(p->__state, TASK_RUNNING); @@ -5030,11 +5059,13 @@ void wake_up_new_task(struct task_struct *p) */ p->recent_used_cpu = task_cpu(p); __set_task_cpu(p, select_task_rq(p, task_cpu(p), &wake_flags)); + if (wake_flags & WF_RQ_SELECTED) + en_flags |= ENQUEUE_RQ_SELECTED; rq = __task_rq_lock(p, &rf); update_rq_clock(rq); post_init_entity_util_avg(p); - activate_task(rq, p, ENQUEUE_NOCLOCK | ENQUEUE_INITIAL); + activate_task(rq, p, en_flags); trace_sched_wakeup_new(p); wakeup_preempt(rq, p, wake_flags); if (p->sched_class->task_woken) { @@ -6297,6 +6328,7 @@ pick_next_task(struct rq *rq, struct rq_flags *rf) __must_hold(__rq_lockp(rq)) { struct task_struct *next, *p, *max; + struct sched_dl_entity *max_dl_server; bool fi_before = false; bool core_clock_updated = (rq == rq->core); unsigned long cookie; @@ -6410,6 +6442,7 @@ pick_next_task(struct rq *rq, struct rq_flags *rf) * Tie-break prio towards the current CPU */ max = NULL; + max_dl_server = NULL; for_each_core_cpu_wrap(i, rq) { rq_i = cpu_rq(i); @@ -6433,8 +6466,16 @@ pick_next_task(struct rq *rq, struct rq_flags *rf) rq_i->core_pick = p; rq_i->core_dl_server = rq_i->dl_server; - if (!max || prio_less(max, p, fi_before)) + /* + * p->dl_server is only set once @p runs; rank a pick that + * came through a DL server by that server. + */ + if (!max || __prio_less(max, max_dl_server, + p, rq_i->dl_server, + fi_before)) { max = p; + max_dl_server = rq_i->dl_server; + } } cookie = rq->core->core_cookie = max->core_cookie; @@ -6453,10 +6494,15 @@ pick_next_task(struct rq *rq, struct rq_flags *rf) p = sched_core_find(rq_i, cookie); if (!p) p = idle_sched_class.pick_task(rq_i, rf); + + /* + * Neither a core tree pick nor idle comes through a + * DL server; drop the one the replaced pick left. + */ + rq_i->core_dl_server = rq_i->dl_server = NULL; } rq_i->core_pick = p; - rq_i->core_dl_server = NULL; if (p == rq_i->idle) { if (rq_i->nr_running) { @@ -7276,8 +7322,13 @@ static void __sched notrace __schedule(int sched_mode) */ prev_state = READ_ONCE(prev->__state); if (sched_mode == SM_IDLE) { - /* SCX must consult the BPF scheduler to tell if rq is empty */ - if (!rq->nr_running && !scx_enabled()) { + /* + * SCX must consult the BPF scheduler to tell if rq is empty, + * and core scheduling may need pick_next_task() to end forced + * idle. + */ + if (!rq->nr_running && !scx_enabled() && + !sched_core_idle_needs_pick(rq)) { next = prev; rq->next_class = &idle_sched_class; goto picked; @@ -9776,6 +9827,8 @@ static int cpu_uclamp_max_show(struct seq_file *sf, void *v) } #endif /* CONFIG_UCLAMP_TASK_GROUP */ +DEFINE_MUTEX(cpu_weight_mutex); + #ifdef CONFIG_GROUP_SCHED_WEIGHT static unsigned long tg_weight(struct task_group *tg) { @@ -9793,7 +9846,10 @@ static int cpu_shares_write_u64(struct cgroup_subsys_state *css, if (shareval > scale_load_down(ULONG_MAX)) shareval = MAX_SHARES; - ret = sched_group_set_shares(css_tg(css), scale_load(shareval)); + + guard(mutex)(&cpu_weight_mutex); + + ret = sched_group_set_shares_locked(css_tg(css), scale_load(shareval)); if (!ret) scx_group_set_weight(css_tg(css), sched_weight_to_cgroup(shareval)); @@ -9808,8 +9864,6 @@ static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css, #endif /* CONFIG_GROUP_SCHED_WEIGHT */ #ifdef CONFIG_CFS_BANDWIDTH -static DEFINE_MUTEX(cfs_constraints_mutex); - static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime); static int tg_set_cfs_bandwidth(struct task_group *tg, @@ -9828,13 +9882,6 @@ static int tg_set_cfs_bandwidth(struct task_group *tg, burst = (u64)burst_us * NSEC_PER_USEC; - /* - * Prevent race between setting of cfs_rq->runtime_enabled and - * unthrottle_offline_cfs_rqs(). - */ - guard(cpus_read_lock)(); - guard(mutex)(&cfs_constraints_mutex); - ret = __cfs_schedulable(tg, period, quota); if (ret) return ret; @@ -10086,6 +10133,8 @@ static u64 cpu_period_read_u64(struct cgroup_subsys_state *css, return period_us; } +static DEFINE_MUTEX(cpu_max_mutex); + static int tg_set_bandwidth(struct task_group *tg, u64 period_us, u64 quota_us, u64 burst_us) { @@ -10128,6 +10177,13 @@ static int tg_set_bandwidth(struct task_group *tg, burst_us + quota_us > max_bw_runtime_us)) return -EINVAL; + /* + * Prevent race between setting of cfs_rq->runtime_enabled and + * unthrottle_offline_cfs_rqs(). + */ + guard(cpus_read_lock)(); + guard(mutex)(&cpu_max_mutex); + #ifdef CONFIG_CFS_BANDWIDTH ret = tg_set_cfs_bandwidth(tg, period_us, quota_us, burst_us); #endif /* CONFIG_CFS_BANDWIDTH */ @@ -10226,6 +10282,8 @@ static int cpu_idle_write_s64(struct cgroup_subsys_state *css, { int ret; + guard(mutex)(&cpu_weight_mutex); + ret = sched_group_set_idle(css_tg(css), idle); if (!ret) scx_group_set_idle(css_tg(css), idle); @@ -10402,7 +10460,9 @@ static int cpu_weight_write_u64(struct cgroup_subsys_state *css, weight = sched_weight_from_cgroup(cgrp_weight); - ret = sched_group_set_shares(css_tg(css), scale_load(weight)); + guard(mutex)(&cpu_weight_mutex); + + ret = sched_group_set_shares_locked(css_tg(css), scale_load(weight)); if (!ret) scx_group_set_weight(css_tg(css), cgrp_weight); return ret; @@ -10439,7 +10499,9 @@ static int cpu_weight_nice_write_s64(struct cgroup_subsys_state *css, idx = array_index_nospec(idx, 40); weight = sched_prio_to_weight[idx]; - ret = sched_group_set_shares(css_tg(css), scale_load(weight)); + guard(mutex)(&cpu_weight_mutex); + + ret = sched_group_set_shares_locked(css_tg(css), scale_load(weight)); if (!ret) scx_group_set_weight(css_tg(css), sched_weight_to_cgroup(weight)); @@ -11314,7 +11376,8 @@ static int sched_non_preferred_cpu_push_stop(void *arg) rq->npc_push_work_pending = false; update_rq_clock(rq); - if (task_rq(p) == rq && task_on_rq_queued(p)) { + if (task_rq(p) == rq && task_on_rq_queued(p) && + !is_migration_disabled(p)) { struct rq *dest_rq = __migrate_task(rq, &rf, p, cpu); if (rq != dest_rq) @@ -11355,6 +11418,11 @@ void sched_push_current_non_preferred_cpu(struct rq *rq) if (rq->npc_push_work_pending) return; + /* + * Racy: is_migration_disabled() isn't stable in IRQ + * context and can race with migrate_disable(). The stopper + * should recheck it. + */ if (is_migration_disabled(push_task)) return; diff --git a/kernel/sched/debug.c b/kernel/sched/debug.c index e6a3b516c703ba..dcf9b1daf3d06b 100644 --- a/kernel/sched/debug.c +++ b/kernel/sched/debug.c @@ -1112,6 +1112,7 @@ void print_cfs_rq(struct seq_file *m, int cpu, struct cfs_rq *cfs_rq) atomic_long_read(&cfs_rq->tg->load_avg)); SEQ_printf(m, " .%-30s: %lu\n", "h_load", cfs_rq->h_load); + SEQ_printf(m, " .%-30s: %d\n", "idle", cfs_rq->idle); #endif /* CONFIG_FAIR_GROUP_SCHED */ #ifdef CONFIG_CFS_BANDWIDTH SEQ_printf(m, " .%-30s: %d\n", "throttled", diff --git a/kernel/sched/ext/ext.c b/kernel/sched/ext/ext.c index 10de6bd865e82a..efa1d01d03afa8 100644 --- a/kernel/sched/ext/ext.c +++ b/kernel/sched/ext/ext.c @@ -134,6 +134,7 @@ DEFINE_PERCPU_RWSEM(scx_fork_rwsem); static atomic_t scx_enable_state_var = ATOMIC_INIT(SCX_DISABLED); static DEFINE_RAW_SPINLOCK(scx_bypass_lock); static bool scx_init_task_enabled; +static bool scx_task_switch_enabled; static bool scx_switching_all; DEFINE_STATIC_KEY_FALSE(__scx_switched_all); static DEFINE_STATIC_KEY_FALSE(__scx_tid_to_task_enabled); @@ -6493,6 +6494,15 @@ bool task_should_scx(int policy) if (!scx_enabled()) return false; + /* + * static_branch_enable(&__scx_enabled) patches call sites one by one. + * Wait until all sites are patched before routing tasks to SCX, so + * __schedule() never sees !scx_enabled() when a task is on SCX. Pairs + * with smp_store_release() in scx_root_enable_workfn(). + */ + if (unlikely(!smp_load_acquire(&scx_task_switch_enabled))) + return false; + /* scx is taking over all SCHED_OTHER and SCHED_EXT tasks */ if (READ_ONCE(scx_switching_all)) return true; @@ -7566,8 +7576,24 @@ static void scx_root_disable(struct scx_sched *sch) was_switched_all = scx_switched_all(); + /* + * Tasks fall back to fair from here on. Attach fair_server now, or an + * RT task can starve them while we wait for RCU grace periods below. + * If its bandwidth doesn't fit, the swap at the end attaches it. + */ + if (was_switched_all) { + for_each_possible_cpu(cpu) { + struct rq *rq = cpu_rq(cpu); + + guard(rq_lock_irqsave)(rq); + update_rq_clock(rq); + dl_server_attach_bw(&rq->fair_server); + } + } + static_branch_disable(&__scx_switched_all); WRITE_ONCE(scx_switching_all, false); + WRITE_ONCE(scx_task_switch_enabled, false); /* * Shut down cgroup support before tasks so that the cgroup attach and @@ -7615,8 +7641,8 @@ static void scx_root_disable(struct scx_sched *sch) /* * Re-balance the dl_server bandwidth reservations: detach ext_server - * (no more sched_ext tasks) and reinstate fair_server if it was - * previously detached because we were running in full mode. + * (no more sched_ext tasks) and attach fair_server if the attach + * above failed. * * Unlike the enable path, this runs on a recovery path that cannot * fail, so we use dl_server_swap_bw() to atomically free ext_server's @@ -8965,11 +8991,14 @@ static void scx_root_enable_workfn(struct kthread_work *work) percpu_up_write(&scx_fork_rwsem); /* - * All tasks are READY. It's safe to turn on scx_enabled() and switch - * all eligible tasks. + * All tasks are READY. Finish patching all scx_enabled() sites before + * opening task_should_scx() and switching eligible tasks. */ - WRITE_ONCE(scx_switching_all, !(ops->flags & SCX_OPS_SWITCH_PARTIAL)); + WARN_ON_ONCE(scx_task_switch_enabled); static_branch_enable(&__scx_enabled); + WRITE_ONCE(scx_switching_all, !(ops->flags & SCX_OPS_SWITCH_PARTIAL)); + /* pairs with smp_load_acquire() in task_should_scx() */ + smp_store_release(&scx_task_switch_enabled, true); /* * We're fully committed and can't fail. The task READY -> ENABLED @@ -9294,15 +9323,17 @@ static int bpf_scx_check_member(const struct btf_type *t, * sub-scheds and sub-scheds themselves but I don't know how to access * struct_ops from here. */ - switch (moff) { - case offsetof(struct sched_ext_ops, dispatch): - prog->aux->priv_stack_requested = true; - prog->aux->recursion_detected = scx_pstack_recursion_on_dispatch; - break; - case offsetof(struct sched_ext_ops, sub_caps_updated): - prog->aux->priv_stack_requested = true; - prog->aux->recursion_detected = scx_pstack_recursion_on_caps_updated; - break; + if (bpf_jit_supports_private_stack()) { + switch (moff) { + case offsetof(struct sched_ext_ops, dispatch): + prog->aux->priv_stack_requested = true; + prog->aux->recursion_detected = scx_pstack_recursion_on_dispatch; + break; + case offsetof(struct sched_ext_ops, sub_caps_updated): + prog->aux->priv_stack_requested = true; + prog->aux->recursion_detected = scx_pstack_recursion_on_caps_updated; + break; + } } #endif /* CONFIG_EXT_SUB_SCHED */ @@ -11153,7 +11184,7 @@ __bpf_kfunc struct task_struct *scx_bpf_dsq_peek(u64 dsq_id, return NULL; } - return rcu_dereference(dsq->first_task); + return rcu_dereference_all(dsq->first_task); } /** @@ -11894,8 +11925,6 @@ __bpf_kfunc struct task_struct *scx_bpf_cpu_curr(s32 cpu, const struct bpf_prog_ { struct scx_sched *sch; - guard(rcu)(); - sch = scx_prog_sched(aux); if (unlikely(!sch)) return NULL; @@ -11903,7 +11932,7 @@ __bpf_kfunc struct task_struct *scx_bpf_cpu_curr(s32 cpu, const struct bpf_prog_ if (!scx_cpu_valid(sch, cpu, NULL)) return NULL; - return rcu_dereference(cpu_rq(cpu)->donor); + return rcu_dereference_all(cpu_rq(cpu)->donor); } /** @@ -11919,15 +11948,13 @@ __bpf_kfunc struct task_struct *scx_bpf_cid_curr(s32 cid, const struct bpf_prog_ struct scx_sched *sch; s32 cpu; - guard(rcu)(); - sch = scx_prog_sched(aux); if (unlikely(!sch)) return NULL; cpu = scx_cid_to_cpu(sch, cid); if (cpu < 0) return NULL; - return rcu_dereference(cpu_rq(cpu)->donor); + return rcu_dereference_all(cpu_rq(cpu)->donor); } /** @@ -11944,7 +11971,7 @@ __bpf_kfunc struct task_struct *scx_bpf_tid_to_task(u64 tid) struct sched_ext_entity *scx; if (!scx_tid_to_task_enabled()) { - struct scx_sched *sch = rcu_dereference(scx_root); + struct scx_sched *sch = rcu_dereference_all(scx_root); if (sch) scx_error(sch, "scx_bpf_tid_to_task() called without SCX_OPS_TID_TO_TASK"); @@ -12279,7 +12306,6 @@ static const u32 scx_kf_allow_flags[] = { [SCX_OP_IDX(dispatch)] = SCX_KF_ALLOW_ENQUEUE | SCX_KF_ALLOW_DISPATCH, [SCX_OP_IDX(cpu_release)] = SCX_KF_ALLOW_CPU_RELEASE, [SCX_OP_IDX(init_task)] = SCX_KF_ALLOW_UNLOCKED, - [SCX_OP_IDX(dump)] = SCX_KF_ALLOW_UNLOCKED, #ifdef CONFIG_EXT_GROUP_SCHED [SCX_OP_IDX(cgroup_init)] = SCX_KF_ALLOW_UNLOCKED, [SCX_OP_IDX(cgroup_exit)] = SCX_KF_ALLOW_UNLOCKED, @@ -12295,7 +12321,12 @@ static const u32 scx_kf_allow_flags[] = { [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, + /* + * ops.init_cids() runs before the cid tables are published and before + * the arena pool and pshards are allocated. Limit it to finalizing the + * cid layout; everything else belongs in ops.init(). + */ + [SCX_OP_IDX(init_cids)] = SCX_KF_ALLOW_INIT_CIDS, [SCX_OP_IDX(init)] = SCX_KF_ALLOW_UNLOCKED, [SCX_OP_IDX(exit)] = SCX_KF_ALLOW_UNLOCKED, }; diff --git a/kernel/sched/ext/internal.h b/kernel/sched/ext/internal.h index 58652370da5ad2..c0109ac9834705 100644 --- a/kernel/sched/ext/internal.h +++ b/kernel/sched/ext/internal.h @@ -2674,6 +2674,8 @@ static inline bool scx_task_on_sched(struct scx_sched *sch, return rcu_access_pointer(p->scx.sched) == sch; } +static struct bpf_struct_ops bpf_sched_ext_ops, bpf_sched_ext_ops_cid; + /** * scx_prog_sched - Find scx_sched associated with a BPF prog * @aux: aux passed in from BPF to a kfunc @@ -2687,7 +2689,8 @@ static inline struct scx_sched *scx_prog_sched(const struct bpf_prog_aux *aux) struct sched_ext_ops *ops; struct scx_sched *sch, *root; - ops = bpf_prog_get_assoc_struct_ops(aux); + ops = bpf_prog_get_assoc_struct_ops(aux, &bpf_sched_ext_ops) ?: + bpf_prog_get_assoc_struct_ops(aux, &bpf_sched_ext_ops_cid); if (likely(ops)) { sch = rcu_dereference_all(ops->priv); if (sch && unlikely(READ_ONCE(sch->dead))) diff --git a/kernel/sched/ext/sub.c b/kernel/sched/ext/sub.c index d2a20114eaa23f..7c069a28976606 100644 --- a/kernel/sched/ext/sub.c +++ b/kernel/sched/ext/sub.c @@ -2246,6 +2246,12 @@ void scx_sub_enable_workfn(struct kthread_work *work) goto out_unlock; } + /* nesting ops need private stacks, see bpf_scx_check_member() */ + if (!bpf_jit_supports_private_stack()) { + ret = -EOPNOTSUPP; + goto out_unlock; + } + cgrp = cgroup_get_from_id(ops->sub_cgroup_id); if (IS_ERR(cgrp)) { ret = PTR_ERR(cgrp); diff --git a/kernel/sched/fair.c b/kernel/sched/fair.c index 0c8af1cac2d5bb..8a55571b9719dc 100644 --- a/kernel/sched/fair.c +++ b/kernel/sched/fair.c @@ -445,8 +445,10 @@ static int cfs_rq_is_idle(struct cfs_rq *cfs_rq) static int se_is_idle(struct sched_entity *se) { - if (entity_is_task(se)) - return task_has_idle_policy(task_of(se)); + if (entity_is_task(se)) { + return task_has_idle_policy(task_of(se)) || + cfs_rq_is_idle(cfs_rq_of(se)); + } return cfs_rq_is_idle(group_cfs_rq(se)); } @@ -6547,19 +6549,8 @@ static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq); static void set_delayed(struct sched_entity *se) { - /* - * Delayed se of cfs_rq have no tasks queued on them. - * Do not adjust h_nr_runnable since __dequeue_task() - * will account it for blocked tasks. - * - * This check can be removed because when flat pick - * patches get merged as only task can get delayed, - * same for clear_delayed(). - */ - if (!entity_is_task(se)) { - se->sched_delayed = 1; - return; - } + /* Only tasks can be delayed. */ + WARN_ON_ONCE(!entity_is_task(se)); /* * Drop a task leaving the runnable set. @@ -6576,18 +6567,16 @@ static void set_delayed(struct sched_entity *se) } } -static void clear_delayed(struct sched_entity *se) +static void __clear_delayed(struct sched_entity *se) { + /* Only tasks can be delayed. */ + WARN_ON_ONCE(!entity_is_task(se)); se->sched_delayed = 0; +} - /* - * Delayed se of cfs_rq have no tasks queued on them. - * Do not adjust h_nr_runnable since a dequeue has - * already accounted for it or an enqueue of a task - * below it will account for it in enqueue_task_fair(). - */ - if (!entity_is_task(se)) - return; +static void clear_delayed(struct sched_entity *se) +{ + __clear_delayed(se); /* * Re-add on wake, after sched_delayed is cleared. On a final delayed @@ -8111,12 +8100,15 @@ requeue_delayed_entity(struct cfs_rq *cfs_rq, struct sched_entity *se) static unsigned long enqueue_hierarchy(struct task_struct *p, int flags) { unsigned long weight = NICE_0_LOAD; - int task_new = !(flags & ENQUEUE_WAKEUP); struct sched_entity *se = &p->se; int h_nr_idle = task_has_idle_policy(p); int h_nr_runnable = 1; - if (task_new && se->sched_delayed) + /* + * Accounted via requeue_delayed_entity() calling + * clear_delayed() when delayed task wakes up. + */ + if (se->sched_delayed) h_nr_runnable = 0; for_each_sched_entity(se) { @@ -8190,6 +8182,9 @@ enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags) return; } + /* Wakeup of delayed tasks must be handled above. */ + WARN_ON_ONCE(!task_new && se->sched_delayed); + /* * If in_iowait is set, the code below may not trigger any cpufreq * utilization updates, so do it here explicitly with the IOWAIT flag @@ -8207,9 +8202,6 @@ enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags) if (curr) place_entity(cfs_rq, se, flags); - if (se->on_rq && se->sched_delayed) - requeue_delayed_entity(cfs_rq, se); - weight = enqueue_hierarchy(p, flags); if (!curr) { @@ -8249,15 +8241,14 @@ enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags) static void dequeue_hierarchy(struct task_struct *p, int flags) { struct sched_entity *se = &p->se; - bool task_sleep = flags & DEQUEUE_SLEEP; - bool task_delayed = flags & DEQUEUE_DELAYED; bool task_throttled = flags & DEQUEUE_THROTTLE; - int h_nr_runnable = 0; + int h_nr_runnable = 1; int h_nr_idle = task_has_idle_policy(p); bool dequeue = true; - if (task_sleep || task_delayed || !se->sched_delayed) - h_nr_runnable = 1; + /* Already accounted via set_delayed(). */ + if (se->sched_delayed) + h_nr_runnable = 0; for_each_sched_entity(se) { struct cfs_rq *cfs_rq = cfs_rq_of(se); @@ -8347,7 +8338,11 @@ static bool __dequeue_task(struct rq *rq, struct task_struct *p, int flags) rq->next_balance = jiffies; if (task_delayed) { - clear_delayed(se); + /* + * Skip accounting since set_delayed() has already + * adjusted it. Just clear se->sched_delayed. + */ + __clear_delayed(se); WARN_ON_ONCE(!task_sleep); WARN_ON_ONCE(p->on_rq != 1); @@ -15672,19 +15667,20 @@ int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent) void online_fair_sched_group(struct task_group *tg) { - struct sched_entity *se; - struct rq_flags rf; - struct rq *rq; int i; for_each_possible_cpu(i) { - rq = cpu_rq(i); - se = tg_se(tg, i); - rq_lock_irq(rq, &rf); + struct cfs_rq *cfs_rq = tg_cfs_rq(tg, i); + struct sched_entity *se = tg_se(tg, i); + struct rq *rq = cpu_rq(i); + + guard(rq_lock_irq)(rq); + update_rq_clock(rq); attach_entity_cfs_rq(se); sync_throttle(tg, i); - rq_unlock_irq(rq, &rf); + + cfs_rq->idle = tg_cfs_rq(tg->parent, i)->idle; } } @@ -15741,13 +15737,11 @@ void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq, se->parent = parent; } -static DEFINE_MUTEX(shares_mutex); - static int __sched_group_set_shares(struct task_group *tg, unsigned long shares) { int i; - lockdep_assert_held(&shares_mutex); + lockdep_assert_held(&cpu_weight_mutex); /* * We can't change the weight of the root cgroup. @@ -15779,73 +15773,90 @@ static int __sched_group_set_shares(struct task_group *tg, unsigned long shares) return 0; } -int sched_group_set_shares(struct task_group *tg, unsigned long shares) +int sched_group_set_shares_locked(struct task_group *tg, unsigned long shares) { int ret; - mutex_lock(&shares_mutex); + lockdep_assert_held(&cpu_weight_mutex); + if (tg_is_idle(tg)) ret = -EINVAL; else ret = __sched_group_set_shares(tg, shares); - mutex_unlock(&shares_mutex); return ret; } +struct tg_set_idle_struct { + long idle; + int cpu; +}; + +static int tg_set_idle_up(struct task_group *tg, void *data) +{ + struct tg_set_idle_struct *tsi = data; + struct cfs_rq *grp_cfs_rq = tg_cfs_rq(tg, tsi->cpu); + struct sched_entity *se = tg_se(tg, tsi->cpu); + int old_idle = grp_cfs_rq->idle; + int task_delta; + + grp_cfs_rq->idle += tsi->idle; + + if (!!old_idle == !!grp_cfs_rq->idle) + return 0; + + task_delta = grp_cfs_rq->h_nr_queued - grp_cfs_rq->h_nr_idle; + if (!task_delta) + return 0; + + task_delta *= tsi->idle; + for_each_sched_entity(se) { + struct cfs_rq *cfs_rq = cfs_rq_of(se); + + if (!se->on_rq) + break; + + cfs_rq->h_nr_idle += task_delta; + + if (cfs_rq_is_idle(cfs_rq)) + break; + } + return 0; +} + +int sched_group_set_shares(struct task_group *tg, unsigned long shares) +{ + guard(mutex)(&cpu_weight_mutex); + return sched_group_set_shares_locked(tg, shares); +} + int sched_group_set_idle(struct task_group *tg, long idle) { int i; + lockdep_assert_held(&cpu_weight_mutex); + if (tg == &root_task_group) return -EINVAL; if (idle < 0 || idle > 1) return -EINVAL; - mutex_lock(&shares_mutex); - - if (tg->idle == idle) { - mutex_unlock(&shares_mutex); + if (tg->idle == idle) return 0; - } tg->idle = idle; for_each_possible_cpu(i) { struct rq *rq = cpu_rq(i); - struct sched_entity *se = tg_se(tg, i); - struct cfs_rq *grp_cfs_rq = tg_cfs_rq(tg, i); - bool was_idle = cfs_rq_is_idle(grp_cfs_rq); - long idle_task_delta; - struct rq_flags rf; - - rq_lock_irqsave(rq, &rf); - - grp_cfs_rq->idle = idle; - if (WARN_ON_ONCE(was_idle == cfs_rq_is_idle(grp_cfs_rq))) - goto next_cpu; - - idle_task_delta = grp_cfs_rq->h_nr_queued - - grp_cfs_rq->h_nr_idle; - if (!cfs_rq_is_idle(grp_cfs_rq)) - idle_task_delta *= -1; - for_each_sched_entity(se) { - struct cfs_rq *cfs_rq = cfs_rq_of(se); - - if (!se->on_rq) - break; - - cfs_rq->h_nr_idle += idle_task_delta; - - /* Already accounted at parent level and above. */ - if (cfs_rq_is_idle(cfs_rq)) - break; - } + guard(rq_lock_irqsave)(rq); -next_cpu: - rq_unlock_irqrestore(rq, &rf); + struct tg_set_idle_struct tsi = { + .idle = idle ? 1 : -1, + .cpu = i, + }; + walk_tg_tree_from(tg, tg_nop, tg_set_idle_up, &tsi); } /* Idle groups have minimum weight. */ @@ -15854,7 +15865,6 @@ int sched_group_set_idle(struct task_group *tg, long idle) else __sched_group_set_shares(tg, NICE_0_LOAD); - mutex_unlock(&shares_mutex); return 0; } diff --git a/kernel/sched/idle.c b/kernel/sched/idle.c index e0c10a5dbda2bd..717d566b0809ce 100644 --- a/kernel/sched/idle.c +++ b/kernel/sched/idle.c @@ -573,6 +573,13 @@ static void update_curr_idle(struct rq *rq) se->exec_start = now; + /* + * Forced idle was not time available to any class on this rq, so + * don't let the deferred servers consume their runtime on it. + */ + if (forced_idle_rq(rq)) + return; + dl_server_update_idle(&rq->fair_server, delta_exec); #ifdef CONFIG_SCHED_CLASS_EXT dl_server_update_idle(&rq->ext_server, delta_exec); diff --git a/kernel/sched/isolation.c b/kernel/sched/isolation.c index 156025ef81b75a..c0c8b8862cbdc3 100644 --- a/kernel/sched/isolation.c +++ b/kernel/sched/isolation.c @@ -120,6 +120,17 @@ bool housekeeping_test_cpu(int cpu, enum hk_type type) } EXPORT_SYMBOL_GPL(housekeeping_test_cpu); +void __init housekeeping_set_cpu(int cpu, enum hk_type type) +{ + /* Only CPU setting of HK_TYPE_KERNEL_NOISE is currently supported */ + if (type != HK_TYPE_KERNEL_NOISE) + return; + + if (static_branch_unlikely(&housekeeping_overridden) && + READ_ONCE(housekeeping.flags) & BIT(type)) + cpumask_set_cpu(cpu, housekeeping_cpumask_dereference(type)); +} + int housekeeping_update(struct cpumask *isol_mask) { struct cpumask *trial, *old = NULL; diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h index 220927453a8892..804c70317637d2 100644 --- a/kernel/sched/sched.h +++ b/kernel/sched/sched.h @@ -599,7 +599,10 @@ extern void sched_release_group(struct task_group *tg); extern void sched_move_task(struct task_struct *tsk, bool for_autogroup); #ifdef CONFIG_FAIR_GROUP_SCHED +extern struct mutex cpu_weight_mutex; + extern int sched_group_set_shares(struct task_group *tg, unsigned long shares); +extern int sched_group_set_shares_locked(struct task_group *tg, unsigned long shares); extern int sched_group_set_idle(struct task_group *tg, long idle); @@ -607,6 +610,10 @@ extern void set_task_rq_fair(struct sched_entity *se, struct cfs_rq *prev, struct cfs_rq *next); #else /* !CONFIG_FAIR_GROUP_SCHED: */ static inline int sched_group_set_shares(struct task_group *tg, unsigned long shares) { return 0; } +static inline int sched_group_set_shares_locked(struct task_group *tg, unsigned long shares) +{ + return 0; +} static inline int sched_group_set_idle(struct task_group *tg, long idle) { return 0; } #endif /* !CONFIG_FAIR_GROUP_SCHED */ @@ -751,7 +758,7 @@ struct cfs_rq { struct list_head leaf_cfs_rq_list; struct task_group *tg; /* Group that "owns" this runqueue */ - /* Locally cached copy of our task_group's idle value */ + /* Sum of all ancestor tg->idle. */ int idle; # ifdef CONFIG_CFS_BANDWIDTH @@ -1514,6 +1521,16 @@ static inline bool sched_core_disabled(void) return !static_branch_unlikely(&__sched_core_enabled); } +/* + * True while core scheduling keeps @rq idle because a SMT sibling runs a task + * with an incompatible cookie, even though @rq has runnable tasks of its own. + */ +static inline bool forced_idle_rq(struct rq *rq) +{ + return sched_core_enabled(rq) && rq->core->core_forceidle_count && + rq->nr_running; +} + /* * Be careful with this function; not for general use. The return value isn't * stable unless you actually hold a relevant rq->__lock. @@ -1648,6 +1665,11 @@ static inline bool sched_core_disabled(void) return true; } +static inline bool forced_idle_rq(struct rq *rq) +{ + return false; +} + static inline raw_spinlock_t *rq_lockp(struct rq *rq) { return &rq->__lock; diff --git a/kernel/sched/topology.c b/kernel/sched/topology.c index 9d3a1b8dd39349..2e355a658dfc63 100644 --- a/kernel/sched/topology.c +++ b/kernel/sched/topology.c @@ -3187,7 +3187,13 @@ build_sched_domains(const struct cpumask *cpu_map, struct sched_domain_attr *att sd = sd->parent; if (sd->flags & SD_SHARE_LLC) { - init_sched_domain_shared(&d, sd, SD_SHARE_LLC); + /* + * The asym path above may have claimed a shared object + * on this very domain; claiming it again overwrites + * sd->shared and leaks the first reference. + */ + if (!sd->shared) + init_sched_domain_shared(&d, sd, SD_SHARE_LLC); /* * In presence of higher domains, adjust the diff --git a/kernel/sched/wait.c b/kernel/sched/wait.c index f8d6d8b9d03e66..020cf3f77611de 100644 --- a/kernel/sched/wait.c +++ b/kernel/sched/wait.c @@ -85,6 +85,11 @@ EXPORT_SYMBOL(remove_wait_queue); * may be at the head of the list, and can consume the event without any other * tasks being woken if it's also an exclusive task. * + * An exclusive waiter that returns >0 promises to handle the event. Pollers + * (EPOLLEXCLUSIVE) can't promise that, since userspace may never consume it. + * They use WQ_FLAG_POLL_EXCLUSIVE instead: only one of them is woken, but they + * never count against nr_exclusive or stop the walk. + * * There are circumstances in which we can try to wake a task which has already * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns * zero in this (rare) case, and we handle it by continuing to scan the queue. @@ -93,22 +98,24 @@ static int __wake_up_common(struct wait_queue_head *wq_head, unsigned int mode, int nr_exclusive, int wake_flags, void *key) { wait_queue_entry_t *curr, *next; + bool poll_woken = false; lockdep_assert_held(&wq_head->lock); - curr = list_first_entry(&wq_head->head, wait_queue_entry_t, entry); - - if (&curr->entry == &wq_head->head) - return nr_exclusive; - - list_for_each_entry_safe_from(curr, next, &wq_head->head, entry) { + list_for_each_entry_safe(curr, next, &wq_head->head, entry) { unsigned flags = curr->flags; int ret; + if ((flags & WQ_FLAG_POLL_EXCLUSIVE) && poll_woken) + continue; ret = curr->func(curr, mode, wake_flags, key); if (ret < 0) break; - if (ret && (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive) + if (!ret) + continue; + if (flags & WQ_FLAG_POLL_EXCLUSIVE) + poll_woken = nr_exclusive > 0; + else if ((flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive) break; } diff --git a/kernel/time/jiffies.c b/kernel/time/jiffies.c index af1c69bf0c23db..b861dc860d3452 100644 --- a/kernel/time/jiffies.c +++ b/kernel/time/jiffies.c @@ -137,11 +137,19 @@ static int sysctl_k2u_int_conv_userhz(bool *negp, ulong *u_ptr, const int *k_ptr return proc_int_k2u_conv_kop(u_ptr, k_ptr, negp, sysctl_jiffies_to_clock_t); } +/* + * Calc ms <-> jiffies conversions for sysctls in unsigned long arithmetic. + * Think hard about using the non-sysctl converters (msecs_to_jiffies & + * jiffies_to_msecs) as the interaction between ulong and uint is not trivial. + */ static ulong sysctl_msecs_to_jiffies(const ulong val) { - if (val > jiffies_to_msecs(MAX_JIFFY_OFFSET)) - return MAX_JIFFY_OFFSET; - return msecs_to_jiffies(val); + ulong secs = val / MSEC_PER_SEC; + + if (secs >= ULONG_MAX / HZ) + return ULONG_MAX; + + return secs * HZ + DIV_ROUND_UP((val % MSEC_PER_SEC) * HZ, MSEC_PER_SEC); } static int sysctl_u2k_int_conv_ms(const bool *negp, const ulong *u_ptr, int *k_ptr) @@ -151,7 +159,12 @@ static int sysctl_u2k_int_conv_ms(const bool *negp, const ulong *u_ptr, int *k_p static ulong sysctl_jiffies_to_msecs(const ulong val) { - return jiffies_to_msecs(val); + ulong secs = val / HZ; + + if (secs >= ULONG_MAX / MSEC_PER_SEC) + return ULONG_MAX; + + return secs * MSEC_PER_SEC + (val % HZ) * MSEC_PER_SEC / HZ; } static int sysctl_k2u_int_conv_ms(bool *negp, ulong *u_ptr, const int *k_ptr) diff --git a/kernel/time/tick-sched.c b/kernel/time/tick-sched.c index c6d86e4da8a917..867d83a4bd7e4d 100644 --- a/kernel/time/tick-sched.c +++ b/kernel/time/tick-sched.c @@ -22,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -683,6 +684,11 @@ void __init tick_nohz_init(void) pr_warn("NO_HZ: Clearing %d from nohz_full range " "for timekeeping\n", cpu); cpumask_clear_cpu(cpu, tick_nohz_full_mask); + housekeeping_set_cpu(cpu, HK_TYPE_KERNEL_NOISE); + if (cpumask_empty(tick_nohz_full_mask)) { + tick_nohz_full_running = false; + return; + } } } diff --git a/kernel/trace/bpf_trace.c b/kernel/trace/bpf_trace.c index d22e78e7f28da7..19e6b51bb2f000 100644 --- a/kernel/trace/bpf_trace.c +++ b/kernel/trace/bpf_trace.c @@ -807,7 +807,7 @@ const struct bpf_func_proto bpf_get_current_task_btf_proto = { BPF_CALL_1(bpf_task_pt_regs, struct task_struct *, task) { - return (unsigned long) task_pt_regs(task); + return task ? (unsigned long)task_pt_regs(task) : 0; } BTF_ID_LIST_SINGLE(bpf_task_pt_regs_ids, struct, pt_regs) @@ -946,6 +946,8 @@ BPF_CALL_3(bpf_d_path, const struct path *, path, char *, buf, u32, sz) len = copy_from_kernel_nofault(©, path, sizeof(*path)); if (len < 0) return len; + if (!copy.mnt || !copy.dentry) + return -EFAULT; p = d_path(©, buf, sz); if (IS_ERR(p)) { @@ -980,6 +982,10 @@ BTF_SET_END(btf_allowlist_d_path_fentry) static bool bpf_d_path_allowed(const struct bpf_prog *prog) { + /* attach_btf_id is a function of the target program */ + if (prog->aux->dst_prog) + return false; + if (prog->type == BPF_PROG_TYPE_TRACING && prog->expected_attach_type == BPF_TRACE_ITER) return true; @@ -1397,8 +1403,16 @@ static bool kprobe_prog_is_valid_access(int off, int size, enum bpf_access_type if (off + size > sizeof(struct pt_regs)) return false; - if (type == BPF_WRITE) + if (type == BPF_WRITE) { + /* + * pt_regs also holds what the kernel restores on the way to + * user space: cs and flags on x86, pstate on arm64, status on + * riscv. A prog can write the registers of the task only. + */ + if (!arch_uprobe_regs_writable(off, size)) + return false; prog->aux->kprobe_write_ctx = true; + } return true; } diff --git a/kernel/trace/fgraph.c b/kernel/trace/fgraph.c index 6d87143b3ddb5f..d1f79a85ed2e97 100644 --- a/kernel/trace/fgraph.c +++ b/kernel/trace/fgraph.c @@ -568,7 +568,11 @@ ftrace_push_return_trace(unsigned long ret, unsigned long func, if (unlikely(ftrace_graph_is_dead())) return -EBUSY; - if (!current->ret_stack) + /* + * We must make sure the ret_stack is tested before we read + * anything else (See alloc_retstack_tasklist()). + */ + if (!smp_load_acquire(¤t->ret_stack)) return -EBUSY; BUILD_BUG_ON(SHADOW_STACK_SIZE % sizeof(long)); @@ -576,12 +580,6 @@ ftrace_push_return_trace(unsigned long ret, unsigned long func, /* Set val to "reserved" with the delta to the new fgraph frame */ val = (FGRAPH_TYPE_RESERVED << FGRAPH_TYPE_SHIFT) | FGRAPH_FRAME_OFFSET; - /* - * We must make sure the ret_stack is tested before we read - * anything else. - */ - smp_rmb(); - /* * Check if there's room on the shadow stack to fit a fraph frame * and a bitmap word. @@ -700,11 +698,7 @@ int function_graph_enter_regs(unsigned long ret, unsigned long func, if (!bitmap) goto out_ret; - /* - * Since this function uses fgraph_idx = 0 as a tail-call checking - * flag, set that bit always. - */ - set_bitmap(current, offset, bitmap | BIT(0)); + set_bitmap(current, offset, bitmap); ftrace_test_recursion_unlock(bit); return 0; out_ret: @@ -1033,13 +1027,16 @@ void ftrace_stub_graph(struct ftrace_graph_ret *trace, struct fgraph_ops *gops, trace_func_graph_ret_t ftrace_graph_return = ftrace_stub_graph; trace_func_graph_ent_t ftrace_graph_entry = ftrace_graph_entry_stub; -/* Try to assign a return stack array on FTRACE_RETSTACK_ALLOC_SIZE tasks. */ +/* + * Loop thru all the tasks in the system and assign ret_stack. + * The @ret_stack_list is a small pre-allocated fallback, in case + * the GFP_NOWAIT allocations here fail. + */ static int alloc_retstack_tasklist(unsigned long **ret_stack_list) { - int i; - int ret = 0; int start = 0, end = FTRACE_RETSTACK_ALLOC_SIZE; struct task_struct *g, *t; + int i, ret = 0; if (WARN_ON_ONCE(!fgraph_stack_cachep)) return -ENOMEM; @@ -1054,26 +1051,31 @@ static int alloc_retstack_tasklist(unsigned long **ret_stack_list) } } - rcu_read_lock(); - for_each_process_thread(g, t) { - if (start == end) { - ret = -EAGAIN; - goto unlock; - } + scoped_guard (rcu) { + for_each_process_thread(g, t) { + unsigned long *rs; + + if (t->ret_stack) + continue; + + rs = kmem_cache_alloc(fgraph_stack_cachep, GFP_NOWAIT); + if (!rs) { + if (start == end) { + ret = -EAGAIN; + goto free; + } + rs = ret_stack_list[start++]; + } - if (t->ret_stack == NULL) { atomic_set(&t->trace_overrun, 0); - ret_stack_init_task_vars(ret_stack_list[start]); + ret_stack_init_task_vars(rs); t->curr_ret_stack = 0; t->curr_ret_depth = -1; /* Make sure the tasks see the 0 first: */ - smp_wmb(); - t->ret_stack = ret_stack_list[start++]; + smp_store_release(&t->ret_stack, rs); } } -unlock: - rcu_read_unlock(); free: for (i = start; i < end; i++) kmem_cache_free(fgraph_stack_cachep, ret_stack_list[i]); @@ -1117,8 +1119,7 @@ graph_init_task(struct task_struct *t, unsigned long *ret_stack) t->curr_ret_stack = 0; t->curr_ret_depth = -1; /* make curr_ret_stack visible before we add the ret_stack */ - smp_wmb(); - t->ret_stack = ret_stack; + smp_store_release(&t->ret_stack, ret_stack); } /* diff --git a/kernel/trace/ftrace.c b/kernel/trace/ftrace.c index c7d74b33d36de1..5b161959e7019c 100644 --- a/kernel/trace/ftrace.c +++ b/kernel/trace/ftrace.c @@ -5029,7 +5029,8 @@ match_records(struct ftrace_hash *hash, char *func, int len, char *mod) if (unlikely(ftrace_disabled)) return 0; - if (func_g.type == MATCH_INDEX) + if (func_g.type == MATCH_FULL && !mod && + func_g.search && isdigit(func_g.search[0])) return add_rec_by_index(hash, &func_g, clear_filter); do_for_each_ftrace_rec(pg, rec) { @@ -5846,6 +5847,13 @@ static int ftrace_process_regex(struct ftrace_iterator *iter, /* command found */ + /* + * A double "!!" confuses the parser. This isn't a boolean operation, + * simply reject it. + */ + if (func[0] == '!' && func[1] == '!') + return -EINVAL; + command = strsep(&next, ":"); guard(mutex)(&ftrace_cmd_mutex); diff --git a/kernel/trace/ring_buffer.c b/kernel/trace/ring_buffer.c index 75cd8df23c1b9c..65dddfac5e047b 100644 --- a/kernel/trace/ring_buffer.c +++ b/kernel/trace/ring_buffer.c @@ -2468,8 +2468,17 @@ static int __rb_allocate_pages(struct ring_buffer_per_cpu *cpu_buffer, * memory. It may not be accurate. But we don't care, we just want * to prevent doing any allocation when it is obvious that it is * not going to succeed. + * + * With CONFIG_DEFERRED_STRUCT_PAGE_INIT, si_mem_available() + * will reflect the actual available memory only after + * SYSTEM_FREEING_INITMEM. */ - i = si_mem_available(); + if (IS_ENABLED(CONFIG_DEFERRED_STRUCT_PAGE_INIT) && + unlikely(system_state < SYSTEM_FREEING_INITMEM)) + i = LONG_MAX; + else + i = si_mem_available(); + if (i < (nr_pages << subbuf_order)) return -ENOMEM; @@ -5615,14 +5624,12 @@ unsigned long ring_buffer_overruns(struct trace_buffer *buffer) } EXPORT_SYMBOL_GPL(ring_buffer_overruns); -static bool rb_read_remote_meta_page(struct ring_buffer_per_cpu *cpu_buffer) +static void rb_read_remote_meta_page(struct ring_buffer_per_cpu *cpu_buffer) { local_set(&cpu_buffer->entries, READ_ONCE(cpu_buffer->meta_page->entries)); local_set(&cpu_buffer->overrun, READ_ONCE(cpu_buffer->meta_page->overrun)); local_set(&cpu_buffer->pages_touched, READ_ONCE(cpu_buffer->meta_page->pages_touched)); local_set(&cpu_buffer->pages_lost, READ_ONCE(cpu_buffer->meta_page->pages_lost)); - - return rb_num_of_entries(cpu_buffer); } static void rb_update_remote_head(struct ring_buffer_per_cpu *cpu_buffer) @@ -5825,15 +5832,20 @@ __rb_get_reader_page_from_remote(struct ring_buffer_per_cpu *cpu_buffer) { struct buffer_page *new_reader, *prev_reader, *prev_head, *new_head, *last; - if (!rb_read_remote_meta_page(cpu_buffer)) - return NULL; + rb_read_remote_meta_page(cpu_buffer); + + /* + * Order meta::entries read before page::commit, most likely paired with + * simple_ring_buffer_commit(). + */ + smp_rmb(); /* More to read on the reader page */ - if (cpu_buffer->reader_page->read < rb_page_size(cpu_buffer->reader_page)) { - if (!cpu_buffer->reader_page->read) - cpu_buffer->read_stamp = cpu_buffer->reader_page->page->time_stamp; - return cpu_buffer->reader_page; - } + if (cpu_buffer->reader_page->read < rb_page_size(cpu_buffer->reader_page)) + goto out; + + if (!rb_num_of_entries(cpu_buffer)) + return NULL; prev_reader = cpu_buffer->subbuf_ids[cpu_buffer->meta_page->reader.id]; @@ -5848,7 +5860,8 @@ __rb_get_reader_page_from_remote(struct ring_buffer_per_cpu *cpu_buffer) new_reader = cpu_buffer->subbuf_ids[cpu_buffer->meta_page->reader.id]; - WARN_ON_ONCE(prev_reader == new_reader); + if (prev_reader == new_reader) + return NULL; prev_head = new_reader; /* New reader was also the previous head */ new_head = prev_head; @@ -5876,10 +5889,24 @@ __rb_get_reader_page_from_remote(struct ring_buffer_per_cpu *cpu_buffer) cpu_buffer->reader_page = new_reader; cpu_buffer->reader_page->read = 0; cpu_buffer->pages = &new_head->list; - cpu_buffer->read_stamp = new_reader->page->time_stamp; cpu_buffer->lost_events = cpu_buffer->meta_page->reader.lost_events; + local_inc(&cpu_buffer->pages_read); + cpu_buffer->cnt++; - return rb_page_size(cpu_buffer->reader_page) ? cpu_buffer->reader_page : NULL; + if (!rb_page_size(cpu_buffer->reader_page)) + return NULL; + +out: + /* + * Order page::commit read before page::data and page::time_stamp, most + * likely paired with simple_ring_buffer_commit(). + */ + smp_rmb(); + + if (!cpu_buffer->reader_page->read) + cpu_buffer->read_stamp = cpu_buffer->reader_page->page->time_stamp; + + return cpu_buffer->reader_page; } static struct buffer_page * @@ -6908,7 +6935,8 @@ int ring_buffer_poll_remote(struct trace_buffer *buffer, int cpu) cpu_buffer = buffer->buffers[cpu]; guard(raw_spinlock)(&cpu_buffer->reader_lock); - if (rb_read_remote_meta_page(cpu_buffer)) + rb_read_remote_meta_page(cpu_buffer); + if (rb_num_of_entries(cpu_buffer)) rb_wakeups(buffer, cpu_buffer); return 0; @@ -8091,8 +8119,7 @@ int trace_rb_cpu_prepare(unsigned int cpu, struct hlist_node *node) buffer->buffers[cpu] = rb_allocate_cpu_buffer(buffer, nr_pages, cpu); if (!buffer->buffers[cpu]) { - WARN(1, "failed to allocate ring buffer on CPU %u\n", - cpu); + pr_warn("failed to allocate ring buffer on CPU %u\n", cpu); return -ENOMEM; } diff --git a/kernel/trace/simple_ring_buffer.c b/kernel/trace/simple_ring_buffer.c index abfaf9bee12e1f..2dddaef638dc64 100644 --- a/kernel/trace/simple_ring_buffer.c +++ b/kernel/trace/simple_ring_buffer.c @@ -139,6 +139,13 @@ int simple_ring_buffer_swap_reader_page(struct simple_rb_per_cpu *cpu_buffer) reader = cpu_buffer->reader_page; + /* + * The reader is already the tail page. See simple_rb_move_tail() for + * memory ordering. + */ + if (reader == smp_load_acquire(&cpu_buffer->tail_page)) + return 0; + do { /* Run after the writer to find the head */ ret = simple_rb_find_head(cpu_buffer); @@ -196,7 +203,13 @@ static struct simple_buffer_page *simple_rb_move_tail(struct simple_rb_per_cpu * } simple_bpage_reset(new_tail); - cpu_buffer->tail_page = new_tail; + + /* + * Setting a new tail may unblock the swap in + * simple_ring_buffer_swap_reader_page(). Ensure the reader observes the + * page::commit reset. + */ + smp_store_release(&cpu_buffer->tail_page, new_tail); simple_rb_meta_inc(cpu_buffer->meta->pages_touched, 1); @@ -294,8 +307,19 @@ EXPORT_SYMBOL_GPL(simple_ring_buffer_reserve); */ void simple_ring_buffer_commit(struct simple_rb_per_cpu *cpu_buffer) { + /* + * Order page::data and page::time_stamp before page::commit. Paired + * with __rb_get_reader_page_from_remote(). + */ + smp_wmb(); local_set(&cpu_buffer->tail_page->page->commit, cpu_buffer->tail_page->write); + + /* + * Order page::commit before meta::entries. Paired with + * __rb_get_reader_page_from_remote(). + */ + smp_wmb(); simple_rb_meta_inc(cpu_buffer->meta->entries, 1); /* diff --git a/kernel/trace/trace.c b/kernel/trace/trace.c index 4ccdefb5c3efe5..fa65ef8d7fbea3 100644 --- a/kernel/trace/trace.c +++ b/kernel/trace/trace.c @@ -1456,6 +1456,13 @@ static void free_tracers(struct trace_array *tr) } } +static void free_tracer_options(struct trace_array *tr) +{ + for (int i = 0; i < tr->nr_topts; i++) + kfree(tr->topts[i].topts); + kfree(tr->topts); +} + /** * register_tracer - register a tracer with the ftrace system. * @type: the plugin for the tracer @@ -1879,7 +1886,8 @@ trace_event_buffer_lock_reserve(struct trace_buffer **current_rb, *current_rb = tr->array_buffer.buffer; if (!tr->no_filter_buffering_ref && - (trace_file->flags & (EVENT_FILE_FL_SOFT_DISABLED | EVENT_FILE_FL_FILTERED))) { + (READ_ONCE(trace_file->flags) & + (EVENT_FILE_FL_SOFT_DISABLED | EVENT_FILE_FL_FILTERED))) { preempt_disable_notrace(); /* * Filtering is on, so try to use the per cpu buffer first. @@ -1940,7 +1948,7 @@ trace_event_buffer_lock_reserve(struct trace_buffer **current_rb, * to store the trace event for the trigger to use. It's recursive * safe and will not be recorded anywhere. */ - if (!entry && trace_file->flags & EVENT_FILE_FL_TRIGGER_COND) { + if (!entry && (READ_ONCE(trace_file->flags) & EVENT_FILE_FL_TRIGGER_COND)) { *current_rb = temp_buffer; entry = __trace_buffer_lock_reserve(*current_rb, type, len, trace_ctx); @@ -1971,7 +1979,7 @@ static void output_printk(struct trace_event_buffer *fbuffer) file = fbuffer->trace_file; if (test_bit(EVENT_FILE_FL_SOFT_DISABLED_BIT, &file->flags) || - (unlikely(file->flags & EVENT_FILE_FL_FILTERED) && + (unlikely(test_bit(EVENT_FILE_FL_FILTERED_BIT, &file->flags)) && !filter_match_preds(file->filter, fbuffer->entry))) return; @@ -4028,7 +4036,9 @@ int set_tracer_flag(struct trace_array *tr, u64 mask, int enabled) break; case TRACE_ITER(COPY_MARKER): - update_marker_trace(tr, enabled); + /* Writers of the top level trace_marker may still be on this instance */ + if (update_marker_trace(tr, enabled) && !enabled) + synchronize_rcu(); /* update_marker_trace updates the tr->trace_flags */ return 0; } @@ -6289,7 +6299,7 @@ char *trace_user_fault_read(struct trace_user_buf_info *tinfo, if (copy_func) { ret = copy_func(buffer, ptr, size, data); } else { - ret = __copy_from_user(buffer, ptr, size); + ret = copy_from_user(buffer, ptr, size); } preempt_disable_notrace(); @@ -6345,9 +6355,10 @@ tracing_mark_write(struct file *filp, const char __user *ubuf, if (tr == &global_trace) { guard(rcu)(); list_for_each_entry_rcu(tr, &marker_copies, marker_list) { - written = write_marker_to_buffer(tr, buf, cnt, ip); - if (written < 0) - break; + ssize_t w = write_marker_to_buffer(tr, buf, cnt, ip); + + if (w >= 0 && w > written) + written = w; } } else { written = write_marker_to_buffer(tr, buf, cnt, ip); @@ -6424,9 +6435,10 @@ tracing_mark_raw_write(struct file *filp, const char __user *ubuf, if (tr == &global_trace) { guard(rcu)(); list_for_each_entry_rcu(tr, &marker_copies, marker_list) { - written = write_raw_marker_to_buffer(tr, buf, cnt); - if (written < 0) - break; + ssize_t w = write_raw_marker_to_buffer(tr, buf, cnt); + + if (w >= 0 && w > written) + written = w; } } else { written = write_raw_marker_to_buffer(tr, buf, cnt); @@ -7404,8 +7416,12 @@ static long tracing_buffers_ioctl(struct file *file, unsigned int cmd, unsigned return err; } - return ring_buffer_map_get_reader(iter->array_buffer->buffer, - iter->cpu_file); + trace_access_lock(iter->cpu_file); + err = ring_buffer_map_get_reader(iter->array_buffer->buffer, + iter->cpu_file); + trace_access_unlock(iter->cpu_file); + + return err; } else if (cmd) { return -ENOTTY; } @@ -8761,7 +8777,7 @@ trace_array_create_systems(const char *name, const char *systems, if (trace_instance_dir) { ret = trace_array_create_dir(tr); if (ret) - goto out_free_tr; + goto out_free_tracers; } else __trace_early_add_events(tr); @@ -8771,6 +8787,9 @@ trace_array_create_systems(const char *name, const char *systems, return tr; + out_free_tracers: + free_tracers(tr); + free_tracer_options(tr); out_free_tr: ftrace_free_ftrace_ops(tr); free_trace_buffers(tr); @@ -8924,10 +8943,7 @@ static int __remove_instance(struct trace_array *tr) if (tr->flags & TRACE_ARRAY_FL_VMALLOC) vfree((void *)tr->range_addr_start); - for (i = 0; i < tr->nr_topts; i++) { - kfree(tr->topts[i].topts); - } - kfree(tr->topts); + free_tracer_options(tr); free_cpumask_var(tr->pipe_cpumask); free_cpumask_var(tr->tracing_cpumask); diff --git a/kernel/trace/trace.h b/kernel/trace/trace.h index 0635503a31dd75..32997b58a8a0a4 100644 --- a/kernel/trace/trace.h +++ b/kernel/trace/trace.h @@ -1729,24 +1729,26 @@ __event_trigger_test_discard(struct trace_event_file *file, void *entry, enum event_trigger_type *tt) { - unsigned long eflags = file->flags; + unsigned long eflags = READ_ONCE(file->flags); - if (eflags & EVENT_FILE_FL_TRIGGER_COND) + if (eflags & EVENT_FILE_FL_TRIGGER_COND) { *tt = event_triggers_call(file, buffer, entry, event); + eflags = READ_ONCE(file->flags); + } - if (likely(!(file->flags & (EVENT_FILE_FL_SOFT_DISABLED | - EVENT_FILE_FL_FILTERED | - EVENT_FILE_FL_PID_FILTER)))) + if (likely(!(eflags & (EVENT_FILE_FL_SOFT_DISABLED | + EVENT_FILE_FL_FILTERED | + EVENT_FILE_FL_PID_FILTER)))) return false; - if (file->flags & EVENT_FILE_FL_SOFT_DISABLED) + if (eflags & EVENT_FILE_FL_SOFT_DISABLED) goto discard; - if (file->flags & EVENT_FILE_FL_FILTERED && + if (eflags & EVENT_FILE_FL_FILTERED && !filter_match_preds(file->filter, entry)) goto discard; - if ((file->flags & EVENT_FILE_FL_PID_FILTER) && + if ((eflags & EVENT_FILE_FL_PID_FILTER) && trace_event_ignore_this_pid(file)) goto discard; @@ -1807,7 +1809,6 @@ enum regex_type { MATCH_MIDDLE_ONLY, MATCH_END_ONLY, MATCH_GLOB, - MATCH_INDEX, }; struct regex { @@ -1912,9 +1913,11 @@ extern const struct file_operations event_inject_fops; #ifdef CONFIG_HIST_TRIGGERS extern int register_trigger_hist_cmd(void); extern int register_trigger_hist_enable_disable_cmds(void); +extern void hist_put_synth_event(struct trace_event_file *file); #else static inline int register_trigger_hist_cmd(void) { return 0; } static inline int register_trigger_hist_enable_disable_cmds(void) { return 0; } +static inline void hist_put_synth_event(struct trace_event_file *file) { } #endif extern int register_trigger_cmds(void); diff --git a/kernel/trace/trace_events.c b/kernel/trace/trace_events.c index 49d135bc2fbfcc..394d7cde1a7031 100644 --- a/kernel/trace/trace_events.c +++ b/kernel/trace/trace_events.c @@ -707,7 +707,7 @@ void *trace_event_buffer_reserve(struct trace_event_buffer *fbuffer, { struct trace_event_call *event_call = trace_file->event_call; - if ((trace_file->flags & EVENT_FILE_FL_PID_FILTER) && + if (test_bit(EVENT_FILE_FL_PID_FILTER_BIT, &trace_file->flags) && trace_event_ignore_this_pid(trace_file)) return NULL; @@ -4317,7 +4317,7 @@ static void update_event_probe(struct event_probe_data *data) set_bit(EVENT_FILE_FL_SOFT_DISABLED_BIT, &data->file->flags); } -static void +static void notrace event_enable_probe(unsigned long ip, unsigned long parent_ip, struct trace_array *tr, struct ftrace_probe_ops *ops, void *data) @@ -4334,7 +4334,7 @@ event_enable_probe(unsigned long ip, unsigned long parent_ip, update_event_probe(edata); } -static void +static void notrace event_enable_count_probe(unsigned long ip, unsigned long parent_ip, struct trace_array *tr, struct ftrace_probe_ops *ops, void *data) @@ -5026,8 +5026,8 @@ void __init trace_event_init(void) { event_trace_memsetup(); init_ftrace_syscalls(); - event_trace_enable(); event_trace_init_fields(); + event_trace_enable(); } #ifdef CONFIG_EVENT_TRACE_STARTUP_TEST @@ -5205,7 +5205,7 @@ static DEFINE_PER_CPU(atomic_t, ftrace_test_event_disable); static struct trace_event_file event_trace_file __initdata; -static void __init +static void notrace __init function_test_events_call(unsigned long ip, unsigned long parent_ip, struct ftrace_ops *op, struct ftrace_regs *regs) { diff --git a/kernel/trace/trace_events_filter.c b/kernel/trace/trace_events_filter.c index c10951bcfc5f14..b3ac2519a62d16 100644 --- a/kernel/trace/trace_events_filter.c +++ b/kernel/trace/trace_events_filter.c @@ -758,7 +758,7 @@ static int filter_pred_##size##_cpumask(struct filter_pred *pred, void *event) \ unsigned int cpu = *addr; \ \ if (cpu >= nr_cpu_ids) \ - return 0; \ + return pred->op == OP_NE; \ \ return do_filter_scalar_cpumask(pred->op, cpu, pred->mask); \ } @@ -891,6 +891,25 @@ static int filter_pred_pchar_user(struct filter_pred *pred, void *event) return filter_pchar(pred, str); } +static __always_inline int filter_dyn_string(struct filter_pred *pred, + char *str, int len) +{ + int cmp; + + /* + * The regex callbacks use zero for an unknown-length, NUL-terminated + * string. A zero-length data_loc or rel_loc field has no bytes at all. + * Match an empty string instead of reading past the end of the field. + */ + if (!len) { + str = ""; + len = 1; + } + + cmp = pred->regex->match(str, pred->regex, len); + return cmp ^ pred->not; +} + /* * Filter predicate for dynamic sized arrays of characters. * These are implemented through a list of strings at the end @@ -907,13 +926,8 @@ static int filter_pred_strloc(struct filter_pred *pred, void *event) int str_loc = str_item & 0xffff; int str_len = str_item >> 16; char *addr = (char *)(event + str_loc); - int cmp, match; - cmp = pred->regex->match(addr, pred->regex, str_len); - - match = cmp ^ pred->not; - - return match; + return filter_dyn_string(pred, addr, str_len); } /* @@ -930,13 +944,8 @@ static int filter_pred_strrelloc(struct filter_pred *pred, void *event) int str_loc = str_item & 0xffff; int str_len = str_item >> 16; char *addr = (char *)(&item[1]) + str_loc; - int cmp, match; - - cmp = pred->regex->match(addr, pred->regex, str_len); - match = cmp ^ pred->not; - - return match; + return filter_dyn_string(pred, addr, str_len); } /* Filter predicate for CPUs. */ @@ -1037,7 +1046,8 @@ static int filter_pred_within(struct filter_pred *pred, void *event) * * @str: the string to be searched * @r: the regex structure containing the pattern string - * @len: the length of the string to be searched (including '\0') + * @len: the length of the string to be searched (including '\0'), or zero + * for a NUL-terminated string of unknown length * * Note: * - @str might not be NULL-terminated if it's of type DYN_STRING @@ -1046,7 +1056,7 @@ static int filter_pred_within(struct filter_pred *pred, void *event) static int regex_match_full(char *str, struct regex *r, int len) { - /* len of zero means str is dynamic and ends with '\0' */ + /* Zero is reserved for a NUL-terminated string of unknown length. */ if (!len) return strcmp(str, r->pattern) == 0; @@ -1082,6 +1092,30 @@ static int regex_match_end(char *str, struct regex *r, int len) return 0; } +static int regex_match_end_str(char *str, struct regex *r, int len) +{ + int slen; + + if (len < r->len) + return 0; + + slen = strnlen(str, len); + if (slen >= r->len && + memcmp(str + slen - r->len, r->pattern, r->len) == 0) + return 1; + return 0; +} + +static int regex_match_end_dynstr(char *str, struct regex *r, int len) +{ + int slen = strlen(str); + + if (slen >= r->len && + memcmp(str + slen - r->len, r->pattern, r->len) == 0) + return 1; + return 0; +} + static int regex_match_glob(char *str, struct regex *r, int len) { return glob_match_len(r->pattern, str, len) ? 1 : 0; @@ -1118,9 +1152,6 @@ enum regex_type filter_parse_regex(char *buff, int len, char **search, int *not) *search = buff; - if (isdigit(buff[0])) - return MATCH_INDEX; - for (i = 0; i < len; i++) { if (buff[i] == '*') { if (!i) { @@ -1158,8 +1189,6 @@ static void filter_build_regex(struct filter_pred *pred) } switch (type) { - /* MATCH_INDEX should not happen, but if it does, match full */ - case MATCH_INDEX: case MATCH_FULL: r->match = regex_match_full; break; @@ -1320,11 +1349,7 @@ static void free_prog(struct event_filter *filter) static void filter_disable(struct trace_event_file *file) { - unsigned long old_flags = file->flags; - - file->flags &= ~EVENT_FILE_FL_FILTERED; - - if (old_flags != file->flags) + if (test_and_clear_bit(EVENT_FILE_FL_FILTERED_BIT, &file->flags)) trace_buffered_event_disable(); } @@ -1708,7 +1733,9 @@ static int parse_pred(const char *str, void *data, /* See if the field is a kernel function name */ if ((len = str_has_prefix(str + i, ".function"))) { - function = true; + /* Ignore if event is already a function */ + if (!ftrace_event_is_function(call)) + function = true; i += len; } @@ -1732,6 +1759,11 @@ static int parse_pred(const char *str, void *data, while (isspace(str[i])) i++; + if (!str[i]) { + parse_error(pe, FILT_ERR_INVALID_FILTER, pos + i); + goto err_free; + } + s = i; pred = kzalloc_obj(*pred); @@ -2021,10 +2053,18 @@ static int parse_pred(const char *str, void *data, if (field->filter_type == FILTER_COMM) { pred->fn_num = FILTER_PRED_FN_COMM; + if (pred->regex->match == regex_match_end) + pred->regex->match = regex_match_end_str; } else if (field->filter_type == FILTER_STATIC_STRING) { pred->fn_num = FILTER_PRED_FN_STRING; pred->regex->field_len = field->size; + if (pred->regex->match == regex_match_end) { + if (!field->size) + pred->regex->match = regex_match_end_dynstr; + else + pred->regex->match = regex_match_end_str; + } } else if (field->filter_type == FILTER_DYN_STRING) { pred->fn_num = FILTER_PRED_FN_STRLOC; @@ -2287,11 +2327,7 @@ static int process_preds(struct trace_event_call *call, static inline void event_set_filtered_flag(struct trace_event_file *file) { - unsigned long old_flags = file->flags; - - file->flags |= EVENT_FILE_FL_FILTERED; - - if (old_flags != file->flags) + if (!test_and_set_bit(EVENT_FILE_FL_FILTERED_BIT, &file->flags)) trace_buffered_event_enable(); } @@ -2305,6 +2341,7 @@ static int process_system_preds(struct trace_subsystem_dir *dir, struct event_filter *filter = NULL; struct filter_head *filter_list; bool fail = true; + int ret = -ENOMEM; int err; filter_list = kmalloc_obj(*filter_list); @@ -2331,9 +2368,10 @@ static int process_system_preds(struct trace_subsystem_dir *dir, filter_disable(file); parse_error(pe, FILT_ERR_BAD_SUBSYS_FILTER, 0); append_filter_err(tr, pe, filter); - } else + } else { event_set_filtered_flag(file); - + fail = false; + } filter_item = kzalloc_obj(*filter_item); if (!filter_item) @@ -2347,8 +2385,6 @@ static int process_system_preds(struct trace_subsystem_dir *dir, filter_item->filter = event_filter(file); event_set_filter(file, filter); filter = NULL; - - fail = false; } if (fail) @@ -2363,19 +2399,18 @@ static int process_system_preds(struct trace_subsystem_dir *dir, return 0; fail: /* No call succeeded */ - free_filter_list(filter_list); parse_error(pe, FILT_ERR_BAD_SUBSYS_FILTER, 0); - return -EINVAL; + ret = -EINVAL; fail_mem: __free_filter(filter); - /* If any call succeeded, we still need to sync */ - if (!fail) + /* If any filter was replaced, we still need to sync */ + if (!list_empty(&filter_list->list)) delay_free_filter(filter_list); else free_filter_list(filter_list); - return -ENOMEM; + return ret; } static int create_filter_start(char *filter_string, bool set_str, @@ -2749,6 +2784,28 @@ static int ftrace_function_set_filter(struct perf_event *event, } #endif /* CONFIG_FUNCTION_TRACER */ +static int ftrace_profile_filter_perm(struct event_filter *filter) +{ + struct prog_entry *prog = rcu_dereference_protected(filter->prog, + lockdep_is_held(&event_mutex)); + int i, err; + + for (i = 0; prog[i].pred; i++) { + if (prog[i].pred->fn_num != FILTER_PRED_FN_PCHAR) + continue; + + /* + * Even a counting filter can reveal kernel string data. + * Require the same access as raw kernel tracepoints. + */ + err = perf_allow_kernel(); + if (err) + return err; + return perf_allow_tracepoint(); + } + return 0; +} + int ftrace_profile_set_filter(struct perf_event *event, int event_id, char *filter_str) { @@ -2770,6 +2827,10 @@ int ftrace_profile_set_filter(struct perf_event *event, int event_id, if (err) goto free_filter; + err = ftrace_profile_filter_perm(filter); + if (err) + goto free_filter; + if (ftrace_event_is_function(call)) err = ftrace_function_set_filter(event, filter); else @@ -2789,6 +2850,8 @@ int ftrace_profile_set_filter(struct perf_event *event, int event_id, #include #include +#include "trace_probe.h" + #define CREATE_TRACE_POINTS #include "trace_events_filter_test.h" @@ -2800,12 +2863,22 @@ int ftrace_profile_set_filter(struct perf_event *event, int event_id, .match = m, \ .not_visited = nvisit, \ } + +#define DATA_STR(m, s) \ +{ \ + .filter = FILTER, \ + .str = s, \ + .match = m, \ + .not_visited = "", \ +} + #define YES 1 #define NO 0 static struct test_filter_data_t { char *filter; struct trace_event_raw_ftrace_test_filter rec; + const char *str; int match; char *not_visited; } test_filter_data[] = { @@ -2857,9 +2930,46 @@ static struct test_filter_data_t { DATA_REC(YES, 1, 1, 1, 1, 1, 1, 1, 1, "bdfh"), DATA_REC(YES, 0, 1, 0, 1, 0, 1, 0, 1, ""), DATA_REC(YES, 1, 0, 1, 0, 1, 0, 1, 0, "bdfh"), +#undef FILTER +#define FILTER "str ~ \"0001:*\"" + DATA_STR(YES, "0001:01:00.0"), + DATA_STR(YES, "0001:"), + DATA_STR(NO, "0002:01:00.0"), + DATA_STR(NO, "pci:0001:01:00.0"), + DATA_STR(NO, "0001"), +#undef FILTER +#define FILTER "str ~ \"!0001:*\"" + DATA_STR(NO, "0001:01:00.0"), + DATA_STR(YES, "0002:01:00.0"), +#undef FILTER +#define FILTER "str ~ \"0001:*:00.[0-9]\"" + DATA_STR(YES, "0001:01:00.0"), + DATA_STR(YES, "0001:ff:00.7"), + DATA_STR(NO, "0001:01:00.a"), + DATA_STR(NO, "0002:01:00.0"), +#undef FILTER +#define FILTER "str ~ \"0001:01:00.0\"" + DATA_STR(YES, "0001:01:00.0"), + DATA_STR(NO, "0001:01:00.1"), + DATA_STR(NO, "0001:01:00.00"), + DATA_STR(NO, "0001:01:00"), +#undef FILTER +#define FILTER "str == \"0001:01:00.0\"" + DATA_STR(YES, "0001:01:00.0"), + DATA_STR(NO, "0001:01:00.1"), +#undef FILTER +#define FILTER "str ~ \"*0001:*\"" + DATA_STR(YES, "0001:01:00.0"), + DATA_STR(YES, "pci:0001:01:00.0"), + DATA_STR(NO, "0002:01:00.0"), +#undef FILTER +#define FILTER "str ~ \"*:00.0\"" + DATA_STR(YES, "0001:01:00.0"), + DATA_STR(NO, "0001:01:00.1"), }; #undef DATA_REC +#undef DATA_STR #undef FILTER #undef YES #undef NO @@ -2910,8 +3020,29 @@ static __init int ftrace_test_event_filter(void) for (i = 0; i < DATA_CNT; i++) { struct event_filter *filter = NULL; struct test_filter_data_t *d = &test_filter_data[i]; + union { + struct trace_event_raw_ftrace_test_filter rec; + /* Add some spare, to append the string contents. */ + char buf[sizeof(struct trace_event_raw_ftrace_test_filter) + 32]; + } event = { .rec = d->rec }; int err; + if (d->str) { + struct ftrace_event_field *field; + u32 offset = offsetof(typeof(event.rec), __data); + u32 len = strlen(d->str) + 1; + u32 *str_item; + + field = trace_find_event_field(&event_ftrace_test_filter, "str"); + if (WARN_ON_ONCE(!field)) + break; + if (WARN_ON_ONCE(offset + len > sizeof(event.buf))) + break; + str_item = (u32 *)&event.buf[field->offset]; + *str_item = make_data_loc(len, offset); + memcpy(&event.buf[offset], d->str, len); + } + err = create_filter(NULL, &event_ftrace_test_filter, d->filter, false, &filter); if (err) { @@ -2933,7 +3064,7 @@ static __init int ftrace_test_event_filter(void) update_pred_fn(filter, d->not_visited); test_pred_visited = 0; - err = filter_match_preds(filter, &d->rec); + err = filter_match_preds(filter, &event.rec); preempt_enable(); mutex_unlock(&event_mutex); @@ -2960,7 +3091,7 @@ static __init int ftrace_test_event_filter(void) /* Need to call ftrace_test_filter to prevent a warning */ if (!trace_ftrace_test_filter_enabled()) - trace_ftrace_test_filter(1, 2, 3, 4, 5, 6, 7, 8); + trace_ftrace_test_filter(1, 2, 3, 4, 5, 6, 7, 8, ""); return 0; } diff --git a/kernel/trace/trace_events_filter_test.h b/kernel/trace/trace_events_filter_test.h index e651dfbd345e63..74a9dba91545d7 100644 --- a/kernel/trace/trace_events_filter_test.h +++ b/kernel/trace/trace_events_filter_test.h @@ -9,9 +9,10 @@ TRACE_EVENT(ftrace_test_filter, - TP_PROTO(int a, int b, int c, int d, int e, int f, int g, int h), + TP_PROTO(int a, int b, int c, int d, int e, int f, int g, int h, + const char *str), - TP_ARGS(a, b, c, d, e, f, g, h), + TP_ARGS(a, b, c, d, e, f, g, h, str), TP_STRUCT__entry( __field(int, a) @@ -22,6 +23,7 @@ TRACE_EVENT(ftrace_test_filter, __field(int, f) __field(int, g) __field(int, h) + __string(str, str) ), TP_fast_assign( @@ -33,11 +35,13 @@ TRACE_EVENT(ftrace_test_filter, __entry->f = f; __entry->g = g; __entry->h = h; + __assign_str(str); ), - TP_printk("a %d, b %d, c %d, d %d, e %d, f %d, g %d, h %d", + TP_printk("a %d, b %d, c %d, d %d, e %d, f %d, g %d, h %d, str %s", __entry->a, __entry->b, __entry->c, __entry->d, - __entry->e, __entry->f, __entry->g, __entry->h) + __entry->e, __entry->f, __entry->g, __entry->h, + __get_str(str)) ); #endif /* _TRACE_TEST_H || TRACE_HEADER_MULTI_READ */ diff --git a/kernel/trace/trace_events_hist.c b/kernel/trace/trace_events_hist.c index 1aae7d7c6dc54e..d4702ad4e0036a 100644 --- a/kernel/trace/trace_events_hist.c +++ b/kernel/trace/trace_events_hist.c @@ -1430,6 +1430,11 @@ static int parse_map_size(char *str) if (ret) goto out; + if (!size) { + ret = -EINVAL; + goto out; + } + map_bits = ilog2(roundup_pow_of_two(size)); if (map_bits < TRACING_MAP_BITS_MIN || map_bits > TRACING_MAP_BITS_MAX) @@ -6761,6 +6766,17 @@ static bool hist_trigger_check_refs(struct event_trigger_data *data, return false; } +void hist_put_synth_event(struct trace_event_file *file) +{ + struct synth_event *se; + + lockdep_assert_held(&event_mutex); + + se = find_synth_event_call(file->event_call); + if (se) + se->ref--; +} + static void hist_unregister_trigger(char *glob, struct event_trigger_data *data, struct trace_event_file *file) @@ -6816,7 +6832,6 @@ static void hist_unreg_all(struct trace_event_file *file) { struct event_trigger_data *test, *n; struct hist_trigger_data *hist_data; - struct synth_event *se; lockdep_assert_held(&event_mutex); @@ -6829,9 +6844,7 @@ static void hist_unreg_all(struct trace_event_file *file) list_del_rcu(&test->list); trace_event_trigger_enable_disable(file, 0); - se = find_synth_event_call(file->event_call); - if (se) - se->ref--; + hist_put_synth_event(file); update_cond_flag(file); if (hist_data->enable_timestamps) @@ -6946,9 +6959,7 @@ static int event_hist_trigger_parse(struct event_command *cmd_ops, } event_trigger_unregister(cmd_ops, file, glob+1, trigger_data); - se = find_synth_event_call(file->event_call); - if (se) - se->ref--; + hist_put_synth_event(file); ret = 0; goto out_free; } diff --git a/kernel/trace/trace_events_trigger.c b/kernel/trace/trace_events_trigger.c index 4d2fde996c0f6c..96203ba72ab976 100644 --- a/kernel/trace/trace_events_trigger.c +++ b/kernel/trace/trace_events_trigger.c @@ -214,7 +214,7 @@ EXPORT_SYMBOL_GPL(event_triggers_call); bool __trace_trigger_soft_disabled(struct trace_event_file *file) { - unsigned long eflags = file->flags; + unsigned long eflags = READ_ONCE(file->flags); if (eflags & EVENT_FILE_FL_TRIGGER_MODE) event_triggers_call(file, NULL, NULL, NULL); @@ -643,6 +643,8 @@ clear_event_triggers(struct trace_array *tr) list_for_each_entry_safe(data, n, &file->triggers, list) { trace_event_trigger_enable_disable(file, 0); list_del_rcu(&data->list); + if (data->cmd_ops->trigger_type == ETT_EVENT_HIST) + hist_put_synth_event(file); if (data->cmd_ops->free) data->cmd_ops->free(data); } @@ -1690,7 +1692,8 @@ event_enable_count_func(struct event_trigger_data *data, return false; /* Skip if the event is in a state we want to switch to */ - if (enable_data->enable == !(enable_data->file->flags & EVENT_FILE_FL_SOFT_DISABLED)) + if (enable_data->enable == !test_bit(EVENT_FILE_FL_SOFT_DISABLED_BIT, + &enable_data->file->flags)) return false; if (data->count != -1) diff --git a/kernel/trace/trace_events_user.c b/kernel/trace/trace_events_user.c index f658c3a77aa7a1..c561443f794703 100644 --- a/kernel/trace/trace_events_user.c +++ b/kernel/trace/trace_events_user.c @@ -256,6 +256,11 @@ static void delayed_destroy_user_event(struct work_struct *work) * attempt to delete it later. */ pr_warn("user_events: Unable to delete event\n"); + /* + * Keep it as persistent so it can be still deleted + * since nobody own this event + */ + user->reg_flags |= USER_EVENT_REG_PERSIST; refcount_set(&user->refcnt, 1); } out: @@ -863,7 +868,7 @@ void user_event_mm_remove(struct task_struct *t) queue_rcu_work(system_percpu_wq, &mm->put_rwork); } -void user_event_mm_dup(struct task_struct *t, struct user_event_mm *old_mm) +int user_event_mm_dup(struct task_struct *t, struct user_event_mm *old_mm) { struct user_event_mm *mm = user_event_mm_alloc(t); struct user_event_enabler *enabler; @@ -872,7 +877,7 @@ void user_event_mm_dup(struct task_struct *t, struct user_event_mm *old_mm) t->user_event_mm = NULL; if (!mm) - return; + return -ENOMEM; rcu_read_lock(); @@ -884,10 +889,12 @@ void user_event_mm_dup(struct task_struct *t, struct user_event_mm *old_mm) rcu_read_unlock(); user_event_mm_attach(mm, t); - return; + return 0; error: rcu_read_unlock(); user_event_mm_destroy(mm); + + return -ENOMEM; } static bool current_user_event_enabler_exists(unsigned long uaddr, @@ -1035,6 +1042,9 @@ static int user_event_parse_cmd(struct user_event_group *group, if (flags) *flags++ = '\0'; + if (strstr(name, "/") != NULL) + return -EINVAL; + return user_event_parse(group, name, args, flags, newuser, reg_flags); } @@ -1506,6 +1516,10 @@ static int destroy_user_event(struct user_event *user) lockdep_assert_held(&event_mutex); + /* If there is a reference to a dynamic event */ + if (trace_event_dyn_busy(&user->call)) + return -EBUSY; + /* * Detach the fields before removing the call. Removing the event * frees the field list memory (trace_destroy_fields() is run on diff --git a/kernel/trace/trace_hwlat.c b/kernel/trace/trace_hwlat.c index 3fe274b84f1c2e..5be9031f1ffe30 100644 --- a/kernel/trace/trace_hwlat.c +++ b/kernel/trace/trace_hwlat.c @@ -203,14 +203,12 @@ static int get_sample(void) time_type start, t1, t2, last_t2; s64 diff, outer_diff, total, last_total = 0; u64 sample = 0; - u64 sample_width = READ_ONCE(hwlat_data.sample_width); + u64 sample_width = READ_ONCE(hwlat_data.sample_width) * NSEC_PER_USEC; u64 thresh = tracing_thresh; u64 outer_sample = 0; - int ret = -1; + int ret = 0; unsigned int count = 0; - do_div(thresh, NSEC_PER_USEC); /* modifies interval value */ - kdata->nmi_total_ts = 0; kdata->nmi_count = 0; /* Make sure NMIs see this first */ @@ -229,28 +227,37 @@ static int get_sample(void) if (time_u64(last_t2)) { /* Check the delta from outer loop (t2 to next t1) */ - outer_diff = time_to_us(time_sub(t1, last_t2)); + outer_diff = time_sub(t1, last_t2); /* This shouldn't happen */ if (outer_diff < 0) { hwlat_err(BANNER "time running backwards\n"); - goto out; + ret = -1; + break; } if (outer_diff > outer_sample) outer_sample = outer_diff; } last_t2 = t2; - total = time_to_us(time_sub(t2, start)); /* sample width */ + total = time_sub(t2, start); /* sample width */ /* Check for possible overflows */ if (total < last_total) { hwlat_err("Time total overflowed\n"); + /* Keep ret == 0 to preserve any latencies already detected */ break; } last_total = total; /* This checks the inner loop (t1 to t2) */ - diff = time_to_us(time_sub(t2, t1)); /* current diff */ + diff = time_sub(t2, t1); /* current diff */ + + /* This shouldn't happen: time went backwards between t1 and t2 */ + if (diff < 0) { + hwlat_err(BANNER "time running backwards\n"); + ret = -1; + break; + } if (diff > thresh || outer_diff > thresh) { if (!count) @@ -258,12 +265,6 @@ static int get_sample(void) count++; } - /* This shouldn't happen */ - if (diff < 0) { - hwlat_err(BANNER "time running backwards\n"); - goto out; - } - if (diff > sample) sample = diff; /* only want highest value */ @@ -273,10 +274,11 @@ static int get_sample(void) trace_hwlat_callback_enabled = false; barrier(); /* Make sure nmi_total_ts is no longer updated */ - ret = 0; + if (ret) + return ret; /* If we exceed the threshold value, we have found a hardware latency */ - if (sample > thresh || outer_sample > thresh) { + if (count) { u64 latency; ret = 1; @@ -286,8 +288,8 @@ static int get_sample(void) do_div(kdata->nmi_total_ts, NSEC_PER_USEC); s.seqnum = atomic64_inc_return(&hwlat_data.count); - s.duration = sample; - s.outer_duration = outer_sample; + s.duration = time_to_us(sample); + s.outer_duration = time_to_us(outer_sample); s.nmi_total_ts = kdata->nmi_total_ts; s.nmi_count = kdata->nmi_count; s.count = count; @@ -301,8 +303,6 @@ static int get_sample(void) latency_fsnotify(tr); } } - -out: return ret; } @@ -835,7 +835,6 @@ static int hwlat_tracer_init(struct trace_array *tr) tr->max_latency = 0; save_tracing_thresh = tracing_thresh; - /* tracing_thresh is in nsecs, we speak in usecs */ if (!tracing_thresh) tracing_thresh = last_tracing_thresh; diff --git a/kernel/trace/trace_osnoise.c b/kernel/trace/trace_osnoise.c index 995da9e0b548af..fbba422867474b 100644 --- a/kernel/trace/trace_osnoise.c +++ b/kernel/trace/trace_osnoise.c @@ -2039,6 +2039,14 @@ static int start_kthread(unsigned int cpu) return 0; if (timerlat_enabled()) { + /* + * In timerlat user-space mode the workload is the user task + * reading timerlat_fd, so there is no kernel thread to start. + * One started here would set its kthread_cpumask bit, which + * stop_kthread() reads as "osnoise workload kthread". + */ + if (!test_bit(OSN_WORKLOAD, &osnoise_options)) + return 0; snprintf(comm, 24, "timerlat/%d", cpu); main = timerlat_main; } else { diff --git a/kernel/trace/trace_probe_tmpl.h b/kernel/trace/trace_probe_tmpl.h index 8acc0f0ebd7a6b..b9fd2f61a0ca73 100644 --- a/kernel/trace/trace_probe_tmpl.h +++ b/kernel/trace/trace_probe_tmpl.h @@ -96,7 +96,8 @@ fetch_store_symstring(unsigned long addr, void *dest, void *base) return -ENOMEM; __dest = get_loc_data(dest, base); - len = sprint_symbol(namebuf, addr); + /* Do not dereference NULL pointers */ + len = addr ? sprint_symbol(namebuf, addr) : -1; if (len < 0) { *(u32 *)dest = make_data_loc(0, __dest - base); return 0; @@ -133,13 +134,65 @@ process_common_fetch_insn(struct fetch_insn *code, unsigned long *val) return 0; } +/* On failure, zero out the destination */ +static nokprobe_inline int +do_probe_mem_read_user(void *dest, void *src, size_t size) +{ + int ret; + + /* Do not dereference NULL pointers */ + ret = src ? probe_mem_read_user(dest, src, size) : -1; + if (ret < 0) + memset(dest, 0, size); + return ret; +} + +/* On failure, zero out the destination */ +static nokprobe_inline int +do_probe_mem_read(void *dest, void *src, size_t size) +{ + int ret; + + /* Do not dereference NULL pointers */ + ret = src ? probe_mem_read(dest, src, size) : -1; + if (ret < 0) + memset(dest, 0, size); + return ret; +} + +static nokprobe_inline int +do_fetch_store_string(unsigned long addr, void *dest, void *base) +{ + /* NULL addr gets zero size string */ + if (!addr) { + void *__dest = get_loc_data(dest, base); + + *(u32 *)dest = make_data_loc(0, __dest - base); + return 0; + } + return fetch_store_string(addr, dest, base); +} + +static nokprobe_inline int +do_fetch_store_string_user(unsigned long addr, void *dest, void *base) +{ + /* NULL addr gets zero size string */ + if (!addr) { + void *__dest = get_loc_data(dest, base); + + *(u32 *)dest = make_data_loc(0, __dest - base); + return 0; + } + return fetch_store_string_user(addr, dest, base); +} + /* From the 2nd stage, routine is same */ static nokprobe_inline int process_fetch_insn_bottom(struct fetch_insn *code, unsigned long val, void *dest, void *base) { struct fetch_insn *s3 = NULL; - int total = 0, ret = 0, i = 0; + int total = 0, ret = 0, i = 0, offset; u32 loc = 0; unsigned long lval, llval = val; @@ -147,25 +200,26 @@ process_fetch_insn_bottom(struct fetch_insn *code, unsigned long val, /* 2nd stage: dereference memory if needed */ do { lval = val; + /* Prevent dereferencing NULL val pointer */ + offset = val ? code->offset : 0; switch (code->op) { case FETCH_OP_DEREF: - ret = probe_mem_read(&val, (void *)val + code->offset, - sizeof(val)); + do_probe_mem_read(&val, (void *)val + offset, + sizeof(val)); break; case FETCH_OP_UDEREF: - ret = probe_mem_read_user(&val, - (void *)val + code->offset, sizeof(val)); + do_probe_mem_read_user(&val, (void *)val + offset, + sizeof(val)); break; case FETCH_OP_CPU_PTR: - val = (unsigned long)this_cpu_ptr((void __percpu *)val); - ret = 0; + /* Do not dereference NULL pointers */ + if (val) + val = (unsigned long)this_cpu_ptr((void __percpu *)val); break; default: lval = llval; goto out; } - if (ret) - return ret; llval = lval; code++; } while (1); @@ -175,17 +229,18 @@ process_fetch_insn_bottom(struct fetch_insn *code, unsigned long val, stage3: /* 3rd stage: store value to buffer */ if (unlikely(!dest)) { + offset = code->offset; switch (code->op) { case FETCH_OP_ST_STRING: - ret = fetch_store_strlen(val + code->offset); + ret = val ? fetch_store_strlen(val + offset) : 0; code++; goto array; case FETCH_OP_ST_USTRING: - ret = fetch_store_strlen_user(val + code->offset); + ret = val ? fetch_store_strlen_user(val + offset) : 0; code++; goto array; case FETCH_OP_ST_SYMSTR: - ret = fetch_store_symstrlen(val + code->offset); + ret = val ? fetch_store_symstrlen(val + offset) : 0; code++; goto array; default: @@ -193,27 +248,33 @@ process_fetch_insn_bottom(struct fetch_insn *code, unsigned long val, } } + /* + * Once val is zero, it is pointing to NULL. Any new dereference is + * also treated as a NULL pointer. + */ + offset = val ? code->offset : 0; + switch (code->op) { case FETCH_OP_ST_RAW: fetch_store_raw(val, code, dest); break; case FETCH_OP_ST_MEM: - probe_mem_read(dest, (void *)val + code->offset, code->size); + do_probe_mem_read(dest, (void *)val + offset, code->size); break; case FETCH_OP_ST_UMEM: - probe_mem_read_user(dest, (void *)val + code->offset, code->size); + do_probe_mem_read_user(dest, (void *)val + offset, code->size); break; case FETCH_OP_ST_STRING: loc = *(u32 *)dest; - ret = fetch_store_string(val + code->offset, dest, base); + ret = do_fetch_store_string(val + offset, dest, base); break; case FETCH_OP_ST_USTRING: loc = *(u32 *)dest; - ret = fetch_store_string_user(val + code->offset, dest, base); + ret = do_fetch_store_string_user(val + offset, dest, base); break; case FETCH_OP_ST_SYMSTR: loc = *(u32 *)dest; - ret = fetch_store_symstring(val + code->offset, dest, base); + ret = fetch_store_symstring(val + offset, dest, base); break; default: return -EILSEQ; @@ -237,11 +298,13 @@ process_fetch_insn_bottom(struct fetch_insn *code, unsigned long val, if (s3->op != FETCH_OP_ST_STRING && s3->op != FETCH_OP_ST_USTRING) { dest += s3->size; - val += s3->size; + /* Only update a non NULL val */ + if (val) + val += s3->size; goto stage3; } code--; - val = lval + sizeof(char *); + val = lval ? lval + sizeof(char *) : 0; if (dest) { dest += sizeof(u32); *(u32 *)dest = update_data_loc(loc, ret); diff --git a/kernel/trace/trace_recursion_record.c b/kernel/trace/trace_recursion_record.c index bac4bc844ccd8b..4f63bec052fca2 100644 --- a/kernel/trace/trace_recursion_record.c +++ b/kernel/trace/trace_recursion_record.c @@ -17,8 +17,8 @@ static struct recursed_functions recursed_functions[CONFIG_FTRACE_RECORD_RECURSI static atomic_t nr_records; /* - * Cache the last found function. Yes, updates to this is racey, but - * so is memory cache ;-) + * Cache the last function found in or added to recursed_functions[]. + * Updates to this are racy, but this is only a best-effort cache. */ static unsigned long cached_function; @@ -67,24 +67,25 @@ void ftrace_record_recursion(unsigned long ip, unsigned long parent_ip) } } - cached_function = ip; - /* * We only want to add a function if it hasn't been added before. - * Add to the current location before incrementing the count. - * If it fails to add, then increment the index (save in i) - * and try again. + * Claim the current slot before incrementing the count. If the slot + * is occupied by another function, advance to the next slot and retry. + * + * Do not update cached_function until ip is known to be present; + * otherwise the retry would match its own cache update. */ old = cmpxchg(&recursed_functions[index].ip, 0, ip); if (old != 0) { /* Did something else already added this for us? */ if (old == ip) return; - /* Try the next location (use i for the next index) */ + /* Try the next location */ index++; goto again; } + cached_function = ip; recursed_functions[index].parent_ip = parent_ip; /* diff --git a/kernel/trace/trace_remote.c b/kernel/trace/trace_remote.c index 2d5bc423efca58..7e35f48ae46721 100644 --- a/kernel/trace/trace_remote.c +++ b/kernel/trace/trace_remote.c @@ -1098,6 +1098,7 @@ static int remote_event_format_show(struct seq_file *s, void *unused) field = &evt->fields[0]; while (field->name) { + offset = ALIGN(offset, field->align); seq_printf(s, "\tfield:%s %s;\toffset:%zu;\tsize:%u;\tsigned:%d;\n", field->type, field->name, offset, field->size, field->is_signed); diff --git a/kernel/workqueue.c b/kernel/workqueue.c index af845214e78bfd..a2a441837a9db6 100644 --- a/kernel/workqueue.c +++ b/kernel/workqueue.c @@ -281,6 +281,7 @@ struct pool_workqueue { int total_in_flight; /* L: sum of nr_in_flight[] */ int nr_in_flight[WORK_NR_COLORS]; /* L: nr of in_flight works */ + unsigned long nr_started; /* L: see drain_workqueue() */ struct list_head flush_node; /* FN: node on wq_flush_pnode->pwqs */ bool plugged; /* L: execution suspended */ @@ -3455,6 +3456,7 @@ __acquires(&pool->lock) */ set_work_pool_and_clear_pending(work, pool->id, pool_offq_flags(pool)); + pwq->nr_started++; pwq->stats[PWQ_STAT_STARTED]++; rcu_read_lock(); @@ -4449,6 +4451,33 @@ void __flush_workqueue(struct workqueue_struct *wq) } EXPORT_SYMBOL(__flush_workqueue); +/* + * Return 0 if any pwq of @wq is busy. Otherwise, return the sum of nr_started + * of all pwqs encoded as 2 * sum + 1, which is always odd, so that 0 can only + * mean busy. + */ +static unsigned long pwqs_nr_started(struct workqueue_struct *wq) +{ + struct pool_workqueue *pwq; + unsigned long sum = 0; + + lockdep_assert_held(&wq->mutex); + + for_each_pwq(pwq, wq) { + bool empty; + + raw_spin_lock_irq(&pwq->pool->lock); + empty = pwq_is_empty(pwq); + sum += pwq->nr_started; + raw_spin_unlock_irq(&pwq->pool->lock); + + if (!empty) + return 0; + } + + return 2 * sum + 1; +} + /** * drain_workqueue - drain a workqueue * @wq: workqueue to drain @@ -4462,8 +4491,8 @@ EXPORT_SYMBOL(__flush_workqueue); */ void drain_workqueue(struct workqueue_struct *wq) { + unsigned long started; unsigned int flush_cnt = 0; - struct pool_workqueue *pwq; /* * __queue_work() needs to test whether there are drainers, is much @@ -4479,16 +4508,16 @@ void drain_workqueue(struct workqueue_struct *wq) mutex_lock(&wq->mutex); - for_each_pwq(pwq, wq) { - bool drained; - - raw_spin_lock_irq(&pwq->pool->lock); - drained = pwq_is_empty(pwq); - raw_spin_unlock_irq(&pwq->pool->lock); - - if (drained) - continue; - + /* + * A pass isn't atomic across pwqs, so a chained work item can land on + * a pwq it already found empty. Anything slipping past the second pass + * needs a work item that was in flight at its pwq's first check, or + * that started between its pwq's two checks. The first makes the first + * pass fail, the second changes nr_started. wq->mutex keeps the set of + * pwqs stable across both passes. + */ + started = pwqs_nr_started(wq); + if (!started || pwqs_nr_started(wq) != started) { if (++flush_cnt == 10 || (flush_cnt % 100 == 0 && flush_cnt <= 1000)) pr_warn("workqueue %s: %s() isn't complete after %u tries\n", @@ -7195,6 +7224,14 @@ int workqueue_online_cpu(unsigned int cpu) mutex_unlock(&wq_pool_attach_mutex); } + /* + * Before topology initialization, the SYSTEM pod covers all possible + * CPUs, so CPU onlining does not require updating pwq mappings. + * wq_update_node_max_active() also returns early at this stage. + */ + if (!wq_topo_initialized) + goto out_unlock; + /* update pod affinity of unbound workqueues */ list_for_each_entry(wq, &workqueues, list) { struct workqueue_attrs *attrs = wq->attrs; @@ -7212,6 +7249,7 @@ int workqueue_online_cpu(unsigned int cpu) } } +out_unlock: mutex_unlock(&wq_pool_mutex); return 0; } diff --git a/lib/assoc_array.c b/lib/assoc_array.c index b6c9723e12ced5..f19888ec3e0931 100644 --- a/lib/assoc_array.c +++ b/lib/assoc_array.c @@ -470,33 +470,32 @@ static bool assoc_array_insert_in_empty_tree(struct assoc_array_edit *edit) } /* - * Handle insertion into a terminal node. + * The pointer that leads to a node or shortcut with the given back pointer + * and parent slot: the root, a slot in a node, or a shortcut's next node. */ -static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit, - const struct assoc_array_ops *ops, - const void *index_key, - struct assoc_array_walk_result *result) +static struct assoc_array_ptr **assoc_array_parent_link(struct assoc_array *array, + struct assoc_array_ptr *back_pointer, + int parent_slot) { - struct assoc_array_shortcut *shortcut, *new_s0; - struct assoc_array_node *node, *new_n0, *new_n1, *side; - struct assoc_array_ptr *ptr; - unsigned long dissimilarity, base_seg, blank; - size_t keylen; - bool have_meta; - int level, diff; - int slot, next_slot, free_slot, i, j; - - node = result->terminal_node.node; - level = result->terminal_node.level; - edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = result->terminal_node.slot; + if (!back_pointer) + return &array->root; + if (assoc_array_ptr_is_node(back_pointer)) + return &assoc_array_ptr_to_node(back_pointer)->slots[parent_slot]; + return &assoc_array_ptr_to_shortcut(back_pointer)->next_node; +} - pr_devel("-->%s()\n", __func__); +/* + * Insert into a terminal node without changing its shape, if that can be + * done: in place of a leaf with the same index key, or in a free slot. + */ +static bool assoc_array_insert_in_node(struct assoc_array_edit *edit, + const struct assoc_array_ops *ops, + const void *index_key, + struct assoc_array_node *node) +{ + struct assoc_array_ptr *ptr; + int free_slot, i; - /* We arrived at a node which doesn't have an onward node or shortcut - * pointer that we have to follow. This means that (a) the leaf we - * want must go here (either by insertion or replacement) or (b) we - * need to split this node and insert in one of the fragments. - */ free_slot = -1; /* Firstly, we have to check the leaves in this node to see if there's @@ -514,7 +513,6 @@ static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit, pr_devel("replace in slot %d\n", i); edit->leaf_p = &node->slots[i]; edit->dead_leaf = node->slots[i]; - pr_devel("<--%s() = ok [replace]\n", __func__); return true; } } @@ -526,28 +524,28 @@ static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit, pr_devel("insert in free slot %d\n", free_slot); edit->leaf_p = &node->slots[free_slot]; edit->adjust_count_on = node; - pr_devel("<--%s() = ok [insert]\n", __func__); return true; } - /* The node has no spare slots - so we're either going to have to split - * it or insert another node before it. - * - * Whatever, we're going to need at least two new nodes - so allocate - * those now. We may also need a new shortcut, but we deal with that - * when we need it. - */ - new_n0 = kzalloc_obj(struct assoc_array_node); - if (!new_n0) - return false; - edit->new_meta[0] = assoc_array_node_to_ptr(new_n0); - new_n1 = kzalloc_obj(struct assoc_array_node); - if (!new_n1) - return false; - edit->new_meta[1] = assoc_array_node_to_ptr(new_n1); + return false; +} + +/* + * Fill in the edit script's segment cache for a full node: the segment at + * this level of each leaf's index key, or 0xff for a metadata pointer. + * The new key's segment, in the last entry, is left to the caller. Returns + * true if there are any metadata pointers. + */ +static bool assoc_array_fill_segment_cache(struct assoc_array_edit *edit, + const struct assoc_array_ops *ops, + const struct assoc_array_node *node, + int level) +{ + struct assoc_array_ptr *ptr; + unsigned long base_seg; + bool have_meta; + int i; - /* We need to find out how similar the leaves are. */ - pr_devel("no spare slots\n"); have_meta = false; for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { ptr = node->slots[i]; @@ -561,65 +559,42 @@ static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit, base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK; edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK; } + return have_meta; +} - if (have_meta) { - pr_devel("have meta\n"); - goto split_node; - } - - /* The node contains only leaves */ - dissimilarity = 0; - base_seg = edit->segment_cache[0]; - for (i = 1; i < ASSOC_ARRAY_FAN_OUT; i++) - dissimilarity |= edit->segment_cache[i] ^ base_seg; - - pr_devel("only leaves; dissimilarity=%lx\n", dissimilarity); +/* + * Whether the leaves of a full node and the new key all share one segment, + * so that splitting the node cannot make room. + */ +static bool assoc_array_all_one_segment(const struct assoc_array_edit *edit) +{ + int i; - if ((dissimilarity & ASSOC_ARRAY_FAN_MASK) == 0) { - /* The old leaves all cluster in the same slot. We will need - * to insert a shortcut if the new node wants to cluster with them. - */ - if ((edit->segment_cache[ASSOC_ARRAY_FAN_OUT] ^ base_seg) == 0) - goto all_leaves_cluster_together; + for (i = 1; i < ASSOC_ARRAY_FAN_OUT + 1; i++) + if (edit->segment_cache[i] != edit->segment_cache[0]) + return false; + return true; +} - /* Otherwise all the old leaves cluster in the same slot, but - * the new leaf wants to go into a different slot - so we - * create a new node (n0) to hold the new leaf and a pointer to - * a new node (n1) holding all the old leaves. - * - * This can be done by falling through to the node splitting - * path. - */ - pr_devel("present leaves cluster but not new leaf\n"); - } +/* + * Split a full node into new_n0, which takes its place, and new_n1, below + * new_n0 in the slot of a segment that at least two of the leaves share, + * the new one included. The caller has filled in the segment cache and + * set new_n0's back pointer and parent slot. + */ +static void assoc_array_split_node(struct assoc_array_edit *edit, + struct assoc_array_node *node, + struct assoc_array_node *new_n0, + struct assoc_array_node *new_n1) +{ + struct assoc_array_shortcut *shortcut; + struct assoc_array_node *side; + struct assoc_array_ptr *ptr; + int slot, next_slot, free_slot, i, j; -split_node: pr_devel("split node\n"); - /* We need to split the current node. The node must contain anything - * from a single leaf (in the one leaf case, this leaf will cluster - * with the new leaf) and the rest meta-pointers, to all leaves, some - * of which may cluster. - * - * It won't contain the case in which all the current leaves plus the - * new leaves want to cluster in the same slot. - * - * We need to expel at least two leaves out of a set consisting of the - * leaves in the node and the new leaf. The current meta pointers can - * just be copied as they shouldn't cluster with any of the leaves. - * - * We need a new node (n0) to replace the current one and a new node to - * take the expelled nodes (n1). - */ - edit->set[0].to = assoc_array_node_to_ptr(new_n0); - new_n0->back_pointer = node->back_pointer; - new_n0->parent_slot = node->parent_slot; new_n1->back_pointer = assoc_array_node_to_ptr(new_n0); - new_n1->parent_slot = -1; /* Need to calculate this */ - -do_split_node: - pr_devel("do_split_node\n"); - new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch; new_n1->nr_leaves_on_branch = 0; @@ -699,26 +674,29 @@ static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit, } } } +} - ptr = node->back_pointer; - if (!ptr) - edit->set[0].ptr = &edit->array->root; - else if (assoc_array_ptr_is_node(ptr)) - edit->set[0].ptr = &assoc_array_ptr_to_node(ptr)->slots[node->parent_slot]; - else - edit->set[0].ptr = &assoc_array_ptr_to_shortcut(ptr)->next_node; - edit->excised_meta[0] = assoc_array_node_to_ptr(node); - pr_devel("<--%s() = ok [split node]\n", __func__); - return true; +/* + * All the leaves, new and old, want to cluster together in this node in the + * same slot, so we have to replace this node with a shortcut to skip over + * the identical parts of the key, leading to new_n0. If the node is the + * target of a shortcut, the new one replaces that shortcut as well. The + * caller then splits the leaves between new_n0 and new_n1 at the shortcut's + * far end, for which this fills in the segment cache. + */ +static struct assoc_array_shortcut * +assoc_array_insert_shortcut(struct assoc_array_edit *edit, + const struct assoc_array_ops *ops, + const void *index_key, + struct assoc_array_node *node, int level, + struct assoc_array_node *new_n0) +{ + struct assoc_array_shortcut *new_s0; + unsigned long base_seg, blank; + size_t keylen; + int diff, i; -all_leaves_cluster_together: - /* All the leaves, new and old, want to cluster together in this node - * in the same slot, so we have to replace this node with a shortcut to - * skip over the identical parts of the key and then place a pair of - * nodes, one inside the other, at the end of the shortcut and - * distribute the keys between them. - * - * Firstly we need to work out where the leaves start diverging as a + /* Firstly we need to work out where the leaves start diverging as a * bit position into their keys so that we know how big the shortcut * needs to be. * @@ -744,17 +722,28 @@ static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit, new_s0 = kzalloc_flex(*new_s0, index_key, keylen); if (!new_s0) - return false; + return NULL; edit->new_meta[2] = assoc_array_shortcut_to_ptr(new_s0); - edit->set[0].to = assoc_array_shortcut_to_ptr(new_s0); new_s0->back_pointer = node->back_pointer; new_s0->parent_slot = node->parent_slot; + + /* A shortcut has to lead to a node, so a node at the end of a shortcut + * is replaced together with that shortcut. The new one holds the index + * key from the root, so it covers what the old one did. + */ + if (node->back_pointer && + assoc_array_ptr_is_shortcut(node->back_pointer)) { + struct assoc_array_shortcut *above = + assoc_array_ptr_to_shortcut(node->back_pointer); + + new_s0->back_pointer = above->back_pointer; + new_s0->parent_slot = above->parent_slot; + edit->excised_meta[1] = node->back_pointer; + } new_s0->next_node = assoc_array_node_to_ptr(new_n0); new_n0->back_pointer = assoc_array_shortcut_to_ptr(new_s0); new_n0->parent_slot = 0; - new_n1->back_pointer = assoc_array_node_to_ptr(new_n0); - new_n1->parent_slot = -1; /* Need to calculate this */ new_s0->skip_to_level = level = diff & ~ASSOC_ARRAY_LEVEL_STEP_MASK; pr_devel("skip_to_level = %d [diff %d]\n", level, diff); @@ -773,18 +762,104 @@ static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit, /* This now reduces to a node splitting exercise for which we'll need * to regenerate the disparity table. */ - for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { - ptr = node->slots[i]; - base_seg = ops->get_object_key_chunk(assoc_array_ptr_to_leaf(ptr), - level); - base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK; - edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK; - } - + assoc_array_fill_segment_cache(edit, ops, node, level); base_seg = ops->get_key_chunk(index_key, level); base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK; edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = base_seg & ASSOC_ARRAY_FAN_MASK; - goto do_split_node; + return new_s0; +} + +/* + * Handle insertion into a terminal node. + */ +static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit, + const struct assoc_array_ops *ops, + const void *index_key, + struct assoc_array_walk_result *result) +{ + struct assoc_array_shortcut *new_s0; + struct assoc_array_node *node, *new_n0, *new_n1; + bool have_meta; + int level; + + node = result->terminal_node.node; + level = result->terminal_node.level; + + pr_devel("-->%s()\n", __func__); + + /* We arrived at a node which doesn't have an onward node or shortcut + * pointer that we have to follow. This means that (a) the leaf we + * want must go here (either by insertion or replacement) or (b) we + * need to split this node and insert in one of the fragments. + */ + if (assoc_array_insert_in_node(edit, ops, index_key, node)) { + pr_devel("<--%s() = ok [in node]\n", __func__); + return true; + } + + /* The node has no spare slots - so we're either going to have to split + * it or insert another node before it. + * + * Whatever, we're going to need at least two new nodes - so allocate + * those now. We may also need a new shortcut, but we deal with that + * when we need it. + */ + new_n0 = kzalloc_obj(struct assoc_array_node); + if (!new_n0) + return false; + edit->new_meta[0] = assoc_array_node_to_ptr(new_n0); + new_n1 = kzalloc_obj(struct assoc_array_node); + if (!new_n1) + return false; + edit->new_meta[1] = assoc_array_node_to_ptr(new_n1); + + /* We need to find out how similar the leaves are. */ + pr_devel("no spare slots\n"); + have_meta = assoc_array_fill_segment_cache(edit, ops, node, level); + edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = result->terminal_node.slot; + + if (!have_meta && assoc_array_all_one_segment(edit)) { + /* The node only contains leaves and all the leaves cluster in + * the same slot, so we need to insert a shortcut to skip the + * common portion of the key and split the node at the + * shortcut's far end. The shortcut goes wherever its back + * pointer says, which may be further up than the node. + */ + new_s0 = assoc_array_insert_shortcut(edit, ops, index_key, + node, level, new_n0); + if (!new_s0) + return false; + edit->set[0].ptr = assoc_array_parent_link(edit->array, + new_s0->back_pointer, + new_s0->parent_slot); + edit->set[0].to = assoc_array_shortcut_to_ptr(new_s0); + } else { + /* We need to split the current node. The node must contain + * anything from a single leaf (in the one leaf case, this leaf + * will cluster with the new leaf) and the rest meta-pointers, + * to all leaves, some of which may cluster. + * + * We need to expel at least two leaves out of a set consisting + * of the leaves in the node and the new leaf. The current meta + * pointers can just be copied as they shouldn't cluster with + * any of the leaves. If all the old leaves cluster in one slot + * and the new leaf does not, they all go and the new leaf stays. + * + * We need a new node (n0) to replace the current one and a new + * node to take the expelled nodes (n1). + */ + new_n0->back_pointer = node->back_pointer; + new_n0->parent_slot = node->parent_slot; + edit->set[0].ptr = assoc_array_parent_link(edit->array, + new_n0->back_pointer, + new_n0->parent_slot); + edit->set[0].to = assoc_array_node_to_ptr(new_n0); + } + + assoc_array_split_node(edit, node, new_n0, new_n1); + edit->excised_meta[0] = assoc_array_node_to_ptr(node); + pr_devel("<--%s() = ok [split node]\n", __func__); + return true; } /* @@ -795,7 +870,7 @@ static bool assoc_array_insert_mid_shortcut(struct assoc_array_edit *edit, struct assoc_array_walk_result *result) { struct assoc_array_shortcut *shortcut, *new_s0, *new_s1; - struct assoc_array_node *node, *new_n0, *side; + struct assoc_array_node *new_n0, *side; unsigned long sc_segments, dissimilarity, blank; size_t keylen; int level, sc_level, diff; @@ -821,14 +896,11 @@ static bool assoc_array_insert_mid_shortcut(struct assoc_array_edit *edit, diff += sc_level & ~ASSOC_ARRAY_KEY_CHUNK_MASK; pr_devel("diff=%d\n", diff); - if (!shortcut->back_pointer) { - edit->set[0].ptr = &edit->array->root; - } else if (assoc_array_ptr_is_node(shortcut->back_pointer)) { - node = assoc_array_ptr_to_node(shortcut->back_pointer); - edit->set[0].ptr = &node->slots[shortcut->parent_slot]; - } else { - BUG(); - } + BUG_ON(shortcut->back_pointer && + !assoc_array_ptr_is_node(shortcut->back_pointer)); + edit->set[0].ptr = assoc_array_parent_link(edit->array, + shortcut->back_pointer, + shortcut->parent_slot); edit->excised_meta[0] = assoc_array_shortcut_to_ptr(shortcut); @@ -843,7 +915,8 @@ static bool assoc_array_insert_mid_shortcut(struct assoc_array_edit *edit, * zero length - otherwise we just connect the new node directly to the * parent. */ - level += ASSOC_ARRAY_LEVEL_STEP; + if (shortcut->back_pointer) + level += ASSOC_ARRAY_LEVEL_STEP; if (diff > level) { pr_devel("pre-shortcut %d...%d\n", level, diff); keylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE); @@ -865,9 +938,11 @@ static bool assoc_array_insert_mid_shortcut(struct assoc_array_edit *edit, memcpy(new_s0->index_key, shortcut->index_key, flex_array_size(new_s0, index_key, keylen)); - blank = ULONG_MAX << (diff & ASSOC_ARRAY_KEY_CHUNK_MASK); - pr_devel("blank off [%zu] %d: %lx\n", keylen - 1, diff, blank); - new_s0->index_key[keylen - 1] &= ~blank; + if (diff & ASSOC_ARRAY_KEY_CHUNK_MASK) { + blank = ULONG_MAX << (diff & ASSOC_ARRAY_KEY_CHUNK_MASK); + pr_devel("blank off [%zu] %d: %lx\n", keylen - 1, diff, blank); + new_s0->index_key[keylen - 1] &= ~blank; + } } else { pr_devel("no pre-shortcut\n"); edit->set[0].to = assoc_array_node_to_ptr(new_n0); @@ -1055,6 +1130,92 @@ static int assoc_array_delete_collapse_iterator(const void *leaf, return 0; } +/* + * Deleting a leaf from node leaves its subtree with FAN_OUT or fewer leaves: + * collapse the subtree into one new node, together with as much of the tree + * above it as also fits. Returns false if the new node cannot be allocated. + */ +static bool assoc_array_delete_collapse(struct assoc_array_edit *edit, + struct assoc_array_node *node) +{ + struct assoc_array_delete_collapse_context collapse; + struct assoc_array_node *parent, *grandparent, *new_n0; + struct assoc_array_ptr *ptr; + bool has_meta; + int i; + + /* First of all, we need to know if this node has metadata so + * that we don't try collapsing if all the leaves are already + * here. + */ + has_meta = false; + for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { + ptr = node->slots[i]; + if (assoc_array_ptr_is_meta(ptr)) { + has_meta = true; + break; + } + } + + pr_devel("leaves: %ld [m=%d]\n", + node->nr_leaves_on_branch - 1, has_meta); + + /* Look further up the tree to see if we can collapse this node + * into a more proximal node too. + */ + for (parent = node;; parent = grandparent) { + pr_devel("collapse subtree: %ld\n", parent->nr_leaves_on_branch); + + ptr = parent->back_pointer; + if (ptr && assoc_array_ptr_is_shortcut(ptr)) + ptr = assoc_array_ptr_to_shortcut(ptr)->back_pointer; + if (!ptr) + break; + + grandparent = assoc_array_ptr_to_node(ptr); + if (grandparent->nr_leaves_on_branch > ASSOC_ARRAY_FAN_OUT + 1) + break; + } + + /* There's no point collapsing if the original node has no meta + * pointers to discard and if we didn't merge into one of that + * node's ancestry. + */ + if (has_meta || parent != node) { + node = parent; + + /* Create a new node to collapse into */ + new_n0 = kzalloc_obj(struct assoc_array_node); + if (!new_n0) + return false; + edit->new_meta[0] = assoc_array_node_to_ptr(new_n0); + + new_n0->back_pointer = node->back_pointer; + new_n0->parent_slot = node->parent_slot; + new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch; + edit->adjust_count_on = new_n0; + + collapse.node = new_n0; + collapse.skip_leaf = assoc_array_ptr_to_leaf(edit->dead_leaf); + collapse.slot = 0; + assoc_array_subtree_iterate(assoc_array_node_to_ptr(node), + node->back_pointer, + assoc_array_delete_collapse_iterator, + &collapse); + pr_devel("collapsed %d,%lu\n", collapse.slot, new_n0->nr_leaves_on_branch); + BUG_ON(collapse.slot != new_n0->nr_leaves_on_branch - 1); + + BUG_ON(node->back_pointer && + assoc_array_ptr_is_leaf(node->back_pointer)); + edit->set[1].ptr = assoc_array_parent_link(edit->array, + node->back_pointer, + node->parent_slot); + edit->set[1].to = assoc_array_node_to_ptr(new_n0); + edit->excised_subtree = assoc_array_node_to_ptr(node); + } + return true; +} + /** * assoc_array_delete - Script deletion of an object from an associative array * @array: The array to search. @@ -1078,13 +1239,11 @@ struct assoc_array_edit *assoc_array_delete(struct assoc_array *array, const struct assoc_array_ops *ops, const void *index_key) { - struct assoc_array_delete_collapse_context collapse; struct assoc_array_walk_result result; - struct assoc_array_node *node, *new_n0; + struct assoc_array_node *node; struct assoc_array_edit *edit; struct assoc_array_ptr *ptr; - bool has_meta; - int slot, i; + int slot; pr_devel("-->%s()\n", __func__); @@ -1095,8 +1254,10 @@ struct assoc_array_edit *assoc_array_delete(struct assoc_array *array, edit->ops = ops; edit->adjust_count_by = -1; - switch (assoc_array_walk(array, ops, index_key, &result)) { - case assoc_array_walk_found_terminal_node: + node = NULL; + slot = ASSOC_ARRAY_FAN_OUT; + if (assoc_array_walk(array, ops, index_key, &result) == + assoc_array_walk_found_terminal_node) { /* We found a node that should contain the leaf we've been * asked to remove - *if* it's in the tree. */ @@ -1109,18 +1270,15 @@ struct assoc_array_edit *assoc_array_delete(struct assoc_array *array, assoc_array_ptr_is_leaf(ptr) && ops->compare_object(assoc_array_ptr_to_leaf(ptr), index_key)) - goto found_leaf; + break; } - fallthrough; - case assoc_array_walk_tree_empty: - case assoc_array_walk_found_wrong_shortcut: - default: + } + if (slot == ASSOC_ARRAY_FAN_OUT) { assoc_array_cancel_edit(edit); pr_devel("not found\n"); return NULL; } -found_leaf: BUG_ON(array->nr_leaves_on_tree <= 0); /* In the simplest form of deletion we just clear the slot and release @@ -1153,103 +1311,15 @@ struct assoc_array_edit *assoc_array_delete(struct assoc_array *array, * We could also try and collapse in partially filled subtrees to take * up space in this node. */ - if (node->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT + 1) { - struct assoc_array_node *parent, *grandparent; - struct assoc_array_ptr *ptr; - - /* First of all, we need to know if this node has metadata so - * that we don't try collapsing if all the leaves are already - * here. - */ - has_meta = false; - for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { - ptr = node->slots[i]; - if (assoc_array_ptr_is_meta(ptr)) { - has_meta = true; - break; - } - } - - pr_devel("leaves: %ld [m=%d]\n", - node->nr_leaves_on_branch - 1, has_meta); - - /* Look further up the tree to see if we can collapse this node - * into a more proximal node too. - */ - parent = node; - collapse_up: - pr_devel("collapse subtree: %ld\n", parent->nr_leaves_on_branch); - - ptr = parent->back_pointer; - if (!ptr) - goto do_collapse; - if (assoc_array_ptr_is_shortcut(ptr)) { - struct assoc_array_shortcut *s = assoc_array_ptr_to_shortcut(ptr); - ptr = s->back_pointer; - if (!ptr) - goto do_collapse; - } - - grandparent = assoc_array_ptr_to_node(ptr); - if (grandparent->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT + 1) { - parent = grandparent; - goto collapse_up; - } - - do_collapse: - /* There's no point collapsing if the original node has no meta - * pointers to discard and if we didn't merge into one of that - * node's ancestry. - */ - if (has_meta || parent != node) { - node = parent; - - /* Create a new node to collapse into */ - new_n0 = kzalloc_obj(struct assoc_array_node); - if (!new_n0) - goto enomem; - edit->new_meta[0] = assoc_array_node_to_ptr(new_n0); - - new_n0->back_pointer = node->back_pointer; - new_n0->parent_slot = node->parent_slot; - new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch; - edit->adjust_count_on = new_n0; - - collapse.node = new_n0; - collapse.skip_leaf = assoc_array_ptr_to_leaf(edit->dead_leaf); - collapse.slot = 0; - assoc_array_subtree_iterate(assoc_array_node_to_ptr(node), - node->back_pointer, - assoc_array_delete_collapse_iterator, - &collapse); - pr_devel("collapsed %d,%lu\n", collapse.slot, new_n0->nr_leaves_on_branch); - BUG_ON(collapse.slot != new_n0->nr_leaves_on_branch - 1); - - if (!node->back_pointer) { - edit->set[1].ptr = &array->root; - } else if (assoc_array_ptr_is_leaf(node->back_pointer)) { - BUG(); - } else if (assoc_array_ptr_is_node(node->back_pointer)) { - struct assoc_array_node *p = - assoc_array_ptr_to_node(node->back_pointer); - edit->set[1].ptr = &p->slots[node->parent_slot]; - } else if (assoc_array_ptr_is_shortcut(node->back_pointer)) { - struct assoc_array_shortcut *s = - assoc_array_ptr_to_shortcut(node->back_pointer); - edit->set[1].ptr = &s->next_node; - } - edit->set[1].to = assoc_array_node_to_ptr(new_n0); - edit->excised_subtree = assoc_array_node_to_ptr(node); - } + if (node->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT + 1 && + !assoc_array_delete_collapse(edit, node)) { + /* Clean up after an out of memory error */ + pr_devel("enomem\n"); + assoc_array_cancel_edit(edit); + return ERR_PTR(-ENOMEM); } return edit; - -enomem: - /* Clean up after an out of memory error */ - pr_devel("enomem\n"); - assoc_array_cancel_edit(edit); - return ERR_PTR(-ENOMEM); } /** @@ -1425,115 +1495,115 @@ void assoc_array_cancel_edit(struct assoc_array_edit *edit) kfree(edit); } -/** - * assoc_array_gc - Garbage collect an associative array. - * @array: The array to clean. - * @ops: The operations to use. - * @iterator: A callback function to pass judgement on each object. - * @iterator_data: Private data for the callback function. - * - * Collect garbage from an associative array and pack down the internal tree to - * save memory. - * - * The iterator function is asked to pass judgement upon each object in the - * array. If it returns false, the object is discard and if it returns true, - * the object is kept. If it returns true, it must increment the object's - * usage count (or whatever it needs to do to retain it) before returning. - * - * This function returns 0 if successful or -ENOMEM if out of memory. In the - * latter case, the array is not changed. - * - * The caller should lock against other modifications and must continue to hold - * the lock until assoc_array_apply_edit() has been called. - * - * Accesses to the tree may take place concurrently with this function, - * provided they hold the RCU read lock. +/* + * Where assoc_array_gc() has got to. It copies the tree depth first without + * recursion: on reaching a subtree it copies it and carries on there, and on + * finishing a node it climbs back up the old tree to the node above. */ -int assoc_array_gc(struct assoc_array *array, - const struct assoc_array_ops *ops, - bool (*iterator)(void *object, void *iterator_data), - void *iterator_data) +struct assoc_array_gc_walk { + struct assoc_array_node *node; /* The node being copied */ + struct assoc_array_node *new_n; /* Its copy */ + int slot; /* The next slot of node to look at */ + struct assoc_array_ptr *new_root; /* The root of the copy */ + unsigned long nr_leaves_on_tree; + bool (*iterator)(void *object, void *iterator_data); + void *iterator_data; +}; + +/* + * Copy the node at cursor, and the shortcut in front of it if there is one, + * into the new tree at *link, below the copy of the node being worked on, + * and work on that node next. + */ +static bool assoc_array_gc_copy(struct assoc_array_gc_walk *w, + struct assoc_array_ptr *cursor, + struct assoc_array_ptr **link) { struct assoc_array_shortcut *shortcut, *new_s; - struct assoc_array_node *node, *new_n; - struct assoc_array_edit *edit; - struct assoc_array_ptr *cursor, *ptr; - struct assoc_array_ptr *new_root, *new_parent, **new_ptr_pp; - unsigned long nr_leaves_on_tree; - bool retained; - int keylen, slot, nr_free, next_slot, i; - - pr_devel("-->%s()\n", __func__); - - if (!array->root) - return 0; - - edit = kzalloc_obj(struct assoc_array_edit); - if (!edit) - return -ENOMEM; - edit->array = array; - edit->ops = ops; - edit->ops_for_excised_subtree = ops; - edit->set[0].ptr = &array->root; - edit->excised_subtree = array->root; + struct assoc_array_node *new_n; + struct assoc_array_ptr *new_parent; + int keylen; - new_root = new_parent = NULL; - new_ptr_pp = &new_root; - cursor = array->root; + new_parent = w->new_n ? assoc_array_node_to_ptr(w->new_n) : NULL; -descend: - /* If this point is a shortcut, then we need to duplicate it and - * advance the target cursor. + /* The node at this position is duplicated, and so is the shortcut in + * front of it if there is one. The node is allocated first: the copy + * of the shortcut starts out pointing at the old node, and must not be + * in the new tree if the node cannot be allocated, or the cleanup + * would follow it into the old tree. */ + new_n = kzalloc_obj(struct assoc_array_node); + if (!new_n) + return false; + if (assoc_array_ptr_is_shortcut(cursor)) { shortcut = assoc_array_ptr_to_shortcut(cursor); keylen = round_up(shortcut->skip_to_level, ASSOC_ARRAY_KEY_CHUNK_SIZE); keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT; new_s = kmalloc_flex(*new_s, index_key, keylen); - if (!new_s) - goto enomem; + if (!new_s) { + kfree(new_n); + return false; + } pr_devel("dup shortcut %p -> %p\n", shortcut, new_s); memcpy(new_s, shortcut, struct_size(new_s, index_key, keylen)); new_s->back_pointer = new_parent; new_s->parent_slot = shortcut->parent_slot; - *new_ptr_pp = new_parent = assoc_array_shortcut_to_ptr(new_s); - new_ptr_pp = &new_s->next_node; + *link = new_parent = assoc_array_shortcut_to_ptr(new_s); + link = &new_s->next_node; cursor = shortcut->next_node; } - /* Duplicate the node at this position */ - node = assoc_array_ptr_to_node(cursor); - new_n = kzalloc_obj(struct assoc_array_node); - if (!new_n) - goto enomem; - pr_devel("dup node %p -> %p\n", node, new_n); + w->node = assoc_array_ptr_to_node(cursor); + pr_devel("dup node %p -> %p\n", w->node, new_n); new_n->back_pointer = new_parent; - new_n->parent_slot = node->parent_slot; - *new_ptr_pp = new_parent = assoc_array_node_to_ptr(new_n); - new_ptr_pp = NULL; - slot = 0; + new_n->parent_slot = w->node->parent_slot; + *link = assoc_array_node_to_ptr(new_n); + w->new_n = new_n; + w->slot = 0; + return true; +} + +/* + * Carry on through the slots of the node being copied, putting the leaves + * the iterator keeps into the copy, as far as the next pointer to a subtree. + * Returns that pointer, with w->slot at it, or NULL when the node is done. + */ +static struct assoc_array_ptr *assoc_array_gc_next(struct assoc_array_gc_walk *w) +{ + struct assoc_array_ptr *ptr; -continue_node: /* Filter across any leaves and gc any subtrees */ - for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) { - ptr = node->slots[slot]; + for (; w->slot < ASSOC_ARRAY_FAN_OUT; w->slot++) { + ptr = w->node->slots[w->slot]; if (!ptr) continue; if (assoc_array_ptr_is_leaf(ptr)) { - if (iterator(assoc_array_ptr_to_leaf(ptr), - iterator_data)) + if (w->iterator(assoc_array_ptr_to_leaf(ptr), + w->iterator_data)) /* The iterator will have done any reference * counting on the object for us. */ - new_n->slots[slot] = ptr; + w->new_n->slots[w->slot] = ptr; continue; } - new_ptr_pp = &new_n->slots[slot]; - cursor = ptr; - goto descend; + return ptr; } + return NULL; +} + +/* + * Fold the children of a finished copy into it where their leaves fit in + * its free slots, and count its leaves. Returns the number of free slots + * left. + */ +static int assoc_array_gc_fold(struct assoc_array_node *new_n) +{ + struct assoc_array_ptr *ptr; + bool retained; + int slot, nr_free, next_slot, i; retry_compress: pr_devel("-- compress node %p --\n", new_n); @@ -1612,8 +1682,24 @@ int assoc_array_gc(struct assoc_array *array, goto retry_compress; } pr_devel("after: %lu\n", new_n->nr_leaves_on_branch); + return nr_free; +} - nr_leaves_on_tree = new_n->nr_leaves_on_branch; +/* + * The copy of the node being worked on is finished: fold its children into + * it, then remove it if all it holds is a shortcut, or remove the shortcut + * in front of it if it is small. Returns what is then the copy's parent, or + * NULL if it is at the root, when the whole tree has been copied. + */ +static struct assoc_array_ptr *assoc_array_gc_pack(struct assoc_array_gc_walk *w) +{ + struct assoc_array_shortcut *new_s; + struct assoc_array_node *new_n = w->new_n; + struct assoc_array_ptr *ptr, *new_parent; + int nr_free, slot; + + nr_free = assoc_array_gc_fold(new_n); + w->nr_leaves_on_tree = new_n->nr_leaves_on_branch; /* Excise this node if it is singly occupied by a shortcut */ if (nr_free == ASSOC_ARRAY_FAN_OUT - 1) { @@ -1631,8 +1717,8 @@ int assoc_array_gc(struct assoc_array *array, if (!new_parent) { new_s->back_pointer = NULL; new_s->parent_slot = 0; - new_root = ptr; - goto gc_complete; + w->new_root = ptr; + return NULL; } if (assoc_array_ptr_is_shortcut(new_parent)) { @@ -1648,16 +1734,15 @@ int assoc_array_gc(struct assoc_array *array, if (!new_parent) { new_s->back_pointer = NULL; new_s->parent_slot = 0; - new_root = ptr; - goto gc_complete; + w->new_root = ptr; + return NULL; } } new_s->back_pointer = new_parent; new_s->parent_slot = slot; - new_n = assoc_array_ptr_to_node(new_parent); - new_n->slots[slot] = ptr; - goto ascend_old_tree; + assoc_array_ptr_to_node(new_parent)->slots[slot] = ptr; + return new_parent; } } @@ -1666,59 +1751,135 @@ int assoc_array_gc(struct assoc_array *array, */ ptr = new_n->back_pointer; if (!ptr) - goto gc_complete; + return NULL; - if (assoc_array_ptr_is_shortcut(ptr)) { - new_s = assoc_array_ptr_to_shortcut(ptr); - new_parent = new_s->back_pointer; - slot = new_s->parent_slot; + if (!assoc_array_ptr_is_shortcut(ptr)) + return ptr; + + new_s = assoc_array_ptr_to_shortcut(ptr); + new_parent = new_s->back_pointer; + slot = new_s->parent_slot; + + if (new_n->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT) { + pr_devel("excise shortcut\n"); + new_n->back_pointer = new_parent; + new_n->parent_slot = slot; + kfree(new_s); + if (!new_parent) { + w->new_root = assoc_array_node_to_ptr(new_n); + return NULL; + } - if (new_n->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT) { - struct assoc_array_node *n; + assoc_array_ptr_to_node(new_parent)->slots[slot] = + assoc_array_node_to_ptr(new_n); + } + return new_parent; +} - pr_devel("excise shortcut\n"); - new_n->back_pointer = new_parent; - new_n->parent_slot = slot; - kfree(new_s); - if (!new_parent) { - new_root = assoc_array_node_to_ptr(new_n); - goto gc_complete; - } +/* + * Go back up from the node just finished to the node above it, whose copy is + * parent, and on to that node's next slot. + */ +static void assoc_array_gc_ascend(struct assoc_array_gc_walk *w, + struct assoc_array_ptr *parent) +{ + struct assoc_array_shortcut *shortcut; + struct assoc_array_ptr *ptr, *cursor; + int slot; - n = assoc_array_ptr_to_node(new_parent); - n->slots[slot] = assoc_array_node_to_ptr(new_n); - } - } else { - new_parent = ptr; - } - new_n = assoc_array_ptr_to_node(new_parent); + w->new_n = assoc_array_ptr_to_node(parent); -ascend_old_tree: - ptr = node->back_pointer; + ptr = w->node->back_pointer; if (assoc_array_ptr_is_shortcut(ptr)) { shortcut = assoc_array_ptr_to_shortcut(ptr); slot = shortcut->parent_slot; cursor = shortcut->back_pointer; - if (!cursor) - goto gc_complete; } else { - slot = node->parent_slot; + slot = w->node->parent_slot; cursor = ptr; } BUG_ON(!cursor); - node = assoc_array_ptr_to_node(cursor); - slot++; - goto continue_node; + w->node = assoc_array_ptr_to_node(cursor); + w->slot = slot + 1; +} + +/** + * assoc_array_gc - Garbage collect an associative array. + * @array: The array to clean. + * @ops: The operations to use. + * @iterator: A callback function to pass judgement on each object. + * @iterator_data: Private data for the callback function. + * + * Collect garbage from an associative array and pack down the internal tree to + * save memory. + * + * The iterator function is asked to pass judgement upon each object in the + * array. If it returns false, the object is discard and if it returns true, + * the object is kept. If it returns true, it must increment the object's + * usage count (or whatever it needs to do to retain it) before returning. + * + * This function returns 0 if successful or -ENOMEM if out of memory. In the + * latter case, the array is not changed. + * + * The caller should lock against other modifications and must continue to hold + * the lock until assoc_array_apply_edit() has been called. + * + * Accesses to the tree may take place concurrently with this function, + * provided they hold the RCU read lock. + */ +int assoc_array_gc(struct assoc_array *array, + const struct assoc_array_ops *ops, + bool (*iterator)(void *object, void *iterator_data), + void *iterator_data) +{ + struct assoc_array_gc_walk w = { + .iterator = iterator, + .iterator_data = iterator_data, + }; + struct assoc_array_edit *edit; + struct assoc_array_ptr *ptr, *parent, **link; + + pr_devel("-->%s()\n", __func__); + + if (!array->root) + return 0; + + edit = kzalloc_obj(struct assoc_array_edit); + if (!edit) + return -ENOMEM; + edit->array = array; + edit->ops = ops; + edit->ops_for_excised_subtree = ops; + edit->set[0].ptr = &array->root; + edit->excised_subtree = array->root; + + ptr = array->root; + link = &w.new_root; + for (;;) { + if (!assoc_array_gc_copy(&w, ptr, link)) + goto enomem; + + /* Find the next subtree to copy: further on in this node, or, + * when it is done, in the nodes above it. + */ + while (!(ptr = assoc_array_gc_next(&w))) { + parent = assoc_array_gc_pack(&w); + if (!parent) + goto copied; + assoc_array_gc_ascend(&w, parent); + } + link = &w.new_n->slots[w.slot]; + } -gc_complete: - edit->set[0].to = new_root; +copied: + edit->set[0].to = w.new_root; assoc_array_apply_edit(edit); - array->nr_leaves_on_tree = nr_leaves_on_tree; + array->nr_leaves_on_tree = w.nr_leaves_on_tree; return 0; enomem: pr_devel("enomem\n"); - assoc_array_destroy_subtree(new_root, edit->ops); + assoc_array_destroy_subtree(w.new_root, edit->ops); kfree(edit); return -ENOMEM; } diff --git a/lib/bootconfig.c b/lib/bootconfig.c index 948c8c10e4b985..9ae9a215b1da3c 100644 --- a/lib/bootconfig.c +++ b/lib/bootconfig.c @@ -421,12 +421,12 @@ int __init xbc_node_compose_key_after(struct xbc_node *root, uint16_t keys[XBC_DEPTH_MAX]; int depth = 0, ret = 0, total = 0; + while (node && xbc_node_is_value(node)) + node = xbc_node_get_parent(node); + if (!node || node == root) return -EINVAL; - if (xbc_node_is_value(node)) - node = xbc_node_get_parent(node); - while (node && node != root) { if (depth == XBC_DEPTH_MAX) return -ERANGE; @@ -587,8 +587,8 @@ int __init xbc_snprint_cmdline_filter(char *buf, size_t size, struct xbc_node *r vnode = xbc_node_get_child(knode); if (!vnode) { - ret = snprintf(buf ? buf + len : NULL, rest(len, size), - "%s ", xbc_namebuf); + ret = snprintf(buf && len < size ? buf + len : NULL, + rest(len, size), "%s ", xbc_namebuf); if (ret < 0) return ret; len += ret; @@ -601,7 +601,8 @@ int __init xbc_snprint_cmdline_filter(char *buf, size_t size, struct xbc_node *r * whitespace. */ q = strpbrk(val, " \t\r\n") ? "\"" : ""; - ret = snprintf(buf ? buf + len : NULL, rest(len, size), + ret = snprintf(buf && len < size ? buf + len : NULL, + rest(len, size), "%s=%s%s%s ", xbc_namebuf, q, val, q); if (ret < 0) return ret; @@ -1058,8 +1059,8 @@ static int __init xbc_verify_tree(void) return xbc_parse_error("Too long key length", xbc_node_get_data(n)); - m = xbc_node_get_child(n); - if (m && xbc_node_is_key(m)) { + m = xbc_node_get_subkey(n); + if (m) { n = m; depth++; if (depth > XBC_DEPTH_MAX) diff --git a/lib/crc/crc64-neon.c b/lib/crc/crc64-neon.c index 4753fb94a4beb8..1267df1310bedf 100644 --- a/lib/crc/crc64-neon.c +++ b/lib/crc/crc64-neon.c @@ -3,7 +3,7 @@ * Accelerated CRC64 (NVMe) using ARM NEON C intrinsics */ -#include +#include #include #include "crc64-neon.h" @@ -11,11 +11,11 @@ u64 crc64_nvme_neon(u64 crc, const u8 *p, size_t len); /* x^191 mod G, x^127 mod G */ -static const u64 fold_consts_val[2] = { 0xeadc41fd2ba3d420ULL, - 0x21e9761e252621acULL }; +static const uint64_t fold_consts_val[2] = { 0xeadc41fd2ba3d420ULL, + 0x21e9761e252621acULL }; /* floor(x^127 / G), (G - x^64) / x */ -static const u64 bconsts_val[2] = { 0x27ecfa329aef9f77ULL, - 0x34d926535897936aULL }; +static const uint64_t bconsts_val[2] = { 0x27ecfa329aef9f77ULL, + 0x34d926535897936aULL }; u64 crc64_nvme_neon(u64 crc, const u8 *p, size_t len) { diff --git a/lib/fault-inject.c b/lib/fault-inject.c index 02916ef2761c60..9182d457baf551 100644 --- a/lib/fault-inject.c +++ b/lib/fault-inject.c @@ -1,6 +1,7 @@ // SPDX-License-Identifier: GPL-2.0-only #include #include +#include #include #include #include @@ -50,7 +51,12 @@ int setup_fault_attr(struct fault_attr *attr, char *str) return 0; } - prandom_init_once(&fault_rnd_state); + /* + * __setup handlers run before slab and workqueues are initialized, + * but prandom_init_once() calls kmalloc() and schedule_work(). So use + * DO_ONCE_LITE() instead. + */ + DO_ONCE_LITE(prandom_seed_full_state, &fault_rnd_state); attr->probability = probability; attr->interval = interval; diff --git a/lib/maple_tree.c b/lib/maple_tree.c index 0b0036c9f84892..f7f51f1b40d931 100644 --- a/lib/maple_tree.c +++ b/lib/maple_tree.c @@ -3891,14 +3891,64 @@ static __always_inline void mas_rewalk(struct ma_state *mas, unsigned long index goto retry; } -static __always_inline bool mas_rewalk_if_dead(struct ma_state *mas, - struct maple_node *node, const unsigned long index) +/* + * mas_next_no_node() - Finish a next walk that restarted into a tree without + * nodes. + * @mas: The inactive maple state (ma_none or ma_root) + * + * The arrival here is either because there is a root value or nothing. Either + * way, the next entry is nothing. So set the limits and overwrite the status. + * + * Return: NULL + */ +static inline void *mas_next_no_node(struct ma_state *mas) { - if (unlikely(ma_dead_node(node))) { - mas_rewalk(mas, index); - return true; + if (mas_is_ptr(mas)) + mas->index = 1; + else + mas->index = 0; + + mas->last = ULONG_MAX; + mas->status = ma_none; + return NULL; +} + +/* + * mas_prev_no_node() - Finish a prev walk that restarted into a tree without + * nodes. + * @mas: The inactive maple state (ma_none or ma_root) + * @index: The start of the range the walk left + * @min: The lowest index to return + * + * The arrival here is either because there is a root value or nothing. With + * nothing, leave the limits mas_walk() sets for an empty tree. A root value + * sits at 0: stop on it as mas_prev_setup() does, unless the walk was at 0. + * + * Return: The root entry if @index and @min allow it, NULL otherwise. A node + * if the root changed again since the walk; the caller restarts. + */ +static inline void *mas_prev_no_node(struct ma_state *mas, unsigned long index, + unsigned long min) +{ + void *entry; + + mas->index = 0; + if (mas_is_none(mas)) { + mas->last = ULONG_MAX; + return NULL; } - return false; + + mas->last = 0; + if (!index || min) + return NULL; + + entry = mas_root(mas); + if (!entry) { + mas->status = ma_none; + mas->last = ULONG_MAX; + } + + return entry; } /* @@ -4006,14 +4056,14 @@ static void *mas_prev_slot(struct ma_state *mas, unsigned long min, bool empty) node = mas_mn(mas); type = mte_node_type(mas->node); pivots = ma_pivots(node, type); - if (unlikely(mas_rewalk_if_dead(mas, node, save_point))) - goto retry; + if (unlikely(ma_dead_node(node))) + goto dead; if (mas->min <= min) { pivot = mas_safe_min(mas, pivots, mas->offset); - if (unlikely(mas_rewalk_if_dead(mas, node, save_point))) - goto retry; + if (unlikely(ma_dead_node(node))) + goto dead; if (pivot <= min) goto underflow; @@ -4028,10 +4078,8 @@ static void *mas_prev_slot(struct ma_state *mas, unsigned long min, bool empty) if (mas->index <= min) goto underflow; - if (mas_prev_node(mas, min)) { - mas_rewalk(mas, save_point); - goto retry; - } + if (mas_prev_node(mas, min)) + goto dead; if (WARN_ON_ONCE(mas_is_underflow(mas))) return NULL; @@ -4045,8 +4093,8 @@ static void *mas_prev_slot(struct ma_state *mas, unsigned long min, bool empty) slots = ma_slots(node, type); entry = mas_slot(mas, slots, mas->offset); - if (unlikely(mas_rewalk_if_dead(mas, node, save_point))) - goto retry; + if (unlikely(ma_dead_node(node))) + goto dead; if (likely(entry)) return entry; @@ -4063,6 +4111,17 @@ static void *mas_prev_slot(struct ma_state *mas, unsigned long min, bool empty) underflow: mas->status = ma_underflow; return NULL; + +dead: + mas_rewalk(mas, save_point); + if (likely(mas_is_active(mas))) + goto retry; + + entry = mas_prev_no_node(mas, save_point, min); + if (unlikely(xa_is_node(entry))) /* The root changed again */ + goto dead; + + return entry; } /* @@ -4176,8 +4235,8 @@ static void *mas_next_slot(struct ma_state *mas, unsigned long max, bool empty) node = mas_mn(mas); type = mte_node_type(mas->node); pivots = ma_pivots(node, type); - if (unlikely(mas_rewalk_if_dead(mas, node, save_point))) - goto retry; + if (unlikely(ma_dead_node(node))) + goto dead; if (mas->max >= max) { if (likely(mas->offset < mas->end)) @@ -4185,8 +4244,8 @@ static void *mas_next_slot(struct ma_state *mas, unsigned long max, bool empty) else pivot = mas->max; - if (unlikely(mas_rewalk_if_dead(mas, node, save_point))) - goto retry; + if (unlikely(ma_dead_node(node))) + goto dead; if (pivot >= max) { /* Was at the limit, next will extend beyond */ mas->status = ma_overflow; @@ -4208,10 +4267,8 @@ static void *mas_next_slot(struct ma_state *mas, unsigned long max, bool empty) return NULL; } - if (mas_next_node(mas, node, max)) { - mas_rewalk(mas, save_point); - goto retry; - } + if (mas_next_node(mas, node, max)) + goto dead; if (WARN_ON_ONCE(mas_is_overflow(mas))) return NULL; @@ -4226,8 +4283,8 @@ static void *mas_next_slot(struct ma_state *mas, unsigned long max, bool empty) slots = ma_slots(node, type); entry = mt_slot(mas->tree, slots, mas->offset); - if (unlikely(mas_rewalk_if_dead(mas, node, save_point))) - goto retry; + if (unlikely(ma_dead_node(node))) + goto dead; if (entry) return entry; @@ -4244,6 +4301,13 @@ static void *mas_next_slot(struct ma_state *mas, unsigned long max, bool empty) } return entry; + +dead: + mas_rewalk(mas, save_point); + if (likely(mas_is_active(mas))) + goto retry; + + return mas_next_no_node(mas); } /* @@ -5450,7 +5514,9 @@ void *mas_find(struct ma_state *mas, unsigned long max) /* Retries on dead nodes handled by mas_next_slot */ entry = mas_next_slot(mas, max, false); /* Ignore overflow */ - mas->status = ma_active; + if (mas_is_overflow(mas)) + mas->status = ma_active; + return entry; } EXPORT_SYMBOL_GPL(mas_find); diff --git a/lib/raid/xor/arm/xor-neon-glue.c b/lib/raid/xor/arm/xor-neon-glue.c index cea39e0199048e..783474bfe81e01 100644 --- a/lib/raid/xor/arm/xor-neon-glue.c +++ b/lib/raid/xor/arm/xor-neon-glue.c @@ -5,6 +5,9 @@ #include "xor_impl.h" #include "xor_arch.h" +DO_XOR_BLOCKS(neon_inner, __xor_neon_2, __xor_neon_3, __xor_neon_4, + __xor_neon_5); + static void xor_gen_neon(void *dest, void **srcs, unsigned int src_cnt, unsigned int bytes) { diff --git a/lib/raid/xor/arm/xor-neon.h b/lib/raid/xor/arm/xor-neon.h index 406e0356f05bb4..5592dec4de5016 100644 --- a/lib/raid/xor/arm/xor-neon.h +++ b/lib/raid/xor/arm/xor-neon.h @@ -3,5 +3,17 @@ extern struct xor_block_template xor_block_arm4regs; extern struct xor_block_template xor_block_neon; -void xor_gen_neon_inner(void *dest, void **srcs, unsigned int src_cnt, - unsigned int bytes); +void __xor_neon_2(unsigned long bytes, unsigned long * __restrict p1, + const unsigned long * __restrict p2); +void __xor_neon_3(unsigned long bytes, unsigned long * __restrict p1, + const unsigned long * __restrict p2, + const unsigned long * __restrict p3); +void __xor_neon_4(unsigned long bytes, unsigned long * __restrict p1, + const unsigned long * __restrict p2, + const unsigned long * __restrict p3, + const unsigned long * __restrict p4); +void __xor_neon_5(unsigned long bytes, unsigned long * __restrict p1, + const unsigned long * __restrict p2, + const unsigned long * __restrict p3, + const unsigned long * __restrict p4, + const unsigned long * __restrict p5); diff --git a/lib/raid/xor/arm64/xor-eor3.c b/lib/raid/xor/arm64/xor-eor3.c index e44016c363f1c7..41bb577b63ebdf 100644 --- a/lib/raid/xor/arm64/xor-eor3.c +++ b/lib/raid/xor/arm64/xor-eor3.c @@ -1,14 +1,8 @@ // SPDX-License-Identifier: GPL-2.0-only -#include #include -#include "xor_impl.h" -#include "xor_arch.h" #include "xor-neon.h" -extern void __xor_eor3_2(unsigned long bytes, unsigned long * __restrict p1, - const unsigned long * __restrict p2); - static inline uint64x2_t eor3(uint64x2_t p, uint64x2_t q, uint64x2_t r) { uint64x2_t res; @@ -19,7 +13,7 @@ static inline uint64x2_t eor3(uint64x2_t p, uint64x2_t q, uint64x2_t r) return res; } -static void __xor_eor3_3(unsigned long bytes, unsigned long * __restrict p1, +void __xor_eor3_3(unsigned long bytes, unsigned long * __restrict p1, const unsigned long * __restrict p2, const unsigned long * __restrict p3) { @@ -53,7 +47,7 @@ static void __xor_eor3_3(unsigned long bytes, unsigned long * __restrict p1, } while (--lines > 0); } -static void __xor_eor3_4(unsigned long bytes, unsigned long * __restrict p1, +void __xor_eor3_4(unsigned long bytes, unsigned long * __restrict p1, const unsigned long * __restrict p2, const unsigned long * __restrict p3, const unsigned long * __restrict p4) @@ -96,7 +90,7 @@ static void __xor_eor3_4(unsigned long bytes, unsigned long * __restrict p1, } while (--lines > 0); } -static void __xor_eor3_5(unsigned long bytes, unsigned long * __restrict p1, +void __xor_eor3_5(unsigned long bytes, unsigned long * __restrict p1, const unsigned long * __restrict p2, const unsigned long * __restrict p3, const unsigned long * __restrict p4, @@ -141,6 +135,3 @@ static void __xor_eor3_5(unsigned long bytes, unsigned long * __restrict p1, dp5 += 8; } while (--lines > 0); } - -__DO_XOR_BLOCKS(eor3_inner, __xor_eor3_2, __xor_eor3_3, __xor_eor3_4, - __xor_eor3_5); diff --git a/lib/raid/xor/arm64/xor-neon-glue.c b/lib/raid/xor/arm64/xor-neon-glue.c index f0284f86feb4c8..ae133d69964936 100644 --- a/lib/raid/xor/arm64/xor-neon-glue.c +++ b/lib/raid/xor/arm64/xor-neon-glue.c @@ -9,6 +9,11 @@ #include "xor_arch.h" #include "xor-neon.h" +DO_XOR_BLOCKS(neon_inner, __xor_neon_2, __xor_neon_3, __xor_neon_4, + __xor_neon_5); +DO_XOR_BLOCKS(eor3_inner, __xor_neon_2, __xor_eor3_3, __xor_eor3_4, + __xor_eor3_5); + #define XOR_TEMPLATE(_name) \ static void xor_gen_##_name(void *dest, void **srcs, unsigned int src_cnt, \ unsigned int bytes) \ diff --git a/lib/raid/xor/arm64/xor-neon.h b/lib/raid/xor/arm64/xor-neon.h index 514699ba8f5f8e..7d7fb96343df32 100644 --- a/lib/raid/xor/arm64/xor-neon.h +++ b/lib/raid/xor/arm64/xor-neon.h @@ -1,6 +1,29 @@ /* SPDX-License-Identifier: GPL-2.0-only */ -void xor_gen_neon_inner(void *dest, void **srcs, unsigned int src_cnt, - unsigned int bytes); -void xor_gen_eor3_inner(void *dest, void **srcs, unsigned int src_cnt, - unsigned int bytes); +void __xor_neon_2(unsigned long bytes, unsigned long * __restrict p1, + const unsigned long * __restrict p2); +void __xor_neon_3(unsigned long bytes, unsigned long * __restrict p1, + const unsigned long * __restrict p2, + const unsigned long * __restrict p3); +void __xor_neon_4(unsigned long bytes, unsigned long * __restrict p1, + const unsigned long * __restrict p2, + const unsigned long * __restrict p3, + const unsigned long * __restrict p4); +void __xor_neon_5(unsigned long bytes, unsigned long * __restrict p1, + const unsigned long * __restrict p2, + const unsigned long * __restrict p3, + const unsigned long * __restrict p4, + const unsigned long * __restrict p5); + +void __xor_eor3_3(unsigned long bytes, unsigned long * __restrict p1, + const unsigned long * __restrict p2, + const unsigned long * __restrict p3); +void __xor_eor3_4(unsigned long bytes, unsigned long * __restrict p1, + const unsigned long * __restrict p2, + const unsigned long * __restrict p3, + const unsigned long * __restrict p4); +void __xor_eor3_5(unsigned long bytes, unsigned long * __restrict p1, + const unsigned long * __restrict p2, + const unsigned long * __restrict p3, + const unsigned long * __restrict p4, + const unsigned long * __restrict p5); diff --git a/lib/raid/xor/xor-neon.c b/lib/raid/xor/xor-neon.c index c7c3cf634e23ac..6b2fd14f50419e 100644 --- a/lib/raid/xor/xor-neon.c +++ b/lib/raid/xor/xor-neon.c @@ -4,12 +4,11 @@ * Copyright (C) 2018,Tianjin KYLIN Information Technology Co., Ltd. */ -#include "xor_impl.h" #include "xor-neon.h" #include -static void __xor_neon_2(unsigned long bytes, unsigned long * __restrict p1, +void __xor_neon_2(unsigned long bytes, unsigned long * __restrict p1, const unsigned long * __restrict p2) { uint64_t *dp1 = (uint64_t *)p1; @@ -36,7 +35,7 @@ static void __xor_neon_2(unsigned long bytes, unsigned long * __restrict p1, } while (--lines > 0); } -static void __xor_neon_3(unsigned long bytes, unsigned long * __restrict p1, +void __xor_neon_3(unsigned long bytes, unsigned long * __restrict p1, const unsigned long * __restrict p2, const unsigned long * __restrict p3) { @@ -72,7 +71,7 @@ static void __xor_neon_3(unsigned long bytes, unsigned long * __restrict p1, } while (--lines > 0); } -static void __xor_neon_4(unsigned long bytes, unsigned long * __restrict p1, +void __xor_neon_4(unsigned long bytes, unsigned long * __restrict p1, const unsigned long * __restrict p2, const unsigned long * __restrict p3, const unsigned long * __restrict p4) @@ -117,7 +116,7 @@ static void __xor_neon_4(unsigned long bytes, unsigned long * __restrict p1, } while (--lines > 0); } -static void __xor_neon_5(unsigned long bytes, unsigned long * __restrict p1, +void __xor_neon_5(unsigned long bytes, unsigned long * __restrict p1, const unsigned long * __restrict p2, const unsigned long * __restrict p3, const unsigned long * __restrict p4, @@ -170,10 +169,3 @@ static void __xor_neon_5(unsigned long bytes, unsigned long * __restrict p1, dp5 += 8; } while (--lines > 0); } - -__DO_XOR_BLOCKS(neon_inner, __xor_neon_2, __xor_neon_3, __xor_neon_4, - __xor_neon_5); - -#ifdef CONFIG_ARM64 -extern typeof(__xor_neon_2) __xor_eor3_2 __alias(__xor_neon_2); -#endif diff --git a/lib/test_maple_tree.c b/lib/test_maple_tree.c index fb40e193a3cb76..10e5577ea0f190 100644 --- a/lib/test_maple_tree.c +++ b/lib/test_maple_tree.c @@ -3740,6 +3740,170 @@ static noinline void __init check_range64_in_rcu(struct maple_tree *mt) rcu_barrier(); } +/* + * A reader that restarts after its leaf died may find a tree without nodes: + * emptied, or emptied and then given a single entry at 0. Each case starts + * from a tree with nodes, built by check_seq(). The stores run while the + * reader holds rcu_read_lock, so they use GFP_ATOMIC. + */ +static noinline void __init check_restart_no_node(struct maple_tree *mt) +{ + void *ptr = xa_mk_value(1234); + void *entry; + MA_STATE(mas, mt, 0, 0); + + MT_BUG_ON(mt, !mtree_empty(mt)); + mt_set_non_kernel(99999); + + /* find: the tree is emptied */ + mt_init_flags(mt, MT_FLAGS_USE_RCU); + check_seq(mt, 100, false); + rcu_read_lock(); + mas_set(&mas, 0); + entry = mas_find(&mas, ULONG_MAX); + MT_BUG_ON(mt, entry != xa_mk_value(0)); + MT_BUG_ON(mt, mtree_store_range(mt, 0, ULONG_MAX, NULL, GFP_ATOMIC)); + entry = mas_find(&mas, ULONG_MAX); + MT_BUG_ON(mt, entry != NULL); + MT_BUG_ON(mt, mas.status != ma_none); + MT_BUG_ON(mt, mas.index != 0); + MT_BUG_ON(mt, mas.last != ULONG_MAX); + entry = mas_find(&mas, ULONG_MAX); + MT_BUG_ON(mt, entry != NULL); + MT_BUG_ON(mt, mas.status != ma_none); + rcu_read_unlock(); + mtree_destroy(mt); + rcu_barrier(); + + /* next: the tree is emptied */ + mt_init_flags(mt, MT_FLAGS_USE_RCU); + check_seq(mt, 100, false); + rcu_read_lock(); + mas_set(&mas, 0); + entry = mas_find(&mas, ULONG_MAX); + MT_BUG_ON(mt, entry != xa_mk_value(0)); + MT_BUG_ON(mt, mtree_store_range(mt, 0, ULONG_MAX, NULL, GFP_ATOMIC)); + entry = mas_next(&mas, ULONG_MAX); + MT_BUG_ON(mt, entry != NULL); + MT_BUG_ON(mt, mas.status != ma_none); + MT_BUG_ON(mt, mas.index != 0); + MT_BUG_ON(mt, mas.last != ULONG_MAX); + rcu_read_unlock(); + mtree_destroy(mt); + rcu_barrier(); + + /* find: the tree is emptied, then holds one entry at 0 */ + mt_init_flags(mt, MT_FLAGS_USE_RCU); + check_seq(mt, 100, false); + rcu_read_lock(); + mas_set(&mas, 0); + entry = mas_find(&mas, ULONG_MAX); + MT_BUG_ON(mt, entry != xa_mk_value(0)); + MT_BUG_ON(mt, mtree_store_range(mt, 0, ULONG_MAX, NULL, GFP_ATOMIC)); + MT_BUG_ON(mt, mtree_store(mt, 0, ptr, GFP_ATOMIC)); + entry = mas_find(&mas, ULONG_MAX); + MT_BUG_ON(mt, entry != NULL); + MT_BUG_ON(mt, mas.status != ma_none); + MT_BUG_ON(mt, mas.index != 1); + MT_BUG_ON(mt, mas.last != ULONG_MAX); + rcu_read_unlock(); + mtree_destroy(mt); + rcu_barrier(); + + /* find_rev: the tree is emptied */ + mt_init_flags(mt, MT_FLAGS_USE_RCU); + check_seq(mt, 100, false); + rcu_read_lock(); + mas_set(&mas, ULONG_MAX); + entry = mas_find_rev(&mas, 0); + MT_BUG_ON(mt, entry != xa_mk_value(100)); + MT_BUG_ON(mt, mtree_store_range(mt, 0, ULONG_MAX, NULL, GFP_ATOMIC)); + entry = mas_find_rev(&mas, 0); + MT_BUG_ON(mt, entry != NULL); + MT_BUG_ON(mt, mas.status != ma_none); + MT_BUG_ON(mt, mas.index != 0); + MT_BUG_ON(mt, mas.last != ULONG_MAX); + entry = mas_find_rev(&mas, 0); + MT_BUG_ON(mt, entry != NULL); + MT_BUG_ON(mt, mas.status != ma_none); + rcu_read_unlock(); + mtree_destroy(mt); + rcu_barrier(); + + /* prev: the tree is emptied, then holds one entry at 0 */ + mt_init_flags(mt, MT_FLAGS_USE_RCU); + check_seq(mt, 100, false); + rcu_read_lock(); + mas_set(&mas, ULONG_MAX); + entry = mas_find_rev(&mas, 0); + MT_BUG_ON(mt, entry != xa_mk_value(100)); + MT_BUG_ON(mt, mtree_store_range(mt, 0, ULONG_MAX, NULL, GFP_ATOMIC)); + MT_BUG_ON(mt, mtree_store(mt, 0, ptr, GFP_ATOMIC)); + entry = mas_prev(&mas, 0); + MT_BUG_ON(mt, entry != ptr); + MT_BUG_ON(mt, mas.status != ma_root); + MT_BUG_ON(mt, mas.index != 0); + MT_BUG_ON(mt, mas.last != 0); + rcu_read_unlock(); + mtree_destroy(mt); + rcu_barrier(); + + /* find_rev: the entry at 0 is below the minimum */ + mt_init_flags(mt, MT_FLAGS_USE_RCU); + check_seq(mt, 100, false); + rcu_read_lock(); + mas_set(&mas, ULONG_MAX); + entry = mas_find_rev(&mas, 1); + MT_BUG_ON(mt, entry != xa_mk_value(100)); + MT_BUG_ON(mt, mtree_store_range(mt, 0, ULONG_MAX, NULL, GFP_ATOMIC)); + MT_BUG_ON(mt, mtree_store(mt, 0, ptr, GFP_ATOMIC)); + entry = mas_find_rev(&mas, 1); + MT_BUG_ON(mt, entry != NULL); + MT_BUG_ON(mt, mas.status != ma_root); + MT_BUG_ON(mt, mas.index != 0); + MT_BUG_ON(mt, mas.last != 0); + rcu_read_unlock(); + mtree_destroy(mt); + rcu_barrier(); + + /* find_rev: the reader is at 0 when the tree gets one entry at 0 */ + mt_init_flags(mt, MT_FLAGS_USE_RCU); + check_seq(mt, 100, false); + rcu_read_lock(); + mas_set(&mas, 0); + entry = mas_find_rev(&mas, 0); + MT_BUG_ON(mt, entry != xa_mk_value(0)); + MT_BUG_ON(mt, mtree_store_range(mt, 0, ULONG_MAX, NULL, GFP_ATOMIC)); + MT_BUG_ON(mt, mtree_store(mt, 0, ptr, GFP_ATOMIC)); + entry = mas_find_rev(&mas, 0); + MT_BUG_ON(mt, entry != NULL); + MT_BUG_ON(mt, mas.status != ma_root); + MT_BUG_ON(mt, mas.index != 0); + MT_BUG_ON(mt, mas.last != 0); + rcu_read_unlock(); + mtree_destroy(mt); + rcu_barrier(); + + /* find_range_rev: the reader is at 0 when the tree gets one entry at 0 */ + mt_init_flags(mt, MT_FLAGS_USE_RCU); + check_seq(mt, 100, false); + rcu_read_lock(); + mas_set(&mas, 0); + entry = mas_find_range_rev(&mas, 0); + MT_BUG_ON(mt, entry != xa_mk_value(0)); + MT_BUG_ON(mt, mtree_store_range(mt, 0, ULONG_MAX, NULL, GFP_ATOMIC)); + MT_BUG_ON(mt, mtree_store(mt, 0, ptr, GFP_ATOMIC)); + entry = mas_find_range_rev(&mas, 0); + MT_BUG_ON(mt, entry != NULL); + MT_BUG_ON(mt, mas.status != ma_root); + MT_BUG_ON(mt, mas.index != 0); + MT_BUG_ON(mt, mas.last != 0); + rcu_read_unlock(); + mtree_destroy(mt); + rcu_barrier(); + mt_set_non_kernel(0); +} + static DEFINE_MTREE(tree); static int __init maple_tree_seed(void) { @@ -4031,6 +4195,7 @@ static int __init maple_tree_seed(void) check_range64_in_rcu(&tree); + check_restart_no_node(&tree); #if defined(BENCH) skip: diff --git a/lib/test_xarray.c b/lib/test_xarray.c index 5ca0aefee9aa5f..615f7730a5bd4a 100644 --- a/lib/test_xarray.c +++ b/lib/test_xarray.c @@ -1247,6 +1247,75 @@ static noinline void check_multi_find_3(struct xarray *xa) } } +static noinline void check_multi_find_4(struct xarray *xa) +{ +#ifdef CONFIG_XARRAY_MULTI + unsigned int order = XA_CHUNK_SHIFT + 1; + unsigned long next = 1UL << order; + unsigned long start = next - 1; + XA_STATE(xas, xa, start); + XA_STATE_ORDER(split, xa, 0, 0); + void *entry; + unsigned long i; + + /* Multi-index entry in two slots of a non-leaf node. */ + xa_store_order(xa, 0, order, xa_mk_index(0), GFP_KERNEL); + XA_BUG_ON(xa, xa_store_index(xa, next, GFP_KERNEL) != NULL); + + rcu_read_lock(); + entry = xas_find(&xas, ULONG_MAX); + XA_BUG_ON(xa, entry != xa_mk_index(0)); + XA_BUG_ON(xa, xas.xa_index != start); + + entry = xas_find(&xas, ULONG_MAX); + XA_BUG_ON(xa, entry != xa_mk_index(next)); + XA_BUG_ON(xa, xas.xa_index != next); + + entry = xas_find(&xas, ULONG_MAX); + XA_BUG_ON(xa, entry != NULL); + rcu_read_unlock(); + + xa_erase_index(xa, next); + xa_erase_index(xa, 0); + XA_BUG_ON(xa, !xa_empty(xa)); + + /* Split the multi-index entry after a lookup begins inside it. */ + xa_store_order(xa, 0, order, xa_mk_index(0), GFP_KERNEL); + XA_BUG_ON(xa, xa_store_index(xa, next, GFP_KERNEL) != NULL); + + xas_set(&xas, start); + rcu_read_lock(); + entry = xas_find(&xas, ULONG_MAX); + XA_BUG_ON(xa, entry != xa_mk_index(0)); + XA_BUG_ON(xa, xas.xa_index != start); + rcu_read_unlock(); + + xas_split_alloc(&split, xa_mk_index(0), order, GFP_KERNEL); + if (xas_error(&split)) { + XA_BUG_ON(xa, true); + goto out; + } + xas_lock(&split); + xas_split(&split, xa_mk_index(0), order); + for (i = 0; i < next; i++) + __xa_store(xa, i, xa_mk_index(i), 0); + xas_unlock(&split); + + rcu_read_lock(); + entry = xas_find(&xas, ULONG_MAX); + XA_BUG_ON(xa, entry != xa_mk_index(next)); + XA_BUG_ON(xa, xas.xa_index != next); + + entry = xas_find(&xas, ULONG_MAX); + XA_BUG_ON(xa, entry != NULL); + rcu_read_unlock(); + +out: + xa_destroy(xa); + XA_BUG_ON(xa, !xa_empty(xa)); +#endif +} + static noinline void check_find_1(struct xarray *xa) { unsigned long i, j, k; @@ -1370,6 +1439,7 @@ static noinline void check_find(struct xarray *xa) check_multi_find_1(xa, i); check_multi_find_2(xa); check_multi_find_3(xa); + check_multi_find_4(xa); } /* See find_swap_entry() in mm/shmem.c */ diff --git a/lib/xarray.c b/lib/xarray.c index bfe7bef80f34eb..48f440d114e15f 100644 --- a/lib/xarray.c +++ b/lib/xarray.c @@ -471,11 +471,12 @@ static void xas_shrink(struct xa_state *xas) if (!xa_is_node(entry)) RCU_INIT_POINTER(node->slots[0], XA_RETRY_ENTRY); xas_update(xas, node); + if (xa_is_node(entry)) + xa_to_node(entry)->parent = NULL; xa_node_free(node); if (!xa_is_node(entry)) break; node = xa_to_node(entry); - node->parent = NULL; } } @@ -1409,9 +1410,11 @@ void *xas_find(struct xa_state *xas, unsigned long max) entry = xas_load(xas); if (entry || xas_not_node(xas->xa_node)) return entry; - } else if (!xas->xa_node->shift && - xas->xa_offset != (xas->xa_index & XA_CHUNK_MASK)) { - xas->xa_offset = ((xas->xa_index - 1) & XA_CHUNK_MASK) + 1; + } else if (xas->xa_offset != get_offset(xas->xa_index, xas->xa_node)) { + if (!xas->xa_node->shift) + xas->xa_offset = ((xas->xa_index - 1) & XA_CHUNK_MASK) + 1; + else + xas->xa_offset = get_offset(xas->xa_index, xas->xa_node); } xas_next_offset(xas); diff --git a/mm/char-mem.c b/mm/char-mem.c index c5761ddedbd7df..53ce0034a4c13c 100644 --- a/mm/char-mem.c +++ b/mm/char-mem.c @@ -272,7 +272,7 @@ static pgprot_t phys_mem_access_prot(struct file *file, unsigned long pfn, unsigned long size, pgprot_t vma_prot) { #ifdef pgprot_noncached - phys_addr_t offset = pfn << PAGE_SHIFT; + phys_addr_t offset = PFN_PHYS(pfn); if (uncached_access(file, offset)) return pgprot_noncached(vma_prot); diff --git a/mm/damon/core.c b/mm/damon/core.c index 946b28440dff10..b8678a53b0a983 100644 --- a/mm/damon/core.c +++ b/mm/damon/core.c @@ -3975,10 +3975,11 @@ static int kdamond_wait_activation(struct damon_ctx *ctx) { struct damos *s; unsigned long wait_time; - unsigned long min_wait_time = 0; - bool init_wait_time = false; while (!kdamond_need_stop(ctx)) { + unsigned long min_wait_time = 0; + bool init_wait_time = false; + damon_for_each_scheme(s, ctx) { wait_time = damos_wmark_wait_us(s); if (!init_wait_time || wait_time < min_wait_time) { diff --git a/mm/damon/stat.c b/mm/damon/stat.c index b05b68f73e10de..e44f5bf3645ccf 100644 --- a/mm/damon/stat.c +++ b/mm/damon/stat.c @@ -32,8 +32,8 @@ static bool enabled __read_mostly = IS_ENABLED( module_param_cb(enabled, &enabled_param_ops, NULL, 0600); MODULE_PARM_DESC(enabled, "Enable of disable DAMON_STAT"); -static unsigned long estimated_memory_bandwidth __read_mostly; -module_param(estimated_memory_bandwidth, ulong, 0400); +static u64 estimated_memory_bandwidth __read_mostly; +module_param(estimated_memory_bandwidth, ullong, 0400); MODULE_PARM_DESC(estimated_memory_bandwidth, "Estimated memory bandwidth usage in bytes per second"); @@ -55,15 +55,18 @@ static void damon_stat_set_estimated_memory_bandwidth(struct damon_ctx *c) { struct damon_target *t; struct damon_region *r; - unsigned long access_bytes = 0; + u64 access_bytes = 0; + u64 remainder, bytes_per_us; damon_for_each_target(t, c) { damon_for_each_region(r, t) - access_bytes += (r->ar.end - r->ar.start) * + access_bytes += (u64)(r->ar.end - r->ar.start) * r->nr_accesses; } - estimated_memory_bandwidth = access_bytes * USEC_PER_MSEC * - MSEC_PER_SEC / c->attrs.aggr_interval; + bytes_per_us = div64_u64_rem(access_bytes, + c->attrs.aggr_interval, &remainder); + estimated_memory_bandwidth = bytes_per_us * USEC_PER_SEC + + div64_u64(remainder * USEC_PER_SEC, c->attrs.aggr_interval); } static int damon_stat_idletime(const struct damon_region *r) diff --git a/mm/damon/tests/sysfs-kunit.h b/mm/damon/tests/sysfs-kunit.h index 138a4b8d14e734..16373ba751dbc8 100644 --- a/mm/damon/tests/sysfs-kunit.h +++ b/mm/damon/tests/sysfs-kunit.h @@ -79,6 +79,15 @@ static void damon_sysfs_test_add_targets(struct kunit *test) kunit_skip(test, "ctx alloc fail"); } + if (damon_select_ops(ctx, DAMON_OPS_VADDR)) { + damon_destroy_ctx(ctx); + kfree(sysfs_targets->targets_arr); + kfree(sysfs_targets); + kfree(sysfs_target->regions); + kfree(sysfs_target); + kunit_skip(test, "vaddr ops not registered"); + } + damon_sysfs_add_targets(ctx, sysfs_targets); KUNIT_EXPECT_EQ(test, 1u, nr_damon_targets(ctx)); diff --git a/mm/filemap.c b/mm/filemap.c index b04be64a5069f4..3bf31cc9d27091 100644 --- a/mm/filemap.c +++ b/mm/filemap.c @@ -3047,10 +3047,11 @@ generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter) EXPORT_SYMBOL(generic_file_read_iter); /* - * Splice subpages from a folio into a pipe. + * Splice subpages from a folio into a pipe. Return the number of bytes spliced, + * or -EFAULT if we cannot splice from the folio. */ -size_t splice_folio_into_pipe(struct pipe_inode_info *pipe, - struct folio *folio, loff_t fpos, size_t size) +ssize_t splice_folio_into_pipe(struct pipe_inode_info *pipe, + struct folio *folio, loff_t fpos, size_t size) { struct page *page; size_t spliced = 0, offset = offset_in_folio(folio, fpos); @@ -3063,13 +3064,15 @@ size_t splice_folio_into_pipe(struct pipe_inode_info *pipe, struct pipe_buffer *buf = pipe_head_buf(pipe); size_t part = min_t(size_t, PAGE_SIZE - offset, size - spliced); + if (!folio_get_checked(folio)) + return spliced ? spliced : -EFAULT; + *buf = (struct pipe_buffer) { .ops = &page_cache_pipe_buf_ops, .page = page, .offset = offset, .len = part, }; - folio_get(folio); pipe->head++; page++; spliced += part; @@ -3094,9 +3097,10 @@ size_t splice_folio_into_pipe(struct pipe_inode_info *pipe, * Return: On success, the number of bytes read will be returned and *@ppos * will be updated if appropriate; 0 will be returned if there is no more data * to be read; -EAGAIN will be returned if the pipe had no space, and some - * other negative error code will be returned on error. A short read may occur - * if the pipe has insufficient space, we reach the end of the data or we hit a - * hole. + * other negative error code will be returned on error; -EFAULT will be returned + * if acquiring a folio reference fails and no data has been spliced. + * A short read may occur if the pipe has insufficient space, we reach the + * end of the data, hit a hole or hit a folio refcount limit. */ ssize_t filemap_splice_read(struct file *in, loff_t *ppos, struct pipe_inode_info *pipe, @@ -3154,7 +3158,7 @@ ssize_t filemap_splice_read(struct file *in, loff_t *ppos, for (i = 0; i < folio_batch_count(&fbatch); i++) { struct folio *folio = fbatch.folios[i]; - size_t n; + ssize_t n; if (folio_pos(folio) >= end_offset) goto out; @@ -3170,13 +3174,15 @@ ssize_t filemap_splice_read(struct file *in, loff_t *ppos, n = min_t(loff_t, len, isize - *ppos); n = splice_folio_into_pipe(pipe, folio, *ppos, n); - if (!n) + if (n <= 0) { + error = n; goto out; + } len -= n; total_spliced += n; *ppos += n; in->f_ra.prev_pos = *ppos; - if (pipe_is_full(pipe)) + if (pipe_is_full(pipe) || *ppos < folio_next_pos(folio)) goto out; } @@ -3774,6 +3780,8 @@ static struct folio *next_uptodate_folio(struct xa_state *xas, continue; if (!folio_try_get(folio)) continue; + if (unlikely(folio_ref_count_over_limit(folio))) + goto skip; if (folio_test_locked(folio)) goto skip; /* Has the page moved or been split? */ @@ -3968,6 +3976,13 @@ vm_fault_t filemap_map_pages(struct vm_fault *vmf, unsigned long end; vm_fault_t map_ret; + /* A lower index could move vmf->pte out of its page table. */ + if (unlikely(xas.xa_index < last_pgoff)) { + folio_unlock(folio); + folio_put(folio); + break; + } + addr += (xas.xa_index - last_pgoff) << PAGE_SHIFT; vmf->pte += xas.xa_index - last_pgoff; last_pgoff = xas.xa_index; @@ -4389,6 +4404,16 @@ ssize_t generic_perform_write(struct kiocb *iocb, struct iov_iter *i) break; } + /* + * Some filesystems can extend i_size even when nothing was copied. + * Prefault writes beyond EOF to catch unreadable source buffers. + */ + if (unlikely(pos > i_size_read(mapping->host)) && + fault_in_iov_iter_readable(i, bytes) == bytes) { + status = -EFAULT; + break; + } + status = a_ops->write_begin(iocb, mapping, pos, bytes, &folio, &fsdata); if (unlikely(status < 0)) diff --git a/mm/folio.c b/mm/folio.c index 35e242b48870b0..7a3394e7c5dca0 100644 --- a/mm/folio.c +++ b/mm/folio.c @@ -107,6 +107,32 @@ void __folio_put(struct folio *folio) } EXPORT_SYMBOL(__folio_put); +bool folio_ref_count_over_limit_slowpath(const struct folio *folio, + unsigned int ref_count) +{ + if (ref_count >= FOLIO_REF_COUNT_ADMIN_LIMIT) + goto over_limit; + /* Background threads must not consume admin reserves. */ + if (current->flags & PF_KTHREAD) + goto over_limit; + /* Neither must interrupt contexts on behalf of the interrupted task. */ + if (!in_task()) + goto over_limit; + /* Capability checks are not safe with IRQs disabled. */ + if (irqs_disabled()) + goto over_limit; + /* Use the task's credentials, which filesystem overrides cannot change. */ + if (has_capability_noaudit(current, CAP_SYS_RESOURCE)) + return false; + +over_limit: + pr_warn_ratelimited("folio:%p refcount:%d mapcount:%d mapping:%p index:%#lx reached refcount limit\n", + folio, (int)ref_count, folio_mapcount(folio), + folio_mapping(folio), folio->index); + return true; +} +EXPORT_SYMBOL_GPL(folio_ref_count_over_limit_slowpath); + typedef void (*move_fn_t)(struct lruvec *lruvec, struct folio *folio); static void lru_add(struct lruvec *lruvec, struct folio *folio) @@ -597,12 +623,10 @@ static void lru_lazyfree(struct lruvec *lruvec, struct folio *folio) folio_test_swapcache(folio) || folio_test_unevictable(folio)) return; + lru_gen_clear_refs(folio); lruvec_del_folio(lruvec, folio); folio_clear_active(folio); - if (lru_gen_enabled()) - lru_gen_clear_refs(folio); - else - folio_clear_referenced(folio); + folio_clear_referenced(folio); /* * Lazyfree folios are clean anonymous folios. They have * the swapbacked flag cleared, to distinguish them from normal diff --git a/mm/gup.c b/mm/gup.c index 2b405cce2ca5ca..7605da0e06d8d7 100644 --- a/mm/gup.c +++ b/mm/gup.c @@ -74,10 +74,14 @@ static inline void sanity_check_pinned_pages(struct page **pages, static inline struct folio *try_get_folio(struct page *page, int refs) { struct folio *folio; + int ref_count; retry: folio = page_folio(page); - if (WARN_ON_ONCE(folio_ref_count(folio) < 0)) + ref_count = folio_ref_count(folio); + if (WARN_ON_ONCE(ref_count < 0)) + return NULL; + if (unlikely(__folio_ref_count_over_limit(folio, ref_count))) return NULL; if (unlikely(!folio_ref_try_add(folio, refs))) return NULL; @@ -140,7 +144,13 @@ static void gup_put_folio(struct folio *folio, int refs, unsigned int flags) int __must_check try_grab_folio(struct folio *folio, int refs, unsigned int flags) { - if (WARN_ON_ONCE(folio_ref_count(folio) <= 0)) + const int ref_count = folio_ref_count(folio); + + if (WARN_ON_ONCE(ref_count <= 0)) + return -ENOMEM; + + if ((flags & (FOLL_GET | FOLL_PIN)) && + unlikely(__folio_ref_count_over_limit(folio, ref_count))) return -ENOMEM; if (unlikely(!(flags & FOLL_PCI_P2PDMA) && folio_is_pci_p2pdma(folio))) @@ -1482,17 +1492,17 @@ static long __get_user_pages(struct mm_struct *mm, struct folio *folio = page_folio(page); /* - * Since we already hold refcount on the - * large folio, this should never fail. + * Grabbing more references can fail once we + * hit folio refcount limits. */ - if (try_grab_folio(folio, page_increm - 1, - gup_flags)) { + ret = try_grab_folio(folio, page_increm - 1, + gup_flags); + if (ret) { /* - * Release the 1st page ref if the - * folio is problematic, fail hard. + * Release the folio reference we + * already took. */ gup_put_folio(folio, 1, gup_flags); - ret = -EFAULT; goto out; } } @@ -3538,10 +3548,10 @@ long memfd_pin_folios(struct file *memfd, loff_t start, loff_t end, break; } - if (try_grab_folio(folio, 1, FOLL_PIN)) { + ret = try_grab_folio(folio, 1, FOLL_PIN); + if (ret) { folio_unlock(folio); folio_batch_release(&fbatch); - ret = -EINVAL; goto err; } diff --git a/mm/huge_memory.c b/mm/huge_memory.c index eb913acb03b74b..d065b26a94dfac 100644 --- a/mm/huge_memory.c +++ b/mm/huge_memory.c @@ -1626,6 +1626,7 @@ static vm_fault_t insert_pmd(struct vm_area_struct *vma, unsigned long addr, { struct mm_struct *mm = vma->vm_mm; pgtable_t pgtable = NULL; + vm_fault_t ret = VM_FAULT_NOPAGE; spinlock_t *ptl; pmd_t entry; @@ -1662,6 +1663,10 @@ static vm_fault_t insert_pmd(struct vm_area_struct *vma, unsigned long addr, if (is_huge_zero_folio(fop.folio)) { entry = pmd_mkspecial(entry); } else { + if (unlikely(folio_ref_count_over_limit(fop.folio))) { + ret = VM_FAULT_SIGBUS; + goto out_unlock; + } folio_get(fop.folio); folio_add_file_rmap_pmd(fop.folio, &fop.folio->page, vma); add_mm_counter(mm, mm_counter_file(fop.folio), HPAGE_PMD_NR); @@ -1688,7 +1693,7 @@ static vm_fault_t insert_pmd(struct vm_area_struct *vma, unsigned long addr, spin_unlock(ptl); if (pgtable) pte_free(mm, pgtable); - return VM_FAULT_NOPAGE; + return ret; } /** @@ -1759,6 +1764,7 @@ static vm_fault_t insert_pud(struct vm_area_struct *vma, unsigned long addr, pud_t *pud, struct folio_or_pfn fop, pgprot_t prot, bool write) { struct mm_struct *mm = vma->vm_mm; + vm_fault_t ret = VM_FAULT_NOPAGE; spinlock_t *ptl; pud_t entry; @@ -1784,6 +1790,10 @@ static vm_fault_t insert_pud(struct vm_area_struct *vma, unsigned long addr, if (fop.is_folio) { entry = folio_mk_pud(fop.folio, vma->vm_page_prot); + if (unlikely(folio_ref_count_over_limit(fop.folio))) { + ret = VM_FAULT_SIGBUS; + goto out_unlock; + } folio_get(fop.folio); folio_add_file_rmap_pud(fop.folio, &fop.folio->page, vma); add_mm_counter(mm, mm_counter_file(fop.folio), HPAGE_PUD_NR); @@ -1799,7 +1809,7 @@ static vm_fault_t insert_pud(struct vm_area_struct *vma, unsigned long addr, update_mmu_cache_pud(vma, addr, pud); out_unlock: spin_unlock(ptl); - return VM_FAULT_NOPAGE; + return ret; } /** @@ -2095,6 +2105,14 @@ int copy_huge_pud(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma if (page) { struct folio *folio = page_folio(page); + if (unlikely(folio_ref_count_over_limit(folio))) { + /* + * VM_MIXEDMAP may contain driver-inserted pages with no + * fault handler to reconstruct the mapping. + */ + ret = (dst_vma->vm_flags & VM_MIXEDMAP) ? -ENOMEM : 0; + goto out_unlock; + } folio_get(folio); /* * TODO: once we support anonymous pages, use @@ -2403,6 +2421,7 @@ vm_fault_t do_huge_pmd_numa_page(struct vm_fault *vmf) return 0; } +#ifdef CONFIG_ADVISE_SYSCALLS /* * Return true if we do MADV_FREE successfully on entire pmd page. * Otherwise, return false. @@ -2437,21 +2456,13 @@ bool madvise_free_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma, if (folio_is_zone_device(folio)) goto out; - /* - * If other processes are mapping this folio, we couldn't discard - * the folio unless they all do MADV_FREE so let's skip the folio. - */ - if (folio_maybe_mapped_shared(folio)) - goto out; - - if (!folio_trylock(folio)) - goto out; - /* * If user want to discard part-pages of THP, split it so MADV_FREE * will deactivate only them. */ if (next - addr != HPAGE_PMD_SIZE) { + if (folio_maybe_mapped_shared(folio) || !folio_trylock(folio)) + goto out; folio_get(folio); spin_unlock(ptl); split_folio(folio); @@ -2460,9 +2471,8 @@ bool madvise_free_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma, goto out_unlocked; } - if (folio_test_dirty(folio)) - folio_clear_dirty(folio); - folio_unlock(folio); + if (!madvise_free_try_prepare_folio(folio, 1)) + goto out; if (pmd_young(orig_pmd) || pmd_dirty(orig_pmd)) { pmdp_invalidate(vma, addr, pmd); @@ -2480,6 +2490,7 @@ bool madvise_free_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma, out_unlocked: return ret; } +#endif /* CONFIG_ADVISE_SYSCALLS */ static inline void zap_deposited_table(struct mm_struct *mm, pmd_t *pmd) { @@ -2490,10 +2501,12 @@ static inline void zap_deposited_table(struct mm_struct *mm, pmd_t *pmd) mm_dec_nr_ptes(mm); } -static void zap_huge_pmd_folio(struct mm_struct *mm, struct vm_area_struct *vma, - pmd_t pmdval, struct folio *folio, bool is_present) +static void zap_huge_pmd_folio(struct mmu_gather *tlb, struct vm_area_struct *vma, + pmd_t pmdval, struct folio *folio, bool is_present, bool *force_flush) { const bool is_device_private = pmd_is_device_private_entry(pmdval); + struct mm_struct *mm = tlb->mm; + bool delay_rmap = false; if (folio_test_anon(folio)) { add_mm_counter(mm, MM_ANONPAGES, -HPAGE_PMD_NR); @@ -2501,23 +2514,42 @@ static void zap_huge_pmd_folio(struct mm_struct *mm, struct vm_area_struct *vma, add_mm_counter(mm, mm_counter_file(folio), -HPAGE_PMD_NR); - if (is_present && pmd_dirty(pmdval)) + if (is_present && pmd_dirty(pmdval)) { folio_mark_dirty(folio); + /* + * Remove rmap after the TLB flush if stale TLB entries + * could still be used to write to a mapping that + * supports writeback. + */ + if (!tlb->fullmm && vma->vm_file && + mapping_can_writeback(vma->vm_file->f_mapping)) + delay_rmap = tlb_can_delay_rmap(); + } if (is_present && pmd_young(pmdval) && likely(vma_has_recency(vma))) folio_mark_accessed(folio); } + if (!is_present && !is_device_private) + return; + /* * Present and device private folios are rmappable. Remove the * rmap after transferring young+dirty to the folio. */ - if (is_present || is_device_private) + if (!delay_rmap) folio_remove_rmap_pmd(folio, &folio->page, vma); - /* Device private folios are pinned. */ + /* Device private folios are pinned and don't need a TLB flush. */ if (is_device_private) folio_put(folio); + else if (__tlb_remove_page_size(tlb, &folio->page, HPAGE_PMD_SIZE)) + *force_flush = true; + + if (delay_rmap) { + tlb_flush_mmu_tlbonly(tlb); + folio_remove_rmap_pmd(folio, &folio->page, vma); + } } static struct folio *normal_or_softleaf_folio_pmd(struct vm_area_struct *vma, @@ -2555,6 +2587,7 @@ bool zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma, struct mm_struct *mm = tlb->mm; struct folio *folio = NULL; bool is_present = false; + bool force_flush = false; bool has_deposit; spinlock_t *ptl; pmd_t orig_pmd; @@ -2579,13 +2612,14 @@ bool zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma, folio = normal_or_softleaf_folio_pmd(vma, addr, orig_pmd, is_present); has_deposit = vma_has_deposited_pgtable(vma); if (folio) - zap_huge_pmd_folio(mm, vma, orig_pmd, folio, is_present); + zap_huge_pmd_folio(tlb, vma, orig_pmd, folio, is_present, + &force_flush); if (has_deposit) zap_deposited_table(mm, pmd); spin_unlock(ptl); - if (is_present && folio) - tlb_remove_page_size(tlb, &folio->page, HPAGE_PMD_SIZE); + if (force_flush) + tlb_flush_mmu(tlb); return true; } @@ -3775,6 +3809,7 @@ static void __split_folio_to_order(struct folio *folio, int old_order, * Don't pass it around before clear_compound_head(). */ struct folio *new_folio = (struct folio *)new_head; + memdesc_flags_t new_flags; VM_BUG_ON_PAGE(atomic_read(&new_folio->_mapcount) != -1, new_head); @@ -3791,8 +3826,15 @@ static void __split_folio_to_order(struct folio *folio, int old_order, * unreferenced sub-pages of an anonymous THP: we can simply drop * PG_anon_exclusive (-> PG_mappedtodisk) for these here. */ - new_folio->flags.f &= ~PAGE_FLAGS_CHECK_AT_PREP; - new_folio->flags.f |= (folio->flags.f & + new_flags.f = new_folio->flags.f & ~PAGE_FLAGS_CHECK_AT_PREP; + /* + * data_race() is used because folio->flags is only read here, + * but a reference-less writer can still write to it, e.g., + * PG_waiters update from softleaf_entry_wait_on_locked(). + * The flag is not transferred to new_flags as it is + * folio specific, so it is not lost. + */ + new_flags.f |= data_race(folio->flags.f) & ((1L << PG_referenced) | (1L << PG_swapbacked) | (1L << PG_swapcache) | @@ -3810,7 +3852,19 @@ static void __split_folio_to_order(struct folio *folio, int old_order, #endif (1L << PG_dirty) | (1L << PG_dropbehind) | - LRU_GEN_MASK | LRU_REFS_MASK)); + LRU_GEN_MASK | LRU_REFS_MASK); + + /* + * Set PG_head before smp_wmb() and clear_compound_head(). + * After clear_compound_head() marks new_head as a folio of its + * own, new_head->flags must not be modified by plain RMWs. + * A plain RMW can cause a loss of atomic PG_* updates from + * a reference-less writer, e.g., setting PG_waiters via + * softleaf_entry_wait_on_locked(). + */ + if (new_order) + new_flags.f |= 1L << PG_head; + WRITE_ONCE(new_folio->flags.f, new_flags.f); new_folio->mapping = folio->mapping; new_folio->index = folio->index + i; @@ -3840,7 +3894,11 @@ static void __split_folio_to_order(struct folio *folio, int old_order, */ clear_compound_head(new_head); if (new_order) { - prep_compound_page(new_head, new_order); + /* + * PG_head is set above, so only set up the remaining + * metadata on head page and tail pages. + */ + __prep_compound_page(new_head, new_order); folio_set_large_rmappable(new_folio); } @@ -4367,11 +4425,20 @@ static int __folio_split(struct folio *folio, unsigned int new_order, const bool is_swapcache = folio_test_swapcache(folio); int old_order = folio_order(folio); struct folio *new_folio, *next; + unsigned int nofs_flags; int ret; VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio); VM_WARN_ON_ONCE_FOLIO(!folio_test_large(folio), folio); + /* + * We might allocate memory while holding the folio lock. Direct + * reclaim or compaction could try evicting the inode, isolating and + * locking our folio, or wait for writeback on cgroup v1, to then + * deadlock on folio locks. + */ + nofs_flags = memalloc_nofs_save(); + if (folio != page_folio(split_at) || folio != page_folio(lock_at)) { ret = -EINVAL; goto out; @@ -4420,6 +4487,7 @@ static int __folio_split(struct folio *folio, unsigned int new_order, if (is_pmd_order(old_order)) count_vm_event(!ret ? THP_SPLIT_PAGE : THP_SPLIT_PAGE_FAILED); count_mthp_stat(old_order, !ret ? MTHP_STAT_SPLIT : MTHP_STAT_SPLIT_FAILED); + memalloc_nofs_restore(nofs_flags); return ret; } @@ -4551,10 +4619,14 @@ int folio_split(struct folio *folio, unsigned int new_order, * If a file-backed folio is truncated, 0 will be returned. Any subsequent * split attempt should get -EBUSY from split checking code. * + * Context: @folio must be locked. + * * Return: @folio's minimum order for split */ unsigned int min_order_for_split(struct folio *folio) { + VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio); + if (folio_test_anon(folio)) return 0; @@ -5215,6 +5287,16 @@ void remove_migration_pmd(struct page_vma_mapped_walk *pvmw, struct folio *folio if (!(pvmw->pmd && !pvmw->pte)) return; + if (!folio_test_anon(folio) && unlikely(folio_ref_count_over_limit(folio))) { + /* Leave the file mapping absent so it can be faulted in. */ + pmd_clear(pvmw->pmd); + if (arch_needs_pgtable_deposit()) + zap_deposited_table(mm, pvmw->pmd); + update_hiwater_rss(mm); + add_mm_counter(mm, mm_counter_file(folio), -HPAGE_PMD_NR); + return; + } + entry = softleaf_from_pmd(*pvmw->pmd); folio_get(folio); pmde = folio_mk_pmd(folio, READ_ONCE(vma->vm_page_prot)); diff --git a/mm/hugetlb.c b/mm/hugetlb.c index ce9c8e57b8e5c0..bf1d0474034e0c 100644 --- a/mm/hugetlb.c +++ b/mm/hugetlb.c @@ -5204,6 +5204,7 @@ unsigned long move_hugetlb_page_tables(struct vm_area_struct *vma, { struct hstate *h = hstate_vma(vma); struct address_space *mapping = vma->vm_file->f_mapping; + struct anon_vma *anon_vma = vma->anon_vma; unsigned long sz = huge_page_size(h); struct mm_struct *mm = vma->vm_mm; unsigned long old_end = old_addr + len; @@ -5227,6 +5228,8 @@ unsigned long move_hugetlb_page_tables(struct vm_area_struct *vma, /* Prevent race with file truncation */ hugetlb_vma_lock_write(vma); i_mmap_lock_write(mapping); + if (anon_vma) + anon_vma_lock_write(anon_vma); for (; old_addr < old_end; old_addr += sz, new_addr += sz) { const unsigned long offset_to_last_entry = (old_addr | last_addr_mask) - old_addr; @@ -5266,7 +5269,20 @@ unsigned long move_hugetlb_page_tables(struct vm_area_struct *vma, continue; } - dst_pte = huge_pte_alloc(mm, new_vma, new_addr, sz); + dst_pte = hugetlb_walk(new_vma, new_addr, sz); + if (!dst_pte) { + /* + * We can allocate memory under anon_vma lock with hugetlb, + * but lockdep does not know about that. So for now we simply + * flush the TLB and temporarily drop the lock. + */ + tlb_flush_mmu_tlbonly(&tlb); + if (anon_vma) + anon_vma_unlock_write(anon_vma); + dst_pte = huge_pte_alloc(mm, new_vma, new_addr, sz); + if (anon_vma) + anon_vma_lock_write(anon_vma); + } if (!dst_pte) break; @@ -5274,7 +5290,10 @@ unsigned long move_hugetlb_page_tables(struct vm_area_struct *vma, tlb_remove_huge_tlb_entry(h, &tlb, src_pte, old_addr); } + /* Flush pending moves before allowing migration to walk the entries. */ tlb_flush_mmu_tlbonly(&tlb); + if (anon_vma) + anon_vma_unlock_write(anon_vma); huge_pmd_unshare_flush(&tlb, vma); mmu_notifier_invalidate_range_end(&range); diff --git a/mm/internal.h b/mm/internal.h index e3f92883bf2384..96cb55d7816b13 100644 --- a/mm/internal.h +++ b/mm/internal.h @@ -61,6 +61,7 @@ void lru_add_drain_cpu(int cpu); void lru_add_drain_cpu_zone(struct zone *zone); void folio_deactivate(struct folio *folio); void folio_mark_lazyfree(struct folio *folio); +bool madvise_free_try_prepare_folio(struct folio *folio, int nr_mappings); /* mm/vmscan.c */ unsigned long zone_reclaimable_pages(struct zone *zone); @@ -834,6 +835,8 @@ static inline void prep_compound_tail(struct page *tail, VM_WARN_ON_ONCE(tail->private); } +void __prep_compound_page(struct page *page, unsigned int order); + #if defined CONFIG_COMPACTION || defined CONFIG_CMA /* @@ -1272,8 +1275,8 @@ struct migration_target_control { /* * mm/filemap.c */ -size_t splice_folio_into_pipe(struct pipe_inode_info *pipe, - struct folio *folio, loff_t fpos, size_t size); +ssize_t splice_folio_into_pipe(struct pipe_inode_info *pipe, + struct folio *folio, loff_t fpos, size_t size); static inline bool vma_is_single_threaded_private(struct vm_area_struct *vma) { diff --git a/mm/kasan/common.c b/mm/kasan/common.c index 7d21c4db68d20f..4187606a88cf4b 100644 --- a/mm/kasan/common.c +++ b/mm/kasan/common.c @@ -68,6 +68,7 @@ void kasan_set_track(struct kasan_track *track, depot_stack_handle_t stack) track->timestamp = ts_nsec >> 9; #endif /* CONFIG_KASAN_EXTRA_INFO */ track->pid = current->pid; + track->rcu_free = 0; track->stack = stack; } @@ -231,7 +232,7 @@ void * __must_check __kasan_init_slab_obj(struct kmem_cache *cache, /* Returns true when freeing the object is not safe. */ static bool check_slab_allocation(struct kmem_cache *cache, void *object, - unsigned long ip) + unsigned long ip, bool after_rcu_delay) { void *tagged_object = object; @@ -242,7 +243,8 @@ static bool check_slab_allocation(struct kmem_cache *cache, void *object, return true; } - if (!kasan_byte_accessible(tagged_object)) { + if (!kasan_byte_accessible(tagged_object) || + kasan_check_rcu_free(cache, object, after_rcu_delay)) { kasan_report_invalid_free(tagged_object, ip, KASAN_REPORT_DOUBLE_FREE); return true; } @@ -259,17 +261,18 @@ static inline void poison_slab_object(struct kmem_cache *cache, void *object, kasan_poison(object, round_up(cache->object_size, KASAN_GRANULE_SIZE), KASAN_SLAB_FREE, init); + kasan_clear_rcu_free(cache, object); if (kasan_stack_collection_enabled()) kasan_save_free_info(cache, tagged_object); } bool __kasan_slab_pre_free(struct kmem_cache *cache, void *object, - unsigned long ip) + unsigned long ip, bool after_rcu_delay) { if (is_kfence_address(object)) return false; - return check_slab_allocation(cache, object, ip); + return check_slab_allocation(cache, object, ip, after_rcu_delay); } bool __kasan_slab_free(struct kmem_cache *cache, void *object, bool init, @@ -544,7 +547,7 @@ bool __kasan_mempool_poison_object(void *ptr, unsigned long ip) slab = page_slab(page); - if (check_slab_allocation(slab->slab_cache, ptr, ip)) + if (check_slab_allocation(slab->slab_cache, ptr, ip, false)) return false; poison_slab_object(slab->slab_cache, ptr, false); diff --git a/mm/kasan/generic.c b/mm/kasan/generic.c index 2b8e73f5f6a70a..3532a41ce966ed 100644 --- a/mm/kasan/generic.c +++ b/mm/kasan/generic.c @@ -533,10 +533,13 @@ size_t kasan_metadata_size(struct kmem_cache *cache, bool in_object) } /* + * Records an auxiliary stack trace for the object at @addr and, if @rcu_free + * is set, marks the object as pending an RCU-delayed free. + * * This function avoids dynamic memory allocations and thus can be called from * contexts that do not allow allocating memory. */ -void kasan_record_aux_stack(void *addr) +static void __kasan_record_aux_stack(void *addr, bool rcu_free) { struct slab *slab = kasan_addr_to_slab(addr); struct kmem_cache *cache; @@ -552,10 +555,22 @@ void kasan_record_aux_stack(void *addr) if (!alloc_meta) return; + if (rcu_free) + alloc_meta->alloc_track.rcu_free = 1; alloc_meta->aux_stack[1] = alloc_meta->aux_stack[0]; alloc_meta->aux_stack[0] = kasan_save_stack(0, 0); } +void kasan_record_aux_stack(void *addr) +{ + __kasan_record_aux_stack(addr, false); +} + +void kasan_mark_rcu_free_pending(void *addr) +{ + __kasan_record_aux_stack(addr, true); +} + void kasan_save_alloc_info(struct kmem_cache *cache, void *object, gfp_t flags) { struct kasan_alloc_meta *alloc_meta; diff --git a/mm/kasan/kasan.h b/mm/kasan/kasan.h index fc9169a547662b..43d6088995441a 100644 --- a/mm/kasan/kasan.h +++ b/mm/kasan/kasan.h @@ -191,7 +191,10 @@ static inline bool kasan_requires_meta(void) #define KASAN_STACK_DEPTH 64 struct kasan_track { - u32 pid; +#define KASAN_PID_BITS const_ilog2(PID_MAX_LIMIT) + u32 pid:KASAN_PID_BITS; + u32 rcu_free:1; + u32 unused:32 - (KASAN_PID_BITS + 1); depot_stack_handle_t stack; #ifdef CONFIG_KASAN_EXTRA_INFO u64 cpu:20; @@ -390,8 +393,37 @@ struct kasan_alloc_meta *kasan_get_alloc_meta(struct kmem_cache *cache, struct kasan_free_meta *kasan_get_free_meta(struct kmem_cache *cache, const void *object); void kasan_init_object_meta(struct kmem_cache *cache, const void *object); + +static inline bool kasan_check_rcu_free(struct kmem_cache *cache, + const void *object, + bool after_rcu_delay) +{ + struct kasan_alloc_meta *alloc_meta; + + alloc_meta = kasan_get_alloc_meta(cache, object); + if (!alloc_meta) + return false; + + return alloc_meta->alloc_track.rcu_free != after_rcu_delay; +} + +static inline void kasan_clear_rcu_free(struct kmem_cache *cache, + const void *object) +{ + struct kasan_alloc_meta *alloc_meta; + + alloc_meta = kasan_get_alloc_meta(cache, object); + if (alloc_meta) + alloc_meta->alloc_track.rcu_free = 0; +} #else static inline void kasan_init_object_meta(struct kmem_cache *cache, const void *object) { } +static inline bool kasan_check_rcu_free(struct kmem_cache *cache, const void *object, + bool after_rcu_delay) +{ + return false; +} +static inline void kasan_clear_rcu_free(struct kmem_cache *cache, const void *object) { } #endif depot_stack_handle_t kasan_save_stack(gfp_t flags, depot_flags_t depot_flags); diff --git a/mm/kasan/kasan_test_c.c b/mm/kasan/kasan_test_c.c index b9e167ed5be328..3c9ffee8001b8f 100644 --- a/mm/kasan/kasan_test_c.c +++ b/mm/kasan/kasan_test_c.c @@ -30,6 +30,7 @@ #include #include "kasan.h" +#include "../slab.h" #define OOB_TAG_OFF (IS_ENABLED(CONFIG_KASAN_GENERIC) ? 0 : KASAN_GRANULE_SIZE) @@ -1070,6 +1071,139 @@ static void kmem_cache_double_free(struct kunit *test) kmem_cache_destroy(cache); } +#ifndef MODULE +static void __kmem_cache_double_free_rcu(struct kunit *test, int mode) +{ + struct kasan_rcu_info *p, *victim = NULL, **objs; + struct kmem_cache *cache; + int i, n = 0; + + KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_KASAN_GENERIC); + KASAN_TEST_NEEDS_CONFIG_OFF(test, CONFIG_PREEMPT_RT); + + cache = kmem_cache_create("test_cache", sizeof(*p), 0, SLAB_NO_MERGE, + NULL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, cache); + + if (!cache->sheaf_capacity) { + kmem_cache_destroy(cache); + kunit_skip(test, "Test requires sheaves"); + } + + objs = kunit_kcalloc(test, cache->sheaf_capacity * 2, sizeof(*objs), + GFP_KERNEL); + if (!objs) { + kunit_err(test, "Allocation failed: %s\n", __func__); + goto out; + } + + migrate_disable(); + + p = kmem_cache_alloc(cache, GFP_KERNEL); + if (!p) { + migrate_enable(); + kunit_err(test, "Allocation failed: %s\n", __func__); + goto out; + } + + switch (mode) { + case 1: + kmem_cache_free(cache, p); + /* p is already in quarantine. */ + KUNIT_EXPECT_KASAN_FAIL(test, kfree_rcu(p, rcu)); + migrate_enable(); + break; + case 2: + /* The actual free order is inverse. */ + kfree_rcu(p, rcu); + KUNIT_EXPECT_KASAN_FAIL(test, kmem_cache_free(cache, p)); + migrate_enable(); + break; + case 3: + kfree_rcu(p, rcu); + + for (i = 0; i < cache->sheaf_capacity - 1; i++) { + objs[i] = kmem_cache_alloc(cache, GFP_KERNEL); + kfree_rcu(objs[i], rcu); + } + + KUNIT_EXPECT_KASAN_FAIL(test, kfree_rcu(p, rcu)); + migrate_enable(); + + /* + * Move the 1st full sheaf to quarantine, keeping the + * 2nd in pcs->rcu_free. + */ + rcu_barrier(); + break; + } + + /* + * Move p to quarantine if not poisoned yet (case 2, + * or fallback in case 3). + */ + if (kasan_byte_accessible(p)) + kvfree_rcu_barrier_on_cache(cache); + + /* + * Evict p from quarantine and reallocate it as a live victim object + * before the RCU sheaf is flushed. + */ + kasan_quarantine_remove_cache(cache); + + for (i = 0; i < cache->sheaf_capacity * 2; i++) { + objs[n] = kmem_cache_alloc(cache, GFP_KERNEL); + if (!objs[n]) + break; + if (objs[n] == p) { + victim = objs[n]; + break; + } + n++; + } + + for (i = 0; i < n; i++) + kmem_cache_free(cache, objs[i]); + + KUNIT_EXPECT_PTR_EQ(test, victim, p); + if (victim != p) + goto out; + + WRITE_ONCE(victim->i, 42); + + /* + * If kfree_rcu() failed to reject the double-free above, + * flushing the RCU sheaf will silently poison the live + * victim and cause a false-positive UAF on victim->i. + */ + kvfree_rcu_barrier_on_cache(cache); + KUNIT_EXPECT_EQ(test, READ_ONCE(victim->i), 42); + + if (!READ_ONCE(test_status.report_found)) + kmem_cache_free(cache, victim); +out: + kmem_cache_destroy(cache); +} + +static void kmem_cache_double_free_rcu_1(struct kunit *test) +{ + /* kmem_cache_free() -> kfree_rcu() */ + __kmem_cache_double_free_rcu(test, 1); +} + +static void kmem_cache_double_free_rcu_2(struct kunit *test) +{ + /* kfree_rcu() -> kmem_cache_free() */ + __kmem_cache_double_free_rcu(test, 2); +} + +static void kmem_cache_double_free_rcu_3(struct kunit *test) +{ + /* kfree_rcu() -> kfree_rcu() */ + __kmem_cache_double_free_rcu(test, 3); +} +#endif + static void kmem_cache_invalid_free(struct kunit *test) { char *p; @@ -2239,6 +2373,11 @@ static struct kunit_case kasan_kunit_test_cases[] = { KUNIT_CASE(kfree_via_phys), KUNIT_CASE(kmem_cache_oob), KUNIT_CASE(kmem_cache_double_free), +#ifndef MODULE + KUNIT_CASE(kmem_cache_double_free_rcu_1), + KUNIT_CASE(kmem_cache_double_free_rcu_2), + KUNIT_CASE(kmem_cache_double_free_rcu_3), +#endif KUNIT_CASE(kmem_cache_invalid_free), KUNIT_CASE(kmem_cache_rcu_uaf), KUNIT_CASE(kmem_cache_rcu_reuse), diff --git a/mm/khugepaged.c b/mm/khugepaged.c index 4bbe319ef86fa3..964f78c3856ba3 100644 --- a/mm/khugepaged.c +++ b/mm/khugepaged.c @@ -1888,6 +1888,12 @@ static enum scan_result try_collapse_pte_mapped_thp(struct mm_struct *mm, unsign goto drop_folio; } + /* Leave any uninitialized folios to the page fault path. */ + if (!folio_test_uptodate(folio)) { + result = SCAN_FAIL; + goto drop_folio; + } + result = find_pmd_or_thp_or_none(mm, haddr, &pmd); switch (result) { case SCAN_SUCCEED: diff --git a/mm/list_lru.c b/mm/list_lru.c index d1d256822ccc73..651983d0bf8bff 100644 --- a/mm/list_lru.c +++ b/mm/list_lru.c @@ -72,12 +72,15 @@ static int lru_shrinker_id(struct list_lru *lru) } static inline struct list_lru_one * -list_lru_from_memcg_idx(struct list_lru *lru, int nid, int idx) +list_lru_from_memcg(struct list_lru *lru, int nid, struct mem_cgroup *memcg) { + int idx = memcg_kmem_id(memcg); + if (list_lru_memcg_aware(lru) && idx >= 0) { struct list_lru_memcg *mlru = xa_load(&lru->xa, idx); - return mlru ? &mlru->node[nid] : NULL; + /* Lists at a reused index belong to another memcg. */ + return mlru && mlru->memcg == memcg ? &mlru->node[nid] : NULL; } return &lru->node[nid].lru; } @@ -91,7 +94,7 @@ lock_list_lru_of_memcg(struct list_lru *lru, int nid, rcu_read_lock(); again: - l = list_lru_from_memcg_idx(lru, nid, memcg_kmem_id(*memcg)); + l = list_lru_from_memcg(lru, nid, *memcg); if (likely(l)) { lock_list_lru(l, irq, irq_flags); if (likely(READ_ONCE(l->nr_items) != LONG_MIN)) { @@ -132,7 +135,7 @@ static inline bool list_lru_memcg_aware(struct list_lru *lru) } static inline struct list_lru_one * -list_lru_from_memcg_idx(struct list_lru *lru, int nid, int idx) +list_lru_from_memcg(struct list_lru *lru, int nid, struct mem_cgroup *memcg) { return &lru->node[nid].lru; } @@ -313,7 +316,7 @@ unsigned long list_lru_count_one(struct list_lru *lru, long count; rcu_read_lock(); - l = list_lru_from_memcg_idx(lru, nid, memcg_kmem_id(memcg)); + l = list_lru_from_memcg(lru, nid, memcg); count = l ? READ_ONCE(l->nr_items) : 0; rcu_read_unlock(); @@ -502,11 +505,10 @@ static void memcg_reparent_list_lru_one(struct list_lru *lru, int nid, struct list_lru_one *src, struct mem_cgroup *dst_memcg) { - int dst_idx = dst_memcg->kmemcg_id; struct list_lru_one *dst; spin_lock_irq(&src->lock); - dst = list_lru_from_memcg_idx(lru, nid, dst_idx); + dst = list_lru_from_memcg(lru, nid, dst_memcg); spin_lock_nested(&dst->lock, SINGLE_DEPTH_NESTING); list_splice_init(&src->list, &dst->list); @@ -566,9 +568,19 @@ void memcg_reparent_list_lrus(struct mem_cgroup *memcg, struct mem_cgroup *paren static inline bool memcg_list_lru_allocated(struct mem_cgroup *memcg, struct list_lru *lru) { + struct list_lru_memcg *mlru; + bool allocated; int idx = memcg->kmemcg_id; - return idx < 0 || xa_load(&lru->xa, idx); + if (idx < 0) + return true; + + rcu_read_lock(); + mlru = xa_load(&lru->xa, idx); + allocated = mlru && mlru->memcg == memcg; + rcu_read_unlock(); + + return allocated; } static int __memcg_list_lru_alloc(struct mem_cgroup *memcg, @@ -602,6 +614,8 @@ static int __memcg_list_lru_alloc(struct mem_cgroup *memcg, if (!mlru) return -ENOMEM; } + /* Set before the lists are published, and never changed after. */ + mlru->memcg = pos; xas_set(&xas, pos->kmemcg_id); do { xas_lock_irqsave(&xas, flags); @@ -645,9 +659,16 @@ int folio_memcg_list_lru_alloc(struct folio *folio, struct list_lru *lru, if (likely(res)) return 0; - /* Allocation may block, pin the memcg */ + /* + * Allocation may block, so pin the memcg. If the folio's cgroup + * was removed after the check above, the folio has moved up to a + * parent memcg. That memcg may already have its lists, or may be + * the root, which uses the global lists and has no parent. So + * check again before allocating. + */ memcg = get_mem_cgroup_from_folio(folio); - res = __memcg_list_lru_alloc(memcg, lru, gfp); + if (!memcg_list_lru_allocated(memcg, lru)) + res = __memcg_list_lru_alloc(memcg, lru, gfp); mem_cgroup_put(memcg); return res; } diff --git a/mm/madvise.c b/mm/madvise.c index 0214efd2a014f9..ebb4ce7daf6cb1 100644 --- a/mm/madvise.c +++ b/mm/madvise.c @@ -661,6 +661,38 @@ static long madvise_pageout(struct madvise_behavior *madv_behavior) return 0; } +bool madvise_free_try_prepare_folio(struct folio *folio, int nr_mappings) +{ + if (!folio_test_swapcache(folio) && !folio_test_dirty(folio)) + return true; + + if (folio_mapcount(folio) != nr_mappings || !folio_trylock(folio)) + return false; + + /* + * KSM folios can gain new mappings at any time, so we must + * not clear their dirty flag. + */ + if (folio_test_ksm(folio)) + goto unlock; + + /* + * Check under the folio lock that the folio is exclusive: we own all + * mappings, and there are no references from swap entries. + */ + if (folio_mapcount(folio) != nr_mappings) + goto unlock; + if (folio_test_swapcache(folio) && !folio_free_swap(folio)) + goto unlock; + + folio_clear_dirty(folio); + folio_unlock(folio); + return true; +unlock: + folio_unlock(folio); + return false; +} + static int madvise_free_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end, struct mm_walk *walk) @@ -753,37 +785,8 @@ static int madvise_free_pte_range(pmd_t *pmd, unsigned long addr, } } - if (folio_test_swapcache(folio) || folio_test_dirty(folio)) { - if (!folio_trylock(folio)) - continue; - /* - * KSM folios can gain new mappings at any time, so we must - * not clear their dirty flag. - */ - if (folio_test_ksm(folio)) { - folio_unlock(folio); - continue; - } - - /* - * If we have a large folio at this point, we know it is - * fully mapped so if its mapcount is the same as its - * number of pages, it must be exclusive. - */ - if (folio_mapcount(folio) != folio_nr_pages(folio)) { - folio_unlock(folio); - continue; - } - - if (folio_test_swapcache(folio) && - !folio_free_swap(folio)) { - folio_unlock(folio); - continue; - } - - folio_clear_dirty(folio); - folio_unlock(folio); - } + if (!madvise_free_try_prepare_folio(folio, folio_nr_pages(folio))) + continue; if (pte_young(ptent) || pte_dirty(ptent)) { clear_young_dirty_ptes(vma, addr, pte, nr, cydp_flags); diff --git a/mm/memcontrol.c b/mm/memcontrol.c index 84f4a8fd4d16f1..afbb638e7e1cbb 100644 --- a/mm/memcontrol.c +++ b/mm/memcontrol.c @@ -1451,7 +1451,13 @@ void mem_cgroup_scan_tasks(struct mem_cgroup *memcg, struct css_task_iter it; struct task_struct *task; - css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it); + /* + * An OOM victim can start exiting well before its mm is + * torn down. Keep it visible so oom_evaluate_task() can + * back off while there's still memory to free. + */ + css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS | + CSS_TASK_ITER_WITH_DEAD, &it); while (!ret && (task = css_task_iter_next(&it))) { ret = fn(task, arg); /* Avoid potential softlockup warning */ @@ -3526,6 +3532,8 @@ static void __refill_obj_stock(struct obj_cgroup *objcg, int i, slot = -1, empty_slot = -1; if (!stock) { + nr_bytes += atomic_read(&objcg->nr_charged_bytes) + ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0; nr_pages = nr_bytes >> PAGE_SHIFT; nr_bytes = nr_bytes & (PAGE_SIZE - 1); atomic_add(nr_bytes, &objcg->nr_charged_bytes); diff --git a/mm/memfd.c b/mm/memfd.c index 0e3ff3eebfa829..05088ab210baba 100644 --- a/mm/memfd.c +++ b/mm/memfd.c @@ -32,6 +32,13 @@ static bool memfd_folio_has_extra_refs(struct folio *folio) { + /* + * Use the precise pincount where available to avoid racy refcount + * comparisons. + */ + if (folio_has_pincount(folio) && folio_maybe_dma_pinned(folio)) + return true; + return folio_ref_count(folio) != folio_expected_ref_count(folio); } diff --git a/mm/memory-failure.c b/mm/memory-failure.c index b705f9f97f420f..b215312f261b83 100644 --- a/mm/memory-failure.c +++ b/mm/memory-failure.c @@ -1320,13 +1320,13 @@ static bool panic_on_unrecoverable_mf(enum mf_action_page_type type, static int action_result(unsigned long pfn, enum mf_action_page_type type, enum mf_result result) { - trace_memory_failure_event(pfn, type, result); - if (type != MF_MSG_ALREADY_POISONED && type != MF_MSG_PFN_MAP) { num_poisoned_pages_inc(pfn); update_per_node_mf_stats(pfn, result); } + trace_memory_failure_event(pfn, type, result); + pr_err("%#lx: recovery action for %s: %s\n", pfn, action_page_types[type], action_name[result]); @@ -1744,26 +1744,6 @@ static int identify_page_state(unsigned long pfn, struct page *p, return page_action(ps, p, pfn); } -/* - * When 'release' is 'false', it means that if thp split has failed, - * there is still more to do, hence the page refcount we took earlier - * is still needed. - */ -static int try_to_split_thp_page(struct page *page, unsigned int new_order, - bool release) -{ - int ret; - - lock_page(page); - ret = split_huge_page_to_order(page, new_order); - unlock_page(page); - - if (ret && release) - put_page(page); - - return ret; -} - static void unmap_and_kill(struct list_head *to_kill, unsigned long pfn, struct address_space *mapping, pgoff_t index, int flags) { @@ -2548,9 +2528,6 @@ int memory_failure(unsigned long pfn, int flags) folio_unlock(folio); if (folio_test_large(folio)) { - const int new_order = min_order_for_split(folio); - int err; - /* * The flag must be set after the refcount is bumped * otherwise it may race with THP split. @@ -2565,24 +2542,25 @@ int memory_failure(unsigned long pfn, int flags) * page is a valid handlable page. */ folio_set_has_hwpoisoned(folio); - err = try_to_split_thp_page(p, new_order, /* release= */ false); + + folio_lock(folio); + split_huge_page_to_order(p, min_order_for_split(folio)); + folio = page_folio(p); + folio_unlock(folio); + /* * If splitting a folio to order-0 fails, kill the process. * Split the folio regardless to minimize unusable pages. * Because the memory failure code cannot handle large * folios, this split is always treated as if it failed. */ - if (err || new_order) { - /* get folio again in case the original one is split */ - folio = page_folio(p); + if (folio_test_large(folio)) { res = -EHWPOISON; kill_procs_now(p, pfn, flags, folio); - put_page(p); + folio_put(folio); action_result(pfn, MF_MSG_UNSPLIT_THP, MF_FAILED); goto unlock_mutex; } - VM_BUG_ON_PAGE(!page_count(p), p); - folio = page_folio(p); } /* @@ -2900,25 +2878,26 @@ static int soft_offline_in_use_page(struct page *page) .reason = MR_MEMORY_FAILURE, }; + folio_lock(folio); if (!huge && folio_test_large(folio)) { - const int new_order = min_order_for_split(folio); - /* - * If new_order (target split order) is not 0, do not split the - * folio at all to retain the still accessible large folio. - * NOTE: if minimizing the number of soft offline pages is - * preferred, split it to non-zero new_order like it is done in - * memory_failure(). + * If we cannot split to order-0, do not split the folio at all + * to retain the still accessible large folio. */ - if (new_order || try_to_split_thp_page(page, /* new_order= */ 0, - /* release= */ true)) { + if (!min_order_for_split(folio)) + ret = split_huge_page_to_order(page, 0) ? -EBUSY : 0; + else + ret = -EBUSY; + folio = page_folio(page); + + if (ret) { + folio_unlock(folio); + folio_put(folio); pr_info("%#lx: thp split failed\n", pfn); - return -EBUSY; + return ret; } - folio = page_folio(page); } - folio_lock(folio); if (!huge) folio_wait_writeback(folio); if (PageHWPoison(page)) { diff --git a/mm/memory.c b/mm/memory.c index ec3d9d99ccee2f..05d350efc84bb0 100644 --- a/mm/memory.c +++ b/mm/memory.c @@ -1168,7 +1168,10 @@ static __always_inline void __copy_present_ptes(struct vm_area_struct *dst_vma, * consecutive pages of the same folio by copying them as well. * * Returns -EAGAIN if one preallocated page is required to copy the next PTE. - * Otherwise, returns the number of copied PTEs (at least 1). + * Returns -ENOMEM if the file folio refcount is too high and the PTE must + * be copied. + * Returns -EHWPOISON if copying a page fails. + * Otherwise, returns the number of processed PTEs (at least 1). */ static inline int copy_present_ptes(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma, @@ -1186,6 +1189,20 @@ copy_present_ptes(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma folio = page_folio(page); + if (!folio_test_anon(folio) && unlikely(folio_ref_count_over_limit(folio))) { + /* + * VM_MIXEDMAP may contain pages inserted by a driver at mmap + * time, with no fault handler to restore a missing PTE. + */ + if (dst_vma->vm_flags & VM_MIXEDMAP) + return -ENOMEM; + if (userfaultfd_pte_rwp(dst_vma, pte)) + return -ENOMEM; + /* Preserve uffd-wp protection when faulting the page back in. */ + cond_install_uffd_wp_ptes(dst_vma, addr, dst_pte, pte, 1); + return 1; + } + /* * If we likely have to copy, just don't bother with batching. Make * sure that the common "small folio" case is as fast as possible @@ -1367,9 +1384,9 @@ copy_pte_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma, /* * If we need a pre-allocated page for this pte, drop the * locks, allocate, and try again. - * If copy failed due to hwpoison in source page, break out. + * Other errors abort the copy after releasing the page table locks. */ - if (unlikely(ret == -EAGAIN || ret == -EHWPOISON)) + if (unlikely(ret < 0)) break; if (unlikely(prealloc)) { /* @@ -1399,7 +1416,7 @@ copy_pte_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma, goto out; } entry.val = 0; - } else if (ret == -EBUSY || unlikely(ret == -EHWPOISON)) { + } else if (ret == -EBUSY || ret == -ENOMEM || unlikely(ret == -EHWPOISON)) { goto out; } else if (ret == -EAGAIN) { prealloc = folio_prealloc(src_mm, src_vma, addr, false); @@ -1740,7 +1757,7 @@ static __always_inline void zap_present_folio_ptes(struct mmu_gather *tlb, ptent = get_and_clear_full_ptes(mm, addr, pte, nr, tlb->fullmm); if (pte_dirty(ptent)) { folio_mark_dirty(folio); - if (tlb_delay_rmap(tlb)) { + if (tlb_can_delay_rmap()) { delay_rmap = true; *force_flush = true; } @@ -2059,8 +2076,8 @@ static unsigned long zap_pte_range(struct mmu_gather *tlb, pte_unmap_unlock(start_pte, ptl); /* - * If we forced a TLB flush (either due to running out of - * batch buffers or because we needed to flush dirty TLB + * If we forced a TLB flush (either to release batched + * references or because we needed to flush dirty TLB * entries before releasing the ptl), free the batched * memory too. Come back again if we didn't do everything. */ @@ -2474,6 +2491,8 @@ static int insert_page_into_pte_locked(struct vm_area_struct *vma, pte_t *pte, if (unlikely(is_zero_folio(folio))) { pteval = pte_mkspecial(pteval); } else { + if (unlikely(folio_ref_count_over_limit(folio))) + return -EOVERFLOW; folio_get(folio); pteval = mk_pte(page, prot); if (mkwrite) { @@ -4130,8 +4149,11 @@ static vm_fault_t wp_page_copy(struct vm_fault *vmf) entry = folio_mk_pte(new_folio, vma->vm_page_prot); entry = pte_sw_mkyoung(entry); if (unlikely(unshare)) { + entry = pte_mkdirty(entry); if (pte_soft_dirty(vmf->orig_pte)) entry = pte_mksoft_dirty(entry); + else + entry = pte_clear_soft_dirty(entry); if (pte_uffd(vmf->orig_pte)) { entry = pte_mkuffd(entry); if (userfaultfd_rwp(vma)) @@ -4959,13 +4981,8 @@ static void folio_pte_range(const struct folio *folio, { /* Stay within the page table and VMA boundaries. */ const unsigned long pmd_start = addr & PMD_MASK; - const unsigned long pmd_end = pmd_start + PMD_SIZE; const unsigned long lower = max(pmd_start, vma->vm_start); - /* - * We cannot use pmd_addr_end(), as it does not clamp reliably. To - * avoid wraparounds, compute using the inclusive end. - */ - const unsigned long upper = min(pmd_end - 1, vma->vm_end - 1) + 1; + const unsigned long upper = pte_table_clamped_end(addr, vma->vm_end); const unsigned long offset = idx << PAGE_SHIFT; /* @@ -5508,8 +5525,7 @@ void map_anon_folio_pte_nopf(struct folio *folio, pte_t *pte, entry = pte_sw_mkyoung(entry); - if (vma->vm_flags & VM_WRITE) - entry = pte_mkwrite(pte_mkdirty(entry), vma); + entry = maybe_mkwrite(pte_mkdirty(entry), vma); if (uffd_wp) entry = pte_mkuffd(entry); @@ -5752,6 +5768,9 @@ vm_fault_t do_set_pmd(struct vm_fault *vmf, struct folio *folio, struct page *pa if (unlikely(folio_test_has_hwpoisoned(folio))) return ret; + if (unlikely(folio_ref_count_over_limit(folio))) + return VM_FAULT_SIGBUS; + /* * Archs like ppc64 need additional space to store information * related to pte entry. Use the preallocated table for that. @@ -5806,6 +5825,9 @@ vm_fault_t do_set_pmd(struct vm_fault *vmf, struct folio *folio, struct page *pa * @page: The first page to create a PTE for. * @nr: The number of PTEs to create. * @addr: The first address to create a PTE for. + * + * For file mappings, the caller must check folio_ref_count_over_limit() + * before installing PTEs. */ void set_pte_range(struct vm_fault *vmf, struct folio *folio, struct page *page, unsigned int nr, unsigned long addr) @@ -5832,6 +5854,12 @@ void set_pte_range(struct vm_fault *vmf, struct folio *folio, /* copy-on-write page */ if (write && !(vma->vm_flags & VM_SHARED)) { VM_BUG_ON_FOLIO(nr != 1, folio); + /* + * Concurrent zapping might have dropped the PTL but not flushed + * the TLB yet. Flush before installing a new folio. + */ + if (mm_tlb_flush_pending(vma->vm_mm)) + flush_tlb_page(vma, addr); folio_add_new_anon_rmap(folio, vma, addr, RMAP_EXCLUSIVE); folio_add_lru_vma(folio, vma); } else { @@ -5972,6 +6000,10 @@ vm_fault_t finish_fault(struct vm_fault *vmf) goto fallback; } + if (!is_cow && unlikely(folio_ref_count_over_limit(folio))) { + ret = VM_FAULT_SIGBUS; + goto unlock; + } folio_ref_add(folio, nr_pages - 1); set_pte_range(vmf, folio, page, nr_pages, addr); type = is_cow ? MM_ANONPAGES : mm_counter_file(folio); diff --git a/mm/mempolicy.c b/mm/mempolicy.c index c7d4d149c9b883..ffe4e45cc97d18 100644 --- a/mm/mempolicy.c +++ b/mm/mempolicy.c @@ -207,15 +207,22 @@ static u8 get_il_weight(int node) */ static void reduce_interleave_weights(unsigned int *bw, u8 *new_iw) { + nodemask_t nodes = NODE_MASK_NONE; u64 sum_bw = 0; unsigned int cast_sum_bw, scaling_factor = 1, iw_gcd = 0; int nid; - for_each_node_state(nid, N_MEMORY) + /* + * N_MEMORY can change while wi_state_lock is held. Remember the + * nodes contributing to sum_bw so all passes use the same set. + */ + for_each_node_state(nid, N_MEMORY) { + node_set(nid, nodes); sum_bw += bw[nid]; + } /* Scale bandwidths to whole numbers in the range [1, weightiness] */ - for_each_node_state(nid, N_MEMORY) { + for_each_node_mask(nid, nodes) { /* * Try not to perform 64-bit division. * If sum_bw < scaling_factor, then sum_bw < U32_MAX. @@ -234,7 +241,7 @@ static void reduce_interleave_weights(unsigned int *bw, u8 *new_iw) } /* 1:2 is strictly better than 16:32. Reduce by the weights' GCD. */ - for_each_node_state(nid, N_MEMORY) + for_each_node_mask(nid, nodes) new_iw[nid] /= iw_gcd; } diff --git a/mm/migrate.c b/mm/migrate.c index 875079464930a4..7841968dd1f528 100644 --- a/mm/migrate.c +++ b/mm/migrate.c @@ -385,6 +385,17 @@ static bool remove_migration_pte(struct folio *folio, try_to_map_unused_to_zeropage(&pvmw, folio, old_pte, idx)) continue; + if (!folio_test_anon(folio) && !folio_test_hugetlb(folio) && + unlikely(folio_ref_count_over_limit(folio))) { + /* File contents remain available for a later fault. */ + pte_clear(vma->vm_mm, pvmw.address, pvmw.pte); + cond_install_uffd_wp_ptes(vma, pvmw.address, + pvmw.pte, old_pte, 1); + update_hiwater_rss(vma->vm_mm); + dec_mm_counter(vma->vm_mm, mm_counter_file(folio)); + continue; + } + folio_get(folio); new = folio_page(folio, idx); pte = mk_pte(new, READ_ONCE(vma->vm_page_prot)); @@ -700,6 +711,16 @@ static int __folio_migrate_mapping(struct address_space *mapping, mod_lruvec_state(old_lruvec, NR_SHMEM_THPS, -nr); mod_lruvec_state(new_lruvec, NR_SHMEM_THPS, nr); } + } else if (!folio_test_swapbacked(folio) && + folio_test_pmd_mappable(folio)) { + mod_lruvec_state(old_lruvec, NR_FILE_THPS, -nr); + mod_lruvec_state(new_lruvec, NR_FILE_THPS, nr); + } + if (test_bit(AS_KERNEL_FILE, &mapping->flags)) { + __mod_node_page_state(oldzone->zone_pgdat, + NR_KERNEL_FILE_PAGES, -nr); + __mod_node_page_state(newzone->zone_pgdat, + NR_KERNEL_FILE_PAGES, nr); } #ifdef CONFIG_SWAP if (folio_test_swapcache(folio)) { @@ -1209,25 +1230,15 @@ static void migrate_folio_done(struct folio *src, } /* Obtain the lock on page, remove all ptes. */ -static int migrate_folio_unmap(new_folio_t get_new_folio, - free_folio_t put_new_folio, unsigned long private, - struct folio *src, struct folio **dstp, enum migrate_mode mode, - struct list_head *ret) +static int migrate_folio_unmap(struct folio *src, struct folio *dst, + enum migrate_mode mode, struct list_head *ret) { - struct folio *dst; int rc = -EAGAIN; int old_folio_state = 0; struct anon_vma *anon_vma = NULL; bool locked = false; bool dst_locked = false; - dst = get_new_folio(src, private); - if (!dst) - return -ENOMEM; - *dstp = dst; - - dst->migrate_info = 0; - if (!folio_trylock(src)) { if (mode == MIGRATE_ASYNC) goto out; @@ -1353,7 +1364,8 @@ static int migrate_folio_unmap(new_folio_t get_new_folio, migrate_folio_undo_src(src, old_folio_state & FOLIO_WAS_MAPPED, anon_vma, locked, ret); - migrate_folio_undo_dst(dst, dst_locked, put_new_folio, private); + if (dst_locked) + folio_unlock(dst); return rc; } @@ -1798,6 +1810,25 @@ static void migrate_folios_undo(struct list_head *src_folios, } } +static void migrate_folio_free_dst(struct folio *dst, + free_folio_t put_new_folio, unsigned long private) +{ + list_del(&dst->lru); + dst->private = NULL; + migrate_folio_undo_dst(dst, false, put_new_folio, private); +} + +static void migrate_folios_undo_unused(struct list_head *pending_folios, + struct list_head *new_folios, free_folio_t put_new_folio, + unsigned long private, struct list_head *from) +{ + struct folio *dst, *tmp; + + list_for_each_entry_safe(dst, tmp, new_folios, lru) + migrate_folio_free_dst(dst, put_new_folio, private); + list_splice(pending_folios, from); +} + /* * migrate_pages_batch() first unmaps folios in the from list as many as * possible, then move the unmapped folios. @@ -1820,8 +1851,10 @@ static int migrate_pages_batch(struct list_head *from, int pass = 0; bool is_thp = false; bool is_large = false; - struct folio *folio, *folio2, *dst = NULL; + struct folio *folio, *dst, *tmp; int rc, rc_saved = 0, nr_pages; + LIST_HEAD(pending_folios); + LIST_HEAD(new_folios); LIST_HEAD(unmap_folios); LIST_HEAD(dst_folios); bool nosplit = (reason == MR_NUMA_MISPLACED); @@ -1834,7 +1867,13 @@ static int migrate_pages_batch(struct list_head *from, thp_retry = 0; nr_retry_pages = 0; - list_for_each_entry_safe(folio, folio2, from, lru) { + /* + * Prepare the source folios, and allocate the destination + * folios before locking any source folio. We must be careful + * when allocating memory while holding folio locks, so just + * avoid it. + */ + list_for_each_entry_safe(folio, tmp, from, lru) { is_large = folio_test_large(folio); is_thp = folio_test_pmd_mappable(folio); nr_pages = folio_nr_pages(folio); @@ -1914,21 +1953,24 @@ static int migrate_pages_batch(struct list_head *from, continue; } - rc = migrate_folio_unmap(get_new_folio, put_new_folio, - private, folio, &dst, mode, ret_folios); /* - * The rules are: - * 0: folio will be put on unmap_folios list, - * dst folio put on dst_folios list - * -EAGAIN: stay on the from list - * -ENOMEM: stay on the from list - * Other errno: put on ret_folios list + * Don't allocate while holding folio locks, but leave + * the folio to the one-by-one fallback in + * migrate_pages_sync(). */ - switch(rc) { - case -ENOMEM: + if (!list_empty(&unmap_folios)) { + retry++; + thp_retry += is_thp; + nr_retry_pages += nr_pages; + continue; + } + + dst = get_new_folio(folio, private); + if (!dst) { /* * When memory is low, don't bother to try to migrate - * other folios, move unmapped folios, then exit. + * other folios, migrate the folios that we have + * destination folios for, then exit. */ nr_failed++; stats->nr_thp_failed += is_thp; @@ -1939,7 +1981,7 @@ static int migrate_pages_batch(struct list_head *from, if (!ret) { stats->nr_thp_split += is_thp; stats->nr_split++; - break; + continue; } else if (reason == MR_LONGTERM_PIN && ret == -EAGAIN) { /* @@ -1952,18 +1994,42 @@ static int migrate_pages_batch(struct list_head *from, /* Undo duplicated failure counting. */ nr_failed--; stats->nr_thp_failed -= is_thp; - break; + continue; } } - stats->nr_failed_pages += nr_pages + nr_retry_pages; - /* nr_failed isn't updated for not used */ - stats->nr_thp_failed += thp_retry; - rc_saved = rc; - if (list_empty(&unmap_folios)) - goto out; - else - goto move; + stats->nr_failed_pages += nr_pages; + rc_saved = -ENOMEM; + break; + } + /* Remember the source folio until we unmap it. */ + dst->private = folio; + list_move_tail(&folio->lru, &pending_folios); + list_add_tail(&dst->lru, &new_folios); + } + + /* + * Lock and unmap the source folios. Each destination folio + * remembers its source folio in ->private, so walk the + * destination folios. + */ + list_for_each_entry_safe(dst, tmp, &new_folios, lru) { + folio = dst->private; + is_thp = folio_test_pmd_mappable(folio); + nr_pages = folio_nr_pages(folio); + + cond_resched_tasks_rcu_qs(); + + rc = migrate_folio_unmap(folio, dst, mode, ret_folios); + /* + * The rules are: + * 0: folio will be put on unmap_folios list, + * dst folio put on dst_folios list + * -EAGAIN: stay on the pending_folios list, + * keep dst + * Other errno: put on ret_folios list, free dst + */ + switch (rc) { case -EAGAIN: retry++; thp_retry += is_thp; @@ -1971,7 +2037,7 @@ static int migrate_pages_batch(struct list_head *from, break; case 0: list_move_tail(&folio->lru, &unmap_folios); - list_add_tail(&dst->lru, &dst_folios); + list_move_tail(&dst->lru, &dst_folios); break; default: /* @@ -1980,12 +2046,24 @@ static int migrate_pages_batch(struct list_head *from, * removed from migration folio list and not * retried in the next outer loop. */ + migrate_folio_free_dst(dst, put_new_folio, + private); nr_failed++; stats->nr_thp_failed += is_thp; stats->nr_failed_pages += nr_pages; break; } } + + if (rc_saved) { + stats->nr_failed_pages += nr_retry_pages; + /* We return rc_saved, so don't update nr_failed. */ + stats->nr_thp_failed += thp_retry; + rc = rc_saved; + if (list_empty(&unmap_folios)) + goto out; + goto move; + } } nr_failed += retry; stats->nr_thp_failed += thp_retry; @@ -2015,6 +2093,8 @@ static int migrate_pages_batch(struct list_head *from, /* Cleanup remaining folios */ migrate_folios_undo(&unmap_folios, &dst_folios, put_new_folio, private, ret_folios); + migrate_folios_undo_unused(&pending_folios, &new_folios, put_new_folio, + private, from); return rc; } diff --git a/mm/migrate_device.c b/mm/migrate_device.c index 9e19fadfa65c67..b4660eeb975a7d 100644 --- a/mm/migrate_device.c +++ b/mm/migrate_device.c @@ -87,39 +87,20 @@ static int migrate_vma_split_folio(struct folio *folio, { int ret; struct folio *fault_folio = fault_page ? page_folio(fault_page) : NULL; - struct folio *new_fault_folio = NULL; - - if (folio != fault_folio) - folio_lock(folio); - - ret = split_folio(folio); - if (ret) { - if (folio != fault_folio) { - folio_unlock(folio); - folio_put(folio); - } - return ret; - } - - new_fault_folio = fault_page ? page_folio(fault_page) : NULL; /* - * Ensure the lock is held on the correct - * folio after the split + * The lock and the reference of the fault handler stay with the + * folio which holds the fault page after the split. */ - if (!new_fault_folio) { - folio_unlock(folio); - folio_put(folio); - } else if (folio != new_fault_folio) { - if (new_fault_folio != fault_folio) { - folio_get(new_fault_folio); - folio_lock(new_fault_folio); - } - folio_unlock(folio); - folio_put(folio); - } + if (folio == fault_folio) + return split_huge_page(fault_page); - return 0; + folio_lock(folio); + ret = split_folio(folio); + folio_unlock(folio); + folio_put(folio); + + return ret; } /** migrate_vma_collect_huge_pmd - collect THP pages without splitting the @@ -252,18 +233,25 @@ static int migrate_vma_collect_pmd(pmd_t *pmdp, struct mm_struct *mm = vma->vm_mm; unsigned long addr = start, unmapped = 0; spinlock_t *ptl; - struct folio *fault_folio = migrate->fault_page ? - page_folio(migrate->fault_page) : NULL; + struct folio *fault_folio; pte_t *ptep; again: + /* The fault page is in another folio once its folio has been split */ + fault_folio = migrate->fault_page ? + page_folio(migrate->fault_page) : NULL; + + /* [start, addr) is collected if we get here after splitting a folio */ if (pmd_trans_huge(*pmdp) || !pmd_present(*pmdp)) { - int ret = migrate_vma_collect_huge_pmd(pmdp, start, end, walk, fault_folio); + int ret = migrate_vma_collect_huge_pmd(pmdp, addr, end, walk, fault_folio); if (ret == -EAGAIN) goto again; - if (ret == 0) + if (ret == 0) { + if (unmapped) + flush_tlb_range(walk->vma, start, end); return 0; + } } ptep = pte_offset_map_lock(mm, pmdp, start, &ptl); @@ -564,6 +552,27 @@ static bool migrate_vma_check_page(struct page *page, struct page *fault_page) return true; } +/* + * Pin the anonymous rmap if present to allow migration entries to be safely + * removed. Returns true if the pin succeeded or no pin is required, and false + * if the folio is no longer mapped. + */ +static bool pin_anon_rmap(struct folio *folio, unsigned long *src_pfn) +{ + if (!folio_test_anon(folio) || folio_test_ksm(folio)) + return true; + if (!folio_get_anon_vma(folio)) /* Pin the anon rmap. */ + return false; + *src_pfn |= MIGRATE_PFN_ANON_RMAP; + return true; +} + +static void unpin_anon_rmap(struct folio *folio, unsigned long src_pfn) +{ + if (src_pfn & MIGRATE_PFN_ANON_RMAP) + put_anon_vma(folio_anon_vma(folio)); /* Unpin the anon rmap. */ +} + /* * Unmaps pages for migration. Returns number of source pfns marked as * migrating. @@ -645,6 +654,7 @@ static unsigned long migrate_device_unmap(unsigned long *src_pfns, folio = page_folio(page); remove_migration_ptes(folio, folio, 0); + unpin_anon_rmap(folio, src_pfns[i]); src_pfns[i] = 0; if (fault_folio != folio) @@ -833,6 +843,13 @@ static int migrate_vma_insert_huge_pmd_page(struct migrate_vma *migrate, goto abort; } + if (folio_memcg_alloc_deferred(folio)) { + count_vm_event(THP_FAULT_FALLBACK); + count_mthp_stat(HPAGE_PMD_ORDER, MTHP_STAT_ANON_FAULT_FALLBACK); + ret = -ENOMEM; + goto abort; + } + __folio_mark_uptodate(folio); pgtable = pte_alloc_one(vma->vm_mm); @@ -1212,6 +1229,11 @@ static void __migrate_device_pages(unsigned long *src_pfns, if (folio_is_device_private(newfolio) || folio_is_device_coherent(newfolio)) { + /* KSM does not scan or track device pages. */ + if (folio_test_ksm(folio)) { + src_pfns[i] &= ~MIGRATE_PFN_MIGRATE; + goto next; + } if (mapping) { /* * For now only support anonymous memory migrating to @@ -1331,6 +1353,7 @@ static void __migrate_device_finalize(unsigned long *src_pfns, if (!folio_is_zone_device(dst)) folio_add_lru(dst); remove_migration_ptes(src, dst, 0); + unpin_anon_rmap(src, src_pfns[i]); if (fault_folio != src) folio_unlock(src); folio_put(src); @@ -1380,6 +1403,7 @@ EXPORT_SYMBOL(migrate_vma_finalize); static unsigned long migrate_device_pfn_lock(unsigned long pfn) { + unsigned long src_pfn = migrate_pfn(pfn) | MIGRATE_PFN_MIGRATE; struct folio *folio; folio = folio_get_nontail_page(pfn_to_page(pfn)); @@ -1391,7 +1415,13 @@ static unsigned long migrate_device_pfn_lock(unsigned long pfn) return 0; } - return migrate_pfn(pfn) | MIGRATE_PFN_MIGRATE; + if (!pin_anon_rmap(folio, &src_pfn)) { + folio_unlock(folio); + folio_put(folio); + return 0; + } + + return src_pfn; } /** @@ -1427,6 +1457,7 @@ int migrate_device_range(unsigned long *src_pfns, unsigned long start, nr = folio_nr_pages(folio); if (nr > npages - i) { if (src_pfns[i] & MIGRATE_PFN_MIGRATE) { + unpin_anon_rmap(folio, src_pfns[i]); folio_unlock(folio); folio_put(folio); } @@ -1470,6 +1501,7 @@ int migrate_device_pfns(unsigned long *src_pfns, unsigned long npages) nr = folio_nr_pages(folio); if (nr > npages - i) { if (src_pfns[i] & MIGRATE_PFN_MIGRATE) { + unpin_anon_rmap(folio, src_pfns[i]); folio_unlock(folio); folio_put(folio); } @@ -1505,6 +1537,11 @@ int migrate_device_coherent_folio(struct folio *folio) folio_lock(folio); src_pfn = migrate_pfn(folio_pfn(folio)) | MIGRATE_PFN_MIGRATE; + if (!pin_anon_rmap(folio, &src_pfn)) { + folio_unlock(folio); + folio_put(folio); + return -EBUSY; + } /* * We don't have a VMA and don't need to walk the page tables to find diff --git a/mm/mmu_gather.c b/mm/mmu_gather.c index 9f353f0e2ef4d2..fc547be33a919b 100644 --- a/mm/mmu_gather.c +++ b/mm/mmu_gather.c @@ -49,7 +49,6 @@ static bool tlb_next_batch(struct mmu_gather *tlb) return true; } -#ifdef CONFIG_SMP static void tlb_flush_rmap_batch(struct mmu_gather_batch *batch, struct vm_area_struct *vma) { struct encoded_page **pages = batch->encoded_pages; @@ -91,7 +90,6 @@ void tlb_flush_rmaps(struct mmu_gather *tlb, struct vm_area_struct *vma) tlb_flush_rmap_batch(tlb->active, vma); tlb->delayed_rmap = 0; } -#endif /* * We might end up freeing a lot of pages. Reschedule on a regular @@ -171,6 +169,8 @@ static bool __tlb_remove_folio_pages_size(struct mmu_gather *tlb, struct mmu_gather_batch *batch; VM_BUG_ON(!tlb->end); + if (delay_rmap) + tlb->delayed_rmap = 1; #ifdef CONFIG_MMU_GATHER_PAGE_SIZE VM_WARN_ON(tlb->page_size != page_size); @@ -179,10 +179,7 @@ static bool __tlb_remove_folio_pages_size(struct mmu_gather *tlb, #endif batch = tlb->active; - /* - * Add the page and check if we are full. If so - * force a flush. - */ + /* Add the pages before deciding whether we need to flush. */ if (likely(nr_pages == 1)) { batch->encoded_pages[batch->nr++] = encode_page(page, flags); } else { @@ -190,6 +187,11 @@ static bool __tlb_remove_folio_pages_size(struct mmu_gather *tlb, batch->encoded_pages[batch->nr++] = encode_page(page, flags); batch->encoded_pages[batch->nr++] = encode_nr_pages(nr_pages); } + /* Flush pending references well before new references are refused. */ + if (unlikely((unsigned int)folio_ref_count(page_folio(page)) >= + FOLIO_REF_COUNT_FLUSH_LIMIT)) + return true; + /* * Make sure that we can always add another "page" + "nr_pages", * requiring two entries instead of only a single one. diff --git a/mm/page_alloc.c b/mm/page_alloc.c index 6624293e4d7875..2fef4092c913c1 100644 --- a/mm/page_alloc.c +++ b/mm/page_alloc.c @@ -681,18 +681,31 @@ static inline bool pcp_allowed_order(unsigned int order) * This usage means that zero-order pages may not be compound. */ -void prep_compound_page(struct page *page, unsigned int order) +/* + * Set up the metadata on head page and tail pages. + * Caller must set PG_head before this. + */ +void __prep_compound_page(struct page *page, unsigned int order) { int i; int nr_pages = 1 << order; - __SetPageHead(page); for (i = 1; i < nr_pages; i++) prep_compound_tail(page + i, page, order); prep_compound_head(page, order); } +/* + * PG_head is set non-atomically. It should be used when no one else can modify + * @page's flags. + */ +void prep_compound_page(struct page *page, unsigned int order) +{ + __SetPageHead(page); + __prep_compound_page(page, order); +} + static inline void set_buddy_order(struct page *page, unsigned int order) { set_page_private(page, order); diff --git a/mm/rmap.c b/mm/rmap.c index 0faef46806e5ca..65646ed6fc4536 100644 --- a/mm/rmap.c +++ b/mm/rmap.c @@ -973,7 +973,7 @@ static bool folio_referenced_one(struct folio *folio, pteval = ptep_get(pvmw.pte); if (pvmw.pte && pte_present(pteval) && folio_test_large(folio)) { - const unsigned long end_addr = pmd_addr_end(address, vma->vm_end); + const unsigned long end_addr = pte_table_clamped_end(address, vma->vm_end); const unsigned int max_nr = (end_addr - address) >> PAGE_SHIFT; nr = folio_pte_batch(folio, pvmw.pte, pteval, max_nr); @@ -1978,7 +1978,7 @@ static inline unsigned int folio_unmap_pte_batch(struct folio *folio, return 1; /* We may only batch within a single VMA and a single page table. */ - end_addr = pmd_addr_end(addr, vma->vm_end); + end_addr = pte_table_clamped_end(addr, vma->vm_end); max_nr = (end_addr - addr) >> PAGE_SHIFT; /* We only support lazyfree or file folios batching for now ... */ diff --git a/mm/shmem.c b/mm/shmem.c index 10cef89b00b087..a5713109c843c9 100644 --- a/mm/shmem.c +++ b/mm/shmem.c @@ -758,6 +758,13 @@ shmem_unused_huge_alloc_lru(struct shmem_sb_info *sbinfo, struct folio *folio, { int ret; + /* + * A migration target is in the page cache before it is charged. Once + * charged, its objcg can't change while we hold a folio reference. + */ + if (!mem_cgroup_disabled() && !folio_memcg_charged(folio)) + return ERR_PTR(-EAGAIN); + ret = folio_memcg_list_lru_alloc(folio, &sbinfo->shrinklist, gfp); if (ret) return ERR_PTR(ret); @@ -887,12 +894,11 @@ static enum lru_status shmem_unused_huge_isolate(struct list_head *item, return LRU_REMOVED; } + /* keep shrinklist_objcg, requeue may need it */ list_lru_isolate(lru, item); - objcg = shmem_get_and_clear_objcg(info); set_shmem_unused_huge_isolated(info); list_add_tail(&info->shrinklist, &scan->list); spin_unlock(&info->lock); - obj_cgroup_put(objcg); return LRU_REMOVED; } @@ -928,10 +934,26 @@ static bool is_shmem_unused_huge_match(struct folio *folio, static void shmem_unused_huge_drop(struct inode *inode) { struct shmem_inode_info *info = SHMEM_I(inode); + struct obj_cgroup *objcg; spin_lock(&info->lock); list_del_init(&info->shrinklist); + objcg = shmem_get_and_clear_objcg(info); spin_unlock(&info->lock); + + obj_cgroup_put(objcg); +} + +static void shmem_unused_huge_requeue_locked(struct shmem_inode_info *info, + struct shmem_sb_info *sbinfo, + int nid) +{ + lockdep_assert_held(&info->lock); + + list_del_init(&info->shrinklist); + shmem_unused_huge_lru_add(sbinfo, &info->shrinklist, nid, + info->shrinklist_objcg); + info->shrinklist_nid = nid; } static void shmem_unused_huge_requeue(struct inode *inode, struct folio *folio) @@ -943,17 +965,18 @@ static void shmem_unused_huge_requeue(struct inode *inode, struct folio *folio) objcg = shmem_unused_huge_alloc_lru(sbinfo, folio, GFP_NOWAIT); if (IS_ERR(objcg)) { - shmem_unused_huge_drop(inode); + spin_lock(&info->lock); + shmem_unused_huge_requeue_locked(info, sbinfo, nid); + spin_unlock(&info->lock); return; } spin_lock(&info->lock); - /* Requeue the inode to shrinklist */ - list_del_init(&info->shrinklist); - shmem_unused_huge_lru_add(sbinfo, &info->shrinklist, nid, objcg); - info->shrinklist_objcg = objcg; - info->shrinklist_nid = nid; + swap(info->shrinklist_objcg, objcg); + shmem_unused_huge_requeue_locked(info, sbinfo, nid); spin_unlock(&info->lock); + + obj_cgroup_put(objcg); } static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo, @@ -2612,11 +2635,14 @@ static int shmem_swapin_folio(struct inode *inode, pgoff_t index, * and swap cache folios are never partially freed. */ folio_lock(folio); - if (!folio_matches_swap_entry(folio, swap) || - shmem_confirm_swap(mapping, index, swap) < 0) { + if (!folio_matches_swap_entry(folio, swap)) { error = -EEXIST; goto unlock; } + if (shmem_confirm_swap(mapping, index, swap) < 0) { + error = -EEXIST; + goto failed; + } if (!folio_test_uptodate(folio)) { error = -EIO; goto failed; @@ -2657,6 +2683,17 @@ static int shmem_swapin_folio(struct inode *inode, pgoff_t index, error = -EEXIST; if (error == -EIO) shmem_set_folio_swapin_error(inode, index, folio, swap); + /* + * A large folio that does not fit the mapping, e.g. because its swap + * entries were freed and reused, would be found again on every retry. + * Drop it from the swap cache so the retry can swap in a fitting one. + * A failed swap write sets dirty and then ends writeback without the + * folio lock, so test writeback before dirty. + */ + if (error == -EEXIST && folio && folio_test_large(folio) && + !folio_test_anon(folio) && !folio_test_writeback(folio) && + !folio_test_dirty(folio)) + swap_cache_del_folio(folio); unlock: if (folio) folio_unlock(folio); @@ -3737,7 +3774,8 @@ static ssize_t shmem_file_splice_read(struct file *in, loff_t *ppos, struct inode *inode = file_inode(in); struct address_space *mapping = inode->i_mapping; struct folio *folio = NULL; - size_t total_spliced = 0, used, npages, n, part; + size_t total_spliced = 0, used, npages, part; + ssize_t n; loff_t isize; int error = 0; @@ -3823,8 +3861,10 @@ static ssize_t shmem_file_splice_read(struct file *in, loff_t *ppos, n = splice_zeropage_into_pipe(pipe, *ppos, part); } - if (!n) + if (n <= 0) { + error = n; break; + } len -= n; total_spliced += n; *ppos += n; diff --git a/mm/slub.c b/mm/slub.c index cd671b93471918..5c33d124706015 100644 --- a/mm/slub.c +++ b/mm/slub.c @@ -2722,7 +2722,7 @@ bool slab_free_hook(struct kmem_cache *s, void *x, bool init, * Give KASAN a chance to notice an invalid free operation before we * modify the object. */ - if (kasan_slab_pre_free(s, x)) + if (kasan_slab_pre_free(s, x, after_rcu_delay)) return false; #ifdef CONFIG_SLUB_RCU_DEBUG @@ -2738,7 +2738,7 @@ bool slab_free_hook(struct kmem_cache *s, void *x, bool init, * We have to do this manually because the rcu_head is * not located inside the object. */ - kasan_record_aux_stack(x); + kasan_mark_rcu_free_pending(x); delayed_free->object = x; call_rcu(&delayed_free->head, slab_free_after_rcu_debug); @@ -6298,6 +6298,12 @@ bool __kfree_rcu_sheaf(struct kmem_cache *s, void *obj, unsigned int free_flags) } do_free: + if (unlikely(kasan_slab_pre_free(s, obj, false))) { + local_unlock(&s->cpu_sheaves->lock); + goto out; + } + + kasan_mark_rcu_free_pending(obj); rcu_sheaf = pcs->rcu_free; @@ -6338,6 +6344,7 @@ bool __kfree_rcu_sheaf(struct kmem_cache *s, void *obj, unsigned int free_flags) local_unlock(&s->cpu_sheaves->lock); stat(s, FREE_RCU_SHEAF); +out: if (!IS_ENABLED(CONFIG_PREEMPT_RT)) lock_map_release(&kfree_rcu_sheaf_map); return true; @@ -6971,7 +6978,7 @@ void kfree_nolock(const void *object) * -> kfree_nolock() -> kasan_report_invalid_free() on the same CPU * is double buggy and deserves to deadlock. */ - if (kasan_slab_pre_free(s, x)) + if (kasan_slab_pre_free(s, x, false)) return; /* * memcg, kasan_slab_pre_free are done for 'x'. diff --git a/mm/swapfile.c b/mm/swapfile.c index 2d2df53fc51a91..226230dda0aa65 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -449,15 +449,23 @@ static void swap_cluster_free_table(struct swap_cluster_info *ci) swap_cluster_free_count_table(table); } -static int swap_cluster_alloc_table(struct swap_cluster_info *ci, gfp_t gfp) +/* + * Return with ci locked. An unlocked allocator also needs si's outer locks; + * initial bad-slot setup passes NULL because the device is not published. + */ +static int swap_cluster_alloc_table(struct swap_info_struct *si, + struct swap_cluster_info *ci, + gfp_t gfp, bool locked) { struct swap_table *table = NULL; +#ifdef CONFIG_MEMCG + struct swap_memcg_table *memcg_table = NULL; +#endif +#if !SWAP_TABLE_HAS_ZEROFLAG + unsigned long *zero_bitmap = NULL; +#endif struct folio *folio; - - /* The cluster must be empty and not on any list during allocation. */ - VM_WARN_ON_ONCE(ci->flags || !cluster_is_empty(ci)); - if (rcu_access_pointer(ci->table)) - return 0; + int ret = -ENOMEM; if (SWP_TABLE_USE_PAGE) { folio = folio_alloc(gfp | __GFP_ZERO, 0); @@ -467,27 +475,49 @@ static int swap_cluster_alloc_table(struct swap_cluster_info *ci, gfp_t gfp) table = kmem_cache_zalloc(swap_table_cachep, gfp); } if (!table) - return -ENOMEM; + goto lock; #ifdef CONFIG_MEMCG if (!mem_cgroup_disabled()) { - VM_WARN_ON_ONCE(ci->memcg_table); - ci->memcg_table = kzalloc_obj(*ci->memcg_table, gfp); - if (!ci->memcg_table) { - swap_cluster_free_count_table(table); - return -ENOMEM; - } + memcg_table = kzalloc_obj(*ci->memcg_table, gfp); + if (!memcg_table) + goto lock; } #endif #if !SWAP_TABLE_HAS_ZEROFLAG - VM_WARN_ON_ONCE(ci->zero_bitmap); - ci->zero_bitmap = bitmap_zalloc(SWAPFILE_CLUSTER, gfp); - if (!ci->zero_bitmap) { - swap_cluster_free_table(ci); - swap_cluster_free_count_table(table); - return -ENOMEM; + zero_bitmap = bitmap_zalloc(SWAPFILE_CLUSTER, gfp); + if (!zero_bitmap) + goto lock; +#endif + ret = 0; + +lock: + if (!locked) { + if (si) { + local_lock(&percpu_swap_cluster.lock); + if (!(si->flags & SWP_SOLIDSTATE)) + spin_lock(&si->global_cluster_lock); + } + spin_lock(&ci->lock); } + lockdep_assert_held(&ci->lock); + + /* A stale reclaimer may have returned the cluster to the free list. */ + if (ci->flags != CLUSTER_FLAG_NONE || cluster_table_is_alloced(ci)) + ret = -EAGAIN; + if (ret) + goto free; + + /* The cluster must be empty and not on any list during allocation. */ + VM_WARN_ON_ONCE(!cluster_is_empty(ci)); +#ifdef CONFIG_MEMCG + VM_WARN_ON_ONCE(ci->memcg_table); + ci->memcg_table = memcg_table; +#endif +#if !SWAP_TABLE_HAS_ZEROFLAG + VM_WARN_ON_ONCE(ci->zero_bitmap); + ci->zero_bitmap = zero_bitmap; #endif /* @@ -496,6 +526,17 @@ static int swap_cluster_alloc_table(struct swap_cluster_info *ci, gfp_t gfp) */ rcu_assign_pointer(ci->table, table); return 0; + +free: +#ifdef CONFIG_MEMCG + kfree(memcg_table); +#endif +#if !SWAP_TABLE_HAS_ZEROFLAG + bitmap_free(zero_bitmap); +#endif + if (table) + swap_cluster_free_count_table(table); + return ret; } /* @@ -546,8 +587,8 @@ swap_cluster_populate(struct swap_info_struct *si, lockdep_assert_held(&si->global_cluster_lock); lockdep_assert_held(&ci->lock); - if (!swap_cluster_alloc_table(ci, __GFP_HIGH | __GFP_NOMEMALLOC | - __GFP_NOWARN)) + if (!swap_cluster_alloc_table(si, ci, __GFP_HIGH | __GFP_NOMEMALLOC | + __GFP_NOWARN, true)) return ci; /* @@ -560,8 +601,8 @@ swap_cluster_populate(struct swap_info_struct *si, spin_unlock(&si->global_cluster_lock); local_unlock(&percpu_swap_cluster.lock); - ret = swap_cluster_alloc_table(ci, __GFP_HIGH | __GFP_NOMEMALLOC | - GFP_KERNEL); + ret = swap_cluster_alloc_table(si, ci, __GFP_HIGH | __GFP_NOMEMALLOC | + GFP_KERNEL, false); /* * Back to atomic context. We might have migrated to a new CPU with a @@ -571,13 +612,9 @@ swap_cluster_populate(struct swap_info_struct *si, * could happen with ignoring the percpu cluster is fragmentation, * which is acceptable since this fallback and race is rare. */ - local_lock(&percpu_swap_cluster.lock); - if (!(si->flags & SWP_SOLIDSTATE)) - spin_lock(&si->global_cluster_lock); - spin_lock(&ci->lock); - if (ret) { - move_cluster(si, ci, &si->free_clusters, CLUSTER_FLAG_FREE); + if (ret != -EAGAIN) + move_cluster(si, ci, &si->free_clusters, CLUSTER_FLAG_FREE); spin_unlock(&ci->lock); return NULL; } @@ -635,6 +672,10 @@ static struct swap_cluster_info *isolate_lock_cluster( u8 flags = CLUSTER_FLAG_NONE; spin_lock(&si->lock); + + if (unlikely(!(si->flags & SWP_WRITEOK))) + goto out; + list_for_each_entry(ci, list, list) { if (!spin_trylock(&ci->lock)) continue; @@ -650,6 +691,7 @@ static struct swap_cluster_info *isolate_lock_cluster( found = ci; break; } +out: spin_unlock(&si->lock); /* Cluster's table is freed when and only when it's on the free list. */ @@ -773,6 +815,13 @@ static void relocate_cluster(struct swap_info_struct *si, if (cluster_is_discard(ci)) return; + /* + * An allocator may still be preparing the table. + * Leave the cluster to it. + */ + if (!cluster_table_is_alloced(ci)) + return; + if (!ci->count) { if (ci->flags != CLUSTER_FLAG_FREE) free_cluster(si, ci); @@ -820,9 +869,13 @@ static int swap_cluster_setup_bad_slot(struct swap_info_struct *si, ci = cluster_info + idx; /* Need to allocate swap table first for initial bad slot marking. */ - if (!ci->count && swap_cluster_alloc_table(ci, GFP_KERNEL)) - return -ENOMEM; - spin_lock(&ci->lock); + if (!ci->count) { + ret = swap_cluster_alloc_table(NULL, ci, GFP_KERNEL, false); + if (ret) + goto out; + } else { + spin_lock(&ci->lock); + } /* Check for duplicated bad swap slots. */ if (__swap_table_xchg(ci, ci_off, SWP_TB_BAD) != SWP_TB_NULL) { pr_warn("Duplicated bad slot offset %d\n", offset); @@ -830,6 +883,7 @@ static int swap_cluster_setup_bad_slot(struct swap_info_struct *si, } else { ci->count++; } +out: spin_unlock(&ci->lock); WARN_ON(ci->count > SWAPFILE_CLUSTER); @@ -968,6 +1022,17 @@ static bool __swap_cluster_alloc_entries(struct swap_info_struct *si, return true; } +/* + * Prefer a new cluster over a nonfull one if the device needs discard, to + * spread out the writes, or if it is not synchronous, to keep the slots + * of a swapout batch contiguous so that its writes can be merged. + */ +static bool swap_prefer_free_cluster(struct swap_info_struct *si) +{ + return (si->flags & SWP_PAGE_DISCARD) || + !(si->flags & SWP_SYNCHRONOUS_IO); +} + /* Try use a new cluster for current CPU and allocate from it. */ static unsigned int alloc_swap_scan_cluster(struct swap_info_struct *si, struct swap_cluster_info *ci, @@ -1138,11 +1203,7 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si, } new_cluster: - /* - * If the device need discard, prefer new cluster over nonfull - * to spread out the writes. - */ - if (si->flags & SWP_PAGE_DISCARD) { + if (swap_prefer_free_cluster(si)) { found = alloc_swap_scan_list(si, &si->free_clusters, folio, false); if (found) goto done; @@ -1154,7 +1215,7 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si, goto done; } - if (!(si->flags & SWP_PAGE_DISCARD)) { + if (!swap_prefer_free_cluster(si)) { found = alloc_swap_scan_list(si, &si->free_clusters, folio, false); if (found) goto done; @@ -3391,7 +3452,7 @@ static int swap_show(struct seq_file *swap, void *v) return 0; } - bytes = K(si->pages); + bytes = K((unsigned long)si->pages); inuse = K(swap_usage_in_pages(si)); file = si->swap_file; @@ -3907,8 +3968,8 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags) /* Sets SWP_WRITEOK, resurrect the percpu ref, expose the swap device */ enable_swap_info(si); - pr_info("Adding %uk swap on %s. Priority:%d extents:%d across:%lluk %s%s%s%s\n", - K(si->pages), name->name, si->prio, nr_extents, + pr_info("Adding %luk swap on %s. Priority:%d extents:%d across:%lluk %s%s%s%s\n", + K((unsigned long)si->pages), name->name, si->prio, nr_extents, K((unsigned long long)span), (si->flags & SWP_SOLIDSTATE) ? "SS" : "", (si->flags & SWP_DISCARDABLE) ? "D" : "", diff --git a/mm/userfaultfd.c b/mm/userfaultfd.c index 169f681f9849b4..65f7399e79b654 100644 --- a/mm/userfaultfd.c +++ b/mm/userfaultfd.c @@ -373,6 +373,10 @@ static int mfill_atomic_install_pte(pmd_t *dst_pmd, goto out_unlock; if (page_in_cache) { + if (unlikely(folio_ref_count_over_limit(folio))) { + ret = -ENOMEM; + goto out_unlock; + } folio_add_file_rmap_pte(folio, page, dst_vma); } else { folio_add_new_anon_rmap(folio, dst_vma, dst_addr, RMAP_EXCLUSIVE); @@ -1105,21 +1109,26 @@ static int mwriteprotect_range(struct userfaultfd_ctx *ctx, unsigned long start, if (atomic_read(&ctx->mmap_changing)) goto out_unlock; + /* + * Validate every spanned VMA before changing any of them, so an + * invalid range is rejected without changing part of it. + */ err = -ENOENT; for_each_vma_range(vmi, dst_vma, end) { - - if (!userfaultfd_wp(dst_vma)) { - err = -ENOENT; - break; - } + if (!userfaultfd_wp(dst_vma)) + goto out_unlock; if (vma_is_hugetlb(dst_vma)) { - err = -EINVAL; page_mask = vma_kernel_pagesize(dst_vma) - 1; - if ((start & page_mask) || (len & page_mask)) - break; + if ((start & page_mask) || (len & page_mask)) { + err = -EINVAL; + goto out_unlock; + } } + } + vma_iter_set(&vmi, start); + for_each_vma_range(vmi, dst_vma, end) { _start = max(dst_vma->vm_start, start); _end = min(dst_vma->vm_end, end); @@ -1266,8 +1275,8 @@ static long move_present_ptes(struct mm_struct *mm, unsigned long src_start = src_addr; unsigned long src_end; - len = pmd_addr_end(dst_addr, dst_addr + len) - dst_addr; - src_end = pmd_addr_end(src_addr, src_addr + len); + len = pte_table_clamped_end(dst_addr, dst_addr + len) - dst_addr; + src_end = pte_table_clamped_end(src_addr, src_addr + len); flush_cache_range(src_vma, src_addr, src_end); double_pt_lock(dst_ptl, src_ptl); @@ -1394,6 +1403,7 @@ static int move_swap_pte(struct mm_struct *mm, struct vm_area_struct *dst_vma, orig_src_pte = ptep_get_and_clear(mm, src_addr, src_pte); if (pgtable_supports_soft_dirty()) orig_src_pte = pte_swp_mksoft_dirty(orig_src_pte); + orig_src_pte = pte_swp_clear_uffd(orig_src_pte); /* Re-arm RWP on the moved swap entry if dst_vma is RWP-registered. */ if (userfaultfd_rwp(dst_vma)) orig_src_pte = pte_swp_mkuffd(orig_src_pte); @@ -2192,6 +2202,32 @@ static void userfaultfd_reset_ctx(struct vm_area_struct *vma) userfaultfd_set_ctx(vma, NULL, 0); } +/* + * Clear uffd state from a WP or RWP range: the uffd bit, WP markers and + * RWP PAGE_NONE entries. Call this before dropping the registration, as it + * needs the VMA flags to know what to resolve. + */ +static void userfaultfd_clear_ptes(struct vm_area_struct *vma, + unsigned long start, unsigned long end) +{ + unsigned int mm_cp_flags = 0; + struct mmu_gather tlb; + + if (!userfaultfd_protected(vma)) + return; + + if (userfaultfd_wp(vma)) + mm_cp_flags |= MM_CP_UFFD_WP_RESOLVE; + if (userfaultfd_rwp(vma)) + mm_cp_flags |= MM_CP_UFFD_RWP_RESOLVE; + if (vma_wants_manual_pte_write_upgrade(vma)) + mm_cp_flags |= MM_CP_TRY_CHANGE_WRITABLE; + + tlb_gather_mmu(&tlb, vma->vm_mm); + change_protection(&tlb, vma, start, end, mm_cp_flags); + tlb_finish_mmu(&tlb); +} + static struct vm_area_struct *userfaultfd_clear_vma(struct vma_iterator *vmi, struct vm_area_struct *prev, struct vm_area_struct *vma, @@ -2211,22 +2247,7 @@ static struct vm_area_struct *userfaultfd_clear_vma(struct vma_iterator *vmi, if (start == vma->vm_start && end == vma->vm_end) give_up_on_oom = true; - /* Clear the uffd bit and/or restore protnone PTEs */ - if (userfaultfd_protected(vma)) { - unsigned int mm_cp_flags = 0; - struct mmu_gather tlb; - - if (userfaultfd_wp(vma)) - mm_cp_flags |= MM_CP_UFFD_WP_RESOLVE; - if (userfaultfd_rwp(vma)) - mm_cp_flags |= MM_CP_UFFD_RWP_RESOLVE; - if (vma_wants_manual_pte_write_upgrade(vma)) - mm_cp_flags |= MM_CP_TRY_CHANGE_WRITABLE; - - tlb_gather_mmu(&tlb, vma->vm_mm); - change_protection(&tlb, vma, start, end, mm_cp_flags); - tlb_finish_mmu(&tlb); - } + userfaultfd_clear_ptes(vma, start, end); ret = vma_modify_flags_uffd(vmi, prev, vma, start, end, &new_vma_flags, NULL_VM_UFFD_CTX, @@ -2335,8 +2356,10 @@ static void userfaultfd_release_new(struct userfaultfd_ctx *ctx) /* the various vma->vm_userfaultfd_ctx still points to it */ mmap_write_lock(mm); for_each_vma(vmi, vma) { - if (vma->vm_userfaultfd_ctx.ctx == ctx) + if (vma->vm_userfaultfd_ctx.ctx == ctx) { + userfaultfd_clear_ptes(vma, vma->vm_start, vma->vm_end); userfaultfd_reset_ctx(vma); + } } mmap_write_unlock(mm); } @@ -3277,6 +3300,25 @@ void userfaultfd_unmap_complete(struct mm_struct *mm, struct list_head *uf) } } +void userfaultfd_unmap_abort(struct list_head *uf) +{ + struct userfaultfd_unmap_ctx *unmap_ctx, *n; + + if (!uf) + return; + + list_for_each_entry_safe(unmap_ctx, n, uf, list) { + struct userfaultfd_ctx *ctx = unmap_ctx->ctx; + + atomic_dec(&ctx->mmap_changing); + VM_WARN_ON_ONCE(atomic_read(&ctx->mmap_changing) < 0); + userfaultfd_ctx_put(ctx); + + list_del(&unmap_ctx->list); + kfree(unmap_ctx); + } +} + static int userfaultfd_release(struct inode *inode, struct file *file) { struct userfaultfd_ctx *ctx = file->private_data; diff --git a/mm/vma.c b/mm/vma.c index e38e22a5e752e4..c82e9306b11ac1 100644 --- a/mm/vma.c +++ b/mm/vma.c @@ -676,6 +676,26 @@ static int dup_anon_vma(struct vm_area_struct *dst, } #ifdef CONFIG_DEBUG_VM_MAPLE_TREE +static void validate_mm_anon_rmap(struct vm_area_struct *vma) +{ + struct anon_vma *anon_vma; + struct anon_vma_chain *avc; + + if (!IS_ENABLED(CONFIG_DEBUG_VM_RB)) + return; + + vma_assert_stabilised(vma); + + anon_vma = READ_ONCE(vma->anon_vma); + if (!anon_vma) + return; + + anon_vma_lock_read(anon_vma); + list_for_each_entry(avc, &vma->anon_vma_chain, same_vma) + anon_rmap_tree_verify(avc); + anon_vma_unlock_read(anon_vma); +} + void validate_mm(struct mm_struct *mm) { int bug = 0; @@ -685,10 +705,6 @@ void validate_mm(struct mm_struct *mm) mt_validate(&mm->mm_mt); for_each_vma(vmi, vma) { -#ifdef CONFIG_DEBUG_VM_RB - struct anon_vma *anon_vma = vma->anon_vma; - struct anon_vma_chain *avc; -#endif unsigned long vmi_start, vmi_end; bool warn = 0; @@ -709,14 +725,8 @@ void validate_mm(struct mm_struct *mm) vma_iter_dump_tree(&vmi); } -#ifdef CONFIG_DEBUG_VM_RB - if (vma_has_anon_rmap(vma)) { - anon_vma_lock_read(anon_vma); - list_for_each_entry(avc, &vma->anon_vma_chain, same_vma) - anon_rmap_tree_verify(avc); - anon_vma_unlock_read(anon_vma); - } -#endif + validate_mm_anon_rmap(vma); + /* Check for a infinite loop */ if (++i > mm->map_count + 10) { i = -1; @@ -1686,9 +1696,18 @@ int do_vmi_align_munmap(struct vma_iterator *vmi, struct vm_area_struct *vma, mt_init_flags(&mt_detach, vmi->mas.tree->ma_flags & MT_FLAGS_LOCK_MASK); mt_on_stack(mt_detach); struct vma_munmap_struct vms; + struct list_head *uf_unmaps; + LIST_HEAD(uf_new_unmaps); int error; - init_vma_munmap(&vms, vmi, vma, start, end, uf, unlock); + /* + * @uf may already hold events of earlier successful unmaps, e.g. in + * mremap(). + * Collect new events on a separate list so they can be dropped if this + * unmap fails, and splice them into @uf on success. + */ + uf_unmaps = uf ? &uf_new_unmaps : NULL; + init_vma_munmap(&vms, vmi, vma, start, end, uf_unmaps, unlock); error = vms_gather_munmap_vmas(&vms, &mas_detach); if (error) goto gather_failed; @@ -1698,12 +1717,15 @@ int do_vmi_align_munmap(struct vma_iterator *vmi, struct vm_area_struct *vma, goto clear_tree_failed; /* Point of no return */ + if (uf) + list_splice_tail(&uf_new_unmaps, uf); vms_complete_munmap_vmas(&vms, &mas_detach); return 0; clear_tree_failed: reattach_vmas(&mas_detach); gather_failed: + userfaultfd_unmap_abort(&uf_new_unmaps); validate_mm(mm); return error; } @@ -2592,7 +2614,7 @@ static int __mmap_setup(struct mmap_state *map, struct vm_area_desc *desc, if (error) { /* On error VMAs will already have been reattached. */ vms->nr_pages = 0; - return error; + goto abort_unmaps; } map->next = vms->next; @@ -2602,8 +2624,10 @@ static int __mmap_setup(struct mmap_state *map, struct vm_area_desc *desc, } /* Check against address space limit. */ - if (!may_expand_vm(map->mm, &map->vma_flags, map->pglen - vms->nr_pages)) - return -ENOMEM; + if (!may_expand_vm(map->mm, &map->vma_flags, map->pglen - vms->nr_pages)) { + error = -ENOMEM; + goto abort_unmaps; + } /* Private writable mapping: check memory availability. */ if (accountable_mapping(map)) { @@ -2613,7 +2637,7 @@ static int __mmap_setup(struct mmap_state *map, struct vm_area_desc *desc, if (uncharged) { error = security_vm_enough_memory_mm(map->mm, uncharged); if (error) - return error; + goto abort_unmaps; } /* Our new mapping owns the entire charge now. */ @@ -2632,6 +2656,10 @@ static int __mmap_setup(struct mmap_state *map, struct vm_area_desc *desc, set_desc_from_map(desc, map); return 0; + +abort_unmaps: + userfaultfd_unmap_abort(uf); + return error; } static bool map_same_file(struct mmap_state *map) diff --git a/mm/vmscan.c b/mm/vmscan.c index 6a1af9b92349fb..a44cdbb3056900 100644 --- a/mm/vmscan.c +++ b/mm/vmscan.c @@ -714,7 +714,8 @@ static pageout_t pageout(struct swap_io_ctx *ctx, struct address_space *mapping, */ if (folio_ref_count(folio) != 1 + folio_nr_pages(folio) || !mapping) return PAGE_KEEP; - if (!shmem_mapping(mapping) && !folio_test_anon(folio)) + /* Anonymous folios outside swapcache returned PAGE_KEEP above. */ + if (!shmem_mapping(mapping) && !folio_test_swapcache(folio)) return PAGE_ACTIVATE; if (!folio_clear_dirty_for_io(folio)) return PAGE_CLEAN; @@ -1455,6 +1456,12 @@ static unsigned int shrink_folio_list(struct list_head *folio_list, flags |= TTU_SYNC; try_to_unmap(folio, flags); + /* + * Flush deferred writable TLB entries before we could + * drop the folio lock and others could start writeback. + */ + if (folio_test_dirty(folio)) + try_to_unmap_flush_dirty(); if (folio_mapped(folio)) { stat->nr_unmap_fail += nr_pages; if (!was_swapbacked && @@ -1496,12 +1503,6 @@ static unsigned int shrink_folio_list(struct list_head *folio_list, if (!sc->may_writepage) goto keep_locked; - /* - * Folio is dirty. Flush the TLB if a writable entry - * potentially exists to avoid CPU writes after I/O - * starts and then write it out here. - */ - try_to_unmap_flush_dirty(); switch (pageout(&ctx, mapping, folio, folio_list)) { case PAGE_KEEP: goto keep_locked; @@ -4751,19 +4752,25 @@ void max_lru_gen_memcg(struct mem_cgroup *memcg, int nid) * The same generation has different meanings in the parent and child memcg, * so this compromise method will cause the LRU inversion problem. But as the * system runs, this problem will be fixed automatically. + * + * Move all MAX_NR_GENS lists, not only the gens from min_seq to max_seq. + * An earlier reparenting can leave a folio whose gen is older than the list + * it is on. Once min_seq passes that gen, sort_folio() puts the folio on the + * list for max_seq + 1, where it stays until the next aging. If that list + * were skipped, the folio would stay behind on a memcg that is about to be + * freed. The parent has MAX_NR_GENS gens here, so every index is valid in it. */ static void __lru_gen_reparent_memcg(struct lruvec *child_lruvec, struct lruvec *parent_lruvec, int zone, int type) { struct lru_gen_folio *child_lrugen, *parent_lrugen; enum lru_list lru = type * LRU_INACTIVE_FILE; - int i; + int gen; child_lrugen = &child_lruvec->lrugen; parent_lrugen = &parent_lruvec->lrugen; - for (i = 0; i < get_nr_gens(child_lruvec, type); i++) { - int gen = lru_gen_from_seq(child_lrugen->max_seq - i); + for (gen = 0; gen < MAX_NR_GENS; gen++) { long nr_pages = child_lrugen->nr_pages[gen][type][zone]; int child_lru_active = lru_gen_is_active(child_lruvec, gen) ? LRU_ACTIVE : 0; int parent_lru_active = lru_gen_is_active(parent_lruvec, gen) ? LRU_ACTIVE : 0; diff --git a/net/bluetooth/6lowpan.c b/net/bluetooth/6lowpan.c index 8c51c20f6c4b13..68ca2f49dadc9b 100644 --- a/net/bluetooth/6lowpan.c +++ b/net/bluetooth/6lowpan.c @@ -345,6 +345,7 @@ static int recv_pkt(struct sk_buff *skb, struct net_device *dev, return NET_RX_SUCCESS; drop: + kfree_skb(skb); dev->stats.rx_dropped++; return NET_RX_DROP; } @@ -356,21 +357,26 @@ static int chan_recv_cb(struct l2cap_chan *chan, struct sk_buff *skb) struct lowpan_peer *peer; int err; + /* The skb is always consumed, so never return an error that would + * make the caller free it again. + */ peer = lookup_peer(chan->conn); if (!peer) - return -ENOENT; + goto drop; dev = lookup_dev(chan->conn); if (!dev || !dev->netdev) - return -ENOENT; + goto drop; err = recv_pkt(skb, dev->netdev, peer); - if (err) { + if (err) BT_DBG("recv pkt %d", err); - err = -EAGAIN; - } - return err; + return 0; + +drop: + kfree_skb(skb); + return 0; } static int setup_header(struct sk_buff *skb, struct net_device *netdev, diff --git a/net/bluetooth/hci_conn.c b/net/bluetooth/hci_conn.c index eebd73988bf66b..2fb37e078d731b 100644 --- a/net/bluetooth/hci_conn.c +++ b/net/bluetooth/hci_conn.c @@ -1019,6 +1019,15 @@ static struct hci_conn *__hci_conn_add(struct hci_dev *hdev, int type, struct hci_conn *conn; struct smp_irk *irk = NULL; + lockdep_assert_held(&hdev->lock); + + /* hci_dev_close_sync() clears HCI_UP before hci_conn_hash_flush(). + * A connection added after that would never be flushed, so refuse + * it. The caller holds hdev->lock, which the flush also takes. + */ + if (!test_bit(HCI_UP, &hdev->flags)) + return ERR_PTR(-ENETDOWN); + switch (type) { case ACL_LINK: if (!hdev->acl_mtu) @@ -1166,6 +1175,9 @@ static struct hci_conn *__hci_conn_add(struct hci_dev *hdev, int type, hci_dev_hold(hdev); + /* Initialize the device before publishing it to RCU readers. */ + hci_conn_init_sysfs(conn); + hci_conn_hash_add(hdev, conn); /* The SCO and eSCO connections will only be notified when their @@ -1177,13 +1189,13 @@ static struct hci_conn *__hci_conn_add(struct hci_dev *hdev, int type, hdev->notify(hdev, HCI_NOTIFY_CONN_ADD); } - hci_conn_init_sysfs(conn); return conn; } struct hci_conn *hci_conn_add_unset(struct hci_dev *hdev, int type, bdaddr_t *dst, u8 dst_type, u8 role) { + struct hci_conn *conn; int handle; bt_dev_dbg(hdev, "dst %pMR", dst); @@ -1192,7 +1204,11 @@ struct hci_conn *hci_conn_add_unset(struct hci_dev *hdev, int type, if (unlikely(handle < 0)) return ERR_PTR(-ECONNREFUSED); - return __hci_conn_add(hdev, type, dst, dst_type, role, handle); + conn = __hci_conn_add(hdev, type, dst, dst_type, role, handle); + if (IS_ERR(conn)) + ida_free(&hdev->unset_handle_ida, handle); + + return conn; } struct hci_conn *hci_conn_add(struct hci_dev *hdev, int type, bdaddr_t *dst, diff --git a/net/bluetooth/hci_core.c b/net/bluetooth/hci_core.c index c97aec3caba023..255005916f3751 100644 --- a/net/bluetooth/hci_core.c +++ b/net/bluetooth/hci_core.c @@ -915,7 +915,9 @@ static void hci_power_on(struct work_struct *work) hci_dev_test_flag(hdev, HCI_MGMT) && hci_dev_test_and_clear_flag(hdev, HCI_AUTO_OFF)) { cancel_delayed_work(&hdev->power_off); + hci_req_sync_lock(hdev); err = hci_powered_update_sync(hdev); + hci_req_sync_unlock(hdev); mgmt_power_on(hdev, err); return; } @@ -1015,10 +1017,14 @@ void hci_link_keys_clear(struct hci_dev *hdev) { struct link_key *key, *tmp; + mutex_lock(&hdev->link_keys_lock); + list_for_each_entry_safe(key, tmp, &hdev->link_keys, list) { list_del_rcu(&key->list); kfree_rcu(key, rcu); } + + mutex_unlock(&hdev->link_keys_lock); } void hci_smp_ltks_clear(struct hci_dev *hdev) @@ -1235,13 +1241,16 @@ struct smp_irk *hci_find_irk_by_addr(struct hci_dev *hdev, bdaddr_t *bdaddr, return irk_to_return; } -struct link_key *hci_add_link_key(struct hci_dev *hdev, struct hci_conn *conn, - bdaddr_t *bdaddr, u8 *val, u8 type, - u8 pin_len, bool *persistent) +/* This function requires the caller holds hdev->link_keys_lock */ +struct link_key *__hci_add_link_key(struct hci_dev *hdev, struct hci_conn *conn, + bdaddr_t *bdaddr, u8 *val, u8 type, + u8 pin_len, bool *persistent) { struct link_key *key, *old_key; u8 old_key_type; + lockdep_assert_held(&hdev->link_keys_lock); + old_key = hci_find_link_key(hdev, bdaddr); if (old_key) { old_key_type = old_key->type; @@ -1284,6 +1293,26 @@ struct link_key *hci_add_link_key(struct hci_dev *hdev, struct hci_conn *conn, return key; } +/* The writers of hdev->link_keys are serialized with hdev->link_keys_lock + * so the list can be modified without hdev->lock (e.g. from SMP, where it + * can't be taken after the l2cap channel lock). The returned key is only + * safe to use while hdev->lock is held, callers without it must use + * __hci_add_link_key() and keep hdev->link_keys_lock while using the key. + */ +struct link_key *hci_add_link_key(struct hci_dev *hdev, struct hci_conn *conn, + bdaddr_t *bdaddr, u8 *val, u8 type, + u8 pin_len, bool *persistent) +{ + struct link_key *key; + + mutex_lock(&hdev->link_keys_lock); + key = __hci_add_link_key(hdev, conn, bdaddr, val, type, pin_len, + persistent); + mutex_unlock(&hdev->link_keys_lock); + + return key; +} + struct smp_ltk *hci_add_ltk(struct hci_dev *hdev, bdaddr_t *bdaddr, u8 addr_type, u8 type, u8 authenticated, u8 tk[16], u8 enc_size, __le16 ediv, __le64 rand) @@ -1345,18 +1374,44 @@ int hci_remove_link_key(struct hci_dev *hdev, bdaddr_t *bdaddr) { struct link_key *key; + mutex_lock(&hdev->link_keys_lock); + key = hci_find_link_key(hdev, bdaddr); - if (!key) + if (!key) { + mutex_unlock(&hdev->link_keys_lock); return -ENOENT; + } BT_DBG("%s removing %pMR", hdev->name, bdaddr); list_del_rcu(&key->list); kfree_rcu(key, rcu); + mutex_unlock(&hdev->link_keys_lock); + return 0; } +/* Remove a key previously returned by hci_add_link_key(), unlike + * hci_remove_link_key() this also works for keys that are blocked. + */ +void hci_del_link_key(struct hci_dev *hdev, struct link_key *key) +{ + struct link_key *k; + + mutex_lock(&hdev->link_keys_lock); + + list_for_each_entry(k, &hdev->link_keys, list) { + if (k == key) { + list_del_rcu(&key->list); + kfree_rcu(key, rcu); + break; + } + } + + mutex_unlock(&hdev->link_keys_lock); +} + int hci_remove_ltk(struct hci_dev *hdev, bdaddr_t *bdaddr, u8 bdaddr_type) { struct smp_ltk *k, *tmp; @@ -1610,17 +1665,11 @@ struct adv_info *hci_get_next_instance(struct hci_dev *hdev, u8 instance) } /* This function requires the caller holds hdev->lock */ -int hci_remove_adv_instance(struct hci_dev *hdev, u8 instance) +void hci_free_adv_instance(struct hci_dev *hdev, struct adv_info *adv_instance) { - struct adv_info *adv_instance; - - adv_instance = hci_find_adv_instance(hdev, instance); - if (!adv_instance) - return -ENOENT; - - BT_DBG("%s removing %dMR", hdev->name, instance); + BT_DBG("%s removing %dMR", hdev->name, adv_instance->instance); - if (hdev->cur_adv_instance == instance) { + if (hdev->cur_adv_instance == adv_instance->instance) { if (hdev->adv_instance_timeout) { cancel_delayed_work(&hdev->adv_instance_expire); hdev->adv_instance_timeout = false; @@ -1634,6 +1683,18 @@ int hci_remove_adv_instance(struct hci_dev *hdev, u8 instance) kfree(adv_instance); hdev->adv_instance_cnt--; +} + +/* This function requires the caller holds hdev->lock */ +int hci_remove_adv_instance(struct hci_dev *hdev, u8 instance) +{ + struct adv_info *adv_instance; + + adv_instance = hci_find_adv_instance(hdev, instance); + if (!adv_instance) + return -ENOENT; + + hci_free_adv_instance(hdev, adv_instance); return 0; } @@ -1973,15 +2034,25 @@ static int hci_remove_adv_monitor(struct hci_dev *hdev, if (status == -ENOENT) bt_dev_warn(hdev, "Removing monitor with no matching handle %d", monitor->handle); + + hci_dev_lock(hdev); hci_free_adv_monitor(hdev, monitor); + hci_dev_unlock(hdev); - return status; + /* The monitor is gone, not having been known by the controller is not + * an error for the caller. + */ + return status == -ENOENT ? 0 : status; } /* This function requires the caller holds hci_req_sync_lock */ int hci_remove_single_adv_monitor(struct hci_dev *hdev, u16 handle) { - struct adv_monitor *monitor = idr_find(&hdev->adv_monitors_idr, handle); + struct adv_monitor *monitor; + + hci_dev_lock(hdev); + monitor = idr_find(&hdev->adv_monitors_idr, handle); + hci_dev_unlock(hdev); if (!monitor) return -EINVAL; @@ -1997,7 +2068,10 @@ int hci_remove_all_adv_monitor(struct hci_dev *hdev) int status = 0; while (1) { + hci_dev_lock(hdev); monitor = idr_get_next(&hdev->adv_monitors_idr, &idr_next_id); + hci_dev_unlock(hdev); + if (!monitor) break; @@ -2499,6 +2573,7 @@ struct hci_dev *hci_alloc_dev_priv(int sizeof_priv) hdev->def_page_scan_window = 0x0012; mutex_init(&hdev->lock); + mutex_init(&hdev->link_keys_lock); mutex_init(&hdev->req_lock); mutex_init(&hdev->mgmt_pending_lock); mutex_init(&hdev->remote_oob_lock); diff --git a/net/bluetooth/hci_debugfs.c b/net/bluetooth/hci_debugfs.c index cd5ef398f23821..1af68bfc2257ad 100644 --- a/net/bluetooth/hci_debugfs.c +++ b/net/bluetooth/hci_debugfs.c @@ -59,7 +59,7 @@ static ssize_t __name ## _write(struct file *file, \ if (enable == test_bit(__quirk, hdev->quirk_flags)) \ return -EALREADY; \ \ - change_bit(__quirk, hdev->quirk_flags); \ + assign_bit(__quirk, hdev->quirk_flags, enable); \ \ return count; \ } \ @@ -777,7 +777,10 @@ static ssize_t force_static_address_write(struct file *file, if (enable == hci_dev_test_flag(hdev, HCI_FORCE_STATIC_ADDR)) return -EALREADY; - hci_dev_change_flag(hdev, HCI_FORCE_STATIC_ADDR); + if (enable) + hci_dev_set_flag(hdev, HCI_FORCE_STATIC_ADDR); + else + hci_dev_clear_flag(hdev, HCI_FORCE_STATIC_ADDR); return count; } @@ -1177,7 +1180,10 @@ static ssize_t force_no_mitm_write(struct file *file, if (enable == hci_dev_test_flag(hdev, HCI_FORCE_NO_MITM)) return -EALREADY; - hci_dev_change_flag(hdev, HCI_FORCE_NO_MITM); + if (enable) + hci_dev_set_flag(hdev, HCI_FORCE_NO_MITM); + else + hci_dev_clear_flag(hdev, HCI_FORCE_NO_MITM); return count; } @@ -1303,20 +1309,32 @@ static ssize_t dut_mode_write(struct file *file, const char __user *user_buf, return -EALREADY; hci_req_sync_lock(hdev); + + /* Check again now that concurrent writers are excluded */ + if (enable == hci_dev_test_flag(hdev, HCI_DUT_MODE)) { + hci_req_sync_unlock(hdev); + return -EALREADY; + } + if (enable) skb = __hci_cmd_sync(hdev, HCI_OP_ENABLE_DUT_MODE, 0, NULL, HCI_CMD_TIMEOUT); else skb = __hci_cmd_sync(hdev, HCI_OP_RESET, 0, NULL, HCI_CMD_TIMEOUT); - hci_req_sync_unlock(hdev); - - if (IS_ERR(skb)) + if (IS_ERR(skb)) { + hci_req_sync_unlock(hdev); return PTR_ERR(skb); + } kfree_skb(skb); - hci_dev_change_flag(hdev, HCI_DUT_MODE); + if (enable) + hci_dev_set_flag(hdev, HCI_DUT_MODE); + else + hci_dev_clear_flag(hdev, HCI_DUT_MODE); + + hci_req_sync_unlock(hdev); return count; } diff --git a/net/bluetooth/hci_event.c b/net/bluetooth/hci_event.c index 5e6b25eb50538c..039bcea98a5adf 100644 --- a/net/bluetooth/hci_event.c +++ b/net/bluetooth/hci_event.c @@ -1671,14 +1671,16 @@ static u8 hci_cc_le_set_ext_adv_enable(struct hci_dev *hdev, void *data, struct hci_cp_ext_adv_set *set; struct adv_info *adv = NULL, *n; struct hci_ev_status *rp = data; + size_t len; bt_dev_dbg(hdev, "status 0x%2.2x", rp->status); if (rp->status) return rp->status; - cp = hci_sent_cmd_data(hdev, HCI_OP_LE_SET_EXT_ADV_ENABLE); - if (!cp) + cp = hci_sent_cmd_data_len(hdev, HCI_OP_LE_SET_EXT_ADV_ENABLE, &len); + if (!cp || len < sizeof(*cp) || + len < sizeof(*cp) + cp->num_of_sets * sizeof(*set)) return rp->status; set = (void *)cp->data; @@ -4960,8 +4962,7 @@ static void hci_link_key_notify_evt(struct hci_dev *hdev, void *data, */ if (key->type == HCI_LK_DEBUG_COMBINATION && !hci_dev_test_flag(hdev, HCI_KEEP_DEBUG_KEYS)) { - list_del_rcu(&key->list); - kfree_rcu(key, rcu); + hci_del_link_key(hdev, key); goto unlock; } @@ -6158,6 +6159,26 @@ static void hci_le_pa_sync_lost_evt(struct hci_dev *hdev, void *data, hci_dev_unlock(hdev); } +/* The instance advertising on the set identified by handle. Handle 0x00 may + * be shared by Global Advertising and an instance, e.g. instance 1 when the + * controller supports a single advertising set, in which case the instance + * enabled on it, if any, owns the set (see hci_le_ext_adv_set_enabled()). + */ +static struct adv_info *hci_le_ext_adv_owner(struct hci_dev *hdev, u8 handle) +{ + struct adv_info *adv; + + if (handle) + return hci_find_adv_instance(hdev, handle); + + list_for_each_entry(adv, &hdev->adv_instances, list) { + if (!adv->handle && adv->enabled) + return adv; + } + + return NULL; +} + static void hci_le_ext_adv_term_evt(struct hci_dev *hdev, void *data, struct sk_buff *skb) { @@ -6181,15 +6202,18 @@ static void hci_le_ext_adv_term_evt(struct hci_dev *hdev, void *data, hci_dev_lock(hdev); - adv = hci_find_adv_instance(hdev, ev->handle); + adv = hci_le_ext_adv_owner(hdev, ev->handle); if (ev->status) { + u8 instance; + if (!adv) goto unlock; /* Remove advertising as it has been terminated */ - hci_remove_adv_instance(hdev, ev->handle); - mgmt_advertising_removed(NULL, hdev, ev->handle); + instance = adv->instance; + hci_free_adv_instance(hdev, adv); + mgmt_advertising_removed(NULL, hdev, instance); list_for_each_entry_safe(adv, n, &hdev->adv_instances, list) { if (adv->enabled) @@ -6206,22 +6230,19 @@ static void hci_le_ext_adv_term_evt(struct hci_dev *hdev, void *data, conn = hci_conn_hash_lookup_handle(hdev, __le16_to_cpu(ev->conn_handle)); if (conn) { - /* Store handle in the connection so the correct advertising - * instance can be re-enabled when disconnected. + /* Store the instance in the connection so the correct + * advertising instance can be re-enabled when disconnected. */ - conn->adv_instance = ev->handle; + conn->adv_instance = adv ? adv->instance : ev->handle; if (hdev->adv_addr_type != ADDR_LE_DEV_RANDOM || bacmp(&conn->resp_addr, BDADDR_ANY)) goto unlock; - if (!ev->handle) { - bacpy(&conn->resp_addr, &hdev->random_addr); - goto unlock; - } - if (adv) bacpy(&conn->resp_addr, &adv->random_addr); + else if (!ev->handle) + bacpy(&conn->resp_addr, &hdev->random_addr); } unlock: diff --git a/net/bluetooth/hci_sync.c b/net/bluetooth/hci_sync.c index 9213e3ef9f268e..638589f770815e 100644 --- a/net/bluetooth/hci_sync.c +++ b/net/bluetooth/hci_sync.c @@ -31,21 +31,23 @@ static void hci_cmd_sync_complete(struct hci_dev *hdev, u8 result, u16 opcode, hdev->req_result = result; WRITE_ONCE(hdev->req_status, HCI_REQ_DONE); - /* Free the request command so it is not used as response */ + /* Free the request command so it is not used as response, and drop + * the reference hci_cmd_sync_alloc() took on its sk, if set: the + * response skb doesn't carry it. + */ hci_dev_lock(hdev); - kfree_skb(hdev->req_skb); - hdev->req_skb = NULL; - hci_dev_unlock(hdev); - - if (skb) { - struct sock *sk = hci_skb_sk(skb); + if (hdev->req_skb) { + struct sock *sk = hci_skb_sk(hdev->req_skb); - /* Drop sk reference if set */ if (sk) sock_put(sk); + } + kfree_skb(hdev->req_skb); + hdev->req_skb = NULL; + hci_dev_unlock(hdev); + if (skb) hdev->req_rsp = skb_get(skb); - } wake_up_interruptible(&hdev->req_wait_q); } @@ -499,7 +501,8 @@ static void cancel_adv_timeout(struct hci_dev *hdev) int hci_clear_adv_instance_sync(struct hci_dev *hdev, struct sock *sk, u8 instance, bool force) { - struct adv_info *adv_instance, *n, *next_instance = NULL; + struct adv_info *adv_instance, *n; + u8 next_instance = 0; int err; u8 rem_inst; @@ -507,12 +510,20 @@ int hci_clear_adv_instance_sync(struct hci_dev *hdev, struct sock *sk, if (!instance || hdev->cur_adv_instance == instance) cancel_adv_timeout(hdev); + /* This is safe as long as there is no command send while the + * lock is held. + */ + hci_dev_lock(hdev); + /* Get the next instance to advertise BEFORE we remove * the current one. This can be the same instance again * if there is only one instance. */ - if (instance && hdev->cur_adv_instance == instance) - next_instance = hci_get_next_instance(hdev, instance); + if (instance && hdev->cur_adv_instance == instance) { + adv_instance = hci_get_next_instance(hdev, instance); + if (adv_instance) + next_instance = adv_instance->instance; + } if (instance == 0x00) { list_for_each_entry_safe(adv_instance, n, &hdev->adv_instances, @@ -531,9 +542,8 @@ int hci_clear_adv_instance_sync(struct hci_dev *hdev, struct sock *sk, if (force || (adv_instance && adv_instance->timeout && !adv_instance->remaining_time)) { /* Don't advertise a removed instance. */ - if (next_instance && - next_instance->instance == instance) - next_instance = NULL; + if (next_instance == instance) + next_instance = 0; err = hci_remove_adv_instance(hdev, instance); if (!err) @@ -541,12 +551,13 @@ int hci_clear_adv_instance_sync(struct hci_dev *hdev, struct sock *sk, } } + hci_dev_unlock(hdev); + if (!hdev_is_powered(hdev) || hci_dev_test_flag(hdev, HCI_ADVERTISING)) return 0; if (next_instance && !ext_adv_capable(hdev)) - return hci_schedule_adv_instance_sync(hdev, - next_instance->instance, + return hci_schedule_adv_instance_sync(hdev, next_instance, false); return 0; @@ -1224,16 +1235,26 @@ static int hci_disable_ext_adv_instance_sync(struct hci_dev *hdev, u8 instance) struct hci_cp_ext_adv_set *set; u8 data[sizeof(*cp) + sizeof(*set) * 1]; u8 size; - struct adv_info *adv = NULL; + u8 handle = instance; /* If request specifies an instance that doesn't exist, fail */ if (instance > 0) { + struct adv_info *adv; + bool enabled = false; + + hci_dev_lock(hdev); adv = hci_find_adv_instance(hdev, instance); + if (adv) { + enabled = adv->enabled; + handle = adv->handle; + } + hci_dev_unlock(hdev); + if (!adv) return -EINVAL; /* If not enabled there is nothing to do */ - if (!adv->enabled) + if (!enabled) return 0; } @@ -1246,7 +1267,7 @@ static int hci_disable_ext_adv_instance_sync(struct hci_dev *hdev, u8 instance) cp->num_of_sets = !!instance; cp->enable = 0x00; - set->handle = adv ? adv->handle : instance; + set->handle = handle; size = sizeof(*cp) + sizeof(*set) * cp->num_of_sets; @@ -1258,6 +1279,8 @@ static int hci_set_adv_set_random_addr_sync(struct hci_dev *hdev, u8 instance, bdaddr_t *random_addr) { struct hci_cp_le_set_adv_set_rand_addr cp; + struct adv_info *adv; + u8 handle = instance; int err; if (!instance) { @@ -1269,15 +1292,46 @@ static int hci_set_adv_set_random_addr_sync(struct hci_dev *hdev, u8 instance, err = hci_set_random_addr_sync(hdev, random_addr); if (err) return err; + } else { + hci_dev_lock(hdev); + adv = hci_find_adv_instance(hdev, instance); + if (adv) + handle = adv->handle; + hci_dev_unlock(hdev); } memset(&cp, 0, sizeof(cp)); - cp.handle = instance; + cp.handle = handle; bacpy(&cp.bdaddr, random_addr); - return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_ADV_SET_RAND_ADDR, - sizeof(cp), &cp, HCI_CMD_TIMEOUT); + err = __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_ADV_SET_RAND_ADDR, + sizeof(cp), &cp, HCI_CMD_TIMEOUT); + if (err || handle == instance) + return err; + + /* hci_cc_le_set_adv_set_random_addr() records the address of the + * instance numbered as the handle, and leaves handle 0x00 to + * hdev->random_addr, so record it here for an instance using another + * handle: instance 1 on handle 0x00, on a controller supporting a + * single advertising set. + */ + hci_dev_lock(hdev); + + adv = hci_find_adv_instance(hdev, instance); + if (adv) { + bacpy(&adv->random_addr, random_addr); + if (!bacmp(&hdev->rpa, random_addr)) { + adv->rpa_expired = false; + queue_delayed_work(hdev->workqueue, + &adv->rpa_expired_cb, + secs_to_jiffies(hdev->rpa_timeout)); + } + } + + hci_dev_unlock(hdev); + + return 0; } static int @@ -1384,14 +1438,21 @@ static int hci_set_ext_adv_data_sync(struct hci_dev *hdev, u8 instance) } static int hci_set_adv_data_sync(struct hci_dev *hdev, u8 instance) + __context_unsafe(/* conditional locking */) { struct hci_cp_le_set_adv_data cp; u8 len; memset(&cp, 0, sizeof(cp)); + if (instance) + hci_dev_lock(hdev); + len = eir_create_adv_data(hdev, instance, cp.data, sizeof(cp.data)); + if (instance) + hci_dev_unlock(hdev); + /* There's nothing to do if the data hasn't changed */ if (hdev->adv_data_len == len && memcmp(cp.data, hdev->adv_data, len) == 0) @@ -1680,17 +1741,33 @@ int hci_enable_ext_advertising_sync(struct hci_dev *hdev, u8 instance) struct hci_cp_le_set_ext_adv_enable *cp; struct hci_cp_ext_adv_set *set; u8 data[sizeof(*cp) + sizeof(*set) * 1]; - struct adv_info *adv; + u8 handle = instance; + u32 duration = 0; if (instance > 0) { + struct adv_info *adv; + + hci_dev_lock(hdev); adv = hci_find_adv_instance(hdev, instance); - if (!adv) + if (!adv) { + hci_dev_unlock(hdev); return -EINVAL; + } /* If already enabled there is nothing to do */ - if (adv->enabled) + if (adv->enabled) { + hci_dev_unlock(hdev); return 0; - } else { - adv = NULL; + } + + handle = adv->handle; + + /* Set duration per instance since controller is + * responsible for scheduling it. + */ + if (adv->timeout) + duration = adv->mesh ? adv->timeout : + adv->timeout * MSEC_PER_SEC; + hci_dev_unlock(hdev); } cp = (void *)data; @@ -1703,18 +1780,10 @@ int hci_enable_ext_advertising_sync(struct hci_dev *hdev, u8 instance) memset(set, 0, sizeof(*set)); - set->handle = adv ? adv->handle : instance; + set->handle = handle; - /* Set duration per instance since controller is responsible for - * scheduling it. - */ - if (adv && adv->timeout) { - u16 duration = adv->mesh ? adv->timeout : - adv->timeout * MSEC_PER_SEC; - - /* Time = N * 10 ms */ - set->duration = cpu_to_le16(duration / 10); - } + /* Time = N * 10 ms */ + set->duration = cpu_to_le16(min_t(u32, duration / 10, U16_MAX)); /* Track which instance owns the advertising set since the handle * alone is ambiguous when instances share handle 0x00, see @@ -1746,20 +1815,57 @@ int hci_start_ext_adv_sync(struct hci_dev *hdev, u8 instance) int hci_disable_per_advertising_sync(struct hci_dev *hdev, u8 instance) { struct hci_cp_le_set_per_adv_enable cp; - struct adv_info *adv = NULL; + struct adv_info *adv; + bool enabled; + u8 handle = instance; + int err; /* If periodic advertising already disabled there is nothing to do. */ + hci_dev_lock(hdev); adv = hci_find_adv_instance(hdev, instance); - if (!adv || !adv->periodic_enabled) + enabled = adv && adv->periodic_enabled; + if (adv) + handle = adv->handle; + hci_dev_unlock(hdev); + if (!enabled) return 0; memset(&cp, 0, sizeof(cp)); cp.enable = 0x00; - cp.handle = instance; + cp.handle = handle; - return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_PER_ADV_ENABLE, - sizeof(cp), &cp, HCI_CMD_TIMEOUT); + err = __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_PER_ADV_ENABLE, + sizeof(cp), &cp, HCI_CMD_TIMEOUT); + if (err || handle == instance) + return err; + + /* Handle 0 is shared with global advertising, so the completion + * cannot identify the software instance from the command alone. + */ + hci_dev_lock(hdev); + adv = hci_find_adv_instance(hdev, instance); + if (adv) + adv->periodic_enabled = false; + hci_dev_unlock(hdev); + + return 0; +} + +/* Map a management instance number to its controller handle. */ +static u8 hci_adv_instance_handle(struct hci_dev *hdev, u8 instance) + __must_not_hold(&hdev->lock) +{ + struct adv_info *adv; + u8 handle = instance; + + hci_dev_lock(hdev); + adv = hci_find_adv_instance(hdev, instance); + if (adv) + handle = adv->handle; + hci_dev_unlock(hdev); + + return handle; } static int hci_set_per_adv_params_sync(struct hci_dev *hdev, u8 instance, @@ -1775,7 +1881,7 @@ static int hci_set_per_adv_params_sync(struct hci_dev *hdev, u8 instance, if (!max_interval) max_interval = DISCOV_LE_PER_ADV_INT_MAX; - cp.handle = instance; + cp.handle = hci_adv_instance_handle(hdev, instance); cp.min_interval = cpu_to_le16(min_interval); cp.max_interval = cpu_to_le16(max_interval); cp.periodic_properties = 0x0000; @@ -1819,44 +1925,76 @@ static int hci_set_per_adv_data_sync(struct hci_dev *hdev, u8 instance) static int hci_enable_per_advertising_sync(struct hci_dev *hdev, u8 instance) { struct hci_cp_le_set_per_adv_enable cp; - struct adv_info *adv = NULL; + struct adv_info *adv; + bool enabled; + u8 handle = instance; + int err; /* If periodic advertising already enabled there is nothing to do. */ + hci_dev_lock(hdev); adv = hci_find_adv_instance(hdev, instance); - if (adv && adv->periodic_enabled) + enabled = adv && adv->periodic_enabled; + if (adv) + handle = adv->handle; + hci_dev_unlock(hdev); + if (enabled) return 0; memset(&cp, 0, sizeof(cp)); cp.enable = 0x01; - cp.handle = instance; + cp.handle = handle; - return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_PER_ADV_ENABLE, - sizeof(cp), &cp, HCI_CMD_TIMEOUT); + err = __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_PER_ADV_ENABLE, + sizeof(cp), &cp, HCI_CMD_TIMEOUT); + if (err || handle == instance) + return err; + + /* Handle 0 is shared with global advertising, so the completion + * cannot identify the software instance from the command alone. + */ + hci_dev_lock(hdev); + adv = hci_find_adv_instance(hdev, instance); + if (adv) + adv->periodic_enabled = true; + hci_dev_unlock(hdev); + + return 0; } /* Checks if periodic advertising data contains a Basic Announcement and if it * does generates a Broadcast ID and add Broadcast Announcement. */ -static int hci_adv_bcast_annoucement(struct hci_dev *hdev, struct adv_info *adv) +static int hci_adv_bcast_annoucement(struct hci_dev *hdev, u8 instance) { + struct adv_info *adv; u8 bid[3]; u8 ad[HCI_MAX_EXT_AD_LENGTH]; u8 len; + int err = 0; - /* Skip if NULL adv as instance 0x00 is used for general purpose + /* Skip if instance 0x00 as it is used for general purpose * advertising so it cannot used for the likes of Broadcast Announcement * as it can be overwritten at any point. */ - if (!adv) + if (!instance) return 0; + hci_dev_lock(hdev); + + /* The instance may have been removed while waiting for the + * controller, in which case there is nothing to announce. + */ + adv = hci_find_adv_instance(hdev, instance); + if (!adv) + goto unlock; + /* Check if PA data doesn't contains a Basic Audio Announcement then * there is nothing to do. */ if (!eir_get_service_data(adv->per_adv_data, adv->per_adv_data_len, 0x1851, NULL)) - return 0; + goto unlock; /* Check if advertising data already has a Broadcast Announcement since * the process may want to control the Broadcast ID directly and in that @@ -1864,34 +2002,44 @@ static int hci_adv_bcast_annoucement(struct hci_dev *hdev, struct adv_info *adv) */ if (eir_get_service_data(adv->adv_data, adv->adv_data_len, 0x1852, NULL)) - return 0; + goto unlock; /* Generate Broadcast ID */ get_random_bytes(bid, sizeof(bid)); len = eir_append_service_data(ad, 0, 0x1852, bid, sizeof(bid)); if (adv->adv_data_len > sizeof(ad) - len) { bt_dev_err(hdev, "No room for Broadcast Announcement"); - return -EINVAL; + err = -EINVAL; + goto unlock; } memcpy(ad + len, adv->adv_data, adv->adv_data_len); - hci_set_adv_instance_data(hdev, adv->instance, len + adv->adv_data_len, + hci_set_adv_instance_data(hdev, instance, len + adv->adv_data_len, ad, 0, NULL); - return hci_update_adv_data_sync(hdev, adv->instance); + hci_dev_unlock(hdev); + + return hci_update_adv_data_sync(hdev, instance); + +unlock: + hci_dev_unlock(hdev); + return err; } int hci_start_per_adv_sync(struct hci_dev *hdev, u8 instance, u8 sid, u8 data_len, u8 *data, u32 flags, u16 min_interval, u16 max_interval, u16 sync_interval) { - struct adv_info *adv = NULL; + struct adv_info *adv; + u8 bcast_instance = 0; int err; bool added = false; hci_disable_per_advertising_sync(hdev, instance); if (instance) { + hci_dev_lock(hdev); + adv = hci_find_adv_instance(hdev, instance); if (adv) { if (sid != HCI_SID_INVALID && adv->sid != sid) { @@ -1900,6 +2048,7 @@ int hci_start_per_adv_sync(struct hci_dev *hdev, u8 instance, u8 sid, */ adv = hci_find_adv_sid(hdev, sid); if (!adv) { + hci_dev_unlock(hdev); bt_dev_err(hdev, "Unable to find adv_info"); return -EINVAL; @@ -1918,11 +2067,17 @@ int hci_start_per_adv_sync(struct hci_dev *hdev, u8 instance, u8 sid, data_len, data, sync_interval, sync_interval); - if (IS_ERR(adv)) + if (IS_ERR(adv)) { + hci_dev_unlock(hdev); return PTR_ERR(adv); + } adv->pending = false; added = true; } + + bcast_instance = adv->instance; + + hci_dev_unlock(hdev); } /* Start advertising */ @@ -1930,7 +2085,7 @@ int hci_start_per_adv_sync(struct hci_dev *hdev, u8 instance, u8 sid, if (err < 0) goto fail; - err = hci_adv_bcast_annoucement(hdev, adv); + err = hci_adv_bcast_annoucement(hdev, bcast_instance); if (err < 0) goto fail; @@ -1950,8 +2105,11 @@ int hci_start_per_adv_sync(struct hci_dev *hdev, u8 instance, u8 sid, return 0; fail: - if (added) + if (added) { + hci_dev_lock(hdev); hci_remove_adv_instance(hdev, instance); + hci_dev_unlock(hdev); + } return err; } @@ -1981,6 +2139,7 @@ int hci_enable_advertising_sync(struct hci_dev *hdev) u8 own_addr_type, enable = 0x01; bool connectable; u16 adv_min_interval, adv_max_interval; + bool scannable; u32 flags; u8 status; @@ -1988,8 +2147,25 @@ int hci_enable_advertising_sync(struct hci_dev *hdev) return hci_enable_ext_advertising_sync(hdev, hdev->cur_adv_instance); + /* Snapshot the instance under hdev->lock since it may be removed + * while waiting for the commands below to complete. + */ + hci_dev_lock(hdev); + flags = hci_adv_instance_flags(hdev, hdev->cur_adv_instance); + scannable = hci_adv_instance_is_scannable(hdev, + hdev->cur_adv_instance); + adv_instance = hci_find_adv_instance(hdev, hdev->cur_adv_instance); + if (adv_instance) { + adv_min_interval = adv_instance->min_interval; + adv_max_interval = adv_instance->max_interval; + } else { + adv_min_interval = hdev->le_adv_min_interval; + adv_max_interval = hdev->le_adv_max_interval; + } + + hci_dev_unlock(hdev); /* If the "connectable" instance flag was not set, then choose between * ADV_IND and ADV_NONCONN_IND based on the global connectable setting. @@ -2023,18 +2199,10 @@ int hci_enable_advertising_sync(struct hci_dev *hdev) memset(&cp, 0, sizeof(cp)); - if (adv_instance) { - adv_min_interval = adv_instance->min_interval; - adv_max_interval = adv_instance->max_interval; - } else { - adv_min_interval = hdev->le_adv_min_interval; - adv_max_interval = hdev->le_adv_max_interval; - } - if (connectable) { cp.type = LE_ADV_IND; } else { - if (hci_adv_instance_is_scannable(hdev, hdev->cur_adv_instance)) + if (scannable) cp.type = LE_ADV_SCAN_IND; else cp.type = LE_ADV_NONCONN_IND; @@ -2077,6 +2245,9 @@ int hci_enable_advertising(struct hci_dev *hdev) int hci_remove_ext_adv_instance_sync(struct hci_dev *hdev, u8 instance, struct sock *sk) { + struct adv_info *adv = NULL; + u8 handle = instance; + bool global = false; int err; if (!ext_adv_capable(hdev)) @@ -2086,13 +2257,53 @@ int hci_remove_ext_adv_instance_sync(struct hci_dev *hdev, u8 instance, if (err) return err; - /* If request specifies an instance that doesn't exist, fail */ - if (instance > 0 && !hci_find_adv_instance(hdev, instance)) - return -EINVAL; + if (instance) { + hci_dev_lock(hdev); + + adv = hci_find_adv_instance(hdev, instance); + if (adv) { + handle = adv->handle; + + /* An instance sharing handle 0x00 with Global + * Advertising doesn't own the set while Global + * Advertising is on, and the set may still be enabled + * for it, which the controller would refuse to remove. + */ + global = !handle && + (hci_dev_test_flag(hdev, HCI_ADVERTISING) || + hci_dev_test_flag(hdev, HCI_LE_ADV_0)); + } + + hci_dev_unlock(hdev); + + /* If request specifies an instance that doesn't exist, fail */ + if (!adv) + return -EINVAL; + } + + if (!global) { + err = __hci_cmd_sync_status_sk(hdev, HCI_OP_LE_REMOVE_ADV_SET, + sizeof(handle), &handle, 0, + HCI_CMD_TIMEOUT, sk); + if (err) + return err; + } + + /* hci_cc_le_remove_adv_set() removes the instance numbered as the + * handle it sent, so remove here an instance using another handle: + * instance 1 on handle 0x00, on a controller supporting a single + * advertising set. The completion can't tell it from instance 0. + */ + if (handle != instance) { + hci_dev_lock(hdev); + + if (!hci_remove_adv_instance(hdev, instance)) + mgmt_advertising_removed(sk, hdev, instance); - return __hci_cmd_sync_status_sk(hdev, HCI_OP_LE_REMOVE_ADV_SET, - sizeof(instance), &instance, 0, - HCI_CMD_TIMEOUT, sk); + hci_dev_unlock(hdev); + } + + return 0; } int hci_le_terminate_big_sync(struct hci_dev *hdev, u8 handle, u8 reason) @@ -2119,9 +2330,13 @@ int hci_schedule_adv_instance_sync(struct hci_dev *hdev, u8 instance, if (hdev->adv_instance_timeout) return -EBUSY; + hci_dev_lock(hdev); + adv = hci_find_adv_instance(hdev, instance); - if (!adv) + if (!adv) { + hci_dev_unlock(hdev); return -ENOENT; + } /* A zero timeout means unlimited advertising. As long as there is * only one instance, duration should be ignored. We still set a timeout @@ -2151,6 +2366,8 @@ int hci_schedule_adv_instance_sync(struct hci_dev *hdev, u8 instance, secs_to_jiffies(timeout)); } + hci_dev_unlock(hdev); + /* If we're just re-scheduling the same instance again then do not * execute any HCI commands. This happens when a single instance is * being advertised. @@ -2248,7 +2465,7 @@ static int hci_remove_adv_sync(struct hci_dev *hdev, u8 instance, int hci_remove_advertising_sync(struct hci_dev *hdev, struct sock *sk, u8 instance, bool force) { - struct adv_info *next = NULL; + u8 next_instance = 0; int err; /* Cancel any timeout concerning the removed instance(s). */ @@ -2259,20 +2476,34 @@ int hci_remove_advertising_sync(struct hci_dev *hdev, struct sock *sk, * the current one. This can be the same instance again * if there is only one instance. */ - if (hdev->cur_adv_instance == instance) + if (hdev->cur_adv_instance == instance) { + struct adv_info *next; + + hci_dev_lock(hdev); next = hci_get_next_instance(hdev, instance); + if (next) + next_instance = next->instance; + hci_dev_unlock(hdev); + } if (!instance) { err = hci_clear_adv_sync(hdev, sk, force); if (err) return err; } else { - struct adv_info *adv = hci_find_adv_instance(hdev, instance); + struct adv_info *adv; + bool remove; + + hci_dev_lock(hdev); + adv = hci_find_adv_instance(hdev, instance); + remove = force || + (adv && adv->timeout && !adv->remaining_time); + hci_dev_unlock(hdev); - if (force || (adv && adv->timeout && !adv->remaining_time)) { + if (remove) { /* Don't advertise a removed instance. */ - if (next && next->instance == instance) - next = NULL; + if (next_instance == instance) + next_instance = 0; err = hci_remove_adv_sync(hdev, instance, sk); if (err) @@ -2283,8 +2514,8 @@ int hci_remove_advertising_sync(struct hci_dev *hdev, struct sock *sk, if (!hdev_is_powered(hdev) || hci_dev_test_flag(hdev, HCI_ADVERTISING)) return 0; - if (next && !ext_adv_capable(hdev)) - hci_schedule_adv_instance_sync(hdev, next->instance, false); + if (next_instance && !ext_adv_capable(hdev)) + hci_schedule_adv_instance_sync(hdev, next_instance, false); return 0; } @@ -2749,10 +2980,28 @@ static int hci_pause_advertising_sync(struct hci_dev *hdev) return 0; } +/* Copy the instance identifiers in list order under hdev->lock. + * There are at most U8_MAX instances, with identifiers 1..U8_MAX. + * Callers can then wait for commands without retaining list pointers. + */ +static size_t adv_instance_list_copy(struct hci_dev *hdev, u8 *ids) +{ + struct adv_info *adv; + size_t n = 0; + + hci_dev_lock(hdev); + + list_for_each_entry(adv, &hdev->adv_instances, list) + ids[n++] = adv->instance; + + hci_dev_unlock(hdev); + + return n; +} + /* This function enables all user advertising instances */ static int hci_resume_advertising_sync(struct hci_dev *hdev) { - struct adv_info *adv, *tmp; int err = 0; /* If advertising has not been paused there is nothing to do. */ @@ -2769,15 +3018,20 @@ static int hci_resume_advertising_sync(struct hci_dev *hdev) bt_dev_dbg(hdev, "Resuming advertising instances"); if (ext_adv_capable(hdev)) { + u8 ids[U8_MAX]; + size_t i, n; + + n = adv_instance_list_copy(hdev, ids); + /* Call for each tracked instance to be re-enabled */ - list_for_each_entry_safe(adv, tmp, &hdev->adv_instances, list) { + for (i = 0; i < n; i++) { err = hci_enable_ext_advertising_sync(hdev, - adv->instance); + ids[i]); if (!err) continue; /* If the instance cannot be resumed remove it */ - hci_remove_ext_adv_instance_sync(hdev, adv->instance, + hci_remove_ext_adv_instance_sync(hdev, ids[i], NULL); } @@ -3602,7 +3856,8 @@ int hci_write_le_host_supported_sync(struct hci_dev *hdev, u8 le, u8 simul) static int hci_powered_update_adv_sync(struct hci_dev *hdev) { - struct adv_info *adv, *tmp; + u8 ids[U8_MAX]; + size_t i, n; int err; if (!hci_dev_test_flag(hdev, HCI_LE_ENABLED)) @@ -3638,9 +3893,11 @@ static int hci_powered_update_adv_sync(struct hci_dev *hdev) hci_enable_advertising_sync(hdev); } + n = adv_instance_list_copy(hdev, ids); + /* Call for each tracked instance to be scheduled */ - list_for_each_entry_safe(adv, tmp, &hdev->adv_instances, list) - hci_schedule_adv_instance_sync(hdev, adv->instance, true); + for (i = 0; i < n; i++) + hci_schedule_adv_instance_sync(hdev, ids[i], true); return 0; } @@ -3798,7 +4055,9 @@ int hci_powered_update_sync(struct hci_dev *hdev) * registration is required so that LE SMP can clearly decide if * the public address or static address is used. */ + hci_dev_lock(hdev); smp_register(hdev); + hci_dev_unlock(hdev); err = hci_write_ssp_mode_sync(hdev, 0x01); if (err) @@ -5614,7 +5873,9 @@ int hci_dev_open_sync(struct hci_dev *hdev) if (!ret) { hci_dev_hold(hdev); hci_dev_set_flag(hdev, HCI_RPA_EXPIRED); + hci_dev_lock(hdev); hci_adv_instances_set_rpa_expired(hdev, true); + hci_dev_unlock(hdev); set_bit(HCI_UP, &hdev->flags); hci_sock_dev_event(hdev, HCI_DEV_UP); hci_leds_update_powered(hdev, true); @@ -5694,6 +5955,7 @@ static int hci_dev_shutdown(struct hci_dev *hdev) int hci_dev_close_sync(struct hci_dev *hdev) { + struct hci_conn *conn; bool auto_off; int err = 0; @@ -5757,10 +6019,28 @@ int hci_dev_close_sync(struct hci_dev *hdev) cancel_delayed_work_sync(&hdev->rpa_expired); + hci_dev_lock(hdev); list_for_each_entry(adv_instance, &hdev->adv_instances, list) cancel_delayed_work_sync(&adv_instance->rpa_expired_cb); + hci_dev_unlock(hdev); } + /* A delayed work whose timer was armed before close would queue + * itself while the workqueue is draining. Disable the connection + * works so that hci_conn_drop() and the timers can no longer queue + * them. The connections are deleted below, so nothing re-enables + * them. HCI_UP is clear, so no new connection can be added after + * this walk. + */ + hci_dev_lock(hdev); + list_for_each_entry(conn, &hdev->conn_hash.list, list) { + disable_delayed_work(&conn->disc_work); + disable_delayed_work(&conn->auto_accept_work); + disable_delayed_work(&conn->idle_work); + disable_delayed_work(&conn->le_conn_timeout); + } + hci_dev_unlock(hdev); + /* Avoid potential lockdep warnings from the *_flush() calls by * ensuring the workqueue is empty up front. */ @@ -5772,6 +6052,11 @@ int hci_dev_close_sync(struct hci_dev *hdev) auto_off = hci_dev_test_and_clear_flag(hdev, HCI_AUTO_OFF); + /* Nothing is going to send the mesh transmissions left, whether or not + * mgmt is told about the controller being powered off. + */ + mgmt_mesh_flush(hdev); + if (!auto_off && !hci_dev_test_flag(hdev, HCI_USER_CHANNEL) && hci_dev_test_flag(hdev, HCI_MGMT)) __mgmt_power_off(hdev); @@ -8002,6 +8287,7 @@ static int hci_le_past_set_info_sync(struct hci_dev *hdev, void *data) { struct past_data *past = data; struct hci_cp_le_past_set_info cp; + struct adv_info *adv; hci_dev_lock(hdev); @@ -8014,6 +8300,9 @@ static int hci_le_past_set_info_sync(struct hci_dev *hdev, void *data) memset(&cp, 0, sizeof(cp)); cp.handle = cpu_to_le16(past->le->handle); cp.adv_handle = past->conn->iso_qos.bcast.bis; + adv = hci_find_adv_instance(hdev, cp.adv_handle); + if (adv) + cp.adv_handle = adv->handle; hci_dev_unlock(hdev); diff --git a/net/bluetooth/l2cap_core.c b/net/bluetooth/l2cap_core.c index 7dcb0586a10b2a..da947b65d26a7e 100644 --- a/net/bluetooth/l2cap_core.c +++ b/net/bluetooth/l2cap_core.c @@ -1033,9 +1033,11 @@ static int l2cap_get_ident(struct l2cap_conn *conn) u8 max; int ident; - /* LE link does not support tools like l2ping so use the full range */ + /* LE link does not support tools like l2ping so use the full range, + * except for L2CAP_IDENT_LE_CREDITS which is reserved. + */ if (conn->hcon->type == LE_LINK) - max = 255; + max = L2CAP_IDENT_LE_CREDITS - 1; /* Get next available identificator. * 1 - 128 are used by kernel. * 129 - 199 are reserved. @@ -1747,10 +1749,40 @@ static void l2cap_le_conn_ready(struct l2cap_conn *conn) } } -static void l2cap_conn_ready(struct l2cap_conn *conn) +static bool l2cap_is_blocked(struct hci_conn *hcon) + __must_hold(&hcon->hdev->lock) { + /* Since we can't actively block incoming LE connections we must + * at least ensure that we ignore incoming data from them. + */ + return hcon->type == LE_LINK && + hci_bdaddr_list_lookup(&hcon->hdev->reject_list, &hcon->dst, + bdaddr_dst_type(hcon)); +} + +static void l2cap_queue_pending_rx(struct hci_conn *hcon) + __must_hold(&hcon->hdev->lock) +{ + struct l2cap_conn *conn = hcon->l2cap_data; + + mutex_lock(&conn->lock); + + if (!skb_queue_empty(&conn->pending_rx)) { + /* Teardown holds hdev->lock while cancelling the worker. + * Pass the decision under conn->lock to avoid that lock. + */ + conn->pending_rx_blocked = l2cap_is_blocked(hcon); + queue_work(hcon->hdev->workqueue, &conn->pending_rx_work); + } + + mutex_unlock(&conn->lock); +} + +static void l2cap_conn_ready(struct hci_conn *hcon) + __must_hold(&hcon->hdev->lock) +{ + struct l2cap_conn *conn = hcon->l2cap_data; struct l2cap_chan *chan; - struct hci_conn *hcon = conn->hcon; BT_DBG("conn %p", conn); @@ -1782,7 +1814,7 @@ static void l2cap_conn_ready(struct l2cap_conn *conn) if (hcon->type == LE_LINK) l2cap_le_conn_ready(conn); - queue_work(hcon->hdev->workqueue, &conn->pending_rx_work); + l2cap_queue_pending_rx(hcon); } /* Notify sockets that we cannot guaranty reliability anymore */ @@ -3828,6 +3860,7 @@ static int l2cap_parse_conf_rsp(struct l2cap_chan *chan, void *rsp, int len, unsigned long val; struct l2cap_conf_rfc rfc = { .mode = L2CAP_MODE_BASIC }; struct l2cap_conf_efs efs; + bool remote_efs = false; BT_DBG("chan %p, rsp %p, len %d, req %p", chan, rsp, len, data); @@ -3883,6 +3916,7 @@ static int l2cap_parse_conf_rsp(struct l2cap_chan *chan, void *rsp, int len, if (olen != sizeof(efs)) break; memcpy(&efs, (void *)val, olen); + remote_efs = true; if (chan->local_stype != L2CAP_SERV_NOTRAFIC && efs.stype != L2CAP_SERV_NOTRAFIC && efs.stype != chan->local_stype) @@ -3921,7 +3955,8 @@ static int l2cap_parse_conf_rsp(struct l2cap_chan *chan, void *rsp, int len, chan->ack_win = min_t(u16, chan->ack_win, rfc.txwin_size); - if (test_bit(FLAG_EFS_ENABLE, &chan->flags)) { + if (remote_efs && + test_bit(FLAG_EFS_ENABLE, &chan->flags)) { chan->local_msdu = le16_to_cpu(efs.msdu); chan->local_sdu_itime = le32_to_cpu(efs.sdu_itime); @@ -5701,6 +5736,16 @@ static inline int l2cap_ecred_conn_rsp(struct l2cap_conn *conn, break; } + /* + * Validate MPS and MTU per BT Core Spec + * Vol 3 Part A Sec 10.2 + */ + if (mtu < L2CAP_ECRED_MIN_MTU || + mps < L2CAP_ECRED_MIN_MPS) { + l2cap_chan_del(chan, ECONNREFUSED); + break; + } + chan->ident = 0; chan->dcid = dcid; chan->omtu = mtu; @@ -6186,6 +6231,7 @@ static void append_skb_frag(struct sk_buff *skb, struct sk_buff *new_frag, static int l2cap_reassemble_sdu(struct l2cap_chan *chan, struct sk_buff *skb, struct l2cap_ctrl *control) { + struct sk_buff *sdu; int err = -EINVAL; switch (control->sar) { @@ -6246,15 +6292,25 @@ static int l2cap_reassemble_sdu(struct l2cap_chan *chan, struct sk_buff *skb, if (chan->sdu->len != chan->sdu_len) break; - err = chan->ops->recv(chan, chan->sdu); + /* Reassembly complete. Hand the SDU over before the + * callback, for the reason given in l2cap_ecred_data_rcv(): + * the callback takes ownership and may free it, while + * l2cap_chan_rx_avail() -> l2cap_chan_le_send_credits() reads + * chan->sdu->len on the way out - it does so before the mode + * test that makes the rest of that function a no-op here. + * Return directly, since the state this leaves is what the + * trailing error block would otherwise set again. + */ + sdu = chan->sdu; + chan->sdu = NULL; + chan->sdu_last_frag = NULL; + chan->sdu_len = 0; - if (!err) { - /* Reassembly complete */ - chan->sdu = NULL; - chan->sdu_last_frag = NULL; - chan->sdu_len = 0; - } - break; + err = chan->ops->recv(chan, sdu); + if (err) + kfree_skb(sdu); + + return err; } if (err) { @@ -7081,7 +7137,6 @@ static void l2cap_chan_le_send_credits(struct l2cap_chan *chan) struct l2cap_conn *conn = chan->conn; struct l2cap_le_credits pkt; u16 return_credits = l2cap_le_rx_credits(chan); - int ident; if (chan->mode != L2CAP_MODE_LE_FLOWCTL && chan->mode != L2CAP_MODE_EXT_FLOWCTL) @@ -7099,18 +7154,14 @@ static void l2cap_chan_le_send_credits(struct l2cap_chan *chan) pkt.cid = cpu_to_le16(chan->scid); pkt.credits = cpu_to_le16(return_credits); - ident = l2cap_get_ident(conn); - - l2cap_send_cmd(conn, ident, L2CAP_LE_CREDITS, sizeof(pkt), &pkt); - - /* L2CAP_LE_CREDITS has no response so the ident is never released by - * l2cap_put_ident() - release it right away, otherwise the tx_ida - * range is exhausted after 254 packets and from then on credits are - * sent with the invalid ident 0, which some remote stacks ignore, - * stalling the channel. + /* L2CAP_LE_CREDITS has no response so it uses the reserved ident rather + * than one from conn->tx_ida, which would have to be released right + * away or would be exhausted after 254 packets, and could otherwise + * collide with the ident of a request still outstanding. A reject of it + * can't match any request either. */ - if (ident > 0) - ida_free(&conn->tx_ida, ident); + l2cap_send_cmd(conn, L2CAP_IDENT_LE_CREDITS, L2CAP_LE_CREDITS, + sizeof(pkt), &pkt); } void l2cap_chan_rx_avail(struct l2cap_chan *chan, ssize_t rx_avail) @@ -7245,12 +7296,26 @@ static int l2cap_ecred_data_rcv(struct l2cap_chan *chan, struct sk_buff *skb) skb = NULL; if (chan->sdu->len == chan->sdu_len) { - err = l2cap_ecred_recv(chan, chan->sdu); - if (!err) { - chan->sdu = NULL; - chan->sdu_last_frag = NULL; - chan->sdu_len = 0; - } + struct sk_buff *sdu = chan->sdu; + + /* The receive callback takes ownership of a reassembled SDU and + * may free it, while l2cap_ecred_recv() goes on to update the + * credits - which reads chan->sdu->len. Drop the reassembly + * state before handing the SDU over, and release it here if the + * callback refused it, so that it is still freed exactly once. + * The reassembly state is already clear at that point, so + * return instead of falling into the failed: block, whose + * kfree_skb(chan->sdu) would have nothing left to free. + */ + chan->sdu = NULL; + chan->sdu_last_frag = NULL; + chan->sdu_len = 0; + + err = l2cap_ecred_recv(chan, sdu); + if (err) + kfree_skb(sdu); + + return 0; } failed: @@ -7381,7 +7446,8 @@ static void l2cap_conless_channel(struct l2cap_conn *conn, __le16 psm, kfree_skb(skb); } -static void l2cap_recv_frame(struct l2cap_conn *conn, struct sk_buff *skb) +static void l2cap_recv_frame(struct l2cap_conn *conn, struct sk_buff *skb, + bool blocked) __must_hold(&conn->lock) { struct l2cap_hdr *lh = (void *) skb->data; @@ -7408,12 +7474,7 @@ static void l2cap_recv_frame(struct l2cap_conn *conn, struct sk_buff *skb) return; } - /* Since we can't actively block incoming LE connections we must - * at least ensure that we ignore incoming data from them. - */ - if (hcon->type == LE_LINK && - hci_bdaddr_list_lookup(&hcon->hdev->reject_list, &hcon->dst, - bdaddr_dst_type(hcon))) { + if (blocked) { kfree_skb(skb); return; } @@ -7461,7 +7522,7 @@ static void process_pending_rx(struct work_struct *work) */ while (!test_bit(HCI_CONN_ENC_KEY_SIZE_PEND, conn->hcon->flags) && (skb = skb_dequeue(&conn->pending_rx))) - l2cap_recv_frame(conn, skb); + l2cap_recv_frame(conn, skb, conn->pending_rx_blocked); mutex_unlock(&conn->lock); } @@ -7913,7 +7974,7 @@ static void l2cap_connect_cfm(struct hci_conn *hcon, u8 status) mutex_unlock(&conn->lock); - l2cap_conn_ready(conn); + l2cap_conn_ready(hcon); } int l2cap_disconn_ind(struct hci_conn *hcon) @@ -8052,8 +8113,7 @@ static void l2cap_security_cfm(struct hci_conn *hcon, u8 status, u8 encrypt) mutex_unlock(&conn->lock); /* Process data held back while the encryption key size was read */ - if (!skb_queue_empty(&conn->pending_rx)) - queue_work(hcon->hdev->workqueue, &conn->pending_rx_work); + l2cap_queue_pending_rx(hcon); } /* Append fragment into frame respecting the maximum len of rx_skb */ @@ -8142,6 +8202,7 @@ int l2cap_recv_acldata(struct hci_dev *hdev, u16 handle, { struct hci_conn *hcon; struct l2cap_conn *conn; + bool blocked; int len; /* Lock hdev for hci_conn, and race on l2cap_data vs. l2cap_conn_del */ @@ -8164,6 +8225,7 @@ int l2cap_recv_acldata(struct hci_dev *hdev, u16 handle, conn = l2cap_conn_add(hcon); conn = l2cap_conn_hold_unless_zero(conn); + blocked = l2cap_is_blocked(hcon); hcon = NULL; hci_dev_unlock(hdev); @@ -8200,7 +8262,7 @@ int l2cap_recv_acldata(struct hci_dev *hdev, u16 handle, if (len == skb->len) { /* Complete frame received */ - l2cap_recv_frame(conn, skb); + l2cap_recv_frame(conn, skb, blocked); goto unlock; } @@ -8224,7 +8286,7 @@ int l2cap_recv_acldata(struct hci_dev *hdev, u16 handle, * setting the socket unreliable. */ skb->len = len; - l2cap_recv_frame(conn, skb); + l2cap_recv_frame(conn, skb, blocked); l2cap_conn_unreliable(conn, ECOMM); goto unlock; } @@ -8274,7 +8336,7 @@ int l2cap_recv_acldata(struct hci_dev *hdev, u16 handle, */ struct sk_buff *rx_skb = conn->rx_skb; conn->rx_skb = NULL; - l2cap_recv_frame(conn, rx_skb); + l2cap_recv_frame(conn, rx_skb, blocked); } break; } diff --git a/net/bluetooth/l2cap_sock.c b/net/bluetooth/l2cap_sock.c index e5c15c083c1acc..6b65710845dcb4 100644 --- a/net/bluetooth/l2cap_sock.c +++ b/net/bluetooth/l2cap_sock.c @@ -1229,11 +1229,11 @@ static void l2cap_publish_rx_avail(struct l2cap_chan *chan) /* Correct available memory by estimated sk_buff overhead. * This is significant due to small transfer sizes. However, accept - * at least one full packet if receive space is non-zero. + * at least one full SDU if receive space is non-zero. */ expected_skbs = DIV_ROUND_UP(avail, chan->mps); skb_overhead = expected_skbs * sizeof(struct sk_buff); - if (skb_overhead < avail) + if (avail - skb_overhead >= chan->imtu + L2CAP_SDULEN_SIZE) l2cap_chan_rx_avail(chan, avail - skb_overhead); else l2cap_chan_rx_avail(chan, -1); @@ -1292,6 +1292,7 @@ static int l2cap_sock_recvmsg(struct socket *sock, struct msghdr *msg, { struct sock *sk = sock->sk; struct l2cap_pinfo *pi = l2cap_pi(sk); + bool have_conn; int err; if (unlikely(flags & MSG_ERRQUEUE)) @@ -1312,9 +1313,12 @@ static int l2cap_sock_recvmsg(struct socket *sock, struct msghdr *msg, pi->chan->mode != L2CAP_MODE_EXT_FLOWCTL) return err; - lock_sock(sk); - + /* Returning credits must be serialized with the RX path */ + have_conn = l2cap_chan_lock_conn(pi->chan); l2cap_publish_rx_avail(pi->chan); + l2cap_chan_unlock_conn(pi->chan, have_conn); + + lock_sock(sk); /* Attempt to put pending rx data in the socket buffer */ while (!list_empty(&pi->rx_busy)) { diff --git a/net/bluetooth/mgmt.c b/net/bluetooth/mgmt.c index b9262ec134a293..e6876c76ca2411 100644 --- a/net/bluetooth/mgmt.c +++ b/net/bluetooth/mgmt.c @@ -444,10 +444,8 @@ static int read_index_list(struct sock *sk, struct hci_dev *hdev, void *data, read_lock(&hci_dev_list_lock); count = 0; - list_for_each_entry(d, &hci_dev_list, list) { - if (!hci_dev_test_flag(d, HCI_UNCONFIGURED)) - count++; - } + list_for_each_entry(d, &hci_dev_list, list) + count++; rp_len = sizeof(*rp) + (2 * count); rp = kmalloc(rp_len, GFP_ATOMIC); @@ -1083,6 +1081,7 @@ static void discov_off(struct work_struct *work) static int send_settings_rsp(struct sock *sk, u16 opcode, struct hci_dev *hdev); +/* This function requires the caller holds hdev->lock */ static void mesh_send_complete(struct hci_dev *hdev, struct mgmt_mesh_tx *mesh_tx, bool silent) { @@ -1095,37 +1094,95 @@ static void mesh_send_complete(struct hci_dev *hdev, mgmt_mesh_remove(mesh_tx); } -static int mesh_send_done_sync(struct hci_dev *hdev, void *data) +/* The cmd_sync entries identify the transmission by handle rather than by + * pointer since the mesh_tx can be removed while the entry is queued or + * running. + */ +#define MESH_TX_DATA(_handle) ((void *)(unsigned long)(_handle)) +#define MESH_TX_HANDLE(_data) ((u8)(unsigned long)(_data)) + +static int mesh_send_sync(struct hci_dev *hdev, void *data); +static void mesh_send_start_complete(struct hci_dev *hdev, void *data, int err); + +/* Start sending the first transmission unless one is already in progress, + * HCI_MESH_SENDING is set while the first transmission is being sent. + * Completion is not reported for @new, the handle of a transmission userspace + * wasn't told about yet. + * + * This function requires the caller holds hdev->lock. + */ +static void __mesh_next(struct hci_dev *hdev, u8 new) { struct mgmt_mesh_tx *mesh_tx; + int err; - hci_dev_clear_flag(hdev, HCI_MESH_SENDING); - if (list_empty(&hdev->adv_instances)) - hci_disable_advertising_sync(hdev); - mesh_tx = mgmt_mesh_next(hdev, NULL); - - if (mesh_tx) - mesh_send_complete(hdev, mesh_tx, false); + while (!hci_dev_test_flag(hdev, HCI_MESH_SENDING)) { + mesh_tx = mgmt_mesh_next(hdev, NULL); + if (!mesh_tx) + return; - return 0; + err = hci_cmd_sync_queue(hdev, mesh_send_sync, + MESH_TX_DATA(mesh_tx->handle), + mesh_send_start_complete); + if (err < 0) + mesh_send_complete(hdev, mesh_tx, + mesh_tx->handle == new); + else + hci_dev_set_flag(hdev, HCI_MESH_SENDING); + } } -static int mesh_send_sync(struct hci_dev *hdev, void *data); -static void mesh_send_start_complete(struct hci_dev *hdev, void *data, int err); static void mesh_next(struct hci_dev *hdev, void *data, int err) { - struct mgmt_mesh_tx *mesh_tx = mgmt_mesh_next(hdev, NULL); - - if (!mesh_tx) + /* The entry is being cancelled with the cmd_sync lock held, which + * can't be taken before hdev->lock. + */ + if (err == -ECANCELED) return; - err = hci_cmd_sync_queue(hdev, mesh_send_sync, mesh_tx, - mesh_send_start_complete); + hci_dev_lock(hdev); + __mesh_next(hdev, 0); + hci_dev_unlock(hdev); +} - if (err < 0) +static int mesh_send_done_sync(struct hci_dev *hdev, void *data) +{ + struct mgmt_mesh_tx *mesh_tx; + u8 handle; + bool disable; + + hci_dev_lock(hdev); + + mesh_tx = mgmt_mesh_next(hdev, NULL); + if (!mesh_tx || !hci_dev_test_flag(hdev, HCI_MESH_SENDING)) { + hci_dev_unlock(hdev); + return 0; + } + + handle = mesh_tx->handle; + disable = list_empty(&hdev->adv_instances); + + hci_dev_unlock(hdev); + + if (disable) + hci_disable_advertising_sync(hdev); + + hci_dev_lock(hdev); + + /* The transmission can be cancelled meanwhile, in which case whoever + * did so already moved on to the next one. HCI_MESH_SENDING is only + * cleared with the transmission removed so Mesh Send doesn't start + * another one in between. + */ + mesh_tx = mgmt_mesh_find(hdev, handle); + if (mesh_tx) { mesh_send_complete(hdev, mesh_tx, false); - else - hci_dev_set_flag(hdev, HCI_MESH_SENDING); + hci_dev_clear_flag(hdev, HCI_MESH_SENDING); + } + + hci_dev_unlock(hdev); + + return 0; } static void mesh_send_done(struct work_struct *work) @@ -1139,6 +1196,33 @@ static void mesh_send_done(struct work_struct *work) hci_cmd_sync_queue(hdev, mesh_send_done_sync, NULL, mesh_next); } +/* Nothing is going to send the transmissions left, e.g. when the controller + * is powered off. + * + * This function requires the caller holds hdev->lock. + */ +static void mesh_flush(struct hci_dev *hdev, bool silent) +{ + struct mgmt_mesh_tx *mesh_tx; + + /* Stop the timer first, it checks HCI_MESH_SENDING without hdev->lock + * so once it is clear and the work is not running anymore nothing can + * queue mesh_send_done_sync behind the dequeue below. + */ + hci_dev_clear_flag(hdev, HCI_MESH_SENDING); + cancel_delayed_work_sync(&hdev->mesh_send_done); + + /* Entries still queued would otherwise run after the controller is + * powered on again and act on the transmissions started by then. The + * destroy callbacks don't take hdev->lock when cancelled. + */ + hci_cmd_sync_dequeue(hdev, mesh_send_sync, NULL, NULL); + hci_cmd_sync_dequeue(hdev, mesh_send_done_sync, NULL, NULL); + + while ((mesh_tx = mgmt_mesh_next(hdev, NULL))) + mesh_send_complete(hdev, mesh_tx, silent); +} + static void mgmt_init_hdev(struct sock *sk, struct hci_dev *hdev) { if (hci_dev_test_flag(hdev, HCI_MGMT)) @@ -2306,38 +2390,71 @@ static int set_mesh(struct sock *sk, struct hci_dev *hdev, void *data, u16 len) static void mesh_send_start_complete(struct hci_dev *hdev, void *data, int err) { - struct mgmt_mesh_tx *mesh_tx = data; - struct mgmt_cp_mesh_send *send = (void *)mesh_tx->param; - unsigned long mesh_send_interval; + struct mgmt_mesh_tx *mesh_tx; + struct mgmt_cp_mesh_send *send; u8 mgmt_err = mgmt_status(err); + /* The entry is being cancelled with the cmd_sync lock held, which + * can't be taken before hdev->lock, so leave the removal of the + * transmission, and HCI_MESH_SENDING, to whoever cancelled it or to + * mgmt_power_off() if the controller is going down. + */ + if (err == -ECANCELED) + return; + + hci_dev_lock(hdev); + + /* Cancelled while the entry was running, whoever did so already moved + * on to the next transmission. + */ + mesh_tx = mgmt_mesh_find(hdev, MESH_TX_HANDLE(data)); + if (!mesh_tx) { + hci_dev_unlock(hdev); + return; + } + /* Report any errors here, but don't report completion */ if (mgmt_err) { - hci_dev_clear_flag(hdev, HCI_MESH_SENDING); /* Send Complete Error Code for handle */ mesh_send_complete(hdev, mesh_tx, false); - if (err != -ECANCELED) - mesh_next(hdev, NULL, 0); + hci_dev_clear_flag(hdev, HCI_MESH_SENDING); + __mesh_next(hdev, 0); + hci_dev_unlock(hdev); return; } - mesh_send_interval = msecs_to_jiffies((send->cnt) * 25); + /* Queued with hdev->lock held so a cancel can't miss it */ + send = (void *)mesh_tx->param; queue_delayed_work(hdev->req_workqueue, &hdev->mesh_send_done, - mesh_send_interval); + msecs_to_jiffies((send->cnt) * 25)); + + hci_dev_unlock(hdev); } static int mesh_send_sync(struct hci_dev *hdev, void *data) { - struct mgmt_mesh_tx *mesh_tx = data; - struct mgmt_cp_mesh_send *send = (void *)mesh_tx->param; + struct mgmt_mesh_tx *mesh_tx; + struct mgmt_cp_mesh_send *send; struct adv_info *adv, *next_instance; u8 instance = hdev->le_num_of_adv_sets + 1; u16 timeout, duration; int err = 0; - if (hdev->le_num_of_adv_sets <= hdev->adv_instance_cnt) + hci_dev_lock(hdev); + + mesh_tx = mgmt_mesh_find(hdev, MESH_TX_HANDLE(data)); + if (!mesh_tx) { + hci_dev_unlock(hdev); + return -ENOENT; + } + + send = (void *)mesh_tx->param; + + if (hdev->le_num_of_adv_sets <= hdev->adv_instance_cnt) { + hci_dev_unlock(hdev); return MGMT_STATUS_BUSY; + } timeout = 1000; duration = send->cnt * INTERVAL_TO_MS(hdev->le_adv_max_interval); @@ -2375,6 +2492,8 @@ static int mesh_send_sync(struct hci_dev *hdev, void *data) instance = 0; } + hci_dev_unlock(hdev); + if (instance) return hci_schedule_adv_instance_sync(hdev, instance, true); @@ -2418,37 +2537,80 @@ static int mesh_features(struct sock *sk, struct hci_dev *hdev, return 0; } +/* Cancel a single transmission, the handle is looked up again after the + * entry has been dequeued since it may be gone or have completed meanwhile. + */ +static void mesh_cancel_tx(struct hci_dev *hdev, u8 handle) +{ + struct mgmt_mesh_tx *mesh_tx; + bool in_progress; + + hci_cmd_sync_dequeue(hdev, mesh_send_sync, MESH_TX_DATA(handle), NULL); + + hci_dev_lock(hdev); + mesh_tx = mgmt_mesh_find(hdev, handle); + in_progress = mesh_tx && hci_dev_test_flag(hdev, HCI_MESH_SENDING) && + mesh_tx == mgmt_mesh_next(hdev, NULL); + hci_dev_unlock(hdev); + + /* The done timer may have fired already and be waiting to complete + * the transmission in progress, which is being cancelled. + */ + if (in_progress) + hci_cmd_sync_dequeue(hdev, mesh_send_done_sync, NULL, NULL); + + hci_dev_lock(hdev); + + mesh_tx = mgmt_mesh_find(hdev, handle); + if (mesh_tx) { + /* If it is the transmission in progress make sure the timer + * doesn't complete the next one in its place. + */ + if (hci_dev_test_flag(hdev, HCI_MESH_SENDING) && + mesh_tx == mgmt_mesh_next(hdev, NULL)) { + cancel_delayed_work(&hdev->mesh_send_done); + hci_dev_clear_flag(hdev, HCI_MESH_SENDING); + } + + mesh_send_complete(hdev, mesh_tx, false); + } + + hci_dev_unlock(hdev); +} + static int send_cancel(struct hci_dev *hdev, void *data) { struct mgmt_pending_cmd *cmd = data; struct mgmt_cp_mesh_send_cancel *cancel = (void *)cmd->param; struct mgmt_mesh_tx *mesh_tx; + u8 handle; if (!cancel->handle) { - do { + for (;;) { + hci_dev_lock(hdev); mesh_tx = mgmt_mesh_next(hdev, cmd->sk); + handle = mesh_tx ? mesh_tx->handle : 0; + hci_dev_unlock(hdev); - if (mesh_tx) { - if (!hci_cmd_sync_dequeue(hdev, mesh_send_sync, - mesh_tx, NULL)) - mesh_send_complete(hdev, mesh_tx, false); - } - } while (mesh_tx); + if (!mesh_tx) + break; + + mesh_cancel_tx(hdev, handle); + } } else { + hci_dev_lock(hdev); mesh_tx = mgmt_mesh_find(hdev, cancel->handle); + handle = mesh_tx && mesh_tx->sk == cmd->sk ? mesh_tx->handle : 0; + hci_dev_unlock(hdev); - if (mesh_tx && mesh_tx->sk == cmd->sk) { - if (!hci_cmd_sync_dequeue(hdev, mesh_send_sync, - mesh_tx, NULL)) - mesh_send_complete(hdev, mesh_tx, false); - } + if (handle) + mesh_cancel_tx(hdev, handle); } mgmt_cmd_complete(cmd->sk, hdev->id, MGMT_OP_MESH_SEND_CANCEL, 0, NULL, 0); - if (!hci_dev_test_flag(hdev, HCI_MESH_SENDING)) - mesh_next(hdev, NULL, 0); + mesh_next(hdev, NULL, 0); return 0; } @@ -2499,7 +2661,6 @@ static int mesh_send(struct sock *sk, struct hci_dev *hdev, void *data, u16 len) struct mgmt_cp_mesh_send *send = data; struct mgmt_rp_mesh_read_features rp; u16 expected_len; - bool sending; int err = 0; if (!lmp_le_capable(hdev) || @@ -2521,6 +2682,15 @@ static int mesh_send(struct sock *sk, struct hci_dev *hdev, void *data, u16 len) hci_dev_lock(hdev); + /* Transmissions are flushed when the controller is closed, which is + * serialized with this by hdev->lock, so none can be left behind. + */ + if (!hdev_is_powered(hdev)) { + err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_MESH_SEND, + MGMT_STATUS_NOT_POWERED); + goto done; + } + memset(&rp, 0, sizeof(rp)); rp.max_handles = MESH_HANDLES_MAX; @@ -2532,27 +2702,27 @@ static int mesh_send(struct sock *sk, struct hci_dev *hdev, void *data, u16 len) goto done; } - sending = hci_dev_test_flag(hdev, HCI_MESH_SENDING); mesh_tx = mgmt_mesh_add(sk, hdev, send, len); - - if (!mesh_tx) + if (!mesh_tx) { err = -ENOMEM; - else if (!sending) - err = hci_cmd_sync_queue(hdev, mesh_send_sync, mesh_tx, - mesh_send_start_complete); + } else { + u8 handle = mesh_tx->handle; + + /* The first transmission is the one queued, which may not be + * the one just added. + */ + __mesh_next(hdev, handle); + + /* Queueing failed, the transmission was removed */ + if (!mgmt_mesh_find(hdev, handle)) + err = -EIO; + } if (err < 0) { bt_dev_err(hdev, "Send Mesh Failed %d", err); err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_MESH_SEND, MGMT_STATUS_FAILED); - - if (mesh_tx) { - if (sending) - mgmt_mesh_remove(mesh_tx); - } } else { - hci_dev_set_flag(hdev, HCI_MESH_SENDING); - mgmt_cmd_complete(sk, hdev->id, MGMT_OP_MESH_SEND, 0, &mesh_tx->handle, 1); } @@ -4013,22 +4183,34 @@ static int user_passkey_neg_reply(struct sock *sk, struct hci_dev *hdev, static int adv_expire_sync(struct hci_dev *hdev, u32 flags) { struct adv_info *adv_instance; + u8 instance; + + hci_dev_lock(hdev); adv_instance = hci_find_adv_instance(hdev, hdev->cur_adv_instance); if (!adv_instance) - return 0; + goto unlock; /* stop if current instance doesn't need to be changed */ if (!(adv_instance->flags & flags)) - return 0; + goto unlock; cancel_adv_timeout(hdev); adv_instance = hci_get_next_instance(hdev, adv_instance->instance); if (!adv_instance) - return 0; + goto unlock; - hci_schedule_adv_instance_sync(hdev, adv_instance->instance, true); + instance = adv_instance->instance; + + hci_dev_unlock(hdev); + + hci_schedule_adv_instance_sync(hdev, instance, true); + + return 0; + +unlock: + hci_dev_unlock(hdev); return 0; } @@ -6627,12 +6809,15 @@ static void set_advertising_complete(struct hci_dev *hdev, void *data, int err) instance = hdev->cur_adv_instance; if (!instance) { + hci_dev_lock(hdev); adv_instance = list_first_entry_or_null(&hdev->adv_instances, struct adv_info, list); - if (!adv_instance) - return; + if (adv_instance) + instance = adv_instance->instance; + hci_dev_unlock(hdev); - instance = adv_instance->instance; + if (!instance) + return; } err = hci_schedule_adv_instance_sync(hdev, instance, true); @@ -9093,9 +9278,9 @@ static void add_advertising_complete(struct hci_dev *hdev, void *data, int err) static int add_advertising_sync(struct hci_dev *hdev, void *data) { struct mgmt_pending_cmd *cmd = data; - struct mgmt_cp_add_advertising *cp = cmd->param; + u8 instance = PTR_UINT(cmd->user_data); - return hci_schedule_adv_instance_sync(hdev, cp->instance, true); + return hci_schedule_adv_instance_sync(hdev, instance, true); } static int add_advertising(struct sock *sk, struct hci_dev *hdev, @@ -9179,7 +9364,9 @@ static int add_advertising(struct sock *sk, struct hci_dev *hdev, if (hdev->adv_instance_cnt > prev_instance_cnt) mgmt_advertising_added(sk, hdev, cp->instance); - if (hdev->cur_adv_instance == cp->instance) { + if (ext_adv_capable(hdev)) { + schedule_instance = cp->instance; + } else if (hdev->cur_adv_instance == cp->instance) { /* If the currently advertised instance is being changed then * cancel the current advertising and schedule the next * instance. If there is only one instance then the overridden @@ -9226,7 +9413,7 @@ static int add_advertising(struct sock *sk, struct hci_dev *hdev, goto unlock; } - cp->instance = schedule_instance; + cmd->user_data = UINT_PTR(schedule_instance); err = hci_cmd_sync_queue(hdev, add_advertising_sync, cmd, add_advertising_complete); @@ -9455,6 +9642,7 @@ static int add_ext_adv_data_sync(struct hci_dev *hdev, void *data) { struct mgmt_pending_cmd *cmd = data; struct mgmt_cp_add_ext_adv_data *cp = cmd->param; + u8 instance = PTR_UINT(cmd->user_data); int err; if (ext_adv_capable(hdev)) { @@ -9469,7 +9657,7 @@ static int add_ext_adv_data_sync(struct hci_dev *hdev, void *data) return hci_enable_ext_advertising_sync(hdev, cp->instance); } - return hci_schedule_adv_instance_sync(hdev, cp->instance, true); + return hci_schedule_adv_instance_sync(hdev, instance, true); } static int add_ext_adv_data(struct sock *sk, struct hci_dev *hdev, void *data, @@ -9531,7 +9719,9 @@ static int add_ext_adv_data(struct sock *sk, struct hci_dev *hdev, void *data, cp->data + cp->adv_data_len); /* If using software rotation, determine next instance to use */ - if (hdev->cur_adv_instance == cp->instance) { + if (ext_adv_capable(hdev)) { + schedule_instance = cp->instance; + } else if (hdev->cur_adv_instance == cp->instance) { /* If the currently advertised instance is being changed * then cancel the current advertising and schedule the * next instance. If there is only one instance then the @@ -9573,6 +9763,8 @@ static int add_ext_adv_data(struct sock *sk, struct hci_dev *hdev, void *data, goto clear_new_instance; } + cmd->user_data = UINT_PTR(schedule_instance); + err = hci_cmd_sync_queue(hdev, add_ext_adv_data_sync, cmd, add_ext_adv_data_complete); if (err < 0) { @@ -9916,7 +10108,8 @@ void mgmt_index_removed(struct hci_dev *hdev) cancel_delayed_work_sync(&hdev->discov_off); cancel_delayed_work_sync(&hdev->service_cache); cancel_delayed_work_sync(&hdev->rpa_expired); - cancel_delayed_work_sync(&hdev->mesh_send_done); + + mesh_flush(hdev, true); } void mgmt_power_on(struct hci_dev *hdev, int err) @@ -9943,6 +10136,16 @@ void mgmt_power_on(struct hci_dev *hdev, int err) hci_dev_unlock(hdev); } +/* This function requires the caller holds hdev->lock */ +void mgmt_mesh_flush(struct hci_dev *hdev) +{ + /* The mesh work is only initialized once mgmt is used */ + if (!hci_dev_test_flag(hdev, HCI_MGMT)) + return; + + mesh_flush(hdev, false); +} + void __mgmt_power_off(struct hci_dev *hdev) { struct cmd_lookup match = { NULL, hdev }; @@ -10218,19 +10421,27 @@ bool mgmt_powering_down(struct hci_dev *hdev) { struct mgmt_pending_cmd *cmd; struct mgmt_mode *cp; + bool powering_down = false; if (hci_dev_test_flag(hdev, HCI_POWERING_DOWN)) return true; - cmd = pending_find(MGMT_OP_SET_POWERED, hdev); - if (!cmd) - return false; + mutex_lock(&hdev->mgmt_pending_lock); - cp = cmd->param; - if (!cp->val) - return true; + list_for_each_entry(cmd, &hdev->mgmt_pending, list) { + if (hci_sock_get_channel(cmd->sk) != HCI_CHANNEL_CONTROL || + cmd->opcode != MGMT_OP_SET_POWERED) + continue; - return false; + /* cmd can only be freed after it is unlinked under the lock */ + cp = cmd->param; + powering_down = !cp->val; + break; + } + + mutex_unlock(&hdev->mgmt_pending_lock); + + return powering_down; } u8 hci_to_mgmt_reason(u8 err) diff --git a/net/bluetooth/mgmt_config.c b/net/bluetooth/mgmt_config.c index fdcc752c6f13f6..834220072450fd 100644 --- a/net/bluetooth/mgmt_config.c +++ b/net/bluetooth/mgmt_config.c @@ -224,6 +224,14 @@ int set_def_system_config(struct sock *sk, struct hci_dev *hdev, void *data, MGMT_STATUS_INVALID_PARAMS); } + /* A zero rotation duration would make the advertising instance + * scheduler requeue itself with no delay. + */ + if (type == 0x000c && !TLV_GET_LE16(buffer)) + return mgmt_cmd_status(sk, hdev->id, + MGMT_OP_SET_DEF_SYSTEM_CONFIG, + MGMT_STATUS_INVALID_PARAMS); + buffer_left -= exp_len; buffer += exp_len; } @@ -362,6 +370,6 @@ int set_def_runtime_config(struct sock *sk, struct hci_dev *hdev, void *data, { bt_dev_dbg(hdev, "sock %p", sk); - return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_DEF_SYSTEM_CONFIG, + return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_DEF_RUNTIME_CONFIG, MGMT_STATUS_INVALID_PARAMS); } diff --git a/net/bluetooth/mgmt_util.c b/net/bluetooth/mgmt_util.c index 6ea107c0e05433..d502e6b933e811 100644 --- a/net/bluetooth/mgmt_util.c +++ b/net/bluetooth/mgmt_util.c @@ -409,16 +409,31 @@ struct mgmt_mesh_tx *mgmt_mesh_add(struct sock *sk, struct hci_dev *hdev, void *data, u16 len) { struct mgmt_mesh_tx *mesh_tx; + u8 handle = hdev->mesh_send_ref; + int i; + + /* The handle is all that identifies a transmission, so it must not be + * in use by one still pending when the counter wraps around. + */ + for (i = 0; i < 255; i++) { + handle++; + if (!handle) + handle++; + + if (!mgmt_mesh_find(hdev, handle)) + break; + } + + if (i == 255) + return NULL; mesh_tx = kzalloc_obj(*mesh_tx); if (!mesh_tx) return NULL; - hdev->mesh_send_ref++; - if (!hdev->mesh_send_ref) - hdev->mesh_send_ref++; + hdev->mesh_send_ref = handle; - mesh_tx->handle = hdev->mesh_send_ref; + mesh_tx->handle = handle; mesh_tx->index = hdev->id; memcpy(mesh_tx->param, data, len); mesh_tx->param_len = len; diff --git a/net/bluetooth/msft.c b/net/bluetooth/msft.c index 2559c5b1bef020..db7b40ab5fc164 100644 --- a/net/bluetooth/msft.c +++ b/net/bluetooth/msft.c @@ -170,11 +170,16 @@ static bool read_supported_features(struct hci_dev *hdev, goto failed; } + /* The event prefix is used by msft_vendor_evt() with hdev->lock held */ + hci_dev_lock(hdev); + if (rp->evt_prefix_len > 0) { msft->evt_prefix = kmemdup(rp->evt_prefix, rp->evt_prefix_len, GFP_KERNEL); - if (!msft->evt_prefix) + if (!msft->evt_prefix) { + hci_dev_unlock(hdev); goto failed; + } } msft->evt_prefix_len = rp->evt_prefix_len; @@ -183,6 +188,8 @@ static bool read_supported_features(struct hci_dev *hdev, if (msft->features & MSFT_FEATURE_MASK_CURVE_VALIDITY) hdev->msft_curve_validity = true; + hci_dev_unlock(hdev); + kfree_skb(skb); return true; @@ -290,6 +297,10 @@ static int msft_le_monitor_advertisement_cb(struct hci_dev *hdev, u16 opcode, handle_data->mgmt_handle = monitor->handle; handle_data->msft_handle = rp->handle; handle_data->cond_type = MSFT_MONITOR_ADVERTISEMENT_TYPE_PATTERN; + handle_data->rssi_high = monitor->rssi.high_threshold; + handle_data->rssi_low = monitor->rssi.low_threshold; + handle_data->rssi_low_interval = (u8)monitor->rssi.low_threshold_timeout; + handle_data->rssi_sampling_period = monitor->rssi.sampling_period; INIT_LIST_HEAD(&handle_data->list); list_add(&handle_data->list, &msft->handle_map); @@ -431,23 +442,54 @@ static int msft_remove_monitor_sync(struct hci_dev *hdev, struct msft_cp_le_cancel_monitor_advertisement cp; struct msft_monitor_advertisement_handle_data *handle_data; struct sk_buff *skb; + int err; + hci_dev_lock(hdev); handle_data = msft_find_handle_data(hdev, monitor->handle, true); + if (handle_data) + cp.handle = handle_data->msft_handle; + hci_dev_unlock(hdev); /* If no matched handle, just remove without telling controller */ if (!handle_data) return -ENOENT; cp.sub_opcode = MSFT_OP_LE_CANCEL_MONITOR_ADVERTISEMENT; - cp.handle = handle_data->msft_handle; skb = __hci_cmd_sync(hdev, hdev->msft_opcode, sizeof(cp), &cp, HCI_CMD_TIMEOUT); if (IS_ERR(skb)) return PTR_ERR(skb); - return msft_le_cancel_monitor_advertisement_cb(hdev, hdev->msft_opcode, - monitor, skb); + err = msft_le_cancel_monitor_advertisement_cb(hdev, hdev->msft_opcode, + monitor, skb); + kfree_skb(skb); + + return err; +} + +/* Keep the advertisement filter enabled only while at least one monitor is + * offloaded to the controller. With the filter enabled and no monitors, some + * controllers (e.g. MediaTek MT7922) drop every advertisement, which breaks + * LE discovery and passive scanning entirely. + * + * This function requires the caller holds hci_req_sync_lock + */ +static void msft_update_filter_enable(struct hci_dev *hdev) +{ + struct msft_data *msft = hdev->msft_data; + bool enable, update; + + if (!msft) + return; + + hci_dev_lock(hdev); + enable = !list_empty(&msft->handle_map); + update = enable != msft->filter_enabled; + hci_dev_unlock(hdev); + + if (update) + msft_set_filter_enable(hdev, enable); } /* This function requires the caller holds hci_req_sync_lock */ @@ -475,6 +517,8 @@ int msft_suspend_sync(struct hci_dev *hdev) /* All monitors have been removed */ msft->suspending = false; + msft_update_filter_enable(hdev); + return 0; } @@ -512,7 +556,6 @@ static int msft_add_monitor_sync(struct hci_dev *hdev, { struct msft_cp_le_monitor_advertisement *cp; struct msft_le_monitor_advertisement_pattern_data *pattern_data; - struct msft_monitor_advertisement_handle_data *handle_data; struct msft_le_monitor_advertisement_pattern *pattern; struct adv_pattern *entry; size_t total_size = sizeof(*cp) + sizeof(*pattern_data); @@ -564,19 +607,7 @@ static int msft_add_monitor_sync(struct hci_dev *hdev, err = msft_le_monitor_advertisement_cb(hdev, hdev->msft_opcode, monitor, skb); - if (err) - goto out_free; - - handle_data = msft_find_handle_data(hdev, monitor->handle, true); - if (!handle_data) { - err = -ENODATA; - goto out_free; - } - - handle_data->rssi_high = cp->rssi_high; - handle_data->rssi_low = cp->rssi_low; - handle_data->rssi_low_interval = cp->rssi_low_interval; - handle_data->rssi_sampling_period = cp->rssi_sampling_period; + kfree_skb(skb); out_free: kfree(cp); @@ -628,6 +659,7 @@ int msft_resume_sync(struct hci_dev *hdev) hci_dev_unlock(hdev); reregister_monitor(hdev); + msft_update_filter_enable(hdev); return 0; } @@ -648,10 +680,12 @@ void msft_do_open(struct hci_dev *hdev) bt_dev_dbg(hdev, "Initialize MSFT extension"); /* Reset existing MSFT data before re-reading */ + hci_dev_lock(hdev); kfree(msft->evt_prefix); msft->evt_prefix = NULL; msft->evt_prefix_len = 0; msft->features = 0; + hci_dev_unlock(hdev); if (!read_supported_features(hdev, msft)) { hci_dev_lock(hdev); @@ -663,11 +697,11 @@ void msft_do_open(struct hci_dev *hdev) if (msft_monitor_supported(hdev)) { msft->resuming = true; - msft_set_filter_enable(hdev, true); /* Monitors get removed on power off, so we need to explicitly * tell the controller to re-monitor. */ reregister_monitor(hdev); + msft_update_filter_enable(hdev); } } @@ -699,6 +733,11 @@ void msft_do_close(struct hci_dev *hdev) kfree(handle_data); } + /* The advertisement filter is back to its default, disabled state + * after power off as well. + */ + msft->filter_enabled = false; + hci_dev_unlock(hdev); mutex_lock(&msft->filter_lock); @@ -1078,12 +1117,15 @@ static void msft_monitor_device_evt(struct hci_dev *hdev, struct sk_buff *skb) void msft_vendor_evt(struct hci_dev *hdev, void *data, struct sk_buff *skb) { - struct msft_data *msft = hdev->msft_data; + struct msft_data *msft; u8 *evt_prefix; u8 *evt; + hci_dev_lock(hdev); + + msft = hdev->msft_data; if (!msft) - return; + goto unlock; /* When the extension has defined an event prefix, check that it * matches, and otherwise just return. @@ -1091,23 +1133,21 @@ void msft_vendor_evt(struct hci_dev *hdev, void *data, struct sk_buff *skb) if (msft->evt_prefix_len > 0) { evt_prefix = msft_skb_pull(hdev, skb, 0, msft->evt_prefix_len); if (!evt_prefix) - return; + goto unlock; if (memcmp(evt_prefix, msft->evt_prefix, msft->evt_prefix_len)) - return; + goto unlock; } /* Every event starts at least with an event code and the rest of * the data is variable and depends on the event code. */ if (skb->len < 1) - return; + goto unlock; evt = msft_skb_pull(hdev, skb, 0, sizeof(*evt)); if (!evt) - return; - - hci_dev_lock(hdev); + goto unlock; switch (*evt) { case MSFT_EV_LE_MONITOR_DEVICE: @@ -1121,6 +1161,7 @@ void msft_vendor_evt(struct hci_dev *hdev, void *data, struct sk_buff *skb) break; } +unlock: hci_dev_unlock(hdev); } @@ -1133,26 +1174,27 @@ __u64 msft_get_features(struct hci_dev *hdev) static void msft_le_set_advertisement_filter_enable_cb(struct hci_dev *hdev, void *user_data, - u8 status) + int err) { struct msft_cp_le_set_advertisement_filter_enable *cp = user_data; struct msft_data *msft = hdev->msft_data; - /* Error 0x0C would be returned if the filter enabled status is + /* Error 0x0C (Command Disallowed), which __hci_cmd_sync_status() + * reports as -EBUSY, would be returned if the filter enabled status is * already set to whatever we were trying to set. * Although the default state should be disabled, some controller set * the initial value to enabled. Because there is no way to know the * actual initial value before sending this command, here we also treat * error 0x0C as success. */ - if (status != 0x00 && status != 0x0C) + if (err && err != -EBUSY) return; hci_dev_lock(hdev); msft->filter_enabled = cp->enable; - if (status == 0x0C) + if (err == -EBUSY) bt_dev_warn(hdev, "MSFT filter_enable is already %s", cp->enable ? "on" : "off"); @@ -1163,6 +1205,7 @@ static void msft_le_set_advertisement_filter_enable_cb(struct hci_dev *hdev, int msft_add_monitor_pattern(struct hci_dev *hdev, struct adv_monitor *monitor) { struct msft_data *msft = hdev->msft_data; + int err; if (!msft) return -EOPNOTSUPP; @@ -1170,13 +1213,17 @@ int msft_add_monitor_pattern(struct hci_dev *hdev, struct adv_monitor *monitor) if (msft->resuming || msft->suspending) return -EBUSY; - return msft_add_monitor_sync(hdev, monitor); + err = msft_add_monitor_sync(hdev, monitor); + msft_update_filter_enable(hdev); + + return err; } /* This function requires the caller holds hci_req_sync_lock */ int msft_remove_monitor(struct hci_dev *hdev, struct adv_monitor *monitor) { struct msft_data *msft = hdev->msft_data; + int err; if (!msft) return -EOPNOTSUPP; @@ -1184,7 +1231,10 @@ int msft_remove_monitor(struct hci_dev *hdev, struct adv_monitor *monitor) if (msft->resuming || msft->suspending) return -EBUSY; - return msft_remove_monitor_sync(hdev, monitor); + err = msft_remove_monitor_sync(hdev, monitor); + msft_update_filter_enable(hdev); + + return err; } int msft_set_filter_enable(struct hci_dev *hdev, bool enable) @@ -1203,7 +1253,7 @@ int msft_set_filter_enable(struct hci_dev *hdev, bool enable) msft_le_set_advertisement_filter_enable_cb(hdev, &cp, err); - return 0; + return err == -EBUSY ? 0 : err; } bool msft_curve_validity(struct hci_dev *hdev) diff --git a/net/bluetooth/smp.c b/net/bluetooth/smp.c index b7015e37e1f1cc..2538096cae0601 100644 --- a/net/bluetooth/smp.c +++ b/net/bluetooth/smp.c @@ -1092,8 +1092,13 @@ static void smp_notify_keys(struct l2cap_conn *conn) else type = HCI_LK_UNAUTH_COMBINATION_P256; - key = hci_add_link_key(hdev, smp->conn->hcon, &hcon->dst, - smp->link_key, type, 0, &persistent); + /* hdev->lock can't be taken here since it is ordered before + * the l2cap channel lock held by the caller. + */ + mutex_lock(&hdev->link_keys_lock); + + key = __hci_add_link_key(hdev, smp->conn->hcon, &hcon->dst, + smp->link_key, type, 0, &persistent); if (key) { mgmt_new_link_key(hdev, key, persistent); @@ -1106,6 +1111,8 @@ static void smp_notify_keys(struct l2cap_conn *conn) kfree_rcu(key, rcu); } } + + mutex_unlock(&hdev->link_keys_lock); } } @@ -1754,7 +1761,8 @@ static u8 smp_cmd_pairing_req(struct l2cap_conn *conn, struct sk_buff *skb) * successfully received our local OOB data - therefore set the * flag to indicate that local OOB is in use. */ - if (req->oob_flag == SMP_OOB_PRESENT && SMP_DEV(hdev)->local_oob) + if (req->oob_flag == SMP_OOB_PRESENT && hdev->smp_data && + SMP_DEV(hdev)->local_oob) set_bit(SMP_FLAG_LOCAL_OOB, &smp->flags); /* SMP over BR/EDR requires special treatment */ @@ -1898,6 +1906,16 @@ static u8 sc_send_public_key(struct smp_chan *smp) } done: + /* Check if remote and local public keys are the same and debug key is + * not in use. + */ + if (!test_bit(SMP_FLAG_DEBUG_KEY, &smp->flags) && + !test_bit(SMP_FLAG_INITIATOR, &smp->flags) && + !crypto_memneq(smp->remote_pk, smp->local_pk, 32)) { + bt_dev_err(hdev, "Remote and local public keys are identical"); + return SMP_DHKEY_CHECK_FAILED; + } + SMP_DBG("Local Public Key X: %32phN", smp->local_pk); SMP_DBG("Local Public Key Y: %32phN", smp->local_pk + 32); @@ -1940,7 +1958,8 @@ static u8 smp_cmd_pairing_rsp(struct l2cap_conn *conn, struct sk_buff *skb) * successfully received our local OOB data - therefore set the * flag to indicate that local OOB is in use. */ - if (rsp->oob_flag == SMP_OOB_PRESENT && SMP_DEV(hdev)->local_oob) + if (rsp->oob_flag == SMP_OOB_PRESENT && hdev->smp_data && + SMP_DEV(hdev)->local_oob) set_bit(SMP_FLAG_LOCAL_OOB, &smp->flags); smp->prsp[0] = SMP_CMD_PAIRING_RSP; @@ -2749,7 +2768,8 @@ static int smp_cmd_public_key(struct l2cap_conn *conn, struct sk_buff *skb) * not in use. */ if (!test_bit(SMP_FLAG_DEBUG_KEY, &smp->flags) && - !crypto_memneq(key, smp->local_pk, 64)) { + test_bit(SMP_FLAG_INITIATOR, &smp->flags) && + !crypto_memneq(key, smp->local_pk, 32)) { bt_dev_err(hdev, "Remote and local public keys are identical"); return SMP_DHKEY_CHECK_FAILED; } @@ -3358,28 +3378,49 @@ static void smp_del_chan(struct l2cap_chan *chan) int smp_force_bredr(struct hci_dev *hdev, bool enable) { - if (enable == hci_dev_test_flag(hdev, HCI_FORCE_BREDR_SMP)) - return -EALREADY; + int err = 0; + + hci_dev_lock(hdev); + if (enable == hci_dev_test_flag(hdev, HCI_FORCE_BREDR_SMP)) { + err = -EALREADY; + goto unlock; + } + + /* The channels are only registered while the controller is powered + * and LE capable. Otherwise just record the flag, smp_register() will + * create the BR/EDR channel on the next power on. + */ if (enable) { struct l2cap_chan *chan; - chan = smp_add_cid(hdev, L2CAP_CID_SMP_BREDR); - if (IS_ERR(chan)) - return PTR_ERR(chan); + if (hdev->smp_data && !hdev->smp_bredr_data) { + chan = smp_add_cid(hdev, L2CAP_CID_SMP_BREDR); + if (IS_ERR(chan)) { + err = PTR_ERR(chan); + goto unlock; + } - hdev->smp_bredr_data = chan; + hdev->smp_bredr_data = chan; + } } else { struct l2cap_chan *chan; chan = hdev->smp_bredr_data; - hdev->smp_bredr_data = NULL; - smp_del_chan(chan); + if (chan) { + hdev->smp_bredr_data = NULL; + smp_del_chan(chan); + } } - hci_dev_change_flag(hdev, HCI_FORCE_BREDR_SMP); + if (enable) + hci_dev_set_flag(hdev, HCI_FORCE_BREDR_SMP); + else + hci_dev_clear_flag(hdev, HCI_FORCE_BREDR_SMP); - return 0; +unlock: + hci_dev_unlock(hdev); + return err; } int smp_register(struct hci_dev *hdev) diff --git a/net/bpf/bpf_dummy_struct_ops.c b/net/bpf/bpf_dummy_struct_ops.c index 191a6b3ee25415..c724a6bc7b807b 100644 --- a/net/bpf/bpf_dummy_struct_ops.c +++ b/net/bpf/bpf_dummy_struct_ops.c @@ -179,7 +179,7 @@ int bpf_struct_ops_test_run(struct bpf_prog *prog, const union bpf_attr *kattr, &st_ops->func_models[op_idx], &dummy_ops_test_ret_function, &image, &image_off, - true); + true, NULL); if (err < 0) goto out; diff --git a/net/bridge/br_input.c b/net/bridge/br_input.c index fc2e381c4fe039..b5bd9d6808fd97 100644 --- a/net/bridge/br_input.c +++ b/net/bridge/br_input.c @@ -257,13 +257,18 @@ static void __br_handle_local_finish(struct sk_buff *skb) br_fdb_update(p->br, p, vlan, eth_hdr(skb)->h_source, 0); } -/* note: already called with rcu_read_lock */ +/* okfn of the link-local NF_BR_LOCAL_IN hook in br_handle_frame(). It is + * only called when a queued frame is reinjected, after br_handle_frame() + * returned RX_HANDLER_CONSUMED for it, so the frame can no longer be + * passed up on the port and has to be freed here. + * note: already called with rcu_read_lock + */ static int br_handle_local_finish(struct net *net, struct sock *sk, struct sk_buff *skb) { __br_handle_local_finish(skb); + kfree_skb(skb); - /* return 1 to signal the okfn() was called so it's ok to use the skb */ - return 1; + return 0; } static int nf_hook_bridge_pre(struct sk_buff *skb, struct sk_buff **pskb) @@ -424,11 +429,14 @@ static rx_handler_result_t br_handle_frame(struct sk_buff **pskb) /* The else clause should be hit when nf_hook(): * - returns < 0 (drop/error) * - returns = 0 (stolen/nf_queue) - * Thus return 1 from the okfn() to signal the skb is ok to pass + * On 1 the frame is passed on here. The okfn() only runs if a + * queued frame is reinjected later, and must consume it then. */ - if (NF_HOOK(NFPROTO_BRIDGE, NF_BR_LOCAL_IN, + if (nf_hook(NFPROTO_BRIDGE, NF_BR_LOCAL_IN, dev_net(skb->dev), NULL, skb, skb->dev, NULL, br_handle_local_finish) == 1) { + *pskb = skb; + __br_handle_local_finish(skb); return RX_HANDLER_PASS; } else { return RX_HANDLER_CONSUMED; diff --git a/net/can/bcm.c b/net/can/bcm.c index 7bd2aa39777af4..dc9e2890490acc 100644 --- a/net/can/bcm.c +++ b/net/can/bcm.c @@ -145,6 +145,7 @@ struct bcm_sock { unsigned long dropped_usr_msgs; struct proc_dir_entry *bcm_proc_read; char procname [32]; /* inode number in decimal with \0 */ + struct mutex conf_lock; /* protects bind and the bcm_op lists */ }; static LIST_HEAD(bcm_notifier_list); @@ -219,11 +220,16 @@ static int bcm_proc_show(struct seq_file *m, void *v) struct net *net = m->private; struct sock *sk = (struct sock *)pde_data(m->file->f_inode); struct bcm_sock *bo = bcm_sk(sk); + int ifindex = READ_ONCE(bo->ifindex); struct bcm_op *op; seq_printf(m, ">>> sock inode %s", bo->procname); seq_printf(m, " / dropped %lu", bo->dropped_usr_msgs); - seq_printf(m, " / bound %s", bcm_proc_getifname(net, ifname, bo->ifindex)); + if (READ_ONCE(bo->bound)) + seq_printf(m, " / bound %s", + bcm_proc_getifname(net, ifname, ifindex)); + else + seq_puts(m, " / unbound"); seq_printf(m, " <<<\n"); rcu_read_lock(); @@ -1643,6 +1649,11 @@ static int bcm_sendmsg(struct socket *sock, struct msghdr *msg, size_t size) struct bcm_sock *bo = bcm_sk(sk); int ifindex; struct bcm_msg_head msg_head; + struct msghdr fmsg = {}; /* CAN frames copied to kernel memory */ + struct kvec kv; + struct canfd_frame sframe; /* stack buffer for up to CANFD_MTU bytes */ + void *frames = &sframe; + size_t flen = 0; int cfsiz; int ret; /* read bytes or error codes as return value */ @@ -1663,12 +1674,53 @@ static int bcm_sendmsg(struct socket *sock, struct msghdr *msg, size_t size) if ((size - MHSIZ) % cfsiz) return -EINVAL; - lock_sock(sk); + /* Copy the CAN frames from user space before taking bo->conf_lock, so a + * stalled copy can not block bcm_notify() waiting for bo->conf_lock + * under RTNL. Only the frames the opcode handler reads are copied. + * The handlers keep their checks and read the frames from fmsg. + */ + switch (msg_head.opcode) { + case TX_SETUP: + if (msg_head.nframes >= 1 && msg_head.nframes <= MAX_NFRAMES) + flen = msg_head.nframes * cfsiz; + break; + + case RX_SETUP: + if (!(msg_head.flags & RX_FILTER_ID) && + msg_head.nframes <= MAX_NFRAMES + 1) + flen = msg_head.nframes * cfsiz; + break; + + case TX_SEND: + if (msg_head.nframes == 1 && size == cfsiz + MHSIZ) + flen = cfsiz; + break; + } + + /* a message with missing frames still fails in the handler */ + flen = min(flen, msg_data_left(msg)); - /* Re-validate under the socket lock: a concurrent bcm_notify() + if (flen > sizeof(sframe)) { + frames = kvmalloc(flen, GFP_KERNEL); + if (!frames) + return -ENOMEM; + } + + if (!copy_from_iter_full(frames, flen, &msg->msg_iter)) { + ret = -EFAULT; + goto out_free; + } + + kv.iov_base = frames; + kv.iov_len = flen; + iov_iter_kvec(&fmsg.msg_iter, ITER_SOURCE, &kv, 1, flen); + + mutex_lock(&bo->conf_lock); + + /* Re-validate under bo->conf_lock: a concurrent bcm_notify() * may have unbound this socket (device removal) after the * lockless fast-path check above. bo->ifindex is only ever - * mutated under lock_sock(), so reading it here - instead of + * mutated under bo->conf_lock, so reading it here - instead of * before taking the lock - guarantees it can't be observed * torn against bo->bound. */ @@ -1721,11 +1773,11 @@ static int bcm_sendmsg(struct socket *sock, struct msghdr *msg, size_t size) switch (msg_head.opcode) { case TX_SETUP: - ret = bcm_tx_setup(&msg_head, msg, ifindex, sk); + ret = bcm_tx_setup(&msg_head, &fmsg, ifindex, sk); break; case RX_SETUP: - ret = bcm_rx_setup(&msg_head, msg, ifindex, sk); + ret = bcm_rx_setup(&msg_head, &fmsg, ifindex, sk); break; case TX_DELETE: @@ -1759,7 +1811,7 @@ static int bcm_sendmsg(struct socket *sock, struct msghdr *msg, size_t size) if ((msg_head.nframes != 1) || (size != cfsiz + MHSIZ)) ret = -EINVAL; else - ret = bcm_tx_send(msg, ifindex, sk, cfsiz); + ret = bcm_tx_send(&fmsg, ifindex, sk, cfsiz); break; default: @@ -1768,7 +1820,10 @@ static int bcm_sendmsg(struct socket *sock, struct msghdr *msg, size_t size) } out_release: - release_sock(sk); + mutex_unlock(&bo->conf_lock); +out_free: + if (frames != &sframe) + kvfree(frames); return ret; } @@ -1789,7 +1844,7 @@ static void bcm_notify(struct bcm_sock *bo, unsigned long msg, switch (msg) { case NETDEV_UNREGISTER: - lock_sock(sk); + mutex_lock(&bo->conf_lock); /* rx_ops: remove device specific receive entries */ list_for_each_entry(op, &bo->rx_ops, list) { @@ -1817,23 +1872,13 @@ static void bcm_notify(struct bcm_sock *bo, unsigned long msg, /* remove device reference, if this is our bound device */ if (bo->bound && bo->ifindex == dev->ifindex) { -#if IS_ENABLED(CONFIG_PROC_FS) - if (sock_net(sk)->can.bcmproc_dir && bo->bcm_proc_read) { - remove_proc_entry(bo->procname, sock_net(sk)->can.bcmproc_dir); - bo->bcm_proc_read = NULL; - } -#endif - /* Paired with the lockless fast-path check in - * bcm_sendmsg(); bo->ifindex itself is only ever - * accessed under lock_sock() so it needs no - * annotation. - */ + /* pairs with the lockless check in bcm_sendmsg() */ WRITE_ONCE(bo->bound, 0); - bo->ifindex = 0; + WRITE_ONCE(bo->ifindex, 0); notify_enodev = 1; } - release_sock(sk); + mutex_unlock(&bo->conf_lock); if (notify_enodev) { sk->sk_err = ENODEV; @@ -1843,7 +1888,8 @@ static void bcm_notify(struct bcm_sock *bo, unsigned long msg, break; case NETDEV_DOWN: - if (bo->bound && bo->ifindex == dev->ifindex) { + if (READ_ONCE(bo->bound) && + READ_ONCE(bo->ifindex) == dev->ifindex) { sk->sk_err = ENETDOWN; if (!sock_flag(sk, SOCK_DEAD)) sk_error_report(sk); @@ -1885,6 +1931,7 @@ static int bcm_init(struct sock *sk) bo->ifindex = 0; bo->dropped_usr_msgs = 0; bo->bcm_proc_read = NULL; + mutex_init(&bo->conf_lock); INIT_LIST_HEAD(&bo->tx_ops); INIT_LIST_HEAD(&bo->rx_ops); @@ -1924,15 +1971,14 @@ static int bcm_release(struct socket *sock) list_del(&bo->notifier); spin_unlock(&bcm_notifier_lock); - /* bcm_notify() can not access this socket anymore */ - lock_sock(sk); - #if IS_ENABLED(CONFIG_PROC_FS) /* remove procfs entry */ if (net->can.bcmproc_dir && bo->bcm_proc_read) remove_proc_entry(bo->procname, net->can.bcmproc_dir); #endif /* CONFIG_PROC_FS */ + mutex_lock(&bo->conf_lock); + list_for_each_entry_safe(op, next, &bo->tx_ops, list) { list_del_rcu(&op->list); bcm_remove_op(op); @@ -1964,13 +2010,14 @@ static int bcm_release(struct socket *sock) /* remove device reference */ if (bo->bound) { WRITE_ONCE(bo->bound, 0); - bo->ifindex = 0; + WRITE_ONCE(bo->ifindex, 0); } + mutex_unlock(&bo->conf_lock); + sock_orphan(sk); sock->sk = NULL; - release_sock(sk); sock_prot_inuse_add(net, sk->sk_prot, -1); sock_put(sk); @@ -1989,7 +2036,7 @@ static int bcm_connect(struct socket *sock, struct sockaddr_unsized *uaddr, int if (len < BCM_MIN_NAMELEN) return -EINVAL; - lock_sock(sk); + mutex_lock(&bo->conf_lock); if (bo->bound) { ret = -EISCONN; @@ -2011,16 +2058,17 @@ static int bcm_connect(struct socket *sock, struct sockaddr_unsized *uaddr, int goto fail; } - bo->ifindex = dev->ifindex; + WRITE_ONCE(bo->ifindex, dev->ifindex); dev_put(dev); } else { /* no interface reference for ifindex = 0 ('any' CAN device) */ - bo->ifindex = 0; + WRITE_ONCE(bo->ifindex, 0); } #if IS_ENABLED(CONFIG_PROC_FS) - if (net->can.bcmproc_dir) { + /* create the procfs entry once, it is removed in bcm_release() */ + if (net->can.bcmproc_dir && !bo->bcm_proc_read) { /* use unique socket inode number as filename */ snprintf(bo->procname, sizeof(bo->procname), "%llu", sock_i_ino(sk)); @@ -2040,7 +2088,7 @@ static int bcm_connect(struct socket *sock, struct sockaddr_unsized *uaddr, int WRITE_ONCE(bo->bound, 1); fail: - release_sock(sk); + mutex_unlock(&bo->conf_lock); return ret; } diff --git a/net/can/isotp.c b/net/can/isotp.c index 7a90ba3f1cf1c4..642fec500af9df 100644 --- a/net/can/isotp.c +++ b/net/can/isotp.c @@ -182,6 +182,7 @@ struct isotp_sock { struct list_head notifier; wait_queue_head_t wait; spinlock_t rx_lock; /* protect single thread state machine */ + struct mutex conf_lock; /* protects bind and setsockopt */ }; static LIST_HEAD(isotp_notifier_list); @@ -633,6 +634,10 @@ static int isotp_rcv_ff(struct sock *sk, struct canfd_frame *cf, int ae) so->rx.sn = 1; WRITE_ONCE(so->rx.state, ISOTP_WAIT_DATA); + /* start rx timeout, isotp_send_fc() restarts it */ + hrtimer_start(&so->rxtimer, ktime_set(ISOTP_FC_TIMEOUT, 0), + HRTIMER_MODE_REL_SOFT); + /* no creation of flow control frames */ if (so->opt.flags & CAN_ISOTP_LISTEN_MODE) return 0; @@ -649,6 +654,17 @@ static int isotp_rcv_cf(struct sock *sk, struct canfd_frame *cf, int ae, struct sk_buff *nskb; int i; + /* CFs are never longer than the FF */ + if (cf->len > so->rx.ll_dl) + return 1; + + /* CFs have usually the LL_DL length */ + if (cf->len < so->rx.ll_dl) { + /* this is only allowed for the last CF */ + if (so->rx.len - so->rx.idx > so->rx.ll_dl - ae - N_PCI_SZ) + return 1; + } + if (READ_ONCE(so->rx.state) != ISOTP_WAIT_DATA) return 0; @@ -661,6 +677,7 @@ static int isotp_rcv_cf(struct sock *sk, struct canfd_frame *cf, int ae, so->lastrxcf_tstamp = skb->tstamp; } + /* stop the rx timeout only for valid CFs (checked above) */ hrtimer_cancel(&so->rxtimer); /* isotp_rx_timer_handler() may have raced us for so->rx.state @@ -669,17 +686,6 @@ static int isotp_rcv_cf(struct sock *sk, struct canfd_frame *cf, int ae, if (READ_ONCE(so->rx.state) != ISOTP_WAIT_DATA) return 1; - /* CFs are never longer than the FF */ - if (cf->len > so->rx.ll_dl) - return 1; - - /* CFs have usually the LL_DL length */ - if (cf->len < so->rx.ll_dl) { - /* this is only allowed for the last CF */ - if (so->rx.len - so->rx.idx > so->rx.ll_dl - ae - N_PCI_SZ) - return 1; - } - if ((cf->data[ae] & 0x0F) != so->rx.sn) { /* wrong sn detected - report 'illegal byte sequence' */ sk->sk_err = EILSEQ; @@ -725,13 +731,13 @@ static int isotp_rcv_cf(struct sock *sk, struct canfd_frame *cf, int ae, return 0; } + /* start rx timeout, isotp_send_fc() restarts it */ + hrtimer_start(&so->rxtimer, ktime_set(ISOTP_FC_TIMEOUT, 0), + HRTIMER_MODE_REL_SOFT); + /* perform blocksize handling, if enabled */ - if (!so->rxfc.bs || ++so->rx.bs < so->rxfc.bs) { - /* start rx timeout watchdog */ - hrtimer_start(&so->rxtimer, ktime_set(ISOTP_FC_TIMEOUT, 0), - HRTIMER_MODE_REL_SOFT); + if (!so->rxfc.bs || ++so->rx.bs < so->rxfc.bs) return 0; - } /* no creation of flow control frames */ if (so->opt.flags & CAN_ISOTP_LISTEN_MODE) @@ -1122,8 +1128,8 @@ static int isotp_sendmsg(struct socket *sock, struct msghdr *msg, size_t size) struct can_skb_ext *csx; struct net_device *dev; struct canfd_frame *cf; - int ae = (so->opt.flags & CAN_ISOTP_EXTEND_ADDR) ? 1 : 0; - int wait_tx_done = (so->opt.flags & CAN_ISOTP_WAIT_TX_DONE) ? 1 : 0; + int ae; + int wait_tx_done; s64 hrtimer_sec = ISOTP_ECHO_TIMEOUT; struct hrtimer *tx_hrt = &so->echotimer; u32 new_state = ISOTP_SENDING; @@ -1182,6 +1188,10 @@ static int isotp_sendmsg(struct socket *sock, struct msghdr *msg, size_t size) goto err_out_drop; } + /* read the options after the claim of the transfer */ + ae = (so->opt.flags & CAN_ISOTP_EXTEND_ADDR) ? 1 : 0; + wait_tx_done = (so->opt.flags & CAN_ISOTP_WAIT_TX_DONE) ? 1 : 0; + /* PDU size > default => try max_pdu_size */ if (size > so->tx.buflen && so->tx.buflen < max_pdu_size) { u8 *newbuf = kmalloc(max_pdu_size, GFP_KERNEL); @@ -1497,7 +1507,7 @@ static int isotp_release(struct socket *sock) list_del(&so->notifier); spin_unlock(&isotp_notifier_lock); - lock_sock(sk); + mutex_lock(&so->conf_lock); /* remove current filters & unregister * the tracked reference so->dev keeps the device's receive lists @@ -1519,6 +1529,8 @@ static int isotp_release(struct socket *sock) WRITE_ONCE(so->bound, 0); so->dev = NULL; + mutex_unlock(&so->conf_lock); + /* Always wait for a grace period before touching the timers below. * A concurrent NETDEV_UNREGISTER may have already unregistered our * filters and cleared so->bound in isotp_notify() without waiting @@ -1535,7 +1547,6 @@ static int isotp_release(struct socket *sock) sock_orphan(sk); sock->sk = NULL; - release_sock(sk); sock_prot_inuse_add(net, sk->sk_prot, -1); sock_put(sk); @@ -1585,8 +1596,8 @@ static int isotp_bind(struct socket *sock, struct sockaddr_unsized *uaddr, int l if (!addr->can_ifindex) return -ENODEV; - /* lock_sock() serializes the binding with isotp_notify() */ - lock_sock(sk); + /* so->conf_lock serializes the binding with isotp_notify() */ + mutex_lock(&so->conf_lock); if (so->bound) { err = -EINVAL; @@ -1596,7 +1607,7 @@ static int isotp_bind(struct socket *sock, struct sockaddr_unsized *uaddr, int l /* A transmission or reception that outlived a previous binding * (unbound by NETDEV_UNREGISTER) may still be draining; the FC/echo * and RX watchdog timers bound how long this takes. Checked together - * with so->bound in the same lock_sock() section above, so there is + * with so->bound in the same so->conf_lock section above, so there is * no window in which a concurrent isotp_notify() could be missed. */ if (READ_ONCE(so->tx.state) != ISOTP_IDLE || @@ -1686,7 +1697,7 @@ static int isotp_bind(struct socket *sock, struct sockaddr_unsized *uaddr, int l sk_error_report(sk); } - release_sock(sk); + mutex_unlock(&so->conf_lock); return err; } @@ -1719,6 +1730,14 @@ static int isotp_setsockopt_locked(struct socket *sock, int optname, if (so->bound) return -EISCONN; + /* A transmission or reception that outlived a previous binding + * (unbound by NETDEV_UNREGISTER) may still be draining and uses the + * socket options, see isotp_bind(). + */ + if (READ_ONCE(so->tx.state) != ISOTP_IDLE || + READ_ONCE(so->rx.state) != ISOTP_IDLE) + return -EAGAIN; + switch (optname) { case CAN_ISOTP_OPTS: memcpy(&so->opt, val, sizeof(so->opt)); @@ -1790,6 +1809,7 @@ static int isotp_setsockopt(struct socket *sock, int level, int optname, { struct sock *sk = sock->sk; + struct isotp_sock *so = isotp_sk(sk); union { struct can_isotp_options opt; struct can_isotp_fc_options rxfc; @@ -1802,7 +1822,7 @@ static int isotp_setsockopt(struct socket *sock, int level, int optname, if (level != SOL_CAN_ISOTP) return -EINVAL; - /* copy the option values from user space before lock_sock() */ + /* copy the option values from user space before taking so->conf_lock */ switch (optname) { case CAN_ISOTP_OPTS: size = sizeof(val.opt); @@ -1831,9 +1851,9 @@ static int isotp_setsockopt(struct socket *sock, int level, int optname, if (copy_from_sockptr(&val, optval, size)) return -EFAULT; - lock_sock(sk); + mutex_lock(&so->conf_lock); ret = isotp_setsockopt_locked(sock, optname, &val); - release_sock(sk); + mutex_unlock(&so->conf_lock); return ret; } @@ -1906,9 +1926,9 @@ static void isotp_notify(struct isotp_sock *so, unsigned long msg, switch (msg) { case NETDEV_UNREGISTER: - lock_sock(sk); + mutex_lock(&so->conf_lock); if (so->dev != dev) { - release_sock(sk); + mutex_unlock(&so->conf_lock); break; } @@ -1932,7 +1952,7 @@ static void isotp_notify(struct isotp_sock *so, unsigned long msg, sk->sk_err = ENODEV; if (!sock_flag(sk, SOCK_DEAD)) sk_error_report(sk); - release_sock(sk); + mutex_unlock(&so->conf_lock); break; case NETDEV_DOWN: @@ -1991,6 +2011,7 @@ static int isotp_init(struct sock *sk) so->ifindex = 0; so->bound = 0; so->dev = NULL; + mutex_init(&so->conf_lock); so->opt.flags = CAN_ISOTP_DEFAULT_FLAGS; so->opt.ext_address = CAN_ISOTP_DEFAULT_EXT_ADDRESS; diff --git a/net/can/raw.c b/net/can/raw.c index f14270b56f5219..b69eaadc5e93ae 100644 --- a/net/can/raw.c +++ b/net/can/raw.c @@ -103,6 +103,7 @@ struct raw_sock { struct can_filter dfilter; /* default/single filter */ struct can_filter *filter; /* pointer to filter(s) */ struct uniqframe __percpu *uniq; + struct mutex conf_lock; /* protects bind, filters and setsockopt */ }; static LIST_HEAD(raw_notifier_list); @@ -319,7 +320,7 @@ static void raw_notify(struct raw_sock *ro, unsigned long msg, /* Lockless fast path, ro->bind_dev covers a concurrent bind(). * Read it before ro->dev, pairs with smp_store_release() in - * raw_bind(). A stale ro->bind_dev only costs a lock_sock(). + * raw_bind(). A stale ro->bind_dev only costs a mutex_lock(). */ bind_dev = smp_load_acquire(&ro->bind_dev); if (READ_ONCE(ro->dev) != dev && @@ -328,9 +329,9 @@ static void raw_notify(struct raw_sock *ro, unsigned long msg, switch (msg) { case NETDEV_UNREGISTER: - lock_sock(sk); + mutex_lock(&ro->conf_lock); if (ro->dev != dev) { - release_sock(sk); + mutex_unlock(&ro->conf_lock); break; } @@ -351,7 +352,7 @@ static void raw_notify(struct raw_sock *ro, unsigned long msg, sk->sk_err = ENODEV; if (!sock_flag(sk, SOCK_DEAD)) sk_error_report(sk); - release_sock(sk); + mutex_unlock(&ro->conf_lock); break; case NETDEV_DOWN: @@ -401,6 +402,7 @@ static int raw_init(struct sock *sk) ro->ifindex = 0; ro->dev = NULL; ro->bind_dev = NULL; + mutex_init(&ro->conf_lock); /* set default filter to single entry dfilter */ ro->dfilter.can_id = 0; @@ -451,7 +453,7 @@ static int raw_release(struct socket *sock) list_del(&ro->notifier); spin_unlock(&raw_notifier_lock); - lock_sock(sk); + mutex_lock(&ro->conf_lock); /* remove current filters & unregister * the tracked reference ro->dev keeps the device's receive lists @@ -474,11 +476,11 @@ static int raw_release(struct socket *sock) ro->dev = NULL; ro->count = 0; + mutex_unlock(&ro->conf_lock); + sock_orphan(sk); sock->sk = NULL; - release_sock(sk); - sock_prot_inuse_add(net, sk->sk_prot, -1); sock_put(sk); @@ -500,8 +502,8 @@ static int raw_bind(struct socket *sock, struct sockaddr_unsized *uaddr, int len if (addr->can_family != AF_CAN) return -EINVAL; - /* lock_sock() serializes the binding with raw_notify() */ - lock_sock(sk); + /* ro->conf_lock serializes the binding with raw_notify() */ + mutex_lock(&ro->conf_lock); if (ro->bound && addr->can_ifindex == ro->ifindex) goto out; @@ -581,7 +583,7 @@ static int raw_bind(struct socket *sock, struct sockaddr_unsized *uaddr, int len sk_error_report(sk); } - release_sock(sk); + mutex_unlock(&ro->conf_lock); return err; } @@ -621,7 +623,7 @@ static int raw_setsockopt_locked(struct socket *sock, int optname, * * The reg_state check is only a shortcut: On a concurrent * unregistration or namespace change raw_notify() waits for - * lock_sock() and removes the filters set here. + * ro->conf_lock and removes the filters set here. */ dev = ro->dev; if (ro->bound && dev && @@ -730,6 +732,7 @@ static int raw_setsockopt(struct socket *sock, int level, int optname, sockptr_t optval, unsigned int optlen) { struct sock *sk = sock->sk; + struct raw_sock *ro = raw_sk(sk); struct can_filter *filter = NULL; /* dyn. alloc'ed filters */ struct can_filter sfilter; /* single filter */ union { @@ -744,9 +747,9 @@ static int raw_setsockopt(struct socket *sock, int level, int optname, if (level != SOL_CAN_RAW) return -EINVAL; - /* Copy the option values from user space before lock_sock(), so a - * stalled copy can not block raw_notify() waiting for lock_sock() - * under RTNL. + /* Copy the option values from user space before taking ro->conf_lock, + * so a stalled copy can not block raw_notify() waiting for + * ro->conf_lock under RTNL. */ switch (optname) { case CAN_RAW_FILTER: @@ -798,11 +801,11 @@ static int raw_setsockopt(struct socket *sock, int level, int optname, return -EFAULT; } - lock_sock(sk); + mutex_lock(&ro->conf_lock); err = raw_setsockopt_locked(sock, optname, &val, filter, count); - release_sock(sk); + mutex_unlock(&ro->conf_lock); /* on error free the filters allocated for CAN_RAW_FILTER above */ if (err && count > 1) @@ -831,7 +834,7 @@ static int raw_getsockopt(struct socket *sock, int level, int optname, struct can_filter *filter = NULL; int err = 0; - lock_sock(sk); + mutex_lock(&ro->conf_lock); if (ro->count > 0) { int fsize = ro->count * sizeof(struct can_filter); @@ -843,7 +846,7 @@ static int raw_getsockopt(struct socket *sock, int level, int optname, } else { if (len > fsize) len = fsize; - /* copy to user space after release_sock() */ + /* copy to user space after mutex_unlock() */ filter = kmemdup(ro->filter, len, GFP_KERNEL); if (!filter) err = -ENOMEM; @@ -851,7 +854,7 @@ static int raw_getsockopt(struct socket *sock, int level, int optname, } else { len = 0; } - release_sock(sk); + mutex_unlock(&ro->conf_lock); if (filter) { if (copy_to_iter(filter, len, &opt->iter_out) != len) diff --git a/net/core/bpf_sk_storage.c b/net/core/bpf_sk_storage.c index 1c59300af05c7e..67288177492ac1 100644 --- a/net/core/bpf_sk_storage.c +++ b/net/core/bpf_sk_storage.c @@ -502,6 +502,10 @@ bpf_sk_storage_diag_alloc(const struct nlattr *nla_stgs) nr_maps++; } + /* It's a dump of all maps, see bpf_sk_storage_diag_put() */ + if (!nr_maps && !perfmon_capable()) + return ERR_PTR(-EPERM); + diag = kzalloc_flex(*diag, maps, nr_maps); if (!diag) return ERR_PTR(-ENOMEM); diff --git a/net/core/dev.c b/net/core/dev.c index 3c58db732761a6..cd0796a1dbfdf8 100644 --- a/net/core/dev.c +++ b/net/core/dev.c @@ -1748,8 +1748,10 @@ static int __dev_open(struct net_device *dev, struct netlink_ext_ack *extack) ret = call_netdevice_notifiers_extack(NETDEV_PRE_UP, dev, extack); ret = notifier_to_errno(ret); - if (ret) + if (ret) { + netpoll_poll_enable(dev); return ret; + } set_bit(__LINK_STATE_START, &dev->state); @@ -6223,6 +6225,10 @@ static int __netif_receive_skb_core(struct sk_buff **pskb, bool pfmemalloc, trace_netif_receive_skb(skb); orig_dev = skb->dev; + if (unlikely(skb_headroom(skb) > SKB_MAX_RX_HEADROOM)) { + drop_reason = SKB_DROP_REASON_SKB_RX_HEADROOM; + goto drop; + } skb_reset_network_header(skb); #if !defined(CONFIG_DEBUG_NET) diff --git a/net/core/filter.c b/net/core/filter.c index 946b07a17fcecf..ea20fd2be65c01 100644 --- a/net/core/filter.c +++ b/net/core/filter.c @@ -232,7 +232,8 @@ static int bpf_skb_load_helper_convert_offset(const struct sk_buff *skb, int off return offset; if (offset >= SKF_NET_OFF) - return offset - SKF_NET_OFF + skb_network_offset(skb); + return bpf_skb_has_network_header(skb) ? + offset - SKF_NET_OFF + skb_network_offset(skb) : INT_MIN; if (offset >= SKF_LL_OFF && skb_mac_header_was_set(skb)) return offset - SKF_LL_OFF + skb_mac_offset(skb); @@ -1862,6 +1863,8 @@ BPF_CALL_5(bpf_skb_load_bytes_relative, const struct sk_buff *, skb, start = skb_mac_header(skb); break; case BPF_HDR_START_NET: + if (unlikely(!bpf_skb_has_network_header(skb))) + goto err_clear; start = skb_network_header(skb); break; default: @@ -2364,7 +2367,11 @@ static int bpf_out_neigh_v4(struct net *net, struct sk_buff *skb, } rcu_read_lock(); - if (!nh) { + if (!nh && netif_is_l3_master(dev)) { + /* The route leads to another device, this one looks it up again */ + skb_dst_drop(skb); + neigh = ip_neigh_gw4(dev, htonl(INADDR_ANY)); + } else if (!nh) { struct rtable *rt = skb_rtable(skb); neigh = ip_neigh_for_gw(rt, skb, &is_v6gw); @@ -2677,20 +2684,6 @@ BPF_CALL_2(bpf_msg_cork_bytes, struct sk_msg *, msg, u32, bytes) return 0; } -static void sk_msg_reset_curr(struct sk_msg *msg) -{ - if (!msg->sg.size) { - msg->sg.curr = msg->sg.start; - msg->sg.copybreak = 0; - } else { - u32 i = msg->sg.end; - - sk_msg_iter_var_prev(i); - msg->sg.curr = i; - msg->sg.copybreak = msg->sg.data[i].length; - } -} - static bool sk_msg_elem_is_copy(const struct sk_msg *msg, u32 i) { return test_bit(i, msg->sg.copy); @@ -2897,6 +2890,10 @@ BPF_CALL_4(bpf_msg_push_data, struct sk_msg *, msg, u32, start, if (start > offset + l) return -EINVAL; + /* A push at the end of the msg works on the last element */ + if (i == msg->sg.end && start != offset) + sk_msg_iter_var_prev(i); + space = MAX_MSG_FRAGS - sk_msg_elem_used(msg); /* If no space available will fallback to copy, we need at @@ -2906,13 +2903,13 @@ BPF_CALL_4(bpf_msg_push_data, struct sk_msg *, msg, u32, start, * offset case because its the common case for inserting a * header. */ - if (!space || (space == 1 && start != offset)) + if (!space || (space == 1 && start != offset && start < offset + l)) copy = msg->sg.data[i].length; if (unlikely(copy + len < copy)) return -EINVAL; - page = alloc_pages(__GFP_NOWARN | GFP_ATOMIC | __GFP_COMP, + page = alloc_pages(__GFP_NOWARN | GFP_ATOMIC | __GFP_COMP | __GFP_ZERO, get_order(copy + len)); if (unlikely(!page)) return -ENOMEM; @@ -2922,8 +2919,6 @@ BPF_CALL_4(bpf_msg_push_data, struct sk_msg *, msg, u32, start, raw = page_address(page); - if (i == msg->sg.end) - sk_msg_iter_var_prev(i); psge = sk_msg_elem(msg, i); front = start - offset; back = psge->length - front; @@ -2945,8 +2940,6 @@ BPF_CALL_4(bpf_msg_push_data, struct sk_msg *, msg, u32, start, } if (start - offset) { - if (i == msg->sg.end) - sk_msg_iter_var_prev(i); psge = sk_msg_elem(msg, i); rsge = sk_msg_elem_cpy(msg, i); rsge_copy = sk_msg_elem_is_copy(msg, i); @@ -3009,6 +3002,8 @@ BPF_CALL_4(bpf_msg_push_data, struct sk_msg *, msg, u32, start, msg->sg.size += len; sk_msg_clear_elem_copy(msg, new); sg_set_page(&msg->sg.data[new], page, len + copy, 0); + /* A free slot can have the end mark */ + sg_unmark_end(&msg->sg.data[new]); if (rsge.length) { get_page(sg_page(&rsge)); sk_msg_iter_var_next(new); @@ -3142,6 +3137,7 @@ BPF_CALL_4(bpf_msg_pop_data, struct sk_msg *, msg, u32, start, sg_set_page(nsge, sg_page(sge), b, sge->offset + pop + a); + sg_unmark_end(nsge); sk_msg_set_elem_copy(msg, i, sge_copy); } else { struct page *page, *orig; @@ -4048,7 +4044,7 @@ static u32 __bpf_skb_min_len(const struct sk_buff *skb) if (skb_transport_header_was_set(skb)) { offset = skb_transport_offset(skb); if (offset > 0) - min_len = offset; + min_len = max_t(u32, min_len, offset); } return min_len; } @@ -4226,10 +4222,15 @@ static const struct bpf_func_proto bpf_xdp_get_buff_len_proto = { .arg1_type = ARG_PTR_TO_CTX, }; +BPF_CALL_1(bpf_xdp_get_buff_len_trace, struct xdp_buff *, xdp) +{ + return xdp ? xdp_get_buff_len(xdp) : 0; +} + BTF_ID_LIST_SINGLE(bpf_xdp_get_buff_len_bpf_ids, struct, xdp_buff) const struct bpf_func_proto bpf_xdp_get_buff_len_trace_proto = { - .func = bpf_xdp_get_buff_len, + .func = bpf_xdp_get_buff_len_trace, .gpl_only = false, .arg1_type = ARG_PTR_TO_BTF_ID, .arg1_btf_id = &bpf_xdp_get_buff_len_bpf_ids[0], @@ -4329,7 +4330,7 @@ void *bpf_xdp_pointer(struct xdp_buff *xdp, u32 offset, u32 len) if (unlikely(offset + len > xdp_get_buff_len(xdp))) return ERR_PTR(-EINVAL); - if (likely(offset < size)) /* linear area */ + if (likely(offset < size || !xdp_buff_has_frags(xdp))) /* linear area */ goto out; sinfo = xdp_get_shared_info_from_buff(xdp); @@ -4895,11 +4896,12 @@ int xdp_do_generic_redirect(struct net_device *dev, struct sk_buff *skb, BPF_CALL_2(bpf_xdp_redirect, u32, ifindex, u64, flags) { - struct bpf_redirect_info *ri = bpf_net_ctx_get_ri(); + struct bpf_redirect_info *ri; - if (unlikely(flags)) + if (unlikely(!bpf_net_ctx_get() || flags)) return XDP_ABORTED; + ri = bpf_net_ctx_get_ri(); /* NB! Map type UNSPEC and map_id == INT_MAX (never generated * by map_idr) is used for ifindex based XDP redirect. */ @@ -5864,10 +5866,16 @@ static int sol_ipv6_sockopt(struct sock *sk, int optname, KERNEL_SOCKPTR(optval), *optlen); } +/* No hook has locked the socket for an async callback */ +static bool bpf_sockopt_allowed(const struct sock *sk) +{ + return sk && sk_fullsock(sk) && !bpf_in_async_cb(); +} + static int __bpf_setsockopt(struct sock *sk, int level, int optname, char *optval, int optlen) { - if (!sk_fullsock(sk)) + if (!bpf_sockopt_allowed(sk)) return -EINVAL; if (level == SOL_SOCKET) @@ -5890,7 +5898,7 @@ static bool is_locked_tcp_sock_ops(struct bpf_sock_ops_kern *bpf_sock) static int _bpf_setsockopt(struct sock *sk, int level, int optname, char *optval, int optlen) { - if (sk_fullsock(sk)) + if (bpf_sockopt_allowed(sk)) sock_owned_by_me(sk); return __bpf_setsockopt(sk, level, optname, optval, optlen); } @@ -5900,7 +5908,7 @@ static int __bpf_getsockopt(struct sock *sk, int level, int optname, { int err, saved_optlen = optlen; - if (!sk_fullsock(sk)) { + if (!bpf_sockopt_allowed(sk)) { err = -EINVAL; goto done; } @@ -5927,7 +5935,7 @@ static int __bpf_getsockopt(struct sock *sk, int level, int optname, static int _bpf_getsockopt(struct sock *sk, int level, int optname, char *optval, int optlen) { - if (sk_fullsock(sk)) + if (bpf_sockopt_allowed(sk)) sock_owned_by_me(sk); return __bpf_getsockopt(sk, level, optname, optval, optlen); } @@ -10456,13 +10464,19 @@ static u32 bpf_convert_ctx_access(enum bpf_access_type type, case offsetof(struct __sk_buff, remote_port): BUILD_BUG_ON(sizeof_field(struct sock_common, skc_dport) != 2); + /* + * The converted value is 4 bytes wide, not 2: on little + * endian the 16-bit port is shifted into the high half. + * Don't use bpf_target_off() here, it would report the + * member size and the narrow-load masking in the fixup + * pass would be skipped. + */ + *target_size = 4; *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk), si->dst_reg, si->src_reg, offsetof(struct sk_buff, sk)); *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg, - bpf_target_off(struct sock_common, - skc_dport, - 2, target_size)); + offsetof(struct sock_common, skc_dport)); #ifndef __BIG_ENDIAN_BITFIELD *insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16); #endif @@ -12392,6 +12406,10 @@ const struct bpf_func_proto bpf_skc_to_tcp_timewait_sock_proto = { BPF_CALL_1(bpf_skc_to_tcp_request_sock, struct sock *, sk) { + /* Ensure BTF for the structs exists even with CONFIG_INET=n. */ + BTF_TYPE_EMIT(struct inet_request_sock); + BTF_TYPE_EMIT(struct tcp_request_sock); + #ifdef CONFIG_INET if (sk && sk->sk_prot == &tcp_prot && sk->sk_state == TCP_NEW_SYN_RECV) return (unsigned long)sk; @@ -12470,7 +12488,7 @@ const struct bpf_func_proto bpf_skc_to_mptcp_sock_proto = { BPF_CALL_1(bpf_sock_from_file, struct file *, file) { - return (unsigned long)sock_from_file(file); + return file ? (unsigned long)sock_from_file(file) : 0; } BTF_ID_LIST(bpf_sock_from_file_btf_ids) @@ -12625,6 +12643,7 @@ __bpf_kfunc int bpf_sock_addr_set_sun_path(struct bpf_sock_addr_kern *sa_kern, return -EINVAL; un = (struct sockaddr_un *)sa_kern->uaddr; + un->sun_family = AF_UNIX; memcpy(un->sun_path, sun_path, sun_path__sz); sa_kern->uaddrlen = offsetof(struct sockaddr_un, sun_path) + sun_path__sz; @@ -13073,11 +13092,20 @@ BTF_KFUNCS_START(bpf_sk_iter_kfunc_ids) BTF_ID_FLAGS(func, bpf_sock_destroy) BTF_KFUNCS_END(bpf_sk_iter_kfunc_ids) +BTF_SET_START(bpf_sk_iter_locked_ids) +#if defined(CONFIG_INET) && defined(CONFIG_PROC_FS) +BTF_ID(func, bpf_iter_tcp) +BTF_ID(func, bpf_iter_udp) +#endif +BTF_SET_END(bpf_sk_iter_locked_ids) + static int tracing_iter_filter(const struct bpf_prog *prog, u32 kfunc_id) { if (btf_id_set8_contains(&bpf_sk_iter_kfunc_ids, kfunc_id) && - prog->expected_attach_type != BPF_TRACE_ITER) + (prog->expected_attach_type != BPF_TRACE_ITER || + !btf_id_set_contains(&bpf_sk_iter_locked_ids, prog->aux->attach_btf_id))) return -EACCES; + return 0; } diff --git a/net/core/neighbour.c b/net/core/neighbour.c index d6e9c7c59a892c..ae2db3912454ad 100644 --- a/net/core/neighbour.c +++ b/net/core/neighbour.c @@ -783,7 +783,7 @@ struct pneigh_entry *pneigh_lookup(struct neigh_table *tbl, int pneigh_create(struct neigh_table *tbl, const void *pkey, struct net_device *dev, - u32 flags, u8 protocol, bool permanent) + u32 flags, u8 protocol, bool permanent, bool update) { struct pneigh_entry *n; unsigned int key_len; @@ -793,8 +793,11 @@ int pneigh_create(struct neigh_table *tbl, mutex_lock(&tbl->phash_lock); n = pneigh_lookup(tbl, pkey, dev); - if (n) + if (n) { + if (!update) + goto out; goto update; + } key_len = tbl->key_len; n = kzalloc(sizeof(*n) + key_len, GFP_KERNEL); @@ -2155,7 +2158,7 @@ static int neigh_add(struct sk_buff *skb, struct nlmsghdr *nlh, } err = pneigh_create(tbl, dst, dev, ndm_flags, protocol, - !!(ndm->ndm_state & NUD_PERMANENT)); + !!(ndm->ndm_state & NUD_PERMANENT), true); goto out; } diff --git a/net/core/net_test.c b/net/core/net_test.c index 2b5080c226636c..47f5dc0fa5cf68 100644 --- a/net/core/net_test.c +++ b/net/core/net_test.c @@ -834,13 +834,14 @@ static void netmem_ref_test_pp_page(struct kunit *test) #endif #if defined(CONFIG_PAGE_POOL) && defined(CONFIG_NET_DEVMEM) +static struct net_devmem_dmabuf_binding binding; + static void dummy_percpu_ref_release(struct percpu_ref *ref) { } static void netmem_ref_test_net_iov(struct kunit *test) { - struct net_devmem_dmabuf_binding binding = {}; struct page_pool_params pp_params = { .order = 0, .pool_size = 4, @@ -853,6 +854,7 @@ static void netmem_ref_test_net_iov(struct kunit *test) long base_ref; int err; + memset(&binding, 0, sizeof(binding)); err = percpu_ref_init(&binding.ref, dummy_percpu_ref_release, PERCPU_REF_INIT_ATOMIC, GFP_KERNEL); KUNIT_ASSERT_EQ(test, err, 0); @@ -995,7 +997,6 @@ static void netmem_ref_test_release_data(struct kunit *test) .nid = NUMA_NO_NODE, }; struct sk_buff *skb, *clone1, *clone2, *ext; - struct net_devmem_dmabuf_binding binding = {}; struct net_iov niov = {}; struct page_pool *pool; struct page *page; @@ -1004,6 +1005,7 @@ static void netmem_ref_test_release_data(struct kunit *test) int base_ref; int i; + memset(&binding, 0, sizeof(binding)); pool = page_pool_create(&pp_params); KUNIT_ASSERT_FALSE(test, IS_ERR(pool)); page = page_pool_dev_alloc_pages(pool); @@ -1185,7 +1187,6 @@ static void netmem_ref_test_skb_segment(struct kunit *test) .flags = SKBFL_ZEROCOPY_ENABLE, }; struct sk_buff *head, *list, *segs, *seg; - struct net_devmem_dmabuf_binding binding = {}; struct net_iov niov = {}; struct page *pp_page, *reg_page; netmem_ref pp_nm, niov_nm; @@ -1193,6 +1194,7 @@ static void netmem_ref_test_skb_segment(struct kunit *test) long base_pp_ref, base_iov_ref; int base_pp_page_ref, base_reg_ref; + memset(&binding, 0, sizeof(binding)); pool = page_pool_create(&pp_params); KUNIT_ASSERT_FALSE(test, IS_ERR(pool)); pp_page = page_pool_dev_alloc_pages(pool); @@ -1484,7 +1486,6 @@ static void netmem_ref_test_try_coalesce(struct kunit *test) .nid = NUMA_NO_NODE, }; struct sk_buff *to, *from, *clone; - struct net_devmem_dmabuf_binding binding = {}; struct net_iov niov = {}; struct page *pp_page, *reg_page; netmem_ref pp_nm, niov_nm; @@ -1494,6 +1495,7 @@ static void netmem_ref_test_try_coalesce(struct kunit *test) bool fragstolen; int delta; + memset(&binding, 0, sizeof(binding)); pool = page_pool_create(&pp_params); KUNIT_ASSERT_FALSE(test, IS_ERR(pool)); pp_page = page_pool_dev_alloc_pages(pool); @@ -1616,7 +1618,6 @@ static void netmem_ref_test_tcp_devmem_recv(struct kunit *test) .pool_size = 4, .nid = NUMA_NO_NODE, }; - struct net_devmem_dmabuf_binding binding = {}; struct msghdr msg = {}; struct dmabuf_token token; struct dmabuf_cmsg *cmsg; @@ -1630,6 +1631,7 @@ static void netmem_ref_test_tcp_devmem_recv(struct kunit *test) long base_iov_ref; int ret; + memset(&binding, 0, sizeof(binding)); KUNIT_ASSERT_EQ(test, sock_create_kern(&init_net, AF_INET, SOCK_STREAM, IPPROTO_TCP, &sock), @@ -1721,7 +1723,58 @@ static void netmem_ref_test_tcp_devmem_recv(struct kunit *test) #endif #endif +/* Can @nr pages of @order be allocated and held at the same time? */ +static bool alloc_skb_with_frags_test_have_pages(unsigned int nr, + unsigned int order) +{ + struct page *pages[MAX_SKB_FRAGS]; + unsigned int i, n; + + for (n = 0; n < nr; n++) { + pages[n] = alloc_pages(GFP_KERNEL | __GFP_NOWARN | + __GFP_NORETRY, order); + if (!pages[n]) + break; + } + for (i = 0; i < n; i++) + __free_pages(pages[i], order); + + return n == nr; +} + +static void alloc_skb_with_frags_test_tail(struct kunit *test) +{ + /* MAX_SKB_FRAGS - 2 full chunks plus a 7 page tail: rounding the + * tail down to 4 + 2 + 1 pages would need one frag too many. + */ + unsigned long len = (MAX_SKB_FRAGS - 2) * + (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER) + + 7 * PAGE_SIZE; + unsigned long frags_len = 0; + struct sk_buff *skb; + int err, i; + + skb = alloc_skb_with_frags(0, len, PAGE_ALLOC_COSTLY_ORDER, &err, + GFP_KERNEL); + /* The full chunks can't fall back to smaller pages here, so the + * call needs up to MAX_SKB_FRAGS - 1 order-3 pages at once. Don't + * report a lack of them as a failure. + */ + if (!skb && !alloc_skb_with_frags_test_have_pages(MAX_SKB_FRAGS - 1, + PAGE_ALLOC_COSTLY_ORDER)) + kunit_skip(test, "not enough order-%d pages", + PAGE_ALLOC_COSTLY_ORDER); + KUNIT_ASSERT_NOT_NULL_MSG(test, skb, "err %d", err); + + for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) + frags_len += skb_frag_size(&skb_shinfo(skb)->frags[i]); + KUNIT_EXPECT_EQ(test, frags_len, len); + + kfree_skb(skb); +} + static struct kunit_case net_test_cases[] = { + KUNIT_CASE(alloc_skb_with_frags_test_tail), KUNIT_CASE_PARAM(gso_test_func, gso_test_gen_params), KUNIT_CASE_PARAM(ip_tunnel_flags_test_run, ip_tunnel_flags_test_gen_params), diff --git a/net/core/skbuff.c b/net/core/skbuff.c index 1ac1e327ac4c62..85d5caa0888777 100644 --- a/net/core/skbuff.c +++ b/net/core/skbuff.c @@ -4789,6 +4789,10 @@ struct sk_buff *skb_segment_list(struct sk_buff *skb, } } + if (!err) + err = skb_cow_head(nskb, offset + tnl_hlen - + skb_network_offset(nskb)); + if (!tail) skb->next = nskb; else @@ -6940,17 +6944,40 @@ struct sk_buff *alloc_skb_with_frags(unsigned long header_len, while (data_len) { if (nr_frags == MAX_SKB_FRAGS) goto failure; - while (order && PAGE_ALIGN(data_len) < (PAGE_SIZE << order)) - order--; + if (order && PAGE_ALIGN(data_len) < (PAGE_SIZE << order)) { + unsigned long pages = DIV_ROUND_UP(data_len, PAGE_SIZE); + + /* If splitting the rest into smaller pages would need + * more frags than we have left, use one larger page. + */ + if (hweight_long(pages) > MAX_SKB_FRAGS - nr_frags) + order = order_base_2(pages); + else + order = ilog2(pages); + } if (order) { page = alloc_pages((gfp_mask & ~__GFP_DIRECT_RECLAIM) | __GFP_COMP | __GFP_NOWARN, order); - if (!page) { - order--; - continue; + if (unlikely(!page)) { + unsigned int shift = PAGE_SHIFT + order - 1; + + /* Can smaller pages hold the rest? */ + if (((data_len - 1) >> shift) + 1 <= + MAX_SKB_FRAGS - nr_frags) { + order--; + continue; + } + /* No, retry this order with direct reclaim. */ + if (!gfpflags_allow_blocking(gfp_mask)) + goto failure; + page = alloc_pages(gfp_mask | __GFP_COMP | + __GFP_NOWARN | __GFP_NORETRY, + order); + if (!page) + goto failure; } } else { page = alloc_page(gfp_mask); @@ -6984,7 +7011,6 @@ static void skb_carve_reset_headers(struct sk_buff *skb) skb_unset_mac_header(skb); skb_unset_transport_header(skb); skb_reset_network_header(skb); - skb->mac_len = 0; /* Inner offsets have no "unset" marker, zero them so that * skb_inner_network_header_was_set() becomes false and no diff --git a/net/core/skmsg.c b/net/core/skmsg.c index df385a5a961e83..4089901a95812a 100644 --- a/net/core/skmsg.c +++ b/net/core/skmsg.c @@ -443,6 +443,9 @@ int __sk_msg_recvmsg(struct sock *sk, struct sk_psock *psock, struct msghdr *msg if (copy) copy = copy_page_to_iter(page, sge->offset, copy, iter); if (!copy) { + /* The elements in front of i are used up */ + if (!peek) + msg_rx->sg.start = i; copied = copied ? copied : -EFAULT; goto out; } @@ -661,7 +664,8 @@ static void sk_psock_skb_state(struct sk_psock *psock, int len, int off) { spin_lock_bh(&psock->ingress_lock); - if (sk_psock_test_state(psock, SK_PSOCK_TX_ENABLED)) { + /* No new state once the psock is stopped, but never keep an old one */ + if (!len || sk_psock_test_state(psock, SK_PSOCK_TX_ENABLED)) { state->len = len; state->off = off; } @@ -690,7 +694,7 @@ static void sk_psock_backlog(struct work_struct *work) * before sk_socket freed. If refcnt increment fails, it indicates * sock_map_close() completed with sk_socket potentially already freed. */ - if (!sk_psock_get(psock->sk)) + if (!refcount_inc_not_zero(&psock->refcnt)) return; mutex_lock(&psock->work_mutex); while ((skb = skb_peek(&psock->ingress_skb))) { @@ -932,6 +936,13 @@ int sk_psock_msg_verdict(struct sock *sk, struct sk_psock *psock, sk_msg_compute_data_pointers(msg); msg->sk = sk; + /* + * The prog may have run on this sk_msg before: it is a cork, or the + * rest of a message of which only a part was sent. The target of that + * run is not the target of this run, and the sk_msg holds no reference + * to it. + */ + msg->sk_redir = NULL; ret = bpf_prog_run_pin_on_cpu(prog, msg); msg->sk = NULL; ret = sk_psock_map_verd(ret, msg->sk_redir); @@ -1120,7 +1131,9 @@ static int sk_psock_strp_parse(struct strparser *strp, struct sk_buff *skb) prog = READ_ONCE(psock->progs.stream_parser); if (likely(prog)) { skb->sk = psock->sk; + skb_dst_drop(skb); ret = bpf_prog_run_pin_on_cpu(prog, skb); + skb_bpf_redirect_clear(skb); skb->sk = NULL; } rcu_read_unlock(); @@ -1138,7 +1151,9 @@ static void sk_psock_strp_data_ready(struct sock *sk) psock = sk_psock(sk); if (likely(psock)) { read_lock_bh(&sk->sk_callback_lock); - strp_data_ready(&psock->strp); + /* This psock may be not the one that has set the callback */ + if (likely(sk_psock_test_state(psock, SK_PSOCK_RX_STRP_ENABLED))) + strp_data_ready(&psock->strp); read_unlock_bh(&sk->sk_callback_lock); } rcu_read_unlock(); @@ -1146,7 +1161,7 @@ static void sk_psock_strp_data_ready(struct sock *sk) int sk_psock_init_strp(struct sock *sk, struct sk_psock *psock) { - int ret; + int ret = 0; static const struct strp_callbacks cb = { .rcv_msg = sk_psock_strp_read, @@ -1154,7 +1169,11 @@ int sk_psock_init_strp(struct sock *sk, struct sk_psock *psock) .parse_msg = sk_psock_strp_parse, }; - ret = strp_init(&psock->strp, sk, &cb); + /* A stopped parser keeps its works and its skb until strp_done() */ + if (sk_psock_test_state(psock, SK_PSOCK_RX_STRP_ENABLED)) + psock->strp.stopped = 0; + else + ret = strp_init(&psock->strp, sk, &cb); if (!ret) sk_psock_set_state(psock, SK_PSOCK_RX_STRP_ENABLED); diff --git a/net/core/sock.c b/net/core/sock.c index ad414878dc5ba8..5675053625e6fe 100644 --- a/net/core/sock.c +++ b/net/core/sock.c @@ -1746,8 +1746,10 @@ static int sk_getsockopt_peerpidfd(struct sock *sk, enum pid_type type, struct pid *peer_pid; int pidfd; - if (len > sizeof(pidfd)) - len = sizeof(pidfd); + /* Userspace can't close a pidfd whose number it didn't get. */ + if (len < sizeof(pidfd)) + return -EINVAL; + len = sizeof(pidfd); spin_lock(&sk->sk_peer_lock); peer_pid = get_pid(sk->sk_peer_pid[type]); @@ -2545,6 +2547,7 @@ struct sock *sk_clone(const struct sock *sk, const gfp_t priority, sk_node_init(&newsk->sk_node); sock_lock_init(newsk); + spin_lock_init(&newsk->sk_peer_lock); if (lock) bh_lock_sock(newsk); diff --git a/net/core/sock_map.c b/net/core/sock_map.c index efe49551caba9e..ac62174e8e01e6 100644 --- a/net/core/sock_map.c +++ b/net/core/sock_map.c @@ -169,7 +169,8 @@ static void sock_map_del_link(struct sock *sk, write_lock_bh(&sk->sk_callback_lock); if (psock->saved_data_ready) { - if (strp_stop) + /* The parser can be from another map, it loses sk_data_ready too */ + if (strp_stop || psock->progs.stream_parser) sk_psock_stop_strp(sk, psock); if (verdict_stop) sk_psock_stop_verdict(sk, psock); @@ -228,6 +229,14 @@ static int sock_map_link(struct bpf_map *map, struct sock *sk) struct sk_psock *psock; int ret; + /* + * A listener receives no data. With the callbacks of a verdict program + * or a parser it would no longer wake accept(), and its children would + * copy them. + */ + if (sk_is_tcp(sk) && sk->sk_state == TCP_LISTEN) + goto no_progs; + stream_verdict = READ_ONCE(progs->stream_verdict); if (stream_verdict) { stream_verdict = bpf_prog_inc_not_zero(stream_verdict); @@ -262,6 +271,7 @@ static int sock_map_link(struct bpf_map *map, struct sock *sk) } } +no_progs: psock = sock_map_psock_get_checked(sk); if (IS_ERR(psock)) { ret = PTR_ERR(psock); @@ -1993,7 +2003,7 @@ static struct bpf_iter_reg sock_map_iter_reg = { { offsetof(struct bpf_iter__sockmap, key), PTR_TO_BUF | PTR_MAYBE_NULL | MEM_RDONLY }, { offsetof(struct bpf_iter__sockmap, sk), - PTR_TO_BTF_ID_OR_NULL }, + PTR_TO_BTF_ID_OR_NULL | PTR_TRUSTED }, }, }; diff --git a/net/core/sock_reuseport.c b/net/core/sock_reuseport.c index b9e5648fa4c515..e039e35f39a90a 100644 --- a/net/core/sock_reuseport.c +++ b/net/core/sock_reuseport.c @@ -461,6 +461,18 @@ void reuseport_detach_sock(struct sock *sk) } EXPORT_SYMBOL(reuseport_detach_sock); +/* + * Only a BPF_PROG_TYPE_SK_REUSEPORT program is verified against + * struct sk_reuseport_kern, which is the context bpf_run_sk_reuseport() + * passes to it. expected_attach_type is set by user space and does not + * identify the program type. + */ +static bool reuseport_is_migration_prog(const struct bpf_prog *prog) +{ + return prog && prog->type == BPF_PROG_TYPE_SK_REUSEPORT && + prog->expected_attach_type == BPF_SK_REUSEPORT_SELECT_OR_MIGRATE; +} + void reuseport_stop_listen_sock(struct sock *sk) { if (sk->sk_protocol == IPPROTO_TCP) { @@ -475,7 +487,7 @@ void reuseport_stop_listen_sock(struct sock *sk) lockdep_is_held(&reuseport_lock)); if (READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_migrate_req) || - (prog && prog->expected_attach_type == BPF_SK_REUSEPORT_SELECT_OR_MIGRATE)) { + reuseport_is_migration_prog(prog)) { /* Migration capable, move sk from the listening section * to the closed section. */ @@ -645,7 +657,7 @@ struct sock *reuseport_migrate_sock(struct sock *sk, hash = migrating_sk->sk_hash; prog = rcu_dereference(reuse->prog); - if (!prog || prog->expected_attach_type != BPF_SK_REUSEPORT_SELECT_OR_MIGRATE) { + if (!reuseport_is_migration_prog(prog)) { if (READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_migrate_req)) goto select_by_hash; goto failure; diff --git a/net/core/stream.c b/net/core/stream.c index cb255e2a3a5dd7..334124d683a7a0 100644 --- a/net/core/stream.c +++ b/net/core/stream.c @@ -150,7 +150,11 @@ int sk_stream_wait_memory(struct sock *sk, long *timeo_p) (sk_stream_memory_free(sk) && !vm_wait), &wait); sk->sk_write_pending--; - if (ret < 0) + /* + * A sender which sockmap has redirected to sk does not keep it + * open. A dead socket has no sk_wq. + */ + if (ret < 0 || sock_flag(sk, SOCK_DEAD)) goto do_error; if (vm_wait) { diff --git a/net/dcb/dcbnl.c b/net/dcb/dcbnl.c index ad0aebe0ad3d2b..95250658ecc156 100644 --- a/net/dcb/dcbnl.c +++ b/net/dcb/dcbnl.c @@ -2393,6 +2393,13 @@ static void dcbnl_flush_dev(struct net_device *dev) } } + list_for_each_entry_safe(itr, tmp, &dcb_rewr_list, list) { + if (itr->ifindex == dev->ifindex) { + list_del(&itr->list); + kfree(itr); + } + } + spin_unlock_bh(&dcb_lock); } diff --git a/net/dsa/tag_brcm.c b/net/dsa/tag_brcm.c index b7c49822ca8880..b58669c9214742 100644 --- a/net/dsa/tag_brcm.c +++ b/net/dsa/tag_brcm.c @@ -149,6 +149,7 @@ static struct sk_buff *brcm_tag_rcv_ll(struct sk_buff *skb, unsigned int offset) { int source_port; + const u8 *dest; u8 *brcm_tag; if (unlikely(!pskb_may_pull(skb, BRCM_TAG_LEN))) { @@ -184,7 +185,11 @@ static struct sk_buff *brcm_tag_rcv_ll(struct sk_buff *skb, /* Remove Broadcom tag and update checksum */ skb_pull_rcsum(skb, BRCM_TAG_LEN); - if (likely(!is_link_local_ether_addr(eth_hdr(skb)->h_dest))) + /* With a prepended tag, the MAC header set by eth_type_trans() starts + * at the tag, and the destination address follows it. + */ + dest = offset == ETH_HLEN ? brcm_tag + BRCM_TAG_LEN : eth_hdr(skb)->h_dest; + if (likely(!is_link_local_ether_addr(dest))) dsa_default_offload_fwd_mark(skb); return skb; diff --git a/net/ieee802154/socket.c b/net/ieee802154/socket.c index be8ca1f053a2b6..362457de8424cc 100644 --- a/net/ieee802154/socket.c +++ b/net/ieee802154/socket.c @@ -128,6 +128,10 @@ static int ieee802154_dev_ioctl(struct sock *sk, struct ifreq __user *arg, int ret = -ENOIOCTLCMD; struct net_device *dev; + if (cmd == SIOCSIFADDR && + !ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) + return -EPERM; + if (get_user_ifreq(&ifr, NULL, arg)) return -EFAULT; diff --git a/net/ipv4/af_inet.c b/net/ipv4/af_inet.c index 8822bae439f88d..5d03a9149b40f9 100644 --- a/net/ipv4/af_inet.c +++ b/net/ipv4/af_inet.c @@ -549,9 +549,9 @@ int __inet_bind(struct sock *sk, struct sockaddr_unsized *uaddr, int addr_len, if (!(flags & BIND_FROM_BPF)) { err = BPF_CGROUP_RUN_PROG_INET4_POST_BIND(sk); if (err) { - inet->inet_saddr = inet->inet_rcv_saddr = 0; if (sk->sk_prot->put_port) sk->sk_prot->put_port(sk); + inet->inet_saddr = inet->inet_rcv_saddr = 0; goto out_release_sock; } } diff --git a/net/ipv4/arp.c b/net/ipv4/arp.c index 1ca4ced280aef2..3bc8db6ccd68e0 100644 --- a/net/ipv4/arp.c +++ b/net/ipv4/arp.c @@ -1099,7 +1099,7 @@ static int arp_req_set_public(struct net *net, struct arpreq *r, if (mask) { __be32 ip = ((struct sockaddr_in *)&r->arp_pa)->sin_addr.s_addr; - return pneigh_create(tbl, &ip, dev, 0, 0, false); + return pneigh_create(tbl, &ip, dev, 0, 0, false, false); } return arp_req_set_proxy(net, dev, 1); diff --git a/net/ipv4/bpf_tcp_ops.c b/net/ipv4/bpf_tcp_ops.c index 2ba73dd6c52cce..432ca078377105 100644 --- a/net/ipv4/bpf_tcp_ops.c +++ b/net/ipv4/bpf_tcp_ops.c @@ -207,7 +207,7 @@ BPF_CALL_0(bpf_tcp_ops_get_retval) * return value chained across the bpf_tcp_ops attached to the cgroup * and is this program's saved_run_ctx. */ - if (WARN_ON_ONCE(!ctx->saved_run_ctx)) + if (bpf_in_async_cb() || WARN_ON_ONCE(!ctx->saved_run_ctx)) return 0; return container_of(ctx->saved_run_ctx, struct bpf_tramp_run_ctx, diff --git a/net/ipv4/fou_core.c b/net/ipv4/fou_core.c index 5c3c8f55d05704..bff4dc488def79 100644 --- a/net/ipv4/fou_core.c +++ b/net/ipv4/fou_core.c @@ -1071,6 +1071,9 @@ static int fou_build_header(struct sk_buff *skb, struct ip_tunnel_encap *e, __be16 sport; int err; + if (skb_cow_head(skb, fou_encap_hlen(e))) + return -ENOMEM; + err = __fou_build_header(skb, e, protocol, &sport, type); if (err) return err; @@ -1083,16 +1086,24 @@ static int fou_build_header(struct sk_buff *skb, struct ip_tunnel_encap *e, static int gue_build_header(struct sk_buff *skb, struct ip_tunnel_encap *e, u8 *protocol, struct flowi4 *fl4) { - int type = e->flags & TUNNEL_ENCAP_FLAG_CSUM ? SKB_GSO_UDP_TUNNEL_CSUM : - SKB_GSO_UDP_TUNNEL; + struct ip_tunnel_encap encap = { + .flags = READ_ONCE(e->flags), + .sport = READ_ONCE(e->sport), + .dport = READ_ONCE(e->dport), + }; + int type = encap.flags & TUNNEL_ENCAP_FLAG_CSUM ? + SKB_GSO_UDP_TUNNEL_CSUM : SKB_GSO_UDP_TUNNEL; __be16 sport; int err; - err = __gue_build_header(skb, e, protocol, &sport, type); + if (skb_cow_head(skb, gue_encap_hlen(&encap))) + return -ENOMEM; + + err = __gue_build_header(skb, &encap, protocol, &sport, type); if (err) return err; - fou_build_udp(skb, e, fl4, protocol, sport); + fou_build_udp(skb, &encap, fl4, protocol, sport); return 0; } diff --git a/net/ipv4/inet_connection_sock.c b/net/ipv4/inet_connection_sock.c index 6c079929e06f69..aa0678a1823d9c 100644 --- a/net/ipv4/inet_connection_sock.c +++ b/net/ipv4/inet_connection_sock.c @@ -420,13 +420,18 @@ static inline int sk_reuseport_match(struct inet_bind_bucket *tb, return 0; if (!uid_eq(tb->fastuid, sk_uid(sk))) return 0; - /* We only need to check the rcv_saddr if this tb was once marked + /* We only need to check the fast_* fields if this tb was once marked * without fastreuseport and then was reset, as we can only know that - * the fast_*rcv_saddr doesn't have any conflicts with the socks on the - * owners list. + * the socket they describe doesn't have any conflicts with the socks + * on the owners list. */ if (tb->fastreuseport == FASTREUSEPORT_ANY) return 1; + if (tb->fast_sk_family != sk->sk_family || + tb->fast_ipv6_only != ipv6_only_sock(sk) || + tb->fast_bound_dev_if != sk->sk_bound_dev_if || + tb->fast_sk_reuse != sk->sk_reuse) + return 0; #if IS_ENABLED(CONFIG_IPV6) if (tb->fast_sk_family == AF_INET6) return ipv6_rcv_saddr_equal(&tb->fast_v6_rcv_saddr, @@ -455,6 +460,8 @@ void inet_csk_update_fastreuse(const struct sock *sk, tb->fast_rcv_saddr = sk->sk_rcv_saddr; tb->fast_ipv6_only = ipv6_only_sock(sk); tb->fast_sk_family = sk->sk_family; + tb->fast_sk_reuse = sk->sk_reuse; + tb->fast_bound_dev_if = sk->sk_bound_dev_if; #if IS_ENABLED(CONFIG_IPV6) tb->fast_v6_rcv_saddr = sk->sk_v6_rcv_saddr; #endif @@ -482,6 +489,8 @@ void inet_csk_update_fastreuse(const struct sock *sk, tb->fast_rcv_saddr = sk->sk_rcv_saddr; tb->fast_ipv6_only = ipv6_only_sock(sk); tb->fast_sk_family = sk->sk_family; + tb->fast_sk_reuse = sk->sk_reuse; + tb->fast_bound_dev_if = sk->sk_bound_dev_if; #if IS_ENABLED(CONFIG_IPV6) tb->fast_v6_rcv_saddr = sk->sk_v6_rcv_saddr; #endif @@ -1073,6 +1082,7 @@ static void reqsk_timer_handler(struct timer_list *t) net = sock_net(sk_listener); max_syn_ack_retries = READ_ONCE(icsk->icsk_syn_retries) ? : READ_ONCE(net->ipv4.sysctl_tcp_synack_retries); + max_syn_ack_retries = min_t(int, max_syn_ack_retries, MAX_TCP_SYNCNT); /* Normally all the openreqs are young and become mature * (i.e. converted to established socket) for first timeout. * If synack was not acknowledged for 1 second, it means @@ -1331,6 +1341,22 @@ static int inet_ulp_can_listen(const struct sock *sk) return 0; } +/* Free all the reqs queued in rskq_rst_head. */ +static void reqsk_fastopen_purge_rst(struct request_sock_queue *queue) +{ + struct request_sock *next, *req; + + spin_lock_bh(&queue->fastopenq.lock); + req = queue->fastopenq.rskq_rst_head; + queue->fastopenq.rskq_rst_head = NULL; + spin_unlock_bh(&queue->fastopenq.lock); + while (req != NULL) { + next = req->dl_next; + reqsk_put(req); + req = next; + } +} + static void reqsk_queue_alloc(struct request_sock_queue *queue) { queue->fastopenq.rskq_rst_head = NULL; @@ -1373,6 +1399,12 @@ int inet_csk_listen_start(struct sock *sk) } inet_sk_set_state(sk, TCP_CLOSE); + + /* A Fast Open child accepted before a previous shutdown() of this + * listener might have queued its request in rskq_rst_head while + * we were transiently in TCP_LISTEN state. + */ + reqsk_fastopen_purge_rst(&icsk->icsk_accept_queue); return err; } @@ -1477,7 +1509,7 @@ void inet_csk_listen_stop(struct sock *sk) { struct inet_connection_sock *icsk = inet_csk(sk); struct request_sock_queue *queue = &icsk->icsk_accept_queue; - struct request_sock *next, *req; + struct request_sock *req; /* Following specs, it would be better either to send FIN * (and enter FIN-WAIT-1, it is normal close) @@ -1533,18 +1565,7 @@ void inet_csk_listen_stop(struct sock *sk) if (!has_current_bpf_ctx()) cond_resched(); } - if (queue->fastopenq.rskq_rst_head) { - /* Free all the reqs queued in rskq_rst_head. */ - spin_lock_bh(&queue->fastopenq.lock); - req = queue->fastopenq.rskq_rst_head; - queue->fastopenq.rskq_rst_head = NULL; - spin_unlock_bh(&queue->fastopenq.lock); - while (req != NULL) { - next = req->dl_next; - reqsk_put(req); - req = next; - } - } + reqsk_fastopen_purge_rst(queue); WARN_ON_ONCE(sk->sk_ack_backlog); } diff --git a/net/ipv4/ip_fragment.c b/net/ipv4/ip_fragment.c index ef7fd61284a3fa..0688be8142c4b3 100644 --- a/net/ipv4/ip_fragment.c +++ b/net/ipv4/ip_fragment.c @@ -250,6 +250,8 @@ static int ip_frag_reinit(struct ipq *qp) qp->q.flags = 0; qp->q.len = 0; qp->q.meat = 0; + qp->q.max_size = 0; + qp->max_df_size = 0; qp->iif = 0; qp->ecn = 0; diff --git a/net/ipv4/ip_input.c b/net/ipv4/ip_input.c index 9860178752b8cc..c74886b1f4453d 100644 --- a/net/ipv4/ip_input.c +++ b/net/ipv4/ip_input.c @@ -207,6 +207,12 @@ void ip_protocol_deliver_rcu(struct net *net, struct sk_buff *skb, int protocol) ret = INDIRECT_CALL_2(ipprot->handler, tcp_v4_rcv, udp_rcv, skb); if (ret < 0) { + if (unlikely(skb_headroom(skb) > SKB_MAX_RX_HEADROOM)) { + __IP_INC_STATS(net, IPSTATS_MIB_INDISCARDS); + kfree_skb_reason(skb, + SKB_DROP_REASON_SKB_RX_HEADROOM); + return; + } protocol = -ret; goto resubmit; } diff --git a/net/ipv4/ip_tunnel.c b/net/ipv4/ip_tunnel.c index 0875474a578a4a..1052af6245df53 100644 --- a/net/ipv4/ip_tunnel.c +++ b/net/ipv4/ip_tunnel.c @@ -610,6 +610,7 @@ void ip_md_tunnel_xmit(struct sk_buff *skb, struct net_device *dev, if (ip_tunnel_encap(skb, &tun_info->encap, &proto, &fl4) < 0) goto tx_error; + inner_iph = (const struct iphdr *)skb_inner_network_header(skb); use_cache = ip_tunnel_dst_cache_usable(skb, tun_info); if (use_cache) @@ -753,6 +754,8 @@ void ip_tunnel_xmit(struct sk_buff *skb, struct net_device *dev, } tos = tnl_params->tos; + df = tnl_params->frag_off; + ttl = tnl_params->ttl; if (tos & 0x1) { tos &= ~0x1; if (payload_protocol == htons(ETH_P_IP)) { @@ -771,6 +774,7 @@ void ip_tunnel_xmit(struct sk_buff *skb, struct net_device *dev, if (ip_tunnel_encap(skb, &tunnel->encap, &protocol, &fl4) < 0) goto tx_error; + inner_iph = (const struct iphdr *)skb_inner_network_header(skb); if (connected && md) { use_cache = ip_tunnel_dst_cache_usable(skb, tun_info); @@ -803,7 +807,6 @@ void ip_tunnel_xmit(struct sk_buff *skb, struct net_device *dev, goto tx_error; } - df = tnl_params->frag_off; if (payload_protocol == htons(ETH_P_IP) && !tunnel->ignore_df) df |= (inner_iph->frag_off & htons(IP_DF)); @@ -825,7 +828,6 @@ void ip_tunnel_xmit(struct sk_buff *skb, struct net_device *dev, } tos = ip_tunnel_ecn_encap(tos, inner_iph, skb); - ttl = tnl_params->ttl; if (ttl == 0) { if (payload_protocol == htons(ETH_P_IP)) ttl = inner_iph->ttl; diff --git a/net/ipv4/syncookies.c b/net/ipv4/syncookies.c index 4e0ff3b820627e..89169c82431c12 100644 --- a/net/ipv4/syncookies.c +++ b/net/ipv4/syncookies.c @@ -290,6 +290,10 @@ static int cookie_tcp_reqsk_init(struct sock *sk, struct sk_buff *skb, */ treq->txhash = treq->snt_isn; treq->syn_tos = TCP_SKB_CB(skb)->ip_dsfield; + treq->saw_accecn_opt = TCP_ACCECN_OPT_NOT_SEEN; + treq->accecn_fail_mode = 0; + treq->syn_ect_rcv = 0; + treq->syn_ect_snt = 0; #if IS_ENABLED(CONFIG_MPTCP) treq->is_mptcp = sk_is_mptcp(sk); @@ -502,6 +506,9 @@ struct sock *cookie_v4_check(struct sock *sk, struct sk_buff *skb) ireq->rcv_wscale = rcv_wscale; ireq->ecn_ok &= cookie_ecn_ok(net, &rt->dst); treq->accecn_ok = ireq->ecn_ok && cookie_accecn_ok(th); + /* SYN-ACK was not sent by the kernel if req->syncookie is set. */ + if (!req->syncookie) + treq->syn_ect_snt = READ_ONCE(inet_sk(sk)->tos) & INET_ECN_MASK; ret = tcp_get_cookie_sock(sk, skb, req, &rt->dst); /* ip_queue_xmit() depends on our flow being setup diff --git a/net/ipv4/tcp.c b/net/ipv4/tcp.c index 832b25ddd3c2ea..80de376a9d2ef9 100644 --- a/net/ipv4/tcp.c +++ b/net/ipv4/tcp.c @@ -358,7 +358,7 @@ static u8 secs_to_retrans(int seconds, int timeout, int rto_max) int period = timeout; res = 1; - while (seconds > period && res < 255) { + while (seconds > period && res < MAX_TCP_SYNCNT) { res++; timeout <<= 1; if (timeout > rto_max) @@ -1352,6 +1352,8 @@ int tcp_sendmsg_locked(struct sock *sk, struct msghdr *msg, size_t size) err = skb_zerocopy_iter_stream(sk, skb, msg, copy, uarg, binding); + if (!skb_zcopy_pure(skb)) + sk_forced_mem_schedule(sk, 0); if (err == -EMSGSIZE || err == -EEXIST) { tcp_mark_push(tp, skb); goto new_segment; diff --git a/net/ipv4/tcp_ao.c b/net/ipv4/tcp_ao.c index bb7bbc20ba3fad..857b8684e01d93 100644 --- a/net/ipv4/tcp_ao.c +++ b/net/ipv4/tcp_ao.c @@ -799,8 +799,8 @@ int tcp_ao_prepare_reset(const struct sock *sk, struct sk_buff *skb, return -ENOTCONN; if ((1 << sk->sk_state) & (TCPF_LISTEN | TCPF_NEW_SYN_RECV)) { - unsigned int family = READ_ONCE(sk->sk_family); union tcp_ao_addr *addr; + unsigned int family; __be32 disn, sisn; if (sk->sk_state == TCP_NEW_SYN_RECV) { @@ -813,14 +813,14 @@ int tcp_ao_prepare_reset(const struct sock *sk, struct sk_buff *skb, sisn = th->seq; disn = 0; } - if (IS_ENABLED(CONFIG_IPV6) && family == AF_INET6) + if (IS_ENABLED(CONFIG_IPV6) && + skb->protocol == htons(ETH_P_IPV6)) { + family = AF_INET6; addr = (union tcp_md5_addr *)&ipv6_hdr(skb)->saddr; - else - addr = (union tcp_md5_addr *)&ip_hdr(skb)->saddr; -#if IS_ENABLED(CONFIG_IPV6) - if (family == AF_INET6 && ipv6_addr_v4mapped(&sk->sk_v6_daddr)) + } else { family = AF_INET; -#endif + addr = (union tcp_md5_addr *)&ip_hdr(skb)->saddr; + } sk = sk_const_to_full_sk(sk); ao_info = rcu_dereference(tcp_sk(sk)->ao_info); diff --git a/net/ipv4/tcp_bpf.c b/net/ipv4/tcp_bpf.c index 8cf63a9e7fed15..788ce08eef4d7a 100644 --- a/net/ipv4/tcp_bpf.c +++ b/net/ipv4/tcp_bpf.c @@ -88,6 +88,24 @@ static int bpf_tcp_ingress(struct sock *sk, struct sk_psock *psock, return ret; } +/* + * The target of a redirect belongs to somebody else. A child that nobody has + * accepted yet, and an orphan, have no struct socket and no wait queue. + * tcp_sendmsg_locked() needs both. See sendmsg_locked() in skbuff.c. + * The sender holds no reference to the file of the target, which can be closed + * whenever tcp_sendmsg_locked() sleeps. sk_stream_wait_connect() and + * inet_wait_for_connect() go back to the wait queue when they wake up, so the + * sender must not wait for a connect. + */ +static bool tcp_bpf_redir_allowed(const struct sock *sk) +{ + if (!sk->sk_socket) + return false; + if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV)) + return tcp_passive_fastopen(sk); + return true; +} + static int tcp_bpf_push(struct sock *sk, struct sk_msg *msg, u32 apply_bytes, int flags, bool uncharge) { @@ -109,6 +127,10 @@ static int tcp_bpf_push(struct sock *sk, struct sk_msg *msg, u32 apply_bytes, page = sg_page(sge); retry: + /* Only a redirect sends data which is not charged to sk */ + if (!uncharge && unlikely(!tcp_bpf_redir_allowed(sk))) + return sock_flag(sk, SOCK_DEAD) ? -EPIPE : -EINVAL; + msghdr.msg_flags = flags | MSG_SPLICE_PAGES; has_tx_ulp = tls_sw_has_ctx_tx(sk); if (has_tx_ulp) @@ -321,7 +343,8 @@ static int tcp_bpf_recvmsg_parser(struct sock *sk, if (!peek) WRITE_ONCE(tcp->copied_seq, seq); tcp_rcv_space_adjust(sk); - if (copied > 0) + /* Data on the psock outlives the connection that it came in on */ + if (copied > 0 && tcp_can_send_ack(sk)) __tcp_cleanup_rbuf(sk, copied); unlock: @@ -446,6 +469,11 @@ static int tcp_bpf_send_verdict(struct sock *sk, struct sk_psock *psock, return -ENOMEM; } } + /* + * A push or a redirect may have taken bytes off the front of + * element sg.curr. The next sendmsg() appends to the cork. + */ + sk_msg_reset_curr(msg); memcpy(psock->cork, msg, sizeof(*msg)); return 0; } @@ -457,8 +485,22 @@ static int tcp_bpf_send_verdict(struct sock *sk, struct sk_psock *psock, switch (psock->eval) { case __SK_PASS: + /* The push may sleep without the socket lock, and it may fail */ + if (!psock->apply_bytes) + psock->eval = __SK_NONE; + origsize = msg->sg.size; ret = tcp_bpf_push(sk, msg, tosend, flags, true); if (unlikely(ret)) { + /* A part of it may have gone out */ + sk_msg_apply_bytes(psock, origsize - msg->sg.size); + /* Another sender can use up the rest during the push */ + if (!psock->apply_bytes) { + psock->eval = __SK_NONE; + if (psock->sk_redir) { + sock_put(psock->sk_redir); + psock->sk_redir = NULL; + } + } *copied -= sk_msg_free(sk, msg); break; } @@ -475,7 +517,11 @@ static int tcp_bpf_send_verdict(struct sock *sk, struct sk_psock *psock, psock->eval = __SK_NONE; psock->sk_redir = NULL; } - if (psock->cork) { + /* + * Another thread can make a cork while this one sends msg + * without the socket lock. Leave that cork alone. + */ + if (psock->cork == msg) { cork = true; psock->cork = NULL; } @@ -498,6 +544,14 @@ static int tcp_bpf_send_verdict(struct sock *sk, struct sk_psock *psock, if (!cork) *copied -= free; } + /* + * The verdict was for tosend bytes. The rest goes back, unless + * another thread made a new cork while the lock was released. + */ + if (cork && msg->sg.size && !psock->cork) { + psock->cork = msg; + cork = false; + } if (cork) { sk_msg_free(sk, msg); kfree(msg); @@ -507,9 +561,12 @@ static int tcp_bpf_send_verdict(struct sock *sk, struct sk_psock *psock, break; case __SK_DROP: default: - sk_msg_free(sk, msg); + /* All of it is thrown away, not only tosend bytes */ + *copied -= sk_msg_free(sk, msg) + delta; sk_msg_apply_bytes(psock, tosend); - *copied -= (tosend + delta); + /* The verdict holds for apply_bytes, not for ever */ + if (!psock->apply_bytes) + psock->eval = __SK_NONE; return -EACCES; } @@ -538,7 +595,7 @@ static int tcp_bpf_sendmsg(struct sock *sk, struct msghdr *msg, size_t size) int flags; /* Don't let internal flags through */ - flags = (msg->msg_flags & ~MSG_SENDPAGE_DECRYPTED); + flags = (msg->msg_flags & ~(MSG_SENDPAGE_DECRYPTED | MSG_FASTOPEN)); flags |= MSG_NO_SHARED_FRAGS; psock = sk_psock_get(sk); @@ -574,8 +631,15 @@ static int tcp_bpf_sendmsg(struct sock *sk, struct msghdr *msg, size_t size) copy = msg_tx->sg.size - osize; } - ret = sk_msg_memcopy_from_iter(sk, &msg->msg_iter, msg_tx, - copy); + /* + * copy is 0 if the ring of the cork was full already and its + * last element could not be extended. Flush the cork below, + * and let the next pass take the data. + */ + ret = 0; + if (copy) + ret = sk_msg_memcopy_from_iter(sk, &msg->msg_iter, + msg_tx, copy); if (ret < 0) { sk_msg_trim(sk, msg_tx, osize); err = ret; @@ -768,7 +832,18 @@ void tcp_bpf_clone(const struct sock *sk, struct sock *newsk) { struct proto *prot = newsk->sk_prot; - if (is_insidevar(prot, tcp_bpf_prots)) - newsk->sk_prot = sk->sk_prot_creator; + if (!is_insidevar(prot, tcp_bpf_prots)) + return; + + newsk->sk_prot = sk->sk_prot_creator; + /* + * sock_map_link() gives a listener no programs, but a socket which got + * them in another state and listens now has the psock's sk_data_ready + * and sk_write_space, and sock_copy() has copied them. + * sk_psock_init() refuses a socket that has sk_user_data or a ULP, so + * what the psock replaced were the defaults of a TCP socket. + */ + newsk->sk_data_ready = sock_def_readable; + newsk->sk_write_space = sk_stream_write_space; } #endif /* CONFIG_BPF_SYSCALL */ diff --git a/net/ipv4/tcp_input.c b/net/ipv4/tcp_input.c index a2074a1af42228..d9a66a1342efdd 100644 --- a/net/ipv4/tcp_input.c +++ b/net/ipv4/tcp_input.c @@ -857,7 +857,11 @@ void tcp_initialize_rcv_mss(struct sock *sk) static void tcp_rcv_rtt_update(struct tcp_sock *tp, u32 sample, int win_dep) { u32 new_sample, old_sample = tp->rcv_rtt_est.rtt_us; - long m = sample << 3; + long m; + + /* Keep sample << 3 and the smoothed estimate within u32. */ + sample = min(sample, TCP_RTT_MAX_US); + m = sample << 3; if (old_sample == 0 || m < old_sample) { new_sample = m; @@ -901,15 +905,16 @@ static inline void tcp_rcv_rtt_measure(struct tcp_sock *tp) tp->rcv_rtt_est.time = tp->tcp_mstamp; } +/* A sample from TSecr above TCP_RTT_MAX_US is bogus, not large. */ static s32 tcp_rtt_tsopt_us(const struct tcp_sock *tp, u32 min_delta) { u32 delta, delta_us; delta = tcp_time_stamp_ts(tp) - tp->rx_opt.rcv_tsecr; if (tp->tcp_usec_ts) - return delta; + return delta <= TCP_RTT_MAX_US ? delta : -1; - if (likely(delta < INT_MAX / (USEC_PER_SEC / TCP_TS_HZ))) { + if (likely(delta <= TCP_RTT_MAX_US / (USEC_PER_SEC / TCP_TS_HZ))) { if (!delta) delta = min_delta; delta_us = delta * (USEC_PER_SEC / TCP_TS_HZ); @@ -1098,8 +1103,11 @@ static void tcp_event_data_recv(struct sock *sk, struct sk_buff *skb) static void tcp_rtt_estimator(struct sock *sk, long mrtt_us) { struct tcp_sock *tp = tcp_sk(sk); - long m = mrtt_us; /* RTT */ u32 srtt = tp->srtt_us; + long m; /* RTT */ + + mrtt_us = min(mrtt_us, TCP_RTT_MAX_US); + m = mrtt_us; /* The following amusing code comes from Jacobson's * article in SIGCOMM '88. Note that rtt and mdev @@ -1221,8 +1229,9 @@ void tcp_set_rto(struct sock *sk) * with correct one. It is exactly, which we pretend to do. */ - /* NOTE: clamping at TCP_RTO_MIN is not required, current algo - * guarantees that rto is higher. + /* NOTE: clamping at tcp_rto_min() is not required, tcp_rtt_estimator() + * applies it to rttvar_us. But rto must never be 0, which exponential + * backoff could not leave: __tcp_set_rto() takes care of that. */ tcp_bound_rto(sk); } diff --git a/net/ipv4/tcp_offload.c b/net/ipv4/tcp_offload.c index b84fcd07c7230f..7691be01da4d28 100644 --- a/net/ipv4/tcp_offload.c +++ b/net/ipv4/tcp_offload.c @@ -105,12 +105,16 @@ static struct sk_buff *tcp4_gso_segment(struct sk_buff *skb, return ERR_PTR(-EINVAL); if (skb_shinfo(skb)->gso_type & SKB_GSO_FRAGLIST) { - struct tcphdr *th = tcp_hdr(skb); + int err; - if ((skb_pagelen(skb) - th->doff * 4 == skb_shinfo(skb)->gso_size) && - !(skb_shinfo(skb)->gso_type & SKB_GSO_DODGY)) + if (skb_gso_fraglist_ok(skb, features, tcp_hdrlen(skb), + htons(ETH_P_IP))) return __tcp4_gso_segment_list(skb, features); + err = skb_cow_head(skb, 0); + if (err < 0) + return ERR_PTR(err); + skb->ip_summed = CHECKSUM_NONE; } diff --git a/net/ipv4/tcp_timer.c b/net/ipv4/tcp_timer.c index 00debcba122b14..814fadb30749b0 100644 --- a/net/ipv4/tcp_timer.c +++ b/net/ipv4/tcp_timer.c @@ -468,6 +468,7 @@ static void tcp_fastopen_synack_timer(struct sock *sk, struct request_sock *req) */ max_retries = READ_ONCE(icsk->icsk_syn_retries) ? : READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_synack_retries) + 1; + max_retries = min_t(int, max_retries, MAX_TCP_SYNCNT); if (req->num_timeout >= max_retries) { tcp_write_err(sk); @@ -489,7 +490,7 @@ static void tcp_fastopen_synack_timer(struct sock *sk, struct request_sock *req) if (!tp->retrans_stamp) tp->retrans_stamp = tcp_time_stamp_ts(tp); tcp_reset_xmit_timer(sk, ICSK_TIME_RETRANS, - req->timeout << req->num_timeout, false); + tcp_reqsk_timeout_sk(sk, req), false); } static bool tcp_rtx_probe0_timed_out(const struct sock *sk, diff --git a/net/ipv4/udp.c b/net/ipv4/udp.c index 2e5562f353f85d..d784faf939c3b8 100644 --- a/net/ipv4/udp.c +++ b/net/ipv4/udp.c @@ -131,6 +131,15 @@ EXPORT_PER_CPU_SYMBOL_GPL(udp_memory_per_cpu_fw_alloc); #define MAX_UDP_PORTS 65536 #define PORTS_PER_CHAIN (MAX_UDP_PORTS / UDP_HTABLE_SIZE_MIN_PERNET) +static bool udp_sk_reuseport_match(struct sock *sk, struct sock *sk2) +{ + return sk2->sk_family == sk->sk_family && + ipv6_only_sock(sk2) == ipv6_only_sock(sk) && + sk2->sk_bound_dev_if == sk->sk_bound_dev_if && + sk2->sk_reuse == sk->sk_reuse && + inet_rcv_saddr_equal(sk, sk2, false); +} + static int udp_lib_lport_inuse(struct net *net, __u16 num, const struct udp_hslot *hslot, unsigned long *bitmap, @@ -154,8 +163,11 @@ static int udp_lib_lport_inuse(struct net *net, __u16 num, if (!bitmap) { if (sk2->sk_reuseport && sk->sk_reuseport && !rcu_access_pointer(sk->sk_reuseport_cb) && - uid_eq(uid, sk_uid(sk2))) - return 0; + uid_eq(uid, sk_uid(sk2))) { + if (udp_sk_reuseport_match(sk, sk2)) + return 0; + continue; + } return 1; } __set_bit(udp_sk(sk2)->udp_port_hash >> log, bitmap); @@ -188,10 +200,13 @@ static int udp_lib_lport_inuse2(struct net *net, __u16 num, if (sk2->sk_reuseport && sk->sk_reuseport && !rcu_access_pointer(sk->sk_reuseport_cb) && uid_eq(uid, sk_uid(sk2))) { - res = 0; - } else { - res = 1; + if (udp_sk_reuseport_match(sk, sk2)) { + res = 0; + break; + } + continue; } + res = 1; break; } } diff --git a/net/ipv4/udp_offload.c b/net/ipv4/udp_offload.c index b77ae2f00c626c..243bd75302d83b 100644 --- a/net/ipv4/udp_offload.c +++ b/net/ipv4/udp_offload.c @@ -519,8 +519,9 @@ struct sk_buff *__udp_gso_segment(struct sk_buff *gso_skb, * the frag_list skbs still have the IP family we segment for, * as their network headers are not rebuilt. */ - if ((skb_pagelen(gso_skb) - sizeof(*uh) == skb_shinfo(gso_skb)->gso_size) && - !(skb_shinfo(gso_skb)->gso_type & SKB_GSO_DODGY) && + if (skb_gso_fraglist_ok(gso_skb, features, sizeof(*uh), + is_ipv6 ? htons(ETH_P_IPV6) : + htons(ETH_P_IP)) && ip_hdr(skb_shinfo(gso_skb)->frag_list)->version == (is_ipv6 ? 6 : 4)) return __udp_gso_segment_list(gso_skb, features, is_ipv6); diff --git a/net/ipv6/af_inet6.c b/net/ipv6/af_inet6.c index a9b8b4b42a1af7..b85125c3f14bdf 100644 --- a/net/ipv6/af_inet6.c +++ b/net/ipv6/af_inet6.c @@ -398,10 +398,10 @@ int __inet6_bind(struct sock *sk, struct sockaddr_unsized *uaddr, int addr_len, if (!(flags & BIND_FROM_BPF)) { err = BPF_CGROUP_RUN_PROG_INET6_POST_BIND(sk); if (err) { - sk->sk_ipv6only = saved_ipv6only; - inet_reset_saddr(sk); if (sk->sk_prot->put_port) sk->sk_prot->put_port(sk); + sk->sk_ipv6only = saved_ipv6only; + inet_reset_saddr(sk); goto out; } } diff --git a/net/ipv6/calipso.c b/net/ipv6/calipso.c index 4cd0ae9313b322..d7838451db0958 100644 --- a/net/ipv6/calipso.c +++ b/net/ipv6/calipso.c @@ -263,13 +263,14 @@ static int calipso_cache_check(const unsigned char *key, static int calipso_cache_add(const unsigned char *calipso_ptr, const struct netlbl_lsm_secattr *secattr) { + int bkt_size = READ_ONCE(calipso_cache_bucketsize); int ret_val = -EPERM; u32 bkt; struct calipso_map_cache_entry *entry = NULL; struct calipso_map_cache_entry *old_entry = NULL; u32 calipso_ptr_len; - if (!calipso_cache_enabled || calipso_cache_bucketsize <= 0) + if (!calipso_cache_enabled || bkt_size <= 0) return 0; calipso_ptr_len = calipso_ptr[1]; @@ -289,7 +290,7 @@ static int calipso_cache_add(const unsigned char *calipso_ptr, bkt = entry->hash & (CALIPSO_CACHE_BUCKETS - 1); spin_lock_bh(&calipso_cache[bkt].lock); - if (calipso_cache[bkt].size < calipso_cache_bucketsize) { + if (calipso_cache[bkt].size < bkt_size) { list_add(&entry->list, &calipso_cache[bkt].list); calipso_cache[bkt].size += 1; } else { diff --git a/net/ipv6/fib6_rules.c b/net/ipv6/fib6_rules.c index 0ffd7b47a0460d..7efb0515b5c8bc 100644 --- a/net/ipv6/fib6_rules.c +++ b/net/ipv6/fib6_rules.c @@ -286,6 +286,12 @@ INDIRECT_CALLABLE_SCOPE bool fib6_rule_suppress(struct fib_rule *rule, struct rt6_info *rt = res->rt6; struct net_device *dev = NULL; + if (arg->lookup_ptr == fib6_table_lookup) { + /* fib6_table_lookup() returns 0 for reject routes. */ + return !(res->fib6_flags & RTF_REJECT) && + res->f6i->fib6_dst.plen <= rule->suppress_prefixlen; + } + if (!rt) return false; diff --git a/net/ipv6/ioam6_iptunnel.c b/net/ipv6/ioam6_iptunnel.c index cfb2c41634a0b0..e8be0d922f7463 100644 --- a/net/ipv6/ioam6_iptunnel.c +++ b/net/ipv6/ioam6_iptunnel.c @@ -254,10 +254,11 @@ static int ioam6_do_fill(struct net *net, struct sk_buff *skb) } static int ioam6_do_inline(struct net *net, struct sk_buff *skb, - struct ioam6_lwt_encap *tuninfo, + const struct ioam6_lwt_encap *tuninfo, struct dst_entry *cache_dst) { struct ipv6hdr *oldhdr, *hdr; + struct ipv6_opt_hdr *opt_hdr; int hdrlen, err; hdrlen = (tuninfo->eh.hdrlen + 1) << 3; @@ -276,12 +277,13 @@ static int ioam6_do_inline(struct net *net, struct sk_buff *skb, hdr = ipv6_hdr(skb); memmove(hdr, oldhdr, sizeof(*oldhdr)); - tuninfo->eh.nexthdr = hdr->nexthdr; skb_set_transport_header(skb, sizeof(*hdr)); skb_postpush_rcsum(skb, hdr, sizeof(*hdr) + hdrlen); - memcpy(skb_transport_header(skb), (u8 *)tuninfo, hdrlen); + opt_hdr = (struct ipv6_opt_hdr *)skb_transport_header(skb); + memcpy(opt_hdr, tuninfo, hdrlen); + opt_hdr->nexthdr = hdr->nexthdr; hdr->nexthdr = NEXTHDR_HOP; hdr->payload_len = cpu_to_be16(skb->len - sizeof(*hdr)); @@ -290,7 +292,7 @@ static int ioam6_do_inline(struct net *net, struct sk_buff *skb, } static int ioam6_do_encap(struct net *net, struct sk_buff *skb, - struct ioam6_lwt_encap *tuninfo, + const struct ioam6_lwt_encap *tuninfo, bool has_tunsrc, struct in6_addr *tunsrc, struct in6_addr *tundst, @@ -298,6 +300,7 @@ static int ioam6_do_encap(struct net *net, struct sk_buff *skb, { struct dst_entry *dst = skb_dst(skb); struct ipv6hdr *hdr, *inner_hdr; + struct ipv6_opt_hdr *opt_hdr; int hdrlen, len, err; hdrlen = (tuninfo->eh.hdrlen + 1) << 3; @@ -314,8 +317,9 @@ static int ioam6_do_encap(struct net *net, struct sk_buff *skb, skb_mac_header_rebuild(skb); skb_set_transport_header(skb, sizeof(*hdr)); - tuninfo->eh.nexthdr = NEXTHDR_IPV6; - memcpy(skb_transport_header(skb), (u8 *)tuninfo, hdrlen); + opt_hdr = (struct ipv6_opt_hdr *)skb_transport_header(skb); + memcpy(opt_hdr, tuninfo, hdrlen); + opt_hdr->nexthdr = NEXTHDR_IPV6; hdr = ipv6_hdr(skb); memcpy(hdr, inner_hdr, sizeof(*hdr)); diff --git a/net/ipv6/ip6_input.c b/net/ipv6/ip6_input.c index d332ec60f9150e..6dc1211eade6ac 100644 --- a/net/ipv6/ip6_input.c +++ b/net/ipv6/ip6_input.c @@ -479,6 +479,10 @@ void ip6_protocol_deliver_rcu(struct net *net, struct sk_buff *skb, int nexthdr, ret = INDIRECT_CALL_2(ipprot->handler, tcp_v6_rcv, udpv6_rcv, skb); if (ret > 0) { + if (unlikely(skb_headroom(skb) > SKB_MAX_RX_HEADROOM)) { + SKB_DR_SET(reason, SKB_RX_HEADROOM); + goto discard; + } if (ipprot->flags & INET6_PROTO_FINAL) { /* Not an extension header, most likely UDP * encapsulation. Use return value as nexthdr diff --git a/net/ipv6/ip6_offload.c b/net/ipv6/ip6_offload.c index 700f1861d8eb7d..01642900c0fa33 100644 --- a/net/ipv6/ip6_offload.c +++ b/net/ipv6/ip6_offload.c @@ -26,6 +26,7 @@ static int ipv6_gro_pull_exthdrs(struct sk_buff *skb, int off, int proto) { const struct net_offload *ops = NULL; struct ipv6_opt_hdr *opth; + int exthdr_cnt = 0; for (;;) { int len; @@ -38,6 +39,13 @@ static int ipv6_gro_pull_exthdrs(struct sk_buff *skb, int off, int proto) if (!(ops->flags & INET6_PROTO_GSO_EXTHDR)) break; + /* Same limit as ip6_protocol_deliver_rcu(). + * @proto is left pointing to an extension header, + * so that the caller does not aggregate this packet. + */ + if (unlikely(exthdr_cnt++ >= IP6_MAX_EXT_HDRS_CNT)) + break; + opth = skb_gro_header(skb, off + sizeof(*opth), off); if (unlikely(!opth)) break; diff --git a/net/ipv6/ip6mr.c b/net/ipv6/ip6mr.c index dd0638d3c3f95a..b7ae220d6b21de 100644 --- a/net/ipv6/ip6mr.c +++ b/net/ipv6/ip6mr.c @@ -1154,7 +1154,7 @@ static int ip6mr_cache_report(const struct mr_table *mrt, struct sk_buff *pkt, /* * Add our header */ - skb_put(skb, sizeof(*msg)); + skb_put_zero(skb, sizeof(*msg)); skb_reset_transport_header(skb); msg = (struct mrt6msg *)skb_transport_header(skb); diff --git a/net/ipv6/mcast.c b/net/ipv6/mcast.c index ecef55f261890c..bce7287ae709f1 100644 --- a/net/ipv6/mcast.c +++ b/net/ipv6/mcast.c @@ -684,7 +684,10 @@ bool inet6_mc_check(const struct sock *sk, const struct in6_addr *mc_addr, static void igmp6_group_added(struct ifmcaddr6 *mc) { struct net_device *dev = mc->idev->dev; - char buf[MAX_ADDR_LEN]; + /* RTNL might not be held: dev->type and dev->addr_len can change. + * Make sure dev_mc_{add|del}() do not use uninitialized bytes. + */ + char buf[MAX_ADDR_LEN] = {}; mc_assert_locked(mc->idev); @@ -720,7 +723,10 @@ static void igmp6_group_added(struct ifmcaddr6 *mc) static void igmp6_group_dropped(struct ifmcaddr6 *mc) { struct net_device *dev = mc->idev->dev; - char buf[MAX_ADDR_LEN]; + /* RTNL might not be held: dev->type and dev->addr_len can change. + * Make sure dev_mc_{add|del}() do not use uninitialized bytes. + */ + char buf[MAX_ADDR_LEN] = {}; mc_assert_locked(mc->idev); diff --git a/net/ipv6/mcast_snoop.c b/net/ipv6/mcast_snoop.c index 04d5fcdfa6e00b..7abf79815aa233 100644 --- a/net/ipv6/mcast_snoop.c +++ b/net/ipv6/mcast_snoop.c @@ -56,7 +56,8 @@ static int ipv6_mc_check_exthdrs(struct sk_buff *skb) if (nexthdr != IPPROTO_ICMPV6) return -ENOMSG; - skb_set_transport_header(skb, offset); + if (!skb_set_transport_header_careful(skb, offset)) + return -EINVAL; return 0; } diff --git a/net/ipv6/syncookies.c b/net/ipv6/syncookies.c index b581cb1ee2e8a9..e8d45a627ca266 100644 --- a/net/ipv6/syncookies.c +++ b/net/ipv6/syncookies.c @@ -17,6 +17,7 @@ #include #include #include +#include #define COOKIEBITS 24 /* Upper bits store count */ #define COOKIEMASK (((__u32)1 << COOKIEBITS) - 1) @@ -205,6 +206,8 @@ struct sock *cookie_v6_check(struct sock *sk, struct sk_buff *skb) ireq->ir_v6_rmt_addr = ipv6_hdr(skb)->saddr; ireq->ir_v6_loc_addr = ipv6_hdr(skb)->daddr; + ireq->ir_rmt_addr = LOOPBACK4_IPV6; + ireq->ir_loc_addr = LOOPBACK4_IPV6; if (security_inet_conn_request(sk, skb, req)) { SKB_DR_SET(reason, SECURITY_HOOK); @@ -273,6 +276,9 @@ struct sock *cookie_v6_check(struct sock *sk, struct sk_buff *skb) ireq->rcv_wscale = rcv_wscale; ireq->ecn_ok &= cookie_ecn_ok(net, dst); tcp_rsk(req)->accecn_ok = ireq->ecn_ok && cookie_accecn_ok(th); + /* SYN-ACK was not sent by the kernel if req->syncookie is set. */ + if (!req->syncookie) + tcp_rsk(req)->syn_ect_snt = READ_ONCE(np->tclass) & INET_ECN_MASK; ret = tcp_get_cookie_sock(sk, skb, req, dst); if (!ret) { diff --git a/net/ipv6/tcpv6_offload.c b/net/ipv6/tcpv6_offload.c index eec3778855eb89..71feb92aeac28a 100644 --- a/net/ipv6/tcpv6_offload.c +++ b/net/ipv6/tcpv6_offload.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -177,12 +178,16 @@ static struct sk_buff *tcp6_gso_segment(struct sk_buff *skb, return ERR_PTR(-EINVAL); if (skb_shinfo(skb)->gso_type & SKB_GSO_FRAGLIST) { - struct tcphdr *th = tcp_hdr(skb); + int err; - if ((skb_pagelen(skb) - th->doff * 4 == skb_shinfo(skb)->gso_size) && - !(skb_shinfo(skb)->gso_type & SKB_GSO_DODGY)) + if (skb_gso_fraglist_ok(skb, features, tcp_hdrlen(skb), + htons(ETH_P_IPV6))) return __tcp6_gso_segment_list(skb, features); + err = skb_cow_head(skb, 0); + if (err < 0) + return ERR_PTR(err); + skb->ip_summed = CHECKSUM_NONE; } diff --git a/net/ipv6/udp.c b/net/ipv6/udp.c index 9dcefa16252235..a6886a0432f973 100644 --- a/net/ipv6/udp.c +++ b/net/ipv6/udp.c @@ -651,12 +651,13 @@ static struct sock *__udp6_lib_err_encap(struct net *net, network_offset = skb_network_offset(skb); transport_offset = skb_transport_offset(skb); + /* Transport header needs to point to the UDP header */ + if (unlikely(!skb_set_transport_header_careful(skb, offset))) + return ERR_PTR(-EINVAL); + /* Network header needs to point to the outer IPv6 header inside ICMP */ skb_reset_network_header(skb); - /* Transport header needs to point to the UDP header */ - skb_set_transport_header(skb, offset); - if (sk) { up = udp_sk(sk); diff --git a/net/kcm/kcmsock.c b/net/kcm/kcmsock.c index a7f94d42036fb1..ca789812124e80 100644 --- a/net/kcm/kcmsock.c +++ b/net/kcm/kcmsock.c @@ -30,6 +30,7 @@ #include #include #include +#include #include #include @@ -1259,9 +1260,10 @@ static int kcm_attach(struct socket *sock, struct socket *csock, lock_sock(csk); - /* Only allow TCP sockets to be attached for now */ - if ((csk->sk_family != AF_INET && csk->sk_family != AF_INET6) || - csk->sk_protocol != IPPROTO_TCP) { + /* Only allow TCP sockets to be attached for now. A raw socket + * created with IPPROTO_TCP has that sk_protocol but no icsk. + */ + if (!sk_is_tcp(csk)) { err = -EOPNOTSUPP; goto out; } @@ -1272,6 +1274,12 @@ static int kcm_attach(struct socket *sock, struct socket *csock, goto out; } + /* KCM and ULPs cannot share the receive path and socket callbacks. */ + if (inet_csk_has_ulp(csk)) { + err = -EOPNOTSUPP; + goto out; + } + psock = kmem_cache_zalloc(kcm_psockp, GFP_KERNEL); if (!psock) { err = -ENOMEM; @@ -1305,6 +1313,7 @@ static int kcm_attach(struct socket *sock, struct socket *csock, psock->save_write_space = csk->sk_write_space; psock->save_state_change = csk->sk_state_change; csk->sk_user_data = psock; + tcp_sk(csk)->kcm_attached = true; WRITE_ONCE(csk->sk_data_ready, psock_data_ready); WRITE_ONCE(csk->sk_write_space, psock_write_space); csk->sk_state_change = psock_state_change; @@ -1386,6 +1395,7 @@ static void kcm_unattach(struct kcm_psock *psock) WRITE_ONCE(csk->sk_write_space, psock->save_write_space); csk->sk_state_change = psock->save_state_change; strp_stop(&psock->strp); + tcp_sk(csk)->kcm_attached = false; if (WARN_ON(psock->rx_kcm)) { write_unlock_bh(&csk->sk_callback_lock); diff --git a/net/key/af_key.c b/net/key/af_key.c index d215b33b7492c2..ab4aaca9147066 100644 --- a/net/key/af_key.c +++ b/net/key/af_key.c @@ -2712,11 +2712,18 @@ static int dump_sp(struct xfrm_policy *xp, int dir, int count, void *ptr) if (!pfkey_can_dump(&pfk->sk)) return -ENOBUFS; + /* Both halves derive the size from xfrm_vec[].encap_family, so + * hold xp->lock against a concurrent xfrm_policy_migrate(). + */ + read_lock(&xp->lock); out_skb = pfkey_xfrm_policy2msg_prep(xp); - if (IS_ERR(out_skb)) + if (IS_ERR(out_skb)) { + read_unlock(&xp->lock); return PTR_ERR(out_skb); + } err = pfkey_xfrm_policy2msg(out_skb, xp, dir); + read_unlock(&xp->lock); if (err < 0) { kfree_skb(out_skb); return err; diff --git a/net/l2tp/l2tp_netlink.c b/net/l2tp/l2tp_netlink.c index 89ef04c78787df..a07009d4cb0099 100644 --- a/net/l2tp/l2tp_netlink.c +++ b/net/l2tp/l2tp_netlink.c @@ -910,14 +910,8 @@ static const struct nla_policy l2tp_nl_policy[L2TP_ATTR_MAX + 1] = { [L2TP_ATTR_MTU] = { .type = NLA_U16, }, [L2TP_ATTR_MRU] = { .type = NLA_U16, }, [L2TP_ATTR_STATS] = { .type = NLA_NESTED, }, - [L2TP_ATTR_IP6_SADDR] = { - .type = NLA_BINARY, - .len = sizeof(struct in6_addr), - }, - [L2TP_ATTR_IP6_DADDR] = { - .type = NLA_BINARY, - .len = sizeof(struct in6_addr), - }, + [L2TP_ATTR_IP6_SADDR] = NLA_POLICY_EXACT_LEN(sizeof(struct in6_addr)), + [L2TP_ATTR_IP6_DADDR] = NLA_POLICY_EXACT_LEN(sizeof(struct in6_addr)), [L2TP_ATTR_IFNAME] = { .type = NLA_NUL_STRING, .len = IFNAMSIZ - 1, diff --git a/net/mac802154/llsec.c b/net/mac802154/llsec.c index 85452ef9a58c69..32565f18897e56 100644 --- a/net/mac802154/llsec.c +++ b/net/mac802154/llsec.c @@ -1019,6 +1019,8 @@ int mac802154_llsec_decrypt(struct mac802154_llsec *sec, struct sk_buff *skb) return 0; if (hdr.fc.version == 0) return -EINVAL; + if (hdr.sec.level == IEEE802154_SCF_SECLEVEL_NONE) + return -EINVAL; read_lock_bh(&sec->lock); if (!sec->params.enabled) { diff --git a/net/mptcp/mptcp_diag.c b/net/mptcp/mptcp_diag.c index 136c2d05c0eeb8..62d8f1fa7a4088 100644 --- a/net/mptcp/mptcp_diag.c +++ b/net/mptcp/mptcp_diag.c @@ -193,10 +193,9 @@ static void mptcp_diag_get_info(struct sock *sk, struct inet_diag_msg *r, void *_info) { struct mptcp_sock *msk = mptcp_sk(sk); - struct mptcp_info *info = _info; r->idiag_rqueue = sk_rmem_alloc_get(sk) + - READ_ONCE(mptcp_sk(sk)->backlog_len); + READ_ONCE(msk->backlog_len); r->idiag_wqueue = sk_wmem_alloc_get(sk); if (inet_sk_state_load(sk) == TCP_LISTEN) { @@ -210,11 +209,29 @@ static void mptcp_diag_get_info(struct sock *sk, struct inet_diag_msg *r, r->idiag_wqueue = READ_ONCE(lsk->sk_max_ack_backlog); } } +} - if (!info) - return; +static int mptcp_diag_get_aux(struct sock *sk, bool net_admin, + struct sk_buff *skb) +{ + struct mptcp_sock *msk = mptcp_sk(sk); + struct mptcp_info *info; + struct nlattr *attr; + attr = nla_reserve_64bit(skb, INET_DIAG_INFO, + sizeof(struct mptcp_info), INET_DIAG_PAD); + if (!attr) + return -EMSGSIZE; + + info = nla_data(attr); mptcp_diag_fill_info(msk, info); + /* Only export seq related counters to user with CAP_NET_ADMIN */ + if (!net_admin) { + info->mptcpi_write_seq = 0; + info->mptcpi_snd_una = 0; + info->mptcpi_rcv_nxt = 0; + } + return 0; } static const struct inet_diag_handler mptcp_diag_handler = { @@ -222,8 +239,9 @@ static const struct inet_diag_handler mptcp_diag_handler = { .dump = mptcp_diag_dump, .dump_one = mptcp_diag_dump_one, .idiag_get_info = mptcp_diag_get_info, + .idiag_get_aux = mptcp_diag_get_aux, .idiag_type = IPPROTO_MPTCP, - .idiag_info_size = sizeof(struct mptcp_info), + .idiag_info_size = 0, }; static int __init mptcp_diag_init(void) diff --git a/net/mptcp/options.c b/net/mptcp/options.c index 02e785a14b8a5c..617358ff7f990c 100644 --- a/net/mptcp/options.c +++ b/net/mptcp/options.c @@ -982,6 +982,8 @@ static bool check_fully_established(struct mptcp_sock *msk, struct sock *ssk, struct sk_buff *skb, struct mptcp_options_received *mp_opt) { + struct sock *sk = (struct sock *)msk; + /* here we can process OoO, in-window pkts, only in-sequence 4th ack * will make the subflow fully established */ @@ -1033,6 +1035,10 @@ static bool check_fully_established(struct mptcp_sock *msk, struct sock *ssk, MPTCP_INC_STATS(sock_net(ssk), MPTCP_MIB_FALLBACKFAILED); goto reset; } + /* this ACK will not reach the fallback path: push from here */ + mptcp_data_lock(sk); + __mptcp_check_push(sk, ssk); + mptcp_data_unlock(sk); return false; } @@ -1043,9 +1049,11 @@ static bool check_fully_established(struct mptcp_sock *msk, struct sock *ssk, if (mp_opt->deny_join_id0) WRITE_ONCE(msk->pm.remote_deny_join_id0, true); - mptcp_data_lock((struct sock *)msk); + mptcp_data_lock(sk); __mptcp_subflow_fully_established(msk, subflow, mp_opt); - mptcp_data_unlock((struct sock *)msk); + if (tcp_sk(ssk)->syn_fastopen_child) + __mptcp_check_push(sk, ssk); + mptcp_data_unlock(sk); check_notify: /* if the subflow is not already linked into the conn_list, we can't @@ -1120,9 +1128,11 @@ static void rwin_update(struct mptcp_sock *msk, struct sock *ssk, static void ack_update_msk(struct mptcp_sock *msk, struct sock *ssk, + const struct sk_buff *skb, struct mptcp_options_received *mp_opt) { u64 new_wnd_end, new_snd_una, old_snd_una; + u32 win = ntohs(tcp_hdr(skb)->window); struct sock *sk = (struct sock *)msk; u64 snd_nxt; @@ -1143,7 +1153,12 @@ static void ack_update_msk(struct mptcp_sock *msk, after64(new_snd_una, snd_nxt))) new_snd_una = old_snd_una; - new_wnd_end = new_snd_una + tcp_sk(ssk)->snd_wnd; + /* What the peer announced: tcp_sk(ssk)->snd_wnd can be larger, see + * mptcp_check_allowed_size(), and is not always updated. + */ + if (likely(!tcp_hdr(skb)->syn)) + win <<= tcp_sk(ssk)->rx_opt.snd_wscale; + new_wnd_end = new_snd_una + win; if (after64(new_wnd_end, msk->wnd_end)) WRITE_ONCE(msk->wnd_end, new_wnd_end); @@ -1313,7 +1328,7 @@ bool mptcp_incoming_options(struct sock *sk, struct sk_buff *skb) * monodirectional flows will stuck */ if (mp_opt.use_ack) - ack_update_msk(msk, sk, &mp_opt); + ack_update_msk(msk, sk, skb, &mp_opt); rwin_update(msk, sk, skb); /* Zero-data-length packets are dropped by the caller and not diff --git a/net/mptcp/protocol.c b/net/mptcp/protocol.c index 8968db58083ef4..bba84018cb671d 100644 --- a/net/mptcp/protocol.c +++ b/net/mptcp/protocol.c @@ -619,12 +619,6 @@ static void mptcp_set_timeout(struct sock *sk) __mptcp_set_timeout(sk, tout); } -static inline bool tcp_can_send_ack(const struct sock *ssk) -{ - return !((1 << inet_sk_state_load(ssk)) & - (TCPF_SYN_SENT | TCPF_SYN_RECV | TCPF_TIME_WAIT | TCPF_CLOSE | TCPF_LISTEN)); -} - void __mptcp_subflow_send_ack(struct sock *ssk) { if (tcp_can_send_ack(ssk)) @@ -2130,8 +2124,10 @@ static int mptcp_sendmsg(struct sock *sk, struct msghdr *msg, size_t len) return copied; do_error: - if (copied) + if (copied) { + __mptcp_push_pending(sk, msg->msg_flags); goto out; + } copied = sk_stream_error(sk, msg->msg_flags, ret); goto out; @@ -3041,7 +3037,8 @@ void mptcp_reset_tout_timer(struct mptcp_sock *msk, unsigned long fail_tout) return; close_timeout = (unsigned long)inet_csk(sk)->icsk_mtup.probe_timestamp - - tcp_jiffies32 + jiffies + mptcp_close_timeout(sk); + tcp_jiffies32; + close_timeout += jiffies + mptcp_close_timeout(sk); /* the close timeout takes precedence on the fail one, and here at least one of * them is active diff --git a/net/mptcp/protocol.h b/net/mptcp/protocol.h index 011e73d04ee604..7d226ee38315da 100644 --- a/net/mptcp/protocol.h +++ b/net/mptcp/protocol.h @@ -1333,7 +1333,11 @@ static inline bool mptcp_try_fallback(struct sock *ssk, int fb_mib) msk = mptcp_sk(sk); if (!__mptcp_try_fallback(msk, fb_mib)) return false; - if (READ_ONCE(msk->snd_data_fin_enable) && !(ssk->sk_shutdown & SEND_SHUTDOWN)) { + + /* no FIN before new data: see mptcp_check_send_data_fin() */ + if (READ_ONCE(msk->snd_data_fin_enable) && + !before64(READ_ONCE(msk->snd_nxt) + 1, READ_ONCE(msk->write_seq)) && + !(ssk->sk_shutdown & SEND_SHUTDOWN)) { gfp_t saved_allocation = ssk->sk_allocation; /* we are in a atomic (BH) scope, override ssk default for data diff --git a/net/mptcp/subflow.c b/net/mptcp/subflow.c index 00677fb3efcdc9..6f07544bfe40bc 100644 --- a/net/mptcp/subflow.c +++ b/net/mptcp/subflow.c @@ -1496,7 +1496,7 @@ static bool subflow_check_data_avail(struct sock *ssk) skb = skb_peek(&ssk->sk_receive_queue); subflow->map_valid = 1; subflow->map_data_len = skb->len; - subflow->map_subflow_seq = tcp_sk(ssk)->copied_seq - subflow->ssn_offset; + subflow->map_subflow_seq = TCP_SKB_CB(skb)->seq - subflow->ssn_offset; subflow->map_seq = __mptcp_expand_seq(subflow->map_seq, subflow->iasn + TCP_SKB_CB(skb)->seq - diff --git a/net/netfilter/ipvs/ip_vs_conn.c b/net/netfilter/ipvs/ip_vs_conn.c index 94f25fb7d87e45..83d8a9153a342f 100644 --- a/net/netfilter/ipvs/ip_vs_conn.c +++ b/net/netfilter/ipvs/ip_vs_conn.c @@ -293,7 +293,6 @@ static inline int ip_vs_conn_hash(struct ip_vs_conn *cp) cp->flags |= IP_VS_CONN_F_HASHED; WRITE_ONCE(cp->hn0.hash_key, hash_key); WRITE_ONCE(cp->hn1.hash_key, hash_key2); - refcount_inc(&cp->refcnt); hlist_bl_add_head_rcu(&cp->hn0.node, head); if (use2) hlist_bl_add_head_rcu(&cp->hn1.node, head2); @@ -319,11 +318,27 @@ static inline bool ip_vs_conn_unlink(struct ip_vs_conn *cp) struct hlist_bl_head *head, *head2; u32 hash_key, hash_key2; struct ip_vs_rht *t; - bool ret = false; bool use2; + /* No more users and no running/pending timer except us? */ + if (!refcount_dec_if_one(&cp->refcnt)) + return false; + + /* The ONE_PACKET connection is special: + * - the flag is present only for normal connections, not for templates + * - its timer is never started + * - it is never hashed, so you can not find it and delete it + * - it is not synced + * - it has only one user + * - it is freed after use immediately + */ if (cp->flags & IP_VS_CONN_F_ONE_PACKET) - return refcount_dec_if_one(&cp->refcnt); + return true; + + /* Add the needed ACQUIRE barrier between the above + * refcount_dec_if_one() call and the read of cp fields + */ + smp_acquire__after_ctrl_dep(); rcu_read_lock(); local_bh_disable(); @@ -337,15 +352,11 @@ static inline bool ip_vs_conn_unlink(struct ip_vs_conn *cp) false /* new_hash2 */, &head, &head2); if (cp->flags & IP_VS_CONN_F_HASHED) { - /* Decrease refcnt and unlink conn only if we are last user */ - if (use2 == ip_vs_conn_use_hash2(cp) && - refcount_dec_if_one(&cp->refcnt)) { - hlist_bl_del_rcu(&cp->hn0.node); - if (use2) - hlist_bl_del_rcu(&cp->hn1.node); - cp->flags &= ~IP_VS_CONN_F_HASHED; - ret = true; - } + /* Unlink conn as we are the last user */ + hlist_bl_del_rcu(&cp->hn0.node); + if (use2) + hlist_bl_del_rcu(&cp->hn1.node); + cp->flags &= ~IP_VS_CONN_F_HASHED; } conn_tab_unlock(head, head2); @@ -353,7 +364,7 @@ static inline bool ip_vs_conn_unlink(struct ip_vs_conn *cp) local_bh_enable(); rcu_read_unlock(); - return ret; + return true; } @@ -579,6 +590,8 @@ struct ip_vs_conn *ip_vs_conn_out_get(const struct ip_vs_conn_param *p) ip_vs_addr_equal(p->af, p->vaddr, &cp->caddr) && ip_vs_addr_equal(p->af, p->caddr, saddr) && + (!p->vport ^ + (!(cp->flags & IP_VS_CONN_F_NO_CPORT))) && p->protocol == cp->protocol) { if (__ip_vs_conn_get(cp)) goto out; @@ -621,9 +634,12 @@ static void __ip_vs_conn_put_timer(struct ip_vs_conn *cp) { unsigned long t = (cp->flags & IP_VS_CONN_F_ONE_PACKET) ? 0 : cp->timeout; - mod_timer(&cp->timer, jiffies+t); - __ip_vs_conn_put(cp); + /* Handoff our reference to the timer if it was just armed, + * put the reference if timer was already pending. + */ + if (mod_timer(&cp->timer, jiffies + t)) + __ip_vs_conn_put(cp); } void ip_vs_conn_put(struct ip_vs_conn *cp) @@ -1154,7 +1170,7 @@ ip_vs_bind_dest(struct ip_vs_conn *cp, struct ip_vs_dest *dest) atomic_inc(&dest->activeconns); tc = atomic_inc_return(&dest->totalconns); if (tc >= READ_ONCE(dest->u_threshold_val)) - ip_vs_dest_update_overload(dest, true); + ip_vs_dest_update_overload(dest); } else { /* It is a persistent connection/template, so increase the persistent connection counter */ @@ -1247,7 +1263,7 @@ static inline void ip_vs_unbind_dest(struct ip_vs_conn *cp) atomic_dec(&dest->activeconns); tc = atomic_fetch_dec(&dest->totalconns); if (tc <= READ_ONCE(dest->l_threshold_val)) - ip_vs_dest_update_overload(dest, false); + ip_vs_dest_update_overload(dest); } else { /* It is a persistent connection/template, so decrease the persistent connection counter */ @@ -1322,36 +1338,48 @@ static void ip_vs_conn_rcu_free(struct rcu_head *head) kmem_cache_free(ip_vs_conn_cachep, cp); } -/* Try to delete connection while not holding reference */ -static void ip_vs_conn_del(struct ip_vs_conn *cp) +/* Try to steal the reference from the pending timer. + * It can be called concurrently and always under RCU lock + * to protect from connection deletion from others. + */ +static bool ip_vs_conn_del_reference(struct ip_vs_conn *cp) { - if (timer_delete(&cp->timer)) { - /* Drop cp->control chain too */ - if (cp->control) - cp->timeout = 0; - ip_vs_conn_expire(&cp->timer); - } + /* Steal reference from the pending timer */ + if (!timer_delete(&cp->timer)) + return false; + + /* Drop cp->control chain too */ + if (cp->control) + cp->timeout = 0; + return true; } -/* Try to delete connection while holding reference */ -static void ip_vs_conn_del_put(struct ip_vs_conn *cp) +/* Try to delete connection while not holding reference. + * Used when we need to remove the connection immediately + * and without overloading the timer processing. + * OTOH, we use ip_vs_conn_expire_now() when we prefer to + * leave the current context (packet processing) and to + * remove the connection from timer. + */ +static void ip_vs_conn_del(struct ip_vs_conn *cp) { - if (timer_delete(&cp->timer)) { - /* Drop cp->control chain too */ - if (cp->control) - cp->timeout = 0; - __ip_vs_conn_put(cp); + if (ip_vs_conn_del_reference(cp)) ip_vs_conn_expire(&cp->timer); - } else { - __ip_vs_conn_put(cp); - } } +/* Connection is removed in the following steps: + * - timer expires (with ref) or connection is deleted (with stolen ref) + * - there should be no more users except us (pending/running timer, + * n_control>0 or refcnt>1) + */ static void ip_vs_conn_expire(struct timer_list *t) { struct ip_vs_conn *cp = timer_container_of(cp, t, timer); struct netns_ipvs *ipvs = cp->ipvs; + rcu_read_lock(); + +repeat: /* * do I control anybody? */ @@ -1361,23 +1389,17 @@ static void ip_vs_conn_expire(struct timer_list *t) /* Unlink conn if not referenced anymore */ if (likely(ip_vs_conn_unlink(cp))) { struct ip_vs_conn *ct = cp->control; - - /* delete the timer if it is activated by other users */ - timer_delete(&cp->timer); + bool next = false; /* does anybody control me? */ if (ct) { - bool has_ref = !cp->timeout && __ip_vs_conn_get(ct); - ip_vs_control_del(cp); /* Drop CTL or non-assured TPL if not used anymore */ - if (has_ref && !atomic_read(&ct->n_control) && + if (!cp->timeout && !atomic_read(&ct->n_control) && (!(ct->flags & IP_VS_CONN_F_TEMPLATE) || !(ct->state & IP_VS_CTPL_S_ASSURED))) { IP_VS_DBG(4, "drop controlling connection\n"); - ip_vs_conn_del_put(ct); - } else if (has_ref) { - __ip_vs_conn_put(ct); + next = ip_vs_conn_del_reference(ct); } } @@ -1405,7 +1427,11 @@ static void ip_vs_conn_expire(struct timer_list *t) else call_rcu(&cp->rcu_head, ip_vs_conn_rcu_free); atomic_dec(&ipvs->conn_count); - return; + if (next) { + cp = ct; + goto repeat; + } + goto out; } expire_later: @@ -1413,13 +1439,16 @@ static void ip_vs_conn_expire(struct timer_list *t) refcount_read(&cp->refcnt), atomic_read(&cp->n_control)); - refcount_inc(&cp->refcnt); - cp->timeout = 60*HZ; + if (cp->timeout || atomic_read(&cp->n_control)) + cp->timeout = 60 * HZ; if (ipvs->sync_state & IP_VS_STATE_MASTER) ip_vs_sync_conn(ipvs, cp, sysctl_sync_threshold(ipvs)); __ip_vs_conn_put_timer(cp); + +out: + rcu_read_unlock(); } /* Modify timer, so that it expires as soon as possible. @@ -1432,7 +1461,7 @@ static void ip_vs_conn_expire(struct timer_list *t) void ip_vs_conn_expire_now(struct ip_vs_conn *cp) { /* Using mod_timer_pending will ensure the timer is not - * modified after the final timer_delete in ip_vs_conn_expire. + * started without giving it new reference. */ if (timer_pending(&cp->timer) && time_after(cp->timer.expires, jiffies)) @@ -1500,9 +1529,9 @@ ip_vs_conn_new(const struct ip_vs_conn_param *p, int dest_af, spin_lock_init(&cp->lock); /* - * Set the entry is referenced by the current thread before hashing - * it in the table, so that other thread run ip_vs_random_dropentry - * but cannot drop this entry. + * Set the entry as referenced by the current thread before starting + * the timer and giving it our reference to allow other threads to + * run ip_vs_random_dropentry() or any deletion method safely. */ refcount_set(&cp->refcnt, 1); diff --git a/net/netfilter/ipvs/ip_vs_core.c b/net/netfilter/ipvs/ip_vs_core.c index 8a3c880fdb266e..f3eb72e95024dd 100644 --- a/net/netfilter/ipvs/ip_vs_core.c +++ b/net/netfilter/ipvs/ip_vs_core.c @@ -1305,6 +1305,7 @@ static inline bool is_new_conn_expected(const struct ip_vs_conn *cp, * In fwmark-VS actual vaddr and vport are unknown to IPVS * 2) Real Server and Virtual Service were NOT configured without port: * This is to allow match of different VS to the same RS ip-addr + * 3) Client port is not 0 */ struct ip_vs_conn *ip_vs_new_conn_out(struct ip_vs_service *svc, struct ip_vs_dest *dest, @@ -1328,7 +1329,7 @@ struct ip_vs_conn *ip_vs_new_conn_out(struct ip_vs_service *svc, /* check pre-requisites are satisfied */ if (svc->fwmark) return NULL; - if (!vport || !dport) + if (!vport || !dport || !cport) return NULL; /* for persistent service first create connection template */ diff --git a/net/netfilter/ipvs/ip_vs_ctl.c b/net/netfilter/ipvs/ip_vs_ctl.c index ce9fe20d6106a8..be818bf7d3806c 100644 --- a/net/netfilter/ipvs/ip_vs_ctl.c +++ b/net/netfilter/ipvs/ip_vs_ctl.c @@ -64,7 +64,8 @@ int ip_vs_get_debug_level(void) /* Protos */ -static void __ip_vs_del_service(struct ip_vs_service *svc, bool cleanup); +static void __ip_vs_del_service(struct ip_vs_service *svc, + struct list_head *dest_trash, bool cleanup); #ifdef CONFIG_IP_VS_IPV6 @@ -918,6 +919,11 @@ static void ip_vs_rs_hash(struct netns_ipvs *ipvs, struct ip_vs_dest *dest) */ hash = ip_vs_rs_hashkey(dest->af, &dest->addr, port); + /* Need RCU grace period when rehashing */ + if (dest->need_gp) { + cond_synchronize_rcu(dest->rcu_state); + dest->need_gp = 0; + } hlist_add_head_rcu(&dest->d_list, &ipvs->rs_table[hash]); dest->in_rs_table = 1; } @@ -1111,6 +1117,8 @@ ip_vs_trash_get_dest(struct ip_vs_service *svc, int dest_af, struct ip_vs_dest *dest; struct netns_ipvs *ipvs = svc->ipvs; + lockdep_assert_held(&ipvs->service_mutex); + /* * Find the destination in trash */ @@ -1144,24 +1152,57 @@ ip_vs_trash_get_dest(struct ip_vs_service *svc, int dest_af, return dest; } -/* Put destination in trash */ -static void ip_vs_trash_put_dest(struct netns_ipvs *ipvs, +/* Add destination in temp list for trash */ +static void ip_vs_trash_add_dest(struct netns_ipvs *ipvs, struct ip_vs_dest *dest, unsigned long istart, - bool cleanup) + struct list_head *dest_trash) { - spin_lock_bh(&ipvs->dest_trash_lock); IP_VS_DBG_BUF(3, "Moving dest %s:%u into trash, dest->refcnt=%d\n", IP_VS_DBG_ADDR(dest->af, &dest->addr), ntohs(dest->port), refcount_read(&dest->refcnt)); + /* dest lives in trash with reference */ + list_add(&dest->t_list, dest_trash); + dest->idle_start = istart; +} + +/* Put destinations in trash */ +static void ip_vs_trash_put_dests(struct netns_ipvs *ipvs, + struct list_head *dest_trash, bool cleanup) +{ + spin_lock_bh(&ipvs->dest_trash_lock); if (list_empty(&ipvs->dest_trash) && !cleanup) mod_timer(&ipvs->dest_trash_timer, jiffies + (IP_VS_DEST_TRASH_PERIOD >> 1)); - /* dest lives in trash with reference */ - list_add(&dest->t_list, &ipvs->dest_trash); - dest->idle_start = istart; + list_splice(dest_trash, &ipvs->dest_trash); spin_unlock_bh(&ipvs->dest_trash_lock); } +/* Put destination back in trash */ +static void ip_vs_trash_put_back(struct netns_ipvs *ipvs, + struct ip_vs_dest *dest) +{ + LIST_HEAD(dest_trash); + + ip_vs_trash_add_dest(ipvs, dest, dest->idle_start, &dest_trash); + ip_vs_trash_put_dests(ipvs, &dest_trash, false); +} + +/* Put destinations in trash and save the RCU state */ +static void ip_vs_trash_save_dests(struct netns_ipvs *ipvs, + struct list_head *dest_trash, bool cleanup) +{ + struct ip_vs_dest *dest; + unsigned long rcu_state; + + if (!list_empty(dest_trash)) { + /* Remember when dests were removed and added to dest_trash */ + rcu_state = get_state_synchronize_rcu(); + list_for_each_entry(dest, dest_trash, t_list) + dest->rcu_state = rcu_state; + ip_vs_trash_put_dests(ipvs, dest_trash, cleanup); + } +} + static void ip_vs_dest_rcu_free(struct rcu_head *head) { struct ip_vs_dest *dest; @@ -1304,12 +1345,12 @@ void ip_vs_stats_free(struct ip_vs_stats *stats) } } -/* Update overload flag based on number of dest conns and lower/upper +/* Update overload state based on number of dest conns and lower/upper * connection thresholds: - * - conns reach u_threshold and exceed it: set the flag - * - conns go below l_threshold (or 75% of u_threshold): clear the flag + * - conns reach u_threshold and exceed it: set the overload state + * - conns go below l_threshold (or 75% of u_threshold): clear the state */ -static void __ip_vs_dest_update_overload(struct ip_vs_dest *dest, bool overload) +static void __ip_vs_dest_update_overload(struct ip_vs_dest *dest) { int conns; u32 l, u; @@ -1320,10 +1361,18 @@ static void __ip_vs_dest_update_overload(struct ip_vs_dest *dest, bool overload) /* 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)) { + if (conns >= (ip_vs_dest_is_overloaded(dest) ? l : u)) { WRITE_ONCE(dest->u_threshold_val, INT_MAX); WRITE_ONCE(dest->l_threshold_val, l); - return; + /* Commit thresholds before repeating the check, + * it is paired with atomic_fetch_dec() in + * ip_vs_unbind_dest() to avoid entering the + * overload state forever. + */ + smp_mb(); + conns = atomic_read(&dest->totalconns); + if (conns >= l) + return; } } @@ -1331,10 +1380,10 @@ static void __ip_vs_dest_update_overload(struct ip_vs_dest *dest, bool overload) WRITE_ONCE(dest->l_threshold_val, 0); } -void ip_vs_dest_update_overload(struct ip_vs_dest *dest, bool overload) +void ip_vs_dest_update_overload(struct ip_vs_dest *dest) { spin_lock_bh(&dest->dst_lock); - __ip_vs_dest_update_overload(dest, overload); + __ip_vs_dest_update_overload(dest); spin_unlock_bh(&dest->dst_lock); } @@ -1369,8 +1418,16 @@ __ip_vs_update_dest(struct ip_vs_service *svc, struct ip_vs_dest *dest, if ((udest->conn_flags & IP_VS_CONN_F_FWD_MASK) != IP_VS_DFWD_METHOD(dest) || udest->tun_type != dest->tun_type || - udest->tun_port != dest->tun_port) + udest->tun_port != dest->tun_port) { + bool unlinked = dest->in_rs_table; + ip_vs_rs_unhash(dest); + if (unlinked) { + dest->rcu_state = get_state_synchronize_rcu(); + /* Need grace period in this or next dest update */ + dest->need_gp = 1; + } + } /* set the tunnel info */ dest->tun_type = udest->tun_type; @@ -1406,13 +1463,10 @@ __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); - overload = ip_vs_dest_is_overloaded(dest); - __ip_vs_dest_update_overload(dest, overload); + __ip_vs_dest_update_overload(dest); spin_unlock_bh(&dest->dst_lock); } @@ -1477,6 +1531,7 @@ ip_vs_new_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest) if (ret < 0) goto err_stats; + dest->u_threshold_val = INT_MAX; dest->af = udest->af; dest->protocol = svc->protocol; dest->vaddr = svc->addr; @@ -1556,6 +1611,11 @@ ip_vs_add_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest) dest = ip_vs_trash_get_dest(svc, udest->af, &daddr, dport); if (dest != NULL) { + /* Readers may still follow the n_list, d_list or estimator list + * links. Wait before reusing any of them. + */ + cond_synchronize_rcu(dest->rcu_state); + IP_VS_DBG_BUF(3, "Get destination %s:%u from trash, " "dest->refcnt=%d, service %u/%s:%u\n", IP_VS_DBG_ADDR(udest->af, &daddr), ntohs(dport), @@ -1566,11 +1626,14 @@ ip_vs_add_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest) ret = ip_vs_start_estimator(svc->ipvs, &dest->stats); /* On error put back dest into the trash */ - if (ret < 0) - ip_vs_trash_put_dest(svc->ipvs, dest, dest->idle_start, - false); - else + if (ret < 0) { + ip_vs_trash_put_back(svc->ipvs, dest); + } else { + /* need_gp matters only on dest edit, reinit it */ + dest->need_gp = 0; + __ip_vs_update_dest(svc, dest, udest, 1); + } } else { /* * Allocate and initialize the dest structure @@ -1634,7 +1697,7 @@ ip_vs_edit_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest) * Delete a destination (must be already unlinked from the service) */ static void __ip_vs_del_dest(struct netns_ipvs *ipvs, struct ip_vs_dest *dest, - bool cleanup) + struct list_head *dest_trash, bool cleanup) { ip_vs_stop_estimator(ipvs, &dest->stats); @@ -1643,7 +1706,7 @@ static void __ip_vs_del_dest(struct netns_ipvs *ipvs, struct ip_vs_dest *dest, */ ip_vs_rs_unhash(dest); - ip_vs_trash_put_dest(ipvs, dest, 0, cleanup); + ip_vs_trash_add_dest(ipvs, dest, 0, dest_trash); /* Queue up delayed work to expire all no destination connections. * No-op when CONFIG_SYSCTL is disabled. @@ -1693,6 +1756,7 @@ ip_vs_del_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest) { struct ip_vs_dest *dest; __be16 dport = udest->port; + LIST_HEAD(dest_trash); /* We use function that requires RCU lock */ rcu_read_lock(); @@ -1712,7 +1776,9 @@ ip_vs_del_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest) /* * Delete the destination */ - __ip_vs_del_dest(svc->ipvs, dest, false); + __ip_vs_del_dest(svc->ipvs, dest, &dest_trash, false); + + ip_vs_trash_save_dests(svc->ipvs, &dest_trash, false); return 0; } @@ -2057,7 +2123,8 @@ ip_vs_edit_service(struct ip_vs_service *svc, struct ip_vs_service_user_kern *u) * - The service must be unlinked, unlocked and not referenced! * - We are called under _bh lock */ -static void __ip_vs_del_service(struct ip_vs_service *svc, bool cleanup) +static void __ip_vs_del_service(struct ip_vs_service *svc, + struct list_head *dest_trash, bool cleanup) { struct ip_vs_dest *dest, *nxt; struct ip_vs_scheduler *old_sched; @@ -2091,7 +2158,7 @@ static void __ip_vs_del_service(struct ip_vs_service *svc, bool cleanup) */ list_for_each_entry_safe(dest, nxt, &svc->destinations, n_list) { __ip_vs_unlink_dest(svc, dest, 0); - __ip_vs_del_dest(svc->ipvs, dest, cleanup); + __ip_vs_del_dest(svc->ipvs, dest, dest_trash, cleanup); } /* @@ -2114,7 +2181,8 @@ static void __ip_vs_del_service(struct ip_vs_service *svc, bool cleanup) /* * Unlink a service from list and try to delete it if its refcnt reached 0 */ -static void ip_vs_unlink_service(struct ip_vs_service *svc, bool cleanup) +static void ip_vs_unlink_service(struct ip_vs_service *svc, + struct list_head *dest_trash, bool cleanup) { ip_vs_unregister_conntrack(svc); /* Hold svc to avoid double release from dest_trash */ @@ -2124,7 +2192,7 @@ static void ip_vs_unlink_service(struct ip_vs_service *svc, bool cleanup) */ ip_vs_svc_unhash(svc); - __ip_vs_del_service(svc, cleanup); + __ip_vs_del_service(svc, dest_trash, cleanup); } /* @@ -2134,12 +2202,14 @@ static int ip_vs_del_service(struct ip_vs_service *svc) { struct netns_ipvs *ipvs; struct ip_vs_rht *t, *p; + LIST_HEAD(dest_trash); int ns; if (svc == NULL) return -EEXIST; ipvs = svc->ipvs; - ip_vs_unlink_service(svc, false); + ip_vs_unlink_service(svc, &dest_trash, false); + ip_vs_trash_save_dests(ipvs, &dest_trash, false); /* Drop the table if no more services */ ns = ip_vs_get_num_services(ipvs); @@ -2190,6 +2260,7 @@ static int ip_vs_flush(struct netns_ipvs *ipvs, bool cleanup) struct hlist_bl_node *ne; struct hlist_bl_node *e; struct ip_vs_rht *t, *p; + LIST_HEAD(dest_trash); /* Stop the resizer and drop the tables */ if (!test_and_set_bit(IP_VS_WORK_SVC_NORESIZE, &ipvs->work_flags)) @@ -2199,8 +2270,9 @@ static int ip_vs_flush(struct netns_ipvs *ipvs, bool cleanup) if (ip_vs_get_num_services(ipvs)) { ip_vs_rht_walk_buckets(ipvs->svc_table, head) { hlist_bl_for_each_entry_safe(svc, e, ne, head, s_list) - ip_vs_unlink_service(svc, cleanup); + ip_vs_unlink_service(svc, &dest_trash, cleanup); } + ip_vs_trash_save_dests(ipvs, &dest_trash, cleanup); } /* Unregister the hash table and release it after RCU grace period */ diff --git a/net/netfilter/ipvs/ip_vs_ftp.c b/net/netfilter/ipvs/ip_vs_ftp.c index 9e3e005a826353..44de99f4d187f9 100644 --- a/net/netfilter/ipvs/ip_vs_ftp.c +++ b/net/netfilter/ipvs/ip_vs_ftp.c @@ -62,6 +62,17 @@ static unsigned short ports[IP_VS_APP_MAX_PORTS] = {21, 0}; module_param_array(ports, ushort, &ports_count, 0444); MODULE_PARM_DESC(ports, "Ports to monitor for FTP control commands"); +static bool is_control_port(u16 port) +{ + unsigned int i; + + for (i = 0; i < ports_count; i++) { + if (ports[i] == port) + return true; + } + return false; +} + static char *ip_vs_ftp_data_ptr(struct sk_buff *skb, struct ip_vs_iphdr *ipvsh) { @@ -319,6 +330,10 @@ static int ip_vs_ftp_out(struct ip_vs_app *app, struct ip_vs_conn *cp, return 1; } + /* Do not redirect data to control ports */ + if (!port || is_control_port(ntohs(port))) + return 0; + /* Now update or create a connection entry for it */ { struct ip_vs_conn_param p; @@ -368,7 +383,7 @@ static int ip_vs_ftp_out(struct ip_vs_app *app, struct ip_vs_conn *cp, buf_len = strlen(buf); ct = nf_ct_get(skb, &ctinfo); - if (ct) { + if (ct && !nf_ct_is_template(ct)) { bool mangled; /* If mangling fails this function will return 0 @@ -529,6 +544,9 @@ static int ip_vs_ftp_in(struct ip_vs_app *app, struct ip_vs_conn *cp, return 1; } + if (!port || is_control_port(ntohs(cp->vport) - 1)) + return 0; + /* Passive mode off */ cp->app_data = (void *) IP_VS_FTP_ACTIVE; diff --git a/net/netfilter/ipvs/ip_vs_lblc.c b/net/netfilter/ipvs/ip_vs_lblc.c index e1111c3b27211a..f5ce1f2afb8606 100644 --- a/net/netfilter/ipvs/ip_vs_lblc.c +++ b/net/netfilter/ipvs/ip_vs_lblc.c @@ -467,10 +467,11 @@ is_overloaded(struct ip_vs_dest *dest, struct ip_vs_service *svc) struct ip_vs_dest *d; list_for_each_entry_rcu(d, &svc->destinations, n_list) { - if (atomic_read(&d->activeconns)*2 - < atomic_read(&d->weight)) { + if (ip_vs_dest_is_overloaded(d)) + continue; + if (atomic_read(&d->activeconns) * 2 < + atomic_read(&d->weight)) return 1; - } } } return 0; @@ -507,6 +508,7 @@ ip_vs_lblc_schedule(struct ip_vs_service *svc, const struct sk_buff *skb, dest = en->dest; if ((dest->cflags & IP_VS_DEST_CF_AVAILABLE) && + !ip_vs_dest_is_overloaded(dest) && atomic_read(&dest->weight) > 0 && !is_overloaded(dest, svc)) goto out; } diff --git a/net/netfilter/ipvs/ip_vs_lblcr.c b/net/netfilter/ipvs/ip_vs_lblcr.c index dfb5bf83750dba..4046608922e7cb 100644 --- a/net/netfilter/ipvs/ip_vs_lblcr.c +++ b/net/netfilter/ipvs/ip_vs_lblcr.c @@ -630,10 +630,11 @@ is_overloaded(struct ip_vs_dest *dest, struct ip_vs_service *svc) struct ip_vs_dest *d; list_for_each_entry_rcu(d, &svc->destinations, n_list) { - if (atomic_read(&d->activeconns)*2 - < atomic_read(&d->weight)) { + if (ip_vs_dest_is_overloaded(d)) + continue; + if (atomic_read(&d->activeconns) * 2 < + atomic_read(&d->weight)) return 1; - } } } return 0; @@ -658,9 +659,6 @@ ip_vs_lblcr_schedule(struct ip_vs_service *svc, const struct sk_buff *skb, if (en) { en->lastuse = jiffies; - /* Get the least loaded destination */ - dest = ip_vs_dest_set_min(&en->set); - /* More than one destination + enough time passed by, cleanup */ if (atomic_read(&en->set.size) > 1 && time_after(jiffies, en->set.lastmod + @@ -676,6 +674,9 @@ ip_vs_lblcr_schedule(struct ip_vs_service *svc, const struct sk_buff *skb, spin_unlock_bh(&svc->sched_lock); } + /* Get the least loaded destination */ + dest = ip_vs_dest_set_min(&en->set); + /* If the destination is not overloaded, use it */ if (dest && !is_overloaded(dest, svc)) goto out; diff --git a/net/netfilter/ipvs/ip_vs_proto_sctp.c b/net/netfilter/ipvs/ip_vs_proto_sctp.c index fb8af6b15a3999..cb34bcceb4f641 100644 --- a/net/netfilter/ipvs/ip_vs_proto_sctp.c +++ b/net/netfilter/ipvs/ip_vs_proto_sctp.c @@ -30,6 +30,7 @@ sctp_conn_schedule(struct netns_ipvs *ipvs, int af, struct sk_buff *skb, sch = skb_header_pointer(skb, iph->len + sizeof(_sctph), sizeof(_schunkh), &_schunkh); if (sch) { + /* Accept packet without scheduling? */ if (sch->type == SCTP_CID_ABORT || !(sysctl_sloppy_sctp(ipvs) || sch->type == SCTP_CID_INIT)) @@ -56,6 +57,12 @@ sctp_conn_schedule(struct netns_ipvs *ipvs, int af, struct sk_buff *skb, if (svc) { int ignored; + /* Do not create connection for port 0 */ + if (!ports[0] || !ports[1]) { + *verdict = NF_DROP; + return 0; + } + if (ip_vs_todrop(ipvs)) { /* * It seems that we are very loaded. diff --git a/net/netfilter/ipvs/ip_vs_proto_tcp.c b/net/netfilter/ipvs/ip_vs_proto_tcp.c index fec0e8b47b7165..25d4576d0e1299 100644 --- a/net/netfilter/ipvs/ip_vs_proto_tcp.c +++ b/net/netfilter/ipvs/ip_vs_proto_tcp.c @@ -48,6 +48,7 @@ tcp_conn_schedule(struct netns_ipvs *ipvs, int af, struct sk_buff *skb, if (likely(!ip_vs_iph_icmp(iph))) { th = skb_header_pointer(skb, iph->len, sizeof(_tcph), &_tcph); if (th) { + /* Accept packet without scheduling? */ if (th->rst || !(sysctl_sloppy_tcp(ipvs) || th->syn)) return 1; ports = &th->source; @@ -74,6 +75,12 @@ tcp_conn_schedule(struct netns_ipvs *ipvs, int af, struct sk_buff *skb, if (svc) { int ignored; + /* Do not create connection for port 0 */ + if (!ports[0] || !ports[1]) { + *verdict = NF_DROP; + return 0; + } + if (ip_vs_todrop(ipvs)) { /* * It seems that we are very loaded. diff --git a/net/netfilter/ipvs/ip_vs_proto_udp.c b/net/netfilter/ipvs/ip_vs_proto_udp.c index f32785682402dd..ab3ab95241687e 100644 --- a/net/netfilter/ipvs/ip_vs_proto_udp.c +++ b/net/netfilter/ipvs/ip_vs_proto_udp.c @@ -62,6 +62,12 @@ udp_conn_schedule(struct netns_ipvs *ipvs, int af, struct sk_buff *skb, if (svc) { int ignored; + /* Do not create connection for port 0 */ + if (!ports[0] || !ports[1]) { + *verdict = NF_DROP; + return 0; + } + if (ip_vs_todrop(ipvs)) { /* * It seems that we are very loaded. diff --git a/net/netfilter/ipvs/ip_vs_sync.c b/net/netfilter/ipvs/ip_vs_sync.c index 157f5c8361ab46..7e562e745ab5d5 100644 --- a/net/netfilter/ipvs/ip_vs_sync.c +++ b/net/netfilter/ipvs/ip_vs_sync.c @@ -539,6 +539,7 @@ static int ip_vs_sync_conn_needed(struct netns_ipvs *ipvs, static void ip_vs_sync_conn_v0(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, int pkts) { + struct ip_vs_sync_conn_options opts; struct ip_vs_sync_mesg_v0 *m; struct ip_vs_sync_conn_v0 *s; struct ip_vs_sync_buff *buff; @@ -557,6 +558,14 @@ static void ip_vs_sync_conn_v0(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, if (!ip_vs_sync_conn_needed(ipvs, cp, pkts)) return; + if (flags & IP_VS_CONN_F_SEQ_MASK) { + /* Take atomic snapshot of flags and seqs */ + spin_lock_bh(&cp->lock); + flags = cp->flags; + memcpy(&opts, &cp->sync_conn_opt, sizeof(opts)); + spin_unlock_bh(&cp->lock); + } + spin_lock_bh(&ipvs->sync_buff_lock); if (!(ipvs->sync_state & IP_VS_STATE_MASTER)) { spin_unlock_bh(&ipvs->sync_buff_lock); @@ -604,7 +613,7 @@ static void ip_vs_sync_conn_v0(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, 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)); + memcpy(opt, &opts, sizeof(*opt)); } m->nr_conns++; @@ -630,6 +639,7 @@ static void ip_vs_sync_conn_v0(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, */ void ip_vs_sync_conn(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, int pkts) { + struct ip_vs_sync_conn_options opts; struct ip_vs_sync_mesg *m; union ip_vs_sync_conn *s; struct ip_vs_sync_buff *buff; @@ -651,6 +661,13 @@ void ip_vs_sync_conn(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, int pkts) if (!ip_vs_sync_conn_needed(ipvs, cp, pkts)) goto control; flags = READ_ONCE(cp->flags); + if (flags & IP_VS_CONN_F_SEQ_MASK) { + /* Take atomic snapshot of flags and seqs */ + spin_lock_bh(&cp->lock); + flags = cp->flags; + memcpy(&opts, &cp->sync_conn_opt, sizeof(opts)); + spin_unlock_bh(&cp->lock); + } /* Sanity checks */ pe_name_len = 0; @@ -732,7 +749,7 @@ void ip_vs_sync_conn(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, int pkts) s->v4.vport = cp->vport; s->v4.dport = cp->dport; s->v4.fwmark = htonl(cp->fwmark); - s->v4.timeout = htonl(cp->timeout / HZ); + s->v4.timeout = htonl(max(1UL, cp->timeout / HZ)); m->nr_conns++; #ifdef CONFIG_IP_VS_IPV6 @@ -752,9 +769,9 @@ void ip_vs_sync_conn(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, int pkts) 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); + hton_seq(&opts.in_seq, (struct ip_vs_seq *)p); p += sizeof(struct ip_vs_seq); - hton_seq(&cp->out_seq, (struct ip_vs_seq *)p); + hton_seq(&opts.out_seq, (struct ip_vs_seq *)p); p += sizeof(struct ip_vs_seq); } /* Handle pe data */ @@ -850,9 +867,29 @@ static void ip_vs_proc_conn(struct netns_ipvs *ipvs, struct ip_vs_conn_param *pa unsigned long timeout, __u32 fwmark, struct ip_vs_sync_conn_options *opt) { + struct ip_vs_conn *cp_new = NULL; struct ip_vs_dest *dest; struct ip_vs_conn *cp; + /* Templates require cport 0. Ordinary connections require + * NO_CPORT exactly when cport is 0. + */ + if (flags & IP_VS_CONN_F_TEMPLATE) { + if (param->cport) { + IP_VS_DBG(2, "BACKUP, template with cport dropped\n"); + kfree(param->pe_data); + return; + } + } else if (!param->cport && !(flags & IP_VS_CONN_F_NO_CPORT)) { + IP_VS_DBG(2, "BACKUP, conn without cport dropped\n"); + kfree(param->pe_data); + return; + } else if (param->cport && (flags & IP_VS_CONN_F_NO_CPORT)) { + IP_VS_DBG(2, "BACKUP, conn with cport and NO_CPORT dropped\n"); + kfree(param->pe_data); + return; + } + if (!(flags & IP_VS_CONN_F_TEMPLATE)) { cp = ip_vs_conn_in_get(param); if (cp && ((cp->dport != dport) || @@ -891,9 +928,6 @@ static void ip_vs_proc_conn(struct netns_ipvs *ipvs, struct ip_vs_conn_param *pa flags &= IP_VS_CONN_F_BACKUP_UPD_MASK; flags |= cp->flags & ~IP_VS_CONN_F_BACKUP_UPD_MASK; cp->flags = flags; - spin_unlock_bh(&cp->lock); - if (!dest) - ip_vs_try_bind_dest(cp); } else { /* * Find the appropriate destination for the connection. @@ -920,6 +954,8 @@ static void ip_vs_proc_conn(struct netns_ipvs *ipvs, struct ip_vs_conn_param *pa } if (!(flags & IP_VS_CONN_F_TEMPLATE)) kfree(param->pe_data); + cp_new = cp; + spin_lock_bh(&cp->lock); } if (opt) { @@ -951,6 +987,9 @@ static void ip_vs_proc_conn(struct netns_ipvs *ipvs, struct ip_vs_conn_param *pa else cp->timeout = (3*60*HZ); } + spin_unlock_bh(&cp->lock); + if (!dest && !cp_new) + ip_vs_try_bind_dest(cp); ip_vs_conn_put(cp); } diff --git a/net/openvswitch/flow.c b/net/openvswitch/flow.c index 3734416b518d71..5fbeb0cca9dce6 100644 --- a/net/openvswitch/flow.c +++ b/net/openvswitch/flow.c @@ -438,7 +438,8 @@ static int parse_ipv6hdr(struct sk_buff *skb, struct sw_flow_key *key) return -EPROTO; nh_len = payload_ofs - nh_ofs; - skb_set_transport_header(skb, nh_ofs + nh_len); + if (unlikely(!skb_set_transport_header_careful(skb, payload_ofs))) + return -EPROTO; key->ip.proto = nexthdr; return nh_len; } diff --git a/net/packet/af_packet.c b/net/packet/af_packet.c index 73222563fb7049..e0ebd0627509f7 100644 --- a/net/packet/af_packet.c +++ b/net/packet/af_packet.c @@ -200,7 +200,7 @@ static void packet_increment_head(struct packet_ring_buffer *buff); static int prb_curr_blk_in_use(struct tpacket_block_desc *); static void *prb_dispatch_next_block(struct tpacket_kbdq_core *, struct packet_sock *); -static void prb_retire_current_block(struct tpacket_kbdq_core *, +static bool prb_retire_current_block(struct tpacket_kbdq_core *, struct packet_sock *, unsigned int status); static int prb_queue_frozen(struct tpacket_kbdq_core *); static void prb_open_block(struct tpacket_kbdq_core *, @@ -677,6 +677,24 @@ static void init_prb_bdqc(struct packet_sock *po, prb_open_block(p1, pbd); } +/* + * Wait for an in-flight skb_copy_bits() before retiring the current block. + * On PREEMPT_RT the read lock can be held by a task that has been preempted + * or is running on another CPU, so do not block while holding + * sk_receive_queue.lock; return false and let the caller retry. + */ +static bool prb_wait_for_copy_bits(struct tpacket_kbdq_core *pkc) +{ + if (IS_ENABLED(CONFIG_PREEMPT_RT)) { + if (!write_trylock(&pkc->blk_fill_in_prog_lock)) + return false; + } else { + write_lock(&pkc->blk_fill_in_prog_lock); + } + write_unlock(&pkc->blk_fill_in_prog_lock); + return true; +} + /* * With a 1MB block-size, on a 1Gbps line, it will take * i) ~8 ms to fill a block + ii) memcpy etc. @@ -711,9 +729,9 @@ static enum hrtimer_restart prb_retire_rx_blk_timer_expired(struct hrtimer *t) * */ if (BLOCK_NUM_PKTS(pbd)) { - /* Waiting for skb_copy_bits to finish... */ - write_lock(&pkc->blk_fill_in_prog_lock); - write_unlock(&pkc->blk_fill_in_prog_lock); + /* Retry later if a packet copy is still in progress. */ + if (!prb_wait_for_copy_bits(pkc)) + goto refresh_timer; } if (!frozen) { @@ -738,6 +756,7 @@ static enum hrtimer_restart prb_retire_rx_blk_timer_expired(struct hrtimer *t) } } +refresh_timer: hrtimer_forward_now(&pkc->retire_blk_timer, pkc->interval_ktime); spin_unlock(&po->sk.sk_receive_queue.lock); return HRTIMER_RESTART; @@ -946,7 +965,7 @@ static void *prb_dispatch_next_block(struct tpacket_kbdq_core *pkc, return (void *)pkc->nxt_offset; } -static void prb_retire_current_block(struct tpacket_kbdq_core *pkc, +static bool prb_retire_current_block(struct tpacket_kbdq_core *pkc, struct packet_sock *po, unsigned int status) { struct tpacket_block_desc *pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc); @@ -963,13 +982,13 @@ static void prb_retire_current_block(struct tpacket_kbdq_core *pkc, * the timer-handler already handled this case. */ if (!(status & TP_STATUS_BLK_TMO)) { - /* Waiting for skb_copy_bits to finish... */ - write_lock(&pkc->blk_fill_in_prog_lock); - write_unlock(&pkc->blk_fill_in_prog_lock); + /* Do not wait for copies while holding the queue lock. */ + if (!prb_wait_for_copy_bits(pkc)) + return false; } prb_close_block(pkc, pbd, po, status); - return; } + return true; } static int prb_curr_blk_in_use(struct tpacket_block_desc *pbd) @@ -1097,7 +1116,8 @@ static void *__packet_lookup_frame_in_block(struct packet_sock *po, } /* Ok, close the current block */ - prb_retire_current_block(pkc, po, 0); + if (!prb_retire_current_block(pkc, po, 0)) + return NULL; /* Now, try to dispatch the next block */ curr = (char *)prb_dispatch_next_block(pkc, po); diff --git a/net/qrtr/ns.c b/net/qrtr/ns.c index bcb090ee79d494..8209573221a5f3 100644 --- a/net/qrtr/ns.c +++ b/net/qrtr/ns.c @@ -374,11 +374,11 @@ static int ctrl_cmd_bye(struct sockaddr_qrtr *from) msg.msg_name = (struct sockaddr *)&sq; msg.msg_namelen = sizeof(sq); + /* A server that cannot take it must not hide it from the rest */ ret = kernel_sendmsg(qrtr_ns.sock, &msg, &iv, 1, sizeof(pkt)); - if (ret < 0 && ret != -ENODEV) { - pr_err("failed to send bye cmd\n"); - goto delete_node; - } + if (ret < 0 && ret != -ENODEV) + pr_err_ratelimited("failed to send bye cmd to %u:%u: %d\n", + srv->node, srv->port, ret); } /* Ignore -ENODEV */ @@ -458,11 +458,11 @@ static int ctrl_cmd_del_client(struct sockaddr_qrtr *from, msg.msg_name = (struct sockaddr *)&sq; msg.msg_namelen = sizeof(sq); + /* A server that cannot take it must not hide it from the rest */ ret = kernel_sendmsg(qrtr_ns.sock, &msg, &iv, 1, sizeof(pkt)); - if (ret < 0 && ret != -ENODEV) { - pr_err("failed to send del client cmd\n"); - return ret; - } + if (ret < 0 && ret != -ENODEV) + pr_err_ratelimited("failed to send del client cmd to %u:%u: %d\n", + srv->node, srv->port, ret); } return 0; } @@ -487,11 +487,10 @@ static int ctrl_cmd_new_server(struct sockaddr_qrtr *from, return -EINVAL; if (srv->node == qrtr_ns.local_node) { + /* The lookups below still need to hear about the server */ ret = service_announce_new(&qrtr_ns.bcast_sq, srv); - if (ret < 0) { + if (ret < 0) pr_err("failed to announce new service\n"); - return ret; - } } /* Notify any potential lookups about the new server */ diff --git a/net/sched/bpf_qdisc.c b/net/sched/bpf_qdisc.c index 5691c13781a8b0..de0c3869e403ed 100644 --- a/net/sched/bpf_qdisc.c +++ b/net/sched/bpf_qdisc.c @@ -5,6 +5,7 @@ #include #include #include +#include #include #include @@ -184,6 +185,19 @@ static int bpf_qdisc_gen_epilogue(struct bpf_insn *insn_buf, const struct bpf_pr return insn - insn_buf; } +static LLIST_HEAD(bpf_skb_free_list); + +static void bpf_skb_free_irq_work(struct irq_work *work) +{ + struct llist_node *list = llist_del_all(&bpf_skb_free_list); + struct sk_buff *skb, *next; + + llist_for_each_entry_safe(skb, next, list, ll_node) + dev_kfree_skb_any(skb); +} + +static DEFINE_IRQ_WORK(bpf_skb_free_work, bpf_skb_free_irq_work); + __bpf_kfunc_start_defs(); /* bpf_skb_get_hash - Get the flow hash of an skb. @@ -196,9 +210,22 @@ __bpf_kfunc u32 bpf_skb_get_hash(struct sk_buff *skb) /* bpf_kfree_skb - Release an skb's reference and drop it immediately. * @skb: The skb whose reference to be released and dropped. + * + * Also the destructor of an skb kptr, which runs wherever an object or a map + * value with such a field is freed: under a bpf_spin_lock too, with irqs off. + * rq lock can be held as well, so don't wake up ksoftirqd from here. */ __bpf_kfunc void bpf_kfree_skb(struct sk_buff *skb) { + if (irqs_disabled() || + (IS_ENABLED(CONFIG_PREEMPT_RT) && !preemptible())) { + /* Only the last reference may link the skb. */ + if (refcount_dec_not_one(&skb->users)) + return; + llist_add(&skb->ll_node, &bpf_skb_free_list); + irq_work_queue(&bpf_skb_free_work); + return; + } kfree_skb(skb); } diff --git a/net/sctp/ipv6.c b/net/sctp/ipv6.c index 97390569c4bdc3..ad5c951efdf064 100644 --- a/net/sctp/ipv6.c +++ b/net/sctp/ipv6.c @@ -170,8 +170,11 @@ static int sctp_v6_err(struct sk_buff *skb, struct inet6_skb_parm *opt, /* Fix up skb to look at the embedded net header. */ saveip = skb->network_header; savesctp = skb->transport_header; + if (unlikely(!skb_set_transport_header_careful(skb, offset))) { + __ICMP6_INC_STATS(net, __in6_dev_get(skb->dev), ICMP6_MIB_INERRORS); + return -EINVAL; + } skb_reset_network_header(skb); - skb_set_transport_header(skb, offset); sk = sctp_err_lookup(net, AF_INET6, skb, sctp_hdr(skb), &asoc, &transport); /* Put back, the original pointers. */ skb->network_header = saveip; diff --git a/net/sctp/outqueue.c b/net/sctp/outqueue.c index e92fb9da4647a7..3dafa6e6cab3b7 100644 --- a/net/sctp/outqueue.c +++ b/net/sctp/outqueue.c @@ -190,9 +190,12 @@ static inline int sctp_cacc_skip(struct sctp_transport *primary, */ void sctp_outq_init(struct sctp_association *asoc, struct sctp_outq *q) { - memset(q, 0, sizeof(struct sctp_outq)); - q->asoc = asoc; + q->out_qlen = 0; + q->error = 0; + q->outstanding_bytes = 0; + q->fast_rtx = 0; + q->cork = 0; INIT_LIST_HEAD(&q->out_chunk_list); INIT_LIST_HEAD(&q->control_chunk_list); INIT_LIST_HEAD(&q->retransmit); diff --git a/net/sctp/sm_make_chunk.c b/net/sctp/sm_make_chunk.c index 15c2d87575a8a7..ba0474c2a0bc82 100644 --- a/net/sctp/sm_make_chunk.c +++ b/net/sctp/sm_make_chunk.c @@ -2870,7 +2870,6 @@ struct sctp_chunk *sctp_make_asconf_update_ip(struct sctp_association *asoc, int addr_param_len = 0; union sctp_addr *addr; int totallen = 0, i; - int del_pickup = 0; struct sctp_af *af; void *addr_buf; @@ -2885,16 +2884,21 @@ struct sctp_chunk *sctp_make_asconf_update_ip(struct sctp_association *asoc, totallen += addr_param_len; addr_buf += af->sockaddr_len; - if (asoc->asconf_addr_del_pending && !del_pickup) { - /* reuse the parameter length from the same scope one */ - totallen += paramlen; - totallen += addr_param_len; - del_pickup = 1; - - pr_debug("%s: picked same-scope del_pending addr, " - "totallen for all addresses is %d\n", - __func__, totallen); - } + } + + if (asoc->asconf_addr_del_pending) { + /* The DEL_IP parameter is serialized from the pending address + * itself below; account for its own address family, which may + * differ from the added ones. + */ + addr = asoc->asconf_addr_del_pending; + af = sctp_get_af_specific(addr->v4.sin_family); + totallen += paramlen; + totallen += af->to_addr_param(addr, &addr_param); + + pr_debug("%s: picked del_pending addr, " + "totallen for all addresses is %d\n", + __func__, totallen); } /* Create an asconf chunk with the required length. */ @@ -2917,7 +2921,7 @@ struct sctp_chunk *sctp_make_asconf_update_ip(struct sctp_association *asoc, addr_buf += af->sockaddr_len; } - if (flags == SCTP_PARAM_ADD_IP && del_pickup) { + if (flags == SCTP_PARAM_ADD_IP && asoc->asconf_addr_del_pending) { addr = asoc->asconf_addr_del_pending; af = sctp_get_af_specific(addr->v4.sin_family); addr_param_len = af->to_addr_param(addr, &addr_param); diff --git a/net/sctp/sm_statefuns.c b/net/sctp/sm_statefuns.c index 64519fd8f94335..6a4205de0aa69c 100644 --- a/net/sctp/sm_statefuns.c +++ b/net/sctp/sm_statefuns.c @@ -6372,7 +6372,8 @@ static struct sctp_sackhdr *sctp_sm_pull_sack(struct sctp_chunk *chunk) num_dup_tsns = ntohs(sack->num_dup_tsns); len = sizeof(struct sctp_sackhdr); len += (num_blocks + num_dup_tsns) * sizeof(__u32); - if (len > chunk->skb->len) + if (len > ntohs(chunk->chunk_hdr->length) - + sizeof(struct sctp_chunkhdr)) return NULL; skb_pull(chunk->skb, len); diff --git a/net/sctp/socket.c b/net/sctp/socket.c index 8e647737b2567d..85ac4952e9cb68 100644 --- a/net/sctp/socket.c +++ b/net/sctp/socket.c @@ -2063,6 +2063,11 @@ static int sctp_sendmsg(struct sock *sk, struct msghdr *msg, size_t msg_len) asoc = transport->asoc; new = true; + /* sctp_sendmsg_to_asoc() may release the socket lock, + * and the new asoc can be peeled off meanwhile. Hold + * it, and free it on error only if sk still owns it. + */ + sctp_association_hold(asoc); } if (!sctp_style(sk, TCP) && !(sflags & SCTP_ADDR_OVER)) @@ -2084,8 +2089,11 @@ static int sctp_sendmsg(struct sock *sk, struct msghdr *msg, size_t msg_len) /* Send msg to the asoc */ err = sctp_sendmsg_to_asoc(asoc, msg, msg_len, transport, sinfo); - if (err < 0 && err != -ESRCH && new) - sctp_association_free(asoc); + if (new) { + if (err < 0 && err != -ESRCH && asoc->base.sk == sk) + sctp_association_free(asoc); + sctp_association_put(asoc); + } out_unlock: release_sock(sk); @@ -9062,6 +9070,15 @@ static int sctp_msghdr_parse(const struct msghdr *msg, struct sctp_cmsgs *cmsgs) return 0; } +/* Don't take wakeups for other events, e.g. EPOLLOUT from write space. */ +static int sctp_receiver_wake_function(wait_queue_entry_t *wait, + unsigned int mode, int sync, void *key) +{ + if (key && !(key_to_poll(key) & (EPOLLIN | EPOLLERR))) + return 0; + return autoremove_wake_function(wait, mode, sync, key); +} + /* * Wait for a packet.. * Note: This function is the same function as in core/datagram.c @@ -9070,7 +9087,7 @@ static int sctp_msghdr_parse(const struct msghdr *msg, struct sctp_cmsgs *cmsgs) static int sctp_wait_for_packet(struct sock *sk, int *err, long *timeo_p) { int error; - DEFINE_WAIT(wait); + DEFINE_WAIT_FUNC(wait, sctp_receiver_wake_function); prepare_to_wait_exclusive(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); diff --git a/net/tipc/socket.c b/net/tipc/socket.c index 65cc0c4964b31f..26771a98dc7a6f 100644 --- a/net/tipc/socket.c +++ b/net/tipc/socket.c @@ -3096,8 +3096,12 @@ static int tipc_sk_join(struct tipc_sock *tsk, struct tipc_group_req *mreq) if (grp) return -EACCES; grp = tipc_group_create(net, tsk->portid, mreq, &tsk->group_is_open); - if (!grp) + if (!grp) { + /* tipc_group_create() may have cleared it before failing */ + tsk->group_is_open = true; + tsk->sk.sk_write_space(&tsk->sk); return -ENOMEM; + } tsk->group = grp; msg_set_lookup_scope(hdr, mreq->scope); msg_set_nametype(hdr, mreq->type); @@ -3109,6 +3113,8 @@ static int tipc_sk_join(struct tipc_sock *tsk, struct tipc_group_req *mreq) if (rc) { tipc_group_delete(net, grp); tsk->group = NULL; + tsk->group_is_open = true; + tsk->sk.sk_write_space(&tsk->sk); return rc; } /* Eliminate any risk that a broadcast overtakes sent JOINs */ @@ -3132,7 +3138,9 @@ static int tipc_sk_leave(struct tipc_sock *tsk) ua.scope = scope; tipc_group_delete(net, grp); tsk->group = NULL; + tsk->group_is_open = true; tipc_sk_withdraw(tsk, &ua); + tsk->sk.sk_write_space(&tsk->sk); return 0; } diff --git a/net/tls/tls_device.c b/net/tls/tls_device.c index 4cdfbb57ecff0a..fa7170cd4fd10f 100644 --- a/net/tls/tls_device.c +++ b/net/tls/tls_device.c @@ -1350,6 +1350,8 @@ static int tls_device_down(struct net_device *netdev) spin_unlock_irqrestore(&tls_device_lock, flags); list_for_each_entry_safe(ctx, tmp, &list, list) { + bool free_ctx; + /* Stop offloaded TX and switch to the fallback. * tls_is_skb_tx_device_offloaded will return false. */ @@ -1387,17 +1389,19 @@ static int tls_device_down(struct net_device *netdev) */ spin_lock_irqsave(&tls_device_lock, flags); list_move_tail(&ctx->list, &tls_device_down_list); + /* Serialize the final removal with sk_destruct. */ + free_ctx = refcount_dec_and_test(&ctx->refcount); + if (free_ctx) + list_del(&ctx->list); spin_unlock_irqrestore(&tls_device_lock, flags); /* Device contexts for RX and TX will be freed in on sk_destruct * by tls_device_free_ctx. rx_conf and tx_conf stay in TLS_HW. - * Now release the ref taken above. */ - if (refcount_dec_and_test(&ctx->refcount)) { + if (free_ctx) { /* sk_destruct ran after tls_device_down took a ref, and * it returned early. Complete the destruction here. */ - list_del(&ctx->list); tls_device_free_ctx(ctx); } } diff --git a/net/tls/tls_main.c b/net/tls/tls_main.c index b8d5a843f76171..d24e86e7f42d9c 100644 --- a/net/tls/tls_main.c +++ b/net/tls/tls_main.c @@ -414,9 +414,9 @@ static __poll_t tls_sk_poll(struct file *file, struct socket *sock, tls_ctx = tls_get_ctx(sk); ctx = tls_sw_ctx_rx(tls_ctx); - if ((skb_queue_empty_lockless(&ctx->rx_list) && - !tls_strp_msg_ready(ctx)) || - READ_ONCE(ctx->key_update_pending)) + if (skb_queue_empty_lockless(&ctx->rx_list) && + (!tls_strp_msg_ready(ctx) || + READ_ONCE(ctx->key_update_pending))) mask &= ~(EPOLLIN | EPOLLRDNORM); return mask; @@ -1067,6 +1067,9 @@ static int tls_init(struct sock *sk) if (sk->sk_state != TCP_ESTABLISHED) return -ENOTCONN; + if (tcp_kcm_attached(sk)) + return -EBUSY; + /* allocate tls context */ write_lock_bh(&sk->sk_callback_lock); ctx = tls_ctx_create(sk); diff --git a/net/unix/af_unix.c b/net/unix/af_unix.c index f847cf1fbeafec..91c1d6cad4974c 100644 --- a/net/unix/af_unix.c +++ b/net/unix/af_unix.c @@ -609,6 +609,28 @@ static void unix_write_space(struct sock *sk) rcu_read_unlock(); } +static void scm_stat_add(struct sock *sk, struct sk_buff *skb) +{ + struct scm_fp_list *fp = UNIXCB(skb).fp; + struct unix_sock *u = unix_sk(sk); + + if (unlikely(fp && fp->count)) { + atomic_add(fp->count, &u->scm_stat.nr_fds); + unix_add_edges(fp, u); + } +} + +static void scm_stat_del(struct sock *sk, struct sk_buff *skb) +{ + struct scm_fp_list *fp = UNIXCB(skb).fp; + struct unix_sock *u = unix_sk(sk); + + if (unlikely(fp && fp->count)) { + atomic_sub(fp->count, &u->scm_stat.nr_fds); + unix_del_edges(fp); + } +} + /* When dgram socket disconnects (or changes its peer), we clear its receive * queue of packets arrived from previous peer. First, it allows to do * flow control based only on wmem_alloc; second, sk connected to peer @@ -616,8 +638,19 @@ static void unix_write_space(struct sock *sk) static void unix_dgram_disconnected(struct sock *sk, struct sock *other) { if (!skb_queue_empty(&sk->sk_receive_queue)) { - skb_queue_purge_reason(&sk->sk_receive_queue, - SKB_DROP_REASON_UNIX_DISCONNECT); + struct sk_buff_head tmp; + struct sk_buff *skb; + + __skb_queue_head_init(&tmp); + + spin_lock(&sk->sk_receive_queue.lock); + skb_queue_splice_init(&sk->sk_receive_queue, &tmp); + spin_unlock(&sk->sk_receive_queue.lock); + + while ((skb = __skb_dequeue(&tmp)) != NULL) { + scm_stat_del(sk, skb); + kfree_skb_reason(skb, SKB_DROP_REASON_UNIX_DISCONNECT); + } wake_up_interruptible_all(&unix_sk(sk)->peer_wait); @@ -2059,28 +2092,6 @@ static bool unix_skb_scm_eq(const struct sock *sk, struct sk_buff *skb, unix_secdata_eq(scm, skb); } -static void scm_stat_add(struct sock *sk, struct sk_buff *skb) -{ - struct scm_fp_list *fp = UNIXCB(skb).fp; - struct unix_sock *u = unix_sk(sk); - - if (unlikely(fp && fp->count)) { - atomic_add(fp->count, &u->scm_stat.nr_fds); - unix_add_edges(fp, u); - } -} - -static void scm_stat_del(struct sock *sk, struct sk_buff *skb) -{ - struct scm_fp_list *fp = UNIXCB(skb).fp; - struct unix_sock *u = unix_sk(sk); - - if (unlikely(fp && fp->count)) { - atomic_sub(fp->count, &u->scm_stat.nr_fds); - unix_del_edges(fp); - } -} - static void unix_orphan_scm(struct sock *sk, struct sk_buff *skb) { scm_stat_del(sk, skb); diff --git a/net/vmw_vsock/vmci_transport.c b/net/vmw_vsock/vmci_transport.c index 1f186e8f83640a..282131544c42ba 100644 --- a/net/vmw_vsock/vmci_transport.c +++ b/net/vmw_vsock/vmci_transport.c @@ -627,6 +627,8 @@ static int vmci_transport_recv_dgram_cb(void *data, struct vmci_datagram *dg) * outside of the create and destruct socket functions. */ vsk = vsock_sk(sk); + if (!vsock_net_mode_global(vsk)) + return VMCI_ERROR_NO_ACCESS; if (!vmci_transport_allow_dgram(vsk, dg->src.context)) return VMCI_ERROR_NO_ACCESS; @@ -1697,6 +1699,10 @@ static int vmci_transport_dgram_bind(struct vsock_sock *vsk, u32 flags; int err; + /* VMCI handles are global and cannot serve local namespaces. */ + if (!vsock_net_mode_global(vsk)) + return -EOPNOTSUPP; + /* VMCI will select a resource ID for us if we provide * VMCI_INVALID_ID. */ diff --git a/net/vmw_vsock/vsock_bpf.c b/net/vmw_vsock/vsock_bpf.c index 9049d26486460c..41307759da9997 100644 --- a/net/vmw_vsock/vsock_bpf.c +++ b/net/vmw_vsock/vsock_bpf.c @@ -34,24 +34,37 @@ static bool vsock_has_data(struct sock *sk, struct sk_psock *psock) return vsock_sk_has_data(sk, psock); } -static bool vsock_msg_wait_data(struct sock *sk, struct sk_psock *psock, long timeo) +/* __vsock_recvmsg() doesn't wait in these states. */ +static bool vsock_rx_done(struct sock *sk) { - bool ret; - - DEFINE_WAIT_FUNC(wait, woken_wake_function); + return sk->sk_err || sk->sk_state != TCP_ESTABLISHED || + (sk->sk_shutdown & RCV_SHUTDOWN) || + (vsock_sk(sk)->peer_shutdown & SEND_SHUTDOWN); +} - if (sk->sk_shutdown & RCV_SHUTDOWN) - return true; +static int vsock_msg_wait_data(struct sock *sk, struct sk_psock *psock, + long timeo) +{ + struct vsock_sock *vsk = vsock_sk(sk); + int ret = 0; - if (!timeo) - return false; + DEFINE_WAIT_FUNC(wait, woken_wake_function); add_wait_queue(sk_sleep(sk), &wait); sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk); - ret = vsock_has_data(sk, psock); - if (!ret) { - wait_woken(&wait, TASK_INTERRUPTIBLE, timeo); - ret = vsock_has_data(sk, psock); + while (vsk->transport && !vsock_has_data(sk, psock) && + !vsock_rx_done(sk)) { + if (!timeo) { + ret = -EAGAIN; + break; + } + if (signal_pending(current)) { + ret = sock_intr_errno(timeo); + break; + } + release_sock(sk); + timeo = wait_woken(&wait, TASK_INTERRUPTIBLE, timeo); + lock_sock(sk); } sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk); remove_wait_queue(sk_sleep(sk), &wait); @@ -80,6 +93,9 @@ static int vsock_bpf_recvmsg(struct sock *sk, struct msghdr *msg, struct vsock_sock *vsk; int copied; + if (unlikely(!len || (flags & (MSG_OOB | MSG_ERRQUEUE)))) + return __vsock_recvmsg(sk, msg, len, flags); + psock = sk_psock_get(sk); if (unlikely(!psock)) return __vsock_recvmsg(sk, msg, len, flags); @@ -102,10 +118,9 @@ static int vsock_bpf_recvmsg(struct sock *sk, struct msghdr *msg, while (copied == 0) { long timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT); - if (!vsock_msg_wait_data(sk, psock, timeo)) { - copied = -EAGAIN; + copied = vsock_msg_wait_data(sk, psock, timeo); + if (copied) break; - } if (sk_psock_queue_empty(psock)) { release_sock(sk); diff --git a/net/xdp/xsk.c b/net/xdp/xsk.c index f22f9a2cdbbeae..18cbd50047d80b 100644 --- a/net/xdp/xsk.c +++ b/net/xdp/xsk.c @@ -948,6 +948,8 @@ static int xsk_skb_init_misc(struct sk_buff *skb, struct xdp_sock *xs, { int err; + skb_reset_network_header(skb); + err = xsk_skb_destructor_set_addr(skb, addr); if (unlikely(err)) return err; @@ -1006,7 +1008,8 @@ static int xsk_skb_metadata(struct sk_buff *skb, void *buffer, csum_offset = READ_ONCE(meta->request.csum_offset); if (unlikely(csum_start + csum_offset + - sizeof(__sum16) > desc->len)) + sizeof(__sum16) > desc->len || + hr + csum_start >= U16_MAX)) return -EINVAL; skb->csum_start = hr + csum_start; diff --git a/net/xfrm/xfrm_interface_core.c b/net/xfrm/xfrm_interface_core.c index 9835fbe63ccb83..aa6e42c3e0e2e8 100644 --- a/net/xfrm/xfrm_interface_core.c +++ b/net/xfrm/xfrm_interface_core.c @@ -531,6 +531,14 @@ static netdev_tx_t xfrmi_xmit(struct sk_buff *skb, struct net_device *dev) memset(&fl, 0, sizeof(fl)); + switch (skb->protocol) { + case htons(ETH_P_IPV6): + case htons(ETH_P_IP): + break; + default: + goto tx_err; + } + if (!pskb_inet_may_pull(skb)) goto tx_err; diff --git a/rust/Makefile b/rust/Makefile index 0165626decbe7e..6dceabbf02c872 100644 --- a/rust/Makefile +++ b/rust/Makefile @@ -167,7 +167,7 @@ pin_init-flags := \ rustdoc_modifiers_workaround := $(if $(call rustc-min-version,108800),-Cunsafe-allow-abi-mismatch=fixed-x18) # Similarly, for doctests (https://github.com/rust-lang/rust/issues/146465). -doctests_modifiers_workaround := $(rustdoc_modifiers_workaround)$(if $(call rustc-min-version,109100),$(comma)sanitizer) +doctests_modifiers_workaround := $(rustdoc_modifiers_workaround)$(if $(call rustc-min-version,109100),$(comma)sanitizer$(comma)indirect-branch-cs-prefix) quiet_cmd_rustdoc = RUSTDOC $(if $(rustdoc_host),H, ) $< cmd_rustdoc = \ diff --git a/rust/kernel/iov.rs b/rust/kernel/iov.rs index 43bae8923c4611..8caf045180476c 100644 --- a/rust/kernel/iov.rs +++ b/rust/kernel/iov.rs @@ -161,7 +161,7 @@ impl<'data> IovIterSource<'data> { /// /// This will never write uninitialized bytes to the provided buffer. #[inline] - pub fn copy_from_iter_raw(&mut self, out: &mut [MaybeUninit]) -> &mut [u8] { + pub fn copy_from_iter_raw<'a>(&mut self, out: &'a mut [MaybeUninit]) -> &'a mut [u8] { let capacity = out.len(); let out = out.as_mut_ptr().cast::(); diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 644b4279a11601..e5fe84eeb5c905 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -645,7 +645,7 @@ impl fmt::Write for RawFormatter { /// Fails if callers attempt to write more than will fit in the buffer. pub struct Formatter<'a>(RawFormatter, PhantomData<&'a mut ()>); -impl Formatter<'_> { +impl<'a> Formatter<'a> { /// Creates a new instance of [`Formatter`] with the given buffer. /// /// # Safety @@ -658,7 +658,7 @@ impl Formatter<'_> { } /// Create a new [`Self`] instance. - pub fn new(buffer: &mut [u8]) -> Self { + pub fn new(buffer: &'a mut [u8]) -> Self { // SAFETY: `buffer` is valid for writes for the entire length for // the lifetime of `Self`. unsafe { Formatter::from_buffer(buffer.as_mut_ptr(), buffer.len()) } diff --git a/scripts/Kconfig.toolchain b/scripts/Kconfig.toolchain index 2acbd40a38f16f..1d68075f046912 100644 --- a/scripts/Kconfig.toolchain +++ b/scripts/Kconfig.toolchain @@ -233,6 +233,9 @@ config CC_OPT_WNO_FORMAT_OVERFLOW config CC_OPT_WNO_STRINGOP_TRUNCATION def_string "$(cc-option-str,-Wno-stringop-truncation)" +config CC_OPT_WNO_CONSTANT_LOGICAL_OPERAND + def_string "$(cc-option-str,-Wno-constant-logical-operand)" + config CC_HAS_COUNTED_BY bool # clang needs to be at least 20.1.0 to avoid potential crashes diff --git a/scripts/Makefile.autofdo b/scripts/Makefile.autofdo index 32c18df237f1b6..f5312711883f15 100644 --- a/scripts/Makefile.autofdo +++ b/scripts/Makefile.autofdo @@ -13,13 +13,16 @@ endif ifdef CLANG_AUTOFDO_PROFILE CFLAGS_AUTOFDO_CLANG += -fprofile-sample-use=$(CLANG_AUTOFDO_PROFILE) -ffunction-sections CFLAGS_AUTOFDO_CLANG += -fsplit-machine-functions + CFLAGS_AUTOFDO_CLANG += $(if $(call clang-min-version,210000),-fno-sample-profile-use-profi) RUSTFLAGS_AUTOFDO_CLANG += $(if $(call rustc-min-version,110000),-Cprofile-sample-use,-Zprofile-sample-use)=$(CLANG_AUTOFDO_PROFILE) -Zfunction-sections=y RUSTFLAGS_AUTOFDO_CLANG += -Cllvm-args=-split-machine-functions + RUSTFLAGS_AUTOFDO_CLANG += -Cllvm-args=-sample-profile-use-profi=false endif ifdef CONFIG_LTO_CLANG_THIN ifdef CLANG_AUTOFDO_PROFILE KBUILD_LDFLAGS += --lto-sample-profile=$(CLANG_AUTOFDO_PROFILE) + KBUILD_LDFLAGS += --mllvm=-sample-profile-use-profi=false endif KBUILD_LDFLAGS += --mllvm=-enable-fs-discriminator=true --mllvm=-improved-fs-discriminator=true -plugin-opt=thinlto KBUILD_LDFLAGS += $(call ld-option,-plugin-opt=-function-splitting=all,-plugin-opt=-split-machine-functions) diff --git a/scripts/Makefile.warn b/scripts/Makefile.warn index 556fa249ca071a..03b677bdbb0af1 100644 --- a/scripts/Makefile.warn +++ b/scripts/Makefile.warn @@ -167,6 +167,7 @@ endif ifdef CONFIG_CC_IS_GCC KBUILD_CFLAGS += -Wno-maybe-uninitialized +KBUILD_CFLAGS += $(CONFIG_CC_OPT_WNO_CONSTANT_LOGICAL_OPERAND) endif endif diff --git a/scripts/get_maintainer.pl b/scripts/get_maintainer.pl index 16b80a700d4ac7..265245e568c6d3 100755 --- a/scripts/get_maintainer.pl +++ b/scripts/get_maintainer.pl @@ -959,6 +959,15 @@ sub get_maintainers { $tvi = $end + 1; } + # THE REST matches every file, so only fall back to it when no + # other matching section provides a mailing list for this file + # that we would actually output with the current options. + my ($the_rest) = grep { get_section_name($_) eq "THE REST" } keys %hash; + if (defined($the_rest) && + grep { $_ != $the_rest && section_has_list($_) } keys %hash) { + delete $hash{$the_rest}; + } + foreach my $line (sort {$hash{$b} <=> $hash{$a}} keys %hash) { add_categories($line, ""); if ($sections) { @@ -1295,6 +1304,40 @@ sub find_ending_index { return $index; } +sub get_section_name { + my ($index) = @_; + + return $typevalue[find_starting_index($index)]; +} + +sub section_has_list { + my ($index) = @_; + + my $start = find_starting_index($index); + my $end = find_ending_index($index); + for (my $i = $start; $i < $end; $i++) { + next if ($typevalue[$i] !~ m/^L:\s*(.*)/); + my $list_additional = ""; + if ($1 =~ m/[^\s]+\s+(.*)$/) { + $list_additional = $1; + } + return 1 if (list_is_selected($list_additional)); + } + return 0; +} + +# Must match the list selection in add_categories() +sub list_is_selected { + my ($list_additional) = @_; + + if ($list_additional =~ m/subscribers-only/) { + return $email_subscriber_list; + } elsif ($list_additional =~ m/moderated/) { + return $email_list && $email_moderated_list; + } + return $email_list; +} + sub get_subsystem_name { my ($index) = @_; diff --git a/security/commoncap.c b/security/commoncap.c index d47ab30223435b..9794a594bdd925 100644 --- a/security/commoncap.c +++ b/security/commoncap.c @@ -1283,6 +1283,26 @@ static int cap_prctl_drop(unsigned long cap) return commit_creds(new); } +/* + * Doing anything with securebits requires privilege (go read about the + * "sendmail capabilities bug"), except for unprivileged bits. Indeed, the + * SECURE_ALL_UNPRIVILEGED bits are not restrictions enforced by the kernel but + * by user space on itself. Only checking CAP_SETPCAP when it is needed keeps + * LSMs from seeing (and logging) a capability check for unprivileged changes. + */ +static bool securebits_need_setpcap(unsigned long old, unsigned long new) +{ + const unsigned long unpriv_and_locks = SECURE_ALL_UNPRIVILEGED | + SECURE_ALL_UNPRIVILEGED << 1; + const unsigned long changed = old ^ new; + + /* For legacy reasons, a non-change requires privilege. */ + if (!changed) + return true; + + return changed & ~unpriv_and_locks; +} + /** * cap_task_prctl - Implement process control functions for this security module * @option: The process control function requested @@ -1346,28 +1366,9 @@ int cap_task_prctl(int option, unsigned long arg2, unsigned long arg3, /* cannot change a locked bit */ return -EPERM; - /* - * Doing anything requires privilege (go read about the - * "sendmail capabilities bug"), except for unprivileged bits. - * Indeed, the SECURE_ALL_UNPRIVILEGED bits are not - * restrictions enforced by the kernel but by user space on - * itself. - */ - if (cap_capable(current_cred(), current_cred()->user_ns, - CAP_SETPCAP, CAP_OPT_NONE) != 0) { - const unsigned long unpriv_and_locks = - SECURE_ALL_UNPRIVILEGED | - SECURE_ALL_UNPRIVILEGED << 1; - const unsigned long changed = old->securebits ^ arg2; - - /* For legacy reason, denies non-change. */ - if (!changed) - return -EPERM; - - /* Denies privileged changes. */ - if (changed & ~unpriv_and_locks) - return -EPERM; - } + if (securebits_need_setpcap(old->securebits, arg2) && + !ns_capable(current_user_ns(), CAP_SETPCAP)) + return -EPERM; new = prepare_creds(); if (!new) diff --git a/security/keys/big_key.c b/security/keys/big_key.c index 268f702df380e1..aa3e82ac93ee23 100644 --- a/security/keys/big_key.c +++ b/security/keys/big_key.c @@ -193,16 +193,24 @@ void big_key_destroy(struct key *key) */ int big_key_update(struct key *key, struct key_preparsed_payload *prep) { + struct big_key_payload old = { }; + bool positive = key_is_positive(key); int ret; - ret = key_payload_reserve(key, prep->datalen); + if (positive) + old = *to_big_key_payload(key->payload); + + ret = generic_key_instantiate(key, prep); if (ret < 0) return ret; - if (key_is_positive(key)) - big_key_destroy(key); + if (positive) { + if (old.length > BIG_KEY_FILE_THRESHOLD) + path_put(&old.path); + kfree_sensitive(old.data); + } - return generic_key_instantiate(key, prep); + return 0; } /* diff --git a/security/keys/key.c b/security/keys/key.c index 3f1f0fc137109a..df31d1024340ef 100644 --- a/security/keys/key.c +++ b/security/keys/key.c @@ -441,6 +441,7 @@ static int __key_instantiate_and_link(struct key *key, ret = -EBUSY; mutex_lock(&key_construction_mutex); + down_write_nested(&key->sem, 2); /* can't instantiate twice */ if (key->state == KEY_IS_UNINSTANTIATED) { @@ -473,6 +474,7 @@ static int __key_instantiate_and_link(struct key *key, } } + up_write(&key->sem); mutex_unlock(&key_construction_mutex); /* wake up anyone waiting for a key to be constructed */ @@ -609,6 +611,7 @@ int key_reject_and_link(struct key *key, } mutex_lock(&key_construction_mutex); + down_write_nested(&key->sem, 2); /* can't instantiate twice */ if (key->state == KEY_IS_UNINSTANTIATED) { @@ -632,6 +635,7 @@ int key_reject_and_link(struct key *key, key_invalidate(authkey); } + up_write(&key->sem); mutex_unlock(&key_construction_mutex); if (keyring && link_ret == 0) diff --git a/security/keys/keyctl_pkey.c b/security/keys/keyctl_pkey.c index e7121523b9c9ac..e10d4ad0a3e1b5 100644 --- a/security/keys/keyctl_pkey.c +++ b/security/keys/keyctl_pkey.c @@ -113,7 +113,8 @@ static int keyctl_pkey_params_get(key_serial_t id, static int keyctl_pkey_params_get_2(const struct keyctl_pkey_params __user *_params, const char __user *_info, int op, - struct kernel_pkey_params *params) + struct kernel_pkey_params *params, + u32 *user_out_len) { struct keyctl_pkey_params uparams; struct kernel_pkey_query info; @@ -175,7 +176,7 @@ static int keyctl_pkey_params_get_2(const struct keyctl_pkey_params __user *_par goto out_up_key_sem; } - params->out_len = info.max_sig_size; + params->in2_len = uparams.in2_len; break; default: ret = -EOPNOTSUPP; @@ -183,6 +184,8 @@ static int keyctl_pkey_params_get_2(const struct keyctl_pkey_params __user *_par } params->in_len = uparams.in_len; + if (user_out_len) + *user_out_len = uparams.out_len; switch (op) { case KEYCTL_PKEY_VERIFY: @@ -264,10 +267,12 @@ long keyctl_pkey_e_d_s(int op, void __user *_out) { struct kernel_pkey_params params; + u32 user_out_len; void *in, *out; long ret; - ret = keyctl_pkey_params_get_2(_params, _info, op, ¶ms); + ret = keyctl_pkey_params_get_2(_params, _info, op, ¶ms, + &user_out_len); if (ret < 0) goto error_params; @@ -310,13 +315,17 @@ long keyctl_pkey_e_d_s(int op, if (ret < 0) goto error_out; + if (ret > user_out_len) { + ret = -EOVERFLOW; + goto error_out; + } if (copy_to_user(_out, out, ret) != 0) ret = -EFAULT; error_out: - kfree(out); + kfree_sensitive(out); error_in: - kfree(in); + kfree_sensitive(in); error_params: keyctl_pkey_params_free(¶ms); return ret; @@ -349,7 +358,7 @@ long keyctl_pkey_verify(const struct keyctl_pkey_params __user *_params, long ret; ret = keyctl_pkey_params_get_2(_params, _info, KEYCTL_PKEY_VERIFY, - ¶ms); + ¶ms, NULL); if (ret < 0) goto out_free_params; diff --git a/security/keys/trusted-keys/trusted_caam.c b/security/keys/trusted-keys/trusted_caam.c index 6a33dbf2a7f55e..33000d7bb1cca4 100644 --- a/security/keys/trusted-keys/trusted_caam.c +++ b/security/keys/trusted-keys/trusted_caam.c @@ -110,7 +110,7 @@ static int trusted_caam_seal(struct trusted_key_payload *p, char *datablob) info.pkey_info.is_pkey = 1; ret = get_pkey_options(datablob, &info.pkey_info); if (ret < 0) - return 0; + return ret; dump_options(&info.pkey_info); } @@ -142,7 +142,7 @@ static int trusted_caam_unseal(struct trusted_key_payload *p, char *datablob) info.pkey_info.is_pkey = 1; ret = get_pkey_options(datablob, &info.pkey_info); if (ret < 0) - return 0; + return ret; dump_options(&info.pkey_info); p->key_len = p->blob_len + sizeof(struct caam_pkey_info); diff --git a/security/keys/trusted-keys/trusted_core.c b/security/keys/trusted-keys/trusted_core.c index 0509d9955f2a6f..11d7d296d063c2 100644 --- a/security/keys/trusted-keys/trusted_core.c +++ b/security/keys/trusted-keys/trusted_core.c @@ -373,14 +373,19 @@ static int __init init_trusted(void) if (!get_random) get_random = kernel_get_random; + static_call_update(trusted_key_seal, trusted_key_sources[i].ops->seal); + static_call_update(trusted_key_unseal, trusted_key_sources[i].ops->unseal); + static_call_update(trusted_key_get_random, get_random); + migratable = trusted_key_sources[i].ops->migratable; + ret = trusted_key_sources[i].ops->init(); if (!ret) { - static_call_update(trusted_key_seal, trusted_key_sources[i].ops->seal); - static_call_update(trusted_key_unseal, trusted_key_sources[i].ops->unseal); - static_call_update(trusted_key_get_random, get_random); - trusted_key_exit = trusted_key_sources[i].ops->exit; - migratable = trusted_key_sources[i].ops->migratable; + } else { + static_call_update(trusted_key_seal, NULL); + static_call_update(trusted_key_unseal, NULL); + static_call_update(trusted_key_get_random, NULL); + migratable = 0; } if (!ret || ret != -ENODEV) diff --git a/security/keys/trusted-keys/trusted_tee.c b/security/keys/trusted-keys/trusted_tee.c index 6e465c8bef5e5b..87ea549f7f0b97 100644 --- a/security/keys/trusted-keys/trusted_tee.c +++ b/security/keys/trusted-keys/trusted_tee.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -56,6 +57,8 @@ struct trusted_key_tee_private { }; static struct trusted_key_tee_private pvt_data; +/* Do not hold this mutex across key type registration or unregistration. */ +static DEFINE_MUTEX(trusted_key_tee_mutex); /* * Have the TEE seal(encrypt) the symmetric key @@ -67,6 +70,12 @@ static int trusted_tee_seal(struct trusted_key_payload *p, char *datablob) struct tee_param param[4]; struct tee_shm *reg_shm = NULL; + mutex_lock(&trusted_key_tee_mutex); + if (!pvt_data.ctx) { + ret = -ENODEV; + goto out_unlock; + } + memset(&inv_arg, 0, sizeof(inv_arg)); memset(¶m, 0, sizeof(param)); @@ -74,7 +83,8 @@ static int trusted_tee_seal(struct trusted_key_payload *p, char *datablob) sizeof(p->key) + sizeof(p->blob)); if (IS_ERR(reg_shm)) { dev_err(pvt_data.dev, "shm register failed\n"); - return PTR_ERR(reg_shm); + ret = PTR_ERR(reg_shm); + goto out_unlock; } inv_arg.func = TA_CMD_SEAL; @@ -100,7 +110,8 @@ static int trusted_tee_seal(struct trusted_key_payload *p, char *datablob) } tee_shm_free(reg_shm); - +out_unlock: + mutex_unlock(&trusted_key_tee_mutex); return ret; } @@ -114,6 +125,12 @@ static int trusted_tee_unseal(struct trusted_key_payload *p, char *datablob) struct tee_param param[4]; struct tee_shm *reg_shm = NULL; + mutex_lock(&trusted_key_tee_mutex); + if (!pvt_data.ctx) { + ret = -ENODEV; + goto out_unlock; + } + memset(&inv_arg, 0, sizeof(inv_arg)); memset(¶m, 0, sizeof(param)); @@ -121,7 +138,8 @@ static int trusted_tee_unseal(struct trusted_key_payload *p, char *datablob) sizeof(p->key) + sizeof(p->blob)); if (IS_ERR(reg_shm)) { dev_err(pvt_data.dev, "shm register failed\n"); - return PTR_ERR(reg_shm); + ret = PTR_ERR(reg_shm); + goto out_unlock; } inv_arg.func = TA_CMD_UNSEAL; @@ -147,7 +165,8 @@ static int trusted_tee_unseal(struct trusted_key_payload *p, char *datablob) } tee_shm_free(reg_shm); - +out_unlock: + mutex_unlock(&trusted_key_tee_mutex); return ret; } @@ -161,13 +180,20 @@ static int trusted_tee_get_random(unsigned char *key, size_t key_len) struct tee_param param[4]; struct tee_shm *reg_shm = NULL; + mutex_lock(&trusted_key_tee_mutex); + if (!pvt_data.ctx) { + ret = -ENODEV; + goto out_unlock; + } + memset(&inv_arg, 0, sizeof(inv_arg)); memset(¶m, 0, sizeof(param)); reg_shm = tee_shm_register_kernel_buf(pvt_data.ctx, key, key_len); if (IS_ERR(reg_shm)) { dev_err(pvt_data.dev, "key shm register failed\n"); - return PTR_ERR(reg_shm); + ret = PTR_ERR(reg_shm); + goto out_unlock; } inv_arg.func = TA_CMD_GET_RANDOM; @@ -189,7 +215,8 @@ static int trusted_tee_get_random(unsigned char *key, size_t key_len) } tee_shm_free(reg_shm); - +out_unlock: + mutex_unlock(&trusted_key_tee_mutex); return ret; } @@ -205,50 +232,67 @@ static int optee_ctx_match(struct tee_ioctl_version_data *ver, const void *data) static int trusted_key_probe(struct tee_client_device *rng_device) { struct device *dev = &rng_device->dev; + struct tee_context *ctx; int ret; struct tee_ioctl_open_session_arg sess_arg; + mutex_lock(&trusted_key_tee_mutex); + if (pvt_data.ctx) { + ret = -EBUSY; + goto out_unlock; + } + memset(&sess_arg, 0, sizeof(sess_arg)); - pvt_data.ctx = tee_client_open_context(NULL, optee_ctx_match, NULL, - NULL); - if (IS_ERR(pvt_data.ctx)) - return -ENODEV; + ctx = tee_client_open_context(NULL, optee_ctx_match, NULL, NULL); + if (IS_ERR(ctx)) { + ret = -ENODEV; + goto out_unlock; + } memcpy(sess_arg.uuid, rng_device->id.uuid.b, TEE_IOCTL_UUID_LEN); sess_arg.clnt_login = TEE_IOCTL_LOGIN_REE_KERNEL; sess_arg.num_params = 0; - ret = tee_client_open_session(pvt_data.ctx, &sess_arg, NULL); + ret = tee_client_open_session(ctx, &sess_arg, NULL); if ((ret < 0) || (sess_arg.ret != 0)) { dev_err(dev, "tee_client_open_session failed, err: %x\n", sess_arg.ret); ret = -EINVAL; goto out_ctx; } + pvt_data.ctx = ctx; pvt_data.session_id = sess_arg.session; - - ret = register_key_type(&key_type_trusted); - if (ret < 0) - goto out_sess; - pvt_data.dev = dev; + mutex_unlock(&trusted_key_tee_mutex); - return 0; + ret = register_key_type(&key_type_trusted); + if (!ret) + return 0; -out_sess: - tee_client_close_session(pvt_data.ctx, pvt_data.session_id); + mutex_lock(&trusted_key_tee_mutex); + tee_client_close_session(ctx, pvt_data.session_id); out_ctx: - tee_client_close_context(pvt_data.ctx); - + tee_client_close_context(ctx); + pvt_data.ctx = NULL; + pvt_data.dev = NULL; + pvt_data.session_id = 0; +out_unlock: + mutex_unlock(&trusted_key_tee_mutex); return ret; } static void trusted_key_remove(struct tee_client_device *dev) { unregister_key_type(&key_type_trusted); + + mutex_lock(&trusted_key_tee_mutex); tee_client_close_session(pvt_data.ctx, pvt_data.session_id); tee_client_close_context(pvt_data.ctx); + pvt_data.ctx = NULL; + pvt_data.dev = NULL; + pvt_data.session_id = 0; + mutex_unlock(&trusted_key_tee_mutex); } static const struct tee_client_device_id trusted_key_id_table[] = { @@ -263,7 +307,8 @@ static struct tee_client_driver trusted_key_driver = { .remove = trusted_key_remove, .id_table = trusted_key_id_table, .driver = { - .name = DRIVER_NAME, + .name = DRIVER_NAME, + .suppress_bind_attrs = true, }, }; diff --git a/security/landlock/access.h b/security/landlock/access.h index f9eaa2f536866d..72afd236f883e6 100644 --- a/security/landlock/access.h +++ b/security/landlock/access.h @@ -18,10 +18,9 @@ #include "limits.h" /* - * All access rights that are denied by default whether they are handled or not - * by a ruleset/layer. This must be ORed with the .handled field of all - * domain->layers[] entries when we need to get the absolute handled access - * masks, see landlock_upgrade_handled_layer_config(). + * All filesystem access rights that are denied by default when a layer handles + * any filesystem access right, even if they are not explicitly declared as + * handled themselves. See landlock_upgrade_handled_layer_config(). */ /* clang-format off */ #define _LANDLOCK_ACCESS_FS_INITIALLY_DENIED ( \ @@ -178,8 +177,8 @@ static inline struct layer_config landlock_upgrade_handled_layer_config(struct layer_config layer_config) { /* - * All access rights that are denied by default whether they are - * explicitly handled or not. + * All filesystem access rights that are denied by default as soon as + * any other filesystem access right is handled. */ if (layer_config.handled.fs) layer_config.handled.fs |= _LANDLOCK_ACCESS_FS_INITIALLY_DENIED; diff --git a/security/landlock/audit.c b/security/landlock/audit.c index be49ef47b4eacc..6d9e54f5deedfb 100644 --- a/security/landlock/audit.c +++ b/security/landlock/audit.c @@ -80,7 +80,8 @@ get_blocker(const enum landlock_request_type type, WARN_ON_ONCE(access_bit != -1); return scope_strings[BIT_INDEX(LANDLOCK_SCOPE_SIGNAL)]; - case LANDLOCK_REQUEST_NAMESPACE: + case LANDLOCK_REQUEST_NAMESPACE_CREATE: + case LANDLOCK_REQUEST_NAMESPACE_ENTER: case LANDLOCK_REQUEST_CAPABILITY: if (WARN_ON_ONCE(access_bit >= ARRAY_SIZE(permission_strings))) return "unknown"; @@ -115,7 +116,8 @@ blocker_prefix(const enum landlock_request_type type) case LANDLOCK_REQUEST_SCOPE_SIGNAL: return "scope."; - case LANDLOCK_REQUEST_NAMESPACE: + case LANDLOCK_REQUEST_NAMESPACE_CREATE: + case LANDLOCK_REQUEST_NAMESPACE_ENTER: return _LANDLOCK_PERMISSION_NAMESPACE_NAME "."; case LANDLOCK_REQUEST_CAPABILITY: @@ -212,6 +214,10 @@ void landlock_audit_denial(const struct landlock_request *const request, audit_log_format(ab, "domain=%llx blockers=", youngest_denied->id); log_blockers(ab, request->type, missing); + if (request->type == LANDLOCK_REQUEST_NAMESPACE_CREATE) + audit_log_format(ab, " namespace_op=create"); + else if (request->type == LANDLOCK_REQUEST_NAMESPACE_ENTER) + audit_log_format(ab, " namespace_op=enter"); audit_log_lsm_data(ab, &request->audit); audit_log_end(ab); diff --git a/security/landlock/cap.c b/security/landlock/cap.c index b4f491b09baa79..ae3acd13a367ad 100644 --- a/security/landlock/cap.c +++ b/security/landlock/cap.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #include "cap.h" @@ -24,25 +25,26 @@ static const struct access_masks cap_permission = { }; /** - * hook_capable - Deny capability use for Landlock-sandboxed processes + * check_cap - Check a capability use against the domain of @cred * * @cred: Credentials being checked. - * @ns: Target user namespace (intentionally ignored; policy depends on the - * acting credentials and @cap, not namespace ownership). + * @ns: Target user namespace used by commoncap's capability check, which is + * not necessarily @cred->user_ns. It is forwarded unchanged to typed + * trace context but is not used for the verdict (policy depends on @cred + * and @cap). * @cap: Capability number (CAP_*). * @opts: Capability check options. CAP_OPT_NOAUDIT skips the denial record: * no audit record, no trace event, and no denial count. * * Pure bitmask check: denies the capability if it is not in the layer's allowed - * set. This hook is purely restrictive: commoncap is registered with - * LSM_ORDER_FIRST so cap_capable() always runs first, which means Landlock can - * deny capabilities that commoncap would allow, but never grant capabilities - * that commoncap denied. + * set. It does not check that @cred holds @cap: only call it for a capability + * that commoncap already granted. * * Return: 0 if allowed, -EPERM if capability use is denied. */ -static int hook_capable(const struct cred *cred, struct user_namespace *ns, - int cap, unsigned int opts) +static int check_cap(const struct cred *const cred, + struct user_namespace *const ns, const int cap, + const unsigned int opts) { const struct landlock_cred_security *subject; size_t denied_layer; @@ -67,13 +69,123 @@ static int hook_capable(const struct cred *cred, struct user_namespace *ns, .permission = LANDLOCK_PERMISSION_CAPABILITY_USE, .layer_plus_one = denied_layer, +#ifdef CONFIG_TRACEPOINTS + .trace_cap = + &(struct landlock_cap_trace){ + .cred = cred, + .user_ns = ns, + }, +#endif /* CONFIG_TRACEPOINTS */ }); return -EPERM; } +/** + * hook_capable - Deny capability use for Landlock-sandboxed processes + * + * @cred: Credentials being checked. + * @ns: Target user namespace, used only as typed trace context. + * @cap: Capability number (CAP_*). + * @opts: Capability check options, see check_cap(). + * + * This hook is purely restrictive: commoncap is registered with LSM_ORDER_FIRST + * so cap_capable() always runs first, which means Landlock can deny + * capabilities that commoncap would allow, but never grant capabilities that + * commoncap denied. + * + * Return: 0 if allowed, -EPERM if capability use is denied. + */ +static int hook_capable(const struct cred *cred, struct user_namespace *ns, + int cap, unsigned int opts) +{ + return check_cap(cred, ns, cap, opts); +} + +/** + * hook_capset - Restrict inheritable capability changes + * + * @new: New credentials (unused). + * @old: Current credentials. + * @effective: New effective set (unused). + * @inheritable: New inheritable set. + * @permitted: New permitted set (unused). + * + * cap_capset() denies a new inheritable set that is not a subset of the old + * inheritable and permitted sets, unless cap_inh_is_capped() finds CAP_SETPCAP. + * This check uses cap_capable(), which skips hook_capable(). commoncap runs + * first, so such a set reaching this hook means that commoncap granted + * CAP_SETPCAP: check it against the domain. capset(2) discards @new if this + * hook fails, so nothing is committed. + * + * Return: 0 if allowed, -EPERM if CAP_SETPCAP use is denied. + */ +static int hook_capset(struct cred *new, const struct cred *old, + const kernel_cap_t *effective, + const kernel_cap_t *inheritable, + const kernel_cap_t *permitted) +{ + if (cap_issubset(*inheritable, + cap_combine(old->cap_inheritable, old->cap_permitted))) + return 0; + + return check_cap(old, old->user_ns, CAP_SETPCAP, CAP_OPT_NONE); +} + +/** + * hook_mmap_addr - Restrict mappings below dac_mmap_min_addr + * + * @addr: Address of the new mapping. + * + * cap_mmap_addr() requires CAP_SYS_RAWIO to map below dac_mmap_min_addr, but + * calls cap_capable() directly, which skips hook_capable(). It checks the + * acting task's credentials against init_user_ns because this global limit must + * not be bypassed with a capability only held in a nested user namespace. + * Mirror the condition, using the same credential for the domain check and both + * objects for typed trace context. commoncap runs first, so this only sees + * mappings that commoncap allowed. + * + * Return: 0 if allowed, -EPERM if CAP_SYS_RAWIO use is denied. + */ +static int hook_mmap_addr(unsigned long addr) +{ + if (addr >= dac_mmap_min_addr) + return 0; + + return check_cap(current_cred(), &init_user_ns, CAP_SYS_RAWIO, + CAP_OPT_NONE); +} + +/** + * hook_vm_enough_memory - Restrict the admin memory reserve + * + * @mm: Address space being charged (unused). + * @pages: Number of pages being charged (unused). + * + * cap_vm_enough_memory() lets CAP_SYS_ADMIN use the vm.admin_reserve_kbytes + * reserve, but calls cap_capable() directly, which skips hook_capable(). It + * checks the acting task's credentials against init_user_ns because a + * capability only held in a nested user namespace must not grant access to the + * global reserve. Mirror the check, using the same credential for the domain + * check and both objects for typed trace context. commoncap runs first, so + * this only sees tasks that commoncap let use the reserve. Like commoncap, do + * not log denials: this only selects a memory limit. + * + * Return: 0 if the domain does not withhold the reserve, -EPERM if + * CAP_SYS_ADMIN use is denied. An error does not fail the allocation by + * itself, but without the reserve, the allocation may fail with -ENOMEM. + */ +static int hook_vm_enough_memory(struct mm_struct *mm, long pages) +{ + return check_cap(current_cred(), &init_user_ns, CAP_SYS_ADMIN, + CAP_OPT_NOAUDIT); +} + static struct security_hook_list landlock_hooks[] __ro_after_init = { LSM_HOOK_INIT(capable, hook_capable), + LSM_HOOK_INIT(capset, hook_capset), + LSM_HOOK_INIT(mmap_addr, hook_mmap_addr), + LSM_HOOK_INIT(vm_enough_memory, hook_vm_enough_memory), }; __init void landlock_add_cap_hooks(void) diff --git a/security/landlock/domain.c b/security/landlock/domain.c index 4c0b1f0e1db5df..71756c68d08e74 100644 --- a/security/landlock/domain.c +++ b/security/landlock/domain.c @@ -753,6 +753,49 @@ static void test_landlock_get_deny_masks(struct kunit *const test) &layers1)); } +static void test_get_fs_access_mask(struct kunit *const test) +{ + static const struct { + struct layer_config config; + access_mask_t expected_fs; + } layers[] = { + { + .config.handled.net = LANDLOCK_ACCESS_NET_BIND_TCP, + .expected_fs = 0, + }, + { + .config.handled.scope = LANDLOCK_SCOPE_SIGNAL, + .expected_fs = 0, + }, + { + .config.handled.fs = LANDLOCK_ACCESS_FS_EXECUTE, + .expected_fs = LANDLOCK_ACCESS_FS_EXECUTE | + LANDLOCK_ACCESS_FS_REFER, + }, + { + .config.handled.fs = LANDLOCK_ACCESS_FS_REFER, + .expected_fs = LANDLOCK_ACCESS_FS_REFER, + }, + }; + struct landlock_domain *domain; + size_t i; + + domain = kunit_kzalloc(test, + struct_size(domain, layers, ARRAY_SIZE(layers)), + GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, domain); + domain->num_layers = ARRAY_SIZE(layers); + + for (i = 0; i < ARRAY_SIZE(layers); i++) + domain->layers[i] = + landlock_upgrade_handled_layer_config(layers[i].config); + + for (i = 0; i < ARRAY_SIZE(layers); i++) + KUNIT_EXPECT_EQ_MSG(test, layers[i].expected_fs, + landlock_get_fs_access_mask(domain, i), + "layer %zu", i); +} + #endif /* CONFIG_SECURITY_LANDLOCK_KUNIT_TEST */ #ifdef CONFIG_SECURITY_LANDLOCK_KUNIT_TEST @@ -761,6 +804,7 @@ static struct kunit_case test_cases[] = { /* clang-format off */ KUNIT_CASE(test_get_layer_deny_mask), KUNIT_CASE(test_landlock_get_deny_masks), + KUNIT_CASE(test_get_fs_access_mask), {} /* clang-format on */ }; diff --git a/security/landlock/domain.h b/security/landlock/domain.h index 935e18b12b3cc8..812c324cb6ef22 100644 --- a/security/landlock/domain.h +++ b/security/landlock/domain.h @@ -262,9 +262,12 @@ static inline access_mask_t landlock_get_fs_access_mask(const struct landlock_domain *const domain, const u16 layer_level) { - /* Handles all initially denied by default access rights. */ - return domain->layers[layer_level].handled.fs | - _LANDLOCK_ACCESS_FS_INITIALLY_DENIED; + /* + * Initially denied by default access rights are already included for + * layers handling filesystem accesses, see + * landlock_upgrade_handled_layer_config(). + */ + return domain->layers[layer_level].handled.fs; } static inline access_mask_t diff --git a/security/landlock/errata/abi-4.h b/security/landlock/errata/abi-4.h index fe11ec7d7ddf55..9784ca64507305 100644 --- a/security/landlock/errata/abi-4.h +++ b/security/landlock/errata/abi-4.h @@ -20,3 +20,24 @@ * that rely on these protocols while using Landlock network restrictions. */ LANDLOCK_ERRATUM(1) + +/** + * DOC: erratum_5 + * + * Erratum 5: Denial of ``LANDLOCK_ACCESS_FS_REFER`` in layered domains + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * This fix addresses an issue where ``LANDLOCK_ACCESS_FS_REFER`` was implicitly + * handled in domain layers that handle no filesystem access rights. + * + * With this fix, a reparenting operation is allowed in a layered Landlock + * domain if and only if each layer, enforced on its own, would allow it. + * + * Impact: + * + * In kernels without this fix, if a domain combined a layer that handles + * filesystem access rights with a layer that doesn't, the resulting layered + * domain would deny all ``LANDLOCK_ACCESS_FS_REFER`` operations, even when the + * filesystem layer granted these operations with a rule. + */ +LANDLOCK_ERRATUM(5) diff --git a/security/landlock/log.c b/security/landlock/log.c index 43efbb95725c37..c132b343f0ee06 100644 --- a/security/landlock/log.c +++ b/security/landlock/log.c @@ -388,7 +388,8 @@ static bool is_valid_request(const struct landlock_request *const request) return false; switch (request->type) { - case LANDLOCK_REQUEST_NAMESPACE: + case LANDLOCK_REQUEST_NAMESPACE_CREATE: + case LANDLOCK_REQUEST_NAMESPACE_ENTER: if (WARN_ON_ONCE(request->permission != LANDLOCK_PERMISSION_NAMESPACE_USE) || WARN_ON_ONCE(request->audit.type != LSM_AUDIT_DATA_NS)) @@ -485,7 +486,8 @@ is_denial_quieted(const struct landlock_request *const request, case LANDLOCK_REQUEST_SCOPE_ABSTRACT_UNIX_SOCKET: return !!(youngest_denied->quiet_access.scope & LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET); - case LANDLOCK_REQUEST_NAMESPACE: + case LANDLOCK_REQUEST_NAMESPACE_CREATE: + case LANDLOCK_REQUEST_NAMESPACE_ENTER: return !!(youngest_denied->quiet_permission.ns_types & landlock_ns_type_to_bit(request->audit.u.ns.ns_type)); case LANDLOCK_REQUEST_CAPABILITY: diff --git a/security/landlock/log.h b/security/landlock/log.h index 596feeeb7aa61a..5ca87870c7b788 100644 --- a/security/landlock/log.h +++ b/security/landlock/log.h @@ -13,10 +13,12 @@ #include "access.h" +struct cred; struct landlock_cred_security; struct landlock_hierarchy; struct sockaddr; struct task_struct; +struct user_namespace; enum landlock_request_type { LANDLOCK_REQUEST_PTRACE = 1, @@ -25,7 +27,8 @@ enum landlock_request_type { LANDLOCK_REQUEST_NET_ACCESS, LANDLOCK_REQUEST_SCOPE_ABSTRACT_UNIX_SOCKET, LANDLOCK_REQUEST_SCOPE_SIGNAL, - LANDLOCK_REQUEST_NAMESPACE, + LANDLOCK_REQUEST_NAMESPACE_CREATE, + LANDLOCK_REQUEST_NAMESPACE_ENTER, LANDLOCK_REQUEST_CAPABILITY, }; @@ -53,6 +56,11 @@ struct landlock_signal_trace { int signal; }; +struct landlock_cap_trace { + const struct cred *cred; + const struct user_namespace *user_ns; +}; + #endif /* CONFIG_TRACEPOINTS */ /* @@ -103,6 +111,8 @@ struct landlock_request { const struct landlock_ptrace_trace *trace_ptrace; /* Synchronous context for a signal denial. */ const struct landlock_signal_trace *trace_signal; + /* Synchronous context for a capability denial. */ + const struct landlock_cap_trace *trace_cap; }; #endif /* CONFIG_TRACEPOINTS */ }; diff --git a/security/landlock/ns.c b/security/landlock/ns.c index 06d9784746fe9e..3d443599b16f42 100644 --- a/security/landlock/ns.c +++ b/security/landlock/ns.c @@ -90,6 +90,7 @@ static const struct access_masks ns_permission = { * check_ns_type - Check namespace use permission * * @ns: The namespace being allocated or installed. + * @request_type: Namespace operation reported on denial. * * Shared check for namespace_init (creation via clone(2), unshare(2), * open_tree(2), or fsmount(2)) and namespace_install (use via setns(2)): denies @@ -99,7 +100,8 @@ static const struct access_masks ns_permission = { * * Return: 0 if allowed, -EPERM if denied. */ -static int check_ns_type(struct ns_common *const ns) +static int check_ns_type(struct ns_common *const ns, + const enum landlock_request_type request_type) { const struct landlock_cred_security *subject; size_t denied_layer; @@ -117,7 +119,7 @@ static int check_ns_type(struct ns_common *const ns) landlock_log_denial(subject, &(struct landlock_request){ - .type = LANDLOCK_REQUEST_NAMESPACE, + .type = request_type, .audit.type = LSM_AUDIT_DATA_NS, .permission = LANDLOCK_PERMISSION_NAMESPACE_USE, @@ -130,13 +132,13 @@ static int check_ns_type(struct ns_common *const ns) static int hook_namespace_init(struct ns_common *const ns) { - return check_ns_type(ns); + return check_ns_type(ns, LANDLOCK_REQUEST_NAMESPACE_CREATE); } static int hook_namespace_install(const struct nsset *const nsset, struct ns_common *const ns) { - return check_ns_type(ns); + return check_ns_type(ns, LANDLOCK_REQUEST_NAMESPACE_ENTER); } static struct security_hook_list landlock_hooks[] __ro_after_init = { diff --git a/security/landlock/syscalls.c b/security/landlock/syscalls.c index fb5af318b69bb4..29e9d5d7399d64 100644 --- a/security/landlock/syscalls.c +++ b/security/landlock/syscalls.c @@ -629,6 +629,7 @@ static int add_rule_capability(struct landlock_ruleset *const ruleset, * - %EAFNOSUPPORT: @rule_type is %LANDLOCK_RULE_NET_PORT but TCP/IP is not * supported by the running kernel; * - %EINVAL: @flags is not valid; + * - %EINVAL: @rule_type is not valid; * - %EINVAL: The rule accesses are inconsistent (i.e. * &landlock_path_beneath_attr.allowed_access or * &landlock_net_port_attr.allowed_access is not a subset of the ruleset diff --git a/security/landlock/trace.c b/security/landlock/trace.c index 995c6b948e16eb..a47fb10dec459e 100644 --- a/security/landlock/trace.c +++ b/security/landlock/trace.c @@ -81,7 +81,8 @@ void landlock_trace_denial( const access_mask_t missing, const bool same_exec, const bool logged) { switch (request->type) { - case LANDLOCK_REQUEST_NAMESPACE: + case LANDLOCK_REQUEST_NAMESPACE_CREATE: + case LANDLOCK_REQUEST_NAMESPACE_ENTER: if (trace_landlock_deny_permission_namespace_enabled()) { const struct landlock_blockers blockers = { .access = missing, @@ -96,14 +97,21 @@ void landlock_trace_denial( break; case LANDLOCK_REQUEST_CAPABILITY: if (trace_landlock_deny_permission_capability_enabled()) { + const struct landlock_cap_trace *const trace_cap = + request->trace_cap; const struct landlock_blockers blockers = { .access = missing, .type = request->type, }; + if (WARN_ON_ONCE(!trace_cap || !trace_cap->cred || + !trace_cap->user_ns)) + return; + trace_landlock_deny_permission_capability( youngest_denied, same_exec, logged, &blockers, - request->audit.u.cap); + request->audit.u.cap, trace_cap->cred, + trace_cap->user_ns); } break; case LANDLOCK_REQUEST_FS_ACCESS: diff --git a/security/selinux/hooks.c b/security/selinux/hooks.c index 9950f89dfaa230..6c4c64d6e9042f 100644 --- a/security/selinux/hooks.c +++ b/security/selinux/hooks.c @@ -4179,8 +4179,11 @@ static int selinux_mmap_file(struct file *file, unsigned long reqprot __always_unused, unsigned long prot, unsigned long flags) { + const unsigned long map_type = (flags & MAP_TYPE); + return selinux_mmap_file_common(file, prot, - (flags & MAP_TYPE) == MAP_SHARED, + (map_type == MAP_SHARED || + map_type == MAP_SHARED_VALIDATE), false); } diff --git a/sound/aoa/core/alsa.c b/sound/aoa/core/alsa.c index aad7dfe089c7d8..bc7e576ab2794d 100644 --- a/sound/aoa/core/alsa.c +++ b/sound/aoa/core/alsa.c @@ -64,7 +64,8 @@ int aoa_snd_device_new(enum snd_device_type type, struct snd_card *card = aoa_get_card(); int err; - if (!card) return -ENOMEM; + if (!card) + return -ENODEV; err = snd_device_new(card, type, device_data, ops); if (err) { diff --git a/sound/aoa/core/core.c b/sound/aoa/core/core.c index 99b032a4081fd2..09eeadba4277f2 100644 --- a/sound/aoa/core/core.c +++ b/sound/aoa/core/core.c @@ -72,12 +72,9 @@ EXPORT_SYMBOL_GPL(aoa_codec_register); void aoa_codec_unregister(struct aoa_codec *codec) { list_del(&codec->list); - if (codec->fabric && codec->exit) - codec->exit(codec); - if (fabric && fabric->remove_codec) - fabric->remove_codec(codec); - codec->fabric = NULL; - module_put(codec->owner); + + if (codec->fabric) + aoa_fabric_unlink_codec(codec); } EXPORT_SYMBOL_GPL(aoa_codec_unregister); diff --git a/sound/aoa/core/gpio-feature.c b/sound/aoa/core/gpio-feature.c index 19ed0e6907da3f..2549b660caa450 100644 --- a/sound/aoa/core/gpio-feature.c +++ b/sound/aoa/core/gpio-feature.c @@ -285,9 +285,9 @@ static void ftr_gpio_exit(struct gpio_runtime *rt) rt->implementation_private = 0; if (rt->headphone_notify.notify) free_irq(headphone_detect_irq, &rt->headphone_notify); - if (rt->line_in_notify.gpio_private) + if (rt->line_in_notify.notify) free_irq(linein_detect_irq, &rt->line_in_notify); - if (rt->line_out_notify.gpio_private) + if (rt->line_out_notify.notify) free_irq(lineout_detect_irq, &rt->line_out_notify); cancel_delayed_work_sync(&rt->headphone_notify.work); cancel_delayed_work_sync(&rt->line_in_notify.work); diff --git a/sound/atmel/ac97c.c b/sound/atmel/ac97c.c index 234549e17351c9..3ab6ddb3259fce 100644 --- a/sound/atmel/ac97c.c +++ b/sound/atmel/ac97c.c @@ -670,7 +670,7 @@ static void atmel_ac97c_reset(struct atmel_ac97c *chip) ac97c_writel(chip, CAMR, 0); ac97c_writel(chip, COMR, 0); - if (!IS_ERR(chip->reset_pin)) { + if (chip->reset_pin) { gpiod_set_value(chip->reset_pin, 0); /* AC97 v2.2 specifications says minimum 1 us. */ udelay(2); @@ -743,9 +743,13 @@ static int atmel_ac97c_probe(struct platform_device *pdev) chip->pdev = pdev; chip->regs = regs; - chip->reset_pin = devm_gpiod_get_index(dev, "ac97", 2, GPIOD_OUT_HIGH); + chip->reset_pin = devm_gpiod_get_index_optional(dev, + "ac97", 2, + GPIOD_OUT_HIGH); if (IS_ERR(chip->reset_pin)) - dev_dbg(dev, "reset pin not available\n"); + return dev_err_probe(dev, + PTR_ERR(chip->reset_pin), + "failed to get reset GPIO\n"); atmel_ac97c_reset(chip); diff --git a/sound/core/memalloc.c b/sound/core/memalloc.c index 5986e9b84ac0a2..8fec4a8fd219e9 100644 --- a/sound/core/memalloc.c +++ b/sound/core/memalloc.c @@ -294,17 +294,21 @@ static void *do_alloc_pages(struct device *dev, size_t size, dma_addr_t *addr, if (!p) return NULL; *addr = page_to_phys(virt_to_page(p)); - if (!dev) + if (!dev || !dev->coherent_dma_mask) return p; if ((*addr + size - 1) & ~dev->coherent_dma_mask) { - if (IS_ENABLED(CONFIG_ZONE_DMA32) && !(gfp & GFP_DMA32)) { + if (IS_ENABLED(CONFIG_ZONE_DMA32) && !(gfp & (GFP_DMA32 | GFP_DMA))) { + free_pages_exact(p, size); gfp |= GFP_DMA32; goto again; } if (IS_ENABLED(CONFIG_ZONE_DMA) && !(gfp & GFP_DMA)) { + free_pages_exact(p, size); gfp = (gfp & ~GFP_DMA32) | GFP_DMA; goto again; } + free_pages_exact(p, size); + return NULL; } #ifdef CONFIG_X86 if (wc) diff --git a/sound/core/oss/pcm_oss.c b/sound/core/oss/pcm_oss.c index 2fc52fe2cb52ee..7850c5d757b6a9 100644 --- a/sound/core/oss/pcm_oss.c +++ b/sound/core/oss/pcm_oss.c @@ -921,7 +921,8 @@ static int snd_pcm_oss_change_params_locked(struct snd_pcm_substream *substream) goto failure; } format_found: - err = _snd_pcm_hw_param_set(sparams, SNDRV_PCM_HW_PARAM_FORMAT, sformat, 0); + err = snd_pcm_hw_param_set(substream, sparams, + SNDRV_PCM_HW_PARAM_FORMAT, sformat, 0); if (err < 0) goto failure; @@ -1246,8 +1247,8 @@ snd_pcm_sframes_t snd_pcm_oss_write3(struct snd_pcm_substream *substream, const break; } mutex_unlock(&runtime->oss.params_lock); - ret = __snd_pcm_lib_xfer(substream, (void *)ptr, true, - frames, in_kernel); + ret = snd_pcm_lib_get_and_xfer(substream, (void *)ptr, true, + frames, in_kernel); mutex_lock(&runtime->oss.params_lock); if (ret != -EPIPE && ret != -ESTRPIPE) break; @@ -1287,9 +1288,10 @@ snd_pcm_sframes_t snd_pcm_oss_read3(struct snd_pcm_substream *substream, char *p if (ret < 0) break; mutex_unlock(&runtime->oss.params_lock); - ret = __snd_pcm_lib_xfer(substream, (void *)ptr, true, - frames, in_kernel); + ret = snd_pcm_lib_get_and_xfer(substream, ptr, true, + frames, in_kernel); mutex_lock(&runtime->oss.params_lock); + if (ret == -EPIPE) { if (snd_pcm_get_state(substream) == SNDRV_PCM_STATE_DRAINING) { ret = snd_pcm_kernel_ioctl(substream, SNDRV_PCM_IOCTL_DROP, NULL); diff --git a/sound/core/pcm_compat.c b/sound/core/pcm_compat.c index c54cb07304ad49..924fd269dace61 100644 --- a/sound/core/pcm_compat.c +++ b/sound/core/pcm_compat.c @@ -293,6 +293,9 @@ static int snd_pcm_ioctl_xferi_compat(struct snd_pcm_substream *substream, return -ENOTTY; if (substream->stream != dir) return -EINVAL; + SND_PCM_BUFFER_ACQUIRE(substream->runtime, lock); + if (SND_PCM_BUFFER_ACQUIRE_ERR(lock)) + return -EBUSY; if (snd_pcm_get_state(substream) == SNDRV_PCM_STATE_OPEN) return -EBADFD; @@ -338,6 +341,9 @@ static int snd_pcm_ioctl_xfern_compat(struct snd_pcm_substream *substream, return -ENOTTY; if (substream->stream != dir) return -EINVAL; + SND_PCM_BUFFER_ACQUIRE(substream->runtime, lock); + if (SND_PCM_BUFFER_ACQUIRE_ERR(lock)) + return -EBUSY; if (snd_pcm_get_state(substream) == SNDRV_PCM_STATE_OPEN) return -EBADFD; diff --git a/sound/core/pcm_lib.c b/sound/core/pcm_lib.c index 65c7472ef22eb5..3d2db8a575a37f 100644 --- a/sound/core/pcm_lib.c +++ b/sound/core/pcm_lib.c @@ -2275,6 +2275,7 @@ int pcm_lib_apply_appl_ptr(struct snd_pcm_substream *substream, } /* the common loop for read/write data */ +/* the caller should reserve the buffer via runtime->buffer_access beforehand */ snd_pcm_sframes_t __snd_pcm_lib_xfer(struct snd_pcm_substream *substream, void *data, bool interleaved, snd_pcm_uframes_t size, bool in_kernel) @@ -2377,10 +2378,6 @@ snd_pcm_sframes_t __snd_pcm_lib_xfer(struct snd_pcm_substream *substream, err = -EINVAL; goto _end_unlock; } - if (!atomic_inc_unless_negative(&runtime->buffer_accessing)) { - err = -EBUSY; - goto _end_unlock; - } snd_pcm_stream_unlock_irq(substream); if (!is_playback) snd_pcm_dma_buffer_sync(substream, SNDRV_DMA_SYNC_CPU); @@ -2389,7 +2386,6 @@ snd_pcm_sframes_t __snd_pcm_lib_xfer(struct snd_pcm_substream *substream, if (is_playback) snd_pcm_dma_buffer_sync(substream, SNDRV_DMA_SYNC_DEVICE); snd_pcm_stream_lock_irq(substream); - atomic_dec(&runtime->buffer_accessing); if (err < 0) goto _end_unlock; err = pcm_accessible_state(substream); diff --git a/sound/core/pcm_native.c b/sound/core/pcm_native.c index da2b789962c213..c7768793422aed 100644 --- a/sound/core/pcm_native.c +++ b/sound/core/pcm_native.c @@ -718,14 +718,20 @@ static int snd_pcm_hw_params_choose(struct snd_pcm_substream *pcm, /* acquire buffer_mutex; if it's in r/w operation, return -EBUSY, otherwise * block the further r/w operations */ -static int snd_pcm_buffer_access_lock(struct snd_pcm_runtime *runtime) +static int __snd_pcm_buffer_access_lock(struct snd_pcm_runtime *runtime, + int depth) { if (!atomic_dec_unless_positive(&runtime->buffer_accessing)) return -EBUSY; - mutex_lock(&runtime->buffer_mutex); + mutex_lock_nested(&runtime->buffer_mutex, depth); return 0; /* keep buffer_mutex, unlocked by below */ } +static int snd_pcm_buffer_access_lock(struct snd_pcm_runtime *runtime) +{ + return __snd_pcm_buffer_access_lock(runtime, 0); +} + /* release buffer_mutex and clear r/w access flag */ static void snd_pcm_buffer_access_unlock(struct snd_pcm_runtime *runtime) { @@ -778,7 +784,7 @@ static int hw_params_state_check(struct snd_pcm_substream *substream, case SNDRV_PCM_STATE_OPEN: case SNDRV_PCM_STATE_SETUP: case SNDRV_PCM_STATE_PREPARED: - if (check_mmap && !is_oss_stream(substream) && + if (check_mmap && atomic_read(&substream->mmap_count)) return -EBADFD; return 0; @@ -1317,26 +1323,38 @@ struct action_ops { * this functions is core for handling of linked stream * Note: the stream state might be changed also on failure * Note2: call with calling stream lock + link lock + * + * Locking: + * When @stream_lock is false, it takes buffer-access lock for all substreams. + * OTOH, when @stream_lock is true, takes substream lock except for the + * target substream (that should have taken its lock before calling this). */ static int snd_pcm_action_group(const struct action_ops *ops, struct snd_pcm_substream *substream, snd_pcm_state_t state, bool stream_lock) { - struct snd_pcm_substream *s = NULL; - struct snd_pcm_substream *s1; - int res = 0, depth = 1; + struct snd_pcm_substream *s, *s1, *last; + int res = 0, depth; + /* the caller already holds the target stream lock at depth 0 */ + depth = stream_lock ? 1 : 0; + + last = NULL; snd_pcm_group_for_each_entry(s, substream) { - if (s != substream) { - if (!stream_lock) - mutex_lock_nested(&s->runtime->buffer_mutex, depth); - else if (s->pcm->nonatomic) + if (!stream_lock) { + res = __snd_pcm_buffer_access_lock(s->runtime, depth); + if (res < 0) + goto _unlock; + depth++; + } else if (s != substream) { + if (s->pcm->nonatomic) mutex_lock_nested(&s->self_group.mutex, depth); else spin_lock_nested(&s->self_group.lock, depth); depth++; } + last = s; res = ops->pre_action(s, state); if (res < 0) goto _unlock; @@ -1351,7 +1369,6 @@ static int snd_pcm_action_group(const struct action_ops *ops, ops->undo_action(s1, state); } } - s = NULL; /* unlock all */ goto _unlock; } } @@ -1359,17 +1376,19 @@ static int snd_pcm_action_group(const struct action_ops *ops, ops->post_action(s, state); } _unlock: + if (!last) + return res; /* unlock streams */ - snd_pcm_group_for_each_entry(s1, substream) { - if (s1 != substream) { - if (!stream_lock) - mutex_unlock(&s1->runtime->buffer_mutex); - else if (s1->pcm->nonatomic) - mutex_unlock(&s1->self_group.mutex); + snd_pcm_group_for_each_entry(s, substream) { + if (!stream_lock) { + snd_pcm_buffer_access_unlock(s->runtime); + } else if (s != substream) { + if (s->pcm->nonatomic) + mutex_unlock(&s->self_group.mutex); else - spin_unlock(&s1->self_group.lock); + spin_unlock(&s->self_group.lock); } - if (s1 == s) /* end */ + if (s == last) /* end */ break; } return res; @@ -1496,13 +1515,13 @@ static int snd_pcm_action_nonatomic(const struct action_ops *ops, /* Guarantee the group members won't change during non-atomic action */ guard(rwsem_read)(&snd_pcm_link_rwsem); + if (snd_pcm_stream_linked(substream)) + return snd_pcm_action_group(ops, substream, state, false); + res = snd_pcm_buffer_access_lock(substream->runtime); if (res < 0) return res; - if (snd_pcm_stream_linked(substream)) - res = snd_pcm_action_group(ops, substream, state, false); - else - res = snd_pcm_action_single(ops, substream, state); + res = snd_pcm_action_single(ops, substream, state); snd_pcm_buffer_access_unlock(substream->runtime); return res; } @@ -3121,7 +3140,8 @@ static snd_pcm_sframes_t snd_pcm_rewind(struct snd_pcm_substream *substream, return 0; /* Keep the DMA buffer alive through the sync below. */ - if (!atomic_inc_unless_negative(&runtime->buffer_accessing)) + SND_PCM_BUFFER_ACQUIRE(runtime, lock); + if (SND_PCM_BUFFER_ACQUIRE_ERR(lock)) return -EBUSY; scoped_guard(pcm_stream_lock_irq, substream) { ret = do_pcm_hwsync(substream); @@ -3131,7 +3151,6 @@ 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; } @@ -3145,7 +3164,8 @@ static snd_pcm_sframes_t snd_pcm_forward(struct snd_pcm_substream *substream, return 0; /* Keep the DMA buffer alive through the sync below. */ - if (!atomic_inc_unless_negative(&runtime->buffer_accessing)) + SND_PCM_BUFFER_ACQUIRE(runtime, lock); + if (SND_PCM_BUFFER_ACQUIRE_ERR(lock)) return -EBUSY; scoped_guard(pcm_stream_lock_irq, substream) { ret = do_pcm_hwsync(substream); @@ -3155,7 +3175,6 @@ 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; } @@ -3166,7 +3185,8 @@ static int snd_pcm_delay(struct snd_pcm_substream *substream, int err; /* Keep the DMA buffer alive through the sync below. */ - if (!atomic_inc_unless_negative(&runtime->buffer_accessing)) + SND_PCM_BUFFER_ACQUIRE(runtime, lock); + if (SND_PCM_BUFFER_ACQUIRE_ERR(lock)) return -EBUSY; scoped_guard(pcm_stream_lock_irq, substream) { err = do_pcm_hwsync(substream); @@ -3174,7 +3194,6 @@ static int snd_pcm_delay(struct snd_pcm_substream *substream, *delay = snd_pcm_calc_delay(substream); } snd_pcm_dma_buffer_sync(substream, SNDRV_DMA_SYNC_CPU); - atomic_dec(&runtime->buffer_accessing); return err; } @@ -3392,6 +3411,9 @@ static int snd_pcm_xferi_frames_ioctl(struct snd_pcm_substream *substream, struct snd_xferi xferi; snd_pcm_sframes_t result; + SND_PCM_BUFFER_ACQUIRE(substream->runtime, lock); + if (SND_PCM_BUFFER_ACQUIRE_ERR(lock)) + return -EBUSY; if (snd_pcm_get_state(substream) == SNDRV_PCM_STATE_OPEN) return -EBADFD; if (put_user(0, &_xferi->result)) @@ -3415,6 +3437,9 @@ static int snd_pcm_xfern_frames_ioctl(struct snd_pcm_substream *substream, void *bufs __free(kfree) = NULL; snd_pcm_sframes_t result; + SND_PCM_BUFFER_ACQUIRE(runtime, lock); + if (SND_PCM_BUFFER_ACQUIRE_ERR(lock)) + return -EBUSY; if (snd_pcm_get_state(substream) == SNDRV_PCM_STATE_OPEN) return -EBADFD; if (runtime->channels > 128) @@ -3654,6 +3679,9 @@ static ssize_t snd_pcm_read(struct file *file, char __user *buf, size_t count, if (PCM_RUNTIME_CHECK(substream)) return -ENXIO; runtime = substream->runtime; + SND_PCM_BUFFER_ACQUIRE(runtime, lock); + if (SND_PCM_BUFFER_ACQUIRE_ERR(lock)) + return -EBUSY; if (snd_pcm_state_open_or_disconnected(substream)) return -EBADFD; if (!frame_aligned(runtime, count)) @@ -3678,6 +3706,9 @@ static ssize_t snd_pcm_write(struct file *file, const char __user *buf, if (PCM_RUNTIME_CHECK(substream)) return -ENXIO; runtime = substream->runtime; + SND_PCM_BUFFER_ACQUIRE(runtime, lock); + if (SND_PCM_BUFFER_ACQUIRE_ERR(lock)) + return -EBUSY; if (snd_pcm_state_open_or_disconnected(substream)) return -EBADFD; if (!frame_aligned(runtime, count)) @@ -3704,6 +3735,9 @@ static ssize_t snd_pcm_readv(struct kiocb *iocb, struct iov_iter *to) if (PCM_RUNTIME_CHECK(substream)) return -ENXIO; runtime = substream->runtime; + SND_PCM_BUFFER_ACQUIRE(runtime, lock); + if (SND_PCM_BUFFER_ACQUIRE_ERR(lock)) + return -EBUSY; if (snd_pcm_state_open_or_disconnected(substream)) return -EBADFD; if (!user_backed_iter(to)) @@ -3743,6 +3777,9 @@ static ssize_t snd_pcm_writev(struct kiocb *iocb, struct iov_iter *from) if (PCM_RUNTIME_CHECK(substream)) return -ENXIO; runtime = substream->runtime; + SND_PCM_BUFFER_ACQUIRE(runtime, lock); + if (SND_PCM_BUFFER_ACQUIRE_ERR(lock)) + return -EBUSY; if (snd_pcm_state_open_or_disconnected(substream)) return -EBADFD; if (!user_backed_iter(from)) @@ -4078,32 +4115,23 @@ int snd_pcm_mmap_data(struct snd_pcm_substream *substream, struct file *file, } runtime = substream->runtime; /* don't race with buffer reallocation in hw_params/hw_free */ - if (!atomic_inc_unless_negative(&runtime->buffer_accessing)) + SND_PCM_BUFFER_ACQUIRE(runtime, lock); + if (SND_PCM_BUFFER_ACQUIRE_ERR(lock)) return -EBUSY; - if (runtime->state == SNDRV_PCM_STATE_OPEN) { - err = -EBADFD; - goto out; - } - if (!(runtime->info & SNDRV_PCM_INFO_MMAP)) { - err = -ENXIO; - goto out; - } + if (runtime->state == SNDRV_PCM_STATE_OPEN) + return -EBADFD; + if (!(runtime->info & SNDRV_PCM_INFO_MMAP)) + return -ENXIO; if (runtime->access == SNDRV_PCM_ACCESS_RW_INTERLEAVED || - runtime->access == SNDRV_PCM_ACCESS_RW_NONINTERLEAVED) { - err = -EINVAL; - goto out; - } + runtime->access == SNDRV_PCM_ACCESS_RW_NONINTERLEAVED) + return -EINVAL; size = area->vm_end - area->vm_start; offset = area->vm_pgoff << PAGE_SHIFT; dma_bytes = PAGE_ALIGN(runtime->dma_bytes); - if ((size_t)size > dma_bytes) { - err = -EINVAL; - goto out; - } - if (offset > dma_bytes - size) { - err = -EINVAL; - goto out; - } + if ((size_t)size > dma_bytes) + return -EINVAL; + if (offset > dma_bytes - size) + return -EINVAL; area->vm_ops = &snd_pcm_vm_ops_data; area->vm_private_data = substream; @@ -4113,8 +4141,6 @@ int snd_pcm_mmap_data(struct snd_pcm_substream *substream, struct file *file, err = snd_pcm_lib_default_mmap(substream, area); if (!err) atomic_inc(&substream->mmap_count); -out: - atomic_dec(&runtime->buffer_accessing); return err; } EXPORT_SYMBOL(snd_pcm_mmap_data); diff --git a/sound/core/seq/seq_ump_convert.c b/sound/core/seq/seq_ump_convert.c index b42a7ffbf31eaa..602afb5a0f285e 100644 --- a/sound/core/seq/seq_ump_convert.c +++ b/sound/core/seq/seq_ump_convert.c @@ -432,6 +432,38 @@ static int cvt_ump_midi1_to_midi2(struct snd_seq_client *dest, atomic, hop); } +/* send a MIDI 2.0 RPN/NRPN as the four MIDI 1.0 CCs that select and set it */ +static int cvt_ump_midi2_rpn_to_midi1(struct snd_seq_client *dest, + struct snd_seq_client_port *dest_port, + struct snd_seq_ump_event *ev_cvt, + const union snd_ump_midi2_msg *midi2, + int atomic, int hop) +{ + union snd_ump_midi1_msg *midi1 = (union snd_ump_midi1_msg *)ev_cvt->ump; + bool rpn = midi2->rpn.status == UMP_MSG_STATUS_RPN; + u16 v = downscale_32_to_14bit(midi2->rpn.data); + const unsigned char cc[4][2] = { + { rpn ? UMP_CC_RPN_MSB : UMP_CC_NRPN_MSB, midi2->rpn.bank }, + { rpn ? UMP_CC_RPN_LSB : UMP_CC_NRPN_LSB, midi2->rpn.index }, + { UMP_CC_DATA, v >> 7 }, + { UMP_CC_DATA_LSB, v & 0x7f }, + }; + int i, err = 0; + + midi1->cc.status = UMP_MSG_STATUS_CC; + for (i = 0; i < ARRAY_SIZE(cc); i++) { + midi1->cc.index = cc[i][0]; + midi1->cc.data = cc[i][1]; + err = __snd_seq_deliver_single_event(dest, dest_port, + (struct snd_seq_event *)ev_cvt, + atomic, hop); + if (err < 0) + return err; + } + + return err; +} + /* convert UMP packet from MIDI 2.0 to MIDI 1.0 and deliver it */ static int cvt_ump_midi2_to_midi1(struct snd_seq_client *dest, struct snd_seq_client_port *dest_port, @@ -488,6 +520,7 @@ static int cvt_ump_midi2_to_midi1(struct snd_seq_client *dest, if (err < 0) return err; midi1->note.status = midi2->note.status; + midi1->cc.data = 0; } midi1->pg.program = midi2->pg.program; break; @@ -499,6 +532,10 @@ static int cvt_ump_midi2_to_midi1(struct snd_seq_client *dest, midi1->pb.data_msb = v >> 7; midi1->pb.data_lsb = v & 0x7f; break; + case UMP_MSG_STATUS_RPN: + case UMP_MSG_STATUS_NRPN: + return cvt_ump_midi2_rpn_to_midi1(dest, dest_port, &ev_cvt, + midi2, atomic, hop); default: return 0; } diff --git a/sound/core/sound.c b/sound/core/sound.c index ba226aa7affd3c..536720bc148824 100644 --- a/sound/core/sound.c +++ b/sound/core/sound.c @@ -18,28 +18,28 @@ #include #include -static int major = CONFIG_SND_MAJOR; -int snd_major; +int snd_major = CONFIG_SND_MAJOR; EXPORT_SYMBOL(snd_major); -static int cards_limit = 1; +/* maximum number of cards allowed for automatic module loading */ +static int snd_cards_limit = 1; + +/* this holds the actual maximum card number currently available. + * it is initialized from snd_cards_limit and increases when + * cards are registered manually at higher indices. + */ +int snd_ecards_limit = 1; +EXPORT_SYMBOL(snd_ecards_limit); MODULE_AUTHOR("Jaroslav Kysela "); MODULE_DESCRIPTION("Advanced Linux Sound Architecture driver for soundcards."); MODULE_LICENSE("GPL"); -module_param(major, int, 0444); +module_param_named(major, snd_major, int, 0444); MODULE_PARM_DESC(major, "Major # for sound driver."); -module_param(cards_limit, int, 0444); +module_param_named(cards_limit, snd_cards_limit, int, 0444); MODULE_PARM_DESC(cards_limit, "Count of auto-loadable soundcards."); MODULE_ALIAS_CHARDEV_MAJOR(CONFIG_SND_MAJOR); -/* this one holds the actual max. card number currently available. - * as default, it's identical with cards_limit option. when more - * modules are loaded manually, this limit number increases, too. - */ -int snd_ecards_limit; -EXPORT_SYMBOL(snd_ecards_limit); - #ifdef CONFIG_SND_DEBUG struct dentry *sound_debugfs_root; EXPORT_SYMBOL_GPL(sound_debugfs_root); @@ -61,7 +61,7 @@ void snd_request_card(int card) { if (snd_card_locked(card)) return; - if (card < 0 || card >= cards_limit) + if (card < 0 || card >= snd_cards_limit) return; request_module("snd-card-%i", card); } @@ -326,7 +326,7 @@ int snd_register_device(int type, struct snd_card *card, int dev, } preg->dev = device; - device->devt = MKDEV(major, minor); + device->devt = MKDEV(snd_major, minor); err = device_add(device); if (err < 0) goto error; @@ -442,18 +442,21 @@ static int __init alsa_sound_init(void) { int err; - snd_major = major; - snd_ecards_limit = cards_limit; + if (!snd_major) + return -EINVAL; + + snd_ecards_limit = snd_cards_limit; - err = register_chrdev(major, "alsa", &snd_fops); + err = register_chrdev(snd_major, "alsa", &snd_fops); if (err < 0) { - pr_err("ALSA core: unable to register native major device number %d\n", major); + pr_err("ALSA core: unable to register native major device number %d\n", + snd_major); return err; } err = snd_info_init(); if (err < 0) { - unregister_chrdev(major, "alsa"); + unregister_chrdev(snd_major, "alsa"); return err; } @@ -472,7 +475,7 @@ static void __exit alsa_sound_exit(void) debugfs_remove(sound_debugfs_root); #endif snd_info_done(); - unregister_chrdev(major, "alsa"); + unregister_chrdev(snd_major, "alsa"); } subsys_initcall(alsa_sound_init); diff --git a/sound/core/sound_oss.c b/sound/core/sound_oss.c index 2f0bc481a46d40..c1439f9d34cb9a 100644 --- a/sound/core/sound_oss.c +++ b/sound/core/sound_oss.c @@ -174,24 +174,25 @@ int snd_unregister_oss_device(int type, struct snd_card *card, int dev) return 0; if (minor < 0) return minor; - guard(mutex)(&sound_oss_mutex); - mptr = snd_oss_minors[minor]; - if (mptr == NULL) - return -ENOENT; - switch (SNDRV_MINOR_OSS_DEVICE(minor)) { - case SNDRV_MINOR_OSS_PCM: - track2 = SNDRV_MINOR_OSS(cidx, SNDRV_MINOR_OSS_AUDIO); - break; - case SNDRV_MINOR_OSS_MIDI: - track2 = SNDRV_MINOR_OSS(cidx, SNDRV_MINOR_OSS_DMMIDI); - break; - case SNDRV_MINOR_OSS_MIDI1: - track2 = SNDRV_MINOR_OSS(cidx, SNDRV_MINOR_OSS_DMMIDI1); - break; + scoped_guard(mutex, &sound_oss_mutex) { + mptr = snd_oss_minors[minor]; + if (mptr == NULL) + return -ENOENT; + switch (SNDRV_MINOR_OSS_DEVICE(minor)) { + case SNDRV_MINOR_OSS_PCM: + track2 = SNDRV_MINOR_OSS(cidx, SNDRV_MINOR_OSS_AUDIO); + break; + case SNDRV_MINOR_OSS_MIDI: + track2 = SNDRV_MINOR_OSS(cidx, SNDRV_MINOR_OSS_DMMIDI); + break; + case SNDRV_MINOR_OSS_MIDI1: + track2 = SNDRV_MINOR_OSS(cidx, SNDRV_MINOR_OSS_DMMIDI1); + break; + } + if (track2 >= 0) + snd_oss_minors[track2] = NULL; + snd_oss_minors[minor] = NULL; } - if (track2 >= 0) - snd_oss_minors[track2] = NULL; - snd_oss_minors[minor] = NULL; /* call unregister_sound_special() outside sound_oss_mutex; * otherwise may deadlock, as it can trigger the release of a card diff --git a/sound/core/timer.c b/sound/core/timer.c index f977eea64f31e3..073031d2f964f3 100644 --- a/sound/core/timer.c +++ b/sound/core/timer.c @@ -657,9 +657,12 @@ static int snd_timer_start1(struct snd_timer_instance *timeri, return result; } -/* start/continue a slave timer */ -static int snd_timer_start_slave(struct snd_timer_instance *timeri, - bool start) +/* + * start/continue a slave timer; + * called with timer->lock held when the slave is linked to a master + */ +static int __snd_timer_start_slave(struct snd_timer_instance *timeri, + bool start) { if (timeri->flags & SNDRV_TIMER_IFLG_DEAD) return -EINVAL; @@ -667,7 +670,6 @@ static int snd_timer_start_slave(struct snd_timer_instance *timeri, return -EBUSY; timeri->flags |= SNDRV_TIMER_IFLG_RUNNING; if (timeri->master && timeri->timer) { - guard(spinlock)(&timeri->timer->lock); list_add_tail(&timeri->active_list, &timeri->master->slave_active_head); snd_timer_notify1(timeri, start ? SNDRV_TIMER_EVENT_START : @@ -676,6 +678,27 @@ static int snd_timer_start_slave(struct snd_timer_instance *timeri, return 1; /* delayed start */ } +/* + * start/continue a slave timer + * + * The flags of a slave linked to a master are updated also from the timer + * interrupt (SNDRV_TIMER_IFLG_CALLBACK in snd_timer_process_callbacks()) + * under timer->lock. Change them only under the same lock, otherwise one + * of the two read-modify-write updates may get lost. The caller holds + * timeri_lock, hence timeri->timer can't change here; an unlinked slave is + * not reachable from any timer and needs no further protection. + */ +static int snd_timer_start_slave(struct snd_timer_instance *timeri, + bool start) +{ + struct snd_timer *timer = timeri->timer; + + if (!timer) + return __snd_timer_start_slave(timeri, start); + guard(spinlock)(&timer->lock); + return __snd_timer_start_slave(timeri, start); +} + /* stop/pause a master timer */ static int snd_timer_stop1(struct snd_timer_instance *timeri, bool stop) { @@ -718,15 +741,17 @@ static int snd_timer_stop1(struct snd_timer_instance *timeri, bool stop) return 0; } -/* stop/pause a slave timer */ -static int snd_timer_stop_slave(struct snd_timer_instance *timeri, bool stop) +/* + * stop/pause a slave timer; + * called with timer->lock held when the slave is linked to a master + */ +static int __snd_timer_stop_slave(struct snd_timer_instance *timeri, bool stop) { bool running; running = timeri->flags & SNDRV_TIMER_IFLG_RUNNING; timeri->flags &= ~SNDRV_TIMER_IFLG_RUNNING; if (timeri->timer) { - guard(spinlock)(&timeri->timer->lock); list_del_init(&timeri->ack_list); list_del_init(&timeri->active_list); if (running) @@ -736,6 +761,17 @@ static int snd_timer_stop_slave(struct snd_timer_instance *timeri, bool stop) return running ? 0 : -EBUSY; } +/* stop/pause a slave timer; see snd_timer_start_slave() for the locking */ +static int snd_timer_stop_slave(struct snd_timer_instance *timeri, bool stop) +{ + struct snd_timer *timer = timeri->timer; + + if (!timer) + return __snd_timer_stop_slave(timeri, stop); + guard(spinlock)(&timer->lock); + return __snd_timer_stop_slave(timeri, stop); +} + /* * start the timer instance */ diff --git a/sound/core/vmaster.c b/sound/core/vmaster.c index f43144ba279788..be4e64a5b2675f 100644 --- a/sound/core/vmaster.c +++ b/sound/core/vmaster.c @@ -102,7 +102,14 @@ static int follower_init(struct link_follower *follower) follower->info.min_val = uinfo->value.integer.min; follower->info.max_val = uinfo->value.integer.max; - return follower_update(follower); + err = follower_update(follower); + if (err < 0) { + /* allow initialization to be retried */ + follower->info.count = 0; + return err; + } + + return 0; } /* initialize master volume */ @@ -193,7 +200,7 @@ static int follower_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct link_follower *follower = snd_kcontrol_chip(kcontrol); - int err, ch, changed = 0; + int err, ch, changed = 0, old_vals[2]; err = follower_init(follower); if (err < 0) @@ -204,6 +211,10 @@ static int follower_put(struct snd_kcontrol *kcontrol, return -EINVAL; } + /* save the original cached values */ + for (ch = 0; ch < follower->info.count; ch++) + old_vals[ch] = follower->vals[ch]; + for (ch = 0; ch < follower->info.count; ch++) { if (follower->vals[ch] != ucontrol->value.integer.value[ch]) { changed = 1; @@ -213,8 +224,13 @@ static int follower_put(struct snd_kcontrol *kcontrol, if (!changed) return 0; err = follower_put_val(follower, ucontrol); - if (err < 0) + if (err < 0) { + /* restore cached values on failure */ + for (ch = 0; ch < follower->info.count; ch++) + follower->vals[ch] = old_vals[ch]; return err; + } + return 1; } @@ -345,17 +361,27 @@ static int sync_followers(struct link_master *master, int old_val, int new_val) struct link_follower *follower; struct snd_ctl_elem_value *uval __free(kfree) = kmalloc_obj(*uval); + int err; if (!uval) return -ENOMEM; list_for_each_entry(follower, &master->followers, list) { master->val = old_val; uval->id = follower->follower.id; - follower_get_val(follower, uval); + err = follower_get_val(follower, uval); + if (err < 0) + goto error; + master->val = new_val; - follower_put_val(follower, uval); + err = follower_put_val(follower, uval); + if (err < 0) + goto error; } return 0; + +error: + master->val = old_val; + return err; } static int master_put(struct snd_kcontrol *kcontrol, diff --git a/sound/firewire/fcp.c b/sound/firewire/fcp.c index e60bfd0ee4accc..b8e7e2c907912b 100644 --- a/sound/firewire/fcp.c +++ b/sound/firewire/fcp.c @@ -14,7 +14,6 @@ #include #include #include -#include #include "fcp.h" #include "lib.h" #include "amdtp-stream.h" @@ -22,7 +21,6 @@ #define CTS_AVC 0x00 #define ERROR_RETRIES 3 -#define ERROR_DELAY_MS 5 #define FCP_TIMEOUT_MS 125 int avc_general_set_sig_fmt(struct fw_unit *unit, unsigned int rate, @@ -272,7 +270,8 @@ int fcp_avc_transaction(struct fw_unit *unit, ret = t.response_size; break; } else if (t.state == STATE_BUS_RESET) { - msleep(ERROR_DELAY_MS); + ret = -EAGAIN; + break; } else if (++tries >= ERROR_RETRIES) { dev_err(&t.unit->device, "FCP command timed out\n"); ret = -EIO; diff --git a/sound/firewire/fireworks/fireworks_transaction.c b/sound/firewire/fireworks/fireworks_transaction.c index 5c859773fe0626..bb9ab8ed52b564 100644 --- a/sound/firewire/fireworks/fireworks_transaction.c +++ b/sound/firewire/fireworks/fireworks_transaction.c @@ -34,7 +34,6 @@ #define MEMORY_SPACE_EFW_RESPONSE 0xecc080000000ULL #define ERROR_RETRIES 3 -#define ERROR_DELAY_MS 5 #define EFC_TIMEOUT_MS 125 static DEFINE_SPINLOCK(instances_lock); @@ -99,7 +98,8 @@ int snd_efw_transaction_run(struct fw_unit *unit, ret = t.size; break; } else if (t.state == STATE_BUS_RESET) { - msleep(ERROR_DELAY_MS); + ret = -EAGAIN; + break; } else if (++tries >= ERROR_RETRIES) { dev_err(&t.unit->device, "EFW transaction timed out\n"); ret = -EIO; diff --git a/sound/hda/codecs/realtek/alc269.c b/sound/hda/codecs/realtek/alc269.c index 9bca07c2c99ac8..3918b2011a12a6 100644 --- a/sound/hda/codecs/realtek/alc269.c +++ b/sound/hda/codecs/realtek/alc269.c @@ -1116,6 +1116,21 @@ static void alc269vb_fixup_aspire_e1_coef(struct hda_codec *codec, alc_update_coef_idx(codec, 0x0d, 0x6000, 0x6000); } +/* + * After a warm reboot from Windows, bit 4 of COEF 0x66 is left set, which + * mutes the internal speaker, and bit 10 of COEF 0x1b is left clear, which + * distorts the output. Restore both at init and resume. + */ +static void alc294_fixup_asus_spk_coefs(struct hda_codec *codec, + const struct hda_fixup *fix, + int action) +{ + if (action != HDA_FIXUP_ACT_INIT) + return; + alc_update_coef_idx(codec, 0x66, 1 << 4, 0); + alc_update_coef_idx(codec, 0x1b, 0, 1 << 10); +} + static void alc269_fixup_pcm_44k(struct hda_codec *codec, const struct hda_fixup *fix, int action) { @@ -1462,6 +1477,17 @@ static void alc245_fixup_minisforum_jack_detect(struct hda_codec *codec, alc_update_coef_idx(codec, 0x4a, BIT(15), 0); } +static void alc245_fixup_acer_hp_jd_reset(struct hda_codec *codec, + const struct hda_fixup *fix, + int action) +{ + if (action == HDA_FIXUP_ACT_INIT) { + /* Pulse Reset HP JD */ + alc_update_coef_idx(codec, 0x4a, BIT(15), BIT(15)); + alc_update_coef_idx(codec, 0x4a, BIT(15), 0); + } +} + /* turn on/off mic-mute LED per capture hook via VREF change */ static int vref_micmute_led_set(struct led_classdev *led_cdev, enum led_brightness brightness) @@ -1909,6 +1935,69 @@ static void alc298_fixup_alc1316_amp(struct hda_codec *codec, } } +/* + * The ONEXPLAYER X1 i drives its speakers through a Realtek smart amplifier at + * I2C address 0x10, reached over the ALC245 coefficient tunnel. The firmware + * leaves the amplifier unconfigured, so the speakers stay silent. The register + * writes below replay what the Windows driver does at initialization. + * + * Tunnel layout: coefficient 0x24 selects the amplifier, 0x25 and 0x26 carry + * the high and low halves of the register address, 0x28 the value, and 0x29 + * commits. Bit 5 of the commit word is a self-clearing go bit; a write takes + * about 200 us. + */ +static void alc245_onexplayer_amp_write(struct hda_codec *codec, u32 reg, u8 val) +{ + int i; + + alc_write_coef_idx(codec, 0x24, 0x0010); + alc_write_coef_idx(codec, 0x25, reg >> 16); + alc_write_coef_idx(codec, 0x26, reg & 0xffff); + alc_write_coef_idx(codec, 0x27, 0x0000); + alc_write_coef_idx(codec, 0x28, val); + alc_write_coef_idx(codec, 0x29, 0xb023); + + for (i = 0; i < 10; i++) { + if (!(alc_read_coef_idx(codec, 0x29) & 0x0020)) + return; + usleep_range(100, 200); + } + codec_warn(codec, "amp write timeout, reg 0x%x\n", reg); +} + +static void alc245_fixup_onexplayer_amp(struct hda_codec *codec, + const struct hda_fixup *fix, int action) +{ + static const struct { + u32 reg; + u8 val; + } init_seq[] = { + { 0xf10a, 0x09 }, { 0xf104, 0xf6 }, { 0xf105, 0x22 }, + { 0xf10b, 0x2c }, { 0xf10b, 0x7c }, { 0xc000, 0x01 }, + { 0xf20d, 0x00 }, { 0xf212, 0x3e }, { 0xc001, 0x02 }, + { 0xc003, 0x22 }, { 0xc004, 0x44 }, { 0xc005, 0x44 }, + { 0xc007, 0x64 }, { 0xc00e, 0xe7 }, { 0xf223, 0x7f }, + { 0xf224, 0xdb }, { 0xf225, 0xee }, { 0xf226, 0x3f }, + { 0xf227, 0x0f }, { 0xf21a, 0x78 }, { 0xf242, 0x3c }, + { 0xc120, 0x40 }, { 0xc125, 0x03 }, { 0xc321, 0x0b }, + { 0xc200, 0xd8 }, { 0xc201, 0x27 }, { 0xc202, 0x0f }, + { 0xc400, 0x0e }, { 0xc401, 0x43 }, { 0xc402, 0xe0 }, + { 0xc403, 0x00 }, { 0xc404, 0x4c }, { 0xc406, 0x40 }, + { 0xc407, 0x02 }, { 0xc408, 0x3f }, { 0xc300, 0x01 }, + { 0x41001888, 0x00 }, { 0xc121, 0x0b }, { 0xf102, 0x00 }, + { 0xf103, 0x00 }, { 0xf104, 0xf5 }, { 0xf105, 0x23 }, + { 0xf109, 0x00 }, { 0xf10a, 0x0b }, { 0xf10b, 0x4c }, + { 0xf10b, 0x5c }, + }; + int i; + + if (action != HDA_FIXUP_ACT_INIT) + return; + + for (i = 0; i < ARRAY_SIZE(init_seq); i++) + alc245_onexplayer_amp_write(codec, init_seq[i].reg, init_seq[i].val); +} + static void alc298_fixup_samsung_amp(struct hda_codec *codec, const struct hda_fixup *fix, int action) { @@ -2688,6 +2777,23 @@ static void asus_tx300_automute(struct hda_codec *codec) spec->gen.mute_bits |= (1ULL << 0x14); } +static void alc282_fixup_hp_250g6(struct hda_codec *codec, + const struct hda_fixup *fix, int action) +{ + if (action != HDA_FIXUP_ACT_INIT) + return; + + alc_write_coef_idx(codec, 0x6d, 0x0900); + + /* filter block: disable, load coefficients, re-enable */ + alc_write_coef_idx(codec, 0x22, 0x400a); + alc_write_coef_idx(codec, 0x24, 0x1ec4); + alc_write_coef_idx(codec, 0x39, 0x1ea9); + alc_write_coef_idx(codec, 0x44, 0x1f61); + alc_write_coef_idx(codec, 0x4f, 0x1fb0); + alc_write_coef_idx(codec, 0x22, 0xe04a); +} + static void alc282_fixup_asus_tx300(struct hda_codec *codec, const struct hda_fixup *fix, int action) { @@ -4232,6 +4338,7 @@ enum { ALC269VB_FIXUP_ORDISSIMO_EVE2, ALC283_FIXUP_CHROME_BOOK, ALC283_FIXUP_SENSE_COMBO_JACK, + ALC282_FIXUP_HP_250G6_EQ, ALC282_FIXUP_ASUS_TX300, ALC283_FIXUP_INT_MIC, ALC290_FIXUP_MONO_SPEAKERS, @@ -4334,6 +4441,7 @@ enum { ALC298_FIXUP_HUAWEI_MBX_STEREO, ALC295_FIXUP_HP_X360, ALC295_FIXUP_HP_PAVILION_X360, + ALC295_FIXUP_HP_CW1XXX, ALC221_FIXUP_HP_HEADSET_MIC, ALC285_FIXUP_LENOVO_HEADPHONE_NOISE, ALC295_FIXUP_HP_AUTO_MUTE, @@ -4372,6 +4480,7 @@ enum { ALC294_FIXUP_ASUS_ALLY_VERBS, ALC294_FIXUP_ASUS_HPE, ALC294_FIXUP_ASUS_COEF_1B, + ALC294_FIXUP_ASUS_SPK_COEFS, ALC294_FIXUP_ASUS_GX502_HP, ALC294_FIXUP_ASUS_GX502_PINS, ALC294_FIXUP_ASUS_GX502_VERBS, @@ -4535,6 +4644,7 @@ enum { ALC233_FIXUP_LENOVO_GPIO2_MIC_HOTKEY, ALC245_FIXUP_BASS_HP_DAC, ALC245_FIXUP_ACER_MICMUTE_LED, + ALC245_FIXUP_ACER_HP_JD_RESET, ALC245_FIXUP_CS35L41_I2C_2_MUTE_LED, ALC245_FIXUP_CS35L41_I2C_2_MUTE_MICMUTE_LED, ALC256_FIXUP_HONOR_MRB_XXX_M1020_AUDIO, @@ -4553,6 +4663,7 @@ enum { ALC256_FIXUP_ASUS_SPEAKER_COEFS, ALC245_FIXUP_MINISFORUM_V3_MIC_NO_PRESENCE, ALC287_FIXUP_TAS2781_I2C_DAC, + ALC245_FIXUP_ONEXPLAYER_AMP, }; /* A special fixup for Lenovo C940 and Yoga Duet 7; @@ -5199,6 +5310,10 @@ static const struct hda_fixup alc269_fixups[] = { .chained = true, .chain_id = ALC283_FIXUP_CHROME_BOOK, }, + [ALC282_FIXUP_HP_250G6_EQ] = { + .type = HDA_FIXUP_FUNC, + .v.func = alc282_fixup_hp_250g6, + }, [ALC282_FIXUP_ASUS_TX300] = { .type = HDA_FIXUP_FUNC, .v.func = alc282_fixup_asus_tx300, @@ -5834,6 +5949,16 @@ static const struct hda_fixup alc269_fixups[] = { .chained = true, .chain_id = ALC295_FIXUP_HP_X360 }, + [ALC295_FIXUP_HP_CW1XXX] = { + .type = HDA_FIXUP_VERBS, + .v.verbs = (const struct hda_verb[]) { + { 0x20, AC_VERB_SET_COEF_INDEX, 0x0d }, + { 0x20, AC_VERB_SET_PROC_COEF, 0xa023 }, + {} + }, + .chained = true, + .chain_id = ALC295_FIXUP_HP_X360 + }, [ALC221_FIXUP_HP_HEADSET_MIC] = { .type = HDA_FIXUP_PINS, .v.pins = (const struct hda_pintbl[]) { @@ -6249,6 +6374,10 @@ static const struct hda_fixup alc269_fixups[] = { .chained = true, .chain_id = ALC289_FIXUP_ASUS_GA401, }, + [ALC294_FIXUP_ASUS_SPK_COEFS] = { + .type = HDA_FIXUP_FUNC, + .v.func = alc294_fixup_asus_spk_coefs, + }, [ALC285_FIXUP_HP_GPIO_LED] = { .type = HDA_FIXUP_FUNC, .v.func = alc285_fixup_hp_gpio_led, @@ -7354,6 +7483,12 @@ static const struct hda_fixup alc269_fixups[] = { .chained = true, .chain_id = ALC2XX_FIXUP_HEADSET_MIC, }, + [ALC245_FIXUP_ACER_HP_JD_RESET] = { + .type = HDA_FIXUP_FUNC, + .v.func = alc245_fixup_acer_hp_jd_reset, + .chained = true, + .chain_id = ALC245_FIXUP_ACER_MICMUTE_LED, + }, [ALC245_FIXUP_CS35L41_I2C_2_MUTE_LED] = { .type = HDA_FIXUP_FUNC, .v.func = alc245_fixup_hp_mute_led_coefbit, @@ -7472,6 +7607,10 @@ static const struct hda_fixup alc269_fixups[] = { .chained = true, .chain_id = ALC245_FIXUP_BASS_HP_DAC }, + [ALC245_FIXUP_ONEXPLAYER_AMP] = { + .type = HDA_FIXUP_FUNC, + .v.func = alc245_fixup_onexplayer_amp, + }, }; static const struct hda_quirk alc269_fixup_tbl[] = { @@ -7538,7 +7677,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x1025, 0x166c, "Acer Predator PH16-71", ALC2XX_FIXUP_HEADSET_MIC), SND_PCI_QUIRK(0x1025, 0x1679, "Acer Nitro 16 AN16-41", ALC2XX_FIXUP_HEADSET_MIC), SND_PCI_QUIRK(0x1025, 0x169a, "Acer Swift SFG16", ALC256_FIXUP_ACER_SFG16_MICMUTE_LED), - SND_PCI_QUIRK(0x1025, 0x170f, "Acer Predator PHN16-71", ALC2XX_FIXUP_HEADSET_MIC), + SND_PCI_QUIRK(0x1025, 0x170f, "Acer Predator PHN16-71", ALC245_FIXUP_ACER_HP_JD_RESET), SND_PCI_QUIRK(0x1025, 0x171e, "Acer Nitro ANV15-51", ALC245_FIXUP_ACER_MICMUTE_LED), SND_PCI_QUIRK(0x1025, 0x172c, "Acer Nitro ANV16-41", ALC2XX_FIXUP_HEADSET_MIC), SND_PCI_QUIRK(0x1025, 0x1731, "Acer Predator PHN16-72", ALC245_FIXUP_ACER_MICMUTE_LED), @@ -7718,6 +7857,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x103c, 0x827f, "HP x360", ALC269_FIXUP_HP_MUTE_LED_MIC3), SND_PCI_QUIRK(0x103c, 0x82bf, "HP G3 mini", ALC221_FIXUP_HP_MIC_NO_PRESENCE), SND_PCI_QUIRK(0x103c, 0x82c0, "HP G3 mini premium", ALC221_FIXUP_HP_MIC_NO_PRESENCE), + SND_PCI_QUIRK(0x103c, 0x832e, "HP 250 G6", ALC282_FIXUP_HP_250G6_EQ), SND_PCI_QUIRK(0x103c, 0x83b9, "HP Spectre x360", ALC269_FIXUP_HP_MUTE_LED_MIC3), SND_PCI_QUIRK(0x103c, 0x841c, "HP Pavilion 15-CK0xx", ALC269_FIXUP_HP_MUTE_LED_MIC3), HDA_CODEC_QUIRK(0x103c, 0x8486, "HP Pavilion x360", ALC295_FIXUP_HP_PAVILION_X360), @@ -7742,6 +7882,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x103c, 0x8603, "HP Omen 17-cb0xxx", ALC285_FIXUP_HP_MUTE_LED), SND_PCI_QUIRK(0x103c, 0x860c, "HP ZBook 17 G6", ALC285_FIXUP_HP_GPIO_AMP_INIT), SND_PCI_QUIRK(0x103c, 0x860f, "HP ZBook 15 G6", ALC285_FIXUP_HP_GPIO_AMP_INIT), + SND_PCI_QUIRK(0x103c, 0x8615, "HP Pavilion 15-cw1xxx", ALC295_FIXUP_HP_CW1XXX), SND_PCI_QUIRK(0x103c, 0x861f, "HP Elite Dragonfly G1", ALC285_FIXUP_HP_GPIO_AMP_INIT), SND_PCI_QUIRK(0x103c, 0x864f, "HP Laptop 15-dy0xxx", ALC236_FIXUP_HP_MUTE_LED_COEFBIT2), SND_PCI_QUIRK(0x103c, 0x869d, "HP", ALC236_FIXUP_HP_MUTE_LED), @@ -7749,6 +7890,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x103c, 0x86c1, "HP Laptop 15-da3001TU", ALC236_FIXUP_HP_MUTE_LED_COEFBIT2), SND_PCI_QUIRK(0x103c, 0x86c7, "HP Envy AiO 32", ALC274_FIXUP_HP_ENVY_GPIO), SND_PCI_QUIRK(0x103c, 0x86c8, "HP Laptop 14s-dr1xxx", ALC236_FIXUP_HP_MUTE_LED_COEFBIT2), + SND_PCI_QUIRK(0x103c, 0x86e2, "HP Pavilion 15-cs3xxx", ALC269_FIXUP_HP_MUTE_LED_MIC3), SND_PCI_QUIRK(0x103c, 0x86e7, "HP Spectre x360 15-eb0xxx", ALC285_FIXUP_HP_SPECTRE_X360_EB1), SND_PCI_QUIRK(0x103c, 0x863e, "HP Spectre x360 15-df1xxx", ALC285_FIXUP_HP_SPECTRE_X360_DF1), SND_PCI_QUIRK(0x103c, 0x86e8, "HP Spectre x360 15-eb0xxx", ALC285_FIXUP_HP_SPECTRE_X360_EB1), @@ -7774,6 +7916,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x103c, 0x8786, "HP OMEN 15", ALC285_FIXUP_HP_MUTE_LED), SND_PCI_QUIRK(0x103c, 0x8787, "HP OMEN 15", ALC285_FIXUP_HP_MUTE_LED), SND_PCI_QUIRK(0x103c, 0x8788, "HP OMEN 15", ALC285_FIXUP_HP_MUTE_LED), + SND_PCI_QUIRK(0x103c, 0x878a, "HP OMEN 15t-ek000", ALC245_FIXUP_HP_MUTE_LED_COEFBIT), SND_PCI_QUIRK(0x103c, 0x87b2, "HP Pavilion Gaming Laptop 15-ec1xxx", ALC285_FIXUP_HP_MUTE_LED), SND_PCI_QUIRK(0x103c, 0x87b7, "HP Laptop 14-fq0xxx", ALC236_FIXUP_HP_MUTE_LED_COEFBIT2), SND_PCI_QUIRK(0x103c, 0x87c8, "HP", ALC287_FIXUP_HP_GPIO_LED), @@ -7828,6 +7971,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x103c, 0x8902, "HP OMEN 16", ALC285_FIXUP_HP_MUTE_LED), SND_PCI_QUIRK(0x103c, 0x890e, "HP 255 G8 Notebook PC", ALC236_FIXUP_HP_MUTE_LED_COEFBIT2), SND_PCI_QUIRK(0x103c, 0x8919, "HP Pavilion Aero Laptop 13-be0xxx", ALC287_FIXUP_HP_GPIO_LED), + SND_PCI_QUIRK(0x103c, 0x891e, "HP Spectre x360 2-in-1 Laptop 16-f2xxx", ALC245_FIXUP_HP_SPECTRE_X360_EU0XXX), SND_PCI_QUIRK(0x103c, 0x896d, "HP ZBook Firefly 16 G9", ALC245_FIXUP_CS35L41_SPI_2_HP_GPIO_LED), SND_PCI_QUIRK(0x103c, 0x896e, "HP EliteBook x360 830 G9", ALC245_FIXUP_CS35L41_SPI_2_HP_GPIO_LED), SND_PCI_QUIRK(0x103c, 0x8971, "HP EliteBook 830 G9", ALC245_FIXUP_CS35L41_SPI_2_HP_GPIO_LED), @@ -7871,7 +8015,8 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x103c, 0x8a26, "HP Victus 16-d1xxx (MB 8A26)", ALC245_FIXUP_HP_MUTE_LED_COEFBIT), SND_PCI_QUIRK(0x103c, 0x8a28, "HP Envy 13", ALC287_FIXUP_CS35L41_I2C_2), SND_PCI_QUIRK(0x103c, 0x8a29, "HP Envy 15", ALC287_FIXUP_CS35L41_I2C_2), - SND_PCI_QUIRK(0x103c, 0x8a2a, "HP Envy 15", ALC287_FIXUP_CS35L41_I2C_2), + SND_PCI_QUIRK(0x103c, 0x8a2a, "HP ENVY x360 2-in-1 Laptop 15-ew0xxx", + ALC287_FIXUP_CS35L41_I2C_2_HP_MUTE_LEDS), SND_PCI_QUIRK(0x103c, 0x8a2b, "HP Envy 15", ALC287_FIXUP_CS35L41_I2C_2), SND_PCI_QUIRK(0x103c, 0x8a2c, "HP Envy 16", ALC287_FIXUP_CS35L41_I2C_2), SND_PCI_QUIRK(0x103c, 0x8a2d, "HP Envy 16", ALC287_FIXUP_CS35L41_I2C_2), @@ -8010,6 +8155,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x103c, 0x8ca2, "HP ZBook Power", ALC236_FIXUP_HP_GPIO_LED), SND_PCI_QUIRK(0x103c, 0x8ca4, "HP ZBook Fury", ALC245_FIXUP_CS35L41_SPI_2_HP_GPIO_LED), SND_PCI_QUIRK(0x103c, 0x8ca7, "HP ZBook Fury", ALC245_FIXUP_CS35L41_SPI_2_HP_GPIO_LED), + SND_PCI_QUIRK(0x103c, 0x8cac, "HP Laptop 15-fd1xxx", ALC236_FIXUP_HP_MUTE_LED_MICMUTE_GPIO), SND_PCI_QUIRK(0x103c, 0x8caf, "HP Elite mt645 G8 Mobile Thin Client", ALC236_FIXUP_HP_MUTE_LED_MICMUTE_VREF), SND_PCI_QUIRK(0x103c, 0x8cbc, "HP Pavilion Laptop 16-ag0xxx", ALC245_FIXUP_HP_X360_MUTE_LEDS), SND_PCI_QUIRK(0x103c, 0x8cbd, "HP Pavilion Aero Laptop 13-bg0xxx", ALC245_FIXUP_HP_X360_MUTE_LEDS), @@ -8103,7 +8249,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x103c, 0x8ee4, "HP Bantie A6U", ALC236_FIXUP_HP_MUTE_LED_MICMUTE_GPIO), SND_PCI_QUIRK(0x103c, 0x8ee5, "HP Bantie A6U", ALC236_FIXUP_HP_MUTE_LED_MICMUTE_GPIO), SND_PCI_QUIRK(0x103c, 0x8ee7, "HP Abe A6U", ALC236_FIXUP_HP_MUTE_LED_MICMUTE_GPIO), - SND_PCI_QUIRK(0x103c, 0x8f07, "HP Agusta G7KX", ALC287_FIXUP_CS35L41_I2C_2), + SND_PCI_QUIRK(0x103c, 0x8f07, "HP OmniBook 7 Laptop 14-hg0xxx", ALC287_FIXUP_CS35L41_I2C_2_HP_MUTE_LEDS), SND_PCI_QUIRK(0x103c, 0x8f0c, "HP ZBook X G2i 16W", ALC236_FIXUP_HP_GPIO_LED), SND_PCI_QUIRK(0x103c, 0x8f0e, "HP ZBook X G2i 16W", ALC236_FIXUP_HP_GPIO_LED), SND_PCI_QUIRK(0x103c, 0x8f2d, "HP Auster 14", ALC287_FIXUP_CS35L41_I2C_2), @@ -8125,6 +8271,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x1043, 0x1024, "ASUS Zephyrus G14 2025", ALC285_FIXUP_ASUS_GA403U_HEADSET_MIC), SND_PCI_QUIRK(0x1043, 0x1032, "ASUS VivoBook X513EA", ALC256_FIXUP_ASUS_MIC_NO_PRESENCE), SND_PCI_QUIRK(0x1043, 0x1034, "ASUS GU605C", ALC285_FIXUP_ASUS_GU605_SPI_SPEAKER2_TO_DAC1), + SND_PCI_QUIRK(0x103c, 0x900c, "HP ZBook Ultra G1a 14", ALC285_FIXUP_HP_GPIO_LED), SND_PCI_QUIRK(0x1043, 0x103e, "ASUS X540SA", ALC256_FIXUP_ASUS_MIC), SND_PCI_QUIRK(0x1043, 0x103f, "ASUS TX300", ALC282_FIXUP_ASUS_TX300), SND_PCI_QUIRK(0x1043, 0x1044, "ASUS GA403UM", ALC285_FIXUP_ASUS_GA403U_HEADSET_MIC), @@ -8196,6 +8343,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x1043, 0x18d3, "ASUS UM3504DA", ALC287_FIXUP_CS35L41_I2C_2), SND_PCI_QUIRK(0x1043, 0x18f1, "Asus FX505DT", ALC256_FIXUP_ASUS_HEADSET_MIC), SND_PCI_QUIRK(0x1043, 0x194e, "ASUS UX563FD", ALC294_FIXUP_ASUS_HPE), + SND_PCI_QUIRK(0x1043, 0x1961, "ASUS VivoBook X509UA", ALC256_FIXUP_ASUS_MIC_NO_PRESENCE), SND_PCI_QUIRK(0x1043, 0x1970, "ASUS UX550VE", ALC289_FIXUP_ASUS_GA401), SND_PCI_QUIRK(0x1043, 0x197e, "ASUS VivoBook X509DAP", ALC256_FIXUP_ASUS_MIC_NO_PRESENCE), SND_PCI_QUIRK(0x1043, 0x1982, "ASUS B1400CEPE", ALC256_FIXUP_ASUS_HPE), @@ -8207,13 +8355,14 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x1043, 0x1a83, "ASUS UM5302LA", ALC287_FIXUP_CS35L41_I2C_2), SND_PCI_QUIRK(0x1043, 0x1a8e, "ASUS G712LWS", ALC294_FIXUP_LENOVO_MIC_LOCATION), SND_PCI_QUIRK(0x1043, 0x1a8f, "ASUS UX582ZS", ALC245_FIXUP_CS35L41_SPI_2), + SND_PCI_QUIRK(0x1043, 0x1b02, "ASUS ExpertBook B7402FEA", ALC294_FIXUP_ASUS_SPK_COEFS), SND_PCI_QUIRK(0x1043, 0x1b11, "ASUS UX431DA", ALC294_FIXUP_ASUS_COEF_1B), SND_PCI_QUIRK(0x1043, 0x1b13, "ASUS U41SV/GA403U", ALC285_FIXUP_ASUS_GA403U_HEADSET_MIC), SND_PCI_QUIRK(0x1043, 0x1b93, "ASUS G614JVR/JIR", ALC245_FIXUP_CS35L41_SPI_2), SND_PCI_QUIRK(0x1043, 0x1bbd, "ASUS Z550MA", ALC255_FIXUP_ASUS_MIC_NO_PRESENCE), SND_PCI_QUIRK(0x1043, 0x1c03, "ASUS UM3406HA", ALC294_FIXUP_ASUS_I2C_HEADSET_MIC), SND_PCI_QUIRK(0x1043, 0x1c23, "Asus X55U", ALC269_FIXUP_LIMIT_INT_MIC_BOOST), - SND_PCI_QUIRK(0x1043, 0x1c33, "ASUS UX5304MA", ALC245_FIXUP_CS35L41_SPI_2), + SND_PCI_QUIRK(0x1043, 0x1c33, "ASUS UX5304MA", ALC294_FIXUP_ASUS_SPI_HEADSET_MIC), SND_PCI_QUIRK(0x1043, 0x1c43, "ASUS UX8406MA", ALC245_FIXUP_CS35L41_SPI_2), SND_PCI_QUIRK(0x1043, 0x1c62, "ASUS GU603", ALC289_FIXUP_ASUS_GA401), SND_PCI_QUIRK(0x1043, 0x1c63, "ASUS GU605M", ALC285_FIXUP_ASUS_GU605_SPI_SPEAKER2_TO_DAC1), @@ -8310,7 +8459,6 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x10cf, 0x1757, "Lifebook E752", ALC269_FIXUP_LIFEBOOK_HP_PIN), SND_PCI_QUIRK(0x10cf, 0x1845, "Lifebook U904", ALC269_FIXUP_LIFEBOOK_EXTMIC), SND_PCI_QUIRK(0x10ec, 0x10f2, "Intel Reference board", ALC700_FIXUP_INTEL_REFERENCE), - SND_PCI_QUIRK(0x10ec, 0x111e, "Higole F9B", ALC290_FIXUP_MONO_SPEAKERS), SND_PCI_QUIRK(0x10ec, 0x118c, "Medion EE4254 MD62100", ALC256_FIXUP_MEDION_HEADSET_NO_PRESENCE), SND_PCI_QUIRK(0x10ec, 0x119e, "Positivo SU C1400", ALC269_FIXUP_ASPIRE_HEADSET_MIC), SND_PCI_QUIRK(0x10ec, 0x11bc, "VAIO VJFE-IL", ALC269_FIXUP_LIMIT_INT_MIC_BOOST), @@ -8357,6 +8505,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x1462, 0xb171, "Cubi N 8GL (MS-B171)", ALC283_FIXUP_HEADSET_MIC), SND_PCI_QUIRK(0x152d, 0x1082, "Quanta NL3", ALC269_FIXUP_LIFEBOOK), SND_PCI_QUIRK(0x152d, 0x1262, "Huawei NBLB-WAX9N", ALC2XX_FIXUP_HEADSET_MIC), + SND_PCI_QUIRK(0x152d, 0x1577, "THUNDEROBOT Gravity16G2Pro", ALC256_FIXUP_XIAOMI_PRO15_RESUME), SND_PCI_QUIRK(0x1558, 0x0353, "Clevo V35[05]SN[CDE]Q", ALC256_FIXUP_SYSTEM76_MIC_NO_PRESENCE), SND_PCI_QUIRK(0x1558, 0x1323, "Clevo N130ZU", ALC293_FIXUP_SYSTEM76_MIC_NO_PRESENCE), SND_PCI_QUIRK(0x1558, 0x1325, "Clevo N15[01][CW]U", ALC293_FIXUP_SYSTEM76_MIC_NO_PRESENCE), @@ -8538,6 +8687,9 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x17aa, 0x3827, "Ideapad S740", ALC285_FIXUP_IDEAPAD_S740_COEF), SND_PCI_QUIRK(0x17aa, 0x3834, "Lenovo IdeaPad Slim 9i 14ITL5", ALC287_FIXUP_YOGA7_14ITL_SPEAKERS), SND_PCI_QUIRK(0x17aa, 0x383d, "Legion Y9000X 2019", ALC285_FIXUP_LEGION_Y9000X_SPEAKERS), + /* Legion 16IRX9H shares PCI SSID 17aa:3842 with Thinkpad X G2 below */ + HDA_CODEC_QUIRK(0x17aa, 0x38cb, "Lenovo Legion 16IRX9H", ALC287_FIXUP_TAS2781_I2C), + HDA_CODEC_QUIRK(0x17aa, 0x38cd, "Lenovo Legion 16IRX9H", ALC287_FIXUP_TAS2781_I2C), SND_PCI_QUIRK(0x17aa, 0x3842, "ThinkBook X G2 IAH", ALC287_FIXUP_MG_RTKC_CSAMP_CS35L41_I2C_4_THINKPAD), /* IdeaPad Pro 5 14IAH10 shares PCI SSID 17aa:3843 with Yoga Book 9i; * use codec SSID to distinguish them @@ -8588,6 +8740,8 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x17aa, 0x3886, "Y780 VECO DUAL", ALC287_FIXUP_TAS2781_I2C), SND_PCI_QUIRK(0x17aa, 0x3891, "Lenovo Yoga Pro 7 14AHP9", ALC287_FIXUP_YOGA9_14IAP7_BASS_SPK_PIN), SND_PCI_QUIRK(0x17aa, 0x38a5, "Y580P AMD dual", ALC287_FIXUP_TAS2781_I2C), + /* Yoga Pro 7 14ASP9 shares PCI SSID 17aa:38a7 with Y780P; match on codec SSID */ + HDA_CODEC_QUIRK(0x17aa, 0x3903, "Lenovo Yoga Pro 7 14ASP9", ALC287_FIXUP_YOGA9_14IAP7_BASS_SPK_PIN), SND_PCI_QUIRK(0x17aa, 0x38a7, "Y780P AMD YG dual", ALC287_FIXUP_TAS2781_I2C), SND_PCI_QUIRK(0x17aa, 0x38a8, "Y780P AMD VECO dual", ALC287_FIXUP_TAS2781_I2C), SND_PCI_QUIRK(0x17aa, 0x38a9, "Thinkbook 16P", ALC287_FIXUP_MG_RTKC_CSAMP_CS35L41_I2C_THINKPAD), @@ -8751,6 +8905,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x1f4c, 0xe001, "Minisforum V3 (SE)", ALC245_FIXUP_MINISFORUM_V3_MIC_NO_PRESENCE), SND_PCI_QUIRK(0x1f66, 0x0105, "Ayaneo Portable Game Player", ALC287_FIXUP_CS35L41_I2C_2), + SND_PCI_QUIRK(0x1f75, 0x1602, "ONEXPLAYER X1 i", ALC245_FIXUP_ONEXPLAYER_AMP), SND_PCI_QUIRK(0x2014, 0x800a, "Positivo ARN50", ALC269_FIXUP_LIMIT_INT_MIC_BOOST), SND_PCI_QUIRK(0x2039, 0x0001, "Inspur S14-G1", ALC295_FIXUP_CHROME_BOOK), SND_PCI_QUIRK(0x2145, 0x0001, "Star Labs StarFighter", ALC233_FIXUP_STARLABS_STARFIGHTER), @@ -8769,6 +8924,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x2782, 0xa128, "Positivo N15RPE-S", ALC269_FIXUP_LIMIT_INT_MIC_BOOST), SND_PCI_QUIRK(0x2782, 0xa212, "Lunnen Ground 14", ALC269VC_FIXUP_LUNNEN_GROUND_14), SND_PCI_QUIRK(0x2782, 0xa248, "COLORFUL L1 Plus", ALC233_FIXUP_MEDION_MTL_SPK), + SND_PCI_QUIRK(0x2782, 0xa24a, "Infinix BL51A7H", ALC233_FIXUP_MEDION_MTL_SPK), SND_PCI_QUIRK(0x7017, 0x2014, "Star Labs StarFighter", ALC233_FIXUP_STARLABS_STARFIGHTER), SND_PCI_QUIRK(0x8086, 0x2073, "Intel NUC 8 Hades Canyon", ALC700_FIXUP_INTEL_HADES_CANYON), diff --git a/sound/hda/codecs/side-codecs/Kconfig b/sound/hda/codecs/side-codecs/Kconfig index b7e2a6fa425881..3c36c82fe0a732 100644 --- a/sound/hda/codecs/side-codecs/Kconfig +++ b/sound/hda/codecs/side-codecs/Kconfig @@ -116,7 +116,6 @@ menu "CS35L56 driver options" config SND_HDA_SCODEC_CS35L56_CAL_DEBUGFS bool "CS35L56 create debugfs for factory calibration" depends on DEBUG_FS - select SND_SOC_CS35L56_CAL_DEBUGFS_COMMON help Create debugfs entries used during factory-line manufacture for factory calibration. diff --git a/sound/hda/codecs/side-codecs/cs35l41_hda_property.c b/sound/hda/codecs/side-codecs/cs35l41_hda_property.c index a2e6b302482075..5ab19b1351af7e 100644 --- a/sound/hda/codecs/side-codecs/cs35l41_hda_property.c +++ b/sound/hda/codecs/side-codecs/cs35l41_hda_property.c @@ -83,18 +83,18 @@ static const struct cs35l41_config cs35l41_config_table[] = { { "103C8C4F", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4100, 24 }, { "103C8C50", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4100, 24 }, { "103C8C51", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4100, 24 }, - { "103C8CDD", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4100, 24 }, - { "103C8CDE", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 3900, 24 }, + { "103C8CDD", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4000, 24 }, + { "103C8CDE", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4000, 24 }, { "103C8E11", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4000, 24 }, { "103C8E12", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4000, 24 }, { "103C8E13", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4000, 24 }, { "103C8E3A", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4000, 24 }, { "103C8E3B", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4000, 24 }, - { "103C8E60", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4000, 24 }, + { "103C8E60", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 3500, 24 }, { "103C8E61", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4000, 24 }, { "103C8E62", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4000, 24 }, { "103C8E75", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4000, 24 }, - { "103C8F07", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 3900, 24 }, + { "103C8F07", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4000, 24 }, { "103C8F57", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4000, 24 }, { "104312AF", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 1, 2, 0, 1000, 4500, 24 }, { "10431433", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4500, 24 }, diff --git a/sound/hda/codecs/side-codecs/tas2781_hda_spi.c b/sound/hda/codecs/side-codecs/tas2781_hda_spi.c index 0951a950d585b7..0c68c5b3348c71 100644 --- a/sound/hda/codecs/side-codecs/tas2781_hda_spi.c +++ b/sound/hda/codecs/side-codecs/tas2781_hda_spi.c @@ -780,6 +780,7 @@ static int tas2781_hda_spi_probe(struct spi_device *spi) if (!hda_priv) return -ENOMEM; + tas_hda->dev = &spi->dev; tas_hda->hda_priv = hda_priv; spi->max_speed_hz = TAS2781_SPI_MAX_FREQ; diff --git a/sound/hda/common/codec.c b/sound/hda/common/codec.c index 51189e305ece67..0470f4e085f7bc 100644 --- a/sound/hda/common/codec.c +++ b/sound/hda/common/codec.c @@ -2353,6 +2353,9 @@ static int snd_hda_spdif_out_switch_put(struct snd_kcontrol *kcontrol, if (WARN_ON(codec->spdif_out.used <= idx)) return -EINVAL; + if (ucontrol->value.integer.value[0] < 0 || + ucontrol->value.integer.value[0] > 1) + return -EINVAL; guard(mutex)(&codec->spdif_mutex); spdif = snd_array_elem(&codec->spdif_out, idx); nid = spdif->nid; @@ -2557,9 +2560,11 @@ static int spdif_share_sw_put(struct snd_kcontrol *kcontrol, { struct hda_codec *codec = snd_kcontrol_chip(kcontrol); struct hda_multi_out *mout = (void *)kcontrol->private_value; - bool val = !!ucontrol->value.integer.value[0]; + long val = ucontrol->value.integer.value[0]; int change; + if (val < 0 || val > 1) + return -EINVAL; guard(mutex)(&codec->spdif_mutex); change = mout->share_spdif != val; mout->share_spdif = val; @@ -2632,9 +2637,11 @@ static int snd_hda_spdif_in_switch_put(struct snd_kcontrol *kcontrol, { struct hda_codec *codec = snd_kcontrol_chip(kcontrol); hda_nid_t nid = kcontrol->private_value; - unsigned int val = !!ucontrol->value.integer.value[0]; + long val = ucontrol->value.integer.value[0]; int change; + if (val < 0 || val > 1) + return -EINVAL; guard(mutex)(&codec->spdif_mutex); change = codec->spdif_in_enable != val; if (change) { diff --git a/sound/hda/common/hda_local.h b/sound/hda/common/hda_local.h index 8bd4497a6b0909..61998cc35a449d 100644 --- a/sound/hda/common/hda_local.h +++ b/sound/hda/common/hda_local.h @@ -616,8 +616,6 @@ int snd_hda_get_int_hint(struct hda_codec *codec, const char *key, int *valp) * power-management */ -void snd_hda_schedule_power_save(struct hda_codec *codec); - struct hda_amp_list { hda_nid_t nid; unsigned char dir; @@ -708,7 +706,6 @@ void snd_hdmi_write_eld_info(struct hdmi_eld *eld, #endif #define SND_PRINT_CHANNEL_ALLOCATION_ADVISED_BUFSIZE 80 -void snd_print_channel_allocation(int spk_alloc, char *buf, int buflen); void snd_hda_codec_display_power(struct hda_codec *codec, bool enable); diff --git a/sound/hda/controllers/acpi.c b/sound/hda/controllers/acpi.c index bad32a5c1ae924..91dd9a9a08bd38 100644 --- a/sound/hda/controllers/acpi.c +++ b/sound/hda/controllers/acpi.c @@ -136,7 +136,7 @@ static int hda_acpi_init(struct hda_acpi *hda) sname = hda->data->short_name ? hda->data->short_name : KBUILD_MODNAME; - if (strlen(sname) > sizeof(card->shortname)) + if (strlen(sname) >= sizeof(card->shortname)) dev_info(dev, "truncating shortname for card %s\n", sname); strscpy(card->shortname, sname); diff --git a/sound/hda/controllers/cix-ipbloq.c b/sound/hda/controllers/cix-ipbloq.c index c07098fc13403c..6983957d17c7ce 100644 --- a/sound/hda/controllers/cix-ipbloq.c +++ b/sound/hda/controllers/cix-ipbloq.c @@ -163,7 +163,7 @@ static int cix_ipbloq_hda_init(struct cix_ipbloq_hda *hda, sname = of_get_property(pdev->dev.of_node, "model", NULL); if (!sname) sname = drv_name; - if (strlen(sname) > sizeof(card->shortname)) + if (strlen(sname) >= sizeof(card->shortname)) dev_dbg(card->dev, "truncating shortname for card\n"); strscpy(card->shortname, sname, sizeof(card->shortname)); diff --git a/sound/hda/controllers/intel.c b/sound/hda/controllers/intel.c index 5a7dd69955d4f0..1f754f04eea8df 100644 --- a/sound/hda/controllers/intel.c +++ b/sound/hda/controllers/intel.c @@ -2452,6 +2452,9 @@ static int azx_probe_continue(struct azx *chip, bool free_on_error) } out_free: + if (!hda->need_i915_power) + display_power(chip, false); + if (err < 0) { if (hda->vga_switcheroo_registered) dev_warn(&pci->dev, "GPU sound probed, but not operational: please add a quirk to driver_denylist\n"); @@ -2462,8 +2465,6 @@ static int azx_probe_continue(struct azx *chip, bool free_on_error) return err; } - if (!hda->need_i915_power) - display_power(chip, false); complete_all(&hda->probe_wait); to_hda_bus(bus)->bus_probing = 0; hda->probe_retry = 0; diff --git a/sound/hda/controllers/tegra.c b/sound/hda/controllers/tegra.c index a765307c08f958..c1d8bcbfedf7e9 100644 --- a/sound/hda/controllers/tegra.c +++ b/sound/hda/controllers/tegra.c @@ -390,7 +390,7 @@ static int hda_tegra_first_init(struct azx *chip, struct platform_device *pdev) sname = of_get_property(np, "nvidia,model", NULL); if (!sname) sname = drv_name; - if (strlen(sname) > sizeof(card->shortname)) + if (strlen(sname) >= sizeof(card->shortname)) dev_info(card->dev, "truncating shortname for card\n"); strscpy(card->shortname, sname); diff --git a/sound/isa/sb/emu8000_pcm.c b/sound/isa/sb/emu8000_pcm.c index d2ca70aad1621e..ec26705808d11b 100644 --- a/sound/isa/sb/emu8000_pcm.c +++ b/sound/isa/sb/emu8000_pcm.c @@ -187,6 +187,8 @@ static void emu8k_pcm_timer_func(struct timer_list *t) bool period_elapsed = false; scoped_guard(spinlock, &rec->timer_lock) { + if (!rec->timer_running) + return; /* update the current pointer */ ptr = emu8k_get_curpos(rec, 0); if (ptr < rec->last_ptr) @@ -246,6 +248,8 @@ static int emu8k_pcm_open(struct snd_pcm_substream *subs) static int emu8k_pcm_close(struct snd_pcm_substream *subs) { struct snd_emu8k_pcm *rec = subs->runtime->private_data; + + timer_delete_sync(&rec->timer); kfree(rec); subs->runtime->private_data = NULL; return 0; diff --git a/sound/oss/dmasound/dmasound_core.c b/sound/oss/dmasound/dmasound_core.c index e80f730d08038f..15e4682e6cf89e 100644 --- a/sound/oss/dmasound/dmasound_core.c +++ b/sound/oss/dmasound/dmasound_core.c @@ -1377,18 +1377,29 @@ int dmasound_init(void) /* Set up sound queue, /dev/audio and /dev/dsp. */ /* Set default settings. */ - if ((res = sq_init()) < 0) - return res ; + res = sq_init(); + if (res < 0) + return res; /* Set up /dev/sndstat. */ - if ((res = state_init()) < 0) - return res ; + res = state_init(); + if (res < 0) { + if (sq_unit >= 0) + unregister_sound_dsp(sq_unit); + return res; + } /* Set up /dev/mixer. */ mixer_init(); if (!dmasound.mach.irqinit()) { printk(KERN_ERR "DMA sound driver: Interrupt initialization failed\n"); + if (mixer_unit >= 0) + unregister_sound_mixer(mixer_unit); + if (state_unit >= 0) + unregister_sound_special(state_unit); + if (sq_unit >= 0) + unregister_sound_dsp(sq_unit); return -ENODEV; } irq_installed = 1; diff --git a/sound/pci/emu10k1/emu10k1_synth_local.h b/sound/pci/emu10k1/emu10k1_synth_local.h index 11373695344b15..36b37e7c1a5caa 100644 --- a/sound/pci/emu10k1/emu10k1_synth_local.h +++ b/sound/pci/emu10k1/emu10k1_synth_local.h @@ -19,7 +19,6 @@ int snd_emu10k1_sample_new(struct snd_emux *private_data, int snd_emu10k1_sample_free(struct snd_emux *private_data, struct snd_sf_sample *sp, struct snd_util_memhdr *hdr); -int snd_emu10k1_memhdr_init(struct snd_emux *emu); /* emu10k1_callback.c */ void snd_emu10k1_ops_setup(struct snd_emux *emu); diff --git a/sound/pci/emu10k1/emufx.c b/sound/pci/emu10k1/emufx.c index ddac6cecc8eb2c..df4661927041f0 100644 --- a/sound/pci/emu10k1/emufx.c +++ b/sound/pci/emu10k1/emufx.c @@ -2506,6 +2506,8 @@ static int snd_emu10k1_fx8010_ioctl(struct snd_hwdep * hw, struct file *file, un kfree(icode); return res; case SNDRV_EMU10K1_IOCTL_PCM_POKE: + if (!capable(CAP_SYS_ADMIN)) + return -EPERM; ipcm = memdup_user(argp, sizeof(*ipcm)); if (IS_ERR(ipcm)) return PTR_ERR(ipcm); diff --git a/sound/pci/mixart/mixart.c b/sound/pci/mixart/mixart.c index f451554cff5f1f..0266467734cad8 100644 --- a/sound/pci/mixart/mixart.c +++ b/sound/pci/mixart/mixart.c @@ -1066,8 +1066,9 @@ static int snd_mixart_free(struct mixart_mgr *mgr) snd_card_free(mgr->chip[i]->card); } - /* stop mailbox */ - snd_mixart_exit_mailbox(mgr); + /* stop mailbox, unless the register BAR was never mapped */ + if (mgr->mem[1].virt) + snd_mixart_exit_mailbox(mgr); /* release irq */ if (mgr->irq >= 0) diff --git a/sound/pci/sis7019.c b/sound/pci/sis7019.c index fe5bda5af6a5f5..f31e62068ee36c 100644 --- a/sound/pci/sis7019.c +++ b/sound/pci/sis7019.c @@ -278,15 +278,11 @@ static void sis_update_voice(struct voice *voice) static void sis_voice_irq(u32 status, struct voice *voice) { + unsigned long bits = status; int bit; - while (status) { - bit = __ffs(status); - status >>= bit + 1; - voice += bit; - sis_update_voice(voice); - voice++; - } + for_each_set_bit(bit, &bits, 32) + sis_update_voice(&voice[bit]); } static irqreturn_t sis_interrupt(int irq, void *dev) diff --git a/sound/soc/Kconfig b/sound/soc/Kconfig index d9b746ffd701ca..c5cd938be87391 100644 --- a/sound/soc/Kconfig +++ b/sound/soc/Kconfig @@ -103,6 +103,7 @@ config SND_SOC_USB # All the supported SoCs source "sound/soc/adi/Kconfig" +source "sound/soc/airoha/Kconfig" source "sound/soc/amd/Kconfig" source "sound/soc/apple/Kconfig" source "sound/soc/atmel/Kconfig" diff --git a/sound/soc/Makefile b/sound/soc/Makefile index ba3cf6eb937aa8..0126272811b809 100644 --- a/sound/soc/Makefile +++ b/sound/soc/Makefile @@ -46,6 +46,7 @@ obj-$(CONFIG_SND_SOC) += codecs/ obj-$(CONFIG_SND_SOC) += generic/ obj-$(CONFIG_SND_SOC) += apple/ obj-$(CONFIG_SND_SOC) += adi/ +obj-$(CONFIG_SND_SOC) += airoha/ obj-$(CONFIG_SND_SOC) += amd/ obj-$(CONFIG_SND_SOC) += atmel/ obj-$(CONFIG_SND_SOC) += au1x/ diff --git a/sound/soc/adi/axi-i2s.c b/sound/soc/adi/axi-i2s.c index 2c4035ff6c2d2d..1eeb96b7fd606e 100644 --- a/sound/soc/adi/axi-i2s.c +++ b/sound/soc/adi/axi-i2s.c @@ -208,7 +208,7 @@ static int axi_i2s_probe(struct platform_device *pdev) if (IS_ERR(i2s->regmap)) return PTR_ERR(i2s->regmap); - i2s->clk = devm_clk_get(&pdev->dev, "axi"); + i2s->clk = devm_clk_get_enabled(&pdev->dev, "axi"); if (IS_ERR(i2s->clk)) return PTR_ERR(i2s->clk); @@ -216,10 +216,6 @@ static int axi_i2s_probe(struct platform_device *pdev) if (IS_ERR(i2s->clk_ref)) return PTR_ERR(i2s->clk_ref); - ret = clk_prepare_enable(i2s->clk); - if (ret) - return ret; - if (i2s->has_playback) { axi_i2s_dai.playback.channels_min = 2; axi_i2s_dai.playback.channels_max = 2; @@ -257,28 +253,17 @@ static int axi_i2s_probe(struct platform_device *pdev) ret = devm_snd_soc_register_component(&pdev->dev, &axi_i2s_component, &axi_i2s_dai, 1); if (ret) - goto err_clk_disable; + return ret; ret = devm_snd_dmaengine_pcm_register(&pdev->dev, NULL, 0); if (ret) - goto err_clk_disable; + return ret; dev_info(&pdev->dev, "probed, capture %s, playback %s\n", str_enabled_disabled(i2s->has_capture), str_enabled_disabled(i2s->has_playback)); return 0; - -err_clk_disable: - clk_disable_unprepare(i2s->clk); - return ret; -} - -static void axi_i2s_dev_remove(struct platform_device *pdev) -{ - struct axi_i2s *i2s = platform_get_drvdata(pdev); - - clk_disable_unprepare(i2s->clk); } static const struct of_device_id axi_i2s_of_match[] = { @@ -293,7 +278,6 @@ static struct platform_driver axi_i2s_driver = { .of_match_table = axi_i2s_of_match, }, .probe = axi_i2s_probe, - .remove = axi_i2s_dev_remove, }; module_platform_driver(axi_i2s_driver); diff --git a/sound/soc/adi/axi-spdif.c b/sound/soc/adi/axi-spdif.c index faa1fc7cb973ff..07363ddebb77a2 100644 --- a/sound/soc/adi/axi-spdif.c +++ b/sound/soc/adi/axi-spdif.c @@ -199,7 +199,7 @@ static int axi_spdif_probe(struct platform_device *pdev) if (IS_ERR(spdif->regmap)) return PTR_ERR(spdif->regmap); - spdif->clk = devm_clk_get(&pdev->dev, "axi"); + spdif->clk = devm_clk_get_enabled(&pdev->dev, "axi"); if (IS_ERR(spdif->clk)) return PTR_ERR(spdif->clk); @@ -207,10 +207,6 @@ static int axi_spdif_probe(struct platform_device *pdev) if (IS_ERR(spdif->clk_ref)) return PTR_ERR(spdif->clk_ref); - ret = clk_prepare_enable(spdif->clk); - if (ret) - return ret; - spdif->dma_data.addr = res->start + AXI_SPDIF_REG_TX_FIFO; spdif->dma_data.addr_width = 4; spdif->dma_data.maxburst = 1; @@ -226,24 +222,13 @@ static int axi_spdif_probe(struct platform_device *pdev) ret = devm_snd_soc_register_component(&pdev->dev, &axi_spdif_component, &axi_spdif_dai, 1); if (ret) - goto err_clk_disable; + return ret; ret = devm_snd_dmaengine_pcm_register(&pdev->dev, NULL, 0); if (ret) - goto err_clk_disable; + return ret; return 0; - -err_clk_disable: - clk_disable_unprepare(spdif->clk); - return ret; -} - -static void axi_spdif_dev_remove(struct platform_device *pdev) -{ - struct axi_spdif *spdif = platform_get_drvdata(pdev); - - clk_disable_unprepare(spdif->clk); } static const struct of_device_id axi_spdif_of_match[] = { @@ -258,7 +243,6 @@ static struct platform_driver axi_spdif_driver = { .of_match_table = axi_spdif_of_match, }, .probe = axi_spdif_probe, - .remove = axi_spdif_dev_remove, }; module_platform_driver(axi_spdif_driver); diff --git a/sound/soc/airoha/Kconfig b/sound/soc/airoha/Kconfig new file mode 100644 index 00000000000000..709ba1ec349fd2 --- /dev/null +++ b/sound/soc/airoha/Kconfig @@ -0,0 +1,11 @@ +# SPDX-License-Identifier: GPL-2.0-only + +config SND_SOC_AN7581_PCM + tristate "PCM support for Airoha AN7581 chip" + depends on ARCH_AIROHA || COMPILE_TEST + select REGMAP_MMIO + help + This adds PCM driver for Airoha AN7581 boards + that can be used with other codecs. + Select Y if you have such device. + If unsure select "N". diff --git a/sound/soc/airoha/Makefile b/sound/soc/airoha/Makefile new file mode 100644 index 00000000000000..2522fe705d9a32 --- /dev/null +++ b/sound/soc/airoha/Makefile @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: GPL-2.0 + +obj-$(CONFIG_SND_SOC_AN7581_PCM) += an7581-pcm.o diff --git a/sound/soc/airoha/an7581-pcm.c b/sound/soc/airoha/an7581-pcm.c new file mode 100644 index 00000000000000..8e06527c741e3d --- /dev/null +++ b/sound/soc/airoha/an7581-pcm.c @@ -0,0 +1,929 @@ +// SPDX-License-Identifier: GPL-2.0 +// +//Airoha ALSA SoC PCM platform driver for AN7581 +// +//Copyright (C) 2026 Christian Marangi +// + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define AN7581_PCM_PICR 0x0 +#define AN7581_PCM_CFG_VALID BIT(26) +#define AN7581_PCM_LPBK_ENABLE BIT(25) +#define AN7581_PCM_SOFT_RESET BIT(24) +#define AN7581_PCM_FRAME_COUNT GENMASK(22, 18) +#define AN7581_PCM_BIT_ORDER BIT(16) +#define AN7581_PCM_ONE_BIT_DELAY BIT(12) +#define AN7581_PCM_FS_EDGE BIT(10) +#define AN7581_PCM_FS_LEN GENMASK(9, 8) +#define AN7581_PCM_FS_LEN_8 FIELD_PREP_CONST(AN7581_PCM_FS_LEN, 0x2) +#define AN7581_PCM_FS_LEN_16 FIELD_PREP_CONST(AN7581_PCM_FS_LEN, 0x3) +#define AN7581_PCM_SAMPLE_CLK BIT(4) +#define AN7581_PCM_SAMPLE_CLK_8KHZ FIELD_PREP_CONST(AN7581_PCM_SAMPLE_CLK, 0x0) +#define AN7581_PCM_SAMPLE_CLK_16KHZ FIELD_PREP_CONST(AN7581_PCM_SAMPLE_CLK, 0x1) +#define AN7581_PCM_BIT_CLK GENMASK(3, 1) +#define AN7581_PCM_BIT_CLK_256KHZ FIELD_PREP_CONST(AN7581_PCM_BIT_CLK, 0x0) +#define AN7581_PCM_BIT_CLK_512KHZ FIELD_PREP_CONST(AN7581_PCM_BIT_CLK, 0x1) +#define AN7581_PCM_BIT_CLK_1024KHZ FIELD_PREP_CONST(AN7581_PCM_BIT_CLK, 0x2) +#define AN7581_PCM_BIT_CLK_2048KHZ FIELD_PREP_CONST(AN7581_PCM_BIT_CLK, 0x3) +#define AN7581_PCM_BIT_CLK_4096KHZ FIELD_PREP_CONST(AN7581_PCM_BIT_CLK, 0x4) +#define AN7581_PCM_BIT_CLK_8192KHZ FIELD_PREP_CONST(AN7581_PCM_BIT_CLK, 0x5) +#define AN7581_PCM_BIT_MSTSLV_MODE BIT(0) +#define AN7581_PCM_BIT_MSTSLV_MODE_MASTER FIELD_PREP_CONST(AN7581_PCM_BIT_MSTSLV_MODE, 0x0) +#define AN7581_PCM_BIT_MSTSLV_MODE_SLAVE FIELD_PREP_CONST(AN7581_PCM_BIT_MSTSLV_MODE, 0x1) +/* Same bitmap for all TX timeslot reg */ +#define AN7581_PCM_PTTSCR0 0x4 +#define AN7581_PCM_TXTS1_BW BIT(28) +#define AN7581_PCM_TXTS1_BW_8BIT FIELD_PREP_CONST(AN7581_PCM_TXTS1_BW, 0x0) +#define AN7581_PCM_TXTS1_BW_16BIT FIELD_PREP_CONST(AN7581_PCM_TXTS1_BW, 0x1) +#define AN7581_PCM_TXTS1_START GENMASK(25, 16) +#define AN7581_PCM_TXTS0_BW BIT(12) +#define AN7581_PCM_TXTS0_BW_8BIT FIELD_PREP_CONST(AN7581_PCM_TXTS0_BW, 0x0) +#define AN7581_PCM_TXTS0_BW_16BIT FIELD_PREP_CONST(AN7581_PCM_TXTS0_BW, 0x1) +#define AN7581_PCM_TXTS0_START GENMASK(9, 0) +#define AN7581_PCM_PTTSCR1 0x8 +#define AN7581_PCM_PTTSCR2 0xc +#define AN7581_PCM_PTTSCR3 0x10 +/* Same bitmap for all RX timeslot reg */ +#define AN7581_PCM_PRTSCR0 0x14 +#define AN7581_PCM_RXTS1_BW BIT(28) +#define AN7581_PCM_RXTS1_BW_8BIT FIELD_PREP_CONST(AN7581_PCM_RXTS1_BW, 0x0) +#define AN7581_PCM_RXTS1_BW_16BIT FIELD_PREP_CONST(AN7581_PCM_RXTS1_BW, 0x1) +#define AN7581_PCM_RXTS1_START GENMASK(25, 16) +#define AN7581_PCM_RXTS0_BW BIT(12) +#define AN7581_PCM_RXTS0_BW_8BIT FIELD_PREP_CONST(AN7581_PCM_RXTS0_BW, 0x0) +#define AN7581_PCM_RXTS0_BW_16BIT FIELD_PREP_CONST(AN7581_PCM_RXTS0_BW, 0x1) +#define AN7581_PCM_RXTS0_START GENMASK(9, 0) +#define AN7581_PCM_PRTSCR1 0x18 +#define AN7581_PCM_PRTSCR2 0x1c +#define AN7581_PCM_PRTSCR3 0x20 +#define AN7581_PCM_ISR 0x24 +#define AN7581_PCM_IMR 0x28 +#define AN7581_PCM_IMR_ISI2_INT BIT(16) +#define AN7581_PCM_IMR_ZSI2_INT BIT(15) +#define AN7581_PCM_IMR_SLIC_INT BIT(14) +#define AN7581_PCM_IMR_SFC_INT BIT(13) +#define AN7581_PCM_IMR_ISI1_INT BIT(12) +#define AN7581_PCM_IMR_ZSI1_INT BIT(11) +#define AN7581_PCM_IMR_HUNT_OVERTIME_INT BIT(10) +#define AN7581_PCM_IMR_HUNT_ERR_INT BIT(9) +#define AN7581_PCM_IMR_AHB_BUS_ERR_INT BIT(8) +#define AN7581_PCM_IMR_RBUF_OVERRUN_INT BIT(7) +#define AN7581_PCM_IMR_TBUF_UNDERRUN_INT BIT(6) +#define AN7581_PCM_IMR_RDESC_END_INT BIT(5) +#define AN7581_PCM_IMR_TDESC_END_INT BIT(4) +#define AN7581_PCM_IMR_RDESC_UPDATE_INT BIT(3) +#define AN7581_PCM_IMR_TDESC_UPDATE_INT BIT(2) +#define AN7581_PCM_IMR_TXRX_FB_INT BIT(0) +#define AN7581_PCM_TPDR 0x2c +#define AN7581_PCM_TX_POLLING BIT(0) +#define AN7581_PCM_RPDR 0x30 +#define AN7581_PCM_RX_POLLING BIT(0) +#define AN7581_PCM_TDRBAR 0x34 +#define AN7581_TDESC_BASE GENMASK(31, 0) +#define AN7581_PCM_RDRBAR 0x38 +#define AN7581_RDESC_BASE GENMASK(31, 0) +#define AN7581_PCM_TRDRSR 0x3c +#define AN7581_DESC_OFFSET GENMASK(7, 4) +#define AN7581_DESC_SIZE GENMASK(3, 0) +#define AN7581_PCM_TRDCR 0x40 +#define AN7581_PCM_DMA_POLICY GENMASK(3, 2) +#define AN7581_PCM_DMA_POLICY_RR FIELD_PREP_CONST(AN7581_PCM_DMA_POLICY, 0x0) +#define AN7581_PCM_DMA_POLICY_RSVD FIELD_PREP_CONST(AN7581_PCM_DMA_POLICY, 0x1) +#define AN7581_PCM_DMA_POLICY_TX_PRIORITY FIELD_PREP_CONST(AN7581_PCM_DMA_POLICY, 0x2) +#define AN7581_PCM_DMA_POLICY_RX_PRIORITY FIELD_PREP_CONST(AN7581_PCM_DMA_POLICY, 0x3) +#define AN7581_PCM_RXDMA_ENABLE BIT(1) +#define AN7581_PCM_TXDMA_ENABLE BIT(0) +#define AN7581_PCM_PTTSCR4 0x48 +#define AN7581_PCM_PTTSCR5 0x4c +#define AN7581_PCM_PTTSCR6 0x50 +#define AN7581_PCM_PTTSCR7 0x54 +#define AN7581_PCM_PTTSCR8 0x58 +#define AN7581_PCM_PTTSCR9 0x5c +#define AN7581_PCM_PTTSCR10 0x60 +#define AN7581_PCM_PTTSCR11 0x64 +#define AN7581_PCM_PTTSCR12 0x68 +#define AN7581_PCM_PTTSCR13 0x6c +#define AN7581_PCM_PTTSCR14 0x70 +#define AN7581_PCM_PTTSCR15 0x74 +#define AN7581_PCM_PTTSCR(chan) ((chan) < 8 ? \ + (AN7581_PCM_PTTSCR0 + ((chan) / 2) * 4) : \ + (AN7581_PCM_PTTSCR4 + (((chan) - 8) / 2) * 4)) +#define AN7581_PCM_TXTS_BW(chan) ((chan) % 2 ? AN7581_PCM_TXTS1_BW : AN7581_PCM_TXTS0_BW) +#define AN7581_PCM_TXTS_BW_8BIT 0x0 +#define AN7581_PCM_TXTS_BW_16BIT(chan) AN7581_PCM_TXTS_BW(chan) +#define AN7581_PCM_TXTS_START(chan) ((chan) % 2 ? AN7581_PCM_TXTS1_START : AN7581_PCM_TXTS0_START) +#define AN7581_PCM_PRTSCR4 0x78 +#define AN7581_PCM_PRTSCR5 0x7c +#define AN7581_PCM_PRTSCR6 0x80 +#define AN7581_PCM_PRTSCR7 0x84 +#define AN7581_PCM_PRTSCR8 0x88 +#define AN7581_PCM_PRTSCR9 0x8c +#define AN7581_PCM_PRTSCR10 0x90 +#define AN7581_PCM_PRTSCR11 0x94 +#define AN7581_PCM_PRTSCR12 0x98 +#define AN7581_PCM_PRTSCR13 0x9c +#define AN7581_PCM_PRTSCR14 0xa0 +#define AN7581_PCM_PRTSCR15 0xa4 +#define AN7581_PCM_PRTSCR(chan) ((chan) < 8 ? \ + (AN7581_PCM_PRTSCR0 + ((chan) / 2) * 4) : \ + (AN7581_PCM_PRTSCR4 + (((chan) - 8) / 2) * 4)) +#define AN7581_PCM_RXTS_BW(chan) ((chan) % 2 ? AN7581_PCM_RXTS1_BW : AN7581_PCM_RXTS0_BW) +#define AN7581_PCM_RXTS_BW_8BIT 0x0 +#define AN7581_PCM_RXTS_BW_16BIT(chan) AN7581_PCM_RXTS_BW(chan) +#define AN7581_PCM_RXTS_START(chan) ((chan) % 2 ? AN7581_PCM_RXTS1_START : AN7581_PCM_RXTS0_START) +#define AN7581_PCM_CHBFOSR 0xa8 +#define AN7581_PCM_DESC_CHBF_OFFSET GENMASK(15, 0) +#define AN7581_PCM_DCHENR 0xac +/* Each channel correspond to a bit. + * Example: + * BIT(0) -> chan 0 + * BIT(1) -> chan 1 + * ... + * + * Notice that it's expected the channel are sequential + * aka it's not possible to have empty channel in between. + * (example BIT(0) | BIT(2)) + */ +#define AN7581_PCM_CHAN_EN GENMASK(31, 0) + +#define AN7581_PCM_MAX_CHANNELS 32 +#define AN7581_PCM_TX_DESCRIPTORS 15 +#define AN7581_PCM_RX_DESCRIPTORS 15 +#define AN7581_PCM_DESCRIPTORS (AN7581_PCM_TX_DESCRIPTORS + AN7581_PCM_RX_DESCRIPTORS) +#define AN7581_PCM_FRAMES_PER_DESC 80 +#define AN7581_PCM_MIN_PERIOD_BYTES (AN7581_PCM_FRAMES_PER_DESC * sizeof(u8)) +#define AN7581_PCM_MAX_SAMPLE_BYTES 2 +#define AN7581_PCM_MAX_PERIOD_BYTES (AN7581_PCM_FRAMES_PER_DESC * \ + AN7581_PCM_MAX_CHANNELS * \ + AN7581_PCM_MAX_SAMPLE_BYTES) +#define AN7581_PCM_MAX_BUFFER_BYTES (AN7581_PCM_MAX_PERIOD_BYTES * \ + AN7581_PCM_TX_DESCRIPTORS) + +#define AN7581_PCM_DESC_STATUS_OWNERSHIP BIT(31) +#define AN7581_PCM_DESC_STATUS_OWNERSHIP_CPU FIELD_PREP_CONST(AN7581_PCM_DESC_STATUS_OWNERSHIP, 0x0) +#define AN7581_PCM_DESC_STATUS_OWNERSHIP_DMA FIELD_PREP_CONST(AN7581_PCM_DESC_STATUS_OWNERSHIP, 0x1) +#define AN7581_PCM_DESC_STATUS_SAMPLE_SIZE GENMASK(9, 0) + +#define AN7581_PCM_DEFAULT_BCLK 2048 + +struct an7581_pcm_desc { + u32 status; + u32 channel_mask; + u32 dma_addr; +} __packed; + +struct an7581_pcm_priv { + struct regmap *map; + + /* Cached current stream for IRQ */ + struct snd_pcm_substream *stream[SNDRV_PCM_STREAM_LAST + 1]; + + /* Protect descriptor idx */ + spinlock_t desc_lock; + /* Protect configuration shared by playback and capture. */ + struct mutex user_lock; + unsigned int users; + unsigned int current_rate; + unsigned int current_channels; + + struct an7581_pcm_desc *tx_descs; + int tx_desc_idx; + dma_addr_t tx_dma; + + struct an7581_pcm_desc *rx_descs; + int rx_desc_idx; + dma_addr_t rx_dma; + + unsigned int tx_pos; + unsigned int rx_pos; +}; + +static const struct snd_pcm_hardware an7581_pcm_hardware = { + .info = SNDRV_PCM_INFO_MMAP | + SNDRV_PCM_INFO_MMAP_VALID | + SNDRV_PCM_INFO_INTERLEAVED | + SNDRV_PCM_INFO_BATCH, + .formats = SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_U16_LE, + + .period_bytes_min = AN7581_PCM_MIN_PERIOD_BYTES, + .period_bytes_max = AN7581_PCM_MAX_PERIOD_BYTES, + + .buffer_bytes_max = AN7581_PCM_MAX_BUFFER_BYTES, + + .periods_min = AN7581_PCM_TX_DESCRIPTORS, + .periods_max = AN7581_PCM_TX_DESCRIPTORS, +}; + +static int an7581_pcm_setup_time_slot(struct an7581_pcm_priv *priv, + int direction, int bit_width) +{ + int bit_counter = 0; + int chan; + + for (chan = 0; chan < AN7581_PCM_MAX_CHANNELS; chan++) { + u32 mask, val; + u32 reg; + + if (direction == SNDRV_PCM_STREAM_PLAYBACK) { + reg = AN7581_PCM_PTTSCR(chan); + mask = AN7581_PCM_TXTS_BW(chan) | + AN7581_PCM_TXTS_START(chan); + + if (bit_width == 8) + val = AN7581_PCM_TXTS_BW_8BIT; + else + val = AN7581_PCM_TXTS_BW_16BIT(chan); + val |= bit_counter << __bf_shf(AN7581_PCM_TXTS_START(chan)); + } else { + reg = AN7581_PCM_PRTSCR(chan); + mask = AN7581_PCM_RXTS_BW(chan) | + AN7581_PCM_RXTS_START(chan); + + if (bit_width == 8) + val = AN7581_PCM_RXTS_BW_8BIT; + else + val = AN7581_PCM_RXTS_BW_16BIT(chan); + val |= bit_counter << __bf_shf(AN7581_PCM_RXTS_START(chan)); + } + + regmap_update_bits(priv->map, reg, mask, val); + + bit_counter += bit_width; + } + + return 0; +} + +static int an7581_pcm_startup(struct snd_pcm_substream *substream, + struct snd_soc_dai *dai) +{ + struct snd_soc_pcm_runtime *rtd = snd_soc_substream_to_rtd(substream); + struct an7581_pcm_priv *priv = snd_soc_card_get_drvdata(rtd->card); + struct snd_pcm_runtime *runtime = substream->runtime; + int ret; + + snd_soc_set_runtime_hwparams(substream, &an7581_pcm_hardware); + + ret = snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_PERIOD_SIZE, + AN7581_PCM_FRAMES_PER_DESC, + AN7581_PCM_FRAMES_PER_DESC); + if (ret < 0) { + dev_err(rtd->card->dev, "failed to constrain period to 80 frames\n"); + return ret; + } + + ret = snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS); + if (ret < 0) { + dev_err(rtd->card->dev, "snd_pcm_hw_constraint_integer failed\n"); + return ret; + } + + /* Cache stream substream for IRQ handling */ + priv->stream[substream->stream] = substream; + + /* On open mask interrupt and disable DMA */ + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { + regmap_clear_bits(priv->map, AN7581_PCM_IMR, + AN7581_PCM_IMR_TDESC_UPDATE_INT); + regmap_clear_bits(priv->map, AN7581_PCM_TRDCR, + AN7581_PCM_TXDMA_ENABLE); + } else { + regmap_clear_bits(priv->map, AN7581_PCM_IMR, + AN7581_PCM_IMR_RDESC_UPDATE_INT); + regmap_clear_bits(priv->map, AN7581_PCM_TRDCR, + AN7581_PCM_RXDMA_ENABLE); + } + + usleep_range(10000, 20000); + + mutex_lock(&priv->user_lock); + + if (!priv->users) { + regmap_clear_bits(priv->map, AN7581_PCM_PICR, + AN7581_PCM_CFG_VALID); + + usleep_range(5000, 10000); + } + + priv->users++; + + mutex_unlock(&priv->user_lock); + + return ret; +} + +static void an7581_pcm_shutdown(struct snd_pcm_substream *substream, + struct snd_soc_dai *dai) +{ + struct snd_soc_pcm_runtime *rtd = snd_soc_substream_to_rtd(substream); + struct an7581_pcm_priv *priv = snd_soc_card_get_drvdata(rtd->card); + + /* On close mask interrupt and disable DMA */ + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { + regmap_clear_bits(priv->map, AN7581_PCM_IMR, + AN7581_PCM_IMR_TDESC_UPDATE_INT); + regmap_clear_bits(priv->map, AN7581_PCM_TRDCR, + AN7581_PCM_TXDMA_ENABLE); + } else { + regmap_clear_bits(priv->map, AN7581_PCM_IMR, + AN7581_PCM_IMR_RDESC_UPDATE_INT); + regmap_clear_bits(priv->map, AN7581_PCM_TRDCR, + AN7581_PCM_RXDMA_ENABLE); + } + + priv->stream[substream->stream] = NULL; + + usleep_range(10000, 20000); + + mutex_lock(&priv->user_lock); + + if (priv->users) + priv->users--; + + if (!priv->users) + regmap_clear_bits(priv->map, AN7581_PCM_PICR, + AN7581_PCM_CFG_VALID); + + mutex_unlock(&priv->user_lock); +} + +/* + * Hardware position is always reset to the start when a TX/RX polling is + * triggered. This is handled in trigger. + */ +static int an7581_pcm_prepare(struct snd_pcm_substream *substream, + struct snd_soc_dai *dai) +{ + struct snd_soc_pcm_runtime *rtd = snd_soc_substream_to_rtd(substream); + struct an7581_pcm_priv *priv = snd_soc_card_get_drvdata(rtd->card); + struct snd_pcm_runtime *runtime = substream->runtime; + struct an7581_pcm_desc *desc; + unsigned int period_bytes; + unsigned long flags; + int num_desc, i; + + spin_lock_irqsave(&priv->desc_lock, flags); + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { + priv->tx_pos = 0; + priv->tx_desc_idx = 0; + desc = priv->tx_descs; + num_desc = AN7581_PCM_TX_DESCRIPTORS; + } else { + priv->rx_pos = 0; + priv->rx_desc_idx = 0; + desc = priv->rx_descs; + num_desc = AN7581_PCM_RX_DESCRIPTORS; + } + spin_unlock_irqrestore(&priv->desc_lock, flags); + + period_bytes = frames_to_bytes(runtime, AN7581_PCM_FRAMES_PER_DESC); + for (i = 0; i < num_desc; i++) { + desc->status |= AN7581_PCM_DESC_STATUS_OWNERSHIP_DMA; + desc->dma_addr = runtime->dma_addr + i * period_bytes; + desc++; + } + + return 0; +} + +static int an7581_pcm_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params, + struct snd_soc_dai *dai) +{ + struct snd_soc_pcm_runtime *rtd = snd_soc_substream_to_rtd(substream); + struct an7581_pcm_priv *priv = snd_soc_card_get_drvdata(rtd->card); + unsigned int channels = params_channels(params); + unsigned int rate = params_rate(params); + int bit_width = params_width(params); + struct an7581_pcm_desc *desc; + int num_desc, i; + + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { + desc = priv->tx_descs; + num_desc = AN7581_PCM_TX_DESCRIPTORS; + } else { + desc = priv->rx_descs; + num_desc = AN7581_PCM_RX_DESCRIPTORS; + } + + mutex_lock(&priv->user_lock); + if (priv->users > 1 && + (priv->current_rate != rate || + priv->current_channels != channels)) { + dev_err(rtd->card->dev, "playback/capture rates/channels must match in full-duplex mode\n"); + mutex_unlock(&priv->user_lock); + return -EBUSY; + } + + if ((unsigned long)rate * channels * bit_width > AN7581_PCM_DEFAULT_BCLK * HZ_PER_KHZ) { + dev_err(rtd->card->dev, + "%u channels at %u Hz and %d-bit exceed %u KHz BCLK\n", + channels, rate, bit_width, + AN7581_PCM_DEFAULT_BCLK); + mutex_unlock(&priv->user_lock); + return -EINVAL; + } + + if (priv->users <= 1) { + /* one bit delay for ZSI */ + regmap_set_bits(priv->map, AN7581_PCM_PICR, AN7581_PCM_ONE_BIT_DELAY); + + regmap_update_bits(priv->map, AN7581_PCM_PICR, + AN7581_PCM_BIT_MSTSLV_MODE, + AN7581_PCM_BIT_MSTSLV_MODE_MASTER); + + regmap_update_bits(priv->map, AN7581_PCM_PICR, + AN7581_PCM_BIT_CLK, + AN7581_PCM_BIT_CLK_2048KHZ); + + regmap_update_bits(priv->map, AN7581_PCM_PICR, + AN7581_PCM_SAMPLE_CLK, + (rate == 16000 ? AN7581_PCM_SAMPLE_CLK_16KHZ : + AN7581_PCM_SAMPLE_CLK_8KHZ)); + + regmap_update_bits(priv->map, AN7581_PCM_PICR, + AN7581_PCM_FS_LEN, + AN7581_PCM_FS_LEN_16); + + regmap_set_bits(priv->map, AN7581_PCM_PICR, AN7581_PCM_BIT_ORDER); + + regmap_clear_bits(priv->map, AN7581_PCM_PICR, AN7581_PCM_FS_EDGE); + } + + /* Setup timeslot */ + an7581_pcm_setup_time_slot(priv, substream->stream, bit_width); + + if (priv->users <= 1) { + /* Setup Descriptor size and number */ + regmap_update_bits(priv->map, AN7581_PCM_TRDRSR, + AN7581_DESC_OFFSET | AN7581_DESC_SIZE, + FIELD_PREP(AN7581_DESC_OFFSET, sizeof(*desc) / sizeof(u32)) | + FIELD_PREP(AN7581_DESC_SIZE, num_desc)); + + /* + * The usage of this register is not entirely clear, it should tell + * DMA the size of the channel buffer. HW Loopback enabled with a + * playback and capture with a 2 channel test audio file, verified + * that channel handling is interleaved and recorded a similar + * audio file compared to the one provided with playback. + */ + regmap_update_bits(priv->map, AN7581_PCM_CHBFOSR, + AN7581_PCM_DESC_CHBF_OFFSET, + FIELD_PREP(AN7581_PCM_DESC_CHBF_OFFSET, + AN7581_PCM_FRAMES_PER_DESC * bit_width / 8)); + } + + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) + regmap_write(priv->map, AN7581_PCM_TDRBAR, priv->tx_dma); + else + regmap_write(priv->map, AN7581_PCM_RDRBAR, priv->rx_dma); + + /* Configure descriptors for DMA ownership and sample size */ + for (i = 0; i < num_desc; i++) { + /* Assign to each descriptor the dma_addr + offset of period bytes */ + desc[i].status = FIELD_PREP(AN7581_PCM_DESC_STATUS_SAMPLE_SIZE, + AN7581_PCM_FRAMES_PER_DESC); + + desc[i].channel_mask = GENMASK(channels - 1, 0); + } + + if (priv->users <= 1) { + /* Enable channels */ + regmap_update_bits(priv->map, AN7581_PCM_DCHENR, + AN7581_PCM_CHAN_EN, + FIELD_PREP(AN7581_PCM_CHAN_EN, GENMASK(channels - 1, 0))); + + /* Signal PCM configuration is now valid */ + regmap_set_bits(priv->map, AN7581_PCM_PICR, + AN7581_PCM_CFG_VALID); + } + + priv->current_rate = rate; + priv->current_channels = channels; + + mutex_unlock(&priv->user_lock); + + return 0; +} + +static int an7581_pcm_trigger(struct snd_pcm_substream *substream, int cmd, + struct snd_soc_dai *dai) +{ + struct snd_soc_pcm_runtime *rtd = snd_soc_substream_to_rtd(substream); + struct an7581_pcm_priv *priv = snd_soc_card_get_drvdata(rtd->card); + + switch (cmd) { + case SNDRV_PCM_TRIGGER_START: + case SNDRV_PCM_TRIGGER_RESUME: + /* Trigger PCM to POLL new descriptor */ + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { + regmap_set_bits(priv->map, AN7581_PCM_TRDCR, + AN7581_PCM_TXDMA_ENABLE); + + regmap_set_bits(priv->map, AN7581_PCM_IMR, + AN7581_PCM_IMR_TDESC_UPDATE_INT); + + regmap_write(priv->map, AN7581_PCM_TPDR, + AN7581_PCM_TX_POLLING); + } else { + regmap_set_bits(priv->map, AN7581_PCM_TRDCR, + AN7581_PCM_RXDMA_ENABLE); + + regmap_set_bits(priv->map, AN7581_PCM_IMR, + AN7581_PCM_IMR_RDESC_UPDATE_INT); + + regmap_write(priv->map, AN7581_PCM_RPDR, + AN7581_PCM_RX_POLLING); + } + + break; + case SNDRV_PCM_TRIGGER_STOP: + case SNDRV_PCM_TRIGGER_SUSPEND: + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { + regmap_clear_bits(priv->map, AN7581_PCM_IMR, + AN7581_PCM_IMR_TDESC_UPDATE_INT); + regmap_clear_bits(priv->map, AN7581_PCM_TRDCR, + AN7581_PCM_TXDMA_ENABLE); + } else { + regmap_clear_bits(priv->map, AN7581_PCM_IMR, + AN7581_PCM_IMR_RDESC_UPDATE_INT); + regmap_clear_bits(priv->map, AN7581_PCM_TRDCR, + AN7581_PCM_RXDMA_ENABLE); + } + + break; + default: + return -EINVAL; + } + + return 0; +} + +static const struct snd_soc_dai_ops an7581_pcm_ops = { + .startup = an7581_pcm_startup, + .shutdown = an7581_pcm_shutdown, + .hw_params = an7581_pcm_hw_params, + .prepare = an7581_pcm_prepare, + .trigger = an7581_pcm_trigger, +}; + +static struct snd_soc_dai_driver an7581_pcm_dai_driver[] = { + { + .name = "DLPCM", + .id = 0, + .playback = { + .stream_name = "DLPCM", + .channels_min = 1, + .channels_max = 32, + .rates = SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000, + .formats = SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_U16_LE, + }, + .ops = &an7581_pcm_ops, + }, + { + .name = "ULPCM", + .id = 1, + .capture = { + .stream_name = "ULPCM", + .channels_min = 1, + .channels_max = 32, + .rates = SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000, + .formats = SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_U16_LE, + }, + .ops = &an7581_pcm_ops, + }, +}; + +static const struct snd_soc_component_driver an7581_pcm_dai_component = { + .name = "an7581-pcm-dai", +}; + +static snd_pcm_uframes_t an7581_pcm_pointer(struct snd_soc_component *component, + struct snd_pcm_substream *substream) +{ + struct snd_soc_card *card = component->card; + struct snd_pcm_runtime *runtime = substream->runtime; + struct an7581_pcm_priv *priv; + unsigned long flags; + unsigned int pos; + + priv = snd_soc_card_get_drvdata(card); + + spin_lock_irqsave(&priv->desc_lock, flags); + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) + pos = bytes_to_frames(runtime, priv->tx_pos); + else + pos = bytes_to_frames(runtime, priv->rx_pos); + spin_unlock_irqrestore(&priv->desc_lock, flags); + + return pos % runtime->buffer_size; +} + +static int an7581_pcm_new(struct snd_soc_component *component, + struct snd_soc_pcm_runtime *rtd) +{ + struct snd_pcm *pcm = rtd->pcm; + + snd_pcm_set_managed_buffer_all(pcm, SNDRV_DMA_TYPE_DEV, component->dev, + 0, + AN7581_PCM_MAX_BUFFER_BYTES); + + return 0; +} + +static const struct snd_soc_component_driver an7581_pcm_platform = { + .name = "an7581-pcm-audio", + .pointer = an7581_pcm_pointer, + .pcm_new = an7581_pcm_new, +}; + +SND_SOC_DAILINK_DEFS(playback, + DAILINK_COMP_ARRAY(COMP_CPU("DLPCM")), + DAILINK_COMP_ARRAY(COMP_DUMMY()), + DAILINK_COMP_ARRAY(COMP_EMPTY())); + +SND_SOC_DAILINK_DEFS(capture, + DAILINK_COMP_ARRAY(COMP_CPU("ULPCM")), + DAILINK_COMP_ARRAY(COMP_DUMMY()), + DAILINK_COMP_ARRAY(COMP_EMPTY())); + +static struct snd_soc_dai_link an7581_pcm_dai_links[] = { + { + .name = "an7581-playback", + .stream_name = "an7581-playback", + .playback_only = 1, + SND_SOC_DAILINK_REG(playback), + }, + { + .name = "an7581-capture", + .stream_name = "an7581-capture", + .capture_only = 1, + SND_SOC_DAILINK_REG(capture), + }, +}; + +static struct snd_soc_card an7581_pcm_card = { + .name = "an7581-pcm", + .owner = THIS_MODULE, + .dai_link = an7581_pcm_dai_links, + .num_links = ARRAY_SIZE(an7581_pcm_dai_links), +}; + +static irqreturn_t an7581_pcm_irq_handler(int irq, void *data) +{ + struct snd_pcm_substream *substream; + struct an7581_pcm_priv *priv = data; + irqreturn_t ret = IRQ_NONE; + unsigned long flags; + u32 status, isr = 0; + + regmap_read(priv->map, AN7581_PCM_ISR, &isr); + + /* Scan descriptor on receiving RX desc update interrupt */ + if (isr & AN7581_PCM_IMR_RDESC_UPDATE_INT) { + struct snd_pcm_runtime *runtime; + struct an7581_pcm_desc *desc; + unsigned int sample_size; + bool rx_poll = false; + int i; + + substream = priv->stream[SNDRV_PCM_STREAM_CAPTURE]; + if (!substream) + goto handle_tx; + + ret = IRQ_HANDLED; + runtime = substream->runtime; + + for (i = 0; i < AN7581_PCM_RX_DESCRIPTORS; i++) { + spin_lock_irqsave(&priv->desc_lock, flags); + + desc = &priv->rx_descs[priv->rx_desc_idx]; + status = desc->status; + if ((status & AN7581_PCM_DESC_STATUS_OWNERSHIP) == + AN7581_PCM_DESC_STATUS_OWNERSHIP_DMA) { + spin_unlock_irqrestore(&priv->desc_lock, + flags); + break; + } + + sample_size = FIELD_GET(AN7581_PCM_DESC_STATUS_SAMPLE_SIZE, + status); + + priv->rx_pos += frames_to_bytes(runtime, sample_size); + priv->rx_desc_idx++; + if (priv->rx_desc_idx == AN7581_PCM_RX_DESCRIPTORS) + priv->rx_desc_idx = 0; + + spin_unlock_irqrestore(&priv->desc_lock, flags); + + snd_pcm_period_elapsed(substream); + + desc->status |= AN7581_PCM_DESC_STATUS_OWNERSHIP_DMA; + + if (snd_pcm_capture_hw_avail(runtime) < runtime->period_size) + goto handle_tx; + + rx_poll = true; + } + + if (rx_poll) + regmap_write(priv->map, AN7581_PCM_RPDR, AN7581_PCM_RX_POLLING); + } + +handle_tx: + /* Scan descriptor on receiving TX desc update interrupt */ + if (isr & AN7581_PCM_IMR_TDESC_UPDATE_INT) { + struct snd_pcm_runtime *runtime; + struct an7581_pcm_desc *desc; + unsigned int sample_size; + bool tx_poll = false; + int i; + + substream = priv->stream[SNDRV_PCM_STREAM_PLAYBACK]; + if (!substream) + goto exit; + + ret = IRQ_HANDLED; + runtime = substream->runtime; + + for (i = 0; i < AN7581_PCM_TX_DESCRIPTORS; i++) { + spin_lock_irqsave(&priv->desc_lock, flags); + + desc = &priv->tx_descs[priv->tx_desc_idx]; + status = desc->status; + if ((status & AN7581_PCM_DESC_STATUS_OWNERSHIP) == + AN7581_PCM_DESC_STATUS_OWNERSHIP_DMA) { + spin_unlock_irqrestore(&priv->desc_lock, + flags); + break; + } + + sample_size = FIELD_GET(AN7581_PCM_DESC_STATUS_SAMPLE_SIZE, + status); + + priv->tx_pos += frames_to_bytes(runtime, sample_size); + priv->tx_desc_idx++; + if (priv->tx_desc_idx == AN7581_PCM_TX_DESCRIPTORS) + priv->tx_desc_idx = 0; + + spin_unlock_irqrestore(&priv->desc_lock, flags); + + snd_pcm_period_elapsed(substream); + + desc->status |= AN7581_PCM_DESC_STATUS_OWNERSHIP_DMA; + + if (snd_pcm_playback_hw_avail(runtime) < runtime->period_size) + return IRQ_HANDLED; + + tx_poll = true; + } + + if (tx_poll) + regmap_write(priv->map, AN7581_PCM_TPDR, + AN7581_PCM_TX_POLLING); + } + +exit: + return ret; +} + +static const struct regmap_config an7581_pcm_regmap_config = { + .reg_bits = 32, + .val_bits = 32, + .reg_stride = 4, +}; + +static int an7581_pcm_probe(struct platform_device *pdev) +{ + struct snd_soc_card *card = &an7581_pcm_card; + struct snd_soc_dai_link *dai_link; + struct device *dev = &pdev->dev; + struct an7581_pcm_priv *priv; + struct reset_control *reset; + void __iomem *base; + int irq; + int ret; + int i; + + card->dev = dev; + + priv = devm_kzalloc(dev, sizeof(*priv), GFP_KERNEL); + if (!priv) + return -ENOMEM; + snd_soc_card_set_drvdata(card, priv); + + base = devm_platform_ioremap_resource(pdev, 0); + if (IS_ERR(base)) + return PTR_ERR(base); + + priv->map = devm_regmap_init_mmio(dev, base, + &an7581_pcm_regmap_config); + if (IS_ERR(priv->map)) + return PTR_ERR(priv->map); + + reset = devm_reset_control_get_exclusive(dev, "pcm1"); + if (IS_ERR(reset)) + return PTR_ERR(reset); + + irq = of_irq_get(dev_of_node(dev), 0); + if (irq < 0) + return irq; + + ret = devm_request_irq(dev, irq, an7581_pcm_irq_handler, + 0, dev_name(dev), priv); + if (ret) + return ret; + + spin_lock_init(&priv->desc_lock); + mutex_init(&priv->user_lock); + + /* Reset the PCM interface */ + reset_control_assert(reset); + usleep_range(5000, 10000); + reset_control_deassert(reset); + usleep_range(5000, 10000); + + ret = dma_set_coherent_mask(dev, DMA_BIT_MASK(32)); + if (ret) + return ret; + + priv->tx_descs = dmam_alloc_coherent(dev, sizeof(struct an7581_pcm_desc) * + AN7581_PCM_TX_DESCRIPTORS, &priv->tx_dma, + GFP_KERNEL); + if (!priv->tx_descs) + return -ENOMEM; + + priv->rx_descs = dmam_alloc_coherent(dev, sizeof(struct an7581_pcm_desc) * + AN7581_PCM_RX_DESCRIPTORS, &priv->rx_dma, + GFP_KERNEL); + if (!priv->rx_descs) + return -ENOMEM; + + for_each_card_prelinks(card, i, dai_link) + dai_link->platforms->of_node = dev->of_node; + + ret = devm_snd_soc_register_component(dev, + &an7581_pcm_platform, + NULL, 0); + if (ret) + return dev_err_probe(dev, ret, "Cannot register PCM component\n"); + + ret = devm_snd_soc_register_component(dev, + &an7581_pcm_dai_component, + an7581_pcm_dai_driver, + ARRAY_SIZE(an7581_pcm_dai_driver)); + if (ret) + return dev_err_probe(dev, ret, "Cannot register PCM DAI component\n"); + + ret = devm_snd_soc_register_card(dev, card); + if (ret) + return dev_err_probe(dev, ret, "%s snd_soc_register_card fail\n", __func__); + + return 0; +} + +static void an7581_pcm_remove(struct platform_device *pdev) +{ + struct snd_soc_card *card = &an7581_pcm_card; + struct an7581_pcm_priv *priv; + + priv = snd_soc_card_get_drvdata(card); + regmap_clear_bits(priv->map, AN7581_PCM_IMR, + AN7581_PCM_IMR_TDESC_UPDATE_INT | + AN7581_PCM_IMR_RDESC_UPDATE_INT); + regmap_clear_bits(priv->map, AN7581_PCM_TRDCR, + AN7581_PCM_TXDMA_ENABLE | + AN7581_PCM_RXDMA_ENABLE); +} + +static const struct of_device_id an7581_pcm_dt_match[] = { + { .compatible = "airoha,an7581-pcm" }, + { /* sentinel */ } +}; +MODULE_DEVICE_TABLE(of, an7581_pcm_dt_match); + +static struct platform_driver an7581_pcm_driver = { + .driver = { + .name = "an7581-pcm", + .of_match_table = an7581_pcm_dt_match, + .pm = &snd_soc_pm_ops, + }, + .probe = an7581_pcm_probe, + .remove = an7581_pcm_remove, +}; +module_platform_driver(an7581_pcm_driver); + +MODULE_DESCRIPTION("Airoha SoC PCM platform driver for ALSA AN7581"); +MODULE_AUTHOR("Christian Marangi "); +MODULE_LICENSE("GPL"); diff --git a/sound/soc/amd/acp-config.c b/sound/soc/amd/acp-config.c index 8bd194daedbf1c..e2daa196a1c1be 100644 --- a/sound/soc/amd/acp-config.c +++ b/sound/soc/amd/acp-config.c @@ -72,6 +72,13 @@ static const struct dmi_system_id acp70_acpi_flag_override_table[] = { DMI_MATCH(DMI_PRODUCT_NAME, "83Q6"), }, }, + { + /* Lenovo IdeaPad Slim 5 16AKP10 (Krackan Point, ACP 7.0) */ + .matches = { + DMI_MATCH(DMI_BOARD_VENDOR, "LENOVO"), + DMI_MATCH(DMI_PRODUCT_NAME, "83HY"), + }, + }, { .matches = { DMI_MATCH(DMI_BOARD_VENDOR, "ASUSTeK COMPUTER INC"), diff --git a/sound/soc/amd/acp/Kconfig b/sound/soc/amd/acp/Kconfig index 1b492a9ab58237..23ce610eabce3a 100644 --- a/sound/soc/amd/acp/Kconfig +++ b/sound/soc/amd/acp/Kconfig @@ -158,6 +158,7 @@ config SND_SOC_AMD_SOF_SDW_MACH select SND_SOC_RT715_SDW select SND_SOC_RT715_SDCA_SDW select SND_SOC_RT722_SDCA_SDW + select SND_SOC_RT766_SDCA_SDW if SND_SOC_SDCA_CLASS help This option enables SOF sound card support for SoundWire enabled AMD platforms along with ACP PDM controller. diff --git a/sound/soc/amd/acp/amd-acp7x-acpi-match.c b/sound/soc/amd/acp/amd-acp7x-acpi-match.c index b71060c9ecb016..a71f8a7929962e 100644 --- a/sound/soc/amd/acp/amd-acp7x-acpi-match.c +++ b/sound/soc/amd/acp/amd-acp7x-acpi-match.c @@ -131,6 +131,42 @@ static const struct snd_soc_acpi_link_adr acp7x_rt722_only[] = { {} }; +static const struct snd_soc_acpi_adr_device rt766_VA0_l0[] = { + { + .adr = 0x000030025d076601ull, + .num_endpoints = ARRAY_SIZE(jack_amp_dmic_endpoints), + .endpoints = jack_amp_dmic_endpoints, + .name_prefix = "rt766" + } +}; + +static const struct snd_soc_acpi_link_adr acp7x_rt766_VA0_l0[] = { + { + .mask = BIT(0), + .num_adr = ARRAY_SIZE(rt766_VA0_l0), + .adr_d = rt766_VA0_l0, + }, + {} +}; + +static const struct snd_soc_acpi_adr_device rt766_VA1_l0[] = { + { + .adr = 0x000040025d076601ull, + .num_endpoints = ARRAY_SIZE(jack_amp_dmic_endpoints), + .endpoints = jack_amp_dmic_endpoints, + .name_prefix = "rt766" + } +}; + +static const struct snd_soc_acpi_link_adr acp7x_rt766_VA1_l0[] = { + { + .mask = BIT(0), + .num_adr = ARRAY_SIZE(rt766_VA1_l0), + .adr_d = rt766_VA1_l0, + }, + {} +}; + static const struct snd_soc_acpi_adr_device rt1320_l1_single_adr[] = { { .adr = 0x000130025d132001ull, @@ -553,6 +589,22 @@ struct snd_soc_acpi_mach snd_soc_acpi_amd_acp7f_sof_sdw_machines[] = { .fw_filename = "sof-acp7f.ri", .get_function_tplg_files = amd_sof_sdw_get_tplg_files, }, + { + .link_mask = BIT(0), + .links = acp7x_rt766_VA0_l0, + .drv_name = "amd_sof_sdw", + .sof_tplg_filename = "sof-acp7f-rt766-l0.tplg", + .fw_filename = "sof-acp7f.ri", + .get_function_tplg_files = amd_sof_sdw_get_tplg_files, + }, + { + .link_mask = BIT(0), + .links = acp7x_rt766_VA1_l0, + .drv_name = "amd_sof_sdw", + .sof_tplg_filename = "sof-acp7f-rt766-l0.tplg", + .fw_filename = "sof-acp7f.ri", + .get_function_tplg_files = amd_sof_sdw_get_tplg_files, + }, { .link_mask = BIT(0) | BIT(1), .links = acp7x_cs42l43_l0u0_cs35l56x4_l1u3210, diff --git a/sound/soc/amd/yc/acp6x-mach.c b/sound/soc/amd/yc/acp6x-mach.c index f636b5ba5b0720..505d481173ce8c 100644 --- a/sound/soc/amd/yc/acp6x-mach.c +++ b/sound/soc/amd/yc/acp6x-mach.c @@ -584,6 +584,21 @@ static const struct dmi_system_id yc_acp_quirk_table[] = { DMI_MATCH(DMI_PRODUCT_NAME, "Crosshair A16 HX D7WFKG"), } }, + { + .driver_data = &acp6x_card, + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "Micro-Star International Co., Ltd."), + DMI_MATCH(DMI_PRODUCT_NAME, "Crosshair A16 HX D8WGKG"), + } + }, + { + .driver_data = &acp6x_card, + .matches = { + DMI_EXACT_MATCH(DMI_BOARD_VENDOR, "Micro-Star International Co., Ltd."), + DMI_EXACT_MATCH(DMI_BOARD_NAME, "MS-184L"), + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Crosshair A18 HX A8WGKG"), + } + }, { .driver_data = &acp6x_card, .matches = { @@ -668,6 +683,13 @@ static const struct dmi_system_id yc_acp_quirk_table[] = { DMI_MATCH(DMI_PRODUCT_NAME, "Swift SFA16-41"), } }, + { + .driver_data = &acp6x_card, + .matches = { + DMI_MATCH(DMI_BOARD_VENDOR, "RB"), + DMI_MATCH(DMI_PRODUCT_NAME, "Nitro AN515-46"), + } + }, { .driver_data = &acp6x_card, .matches = { @@ -731,6 +753,13 @@ static const struct dmi_system_id yc_acp_quirk_table[] = { DMI_MATCH(DMI_BOARD_NAME, "8A22"), } }, + { + .driver_data = &acp6x_card, + .matches = { + DMI_MATCH(DMI_BOARD_VENDOR, "HP"), + DMI_MATCH(DMI_BOARD_NAME, "8D22"), + } + }, { .driver_data = &acp6x_card, .matches = { @@ -955,6 +984,13 @@ static const struct dmi_system_id yc_acp_quirk_table[] = { DMI_MATCH(DMI_BOARD_NAME, "TM2423"), } }, + { + .driver_data = &acp6x_card, + .matches = { + DMI_MATCH(DMI_BOARD_VENDOR, "XIAOMI"), + DMI_MATCH(DMI_BOARD_NAME, "TM2422"), + } + }, { .driver_data = &acp6x_card, .matches = { diff --git a/sound/soc/atmel/atmel-classd.c b/sound/soc/atmel/atmel-classd.c index 746e6bbbf4237b..4216a28d337144 100644 --- a/sound/soc/atmel/atmel-classd.c +++ b/sound/soc/atmel/atmel-classd.c @@ -122,19 +122,10 @@ static int atmel_classd_cpu_dai_startup(struct snd_pcm_substream *substream, { struct snd_soc_pcm_runtime *rtd = snd_soc_substream_to_rtd(substream); struct atmel_classd *dd = snd_soc_card_get_drvdata(rtd->card); - int err; regmap_write(dd->regmap, CLASSD_THR, 0x0); - err = clk_prepare_enable(dd->pclk); - if (err) - return err; - err = clk_prepare_enable(dd->gclk); - if (err) { - clk_disable_unprepare(dd->pclk); - return err; - } - return 0; + return clk_prepare_enable(dd->gclk); } /* platform */ @@ -546,19 +537,15 @@ static int atmel_classd_probe(struct platform_device *pdev) if (dd->irq < 0) return dd->irq; - dd->pclk = devm_clk_get(dev, "pclk"); - if (IS_ERR(dd->pclk)) { - ret = PTR_ERR(dd->pclk); - dev_err(dev, "failed to get peripheral clock: %d\n", ret); - return ret; - } + dd->pclk = devm_clk_get_enabled(dev, "pclk"); + if (IS_ERR(dd->pclk)) + return dev_err_probe(dev, PTR_ERR(dd->pclk), + "failed to get/enable peripheral clock\n"); dd->gclk = devm_clk_get(dev, "gclk"); - if (IS_ERR(dd->gclk)) { - ret = PTR_ERR(dd->gclk); - dev_err(dev, "failed to get GCK clock: %d\n", ret); - return ret; - } + if (IS_ERR(dd->gclk)) + return dev_err_probe(dev, PTR_ERR(dd->gclk), + "failed to get GCK clock\n"); io_base = devm_platform_get_and_ioremap_resource(pdev, 0, &res); if (IS_ERR(io_base)) @@ -569,11 +556,9 @@ static int atmel_classd_probe(struct platform_device *pdev) dd->regmap = devm_regmap_init_mmio(dev, io_base, &atmel_classd_regmap_config); - if (IS_ERR(dd->regmap)) { - ret = PTR_ERR(dd->regmap); - dev_err(dev, "failed to init register map: %d\n", ret); - return ret; - } + if (IS_ERR(dd->regmap)) + return dev_err_probe(dev, PTR_ERR(dd->regmap), + "failed to init register map\n"); ret = devm_snd_soc_register_component(dev, &atmel_classd_cpu_dai_component, @@ -593,29 +578,24 @@ static int atmel_classd_probe(struct platform_device *pdev) /* register sound card */ card = devm_kzalloc_obj(dev, *card); - if (!card) { - ret = -ENOMEM; - goto unregister_codec; - } + if (!card) + return -ENOMEM; snd_soc_card_set_drvdata(card, dd); ret = atmel_classd_asoc_card_init(dev, card); if (ret) { dev_err(dev, "failed to init sound card\n"); - goto unregister_codec; + return ret; } ret = devm_snd_soc_register_card(dev, card); if (ret) { dev_err(dev, "failed to register sound card: %d\n", ret); - goto unregister_codec; + return ret; } return 0; - -unregister_codec: - return ret; } static struct platform_driver atmel_classd_driver = { diff --git a/sound/soc/atmel/mchp-i2s-mcc.c b/sound/soc/atmel/mchp-i2s-mcc.c index cb0f3e55b05d69..6a54d3d67e862c 100644 --- a/sound/soc/atmel/mchp-i2s-mcc.c +++ b/sound/soc/atmel/mchp-i2s-mcc.c @@ -1059,28 +1059,16 @@ static int mchp_i2s_mcc_probe(struct platform_device *pdev) if (irq < 0) return irq; - err = devm_request_irq(&pdev->dev, irq, mchp_i2s_mcc_interrupt, 0, - dev_name(&pdev->dev), dev); - if (err) - return err; - - dev->pclk = devm_clk_get(&pdev->dev, "pclk"); - if (IS_ERR(dev->pclk)) { - err = PTR_ERR(dev->pclk); - dev_err(&pdev->dev, - "failed to get the peripheral clock: %d\n", err); - return err; - } + dev->pclk = devm_clk_get_enabled(&pdev->dev, "pclk"); + if (IS_ERR(dev->pclk)) + return dev_err_probe(&pdev->dev, PTR_ERR(dev->pclk), + "failed to get/enable the peripheral clock\n"); /* Get the optional generated clock */ - dev->gclk = devm_clk_get(&pdev->dev, "gclk"); - if (IS_ERR(dev->gclk)) { - if (PTR_ERR(dev->gclk) == -EPROBE_DEFER) - return -EPROBE_DEFER; - dev_warn(&pdev->dev, - "generated clock not found: %d\n", err); - dev->gclk = NULL; - } + dev->gclk = devm_clk_get_optional(&pdev->dev, "gclk"); + if (IS_ERR(dev->gclk)) + return dev_err_probe(&pdev->dev, PTR_ERR(dev->gclk), + "failed to get the generated clock\n"); dev->soc = of_device_get_match_data(&pdev->dev); err = mchp_i2s_mcc_soc_data_parse(pdev, dev); @@ -1091,19 +1079,16 @@ static int mchp_i2s_mcc_probe(struct platform_device *pdev) dev->regmap = regmap; platform_set_drvdata(pdev, dev); - err = clk_prepare_enable(dev->pclk); - if (err) { - dev_err(&pdev->dev, - "failed to enable the peripheral clock: %d\n", err); + err = devm_request_irq(&pdev->dev, irq, mchp_i2s_mcc_interrupt, 0, + dev_name(&pdev->dev), dev); + if (err) return err; - } err = devm_snd_soc_register_component(&pdev->dev, &mchp_i2s_mcc_component, &mchp_i2s_mcc_dai, 1); if (err) { dev_err(&pdev->dev, "failed to register DAI: %d\n", err); - clk_disable_unprepare(dev->pclk); return err; } @@ -1113,7 +1098,6 @@ static int mchp_i2s_mcc_probe(struct platform_device *pdev) err = devm_snd_dmaengine_pcm_register(&pdev->dev, NULL, 0); if (err) { dev_err(&pdev->dev, "failed to register PCM: %d\n", err); - clk_disable_unprepare(dev->pclk); return err; } @@ -1125,20 +1109,12 @@ static int mchp_i2s_mcc_probe(struct platform_device *pdev) return 0; } -static void mchp_i2s_mcc_remove(struct platform_device *pdev) -{ - struct mchp_i2s_mcc_dev *dev = platform_get_drvdata(pdev); - - clk_disable_unprepare(dev->pclk); -} - static struct platform_driver mchp_i2s_mcc_driver = { .driver = { .name = "mchp_i2s_mcc", .of_match_table = mchp_i2s_mcc_dt_ids, }, .probe = mchp_i2s_mcc_probe, - .remove = mchp_i2s_mcc_remove, }; module_platform_driver(mchp_i2s_mcc_driver); diff --git a/sound/soc/atmel/mchp-pdmc.c b/sound/soc/atmel/mchp-pdmc.c index 039b2eba0d9de5..4b380dc8b6cf05 100644 --- a/sound/soc/atmel/mchp-pdmc.c +++ b/sound/soc/atmel/mchp-pdmc.c @@ -614,6 +614,15 @@ static int mchp_pdmc_hw_params(struct snd_pcm_substream *substream, return 0; } +static int mchp_pdmc_hw_free(struct snd_pcm_substream *substream, + struct snd_soc_dai *dai) +{ + struct mchp_pdmc *dd = snd_soc_dai_get_drvdata(dai); + + atomic_set(&dd->busy_stream, 0); + return 0; +} + static void mchp_pdmc_noise_filter_workaround(struct mchp_pdmc *dd) { u32 tmp, steps = 16; @@ -748,6 +757,7 @@ static const struct snd_soc_dai_ops mchp_pdmc_dai_ops = { .set_fmt = mchp_pdmc_set_fmt, .startup = mchp_pdmc_startup, .hw_params = mchp_pdmc_hw_params, + .hw_free = mchp_pdmc_hw_free, .trigger = mchp_pdmc_trigger, .pcm_new = &mchp_pdmc_pcm_new, .auto_selectable_formats = &mchp_selectable_formats, @@ -832,6 +842,7 @@ static bool mchp_pdmc_volatile_reg(struct device *dev, unsigned int reg) { switch (reg) { case MCHP_PDMC_ISR: + case MCHP_PDMC_IMR: case MCHP_PDMC_RHR: return true; default: @@ -1121,8 +1132,6 @@ static void mchp_pdmc_remove(struct platform_device *pdev) { struct mchp_pdmc *dd = platform_get_drvdata(pdev); - atomic_set(&dd->busy_stream, 0); - if (!pm_runtime_status_suspended(dd->dev)) mchp_pdmc_runtime_suspend(dd->dev); diff --git a/sound/soc/atmel/mchp-spdifrx.c b/sound/soc/atmel/mchp-spdifrx.c index 63089ac3ebdc97..e37470165717d1 100644 --- a/sound/soc/atmel/mchp-spdifrx.c +++ b/sound/soc/atmel/mchp-spdifrx.c @@ -455,7 +455,7 @@ static int mchp_spdifrx_hw_params(struct snd_pcm_substream *substream, } switch (params_format(params)) { - case SNDRV_PCM_FORMAT_S16_BE: + case SNDRV_PCM_FORMAT_U16_BE: case SNDRV_PCM_FORMAT_S20_3BE: case SNDRV_PCM_FORMAT_S24_3BE: case SNDRV_PCM_FORMAT_S24_BE: @@ -502,7 +502,9 @@ static int mchp_spdifrx_hw_params(struct snd_pcm_substream *substream, dev_dbg(dev->dev, "GCLK range min set to %d\n", params_rate(params) * SPDIFRX_GCLK_RATIO_MIN + 1); - ret = regmap_write(dev->regmap, SPDIFRX_MR, mr); + ret = regmap_update_bits(dev->regmap, SPDIFRX_MR, + SPDIFRX_MR_ENDIAN_MASK | SPDIFRX_MR_DATAWIDTH_MASK, + mr); unlock: mutex_unlock(&dev->mlock); @@ -709,7 +711,6 @@ static int mchp_spdifrx_ulock_get(struct snd_kcontrol *kcontrol, struct mchp_spdifrx_mixer_control *ctrl = &dev->control; u32 val; int ret; - bool ulock_old = ctrl->ulock; mutex_lock(&dev->mlock); @@ -735,7 +736,7 @@ static int mchp_spdifrx_ulock_get(struct snd_kcontrol *kcontrol, unlock: mutex_unlock(&dev->mlock); - return ulock_old != ctrl->ulock; + return ret; } static int mchp_spdifrx_badf_get(struct snd_kcontrol *kcontrol, @@ -1079,6 +1080,15 @@ static const struct dev_pm_ops mchp_spdifrx_pm_ops = { NULL) }; +/* Runtime suspend the device on cleanup if necessary */ +static void mchp_spdifrx_runtime_suspend_action(void *data) +{ + struct device *dev = data; + + if (!pm_runtime_status_suspended(dev)) + mchp_spdifrx_runtime_suspend(dev); +} + static int mchp_spdifrx_probe(struct platform_device *pdev) { struct mchp_spdifrx_dev *dev; @@ -1104,33 +1114,22 @@ static int mchp_spdifrx_probe(struct platform_device *pdev) if (IS_ERR(regmap)) return PTR_ERR(regmap); - /* Request IRQ. */ + /* Get IRQ. */ irq = platform_get_irq(pdev, 0); if (irq < 0) return irq; - err = devm_request_irq(&pdev->dev, irq, mchp_spdif_interrupt, 0, - dev_name(&pdev->dev), dev); - if (err) - return err; - /* Get the peripheral clock */ dev->pclk = devm_clk_get(&pdev->dev, "pclk"); - if (IS_ERR(dev->pclk)) { - err = PTR_ERR(dev->pclk); - dev_err(&pdev->dev, "failed to get the peripheral clock: %d\n", - err); - return err; - } + if (IS_ERR(dev->pclk)) + return dev_err_probe(&pdev->dev, PTR_ERR(dev->pclk), + "failed to get the peripheral clock\n"); /* Get the generated clock */ dev->gclk = devm_clk_get(&pdev->dev, "gclk"); - if (IS_ERR(dev->gclk)) { - err = PTR_ERR(dev->gclk); - dev_err(&pdev->dev, - "failed to get the PMC generated clock: %d\n", err); - return err; - } + if (IS_ERR(dev->gclk)) + return dev_err_probe(&pdev->dev, PTR_ERR(dev->gclk), + "failed to get the PMC generated clock\n"); /* * Signal control need a valid rate on gclk. hw_params() configures @@ -1147,20 +1146,37 @@ static int mchp_spdifrx_probe(struct platform_device *pdev) dev->regmap = regmap; platform_set_drvdata(pdev, dev); - pm_runtime_enable(dev->dev); + err = devm_add_action(dev->dev, mchp_spdifrx_runtime_suspend_action, + dev->dev); + if (err) + return err; + + err = devm_pm_runtime_enable(dev->dev); + if (err) + return err; if (!pm_runtime_enabled(dev->dev)) { err = mchp_spdifrx_runtime_resume(dev->dev); - if (err) - goto pm_runtime_disable; + if (err) { + devm_remove_action(dev->dev, + mchp_spdifrx_runtime_suspend_action, + dev->dev); + return err; + } } + /* Request IRQ. */ + err = devm_request_irq(&pdev->dev, irq, mchp_spdif_interrupt, 0, + dev_name(&pdev->dev), dev); + if (err) + return err; + dev->capture.addr = (dma_addr_t)mem->start + SPDIFRX_RHR; dev->capture.maxburst = 1; err = devm_snd_dmaengine_pcm_register(&pdev->dev, NULL, 0); if (err) { dev_err(&pdev->dev, "failed to register PCM: %d\n", err); - goto pm_runtime_suspend; + return err; } err = devm_snd_soc_register_component(&pdev->dev, @@ -1168,34 +1184,17 @@ static int mchp_spdifrx_probe(struct platform_device *pdev) &mchp_spdifrx_dai, 1); if (err) { dev_err(&pdev->dev, "fail to register dai\n"); - goto pm_runtime_suspend; + return err; } regmap_read(regmap, SPDIFRX_VERSION, &vers); dev_info(&pdev->dev, "hw version: %#lx\n", vers & SPDIFRX_VERSION_MASK); return 0; - -pm_runtime_suspend: - if (!pm_runtime_status_suspended(dev->dev)) - mchp_spdifrx_runtime_suspend(dev->dev); -pm_runtime_disable: - pm_runtime_disable(dev->dev); - return err; -} - -static void mchp_spdifrx_remove(struct platform_device *pdev) -{ - struct mchp_spdifrx_dev *dev = platform_get_drvdata(pdev); - - pm_runtime_disable(dev->dev); - if (!pm_runtime_status_suspended(dev->dev)) - mchp_spdifrx_runtime_suspend(dev->dev); } static struct platform_driver mchp_spdifrx_driver = { .probe = mchp_spdifrx_probe, - .remove = mchp_spdifrx_remove, .driver = { .name = "mchp_spdifrx", .of_match_table = mchp_spdifrx_dt_ids, diff --git a/sound/soc/atmel/mchp-spdiftx.c b/sound/soc/atmel/mchp-spdiftx.c index fc635ed6856e15..0406a11caf7d52 100644 --- a/sound/soc/atmel/mchp-spdiftx.c +++ b/sound/soc/atmel/mchp-spdiftx.c @@ -165,6 +165,17 @@ static bool mchp_spdiftx_precious_reg(struct device *dev, unsigned int reg) } } +static bool mchp_spdiftx_volatile_reg(struct device *dev, unsigned int reg) +{ + switch (reg) { + case SPDIFTX_IMR: + case SPDIFTX_ISR: + return true; + default: + return false; + } +} + static const struct regmap_config mchp_spdiftx_regmap_config = { .reg_bits = 32, .reg_stride = 4, @@ -173,6 +184,7 @@ static const struct regmap_config mchp_spdiftx_regmap_config = { .readable_reg = mchp_spdiftx_readable_reg, .writeable_reg = mchp_spdiftx_writeable_reg, .precious_reg = mchp_spdiftx_precious_reg, + .volatile_reg = mchp_spdiftx_volatile_reg, .cache_type = REGCACHE_FLAT, }; @@ -778,6 +790,15 @@ static const struct dev_pm_ops mchp_spdiftx_pm_ops = { NULL) }; +/* Runtime suspend the device on cleanup if necessary */ +static void mchp_spdiftx_runtime_suspend_action(void *data) +{ + struct device *dev = data; + + if (!pm_runtime_status_suspended(dev)) + mchp_spdiftx_runtime_suspend(dev); +} + static int mchp_spdiftx_probe(struct platform_device *pdev) { struct mchp_spdiftx_dev *dev; @@ -803,33 +824,22 @@ static int mchp_spdiftx_probe(struct platform_device *pdev) if (IS_ERR(regmap)) return PTR_ERR(regmap); - /* Request IRQ */ + /* Get IRQ */ irq = platform_get_irq(pdev, 0); if (irq < 0) return irq; - err = devm_request_irq(&pdev->dev, irq, mchp_spdiftx_interrupt, 0, - dev_name(&pdev->dev), dev); - if (err) - return err; - /* Get the peripheral clock */ dev->pclk = devm_clk_get(&pdev->dev, "pclk"); - if (IS_ERR(dev->pclk)) { - err = PTR_ERR(dev->pclk); - dev_err(&pdev->dev, - "failed to get the peripheral clock: %d\n", err); - return err; - } + if (IS_ERR(dev->pclk)) + return dev_err_probe(&pdev->dev, PTR_ERR(dev->pclk), + "failed to get the peripheral clock\n"); /* Get the generic clock */ dev->gclk = devm_clk_get(&pdev->dev, "gclk"); - if (IS_ERR(dev->gclk)) { - err = PTR_ERR(dev->gclk); - dev_err(&pdev->dev, - "failed to get the PMC generic clock: %d\n", err); - return err; - } + if (IS_ERR(dev->gclk)) + return dev_err_probe(&pdev->dev, PTR_ERR(dev->gclk), + "failed to get the PMC generic clock\n"); ctrl = &dev->control; spin_lock_init(&ctrl->lock); @@ -842,20 +852,37 @@ static int mchp_spdiftx_probe(struct platform_device *pdev) dev->regmap = regmap; platform_set_drvdata(pdev, dev); - pm_runtime_enable(dev->dev); + err = devm_add_action(dev->dev, mchp_spdiftx_runtime_suspend_action, + dev->dev); + if (err) + return err; + + err = devm_pm_runtime_enable(dev->dev); + if (err) + return err; if (!pm_runtime_enabled(dev->dev)) { err = mchp_spdiftx_runtime_resume(dev->dev); - if (err) + if (err) { + devm_remove_action(dev->dev, + mchp_spdiftx_runtime_suspend_action, + dev->dev); return err; + } } + /* Request IRQ */ + err = devm_request_irq(&pdev->dev, irq, mchp_spdiftx_interrupt, 0, + dev_name(&pdev->dev), dev); + if (err) + return err; + dev->playback.addr = (dma_addr_t)mem->start + SPDIFTX_CDR; dev->playback.addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES; err = devm_snd_dmaengine_pcm_register(&pdev->dev, NULL, 0); if (err) { dev_err(&pdev->dev, "failed to register PMC: %d\n", err); - goto pm_runtime_suspend; + return err; } err = devm_snd_soc_register_component(&pdev->dev, @@ -863,32 +890,14 @@ static int mchp_spdiftx_probe(struct platform_device *pdev) &mchp_spdiftx_dai, 1); if (err) { dev_err(&pdev->dev, "failed to register component: %d\n", err); - goto pm_runtime_suspend; + return err; } return 0; - -pm_runtime_suspend: - if (!pm_runtime_status_suspended(dev->dev)) - mchp_spdiftx_runtime_suspend(dev->dev); - pm_runtime_disable(dev->dev); - - return err; -} - -static void mchp_spdiftx_remove(struct platform_device *pdev) -{ - struct mchp_spdiftx_dev *dev = platform_get_drvdata(pdev); - - if (!pm_runtime_status_suspended(dev->dev)) - mchp_spdiftx_runtime_suspend(dev->dev); - - pm_runtime_disable(dev->dev); } static struct platform_driver mchp_spdiftx_driver = { .probe = mchp_spdiftx_probe, - .remove = mchp_spdiftx_remove, .driver = { .name = "mchp_spdiftx", .of_match_table = mchp_spdiftx_dt_ids, diff --git a/sound/soc/cirrus/ep93xx-i2s.c b/sound/soc/cirrus/ep93xx-i2s.c index 97816fb7536804..f2d55763a02d36 100644 --- a/sound/soc/cirrus/ep93xx-i2s.c +++ b/sound/soc/cirrus/ep93xx-i2s.c @@ -462,8 +462,8 @@ static int ep93xx_i2s_probe(struct platform_device *pdev) if (IS_ENABLED(CONFIG_SND_EP93XX_SOC_I2S_WATCHDOG)) { int irq = platform_get_irq(pdev, 0); - if (irq <= 0) - return irq < 0 ? irq : -ENODEV; + if (irq < 0) + return irq; err = devm_request_irq(&pdev->dev, irq, ep93xx_i2s_interrupt, 0, pdev->name, info); @@ -471,54 +471,30 @@ static int ep93xx_i2s_probe(struct platform_device *pdev) return err; } - info->mclk = clk_get(&pdev->dev, "mclk"); - if (IS_ERR(info->mclk)) { - err = PTR_ERR(info->mclk); - goto fail; - } + info->mclk = devm_clk_get(&pdev->dev, "mclk"); + if (IS_ERR(info->mclk)) + return PTR_ERR(info->mclk); - info->sclk = clk_get(&pdev->dev, "sclk"); - if (IS_ERR(info->sclk)) { - err = PTR_ERR(info->sclk); - goto fail_put_mclk; - } + info->sclk = devm_clk_get(&pdev->dev, "sclk"); + if (IS_ERR(info->sclk)) + return PTR_ERR(info->sclk); - info->lrclk = clk_get(&pdev->dev, "lrclk"); - if (IS_ERR(info->lrclk)) { - err = PTR_ERR(info->lrclk); - goto fail_put_sclk; - } + info->lrclk = devm_clk_get(&pdev->dev, "lrclk"); + if (IS_ERR(info->lrclk)) + return PTR_ERR(info->lrclk); dev_set_drvdata(&pdev->dev, info); err = devm_snd_soc_register_component(&pdev->dev, &ep93xx_i2s_component, &ep93xx_i2s_dai, 1); if (err) - goto fail_put_lrclk; + return err; err = devm_ep93xx_pcm_platform_register(&pdev->dev); if (err) - goto fail_put_lrclk; + return err; return 0; - -fail_put_lrclk: - clk_put(info->lrclk); -fail_put_sclk: - clk_put(info->sclk); -fail_put_mclk: - clk_put(info->mclk); -fail: - return err; -} - -static void ep93xx_i2s_remove(struct platform_device *pdev) -{ - struct ep93xx_i2s_info *info = dev_get_drvdata(&pdev->dev); - - clk_put(info->lrclk); - clk_put(info->sclk); - clk_put(info->mclk); } static const struct of_device_id ep93xx_i2s_of_ids[] = { @@ -529,7 +505,6 @@ MODULE_DEVICE_TABLE(of, ep93xx_i2s_of_ids); static struct platform_driver ep93xx_i2s_driver = { .probe = ep93xx_i2s_probe, - .remove = ep93xx_i2s_remove, .driver = { .name = "ep93xx-i2s", .of_match_table = ep93xx_i2s_of_ids, diff --git a/sound/soc/codecs/Kconfig b/sound/soc/codecs/Kconfig index 6239de3afa5a47..169427d43898fb 100644 --- a/sound/soc/codecs/Kconfig +++ b/sound/soc/codecs/Kconfig @@ -145,6 +145,7 @@ config SND_SOC_ALL_CODECS imply SND_SOC_LM4857 imply SND_SOC_LM49453 imply SND_SOC_LOCHNAGAR_SC + imply SND_SOC_MA5311 imply SND_SOC_MAX98088 imply SND_SOC_MAX98090 imply SND_SOC_MAX98095 @@ -275,6 +276,7 @@ config SND_SOC_ALL_CODECS imply SND_SOC_STI_SAS imply SND_SOC_TAC5XX2_SDW imply SND_SOC_TAS2552 + imply SND_SOC_TAS2557 imply SND_SOC_TAS2562 imply SND_SOC_TAS2764 imply SND_SOC_TAS2770 @@ -909,16 +911,12 @@ config SND_SOC_CS35L56_SDW help Enable support for Cirrus Logic CS35L56 boosted amplifier with SoundWire control -config SND_SOC_CS35L56_CAL_DEBUGFS_COMMON - bool - menu "CS35L56 driver options" depends on SND_SOC_CS35L56 config SND_SOC_CS35L56_CAL_DEBUGFS bool "CS35L56 create debugfs for factory calibration" depends on DEBUG_FS - select SND_SOC_CS35L56_CAL_DEBUGFS_COMMON help Create debugfs entries used during factory-line manufacture for factory calibration. @@ -927,7 +925,6 @@ config SND_SOC_CS35L56_CAL_DEBUGFS config SND_SOC_CS35L56_CAL_SET_CTRL bool "CS35L56 ALSA control to restore factory calibration" - select SND_SOC_CS35L56_CAL_DEBUGFS_COMMON help Allow restoring factory calibration data through an ALSA control. This is only needed on platforms without UEFI or @@ -940,7 +937,6 @@ config SND_SOC_CS35L56_CAL_SET_CTRL config SND_SOC_CS35L56_CAL_PERFORM_CTRL bool "CS35L56 ALSA control to perform factory calibration" - select SND_SOC_CS35L56_CAL_DEBUGFS_COMMON help Allow performing factory calibration data through an ALSA control. It is recommended to use the debugfs method instead @@ -1448,6 +1444,17 @@ config SND_SOC_LOCHNAGAR_SC This driver support the sound card functionality of the Cirrus Logic Lochnagar audio development board. +config SND_SOC_MA5311 + tristate "Iron Device MA5311 Audio Codec" + depends on I2C && GPIOLIB + select REGMAP_I2C + help + Enable support for the Iron Device MA5311 audio codec with + playback and capture over an I2S/TDM interface. + + To compile this driver as a module, choose M here: the module + will be called snd-soc-ma5311. + config SND_SOC_MADERA tristate select SND_SOC_WM_ADSP @@ -2237,6 +2244,18 @@ config SND_SOC_TAS2552 tristate "Texas Instruments TAS2552 Mono Audio amplifier" depends on I2C +config SND_SOC_TAS2557 + tristate "Texas Instruments TAS2557 Mono Smart Amplifier" + depends on I2C + select SND_SOC_TAS2781_COMLIB + select SND_SOC_TAS2781_COMLIB_I2C + help + Enable support for the Texas Instruments TAS2557 mono smart + amplifier with integrated DSP. The on-chip DSP requires firmware + (tas2557_uCDSP.bin) to be present in the firmware search path; + audio cannot pass through the device without it. Uses the + tas2781-comlib(-i2c) helpers for paged register access. + config SND_SOC_TAS2562 tristate "Texas Instruments TAS2562 Mono Audio amplifier" depends on I2C diff --git a/sound/soc/codecs/Makefile b/sound/soc/codecs/Makefile index 459a2aa463f3dc..6d865448428f98 100644 --- a/sound/soc/codecs/Makefile +++ b/sound/soc/codecs/Makefile @@ -167,6 +167,7 @@ snd-soc-lpass-rx-macro-y := lpass-rx-macro.o snd-soc-lpass-tx-macro-y := lpass-tx-macro.o snd-soc-lpass-wsa-macro-y := lpass-wsa-macro.o snd-soc-lpass-va-macro-y := lpass-va-macro.o +snd-soc-ma5311-y := ma5311.o snd-soc-madera-y := madera.o snd-soc-max9759-y := max9759.o snd-soc-max9768-y := max9768.o @@ -444,6 +445,7 @@ snd-soc-max98504-y := max98504.o snd-soc-simple-amplifier-y := simple-amplifier.o snd-soc-tpa6130a2-y := tpa6130a2.o snd-soc-tas2552-y := tas2552.o +snd-soc-tas2557-y := tas2557.o snd-soc-tas2562-y := tas2562.o snd-soc-tas2764-y := tas2764.o snd-soc-tas2780-y := tas2780.o @@ -614,6 +616,7 @@ obj-$(CONFIG_SND_SOC_JZ4770_CODEC) += snd-soc-jz4770-codec.o obj-$(CONFIG_SND_SOC_LM4857) += snd-soc-lm4857.o obj-$(CONFIG_SND_SOC_LM49453) += snd-soc-lm49453.o obj-$(CONFIG_SND_SOC_LOCHNAGAR_SC) += snd-soc-lochnagar-sc.o +obj-$(CONFIG_SND_SOC_MA5311) += snd-soc-ma5311.o obj-$(CONFIG_SND_SOC_MADERA) += snd-soc-madera.o obj-$(CONFIG_SND_SOC_MAX9759) += snd-soc-max9759.o obj-$(CONFIG_SND_SOC_MAX9768) += snd-soc-max9768.o @@ -773,6 +776,7 @@ obj-$(CONFIG_SND_SOC_STAC9766) += snd-soc-stac9766.o obj-$(CONFIG_SND_SOC_STI_SAS) += snd-soc-sti-sas.o obj-$(CONFIG_SND_SOC_TAC5XX2_SDW) += snd-soc-tac5xx2-sdw.o obj-$(CONFIG_SND_SOC_TAS2552) += snd-soc-tas2552.o +obj-$(CONFIG_SND_SOC_TAS2557) += snd-soc-tas2557.o obj-$(CONFIG_SND_SOC_TAS2562) += snd-soc-tas2562.o obj-$(CONFIG_SND_SOC_TAS2764) += snd-soc-tas2764.o obj-$(CONFIG_SND_SOC_TAS2780) += snd-soc-tas2780.o diff --git a/sound/soc/codecs/ak4535.c b/sound/soc/codecs/ak4535.c index 66ca753e765174..ce877d99569069 100644 --- a/sound/soc/codecs/ak4535.c +++ b/sound/soc/codecs/ak4535.c @@ -237,12 +237,12 @@ static const struct snd_soc_dapm_route ak4535_audio_map[] = { {"Mono 2 Enable", "Switch", "Stereo Mixer"}, /* Aux In */ - {"Aux In", NULL, "AUX"}, + {"AUX In", NULL, "AUX"}, /* ADC */ {"ADC", NULL, "Input Mixer"}, {"Input Mixer", "Mic Capture Switch", "Mic"}, - {"Input Mixer", "Aux Capture Switch", "Aux In"}, + {"Input Mixer", "Aux Capture Switch", "AUX In"}, }; static int ak4535_set_dai_sysclk(struct snd_soc_dai *codec_dai, diff --git a/sound/soc/codecs/arizona-jack.c b/sound/soc/codecs/arizona-jack.c index db60ea1aaec8a6..6f2286eb7cbe1f 100644 --- a/sound/soc/codecs/arizona-jack.c +++ b/sound/soc/codecs/arizona-jack.c @@ -45,7 +45,6 @@ #define ARIZONA_HPDET_MAX 10000 -#define HPDET_DEBOUNCE 500 #define DEFAULT_MICD_TIMEOUT 2000 #define ARIZONA_HPDET_WAIT_COUNT 15 @@ -92,8 +91,6 @@ static const int arizona_micd_levels[] = { 1257, 30000, }; -static void arizona_start_hpdet_acc_id(struct arizona_priv *info); - static void arizona_extcon_hp_clamp(struct arizona_priv *info, bool clamp) { @@ -426,7 +423,7 @@ static int arizona_hpdet_read(struct arizona_priv *info) /* Skip up a range, or report? */ if (range < ARRAY_SIZE(arizona_hpdet_c_ranges) - 1 && - (val >= arizona_hpdet_c_ranges[range].max)) { + val >= arizona_hpdet_c_ranges[range].max) { range++; dev_dbg(arizona->dev, "Moving to HPDET range %d-%d\n", arizona_hpdet_c_ranges[range].min, @@ -439,7 +436,7 @@ static int arizona_hpdet_read(struct arizona_priv *info) return -EAGAIN; } - if (range && (val < arizona_hpdet_c_ranges[range].min)) { + if (range && val < arizona_hpdet_c_ranges[range].min) { dev_dbg(arizona->dev, "Reporting range boundary %d\n", arizona_hpdet_c_ranges[range].min); val = arizona_hpdet_c_ranges[range].min; @@ -455,79 +452,11 @@ static int arizona_hpdet_read(struct arizona_priv *info) return val; } -static int arizona_hpdet_do_id(struct arizona_priv *info, int *reading, - bool *mic) -{ - struct arizona *arizona = info->arizona; - - if (!arizona->pdata.hpdet_acc_id) - return 0; - - /* - * If we're using HPDET for accessory identification we need - * to take multiple measurements, step through them in sequence. - */ - info->hpdet_res[info->num_hpdet_res++] = *reading; - - /* Only check the mic directly if we didn't already ID it */ - if (info->hpdet_id_gpio && info->num_hpdet_res == 1) { - dev_dbg(arizona->dev, "Measuring mic\n"); - - regmap_update_bits(arizona->regmap, - ARIZONA_ACCESSORY_DETECT_MODE_1, - ARIZONA_ACCDET_MODE_MASK | - ARIZONA_ACCDET_SRC, - ARIZONA_ACCDET_MODE_HPR | - info->micd_modes[0].src); - - gpiod_set_value_cansleep(info->hpdet_id_gpio, 1); - - regmap_update_bits(arizona->regmap, ARIZONA_HEADPHONE_DETECT_1, - ARIZONA_HP_POLL, ARIZONA_HP_POLL); - return -EAGAIN; - } - - /* OK, got both. Now, compare... */ - dev_dbg(arizona->dev, "HPDET measured %d %d\n", - info->hpdet_res[0], info->hpdet_res[1]); - - /* Take the headphone impedance for the main report */ - *reading = info->hpdet_res[0]; - - /* Sometimes we get false readings due to slow insert */ - if (*reading >= ARIZONA_HPDET_MAX && !info->hpdet_retried) { - dev_dbg(arizona->dev, "Retrying high impedance\n"); - info->num_hpdet_res = 0; - info->hpdet_retried = true; - arizona_start_hpdet_acc_id(info); - pm_runtime_put(arizona->dev); - return -EAGAIN; - } - - /* - * If we measure the mic as high impedance - */ - if (!info->hpdet_id_gpio || info->hpdet_res[1] > 50) { - dev_dbg(arizona->dev, "Detected mic\n"); - *mic = true; - info->detecting = true; - } else { - dev_dbg(arizona->dev, "Detected headphone\n"); - } - - /* Make sure everything is reset back to the real polarity */ - regmap_update_bits(arizona->regmap, ARIZONA_ACCESSORY_DETECT_MODE_1, - ARIZONA_ACCDET_SRC, info->micd_modes[0].src); - - return 0; -} - static irqreturn_t arizona_hpdet_irq(int irq, void *data) { struct arizona_priv *info = data; struct arizona *arizona = info->arizona; int ret, reading, state, report; - bool mic = false; mutex_lock(&info->lock); @@ -552,18 +481,6 @@ static irqreturn_t arizona_hpdet_irq(int irq, void *data) goto done; reading = ret; - /* Reset back to starting range */ - regmap_update_bits(arizona->regmap, - ARIZONA_HEADPHONE_DETECT_1, - ARIZONA_HP_IMPEDANCE_RANGE_MASK | ARIZONA_HP_POLL, - 0); - - ret = arizona_hpdet_do_id(info, &reading, &mic); - if (ret == -EAGAIN) - goto out; - else if (ret < 0) - goto done; - /* Report high impedence cables as line outputs */ if (reading >= 5000) report = SND_JACK_LINEOUT; @@ -581,11 +498,8 @@ static irqreturn_t arizona_hpdet_irq(int irq, void *data) arizona_extcon_hp_clamp(info, false); - if (info->hpdet_id_gpio) - gpiod_set_value_cansleep(info->hpdet_id_gpio, 0); - /* If we have a mic then reenable MICDET */ - if (state && (mic || info->mic)) + if (state && info->mic) arizona_start_mic(info); if (info->hpdet_active) { @@ -654,55 +568,6 @@ static void arizona_identify_headphone(struct arizona_priv *info) info->hpdet_active = false; } -static void arizona_start_hpdet_acc_id(struct arizona_priv *info) -{ - struct arizona *arizona = info->arizona; - int hp_reading = 32; - bool mic; - int ret; - - dev_dbg(arizona->dev, "Starting identification via HPDET\n"); - - /* Make sure we keep the device enabled during the measurement */ - pm_runtime_get_sync(arizona->dev); - - info->hpdet_active = true; - - arizona_extcon_hp_clamp(info, true); - - ret = regmap_update_bits(arizona->regmap, - ARIZONA_ACCESSORY_DETECT_MODE_1, - ARIZONA_ACCDET_SRC | ARIZONA_ACCDET_MODE_MASK, - info->micd_modes[0].src | - arizona->pdata.hpdet_channel); - if (ret != 0) { - dev_err(arizona->dev, "Failed to set HPDET mode: %d\n", ret); - goto err; - } - - if (arizona->pdata.hpdet_acc_id_line) { - ret = regmap_update_bits(arizona->regmap, - ARIZONA_HEADPHONE_DETECT_1, - ARIZONA_HP_POLL, ARIZONA_HP_POLL); - if (ret) { - dev_err(arizona->dev, "Can't start HPDETL measurement: %d\n", ret); - goto err; - } - } else { - arizona_hpdet_do_id(info, &hp_reading, &mic); - } - - return; - -err: - /* Just report headphone */ - snd_soc_jack_report(info->jack, SND_JACK_HEADPHONE, - SND_JACK_LINEOUT | SND_JACK_HEADPHONE); - - pm_runtime_put_autosuspend(arizona->dev); - info->hpdet_active = false; -} - static void arizona_micd_timeout_work(struct work_struct *work) { struct arizona_priv *info = container_of(work, @@ -961,16 +826,6 @@ static irqreturn_t arizona_micdet(int irq, void *data) return IRQ_HANDLED; } -static void arizona_hpdet_work(struct work_struct *work) -{ - struct arizona_priv *info = container_of(work, - struct arizona_priv, - hpdet_work.work); - - guard(mutex)(&info->lock); - arizona_start_hpdet_acc_id(info); -} - static int arizona_hpdet_wait(struct arizona_priv *info) { struct arizona *arizona = info->arizona; @@ -978,8 +833,7 @@ static int arizona_hpdet_wait(struct arizona_priv *info) int i, ret; for (i = 0; i < ARIZONA_HPDET_WAIT_COUNT; i++) { - ret = regmap_read(arizona->regmap, ARIZONA_HEADPHONE_DETECT_2, - &val); + ret = regmap_read(arizona->regmap, ARIZONA_HEADPHONE_DETECT_2, &val); if (ret) { dev_err(arizona->dev, "Failed to read HPDET state: %d\n", ret); return ret; @@ -1009,10 +863,9 @@ static irqreturn_t arizona_jackdet(int irq, void *data) struct arizona_priv *info = data; struct arizona *arizona = info->arizona; unsigned int val, present, mask; - bool cancelled_hp, cancelled_mic; - int ret, i; + bool cancelled_mic; + int ret; - cancelled_hp = cancel_delayed_work_sync(&info->hpdet_work); cancelled_mic = cancel_delayed_work_sync(&info->micd_timeout_work); guard(pm_runtime_active_auto)(arizona->dev); @@ -1039,11 +892,6 @@ static irqreturn_t arizona_jackdet(int irq, void *data) val &= mask; if (val == info->last_jackdet) { dev_dbg(arizona->dev, "Suppressing duplicate JACKDET\n"); - if (cancelled_hp) - queue_delayed_work(system_power_efficient_wq, - &info->hpdet_work, - msecs_to_jiffies(HPDET_DEBOUNCE)); - if (cancelled_mic) { int micd_timeout = arizona->pdata.micd_timeout; @@ -1062,13 +910,7 @@ static irqreturn_t arizona_jackdet(int irq, void *data) info->mic = false; info->jack_flips = 0; - if (!arizona->pdata.hpdet_acc_id) { - arizona_start_mic(info); - } else { - queue_delayed_work(system_power_efficient_wq, - &info->hpdet_work, - msecs_to_jiffies(HPDET_DEBOUNCE)); - } + arizona_start_mic(info); if (info->micd_clamp || !arizona->pdata.jd_invert) regmap_update_bits(arizona->regmap, @@ -1080,12 +922,8 @@ static irqreturn_t arizona_jackdet(int irq, void *data) arizona_stop_mic(info); - info->num_hpdet_res = 0; - for (i = 0; i < ARRAY_SIZE(info->hpdet_res); i++) - info->hpdet_res[i] = 0; info->mic = false; info->hpdet_done = false; - info->hpdet_retried = false; snd_soc_jack_report(info->jack, 0, ARIZONA_JACK_MASK | info->micd_button_mask); @@ -1183,18 +1021,20 @@ static int arizona_extcon_device_get_pdata(struct device *dev, struct arizona *arizona) { struct arizona_pdata *pdata = &arizona->pdata; - unsigned int val = ARIZONA_ACCDET_MODE_HPL; + unsigned int val; int ret; - device_property_read_u32(arizona->dev, "wlf,hpdet-channel", &val); - switch (val) { - case ARIZONA_ACCDET_MODE_HPL: - case ARIZONA_ACCDET_MODE_HPR: - pdata->hpdet_channel = val; - break; - default: - dev_err(arizona->dev, "Wrong wlf,hpdet-channel DT value %d\n", val); - pdata->hpdet_channel = ARIZONA_ACCDET_MODE_HPL; + if (!device_property_read_u32(arizona->dev, "wlf,hpdet-channel", &val)) { + switch (val) { + case ARIZONA_ACCDET_MODE_HPL: + case ARIZONA_ACCDET_MODE_HPR: + pdata->hpdet_channel = val; + break; + default: + dev_err(arizona->dev, + "Wrong wlf,hpdet-channel DT value %d\n", val); + break; + } } device_property_read_u32(arizona->dev, "wlf,micd-detect-debounce", @@ -1212,21 +1052,23 @@ static int arizona_extcon_device_get_pdata(struct device *dev, device_property_read_u32(arizona->dev, "wlf,micd-timeout-ms", &pdata->micd_timeout); - pdata->micd_force_micbias = device_property_read_bool(arizona->dev, - "wlf,micd-force-micbias"); + pdata->micd_force_micbias |= + device_property_read_bool(arizona->dev, + "wlf,micd-force-micbias"); - pdata->micd_software_compare = device_property_read_bool(arizona->dev, - "wlf,micd-software-compare"); + pdata->micd_software_compare |= + device_property_read_bool(arizona->dev, + "wlf,micd-software-compare"); - pdata->jd_invert = device_property_read_bool(arizona->dev, - "wlf,jd-invert"); + pdata->jd_invert |= device_property_read_bool(arizona->dev, + "wlf,jd-invert"); device_property_read_u32(arizona->dev, "wlf,gpsw", &pdata->gpsw); - pdata->jd_gpio5 = device_property_read_bool(arizona->dev, - "wlf,use-jd2"); - pdata->jd_gpio5_nopull = device_property_read_bool(arizona->dev, - "wlf,use-jd2-nopull"); + pdata->jd_gpio5 |= device_property_read_bool(arizona->dev, + "wlf,use-jd2"); + pdata->jd_gpio5_nopull |= + device_property_read_bool(arizona->dev, "wlf,use-jd2-nopull"); ret = arizona_extcon_get_micd_configs(dev, arizona); if (ret < 0) @@ -1241,8 +1083,7 @@ int arizona_jack_codec_dev_probe(struct arizona_priv *info, struct device *dev) struct arizona_pdata *pdata = &arizona->pdata; int ret, mode; - if (!dev_get_platdata(arizona->dev)) - arizona_extcon_device_get_pdata(dev, arizona); + arizona_extcon_device_get_pdata(dev, arizona); info->micvdd = devm_regulator_get(dev, "MICVDD"); if (IS_ERR(info->micvdd)) @@ -1250,7 +1091,6 @@ int arizona_jack_codec_dev_probe(struct arizona_priv *info, struct device *dev) mutex_init(&info->lock); info->last_jackdet = ~(ARIZONA_MICD_CLAMP_STS | ARIZONA_JD1_STS); - INIT_DELAYED_WORK(&info->hpdet_work, arizona_hpdet_work); INIT_DELAYED_WORK(&info->micd_detect_work, arizona_micd_detect); INIT_DELAYED_WORK(&info->micd_timeout_work, arizona_micd_timeout_work); @@ -1286,6 +1126,9 @@ int arizona_jack_codec_dev_probe(struct arizona_priv *info, struct device *dev) break; } + if (!pdata->hpdet_channel) + pdata->hpdet_channel = ARIZONA_ACCDET_MODE_HPL; + if (!pdata->micd_timeout) pdata->micd_timeout = DEFAULT_MICD_TIMEOUT; @@ -1299,7 +1142,7 @@ int arizona_jack_codec_dev_probe(struct arizona_priv *info, struct device *dev) if (arizona->pdata.gpsw > 0) regmap_update_bits(arizona->regmap, ARIZONA_GP_SWITCH_1, - ARIZONA_SW1_MODE_MASK, arizona->pdata.gpsw); + ARIZONA_SW1_MODE_MASK, arizona->pdata.gpsw); if (info->micd_modes[0].gpio) mode = GPIOD_OUT_HIGH; @@ -1311,24 +1154,13 @@ int arizona_jack_codec_dev_probe(struct arizona_priv *info, struct device *dev) * will reside, but if we devm against that the GPIO * will not be freed if the extcon driver is unloaded. */ - info->micd_pol_gpio = gpiod_get_optional(arizona->dev, - "wlf,micd-pol", - mode); + info->micd_pol_gpio = gpiod_get_optional(arizona->dev, "wlf,micd-pol", mode); if (IS_ERR(info->micd_pol_gpio)) { ret = PTR_ERR(info->micd_pol_gpio); dev_err_probe(arizona->dev, ret, "getting microphone polarity GPIO\n"); return ret; } - info->hpdet_id_gpio = gpiod_get_optional(arizona->dev, - "wlf,hpdet-id-gpio", - mode); - if (IS_ERR(info->hpdet_id_gpio)) { - ret = PTR_ERR(info->hpdet_id_gpio); - dev_err_probe(arizona->dev, ret, "getting headphone detect ID GPIO\n"); - return ret; - } - return 0; } EXPORT_SYMBOL_GPL(arizona_jack_codec_dev_probe); @@ -1336,7 +1168,6 @@ EXPORT_SYMBOL_GPL(arizona_jack_codec_dev_probe); int arizona_jack_codec_dev_remove(struct arizona_priv *info) { gpiod_put(info->micd_pol_gpio); - gpiod_put(info->hpdet_id_gpio); return 0; } EXPORT_SYMBOL_GPL(arizona_jack_codec_dev_remove); @@ -1355,13 +1186,13 @@ static int arizona_jack_enable_jack_detect(struct arizona_priv *info, regmap_update_bits(arizona->regmap, ARIZONA_MIC_DETECT_1, ARIZONA_MICD_BIAS_STARTTIME_MASK, arizona->pdata.micd_bias_start_time - << ARIZONA_MICD_BIAS_STARTTIME_SHIFT); + << ARIZONA_MICD_BIAS_STARTTIME_SHIFT); if (arizona->pdata.micd_rate) regmap_update_bits(arizona->regmap, ARIZONA_MIC_DETECT_1, ARIZONA_MICD_RATE_MASK, arizona->pdata.micd_rate - << ARIZONA_MICD_RATE_SHIFT); + << ARIZONA_MICD_RATE_SHIFT); switch (arizona->pdata.micd_dbtime) { case MICD_DBTIME_FOUR_READINGS: @@ -1582,7 +1413,6 @@ static int arizona_jack_disable_jack_detect(struct arizona_priv *info) arizona_free_irq(arizona, ARIZONA_IRQ_MICDET, info); arizona_free_irq(arizona, jack_irq_rise, info); arizona_free_irq(arizona, jack_irq_fall, info); - cancel_delayed_work_sync(&info->hpdet_work); cancel_delayed_work_sync(&info->micd_detect_work); cancel_delayed_work_sync(&info->micd_timeout_work); diff --git a/sound/soc/codecs/arizona.c b/sound/soc/codecs/arizona.c index 7c296c5b24f726..46e2ca48e70fa1 100644 --- a/sound/soc/codecs/arizona.c +++ b/sound/soc/codecs/arizona.c @@ -11,8 +11,8 @@ #include #include #include -#include #include +#include #include #include #include @@ -2799,77 +2799,76 @@ int arizona_lhpf_coeff_put(struct snd_kcontrol *kcontrol, } EXPORT_SYMBOL_GPL(arizona_lhpf_coeff_put); -int arizona_of_get_audio_pdata(struct arizona *arizona) +static int arizona_get_variable_u32_array(struct device *dev, + const char *propname, + u32 *dest, size_t n_max) { - struct arizona_pdata *pdata = &arizona->pdata; - struct device_node *np = arizona->dev->of_node; - u32 val; - u32 pdm_val[ARIZONA_MAX_PDM_SPK]; - int ret; - int count = 0; - - count = 0; - of_property_for_each_u32(np, "wlf,inmode", val) { - if (count == ARRAY_SIZE(pdata->inmode)) - break; - - pdata->inmode[count] = val; - count++; - } + int n, ret; - count = 0; - of_property_for_each_u32(np, "wlf,dmic-ref", val) { - if (count == ARRAY_SIZE(pdata->dmic_ref)) - break; - - pdata->dmic_ref[count] = val; - count++; - } + n = device_property_count_u32(dev, propname); + if (n < 0) { + if (n == -EINVAL) + return 0; /* missing, ignore */ - count = 0; - of_property_for_each_u32(np, "wlf,out-mono", val) { - if (count == ARRAY_SIZE(pdata->out_mono)) - break; - - pdata->out_mono[count] = !!val; - count++; + dev_warn(dev, "%s malformed (%d)\n", propname, n); + return n; } - count = 0; - of_property_for_each_u32(np, "wlf,max-channels-clocked", val) { - if (count == ARRAY_SIZE(pdata->max_channels_clocked)) - break; - - pdata->max_channels_clocked[count] = val; - count++; - } + if (!n) + return 0; - count = 0; - of_property_for_each_u32(np, "wlf,out-volume-limit", val) { - if (count == ARRAY_SIZE(pdata->out_vol_limit)) - break; + if (n > n_max) + n = n_max; - pdata->out_vol_limit[count] = val; - count++; + ret = device_property_read_u32_array(dev, propname, dest, n); + if (ret < 0) { + dev_warn(dev, "Failed to read %s (%d)\n", propname, ret); + return ret; } - ret = of_property_read_u32_array(np, "wlf,spk-fmt", - pdm_val, ARRAY_SIZE(pdm_val)); - - if (ret >= 0) - for (count = 0; count < ARRAY_SIZE(pdata->spk_fmt); ++count) - pdata->spk_fmt[count] = pdm_val[count]; - - ret = of_property_read_u32_array(np, "wlf,spk-mute", - pdm_val, ARRAY_SIZE(pdm_val)); - - if (ret >= 0) - for (count = 0; count < ARRAY_SIZE(pdata->spk_mute); ++count) - pdata->spk_mute[count] = pdm_val[count]; + return n; +} - return 0; +void arizona_get_audio_pdata(struct arizona *arizona) +{ + struct arizona_pdata *pdata = &arizona->pdata; + u32 out_mono[ARRAY_SIZE(pdata->out_mono)]; + int i, n, ret; + + arizona_get_variable_u32_array(arizona->dev, "wlf,inmode", + pdata->inmode, + ARRAY_SIZE(pdata->inmode)); + + arizona_get_variable_u32_array(arizona->dev, "wlf,dmic-ref", + pdata->dmic_ref, + ARRAY_SIZE(pdata->dmic_ref)); + + n = arizona_get_variable_u32_array(arizona->dev, "wlf,out-mono", + out_mono, ARRAY_SIZE(out_mono)); + for (i = 0; i < n; i++) + pdata->out_mono[i] = !!out_mono[i]; + + arizona_get_variable_u32_array(arizona->dev, "wlf,max-channels-clocked", + pdata->max_channels_clocked, + ARRAY_SIZE(pdata->max_channels_clocked)); + + arizona_get_variable_u32_array(arizona->dev, "wlf,out-volume-limit", + pdata->out_vol_limit, + ARRAY_SIZE(pdata->out_vol_limit)); + + ret = device_property_read_u32_array(arizona->dev, "wlf,spk-fmt", + pdata->spk_fmt, + ARRAY_SIZE(pdata->spk_fmt)); + if (ret && ret != -EINVAL) + dev_warn(arizona->dev, "Failed to read wlf,spk-fmt (%d)\n", ret); + + ret = device_property_read_u32_array(arizona->dev, "wlf,spk-mute", + pdata->spk_mute, + ARRAY_SIZE(pdata->spk_mute)); + if (ret && ret != -EINVAL) + dev_warn(arizona->dev, "Failed to read wlf,spk-mute (%d)\n", ret); } -EXPORT_SYMBOL_GPL(arizona_of_get_audio_pdata); +EXPORT_SYMBOL_GPL(arizona_get_audio_pdata); MODULE_DESCRIPTION("ASoC Wolfson Arizona class device support"); MODULE_AUTHOR("Mark Brown "); diff --git a/sound/soc/codecs/arizona.h b/sound/soc/codecs/arizona.h index 0703182d87b3e9..766a29a2389357 100644 --- a/sound/soc/codecs/arizona.h +++ b/sound/soc/codecs/arizona.h @@ -94,13 +94,11 @@ struct arizona_priv { /* Variables used by arizona-jack.c code */ struct mutex lock; - struct delayed_work hpdet_work; struct delayed_work micd_detect_work; struct delayed_work micd_timeout_work; struct snd_soc_jack *jack; struct regulator *micvdd; struct gpio_desc *micd_pol_gpio; - struct gpio_desc *hpdet_id_gpio; u16 last_jackdet; @@ -117,14 +115,10 @@ struct arizona_priv { bool hpdet_active; bool hpdet_done; - bool hpdet_retried; bool mic; bool detecting; - int num_hpdet_res; - unsigned int hpdet_res[3]; - int jack_flips; int hpdet_ip_version; }; @@ -388,7 +382,7 @@ static inline int arizona_unregister_notifier(struct snd_soc_component *componen return blocking_notifier_chain_unregister(&arizona->notifier, nb); } -int arizona_of_get_audio_pdata(struct arizona *arizona); +void arizona_get_audio_pdata(struct arizona *arizona); int arizona_jack_codec_dev_probe(struct arizona_priv *info, struct device *dev); int arizona_jack_codec_dev_remove(struct arizona_priv *info); diff --git a/sound/soc/codecs/aw88166.c b/sound/soc/codecs/aw88166.c index a520c9089425ca..319aac057d4419 100644 --- a/sound/soc/codecs/aw88166.c +++ b/sound/soc/codecs/aw88166.c @@ -404,7 +404,7 @@ static int aw_dev_init_re_update(struct aw88166 *aw88166, int flag) static void aw_dev_backup_sec_record(struct aw88166 *aw88166) { aw_dev_init_vcalb_update(aw88166, AW88166_RECORD_SEC_DATA); - aw_dev_init_re_update(aw88166, AW88166_RECOVERY_SEC_DATA); + aw_dev_init_re_update(aw88166, AW88166_RECORD_SEC_DATA); } static void aw_dev_backup_sec_recovery(struct aw88166 *aw88166) @@ -961,7 +961,7 @@ static int aw_dev_update_reg_container(struct aw88166 *aw88166, else aw_dev->dsp_cfg = AW88166_DEV_DSP_WORK; - reg_val &= (AW88166_HMUTE_MASK | AW88166_PWDN_MASK | + reg_val &= (AW88166_HMUTE_MASK & AW88166_PWDN_MASK & AW88166_DSPBY_MASK); reg_val |= (AW88166_HMUTE_ENABLE_VALUE | AW88166_PWDN_POWER_DOWN_VALUE | AW88166_DSPBY_BYPASS_VALUE); diff --git a/sound/soc/codecs/aw88261.c b/sound/soc/codecs/aw88261.c index e14df93e67f7ad..d4db919d8a2df6 100644 --- a/sound/soc/codecs/aw88261.c +++ b/sound/soc/codecs/aw88261.c @@ -306,7 +306,7 @@ static int aw88261_dev_get_vcalk(struct aw_device *aw_dev, int16_t *vcalk) reg_vcalk = (reg_vcalk >> AW88261_VCALK_SHIFT) & (reg_vcalkl >> AW88261_VCALKL_SHIFT); - if (reg_vcalk & AW88261_EF_VSN_GESLP_SIGN_MASK) + if (reg_vcalk & (~AW88261_EF_VSN_GESLP_SIGN_MASK)) reg_vcalk = reg_vcalk | (~AW88261_EF_VSN_GESLP_NEG); *vcalk = (int16_t)reg_vcalk; diff --git a/sound/soc/codecs/aw88395/aw88395_device.c b/sound/soc/codecs/aw88395/aw88395_device.c index 3ae418c8b34e10..2dd0b3b7de0d1c 100644 --- a/sound/soc/codecs/aw88395/aw88395_device.c +++ b/sound/soc/codecs/aw88395/aw88395_device.c @@ -1004,16 +1004,16 @@ static int aw_dev_update_reg_container(struct aw_device *aw_dev, u16 read_vol; u16 reg_val; u8 reg_addr; - int i, ret; - - reg_data = (int16_t *)data; - data_len = len >> 1; + int i, ret = 0; - if (data_len & 0x1) { - dev_err(aw_dev->dev, "data len:%d unsupported", data_len); + if (len & 0x3) { + dev_err(aw_dev->dev, "data len:%u unsupported\n", len); return -EINVAL; } + reg_data = (int16_t *)data; + data_len = len >> 1; + for (i = 0; i < data_len; i += 2) { reg_addr = reg_data[i]; reg_val = reg_data[i + 1]; diff --git a/sound/soc/codecs/aw88399-lib.c b/sound/soc/codecs/aw88399-lib.c index f2e2c88f5ec0a7..2517f8ae5df47d 100644 --- a/sound/soc/codecs/aw88399-lib.c +++ b/sound/soc/codecs/aw88399-lib.c @@ -296,7 +296,7 @@ static int aw88399_dev_get_vcalk(struct aw88399 *aw88399, int16_t *vcalk) else vcalk_val = vcalkh_val | vcalkl_val; - if (vcalk_val & AW88399_EF_VSN_GESLP_SIGN_MASK) + if (vcalk_val & (~AW88399_EF_VSN_GESLP_SIGN_MASK)) vcalk_val = vcalk_val | AW88399_EF_VSN_GESLP_SIGN_NEG; *vcalk = (int16_t)vcalk_val; @@ -552,7 +552,7 @@ static void aw_dev_i2s_tx_enable(struct aw_device *aw_dev, bool flag) ret = regmap_update_bits(aw_dev->regmap, AW88399_I2SCTRL3_REG, ~AW88399_I2STXEN_MASK, AW88399_I2STXEN_ENABLE_VALUE); else - ret = regmap_update_bits(aw_dev->regmap, AW88399_I2SCFG1_REG, + ret = regmap_update_bits(aw_dev->regmap, AW88399_I2SCTRL3_REG, ~AW88399_I2STXEN_MASK, AW88399_I2STXEN_DISABLE_VALUE); if (ret) @@ -957,7 +957,7 @@ static int aw_dev_update_reg_container(struct aw88399 *aw88399, else aw_dev->dsp_cfg = AW88399_DEV_DSP_WORK; - reg_val &= (AW88399_HMUTE_MASK | AW88399_PWDN_MASK | + reg_val &= (AW88399_HMUTE_MASK & AW88399_PWDN_MASK & AW88399_DSPBY_MASK); reg_val |= (AW88399_HMUTE_ENABLE_VALUE | AW88399_PWDN_POWER_DOWN_VALUE | AW88399_DSPBY_BYPASS_VALUE); diff --git a/sound/soc/codecs/aw88399.c b/sound/soc/codecs/aw88399.c index 1275ac601bcb00..28a9803a693f17 100644 --- a/sound/soc/codecs/aw88399.c +++ b/sound/soc/codecs/aw88399.c @@ -106,7 +106,7 @@ static int aw_cali_svc_cali_en(struct aw_device *aw_dev, bool cali_en) aw_dev_dsp_enable(aw_dev, false); if (cali_en) { regmap_update_bits(aw_dev->regmap, AW88399_DBGCTRL_REG, - ~AW883XX_DSP_NG_EN_MASK, AW883XX_DSP_NG_EN_DISABLE_VALUE); + ~AW88399_DSP_NG_EN_MASK, AW88399_DSP_NG_EN_DISABLE_VALUE); aw_dev_dsp_write(aw_dev, AW88399_DSP_LOW_POWER_SWITCH_CFG_ADDR, AW88399_DSP_LOW_POWER_SWITCH_DISABLE, AW_DSP_16_DATA); @@ -166,7 +166,7 @@ static void aw_cali_svc_backup_info(struct aw_device *aw_dev) unsigned int reg_val, dsp_val; regmap_read(aw_dev->regmap, AW88399_DBGCTRL_REG, ®_val); - backup_desc->dsp_ng_cfg = reg_val & (~AW883XX_DSP_NG_EN_MASK); + backup_desc->dsp_ng_cfg = reg_val & (~AW88399_DSP_NG_EN_MASK); aw_dev_dsp_read(aw_dev, AW88399_DSP_LOW_POWER_SWITCH_CFG_ADDR, &dsp_val, AW_DSP_16_DATA); @@ -178,7 +178,7 @@ static void aw_cali_svc_recover_info(struct aw_device *aw_dev) struct aw_cali_backup_desc *backup_desc = &aw_dev->cali_desc.backup_info; regmap_update_bits(aw_dev->regmap, AW88399_DBGCTRL_REG, - ~AW883XX_DSP_NG_EN_MASK, backup_desc->dsp_ng_cfg); + ~AW88399_DSP_NG_EN_MASK, backup_desc->dsp_ng_cfg); aw_dev_dsp_write(aw_dev, AW88399_DSP_LOW_POWER_SWITCH_CFG_ADDR, backup_desc->dsp_lp_cfg, AW_DSP_16_DATA); diff --git a/sound/soc/codecs/cs35l56-shared.c b/sound/soc/codecs/cs35l56-shared.c index 4d76f177792723..f7374afb709781 100644 --- a/sound/soc/codecs/cs35l56-shared.c +++ b/sound/soc/codecs/cs35l56-shared.c @@ -49,25 +49,15 @@ int cs35l56_set_asp_defaults(struct cs35l56_base *cs35l56_base) EXPORT_SYMBOL_NS_GPL(cs35l56_set_asp_defaults, "SND_SOC_CS35L56_SHARED"); static const struct reg_sequence cs35l56_patch[] = { - /* - * Firmware can change these to non-defaults to satisfy SDCA. - * Ensure that they are at known defaults. - */ - { CS35L56_SWIRE_DP3_CH1_INPUT, 0x00000018 }, - { CS35L56_SWIRE_DP3_CH2_INPUT, 0x00000019 }, - { CS35L56_SWIRE_DP3_CH3_INPUT, 0x00000029 }, - { CS35L56_SWIRE_DP3_CH4_INPUT, 0x00000028 }, { CS35L56_IRQ1_MASK_18, 0x1f7df0ff }, -}; - -static const struct reg_sequence cs35l56_patch_fw[] = { /* These are not reset by a soft-reset, so patch to defaults. */ { CS35L56_MAIN_RENDER_USER_MUTE, 0x00000000 }, { CS35L56_MAIN_RENDER_USER_VOLUME, 0x00000000 }, { CS35L56_MAIN_POSTURE_NUMBER, 0x00000000 }, }; -static const struct reg_sequence cs35l63_patch_fw[] = { +static const struct reg_sequence cs35l63_patch[] = { + { CS35L56_IRQ1_MASK_18, 0x1f7df0ff }, /* These are not reset by a soft-reset, so patch to defaults. */ { CS35L63_MAIN_RENDER_USER_MUTE, 0x00000000 }, { CS35L63_MAIN_RENDER_USER_VOLUME, 0x00000000 }, @@ -76,39 +66,23 @@ static const struct reg_sequence cs35l63_patch_fw[] = { int cs35l56_set_patch(struct cs35l56_base *cs35l56_base) { - int ret; - - ret = regmap_register_patch(cs35l56_base->regmap, cs35l56_patch, - ARRAY_SIZE(cs35l56_patch)); - if (ret) - return ret; - - switch (cs35l56_base->type) { case 0x54: case 0x56: case 0x57: - ret = regmap_register_patch(cs35l56_base->regmap, cs35l56_patch_fw, - ARRAY_SIZE(cs35l56_patch_fw)); - break; + return regmap_register_patch(cs35l56_base->regmap, cs35l56_patch, + ARRAY_SIZE(cs35l56_patch)); case 0x63: case 0x62: - ret = regmap_register_patch(cs35l56_base->regmap, cs35l63_patch_fw, - ARRAY_SIZE(cs35l63_patch_fw)); - break; + return regmap_register_patch(cs35l56_base->regmap, cs35l63_patch, + ARRAY_SIZE(cs35l63_patch)); default: - break; + return 0; } - - return ret; } EXPORT_SYMBOL_NS_GPL(cs35l56_set_patch, "SND_SOC_CS35L56_SHARED"); static const struct reg_default cs35l56_reg_defaults[] = { - { CS35L56_SWIRE_DP3_CH1_INPUT, 0x00000018 }, - { CS35L56_SWIRE_DP3_CH2_INPUT, 0x00000019 }, - { CS35L56_SWIRE_DP3_CH3_INPUT, 0x00000029 }, - { CS35L56_SWIRE_DP3_CH4_INPUT, 0x00000028 }, { CS35L56_IRQ1_MASK_1, 0x83ffffff }, { CS35L56_IRQ1_MASK_2, 0xffff7fff }, { CS35L56_IRQ1_MASK_4, 0xe0ffffff }, @@ -121,10 +95,6 @@ static const struct reg_default cs35l56_reg_defaults[] = { }; static const struct reg_default cs35l63_reg_defaults[] = { - { CS35L56_SWIRE_DP3_CH1_INPUT, 0x00000018 }, - { CS35L56_SWIRE_DP3_CH2_INPUT, 0x00000019 }, - { CS35L56_SWIRE_DP3_CH3_INPUT, 0x00000029 }, - { CS35L56_SWIRE_DP3_CH4_INPUT, 0x00000028 }, { CS35L56_IRQ1_MASK_1, 0x8003ffff }, { CS35L56_IRQ1_MASK_2, 0xffff7fff }, { CS35L56_IRQ1_MASK_4, 0xe0ffffff }, @@ -262,6 +232,10 @@ static bool cs35l56_common_volatile_reg(unsigned int reg) case CS35L56_DACPCM2_INPUT: /* owned by firmware */ case CS35L56_DSP1RX1_INPUT: /* owned by firmware */ case CS35L56_DSP1RX2_INPUT: /* owned by firmware */ + case CS35L56_SWIRE_DP3_CH1_INPUT: /* owned by firmware */ + case CS35L56_SWIRE_DP3_CH2_INPUT: /* owned by firmware */ + case CS35L56_SWIRE_DP3_CH3_INPUT: /* owned by firmware */ + case CS35L56_SWIRE_DP3_CH4_INPUT: /* owned by firmware */ case CS35L56_IRQ1_STATUS: case CS35L56_IRQ1_EINT_1 ... CS35L56_IRQ1_EINT_8: case CS35L56_IRQ1_EINT_18: @@ -1110,9 +1084,6 @@ ssize_t cs35l56_calibrate_debugfs_write(struct cs35l56_base *cs35l56_base, char buf[11] = { 0 }; int num_amps, ret; - if (!IS_ENABLED(CONFIG_SND_SOC_CS35L56_CAL_DEBUGFS_COMMON)) - return -ENXIO; - if (*ppos) return -EINVAL; @@ -1165,9 +1136,6 @@ ssize_t cs35l56_cal_ambient_debugfs_write(struct cs35l56_base *cs35l56_base, unsigned long val; int ret; - if (!IS_ENABLED(CONFIG_SND_SOC_CS35L56_CAL_DEBUGFS_COMMON)) - return -ENXIO; - if (*ppos) return -EINVAL; @@ -1196,9 +1164,6 @@ ssize_t cs35l56_cal_data_debugfs_read(struct cs35l56_base *cs35l56_base, char __user *to, size_t count, loff_t *ppos) { - if (!IS_ENABLED(CONFIG_SND_SOC_CS35L56_CAL_DEBUGFS_COMMON)) - return -ENXIO; - if (!cs35l56_base->cal_data_valid) return 0; @@ -1214,9 +1179,6 @@ ssize_t cs35l56_cal_data_debugfs_write(struct cs35l56_base *cs35l56_base, struct cirrus_amp_cal_data cal_data; int ret; - if (!IS_ENABLED(CONFIG_SND_SOC_CS35L56_CAL_DEBUGFS_COMMON)) - return -ENXIO; - /* Only allow a full blob to be written */ if (*ppos || (count != sizeof(cal_data))) return -EMSGSIZE; @@ -1236,9 +1198,6 @@ EXPORT_SYMBOL_NS_GPL(cs35l56_cal_data_debugfs_write, "SND_SOC_CS35L56_SHARED"); void cs35l56_create_cal_debugfs(struct cs35l56_base *cs35l56_base, const struct cs35l56_cal_debugfs_fops *fops) { - if (!IS_ENABLED(CONFIG_SND_SOC_CS35L56_CAL_DEBUGFS_COMMON)) - return; - cs35l56_base->debugfs = cs_amp_create_debugfs(cs35l56_base->dev); debugfs_create_file("calibrate", diff --git a/sound/soc/codecs/cs35l56-test.c b/sound/soc/codecs/cs35l56-test.c index b422d19ba0b216..2285076b9d0eba 100644 --- a/sound/soc/codecs/cs35l56-test.c +++ b/sound/soc/codecs/cs35l56-test.c @@ -63,6 +63,7 @@ struct cs35l56_test_priv { bool asp_config_regs_written; bool asp_mixer_regs_written; + bool sdw_mux_regs_written; }; struct cs35l56_test_param { @@ -124,6 +125,11 @@ static const struct range cs35l56_test_asp_mixer_registers_range = { .end = CS35L56_ASP1TX4_INPUT, }; +static const struct range cs35l56_test_sdw_mux_registers_range = { + .start = CS35L56_SWIRE_DP3_CH1_INPUT, + .end = CS35L56_SWIRE_DP3_CH4_INPUT, +}; + static int cs35l56_test_mock_registers_read(void *context, const void *reg_buf, size_t reg_size, void *val_buf, size_t val_size) @@ -200,6 +206,9 @@ static int cs35l56_test_mock_registers_write(void *context, const void *data, si if (range_overlaps(&addr_range, &cs35l56_test_asp_mixer_registers_range)) priv->asp_mixer_regs_written = true; + if (range_overlaps(&addr_range, &cs35l56_test_sdw_mux_registers_range)) + priv->sdw_mux_regs_written = true; + for (i = 0; i < count; i += sizeof(u32)) { val = get_unaligned_be32(buf + i); ret = regmap_write(priv->registers, reg + i, val); @@ -271,6 +280,7 @@ static void cs35l56_test_create_mock_device_registers(struct kunit *test) cs35l56_test_fill_register_range(test, &cs35l56_test_asp_config_registers_range, 0); cs35l56_test_fill_register_range(test, &cs35l56_test_asp_mixer_registers_range, 0); + cs35l56_test_fill_register_range(test, &cs35l56_test_sdw_mux_registers_range, 0); } /* @@ -929,6 +939,79 @@ static void cs35l56_test_component_probe_omits_asp(struct kunit *test) KUNIT_EXPECT_FALSE(test, priv->asp_mixer_regs_written); } +/* + * Probing the component must not write the SoundWire TX mux registers, + * either directly or through a subsequent regcache_sync(). + */ +static void cs35l56_test_component_probe_omits_sdw_mux(struct kunit *test) +{ + struct cs35l56_test_priv *priv = test->priv; + struct cs35l56_private *cs35l56 = priv->cs35l56_priv; + struct snd_soc_card *card = cs35l56->component->card; + struct snd_soc_aux_dev *aux; + struct faux_device *card_dev; + + cs35l56_test_create_mock_supplies(test); + cs35l56_test_create_mock_device_registers(test); + + KUNIT_ASSERT_NOT_NULL(test, priv->regmap_config); + cs35l56->base.regmap = devm_regmap_init(cs35l56->base.dev, + &cs35l56_test_mock_registers_client_regmap_bus, + test, priv->regmap_config); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, cs35l56->base.regmap); + + KUNIT_ASSERT_EQ(test, 0, cs35l56_common_probe(cs35l56, 0)); + KUNIT_ASSERT_EQ(test, 0, + kunit_add_action_or_reset(test, cs35l56_remove_wrapper, cs35l56)); + + /* Prevent real dsp_work */ + INIT_WORK(&cs35l56->dsp_work, cs35l56_test_dummy_dsp_work); + + /* Simulate first attachment and re-attachment after the soft reset. */ + regcache_cache_only(cs35l56->base.regmap, false); + KUNIT_ASSERT_EQ(test, 0, cs35l56_init(cs35l56)); + KUNIT_ASSERT_EQ(test, 0, cs35l56_init(cs35l56)); + KUNIT_ASSERT_TRUE(test, cs35l56->base.init_done); + flush_work(&cs35l56->component_register_work); + KUNIT_ASSERT_TRUE(test, cs35l56->component_registered); + + card_dev = faux_device_create("cs35l56_test_card", NULL, NULL); + KUNIT_ASSERT_NOT_NULL(test, card_dev); + KUNIT_ASSERT_EQ(test, 0, + kunit_add_action_or_reset(test, faux_device_destroy_wrapper, card_dev)); + + /* Bind as an auxiliary component so the ASP DAI is never probed. */ + aux = kunit_kzalloc(test, sizeof(*aux), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, aux); + aux->dlc.name = dev_name(cs35l56->base.dev); + card->name = "cs35l56-test"; + card->dev = &card_dev->dev; + card->owner = THIS_MODULE; + card->aux_dev = aux; + card->num_aux_devs = 1; + KUNIT_ASSERT_EQ(test, 0, snd_soc_register_card(card)); + KUNIT_ASSERT_EQ(test, 0, + kunit_add_action_or_reset(test, snd_soc_unregister_card_wrapper, card)); + KUNIT_ASSERT_TRUE(test, card->instantiated); + KUNIT_EXPECT_FALSE(test, priv->sdw_mux_regs_written); + + /* + * Flush cache to ensure there aren't cached values for the SoundWire muxes. + * The first case without regcache_mark_dirty() tests flushing when + * hardware registers have not reset, and requires a dummy write to + * the cache to make it dirty. + */ + regcache_cache_only(cs35l56->base.regmap, true); + KUNIT_ASSERT_EQ(test, 0, regmap_write(cs35l56->base.regmap, + CS35L56_DSP_VIRTUAL1_MBOX_1, 0)); + regcache_cache_only(cs35l56->base.regmap, false); + KUNIT_ASSERT_EQ(test, 0, regcache_sync(cs35l56->base.regmap)); + regcache_mark_dirty(cs35l56->base.regmap); + KUNIT_ASSERT_EQ(test, 0, regcache_sync(cs35l56->base.regmap)); + + KUNIT_EXPECT_FALSE(test, priv->sdw_mux_regs_written); +} + static int cs35l56_test_case_init_common(struct kunit *test) { struct cs35l56_test_priv *priv; @@ -1233,6 +1316,8 @@ static struct kunit_case cs35l56_test_cases_soundwire[] = { KUNIT_CASE(cs35l56_test_set_fw_name_preserves_spkid_without_onchip_gpios), KUNIT_CASE_PARAM(cs35l56_test_component_probe_omits_asp, cs35l56_test_type_rev_all_gen_params), + KUNIT_CASE_PARAM(cs35l56_test_component_probe_omits_sdw_mux, + cs35l56_test_type_rev_all_gen_params), { } /* terminator */ }; diff --git a/sound/soc/codecs/cs35l56.c b/sound/soc/codecs/cs35l56.c index 30835dc5600643..34588245a8f31e 100644 --- a/sound/soc/codecs/cs35l56.c +++ b/sound/soc/codecs/cs35l56.c @@ -43,6 +43,10 @@ #include "wm_adsp.h" #include "cs35l56.h" +static bool cs35l56_allow_factory_cal = IS_ENABLED(CONFIG_SND_SOC_CS35L56_CAL_DEBUGFS); +module_param_named(allow_factory_cal, cs35l56_allow_factory_cal, bool, 0444); +MODULE_PARM_DESC(allow_factory_cal, "Enable support for factory calibration"); + /* * snd_soc_register_component() can call component_probe() on all instances * in a card, so deferred registration must be protected across all instances. @@ -103,26 +107,6 @@ static void cs35l56_wait_dsp_ready(struct cs35l56_private *cs35l56) flush_work(&cs35l56->dsp_work); } -static int cs35l56_dspwait_get_volsw(struct snd_kcontrol *kcontrol, - struct snd_ctl_elem_value *ucontrol) -{ - struct snd_soc_component *component = snd_kcontrol_chip(kcontrol); - struct cs35l56_private *cs35l56 = snd_soc_component_get_drvdata(component); - - cs35l56_wait_dsp_ready(cs35l56); - return snd_soc_get_volsw(kcontrol, ucontrol); -} - -static int cs35l56_dspwait_put_volsw(struct snd_kcontrol *kcontrol, - struct snd_ctl_elem_value *ucontrol) -{ - struct snd_soc_component *component = snd_kcontrol_chip(kcontrol); - struct cs35l56_private *cs35l56 = snd_soc_component_get_drvdata(component); - - cs35l56_wait_dsp_ready(cs35l56); - return snd_soc_put_volsw(kcontrol, ucontrol); -} - static DECLARE_TLV_DB_SCALE(vol_tlv, -10000, 25, 0); static SOC_ENUM_SINGLE_DECL(cs35l56_cal_set_status_enum, SND_SOC_NOPM, 0, @@ -138,44 +122,32 @@ static int cs35l56_cal_set_status_ctl_get(struct snd_kcontrol *kcontrol, } static const struct snd_kcontrol_new cs35l56_controls[] = { - SOC_SINGLE_EXT("Speaker Switch", - CS35L56_MAIN_RENDER_USER_MUTE, 0, 1, 1, - cs35l56_dspwait_get_volsw, cs35l56_dspwait_put_volsw), - SOC_SINGLE_S_EXT_TLV("Speaker Volume", - CS35L56_MAIN_RENDER_USER_VOLUME, - CS35L56_MAIN_RENDER_USER_VOLUME_SHIFT, - CS35L56_MAIN_RENDER_USER_VOLUME_MIN, - CS35L56_MAIN_RENDER_USER_VOLUME_MAX, - CS35L56_MAIN_RENDER_USER_VOLUME_SIGNBIT, - 0, - cs35l56_dspwait_get_volsw, - cs35l56_dspwait_put_volsw, - vol_tlv), - SOC_SINGLE_EXT("Posture Number", CS35L56_MAIN_POSTURE_NUMBER, - 0, 255, 0, - cs35l56_dspwait_get_volsw, cs35l56_dspwait_put_volsw), + SOC_SINGLE("Speaker Switch", CS35L56_MAIN_RENDER_USER_MUTE, 0, 1, 1), + SOC_SINGLE_S_TLV("Speaker Volume", + CS35L56_MAIN_RENDER_USER_VOLUME, + CS35L56_MAIN_RENDER_USER_VOLUME_SHIFT, + CS35L56_MAIN_RENDER_USER_VOLUME_MIN, + CS35L56_MAIN_RENDER_USER_VOLUME_MAX, + CS35L56_MAIN_RENDER_USER_VOLUME_SIGNBIT, + 0, + vol_tlv), + SOC_SINGLE("Posture Number", CS35L56_MAIN_POSTURE_NUMBER, 0, 255, 0), SOC_ENUM_EXT_ACC("CAL_SET_STATUS", cs35l56_cal_set_status_enum, cs35l56_cal_set_status_ctl_get, NULL, SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_VOLATILE), }; static const struct snd_kcontrol_new cs35l63_controls[] = { - SOC_SINGLE_EXT("Speaker Switch", - CS35L63_MAIN_RENDER_USER_MUTE, 0, 1, 1, - cs35l56_dspwait_get_volsw, cs35l56_dspwait_put_volsw), - SOC_SINGLE_S_EXT_TLV("Speaker Volume", - CS35L63_MAIN_RENDER_USER_VOLUME, - CS35L56_MAIN_RENDER_USER_VOLUME_SHIFT, - CS35L56_MAIN_RENDER_USER_VOLUME_MIN, - CS35L56_MAIN_RENDER_USER_VOLUME_MAX, - CS35L56_MAIN_RENDER_USER_VOLUME_SIGNBIT, - 0, - cs35l56_dspwait_get_volsw, - cs35l56_dspwait_put_volsw, - vol_tlv), - SOC_SINGLE_EXT("Posture Number", CS35L63_MAIN_POSTURE_NUMBER, - 0, 255, 0, - cs35l56_dspwait_get_volsw, cs35l56_dspwait_put_volsw), + SOC_SINGLE("Speaker Switch", CS35L63_MAIN_RENDER_USER_MUTE, 0, 1, 1), + SOC_SINGLE_S_TLV("Speaker Volume", + CS35L63_MAIN_RENDER_USER_VOLUME, + CS35L56_MAIN_RENDER_USER_VOLUME_SHIFT, + CS35L56_MAIN_RENDER_USER_VOLUME_MIN, + CS35L56_MAIN_RENDER_USER_VOLUME_MAX, + CS35L56_MAIN_RENDER_USER_VOLUME_SIGNBIT, + 0, + vol_tlv), + SOC_SINGLE("Posture Number", CS35L63_MAIN_POSTURE_NUMBER, 0, 255, 0), SOC_ENUM_EXT_ACC("CAL_SET_STATUS", cs35l56_cal_set_status_enum, cs35l56_cal_set_status_ctl_get, NULL, SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_VOLATILE), @@ -267,42 +239,6 @@ static const struct snd_kcontrol_new asp1_tx4_mux = SOC_DAPM_ENUM_EXT("ASP1TX4 SRC", cs35l56_asp1tx4_enum, cs35l56_asp_tx_get, cs35l56_asp_tx_put); -static SOC_VALUE_ENUM_SINGLE_DECL(cs35l56_sdw1tx1_enum, - CS35L56_SWIRE_DP3_CH1_INPUT, - 0, CS35L56_SWIRETXn_SRC_MASK, - cs35l56_tx_input_texts, - cs35l56_tx_input_values); - -static const struct snd_kcontrol_new sdw1_tx1_mux = - SOC_DAPM_ENUM("SDW1TX1 SRC", cs35l56_sdw1tx1_enum); - -static SOC_VALUE_ENUM_SINGLE_DECL(cs35l56_sdw1tx2_enum, - CS35L56_SWIRE_DP3_CH2_INPUT, - 0, CS35L56_SWIRETXn_SRC_MASK, - cs35l56_tx_input_texts, - cs35l56_tx_input_values); - -static const struct snd_kcontrol_new sdw1_tx2_mux = - SOC_DAPM_ENUM("SDW1TX2 SRC", cs35l56_sdw1tx2_enum); - -static SOC_VALUE_ENUM_SINGLE_DECL(cs35l56_sdw1tx3_enum, - CS35L56_SWIRE_DP3_CH3_INPUT, - 0, CS35L56_SWIRETXn_SRC_MASK, - cs35l56_tx_input_texts, - cs35l56_tx_input_values); - -static const struct snd_kcontrol_new sdw1_tx3_mux = - SOC_DAPM_ENUM("SDW1TX3 SRC", cs35l56_sdw1tx3_enum); - -static SOC_VALUE_ENUM_SINGLE_DECL(cs35l56_sdw1tx4_enum, - CS35L56_SWIRE_DP3_CH4_INPUT, - 0, CS35L56_SWIRETXn_SRC_MASK, - cs35l56_tx_input_texts, - cs35l56_tx_input_values); - -static const struct snd_kcontrol_new sdw1_tx4_mux = - SOC_DAPM_ENUM("SDW1TX4 SRC", cs35l56_sdw1tx4_enum); - static int cs35l56_play_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { @@ -407,11 +343,6 @@ static const struct snd_soc_dapm_widget cs35l56_dapm_widgets[] = { SND_SOC_DAPM_MUX("ASP1 TX3 Source", SND_SOC_NOPM, 0, 0, &asp1_tx3_mux), SND_SOC_DAPM_MUX("ASP1 TX4 Source", SND_SOC_NOPM, 0, 0, &asp1_tx4_mux), - SND_SOC_DAPM_MUX("SDW1 TX1 Source", SND_SOC_NOPM, 0, 0, &sdw1_tx1_mux), - SND_SOC_DAPM_MUX("SDW1 TX2 Source", SND_SOC_NOPM, 0, 0, &sdw1_tx2_mux), - SND_SOC_DAPM_MUX("SDW1 TX3 Source", SND_SOC_NOPM, 0, 0, &sdw1_tx3_mux), - SND_SOC_DAPM_MUX("SDW1 TX4 Source", SND_SOC_NOPM, 0, 0, &sdw1_tx4_mux), - SND_SOC_DAPM_SIGGEN("VMON ADC"), SND_SOC_DAPM_SIGGEN("IMON ADC"), SND_SOC_DAPM_SIGGEN("ERRVOL ADC"), @@ -420,6 +351,7 @@ static const struct snd_soc_dapm_widget cs35l56_dapm_widgets[] = { SND_SOC_DAPM_SIGGEN("VBSTMON ADC"), SND_SOC_DAPM_SIGGEN("TEMPMON ADC"), SND_SOC_DAPM_SIGGEN("OT25 Reference"), + SND_SOC_DAPM_SIGGEN("OT127 Source"), SND_SOC_DAPM_INPUT("Calibrate"), }; @@ -476,14 +408,7 @@ static const struct snd_soc_dapm_route cs35l56_audio_map[] = { { "ASP1 Capture", NULL, "ASP1TX3" }, { "ASP1 Capture", NULL, "ASP1TX4" }, - CS35L56_SRC_ROUTE("SDW1 TX1") - CS35L56_SRC_ROUTE("SDW1 TX2") - CS35L56_SRC_ROUTE("SDW1 TX3") - CS35L56_SRC_ROUTE("SDW1 TX4") - { "SDW1 Capture", NULL, "SDW1 TX1 Source" }, - { "SDW1 Capture", NULL, "SDW1 TX2 Source" }, - { "SDW1 Capture", NULL, "SDW1 TX3 Source" }, - { "SDW1 Capture", NULL, "SDW1 TX4 Source" }, + { "OT127", NULL, "OT127 Source" }, { "OT25", NULL, "OT25 Reference" }, }; @@ -902,10 +827,10 @@ static struct snd_soc_dai_driver cs35l56_dai[] = { .ops = &cs35l56_sdw_dai_ops, }, { - .name = "cs35l56-sdw1c", + .name = "cs35l56-ot127", .id = 2, .capture = { - .stream_name = "SDW1 Capture", + .stream_name = "OT127", .channels_min = 1, .channels_max = 4, .rates = CS35L56_RATES, @@ -1611,7 +1536,7 @@ static int _cs35l56_component_probe(struct snd_soc_component *component) if (ret) return ret; - if (IS_ENABLED(CONFIG_SND_SOC_CS35L56_CAL_DEBUGFS)) + if (cs35l56_allow_factory_cal) cs35l56_create_cal_debugfs(&cs35l56->base, &cs35l56_cal_debugfs_fops); queue_work(cs35l56->dsp_wq, &cs35l56->dsp_work); diff --git a/sound/soc/codecs/cs47l24.c b/sound/soc/codecs/cs47l24.c index fa2d01ead30bb8..744a610cd1afe3 100644 --- a/sound/soc/codecs/cs47l24.c +++ b/sound/soc/codecs/cs47l24.c @@ -1221,13 +1221,7 @@ static int cs47l24_probe(struct platform_device *pdev) if (!cs47l24) return -ENOMEM; - if (IS_ENABLED(CONFIG_OF)) { - if (!dev_get_platdata(arizona->dev)) { - ret = arizona_of_get_audio_pdata(arizona); - if (ret < 0) - return ret; - } - } + arizona_get_audio_pdata(arizona); platform_set_drvdata(pdev, cs47l24); diff --git a/sound/soc/codecs/da7213.c b/sound/soc/codecs/da7213.c index b08e8ab6b42186..53ed58ca9ab292 100644 --- a/sound/soc/codecs/da7213.c +++ b/sound/soc/codecs/da7213.c @@ -2242,6 +2242,7 @@ static int da7213_i2c_probe(struct i2c_client *i2c) if (ret < 0) { dev_err(&i2c->dev, "Failed to register da7213 component: %d\n", ret); + pm_runtime_disable(&i2c->dev); } return ret; } diff --git a/sound/soc/codecs/es9356.c b/sound/soc/codecs/es9356.c index 74c8978b534790..cc69336dff79ea 100644 --- a/sound/soc/codecs/es9356.c +++ b/sound/soc/codecs/es9356.c @@ -1204,8 +1204,11 @@ static int es9356_sdca_dev_resume(struct device *dev) } regcache_cache_only(es9356->regmap, false); - regcache_sync(es9356->regmap); - return 0; + ret = regcache_sync(es9356->regmap); + if (ret) + regcache_cache_only(es9356->regmap, true); + + return ret; } static const struct dev_pm_ops es9356_sdca_pm = { diff --git a/sound/soc/codecs/lpass-rx-macro.c b/sound/soc/codecs/lpass-rx-macro.c index 5253ad4381888b..9f3186743417ad 100644 --- a/sound/soc/codecs/lpass-rx-macro.c +++ b/sound/soc/codecs/lpass-rx-macro.c @@ -1659,6 +1659,7 @@ static bool rx_is_rw_register(struct device *dev, unsigned int reg) case LPASS_CODEC_VERSION_2_6: case LPASS_CODEC_VERSION_2_7: case LPASS_CODEC_VERSION_2_8: + case LPASS_CODEC_VERSION_2_9: return rx_2_5_is_rw_register(dev, reg); default: break; @@ -2460,6 +2461,8 @@ static void rx_macro_hd2_control(struct snd_soc_component *component, hd2_scale_reg = CDC_RX_RXn_RX_PATH_SEC3(rx, 1); hd2_enable_reg = CDC_RX_RXn_RX_PATH_CFG0(rx, 1); break; + default: + return; } if (hd2_enable_reg && SND_SOC_DAPM_EVENT_ON(event)) { @@ -3698,6 +3701,7 @@ static int rx_macro_component_probe(struct snd_soc_component *component) case LPASS_CODEC_VERSION_2_6: case LPASS_CODEC_VERSION_2_7: case LPASS_CODEC_VERSION_2_8: + case LPASS_CODEC_VERSION_2_9: controls = rx_macro_2_5_snd_controls; num_controls = ARRAY_SIZE(rx_macro_2_5_snd_controls); widgets = rx_macro_2_5_dapm_widgets; @@ -3883,6 +3887,7 @@ static int rx_macro_probe(struct platform_device *pdev) case LPASS_CODEC_VERSION_2_6: case LPASS_CODEC_VERSION_2_7: case LPASS_CODEC_VERSION_2_8: + case LPASS_CODEC_VERSION_2_9: rx->rxn_reg_stride = 0xc0; rx->rxn_reg_stride2 = 0x0; def_count = ARRAY_SIZE(rx_defaults) + ARRAY_SIZE(rx_2_5_defaults); @@ -3957,9 +3962,7 @@ static int rx_macro_probe(struct platform_device *pdev) if (ret) goto err_rpm_put; - ret = pm_runtime_put_autosuspend(dev); - if (ret < 0) - dev_warn(dev, "runtime PM put failed after probe: %d\n", ret); + pm_runtime_put_autosuspend(dev); return 0; diff --git a/sound/soc/codecs/lpass-tx-macro.c b/sound/soc/codecs/lpass-tx-macro.c index 6f2af4907cb84d..45dd079683b056 100644 --- a/sound/soc/codecs/lpass-tx-macro.c +++ b/sound/soc/codecs/lpass-tx-macro.c @@ -2407,9 +2407,7 @@ static int tx_macro_probe(struct platform_device *pdev) if (ret) goto err_rpm_put; - ret = pm_runtime_put_autosuspend(dev); - if (ret < 0) - dev_warn(dev, "runtime PM put failed after probe: %d\n", ret); + pm_runtime_put_autosuspend(dev); return 0; diff --git a/sound/soc/codecs/lpass-va-macro.c b/sound/soc/codecs/lpass-va-macro.c index af8308eacb0baa..eb8c07be92bb35 100644 --- a/sound/soc/codecs/lpass-va-macro.c +++ b/sound/soc/codecs/lpass-va-macro.c @@ -1391,7 +1391,7 @@ static int fsgen_gate_enable(struct clk_hw *hw) { struct va_macro *va = to_va_macro(hw); struct regmap *regmap = va->regmap; - int ret, rpm_ret; + int ret; ret = pm_runtime_resume_and_get(va->dev); if (ret < 0) @@ -1399,11 +1399,7 @@ static int fsgen_gate_enable(struct clk_hw *hw) ret = va_macro_mclk_enable(va, true); if (ret) { - rpm_ret = pm_runtime_put_autosuspend(va->dev); - if (rpm_ret < 0) - dev_warn(va->dev, - "runtime PM put failed in fsgen enable unwind: %d\n", - rpm_ret); + pm_runtime_put_autosuspend(va->dev); return ret; } if (va->has_swr_master) @@ -1417,7 +1413,6 @@ static void fsgen_gate_disable(struct clk_hw *hw) { struct va_macro *va = to_va_macro(hw); struct regmap *regmap = va->regmap; - int ret; if (va->has_swr_master) regmap_update_bits(regmap, CDC_VA_CLK_RST_CTRL_SWR_CONTROL, @@ -1425,9 +1420,7 @@ static void fsgen_gate_disable(struct clk_hw *hw) va_macro_mclk_enable(va, false); - ret = pm_runtime_put_autosuspend(va->dev); - if (ret < 0) - dev_warn(va->dev, "runtime PM put failed in fsgen disable: %d\n", ret); + pm_runtime_put_autosuspend(va->dev); } static int fsgen_gate_is_enabled(struct clk_hw *hw) @@ -1724,9 +1717,7 @@ static int va_macro_probe(struct platform_device *pdev) goto err_rpm_put; } - rpm_ret = pm_runtime_put_autosuspend(dev); - if (rpm_ret < 0) - dev_warn(dev, "runtime PM put failed after probe: %d\n", rpm_ret); + pm_runtime_put_autosuspend(dev); return 0; diff --git a/sound/soc/codecs/lpass-wsa-macro.c b/sound/soc/codecs/lpass-wsa-macro.c index 2b63954f783b35..f9646d1c09dd5d 100644 --- a/sound/soc/codecs/lpass-wsa-macro.c +++ b/sound/soc/codecs/lpass-wsa-macro.c @@ -2605,9 +2605,7 @@ static int wsa_swrm_clock(struct wsa_macro *wsa, bool enable) CDC_WSA_SWR_CLK_EN_MASK, 0); wsa_macro_mclk_enable(wsa, false); - ret = pm_runtime_put_autosuspend(wsa->dev); - if (ret < 0) - dev_warn(wsa->dev, "runtime PM put failed: %d\n", ret); + pm_runtime_put_autosuspend(wsa->dev); } return 0; @@ -2871,9 +2869,7 @@ static int wsa_macro_probe(struct platform_device *pdev) if (ret) goto err_rpm_put; - ret = pm_runtime_put_autosuspend(dev); - if (ret < 0) - dev_warn(dev, "runtime PM put failed after probe: %d\n", ret); + pm_runtime_put_autosuspend(dev); return 0; err_rpm_put: diff --git a/sound/soc/codecs/ma5311.c b/sound/soc/codecs/ma5311.c new file mode 100644 index 00000000000000..d548fcd0267b48 --- /dev/null +++ b/sound/soc/codecs/ma5311.c @@ -0,0 +1,2300 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// ma5311.c -- ma5311 ALSA SoC Audio driver +// +// Copyright 2026 Iron Device Corporation +// +// Author: Gyuhwa Park +// Author: Hyunuk Son + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ma5311.h" + +/* Board-selected delays; RSTN timing has not been hardware-validated. */ +#define MA5311_RESET_ASSERT_MS 50 +#define MA5311_RESET_RECOVERY_MS 50 + +#define MA5311_PLL_MATCH(_input_clk, _post_n, _n, _f1, _f2, _f3_p_cp) \ + { \ + .input_clk = (_input_clk), \ + .post_n = (_post_n), \ + .n = (_n), \ + .f1 = (_f1), \ + .f2 = (_f2), \ + .f3_p_cp = (_f3_p_cp), \ + } + +struct ma5311_pll_match { + unsigned int input_clk; + unsigned int post_n; + unsigned int n; + unsigned int f1; + unsigned int f2; + unsigned int f3_p_cp; +}; + +struct ma5311_priv { + bool amp_power_status; + bool adc_power_status; + enum ma5311_mode amp_mode; + unsigned int num_of_pll_matches; + struct device *dev; + struct regmap *ctrl_regmap; + struct i2c_client *adc_client; + struct regmap *adc_regmap; + struct gpio_desc *reset_gpio; + const struct ma5311_pll_match *pll_matches; + unsigned int format; + unsigned int frame_size; + unsigned int last_bclk; + unsigned int sys_clk_id; + + /* For dai configuration backup */ + unsigned int dai_sys_clk; /* 0x00: MA5311_DAC_CLKSYSTEM_MASK */ + unsigned int dai_clk_mode; + unsigned int dai_leftpol; + unsigned int dai_sck_edge; + unsigned int dai_spk_mute; + unsigned int dai_tdm1_rx_pos; + unsigned int dai_tdm2_data_len; + unsigned int dai_tdm2_capture_cfg; + unsigned int dai_data_path; + unsigned int dai_tdm_slot_enable; + unsigned int dai_pll_input; /* 0xa2: PLL input and reference clock selection */ + unsigned int dai_pll_post_n; + unsigned int dai_pll_n; + unsigned int dai_pll_f1; + unsigned int dai_pll_f2; + unsigned int dai_pll_f3_p_cp; + unsigned int dai_sdo_len; + unsigned int dai_sck_rate; + unsigned int dai_o_format; + unsigned int dai_adc_mix_ch; + unsigned int dai_mas_clk_sel; /* 0xb8: MA5311_LRCK_SCK_MAS_CLK_SEL_MASK */ + unsigned int dai_adc_clk; /* 0xb8: MA5311_DAC_ADC_CLK_ON_MASK */ + + unsigned int dai_adc1_word_len; + unsigned int dai_adc1_sck_rate; + unsigned int dai_adc2_word_len; + unsigned int dai_adc2_sck_rate; + unsigned int dai_adc3_word_len; + unsigned int dai_adc3_sck_rate; + unsigned int dai_adc4_word_len; + unsigned int dai_adc4_sck_rate; + + bool flag_ext_rst; + bool flag_dai_tdm; +}; + +static const struct ma5311_pll_match ma5311_pll_matches[] = { + /* Input clock in Hz; register values produce a 24.576 MHz PLL clock. */ + MA5311_PLL_MATCH(1536000, 0x07, 0xE0, 0x00, 0x00, 0x03), + MA5311_PLL_MATCH(3072000, 0x07, 0x70, 0x00, 0x00, 0x03), + MA5311_PLL_MATCH(6144000, 0x07, 0x70, 0x00, 0x00, 0x07), + MA5311_PLL_MATCH(12288000, 0x07, 0x70, 0x00, 0x00, 0x0B), +}; + +static const struct reg_default ma5311_ctrl_reg_def[] = { + { 0x00, 0x08 }, + { 0x01, 0x00 }, + { 0x02, 0x00 }, + { 0x03, 0x01 }, + { 0x04, 0x17 }, + { 0x05, 0x01 }, + { 0x09, 0x00 }, + { 0x0A, 0x58 }, + { 0x0B, 0x58 }, + { 0x0E, 0xAF }, + { 0x0F, 0x0F }, + { 0x10, 0x00 }, + { 0x11, 0x00 }, + { 0x12, 0x01 }, + { 0x14, 0x5B }, + { 0x15, 0x01 }, + { 0x16, 0x0F }, + { 0x17, 0x0F }, + { 0x18, 0x0F }, + { 0x19, 0x00 }, + { 0x1A, 0x00 }, + { 0x1B, 0x00 }, + { 0x23, 0x19 }, + { 0x24, 0x00 }, + { 0x25, 0x00 }, + { 0x26, 0x04 }, + { 0x2B, 0x00 }, + { 0x2C, 0x0C }, + { 0x2D, 0x0C }, + { 0x2E, 0x0C }, + { 0x2F, 0x0C }, + { 0x30, 0x0C }, + { 0x33, 0x2C }, + { 0x34, 0x00 }, + { 0x35, 0x00 }, + { 0x36, 0x92 }, + { 0x37, 0x01 }, + { 0x38, 0x41 }, + { 0x39, 0x00 }, + { 0x3A, 0x00 }, + { 0x3B, 0x00 }, + { 0x3C, 0x00 }, + { 0x3D, 0x00 }, + { 0x40, 0x00 }, + { 0x41, 0x00 }, + { 0x42, 0x00 }, + { 0x43, 0x00 }, + { 0x44, 0x00 }, + { 0x45, 0x00 }, + { 0x46, 0x20 }, + { 0x47, 0x00 }, + { 0x48, 0x00 }, + { 0x49, 0x00 }, + { 0x4A, 0x00 }, + { 0x4B, 0x00 }, + { 0x4C, 0x00 }, + { 0x4D, 0x00 }, + { 0x4E, 0x00 }, + { 0x4F, 0x00 }, + { 0x50, 0x00 }, + { 0x51, 0x00 }, + { 0x52, 0x00 }, + { 0x53, 0x00 }, + { 0x54, 0x00 }, + { 0x55, 0x20 }, + { 0x56, 0x00 }, + { 0x57, 0x00 }, + { 0x58, 0x00 }, + { 0x59, 0x00 }, + { 0x5A, 0x00 }, + { 0x5B, 0x00 }, + { 0x5C, 0x00 }, + { 0x5D, 0x00 }, + { 0x5E, 0x00 }, + { 0x5F, 0x00 }, + { 0x60, 0x00 }, + { 0x61, 0x00 }, + { 0x62, 0x00 }, + { 0x63, 0x00 }, + { 0x64, 0x20 }, + { 0x65, 0x00 }, + { 0x66, 0x00 }, + { 0x67, 0x00 }, + { 0x68, 0x00 }, + { 0x69, 0x00 }, + { 0x6A, 0x00 }, + { 0x6B, 0x00 }, + { 0x6C, 0x00 }, + { 0x6D, 0x00 }, + { 0x6E, 0x00 }, + { 0x6F, 0x00 }, + { 0x70, 0x00 }, + { 0x71, 0x00 }, + { 0x72, 0x00 }, + { 0x73, 0x20 }, + { 0x74, 0x00 }, + { 0x75, 0x00 }, + { 0x76, 0x00 }, + { 0x77, 0x00 }, + { 0x78, 0x00 }, + { 0x79, 0x00 }, + { 0x7A, 0x00 }, + { 0x7B, 0x00 }, + { 0x7C, 0x00 }, + { 0x7D, 0x00 }, + { 0x7E, 0x00 }, + { 0x7F, 0x00 }, + { 0x80, 0x00 }, + { 0x81, 0x00 }, + { 0x82, 0x20 }, + { 0x83, 0x00 }, + { 0x84, 0x00 }, + { 0x85, 0x00 }, + { 0x86, 0x00 }, + { 0x87, 0x00 }, + { 0x88, 0x00 }, + { 0x89, 0x00 }, + { 0x8A, 0x00 }, + { 0x8B, 0x08 }, + { 0x8C, 0x20 }, + { 0x8D, 0x00 }, + { 0x8E, 0x00 }, + { 0x8F, 0x02 }, + { 0x91, 0x00 }, + { 0xA1, 0x40 }, + { 0xA2, 0x48 }, + { 0xA3, 0x20 }, + { 0xA4, 0x00 }, + { 0xA5, 0x1A }, + { 0xA6, 0x52 }, + { 0xA7, 0x00 }, + { 0xA8, 0x28 }, + { 0xA9, 0x25 }, + { 0xAA, 0x44 }, + { 0xAB, 0x62 }, + { 0xAC, 0x04 }, + { 0xAD, 0x00 }, + { 0xAE, 0x00 }, + { 0xAF, 0x00 }, + { 0xB0, 0x00 }, + { 0xB1, 0x00 }, + { 0xB2, 0x00 }, + { 0xB3, 0x04 }, + { 0xB4, 0x00 }, + { 0xB5, 0x00 }, + { 0xB7, 0x20 }, + { 0xB8, 0x44 }, + { 0xB9, 0x0B }, + { 0xBB, 0x42 }, + { 0xBC, 0x82 }, + { 0xBD, 0x61 }, + { 0xBE, 0x67 }, + { 0xBF, 0x67 }, +}; + +static const struct reg_default ma5311_adc_reg_def[] = { + { 0x00, 0x89 }, + { 0x01, 0x6C }, + { 0x02, 0x07 }, + { 0x03, 0x00 }, + { 0x04, 0xFF }, + { 0x05, 0xFF }, + { 0x06, 0x00 }, + { 0x07, 0xC0 }, + { 0x08, 0xC0 }, + { 0x09, 0x10 }, + { 0x0A, 0x10 }, + { 0x0B, 0xFF }, + { 0x0C, 0x6C }, + { 0x0D, 0x6C }, + { 0x0E, 0x00 }, + { 0x0F, 0x82 }, + { 0x10, 0x89 }, + { 0x11, 0x6C }, + { 0x12, 0x07 }, + { 0x13, 0x00 }, + { 0x14, 0xFF }, + { 0x15, 0xFF }, + { 0x16, 0x00 }, + { 0x17, 0xC0 }, + { 0x18, 0xC0 }, + { 0x19, 0x10 }, + { 0x1A, 0x10 }, + { 0x1B, 0xFF }, + { 0x1C, 0x6C }, + { 0x1D, 0x6C }, + { 0x1E, 0x00 }, + { 0x1F, 0x82 }, + { 0x20, 0x89 }, + { 0x21, 0x6C }, + { 0x22, 0x07 }, + { 0x23, 0x00 }, + { 0x24, 0xFF }, + { 0x25, 0xFF }, + { 0x26, 0x00 }, + { 0x27, 0xC0 }, + { 0x28, 0xC0 }, + { 0x29, 0x10 }, + { 0x2A, 0x10 }, + { 0x2B, 0xFF }, + { 0x2C, 0x6C }, + { 0x2D, 0x6C }, + { 0x2E, 0x00 }, + { 0x2F, 0x82 }, + { 0x30, 0x89 }, + { 0x31, 0x6C }, + { 0x32, 0x07 }, + { 0x33, 0x00 }, + { 0x34, 0xFF }, + { 0x35, 0xFF }, + { 0x36, 0x00 }, + { 0x37, 0xC0 }, + { 0x38, 0xC0 }, + { 0x39, 0x10 }, + { 0x3A, 0x10 }, + { 0x3B, 0xFF }, + { 0x3C, 0x6C }, + { 0x3D, 0x6C }, + { 0x3E, 0x00 }, + { 0x3F, 0x82 }, +}; + +static bool ma5311_ctrl_readable_register(struct device *dev, unsigned int reg) +{ + if (reg > MA5311_DAC_FF_VERSION) + return false; + + switch (reg) { + case MA5311_DAC_00_SYSTEM_CTRL1 ... MA5311_DAC_05_ADC_DAC_MIX2: + case MA5311_DAC_09_OUTPUT_CTRL ... MA5311_DAC_0B_SPK_VOL_R: + case MA5311_DAC_0E_MUTE_VOL_CTRL ... MA5311_DAC_12_SYSTEM_CTRL5: + case MA5311_DAC_14_MODULATOR2 ... MA5311_DAC_1B_BASS_SPK7: + case MA5311_DAC_23_COMP_LIM1 ... MA5311_DAC_26_COMP_LIM4: + case MA5311_DAC_2B_EQ_MODE ... MA5311_DAC_30_EQ_GRAPHIC5: + case MA5311_DAC_33_FLL_CTRL3 ... MA5311_DAC_3D_TEST3: + case MA5311_DAC_40_EQ_CTRL1 ... MA5311_DAC_8F_PLL_F3_P_CP: + case MA5311_DAC_91_ADC_DAC_MIX: + case MA5311_DAC_A1_TOP_MAN1_FOR_SDO ... MA5311_DAC_B5_MCLKO_TEST: + case MA5311_DAC_B7_TOP_MAN4 ... MA5311_DAC_B9_PLL_A_SETTING: + case MA5311_DAC_BB_CLASS_G_LEVEL1 ... MA5311_DAC_BF_POWER_METER: + case MA5311_DAC_EA_DAC_STATUS ... MA5311_DAC_EC_DAC_SCP_STATUS: + case MA5311_DAC_FB_STATUS2 ... MA5311_DAC_FD_POWER_METER_DISPLAY: + case MA5311_DAC_FF_VERSION: + break; + default: + return false; + } + + return true; +} + +static bool ma5311_ctrl_writeable_register(struct device *dev, unsigned int reg) +{ + if (reg > MA5311_DAC_FF_VERSION) + return false; + + switch (reg) { + case MA5311_DAC_00_SYSTEM_CTRL1 ... MA5311_DAC_05_ADC_DAC_MIX2: + case MA5311_DAC_09_OUTPUT_CTRL ... MA5311_DAC_0B_SPK_VOL_R: + case MA5311_DAC_0E_MUTE_VOL_CTRL ... MA5311_DAC_12_SYSTEM_CTRL5: + case MA5311_DAC_14_MODULATOR2 ... MA5311_DAC_1B_BASS_SPK7: + case MA5311_DAC_23_COMP_LIM1 ... MA5311_DAC_26_COMP_LIM4: + case MA5311_DAC_2B_EQ_MODE ... MA5311_DAC_30_EQ_GRAPHIC5: + case MA5311_DAC_33_FLL_CTRL3 ... MA5311_DAC_3D_TEST3: + case MA5311_DAC_40_EQ_CTRL1 ... MA5311_DAC_8F_PLL_F3_P_CP: + case MA5311_DAC_91_ADC_DAC_MIX: + case MA5311_DAC_A1_TOP_MAN1_FOR_SDO ... MA5311_DAC_B5_MCLKO_TEST: + case MA5311_DAC_B7_TOP_MAN4 ... MA5311_DAC_B9_PLL_A_SETTING: + case MA5311_DAC_BB_CLASS_G_LEVEL1 ... MA5311_DAC_BF_POWER_METER: + break; + default: + return false; + } + + return true; +} + +static bool ma5311_ctrl_volatile_register(struct device *dev, unsigned int reg) +{ + if (reg > MA5311_DAC_FF_VERSION) + return false; + + switch (reg) { + case MA5311_DAC_EA_DAC_STATUS ... MA5311_DAC_EC_DAC_SCP_STATUS: + case MA5311_DAC_FB_STATUS2 ... MA5311_DAC_FD_POWER_METER_DISPLAY: + case MA5311_DAC_FF_VERSION: + break; + default: + return false; + } + + return true; +} + +static bool ma5311_adc_readable_register(struct device *dev, unsigned int reg) +{ + if (reg > MA5311_ADC_CH4_3F_OUTPUT_FORMAT) + return false; + + switch (reg) { + case MA5311_ADC_CH1_00_GENERAL_SETTING ... MA5311_ADC_CH4_3F_OUTPUT_FORMAT: + break; + default: + return false; + } + + return true; +} + +static bool ma5311_adc_writeable_register(struct device *dev, unsigned int reg) +{ + if (reg > MA5311_ADC_CH4_3F_OUTPUT_FORMAT) + return false; + + switch (reg) { + case MA5311_ADC_CH1_00_GENERAL_SETTING ... MA5311_ADC_CH4_3F_OUTPUT_FORMAT: + break; + default: + return false; + } + + return true; +} + +static const DECLARE_TLV_DB_RANGE(ma5311_adc_vol_tlv, + 0x00, 0xef, TLV_DB_MINMAX_ITEM(-7200, 1763), + 0xf0, 0xff, TLV_DB_SCALE_ITEM(1763, 0, 0)); + +static const DECLARE_TLV_DB_RANGE(ma5311_adc_pga_tlv, + 0x00, 0x3b, TLV_DB_MINMAX_ITEM(-1200, 3225), + 0x3c, 0x3f, TLV_DB_SCALE_ITEM(3225, 0, 0)); + +static const DECLARE_TLV_DB_RANGE(ma5311_spk_tlv, + 0x00, 0xa8, TLV_DB_MINMAX_ITEM(-6000, 2400), + 0xa9, 0xff, TLV_DB_SCALE_ITEM(-6000, 0, 0)); + +static const char *const ma5311_aif_in_source_text[] = { + "Mono Both", "Stereo", +}; + +static const char *const ma5311_rx_slot_text[] = { + "None", "Slot01", "Slot23", "Slot45", "Slot67", +}; + +static const char *const ma5311_reset_text[] = { + "idle", "reset", +}; + +static const unsigned int ma5311_tdm_rx_slot_values[] = { + MA5311_DISABLE_TDM_SLOT, + MA5311_TDM_SLOT0_RX_POS_0 | MA5311_TDM_SLOT1_RX_POS_1, + MA5311_TDM_SLOT0_RX_POS_2 | MA5311_TDM_SLOT1_RX_POS_3, + MA5311_TDM_SLOT0_RX_POS_4 | MA5311_TDM_SLOT1_RX_POS_5, + MA5311_TDM_SLOT0_RX_POS_6 | MA5311_TDM_SLOT1_RX_POS_7, +}; + +static const struct soc_enum ma5311_reset_enum = + SOC_ENUM_SINGLE_EXT(ARRAY_SIZE(ma5311_reset_text), ma5311_reset_text); + +static SOC_ENUM_SINGLE_VIRT_DECL(ma5311_aif_in_source_enum, + ma5311_aif_in_source_text); + +static const struct soc_enum ma5311_rx_slot_enum = + SOC_VALUE_ENUM_SINGLE(MA5311_DAC_37_TDM1, 0, + MA5311_TDM_SLOT0_RX_POS_MASK | + MA5311_TDM_SLOT1_RX_POS_MASK, + ARRAY_SIZE(ma5311_rx_slot_text), + ma5311_rx_slot_text, + ma5311_tdm_rx_slot_values); + +static void ma5311_restore_dai_config(struct ma5311_priv *ma5311) +{ + /* Restore clock settings without powering up the chip or PLL. */ + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_00_SYSTEM_CTRL1, + MA5311_DAC_CLKSYSTEM_MASK, + ma5311->dai_sys_clk); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_01_INPUT1_CTRL1, + MA5311_LEFTPOL_MASK | + MA5311_SCK_RISING_MASK | + MA5311_CONTROLLER_DEVICE_MASK, + ma5311->dai_leftpol | + ma5311->dai_sck_edge | + ma5311->dai_clk_mode); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_0E_MUTE_VOL_CTRL, + MA5311_DAC_MUTE_VOL_MASK, + ma5311->dai_spk_mute); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_37_TDM1, + MA5311_TDM_SLOT0_RX_POS_MASK | + MA5311_TDM_SLOT1_RX_POS_MASK, + ma5311->dai_tdm1_rx_pos); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_38_TDM2, + MA5311_DAC_38_DATA_LEN_MASK | + MA5311_ADC_TDM2_SETTING_MASK, + ma5311->dai_tdm2_data_len | + ma5311->dai_tdm2_capture_cfg); + + regmap_write(ma5311->ctrl_regmap, + MA5311_DAC_39_DATA_PATH, + ma5311->dai_data_path); + + regmap_write(ma5311->ctrl_regmap, + MA5311_DAC_3A_TDM_SLOT_ENABLE, + ma5311->dai_tdm_slot_enable); + + regmap_write(ma5311->ctrl_regmap, + MA5311_DAC_8B_PLL_POST_N, + ma5311->dai_pll_post_n); + + regmap_write(ma5311->ctrl_regmap, + MA5311_DAC_8C_PLL_N, + ma5311->dai_pll_n); + + regmap_write(ma5311->ctrl_regmap, + MA5311_DAC_8D_PLL_F1, + ma5311->dai_pll_f1); + + regmap_write(ma5311->ctrl_regmap, + MA5311_DAC_8E_PLL_F2, + ma5311->dai_pll_f2); + + regmap_write(ma5311->ctrl_regmap, + MA5311_DAC_8F_PLL_F3_P_CP, + ma5311->dai_pll_f3_p_cp); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_91_ADC_DAC_MIX, + MA5311_DAC_ADC_DAC_MIX_CH_MASK, + ma5311->dai_adc_mix_ch); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A1_TOP_MAN1_FOR_SDO, + MA5311_TOP_MAN1_SOO_LENGTH_MASK | + MA5311_DAC_A1_SCK_RATE_MASK | + MA5311_TOP_MAN1_O_FORMAT_MASK, + ma5311->dai_sdo_len | + ma5311->dai_sck_rate | + ma5311->dai_o_format); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A2_TOP_MAN2, + MA5311_DAC_PLLIN_CLK_MASK | + MA5311_DAC_PLL_REF_CLK1_MASK | + MA5311_DAC_PLL_REF_CLK2_MASK, + ma5311->dai_pll_input); + + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH1_0F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_WORD_LENGTH_MASK | + MA5311_ADC_OUTPUT_SCK_RATE_MASK, + ma5311->dai_adc1_word_len | + ma5311->dai_adc1_sck_rate); + + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH2_1F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_WORD_LENGTH_MASK | + MA5311_ADC_OUTPUT_SCK_RATE_MASK, + ma5311->dai_adc2_word_len | + ma5311->dai_adc2_sck_rate); + + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH3_2F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_WORD_LENGTH_MASK | + MA5311_ADC_OUTPUT_SCK_RATE_MASK, + ma5311->dai_adc3_word_len | + ma5311->dai_adc3_sck_rate); + + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH4_3F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_WORD_LENGTH_MASK | + MA5311_ADC_OUTPUT_SCK_RATE_MASK, + ma5311->dai_adc4_word_len | + ma5311->dai_adc4_sck_rate); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_B8_TOP_MAN5, + MA5311_LRCK_SCK_MAS_CLK_SEL_MASK | + MA5311_DAC_ADC_CLK_ON_MASK, + ma5311->dai_mas_clk_sel | ma5311->dai_adc_clk); +} + +static int ma5311_reset(struct snd_soc_component *component) +{ + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + unsigned int status, revision, i; + int ret; + + ret = regmap_read(ma5311->ctrl_regmap, MA5311_DAC_FF_VERSION, &status); + if (ret) { + dev_err(component->dev, "Register read operation failed\n"); + return ret; + } + + revision = status & MA5311_REV_NUM_STATUS; + dev_dbg(component->dev, "MA5311 revision: %u\n", revision); + + /* + * Critical register settings including speaker, ADC, PGA gains are + * following factory defaults, while rest of settings are fixed + * in practical settings including data format and path settings. + */ + + for (i = 0; i < ARRAY_SIZE(ma5311_ctrl_reg_def); i++) { + regmap_write(ma5311->ctrl_regmap, + ma5311_ctrl_reg_def[i].reg, + ma5311_ctrl_reg_def[i].def); + } + + for (i = 0; i < ARRAY_SIZE(ma5311_adc_reg_def); i++) { + regmap_write(ma5311->adc_regmap, + ma5311_adc_reg_def[i].reg, + ma5311_adc_reg_def[i].def); + } + + if (ma5311->flag_ext_rst) + ma5311_restore_dai_config(ma5311); + + return 0; +} + +static int ma5311_adc_volume_control_get(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + struct snd_soc_component *component = snd_kcontrol_chip(kcontrol); + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + const struct soc_mixer_control *mc = + (const struct soc_mixer_control *)kcontrol->private_value; + unsigned int val; + int ret; + + ret = regmap_read(ma5311->adc_regmap, mc->reg, &val); + if (ret) + return ret; + + ucontrol->value.integer.value[0] = val & MA5311_ADC_VOL_CTRL_MASK; + + return 0; +} + +static int ma5311_adc_volume_control_put(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + struct snd_soc_component *component = snd_kcontrol_chip(kcontrol); + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + const struct soc_mixer_control *mc = + (const struct soc_mixer_control *)kcontrol->private_value; + long input = ucontrol->value.integer.value[0]; + unsigned int val; + bool changed; + int ret; + + if (input < 0 || input > MA5311_ADC_VOL_CTRL_MASK) + return -EINVAL; + + val = input; + + ret = regmap_update_bits_check(ma5311->adc_regmap, mc->reg, + MA5311_ADC_VOL_CTRL_MASK, val, &changed); + if (ret) + return ret; + + return changed; +} + +static int ma5311_adc_pga_control_get(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + struct snd_soc_component *component = snd_kcontrol_chip(kcontrol); + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + const struct soc_mixer_control *mc = + (const struct soc_mixer_control *)kcontrol->private_value; + unsigned int val; + int ret; + + ret = regmap_read(ma5311->adc_regmap, mc->reg, &val); + if (ret) + return ret; + + ucontrol->value.integer.value[0] = val & MA5311_ADC_PGA_CTRL_MASK; + + return 0; +} + +static int ma5311_adc_pga_control_put(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + struct snd_soc_component *component = snd_kcontrol_chip(kcontrol); + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + const struct soc_mixer_control *mc = + (const struct soc_mixer_control *)kcontrol->private_value; + long input = ucontrol->value.integer.value[0]; + unsigned int val; + int ret; + bool changed; + + if (input < 0 || input > MA5311_ADC_PGA_CTRL_MASK) + return -EINVAL; + + val = input; + + ret = regmap_update_bits_check(ma5311->adc_regmap, mc->reg, + MA5311_ADC_PGA_CTRL_MASK, val, &changed); + if (ret) + return ret; + + return changed; +} + +static int ma5311_startup(struct snd_soc_component *component) +{ + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A2_TOP_MAN2, + MA5311_PLL_MASK, MA5311_PLL_ON); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_00_SYSTEM_CTRL1, + MA5311_POWER_MASK, MA5311_POWER_ON); + + if (ma5311->amp_mode == MA5311_MONO_BOTH_MODE) { + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_10_SYSTEM_CTRL3, + MA5311_SPK_MODE_MASK, + MA5311_SPK_MONO_BOTH); + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_37_TDM1, + MA5311_DAC_TDM_STEREO_MASK, + MA5311_DAC_TDM_MONO); + } else { + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_10_SYSTEM_CTRL3, + MA5311_SPK_MODE_MASK, + MA5311_SPK_STEREO); + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_37_TDM1, + MA5311_DAC_TDM_STEREO_MASK, + MA5311_DAC_TDM_STEREO); + } + + ma5311->amp_power_status = true; + msleep(55); + + return 0; +} + +static int ma5311_shutdown(struct snd_soc_component *component) +{ + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + + regmap_update_bits(ma5311->ctrl_regmap, MA5311_DAC_0E_MUTE_VOL_CTRL, + MA5311_DAC_MUTE_VOL_MASK, MA5311_SPK_MUTE); + + msleep(55); + + regmap_update_bits(ma5311->ctrl_regmap, MA5311_DAC_10_SYSTEM_CTRL3, + MA5311_SPK_MODE_MASK, MA5311_SPK_OFF); + + ma5311->amp_power_status = false; + + /* Capture shares the PLL and global power with playback. */ + if (!ma5311->adc_power_status) { + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A2_TOP_MAN2, + MA5311_PLL_MASK, MA5311_PLL_OFF); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_00_SYSTEM_CTRL1, + MA5311_POWER_MASK, MA5311_POWER_OFF); + } + + return 0; +} + +static int ma5311_reset_control_get(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + struct snd_soc_component *component = snd_kcontrol_chip(kcontrol); + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + + if (!ma5311->reset_gpio) + return -ENODEV; + + ucontrol->value.enumerated.item[0] = 0; + + return 0; +} + +static int ma5311_reset_control_put(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + struct snd_soc_component *component = snd_kcontrol_chip(kcontrol); + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + struct snd_soc_dapm_context *dapm = + snd_soc_component_to_dapm(component); + struct snd_kcontrol *slot_control; + unsigned int val = ucontrol->value.enumerated.item[0]; + unsigned int rx_slot; + int ret = 0; + + if (!val) + return 0; + + if (!ma5311->reset_gpio) + return -ENODEV; + + if (val >= ARRAY_SIZE(ma5311_reset_text)) + return -EINVAL; + + slot_control = snd_soc_card_get_kcontrol(component->card, + "RX Slot Configuration"); + if (!slot_control) + return -ENOENT; + + snd_soc_dpcm_mutex_lock(component->card); + snd_soc_dapm_mutex_lock(dapm); + + if (ma5311->amp_power_status || ma5311->adc_power_status) { + dev_warn(component->dev, + "Reset denied: playback or capture path is powered\n"); + ret = -EBUSY; + goto unlock; + } + + if (snd_soc_component_active(component)) { + dev_warn(component->dev, + "Reset denied: pcm stream is in active state\n"); + ret = -EBUSY; + goto unlock; + } + + gpiod_set_value_cansleep(ma5311->reset_gpio, 1); + msleep(MA5311_RESET_ASSERT_MS); + + gpiod_set_value_cansleep(ma5311->reset_gpio, 0); + msleep(MA5311_RESET_RECOVERY_MS); + + rx_slot = snd_soc_dapm_kcontrol_get_value(slot_control); + rx_slot &= MA5311_TDM_SLOT0_RX_POS_MASK | + MA5311_TDM_SLOT1_RX_POS_MASK; + ma5311->dai_tdm1_rx_pos = rx_slot; + + ma5311->flag_ext_rst = true; + ret = ma5311_reset(component); + ma5311->flag_ext_rst = false; + +unlock: + snd_soc_dapm_mutex_unlock(dapm); + snd_soc_dpcm_mutex_unlock(component->card); + + return ret; +} + +static const struct snd_kcontrol_new ma5311_reset_controls[] = { + SOC_ENUM_EXT(MA5311_RESET_CTRL_NAME, ma5311_reset_enum, + ma5311_reset_control_get, ma5311_reset_control_put), +}; + +static const struct snd_kcontrol_new ma5311_snd_controls[] = { + SOC_SINGLE_TLV(MA5311_LEFT_VOL_CTRL_NAME, MA5311_DAC_0A_SPK_VOL_L, 0, + 168, 1, ma5311_spk_tlv), + SOC_SINGLE_TLV(MA5311_RIGHT_VOL_CTRL_NAME, MA5311_DAC_0B_SPK_VOL_R, 0, + 168, 1, ma5311_spk_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC1_LEFT_VOL_CTRL_NAME, + MA5311_ADC_CH1_07_VOLUME_LEFT, 0, + MA5311_ADC_VOL_CTRL_MASK, 0, + ma5311_adc_volume_control_get, + ma5311_adc_volume_control_put, ma5311_adc_vol_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC1_RIGHT_VOL_CTRL_NAME, + MA5311_ADC_CH1_08_VOLUME_RIGHT, 0, + MA5311_ADC_VOL_CTRL_MASK, 0, + ma5311_adc_volume_control_get, + ma5311_adc_volume_control_put, ma5311_adc_vol_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC2_LEFT_VOL_CTRL_NAME, + MA5311_ADC_CH2_17_VOLUME_LEFT, 0, + MA5311_ADC_VOL_CTRL_MASK, 0, + ma5311_adc_volume_control_get, + ma5311_adc_volume_control_put, ma5311_adc_vol_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC2_RIGHT_VOL_CTRL_NAME, + MA5311_ADC_CH2_18_VOLUME_RIGHT, 0, + MA5311_ADC_VOL_CTRL_MASK, 0, + ma5311_adc_volume_control_get, + ma5311_adc_volume_control_put, ma5311_adc_vol_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC3_LEFT_VOL_CTRL_NAME, + MA5311_ADC_CH3_27_VOLUME_LEFT, 0, + MA5311_ADC_VOL_CTRL_MASK, 0, + ma5311_adc_volume_control_get, + ma5311_adc_volume_control_put, ma5311_adc_vol_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC3_RIGHT_VOL_CTRL_NAME, + MA5311_ADC_CH3_28_VOLUME_RIGHT, 0, + MA5311_ADC_VOL_CTRL_MASK, 0, + ma5311_adc_volume_control_get, + ma5311_adc_volume_control_put, ma5311_adc_vol_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC4_LEFT_VOL_CTRL_NAME, + MA5311_ADC_CH4_37_VOLUME_LEFT, 0, + MA5311_ADC_VOL_CTRL_MASK, 0, + ma5311_adc_volume_control_get, + ma5311_adc_volume_control_put, ma5311_adc_vol_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC4_RIGHT_VOL_CTRL_NAME, + MA5311_ADC_CH4_38_VOLUME_RIGHT, 0, + MA5311_ADC_VOL_CTRL_MASK, 0, + ma5311_adc_volume_control_get, + ma5311_adc_volume_control_put, ma5311_adc_vol_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC1_LEFT_PGA_CTRL_NAME, + MA5311_ADC_CH1_09_PGA_LEFT, 0, + MA5311_ADC_PGA_CTRL_MASK, 0, + ma5311_adc_pga_control_get, + ma5311_adc_pga_control_put, ma5311_adc_pga_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC1_RIGHT_PGA_CTRL_NAME, + MA5311_ADC_CH1_0A_PGA_RIGHT, 0, + MA5311_ADC_PGA_CTRL_MASK, 0, + ma5311_adc_pga_control_get, + ma5311_adc_pga_control_put, ma5311_adc_pga_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC2_LEFT_PGA_CTRL_NAME, + MA5311_ADC_CH2_19_PGA_LEFT, 0, + MA5311_ADC_PGA_CTRL_MASK, 0, + ma5311_adc_pga_control_get, + ma5311_adc_pga_control_put, ma5311_adc_pga_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC2_RIGHT_PGA_CTRL_NAME, + MA5311_ADC_CH2_1A_PGA_RIGHT, 0, + MA5311_ADC_PGA_CTRL_MASK, 0, + ma5311_adc_pga_control_get, + ma5311_adc_pga_control_put, ma5311_adc_pga_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC3_LEFT_PGA_CTRL_NAME, + MA5311_ADC_CH3_29_PGA_LEFT, 0, + MA5311_ADC_PGA_CTRL_MASK, 0, + ma5311_adc_pga_control_get, + ma5311_adc_pga_control_put, ma5311_adc_pga_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC3_RIGHT_PGA_CTRL_NAME, + MA5311_ADC_CH3_2A_PGA_RIGHT, 0, + MA5311_ADC_PGA_CTRL_MASK, 0, + ma5311_adc_pga_control_get, + ma5311_adc_pga_control_put, ma5311_adc_pga_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC4_LEFT_PGA_CTRL_NAME, + MA5311_ADC_CH4_39_PGA_LEFT, 0, + MA5311_ADC_PGA_CTRL_MASK, 0, + ma5311_adc_pga_control_get, + ma5311_adc_pga_control_put, ma5311_adc_pga_tlv), + + SOC_SINGLE_EXT_TLV(MA5311_ADC4_RIGHT_PGA_CTRL_NAME, + MA5311_ADC_CH4_3A_PGA_RIGHT, 0, + MA5311_ADC_PGA_CTRL_MASK, 0, + ma5311_adc_pga_control_get, + ma5311_adc_pga_control_put, ma5311_adc_pga_tlv), +}; + +static int ma5311_dapm_aif_in_put(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + struct snd_soc_dapm_context *dapm = + snd_soc_dapm_kcontrol_to_dapm(kcontrol); + struct snd_soc_component *component = snd_soc_dapm_to_component(dapm); + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + unsigned int val = ucontrol->value.enumerated.item[0]; + unsigned int old_val = snd_soc_dapm_kcontrol_get_value(kcontrol); + + if (val >= ARRAY_SIZE(ma5311_aif_in_source_text)) { + dev_err(ma5311->dev, "%s: Out of range\n", __func__); + return -EINVAL; + } + + if (old_val == val) + return 0; + + if (ma5311->amp_power_status) { + dev_warn(ma5311->dev, + "Cannot change AIF IN Source during playback\n"); + return -EBUSY; + } + + return snd_soc_dapm_put_enum_double(kcontrol, ucontrol); +} + +static const struct snd_kcontrol_new ma5311_aif_in_source_control = { + .iface = SNDRV_CTL_ELEM_IFACE_MIXER, + .name = MA5311_AIF_IN_NAME, + .info = snd_soc_info_enum_double, + .get = snd_soc_dapm_get_enum_double, + .put = ma5311_dapm_aif_in_put, + .private_value = (unsigned long)&ma5311_aif_in_source_enum, +}; + +static const struct snd_kcontrol_new ma5311_rx_slot_control = + SOC_DAPM_ENUM("Route", ma5311_rx_slot_enum); + +static int ma5311_aif_in_event(struct snd_soc_dapm_widget *w, + struct snd_kcontrol *kcontrol, int event) +{ + struct snd_soc_component *component = snd_soc_dapm_to_component(w->dapm); + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + unsigned int mux = snd_soc_dapm_kcontrol_get_value(w->kcontrols[0]); + + switch (event) { + case SND_SOC_DAPM_PRE_PMU: + switch (mux) { + case MA5311_MONO_BOTH_MODE: + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_10_SYSTEM_CTRL3, + MA5311_SPK_MODE_MASK, + MA5311_SPK_MONO_BOTH); + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_37_TDM1, + MA5311_DAC_TDM_STEREO_MASK, + MA5311_DAC_TDM_MONO); + break; + case MA5311_STEREO_MODE: + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_10_SYSTEM_CTRL3, + MA5311_SPK_MODE_MASK, + MA5311_SPK_STEREO); + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_37_TDM1, + MA5311_DAC_TDM_STEREO_MASK, + MA5311_DAC_TDM_STEREO); + break; + default: + dev_err(ma5311->dev, "%s: Invalid value (%u)\n", + __func__, mux); + return -EINVAL; + } + + ma5311->amp_mode = mux; + break; + } + + return 0; +} + +static int ma5311_power_event(struct snd_soc_dapm_widget *w, + struct snd_kcontrol *kcontrol, int event) +{ + struct snd_soc_component *component = snd_soc_dapm_to_component(w->dapm); + + switch (event) { + case SND_SOC_DAPM_POST_PMU: + return ma5311_startup(component); + case SND_SOC_DAPM_PRE_PMD: + return ma5311_shutdown(component); + } + + return 0; +} + +static int ma5311_adc_event(struct snd_soc_dapm_widget *w, + struct snd_kcontrol *kcontrol, int event) +{ + struct snd_soc_component *component = snd_soc_dapm_to_component(w->dapm); + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + unsigned int format = ma5311->format; + + switch (event) { + case SND_SOC_DAPM_PRE_PMU: + regmap_update_bits(ma5311->ctrl_regmap, MA5311_DAC_A2_TOP_MAN2, + MA5311_PLL_MASK, MA5311_PLL_ON); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_00_SYSTEM_CTRL1, + MA5311_POWER_MASK, MA5311_POWER_ON); + + switch (format) { + case SND_SOC_DAIFMT_I2S: + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH1_00_GENERAL_SETTING, + MA5311_ADC_POWER_MASK, + MA5311_ADC_POWER_ON); + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH1_0E_MUTE_DATA_FLOW, + MA5311_ADC_MUTE_BOTH_MASK, + MA5311_ADC_BOTH_DEMUTE); + break; + case SND_SOC_DAIFMT_DSP_A: + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH1_00_GENERAL_SETTING, + MA5311_ADC_POWER_MASK, + MA5311_ADC_POWER_ON); + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH1_0E_MUTE_DATA_FLOW, + MA5311_ADC_MUTE_BOTH_MASK, + MA5311_ADC_BOTH_DEMUTE); + + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH2_10_GENERAL_SETTING, + MA5311_ADC_POWER_MASK, + MA5311_ADC_POWER_ON); + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH2_1E_MUTE_DATA_FLOW, + MA5311_ADC_MUTE_BOTH_MASK, + MA5311_ADC_BOTH_DEMUTE); + + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH3_20_GENERAL_SETTING, + MA5311_ADC_POWER_MASK, + MA5311_ADC_POWER_ON); + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH3_2E_MUTE_DATA_FLOW, + MA5311_ADC_MUTE_BOTH_MASK, + MA5311_ADC_BOTH_DEMUTE); + + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH4_30_GENERAL_SETTING, + MA5311_ADC_POWER_MASK, + MA5311_ADC_POWER_ON); + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH4_3E_MUTE_DATA_FLOW, + MA5311_ADC_MUTE_BOTH_MASK, + MA5311_ADC_BOTH_DEMUTE); + break; + default: + dev_err(ma5311->dev, "%s: Invalid value (%u)\n", + __func__, format); + return -EINVAL; + } + + ma5311->adc_power_status = true; + break; + + case SND_SOC_DAPM_POST_PMD: + switch (format) { + case SND_SOC_DAIFMT_I2S: + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH1_0E_MUTE_DATA_FLOW, + MA5311_ADC_MUTE_BOTH_MASK, + MA5311_ADC_BOTH_MUTE); + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH1_00_GENERAL_SETTING, + MA5311_ADC_POWER_MASK, + MA5311_ADC_POWER_DOWN); + break; + case SND_SOC_DAIFMT_DSP_A: + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH1_0E_MUTE_DATA_FLOW, + MA5311_ADC_MUTE_BOTH_MASK, + MA5311_ADC_BOTH_MUTE); + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH1_00_GENERAL_SETTING, + MA5311_ADC_POWER_MASK, + MA5311_ADC_POWER_DOWN); + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH2_1E_MUTE_DATA_FLOW, + MA5311_ADC_MUTE_BOTH_MASK, + MA5311_ADC_BOTH_MUTE); + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH2_10_GENERAL_SETTING, + MA5311_ADC_POWER_MASK, + MA5311_ADC_POWER_DOWN); + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH3_2E_MUTE_DATA_FLOW, + MA5311_ADC_MUTE_BOTH_MASK, + MA5311_ADC_BOTH_MUTE); + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH3_20_GENERAL_SETTING, + MA5311_ADC_POWER_MASK, + MA5311_ADC_POWER_DOWN); + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH4_3E_MUTE_DATA_FLOW, + MA5311_ADC_MUTE_BOTH_MASK, + MA5311_ADC_BOTH_MUTE); + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH4_30_GENERAL_SETTING, + MA5311_ADC_POWER_MASK, + MA5311_ADC_POWER_DOWN); + break; + default: + dev_err(ma5311->dev, "%s: Invalid value (%u)\n", + __func__, format); + return -EINVAL; + } + + ma5311->adc_power_status = false; + + if (!ma5311->amp_power_status) { + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A2_TOP_MAN2, + MA5311_PLL_MASK, MA5311_PLL_OFF); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_00_SYSTEM_CTRL1, + MA5311_POWER_MASK, MA5311_POWER_OFF); + } + } + + return 0; +} + +static const struct snd_soc_dapm_widget ma5311_dapm_widgets[] = { + /* Playback */ + SND_SOC_DAPM_AIF_IN("AIF IN", "Playback", 0, SND_SOC_NOPM, 0, 0), + SND_SOC_DAPM_MUX_E("AIF IN Source", SND_SOC_NOPM, 0, 0, + &ma5311_aif_in_source_control, ma5311_aif_in_event, + SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU), + SND_SOC_DAPM_MUX("RX Slot Configuration", SND_SOC_NOPM, 0, 0, + &ma5311_rx_slot_control), + SND_SOC_DAPM_OUT_DRV_E("AMP Power", SND_SOC_NOPM, 0, 0, NULL, 0, + ma5311_power_event, + SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD), + SND_SOC_DAPM_OUTPUT("AOUT1L"), + SND_SOC_DAPM_OUTPUT("AOUT1R"), + + /* Capture */ + SND_SOC_DAPM_INPUT("ADC IN"), + SND_SOC_DAPM_ADC_E("ADC", NULL, SND_SOC_NOPM, 0, 0, ma5311_adc_event, + SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), + SND_SOC_DAPM_AIF_OUT("AIF OUT", "Capture", 0, SND_SOC_NOPM, 0, 0), +}; + +static const struct snd_soc_dapm_route ma5311_dapm_routes[] = { + /* Playback */ + { "AIF IN Source", "Mono Both", "AIF IN" }, + { "AIF IN Source", "Stereo", "AIF IN" }, + + { "RX Slot Configuration", "None", "AIF IN Source" }, + { "RX Slot Configuration", "Slot01", "AIF IN Source" }, + { "RX Slot Configuration", "Slot23", "AIF IN Source" }, + { "RX Slot Configuration", "Slot45", "AIF IN Source" }, + { "RX Slot Configuration", "Slot67", "AIF IN Source" }, + + { "AMP Power", NULL, "RX Slot Configuration" }, + + { "AOUT1L", NULL, "AMP Power" }, + { "AOUT1R", NULL, "AMP Power" }, + + /* Capture */ + { "ADC", NULL, "ADC IN" }, + { "AIF OUT", NULL, "ADC" }, +}; + +static int ma5311_probe(struct snd_soc_component *component) +{ + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + int ret; + + if (ma5311->reset_gpio) { + ret = snd_soc_add_component_controls(component, + ma5311_reset_controls, + ARRAY_SIZE(ma5311_reset_controls)); + if (ret) + return ret; + } + + return ma5311_reset(component); +} + +static const struct snd_soc_component_driver ma5311_component = { + .probe = ma5311_probe, + .controls = ma5311_snd_controls, + .num_controls = ARRAY_SIZE(ma5311_snd_controls), + .dapm_widgets = ma5311_dapm_widgets, + .num_dapm_widgets = ARRAY_SIZE(ma5311_dapm_widgets), + .dapm_routes = ma5311_dapm_routes, + .num_dapm_routes = ARRAY_SIZE(ma5311_dapm_routes), +}; + +static const struct regmap_config ma5311_ctrl_regmap_config = { + .reg_bits = 8, + .val_bits = 8, + + .max_register = MA5311_DAC_FF_VERSION, + .readable_reg = ma5311_ctrl_readable_register, + .writeable_reg = ma5311_ctrl_writeable_register, + .volatile_reg = ma5311_ctrl_volatile_register, + + .cache_type = REGCACHE_FLAT, + .reg_defaults = ma5311_ctrl_reg_def, + .num_reg_defaults = ARRAY_SIZE(ma5311_ctrl_reg_def), +}; + +static const struct regmap_config ma5311_adc_regmap_config = { + .reg_bits = 8, + .val_bits = 8, + + .max_register = MA5311_ADC_CH4_3F_OUTPUT_FORMAT, + .readable_reg = ma5311_adc_readable_register, + .writeable_reg = ma5311_adc_writeable_register, + + .cache_type = REGCACHE_FLAT, + .reg_defaults = ma5311_adc_reg_def, + .num_reg_defaults = ARRAY_SIZE(ma5311_adc_reg_def), +}; + +static int ma5311_setup_pll(struct snd_soc_component *component, + unsigned int bclk) +{ + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + unsigned int i = 0; + unsigned int pll_post_n; + unsigned int pll_n; + unsigned int pll_f1; + unsigned int pll_f2; + unsigned int pll_f3_p_cp; + + dev_dbg(component->dev, "PLL input BCLK: %u Hz\n", bclk); + + if (ma5311->sys_clk_id == MA5311_PLL_CLKIN_BCLK) { + for (i = 0; i < ma5311->num_of_pll_matches; i++) { + if (ma5311->pll_matches[i].input_clk == bclk) + break; + } + + if (i == ma5311->num_of_pll_matches) { + dev_warn(component->dev, + "%s: No matching value between pll table and SCK\n", + __func__); + return -EINVAL; + } + + pll_post_n = ma5311->pll_matches[i].post_n; + pll_n = ma5311->pll_matches[i].n; + pll_f1 = ma5311->pll_matches[i].f1; + pll_f2 = ma5311->pll_matches[i].f2; + pll_f3_p_cp = ma5311->pll_matches[i].f3_p_cp; + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A2_TOP_MAN2, + MA5311_DAC_PLLIN_CLK_MASK, + MA5311_DAC_PLLIN_EXT_OSC); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A2_TOP_MAN2, + MA5311_DAC_PLL_REF_CLK1_MASK, + MA5311_DAC_PLL_REF_EXT_CLK); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A2_TOP_MAN2, + MA5311_DAC_PLL_REF_CLK2_MASK, + MA5311_DAC_PLL_REF_CLK2_SCK); + + ma5311->dai_pll_input = MA5311_DAC_PLLIN_EXT_OSC | + MA5311_DAC_PLL_REF_EXT_CLK | + MA5311_DAC_PLL_REF_CLK2_SCK; + } else if (ma5311->sys_clk_id == MA5311_INTERNAL_OSC) { + pll_post_n = MA5311_INT_OSC_POST_N; + pll_n = MA5311_INT_OSC_N; + pll_f1 = MA5311_INT_OSC_F1; + pll_f2 = MA5311_INT_OSC_F2; + pll_f3_p_cp = MA5311_INT_OSC_F3_P_CP; + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A2_TOP_MAN2, + MA5311_DAC_PLLIN_CLK_MASK, + MA5311_DAC_PLLIN_INT_OSC); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A2_TOP_MAN2, + MA5311_DAC_PLL_REF_CLK1_MASK, + MA5311_DAC_PLL_REF_INT_OSC); + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A2_TOP_MAN2, + MA5311_DAC_PLL_REF_CLK2_MASK, + MA5311_DAC_PLL_REF_CLK2_REF1); + + ma5311->dai_pll_input = MA5311_DAC_PLLIN_INT_OSC | + MA5311_DAC_PLL_REF_INT_OSC | + MA5311_DAC_PLL_REF_CLK2_REF1; + } else { + return 0; + } + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A2_TOP_MAN2, + MA5311_PLL_MASK, MA5311_PLL_ON); + + regmap_write(ma5311->ctrl_regmap, MA5311_DAC_8B_PLL_POST_N, + pll_post_n); + ma5311->dai_pll_post_n = pll_post_n; + + regmap_write(ma5311->ctrl_regmap, MA5311_DAC_8C_PLL_N, + pll_n); + ma5311->dai_pll_n = pll_n; + + regmap_write(ma5311->ctrl_regmap, MA5311_DAC_8D_PLL_F1, + pll_f1); + ma5311->dai_pll_f1 = pll_f1; + + regmap_write(ma5311->ctrl_regmap, MA5311_DAC_8E_PLL_F2, + pll_f2); + ma5311->dai_pll_f2 = pll_f2; + + regmap_write(ma5311->ctrl_regmap, MA5311_DAC_8F_PLL_F3_P_CP, + pll_f3_p_cp); + ma5311->dai_pll_f3_p_cp = pll_f3_p_cp; + + return 0; +} + +static int ma5311_dai_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params, + struct snd_soc_dai *dai) +{ + struct snd_soc_component *component = dai->component; + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + unsigned int bclk = 0; + unsigned int frame_size; + int ret; + + switch (params_rate(params)) { + case 48000: + break; + + default: + dev_err(component->dev, "%s: unsupported sample rate: %u\n", + __func__, params_rate(params)); + + return -EINVAL; + } + + if (params_channels(params) > 8) { + dev_err(component->dev, "%s: unsupported channel count: %u\n", + __func__, params_channels(params)); + + return -EINVAL; + } + + if (ma5311->format == SND_SOC_DAIFMT_DSP_A) { + if (ma5311->frame_size) + frame_size = ma5311->frame_size; + else + frame_size = params_channels(params) * + params_physical_width(params); + + bclk = params_rate(params) * frame_size; + dev_dbg(component->dev, "Estimated TDM BCLK: %u Hz\n", bclk); + } else if (ma5311->format == SND_SOC_DAIFMT_I2S) { + bclk = params_rate(params) * params_physical_width(params) * 2; + dev_dbg(component->dev, "Estimated I2S BCLK: %u Hz\n", bclk); + } else { + return -EINVAL; + } + + if (ma5311->sys_clk_id == MA5311_PLL_CLKIN_BCLK) { + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_00_SYSTEM_CTRL1, + MA5311_DAC_CLKSYSTEM_MASK, + MA5311_DAC_EXT_CLK_24_576); + ma5311->dai_sys_clk = MA5311_DAC_EXT_CLK_24_576; + } else { + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_00_SYSTEM_CTRL1, + MA5311_DAC_CLKSYSTEM_MASK, + MA5311_DAC_INT_OSCILLATOR); + ma5311->dai_sys_clk = MA5311_DAC_INT_OSCILLATOR; + } + + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { + if (ma5311->sys_clk_id == MA5311_PLL_CLKIN_BCLK && + ma5311->last_bclk != bclk) { + dev_dbg(component->dev, "Playback BCLK: %u Hz\n", bclk); + ret = ma5311_setup_pll(component, bclk); + + if (ret) { + ma5311->last_bclk = 0; + dev_err(component->dev, + "Failed to configure PLL: %d\n", ret); + return ret; + } + + ma5311->last_bclk = bclk; + } else if (ma5311->sys_clk_id == MA5311_INTERNAL_OSC) { + ret = ma5311_setup_pll(component, MA5311_DUMMY_BCLK); + + if (ret) { + ma5311->last_bclk = 0; + dev_err(component->dev, + "Failed to configure PLL: %d\n", ret); + return ret; + } + + ma5311->last_bclk = 0; + } + + switch (params_format(params)) { + case SNDRV_PCM_FORMAT_S16_LE: + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A1_TOP_MAN1_FOR_SDO, + MA5311_TOP_MAN1_SOO_LENGTH_MASK, + MA5311_TOP_MAN1_SDO_16B); + ma5311->dai_sdo_len = MA5311_TOP_MAN1_SDO_16B; + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A1_TOP_MAN1_FOR_SDO, + MA5311_DAC_A1_SCK_RATE_MASK, + MA5311_DAC_A1_SCK_RATE_32FS); + ma5311->dai_sck_rate = MA5311_DAC_A1_SCK_RATE_32FS; + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_38_TDM2, + MA5311_DAC_38_DATA_LEN_MASK, + MA5311_DAC_38_DATA_LEN_16); + ma5311->dai_tdm2_data_len = MA5311_DAC_38_DATA_LEN_16; + break; + + case SNDRV_PCM_FORMAT_S32_LE: + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A1_TOP_MAN1_FOR_SDO, + MA5311_TOP_MAN1_SOO_LENGTH_MASK, + MA5311_TOP_MAN1_SDO_24B); + ma5311->dai_sdo_len = MA5311_TOP_MAN1_SDO_24B; + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A1_TOP_MAN1_FOR_SDO, + MA5311_DAC_A1_SCK_RATE_MASK, + MA5311_DAC_A1_SCK_RATE_64FS); + ma5311->dai_sck_rate = MA5311_DAC_A1_SCK_RATE_64FS; + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_38_TDM2, + MA5311_DAC_38_DATA_LEN_MASK, + MA5311_DAC_38_DATA_LEN_32); + ma5311->dai_tdm2_data_len = MA5311_DAC_38_DATA_LEN_32; + break; + + default: + dev_err(component->dev, + "%s: unsupported PCM format: %d\n", __func__, + params_format(params)); + return -EINVAL; + } + + switch (ma5311->format) { + case SND_SOC_DAIFMT_I2S: + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_37_TDM1, + MA5311_TDM_SLOT0_RX_POS_MASK | + MA5311_TDM_SLOT1_RX_POS_MASK, + MA5311_DISABLE_TDM_SLOT); + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A1_TOP_MAN1_FOR_SDO, + MA5311_TOP_MAN1_O_FORMAT_MASK, + MA5311_TOP_MAN1_O_FORMAT_I2S); + ma5311->dai_tdm1_rx_pos = MA5311_DISABLE_TDM_SLOT; + ma5311->dai_o_format = MA5311_TOP_MAN1_O_FORMAT_I2S; + break; + + case SND_SOC_DAIFMT_DSP_A: + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A1_TOP_MAN1_FOR_SDO, + MA5311_TOP_MAN1_O_FORMAT_MASK, + MA5311_TOP_MAN1_O_FORMAT_TDM); + ma5311->dai_o_format = MA5311_TOP_MAN1_O_FORMAT_TDM; + break; + + default: + return -EINVAL; + } + } + + if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) { + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_B8_TOP_MAN5, + MA5311_DAC_ADC_CLK_ON_MASK, + MA5311_DAC_ADC_CLK_ON); + ma5311->dai_adc_clk = MA5311_DAC_ADC_CLK_ON; + + if (ma5311->sys_clk_id == MA5311_PLL_CLKIN_BCLK && + ma5311->last_bclk != bclk) { + dev_dbg(component->dev, "Capture BCLK: %u Hz\n", bclk); + ret = ma5311_setup_pll(component, bclk); + if (ret) { + ma5311->last_bclk = 0; + dev_err(component->dev, + "Failed to configure PLL: %d\n", ret); + return ret; + } + + ma5311->last_bclk = bclk; + } else if (ma5311->sys_clk_id == MA5311_INTERNAL_OSC) { + ret = ma5311_setup_pll(component, MA5311_DUMMY_BCLK); + + if (ret) { + ma5311->last_bclk = 0; + dev_err(component->dev, + "Failed to configure PLL: %d\n", ret); + return ret; + } + + ma5311->last_bclk = 0; + } + + switch (params_format(params)) { + case SNDRV_PCM_FORMAT_S16_LE: + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_38_TDM2, + MA5311_DAC_38_DATA_LEN_MASK, + MA5311_DAC_38_DATA_LEN_16); + ma5311->dai_tdm2_data_len = MA5311_DAC_38_DATA_LEN_16; + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A1_TOP_MAN1_FOR_SDO, + MA5311_TOP_MAN1_SOO_LENGTH_MASK, + MA5311_TOP_MAN1_SDO_16B); + ma5311->dai_sdo_len = MA5311_TOP_MAN1_SDO_16B; + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A1_TOP_MAN1_FOR_SDO, + MA5311_DAC_A1_SCK_RATE_MASK, + MA5311_DAC_A1_SCK_RATE_32FS); + ma5311->dai_sck_rate = MA5311_DAC_A1_SCK_RATE_32FS; + + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH1_0F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_WORD_LENGTH_MASK, + MA5311_ADC_WORD_LENGTH_16); + ma5311->dai_adc1_word_len = MA5311_ADC_WORD_LENGTH_16; + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH2_1F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_WORD_LENGTH_MASK, + MA5311_ADC_WORD_LENGTH_16); + ma5311->dai_adc2_word_len = MA5311_ADC_WORD_LENGTH_16; + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH3_2F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_WORD_LENGTH_MASK, + MA5311_ADC_WORD_LENGTH_16); + ma5311->dai_adc3_word_len = MA5311_ADC_WORD_LENGTH_16; + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH4_3F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_WORD_LENGTH_MASK, + MA5311_ADC_WORD_LENGTH_16); + ma5311->dai_adc4_word_len = MA5311_ADC_WORD_LENGTH_16; + + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH1_0F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_SCK_RATE_MASK, + MA5311_ADC_SCK_RATE_16BIT_CFG); + ma5311->dai_adc1_sck_rate = MA5311_ADC_SCK_RATE_16BIT_CFG; + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH2_1F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_SCK_RATE_MASK, + MA5311_ADC_SCK_RATE_16BIT_CFG); + ma5311->dai_adc2_sck_rate = MA5311_ADC_SCK_RATE_16BIT_CFG; + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH3_2F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_SCK_RATE_MASK, + MA5311_ADC_SCK_RATE_16BIT_CFG); + ma5311->dai_adc3_sck_rate = MA5311_ADC_SCK_RATE_16BIT_CFG; + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH4_3F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_SCK_RATE_MASK, + MA5311_ADC_SCK_RATE_16BIT_CFG); + ma5311->dai_adc4_sck_rate = MA5311_ADC_SCK_RATE_16BIT_CFG; + break; + + case SNDRV_PCM_FORMAT_S32_LE: + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_38_TDM2, + MA5311_DAC_38_DATA_LEN_MASK, + MA5311_DAC_38_DATA_LEN_32); + ma5311->dai_tdm2_data_len = MA5311_DAC_38_DATA_LEN_32; + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A1_TOP_MAN1_FOR_SDO, + MA5311_TOP_MAN1_SOO_LENGTH_MASK, + MA5311_TOP_MAN1_SDO_24B); + ma5311->dai_sdo_len = MA5311_TOP_MAN1_SDO_24B; + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A1_TOP_MAN1_FOR_SDO, + MA5311_DAC_A1_SCK_RATE_MASK, + MA5311_DAC_A1_SCK_RATE_64FS); + ma5311->dai_sck_rate = MA5311_DAC_A1_SCK_RATE_64FS; + + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH1_0F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_WORD_LENGTH_MASK, + MA5311_ADC_WORD_LENGTH_24); + ma5311->dai_adc1_word_len = MA5311_ADC_WORD_LENGTH_24; + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH2_1F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_WORD_LENGTH_MASK, + MA5311_ADC_WORD_LENGTH_24); + ma5311->dai_adc2_word_len = MA5311_ADC_WORD_LENGTH_24; + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH3_2F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_WORD_LENGTH_MASK, + MA5311_ADC_WORD_LENGTH_24); + ma5311->dai_adc3_word_len = MA5311_ADC_WORD_LENGTH_24; + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH4_3F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_WORD_LENGTH_MASK, + MA5311_ADC_WORD_LENGTH_24); + ma5311->dai_adc4_word_len = MA5311_ADC_WORD_LENGTH_24; + + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH1_0F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_SCK_RATE_MASK, + MA5311_ADC_SCK_RATE_24BIT_CFG); + ma5311->dai_adc1_sck_rate = MA5311_ADC_SCK_RATE_24BIT_CFG; + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH2_1F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_SCK_RATE_MASK, + MA5311_ADC_SCK_RATE_24BIT_CFG); + ma5311->dai_adc2_sck_rate = MA5311_ADC_SCK_RATE_24BIT_CFG; + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH3_2F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_SCK_RATE_MASK, + MA5311_ADC_SCK_RATE_24BIT_CFG); + ma5311->dai_adc3_sck_rate = MA5311_ADC_SCK_RATE_24BIT_CFG; + regmap_update_bits(ma5311->adc_regmap, + MA5311_ADC_CH4_3F_OUTPUT_FORMAT, + MA5311_ADC_OUTPUT_SCK_RATE_MASK, + MA5311_ADC_SCK_RATE_24BIT_CFG); + ma5311->dai_adc4_sck_rate = MA5311_ADC_SCK_RATE_24BIT_CFG; + break; + default: + dev_err(component->dev, + "%s: unsupported PCM format: %d\n", __func__, + params_format(params)); + return -EINVAL; + } + + switch (ma5311->format) { + case SND_SOC_DAIFMT_I2S: + dev_info(component->dev, "Working in I2S TX Mode\n"); + regmap_write(ma5311->ctrl_regmap, + MA5311_DAC_39_DATA_PATH, + MA5311_ADC_DATA_PATH_I2S); + ma5311->dai_data_path = MA5311_ADC_DATA_PATH_I2S; + + regmap_write(ma5311->ctrl_regmap, + MA5311_DAC_3A_TDM_SLOT_ENABLE, + MA5311_TDM_SLOT_DISABLE_ALL); + ma5311->dai_tdm_slot_enable = MA5311_TDM_SLOT_DISABLE_ALL; + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_91_ADC_DAC_MIX, + MA5311_DAC_ADC_DAC_MIX_CH_MASK, + MA5311_ADC_MIX_CH0); + ma5311->dai_adc_mix_ch = MA5311_ADC_MIX_CH0; + + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A1_TOP_MAN1_FOR_SDO, + MA5311_TOP_MAN1_O_FORMAT_MASK, + MA5311_TOP_MAN1_O_FORMAT_I2S); + ma5311->dai_o_format = MA5311_TOP_MAN1_O_FORMAT_I2S; + + break; + + case SND_SOC_DAIFMT_DSP_A: + dev_info(component->dev, "Working in TDM TX Mode\n"); + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_A1_TOP_MAN1_FOR_SDO, + MA5311_TOP_MAN1_O_FORMAT_MASK, + MA5311_TOP_MAN1_O_FORMAT_TDM); + ma5311->dai_o_format = MA5311_TOP_MAN1_O_FORMAT_TDM; + + if (!ma5311->flag_dai_tdm) { + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_38_TDM2, + MA5311_ADC_TDM2_SETTING_MASK, + MA5311_DAC_38_CAPTURE_8CH_CFG); + ma5311->dai_tdm2_capture_cfg = MA5311_DAC_38_CAPTURE_8CH_CFG; + + regmap_write(ma5311->ctrl_regmap, + MA5311_DAC_39_DATA_PATH, MA5311_ADC_DATA_PATH_TDM_8CH); + ma5311->dai_data_path = MA5311_ADC_DATA_PATH_TDM_8CH; + + regmap_write(ma5311->ctrl_regmap, + MA5311_DAC_3A_TDM_SLOT_ENABLE, + MA5311_TDM_SLOT_ENABLE_ALL); + ma5311->dai_tdm_slot_enable = MA5311_TDM_SLOT_ENABLE_ALL; + } + + break; + } + } + + return 0; +} + +static int ma5311_dai_set_fmt(struct snd_soc_dai *dai, unsigned int fmt) +{ + struct snd_soc_component *component = dai->component; + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + + switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) { + case SND_SOC_DAIFMT_I2S: + case SND_SOC_DAIFMT_DSP_A: + break; + default: + return -EINVAL; + } + + switch (fmt & SND_SOC_DAIFMT_INV_MASK) { + case SND_SOC_DAIFMT_NB_NF: + case SND_SOC_DAIFMT_NB_IF: + case SND_SOC_DAIFMT_IB_NF: + case SND_SOC_DAIFMT_IB_IF: + break; + default: + return -EINVAL; + } + + switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) { + case SND_SOC_DAIFMT_I2S: + case SND_SOC_DAIFMT_DSP_A: + break; + + default: + return -EINVAL; + } + + switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) { + case SND_SOC_DAIFMT_CBC_CFC: + dev_dbg(component->dev, "BCLK and frame clock consumer\n"); + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_01_INPUT1_CTRL1, + MA5311_CONTROLLER_DEVICE_MASK, + MA5311_DEVICE_MODE); + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_B8_TOP_MAN5, + MA5311_LRCK_SCK_MAS_CLK_SEL_MASK, + MA5311_LRCK_SCK_CLK_SLAVE_MODE); + ma5311->dai_clk_mode = MA5311_DEVICE_MODE; + ma5311->dai_mas_clk_sel = MA5311_LRCK_SCK_CLK_SLAVE_MODE; + break; + + case SND_SOC_DAIFMT_CBP_CFP: + dev_dbg(component->dev, "BCLK and frame clock provider\n"); + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_01_INPUT1_CTRL1, + MA5311_CONTROLLER_DEVICE_MASK, + MA5311_CONTROLLER_MODE); + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_B8_TOP_MAN5, + MA5311_LRCK_SCK_MAS_CLK_SEL_MASK, + MA5311_LRCK_SCK_CLK_MASTER_MODE); + + ma5311->dai_clk_mode = MA5311_CONTROLLER_MODE; + ma5311->dai_mas_clk_sel = MA5311_LRCK_SCK_CLK_MASTER_MODE; + break; + + default: + dev_err(component->dev, + "%s: Unsupported Controller/Device : 0x%x\n", __func__, + fmt); + return -EINVAL; + } + + switch (fmt & SND_SOC_DAIFMT_INV_MASK) { + case SND_SOC_DAIFMT_NB_NF: + dev_dbg(component->dev, "Normal BCLK, normal frame clock\n"); + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_01_INPUT1_CTRL1, + MA5311_LEFTPOL_MASK | + MA5311_SCK_RISING_MASK, + MA5311_LOW_FIRST_CH | + MA5311_SCK_FALLING_EDGE); + ma5311->dai_leftpol = MA5311_LOW_FIRST_CH; + ma5311->dai_sck_edge = MA5311_SCK_FALLING_EDGE; + break; + + case SND_SOC_DAIFMT_NB_IF: + dev_dbg(component->dev, "Normal BCLK, inverted frame clock\n"); + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_01_INPUT1_CTRL1, + MA5311_LEFTPOL_MASK | + MA5311_SCK_RISING_MASK, + MA5311_HIGH_FIRST_CH | + MA5311_SCK_FALLING_EDGE); + ma5311->dai_leftpol = MA5311_HIGH_FIRST_CH; + ma5311->dai_sck_edge = MA5311_SCK_FALLING_EDGE; + break; + + case SND_SOC_DAIFMT_IB_NF: + dev_dbg(component->dev, "Inverted BCLK, normal frame clock\n"); + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_01_INPUT1_CTRL1, + MA5311_LEFTPOL_MASK | + MA5311_SCK_RISING_MASK, + MA5311_LOW_FIRST_CH | + MA5311_SCK_RISING_EDGE); + ma5311->dai_leftpol = MA5311_LOW_FIRST_CH; + ma5311->dai_sck_edge = MA5311_SCK_RISING_EDGE; + break; + + case SND_SOC_DAIFMT_IB_IF: + dev_dbg(component->dev, + "Inverted BCLK, inverted frame clock\n"); + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_01_INPUT1_CTRL1, + MA5311_LEFTPOL_MASK | MA5311_SCK_RISING_MASK, + MA5311_HIGH_FIRST_CH | + MA5311_SCK_RISING_EDGE); + ma5311->dai_leftpol = MA5311_HIGH_FIRST_CH; + ma5311->dai_sck_edge = MA5311_SCK_RISING_EDGE; + break; + + default: + dev_err(component->dev, + "%s: Unsupported Bit & Frameclock : 0x%x\n", __func__, + fmt); + return -EINVAL; + } + + ma5311->format = fmt & SND_SOC_DAIFMT_FORMAT_MASK; + + return 0; +} + +static int ma5311_dai_set_sysclk(struct snd_soc_dai *dai, int clk_id, + unsigned int freq, int dir) +{ + struct snd_soc_component *component = dai->component; + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + + switch (clk_id) { + case MA5311_PLL_CLKIN_BCLK: + case MA5311_INTERNAL_OSC: + if (clk_id == MA5311_PLL_CLKIN_BCLK) + dev_dbg(component->dev, "PLL input: BCLK\n"); + break; + + default: + dev_err(component->dev, "%s: Invalid clk id: %d\n", __func__, + clk_id); + return -EINVAL; + } + + ma5311->sys_clk_id = clk_id; + + return 0; +} + +static int ma5311_dai_set_tdm_slot(struct snd_soc_dai *dai, + unsigned int tx_mask, unsigned int rx_mask, + int slots, int slot_width) +{ + struct snd_soc_component *component = dai->component; + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + unsigned int rx_val = MA5311_TDM_SLOT0_RX_POS_0 | + MA5311_TDM_SLOT1_RX_POS_1; + int ret; + + /* Reject invalid frame geometry before changing the hardware. */ + switch (slot_width) { + case 16: + case 32: + break; + default: + dev_err(component->dev, "%s: unsupported TDM slot width: %d\n", + __func__, slot_width); + return -EINVAL; + } + + switch (slots) { + case 8: + break; + default: + dev_err(component->dev, "%s: unsupported TDM slot count: %d\n", + __func__, slots); + return -EINVAL; + } + + if (rx_mask & ~GENMASK(7, 0)) { + dev_err(component->dev, + "RX mask %#x exceeds %d slots\n", rx_mask, slots); + return -EINVAL; + } + + if (tx_mask != 0 && tx_mask != GENMASK(7, 0)) + return -EINVAL; + + switch (rx_mask) { + case 0: + break; + + case BIT(0) | BIT(1): + rx_val = MA5311_TDM_SLOT0_RX_POS_0 | + MA5311_TDM_SLOT1_RX_POS_1; + break; + + case BIT(2) | BIT(3): + rx_val = MA5311_TDM_SLOT0_RX_POS_2 | + MA5311_TDM_SLOT1_RX_POS_3; + break; + + case BIT(4) | BIT(5): + rx_val = MA5311_TDM_SLOT0_RX_POS_4 | + MA5311_TDM_SLOT1_RX_POS_5; + break; + + case BIT(6) | BIT(7): + rx_val = MA5311_TDM_SLOT0_RX_POS_6 | + MA5311_TDM_SLOT1_RX_POS_7; + break; + + default: + dev_err(component->dev, "Unsupported RX mask: %#x\n", + rx_mask); + return -EINVAL; + } + + ret = regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_37_TDM1, + MA5311_TDM_SLOT0_RX_POS_MASK | + MA5311_TDM_SLOT1_RX_POS_MASK, + rx_val); + if (ret) + return ret; + + ma5311->dai_tdm1_rx_pos = rx_val; + + switch (tx_mask) { + case 0: + break; + + case GENMASK(7, 0): + regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_38_TDM2, + MA5311_ADC_TDM2_SETTING_MASK, + MA5311_DAC_38_CAPTURE_8CH_CFG); + ma5311->dai_tdm2_capture_cfg = MA5311_DAC_38_CAPTURE_8CH_CFG; + + regmap_write(ma5311->ctrl_regmap, + MA5311_DAC_39_DATA_PATH, MA5311_ADC_DATA_PATH_TDM_8CH); + ma5311->dai_data_path = MA5311_ADC_DATA_PATH_TDM_8CH; + + regmap_write(ma5311->ctrl_regmap, + MA5311_DAC_3A_TDM_SLOT_ENABLE, + MA5311_TDM_SLOT_ENABLE_ALL); + ma5311->dai_tdm_slot_enable = MA5311_TDM_SLOT_ENABLE_ALL; + break; + + default: + dev_err(component->dev, "Unsupported TX mask: %#x\n", + tx_mask); + return -EINVAL; + } + + ma5311->frame_size = slots * slot_width; + + dev_dbg(component->dev, "TDM slots=%d width=%d\n", slots, slot_width); + + if (!ma5311->flag_dai_tdm) + ma5311->flag_dai_tdm = true; + + return 0; +} + +static int ma5311_dai_mute_stream(struct snd_soc_dai *dai, int mute, int stream) +{ + struct snd_soc_component *component = dai->component; + struct ma5311_priv *ma5311 = snd_soc_component_get_drvdata(component); + unsigned int val = MA5311_SPK_UNMUTE; + int ret; + + if (stream == SNDRV_PCM_STREAM_CAPTURE) + return 0; + + if (mute) + val = MA5311_SPK_MUTE; + + ret = regmap_update_bits(ma5311->ctrl_regmap, + MA5311_DAC_0E_MUTE_VOL_CTRL, + MA5311_DAC_MUTE_VOL_MASK, val); + if (ret) + return ret; + + ma5311->dai_spk_mute = val; + + return 0; +} + +static const struct snd_soc_dai_ops ma5311_dai_ops_amp = { + .hw_params = ma5311_dai_hw_params, + .set_fmt = ma5311_dai_set_fmt, + .set_sysclk = ma5311_dai_set_sysclk, + .set_tdm_slot = ma5311_dai_set_tdm_slot, + .mute_stream = ma5311_dai_mute_stream, +}; + +#define MA5311_RATES_PLAYBACK SNDRV_PCM_RATE_48000 +#define MA5311_RATES_CAPTURE SNDRV_PCM_RATE_48000 +#define MA5311_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S32_LE) + +static struct snd_soc_dai_driver ma5311_dai[] = { + { + .name = "ma5311-amplifier", + .id = 0, + .playback = { + .stream_name = "Playback", + .channels_min = 1, + .channels_max = 8, + .rates = MA5311_RATES_PLAYBACK, + .formats = MA5311_FORMATS, + }, + .capture = { + .stream_name = "Capture", + .channels_min = 1, + .channels_max = 8, + .rates = MA5311_RATES_CAPTURE, + .formats = MA5311_FORMATS, + }, + .ops = &ma5311_dai_ops_amp, + .symmetric_rate = 1, + .symmetric_sample_bits = 1, + }, +}; + +static void ma5311_unregister_ancillary_client(void *data) +{ + struct i2c_client *client = data; + + i2c_unregister_device(client); +} + +static irqreturn_t ma5311_irq_thread(int irq, void *data) +{ + struct ma5311_priv *ma5311 = data; + unsigned int dac_status; + int ret = 0; + + ret = regmap_read(ma5311->ctrl_regmap, + MA5311_DAC_EA_DAC_STATUS, &dac_status); + if (ret) { + dev_err_ratelimited(ma5311->dev, + "I2C Read Failed During Interrupt Handling\n"); + return IRQ_NONE; + } + + if (!(dac_status & MA5311_DAC_EA_FAULT_MASK)) + return IRQ_NONE; + + dev_err_ratelimited(ma5311->dev, "FAULT Asserted\n"); + + return IRQ_HANDLED; +} + +static int ma5311_i2c_probe(struct i2c_client *client) +{ + struct ma5311_priv *ma5311; + int ret; + unsigned int irq_type; + + ma5311 = devm_kzalloc(&client->dev, sizeof(*ma5311), GFP_KERNEL); + if (!ma5311) + return -ENOMEM; + + ma5311->ctrl_regmap = devm_regmap_init_i2c(client, + &ma5311_ctrl_regmap_config); + if (IS_ERR(ma5311->ctrl_regmap)) + return dev_err_probe(&client->dev, PTR_ERR(ma5311->ctrl_regmap), + "%s: Failed to allocate control regmap\n", + __func__); + + ma5311->adc_client = i2c_new_ancillary_device(client, "adc", 0x3f); + if (IS_ERR(ma5311->adc_client)) + return dev_err_probe(&client->dev, PTR_ERR(ma5311->adc_client), + "Failed to create ADC ancillary client\n"); + + ret = devm_add_action_or_reset(&client->dev, + ma5311_unregister_ancillary_client, + ma5311->adc_client); + if (ret) + return ret; + + ma5311->adc_regmap = devm_regmap_init_i2c(ma5311->adc_client, + &ma5311_adc_regmap_config); + if (IS_ERR(ma5311->adc_regmap)) + return dev_err_probe(&client->dev, PTR_ERR(ma5311->adc_regmap), + "Failed to allocate ADC regmap\n"); + + ma5311->reset_gpio = devm_gpiod_get_optional(&client->dev, "reset", + GPIOD_OUT_LOW); + if (IS_ERR(ma5311->reset_gpio)) + return dev_err_probe(&client->dev, PTR_ERR(ma5311->reset_gpio), + "Failed to acquire reset GPIO\n"); + + if (ma5311->reset_gpio) + msleep(MA5311_RESET_RECOVERY_MS); + + ma5311->amp_mode = MA5311_MONO_BOTH_MODE; + ma5311->num_of_pll_matches = ARRAY_SIZE(ma5311_pll_matches); + ma5311->pll_matches = ma5311_pll_matches; + ma5311->format = SND_SOC_DAIFMT_I2S; + ma5311->sys_clk_id = MA5311_PLL_CLKIN_BCLK; + ma5311->dev = &client->dev; + ma5311->frame_size = 0; + ma5311->dai_sys_clk = 0; + ma5311->dai_mas_clk_sel = MA5311_LRCK_SCK_CLK_SLAVE_MODE; + ma5311->dai_adc_clk = 0; + ma5311->dai_adc_mix_ch = MA5311_ADC_MIX_CH0; + ma5311->dai_clk_mode = MA5311_DEVICE_MODE; + ma5311->dai_leftpol = MA5311_LOW_FIRST_CH; + ma5311->dai_sck_edge = MA5311_SCK_FALLING_EDGE; + ma5311->dai_spk_mute = MA5311_SPK_MUTE; + ma5311->dai_tdm1_rx_pos = MA5311_TDM_SLOT0_RX_POS_0 | + MA5311_TDM_SLOT1_RX_POS_1; + ma5311->dai_tdm2_data_len = MA5311_DAC_38_DATA_LEN_16; + ma5311->dai_tdm2_capture_cfg = MA5311_DAC_38_CAPTURE_8CH_CFG; + ma5311->dai_data_path = MA5311_ADC_DATA_PATH_CH0; + ma5311->dai_tdm_slot_enable = MA5311_TDM_SLOT_DISABLE_ALL; + ma5311->dai_pll_input = MA5311_DAC_PLLIN_EXT_OSC | + MA5311_DAC_PLL_REF_EXT_CLK | + MA5311_DAC_PLL_REF_CLK2_SCK; + ma5311->dai_pll_post_n = MA5311_PLL_POST_N_DEFAULT; + ma5311->dai_pll_n = MA5311_PLL_N_DEFAULT; + ma5311->dai_pll_f1 = MA5311_PLL_F1_DEFAULT; + ma5311->dai_pll_f2 = MA5311_PLL_F2_DEFAULT; + ma5311->dai_pll_f3_p_cp = MA5311_PLL_F3_P_CP_DEFAULT; + ma5311->dai_sdo_len = MA5311_TOP_MAN1_SDO_16B; + ma5311->dai_sck_rate = MA5311_DAC_A1_SCK_RATE_32FS; + ma5311->dai_o_format = MA5311_TOP_MAN1_O_FORMAT_I2S; + ma5311->dai_adc1_word_len = MA5311_ADC_WORD_LENGTH_24; + ma5311->dai_adc1_sck_rate = MA5311_ADC_SCK_RATE_24BIT_CFG; + ma5311->dai_adc2_word_len = MA5311_ADC_WORD_LENGTH_24; + ma5311->dai_adc2_sck_rate = MA5311_ADC_SCK_RATE_24BIT_CFG; + ma5311->dai_adc3_word_len = MA5311_ADC_WORD_LENGTH_24; + ma5311->dai_adc3_sck_rate = MA5311_ADC_SCK_RATE_24BIT_CFG; + ma5311->dai_adc4_word_len = MA5311_ADC_WORD_LENGTH_24; + ma5311->dai_adc4_sck_rate = MA5311_ADC_SCK_RATE_24BIT_CFG; + ma5311->flag_ext_rst = false; + ma5311->flag_dai_tdm = false; + i2c_set_clientdata(client, ma5311); + + ret = devm_snd_soc_register_component(&client->dev, &ma5311_component, + ma5311_dai, 1); + if (ret) { + dev_err(&client->dev, "Failed to register component: %d\n", + ret); + return ret; + } + + if (client->irq > 0) { + irq_type = irq_get_trigger_type(client->irq); + if (irq_type != IRQ_TYPE_EDGE_FALLING) + return dev_err_probe(&client->dev, -EINVAL, + "Falling-edge IRQ required\n"); + + ret = devm_request_threaded_irq(&client->dev, client->irq, NULL, + ma5311_irq_thread, IRQF_ONESHOT, + "ma5311", ma5311); + if (ret) + return dev_err_probe(&client->dev, ret, + "Failed to request IRQ %d\n", + client->irq); + } else { + dev_warn(&client->dev, "No IRQ configured\n"); + } + + return ret; +} + +static const struct i2c_device_id ma5311_i2c_id[] = { + { .name = "ma5311", .driver_data = 0 }, + { } +}; + +MODULE_DEVICE_TABLE(i2c, ma5311_i2c_id); + +static const struct of_device_id ma5311_of_match[] = { + { .compatible = "irondevice,ma5311" }, + { } +}; + +MODULE_DEVICE_TABLE(of, ma5311_of_match); + +static struct i2c_driver ma5311_i2c_driver = { + .driver = { + .name = "ma5311", + .of_match_table = ma5311_of_match, + }, + .probe = ma5311_i2c_probe, + .id_table = ma5311_i2c_id, +}; + +module_i2c_driver(ma5311_i2c_driver); + +MODULE_DESCRIPTION("ALSA SoC MA5311 driver"); +MODULE_AUTHOR("Hyunuk Son, "); +MODULE_LICENSE("GPL"); diff --git a/sound/soc/codecs/ma5311.h b/sound/soc/codecs/ma5311.h new file mode 100644 index 00000000000000..2470124e4290dc --- /dev/null +++ b/sound/soc/codecs/ma5311.h @@ -0,0 +1,558 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * ma5311.h -- MA5311 ALSA SoC codec register definitions + */ + +#ifndef _MA5311_H +#define _MA5311_H + +#include + +/* DAC/control and ADC registers use separate I2C banks. */ + +/* I2C addresses */ +#define MA5311_ADC_I2C_ADDR_00 0x3f +#define MA5311_ADC_I2C_ADDR_01 0x4f +#define MA5311_ADC_I2C_ADDR_10 0x5f +#define MA5311_ADC_I2C_ADDR_11 0x6f + +#define MA5311_I2C_RETRY_COUNT 3 + +/* DAC and control register addresses */ +#define MA5311_DAC_00_SYSTEM_CTRL1 0x00 +#define MA5311_DAC_01_INPUT1_CTRL1 0x01 +#define MA5311_DAC_02_INPUT1_CTRL2 0x02 +#define MA5311_DAC_03_INPUT1_CTRL3 0x03 +#define MA5311_DAC_04_INPUT1_CTRL4 0x04 +#define MA5311_DAC_05_ADC_DAC_MIX2 0x05 +#define MA5311_DAC_09_OUTPUT_CTRL 0x09 +#define MA5311_DAC_0A_SPK_VOL_L 0x0a +#define MA5311_DAC_0B_SPK_VOL_R 0x0b +#define MA5311_DAC_0E_MUTE_VOL_CTRL 0x0e +#define MA5311_DAC_0F_SYSTEM_CTRL2 0x0f +#define MA5311_DAC_10_SYSTEM_CTRL3 0x10 +#define MA5311_DAC_11_SYSTEM_CTRL4 0x11 +#define MA5311_DAC_12_SYSTEM_CTRL5 0x12 +#define MA5311_DAC_14_MODULATOR2 0x14 +#define MA5311_DAC_15_BASS_SPK1 0x15 +#define MA5311_DAC_16_BASS_SPK2 0x16 +#define MA5311_DAC_17_BASS_SPK3 0x17 +#define MA5311_DAC_18_BASS_SPK4 0x18 +#define MA5311_DAC_19_BASS_SPK5 0x19 +#define MA5311_DAC_1A_BASS_SPK6 0x1a +#define MA5311_DAC_1B_BASS_SPK7 0x1b +#define MA5311_DAC_23_COMP_LIM1 0x23 +#define MA5311_DAC_24_COMP_LIM2 0x24 +#define MA5311_DAC_25_COMP_LIM3 0x25 +#define MA5311_DAC_26_COMP_LIM4 0x26 +#define MA5311_DAC_2B_EQ_MODE 0x2b +#define MA5311_DAC_2C_EQ_GRAPHIC1 0x2c +#define MA5311_DAC_2D_EQ_GRAPHIC2 0x2d +#define MA5311_DAC_2E_EQ_GRAPHIC3 0x2e +#define MA5311_DAC_2F_EQ_GRAPHIC4 0x2f +#define MA5311_DAC_30_EQ_GRAPHIC5 0x30 +#define MA5311_DAC_33_FLL_CTRL3 0x33 +#define MA5311_DAC_34_EQ_CTRL 0x34 +#define MA5311_DAC_35_POST_DRC_CTRL 0x35 +#define MA5311_DAC_36_PROTECTION 0x36 +#define MA5311_DAC_37_TDM1 0x37 +#define MA5311_DAC_38_TDM2 0x38 +#define MA5311_DAC_39_DATA_PATH 0x39 +#define MA5311_DAC_3A_TDM_SLOT_ENABLE 0x3a +#define MA5311_DAC_3B_TEST1 0x3b +#define MA5311_DAC_3C_TEST2 0x3c +#define MA5311_DAC_3D_TEST3 0x3d +#define MA5311_DAC_40_EQ_CTRL1 0x40 +#define MA5311_DAC_41_EQ_CTRL2 0x41 +#define MA5311_DAC_42_EQ_CTRL3 0x42 +#define MA5311_DAC_43_EQ_CTRL4 0x43 +#define MA5311_DAC_44_EQ_CTRL5 0x44 +#define MA5311_DAC_45_EQ_CTRL6 0x45 +#define MA5311_DAC_46_EQ_CTRL7 0x46 +#define MA5311_DAC_47_EQ_CTRL8 0x47 +#define MA5311_DAC_48_EQ_CTRL9 0x48 +#define MA5311_DAC_49_EQ_CTRL10 0x49 +#define MA5311_DAC_4A_EQ_CTRL11 0x4a +#define MA5311_DAC_4B_EQ_CTRL12 0x4b +#define MA5311_DAC_4C_EQ_CTRL13 0x4c +#define MA5311_DAC_4D_EQ_CTRL14 0x4d +#define MA5311_DAC_4E_EQ_CTRL15 0x4e +#define MA5311_DAC_4F_EQ_CTRL16 0x4f +#define MA5311_DAC_50_EQ_CTRL17 0x50 +#define MA5311_DAC_51_EQ_CTRL18 0x51 +#define MA5311_DAC_52_EQ_CTRL19 0x52 +#define MA5311_DAC_53_EQ_CTRL20 0x53 +#define MA5311_DAC_54_EQ_CTRL21 0x54 +#define MA5311_DAC_55_EQ_CTRL22 0x55 +#define MA5311_DAC_56_EQ_CTRL23 0x56 +#define MA5311_DAC_57_EQ_CTRL24 0x57 +#define MA5311_DAC_58_EQ_CTRL25 0x58 +#define MA5311_DAC_59_EQ_CTRL26 0x59 +#define MA5311_DAC_5A_EQ_CTRL27 0x5a +#define MA5311_DAC_5B_EQ_CTRL28 0x5b +#define MA5311_DAC_5C_EQ_CTRL29 0x5c +#define MA5311_DAC_5D_EQ_CTRL30 0x5d +#define MA5311_DAC_5E_EQ_CTRL31 0x5e +#define MA5311_DAC_5F_EQ_CTRL32 0x5f +#define MA5311_DAC_60_EQ_CTRL33 0x60 +#define MA5311_DAC_61_EQ_CTRL34 0x61 +#define MA5311_DAC_62_EQ_CTRL35 0x62 +#define MA5311_DAC_63_EQ_CTRL36 0x63 +#define MA5311_DAC_64_EQ_CTRL37 0x64 +#define MA5311_DAC_65_EQ_CTRL38 0x65 +#define MA5311_DAC_66_EQ_CTRL39 0x66 +#define MA5311_DAC_67_EQ_CTRL40 0x67 +#define MA5311_DAC_68_EQ_CTRL41 0x68 +#define MA5311_DAC_69_EQ_CTRL42 0x69 +#define MA5311_DAC_6A_EQ_CTRL43 0x6a +#define MA5311_DAC_6B_EQ_CTRL44 0x6b +#define MA5311_DAC_6C_EQ_CTRL45 0x6c +#define MA5311_DAC_6D_EQ_CTRL46 0x6d +#define MA5311_DAC_6E_EQ_CTRL47 0x6e +#define MA5311_DAC_6F_EQ_CTRL48 0x6f +#define MA5311_DAC_70_EQ_CTRL49 0x70 +#define MA5311_DAC_71_EQ_CTRL50 0x71 +#define MA5311_DAC_72_EQ_CTRL51 0x72 +#define MA5311_DAC_73_EQ_CTRL52 0x73 +#define MA5311_DAC_74_EQ_CTRL53 0x74 +#define MA5311_DAC_75_EQ_CTRL54 0x75 +#define MA5311_DAC_76_EQ_CTRL55 0x76 +#define MA5311_DAC_77_EQ_CTRL56 0x77 +#define MA5311_DAC_78_EQ_CTRL57 0x78 +#define MA5311_DAC_79_EQ_CTRL58 0x79 +#define MA5311_DAC_7A_EQ_CTRL59 0x7a +#define MA5311_DAC_7B_EQ_CTRL60 0x7b +#define MA5311_DAC_7C_EQ_CTRL61 0x7c +#define MA5311_DAC_7D_EQ_CTRL62 0x7d +#define MA5311_DAC_7E_EQ_CTRL63 0x7e +#define MA5311_DAC_7F_EQ_CTRL64 0x7f +#define MA5311_DAC_80_EQ_CTRL65 0x80 +#define MA5311_DAC_81_EQ_CTRL66 0x81 +#define MA5311_DAC_82_EQ_CTRL67 0x82 +#define MA5311_DAC_83_EQ_CTRL68 0x83 +#define MA5311_DAC_84_EQ_CTRL69 0x84 +#define MA5311_DAC_85_EQ_CTRL70 0x85 +#define MA5311_DAC_86_EQ_CTRL71 0x86 +#define MA5311_DAC_87_EQ_CTRL72 0x87 +#define MA5311_DAC_88_EQ_CTRL73 0x88 +#define MA5311_DAC_89_EQ_CTRL74 0x89 +#define MA5311_DAC_8A_EQ_CTRL75 0x8a +#define MA5311_DAC_8B_PLL_POST_N 0x8b +#define MA5311_DAC_8C_PLL_N 0x8c +#define MA5311_DAC_8D_PLL_F1 0x8d +#define MA5311_DAC_8E_PLL_F2 0x8e +#define MA5311_DAC_8F_PLL_F3_P_CP 0x8f +#define MA5311_DAC_91_ADC_DAC_MIX 0x91 +#define MA5311_DAC_A1_TOP_MAN1_FOR_SDO 0xa1 +#define MA5311_DAC_A2_TOP_MAN2 0xa2 +#define MA5311_DAC_A3_TOP_MAN3 0xa3 +#define MA5311_DAC_A4_BLOCK_CONTROL 0xa4 +#define MA5311_DAC_A5_VALUE_CONTROL 0xa5 +#define MA5311_DAC_A6_VALUE_CONTROL2 0xa6 +#define MA5311_DAC_A7_DT_CONTROL 0xa7 +#define MA5311_DAC_A8_SLOPE_CONTROL 0xa8 +#define MA5311_DAC_A9_FDPEC_CONTROL 0xa9 +#define MA5311_DAC_AA_LDO_CONTROL 0xaa +#define MA5311_DAC_AB_PRESCALER 0xab +#define MA5311_DAC_AC_MBD_COMP_LIM1 0xac +#define MA5311_DAC_AD_MBD_COMP_LIM2 0xad +#define MA5311_DAC_AE_MBD_COMP_LIM3 0xae +#define MA5311_DAC_AF_MBD_COMP_LIM4 0xaf +#define MA5311_DAC_B0_BPD_COMP_LIM1 0xb0 +#define MA5311_DAC_B1_BPD_COMP_LIM2 0xb1 +#define MA5311_DAC_B2_BPD_COMP_LIM3 0xb2 +#define MA5311_DAC_B3_BPD_COMP_LIM4 0xb3 +#define MA5311_DAC_B4_DSP_SPK_CTRL 0xb4 +#define MA5311_DAC_B5_MCLKO_TEST 0xb5 +#define MA5311_DAC_B7_TOP_MAN4 0xb7 +#define MA5311_DAC_B8_TOP_MAN5 0xb8 +#define MA5311_DAC_B9_PLL_A_SETTING 0xb9 +#define MA5311_DAC_BB_CLASS_G_LEVEL1 0xbb +#define MA5311_DAC_BC_CLASS_G_LEVEL2 0xbc +#define MA5311_DAC_BD_TONE_GENERATOR 0xbd +#define MA5311_DAC_BE_TONE_FINE_VOLUME 0xbe +#define MA5311_DAC_BF_POWER_METER 0xbf +#define MA5311_DAC_EA_DAC_STATUS 0xea +#define MA5311_DAC_EB_DAC_OCP_STATUS 0xeb +#define MA5311_DAC_EC_DAC_SCP_STATUS 0xec +#define MA5311_DAC_FB_STATUS2 0xfb +#define MA5311_DAC_FC_STATUS3 0xfc +#define MA5311_DAC_FD_POWER_METER_DISPLAY 0xfd +#define MA5311_DAC_FF_VERSION 0xff + +/* DAC/control register masks and values */ + +#define MA5311_POWER_MASK BIT(0) +#define MA5311_POWER_OFF 0 +#define MA5311_POWER_ON BIT(0) + +#define MA5311_DAC_MUTE_VOL_MASK GENMASK(1, 0) +#define MA5311_SPK_MUTE 0x03 +#define MA5311_SPK_UNMUTE 0x00 + +/* 0x10: Speaker mode */ +#define MA5311_SPK_MODE_MASK GENMASK(4, 2) +#define MA5311_SPK_MONO_LEFT 0x02 +#define MA5311_SPK_MONO_RIGHT 0x04 +#define MA5311_SPK_MONO_BOTH 0x0c +#define MA5311_SPK_STEREO 0x10 +#define MA5311_SPK_OFF 0x00 + +/* 0x37: TDM receive slot positions */ +#define MA5311_TDM_SLOT0_RX_POS_MASK GENMASK(5, 3) +#define MA5311_TDM_SLOT0_RX_POS_0 0x00 +#define MA5311_TDM_SLOT0_RX_POS_1 0x08 +#define MA5311_TDM_SLOT0_RX_POS_2 0x10 +#define MA5311_TDM_SLOT0_RX_POS_3 0x18 +#define MA5311_TDM_SLOT0_RX_POS_4 0x20 +#define MA5311_TDM_SLOT0_RX_POS_5 0x28 +#define MA5311_TDM_SLOT0_RX_POS_6 0x30 +#define MA5311_TDM_SLOT0_RX_POS_7 0x38 + +#define MA5311_TDM_SLOT1_RX_POS_MASK GENMASK(2, 0) +#define MA5311_TDM_SLOT1_RX_POS_0 0x00 +#define MA5311_TDM_SLOT1_RX_POS_1 0x01 +#define MA5311_TDM_SLOT1_RX_POS_2 0x02 +#define MA5311_TDM_SLOT1_RX_POS_3 0x03 +#define MA5311_TDM_SLOT1_RX_POS_4 0x04 +#define MA5311_TDM_SLOT1_RX_POS_5 0x05 +#define MA5311_TDM_SLOT1_RX_POS_6 0x06 +#define MA5311_TDM_SLOT1_RX_POS_7 0x07 + +#define MA5311_TDM_N_SLOT_MASK BIT(6) +#define MA5311_TDM_N_SLOT_4 0 +#define MA5311_TDM_N_SLOT_8 BIT(6) + +#define MA5311_TDM_SLOT0_TX_POS_MASK GENMASK(5, 3) +#define MA5311_TDM_SLOT0_TX_POS_0 0x00 +#define MA5311_TDM_SLOT0_TX_POS_1 0x08 +#define MA5311_TDM_SLOT0_TX_POS_2 0x10 +#define MA5311_TDM_SLOT0_TX_POS_3 0x18 +#define MA5311_TDM_SLOT0_TX_POS_4 0x20 +#define MA5311_TDM_SLOT0_TX_POS_5 0x28 +#define MA5311_TDM_SLOT0_TX_POS_6 0x30 +#define MA5311_TDM_SLOT0_TX_POS_7 0x38 + +#define MA5311_TDM_SLOT1_TX_POS_MASK GENMASK(2, 0) +#define MA5311_TDM_SLOT1_TX_POS_0 0x00 +#define MA5311_TDM_SLOT1_TX_POS_1 0x01 +#define MA5311_TDM_SLOT1_TX_POS_2 0x02 +#define MA5311_TDM_SLOT1_TX_POS_3 0x03 +#define MA5311_TDM_SLOT1_TX_POS_4 0x04 +#define MA5311_TDM_SLOT1_TX_POS_5 0x05 +#define MA5311_TDM_SLOT1_TX_POS_6 0x06 +#define MA5311_TDM_SLOT1_TX_POS_7 0x07 + +#define MA5311_ADC_TDM2_SETTING_MASK GENMASK(6, 0) + +/* 0x39: SDO data path */ +#define MA5311_DAC_SDO_DATA_PATH_MASK GENMASK(3, 2) + +/* 0x91: ADC-to-DAC mix */ +#define MA5311_DAC_ADC_DAC_MIX_CH_MASK GENMASK(1, 0) + +/* 0xA1: SDO output format and word length */ +#define MA5311_TOP_MAN1_O_FORMAT_MASK GENMASK(7, 5) +#define MA5311_TOP_MAN1_O_FORMAT_I2S 0x40 +#define MA5311_TOP_MAN1_O_FORMAT_TDM 0x80 +#define MA5311_TOP_MAN1_SOO_LENGTH_MASK GENMASK(2, 1) +#define MA5311_TOP_MAN1_SDO_16B 0x04 +#define MA5311_TOP_MAN1_SDO_24B 0x00 + +/* 0xA2: PLL power */ +#define MA5311_PLL_MASK BIT(6) +#define MA5311_PLL_ON 0 +#define MA5311_PLL_OFF BIT(6) + +/* 0xFF: Device identification and revision */ +#define MA5311_DAC_VERSION_MASK GENMASK(7, 0) +#define MA5311_DEVICE_ID 0x0bU +#define MA5311_REV_NUM_STATUS GENMASK(7, 0) + +/* ADC register addresses */ +/* ADC CH1(L/R) */ +/* General Settings */ +#define MA5311_ADC_CH1_00_GENERAL_SETTING 0x00 +#define MA5311_ADC_CH1_01_DMIC_ALC1 0x01 +#define MA5311_ADC_CH1_02_ALC2 0x02 +#define MA5311_ADC_CH1_03_ALC3 0x03 +#define MA5311_ADC_CH1_04_ALC4 0x04 +#define MA5311_ADC_CH1_05_ALC5 0x05 +#define MA5311_ADC_CH1_06_ALC6 0x06 +#define MA5311_ADC_CH1_07_VOLUME_LEFT 0x07 +#define MA5311_ADC_CH1_08_VOLUME_RIGHT 0x08 +#define MA5311_ADC_CH1_09_PGA_LEFT 0x09 +#define MA5311_ADC_CH1_0A_PGA_RIGHT 0x0a +#define MA5311_ADC_CH1_0B_AFE 0x0b +#define MA5311_ADC_CH1_0C_VOLUME_BOOST_LINE1 0x0c +#define MA5311_ADC_CH1_0D_VOLUME_BOOST_LINE2 0x0d +#define MA5311_ADC_CH1_0E_MUTE_DATA_FLOW 0x0e +#define MA5311_ADC_CH1_0F_OUTPUT_FORMAT 0x0f + +/* ADC CH2(L/R) */ +#define MA5311_ADC_CH2_10_GENERAL_SETTING 0x10 +#define MA5311_ADC_CH2_11_DMIC_ALC1 0x11 +#define MA5311_ADC_CH2_12_ALC2 0x12 +#define MA5311_ADC_CH2_13_ALC3 0x13 +#define MA5311_ADC_CH2_14_ALC4 0x14 +#define MA5311_ADC_CH2_15_ALC5 0x15 +#define MA5311_ADC_CH2_16_ALC6 0x16 +#define MA5311_ADC_CH2_17_VOLUME_LEFT 0x17 +#define MA5311_ADC_CH2_18_VOLUME_RIGHT 0x18 +#define MA5311_ADC_CH2_19_PGA_LEFT 0x19 +#define MA5311_ADC_CH2_1A_PGA_RIGHT 0x1a +#define MA5311_ADC_CH2_1B_AFE 0x1b +#define MA5311_ADC_CH2_1C_VOLUME_BOOST_LINE1 0x1c +#define MA5311_ADC_CH2_1D_VOLUME_BOOST_LINE2 0x1d +#define MA5311_ADC_CH2_1E_MUTE_DATA_FLOW 0x1e +#define MA5311_ADC_CH2_1F_OUTPUT_FORMAT 0x1f + +/* ADC CH3(L/R) */ +#define MA5311_ADC_CH3_20_GENERAL_SETTING 0x20 +#define MA5311_ADC_CH3_21_DMIC_ALC1 0x21 +#define MA5311_ADC_CH3_22_ALC2 0x22 +#define MA5311_ADC_CH3_23_ALC3 0x23 +#define MA5311_ADC_CH3_24_ALC4 0x24 +#define MA5311_ADC_CH3_25_ALC5 0x25 +#define MA5311_ADC_CH3_26_ALC6 0x26 +#define MA5311_ADC_CH3_27_VOLUME_LEFT 0x27 +#define MA5311_ADC_CH3_28_VOLUME_RIGHT 0x28 +#define MA5311_ADC_CH3_29_PGA_LEFT 0x29 +#define MA5311_ADC_CH3_2A_PGA_RIGHT 0x2a +#define MA5311_ADC_CH3_2B_AFE 0x2b +#define MA5311_ADC_CH3_2C_VOLUME_BOOST_LINE1 0x2c +#define MA5311_ADC_CH3_2D_VOLUME_BOOST_LINE2 0x2d +#define MA5311_ADC_CH3_2E_MUTE_DATA_FLOW 0x2e +#define MA5311_ADC_CH3_2F_OUTPUT_FORMAT 0x2f + +/* ADC CH4(L/R) */ +#define MA5311_ADC_CH4_30_GENERAL_SETTING 0x30 +#define MA5311_ADC_CH4_31_DMIC_ALC1 0x31 +#define MA5311_ADC_CH4_32_ALC2 0x32 +#define MA5311_ADC_CH4_33_ALC3 0x33 +#define MA5311_ADC_CH4_34_ALC4 0x34 +#define MA5311_ADC_CH4_35_ALC5 0x35 +#define MA5311_ADC_CH4_36_ALC6 0x36 +#define MA5311_ADC_CH4_37_VOLUME_LEFT 0x37 +#define MA5311_ADC_CH4_38_VOLUME_RIGHT 0x38 +#define MA5311_ADC_CH4_39_PGA_LEFT 0x39 +#define MA5311_ADC_CH4_3A_PGA_RIGHT 0x3a +#define MA5311_ADC_CH4_3B_AFE 0x3b +#define MA5311_ADC_CH4_3C_VOLUME_BOOST_LINE1 0x3c +#define MA5311_ADC_CH4_3D_VOLUME_BOOST_LINE2 0x3d +#define MA5311_ADC_CH4_3E_MUTE_DATA_FLOW 0x3e +#define MA5311_ADC_CH4_3F_OUTPUT_FORMAT 0x3f + +/* ADC register masks and values */ +#define MA5311_ADC_HPF_ENABLE_MASK BIT(7) +#define MA5311_ADC_OSR_SDM_MASK BIT(6) +#define MA5311_ADC_SAMPLE_RATE_MASK GENMASK(4, 2) +#define MA5311_ADC_SAMPLE_RATE_192K 0x00U +#define MA5311_ADC_SAMPLE_RATE_96K 0x04U +#define MA5311_ADC_SAMPLE_RATE_48K 0x08U +#define MA5311_ADC_SAMPLE_RATE_24K 0x10U +#define MA5311_ADC_SAMPLE_RATE_12K 0x18U +#define MA5311_ADC_OSR_DEC_MASK BIT(1) +#define MA5311_ADC_POWER_MASK BIT(0) +#define MA5311_ADC_POWER_ON 0U +#define MA5311_ADC_POWER_DOWN BIT(0) + +#define MA5311_ADC_SYSCLK_MASK GENMASK(7, 6) +#define MA5311_ADC_DMIC_CLOCK_MASK BIT(5) +#define MA5311_ADC_DMIC_MODE_MASK BIT(4) +#define MA5311_ADC_ALC_SELECT_MASK GENMASK(1, 0) + +#define MA5311_ADC_VOL_CTRL_MASK GENMASK(7, 0) +#define MA5311_ADC_PGA_CTRL_MASK GENMASK(5, 0) + +#define MA5311_ADC_LRCK_POL_MASK BIT(7) +#define MA5311_ADC_SCK_POL_MASK BIT(6) +#define MA5311_ADC_SWAP_LR_MASK BIT(5) +#define MA5311_ADC_MUTE_SLOPE_MASK GENMASK(4, 3) +#define MA5311_ADC_MUTE_RIGHT_MASK BIT(2) +#define MA5311_ADC_MUTE_LEFT_MASK BIT(1) + +#define MA5311_ADC_LEFT_MUTE BIT(1) +#define MA5311_ADC_LEFT_DEMUTE 0 +#define MA5311_ADC_RIGHT_MUTE BIT(2) +#define MA5311_ADC_RIGHT_DEMUTE 0 + +#define MA5311_ADC_MUTE_BOTH_MASK GENMASK(2, 1) +#define MA5311_ADC_BOTH_MUTE 0x06 +#define MA5311_ADC_BOTH_DEMUTE 0x00 + +#define MA5311_ADC_OUTPUT_MASTER_MASK BIT(7) +#define MA5311_ADC_OUTPUT_SCK_RATE_MASK GENMASK(6, 5) +#define MA5311_ADC_OUTPUT_WORD_LENGTH_MASK GENMASK(4, 3) +#define MA5311_ADC_OUTPUT_FORMAT_MASK GENMASK(2, 0) +#define MA5311_ADC_OUTPUT_FORMAT_RJ 0x00U +#define MA5311_ADC_OUTPUT_FORMAT_LJ 0x01U +#define MA5311_ADC_OUTPUT_FORMAT_I2S 0x02U +#define MA5311_ADC_OUTPUT_FORMAT_SPI 0x03U +#define MA5311_ADC_OUTPUT_FORMAT_PCM_SHORT 0x04U + +#define MA5311_ADC_WORD_LENGTH_24 0x00 +#define MA5311_ADC_WORD_LENGTH_16 0x18 + +#define MA5311_PLL_CLKIN_BCLK 0x00 +#define MA5311_INTERNAL_OSC 0x01 +#define MA5311_DUMMY_BCLK 0 +#define MA5311_INT_OSC_POST_N 0x07 +#define MA5311_INT_OSC_N 0x70 +#define MA5311_INT_OSC_F1 0x00 +#define MA5311_INT_OSC_F2 0x00 +#define MA5311_INT_OSC_F3_P_CP 0x0b + +#define MA5311_RESET_CTRL_NAME "Reset Command" +#define MA5311_LEFT_VOL_CTRL_NAME "Left Speaker Volume" +#define MA5311_RIGHT_VOL_CTRL_NAME "Right Speaker Volume" + +#define MA5311_ADC1_LEFT_VOL_CTRL_NAME "ADC1 Left Volume" +#define MA5311_ADC1_RIGHT_VOL_CTRL_NAME "ADC1 Right Volume" +#define MA5311_ADC1_LEFT_PGA_CTRL_NAME "ADC1 Left PGA" +#define MA5311_ADC1_RIGHT_PGA_CTRL_NAME "ADC1 Right PGA" + +#define MA5311_ADC2_LEFT_VOL_CTRL_NAME "ADC2 Left Volume" +#define MA5311_ADC2_RIGHT_VOL_CTRL_NAME "ADC2 Right Volume" +#define MA5311_ADC2_LEFT_PGA_CTRL_NAME "ADC2 Left PGA" +#define MA5311_ADC2_RIGHT_PGA_CTRL_NAME "ADC2 Right PGA" + +#define MA5311_ADC3_LEFT_VOL_CTRL_NAME "ADC3 Left Volume" +#define MA5311_ADC3_RIGHT_VOL_CTRL_NAME "ADC3 Right Volume" +#define MA5311_ADC3_LEFT_PGA_CTRL_NAME "ADC3 Left PGA" +#define MA5311_ADC3_RIGHT_PGA_CTRL_NAME "ADC3 Right PGA" + +#define MA5311_ADC4_LEFT_VOL_CTRL_NAME "ADC4 Left Volume" +#define MA5311_ADC4_RIGHT_VOL_CTRL_NAME "ADC4 Right Volume" +#define MA5311_ADC4_LEFT_PGA_CTRL_NAME "ADC4 Left PGA" +#define MA5311_ADC4_RIGHT_PGA_CTRL_NAME "ADC4 Right PGA" + +#define MA5311_CAPTURE_NAME "Capture Mode" +#define MA5311_TDM_RX_SLOT "TDM RX Slot" + +#define MA5311_AIF_IN_NAME "AIF IN Source" +#define MA5311_AIF_OUT0_NAME "AIF OUT0 Source" +#define MA5311_AIF_OUT1_NAME "AIF OUT1 Source" + +#define MA5311_CONTROLLER_DEVICE_MASK BIT(7) +#define MA5311_DEVICE_MODE 0 +#define MA5311_CONTROLLER_MODE BIT(7) + +#define MA5311_SCK_RISING_MASK BIT(2) +#define MA5311_SCK_RISING_EDGE BIT(2) +#define MA5311_SCK_FALLING_EDGE 0 + +#define MA5311_LEFTPOL_MASK BIT(3) +#define MA5311_LOW_FIRST_CH 0 +#define MA5311_HIGH_FIRST_CH BIT(3) + +enum ma5311_mode { + MA5311_MONO_BOTH_MODE, + MA5311_STEREO_MODE, + MA5311_MONO_LEFT_MODE, + MA5311_MONO_RIGHT_MODE, +}; + +enum ma5311_setting { + MA5311_SPEAKER_MODE, + MA5311_RECEIVER_MODE, +}; + +enum ma5311_adc_mode { + MA5311_I2S_MODE_ADC1, + MA5311_I2S_MODE_ADC2, + MA5311_I2S_MODE_ADC3, + MA5311_I2S_MODE_ADC4, + MA5311_TDM_MODE, +}; + +#define MA5311_TSD_FAULT_STATUS BIT(2) + +/* Field encodings used by the existing serial audio configuration. */ +#define MA5311_DAC_A1_SCK_RATE_MASK GENMASK(4, 3) +#define MA5311_DAC_A1_SCK_RATE_32FS 0x18 +#define MA5311_DAC_A1_SCK_RATE_64FS 0x00 + +/* MA5311_DAC_38_TDM2 data length field. */ +#define MA5311_DAC_38_DATA_LEN_MASK BIT(7) +#define MA5311_DAC_38_DATA_LEN_16 0 +#define MA5311_DAC_38_DATA_LEN_32 BIT(7) +#define MA5311_DAC_38_CAPTURE_8CH_CFG 0x41 +#define MA5311_DAC_38_CAPTURE_4CH_CFG 0x01 + +/* Full-register values: keep the other DATA_PATH bits cleared. */ +#define MA5311_ADC_DATA_PATH_I2S 0x00 +#define MA5311_ADC_DATA_PATH_TDM_8CH 0x01 +#define MA5311_TDM_SLOT_ENABLE_ALL 0xff +#define MA5311_TDM_SLOT_DISABLE_ALL 0x00 + +/* Preserve the SCK_RATE encoding used for 16-bit ADC capture. */ +#define MA5311_ADC_SCK_RATE_16BIT_CFG 0x40 +#define MA5311_ADC_SCK_RATE_24BIT_CFG 0x00 + +/* 0xEA: DAC fault status */ +#define MA5311_DAC_EA_FAULT_MASK BIT(7) +#define MA5311_DAC_EA_UVLON_CH1_MASK BIT(6) +#define MA5311_DAC_EA_UVLON_CH2_MASK BIT(5) +#define MA5311_DAC_EA_TSDW_MASK BIT(3) +#define MA5311_DAC_EA_TSD_MASK BIT(2) + +/* 0xEB: DAC OCP status */ +#define MA5311_DAC_EB_IPSC_2U_MASK BIT(7) +#define MA5311_DAC_EB_IPSC_2L_MASK BIT(6) +#define MA5311_DAC_EB_IPSC_1U_MASK BIT(5) +#define MA5311_DAC_EB_IPSC_1L_MASK BIT(4) +#define MA5311_DAC_EB_OCP_2B_MASK BIT(3) +#define MA5311_DAC_EB_OCP_2A_MASK BIT(2) +#define MA5311_DAC_EB_OCP_1B_MASK BIT(1) +#define MA5311_DAC_EB_OCP_1A_MASK BIT(0) + +/* 0xEC: DAC SCP status */ +#define MA5311_DAC_EC_SCP_2B_MASK BIT(3) +#define MA5311_DAC_EC_SCP_2A_MASK BIT(2) +#define MA5311_DAC_EC_SCP_1B_MASK BIT(1) +#define MA5311_DAC_EC_SCP_1A_MASK BIT(0) + +/* 0xFB: Clock fault status */ +#define MA5311_DAC_FB_CLOCK_MON_MASK BIT(0) + +/* Factory Default */ +#define MA5311_PLL_POST_N_DEFAULT BIT(3) +#define MA5311_PLL_N_DEFAULT BIT(5) +#define MA5311_PLL_F1_DEFAULT 0 +#define MA5311_PLL_F2_DEFAULT 0 +#define MA5311_PLL_F3_P_CP_DEFAULT BIT(1) + +#define MA5311_LRCK_SCK_MAS_CLK_SEL_MASK BIT(0) +#define MA5311_LRCK_SCK_CLK_MASTER_MODE 1 +#define MA5311_LRCK_SCK_CLK_SLAVE_MODE 0 + +#define MA5311_DAC_CLKSYSTEM_MASK GENMASK(7, 5) +#define MA5311_DAC_EXT_CLK_24_576 BIT(7) +#define MA5311_DAC_INT_OSCILLATOR 0 + +#define MA5311_DAC_TDM_STEREO_MASK BIT(6) +#define MA5311_DAC_TDM_MONO 0 +#define MA5311_DAC_TDM_STEREO BIT(6) + +#define MA5311_DAC_ADC_CLK_ON_MASK BIT(4) +#define MA5311_DAC_ADC_CLK_ON BIT(4) +#define MA5311_DAC_ADC_CLK_OFF 0 + +#define MA5311_DISABLE_TDM_SLOT 0X00 +#define MA5311_ADC_MIX_CH0 0 +#define MA5311_ADC_DATA_PATH_CH0 0 + +#define MA5311_DAC_PLLIN_CLK_MASK BIT(7) +#define MA5311_DAC_PLLIN_EXT_OSC 0 +#define MA5311_DAC_PLLIN_INT_OSC BIT(7) + +#define MA5311_DAC_PLL_REF_CLK1_MASK BIT(4) +#define MA5311_DAC_PLL_REF_EXT_CLK 0 +#define MA5311_DAC_PLL_REF_INT_OSC BIT(4) + +#define MA5311_DAC_PLL_REF_CLK2_MASK BIT(3) +#define MA5311_DAC_PLL_REF_CLK2_REF1 0 +#define MA5311_DAC_PLL_REF_CLK2_SCK BIT(3) + +#endif /* _MA5311_H */ diff --git a/sound/soc/codecs/max98520.c b/sound/soc/codecs/max98520.c index 56e559db88de9d..a1996568dda446 100644 --- a/sound/soc/codecs/max98520.c +++ b/sound/soc/codecs/max98520.c @@ -643,11 +643,16 @@ static int max98520_suspend(struct device *dev) static int max98520_resume(struct device *dev) { struct max98520_priv *max98520 = dev_get_drvdata(dev); + int ret; regcache_cache_only(max98520->regmap, false); - regmap_write(max98520->regmap, MAX98520_R2000_SW_RESET, 1); - regcache_sync(max98520->regmap); - return 0; + ret = regmap_write(max98520->regmap, MAX98520_R2000_SW_RESET, 1); + if (!ret) + ret = regcache_sync(max98520->regmap); + if (ret) + regcache_cache_only(max98520->regmap, true); + + return ret; } static const struct dev_pm_ops max98520_pm = { diff --git a/sound/soc/codecs/rk817_codec.c b/sound/soc/codecs/rk817_codec.c index 2c0fe1dfd842c6..c7804b2b559c72 100644 --- a/sound/soc/codecs/rk817_codec.c +++ b/sound/soc/codecs/rk817_codec.c @@ -434,7 +434,7 @@ static int rk817_probe(struct snd_soc_component *component) static void rk817_remove(struct snd_soc_component *component) { - snd_soc_component_exit_regmap(component); + component->regmap = NULL; } static const struct snd_soc_component_driver soc_codec_dev_rk817 = { diff --git a/sound/soc/codecs/rt1320-sdw.c b/sound/soc/codecs/rt1320-sdw.c index 19079212ba6c04..6724012d5c09d5 100644 --- a/sound/soc/codecs/rt1320-sdw.c +++ b/sound/soc/codecs/rt1320-sdw.c @@ -2829,6 +2829,8 @@ static int rt1320_set_gain_put(struct snd_kcontrol *kcontrol, reg_base = SDW_SDCA_CTL(FUNC_NUM_MIC, RT1320_SDCA_ENT_FU113, RT1320_SDCA_CTL_FU_VOLUME, CH_01); regmap_read(rt1320->mbq_regmap, reg_base + i, ®value[i]); break; + default: + return -EINVAL; } gain_val[i] = ucontrol->value.integer.value[i]; @@ -2859,6 +2861,8 @@ static int rt1320_set_gain_put(struct snd_kcontrol *kcontrol, reg_base = SDW_SDCA_CTL(FUNC_NUM_MIC, RT1320_SDCA_ENT_FU113, RT1320_SDCA_CTL_FU_VOLUME, CH_01); err = regmap_write(rt1320->mbq_regmap, reg_base + i, gain_val[i]); break; + default: + return -EINVAL; } if (err < 0) @@ -2917,6 +2921,8 @@ static int rt1320_set_gain_get(struct snd_kcontrol *kcontrol, reg_base = SDW_SDCA_CTL(FUNC_NUM_MIC, RT1320_SDCA_ENT_FU113, RT1320_SDCA_CTL_FU_VOLUME, CH_01); regmap_read(rt1320->mbq_regmap, reg_base + i, ®value); break; + default: + return -EINVAL; } ctl = p->max - (((0x1e00 - regvalue) & 0xffff) / interval_offset); diff --git a/sound/soc/codecs/rt5514-spi.h b/sound/soc/codecs/rt5514-spi.h index cedb19709c9aca..fce9fba1fc9c88 100644 --- a/sound/soc/codecs/rt5514-spi.h +++ b/sound/soc/codecs/rt5514-spi.h @@ -9,9 +9,9 @@ #ifndef __RT5514_SPI_H__ #define __RT5514_SPI_H__ -/** +/* * RT5514_SPI_BUF_LEN is the buffer size of SPI master controller. -*/ + */ #define RT5514_SPI_BUF_LEN 240 #define RT5514_BUFFER_VOICE_BASE 0x18000200 diff --git a/sound/soc/codecs/sn624x-sdca-sdw.c b/sound/soc/codecs/sn624x-sdca-sdw.c index af6c0e7769b1e9..734c7eb91d908a 100644 --- a/sound/soc/codecs/sn624x-sdca-sdw.c +++ b/sound/soc/codecs/sn624x-sdca-sdw.c @@ -176,6 +176,9 @@ static int sn624x_uaj_ge35_apply_detected_mode(struct device *dev, SDW_SDCA_CTL(SN624X_FUNC_NUM_MIC_ARRAY, SN624X_SDCA_ENT_ENTITY0, \ SN624X_SDCA_CTL_FUNCTION_STATUS, 0) +#define SN624X_REG_AMP_FUN_STATUS_CTL \ + SDW_SDCA_CTL(SN624X_FUNC_NUM_SPEAKER_AMP, SN624X_SDCA_ENT_ENTITY0, \ + SN624X_SDCA_CTL_FUNCTION_STATUS, 0) /* * Write REQUESTED_PS then poll ACTUAL_PS with the shared SDCA helper * (sdca_asoc_pde_poll_actual_ps). Caller must not hand-roll ACTUAL_PS waits. @@ -1055,6 +1058,49 @@ static int sn624x_dmic_apply_defaults(struct device *dev, return sn624x_dmic_oem_fallback_init(dev, sn624x); } +/* + * Return true only when ACPI DisCo is present and lists no MIC function. + * Without DisCo, return false so the legacy OEM fallback path still runs. + */ +static bool sn624x_sdca_disco_omits_mic(const struct sdw_slave *slave) +{ + int i; + + if (!slave->sdca_data.interface_revision || !slave->sdca_data.num_functions) + return false; + for (i = 0; i < slave->sdca_data.num_functions; i++) { + const struct sdca_function_desc *desc = &slave->sdca_data.function[i]; + + if (desc->adr == SN624X_FUNC_NUM_MIC_ARRAY) + return false; + switch (desc->type) { + case SDCA_FUNCTION_TYPE_SMART_MIC: + case SDCA_FUNCTION_TYPE_SIMPLE_MIC: + return false; + default: + break; + } + } + return true; +} + +static int sn624x_amp_apply_defaults(struct device *dev, + struct sn624x_sdca_priv *sn624x) +{ + int ret; + + if (!sn624x || !sn624x->regmap || !sn624x->slave) + return -ENODEV; + if (!sn624x->amp_func) + return 0; + ret = sn624x_write_sdca_init_table(dev, sn624x, sn624x->amp_func, "amp"); + if (ret == -ENOENT) + return 0; + if (ret == 0) + usleep_range(1000, 1500); + return ret; +} + static int sn624x_sdca_jack_function_init(struct device *dev, struct sn624x_sdca_priv *sn624x) { @@ -1088,11 +1134,18 @@ static int sn624x_sdca_jack_function_init(struct device *dev, static int sn624x_sdca_dmic_function_init(struct device *dev, struct sn624x_sdca_priv *sn624x) { + struct sdw_slave *slave = sn624x->slave; unsigned int dmic_func_status; const struct reg_sequence clear_status = REG_SEQ0(SN624X_REG_DMIC_FUN_STATUS_CTL, 0x61); int ret; + if (sn624x_sdca_disco_omits_mic(slave)) { + dev_dbg(dev, + "sn624x: ACPI DisCo has no MIC function, skip DMIC init\n"); + return 0; + } + ret = regmap_read_bypassed(sn624x->regmap, SN624X_REG_DMIC_FUN_STATUS_CTL, &dmic_func_status); @@ -1104,6 +1157,39 @@ static int sn624x_sdca_dmic_function_init(struct device *dev, return 0; ret = sn624x_dmic_apply_defaults(dev, sn624x); + if (ret < 0) + return ret; + ret = regmap_multi_reg_write_bypassed(sn624x->regmap, &clear_status, 1); + if (ret < 0) + return ret; + usleep_range(1000, 1500); + return 0; +} + +static int sn624x_sdca_amp_function_init(struct device *dev, + struct sn624x_sdca_priv *sn624x) +{ + unsigned int amp_func_status; + const struct reg_sequence clear_status = + REG_SEQ0(SN624X_REG_AMP_FUN_STATUS_CTL, 0x61); + int ret; + + if (!sn624x->amp_func) + return 0; + ret = regmap_read_bypassed(sn624x->regmap, + SN624X_REG_AMP_FUN_STATUS_CTL, + &_func_status); + if (ret < 0) + return ret; + if (!(amp_func_status & (SN624X_JACK_FUN_NEEDS_INIT | + SN624X_JACK_FUN_HAS_BEEN_RESET))) { + if (!sn624x->amp_func->num_init_table) + return 0; + dev_dbg(dev, + "sn624x: amp FUN STATUS 0x%x, apply ACPI init table\n", + amp_func_status); + } + ret = sn624x_amp_apply_defaults(dev, sn624x); if (ret < 0) return ret; @@ -1161,6 +1247,11 @@ static int sn624x_sdca_io_init(struct device *dev, struct sdw_slave *slave) dev_err(dev, "sn624x: jack function init failed (%d)\n", ret); goto err; } + ret = sn624x_sdca_amp_function_init(dev, sn624x); + if (ret < 0) { + dev_err(dev, "sn624x: amp function init failed (%d)\n", ret); + goto err; + } ret = sn624x_sdca_dmic_function_init(dev, sn624x); if (ret < 0) { @@ -1253,8 +1344,9 @@ static int sn624x_sdca_read_prop(struct sdw_slave *slave) prop->use_domain_irq = true; prop->wake_capable = true; - prop->source_ports = BIT(SN624X_PORT_JACK_CAPTURE) | - BIT(SN624X_PORT_DMIC_CAPTURE); + prop->source_ports = BIT(SN624X_PORT_JACK_CAPTURE); + if (!sn624x_sdca_disco_omits_mic(slave)) + prop->source_ports |= BIT(SN624X_PORT_DMIC_CAPTURE); prop->sink_ports = BIT(SN624X_PORT_JACK_PLAYBACK) | BIT(SN624X_PORT_SPEAKER_PLAYBACK); @@ -1292,8 +1384,9 @@ static int sn624x_sdca_read_prop(struct sdw_slave *slave) prop->simple_clk_stop_capable = true; prop->lane_control_support = true; SN624X_DBG(&slave->dev, - "read_prop: src_ports=0x%x sink_ports=0x%x lane irq paging\n", - prop->source_ports, prop->sink_ports); + "read_prop: src_ports=0x%x sink_ports=0x%x disco_omits_mic=%d lane irq paging\n", + prop->source_ports, prop->sink_ports, + sn624x_sdca_disco_omits_mic(slave)); return 0; } diff --git a/sound/soc/codecs/tas2557.c b/sound/soc/codecs/tas2557.c new file mode 100644 index 00000000000000..c49917149c863d --- /dev/null +++ b/sound/soc/codecs/tas2557.c @@ -0,0 +1,2973 @@ +// SPDX-License-Identifier: GPL-2.0-only +// +// ALSA SoC Texas Instruments TAS2557 Smart Amplifier +// +// Copyright (C) 2016 Texas Instruments Inc. +// Copyright (C) 2026 Gianluca Boiano +// +// The TAS2557 requires DSP firmware (tas2557_uCDSP.bin for PG2.x, +// tas2557_pg1p0_uCDSP.bin for PG1.0) to route audio through its internal +// DSP and DAC. Without loaded firmware the device produces no audio. +// +// Probe reads REV_PGID to detect the PG version, then requests firmware +// asynchronously. The firmware program, PLL and config blocks are loaded +// once the firmware arrives and again only when the chips lost them or a +// different config is needed (sample rate change, fault recovery, resume). +// +// Register access, the paged regmap and the i2c_client address swap needed +// to reach several chips through one i2c_client are provided by +// tas2781-comlib(-i2c). One DT node drives up to TAS2557_MAX_DEV chips, +// addressed by channel index into tas_priv->tasdevice[] and +// struct tas2557_priv::devs[]. Firmware, DAI, power and mute state are +// shared by the group; DSP program bookkeeping, ASI slot offsets and the +// reset/IRQ lines are per chip. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "tas2557.h" + +/* Special delay markers embedded in register sequence tables */ +#define TAS2557_UDELAY 0xFFFFFFFE +#define TAS2557_MDELAY 0xFFFFFFFD + +/* Supported PCM formats exposed to the ASoC core */ +#define TAS2557_FORMATS \ + (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S20_3LE | \ + SNDRV_PCM_FMTBIT_S24_LE | SNDRV_PCM_FMTBIT_S32_LE) + +/* struct tas2557_block - one block of register-write commands from firmware */ +struct tas2557_block { + u32 type; + u32 num_commands; + u8 *data; /* num_commands * 4 bytes: [book][page][reg][val] */ +}; + +/* struct tas2557_data - named container of firmware blocks */ +struct tas2557_data { + char name[64]; + u32 num_blocks; + struct tas2557_block *blocks; +}; + +/* struct tas2557_pll - one PLL configuration */ +struct tas2557_pll { + char name[64]; + struct tas2557_block block; +}; + +/* struct tas2557_program - one DSP program */ +struct tas2557_program { + char name[64]; + struct tas2557_data data; +}; + +/* struct tas2557_config - one audio configuration (tied to a sample rate) */ +struct tas2557_config { + char name[64]; + u32 program; /* which program this config is for */ + u32 pll; /* which PLL config to use */ + u32 sample_rate; + struct tas2557_data data; +}; + +/* struct tas2557_firmware - top-level parsed firmware container */ +struct tas2557_firmware { + u32 ppc_version; + u32 fw_version; + u32 driver_version; + u32 device; + u32 num_plls; + struct tas2557_pll *plls; + u32 num_programs; + struct tas2557_program *programs; + u32 num_configs; + struct tas2557_config *configs; +}; + +/* + * struct tas2557_dev - per-chip state that comlib's struct tasdevice has + * no field for. One instance per entry in tas_priv->tasdevice[]. + */ +struct tas2557_dev { + /* Hardware revision of this chip */ + int pg_id; + + /* + * DSP program/config currently loaded and recovery-attempt count. + * tas2557_set_program() drives every chip to the same program and + * config, so these stay in lock-step; devs[0] is read back as the + * group's value. + */ + unsigned int current_program; + unsigned int current_config; + unsigned int restart_count; + + /* + * Cached ASI RX (playback) data-slot offset in BCLK cycles for this + * chip, set by set_tdm_slot() and re-applied by + * tas2557_apply_runtime_state(). + */ + unsigned int asi_offset; +}; + +/* + * struct tas2557_priv - group driver state (one node, up to TAS2557_MAX_DEV + * chips), wrapping the shared tas2781-comlib device. + */ +struct tas2557_priv { + struct tasdevice_priv *tas_priv; + + /* Per-device reset lines and fault IRQs (reset-gpios/interrupts) */ + struct gpio_desc *reset[TAS2557_MAX_DEV]; + int irq[TAS2557_MAX_DEV]; + bool irq_enabled; + + /* Which ASI (1 or 2) this board wires up (ti,asi-port, default 2) */ + unsigned int asi_port; + + /* Chip-specific state, one entry per tas_priv->tasdevice[] slot */ + struct tas2557_dev devs[TAS2557_MAX_DEV]; + + /* Power state */ + bool powered; + bool dac_muted; /* mute state for SNDRV_PCM_STREAM_PLAYBACK */ + + /* Firmware state, one image shared by the group */ + struct tas2557_firmware *fw; /* NULL until tas2557_fw_ready() parses it */ + char fw_name[64]; /* filename requested at probe */ + bool fw_requested; /* request_firmware_nowait() was issued */ + struct completion fw_done; /* signalled when tas2557_fw_ready() returns */ + + /* + * devs[].current_program/current_config are still loaded on the + * chips. Cleared by every reset, resume, fw (re)load and failed + * program load; set when tas2557_set_program() completes. + */ + bool prog_valid; + + /* Sample rates of the current program's configs, for DAI startup */ + unsigned int *rates; + struct snd_pcm_hw_constraint_list rate_list; + + /* Runtime audio configuration */ + unsigned int sample_rate; + int dai_fmt; /* ASI format from set_dai_fmt(), -1 = never set */ + unsigned int asi_delay; /* 1 BCLK for DSP_A, 0 otherwise */ + unsigned int wordlength; /* ASI WORDLENGTH_* bits from hw_params */ + + bool tdm_configured; /* true once set_tdm_slot() set an RX slot */ + + /* Volume control */ + unsigned int dac_gain; +}; + +/* + * tas2557_asi_reg() - pick the DAC format or RX offset register of + * whichever ASI (ti,asi-port) this board wires up. The other ASI's + * registers are never written by this driver. + */ +static unsigned int tas2557_asi_reg(struct tas2557_priv *tas2557, + unsigned int asi1_reg, unsigned int asi2_reg) +{ + return tas2557->asi_port == TAS2557_ASI_PORT1 ? asi1_reg : asi2_reg; +} + +/* Forward declarations */ +static void tas2557_hw_reset(struct tas2557_priv *tas2557); +static int tas2557_failsafe_recovery(struct tas2557_priv *tas2557); +static int tas2557_apply_runtime_state(struct tas2557_priv *tas2557); +static int tas2557_power_up_locked(struct tas2557_priv *tas2557, + unsigned int prog_idx); + +/* + * Default device initialization sequence - identical to the TI Android + * driver (p_tas2557_default_data). Written once after every + * hardware/software reset. + */ +static const unsigned int tas2557_default_data[] = { + TAS2557_SAR_ADC2_REG, 0x05, /* enable SAR ADC */ + TAS2557_CLK_ERR_CTRL2, 0x21, /* clk1: hysteresis 0.34 ms */ + TAS2557_CLK_ERR_CTRL3, 0x21, /* clk2: rampDown 15 dB/us */ + TAS2557_SAFE_GUARD_REG, TAS2557_SAFE_GUARD_PATTERN, + 0xFFFFFFFF, 0xFFFFFFFF +}; + +/* + * Interrupt output configuration - identical to the TI reference + * (p_tas2557_irq_config). Reloaded after every reset. GPIO4=INT1 + * output is wired the same way regardless of which ASI carries audio, + * so it stays common to both ASI selections. + */ +static const unsigned int tas2557_irq_config[] = { + TAS2557_CLK_HALT_REG, 0x71, /* enable clk-halt detect2 interrupt */ + TAS2557_INT_GEN1_REG, 0x11, /* enable SPK OC and OV */ + TAS2557_INT_GEN2_REG, 0x11, /* enable clk-err1 and die OT */ + TAS2557_INT_GEN3_REG, 0x11, /* enable clk-err2 and brownout */ + TAS2557_INT_GEN4_REG, 0x01, /* disable SAR, enable clk-halt */ + TAS2557_GPIO4_PIN_REG, 0x07, /* GPIO4 = INT1 output */ + TAS2557_INT_MODE_REG, 0x80, /* active-high, held until cleared */ + 0xFFFFFFFF, 0xFFFFFFFF +}; + +/* + * Startup sequence - power up Class-D, Boost, DSP/PLL clocks. Split into + * a common part and one part per ASI: only the ASI selected by + * ti,asi-port is programmed, the other ASI's GPIOx_PIN registers stay at + * reset defaults. The PLL is not configured here; it comes from the + * firmware PLL block loaded by tas2557_set_program(). + */ +static const unsigned int tas2557_startup_common_data[] = { + TAS2557_GPI_PIN_REG, 0x15, /* enable DIN, MCLK, CCI */ + /* Power sequencing: Class-D + Boost first, then DSP/PLL */ + TAS2557_POWER_CTRL2_REG, 0xA0, /* Class-D, Boost power up */ + TAS2557_POWER_CTRL2_REG, 0xA3, /* Class-D, Boost, IV-sense power up */ + TAS2557_POWER_CTRL1_REG, 0xF8, /* PLL, DSP, clock dividers power up */ + TAS2557_UDELAY, 2000, /* 2 ms stabilisation */ + /* CE1_IC = ASI1; TI's ASI2 build writes the same value */ + TAS2557_CLK_ERR_CTRL, 0x2b, /* enable clock error detection */ + TAS2557_DBOOST_CFG_REG, 0x0b, /* reduce full-band noise */ + 0xFFFFFFFF, 0xFFFFFFFF +}; + +/* ASI1 pin wiring: BCLK/WCLK/DOUT on GPIO1/GPIO2/GPIO3 */ +static const unsigned int tas2557_startup_asi1_data[] = { + TAS2557_GPIO1_PIN_REG, 0x01, /* enable BCLK (ASI1) */ + TAS2557_GPIO2_PIN_REG, 0x01, /* enable WCLK (ASI1) */ + TAS2557_GPIO3_PIN_REG, 0x10, /* GPIO3 = ASI1 DOUT */ + 0xFFFFFFFF, 0xFFFFFFFF +}; + +/* + * ASI2 pin wiring (GPIO5-8) and BDIV/WDIV clock dividers; arm the BCLK + * source (GPIO5) before its dividers. + */ +static const unsigned int tas2557_startup_asi2_data[] = { + TAS2557_GPIO6_PIN_REG, 0x01, /* GPIO6 = ASI2 WCLK input */ + TAS2557_GPIO8_PIN_REG, 0x02, /* GPIO8 = ASI2 DIN */ + TAS2557_GPIO5_PIN_REG, 0x01, /* GPIO5 = ASI2 BCLK input */ + TAS2557_ASI2_BDIV_CLK_SEL_REG, 0x01, + TAS2557_ASI2_BDIV_CLK_RATIO_REG, 0x01, + TAS2557_ASI2_BDIV_CLK_RATIO_REG, 0x81, /* power up BDIV */ + TAS2557_ASI2_WDIV_CLK_RATIO_REG, 0x40, + TAS2557_ASI2_WDIV_CLK_RATIO_REG, 0xc0, /* power up WDIV */ + TAS2557_GPIO7_PIN_REG, 0x15, /* GPIO7 = ASI2 DOUT */ + 0xFFFFFFFF, 0xFFFFFFFF +}; + +/* Unmute sequence */ +static const unsigned int tas2557_unmute_data[] = { + TAS2557_MUTE_REG, 0x00, /* unmute I and V sense */ + TAS2557_SOFT_MUTE_REG, 0x00, /* clear soft-mute in DSP */ + 0xFFFFFFFF, 0xFFFFFFFF +}; + +/* Shutdown sequence: device-independent part, run before the ASI part */ +static const unsigned int tas2557_shutdown_common_data[] = { + TAS2557_CLK_ERR_CTRL, 0x00, /* disable clock error detection */ + TAS2557_SOFT_MUTE_REG, 0x01, /* soft mute */ + TAS2557_UDELAY, 10000, /* 10 ms */ + TAS2557_MUTE_REG, 0x03, /* mute I and V sense */ + TAS2557_POWER_CTRL1_REG, 0x60, /* DSP power down */ + TAS2557_UDELAY, 2000, /* 2 ms */ + TAS2557_POWER_CTRL2_REG, 0x00, /* Class-D, Boost power down */ + TAS2557_POWER_CTRL1_REG, 0x00, /* all power down */ + 0xFFFFFFFF, 0xFFFFFFFF +}; + +/* Disable ASI1 GPIOs */ +static const unsigned int tas2557_shutdown_asi1_data[] = { + TAS2557_GPIO1_PIN_REG, 0x00, + TAS2557_GPIO2_PIN_REG, 0x00, + TAS2557_GPIO3_PIN_REG, 0x00, + 0xFFFFFFFF, 0xFFFFFFFF +}; + +/* Disable ASI2 GPIOs */ +static const unsigned int tas2557_shutdown_asi2_data[] = { + TAS2557_GPIO5_PIN_REG, 0x00, + TAS2557_GPIO6_PIN_REG, 0x00, + TAS2557_GPIO7_PIN_REG, 0x00, + TAS2557_GPIO8_PIN_REG, 0x00, + 0xFFFFFFFF, 0xFFFFFFFF +}; + +/* Disable the shared DIN/MCLK/CCI enable, run after the ASI-specific part */ +static const unsigned int tas2557_shutdown_tail_data[] = { + TAS2557_GPI_PIN_REG, 0x00, + 0xFFFFFFFF, 0xFFFFFFFF +}; + +/* + * Book/page/register access + * + * All register I/O goes through tas2781-comlib's tasdevice_dev_*() + * helpers, which drive a paged regmap and swap the i2c_client address to + * reach each chip in the group. Comlib does not lock: every caller holds + * tas_priv->codec_lock, which also protects all driver state. @chn + * indexes tas_priv->tasdevice[]/tas2557->devs[]; @reg is built with + * TASDEVICE_REG(book, page, reg). + */ + +static int tas2557_dev_read(struct tas2557_priv *tas2557, unsigned int chn, + unsigned int reg, unsigned int *value) +{ + return tasdevice_dev_read(tas2557->tas_priv, chn, reg, value); +} + +static int tas2557_dev_write(struct tas2557_priv *tas2557, unsigned int chn, + unsigned int reg, unsigned int value) +{ + return tasdevice_dev_write(tas2557->tas_priv, chn, reg, value); +} + +static int tas2557_dev_update_bits(struct tas2557_priv *tas2557, unsigned int chn, + unsigned int reg, unsigned int mask, + unsigned int value) +{ + return tasdevice_dev_update_bits(tas2557->tas_priv, chn, reg, mask, value); +} + +static int tas2557_dev_bulk_write(struct tas2557_priv *tas2557, unsigned int chn, + unsigned int reg, const u8 *data, size_t len) +{ + /* The chip auto-increments past reg 0x7f into the page register */ + if (TASDEVICE_PAGE_REG(reg) + len > 128) + return -EINVAL; + + return tasdevice_dev_bulk_write(tas2557->tas_priv, chn, reg, + (unsigned char *)data, len); +} + +static int tas2557_load_data(struct tas2557_priv *tas2557, unsigned int chn, + const unsigned int *data) +{ + unsigned int reg, val; + int i = 0, ret = 0; + + while (1) { + reg = data[i * 2]; + val = data[i * 2 + 1]; + + if (reg == 0xFFFFFFFF) + break; + + if (reg == TAS2557_UDELAY) { + usleep_range(val, val + 100); + } else if (reg == TAS2557_MDELAY) { + msleep(val); + } else { + ret = tas2557_dev_write(tas2557, chn, reg, val); + if (ret < 0) + break; + } + i++; + } + + return ret; +} + +/* tas2557_load_data_all - apply a {reg,val} sequence table to every chip */ +static int tas2557_load_data_all(struct tas2557_priv *tas2557, + const unsigned int *data) +{ + unsigned int chn; + int ret; + + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) { + ret = tas2557_load_data(tas2557, chn, data); + if (ret < 0) + return ret; + } + + return 0; +} + +/* tas2557_write_all - write the same register/value to every chip */ +static int tas2557_write_all(struct tas2557_priv *tas2557, + unsigned int reg, unsigned int value) +{ + unsigned int chn; + int ret; + + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) { + ret = tas2557_dev_write(tas2557, chn, reg, value); + if (ret < 0) + return ret; + } + + return 0; +} + +/* tas2557_update_bits_all - update_bits the same register/mask/value on every chip */ +static int tas2557_update_bits_all(struct tas2557_priv *tas2557, + unsigned int reg, unsigned int mask, + unsigned int value) +{ + unsigned int chn; + int ret; + + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) { + ret = tas2557_dev_update_bits(tas2557, chn, reg, mask, value); + if (ret < 0) + return ret; + } + + return 0; +} + +/* + * tas2557_asi_fmt_update_all - update_bits @mask/@value in the DAC (playback) + * format register of the selected ASI on every chip. + */ +static int tas2557_asi_fmt_update_all(struct tas2557_priv *tas2557, + unsigned int mask, unsigned int value) +{ + unsigned int dac = tas2557_asi_reg(tas2557, TAS2557_ASI1_DAC_FORMAT_REG, + TAS2557_ASI2_DAC_FORMAT_REG); + + return tas2557_update_bits_all(tas2557, dac, mask, value); +} + +/* + * tas2557_write_rx_offset - program OFFSET1 of the selected ASI on one chip: + * its TDM slot offset plus the 1 BCLK delay of DSP_A. The chip's DSP + * format at offset 0 is DSP_B. + */ +static int tas2557_write_rx_offset(struct tas2557_priv *tas2557, + unsigned int chn) +{ + unsigned int reg = tas2557_asi_reg(tas2557, TAS2557_ASI1_OFFSET1_REG, + TAS2557_ASI2_OFFSET1_REG); + + return tas2557_dev_write(tas2557, chn, reg, + tas2557->asi_delay + tas2557->devs[chn].asi_offset); +} + +/* + * tas2557_startup_sequence / tas2557_shutdown_sequence - run the common + * part of the power up/down sequence together with the part of the ASI + * selected by ti,asi-port. + * + * The shutdown tables only mute, stop clock error detection, power down + * the DSP/PLL/Class-D blocks and clear the GPIO pin muxes. They do not + * reset the chip or write the DSP program, coefficient or PLL registers, + * so the firmware loaded by tas2557_set_program() survives a shutdown and + * the next power-up only has to re-run the startup sequence. + */ +static int tas2557_startup_sequence(struct tas2557_priv *tas2557) +{ + const unsigned int *asi = tas2557->asi_port == TAS2557_ASI_PORT1 ? + tas2557_startup_asi1_data : + tas2557_startup_asi2_data; + unsigned int dout_reg = tas2557_asi_reg(tas2557, TAS2557_GPIO3_PIN_REG, + TAS2557_GPIO7_PIN_REG); + unsigned int chn; + int ret; + + ret = tas2557_load_data_all(tas2557, tas2557_startup_common_data); + if (ret < 0) + return ret; + + ret = tas2557_load_data_all(tas2557, asi); + if (ret < 0) + return ret; + + /* Only chip 0 drives DOUT of the shared ASI */ + for (chn = 1; chn < tas2557->tas_priv->ndev; chn++) { + ret = tas2557_dev_write(tas2557, chn, dout_reg, 0x00); + if (ret < 0) + return ret; + } + + return 0; +} + +static int tas2557_shutdown_sequence(struct tas2557_priv *tas2557) +{ + const unsigned int *asi = tas2557->asi_port == TAS2557_ASI_PORT1 ? + tas2557_shutdown_asi1_data : + tas2557_shutdown_asi2_data; + int ret; + + ret = tas2557_load_data_all(tas2557, tas2557_shutdown_common_data); + if (ret < 0) + return ret; + + ret = tas2557_load_data_all(tas2557, asi); + if (ret < 0) + return ret; + + return tas2557_load_data_all(tas2557, tas2557_shutdown_tail_data); +} + +/* ========================================================================= + * Firmware parsing + * + * Format (all multi-byte fields are big-endian): + * 4 bytes magic 0x35 0x35 0x35 0x32 ("5552") + * 4 bytes size + * 4 bytes checksum + * 4 bytes ppc_version + * 4 bytes fw_version + * 4 bytes driver_version + * 4 bytes timestamp + * 64 bytes ddc_name (null-padded) + * N bytes description (null-terminated string) + * 4 bytes device_family (must be 0) + * 4 bytes device (2 = mono, 3 = stereo) + * then PLLs, programs, configs + * + * Fields the driver does not use (size, checksum, timestamp, description, + * per-block checksums, ...) are skipped, not stored. + * ========================================================================= + */ + +static void tas2557_fw_free(struct tas2557_firmware *fw) +{ + unsigned int i, j; + + if (!fw) + return; + + if (fw->plls) { + for (i = 0; i < fw->num_plls; i++) + kfree(fw->plls[i].block.data); + kfree(fw->plls); + } + + if (fw->programs) { + for (i = 0; i < fw->num_programs; i++) { + if (fw->programs[i].data.blocks) { + for (j = 0; j < fw->programs[i].data.num_blocks; j++) + kfree(fw->programs[i].data.blocks[j].data); + kfree(fw->programs[i].data.blocks); + } + } + kfree(fw->programs); + } + + if (fw->configs) { + for (i = 0; i < fw->num_configs; i++) { + if (fw->configs[i].data.blocks) { + for (j = 0; j < fw->configs[i].data.num_blocks; j++) + kfree(fw->configs[i].data.blocks[j].data); + kfree(fw->configs[i].data.blocks); + } + } + kfree(fw->configs); + } + + kfree(fw); +} + +static int fw_parse_header(struct tas2557_priv *tas2557, + struct tas2557_firmware *fw, + const u8 *data, size_t size) +{ + const u8 *start = data; + size_t desc_len; + u32 device_family; + char ddc_name[64]; + + if (size < 104) { + dev_err(tas2557->tas_priv->dev, "firmware header too short (%zu bytes)\n", + size); + return -EINVAL; + } + + /* Magic: four bytes "5552" (0x35 0x35 0x35 0x32) */ + if (data[0] != 0x35 || data[1] != 0x35 || + data[2] != 0x35 || data[3] != 0x32) { + dev_err(tas2557->tas_priv->dev, + "firmware magic mismatch: %02x%02x%02x%02x (expected 35353532)\n", + data[0], data[1], data[2], data[3]); + return -EINVAL; + } + data += 4; + + /* size, checksum: not needed at runtime, skip */ + data += 8; + + fw->ppc_version = get_unaligned_be32(data); data += 4; + fw->fw_version = get_unaligned_be32(data); data += 4; + fw->driver_version = get_unaligned_be32(data); data += 4; + + /* timestamp: not needed at runtime, skip */ + data += 4; + + memcpy(ddc_name, data, 64); + ddc_name[63] = '\0'; + data += 64; + + desc_len = strnlen(data, size - (size_t)(data - start)); + if (desc_len >= size - (size_t)(data - start)) { + dev_err(tas2557->tas_priv->dev, "firmware header: description not NUL-terminated\n"); + return -EINVAL; + } + /* description string: informational only, not stored */ + data += desc_len + 1; + + if ((data - start) + 8 > (ptrdiff_t)size) { + dev_err(tas2557->tas_priv->dev, "firmware header truncated\n"); + return -EINVAL; + } + + device_family = get_unaligned_be32(data); data += 4; + if (device_family != 0) { + dev_err(tas2557->tas_priv->dev, "unsupported device family: %u\n", + device_family); + return -EINVAL; + } + + fw->device = get_unaligned_be32(data); data += 4; + if (fw->device != TASDEVICE_DSP_TAS_2557_MONO && + fw->device != TASDEVICE_DSP_TAS_2557_DUAL_MONO) { + dev_err(tas2557->tas_priv->dev, + "unsupported device %u in firmware (expected 2=mono or 3=stereo)\n", + fw->device); + return -EINVAL; + } + + dev_dbg(tas2557->tas_priv->dev, + "firmware header: DDC=%s fw_ver=0x%x ppc=0x%x drv=0x%x\n", + ddc_name, fw->fw_version, fw->ppc_version, fw->driver_version); + + return data - start; +} + +static int fw_parse_block(struct tas2557_priv *tas2557, + struct tas2557_firmware *fw, + struct tas2557_block *block, + const u8 *data, size_t remaining) +{ + const u8 *start = data; + size_t data_len; + + if (remaining < 4) + return -EINVAL; + + block->type = get_unaligned_be32(data); + data += 4; + remaining -= 4; + + if (fw->driver_version >= PPC_DRIVER_CRCCHK) { + /* Per-block checksum bytes (pchksum/ychksum): not used, skip */ + if (remaining < 4) + return -EINVAL; + data += 4; + remaining -= 4; + } + + if (remaining < 4) + return -EINVAL; + + block->num_commands = get_unaligned_be32(data); + data += 4; + remaining -= 4; + + /* + * num_commands comes straight from the firmware file; bound it + * against the bytes left before multiplying so the size cannot wrap. + */ + if (block->num_commands > remaining / 4) { + dev_err(tas2557->tas_priv->dev, + "block type 0x%x truncated: %u cmds, %zu bytes left\n", + block->type, block->num_commands, remaining); + return -EINVAL; + } + data_len = (size_t)block->num_commands * 4; + + if (data_len > 0) { + block->data = kmemdup(data, data_len, GFP_KERNEL); + if (!block->data) + return -ENOMEM; + } + data += data_len; + + return data - start; +} + +static int fw_parse_data(struct tas2557_priv *tas2557, + struct tas2557_firmware *fw, + struct tas2557_data *img_data, + const u8 *data, size_t remaining) +{ + const u8 *start = data; + size_t desc_len; + unsigned int i; + int ret; + + if (remaining < 64) + return -EINVAL; + + memcpy(img_data->name, data, 64); + img_data->name[63] = '\0'; + data += 64; + remaining -= 64; + + desc_len = strnlen(data, remaining); + if (desc_len >= remaining) + return -EINVAL; + /* description string: informational only, not stored */ + data += desc_len + 1; + remaining -= desc_len + 1; + + if (remaining < 2) + return -EINVAL; + + img_data->num_blocks = get_unaligned_be16(data); + data += 2; + remaining -= 2; + + if (img_data->num_blocks == 0) + return data - start; + + img_data->blocks = kcalloc(img_data->num_blocks, + sizeof(struct tas2557_block), GFP_KERNEL); + if (!img_data->blocks) + return -ENOMEM; + + for (i = 0; i < img_data->num_blocks; i++) { + ret = fw_parse_block(tas2557, fw, &img_data->blocks[i], + data, remaining); + if (ret < 0) + return ret; + data += ret; + remaining -= ret; + } + + return data - start; +} + +static int fw_parse_plls(struct tas2557_priv *tas2557, + struct tas2557_firmware *fw, + const u8 *data, size_t remaining) +{ + const u8 *start = data; + size_t desc_len; + unsigned int i; + int ret; + + if (remaining < 2) + return -EINVAL; + + fw->num_plls = get_unaligned_be16(data); + data += 2; + remaining -= 2; + + if (fw->num_plls == 0) + return data - start; + + fw->plls = kcalloc(fw->num_plls, sizeof(struct tas2557_pll), + GFP_KERNEL); + if (!fw->plls) + return -ENOMEM; + + for (i = 0; i < fw->num_plls; i++) { + if (remaining < 64) + return -EINVAL; + + memcpy(fw->plls[i].name, data, 64); + fw->plls[i].name[63] = '\0'; + data += 64; + remaining -= 64; + + desc_len = strnlen(data, remaining); + if (desc_len >= remaining) + return -EINVAL; + data += desc_len + 1; + remaining -= desc_len + 1; + + ret = fw_parse_block(tas2557, fw, &fw->plls[i].block, + data, remaining); + if (ret < 0) + return ret; + data += ret; + remaining -= ret; + } + + return data - start; +} + +static int fw_parse_programs(struct tas2557_priv *tas2557, + struct tas2557_firmware *fw, + const u8 *data, size_t remaining) +{ + const u8 *start = data; + size_t desc_len; + unsigned int i; + int ret; + + if (remaining < 2) + return -EINVAL; + + fw->num_programs = get_unaligned_be16(data); + data += 2; + remaining -= 2; + + if (fw->num_programs == 0) { + dev_err(tas2557->tas_priv->dev, "firmware contains no programs\n"); + return -EINVAL; + } + + fw->programs = kcalloc(fw->num_programs, sizeof(struct tas2557_program), + GFP_KERNEL); + if (!fw->programs) + return -ENOMEM; + + for (i = 0; i < fw->num_programs; i++) { + if (remaining < 64) + return -EINVAL; + + memcpy(fw->programs[i].name, data, 64); + fw->programs[i].name[63] = '\0'; + data += 64; + remaining -= 64; + + desc_len = strnlen(data, remaining); + if (desc_len >= remaining) + return -EINVAL; + data += desc_len + 1; + remaining -= desc_len + 1; + + /* app_mode (1 byte) + boost (2 bytes): not used, skip */ + if (remaining < 3) + return -EINVAL; + data += 3; + remaining -= 3; + + ret = fw_parse_data(tas2557, fw, &fw->programs[i].data, + data, remaining); + if (ret < 0) + return ret; + data += ret; + remaining -= ret; + } + + return data - start; +} + +static int fw_parse_configs(struct tas2557_priv *tas2557, + struct tas2557_firmware *fw, + const u8 *data, size_t remaining) +{ + const u8 *start = data; + size_t desc_len; + unsigned int i; + int ret; + + if (remaining < 2) + return -EINVAL; + + fw->num_configs = get_unaligned_be16(data); + data += 2; + remaining -= 2; + + if (fw->num_configs == 0) { + dev_err(tas2557->tas_priv->dev, "firmware contains no configurations\n"); + return -EINVAL; + } + + fw->configs = kcalloc(fw->num_configs, sizeof(struct tas2557_config), + GFP_KERNEL); + if (!fw->configs) + return -ENOMEM; + + for (i = 0; i < fw->num_configs; i++) { + if (remaining < 64) + return -EINVAL; + + memcpy(fw->configs[i].name, data, 64); + fw->configs[i].name[63] = '\0'; + data += 64; + remaining -= 64; + + desc_len = strnlen(data, remaining); + if (desc_len >= remaining) + return -EINVAL; + data += desc_len + 1; + remaining -= desc_len + 1; + + /* + * Device-count field present from driver_version 0x101. + * Consume it (unused here) across the [0x101, 0x1ff] band + * and for >= 0x300, matching the TI fw_parse_configuration. + */ + if (fw->driver_version >= PPC_DRIVER_CONFDEV || + (fw->driver_version >= PPC_DRIVER_CFGDEV_NONCRC && + fw->driver_version < PPC_DRIVER_CRCCHK)) { + if (remaining < 2) + return -EINVAL; + data += 2; remaining -= 2; + } + + if (remaining < 6) + return -EINVAL; + + fw->configs[i].program = data[0]; data++; remaining--; + fw->configs[i].pll = data[0]; data++; remaining--; + if (fw->configs[i].pll >= fw->num_plls) { + dev_err(tas2557->tas_priv->dev, + "config %u: PLL index %u out of range (%u total)\n", + i, fw->configs[i].pll, fw->num_plls); + return -EINVAL; + } + fw->configs[i].sample_rate = get_unaligned_be32(data); + data += 4; remaining -= 4; + + /* PLL source fields present when driver >= MTPLLSRC: skip */ + if (fw->driver_version >= PPC_DRIVER_MTPLLSRC) { + if (remaining < 5) + return -EINVAL; + data += 5; remaining -= 5; + } + + ret = fw_parse_data(tas2557, fw, &fw->configs[i].data, + data, remaining); + if (ret < 0) + return ret; + data += ret; + remaining -= ret; + } + + return data - start; +} + +static struct tas2557_firmware *fw_parse(struct tas2557_priv *tas2557, + const u8 *data, size_t size) +{ + struct tas2557_firmware *fw; + size_t remaining = size; + int ret; + + fw = kzalloc_obj(*fw, GFP_KERNEL); + if (!fw) + return ERR_PTR(-ENOMEM); + + ret = fw_parse_header(tas2557, fw, data, remaining); + if (ret < 0) + goto err; + data += ret; remaining -= ret; + + ret = fw_parse_plls(tas2557, fw, data, remaining); + if (ret < 0) + goto err; + data += ret; remaining -= ret; + + ret = fw_parse_programs(tas2557, fw, data, remaining); + if (ret < 0) + goto err; + data += ret; remaining -= ret; + + ret = fw_parse_configs(tas2557, fw, data, remaining); + if (ret < 0) + goto err; + + return fw; + +err: + tas2557_fw_free(fw); + return ERR_PTR(ret); +} + +/* ========================================================================= + * Firmware application + * + * Each firmware block contains a sequence of 4-byte commands: + * [book][page][reg][val] - single register write + * [hi][lo][0x81][--] - msleep((hi<<8)|lo) + * [hi][lo][0x85][first] - bulk write: length=(hi<<8)|lo, data follows + * ========================================================================= + */ + +static int tas2557_load_block(struct tas2557_priv *tas2557, + struct tas2557_block *block, unsigned int chn) +{ + const u8 *data = block->data; + unsigned int i; + u8 book, page, offset, value; + u16 sleep_time, bulk_len; + int ret; + + dev_dbg(tas2557->tas_priv->dev, "chn %u: load block type=0x%x cmds=%u\n", + chn, block->type, block->num_commands); + + for (i = 0; i < block->num_commands; ) { + book = data[i * 4]; + page = data[i * 4 + 1]; + offset = data[i * 4 + 2]; + value = data[i * 4 + 3]; + i++; + + if (offset <= 0x7f) { + ret = tas2557_dev_write(tas2557, chn, + TAS2557_REG(book, page, offset), + value); + if (ret < 0) + return ret; + } else if (offset == 0x81) { + sleep_time = ((u16)book << 8) | page; + msleep(sleep_time); + } else if (offset == 0x85) { + bulk_len = ((u16)book << 8) | page; + + if (bulk_len == 0) + return -EINVAL; + + if (i >= block->num_commands) + return -EINVAL; + /* Verify bulk payload stays within block->data */ + if ((size_t)i * 4 + 3 + bulk_len > + (size_t)block->num_commands * 4) + return -EINVAL; + + book = data[i * 4]; + page = data[i * 4 + 1]; + offset = data[i * 4 + 2]; + + if (bulk_len > 1) + ret = tas2557_dev_bulk_write(tas2557, chn, + TAS2557_REG(book, page, offset), + &data[i * 4 + 3], bulk_len); + else + ret = tas2557_dev_write(tas2557, chn, + TAS2557_REG(book, page, offset), + data[i * 4 + 3]); + if (ret < 0) + return ret; + + i++; + if (bulk_len >= 2) + i += (bulk_len - 2) / 4 + 1; + } + } + + return 0; +} + +/* + * tas2557_block_chn_range - which devs[] a firmware block type targets + * + * Mirrors tasdevice_load_block()'s dispatch in tas2781-fmwlib.c: DEV_A/ + * DEV_B blocks target exactly one physical chip (selected by its index in + * the DT `reg` array, see the ti,tas2557.yaml binding), device-independent + * blocks (PGM_ALL, CFG_POST, CFG_POST_POWER) and the PLL block target every + * chip in the group. @chnend is clamped to tas2557->tas_priv->ndev, so a DEV_B block + * becomes an empty range on a single-chip group instead of touching a + * devs[] slot that was never populated. Returns false for a block type + * this driver does not recognise, so the caller does not apply it blindly. + */ +static bool tas2557_block_chn_range(struct tas2557_priv *tas2557, + unsigned int type, + unsigned int *chn, unsigned int *chnend) +{ + switch (type) { + case TAS2557_BLOCK_PGM_DEV_A: + case TAS2557_BLOCK_CFG_COEFF_DEV_A: + case TAS2557_BLOCK_CFG_PRE_DEV_A: + *chn = 0; + *chnend = 1; + break; + case TAS2557_BLOCK_PGM_DEV_B: + case TAS2557_BLOCK_CFG_COEFF_DEV_B: + case TAS2557_BLOCK_CFG_PRE_DEV_B: + *chn = 1; + *chnend = 2; + break; + case TAS2557_BLOCK_PLL: + case TAS2557_BLOCK_PGM_ALL: + case TAS2557_BLOCK_CFG_POST: + case TAS2557_BLOCK_CFG_POST_POWER: + *chn = 0; + *chnend = tas2557->tas_priv->ndev; + break; + default: + return false; + } + + if (*chnend > tas2557->tas_priv->ndev) + *chnend = tas2557->tas_priv->ndev; + + return true; +} + +/* + * tas2557_load_fw_data - apply every block of a data set in storage order, + * each to whichever devs[] its type targets. Used for program->data, + * which only ever contains PGM_ALL/PGM_DEV_A/PGM_DEV_B blocks with no + * ordering constraint between them. + */ +static int tas2557_load_fw_data(struct tas2557_priv *tas2557, + struct tas2557_data *img_data) +{ + unsigned int i, chn, chnend, c; + int ret; + + for (i = 0; i < img_data->num_blocks; i++) { + if (!tas2557_block_chn_range(tas2557, img_data->blocks[i].type, + &chn, &chnend)) + continue; + + for (c = chn; c < chnend; c++) { + ret = tas2557_load_block(tas2557, &img_data->blocks[i], c); + if (ret < 0) + return ret; + } + } + + return 0; +} + +/* + * tas2557_load_fw_data_type - apply only the blocks of a single type, + * in storage order, each to whichever devs[] that type targets. + */ +static int tas2557_load_fw_data_type(struct tas2557_priv *tas2557, + struct tas2557_data *img_data, + unsigned int type) +{ + unsigned int i, chn, chnend, c; + int ret; + + if (!tas2557_block_chn_range(tas2557, type, &chn, &chnend)) + return 0; + + for (i = 0; i < img_data->num_blocks; i++) { + if (img_data->blocks[i].type != type) + continue; + + for (c = chn; c < chnend; c++) { + ret = tas2557_load_block(tas2557, &img_data->blocks[i], c); + if (ret < 0) + return ret; + } + } + + return 0; +} + +/* + * tas2557_load_config_data - apply a configuration's pre-power blocks in the + * order the hardware expects: each chip's pre-coefficient block, then its + * coefficient block (DEV_A before DEV_B), then the device-independent + * CFG_POST block. The CFG_POST_POWER block is NOT applied here; it needs + * active clocks and is loaded by tas2557_load_config_post_power() after the + * device is powered up. Blocks are applied by type, not storage order (per + * TI); tas2557_block_chn_range() decides which chip(s) each type reaches. + */ +static int tas2557_load_config_data(struct tas2557_priv *tas2557, + struct tas2557_data *img_data) +{ + static const unsigned int order[] = { + TAS2557_BLOCK_CFG_PRE_DEV_A, + TAS2557_BLOCK_CFG_COEFF_DEV_A, + TAS2557_BLOCK_CFG_PRE_DEV_B, + TAS2557_BLOCK_CFG_COEFF_DEV_B, + TAS2557_BLOCK_CFG_POST, + }; + unsigned int i; + int ret; + + for (i = 0; i < ARRAY_SIZE(order); i++) { + ret = tas2557_load_fw_data_type(tas2557, img_data, order[i]); + if (ret < 0) + return ret; + } + + return 0; +} + +/* + * tas2557_load_config_post_power - apply the CFG_POST_POWER block of the + * current configuration. These register writes target DSP/clock state that + * only latches once the Class-D/DSP power-up sequence has run, so this is + * called from the power-up path after tas2557_startup_sequence(), not during the + * (powered-down) configuration load. current_config is kept in lock-step + * across every devs[] entry by tas2557_set_program(), so devs[0] is read + * back as the group's representative value. + */ +static int tas2557_load_config_post_power(struct tas2557_priv *tas2557) +{ + struct tas2557_config *config; + + if (!tas2557->fw || tas2557->devs[0].current_config >= tas2557->fw->num_configs) + return 0; + + config = &tas2557->fw->configs[tas2557->devs[0].current_config]; + + return tas2557_load_fw_data_type(tas2557, &config->data, + TAS2557_BLOCK_CFG_POST_POWER); +} + +/* + * tas2557_load_pll - apply a firmware PLL block to every chip in the group. + * PLL configuration is device-independent (each chip clocks itself off the + * same shared reference), so this is loaded on every devs[] entry. + */ +static int tas2557_load_pll(struct tas2557_priv *tas2557, unsigned int pll_idx) +{ + unsigned int chn; + int ret; + + if (!tas2557->fw || pll_idx >= tas2557->fw->num_plls) + return -EINVAL; + + dev_dbg(tas2557->tas_priv->dev, "loading PLL[%u]: %s\n", + pll_idx, tas2557->fw->plls[pll_idx].name); + + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) { + ret = tas2557_load_block(tas2557, + &tas2557->fw->plls[pll_idx].block, chn); + if (ret < 0) + return ret; + } + + return 0; +} + +/* + * tas2557_find_config - first config of @prog_idx for @rate (0 = any rate), + * or -EINVAL if the firmware has none. + */ +static int tas2557_find_config(const struct tas2557_firmware *fw, + unsigned int prog_idx, unsigned int rate) +{ + unsigned int i; + + for (i = 0; i < fw->num_configs; i++) { + if (fw->configs[i].program != prog_idx) + continue; + if (rate == 0 || rate == fw->configs[i].sample_rate) + return i; + } + + return -EINVAL; +} + +/* + * tas2557_set_program - reset the device group and load a firmware program + * and config + * + * Hardware reset, software reset, default registers and IRQ config on every + * chip, then the program blocks, the config's PLL block and the config + * blocks. The PLL is configured only by the firmware PLL block. The group + * is not powered up: callers run the startup sequence afterwards. A + * powered group must be shut down by the caller first. + * + * Caller must hold tas_priv->codec_lock. + * + * @config_idx: -1 to select the config for the current sample_rate; while + * that is still 0, the first config of the program + */ +static int tas2557_set_program(struct tas2557_priv *tas2557, + unsigned int prog_idx, int config_idx) +{ + struct tas2557_firmware *fw = tas2557->fw; + struct tas2557_program *program; + struct tas2557_config *config; + unsigned int chn; + int ret; + + lockdep_assert_held(&tas2557->tas_priv->codec_lock); + + if (!fw || !fw->programs || !fw->configs) { + dev_err(tas2557->tas_priv->dev, "firmware not loaded, cannot set program\n"); + return -EINVAL; + } + + if (prog_idx >= fw->num_programs) { + dev_err(tas2557->tas_priv->dev, "program %u out of range (%u total)\n", + prog_idx, fw->num_programs); + return -EINVAL; + } + + if (config_idx < 0) { + config_idx = tas2557_find_config(fw, prog_idx, tas2557->sample_rate); + if (config_idx < 0) { + dev_err(tas2557->tas_priv->dev, + "no config for program %u at %u Hz\n", + prog_idx, tas2557->sample_rate); + return -EINVAL; + } + } + + if ((unsigned int)config_idx >= fw->num_configs) { + dev_err(tas2557->tas_priv->dev, "config %d out of range (%u total)\n", + config_idx, fw->num_configs); + return -EINVAL; + } + + config = &fw->configs[config_idx]; + if (config->program != prog_idx) { + dev_err(tas2557->tas_priv->dev, + "config %u belongs to program %u, not %u\n", + config_idx, config->program, prog_idx); + return -EINVAL; + } + + program = &fw->programs[prog_idx]; + + /* Hard + soft reset (every chip), then baseline register setup */ + tas2557_hw_reset(tas2557); + + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) { + ret = tas2557_dev_write(tas2557, chn, TAS2557_SW_RESET_REG, 0x01); + if (ret < 0) + return ret; + } + usleep_range(1000, 2000); + + ret = tas2557_load_data_all(tas2557, tas2557_default_data); + if (ret < 0) + return ret; + + /* Restore IRQ configuration lost by the reset */ + ret = tas2557_load_data_all(tas2557, tas2557_irq_config); + if (ret < 0) + dev_warn(tas2557->tas_priv->dev, "IRQ config reload failed: %d\n", ret); + + /* + * Load DSP program blocks. Which chip(s) each block targets is + * decided purely by the block's own type (PGM_ALL/PGM_DEV_A/ + * PGM_DEV_B) via tas2557_block_chn_range(); DEV_A/DEV_B tuning maps + * onto devs[0]/devs[1], i.e. onto the chip order of the DT `reg` + * array, not any runtime TDM slot selection. + */ + dev_dbg(tas2557->tas_priv->dev, "loading program %u (%s)\n", + prog_idx, program->name); + ret = tas2557_load_fw_data(tas2557, &program->data); + if (ret < 0) + return ret; + + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) + tas2557->devs[chn].current_program = prog_idx; + + /* Load the PLL configuration of this config (index checked at parse) */ + ret = tas2557_load_pll(tas2557, config->pll); + if (ret < 0) + return ret; + + /* Load config blocks (coefficients, sample-rate-specific settings) */ + dev_dbg(tas2557->tas_priv->dev, + "loading config %u (%s) rate=%u Hz PLL[%u]\n", + config_idx, config->name, config->sample_rate, config->pll); + ret = tas2557_load_config_data(tas2557, &config->data); + if (ret < 0) + return ret; + + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) + tas2557->devs[chn].current_config = config_idx; + + tas2557->prog_valid = true; + + return 0; +} + +static const char *tas2557_pg_name(int pg_id) +{ + switch (pg_id) { + case TAS2557_PG_VERSION_1P0: + return "PG1.0"; + case TAS2557_PG_VERSION_2P0: + return "PG2.0"; + case TAS2557_PG_VERSION_2P1: + return "PG2.1"; + default: + return "PG?"; + } +} + +/* + * tas2557_build_rate_list - collect the distinct sample rates of the + * current program's configs for the DAI rate constraint. Caller holds + * tas_priv->codec_lock. + */ +static int tas2557_build_rate_list(struct tas2557_priv *tas2557) +{ + const struct tas2557_firmware *fw = tas2557->fw; + unsigned int prog_idx = tas2557->devs[0].current_program; + unsigned int *rates, num = 0, i, j; + + rates = kmalloc_array(fw->num_configs, sizeof(*rates), GFP_KERNEL); + if (!rates) + return -ENOMEM; + + for (i = 0; i < fw->num_configs; i++) { + unsigned int rate = fw->configs[i].sample_rate; + + if (fw->configs[i].program != prog_idx || !rate) + continue; + + for (j = 0; j < num; j++) + if (rates[j] == rate) + break; + if (j == num) + rates[num++] = rate; + } + + kfree(tas2557->rates); + tas2557->rates = rates; + tas2557->rate_list.list = rates; + tas2557->rate_list.count = num; + + return 0; +} + +/* + * tas2557_fw_ready - firmware load callback + * + * Called from request_firmware_nowait(). Parses the firmware and, if it + * matches the configured chip count, installs it, builds the rate list and + * loads program 0 so the DSP is ready for the first power-up. Every path + * reaches the completion at the end, so tas2557_fw_teardown() and DAPM can + * always wait for this callback to finish. + */ +static void tas2557_fw_ready(const struct firmware *fw_entry, void *context) +{ + struct tas2557_priv *tas2557 = context; + struct tas2557_firmware *fw = NULL; + int ret; + + if (!fw_entry || !fw_entry->data || fw_entry->size == 0) { + /* + * Firmware is required: without it the DSP cannot route + * audio and the Class-D stage stays muted. + */ + dev_err(tas2557->tas_priv->dev, + "firmware '%s' not found, the amplifier cannot work without it\n", + tas2557->fw_name); + release_firmware(fw_entry); + goto done; + } + + dev_dbg(tas2557->tas_priv->dev, "firmware received, size=%zu\n", fw_entry->size); + + fw = fw_parse(tas2557, fw_entry->data, fw_entry->size); + release_firmware(fw_entry); + + if (IS_ERR(fw)) { + dev_err(tas2557->tas_priv->dev, + "firmware '%s' parse error %ld, it may be corrupt\n", + tas2557->fw_name, PTR_ERR(fw)); + fw = NULL; + goto done; + } + + /* + * The firmware's device field is the number of chips it was built + * for; a mismatch with the DT group size means the wrong file. + */ + if ((fw->device == TASDEVICE_DSP_TAS_2557_MONO && + tas2557->tas_priv->ndev != 1) || + (fw->device == TASDEVICE_DSP_TAS_2557_DUAL_MONO && + tas2557->tas_priv->ndev != 2)) { + dev_err(tas2557->tas_priv->dev, + "firmware '%s' is for %s but %u chip(s) are configured\n", + tas2557->fw_name, + fw->device == TASDEVICE_DSP_TAS_2557_MONO ? "mono" : "stereo", + tas2557->tas_priv->ndev); + tas2557_fw_free(fw); + goto done; + } + + mutex_lock(&tas2557->tas_priv->codec_lock); + + tas2557_fw_free(tas2557->fw); + tas2557->fw = fw; + tas2557->prog_valid = false; + + if (tas2557_build_rate_list(tas2557) < 0) + dev_warn(tas2557->tas_priv->dev, + "no memory for the rate list, rates are not constrained\n"); + + ret = tas2557_set_program(tas2557, 0, -1); + if (ret < 0) + dev_err(tas2557->tas_priv->dev, "initial program load failed: %d\n", ret); + else + dev_info(tas2557->tas_priv->dev, + "%s ready: fw '%s' ver=0x%x drv=0x%x (%u prog, %u cfg)\n", + tas2557_pg_name(tas2557->devs[0].pg_id), tas2557->fw_name, + fw->fw_version, fw->driver_version, + fw->num_programs, fw->num_configs); + + mutex_unlock(&tas2557->tas_priv->codec_lock); + +done: + complete_all(&tas2557->fw_done); +} + +/* + * tas2557_fw_teardown - release firmware resources on driver teardown + * + * Waits for a pending tas2557_fw_ready() callback (if a request is still + * in flight) before freeing the parsed firmware, closing the + * use-after-free window where the firmware core could still be about to + * invoke tas2557_fw_ready() while the device is being unbound. See the + * comment above its devm_add_action_or_reset() registration in + * tas2557_i2c_probe() for why this ordering is safe. + */ +static void tas2557_fw_teardown(void *data) +{ + struct tas2557_priv *tas2557 = data; + + if (tas2557->fw_requested) + wait_for_completion(&tas2557->fw_done); + + mutex_lock(&tas2557->tas_priv->codec_lock); + tas2557_fw_free(tas2557->fw); + tas2557->fw = NULL; + kfree(tas2557->rates); + tas2557->rates = NULL; + mutex_unlock(&tas2557->tas_priv->codec_lock); +} + +/* + * tas2557_hw_reset - assert and release every configured reset line + * together. A lone reset-gpios entry is replicated into every slot by + * tas2557_parse_dt(). Invalidates the loaded program and comlib's cached + * book numbers; without a reset GPIO only that bookkeeping is done. + */ +static void tas2557_hw_reset(struct tas2557_priv *tas2557) +{ + unsigned int chn; + bool have_reset = false; + + tas2557->prog_valid = false; + + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) { + if (tas2557->reset[chn]) { + have_reset = true; + /* Assert reset (active-low: logical 1 = reset asserted) */ + gpiod_set_value_cansleep(tas2557->reset[chn], 1); + } + } + + if (have_reset) { + usleep_range(5000, 6000); + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) + if (tas2557->reset[chn]) + gpiod_set_value_cansleep(tas2557->reset[chn], 0); + usleep_range(10000, 11000); + } + + /* The reset clears the selected book; force comlib to reselect it */ + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) + tas2557->tas_priv->tasdevice[chn].cur_book = -1; +} + +/* + * tas2557_irq_arm()/tas2557_irq_disarm() - enable/disable every configured + * fault IRQ from the power path (interrupts, minItems 1 maxItems 2, + * one entry may apply to every chip; every distinct line is armed and + * disarmed once, together, since the whole group is powered up/down together). + * Called with tas_priv->codec_lock NOT held: enable_irq()/disable_irq() must not + * run while the threaded handler could be blocked waiting for + * tas_priv->codec_lock, or a self-deadlock results (disable_irq() waits for the + * handler thread to finish, which is waiting on the lock the caller is + * holding). + */ +static void tas2557_irq_arm(struct tas2557_priv *tas2557) +{ + unsigned int chn; + + if (tas2557->irq_enabled) + return; + tas2557->irq_enabled = true; + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) { + if (chn > 0 && tas2557->irq[chn] == tas2557->irq[chn - 1]) + continue; + if (tas2557->irq[chn] > 0) + enable_irq(tas2557->irq[chn]); + } +} + +static void tas2557_irq_disarm(struct tas2557_priv *tas2557) +{ + unsigned int chn; + + if (!tas2557->irq_enabled) + return; + tas2557->irq_enabled = false; + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) { + if (chn > 0 && tas2557->irq[chn] == tas2557->irq[chn - 1]) + continue; + if (tas2557->irq[chn] > 0) + disable_irq(tas2557->irq[chn]); + } +} + +/* + * tas2557_irq_handler - threaded fault IRQ handler + * + * GPIO4 is programmed as the INT1 output (see tas2557_irq_config) on every + * chip; every configured host IRQ line shares this same handler with + * dev_id = tas2557, so a fault on any chip's INT line diagnoses and + * recovers the whole group the same way. FLAGS_1/FLAGS_2/POWER_UP_FLAG + * are read back from each chip in turn: any single chip reporting a fault + * triggers failsafe recovery for the whole group. + */ +static irqreturn_t tas2557_irq_handler(int irq, void *data) +{ + struct tas2557_priv *tas2557 = data; + unsigned int chn; + bool fault = false; + int ret = 0; + + mutex_lock(&tas2557->tas_priv->codec_lock); + + if (!tas2557->fw || !tas2557->powered) { + mutex_unlock(&tas2557->tas_priv->codec_lock); + return IRQ_NONE; + } + + /* Gate the chips' INT output while diagnosing the fault */ + tas2557_write_all(tas2557, TAS2557_GPIO4_PIN_REG, 0x00); + + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) { + unsigned int int1 = 0, int2 = 0, pwr_flag = 0; + + ret = tas2557_dev_read(tas2557, chn, TAS2557_FLAGS_1, &int1); + if (ret >= 0) + ret = tas2557_dev_read(tas2557, chn, TAS2557_FLAGS_2, &int2); + + if (ret < 0) { + dev_err(tas2557->tas_priv->dev, "IRQ: chn %u failed to read FLAGS\n", chn); + fault = true; + break; + } + + if ((int1 & 0xfc) || (int2 & 0x0c)) { + /* + * Clock faults while muted are expected: the host is + * allowed to stop the I2S clocks around stream stop + * while the amplifier is still powered. Nothing to + * recover from. + */ + if (tas2557->dac_muted && !(int1 & 0xd8)) { + dev_dbg(tas2557->tas_priv->dev, + "IRQ: chn %u clock stop while muted (FLAGS_1=0x%02x FLAGS_2=0x%02x)\n", + chn, int1, int2); + continue; + } + dev_err(tas2557->tas_priv->dev, "IRQ: chn %u FLAGS_1=0x%02x FLAGS_2=0x%02x\n", + chn, int1, int2); + fault = true; + break; + } + + if (!tas2557->dac_muted) { + ret = tas2557_dev_read(tas2557, chn, TAS2557_POWER_UP_FLAG_REG, + &pwr_flag); + if (ret < 0) { + fault = true; + break; + } + + if ((pwr_flag & 0xc0) != 0xc0) { + dev_err(tas2557->tas_priv->dev, "IRQ: chn %u power-up flag=0x%02x\n", + chn, pwr_flag); + fault = true; + break; + } + } + } + + if (!fault) { + /* No fault (or expected clock stop): re-enable the INT output */ + tas2557_write_all(tas2557, TAS2557_GPIO4_PIN_REG, 0x07); + mutex_unlock(&tas2557->tas_priv->codec_lock); + return IRQ_HANDLED; + } + + if (tas2557_failsafe_recovery(tas2557) == 0) + tas2557_write_all(tas2557, TAS2557_GPIO4_PIN_REG, 0x07); + + mutex_unlock(&tas2557->tas_priv->codec_lock); + return IRQ_HANDLED; +} + +/* + * tas2557_clk_err_detect - gate the chips' clock error/halt detection + * + * The host is allowed to stop the I2S clocks whenever no audio is + * playing (amplifier muted), so detection is armed only between unmute + * and mute; otherwise a normal stream stop looks like a clock-halt + * fault. This matches the TI reference sequences, which disable + * detection as the first step of the shutdown sequence. + */ +static int tas2557_clk_err_detect(struct tas2557_priv *tas2557, bool enable) +{ + return tas2557_write_all(tas2557, TAS2557_CLK_ERR_CTRL, + enable ? 0x2b : 0x00); +} + +/* + * tas2557_apply_mute_state - program the cached mute state into a freshly + * powered group. + * + * With the DAC unmuted, unmute (I/V sense are unmuted with it, as the DSP + * needs the IV feedback while the amplifier plays) and arm clock error + * detection. With the DAC muted the host may not be clocking the bus, so + * keep detection off. tas2557_mute_stream() arms detection when the DAC + * is unmuted later. + */ +static int tas2557_apply_mute_state(struct tas2557_priv *tas2557) +{ + int ret; + + if (!tas2557->dac_muted) { + ret = tas2557_load_data_all(tas2557, tas2557_unmute_data); + if (ret >= 0) + ret = tas2557_clk_err_detect(tas2557, true); + } else { + ret = tas2557_clk_err_detect(tas2557, false); + } + + return ret; +} + +/* + * tas2557_failsafe_recovery - re-initialise the device group after a fault IRQ + * + * Caller must hold tas_priv->codec_lock (called from tas2557_irq_handler()). + * Capped at 5 attempts so a permanently faulty amplifier does not spin + * the IRQ thread forever; the group is recovered together, so restart_count + * is incremented on every chip and devs[0] is read back. + */ +static int tas2557_failsafe_recovery(struct tas2557_priv *tas2557) +{ + unsigned int chn; + int ret; + + lockdep_assert_held(&tas2557->tas_priv->codec_lock); + + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) + tas2557->devs[chn].restart_count++; + + dev_info(tas2557->tas_priv->dev, "failsafe recovery attempt %u\n", + tas2557->devs[0].restart_count); + + if (tas2557->devs[0].restart_count > 5) { + dev_err(tas2557->tas_priv->dev, "too many recovery attempts, giving up\n"); + /* The handler zeroed INT1 routing; force a reload at next power-up */ + tas2557->prog_valid = false; + return -EIO; + } + + /* + * tas2557_set_program() does the hardware reset, the software + * reset and the defaults/IRQ config reload. The faulted chips are + * reset directly, without a graceful shutdown. + */ + ret = tas2557_set_program(tas2557, tas2557->devs[0].current_program, + (int)tas2557->devs[0].current_config); + if (ret < 0) + return ret; + + if (tas2557->powered) { + ret = tas2557_startup_sequence(tas2557); + if (ret < 0) + return ret; + + ret = tas2557_apply_runtime_state(tas2557); + if (ret < 0) + return ret; + + ret = tas2557_load_config_post_power(tas2557); + if (ret < 0) + return ret; + + ret = tas2557_apply_mute_state(tas2557); + if (ret < 0) + return ret; + } + + dev_info(tas2557->tas_priv->dev, "failsafe recovery succeeded\n"); + return 0; +} + +static void tas2557_check_pll_lock(struct tas2557_priv *tas2557) +{ + unsigned int chn; + + /* + * The PLL needs a few ms to lock after the I2S bit clock starts + * flowing. Poll POWER_UP_FLAG rather than sampling it once, so we + * don't emit a spurious "not locked" warning during clock ramp-up. + */ + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) { + unsigned int flag = 0, f1 = 0, f2 = 0; + int i; + + for (i = 0; i < 20; i++) { + tas2557_dev_read(tas2557, chn, TAS2557_POWER_UP_FLAG_REG, &flag); + if ((flag & 0xc0) == 0xc0) + break; + usleep_range(2000, 2500); + } + + tas2557_dev_read(tas2557, chn, TAS2557_FLAGS_1, &f1); + tas2557_dev_read(tas2557, chn, TAS2557_FLAGS_2, &f2); + + if ((flag & 0xc0) == 0xc0) + dev_dbg(tas2557->tas_priv->dev, + "chn %u: PLL locked, power-up OK (FLAG=0x%02x F1=0x%02x F2=0x%02x)\n", + chn, flag, f1, f2); + else + dev_warn(tas2557->tas_priv->dev, + "chn %u: PLL or clock may not have locked (FLAG=0x%02x F1=0x%02x F2=0x%02x)\n", + chn, flag, f1, f2); + + if (f1 & 0x04) + dev_warn(tas2557->tas_priv->dev, "chn %u: clock error detected (FLAGS_1=0x%02x)\n", + chn, f1); + } +} + +/* + * Power-up sequence, see tas2557_power_up_locked(): + * 1. tas2557_set_program() - only if the chips no longer hold the needed + * program/config: reset, defaults, IRQ config, firmware program, PLL + * and config blocks + * 2. tas2557_startup_sequence() - GPIO clocks, Class-D, Boost, DSP + * 3. DAC gain, ASI word length/format and slot offset + * 4. CFG_POST_POWER firmware block + * 5. Cached mute state + * 6. POWER_UP_FLAG/FLAGS check for PLL lock and clock errors + * + * tas2557_hw_params() runs it again while powered for a live sample rate + * change, which always reloads the program and config. + */ + +/* + * tas2557_apply_runtime_state - program the cached ALSA/DAI state: DAC + * gain, ASI word length/format and the RX data-slot offset of the ASI + * selected by ti,asi-port. Run after every startup sequence and after a + * reset. Caller holds tas_priv->codec_lock. + */ +static int tas2557_apply_runtime_state(struct tas2557_priv *tas2557) +{ + unsigned int chn; + int ret; + + lockdep_assert_held(&tas2557->tas_priv->codec_lock); + + ret = tas2557_update_bits_all(tas2557, TAS2557_SPK_CTRL_REG, + TAS2557_DAC_GAIN_MASK, + tas2557->dac_gain << TAS2557_DAC_GAIN_SHIFT); + if (ret < 0) + return ret; + + /* Word length is always valid (seeded at probe); format only if set */ + ret = tas2557_asi_fmt_update_all(tas2557, TAS2557_WORDLENGTH_MASK, + tas2557->wordlength); + if (ret < 0) + return ret; + + if (tas2557->dai_fmt >= 0) { + ret = tas2557_asi_fmt_update_all(tas2557, TAS2557_FORMAT_MASK, + tas2557->dai_fmt); + if (ret < 0) + return ret; + } + + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) { + ret = tas2557_write_rx_offset(tas2557, chn); + if (ret < 0) + return ret; + } + + return 0; +} + +/* + * tas2557_power_up_locked - power up the amplifier group with @prog_idx at + * the current tas2557->sample_rate, loading the program and config first + * when the chips do not hold them. + * + * The program is reloaded if the loaded state was invalidated, a different + * config is needed for the rate, or the group is already powered (live rate + * change from hw_params(); it is shut down first). + * + * Caller must hold tas_priv->codec_lock and must have already verified that + * firmware is loaded. + */ +static int tas2557_power_up_locked(struct tas2557_priv *tas2557, + unsigned int prog_idx) +{ + int cfg_idx, ret; + + lockdep_assert_held(&tas2557->tas_priv->codec_lock); + + cfg_idx = tas2557_find_config(tas2557->fw, prog_idx, tas2557->sample_rate); + if (cfg_idx < 0) { + dev_err(tas2557->tas_priv->dev, "no config for program %u at %u Hz\n", + prog_idx, tas2557->sample_rate); + return cfg_idx; + } + + if (tas2557->powered || !tas2557->prog_valid || + tas2557->devs[0].current_program != prog_idx || + tas2557->devs[0].current_config != cfg_idx) { + if (tas2557->powered) { + ret = tas2557_shutdown_sequence(tas2557); + if (ret < 0) + return ret; + /* Callers set powered again on success */ + tas2557->powered = false; + tas2557->dac_muted = true; + } + + ret = tas2557_set_program(tas2557, prog_idx, cfg_idx); + if (ret < 0) { + dev_err(tas2557->tas_priv->dev, + "firmware program load failed on power-up: %d\n", + ret); + return ret; + } + } + + /* Power up Class-D + Boost + selected-ASI clocks on every chip */ + ret = tas2557_startup_sequence(tas2557); + if (ret < 0) { + dev_err(tas2557->tas_priv->dev, "startup sequence failed: %d\n", + ret); + goto err_shutdown; + } + + ret = tas2557_apply_runtime_state(tas2557); + if (ret < 0) + goto err_shutdown; + + /* DSP post-power coefficients need active clocks to latch */ + ret = tas2557_load_config_post_power(tas2557); + if (ret < 0) { + dev_err(tas2557->tas_priv->dev, + "post-power config load failed: %d\n", ret); + goto err_shutdown; + } + + /* + * On DPCM systems mute_stream(0) for a back-end DAI can run before + * the DAPM widgets power up, so the unmute may already be recorded + * while the device is still off. + */ + ret = tas2557_apply_mute_state(tas2557); + if (ret < 0) + goto err_shutdown; + + /* Verify PLL lock and clock health on every chip */ + tas2557_check_pll_lock(tas2557); + + return 0; + +err_shutdown: + /* Do not leave the chips powered while powered == false */ + tas2557_shutdown_sequence(tas2557); + tas2557->powered = false; + tas2557->dac_muted = true; + return ret; +} + +/* + * tas2557_enable - power the amplifier group up or down + * + * Caller must hold tas_priv->codec_lock. Does not touch the fault IRQ or the + * mute state; see tas2557_classd_event() and tas2557_mute_stream(). + */ +static int tas2557_enable(struct tas2557_priv *tas2557, bool enable) +{ + unsigned int chn; + int ret = 0; + + lockdep_assert_held(&tas2557->tas_priv->codec_lock); + + if (enable && !tas2557->powered) { + if (!tas2557->fw) { + dev_warn(tas2557->tas_priv->dev, + "firmware not loaded, cannot produce audio; install %s\n", + tas2557->fw_name[0] ? tas2557->fw_name + : TAS2557_FW_NAME); + return -ENODEV; + } + + ret = tas2557_power_up_locked(tas2557, tas2557->devs[0].current_program); + if (ret < 0) + return ret; + + tas2557->powered = true; + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) + tas2557->devs[chn].restart_count = 0; + + dev_dbg(tas2557->tas_priv->dev, "amplifier group powered on (prog=%u cfg=%u)\n", + tas2557->devs[0].current_program, tas2557->devs[0].current_config); + + } else if (!enable && tas2557->powered) { + ret = tas2557_shutdown_sequence(tas2557); + if (ret < 0) + dev_err(tas2557->tas_priv->dev, "shutdown failed: %d\n", ret); + + tas2557->powered = false; + tas2557->dac_muted = true; + + dev_dbg(tas2557->tas_priv->dev, "amplifier group powered off\n"); + } + + return ret; +} + +/* ========================================================================= + * ASoC DAI operations + * ========================================================================= + */ + +/* + * tas2557_wait_fw - wait, bounded, for the asynchronous firmware load to + * finish. Must be called without tas_priv->codec_lock held: + * tas2557_fw_ready() takes it before it completes fw_done. + */ +static void tas2557_wait_fw(struct tas2557_priv *tas2557) +{ + if (tas2557->fw_requested && + !wait_for_completion_timeout(&tas2557->fw_done, + msecs_to_jiffies(5000))) + dev_warn(tas2557->tas_priv->dev, "firmware load timed out\n"); +} + +/* + * The firmware configs have fixed sample rates, so once the firmware is + * loaded restrict the stream to the rates of the current program. Without + * firmware the stream opens unconstrained and power-up reports the error. + */ +static int tas2557_startup(struct snd_pcm_substream *substream, + struct snd_soc_dai *dai) +{ + struct tas2557_priv *tas2557 = snd_soc_component_get_drvdata(dai->component); + + tas2557_wait_fw(tas2557); + + guard(mutex)(&tas2557->tas_priv->codec_lock); + + if (!tas2557->fw || !tas2557->rate_list.count) + return 0; + + return snd_pcm_hw_constraint_list(substream->runtime, 0, + SNDRV_PCM_HW_PARAM_RATE, + &tas2557->rate_list); +} + +static int tas2557_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params, + struct snd_soc_dai *dai) +{ + struct snd_soc_component *component = dai->component; + struct tas2557_priv *tas2557 = snd_soc_component_get_drvdata(component); + unsigned int rate = params_rate(params); + unsigned int chn, wordlength; + bool rate_changed, fmt_changed, live, remute; + int ret; + + guard(mutex)(&tas2557->tas_priv->codec_lock); + + dev_dbg(tas2557->tas_priv->dev, "hw_params: rate=%u width=%d\n", + rate, params_physical_width(params)); + + /* + * Firmware configs have fixed sample rates. Reject a rate the + * program has no config for before changing any state; without + * firmware the check is left to power-up. + */ + if (tas2557->fw && + tas2557_find_config(tas2557->fw, tas2557->devs[0].current_program, + rate) < 0) { + dev_err(tas2557->tas_priv->dev, + "no firmware config for program %u at %u Hz\n", + tas2557->devs[0].current_program, rate); + return -EINVAL; + } + + /* Validate the ASI word length before committing any cached state */ + switch (params_width(params)) { + case 16: + wordlength = TAS2557_WORDLENGTH_16BIT; + break; + case 20: + wordlength = TAS2557_WORDLENGTH_20BIT; + break; + case 24: + wordlength = TAS2557_WORDLENGTH_24BIT; + break; + case 32: + wordlength = TAS2557_WORDLENGTH_32BIT; + break; + default: + dev_err(tas2557->tas_priv->dev, "unsupported sample width %d\n", + params_width(params)); + return -EINVAL; + } + + /* + * Without set_tdm_slot() the slot offset is 0 for every chip (the + * DSP_A BCLK is added when it is written); an explicit + * set_tdm_slot() takes precedence and leaves asi_offset alone. + */ + if (!tas2557->tdm_configured) { + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) + tas2557->devs[chn].asi_offset = 0; + } + + /* A lost program (failed reload, recovery give-up) forces a reload too */ + rate_changed = tas2557->powered && + (rate != tas2557->sample_rate || !tas2557->prog_valid); + fmt_changed = tas2557->powered && wordlength != tas2557->wordlength; + live = rate_changed || fmt_changed; + + /* + * If the group is powered and the rate or word length changed, apply + * it now instead of at the next power-up. A rate change needs the + * new config's PLL block and goes through tas2557_power_up_locked(); + * a word-length change is written to the format registers under + * mute. + */ + remute = live && fmt_changed && !rate_changed && !tas2557->dac_muted; + if (remute) { + ret = tas2557_update_bits_all(tas2557, TAS2557_SOFT_MUTE_REG, + TAS2557_PDM_SOFT_MUTE, + TAS2557_PDM_SOFT_MUTE); + if (ret >= 0) { + usleep_range(10000, 11000); + ret = tas2557_write_all(tas2557, TAS2557_MUTE_REG, + TAS2557_MUTE_ISNS | + TAS2557_MUTE_VSNS); + } + if (ret < 0) + return ret; + } + + /* Program the selected ASI's data-slot offset on every chip */ + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) { + ret = tas2557_write_rx_offset(tas2557, chn); + if (ret < 0) { + dev_err(tas2557->tas_priv->dev, "chn %u: ASI offset write failed: %d\n", + chn, ret); + return ret; + } + } + + if (live && fmt_changed && !rate_changed) { + ret = tas2557_asi_fmt_update_all(tas2557, TAS2557_WORDLENGTH_MASK, + wordlength); + if (ret < 0) + return ret; + } + + /* Commit cached stream state now the hardware writes have succeeded */ + tas2557->sample_rate = rate; + tas2557->wordlength = wordlength; + + if (rate_changed) { + ret = tas2557_power_up_locked(tas2557, tas2557->devs[0].current_program); + if (ret < 0) { + /* + * The chips are down but ClassD is still on: keep + * powered so that a retry reloads the program and + * PRE_PMD still runs the shutdown. + */ + tas2557->powered = true; + tas2557->dac_muted = true; + tas2557->prog_valid = false; + return ret; + } + tas2557->powered = true; + } else if (remute) { + ret = tas2557_write_all(tas2557, TAS2557_MUTE_REG, 0); + if (ret >= 0) + ret = tas2557_update_bits_all(tas2557, + TAS2557_SOFT_MUTE_REG, + TAS2557_PDM_SOFT_MUTE, 0); + if (ret < 0) + return ret; + } + + return 0; +} + +static int tas2557_set_dai_fmt(struct snd_soc_dai *dai, unsigned int fmt) +{ + struct snd_soc_component *component = dai->component; + struct tas2557_priv *tas2557 = snd_soc_component_get_drvdata(component); + unsigned int asi_fmt = 0, asi_delay = 0, chn; + int ret; + + /* The chip is always the clock consumer and has no inversion support */ + if ((fmt & SND_SOC_DAIFMT_CLOCK_PROVIDER_MASK) != SND_SOC_DAIFMT_CBC_CFC || + (fmt & SND_SOC_DAIFMT_INV_MASK) != SND_SOC_DAIFMT_NB_NF) { + dev_err(tas2557->tas_priv->dev, "unsupported DAI format 0x%x\n", fmt); + return -EINVAL; + } + + switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) { + case SND_SOC_DAIFMT_I2S: + asi_fmt = TAS2557_FORMAT_I2S; + break; + case SND_SOC_DAIFMT_DSP_A: + /* The DSP format at OFFSET1 = 0 is DSP_B; DSP_A is 1 BCLK later */ + asi_delay = 1; + fallthrough; + case SND_SOC_DAIFMT_DSP_B: + asi_fmt = TAS2557_FORMAT_DSP; + break; + case SND_SOC_DAIFMT_RIGHT_J: + asi_fmt = TAS2557_FORMAT_RIGHT_J; + break; + case SND_SOC_DAIFMT_LEFT_J: + asi_fmt = TAS2557_FORMAT_LEFT_J; + break; + default: + dev_err(tas2557->tas_priv->dev, "unsupported DAI format 0x%x\n", fmt); + return -EINVAL; + } + + guard(mutex)(&tas2557->tas_priv->codec_lock); + + tas2557->dai_fmt = asi_fmt; + tas2557->asi_delay = asi_delay; + + ret = tas2557_asi_fmt_update_all(tas2557, TAS2557_FORMAT_MASK, asi_fmt); + if (ret < 0) + return ret; + + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) { + ret = tas2557_write_rx_offset(tas2557, chn); + if (ret < 0) + return ret; + } + + return 0; +} + +static int tas2557_set_tdm_slot(struct snd_soc_dai *dai, + unsigned int tx_mask, unsigned int rx_mask, + int slots, int slot_width) +{ + struct snd_soc_component *component = dai->component; + struct tas2557_priv *tas2557 = snd_soc_component_get_drvdata(component); + unsigned int ndev = tas2557->tas_priv->ndev; + unsigned int offsets[TAS2557_MAX_DEV] = { }; + bool per_chip_slots = false; + unsigned int mask = rx_mask; + unsigned int chn; + int ret = 0; + + switch (slot_width) { + case 0: + case 16: + case 24: + case 32: + break; + default: + dev_err(tas2557->tas_priv->dev, "unsupported TDM slot width %d\n", + slot_width); + return -EINVAL; + } + + /* + * With at least two slots in the mask and at least as many as + * chips, chip n takes the n-th slot; otherwise every chip takes the + * first one. Only the slots actually used are checked. + */ + if (rx_mask) { + per_chip_slots = hweight32(rx_mask) >= 2 && + hweight32(rx_mask) >= ndev; + + for (chn = 0; chn < ndev; chn++) { + unsigned int slot = __ffs(mask); + + if (slot && !slot_width) { + dev_err(tas2557->tas_priv->dev, + "TDM slot %u needs a slot width\n", slot); + return -EINVAL; + } + if (per_chip_slots) + mask &= mask - 1; + offsets[chn] = slot * slot_width; + } + } + + guard(mutex)(&tas2557->tas_priv->codec_lock); + + /* The offset plus the DSP_A BCLK must fit the 8-bit OFFSET1 register */ + for (chn = 0; chn < ndev; chn++) + if (offsets[chn] + tas2557->asi_delay > U8_MAX) { + dev_err(tas2557->tas_priv->dev, + "TDM slot offset %u out of range\n", offsets[chn]); + return -EINVAL; + } + + /* + * tx_mask is accepted but not programmed: DOUT slot placement is not + * handled by this driver. Clearing both masks leaves TDM mode and + * restores the default offset. + */ + if (!rx_mask && tx_mask) + return 0; + + tas2557->tdm_configured = !!rx_mask; + + for (chn = 0; chn < ndev; chn++) { + tas2557->devs[chn].asi_offset = offsets[chn]; + + ret = tas2557_write_rx_offset(tas2557, chn); + if (ret < 0) + return ret; + } + + dev_dbg(tas2557->tas_priv->dev, "TDM: rx_mask=0x%x width=%d\n", + rx_mask, slot_width); + + return 0; +} + +static int tas2557_mute_stream(struct snd_soc_dai *dai, int mute, int direction) +{ + struct snd_soc_component *component = dai->component; + struct tas2557_priv *tas2557 = snd_soc_component_get_drvdata(component); + int ret = 0; + + guard(mutex)(&tas2557->tas_priv->codec_lock); + + if (!tas2557->powered) { + tas2557->dac_muted = mute; + return 0; + } + + if (mute) { + /* Detection off first: the host is about to stop the clocks */ + ret = tas2557_clk_err_detect(tas2557, false); + if (ret >= 0) + ret = tas2557_update_bits_all(tas2557, + TAS2557_SOFT_MUTE_REG, + TAS2557_PDM_SOFT_MUTE, + TAS2557_PDM_SOFT_MUTE); + if (ret >= 0) { + usleep_range(10000, 11000); + ret = tas2557_write_all(tas2557, TAS2557_MUTE_REG, + TAS2557_MUTE_ISNS | + TAS2557_MUTE_VSNS); + } + tas2557->dac_muted = mute; + } else { + /* Clocks are running now: unmute and arm error detection */ + tas2557->dac_muted = false; + ret = tas2557_apply_mute_state(tas2557); + } + + return ret; +} + +static const struct snd_soc_dai_ops tas2557_dai_ops = { + .startup = tas2557_startup, + .hw_params = tas2557_hw_params, + .set_fmt = tas2557_set_dai_fmt, + .set_tdm_slot = tas2557_set_tdm_slot, + .mute_stream = tas2557_mute_stream, + /* + * The DSP needs the IV sense feedback while the amplifier plays, so + * only the playback stream is muted. + */ + .no_capture_mute = 1, +}; + +static struct snd_soc_dai_driver tas2557_dai = { + .name = "tas2557-amplifier", + .playback = { + .stream_name = "Playback", + .channels_min = 1, + .channels_max = 2, + .rates = SNDRV_PCM_RATE_8000_192000, + .formats = TAS2557_FORMATS, + }, + .capture = { + .stream_name = "Capture", + .channels_min = 1, + .channels_max = 2, + .rates = SNDRV_PCM_RATE_8000_192000, + .formats = TAS2557_FORMATS, + }, + .ops = &tas2557_dai_ops, + /* + * One firmware config (hence one rate) is active at a time, and + * playback and capture share the single ASI word length, so both + * substreams must agree on rate and sample width. + */ + .symmetric_rate = 1, + .symmetric_sample_bits = 1, +}; + +/* ========================================================================= + * ALSA mixer controls + * ========================================================================= + */ +static DECLARE_TLV_DB_SCALE(tas2557_dac_tlv, 0, 100, 0); + +static int tas2557_volume_get(struct snd_kcontrol *kc, + struct snd_ctl_elem_value *ucontrol) +{ + struct tas2557_priv *tas2557 = + snd_soc_component_get_drvdata(snd_kcontrol_chip(kc)); + + ucontrol->value.integer.value[0] = tas2557->dac_gain; + return 0; +} + +static int tas2557_volume_put(struct snd_kcontrol *kc, + struct snd_ctl_elem_value *ucontrol) +{ + struct tas2557_priv *tas2557 = + snd_soc_component_get_drvdata(snd_kcontrol_chip(kc)); + unsigned int gain = ucontrol->value.integer.value[0]; + int ret = 0; + + if (gain > TAS2557_DAC_GAIN_MAX) + return -EINVAL; + + guard(mutex)(&tas2557->tas_priv->codec_lock); + + if (gain == tas2557->dac_gain) + return 0; + + if (tas2557->powered) { + ret = tas2557_update_bits_all(tas2557, TAS2557_SPK_CTRL_REG, + TAS2557_DAC_GAIN_MASK, + gain << TAS2557_DAC_GAIN_SHIFT); + if (ret < 0) + return ret; + } + + /* Only commit the cached gain once the hardware write has succeeded */ + tas2557->dac_gain = gain; + + return 1; +} + +static const struct snd_kcontrol_new tas2557_controls[] = { + SOC_SINGLE_EXT_TLV("Speaker Playback Volume", SND_SOC_NOPM, 0, + TAS2557_DAC_GAIN_MAX, 0, + tas2557_volume_get, tas2557_volume_put, + tas2557_dac_tlv), +}; + +/* ========================================================================= + * DAPM topology + * + * Playback path: ASI (AIF_IN, stream "Playback") -> DAC -> ClassD -> OUT + * Capture path: ClassD -> ISENSE/VSENSE -> SENSE (AIF_OUT, "Capture") + * + * One AIF widget serves whichever ASI ti,asi-port selects; the pin and + * format programming is done by the startup sequence, not by DAPM. + * ========================================================================= + */ +static int tas2557_classd_event(struct snd_soc_dapm_widget *w, + struct snd_kcontrol *kcontrol, int event) +{ + struct snd_soc_component *component = + snd_soc_dapm_to_component(w->dapm); + struct tas2557_priv *tas2557 = snd_soc_component_get_drvdata(component); + int ret; + + switch (event) { + case SND_SOC_DAPM_POST_PMU: + /* Not under codec_lock, see tas2557_wait_fw() */ + tas2557_wait_fw(tas2557); + + mutex_lock(&tas2557->tas_priv->codec_lock); + ret = tas2557_enable(tas2557, true); + mutex_unlock(&tas2557->tas_priv->codec_lock); + if (ret < 0) + return ret; + tas2557_irq_arm(tas2557); + return 0; + case SND_SOC_DAPM_PRE_PMD: + tas2557_irq_disarm(tas2557); + mutex_lock(&tas2557->tas_priv->codec_lock); + ret = tas2557_enable(tas2557, false); + mutex_unlock(&tas2557->tas_priv->codec_lock); + return ret; + default: + return 0; + } +} + +static const struct snd_soc_dapm_widget tas2557_dapm_widgets[] = { + SND_SOC_DAPM_AIF_IN("ASI", "Playback", 0, SND_SOC_NOPM, 0, 0), + + SND_SOC_DAPM_DAC("DAC", NULL, SND_SOC_NOPM, 0, 0), + + SND_SOC_DAPM_OUT_DRV_E("ClassD", SND_SOC_NOPM, 0, 0, NULL, 0, + tas2557_classd_event, + SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD), + + /* IV sense is powered by the startup sequence, not by DAPM writes */ + SND_SOC_DAPM_ADC("ISENSE", NULL, SND_SOC_NOPM, 0, 0), + SND_SOC_DAPM_ADC("VSENSE", NULL, SND_SOC_NOPM, 0, 0), + + SND_SOC_DAPM_OUTPUT("OUT"), + SND_SOC_DAPM_AIF_OUT("SENSE", "Capture", 0, SND_SOC_NOPM, 0, 0), +}; + +static const struct snd_soc_dapm_route tas2557_dapm_routes[] = { + { "ASI", NULL, "Playback" }, + { "DAC", NULL, "ASI" }, + { "ClassD", NULL, "DAC" }, + { "OUT", NULL, "ClassD" }, + + { "ISENSE", NULL, "ClassD" }, + { "VSENSE", NULL, "ClassD" }, + { "SENSE", NULL, "ISENSE" }, + { "SENSE", NULL, "VSENSE" }, + { "Capture", NULL, "SENSE" }, +}; + +/* ========================================================================= + * ASoC component probe / suspend / resume + * ========================================================================= + */ +static int tas2557_codec_probe(struct snd_soc_component *component) +{ + struct tas2557_priv *tas2557 = snd_soc_component_get_drvdata(component); + const char *default_fw; + unsigned int chn; + int ret; + + /* Serialise against a pending tas2557_fw_ready() on a card re-bind */ + guard(mutex)(&tas2557->tas_priv->codec_lock); + + tas2557_hw_reset(tas2557); + + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) { + ret = tas2557_dev_write(tas2557, chn, TAS2557_SW_RESET_REG, 0x01); + if (ret < 0) { + dev_err(tas2557->tas_priv->dev, "chn %u: software reset failed: %d\n", + chn, ret); + return ret; + } + } + usleep_range(1000, 2000); + + for (chn = 0; chn < tas2557->tas_priv->ndev; chn++) { + unsigned int pg_id; + + ret = tas2557_dev_read(tas2557, chn, TAS2557_REV_PGID_REG, &pg_id); + if (ret < 0) { + dev_err(tas2557->tas_priv->dev, "chn %u: failed to read REV_PGID: %d\n", + chn, ret); + return ret; + } + tas2557->devs[chn].pg_id = pg_id; + } + + /* + * Firmware selection is group-wide (one shared image); the PG + * version of devs[0] is used as the representative silicon + * revision, matching how current_program/current_config/pg_id are + * otherwise read back from devs[0] elsewhere in this driver. + */ + switch (tas2557->devs[0].pg_id) { + case TAS2557_PG_VERSION_1P0: + dev_dbg(tas2557->tas_priv->dev, "silicon: PG1.0 (0x%02x)\n", + tas2557->devs[0].pg_id); + default_fw = TAS2557_PG1P0_FW_NAME; + break; + case TAS2557_PG_VERSION_2P0: + dev_dbg(tas2557->tas_priv->dev, "silicon: PG2.0 (0x%02x)\n", + tas2557->devs[0].pg_id); + default_fw = TAS2557_FW_NAME; + break; + case TAS2557_PG_VERSION_2P1: + dev_dbg(tas2557->tas_priv->dev, "silicon: PG2.1 (0x%02x)\n", + tas2557->devs[0].pg_id); + default_fw = TAS2557_FW_NAME; + break; + default: + dev_warn(tas2557->tas_priv->dev, + "unknown silicon version 0x%02x, assuming PG2.x fw\n", + tas2557->devs[0].pg_id); + default_fw = TAS2557_FW_NAME; + break; + } + + /* + * A "firmware-name" DT property (read at i2c probe) overrides the + * PG-based default; dual-amp stereo boards load a different DSP + * blob (e.g. tas2557s_uCDSP.bin). + */ + if (!tas2557->fw_name[0]) + strscpy(tas2557->fw_name, default_fw, sizeof(tas2557->fw_name)); + + ret = tas2557_load_data_all(tas2557, tas2557_default_data); + if (ret < 0) { + dev_err(tas2557->tas_priv->dev, "default data load failed: %d\n", ret); + return ret; + } + + ret = tas2557_load_data_all(tas2557, tas2557_irq_config); + if (ret < 0) + dev_warn(tas2557->tas_priv->dev, "IRQ config failed: %d\n", ret); + + /* + * Component rebind (e.g. after an unbind/bind cycle): firmware is + * already parsed and stored, so do not request it again. + */ + if (!tas2557->fw_requested) { + reinit_completion(&tas2557->fw_done); + ret = request_firmware_nowait(THIS_MODULE, FW_ACTION_UEVENT, + tas2557->fw_name, tas2557->tas_priv->dev, + GFP_KERNEL, tas2557, + tas2557_fw_ready); + if (ret) { + return dev_err_probe(tas2557->tas_priv->dev, ret, + "failed to request fw '%s'\n", + tas2557->fw_name); + } + tas2557->fw_requested = true; + } + + dev_dbg(tas2557->tas_priv->dev, "codec probed (%u chip(s)), requesting firmware '%s'\n", + tas2557->tas_priv->ndev, tas2557->fw_name); + return 0; +} + +static int tas2557_suspend(struct snd_soc_component *component) +{ + struct tas2557_priv *tas2557 = snd_soc_component_get_drvdata(component); + + tas2557_irq_disarm(tas2557); + + guard(mutex)(&tas2557->tas_priv->codec_lock); + if (!tas2557->powered) + return 0; + + return tas2557_enable(tas2557, false); +} + +static int tas2557_resume(struct snd_soc_component *component) +{ + struct tas2557_priv *tas2557 = snd_soc_component_get_drvdata(component); + int ret; + + guard(mutex)(&tas2557->tas_priv->codec_lock); + + /* Also invalidates the loaded program, even without a reset GPIO */ + tas2557_hw_reset(tas2557); + + ret = tas2557_load_data_all(tas2557, tas2557_default_data); + if (ret < 0) + dev_err(tas2557->tas_priv->dev, "defaults reload on resume failed: %d\n", + ret); + else if (tas2557_load_data_all(tas2557, tas2557_irq_config) < 0) + dev_warn(tas2557->tas_priv->dev, "IRQ config reload on resume failed\n"); + + /* + * The group stays powered down until the next DAPM power-up, which + * reloads the program and applies both mute states. + */ + + return ret; +} + +static const struct snd_soc_component_driver soc_component_tas2557 = { + .probe = tas2557_codec_probe, + .suspend = tas2557_suspend, + .resume = tas2557_resume, + .controls = tas2557_controls, + .num_controls = ARRAY_SIZE(tas2557_controls), + .dapm_widgets = tas2557_dapm_widgets, + .num_dapm_widgets = ARRAY_SIZE(tas2557_dapm_widgets), + .dapm_routes = tas2557_dapm_routes, + .num_dapm_routes = ARRAY_SIZE(tas2557_dapm_routes), + .idle_bias_on = 1, + .use_pmdown_time = 1, + .endianness = 1, +}; + +/* ========================================================================= + * I2C driver + * ========================================================================= + */ + +/* + * tas2557_parse_dt - populate tas_priv->tasdevice[]/ndev, the per-chip + * reset/IRQ lines and ti,asi-port + * + * `reg` holds one I2C address per chip (up to TAS2557_MAX_DEV), read with + * of_property_read_reg() as tasdevice_parse_dt() does, since + * i2c_client::addr only reflects the first entry. Without an OF node a + * single chip at the i2c_client's address is used. + * + * A single reset-gpios/interrupts entry applies to every chip. + */ +static int tas2557_parse_dt(struct tas2557_priv *tas2557, struct i2c_client *client) +{ + struct tasdevice_priv *tas_priv = tas2557->tas_priv; + struct device *dev = tas_priv->dev; + struct device_node *np = dev->of_node; + unsigned int i; + int ndev = 0; + int ret; + + if (np) { + u64 addr; + + for (i = 0; i < TAS2557_MAX_DEV; i++) { + if (of_property_read_reg(np, i, &addr, NULL)) + break; + tas_priv->tasdevice[ndev++].dev_addr = addr; + } + } + + if (ndev == 0) { + ndev = 1; + tas_priv->tasdevice[0].dev_addr = client->addr; + } + + tas_priv->ndev = ndev; + + /* + * Reserve every secondary address on the bus so no other + * driver can claim it; tasdevice_change_chn_book() keeps swapping + * client->addr to reach each chip, these dummies only reserve the + * i2c_client namespace. + */ + for (i = 1; i < tas_priv->ndev; i++) { + struct i2c_client *dummy = devm_i2c_new_dummy_device(dev, + client->adapter, tas_priv->tasdevice[i].dev_addr); + if (IS_ERR(dummy)) + return dev_err_probe(dev, PTR_ERR(dummy), + "failed to reserve i2c addr 0x%02x\n", + tas_priv->tasdevice[i].dev_addr); + } + + /* + * reset-gpios / interrupts, minItems 1 maxItems 2; a single + * entry applies to every chip. Reset GPIOs are modeled active-low + * in DT: the logical value 0 (GPIOD_OUT_LOW) deasserts reset, + * releasing the device group. + */ + for (i = 0; i < tas_priv->ndev; i++) { + tas2557->reset[i] = devm_gpiod_get_index_optional(dev, "reset", i, + GPIOD_OUT_LOW); + if (IS_ERR(tas2557->reset[i])) + return dev_err_probe(dev, PTR_ERR(tas2557->reset[i]), + "failed to get reset GPIO %u\n", i); + if (!tas2557->reset[i] && i > 0) + tas2557->reset[i] = tas2557->reset[0]; + + tas2557->irq[i] = of_irq_get(np, i); + if (tas2557->irq[i] == -EPROBE_DEFER) + return dev_err_probe(dev, tas2557->irq[i], + "interrupt %u not ready\n", i); + if (tas2557->irq[i] <= 0 && i > 0) + tas2557->irq[i] = tas2557->irq[0]; + /* Index 0 falls back to the primary i2c_client IRQ */ + if (i == 0 && tas2557->irq[i] <= 0) + tas2557->irq[i] = client->irq; + } + + /* Which ASI's pins/dividers/format registers to program */ + tas2557->asi_port = TAS2557_ASI_PORT_DEFAULT; + ret = of_property_read_u32(np, "ti,asi-port", &tas2557->asi_port); + if (ret && ret != -EINVAL) + return dev_err_probe(dev, ret, "failed to read ti,asi-port\n"); + if (tas2557->asi_port != TAS2557_ASI_PORT1 && + tas2557->asi_port != TAS2557_ASI_PORT2) + return dev_err_probe(dev, -EINVAL, + "ti,asi-port must be 1 or 2, got %u\n", + tas2557->asi_port); + + for (i = 0; i < tas_priv->ndev; i++) { + tas2557->devs[i].pg_id = 0; + tas2557->devs[i].current_program = 0; + tas2557->devs[i].current_config = 0; + tas2557->devs[i].restart_count = 0; + tas2557->devs[i].asi_offset = 0; + } + + return 0; +} + +/* + * Destroys codec_lock; must run after everything that can take it. + * comlib leaves client->addr on the last chip it accessed; put the primary + * address back so a later probe can reserve it again. + */ +static void tas2557_comlib_remove(void *data) +{ + struct tasdevice_priv *tas_priv = data; + struct i2c_client *client = tas_priv->client; + + client->addr = tas_priv->tasdevice[0].dev_addr; + tasdevice_remove(tas_priv); +} + +static int tas2557_i2c_probe(struct i2c_client *client) +{ + static const char * const tas2557_supplies[] = { + "vbat", "iovdd", "avdd", "dvdd" + }; + struct device *dev = &client->dev; + struct tas2557_priv *tas2557; + struct tasdevice_priv *tas_priv; + const char *fw_name; + unsigned int i, j; + int irq, ret; + + tas2557 = devm_kzalloc(dev, sizeof(*tas2557), GFP_KERNEL); + if (!tas2557) + return -ENOMEM; + + /* tas2781-comlib owns the paged regmap and per-chip register I/O */ + tas_priv = tasdevice_kzalloc(client); + if (!tas_priv) + return -ENOMEM; + tas2557->tas_priv = tas_priv; + + i2c_set_clientdata(client, tas2557); + + init_completion(&tas2557->fw_done); + tas2557->fw_requested = false; + + ret = tas2557_parse_dt(tas2557, client); + if (ret) + return ret; + + /* Default gain: +15 dB, as the firmware programs write */ + tas2557->dac_gain = TAS2557_DAC_GAIN_MAX; + + /* The device group comes out of reset muted */ + tas2557->dac_muted = true; + + /* -1 means "never set"; see tas2557_apply_runtime_state() */ + tas2557->dai_fmt = -1; + + /* Seed a valid ASI word length before the first hw_params() */ + tas2557->wordlength = TAS2557_WORDLENGTH_32BIT; + + /* Explicit firmware name; overrides the PG-based mono default */ + if (!of_property_read_string(dev->of_node, "firmware-name", &fw_name)) + strscpy(tas2557->fw_name, fw_name, sizeof(tas2557->fw_name)); + else if (tas_priv->ndev > 1) + return dev_err_probe(dev, -EINVAL, + "firmware-name is required for two chips\n"); + + ret = devm_regulator_bulk_get_enable(dev, ARRAY_SIZE(tas2557_supplies), + tas2557_supplies); + if (ret) + return dev_err_probe(dev, ret, + "failed to get/enable supplies\n"); + usleep_range(5000, 10000); + + ret = tasdevice_init(tas_priv); + if (ret) + return dev_err_probe(dev, ret, "comlib init failed\n"); + + /* + * Both actions are registered right after tasdevice_init(). devm + * actions run in LIFO order: the component registered below goes + * first, then the IRQs, then tas2557_fw_teardown() (nothing can + * still run tas2557_irq_handler() or the DAI ops at that point, and + * it waits for tas2557_fw_ready()), and only then is codec_lock + * destroyed, before the comlib regmap, reset GPIOs and regulators + * are released. + */ + ret = devm_add_action_or_reset(dev, tas2557_comlib_remove, tas_priv); + if (ret) + return ret; + + ret = devm_add_action_or_reset(dev, tas2557_fw_teardown, tas2557); + if (ret) + return ret; + + /* One threaded handler per configured IRQ, same dev_id */ + for (i = 0; i < tas_priv->ndev; i++) { + if (i > 0 && tas2557->irq[i] == tas2557->irq[i - 1]) + continue; + if (tas2557->irq[i] <= 0) + continue; + + irq = tas2557->irq[i]; + ret = devm_request_threaded_irq(dev, irq, NULL, + tas2557_irq_handler, + IRQF_ONESHOT | IRQF_NO_AUTOEN, + "tas2557", tas2557); + if (ret) { + dev_warn(dev, "IRQ %d request failed: %d\n", irq, ret); + /* Every chip sharing the line loses it */ + for (j = i; j < tas_priv->ndev; j++) + if (tas2557->irq[j] == irq) + tas2557->irq[j] = 0; + } else { + dev_dbg(dev, "IRQ %d registered\n", irq); + } + } + + ret = devm_snd_soc_register_component(dev, &soc_component_tas2557, + &tas2557_dai, 1); + if (ret) + return dev_err_probe(dev, ret, + "component registration failed\n"); + + dev_dbg(dev, "TAS2557 probed (%u chip(s), primary I2C addr 0x%02x, ASI%u)\n", + tas_priv->ndev, client->addr, tas2557->asi_port); + return 0; +} + +static const struct i2c_device_id tas2557_i2c_id[] = { + { .name = "tas2557" }, + { } +}; +MODULE_DEVICE_TABLE(i2c, tas2557_i2c_id); + +static const struct of_device_id tas2557_of_match[] = { + { .compatible = "ti,tas2557" }, + { } +}; +MODULE_DEVICE_TABLE(of, tas2557_of_match); + +static struct i2c_driver tas2557_i2c_driver = { + .driver = { + .name = "tas2557", + .of_match_table = tas2557_of_match, + }, + .probe = tas2557_i2c_probe, + .id_table = tas2557_i2c_id, +}; +module_i2c_driver(tas2557_i2c_driver); + +MODULE_AUTHOR("Texas Instruments Inc."); +MODULE_AUTHOR("Gianluca Boiano "); +MODULE_DESCRIPTION("ASoC TAS2557 Smart Amplifier Driver"); +MODULE_FIRMWARE(TAS2557_FW_NAME); +MODULE_FIRMWARE(TAS2557_PG1P0_FW_NAME); +MODULE_LICENSE("GPL"); diff --git a/sound/soc/codecs/tas2557.h b/sound/soc/codecs/tas2557.h new file mode 100644 index 00000000000000..0b01496d944a30 --- /dev/null +++ b/sound/soc/codecs/tas2557.h @@ -0,0 +1,207 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* + * ALSA SoC Texas Instruments TAS2557 Smart Amplifier + * + * Copyright (C) 2016 Texas Instruments Inc. + * Copyright (C) 2026 Gianluca Boiano + */ + +#ifndef __TAS2557_H__ +#define __TAS2557_H__ + +#include +#include + +/* + * TAS2557 uses a book/page/register addressing scheme, same layout as + * tas2781-comlib's TASDEVICE_REG(): 8-bit registers, page selected via + * register 0, book selected via register 0x7f in page 0. Register + * access, book/page switching and the paged-window regmap are all + * provided by tas2781-comlib(-i2c); this header only keeps the TAS2557_* + * register names for readability, defined in terms of TASDEVICE_REG(). + */ + +/* Build a register address from firmware-block book/page/offset bytes */ +#define TAS2557_REG(book, page, reg) TASDEVICE_REG(book, page, reg) + +/* Book 0, Page 0 registers */ +#define TAS2557_SW_RESET_REG TASDEVICE_REG(0, 0, 1) +#define TAS2557_REV_PGID_REG TASDEVICE_REG(0, 0, 3) +#define TAS2557_POWER_CTRL1_REG TASDEVICE_REG(0, 0, 4) +#define TAS2557_POWER_CTRL2_REG TASDEVICE_REG(0, 0, 5) +#define TAS2557_SPK_CTRL_REG TASDEVICE_REG(0, 0, 6) +#define TAS2557_MUTE_REG TASDEVICE_REG(0, 0, 7) +#define TAS2557_ADC_INPUT_SEL_REG TASDEVICE_REG(0, 0, 9) +#define TAS2557_DBOOST_CTL_REG TASDEVICE_REG(0, 0, 10) +#define TAS2557_SAR_SAMPLING_TIME_REG TASDEVICE_REG(0, 0, 19) +#define TAS2557_SAR_ADC1_REG TASDEVICE_REG(0, 0, 20) +#define TAS2557_SAR_ADC2_REG TASDEVICE_REG(0, 0, 21) +#define TAS2557_CRC_CHECKSUM_REG TASDEVICE_REG(0, 0, 32) +#define TAS2557_CRC_RESET_REG TASDEVICE_REG(0, 0, 33) +#define TAS2557_DSP_MODE_SELECT_REG TASDEVICE_REG(0, 0, 34) +#define TAS2557_SAFE_GUARD_REG TASDEVICE_REG(0, 0, 37) +#define TAS2557_ASI_CTL1_REG TASDEVICE_REG(0, 0, 42) +#define TAS2557_CLK_ERR_CTRL TASDEVICE_REG(0, 0, 44) +#define TAS2557_CLK_ERR_CTRL2 TASDEVICE_REG(0, 0, 45) +#define TAS2557_CLK_ERR_CTRL3 TASDEVICE_REG(0, 0, 46) +#define TAS2557_DBOOST_CFG_REG TASDEVICE_REG(0, 0, 52) +#define TAS2557_POWER_UP_FLAG_REG TASDEVICE_REG(0, 0, 100) +#define TAS2557_FLAGS_1 TASDEVICE_REG(0, 0, 104) +#define TAS2557_FLAGS_2 TASDEVICE_REG(0, 0, 108) + +/* Book 0, Page 1 registers - ASI1 configuration */ +#define TAS2557_ASI1_DAC_FORMAT_REG TASDEVICE_REG(0, 1, 1) +#define TAS2557_ASI1_OFFSET1_REG TASDEVICE_REG(0, 1, 3) +#define TAS2557_ASI1_ADC_PATH_REG TASDEVICE_REG(0, 1, 7) +#define TAS2557_ASI1_DAC_BCLK_REG TASDEVICE_REG(0, 1, 8) +#define TAS2557_ASI1_DAC_WCLK_REG TASDEVICE_REG(0, 1, 9) +#define TAS2557_ASI1_ADC_BCLK_REG TASDEVICE_REG(0, 1, 10) +#define TAS2557_ASI1_ADC_WCLK_REG TASDEVICE_REG(0, 1, 11) +#define TAS2557_ASI1_DIN_DOUT_MUX_REG TASDEVICE_REG(0, 1, 12) + +/* Book 0, Page 1 - ASI2 configuration */ +#define TAS2557_ASI2_DAC_FORMAT_REG TASDEVICE_REG(0, 1, 21) +#define TAS2557_ASI2_OFFSET1_REG TASDEVICE_REG(0, 1, 23) +#define TAS2557_ASI2_ADC_PATH_REG TASDEVICE_REG(0, 1, 27) +#define TAS2557_ASI2_DAC_BCLK_REG TASDEVICE_REG(0, 1, 28) +#define TAS2557_ASI2_DAC_WCLK_REG TASDEVICE_REG(0, 1, 29) +#define TAS2557_ASI2_ADC_BCLK_REG TASDEVICE_REG(0, 1, 30) +#define TAS2557_ASI2_ADC_WCLK_REG TASDEVICE_REG(0, 1, 31) +#define TAS2557_ASI2_DIN_DOUT_MUX_REG TASDEVICE_REG(0, 1, 32) +#define TAS2557_ASI2_BDIV_CLK_SEL_REG TASDEVICE_REG(0, 1, 33) +#define TAS2557_ASI2_BDIV_CLK_RATIO_REG TASDEVICE_REG(0, 1, 34) +#define TAS2557_ASI2_WDIV_CLK_RATIO_REG TASDEVICE_REG(0, 1, 35) +#define TAS2557_ASI2_DAC_CLKOUT_REG TASDEVICE_REG(0, 1, 36) +#define TAS2557_ASI2_ADC_CLKOUT_REG TASDEVICE_REG(0, 1, 37) + +/* Book 0, Page 1 - GPIO pin configuration */ +#define TAS2557_GPIO1_PIN_REG TASDEVICE_REG(0, 1, 61) +#define TAS2557_GPIO2_PIN_REG TASDEVICE_REG(0, 1, 62) +#define TAS2557_GPIO3_PIN_REG TASDEVICE_REG(0, 1, 63) +#define TAS2557_GPIO4_PIN_REG TASDEVICE_REG(0, 1, 64) +#define TAS2557_GPIO5_PIN_REG TASDEVICE_REG(0, 1, 65) +#define TAS2557_GPIO6_PIN_REG TASDEVICE_REG(0, 1, 66) +#define TAS2557_GPIO7_PIN_REG TASDEVICE_REG(0, 1, 67) +#define TAS2557_GPIO8_PIN_REG TASDEVICE_REG(0, 1, 68) +#define TAS2557_GPI_PIN_REG TASDEVICE_REG(0, 1, 77) + +/* Book 0, Page 1 - interrupt configuration */ +#define TAS2557_CLK_HALT_REG TASDEVICE_REG(0, 1, 106) +#define TAS2557_INT_GEN1_REG TASDEVICE_REG(0, 1, 108) +#define TAS2557_INT_GEN2_REG TASDEVICE_REG(0, 1, 109) +#define TAS2557_INT_GEN3_REG TASDEVICE_REG(0, 1, 110) +#define TAS2557_INT_GEN4_REG TASDEVICE_REG(0, 1, 111) +#define TAS2557_INT_MODE_REG TASDEVICE_REG(0, 1, 114) +#define TAS2557_MAIN_CLKIN_REG TASDEVICE_REG(0, 1, 115) +#define TAS2557_PLL_CLKIN_REG TASDEVICE_REG(0, 1, 116) + +/* Book 0, Page 2 */ +#define TAS2557_SLEEPMODE_CTL_REG TASDEVICE_REG(0, 2, 7) + +/* Book 100, Page 0 - DSP / PLL registers */ +#define TAS2557_DAC_INTERPOL_REG TASDEVICE_REG(100, 0, 1) +#define TAS2557_SOFT_MUTE_REG TASDEVICE_REG(100, 0, 7) +#define TAS2557_PLL_P_VAL_REG TASDEVICE_REG(100, 0, 27) +#define TAS2557_PLL_J_VAL_REG TASDEVICE_REG(100, 0, 28) +#define TAS2557_PLL_D_VAL_MSB_REG TASDEVICE_REG(100, 0, 29) +#define TAS2557_PLL_D_VAL_LSB_REG TASDEVICE_REG(100, 0, 30) +#define TAS2557_CLK_MISC_REG TASDEVICE_REG(100, 0, 31) +#define TAS2557_PLL_N_VAL_REG TASDEVICE_REG(100, 0, 32) +#define TAS2557_DAC_MADC_VAL_REG TASDEVICE_REG(100, 0, 33) +#define TAS2557_VBOOST_CTL_REG TASDEVICE_REG(100, 0, 64) + +/* Book 130, Page 2 - Die temperature */ +#define TAS2557_DIE_TEMP_REG TASDEVICE_REG(130, 2, 124) + +/* DSP coefficient swap register (skipped by the firmware CRC checker) */ +#define TAS2557_SA_COEFF_SWAP_REG TASDEVICE_REG(0, 53, 44) + +/* PG (Process Generation) version identifiers from REV_PGID_REG */ +#define TAS2557_PG_VERSION_1P0 0x80 +#define TAS2557_PG_VERSION_2P0 0x90 +#define TAS2557_PG_VERSION_2P1 0xa0 + +/* B0P0R4 - TAS2557_POWER_CTRL1_REG */ +#define TAS2557_SW_SHUTDOWN BIT(0) +#define TAS2557_MADC_POWER_UP BIT(3) +#define TAS2557_MDAC_POWER_UP BIT(4) +#define TAS2557_NDIV_POWER_UP BIT(5) +#define TAS2557_PLL_POWER_UP BIT(6) +#define TAS2557_DSP_POWER_UP BIT(7) + +/* B0P0R5 - TAS2557_POWER_CTRL2_REG */ +#define TAS2557_BOOST_ENABLE BIT(5) +#define TAS2557_CLASSD_ENABLE BIT(7) + +/* B0P0R6 - TAS2557_SPK_CTRL_REG */ +#define TAS2557_DAC_GAIN_MASK (0xf << 3) +#define TAS2557_DAC_GAIN_SHIFT 3 +#define TAS2557_DAC_GAIN_MAX 0x0f + +/* B0P0R7 - TAS2557_MUTE_REG */ +#define TAS2557_MUTE_VSNS BIT(0) +#define TAS2557_MUTE_ISNS BIT(1) + +/* B100P0R7 - TAS2557_SOFT_MUTE_REG */ +#define TAS2557_PDM_SOFT_MUTE BIT(0) + +/* ASI format field in ASIx_DAC_FORMAT_REG bits [7:5] */ +#define TAS2557_FORMAT_I2S (0x0 << 5) +#define TAS2557_FORMAT_DSP (0x1 << 5) +#define TAS2557_FORMAT_RIGHT_J (0x2 << 5) +#define TAS2557_FORMAT_LEFT_J (0x3 << 5) +#define TAS2557_FORMAT_MONO_PCM (0x4 << 5) +#define TAS2557_FORMAT_MASK (0x7 << 5) + +/* ASI word length field in ASIx_DAC_FORMAT_REG bits [4:3] */ +#define TAS2557_WORDLENGTH_16BIT (0x0 << 3) +#define TAS2557_WORDLENGTH_20BIT (0x1 << 3) +#define TAS2557_WORDLENGTH_24BIT (0x2 << 3) +#define TAS2557_WORDLENGTH_32BIT (0x3 << 3) +#define TAS2557_WORDLENGTH_MASK (0x3 << 3) + +/* Safe guard pattern written to TAS2557_SAFE_GUARD_REG */ +#define TAS2557_SAFE_GUARD_PATTERN 0x5a + +/* Firmware filenames - PG version determines which file is loaded */ +#define TAS2557_FW_NAME "tas2557_uCDSP.bin" +#define TAS2557_PG1P0_FW_NAME "tas2557_pg1p0_uCDSP.bin" + +/* Firmware block type codes */ +#define TAS2557_BLOCK_PLL 0x00 +#define TAS2557_BLOCK_PGM_ALL 0x0d +#define TAS2557_BLOCK_PGM_DEV_A 0x01 +#define TAS2557_BLOCK_PGM_DEV_B 0x08 +#define TAS2557_BLOCK_CFG_COEFF_DEV_A 0x03 +#define TAS2557_BLOCK_CFG_COEFF_DEV_B 0x0a +#define TAS2557_BLOCK_CFG_PRE_DEV_A 0x04 +#define TAS2557_BLOCK_CFG_PRE_DEV_B 0x0b +#define TAS2557_BLOCK_CFG_POST 0x05 +#define TAS2557_BLOCK_CFG_POST_POWER 0x06 + +/* + * ti,asi-port selects which ASI's pin mux/clock dividers/format registers + * this driver programs; the other ASI's registers are left untouched at + * reset defaults. + */ +#define TAS2557_ASI_PORT1 1 +#define TAS2557_ASI_PORT2 2 +#define TAS2557_ASI_PORT_DEFAULT TAS2557_ASI_PORT2 + +/* + * One DT node manages an array of up to TAS2557_MAX_DEV physical chips + * (one entry per `reg` address), all sharing one firmware image, DAI and + * mute/power state via tas2781-comlib's per-channel register access + * (tasdevice_dev_*(tas_priv, chn, ...)). reset-gpios/interrupts follow + * the same per-index convention (a single entry applies to every chip). + */ +#define TAS2557_MAX_DEV 2 + +/* Firmware driver version flags (driver_version field) */ +#define PPC_DRIVER_CRCCHK 0x00000200 +#define PPC_DRIVER_CONFDEV 0x00000300 +#define PPC_DRIVER_MTPLLSRC 0x00000400 +/* Present from driver_version 0x101; carries a 2-byte device field */ +#define PPC_DRIVER_CFGDEV_NONCRC 0x00000101 + +#endif /* __TAS2557_H__ */ diff --git a/sound/soc/codecs/tas2781-fmwlib.c b/sound/soc/codecs/tas2781-fmwlib.c index 527d5e0ab906fd..f5ac082e07f3d0 100644 --- a/sound/soc/codecs/tas2781-fmwlib.c +++ b/sound/soc/codecs/tas2781-fmwlib.c @@ -897,7 +897,7 @@ static int tasdevice_process_block(void *context, unsigned char *data, unsigned char dev_idx, int sublocksize) { struct tasdevice_priv *tas_priv = (struct tasdevice_priv *)context; - int subblk_offset, chn, chnend, rc; + int subblk_offset = 0, chn, chnend, rc; unsigned char subblk_typ = data[1]; int blktyp = dev_idx & 0xC0; int idx = dev_idx & 0x3F; diff --git a/sound/soc/codecs/tas2781-i2c.c b/sound/soc/codecs/tas2781-i2c.c index e44a1d460c703d..2dbbd13f5e8143 100644 --- a/sound/soc/codecs/tas2781-i2c.c +++ b/sound/soc/codecs/tas2781-i2c.c @@ -1605,70 +1605,12 @@ static int tas2573_status_get_common(struct snd_kcontrol *kcontrol, return 0; } +/* Calibration status control */ static int tas2573_calib_status_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { - struct snd_soc_component *comp = snd_kcontrol_chip(kcontrol); - struct tasdevice_priv *priv = snd_soc_component_get_drvdata(comp); - unsigned char *dst = ucontrol->value.bytes.data; - struct soc_bytes_ext *bytes_ext = - (struct soc_bytes_ext *) kcontrol->private_value; - unsigned int fct_status_regs[] = { - TAS2573_FCT_INT_LATCH, - TAS2573_FCT_STATUS_CTRL, - TAS2573_FCT_STATUS_BINNING, - TAS2573_SILENCE_DETECTED, - TAS2573_OPEN_CIRCUIT, - TAS2573_SHORTCKT, - TAS2573_FCT_OUTPUT_R0, - TAS2573_FCT_OUTPUT_R0_LOW, - TAS2573_FCT_OUTPUT_INV_R0, - TAS2573_FCT_OUTPUT_POWERTOT, - TAS2573_FCT_OUTPUT_F0, - TAS2573_RE_OUT, - }; - unsigned int j, k, val; - unsigned int i = 0; - int rc; - - guard(mutex)(&priv->codec_lock); - dst[i++] = bytes_ext->max; - dst[i++] = 'r'; - - for (j = 0; j < ARRAY_SIZE(fct_status_regs); j++) { - dst[i++] = TASDEVICE_BOOK_ID(fct_status_regs[j]); - dst[i++] = TASDEVICE_PAGE_ID(fct_status_regs[j]); - dst[i++] = TASDEVICE_PAGE_REG(fct_status_regs[j]); - } - dst[i++] = 'D'; - - for (j = 0; j < priv->ndev; j++) { - dst[i++] = j; - dst[i++] = 0; - dst[i++] = 0; - dst[i++] = 0; - - rc = tasdevice_dev_read(priv, j, fct_status_regs[0], &val); - if (rc < 0) - dev_err(priv->dev, - "chn %d fct_status_regs[0] rd err = %d\n", - j, rc); - else - dst[i++] = val; - - for (k = 1; k < ARRAY_SIZE(fct_status_regs); k++, i += 4) { - rc = tasdevice_dev_bulk_read(priv, j, - fct_status_regs[k], &dst[i], 4); - if (rc < 0) { - dev_err(priv->dev, - "chn %d regs[%u] bulk_rd err = %d\n", - j, k, rc); - } - } - - } - - return 0; + return tas2573_status_get_common(kcontrol, ucontrol, + &calib_status_map); } static int create_tas2573_cali_status_ktrl(struct tasdevice_priv @@ -1696,7 +1638,8 @@ static int create_tas2573_cali_status_ktrl(struct tasdevice_priv * Sine gain for Device #i (48 bytes) * } */ - ext_cali_start->max = 39 + priv->ndev * 49; + ext_cali_start->max = calib_status_map.nregs * 3 + 3 + + priv->ndev * (calib_status_map.nregs * 4 + 1); cali_ctrl->name = cali_start_name; cali_ctrl->iface = SNDRV_CTL_ELEM_IFACE_MIXER; cali_ctrl->info = snd_soc_bytes_info_ext; diff --git a/sound/soc/codecs/wcd-common.c b/sound/soc/codecs/wcd-common.c index 9016e974582f55..7c2d96ace030fe 100644 --- a/sound/soc/codecs/wcd-common.c +++ b/sound/soc/codecs/wcd-common.c @@ -15,6 +15,8 @@ #include "wcd-common.h" +#define WCD_IRQ_MAX_RETRIES 10 + #define WCD_MIN_MICBIAS_MV 1000 #define WCD_DEF_MICBIAS_MV 1800 #define WCD_MAX_MICBIAS_MV 2850 @@ -127,16 +129,27 @@ int wcd_interrupt_callback(struct sdw_slave *slave, struct irq_domain *slave_irq { struct regmap *regmap = dev_get_regmap(&slave->dev, NULL); u32 sts1, sts2, sts3; + int ret, i; - do { + /* A failed read or a stuck status must not hold sdw_dev_lock forever. */ + for (i = 0; i < WCD_IRQ_MAX_RETRIES; i++) { handle_nested_irq(irq_find_mapping(slave_irq, 0)); - regmap_read(regmap, wcd_intr_status0, &sts1); - regmap_read(regmap, wcd_intr_status1, &sts2); - regmap_read(regmap, wcd_intr_status2, &sts3); + ret = regmap_read(regmap, wcd_intr_status0, &sts1); + if (ret) + return ret; + ret = regmap_read(regmap, wcd_intr_status1, &sts2); + if (ret) + return ret; + ret = regmap_read(regmap, wcd_intr_status2, &sts3); + if (ret) + return ret; - } while (sts1 || sts2 || sts3); + if (!(sts1 || sts2 || sts3)) + return IRQ_HANDLED; + } - return IRQ_HANDLED; + dev_err_ratelimited(&slave->dev, "interrupt status did not clear\n"); + return -ETIMEDOUT; } EXPORT_SYMBOL_GPL(wcd_interrupt_callback); diff --git a/sound/soc/codecs/wcd934x.c b/sound/soc/codecs/wcd934x.c index f274b24c58a75e..99e198761a6c6b 100644 --- a/sound/soc/codecs/wcd934x.c +++ b/sound/soc/codecs/wcd934x.c @@ -1702,7 +1702,6 @@ static int wcd934x_slim_set_hw_params(struct wcd934x_codec *wcd, /* Configure slave interface device */ list_for_each_entry(ch, slim_ch_list, list) { cfg->ch_count++; - payload |= 1 << ch->shift; cfg->port_mask |= BIT(ch->port); } @@ -1712,6 +1711,14 @@ static int wcd934x_slim_set_hw_params(struct wcd934x_codec *wcd, i = 0; list_for_each_entry(ch, slim_ch_list, list) { + /* + * Each port carries its own channel mask. Accumulating the bits + * across the whole list and writing the sum into every port would + * enable the other channels on a port that only gets one of them + * allocated on the bus; the codec then overruns the port's TX FIFO + * ("overflow error on TX port N"). + */ + payload = BIT(ch->shift); cfg->chs[i++] = ch->ch_num; if (direction == SNDRV_PCM_STREAM_PLAYBACK) { /* write to interface device */ @@ -5625,6 +5632,28 @@ static const struct snd_soc_dapm_widget wcd934x_dapm_widgets[] = { }; static const struct snd_soc_dapm_route wcd934x_audio_map[] = { + /* + * The ADC/DMIC front ends cannot produce a single sample without the + * codec sysclk: MCLK also gates the analog bias generator and the + * decimator clocks (see __wcd934x_cdc_mclk_enable()). Upstream only + * ever wired MCLK into the graph from the board file, as + * "RX_BIAS" -> "MCLK", i.e. from the playback side. A board that can + * only record (or that plays through another amp, like polaris) then + * runs a capture stream with an unclocked codec and reads digital + * silence. Express the dependency where it belongs, on the capture + * front ends, so no board has to remember it. + */ + {"ADC1", NULL, "MCLK"}, + {"ADC2", NULL, "MCLK"}, + {"ADC3", NULL, "MCLK"}, + {"ADC4", NULL, "MCLK"}, + {"DMIC0", NULL, "MCLK"}, + {"DMIC1", NULL, "MCLK"}, + {"DMIC2", NULL, "MCLK"}, + {"DMIC3", NULL, "MCLK"}, + {"DMIC4", NULL, "MCLK"}, + {"DMIC5", NULL, "MCLK"}, + /* RX0-RX7 */ WCD934X_SLIM_RX_AIF_PATH(0), WCD934X_SLIM_RX_AIF_PATH(1), diff --git a/sound/soc/codecs/wcd937x-sdw.c b/sound/soc/codecs/wcd937x-sdw.c index 57549518767ce9..5ad6b30d6555f4 100644 --- a/sound/soc/codecs/wcd937x-sdw.c +++ b/sound/soc/codecs/wcd937x-sdw.c @@ -1003,6 +1003,8 @@ static int wcd9370_probe(struct sdw_slave *pdev, if (wcd->is_tx) { master_ch_mask_size = of_property_count_u8_elems(dev->of_node, "qcom,tx-channel-mapping"); + master_ch_mask_size = min_t(int, master_ch_mask_size, + ARRAY_SIZE(master_ch_mask)); if (master_ch_mask_size) ret = of_property_read_u8_array(dev->of_node, "qcom,tx-channel-mapping", @@ -1010,6 +1012,8 @@ static int wcd9370_probe(struct sdw_slave *pdev, } else { master_ch_mask_size = of_property_count_u8_elems(dev->of_node, "qcom,rx-channel-mapping"); + master_ch_mask_size = min_t(int, master_ch_mask_size, + ARRAY_SIZE(master_ch_mask)); if (master_ch_mask_size) ret = of_property_read_u8_array(dev->of_node, "qcom,rx-channel-mapping", @@ -1023,6 +1027,8 @@ static int wcd9370_probe(struct sdw_slave *pdev, pdev->prop.source_ports = GENMASK(WCD937X_MAX_TX_SWR_PORTS, 0); pdev->prop.src_dpn_prop = wcd937x_dpn_prop; wcd->ch_info = &wcd937x_sdw_tx_ch_info[0]; + master_ch_mask_size = min_t(int, master_ch_mask_size, + ARRAY_SIZE(wcd937x_sdw_tx_ch_info)); for (i = 0; i < master_ch_mask_size; i++) wcd->ch_info[i].master_ch_mask = WCD937X_SWRM_CH_MASK(master_ch_mask[i]); @@ -1040,6 +1046,8 @@ static int wcd9370_probe(struct sdw_slave *pdev, pdev->prop.sink_ports = GENMASK(WCD937X_MAX_SWR_PORTS - 1, 0); pdev->prop.sink_dpn_prop = wcd937x_dpn_prop; wcd->ch_info = &wcd937x_sdw_rx_ch_info[0]; + master_ch_mask_size = min_t(int, master_ch_mask_size, + ARRAY_SIZE(wcd937x_sdw_rx_ch_info)); for (i = 0; i < master_ch_mask_size; i++) wcd->ch_info[i].master_ch_mask = WCD937X_SWRM_CH_MASK(master_ch_mask[i]); diff --git a/sound/soc/codecs/wm5102.c b/sound/soc/codecs/wm5102.c index 762e81979cb8d4..b52f1d30c3c05b 100644 --- a/sound/soc/codecs/wm5102.c +++ b/sound/soc/codecs/wm5102.c @@ -2040,13 +2040,7 @@ static int wm5102_probe(struct platform_device *pdev) return -ENOMEM; platform_set_drvdata(pdev, wm5102); - if (IS_ENABLED(CONFIG_OF)) { - if (!dev_get_platdata(arizona->dev)) { - ret = arizona_of_get_audio_pdata(arizona); - if (ret < 0) - return ret; - } - } + arizona_get_audio_pdata(arizona); mutex_init(&arizona->dac_comp_lock); diff --git a/sound/soc/codecs/wm5110.c b/sound/soc/codecs/wm5110.c index faa85d88a489bc..34a6ef55553010 100644 --- a/sound/soc/codecs/wm5110.c +++ b/sound/soc/codecs/wm5110.c @@ -2402,13 +2402,7 @@ static int wm5110_probe(struct platform_device *pdev) return -ENOMEM; platform_set_drvdata(pdev, wm5110); - if (IS_ENABLED(CONFIG_OF)) { - if (!dev_get_platdata(arizona->dev)) { - ret = arizona_of_get_audio_pdata(arizona); - if (ret < 0) - return ret; - } - } + arizona_get_audio_pdata(arizona); wm5110->core.arizona = arizona; wm5110->core.num_inputs = 8; diff --git a/sound/soc/codecs/wm8731.c b/sound/soc/codecs/wm8731.c index f25b50919a9a58..f22f57b05ff27d 100644 --- a/sound/soc/codecs/wm8731.c +++ b/sound/soc/codecs/wm8731.c @@ -557,6 +557,7 @@ static struct snd_soc_dai_driver wm8731_dai = { .formats = WM8731_FORMATS,}, .ops = &wm8731_dai_ops, .symmetric_rate = 1, + .symmetric_sample_bits = 1, }; static const struct snd_soc_component_driver soc_component_dev_wm8731 = { diff --git a/sound/soc/codecs/wm8993.c b/sound/soc/codecs/wm8993.c index fbadbb33b6079d..f84736bb5d26f6 100644 --- a/sound/soc/codecs/wm8993.c +++ b/sound/soc/codecs/wm8993.c @@ -1729,14 +1729,13 @@ static int wm8993_i2c_probe(struct i2c_client *i2c) &soc_component_dev_wm8993, &wm8993_dai, 1); if (ret != 0) { dev_err(&i2c->dev, "Failed to register CODEC: %d\n", ret); - goto err_irq; + if (i2c->irq) + free_irq(i2c->irq, wm8993); + return ret; } return 0; -err_irq: - if (i2c->irq) - free_irq(i2c->irq, wm8993); err_enable: regulator_bulk_disable(ARRAY_SIZE(wm8993->supplies), wm8993->supplies); return ret; @@ -1748,7 +1747,6 @@ static void wm8993_i2c_remove(struct i2c_client *i2c) if (i2c->irq) free_irq(i2c->irq, wm8993); - regulator_bulk_disable(ARRAY_SIZE(wm8993->supplies), wm8993->supplies); } static const struct i2c_device_id wm8993_i2c_id[] = { diff --git a/sound/soc/codecs/wm8997.c b/sound/soc/codecs/wm8997.c index f041dfc905a427..f4608c1f16bb6c 100644 --- a/sound/soc/codecs/wm8997.c +++ b/sound/soc/codecs/wm8997.c @@ -1118,13 +1118,7 @@ static int wm8997_probe(struct platform_device *pdev) return -ENOMEM; platform_set_drvdata(pdev, wm8997); - if (IS_ENABLED(CONFIG_OF)) { - if (!dev_get_platdata(arizona->dev)) { - ret = arizona_of_get_audio_pdata(arizona); - if (ret < 0) - return ret; - } - } + arizona_get_audio_pdata(arizona); wm8997->core.arizona = arizona; wm8997->core.num_inputs = 4; diff --git a/sound/soc/codecs/wm8998.c b/sound/soc/codecs/wm8998.c index 1158e9ca40a132..9eb82d46346ce7 100644 --- a/sound/soc/codecs/wm8998.c +++ b/sound/soc/codecs/wm8998.c @@ -1345,13 +1345,7 @@ static int wm8998_probe(struct platform_device *pdev) return -ENOMEM; platform_set_drvdata(pdev, wm8998); - if (IS_ENABLED(CONFIG_OF)) { - if (!dev_get_platdata(arizona->dev)) { - ret = arizona_of_get_audio_pdata(arizona); - if (ret < 0) - return ret; - } - } + arizona_get_audio_pdata(arizona); wm8998->core.arizona = arizona; wm8998->core.num_inputs = 3; /* IN1L, IN1R, IN2 */ diff --git a/sound/soc/fsl/fsl_asrc.c b/sound/soc/fsl/fsl_asrc.c index b1dadec221fc97..9a24c944a07191 100644 --- a/sound/soc/fsl/fsl_asrc.c +++ b/sound/soc/fsl/fsl_asrc.c @@ -216,6 +216,8 @@ static void fsl_asrc_sel_proc(int inrate, int outrate, * It assigns pair by the order of A->C->B because allocation of pair B, * within range [ANCA, ANCA+ANCB-1], depends on the channels of pair A * while pair A and pair C are comparatively independent. + * + * If @pair already owns a pair, it is kept and only its channels are updated. */ static int fsl_asrc_request_pair(int channels, struct fsl_asrc_pair *pair) { @@ -226,6 +228,19 @@ static int fsl_asrc_request_pair(int channels, struct fsl_asrc_pair *pair) guard(spinlock_irqsave)(&asrc->lock); + if (asrc->pair[pair->index] == pair) { + if (asrc->channel_avail + pair->channels < channels) { + dev_err(dev, "can't afford required channels: %d\n", channels); + return -EINVAL; + } + + asrc->channel_avail += pair->channels; + asrc->channel_avail -= channels; + pair->channels = channels; + + return 0; + } + for (i = ASRC_PAIR_A; i < ASRC_PAIR_MAX_NUM; i++) { if (asrc->pair[i] != NULL) continue; @@ -257,12 +272,19 @@ static int fsl_asrc_request_pair(int channels, struct fsl_asrc_pair *pair) * @pair: pair to release * * It clears the resource from asrc and releases the occupied channels. + * Nothing is done if @pair does not own a pair. */ static void fsl_asrc_release_pair(struct fsl_asrc_pair *pair) { struct fsl_asrc *asrc = pair->asrc; enum asrc_pair_index index = pair->index; + /* Only the owner clears its entry, so it cannot change after this check */ + scoped_guard(spinlock_irqsave, &asrc->lock) { + if (asrc->pair[index] != pair) + return; + } + /* Make sure the pair is disabled */ regmap_update_bits(asrc->regmap, REG_ASRCTR, ASRCTR_ASRCEi_MASK(index), 0); diff --git a/sound/soc/fsl/fsl_asrc_dma.c b/sound/soc/fsl/fsl_asrc_dma.c index 57f131c383758d..6e53f4c5af28ad 100644 --- a/sound/soc/fsl/fsl_asrc_dma.c +++ b/sound/soc/fsl/fsl_asrc_dma.c @@ -123,6 +123,19 @@ static int fsl_asrc_dma_trigger(struct snd_soc_component *component, return 0; } +static void fsl_asrc_dma_release_chans(struct fsl_asrc_pair *pair, u8 dir) +{ + if (pair->dma_chan[!dir]) + dma_release_channel(pair->dma_chan[!dir]); + + /* release dev_to_dev chan if we aren't reusing the Back-End one */ + if (pair->dma_chan[dir] && pair->req_dma_chan) + dma_release_channel(pair->dma_chan[dir]); + + pair->dma_chan[!dir] = NULL; + pair->dma_chan[dir] = NULL; +} + static int fsl_asrc_dma_hw_params(struct snd_soc_component *component, struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params) @@ -189,6 +202,9 @@ static int fsl_asrc_dma_hw_params(struct snd_soc_component *component, dma_params_fe->addr = asrc->paddr + asrc->get_fifo_addr(!dir, index); dma_params_fe->maxburst = dma_params_be->maxburst; + /* hw_params() may be called again without hw_free() in between */ + fsl_asrc_dma_release_chans(pair, dir); + tmp_chan = asrc->get_dma_channel(pair, !dir); if (IS_ERR(tmp_chan)) { dev_err(dev, "failed to request DMA channel\n"); @@ -341,6 +357,7 @@ static int fsl_asrc_dma_hw_params(struct snd_soc_component *component, dev_err(dev, "failed to config DMA channel for Back-End\n"); if (pair->req_dma_chan) dma_release_channel(pair->dma_chan[dir]); + pair->dma_chan[dir] = NULL; return ret; } @@ -355,15 +372,7 @@ static int fsl_asrc_dma_hw_free(struct snd_soc_component *component, struct fsl_asrc_pair *pair = runtime->private_data; u8 dir = tx ? OUT : IN; - if (pair->dma_chan[!dir]) - dma_release_channel(pair->dma_chan[!dir]); - - /* release dev_to_dev chan if we aren't reusing the Back-End one */ - if (pair->dma_chan[dir] && pair->req_dma_chan) - dma_release_channel(pair->dma_chan[dir]); - - pair->dma_chan[!dir] = NULL; - pair->dma_chan[dir] = NULL; + fsl_asrc_dma_release_chans(pair, dir); return 0; } diff --git a/sound/soc/fsl/fsl_asrc_m2m.c b/sound/soc/fsl/fsl_asrc_m2m.c index e78e137fbb574b..809b26d58e0167 100644 --- a/sound/soc/fsl/fsl_asrc_m2m.c +++ b/sound/soc/fsl/fsl_asrc_m2m.c @@ -53,21 +53,27 @@ static void asrc_read_last_fifo(struct fsl_asrc_pair *pair, void *dma_vaddr, u32 { struct fsl_asrc *asrc = pair->asrc; enum asrc_pair_index index = pair->index; - u32 i, reg, size, t_size = 0, width; + u32 i, reg, size, t_size = 0, width, sample_bytes, frame_bytes; u32 *reg32 = NULL; u16 *reg16 = NULL; u8 *reg24 = NULL; width = snd_pcm_format_physical_width(pair->sample_format[OUT]); - if (width == 32) + if (width == 32) { reg32 = dma_vaddr + *length; - else if (width == 16) + sample_bytes = 4; + } else if (width == 16) { reg16 = dma_vaddr + *length; - else + sample_bytes = 2; + } else { reg24 = dma_vaddr + *length; + sample_bytes = 3; + } + + frame_bytes = pair->channels * sample_bytes; retry: size = asrc->get_output_fifo_size(pair); - if (size + *length > ASRC_M2M_BUFFER_SIZE) + if (*length + (t_size + size) * frame_bytes > ASRC_M2M_BUFFER_SIZE) goto end; for (i = 0; i < size * pair->channels; i++) { @@ -89,12 +95,7 @@ static void asrc_read_last_fifo(struct fsl_asrc_pair *pair, void *dma_vaddr, u32 goto retry; end: /* Update payload length */ - if (reg32) - *length += t_size * pair->channels * 4; - else if (reg16) - *length += t_size * pair->channels * 2; - else - *length += t_size * pair->channels * 3; + *length += t_size * frame_bytes; } /* config dma channel */ @@ -468,6 +469,10 @@ static int fsl_asrc_m2m_comp_task_create(struct snd_compr_stream *stream, struct dma_chan *tmp_chan; int ret; + /* All tasks share the pair and DMA channels: one task at a time */ + if (pair->dma_chan[IN]) + return -EBUSY; + exp_info_in.ops = &fsl_asrc_m2m_dma_buf_ops; exp_info_in.size = ASRC_M2M_BUFFER_SIZE; exp_info_in.flags = O_RDWR; @@ -524,6 +529,7 @@ static int fsl_asrc_m2m_comp_task_create(struct snd_compr_stream *stream, err_dma_channel_out: dma_release_channel(pair->dma_chan[IN]); + pair->dma_chan[IN] = NULL; err_dma_channel_in: if (asrc->m2m_unprepare) asrc->m2m_unprepare(pair); @@ -568,6 +574,8 @@ static int fsl_asrc_m2m_comp_task_free(struct snd_compr_stream *stream, dma_release_channel(pair->dma_chan[IN]); if (pair->dma_chan[OUT]) dma_release_channel(pair->dma_chan[OUT]); + pair->dma_chan[IN] = NULL; + pair->dma_chan[OUT] = NULL; return 0; } diff --git a/sound/soc/fsl/fsl_aud2htx.h b/sound/soc/fsl/fsl_aud2htx.h index cf292e3ccc0209..51e48ae603c767 100644 --- a/sound/soc/fsl/fsl_aud2htx.h +++ b/sound/soc/fsl/fsl_aud2htx.h @@ -48,7 +48,7 @@ #define AUD2HTX_MAXBURST 0x10 /** - * fsl_aud2htx: AUD2HTX private data + * struct fsl_aud2htx: AUD2HTX private data * * @pdev: platform device pointer * @regmap: regmap handler diff --git a/sound/soc/fsl/fsl_easrc.c b/sound/soc/fsl/fsl_easrc.c index 5c5002537951ee..b7a429170794fe 100644 --- a/sound/soc/fsl/fsl_easrc.c +++ b/sound/soc/fsl/fsl_easrc.c @@ -1347,6 +1347,10 @@ static void fsl_easrc_release_context(struct fsl_asrc_pair *ctx) guard(spinlock_irqsave)(&easrc->lock); + /* Nothing to release if the context is not owned by @ctx */ + if (easrc->pair[ctx->index] != ctx) + return; + fsl_easrc_release_slot(easrc, ctx->index); easrc->channel_avail += ctx->channels; @@ -1500,6 +1504,12 @@ static int fsl_easrc_hw_params(struct snd_pcm_substream *substream, snd_pcm_format_t format = params_format(params); int ret; + /* hw_params() may be called again without hw_free() in between */ + if (ctx_priv->ctx_streams & BIT(substream->stream)) { + ctx_priv->ctx_streams &= ~BIT(substream->stream); + fsl_easrc_release_context(ctx); + } + ret = fsl_easrc_request_context(channels, ctx); if (ret) { dev_err(dev, "failed to request context\n"); diff --git a/sound/soc/fsl/fsl_mqs.c b/sound/soc/fsl/fsl_mqs.c index fd4a5f4a56bed8..b171120952aad0 100644 --- a/sound/soc/fsl/fsl_mqs.c +++ b/sound/soc/fsl/fsl_mqs.c @@ -87,7 +87,7 @@ static int fsl_mqs_sm_read(void *context, unsigned int reg, unsigned int *val) return scmi_imx_misc_ctrl_get(mqs_priv->soc->sm_index, &num, val); return -EINVAL; -}; +} static int fsl_mqs_sm_write(void *context, unsigned int reg, unsigned int val) { @@ -98,7 +98,7 @@ static int fsl_mqs_sm_write(void *context, unsigned int reg, unsigned int val) return scmi_imx_misc_ctrl_set(mqs_priv->soc->sm_index, val); return -EINVAL; -}; +} static int fsl_mqs_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, @@ -312,9 +312,14 @@ static int fsl_mqs_probe(struct platform_device *pdev) ret = devm_snd_soc_register_component(&pdev->dev, &soc_codec_fsl_mqs, &fsl_mqs_dai, 1); if (ret) - return ret; + goto err_pm_disable; return 0; + +err_pm_disable: + pm_runtime_disable(&pdev->dev); + + return ret; } static void fsl_mqs_remove(struct platform_device *pdev) diff --git a/sound/soc/fsl/imx-audmix.c b/sound/soc/fsl/imx-audmix.c index 2372cd26ee4716..8d7faa1b9cc310 100644 --- a/sound/soc/fsl/imx-audmix.c +++ b/sound/soc/fsl/imx-audmix.c @@ -10,6 +10,7 @@ * https://www.gnu.org/copyleft/gpl.html */ +#include #include #include #include @@ -123,6 +124,11 @@ static const char *name[][3] = { {"SAI-Playback", "SAI-Playback", "AUDMIX-Capture-0"}, }; +static void imx_audmix_put_node(void *data) +{ + of_node_put(data); +} + static int imx_audmix_probe(struct platform_device *pdev) { struct device_node *np = pdev->dev.of_node; @@ -206,6 +212,11 @@ static int imx_audmix_probe(struct platform_device *pdev) return ret; } + ret = devm_add_action_or_reset(&pdev->dev, imx_audmix_put_node, + args.np); + if (ret) + return ret; + cpu_pdev = of_find_device_by_node(args.np); if (!cpu_pdev) { dev_err(&pdev->dev, "failed to find SAI platform device\n"); diff --git a/sound/soc/fsl/imx-pcm-rpmsg.h b/sound/soc/fsl/imx-pcm-rpmsg.h index 8286b55f00ae95..52f2529724f62b 100644 --- a/sound/soc/fsl/imx-pcm-rpmsg.h +++ b/sound/soc/fsl/imx-pcm-rpmsg.h @@ -397,7 +397,7 @@ struct param_s { } __packed; /** - * struct param_s: send rpmsg parameter + * struct param_r: send rpmsg parameter * * @audioindex: audio instance index * @resp: response value diff --git a/sound/soc/intel/atom/sst-mfld-platform-pcm.c b/sound/soc/intel/atom/sst-mfld-platform-pcm.c index 8c0e4c1d0c0c13..bbd43d1b5bfa32 100644 --- a/sound/soc/intel/atom/sst-mfld-platform-pcm.c +++ b/sound/soc/intel/atom/sst-mfld-platform-pcm.c @@ -37,7 +37,6 @@ int sst_register_dsp(struct sst_device *dev) if (sst) { dev_err(dev->dev, "we already have a device %s\n", sst->name); module_put(dev->dev->driver->owner); - mutex_unlock(&sst_lock); return -EEXIST; } dev_dbg(dev->dev, "registering device %s\n", dev->name); diff --git a/sound/soc/intel/atom/sst/sst.h b/sound/soc/intel/atom/sst/sst.h index 4c759ba377ae18..42baeb7df02d21 100644 --- a/sound/soc/intel/atom/sst/sst.h +++ b/sound/soc/intel/atom/sst/sst.h @@ -487,7 +487,7 @@ int get_stream_id_mrfld(struct intel_sst_drv *sst_drv_ctx, u32 relocate_imr_addr_mrfld(u32 base_addr); void sst_add_to_dispatch_list_and_post(struct intel_sst_drv *sst, struct ipc_post *msg); -int sst_pm_runtime_put(struct intel_sst_drv *sst_drv); +void sst_pm_runtime_put(struct intel_sst_drv *sst_drv); int sst_shim_write(void __iomem *addr, int offset, int value); u32 sst_shim_read(void __iomem *addr, int offset); u64 sst_reg_read64(void __iomem *addr, int offset); diff --git a/sound/soc/intel/atom/sst/sst_drv_interface.c b/sound/soc/intel/atom/sst/sst_drv_interface.c index 2646c4632ca1ca..c99697b975d836 100644 --- a/sound/soc/intel/atom/sst/sst_drv_interface.c +++ b/sound/soc/intel/atom/sst/sst_drv_interface.c @@ -135,13 +135,13 @@ static int sst_power_control(struct device *dev, bool state) if (ret) { dev_err(dev, "FW download fail %d\n", ret); sst_set_fw_state_locked(ctx, SST_RESET); - ret = sst_pm_runtime_put(ctx); + sst_pm_runtime_put(ctx); } } } else { usage_count = GET_USAGE_COUNT(dev); dev_dbg(ctx->dev, "Disable: pm usage count: %d\n", usage_count); - return sst_pm_runtime_put(ctx); + sst_pm_runtime_put(ctx); } return ret; } diff --git a/sound/soc/intel/atom/sst/sst_pvt.c b/sound/soc/intel/atom/sst/sst_pvt.c index 0b0cfd70efbc26..913e232bf6ed98 100644 --- a/sound/soc/intel/atom/sst/sst_pvt.c +++ b/sound/soc/intel/atom/sst/sst_pvt.c @@ -255,14 +255,9 @@ int sst_prepare_and_post_msg(struct intel_sst_drv *sst, return ret; } -int sst_pm_runtime_put(struct intel_sst_drv *sst_drv) +void sst_pm_runtime_put(struct intel_sst_drv *sst_drv) { - int ret; - - ret = pm_runtime_put_autosuspend(sst_drv->dev); - if (ret < 0) - return ret; - return 0; + pm_runtime_put_autosuspend(sst_drv->dev); } void sst_fill_header_mrfld(union ipc_header_mrfld *header, diff --git a/sound/soc/intel/boards/skl_hda_dsp_generic.c b/sound/soc/intel/boards/skl_hda_dsp_generic.c index faa7d1cf7b9726..3c86bb6546dca6 100644 --- a/sound/soc/intel/boards/skl_hda_dsp_generic.c +++ b/sound/soc/intel/boards/skl_hda_dsp_generic.c @@ -53,7 +53,7 @@ static void skl_set_hda_codec_autosuspend_delay(struct snd_soc_card *card) #define DMIC01_BE_ID 6 #define DMIC16K_BE_ID 7 #define BT_OFFLOAD_BE_ID 8 -#define HDMI_IN_BE_ID 13 +#define HDMI_IN_BE_ID 13 #define HDA_LINK_ORDER SOF_LINK_ORDER(SOF_LINK_IDISP_HDMI, \ SOF_LINK_HDA, \ diff --git a/sound/soc/intel/keembay/kmb_platform.c b/sound/soc/intel/keembay/kmb_platform.c index 1ca8ef95d41e71..2a8cc47ae3b310 100644 --- a/sound/soc/intel/keembay/kmb_platform.c +++ b/sound/soc/intel/keembay/kmb_platform.c @@ -888,8 +888,8 @@ static int kmb_plat_dai_probe(struct platform_device *pdev) } else { kmb_i2s->play_dma_data.addr = res->start + I2S_TXDMA; kmb_i2s->capture_dma_data.addr = res->start + I2S_RXDMA; - ret = snd_dmaengine_pcm_register(&pdev->dev, - NULL, 0); + ret = devm_snd_dmaengine_pcm_register(&pdev->dev, + NULL, 0); if (ret) { dev_err(&pdev->dev, "could not register dmaengine: %d\n", ret); diff --git a/sound/soc/kirkwood/armada-370-db.c b/sound/soc/kirkwood/armada-370-db.c index 77a5f440364e43..a60aa78d316e0b 100644 --- a/sound/soc/kirkwood/armada-370-db.c +++ b/sound/soc/kirkwood/armada-370-db.c @@ -102,9 +102,15 @@ static struct snd_soc_card a370db = { .num_dapm_routes = ARRAY_SIZE(a370db_route), }; +static void a370db_of_node_put(void *np) +{ + of_node_put(np); +} + static int a370db_probe(struct platform_device *pdev) { struct snd_soc_card *card = &a370db; + int ret; card->dev = &pdev->dev; @@ -112,10 +118,22 @@ static int a370db_probe(struct platform_device *pdev) of_parse_phandle(pdev->dev.of_node, "marvell,audio-controller", 0); a370db_dai[0].platforms->of_node = a370db_dai[0].cpus->of_node; + if (a370db_dai[0].cpus->of_node) { + ret = devm_add_action_or_reset(&pdev->dev, a370db_of_node_put, + a370db_dai[0].cpus->of_node); + if (ret) + return ret; + } a370db_dai[0].codecs->of_node = of_parse_phandle(pdev->dev.of_node, "marvell,audio-codec", 0); + if (a370db_dai[0].codecs->of_node) { + ret = devm_add_action_or_reset(&pdev->dev, a370db_of_node_put, + a370db_dai[0].codecs->of_node); + if (ret) + return ret; + } a370db_dai[1].cpus->of_node = a370db_dai[0].cpus->of_node; a370db_dai[1].platforms->of_node = a370db_dai[0].cpus->of_node; @@ -123,6 +141,12 @@ static int a370db_probe(struct platform_device *pdev) a370db_dai[1].codecs->of_node = of_parse_phandle(pdev->dev.of_node, "marvell,audio-codec", 1); + if (a370db_dai[1].codecs->of_node) { + ret = devm_add_action_or_reset(&pdev->dev, a370db_of_node_put, + a370db_dai[1].codecs->of_node); + if (ret) + return ret; + } a370db_dai[2].cpus->of_node = a370db_dai[0].cpus->of_node; a370db_dai[2].platforms->of_node = a370db_dai[0].cpus->of_node; @@ -130,6 +154,12 @@ static int a370db_probe(struct platform_device *pdev) a370db_dai[2].codecs->of_node = of_parse_phandle(pdev->dev.of_node, "marvell,audio-codec", 2); + if (a370db_dai[2].codecs->of_node) { + ret = devm_add_action_or_reset(&pdev->dev, a370db_of_node_put, + a370db_dai[2].codecs->of_node); + if (ret) + return ret; + } return devm_snd_soc_register_card(card->dev, card); } diff --git a/sound/soc/loongson/loongson_card.c b/sound/soc/loongson/loongson_card.c index b06b596047b88f..b4dc3cd6e4d65c 100644 --- a/sound/soc/loongson/loongson_card.c +++ b/sound/soc/loongson/loongson_card.c @@ -152,7 +152,7 @@ static int loongson_card_hw_params(struct snd_pcm_substream *substream, return ret; } - return snd_soc_runtime_set_dai_fmt(rtd, ls_card->cfg->fmt); + return 0; } static const struct snd_soc_ops loongson_ops = { @@ -312,6 +312,16 @@ static int loongson_asoc_card_probe(struct platform_device *pdev) card->dai_link = loongson_dai_links; card->num_links = ARRAY_SIZE(loongson_dai_links); + /* + * The DAI format is fixed per board. Describe it in the DAI link so + * that the ASoC core takes it into account when it auto-selects the + * format from the DAIs' .auto_selectable_formats. Otherwise the + * CLOCK_PROVIDER bits are lost and the codec is configured with a + * format it cannot accept (e.g. es8328_set_dai_fmt() rejecting it). + */ + for (unsigned int i = 0; i < card->num_links; i++) + loongson_dai_links[i].dai_fmt = ls_priv->cfg->fmt; + if (ls_priv->cfg->add_dapm_widgets) { card->dapm_widgets = loongson_asoc_dapm_widgets; card->num_dapm_widgets = ARRAY_SIZE(loongson_asoc_dapm_widgets); diff --git a/sound/soc/loongson/loongson_i2s.c b/sound/soc/loongson/loongson_i2s.c index 438bbae0888f81..76741ec139fe76 100644 --- a/sound/soc/loongson/loongson_i2s.c +++ b/sound/soc/loongson/loongson_i2s.c @@ -73,6 +73,11 @@ static int loongson_i2s_hw_params(struct snd_pcm_substream *substream, u32 mask; u32 val = 0; + if (!sysclk) { + dev_err(i2s->dev, "invalid sysclk\n"); + return -EINVAL; + } + switch (i2s->rev_id) { case 0: bclk_ratio = DIV_ROUND_CLOSEST(clk_rate, diff --git a/sound/soc/mediatek/an7581/an7581-afe-pcm.c b/sound/soc/mediatek/an7581/an7581-afe-pcm.c index 1b12655ab42aa9..21655b0fe29b87 100644 --- a/sound/soc/mediatek/an7581/an7581-afe-pcm.c +++ b/sound/soc/mediatek/an7581/an7581-afe-pcm.c @@ -444,7 +444,7 @@ static int an7581_afe_pcm_dev_probe(struct platform_device *pdev) return irq_id; /* init memif */ - for (i = 0; i < afe->memif_size; i++) { + for (i = 0; i < AN7581_MEMIF_NUM; i++) { int sel_irq = an7581_memif_irq_descs[i].irq; afe->memif[i].data = &memif_data[i]; diff --git a/sound/soc/mediatek/mt8189/mt8189-afe-pcm.c b/sound/soc/mediatek/mt8189/mt8189-afe-pcm.c index 5386a50d20641f..8f2acbaa04e0fe 100644 --- a/sound/soc/mediatek/mt8189/mt8189-afe-pcm.c +++ b/sound/soc/mediatek/mt8189/mt8189-afe-pcm.c @@ -2558,6 +2558,7 @@ static int mt8189_afe_pcm_dev_probe(struct platform_device *pdev) &mt8189_afe_regmap_config); if (IS_ERR(afe->regmap)) { ret = PTR_ERR(afe->regmap); + afe->regmap = NULL; goto err_pm_put; } diff --git a/sound/soc/mediatek/mt8196/mt8196-afe-pcm.c b/sound/soc/mediatek/mt8196/mt8196-afe-pcm.c index d0fe5d5f648d62..b0ac6cdb1613c5 100644 --- a/sound/soc/mediatek/mt8196/mt8196-afe-pcm.c +++ b/sound/soc/mediatek/mt8196/mt8196-afe-pcm.c @@ -2445,6 +2445,7 @@ static int mt8196_afe_pcm_dev_probe(struct platform_device *pdev) &mt8196_afe_regmap_config); if (IS_ERR(afe->regmap)) { ret = PTR_ERR(afe->regmap); + afe->regmap = NULL; goto err_pm_put; } diff --git a/sound/soc/meson/g12a-toacodec.c b/sound/soc/meson/g12a-toacodec.c index b3d74419e56ecb..ecee099ac8bf18 100644 --- a/sound/soc/meson/g12a-toacodec.c +++ b/sound/soc/meson/g12a-toacodec.c @@ -40,6 +40,10 @@ #define CTRL0_BCLK_SEL_MSB 5 #define CTRL0_BCLK_SEL_LSB 4 #define CTRL0_MCLK_SEL GENMASK(2, 0) +#define CTRL0_BCLK_ENABLE_SHIFT_S4 30 +#define CTRL0_MCLK_ENABLE_SHIFT_S4 29 +#define CTRL0_DAT_SEL_S4_MSB 20 +#define CTRL0_DAT_SEL_S4_LSB 19 #define TOACODEC_OUT_CHMAX 2 @@ -123,6 +127,19 @@ static const struct snd_kcontrol_new sm1_toacodec_mux = snd_soc_dapm_get_enum_double, g12a_toacodec_mux_put_enum); +/* + * The S4 lane selector is one bit wider than the SM1 one, which pushes the + * data selector up by one bit as well. + */ +static SOC_ENUM_SINGLE_DECL(s4_toacodec_mux_enum, TOACODEC_CTRL0, + CTRL0_DAT_SEL_S4_LSB, + g12a_toacodec_mux_texts); + +static const struct snd_kcontrol_new s4_toacodec_mux = + SOC_DAPM_ENUM_EXT("Source", s4_toacodec_mux_enum, + snd_soc_dapm_get_enum_double, + g12a_toacodec_mux_put_enum); + static const struct snd_kcontrol_new g12a_toacodec_out_enable = SOC_DAPM_SINGLE_AUTODISABLE("Switch", TOACODEC_CTRL0, CTRL0_ENABLE_SHIFT, 1, 0); @@ -141,6 +158,17 @@ static const struct snd_soc_dapm_widget sm1_toacodec_widgets[] = { &g12a_toacodec_out_enable), }; +static const struct snd_soc_dapm_widget s4_toacodec_widgets[] = { + SND_SOC_DAPM_MUX("SRC", SND_SOC_NOPM, 0, 0, + &s4_toacodec_mux), + SND_SOC_DAPM_SWITCH("OUT EN", SND_SOC_NOPM, 0, 0, + &g12a_toacodec_out_enable), + SND_SOC_DAPM_SUPPLY("I2S BCLK EN", TOACODEC_CTRL0, + CTRL0_BCLK_ENABLE_SHIFT_S4, 0, NULL, 0), + SND_SOC_DAPM_SUPPLY("I2S MCLK EN", TOACODEC_CTRL0, + CTRL0_MCLK_ENABLE_SHIFT_S4, 0, NULL, 0), +}; + static int g12a_toacodec_input_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *dai) @@ -226,6 +254,16 @@ static const struct snd_soc_dapm_route g12a_toacodec_routes[] = { { "OUT Capture", NULL, "OUT EN" }, }; +static const struct snd_soc_dapm_route s4_toacodec_routes[] = { + { "SRC", "I2S A", "IN A Playback" }, + { "SRC", "I2S B", "IN B Playback" }, + { "SRC", "I2S C", "IN C Playback" }, + { "OUT EN", "Switch", "SRC" }, + { "OUT Capture", NULL, "OUT EN" }, + { "OUT EN", NULL, "I2S BCLK EN" }, + { "OUT EN", NULL, "I2S MCLK EN" }, +}; + static const struct snd_kcontrol_new g12a_toacodec_controls[] = { SOC_SINGLE("Lane Select", TOACODEC_CTRL0, CTRL0_LANE_SEL, 3, 0), }; @@ -234,6 +272,10 @@ static const struct snd_kcontrol_new sm1_toacodec_controls[] = { SOC_SINGLE("Lane Select", TOACODEC_CTRL0, CTRL0_LANE_SEL_SM1, 3, 0), }; +static const struct snd_kcontrol_new s4_toacodec_controls[] = { + SOC_SINGLE("Lane Select", TOACODEC_CTRL0, CTRL0_LANE_SEL_SM1, 7, 0), +}; + static const struct snd_soc_component_driver g12a_toacodec_component_drv = { .probe = g12a_toacodec_component_probe, .controls = g12a_toacodec_controls, @@ -256,6 +298,17 @@ static const struct snd_soc_component_driver sm1_toacodec_component_drv = { .endianness = 1, }; +static const struct snd_soc_component_driver s4_toacodec_component_drv = { + .probe = sm1_toacodec_component_probe, + .controls = s4_toacodec_controls, + .num_controls = ARRAY_SIZE(s4_toacodec_controls), + .dapm_widgets = s4_toacodec_widgets, + .num_dapm_widgets = ARRAY_SIZE(s4_toacodec_widgets), + .dapm_routes = s4_toacodec_routes, + .num_dapm_routes = ARRAY_SIZE(s4_toacodec_routes), + .endianness = 1, +}; + static const struct regmap_config g12a_toacodec_regmap_cfg = { .reg_bits = 32, .val_bits = 32, @@ -276,6 +329,13 @@ static const struct g12a_toacodec_match_data sm1_toacodec_match_data = { .field_bclk_sel = REG_FIELD(TOACODEC_CTRL0, 4, 6), }; +static const struct g12a_toacodec_match_data s4_toacodec_match_data = { + .component_drv = &s4_toacodec_component_drv, + .field_dat_sel = REG_FIELD(TOACODEC_CTRL0, 19, 20), + .field_lrclk_sel = REG_FIELD(TOACODEC_CTRL0, 12, 14), + .field_bclk_sel = REG_FIELD(TOACODEC_CTRL0, 4, 6), +}; + static const struct of_device_id g12a_toacodec_of_match[] = { { .compatible = "amlogic,g12a-toacodec", @@ -285,6 +345,10 @@ static const struct of_device_id g12a_toacodec_of_match[] = { .compatible = "amlogic,sm1-toacodec", .data = &sm1_toacodec_match_data, }, + { + .compatible = "amlogic,s4-toacodec", + .data = &s4_toacodec_match_data, + }, {} }; MODULE_DEVICE_TABLE(of, g12a_toacodec_of_match); diff --git a/sound/soc/qcom/common.c b/sound/soc/qcom/common.c index af5cacddf67dff..77845d43c21943 100644 --- a/sound/soc/qcom/common.c +++ b/sound/soc/qcom/common.c @@ -426,6 +426,7 @@ int qcom_snd_wcd_jack_setup(struct snd_soc_pcm_runtime *rtd, case TX_CODEC_DMA_TX_1: case TX_CODEC_DMA_TX_2: case TX_CODEC_DMA_TX_3: + case VA_CODEC_DMA_TX_1: for_each_rtd_codec_dais(rtd, i, codec_dai) { rval = snd_soc_component_set_jack(codec_dai->component, jack, NULL); diff --git a/sound/soc/qcom/lpass-platform.c b/sound/soc/qcom/lpass-platform.c index dad4becf7579e0..594cdd21c3d399 100644 --- a/sound/soc/qcom/lpass-platform.c +++ b/sound/soc/qcom/lpass-platform.c @@ -963,8 +963,9 @@ static irqreturn_t lpass_dma_interrupt_handler( val = 0; break; default: - dev_err(soc_runtime->dev, "%s: invalid %d interface\n", __func__, dai_id); - return -EINVAL; + dev_err(soc_runtime->dev, "%s: invalid %d interface\n", + __func__, dai_id); + return IRQ_NONE; } if (interrupts & LPAIF_IRQ_PER(chan)) { rv = regmap_write_bits(map, reg, mask, (LPAIF_IRQ_PER(chan) | val)); @@ -1281,7 +1282,7 @@ int asoc_qcom_lpass_platform_register(struct platform_device *pdev) drvdata->lpaif_irq = platform_get_irq_byname(pdev, "lpass-irq-lpaif"); if (drvdata->lpaif_irq < 0) - return -ENODEV; + return drvdata->lpaif_irq; /* ensure audio hardware is disabled */ ret = regmap_write(drvdata->lpaif_map, @@ -1322,7 +1323,7 @@ int asoc_qcom_lpass_platform_register(struct platform_device *pdev) } drvdata->rxtxif_irq = platform_get_irq_byname(pdev, "lpass-irq-rxtxif"); if (drvdata->rxtxif_irq < 0) - return -ENODEV; + return drvdata->rxtxif_irq; ret = devm_request_irq(&pdev->dev, drvdata->rxtxif_irq, lpass_platform_rxtxif_irq, 0, "lpass-irq-rxtxif", drvdata); @@ -1341,7 +1342,7 @@ int asoc_qcom_lpass_platform_register(struct platform_device *pdev) drvdata->vaif_irq = platform_get_irq_byname(pdev, "lpass-irq-vaif"); if (drvdata->vaif_irq < 0) - return -ENODEV; + return drvdata->vaif_irq; ret = devm_request_irq(&pdev->dev, drvdata->vaif_irq, lpass_platform_vaif_irq, 0, "lpass-irq-vaif", drvdata); @@ -1362,7 +1363,7 @@ int asoc_qcom_lpass_platform_register(struct platform_device *pdev) if (drvdata->hdmi_port_enable) { drvdata->hdmiif_irq = platform_get_irq_byname(pdev, "lpass-irq-hdmi"); if (drvdata->hdmiif_irq < 0) - return -ENODEV; + return drvdata->hdmiif_irq; ret = devm_request_irq(&pdev->dev, drvdata->hdmiif_irq, lpass_platform_hdmiif_irq, 0, "lpass-irq-hdmi", drvdata); diff --git a/sound/soc/qcom/qdsp6/audioreach.c b/sound/soc/qcom/qdsp6/audioreach.c index aa1f4e29676474..5b5289bf6d1393 100644 --- a/sound/soc/qcom/qdsp6/audioreach.c +++ b/sound/soc/qcom/qdsp6/audioreach.c @@ -306,22 +306,6 @@ void *audioreach_alloc_apm_cmd_pkt(int pkt_size, uint32_t opcode, uint32_t token } EXPORT_SYMBOL_GPL(audioreach_alloc_apm_cmd_pkt); -void audioreach_set_default_channel_mapping(u8 *ch_map, int num_channels) -{ - if (num_channels == 1) { - ch_map[0] = PCM_CHANNEL_FL; - } else if (num_channels == 2) { - ch_map[0] = PCM_CHANNEL_FL; - ch_map[1] = PCM_CHANNEL_FR; - } else if (num_channels == 4) { - ch_map[0] = PCM_CHANNEL_FL; - ch_map[1] = PCM_CHANNEL_FR; - ch_map[2] = PCM_CHANNEL_LS; - ch_map[3] = PCM_CHANNEL_RS; - } -} -EXPORT_SYMBOL_GPL(audioreach_set_default_channel_mapping); - static void apm_populate_container_config(struct apm_container_obj *cfg, const struct audioreach_container *cont) { @@ -760,7 +744,7 @@ static int audioreach_codec_dma_set_media_format(struct q6apm_graph *graph, intf_cfg->cfg.intf_index = module->hw_interface_idx; intf_cfg->cfg.active_channels_mask = 0; /* Convert the physical channel mapping into a bit field */ - for (i = 0; i < AR_PCM_MAX_NUM_CHANNEL; i++) + for (i = 0; i < PCM_MAX_NUM_CHANNEL; i++) if (cfg->channel_map[i]) intf_cfg->cfg.active_channels_mask |= BIT(i); @@ -883,7 +867,7 @@ static int audioreach_mfc_set_media_format(struct q6apm_graph *graph, media_format->bit_width = cfg->bit_width; media_format->num_channels = cfg->num_channels; /* Convert the physical mapping to a logical mapping of the channels */ - for (i = 0, j = 0; i < AR_PCM_MAX_NUM_CHANNEL && j < cfg->num_channels; i++) { + for (i = 0, j = 0; i < PCM_MAX_NUM_CHANNEL && j < cfg->num_channels; i++) { if (!cfg->channel_map[i]) continue; media_format->channel_mapping[j++] = cfg->channel_map[i]; @@ -1185,11 +1169,6 @@ static int audioreach_pcm_set_media_format(struct q6apm_graph *graph, int payload_size; int i, j; - if (num_channels > 4) { - dev_err(graph->dev, "Error: Invalid channels (%d)!\n", num_channels); - return -EINVAL; - } - payload_size = APM_PCM_MODULE_FMT_CMD_PSIZE(num_channels); struct gpr_pkt *pkt __free(kfree) = @@ -1223,7 +1202,7 @@ static int audioreach_pcm_set_media_format(struct q6apm_graph *graph, */ media_cfg->bits_per_sample = mcfg->bit_width == 24 ? 32 : mcfg->bit_width; /* Convert the physical mapping to a logical mapping of the channels */ - for (i = 0, j = 0; i < AR_PCM_MAX_NUM_CHANNEL && j < mcfg->num_channels; i++) { + for (i = 0, j = 0; i < PCM_MAX_NUM_CHANNEL && j < mcfg->num_channels; i++) { if (!mcfg->channel_map[i]) continue; media_cfg->channel_mapping[j++] = mcfg->channel_map[i]; @@ -1280,11 +1259,6 @@ static int audioreach_shmem_set_media_format(struct q6apm_graph *graph, int i, j; void *p; - if (num_channels > 4) { - dev_err(graph->dev, "Error: Invalid channels (%d)!\n", num_channels); - return -EINVAL; - } - payload_size = APM_SHMEM_FMT_CFG_PSIZE(num_channels) + APM_MODULE_PARAM_DATA_SIZE; struct gpr_pkt *pkt __free(kfree) = @@ -1319,7 +1293,7 @@ static int audioreach_shmem_set_media_format(struct q6apm_graph *graph, cfg->endianness = PCM_LITTLE_ENDIAN; cfg->num_channels = mcfg->num_channels; /* Convert the physical mapping to a logical mapping of the channels */ - for (i = 0, j = 0; i < AR_PCM_MAX_NUM_CHANNEL && j < cfg->num_channels; i++) { + for (i = 0, j = 0; i < PCM_MAX_NUM_CHANNEL && j < cfg->num_channels; i++) { if (!mcfg->channel_map[i]) continue; cfg->channel_mapping[j++] = mcfg->channel_map[i]; @@ -1442,7 +1416,7 @@ static int audioreach_speaker_protection_vi(struct q6apm_graph *graph, cm_cfg->cfg.num_channels = num_channels * 2; /* Convert the physical mapping to a logical mapping of the channels */ - for (i = 0, j = 0; i < AR_PCM_MAX_NUM_CHANNEL && j < num_channels; i++) { + for (i = 0, j = 0; i < PCM_MAX_NUM_CHANNEL && j < num_channels; i++) { if (!mcfg->channel_map[i]) continue; /* diff --git a/sound/soc/qcom/qdsp6/audioreach.h b/sound/soc/qcom/qdsp6/audioreach.h index 0a50b933773826..542775f493f108 100644 --- a/sound/soc/qcom/qdsp6/audioreach.h +++ b/sound/soc/qcom/qdsp6/audioreach.h @@ -6,6 +6,7 @@ #include #include #include +#include "q6dsp-common.h" struct q6apm; struct q6apm_graph; @@ -805,7 +806,6 @@ struct param_id_hw_ep_power_mode_cfg { #define PARAM_ID_HW_EP_DMA_DATA_ALIGN 0x08001233 #define AR_HW_EP_DMA_DATA_ALIGN_MSB 0 #define AR_HW_EP_DMA_DATA_ALIGN_LSB 1 -#define AR_PCM_MAX_NUM_CHANNEL 8 struct param_id_hw_ep_dma_data_align { uint32_t dma_data_align; @@ -998,7 +998,7 @@ struct audioreach_module_config { u16 nslots_per_frame; u16 slot_width; struct snd_codec codec; - u8 channel_map[AR_PCM_MAX_NUM_CHANNEL]; + u8 channel_map[PCM_MAX_NUM_CHANNEL]; }; /* Packet Allocation routines */ @@ -1009,7 +1009,6 @@ static inline u16 audioreach_gpr_dest_domain(gpr_device_t *gdev) void *audioreach_alloc_apm_cmd_pkt(int pkt_size, uint32_t opcode, uint32_t token); -void audioreach_set_default_channel_mapping(u8 *ch_map, int num_channels); void *audioreach_alloc_cmd_pkt(int payload_size, uint32_t opcode, uint32_t token, uint32_t src_port, uint32_t dest_port); diff --git a/sound/soc/qcom/qdsp6/q6apm-dai.c b/sound/soc/qcom/qdsp6/q6apm-dai.c index afa4bb095e09fc..3d667d7c612e26 100644 --- a/sound/soc/qcom/qdsp6/q6apm-dai.c +++ b/sound/soc/qcom/qdsp6/q6apm-dai.c @@ -21,6 +21,7 @@ #include #include #include "q6apm.h" +#include "q6dsp-common.h" #define DRV_NAME "q6apm-dai" #define POS_BUFFER_BYTES 4096 @@ -91,6 +92,8 @@ struct q6apm_dai_rtd { uint64_t copied_total; uint16_t bits_per_sample; snd_pcm_uframes_t queue_ptr; + unsigned int in_flight; + struct device *dev; bool next_track; enum stream_state state; struct q6apm_graph *graph; @@ -236,6 +239,8 @@ static const struct snd_pcm_hardware q6apm_dai_hardware_playback = { .fifo_size = 0, }; +static int q6apm_dai_queue_playback(struct snd_pcm_substream *substream); + static void event_handler(uint32_t opcode, uint32_t token, void *payload, void *priv) { struct q6apm_dai_rtd *prtd = priv; @@ -249,7 +254,13 @@ static void event_handler(uint32_t opcode, uint32_t token, void *payload, void * prtd->state = Q6APM_STREAM_STOPPED; break; case APM_CLIENT_EVENT_DATA_WRITE_DONE: - snd_pcm_period_elapsed(substream); + scoped_guard(pcm_stream_lock_irqsave, substream) { + if (prtd->in_flight) + prtd->in_flight--; + snd_pcm_period_elapsed_under_stream_lock(substream); + /* The returned buffer may be needed for data already written. */ + q6apm_dai_queue_playback(substream); + } break; case APM_CLIENT_EVENT_DATA_READ_DONE: @@ -344,7 +355,21 @@ static int q6apm_dai_prepare(struct snd_soc_component *component, cfg.num_channels = runtime->channels; cfg.bit_width = prtd->bits_per_sample; cfg.fmt = SND_AUDIOCODEC_PCM; - audioreach_set_default_channel_mapping(cfg.channel_map, runtime->channels); + ret = q6dsp_map_channels(cfg.channel_map, runtime->channels); + if (ret) + return ret; + + /* + * A second prepare finds the stream running. Stop .ack from queueing + * while the graph and its buffers are replaced. + */ + snd_pcm_stream_lock_irq(substream); + if (prtd->state == Q6APM_STREAM_RUNNING) + prtd->state = Q6APM_STREAM_STOPPED; + /* ALSA sets appl_ptr to 0 after a successful prepare */ + prtd->queue_ptr = 0; + snd_pcm_stream_unlock_irq(substream); + if (prtd->state) { /* clear the previous setup if any */ q6apm_graph_stop(prtd->graph); @@ -352,6 +377,10 @@ static int q6apm_dai_prepare(struct snd_soc_component *component, } prtd->last_pos_index = 0; + /* The graph gets a new set of buffers and starts with none queued. */ + snd_pcm_stream_lock_irq(substream); + prtd->in_flight = 0; + snd_pcm_stream_unlock_irq(substream); prtd->pcm_count = snd_pcm_lib_period_bytes(substream); if (q6apm_is_graph_in_push_pull_mode(prtd->graph)) { if (prtd->pcm_size != prtd->push_pull_size) { @@ -415,33 +444,144 @@ static int q6apm_dai_prepare(struct snd_soc_component *component, } /* Now that graph as been prepared and started update the internal state accordingly */ + snd_pcm_stream_lock_irq(substream); prtd->state = Q6APM_STREAM_RUNNING; + snd_pcm_stream_unlock_irq(substream); return 0; } -static int q6apm_dai_ack(struct snd_soc_component *component, struct snd_pcm_substream *substream) +/* + * Give queue_ptr its ring offset back relative to hw_ptr. Called with the + * stream lock held after hw_ptr moved without it. + */ +static void q6apm_dai_align_queue(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime = substream->runtime; struct q6apm_dai_rtd *prtd = runtime->private_data; - int i, ret = 0, avail_periods; + snd_pcm_uframes_t hw_ptr = runtime->status->hw_ptr; + snd_pcm_uframes_t ahead; - if (q6apm_is_graph_in_push_pull_mode(prtd->graph)) + ahead = (prtd->queue_ptr % runtime->buffer_size + runtime->buffer_size - + hw_ptr % runtime->buffer_size) % runtime->buffer_size; + /* + * The offset is 0 both for an empty and for a full queue. A running + * stream with every buffer queued continues with the buffers the DSP + * holds. A paused stream can have them played before its hw_ptr moves + * again, so a stream that is not running queues what is written from + * here on. + */ + if (!ahead && snd_pcm_running(substream) && prtd->in_flight == runtime->periods) + ahead = runtime->buffer_size; + + prtd->queue_ptr = (hw_ptr + ahead) % runtime->boundary; +} + +/* Queue the periods written and not yet queued. Called with the stream lock held. */ +static int q6apm_dai_queue_playback(struct snd_pcm_substream *substream) +{ + struct snd_pcm_runtime *runtime = substream->runtime; + struct q6apm_dai_rtd *prtd = runtime->private_data; + snd_pcm_sframes_t ahead, pending; + int i, ret, avail_periods; + + /* + * ALSA calls .ack whenever appl_ptr moves, also after a stop and + * before the next prepare. The graph has no queue to fill then, and + * queue_ptr is out of step with appl_ptr until prepare resets both. + */ + if (prtd->state != Q6APM_STREAM_RUNNING) return 0; - if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { - avail_periods = (runtime->control->appl_ptr - prtd->queue_ptr)/runtime->period_size; - for (i = 0; i < avail_periods; i++) { - ret = q6apm_write_async(prtd->graph, prtd->pcm_count, 0, 0, NO_TIMESTAMP); - if (ret < 0) { - dev_err(component->dev, "Error queuing playback buffer %d\n", ret); - return ret; - } - prtd->queue_ptr += runtime->period_size; + /* A drop before start does not reach the trigger callback. */ + switch (runtime->state) { + case SNDRV_PCM_STATE_PREPARED: + case SNDRV_PCM_STATE_RUNNING: + case SNDRV_PCM_STATE_PAUSED: + case SNDRV_PCM_STATE_DRAINING: + break; + default: + return 0; + } + + /* Frames queued that hw_ptr has not passed yet, at most one ring. */ + ahead = prtd->queue_ptr - runtime->status->hw_ptr; + if (ahead < 0) + ahead += runtime->boundary; + if (ahead > runtime->buffer_size) { + q6apm_dai_align_queue(substream); + ahead = prtd->queue_ptr - runtime->status->hw_ptr; + if (ahead < 0) + ahead += runtime->boundary; + } + + /* Nothing to queue until appl_ptr has passed queue_ptr. */ + pending = snd_pcm_playback_hw_avail(runtime) - ahead; + if (pending <= 0) + return 0; + + /* Leave the buffers the DSP still holds alone. */ + avail_periods = min_t(snd_pcm_sframes_t, pending / runtime->period_size, + (snd_pcm_sframes_t)runtime->periods - + (snd_pcm_sframes_t)prtd->in_flight); + for (i = 0; i < avail_periods; i++) { + ret = q6apm_write_async(prtd->graph, prtd->pcm_count, 0, 0, NO_TIMESTAMP); + if (ret < 0) { + dev_err(prtd->dev, "Error queuing playback buffer %d\n", ret); + /* + * The core has moved on to its next buffer. Only a + * prepare brings queue_ptr back in step with it. + */ + snd_pcm_stop(substream, SNDRV_PCM_STATE_XRUN); + return ret; } + prtd->in_flight++; + prtd->queue_ptr += runtime->period_size; + if (prtd->queue_ptr >= runtime->boundary) + prtd->queue_ptr -= runtime->boundary; } - return ret; + return 0; +} + +static int q6apm_dai_ack(struct snd_soc_component *component, struct snd_pcm_substream *substream) +{ + struct snd_pcm_runtime *runtime = substream->runtime; + struct q6apm_dai_rtd *prtd = runtime->private_data; + + if (q6apm_is_graph_in_push_pull_mode(prtd->graph)) + return 0; + + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) + return q6apm_dai_queue_playback(substream); + + return 0; +} + +/* + * A PCM reset, which ALSA also runs at the end of every prepare, moves + * hw_ptr: modulo the buffer size on a running stream, to 0 otherwise. + * appl_ptr follows it without a call to .ack. The buffers the DSP holds + * stay with it, so keep queue_ptr in step with the ring. + */ +static int q6apm_dai_ioctl(struct snd_soc_component *component, + struct snd_pcm_substream *substream, + unsigned int cmd, void *arg) +{ + struct snd_pcm_runtime *runtime = substream->runtime; + struct q6apm_dai_rtd *prtd = runtime->private_data; + int ret; + + ret = snd_pcm_lib_ioctl(substream, cmd, arg); + if (ret < 0 || cmd != SNDRV_PCM_IOCTL1_RESET || + substream->stream != SNDRV_PCM_STREAM_PLAYBACK || + q6apm_is_graph_in_push_pull_mode(prtd->graph)) + return ret; + + guard(pcm_stream_lock_irq)(substream); + q6apm_dai_align_queue(substream); + + return 0; } static int q6apm_dai_trigger(struct snd_soc_component *component, @@ -497,6 +637,7 @@ static int q6apm_dai_open(struct snd_soc_component *component, return -ENOMEM; spin_lock_init(&prtd->lock); + prtd->dev = dev; prtd->substream = substream; prtd->graph = q6apm_graph_open(dev, event_handler, prtd, graph_id, substream->stream); if (IS_ERR(prtd->graph)) { @@ -1019,8 +1160,10 @@ static int q6apm_dai_compr_set_params(struct snd_soc_component *component, cfg.num_channels = 2; cfg.bit_width = prtd->bits_per_sample; cfg.fmt = codec->id; - audioreach_set_default_channel_mapping(cfg.channel_map, - cfg.num_channels); + ret = q6dsp_map_channels(cfg.channel_map, cfg.num_channels); + if (ret) + return ret; + memcpy(&cfg.codec, codec, sizeof(*codec)); ret = q6apm_graph_media_format_shmem(prtd->graph, &cfg); @@ -1191,6 +1334,7 @@ static const struct snd_soc_component_driver q6apm_fe_dai_component = { .pointer = q6apm_dai_pointer, .trigger = q6apm_dai_trigger, .ack = q6apm_dai_ack, + .ioctl = q6apm_dai_ioctl, .compress_ops = &q6apm_dai_compress_ops, .use_dai_pcm_id = true, .remove_order = SND_SOC_COMP_ORDER_EARLY, diff --git a/sound/soc/qcom/qdsp6/q6apm-lpass-dais.c b/sound/soc/qcom/qdsp6/q6apm-lpass-dais.c index c63622629f1515..d43d97d1384101 100644 --- a/sound/soc/qcom/qdsp6/q6apm-lpass-dais.c +++ b/sound/soc/qcom/qdsp6/q6apm-lpass-dais.c @@ -94,7 +94,7 @@ static int q6dma_set_channel_map(struct snd_soc_dai *dai, return -EINVAL; } - if (tx_num > AR_PCM_MAX_NUM_CHANNEL) { + if (tx_num > PCM_MAX_NUM_CHANNEL) { dev_err(dai->dev, "invalid tx num %d\n", tx_num); return -EINVAL; @@ -147,7 +147,9 @@ static int q6hdmi_hw_params(struct snd_pcm_substream *substream, cfg->bit_width = params_width(params); cfg->sample_rate = params_rate(params); cfg->num_channels = channels; - audioreach_set_default_channel_mapping(cfg->channel_map, channels); + ret = q6dsp_map_channels(cfg->channel_map, channels); + if (ret) + return ret; switch (dai->id) { case DISPLAY_PORT_RX_0: @@ -173,16 +175,14 @@ static int q6dma_hw_params(struct snd_pcm_substream *substream, struct q6apm_lpass_dai_data *dai_data = dev_get_drvdata(dai->dev); struct audioreach_module_config *cfg = &dai_data->module_config[dai->id]; int channels = hw_param_interval_c(params, SNDRV_PCM_HW_PARAM_CHANNELS)->max; - int i; + int ret; cfg->bit_width = params_width(params); cfg->sample_rate = params_rate(params); cfg->num_channels = channels; - memset(cfg->channel_map, 0, sizeof(cfg->channel_map)); - audioreach_set_default_channel_mapping(cfg->channel_map, channels); - for (i = 0; i < channels && i < AR_PCM_MAX_NUM_CHANNEL; i++) - if (!cfg->channel_map[i]) - cfg->channel_map[i] = i + 1; + ret = q6dsp_map_channels(cfg->channel_map, channels); + if (ret) + return ret; return 0; } diff --git a/sound/soc/qcom/qdsp6/q6asm-dai.c b/sound/soc/qcom/qdsp6/q6asm-dai.c index 3840669867351a..57cbce2bb0cb71 100644 --- a/sound/soc/qcom/qdsp6/q6asm-dai.c +++ b/sound/soc/qcom/qdsp6/q6asm-dai.c @@ -63,6 +63,7 @@ struct q6asm_dai_rtd { uint64_t bytes_received; uint64_t copied_total; uint16_t bits_per_sample; + uint16_t sample_word_size; snd_pcm_uframes_t queue_ptr; uint16_t source; /* Encoding source bit mask */ struct audio_client *audio_client; @@ -90,7 +91,7 @@ static const struct snd_pcm_hardware q6asm_dai_hardware_capture = { SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_PAUSE | SNDRV_PCM_INFO_RESUME), .formats = (SNDRV_PCM_FMTBIT_S16_LE | - SNDRV_PCM_FMTBIT_S24_LE), + SNDRV_PCM_FMTBIT_S24_3LE), .rates = SNDRV_PCM_RATE_8000_48000, .rate_min = 8000, .rate_max = 48000, @@ -113,7 +114,8 @@ static const struct snd_pcm_hardware q6asm_dai_hardware_playback = { SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_PAUSE | SNDRV_PCM_INFO_RESUME), .formats = (SNDRV_PCM_FMTBIT_S16_LE | - SNDRV_PCM_FMTBIT_S24_LE), + SNDRV_PCM_FMTBIT_S24_3LE | + SNDRV_PCM_FMTBIT_S32_LE), .rates = SNDRV_PCM_RATE_8000_192000, .rate_min = 8000, .rate_max = 192000, @@ -139,7 +141,8 @@ static const struct snd_pcm_hardware q6asm_dai_hardware_playback = { SNDRV_PCM_RATE_176400 | \ SNDRV_PCM_RATE_192000), \ .formats = (SNDRV_PCM_FMTBIT_S16_LE | \ - SNDRV_PCM_FMTBIT_S24_LE), \ + SNDRV_PCM_FMTBIT_S24_3LE | \ + SNDRV_PCM_FMTBIT_S32_LE), \ .channels_min = 1, \ .channels_max = 8, \ .rate_min = 8000, \ @@ -151,7 +154,7 @@ static const struct snd_pcm_hardware q6asm_dai_hardware_playback = { SNDRV_PCM_RATE_12000 | \ SNDRV_PCM_RATE_24000), \ .formats = (SNDRV_PCM_FMTBIT_S16_LE | \ - SNDRV_PCM_FMTBIT_S24_LE), \ + SNDRV_PCM_FMTBIT_S24_3LE), \ .channels_min = 1, \ .channels_max = 4, \ .rate_min = 8000, \ @@ -284,13 +287,15 @@ static int q6asm_dai_prepare(struct snd_soc_component *component, ret = q6asm_media_format_block_multi_ch_pcm( prtd->audio_client, prtd->stream_id, runtime->rate, runtime->channels, NULL, - prtd->bits_per_sample); + prtd->bits_per_sample, + prtd->sample_word_size); } else if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) { ret = q6asm_enc_cfg_blk_pcm_format_support(prtd->audio_client, prtd->stream_id, runtime->rate, runtime->channels, - prtd->bits_per_sample); + prtd->bits_per_sample, + prtd->sample_word_size); /* Queue the buffers */ for (i = 0; i < runtime->periods; i++) @@ -507,9 +512,16 @@ static int q6asm_dai_hw_params(struct snd_soc_component *component, switch (params_format(params)) { case SNDRV_PCM_FORMAT_S16_LE: prtd->bits_per_sample = 16; + prtd->sample_word_size = 16; break; - case SNDRV_PCM_FORMAT_S24_LE: + case SNDRV_PCM_FORMAT_S24_3LE: + /* 24-bit samples packed in three bytes, no padding */ prtd->bits_per_sample = 24; + prtd->sample_word_size = 24; + break; + case SNDRV_PCM_FORMAT_S32_LE: + prtd->bits_per_sample = 32; + prtd->sample_word_size = 32; break; } diff --git a/sound/soc/qcom/qdsp6/q6asm.c b/sound/soc/qcom/qdsp6/q6asm.c index d042132caf0343..ee1930e41d4b63 100644 --- a/sound/soc/qcom/qdsp6/q6asm.c +++ b/sound/soc/qcom/qdsp6/q6asm.c @@ -40,6 +40,10 @@ #define ASM_PARAM_ID_ENCDEC_ENC_CFG_BLK_V2 0x00010DA3 #define ASM_SESSION_CMD_RUN_V2 0x00010DAA #define ASM_MEDIA_FMT_MULTI_CHANNEL_PCM_V2 0x00010DA5 +#define ASM_MEDIA_FMT_MULTI_CHANNEL_PCM_V4 0x0001320C +#define ASM_MEDIA_FMT_MULTI_CHANNEL_PCM_V5 0x00013222 +/* ADSP ASM service API version at which the V5 PCM media format is supported */ +#define ADSP_ASM_API_VERSION_V2 2 #define ASM_MEDIA_FMT_MP3 0x00010BE9 #define ASM_MEDIA_FMT_FLAC 0x00010C16 #define ASM_MEDIA_FMT_WMA_V9 0x00010DA8 @@ -99,6 +103,31 @@ struct asm_multi_channel_pcm_fmt_blk_v2 { u8 channel_mapping[PCM_MAX_NUM_CHANNEL]; } __packed; +/* Note: in V4 the channel map precedes endianness/mode (unlike V5) */ +struct asm_multi_channel_pcm_fmt_blk_v4 { + struct asm_data_cmd_media_fmt_update_v2 fmt_blk; + u16 num_channels; + u16 bits_per_sample; + u32 sample_rate; + u16 is_signed; + u16 sample_word_size; + u8 channel_mapping[PCM_MAX_NUM_CHANNEL]; + u16 endianness; /* 0: little endian */ + u16 mode; /* 0: default Q factors */ +} __packed; + +struct asm_multi_channel_pcm_fmt_blk_v5 { + struct asm_data_cmd_media_fmt_update_v2 fmt_blk; + u16 num_channels; + u16 bits_per_sample; + u32 sample_rate; + u16 is_signed; + u16 sample_word_size; + u16 endianness; /* 0: little endian */ + u16 mode; /* 0: default Q factors */ + u8 channel_mapping[PCM_MAX_NUM_CHANNEL]; +} __packed; + struct asm_flac_fmt_blk_v2 { struct asm_data_cmd_media_fmt_update_v2 fmt_blk; u16 is_stream_info_present; @@ -191,6 +220,33 @@ struct asm_multi_channel_pcm_enc_cfg_v2 { uint8_t channel_mapping[8]; } __packed; +/* Note: in V4 the channel map precedes endianness/mode (unlike V5) */ +struct asm_multi_channel_pcm_enc_cfg_v4 { + struct asm_stream_cmd_set_encdec_param encdec; + struct asm_enc_cfg_blk_param_v2 encblk; + u16 num_channels; + u16 bits_per_sample; + u32 sample_rate; + u16 is_signed; + u16 sample_word_size; + u8 channel_mapping[PCM_MAX_NUM_CHANNEL]; + u16 endianness; /* 0: little endian */ + u16 mode; /* 0: default Q factors */ +} __packed; + +struct asm_multi_channel_pcm_enc_cfg_v5 { + struct asm_stream_cmd_set_encdec_param encdec; + struct asm_enc_cfg_blk_param_v2 encblk; + u16 num_channels; + u16 bits_per_sample; + u32 sample_rate; + u16 is_signed; + u16 sample_word_size; + u16 endianness; /* 0: little endian */ + u16 mode; /* 0: default Q factors */ + u8 channel_mapping[PCM_MAX_NUM_CHANNEL]; +} __packed; + struct asm_data_cmd_read_v2 { u32 buf_addr_lsw; u32 buf_addr_msw; @@ -912,6 +968,19 @@ static int q6asm_ac_send_cmd_sync(struct audio_client *ac, struct apr_pkt *pkt) return rc; } +/* + * Both the V4 and V5 multichannel PCM media formats carry the sample word size + * needed to describe e.g. 24-bit samples held in a 32-bit word. V5 is only + * understood by newer ADSP firmware (ASM API version >= 2); everything else - + * including when the version query is unsupported and ainfo is left zeroed - + * uses V4, which the QDSP6 firmware has supported since its introduction. (The + * old V2 format, which lacks the word size, is no longer used for playback.) + */ +static bool q6asm_pcm_fmt_v5_supported(struct audio_client *ac) +{ + return ac->q6asm->ainfo.api_version >= ADSP_ASM_API_VERSION_V2; +} + /** * q6asm_open_write() - Open audio client for writing * @ac: audio client pointer @@ -955,7 +1024,9 @@ int q6asm_open_write(struct audio_client *ac, uint32_t stream_id, open->dec_fmt_id = ASM_MEDIA_FMT_MP3; break; case FORMAT_LINEAR_PCM: - open->dec_fmt_id = ASM_MEDIA_FMT_MULTI_CHANNEL_PCM_V2; + open->dec_fmt_id = q6asm_pcm_fmt_v5_supported(ac) ? + ASM_MEDIA_FMT_MULTI_CHANNEL_PCM_V5 : + ASM_MEDIA_FMT_MULTI_CHANNEL_PCM_V4; break; case SND_AUDIOCODEC_FLAC: open->dec_fmt_id = ASM_MEDIA_FMT_FLAC; @@ -1078,6 +1149,7 @@ EXPORT_SYMBOL_GPL(q6asm_run_nowait); * @channels: number of audio channels. * @channel_map: channel map pointer * @bits_per_sample: bits per sample + * @sample_word_size: size in bits of the word that holds a sample of a channel * * Return: Will be an negative value on error or zero on success */ @@ -1085,30 +1157,60 @@ int q6asm_media_format_block_multi_ch_pcm(struct audio_client *ac, uint32_t stream_id, uint32_t rate, uint32_t channels, u8 channel_map[PCM_MAX_NUM_CHANNEL], - uint16_t bits_per_sample) + uint16_t bits_per_sample, + uint16_t sample_word_size) { - struct asm_multi_channel_pcm_fmt_blk_v2 *fmt; + bool use_v5 = q6asm_pcm_fmt_v5_supported(ac); + struct asm_multi_channel_pcm_fmt_blk_v5 *fmt_v5; + struct asm_multi_channel_pcm_fmt_blk_v4 *fmt_v4; struct apr_pkt *pkt; u8 *channel_mapping; - int pkt_size = APR_HDR_SIZE + sizeof(*fmt); + int pkt_size = APR_HDR_SIZE + + (use_v5 ? sizeof(*fmt_v5) : sizeof(*fmt_v4)); void *p __free(kfree) = kzalloc(pkt_size, GFP_KERNEL); if (!p) return -ENOMEM; pkt = p; - fmt = p + APR_HDR_SIZE; q6asm_add_hdr(ac, &pkt->hdr, pkt_size, true, stream_id); - pkt->hdr.opcode = ASM_DATA_CMD_MEDIA_FMT_UPDATE_V2; - fmt->fmt_blk.fmt_blk_size = sizeof(*fmt) - sizeof(fmt->fmt_blk); - fmt->num_channels = channels; - fmt->bits_per_sample = bits_per_sample; - fmt->sample_rate = rate; - fmt->is_signed = 1; - channel_mapping = fmt->channel_mapping; + dev_dbg(ac->dev, "%s: fmt=%s rate=%u ch=%u bps=%u word=%u (asm api %u)\n", + __func__, use_v5 ? "V5" : "V4", rate, channels, + bits_per_sample, sample_word_size, ac->q6asm->ainfo.api_version); + + /* + * Leave mode=0 (default Q factors). Per the ADSP ABI the defaults + * are Q15 for 16-bit, Q23 for 24-bit packed (word_size=24), and Q31 + * for 32-bit, which match every format we advertise to userspace. + * The explicit override values (15/23/31) are not honoured by every + * firmware; the default path is the safe choice. + */ + if (use_v5) { + fmt_v5 = p + APR_HDR_SIZE; + fmt_v5->fmt_blk.fmt_blk_size = sizeof(*fmt_v5) - + sizeof(fmt_v5->fmt_blk); + fmt_v5->num_channels = channels; + fmt_v5->bits_per_sample = bits_per_sample; + fmt_v5->sample_rate = rate; + fmt_v5->is_signed = 1; + fmt_v5->sample_word_size = sample_word_size; + fmt_v5->mode = 0; /* default Q-factor per bps/word_size */ + channel_mapping = fmt_v5->channel_mapping; + } else { + fmt_v4 = p + APR_HDR_SIZE; + fmt_v4->fmt_blk.fmt_blk_size = sizeof(*fmt_v4) - + sizeof(fmt_v4->fmt_blk); + fmt_v4->num_channels = channels; + fmt_v4->bits_per_sample = bits_per_sample; + fmt_v4->sample_rate = rate; + fmt_v4->is_signed = 1; + fmt_v4->sample_word_size = sample_word_size; + fmt_v4->mode = 0; /* default Q-factor per bps/word_size */ + channel_mapping = fmt_v4->channel_mapping; + } if (channel_map) { memcpy(channel_mapping, channel_map, PCM_MAX_NUM_CHANNEL); @@ -1347,40 +1449,62 @@ EXPORT_SYMBOL_GPL(q6asm_stream_remove_trailing_silence); * @rate: audio sample rate * @channels: number of audio channels. * @bits_per_sample: bits per sample + * @sample_word_size: size in bits of the word that holds a sample of a channel * * Return: Will be an negative value on error or zero on success */ int q6asm_enc_cfg_blk_pcm_format_support(struct audio_client *ac, uint32_t stream_id, uint32_t rate, uint32_t channels, - uint16_t bits_per_sample) + uint16_t bits_per_sample, + uint16_t sample_word_size) { - struct asm_multi_channel_pcm_enc_cfg_v2 *enc_cfg; + bool use_v5 = q6asm_pcm_fmt_v5_supported(ac); + struct asm_multi_channel_pcm_enc_cfg_v5 *enc_v5; + struct asm_multi_channel_pcm_enc_cfg_v4 *enc_v4; struct apr_pkt *pkt; u8 *channel_mapping; u32 frames_per_buf = 0; - int pkt_size = APR_HDR_SIZE + sizeof(*enc_cfg); + int pkt_size = APR_HDR_SIZE + + (use_v5 ? sizeof(*enc_v5) : sizeof(*enc_v4)); void *p __free(kfree) = kzalloc(pkt_size, GFP_KERNEL); if (!p) return -ENOMEM; pkt = p; - enc_cfg = p + APR_HDR_SIZE; q6asm_add_hdr(ac, &pkt->hdr, pkt_size, true, stream_id); - pkt->hdr.opcode = ASM_STREAM_CMD_SET_ENCDEC_PARAM; - enc_cfg->encdec.param_id = ASM_PARAM_ID_ENCDEC_ENC_CFG_BLK_V2; - enc_cfg->encdec.param_size = sizeof(*enc_cfg) - sizeof(enc_cfg->encdec); - enc_cfg->encblk.frames_per_buf = frames_per_buf; - enc_cfg->encblk.enc_cfg_blk_size = enc_cfg->encdec.param_size - - sizeof(struct asm_enc_cfg_blk_param_v2); - - enc_cfg->num_channels = channels; - enc_cfg->bits_per_sample = bits_per_sample; - enc_cfg->sample_rate = rate; - enc_cfg->is_signed = 1; - channel_mapping = enc_cfg->channel_mapping; + + if (use_v5) { + enc_v5 = p + APR_HDR_SIZE; + enc_v5->encdec.param_id = ASM_PARAM_ID_ENCDEC_ENC_CFG_BLK_V2; + enc_v5->encdec.param_size = sizeof(*enc_v5) - + sizeof(enc_v5->encdec); + enc_v5->encblk.frames_per_buf = frames_per_buf; + enc_v5->encblk.enc_cfg_blk_size = enc_v5->encdec.param_size - + sizeof(struct asm_enc_cfg_blk_param_v2); + enc_v5->num_channels = channels; + enc_v5->bits_per_sample = bits_per_sample; + enc_v5->sample_rate = rate; + enc_v5->is_signed = 1; + enc_v5->sample_word_size = sample_word_size; + channel_mapping = enc_v5->channel_mapping; + } else { + enc_v4 = p + APR_HDR_SIZE; + enc_v4->encdec.param_id = ASM_PARAM_ID_ENCDEC_ENC_CFG_BLK_V2; + enc_v4->encdec.param_size = sizeof(*enc_v4) - + sizeof(enc_v4->encdec); + enc_v4->encblk.frames_per_buf = frames_per_buf; + enc_v4->encblk.enc_cfg_blk_size = enc_v4->encdec.param_size - + sizeof(struct asm_enc_cfg_blk_param_v2); + enc_v4->num_channels = channels; + enc_v4->bits_per_sample = bits_per_sample; + enc_v4->sample_rate = rate; + enc_v4->is_signed = 1; + enc_v4->sample_word_size = sample_word_size; + channel_mapping = enc_v4->channel_mapping; + } if (q6dsp_map_channels(channel_mapping, channels)) return -EINVAL; @@ -1473,7 +1597,9 @@ static int __q6asm_open_read(struct audio_client *ac, uint32_t stream_id, switch (format) { case FORMAT_LINEAR_PCM: open->mode_flags |= 0x00; - open->enc_cfg_id = ASM_MEDIA_FMT_MULTI_CHANNEL_PCM_V2; + open->enc_cfg_id = q6asm_pcm_fmt_v5_supported(ac) ? + ASM_MEDIA_FMT_MULTI_CHANNEL_PCM_V5 : + ASM_MEDIA_FMT_MULTI_CHANNEL_PCM_V4; break; default: pr_err("Invalid format[%d]\n", format); diff --git a/sound/soc/qcom/qdsp6/q6asm.h b/sound/soc/qcom/qdsp6/q6asm.h index 6fafda5bd8498e..2d969dbffcffce 100644 --- a/sound/soc/qcom/qdsp6/q6asm.h +++ b/sound/soc/qcom/qdsp6/q6asm.h @@ -106,7 +106,8 @@ int q6asm_open_read(struct audio_client *ac, uint32_t stream_id, int q6asm_enc_cfg_blk_pcm_format_support(struct audio_client *ac, uint32_t stream_id, uint32_t rate, uint32_t channels, - uint16_t bits_per_sample); + uint16_t bits_per_sample, + uint16_t sample_word_size); int q6asm_read(struct audio_client *ac, uint32_t stream_id); @@ -114,7 +115,8 @@ int q6asm_media_format_block_multi_ch_pcm(struct audio_client *ac, uint32_t stream_id, uint32_t rate, uint32_t channels, u8 channel_map[PCM_MAX_NUM_CHANNEL], - uint16_t bits_per_sample); + uint16_t bits_per_sample, + uint16_t sample_word_size); int q6asm_stream_media_format_block_flac(struct audio_client *ac, uint32_t stream_id, struct q6asm_flac_cfg *cfg); diff --git a/sound/soc/qcom/qdsp6/q6dsp-lpass-ports.c b/sound/soc/qcom/qdsp6/q6dsp-lpass-ports.c index f422346a50c694..49902abf8d2d1c 100644 --- a/sound/soc/qcom/qdsp6/q6dsp-lpass-ports.c +++ b/sound/soc/qcom/qdsp6/q6dsp-lpass-ports.c @@ -389,7 +389,8 @@ static struct snd_soc_dai_driver q6dsp_audio_fe_dais[] = { .rates = SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000, .formats = SNDRV_PCM_FMTBIT_S16_LE | - SNDRV_PCM_FMTBIT_S24_LE, + SNDRV_PCM_FMTBIT_S24_LE | + SNDRV_PCM_FMTBIT_S32_LE, .channels_min = 1, .channels_max = 8, .rate_min = 8000, @@ -416,7 +417,9 @@ static struct snd_soc_dai_driver q6dsp_audio_fe_dais[] = { .stream_name = "Secondary MI2S Playback", .rates = SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000, - .formats = SNDRV_PCM_FMTBIT_S16_LE, + .formats = SNDRV_PCM_FMTBIT_S16_LE | + SNDRV_PCM_FMTBIT_S24_LE | + SNDRV_PCM_FMTBIT_S32_LE, .channels_min = 1, .channels_max = 8, .rate_min = 8000, @@ -443,7 +446,9 @@ static struct snd_soc_dai_driver q6dsp_audio_fe_dais[] = { .stream_name = "Tertiary MI2S Playback", .rates = SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000, - .formats = SNDRV_PCM_FMTBIT_S16_LE, + .formats = SNDRV_PCM_FMTBIT_S16_LE | + SNDRV_PCM_FMTBIT_S24_LE | + SNDRV_PCM_FMTBIT_S32_LE, .channels_min = 1, .channels_max = 8, .rate_min = 8000, @@ -470,7 +475,9 @@ static struct snd_soc_dai_driver q6dsp_audio_fe_dais[] = { .stream_name = "Quaternary MI2S Playback", .rates = SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000, - .formats = SNDRV_PCM_FMTBIT_S16_LE, + .formats = SNDRV_PCM_FMTBIT_S16_LE | + SNDRV_PCM_FMTBIT_S24_LE | + SNDRV_PCM_FMTBIT_S32_LE, .channels_min = 1, .channels_max = 8, .rate_min = 8000, @@ -498,7 +505,9 @@ static struct snd_soc_dai_driver q6dsp_audio_fe_dais[] = { .rates = SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000 | SNDRV_PCM_RATE_96000 | SNDRV_PCM_RATE_192000, - .formats = SNDRV_PCM_FMTBIT_S16_LE, + .formats = SNDRV_PCM_FMTBIT_S16_LE | + SNDRV_PCM_FMTBIT_S24_LE | + SNDRV_PCM_FMTBIT_S32_LE, .channels_min = 1, .channels_max = 8, .rate_min = 8000, diff --git a/sound/soc/qcom/qdsp6/q6routing.c b/sound/soc/qcom/qdsp6/q6routing.c index 0a55d1f384d4d8..5e532b8336dfe7 100644 --- a/sound/soc/qcom/qdsp6/q6routing.c +++ b/sound/soc/qcom/qdsp6/q6routing.c @@ -1170,6 +1170,9 @@ static int routing_hw_params(struct snd_soc_component *component, case SNDRV_PCM_FORMAT_S24_LE: session->bits_per_sample = 24; break; + case SNDRV_PCM_FORMAT_S32_LE: + session->bits_per_sample = 32; + break; default: break; } diff --git a/sound/soc/qcom/sc8280xp.c b/sound/soc/qcom/sc8280xp.c index ac4dfb2c2182ca..f655b3ae1d5bf4 100644 --- a/sound/soc/qcom/sc8280xp.c +++ b/sound/soc/qcom/sc8280xp.c @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -45,6 +46,7 @@ static struct snd_soc_dapm_widget sc8280xp_dapm_widgets[] = { static const struct snd_kcontrol_new max98090_controls[] = { SOC_DAPM_PIN_SWITCH("Headset Mic12"), SOC_DAPM_PIN_SWITCH("Headphone"), + SOC_DAPM_PIN_SWITCH("Headset Mic34"), SOC_DAPM_PIN_SWITCH("Headset Mic56"), SOC_DAPM_PIN_SWITCH("Speaker"), SOC_DAPM_PIN_SWITCH("Receiver"), @@ -56,6 +58,7 @@ static const struct snd_soc_dapm_widget max98090_dapm_widgets[] = { SND_SOC_DAPM_MIC("Mic Jack", NULL), SND_SOC_DAPM_HP("Headphone", NULL), SND_SOC_DAPM_MIC("Headset Mic12", NULL), + SND_SOC_DAPM_MIC("Headset Mic34", NULL), SND_SOC_DAPM_MIC("Headset Mic56", NULL), SND_SOC_DAPM_MIC("Int Mic", NULL), SND_SOC_DAPM_SPK("Receiver", NULL), @@ -71,6 +74,7 @@ enum sc8280xp_jack_setup { struct sc8280xp_dai_data { unsigned int id; unsigned int mclk_rate; + unsigned int cpu_dai_fmt; bool codec_sysclk_set; bool mi2s_mclk_enable; bool mi2s_bclk_enable; @@ -159,6 +163,7 @@ static int sc8280xp_tdm_hw_params(struct snd_pcm_substream *substream, struct qcom_snd_tdm_slot_cfg codec_cfg; bool codec_sysclk_set = data->priv->codec_sysclk_set; bool mi2s_bclk_enable = data->priv->mi2s_bclk_enable; + unsigned int cpu_dai_fmt = SND_SOC_DAIFMT_BP_FP; int bclk_freq; int ret; int i; @@ -167,6 +172,8 @@ static int sc8280xp_tdm_hw_params(struct snd_pcm_substream *substream, if (dai_data) { codec_sysclk_set = dai_data->codec_sysclk_set; mi2s_bclk_enable = dai_data->mi2s_bclk_enable; + if (dai_data->cpu_dai_fmt) + cpu_dai_fmt = dai_data->cpu_dai_fmt; } ret = qcom_snd_get_dai_tdm_slots(rtd, &cpu_cfg, &codec_cfg); @@ -176,7 +183,7 @@ static int sc8280xp_tdm_hw_params(struct snd_pcm_substream *substream, if (!cpu_cfg.slots) return 0; - ret = snd_soc_dai_set_fmt(cpu_dai, SND_SOC_DAIFMT_BP_FP); + ret = snd_soc_dai_set_fmt(cpu_dai, cpu_dai_fmt); if (ret && ret != -ENOTSUPP) return ret; @@ -329,6 +336,7 @@ static int sc8280xp_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd, case TX_CODEC_DMA_TX_1: case TX_CODEC_DMA_TX_2: case TX_CODEC_DMA_TX_3: + case VA_CODEC_DMA_TX_1: channels->min = 1; break; case PRIMARY_MI2S_RX ... QUATERNARY_MI2S_TX: @@ -388,6 +396,7 @@ static int sc8280xp_snd_hw_params(struct snd_pcm_substream *substream, bool codec_sysclk_set = data->priv->codec_sysclk_set; bool mi2s_mclk_enable = data->priv->mi2s_mclk_enable; bool mi2s_bclk_enable = data->priv->mi2s_bclk_enable; + unsigned int cpu_dai_fmt = SND_SOC_DAIFMT_BP_FP; int mclk_freq; int bclk_freq = sc8280xp_get_bclk_freq(params); int ret; @@ -398,6 +407,8 @@ static int sc8280xp_snd_hw_params(struct snd_pcm_substream *substream, codec_sysclk_set = dai_data->codec_sysclk_set; mi2s_mclk_enable = dai_data->mi2s_mclk_enable; mi2s_bclk_enable = dai_data->mi2s_bclk_enable; + if (dai_data->cpu_dai_fmt) + cpu_dai_fmt = dai_data->cpu_dai_fmt; if (dai_data->mclk_rate) mclk_freq = dai_data->mclk_rate; } @@ -408,7 +419,7 @@ static int sc8280xp_snd_hw_params(struct snd_pcm_substream *substream, case SENARY_MI2S_RX ... SENARY_MI2S_TX: case LPI_MI2S_RX_0 ... LPI_MI2S_TX_4: case AIF_MI2S_RX_0 ... AIF_MI2S_TX_12: - ret = snd_soc_dai_set_fmt(cpu_dai, SND_SOC_DAIFMT_BP_FP); + ret = snd_soc_dai_set_fmt(cpu_dai, cpu_dai_fmt); if (ret && ret != -ENOTSUPP) return ret; @@ -544,7 +555,17 @@ static void sc8280xp_add_be_ops(struct snd_soc_card *card) int i; for_each_card_prelinks(card, i, link) { - if (link->no_pcm == 1) { + /* + * Attach the ops to DPCM backends and to plain CPU <-> codec + * links, which boards that do not route audio through the DSP + * describe without a platform node. Both have a real codec DAI + * to configure. + * + * DPCM frontends must be skipped: qcom_snd_parse_of() marks + * them dynamic and attaches snd_soc_dummy_dlc to them, so + * num_codecs is never zero and cannot tell them apart. + */ + if (link->no_pcm == 1 || !link->dynamic) { link->init = sc8280xp_snd_init; link->exit = sc8280xp_snd_exit; link->be_hw_params_fixup = sc8280xp_be_hw_params_fixup; @@ -553,6 +574,9 @@ static void sc8280xp_add_be_ops(struct snd_soc_card *card) } } +static const struct qcom_snd_soc_common monza_priv_data; +static const struct qcom_snd_soc_common qcs8275_priv_data; + static int sc8280xp_platform_probe(struct platform_device *pdev) { struct snd_soc_card *card; @@ -573,6 +597,15 @@ static int sc8280xp_platform_probe(struct platform_device *pdev) if (!data->priv) return -ENODEV; + /* + * Legacy monaco-arduino-monza DTBs used the generic + * "qcom,qcs8275-sndcard" compatible before "arduino,monza-sndcard" + * was introduced. + */ + if (data->priv == &qcs8275_priv_data && + of_machine_is_compatible("arduino,monza")) + data->priv = &monza_priv_data; + card->owner = THIS_MODULE; card->dev = dev; dev_set_drvdata(dev, card); @@ -641,6 +674,18 @@ static const struct qcom_snd_soc_common maili_priv_data = { .wcd_jack = true, }; +static const struct qcom_snd_soc_common monza_priv_data = { + .driver_name = "qcs8300", + .dapm_widgets = max98090_dapm_widgets, + .num_dapm_widgets = ARRAY_SIZE(max98090_dapm_widgets), + .controls = max98090_controls, + .num_controls = ARRAY_SIZE(max98090_controls), + .codec_sysclk_set = true, + .codec_dai_fmt = SND_SOC_DAIFMT_NB_NF | + SND_SOC_DAIFMT_I2S | + SND_SOC_DAIFMT_BC_FC, +}; + static const struct qcom_snd_soc_common nord_priv_data = { .driver_name = "nord", .mi2s_bclk_enable = true, @@ -701,12 +746,8 @@ static const struct qcom_snd_soc_common rubikpi3_priv_data = { static const struct qcom_snd_soc_common qcs8275_priv_data = { .driver_name = "qcs8300", - .dapm_widgets = max98090_dapm_widgets, - .num_dapm_widgets = ARRAY_SIZE(max98090_dapm_widgets), - .controls = max98090_controls, - .num_controls = ARRAY_SIZE(max98090_controls), - .codec_sysclk_set = true, - .codec_dai_fmt = SND_SOC_DAIFMT_NB_NF | SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_BC_FC, + .dapm_widgets = sc8280xp_dapm_widgets, + .num_dapm_widgets = ARRAY_SIZE(sc8280xp_dapm_widgets), }; static const struct qcom_snd_soc_common sc8280xp_priv_data = { @@ -716,6 +757,53 @@ static const struct qcom_snd_soc_common sc8280xp_priv_data = { .wcd_jack = true, }; +static const struct qcom_snd_soc_common shikra_cqm_priv_data = { + .driver_name = "shikra", + .dapm_widgets = sc8280xp_dapm_widgets, + .num_dapm_widgets = ARRAY_SIZE(sc8280xp_dapm_widgets), + .wcd_jack = true, + SC8280XP_DAI_DATA({ + .id = AIF_TDM_RX_2, + .cpu_dai_fmt = SND_SOC_DAIFMT_DSP_A | SND_SOC_DAIFMT_BP_FP, + .codec_sysclk_set = true, + .mi2s_bclk_enable = true, + } + ), +}; + +static const struct qcom_snd_soc_common shikra_cqs_priv_data = { + .driver_name = "shikra", + .dapm_widgets = sc8280xp_dapm_widgets, + .num_dapm_widgets = ARRAY_SIZE(sc8280xp_dapm_widgets), + .wcd_jack = true, + SC8280XP_DAI_DATA({ + .id = AIF_TDM_RX_2, + .codec_sysclk_set = true, + .mi2s_bclk_enable = true, + } + ), +}; + +static const struct qcom_snd_soc_common shikra_iqs_priv_data = { + .driver_name = "shikra", + .dapm_widgets = max98090_dapm_widgets, + .num_dapm_widgets = ARRAY_SIZE(max98090_dapm_widgets), + .controls = max98090_controls, + .num_controls = ARRAY_SIZE(max98090_controls), + .codec_dai_fmt = SND_SOC_DAIFMT_NB_NF | SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_BC_FC, + SC8280XP_DAI_DATA({ + .id = AIF_MI2S_RX_0, + .codec_sysclk_set = true, + .mi2s_bclk_enable = true, + .jack_setup = SC8280XP_JACK_SETUP_CODEC, + }, { + .id = AIF_MI2S_TX_0, + .codec_sysclk_set = true, + .mi2s_bclk_enable = true, + } + ), +}; + static const struct qcom_snd_soc_common sm8450_priv_data = { .driver_name = "sm8450", .dapm_widgets = sc8280xp_dapm_widgets, @@ -770,6 +858,7 @@ static const struct qcom_snd_soc_common sm8750_priv_data = { }; static const struct of_device_id snd_sc8280xp_dt_match[] = { + { .compatible = "arduino,monza-sndcard", .data = &monza_priv_data }, { .compatible = "ayaneo,pocket-s2-sndcard", .data = &ayaneo_ps2_priv_data }, { .compatible = "motorola,vantage-sndcard", .data = &motorola_vantage_priv_data }, { .compatible = "qcom,eliza-sndcard", .data = &eliza_priv_data }, @@ -785,6 +874,9 @@ static const struct of_device_id snd_sc8280xp_dt_match[] = { { .compatible = "qcom,qcs9075-sndcard", .data = &qcs9100_priv_data }, { .compatible = "qcom,qcs9100-sndcard", .data = &qcs9100_priv_data }, { .compatible = "qcom,sc8280xp-sndcard", .data = &sc8280xp_priv_data }, + { .compatible = "qcom,shikra-cqm-sndcard", .data = &shikra_cqm_priv_data }, + { .compatible = "qcom,shikra-cqs-sndcard", .data = &shikra_cqs_priv_data }, + { .compatible = "qcom,shikra-iqs-sndcard", .data = &shikra_iqs_priv_data }, { .compatible = "qcom,sm8450-sndcard", .data = &sm8450_priv_data }, { .compatible = "qcom,sm8475-sndcard", .data = &sm8475_priv_data }, { .compatible = "qcom,sm8550-sndcard", .data = &sm8550_priv_data }, diff --git a/sound/soc/qcom/sdw.c b/sound/soc/qcom/sdw.c index 6576b47a4c8c35..e19adb7c750b0d 100644 --- a/sound/soc/qcom/sdw.c +++ b/sound/soc/qcom/sdw.c @@ -30,6 +30,7 @@ static bool qcom_snd_is_sdw_dai(int id) case TX_CODEC_DMA_TX_5: case RX_CODEC_DMA_RX_6: case RX_CODEC_DMA_RX_7: + case VA_CODEC_DMA_TX_1: case SLIMBUS_0_RX...SLIMBUS_6_TX: return true; default: diff --git a/sound/soc/qcom/sm8250.c b/sound/soc/qcom/sm8250.c index d0015e5f525761..ba0aaf4282ad27 100644 --- a/sound/soc/qcom/sm8250.c +++ b/sound/soc/qcom/sm8250.c @@ -231,6 +231,7 @@ static const struct of_device_id snd_sm8250_dt_match[] = { { .compatible = "qcom,qrb5165-rb5-sndcard", .data = "sm8250" }, { .compatible = "qcom,sdm660-sndcard", .data = "sdm660" }, { .compatible = "qcom,sm8250-sndcard", .data = "sm8250" }, + { .compatible = "qcom,sm8350-sndcard", .data = "sm8350" }, {} }; diff --git a/sound/soc/rockchip/rockchip_sai.c b/sound/soc/rockchip/rockchip_sai.c index b625d69f76c814..866b68cc706c13 100644 --- a/sound/soc/rockchip/rockchip_sai.c +++ b/sound/soc/rockchip/rockchip_sai.c @@ -1459,20 +1459,30 @@ static int rockchip_sai_probe(struct platform_device *pdev) return dev_err_probe(&pdev->dev, PTR_ERR(sai->mclk), "Failed to get mclk\n"); - sai->hclk = devm_clk_get_enabled(&pdev->dev, "hclk"); + sai->hclk = devm_clk_get(&pdev->dev, "hclk"); if (IS_ERR(sai->hclk)) return dev_err_probe(&pdev->dev, PTR_ERR(sai->hclk), "Failed to get hclk\n"); + /* + * hclk is only needed until runtime PM takes over below, so it is + * enabled by hand and not with devm_clk_get_enabled(). + */ + ret = clk_prepare_enable(sai->hclk); + if (ret) + return dev_err_probe(&pdev->dev, ret, "Failed to enable hclk\n"); + regmap_read(sai->regmap, SAI_VERSION, &sai->version); ret = rockchip_sai_init_dai(sai, res, &dai); - if (ret) - return dev_err_probe(&pdev->dev, ret, "Failed to initialize DAI\n"); + if (ret) { + dev_err_probe(&pdev->dev, ret, "Failed to initialize DAI\n"); + goto err_disable_hclk; + } ret = rockchip_sai_parse_paths(sai, node); if (ret) - return ret; + goto err_disable_hclk; /* * From here on, all register accesses need to be wrapped in @@ -1480,11 +1490,15 @@ static int rockchip_sai_probe(struct platform_device *pdev) * * NB: we don't rely on _resume_and_get in case of !CONFIG_PM */ - devm_pm_runtime_enable(&pdev->dev); - pm_runtime_get_noresume(&pdev->dev); ret = rockchip_sai_runtime_resume(&pdev->dev); - if (ret) - return dev_err_probe(&pdev->dev, ret, "Failed to resume device\n"); + if (ret) { + dev_err_probe(&pdev->dev, ret, "Failed to resume device\n"); + goto err_disable_hclk; + } + + pm_runtime_set_active(&pdev->dev); + pm_runtime_get_noresume(&pdev->dev); + devm_pm_runtime_enable(&pdev->dev); ret = devm_snd_dmaengine_pcm_register(&pdev->dev, NULL, 0); if (ret) @@ -1505,9 +1519,11 @@ static int rockchip_sai_probe(struct platform_device *pdev) err_runtime_suspend: if (IS_ENABLED(CONFIG_PM)) - pm_runtime_put(&pdev->dev); + pm_runtime_put_sync(&pdev->dev); else rockchip_sai_runtime_suspend(&pdev->dev); +err_disable_hclk: + clk_disable_unprepare(sai->hclk); return ret; } diff --git a/sound/soc/samsung/snow.c b/sound/soc/samsung/snow.c index 9b73c2e62296ac..a1a34ec95c8204 100644 --- a/sound/soc/samsung/snow.c +++ b/sound/soc/samsung/snow.c @@ -222,11 +222,11 @@ static int snow_probe(struct platform_device *pdev) static void snow_remove(struct platform_device *pdev) { - struct snow_priv *priv = platform_get_drvdata(pdev); + struct snd_soc_card *card = platform_get_drvdata(pdev); + struct snow_priv *priv = snd_soc_card_get_drvdata(card); struct snd_soc_dai_link *link = &priv->dai_link; of_node_put(link->cpus->of_node); - of_node_put(link->codecs->of_node); snd_soc_of_put_dai_link_codecs(link); clk_put(priv->clk_i2s_bus); diff --git a/sound/soc/sdca/sdca_asoc.c b/sound/soc/sdca/sdca_asoc.c index aaa84156f20a84..d58be660ced7f5 100644 --- a/sound/soc/sdca/sdca_asoc.c +++ b/sound/soc/sdca/sdca_asoc.c @@ -1214,19 +1214,28 @@ static u64 width_find_mask(unsigned int bits) { switch (bits) { case 0: - return SNDRV_PCM_FMTBIT_S8 | SNDRV_PCM_FMTBIT_S16_LE | - SNDRV_PCM_FMTBIT_S20_LE | SNDRV_PCM_FMTBIT_S24_LE | - SNDRV_PCM_FMTBIT_S32_LE; + return SNDRV_PCM_FMTBIT_S8 | + SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S16_BE | + SNDRV_PCM_FMTBIT_S18_3LE | SNDRV_PCM_FMTBIT_S18_3BE | + SNDRV_PCM_FMTBIT_S20_LE | SNDRV_PCM_FMTBIT_S20_BE | + SNDRV_PCM_FMTBIT_S20_3LE | SNDRV_PCM_FMTBIT_S20_3BE | + SNDRV_PCM_FMTBIT_S24_LE | SNDRV_PCM_FMTBIT_S24_BE | + SNDRV_PCM_FMTBIT_S24_3LE | SNDRV_PCM_FMTBIT_S24_3BE | + SNDRV_PCM_FMTBIT_S32_LE | SNDRV_PCM_FMTBIT_S32_BE; case 8: return SNDRV_PCM_FMTBIT_S8; case 16: - return SNDRV_PCM_FMTBIT_S16_LE; + return SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S16_BE; + case 18: + return SNDRV_PCM_FMTBIT_S18_3LE | SNDRV_PCM_FMTBIT_S18_3BE; case 20: - return SNDRV_PCM_FMTBIT_S20_LE; + return SNDRV_PCM_FMTBIT_S20_LE | SNDRV_PCM_FMTBIT_S20_BE | + SNDRV_PCM_FMTBIT_S20_3LE | SNDRV_PCM_FMTBIT_S20_3BE; case 24: - return SNDRV_PCM_FMTBIT_S24_LE; + return SNDRV_PCM_FMTBIT_S24_LE | SNDRV_PCM_FMTBIT_S24_BE | + SNDRV_PCM_FMTBIT_S24_3LE | SNDRV_PCM_FMTBIT_S24_3BE; case 32: - return SNDRV_PCM_FMTBIT_S32_LE; + return SNDRV_PCM_FMTBIT_S32_LE | SNDRV_PCM_FMTBIT_S32_BE; default: return 0; } @@ -1510,35 +1519,6 @@ static int get_cluster_mask(struct device *dev, struct sdca_function_data *funct return 0; } -static u64 get_word_mask(unsigned int width) -{ - switch (width) { - case 8: - return SNDRV_PCM_FMTBIT_S8 | SNDRV_PCM_FMTBIT_U8; - case 16: - return SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S16_BE | - SNDRV_PCM_FMTBIT_U16_LE | SNDRV_PCM_FMTBIT_U16_BE; - case 18: - return SNDRV_PCM_FMTBIT_S18_3LE | SNDRV_PCM_FMTBIT_U18_3LE | - SNDRV_PCM_FMTBIT_S18_3BE | SNDRV_PCM_FMTBIT_U18_3BE; - case 20: - return SNDRV_PCM_FMTBIT_S20_LE | SNDRV_PCM_FMTBIT_U20_LE | - SNDRV_PCM_FMTBIT_S20_BE | SNDRV_PCM_FMTBIT_U20_BE | - SNDRV_PCM_FMTBIT_S20_3LE | SNDRV_PCM_FMTBIT_U20_3LE | - SNDRV_PCM_FMTBIT_S20_3BE | SNDRV_PCM_FMTBIT_U20_3BE; - case 24: - return SNDRV_PCM_FMTBIT_S24_LE | SNDRV_PCM_FMTBIT_S24_BE | - SNDRV_PCM_FMTBIT_U24_LE | SNDRV_PCM_FMTBIT_U24_BE | - SNDRV_PCM_FMTBIT_S24_3LE | SNDRV_PCM_FMTBIT_U24_3LE | - SNDRV_PCM_FMTBIT_S24_3BE | SNDRV_PCM_FMTBIT_U24_3BE; - case 32: - return SNDRV_PCM_FMTBIT_S32_LE | SNDRV_PCM_FMTBIT_S32_BE | - SNDRV_PCM_FMTBIT_U32_LE | SNDRV_PCM_FMTBIT_U32_BE; - default: - return 0; - } -} - static int get_port_masks(struct sdw_slave *sdw, unsigned int port, struct snd_pcm_substream *substream, u64 *word_mask, unsigned int *ch_mask) @@ -1564,7 +1544,7 @@ static int get_port_masks(struct sdw_slave *sdw, unsigned int port, if (prop[i].num_words) { for (j = 0; j < prop[i].num_words; j++) - *word_mask |= get_word_mask(prop[i].words[j]); + *word_mask |= width_find_mask(prop[i].words[j]); } else { unsigned int max = prop[i].max_word; @@ -1572,7 +1552,7 @@ static int get_port_masks(struct sdw_slave *sdw, unsigned int port, max = 32; for (j = MAX(1, prop[i].min_word); j <= max; j++) - *word_mask |= get_word_mask(j); + *word_mask |= width_find_mask(j); } /* Only handle the number of channels for constraints. */ diff --git a/sound/soc/sdca/sdca_fdl.c b/sound/soc/sdca/sdca_fdl.c index 7fc809707944d0..6c34e68fe729dd 100644 --- a/sound/soc/sdca/sdca_fdl.c +++ b/sound/soc/sdca/sdca_fdl.c @@ -147,47 +147,77 @@ int sdca_fdl_sync(struct device *dev, struct sdca_function_data *function, } EXPORT_SYMBOL_NS_GPL(sdca_fdl_sync, "SND_SOC_SDCA"); -static char *fdl_get_sku_filename(struct device *dev, - struct sdca_fdl_file *fdl_file) +static int fdl_get_sku_filename(struct sdca_interrupt *interrupt, + struct sdca_fdl_file *fdl_file, + char **disk_filename, + char **fallback_filename) { - struct device *parent = dev; + unsigned int adr = interrupt->function->desc->adr; + char extension[sizeof("fe0000v00/")] = ""; + struct device *parent = interrupt->dev; const char *product_vendor; const char *product_sku; + unsigned int id = 0, version = 0; + + regmap_read(interrupt->function_regmap, + SDW_SDCA_CTL(adr, SDCA_ENTITY_TYPE_ENTITY_0, + SDCA_CTL_ENTITY_0_FUNCTION_EXTENSION_ID, 0), + &id); + regmap_read(interrupt->function_regmap, + SDW_SDCA_CTL(adr, SDCA_ENTITY_TYPE_ENTITY_0, + SDCA_CTL_ENTITY_0_FUNCTION_EXTENSION_VERSION, 0), + &version); + + if (id || version) + snprintf(extension, sizeof(extension), "fe%xv%x/", id, version); /* * Try to find pci_dev manually because the card may not be ready to be * used for snd_soc_card_get_pci_ssid yet */ - while (parent) { - if (dev_is_pci(parent)) { - struct pci_dev *pci_dev = to_pci_dev(parent); - - return kasprintf(GFP_KERNEL, "sdca/%x/%x/%x/%x.bin", - fdl_file->vendor_id, - pci_dev->subsystem_vendor, - pci_dev->subsystem_device, - fdl_file->file_id); - } else { - parent = parent->parent; - } + while (parent && !dev_is_pci(parent)) + parent = parent->parent; + + if (parent) { + struct pci_dev *pci_dev = to_pci_dev(parent); + + *disk_filename = kasprintf(GFP_KERNEL, "sdca/%x/%x/%x/%s%x.bin", + fdl_file->vendor_id, + pci_dev->subsystem_vendor, + pci_dev->subsystem_device, + extension, fdl_file->file_id); + } else { + product_vendor = dmi_get_system_info(DMI_SYS_VENDOR); + if (!product_vendor || !strcmp(product_vendor, "Default string")) + product_vendor = dmi_get_system_info(DMI_BOARD_VENDOR); + if (!product_vendor || !strcmp(product_vendor, "Default string")) + product_vendor = dmi_get_system_info(DMI_CHASSIS_VENDOR); + if (!product_vendor) + product_vendor = "unknown"; + + product_sku = dmi_get_system_info(DMI_PRODUCT_SKU); + if (!product_sku || !strcmp(product_sku, "Default string")) + product_sku = dmi_get_system_info(DMI_PRODUCT_NAME); + if (!product_sku) + product_sku = "unknown"; + + *disk_filename = kasprintf(GFP_KERNEL, "sdca/%x/%s/%s/%s%x.bin", + fdl_file->vendor_id, product_vendor, + product_sku, extension, + fdl_file->file_id); + } + + *fallback_filename = kasprintf(GFP_KERNEL, "sdca/%x/%s%x.bin", + fdl_file->vendor_id, extension, + fdl_file->file_id); + + if (!*disk_filename || !*fallback_filename) { + kfree(*disk_filename); + kfree(*fallback_filename); + return -ENOMEM; } - product_vendor = dmi_get_system_info(DMI_SYS_VENDOR); - if (!product_vendor || !strcmp(product_vendor, "Default string")) - product_vendor = dmi_get_system_info(DMI_BOARD_VENDOR); - if (!product_vendor || !strcmp(product_vendor, "Default string")) - product_vendor = dmi_get_system_info(DMI_CHASSIS_VENDOR); - if (!product_vendor) - product_vendor = "unknown"; - - product_sku = dmi_get_system_info(DMI_PRODUCT_SKU); - if (!product_sku || !strcmp(product_sku, "Default string")) - product_sku = dmi_get_system_info(DMI_PRODUCT_NAME); - if (!product_sku) - product_sku = "unknown"; - - return kasprintf(GFP_KERNEL, "sdca/%x/%s/%s/%x.bin", fdl_file->vendor_id, - product_vendor, product_sku, fdl_file->file_id); + return 0; } static int fdl_load_file(struct sdca_interrupt *interrupt, @@ -197,7 +227,9 @@ static int fdl_load_file(struct sdca_interrupt *interrupt, struct sdca_fdl_data *fdl_data = &interrupt->function->fdl_data; struct acpi_sw_file *swf = NULL, *tmp; struct sdca_fdl_file *fdl_file; - char *disk_filename; + const char *source = "ACPI SWFT"; + const char *disk_source; + char *disk_filename, *fallback_filename; int ret; if (!set) { @@ -231,25 +263,17 @@ static int fdl_load_file(struct sdca_interrupt *interrupt, } } - disk_filename = fdl_get_sku_filename(dev, fdl_file); - if (!disk_filename) - return -ENOMEM; - - dev_dbg(dev, "FDL disk filename: %s\n", disk_filename); + ret = fdl_get_sku_filename(interrupt, fdl_file, + &disk_filename, &fallback_filename); + if (ret) + return ret; const struct firmware *firmware __free(firmware) = NULL; + disk_source = disk_filename; ret = firmware_request_nowarn(&firmware, disk_filename, dev); - kfree(disk_filename); if (ret) { - disk_filename = kasprintf(GFP_KERNEL, "sdca/%x/%x.bin", - fdl_file->vendor_id, fdl_file->file_id); - if (!disk_filename) - return -ENOMEM; - - dev_dbg(dev, "FDL disk filename: %s\n", disk_filename); - - ret = firmware_request_nowarn(&firmware, disk_filename, dev); - kfree(disk_filename); + disk_source = fallback_filename; + ret = firmware_request_nowarn(&firmware, fallback_filename, dev); } if (!ret) { @@ -259,25 +283,35 @@ static int fdl_load_file(struct sdca_interrupt *interrupt, tmp->file_length != firmware->size) { dev_err(dev, "bad disk SWF size\n"); } else if (!swf || swf->file_version <= tmp->file_version) { - dev_dbg(dev, "using SWF from disk\n"); swf = tmp; + source = disk_source; } } if (!swf) { - dev_err(dev, "failed to locate SWF\n"); - return -ENOENT; + dev_err(dev, "failed to locate SWF: %x-%x\n" + "Attempted FDL disk filename: %s\n" + "Attempted FDL fallback filename: %s\n", + fdl_file->vendor_id, fdl_file->file_id, + disk_filename, fallback_filename); + ret = -ENOENT; + } else { + dev_info(dev, "loading SWF: %x-%x-%x from %s\n", + swf->vendor_id, swf->file_id, swf->file_version, source); + + ret = sdca_ump_write_message(dev, interrupt->device_regmap, + interrupt->function_regmap, + interrupt->function, interrupt->entity, + SDCA_CTL_XU_FDL_MESSAGEOFFSET, + fdl_file->fdl_offset, + SDCA_CTL_XU_FDL_MESSAGELENGTH, swf->data, + swf->file_length - + offsetof(struct acpi_sw_file, data)); } - dev_info(dev, "loading SWF: %x-%x-%x\n", - swf->vendor_id, swf->file_id, swf->file_version); + kfree(disk_filename); + kfree(fallback_filename); - ret = sdca_ump_write_message(dev, interrupt->device_regmap, - interrupt->function_regmap, - interrupt->function, interrupt->entity, - SDCA_CTL_XU_FDL_MESSAGEOFFSET, fdl_file->fdl_offset, - SDCA_CTL_XU_FDL_MESSAGELENGTH, swf->data, - swf->file_length - offsetof(struct acpi_sw_file, data)); return ret; } diff --git a/sound/soc/soc-card.c b/sound/soc/soc-card.c index 6137662cdb484b..6cd48e18ad3868 100644 --- a/sound/soc/soc-card.c +++ b/sound/soc/soc-card.c @@ -876,12 +876,8 @@ static void snd_soc_remove_device_links(struct snd_soc_card *card) { struct snd_soc_component *component; - for_each_card_components(card, component) { - if (component->card_device_link) { - device_link_del(component->card_device_link); - component->card_device_link = NULL; - } - } + for_each_card_components(card, component) + snd_soc_component_device_link_del(component); } void snd_soc_card_unbind(struct snd_soc_card *card, bool reuse) @@ -1038,18 +1034,8 @@ static int snd_soc_card_bind(struct snd_soc_card *card) * If a driver pair already have a link in the opposite direction * they must manage their own suspend order. */ - for_each_card_components(card, component) { - if (card->dev == component->dev) - continue; - - component->card_device_link = device_link_add(card->dev, - component->dev, - DL_FLAG_STATELESS); - if (!component->card_device_link) { - dev_warn(card->dev, "Could not create device link to %s\n", - dev_name(component->dev)); - } - } + for_each_card_components(card, component) + snd_soc_component_device_link_add(component); ret = snd_soc_card_late_probe(card); if (ret < 0) diff --git a/sound/soc/soc-component.c b/sound/soc/soc-component.c index a6e280c798f3dd..de3218bb2b2a8d 100644 --- a/sound/soc/soc-component.c +++ b/sound/soc/soc-component.c @@ -43,6 +43,12 @@ const char *snd_soc_component_name(struct snd_soc_component *component) } EXPORT_SYMBOL_GPL(snd_soc_component_name); +const char *snd_soc_component_name_prefix(struct snd_soc_component *component) +{ + return component->name_prefix; +} +EXPORT_SYMBOL_GPL(snd_soc_component_name_prefix); + void snd_soc_component_set_priv(struct snd_soc_component *component, void *priv) { component->priv = priv; @@ -55,18 +61,95 @@ void *snd_soc_component_to_priv(struct snd_soc_component *component) } EXPORT_SYMBOL_GPL(snd_soc_component_to_priv); +struct device *snd_soc_component_to_dev(struct snd_soc_component *component) +{ + return component->dev; +} +EXPORT_SYMBOL_GPL(snd_soc_component_to_dev); + struct snd_soc_dapm_context *snd_soc_component_to_dapm(struct snd_soc_component *component) { return component->dapm; } EXPORT_SYMBOL_GPL(snd_soc_component_to_dapm); +const struct snd_soc_component_driver * +snd_soc_component_to_driver(struct snd_soc_component *component) +{ + return component->driver; +} +EXPORT_SYMBOL_GPL(snd_soc_component_to_driver); + +struct snd_soc_card *snd_soc_component_to_card(struct snd_soc_component *component) +{ + return component->card; +} +EXPORT_SYMBOL_GPL(snd_soc_component_to_card); + +struct dentry *snd_soc_component_to_debugfs_root(struct snd_soc_component *component) +{ + return component->debugfs_root; +} +EXPORT_SYMBOL_GPL(snd_soc_component_to_debugfs_root); + +struct regmap *snd_soc_component_to_regmap(struct snd_soc_component *component) +{ + return component->regmap; +} +EXPORT_SYMBOL_GPL(snd_soc_component_to_regmap); + unsigned int snd_soc_component_active(struct snd_soc_component *component) { return component->active; } EXPORT_SYMBOL_GPL(snd_soc_component_active); +void snd_soc_component_active_update(struct snd_soc_component *component, int action) +{ + component->active += action; +} + +int snd_soc_component_num_dai(struct snd_soc_component *component) +{ + return component->num_dai; +} +EXPORT_SYMBOL_GPL(snd_soc_component_num_dai); + +void snd_soc_component_connect_dai(struct snd_soc_component *component, struct snd_soc_dai *dai) +{ + /* dai->list <-> component->dai_list */ + list_add_tail(snd_soc_dai_to_list(dai), &component->dai_list); + component->num_dai++; +} + +void snd_soc_component_device_link_del(struct snd_soc_component *component) +{ + if (component->card_device_link) { + device_link_del(component->card_device_link); + component->card_device_link = NULL; + } +} + +int snd_soc_component_device_link_add(struct snd_soc_component *component) +{ + struct snd_soc_card *card = snd_soc_component_to_card(component); + struct device *card_dev = card->dev; + struct device *component_dev = snd_soc_component_to_dev(component); + + if (card_dev == component_dev) + return 0; + + component->card_device_link = device_link_add(card_dev, component_dev, + DL_FLAG_STATELESS); + if (!component->card_device_link) { + dev_warn(card_dev, "Could not create device link to %s\n", + dev_name(component_dev)); + return -EINVAL; + } + + return 0; +} + /* * We might want to check substream by using list. * In such case, we can update these macros. @@ -386,7 +469,60 @@ int snd_soc_component_of_xlate_dai_name(struct snd_soc_component *component, return -ENOTSUPP; } -int snd_soc_component_regmap_val_bytes(struct snd_soc_component *component) +#ifdef CONFIG_REGMAP + +/** + * snd_soc_component_regmap_init() - Initialize regmap instance for the + * component + * @component: The component for which to initialize the regmap instance + * @regmap: The regmap instance that should be used by the component + * + * This function allows deferred assignment of the regmap instance that is + * associated with the component. Only use this if the regmap instance is not + * yet ready when the component is registered. The function must also be called + * before the first IO attempt of the component. + */ +void snd_soc_component_regmap_init(struct snd_soc_component *component, + struct regmap *regmap) +{ + component->regmap = regmap; +} +EXPORT_SYMBOL_GPL(snd_soc_component_regmap_init); + +/** + * snd_soc_component_regmap_exit() - De-initialize regmap instance for the + * component + * @component: The component for which to de-initialize the regmap instance + * + * Calls regmap_exit() on the regmap instance associated to the component and + * removes the regmap instance from the component. + * + * This function should only be used if snd_soc_component_regmap_init() was used + * to initialize the regmap instance. + */ +void snd_soc_component_regmap_exit(struct snd_soc_component *component) +{ + regmap_exit(component->regmap); + component->regmap = NULL; +} +EXPORT_SYMBOL_GPL(snd_soc_component_regmap_exit); + +int snd_soc_component_regmap_multi_reg_write_bypassed(struct snd_soc_component *component, + const struct reg_sequence *regs, + int num_regs) +{ + struct regmap *regmap = component->regmap; + + if (!regmap) + return 0; + + return regmap_multi_reg_write_bypassed(regmap, regs, num_regs); +} +EXPORT_SYMBOL_GPL(snd_soc_component_regmap_multi_reg_write_bypassed); + +#endif + +int snd_soc_component_regmap_get_val_bytes(struct snd_soc_component *component) { int val_bytes; @@ -401,22 +537,7 @@ int snd_soc_component_regmap_val_bytes(struct snd_soc_component *component) return val_bytes; } -EXPORT_SYMBOL_GPL(snd_soc_component_regmap_val_bytes); - -/** - * snd_soc_component_regmap_cache_sync() - Sync the register cache with the hardware - * @component: COMPONENT to sync - * - * Note: This function will call regcache_sync() - */ -int snd_soc_component_regmap_cache_sync(struct snd_soc_component *component) -{ - if (!component->regmap) - return 0; - - return regcache_sync(component->regmap); -} -EXPORT_SYMBOL_GPL(snd_soc_component_regmap_cache_sync); +EXPORT_SYMBOL_GPL(snd_soc_component_regmap_get_val_bytes); /** * snd_soc_component_regmap_async_complete() - Ensure asynchronous I/O has completed @@ -432,45 +553,47 @@ void snd_soc_component_regmap_async_complete(struct snd_soc_component *component } EXPORT_SYMBOL_GPL(snd_soc_component_regmap_async_complete); -#ifdef CONFIG_REGMAP - /** - * snd_soc_component_init_regmap() - Initialize regmap instance for the - * component - * @component: The component for which to initialize the regmap instance - * @regmap: The regmap instance that should be used by the component + * snd_soc_component_regcache_sync() - Sync the register cache with the hardware + * @component: COMPONENT to sync * - * This function allows deferred assignment of the regmap instance that is - * associated with the component. Only use this if the regmap instance is not - * yet ready when the component is registered. The function must also be called - * before the first IO attempt of the component. + * Note: This function will call regcache_sync() */ -void snd_soc_component_init_regmap(struct snd_soc_component *component, - struct regmap *regmap) +int snd_soc_component_regcache_sync(struct snd_soc_component *component) { - component->regmap = regmap; + if (!component->regmap) + return 0; + + return regcache_sync(component->regmap); } -EXPORT_SYMBOL_GPL(snd_soc_component_init_regmap); +EXPORT_SYMBOL_GPL(snd_soc_component_regcache_sync); -/** - * snd_soc_component_exit_regmap() - De-initialize regmap instance for the - * component - * @component: The component for which to de-initialize the regmap instance - * - * Calls regmap_exit() on the regmap instance associated to the component and - * removes the regmap instance from the component. - * - * This function should only be used if snd_soc_component_init_regmap() was used - * to initialize the regmap instance. - */ -void snd_soc_component_exit_regmap(struct snd_soc_component *component) +void snd_soc_component_regcache_mark_dirty(struct snd_soc_component *component) { - regmap_exit(component->regmap); - component->regmap = NULL; + struct regmap *regmap = component->regmap; + + if (regmap) + regcache_mark_dirty(regmap); } -EXPORT_SYMBOL_GPL(snd_soc_component_exit_regmap); +EXPORT_SYMBOL_GPL(snd_soc_component_regcache_mark_dirty); -#endif +void snd_soc_component_regcache_cache_only(struct snd_soc_component *component, bool enable) +{ + struct regmap *regmap = component->regmap; + + if (regmap) + regcache_cache_only(regmap, enable); +} +EXPORT_SYMBOL_GPL(snd_soc_component_regcache_cache_only); + +void snd_soc_component_regcache_cache_bypass(struct snd_soc_component *component, bool enable) +{ + struct regmap *regmap = component->regmap; + + if (regmap) + regcache_cache_bypass(regmap, enable); +} +EXPORT_SYMBOL_GPL(snd_soc_component_regcache_cache_bypass); int snd_soc_component_compr_open(struct snd_soc_component *component, struct snd_compr_stream *cstream) @@ -1553,3 +1676,300 @@ struct snd_soc_component *snd_soc_component_lookup_by_name(const char *component return NULL; } EXPORT_SYMBOL_GPL(snd_soc_component_lookup_by_name); + +/** + * snd_soc_unregister_dais - Unregister DAIs from the ASoC core + * + * @component: The component for which the DAIs should be unregistered + */ +static void snd_soc_unregister_dais(struct snd_soc_component *component) +{ + struct snd_soc_dai *dai, *_dai; + + for_each_component_dais_safe(component, dai, _dai) + snd_soc_unregister_dai(dai); +} + +/** + * snd_soc_register_dais - Register a DAI with the ASoC core + * + * @component: The component the DAIs are registered for + * @dai_drv: DAI driver to use for the DAIs + * @count: Number of DAIs + */ +static int snd_soc_register_dais(struct snd_soc_component *component, + struct snd_soc_dai_driver *dai_drv, + size_t count) +{ + struct snd_soc_dai *dai; + unsigned int i; + int ret; + + for (i = 0; i < count; i++) { + dai = snd_soc_register_dai(component, dai_drv + i, count == 1 && + component->driver->legacy_dai_naming); + if (dai == NULL) { + ret = -ENOMEM; + goto err; + } + } + + return 0; + +err: + snd_soc_unregister_dais(component); + + return ret; +} + +#define ENDIANNESS_MAP(name) \ + (SNDRV_PCM_FMTBIT_##name##LE | SNDRV_PCM_FMTBIT_##name##BE) +static u64 endianness_format_map[] = { + ENDIANNESS_MAP(S16_), + ENDIANNESS_MAP(U16_), + ENDIANNESS_MAP(S24_), + ENDIANNESS_MAP(U24_), + ENDIANNESS_MAP(S32_), + ENDIANNESS_MAP(U32_), + ENDIANNESS_MAP(S24_3), + ENDIANNESS_MAP(U24_3), + ENDIANNESS_MAP(S20_3), + ENDIANNESS_MAP(U20_3), + ENDIANNESS_MAP(S18_3), + ENDIANNESS_MAP(U18_3), + ENDIANNESS_MAP(FLOAT_), + ENDIANNESS_MAP(FLOAT64_), + ENDIANNESS_MAP(IEC958_SUBFRAME_), +}; + +/* + * Fix up the DAI formats for endianness: codecs don't actually see + * the endianness of the data but we're using the CPU format + * definitions which do need to include endianness so we ensure that + * codec DAIs always have both big and little endian variants set. + */ +static void convert_endianness_formats(struct snd_soc_pcm_stream *stream) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(endianness_format_map); i++) + if (stream->formats & endianness_format_map[i]) + stream->formats |= endianness_format_map[i]; +} + +struct snd_soc_component *snd_soc_component_new(struct device *dev, const char *name, + const struct snd_soc_component_driver *driver) +{ + struct snd_soc_component *component; + + component = devm_kzalloc_obj(dev, *component); + if (!component) + return ERR_PTR(-ENOMEM); + + component->dapm = snd_soc_dapm_alloc(dev); + if (!component->dapm) + return ERR_PTR(-ENOMEM); + + if (!name) { + name = snd_soc_fmt_single_name(dev, NULL); + if (!name) { + dev_err(dev, "ASoC: Failed to allocate name\n"); + return ERR_PTR(-ENOMEM); + } + } + + component->dev = dev; + component->name = name; + component->driver = driver; + + INIT_LIST_HEAD(&component->dai_list); + INIT_LIST_HEAD(&component->dobj_list); + INIT_LIST_HEAD(&component->card_list); + INIT_LIST_HEAD(&component->list); + INIT_LIST_HEAD(&component->card_aux_list); + mutex_init(&component->io_mutex); + + return component; +} +EXPORT_SYMBOL_GPL(snd_soc_component_new); + +static void snd_soc_component_unregister_unlocked(struct snd_soc_component *component) +{ + struct snd_soc_card *card = component->card; + + snd_soc_unregister_dais(component); + + if (card) + snd_soc_card_unbind(card, true); + + list_del(&component->list); +} + +void snd_soc_component_unregister(struct snd_soc_component *component) +{ + guard(mutex)(&client_mutex); + + snd_soc_component_unregister_unlocked(component); +} +EXPORT_SYMBOL_GPL(snd_soc_component_unregister); + +int snd_soc_component_register(struct snd_soc_component *component, + struct snd_soc_dai_driver *dai_drv, + int num_dai) +{ + int ret; + int i; + guard(mutex)(&client_mutex); + + if (component->driver->endianness) { + for (i = 0; i < num_dai; i++) { + convert_endianness_formats(&dai_drv[i].playback); + convert_endianness_formats(&dai_drv[i].capture); + } + } + + ret = snd_soc_register_dais(component, dai_drv, num_dai); + if (ret < 0) { + dev_err(component->dev, "ASoC: Failed to register DAIs: %d\n", + ret); + goto err_cleanup; + } + + if (!component->driver->write && !component->driver->read) { + if (!component->regmap) + component->regmap = dev_get_regmap(component->dev, + NULL); + } + + /* see for_each_component */ + list_add(&component->list, snd_soc_component_get_list_head()); + + snd_soc_card_rebind(); + +err_cleanup: + if (ret < 0) + snd_soc_component_unregister_unlocked(component); + + return ret; +} +EXPORT_SYMBOL_GPL(snd_soc_component_register); + +int snd_soc_register_component(struct device *dev, + const struct snd_soc_component_driver *component_driver, + struct snd_soc_dai_driver *dai_drv, + int num_dai) +{ + struct snd_soc_component *component; + + component = snd_soc_component_new(dev, NULL, component_driver); + if (IS_ERR(component)) + return PTR_ERR(component); + + return snd_soc_component_register(component, dai_drv, num_dai); +} +EXPORT_SYMBOL_GPL(snd_soc_register_component); + +/** + * snd_soc_unregister_component - Unregister component using a given driver + * from the ASoC core + * + * @dev: The device to unregister + */ +void snd_soc_unregister_component(struct device *dev) +{ + guard(mutex)(&client_mutex); + + while (1) { + struct snd_soc_component *component = snd_soc_lookup_component_nolocked(dev, NULL); + + if (!component) + break; + + snd_soc_component_unregister_unlocked(component); + } +} +EXPORT_SYMBOL_GPL(snd_soc_unregister_component); + +static void devm_component_release(struct device *dev, void *res) +{ + struct snd_soc_component **component = res; + + snd_soc_component_unregister(*component); +} + +/** + * devm_snd_soc_register_component - resource managed component registration + * @dev: Device used to manage component + * @cmpnt_drv: Component driver + * @dai_drv: DAI driver + * @num_dai: Number of DAIs to register + * + * Register a component with automatic unregistration when the device is + * unregistered. + */ +int devm_snd_soc_register_component(struct device *dev, + const struct snd_soc_component_driver *cmpnt_drv, + struct snd_soc_dai_driver *dai_drv, int num_dai) +{ + const struct snd_soc_component **ptr; + struct snd_soc_component *component; + int ret = -ENOMEM; + + component = snd_soc_component_new(dev, NULL, cmpnt_drv); + if (IS_ERR(component)) + goto err; + + ptr = devres_alloc(devm_component_release, sizeof(*ptr), GFP_KERNEL); + if (!ptr) + goto free_component; + + ret = snd_soc_component_register(component, dai_drv, num_dai); + if (ret < 0) + goto free_devres; + + *ptr = component; + devres_add(dev, ptr); + + return ret; + +free_devres: + devres_free(ptr); +free_component: + devm_kfree(dev, component); +err: + return ret; +} +EXPORT_SYMBOL_GPL(devm_snd_soc_register_component); + +/** + * snd_soc_component_of_simple_xlate_dai_name - Resolve a sound-dai phandle argument to a + * DAI name by searching the component DAI list. + * @component: ASoC component to search. + * @args: Phandle arguments from the sound-dai property; args[0] is the + * DAI ID. + * @dai_name: Output pointer set to the matched DAI name on success. + * + * Return: 0 on success, -EINVAL if args_count != 1 or no match is found. + */ +int snd_soc_component_of_simple_xlate_dai_name(struct snd_soc_component *component, + const struct of_phandle_args *args, + const char **dai_name) +{ + struct snd_soc_dai *dai; + int id; + + if (args->args_count != 1) + return -EINVAL; + + id = args->args[0]; + + for_each_component_dais(component, dai) { + if (dai->driver->id == id) { + *dai_name = snd_soc_dai_name(dai); + return 0; + } + } + + return -EINVAL; +} +EXPORT_SYMBOL_GPL(snd_soc_component_of_simple_xlate_dai_name); diff --git a/sound/soc/soc-core.c b/sound/soc/soc-core.c index 7dfd79b4ca3e56..894a81b2d98365 100644 --- a/sound/soc/soc-core.c +++ b/sound/soc/soc-core.c @@ -1377,218 +1377,6 @@ char *snd_soc_fmt_multiple_name(struct device *dev, struct snd_soc_dai_driver *d return devm_kstrdup(dev, dai_drv->name, GFP_KERNEL); } -/** - * snd_soc_unregister_dais - Unregister DAIs from the ASoC core - * - * @component: The component for which the DAIs should be unregistered - */ -static void snd_soc_unregister_dais(struct snd_soc_component *component) -{ - struct snd_soc_dai *dai, *_dai; - - for_each_component_dais_safe(component, dai, _dai) - snd_soc_unregister_dai(dai); -} - -/** - * snd_soc_register_dais - Register a DAI with the ASoC core - * - * @component: The component the DAIs are registered for - * @dai_drv: DAI driver to use for the DAIs - * @count: Number of DAIs - */ -static int snd_soc_register_dais(struct snd_soc_component *component, - struct snd_soc_dai_driver *dai_drv, - size_t count) -{ - struct snd_soc_dai *dai; - unsigned int i; - int ret; - - for (i = 0; i < count; i++) { - dai = snd_soc_register_dai(component, dai_drv + i, count == 1 && - component->driver->legacy_dai_naming); - if (dai == NULL) { - ret = -ENOMEM; - goto err; - } - } - - return 0; - -err: - snd_soc_unregister_dais(component); - - return ret; -} - -#define ENDIANNESS_MAP(name) \ - (SNDRV_PCM_FMTBIT_##name##LE | SNDRV_PCM_FMTBIT_##name##BE) -static u64 endianness_format_map[] = { - ENDIANNESS_MAP(S16_), - ENDIANNESS_MAP(U16_), - ENDIANNESS_MAP(S24_), - ENDIANNESS_MAP(U24_), - ENDIANNESS_MAP(S32_), - ENDIANNESS_MAP(U32_), - ENDIANNESS_MAP(S24_3), - ENDIANNESS_MAP(U24_3), - ENDIANNESS_MAP(S20_3), - ENDIANNESS_MAP(U20_3), - ENDIANNESS_MAP(S18_3), - ENDIANNESS_MAP(U18_3), - ENDIANNESS_MAP(FLOAT_), - ENDIANNESS_MAP(FLOAT64_), - ENDIANNESS_MAP(IEC958_SUBFRAME_), -}; - -/* - * Fix up the DAI formats for endianness: codecs don't actually see - * the endianness of the data but we're using the CPU format - * definitions which do need to include endianness so we ensure that - * codec DAIs always have both big and little endian variants set. - */ -static void convert_endianness_formats(struct snd_soc_pcm_stream *stream) -{ - int i; - - for (i = 0; i < ARRAY_SIZE(endianness_format_map); i++) - if (stream->formats & endianness_format_map[i]) - stream->formats |= endianness_format_map[i]; -} - -static void snd_soc_del_component_unlocked(struct snd_soc_component *component) -{ - struct snd_soc_card *card = component->card; - - snd_soc_unregister_dais(component); - - if (card) - snd_soc_card_unbind(card, true); - - list_del(&component->list); -} - -struct snd_soc_component *snd_soc_component_new(struct device *dev, const char *name, - const struct snd_soc_component_driver *driver) -{ - struct snd_soc_component *component; - - component = devm_kzalloc_obj(dev, *component); - if (!component) - return ERR_PTR(-ENOMEM); - - component->dapm = snd_soc_dapm_alloc(dev); - if (!component->dapm) - return ERR_PTR(-ENOMEM); - - if (!name) { - name = snd_soc_fmt_single_name(dev, NULL); - if (!name) { - dev_err(dev, "ASoC: Failed to allocate name\n"); - return ERR_PTR(-ENOMEM); - } - } - - component->dev = dev; - component->name = name; - component->driver = driver; - - INIT_LIST_HEAD(&component->dai_list); - INIT_LIST_HEAD(&component->dobj_list); - INIT_LIST_HEAD(&component->card_list); - INIT_LIST_HEAD(&component->list); - INIT_LIST_HEAD(&component->card_aux_list); - mutex_init(&component->io_mutex); - - return component; -} -EXPORT_SYMBOL_GPL(snd_soc_component_new); - -int snd_soc_component_register(struct snd_soc_component *component, - struct snd_soc_dai_driver *dai_drv, - int num_dai) -{ - int ret; - int i; - guard(mutex)(&client_mutex); - - if (component->driver->endianness) { - for (i = 0; i < num_dai; i++) { - convert_endianness_formats(&dai_drv[i].playback); - convert_endianness_formats(&dai_drv[i].capture); - } - } - - ret = snd_soc_register_dais(component, dai_drv, num_dai); - if (ret < 0) { - dev_err(component->dev, "ASoC: Failed to register DAIs: %d\n", - ret); - goto err_cleanup; - } - - if (!component->driver->write && !component->driver->read) { - if (!component->regmap) - component->regmap = dev_get_regmap(component->dev, - NULL); - } - - /* see for_each_component */ - list_add(&component->list, snd_soc_component_get_list_head()); - - snd_soc_card_rebind(); - -err_cleanup: - if (ret < 0) - snd_soc_del_component_unlocked(component); - - return ret; -} -EXPORT_SYMBOL_GPL(snd_soc_component_register); - -int snd_soc_register_component(struct device *dev, - const struct snd_soc_component_driver *component_driver, - struct snd_soc_dai_driver *dai_drv, - int num_dai) -{ - struct snd_soc_component *component; - - component = snd_soc_component_new(dev, NULL, component_driver); - if (IS_ERR(component)) - return PTR_ERR(component); - - return snd_soc_component_register(component, dai_drv, num_dai); -} -EXPORT_SYMBOL_GPL(snd_soc_register_component); - -/** - * snd_soc_unregister_component_by_driver - Unregister component using a given driver - * from the ASoC core - * - * @dev: The device to unregister - * @component_driver: The component driver to unregister - */ -void snd_soc_unregister_component_by_driver(struct device *dev, - const struct snd_soc_component_driver *component_driver) -{ - const char *driver_name = NULL; - - if (component_driver) - driver_name = component_driver->name; - - guard(mutex)(&client_mutex); - - while (1) { - struct snd_soc_component *component = snd_soc_lookup_component_nolocked(dev, driver_name); - - if (!component) - break; - - snd_soc_del_component_unlocked(component); - } -} -EXPORT_SYMBOL_GPL(snd_soc_unregister_component_by_driver); - /* Retrieve a card's name from device tree */ int snd_soc_of_parse_card_name(struct snd_soc_card *card, const char *propname) @@ -1803,39 +1591,6 @@ int snd_soc_of_parse_tdm_slot(struct device_node *np, } EXPORT_SYMBOL_GPL(snd_soc_of_parse_tdm_slot); -/** - * snd_soc_of_xlate_dai_name - Resolve a sound-dai phandle argument to a - * DAI name by searching the component DAI list. - * @component: ASoC component to search. - * @args: Phandle arguments from the sound-dai property; args[0] is the - * DAI ID. - * @dai_name: Output pointer set to the matched DAI name on success. - * - * Return: 0 on success, -EINVAL if args_count != 1 or no match is found. - */ -int snd_soc_of_xlate_dai_name(struct snd_soc_component *component, - const struct of_phandle_args *args, - const char **dai_name) -{ - struct snd_soc_dai *dai; - int id; - - if (args->args_count != 1) - return -EINVAL; - - id = args->args[0]; - - for_each_component_dais(component, dai) { - if (dai->driver->id == id) { - *dai_name = snd_soc_dai_name(dai); - return 0; - } - } - - return -EINVAL; -} -EXPORT_SYMBOL_GPL(snd_soc_of_xlate_dai_name); - void snd_soc_dlc_use_cpu_as_platform(struct snd_soc_dai_link_component *platforms, struct snd_soc_dai_link_component *cpus) { diff --git a/sound/soc/soc-dai.c b/sound/soc/soc-dai.c index 9e34f34eac3d8a..73aea7291fa73e 100644 --- a/sound/soc/soc-dai.c +++ b/sound/soc/soc-dai.c @@ -713,7 +713,7 @@ void snd_soc_dai_active_update(struct snd_soc_dai *dai, int stream, int action) dai->stream[stream].active += action; /* see snd_soc_component_active() */ - dai->component->active += action; + snd_soc_component_active_update(dai->component, action); } int snd_soc_dai_active(const struct snd_soc_dai *dai) @@ -1265,8 +1265,7 @@ struct snd_soc_dai *snd_soc_dai_register(struct snd_soc_component *component, dai->driver = dai_drv; /* see for_each_component_dais */ - list_add_tail(&dai->list, &component->dai_list); - component->num_dai++; + snd_soc_component_connect_dai(component, dai); dev_dbg(dev, "ASoC: Registered DAI '%s'\n", dai->name); return dai; diff --git a/sound/soc/soc-devres.c b/sound/soc/soc-devres.c index 718165ba84ac87..431bb366468ac9 100644 --- a/sound/soc/soc-devres.c +++ b/sound/soc/soc-devres.c @@ -9,46 +9,6 @@ #include #include -static void devm_component_release(struct device *dev, void *res) -{ - const struct snd_soc_component_driver **cmpnt_drv = res; - - snd_soc_unregister_component_by_driver(dev, *cmpnt_drv); -} - -/** - * devm_snd_soc_register_component - resource managed component registration - * @dev: Device used to manage component - * @cmpnt_drv: Component driver - * @dai_drv: DAI driver - * @num_dai: Number of DAIs to register - * - * Register a component with automatic unregistration when the device is - * unregistered. - */ -int devm_snd_soc_register_component(struct device *dev, - const struct snd_soc_component_driver *cmpnt_drv, - struct snd_soc_dai_driver *dai_drv, int num_dai) -{ - const struct snd_soc_component_driver **ptr; - int ret; - - ptr = devres_alloc(devm_component_release, sizeof(*ptr), GFP_KERNEL); - if (!ptr) - return -ENOMEM; - - ret = snd_soc_register_component(dev, cmpnt_drv, dai_drv, num_dai); - if (ret == 0) { - *ptr = cmpnt_drv; - devres_add(dev, ptr); - } else { - devres_free(ptr); - } - - return ret; -} -EXPORT_SYMBOL_GPL(devm_snd_soc_register_component); - /** * devm_snd_soc_register_card - resource managed card registration * @dev: Device used to manage card @@ -63,43 +23,3 @@ int devm_snd_soc_register_card(struct device *dev, struct snd_soc_card *card) return snd_soc_register_card(card); } EXPORT_SYMBOL_GPL(devm_snd_soc_register_card); - -#ifdef CONFIG_SND_SOC_GENERIC_DMAENGINE_PCM - -static void devm_dmaengine_pcm_release(struct device *dev, void *res) -{ - snd_dmaengine_pcm_unregister(*(struct device **)res); -} - -/** - * devm_snd_dmaengine_pcm_register - resource managed dmaengine PCM registration - * @dev: The parent device for the PCM device - * @config: Platform specific PCM configuration - * @flags: Platform specific quirks - * - * Register a dmaengine based PCM device with automatic unregistration when the - * device is unregistered. - */ -int devm_snd_dmaengine_pcm_register(struct device *dev, - const struct snd_dmaengine_pcm_config *config, unsigned int flags) -{ - struct device **ptr; - int ret; - - ptr = devres_alloc(devm_dmaengine_pcm_release, sizeof(*ptr), GFP_KERNEL); - if (!ptr) - return -ENOMEM; - - ret = snd_dmaengine_pcm_register(dev, config, flags); - if (ret == 0) { - *ptr = dev; - devres_add(dev, ptr); - } else { - devres_free(ptr); - } - - return ret; -} -EXPORT_SYMBOL_GPL(devm_snd_dmaengine_pcm_register); - -#endif diff --git a/sound/soc/soc-generic-dmaengine-pcm.c b/sound/soc/soc-generic-dmaengine-pcm.c index c7523bae45af76..62f86d97668ef4 100644 --- a/sound/soc/soc-generic-dmaengine-pcm.c +++ b/sound/soc/soc-generic-dmaengine-pcm.c @@ -514,11 +514,47 @@ void snd_dmaengine_pcm_unregister(struct device *dev) pcm = snd_soc_component_to_priv(component); - snd_soc_unregister_component_by_driver(dev, component->driver); + snd_soc_component_unregister(component); dmaengine_pcm_release_chan(pcm); kfree(pcm); } EXPORT_SYMBOL_GPL(snd_dmaengine_pcm_unregister); +static void devm_dmaengine_pcm_release(struct device *dev, void *res) +{ + snd_dmaengine_pcm_unregister(*(struct device **)res); +} + +/** + * devm_snd_dmaengine_pcm_register - resource managed dmaengine PCM registration + * @dev: The parent device for the PCM device + * @config: Platform specific PCM configuration + * @flags: Platform specific quirks + * + * Register a dmaengine based PCM device with automatic unregistration when the + * device is unregistered. + */ +int devm_snd_dmaengine_pcm_register(struct device *dev, + const struct snd_dmaengine_pcm_config *config, unsigned int flags) +{ + struct device **ptr; + int ret; + + ptr = devres_alloc(devm_dmaengine_pcm_release, sizeof(*ptr), GFP_KERNEL); + if (!ptr) + return -ENOMEM; + + ret = snd_dmaengine_pcm_register(dev, config, flags); + if (ret == 0) { + *ptr = dev; + devres_add(dev, ptr); + } else { + devres_free(ptr); + } + + return ret; +} +EXPORT_SYMBOL_GPL(devm_snd_dmaengine_pcm_register); + MODULE_DESCRIPTION("ASoC helpers for generic PCM dmaengine API"); MODULE_LICENSE("GPL"); diff --git a/sound/soc/soc-internal.h b/sound/soc/soc-internal.h index e09d283d443a84..e713d13543b2d7 100644 --- a/sound/soc/soc-internal.h +++ b/sound/soc/soc-internal.h @@ -69,6 +69,10 @@ bool snd_soc_component_matches_dlc(struct snd_soc_component *component, void snd_soc_component_remove(struct snd_soc_component *component, int probed); int snd_soc_component_probe(struct snd_soc_component *component, struct snd_soc_card *card); struct list_head *snd_soc_component_get_list_head(void); +void snd_soc_component_connect_dai(struct snd_soc_component *component, struct snd_soc_dai *dai); +void snd_soc_component_active_update(struct snd_soc_component *component, int action); +void snd_soc_component_device_link_del(struct snd_soc_component *component); +int snd_soc_component_device_link_add(struct snd_soc_component *component); #define for_each_component(component) \ list_for_each_entry(component, snd_soc_component_get_list_head(), list) diff --git a/sound/soc/soc-pcm.c b/sound/soc/soc-pcm.c index ef8ccf52798eb6..dac353fec4bcfd 100644 --- a/sound/soc/soc-pcm.c +++ b/sound/soc/soc-pcm.c @@ -374,7 +374,7 @@ void snd_soc_runtime_action(struct snd_soc_pcm_runtime *rtd, for_each_rtd_components(rtd, i, component) { if (component->num_dai) continue; - component->active += action; + snd_soc_component_active_update(component, action); } } EXPORT_SYMBOL_GPL(snd_soc_runtime_action); diff --git a/sound/soc/sof/amd/acp.c b/sound/soc/sof/amd/acp.c index 0d208df621e295..b93330dcf22e8e 100644 --- a/sound/soc/sof/amd/acp.c +++ b/sound/soc/sof/amd/acp.c @@ -1585,6 +1585,12 @@ int amd_sof_acp7x_suspend(struct snd_sof_dev *sdev, u32 target_state) acp_data = sdev->pdata->hw_pdata; + /* snd_sof_prepare() can't detect S4 if FW crashed; reload from disk */ + if (acp_data->asp_carveout_base && + (sdev->fw_state == SOF_FW_CRASHED || + sdev->fw_state == SOF_FW_BOOT_FAILED)) + acp_data->fw_code_carveout_addr = 0; + if (acp_data->is_sdw_dev && check_acp_sdw_enable_status(sdev)) { snd_sof_dsp_write(sdev, ACP_DSP_BAR, ACP7X_ZSC_DSP_CTRL, 1); return acp_dsp_reset(sdev); @@ -1655,6 +1661,11 @@ int amd_sof_acp7x_resume(struct snd_sof_dev *sdev) acp_data = sdev->pdata->hw_pdata; + /* Carveout is unpowered in S4/S5; force a full firmware reload */ + if (acp_data->asp_carveout_base && + sdev->system_suspend_target > SOF_SUSPEND_S3) + acp_data->fw_code_carveout_addr = 0; + if (acp_data->sdw_en_stat) { snd_sof_dsp_write(sdev, ACP_DSP_BAR, ACP7X_ZSC_DSP_CTRL, 0); snd_sof_dsp_write(sdev, ACP_DSP_BAR, ACP7X_PME_EN, 1); diff --git a/sound/soc/sof/amd/pci-acp7x.c b/sound/soc/sof/amd/pci-acp7x.c index 6aa16d1a12b952..e6edefff5ab9d8 100644 --- a/sound/soc/sof/amd/pci-acp7x.c +++ b/sound/soc/sof/amd/pci-acp7x.c @@ -67,6 +67,7 @@ static const struct sof_dev_desc acp7b_desc = { .nocodec_tplg_filename = "sof-acp.tplg", .ops = &sof_acp7x_ops, .ops_init = sof_acp7x_ops_init, + .use_acpi_target_states = true, }; static const struct sof_amd_acp_desc acp7f_chip_info = { @@ -110,6 +111,7 @@ static const struct sof_dev_desc acp7f_desc = { .nocodec_tplg_filename = "sof-acp.tplg", .ops = &sof_acp7x_ops, .ops_init = sof_acp7x_ops_init, + .use_acpi_target_states = true, }; static const struct pci_device_id acp7b_pci_id = { diff --git a/sound/soc/sof/control.c b/sound/soc/sof/control.c index 74d997a4f6203c..a0dfb59534ff25 100644 --- a/sound/soc/sof/control.c +++ b/sound/soc/sof/control.c @@ -15,6 +15,35 @@ #include "sof-priv.h" #include "sof-audio.h" +/* the maximum value as snd_soc_info_volsw() reports it */ +static int sof_mixer_max(const struct soc_mixer_control *sm) +{ + int max = sm->max - sm->min; + + if (sm->platform_max && sm->platform_max < max) + max = sm->platform_max; + + return max; +} + +/* the IPC put handlers do not check the range */ +static int sof_mixer_check_values(const struct soc_mixer_control *sm, + const struct snd_sof_control *scontrol, + const struct snd_ctl_elem_value *ucontrol) +{ + int max = sof_mixer_max(sm); + unsigned int i; + + for (i = 0; i < scontrol->num_channels; i++) { + long val = ucontrol->value.integer.value[i]; + + if (val < 0 || val > max) + return -EINVAL; + } + + return 0; +} + int snd_sof_volume_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { @@ -38,6 +67,11 @@ int snd_sof_volume_put(struct snd_kcontrol *kcontrol, struct snd_soc_component *scomp = scontrol->scomp; struct snd_sof_dev *sdev = snd_soc_component_get_drvdata(scomp); const struct sof_ipc_tplg_ops *tplg_ops = sof_ipc_get_ops(sdev, tplg); + int ret; + + ret = sof_mixer_check_values(sm, scontrol, ucontrol); + if (ret) + return ret; if (tplg_ops && tplg_ops->control && tplg_ops->control->volume_put) return tplg_ops->control->volume_put(scontrol, ucontrol); @@ -50,20 +84,16 @@ int snd_sof_volume_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info struct soc_mixer_control *sm = (struct soc_mixer_control *)kcontrol->private_value; struct snd_sof_control *scontrol = sm->dobj.private; unsigned int channels = scontrol->num_channels; - int platform_max; + int max = sof_mixer_max(sm); - if (!sm->platform_max) - sm->platform_max = sm->max; - platform_max = sm->platform_max; - - if (platform_max == 1 && !strstr(kcontrol->id.name, " Volume")) + if (max == 1 && !strstr(kcontrol->id.name, " Volume")) uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN; else uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER; uinfo->count = channels; uinfo->value.integer.min = 0; - uinfo->value.integer.max = platform_max - sm->min; + uinfo->value.integer.max = max; return 0; } @@ -90,6 +120,11 @@ int snd_sof_switch_put(struct snd_kcontrol *kcontrol, struct snd_soc_component *scomp = scontrol->scomp; struct snd_sof_dev *sdev = snd_soc_component_get_drvdata(scomp); const struct sof_ipc_tplg_ops *tplg_ops = sof_ipc_get_ops(sdev, tplg); + int ret; + + ret = sof_mixer_check_values(sm, scontrol, ucontrol); + if (ret) + return ret; if (tplg_ops && tplg_ops->control && tplg_ops->control->switch_put) return tplg_ops->control->switch_put(scontrol, ucontrol); @@ -120,6 +155,11 @@ int snd_sof_enum_put(struct snd_kcontrol *kcontrol, struct snd_soc_component *scomp = scontrol->scomp; struct snd_sof_dev *sdev = snd_soc_component_get_drvdata(scomp); const struct sof_ipc_tplg_ops *tplg_ops = sof_ipc_get_ops(sdev, tplg); + unsigned int i; + + for (i = 0; i < scontrol->num_channels; i++) + if (ucontrol->value.enumerated.item[i] >= se->items) + return -EINVAL; if (tplg_ops && tplg_ops->control && tplg_ops->control->enum_put) return tplg_ops->control->enum_put(scontrol, ucontrol); @@ -185,7 +225,7 @@ int snd_sof_bytes_ext_volatile_get(struct snd_kcontrol *kcontrol, unsigned int _ struct snd_soc_component *scomp = scontrol->scomp; struct snd_sof_dev *sdev = snd_soc_component_get_drvdata(scomp); const struct sof_ipc_tplg_ops *tplg_ops = sof_ipc_get_ops(sdev, tplg); - int ret, err; + int ret; /* ignore the ext_volatile_get call if the callbacks are not provided */ if (!tplg_ops || !tplg_ops->control || @@ -205,9 +245,7 @@ int snd_sof_bytes_ext_volatile_get(struct snd_kcontrol *kcontrol, unsigned int _ binary_data, size); - err = pm_runtime_put_autosuspend(scomp->dev); - if (err < 0) - dev_err_ratelimited(scomp->dev, "%s: failed to idle %d\n", __func__, err); + pm_runtime_put_autosuspend(scomp->dev); return ret; } diff --git a/sound/soc/sof/imx/imx8.c b/sound/soc/sof/imx/imx8.c index 5cd3f44c90d2bb..80326d2eb1fc04 100644 --- a/sound/soc/sof/imx/imx8.c +++ b/sound/soc/sof/imx/imx8.c @@ -26,19 +26,18 @@ /* imx8ulp macros */ #define FSL_SIP_HIFI_XRDC 0xc200000e -#define SYSCTRL0 0x8 -#define EXECUTE_BIT BIT(13) -#define RESET_BIT BIT(16) -#define HIFI4_CLK_BIT BIT(17) -#define PB_CLK_BIT BIT(18) -#define PLAT_CLK_BIT BIT(19) -#define DEBUG_LOGIC_BIT BIT(25) struct imx8m_chip_data { void __iomem *dap; struct reset_control *run_stall; }; +struct imx8ulp_chip_data { + struct reset_control *run_stall; + struct reset_control *soft_rst; + struct reset_control *dbg_rst; +}; + static int imx8_shutdown(struct snd_sof_dev *sdev) { int ret; @@ -202,42 +201,31 @@ static int imx8m_probe(struct snd_sof_dev *sdev) static int imx8ulp_run(struct snd_sof_dev *sdev) { - struct regmap *regmap = get_chip_pdata(sdev); + struct imx8ulp_chip_data *chip = get_chip_pdata(sdev); - /* Controls the HiFi4 DSP Reset: 1 in reset, 0 out of reset */ - regmap_update_bits(regmap, SYSCTRL0, RESET_BIT, 0); + reset_control_deassert(chip->soft_rst); - /* Reset HiFi4 DSP Debug logic: 1 debug reset, 0 out of reset*/ - regmap_update_bits(regmap, SYSCTRL0, DEBUG_LOGIC_BIT, 0); + /* Release HiFi4 DSP Debug logic */ + reset_control_deassert(chip->dbg_rst); - /* Stall HIFI4 DSP Execution: 1 stall, 0 run */ - regmap_update_bits(regmap, SYSCTRL0, EXECUTE_BIT, 0); + /* Run HIFI4 DSP Execution */ + reset_control_deassert(chip->run_stall); return 0; } static int imx8ulp_reset(struct snd_sof_dev *sdev) { + struct imx8ulp_chip_data *chip = get_chip_pdata(sdev); struct arm_smccc_res smc_res; - struct regmap *regmap; - - regmap = get_chip_pdata(sdev); - - /* HiFi4 Platform Clock Enable: 1 enabled, 0 disabled */ - regmap_update_bits(regmap, SYSCTRL0, PLAT_CLK_BIT, PLAT_CLK_BIT); - /* HiFi4 PBCLK clock enable: 1 enabled, 0 disabled */ - regmap_update_bits(regmap, SYSCTRL0, PB_CLK_BIT, PB_CLK_BIT); - - /* HiFi4 Clock Enable: 1 enabled, 0 disabled */ - regmap_update_bits(regmap, SYSCTRL0, HIFI4_CLK_BIT, HIFI4_CLK_BIT); - - regmap_update_bits(regmap, SYSCTRL0, RESET_BIT, RESET_BIT); + reset_control_assert(chip->soft_rst); usleep_range(1, 2); - /* Stall HIFI4 DSP Execution: 1 stall, 0 not stall */ - regmap_update_bits(regmap, SYSCTRL0, EXECUTE_BIT, EXECUTE_BIT); + /* Stall HIFI4 DSP Execution: */ + reset_control_assert(chip->run_stall); + usleep_range(1, 2); arm_smccc_smc(FSL_SIP_HIFI_XRDC, 0, 0, 0, 0, 0, 0, 0, &smc_res); @@ -248,16 +236,30 @@ static int imx8ulp_reset(struct snd_sof_dev *sdev) static int imx8ulp_probe(struct snd_sof_dev *sdev) { struct imx_common_data *common; - struct regmap *regmap; + struct imx8ulp_chip_data *chip; + + chip = devm_kzalloc(sdev->dev, sizeof(*chip), GFP_KERNEL); + if (!chip) + return -ENOMEM; common = sdev->pdata->hw_pdata; - regmap = syscon_regmap_lookup_by_phandle(sdev->dev->of_node, "fsl,dsp-ctrl"); - if (IS_ERR(regmap)) - return dev_err_probe(sdev->dev, PTR_ERR(regmap), - "failed to fetch dsp ctrl regmap\n"); + chip->run_stall = devm_reset_control_get_exclusive(sdev->dev, "runstall"); + if (IS_ERR(chip->run_stall)) + return dev_err_probe(sdev->dev, PTR_ERR(chip->run_stall), + "failed to get dsp runstall reset control\n"); + + chip->soft_rst = devm_reset_control_get_optional_exclusive(sdev->dev, "softreset"); + if (IS_ERR(chip->soft_rst)) + return dev_err_probe(sdev->dev, PTR_ERR(chip->soft_rst), + "failed to get dsp softreset reset control\n"); - common->chip_pdata = regmap; + chip->dbg_rst = devm_reset_control_get_optional_exclusive(sdev->dev, "dbgreset"); + if (IS_ERR(chip->dbg_rst)) + return dev_err_probe(sdev->dev, PTR_ERR(chip->dbg_rst), + "failed to get dsp dbgreset reset control\n"); + + common->chip_pdata = chip; return 0; } diff --git a/sound/soc/sof/intel/hda-dai.c b/sound/soc/sof/intel/hda-dai.c index 60134d34b0528a..b9e28e79ef82cb 100644 --- a/sound/soc/sof/intel/hda-dai.c +++ b/sound/soc/sof/intel/hda-dai.c @@ -225,13 +225,15 @@ static int __maybe_unused hda_dai_hw_free(struct snd_pcm_substream *substream, { const struct hda_dai_widget_dma_ops *ops = hda_dai_get_ops(substream, cpu_dai); struct hdac_ext_stream *hext_stream; - struct snd_sof_dev *sdev = dai_to_sdev(substream, cpu_dai); + struct snd_sof_dev *sdev; if (!ops) { dev_err(cpu_dai->dev, "DAI widget ops not set\n"); return -EINVAL; } + sdev = dai_to_sdev(substream, cpu_dai); + hext_stream = ops->get_hext_stream(sdev, cpu_dai, substream); if (!hext_stream) return 0; @@ -248,14 +250,16 @@ static int __maybe_unused hda_dai_hw_params_data(struct snd_pcm_substream *subst struct snd_soc_dapm_widget *w = snd_soc_dai_get_widget(dai, substream->stream); const struct hda_dai_widget_dma_ops *ops = hda_dai_get_ops(substream, dai); struct hdac_ext_stream *hext_stream; - struct snd_sof_dev *sdev = widget_to_sdev(w); + struct snd_sof_dev *sdev; int ret; if (!ops) { - dev_err(sdev->dev, "DAI widget ops not set\n"); + dev_err(dai->dev, "DAI widget ops not set\n"); return -EINVAL; } + sdev = widget_to_sdev(w); + hext_stream = ops->get_hext_stream(sdev, dai, substream); if (hext_stream && hext_stream->link_prepared) return 0; diff --git a/sound/soc/sof/ipc4-fw-reg.h b/sound/soc/sof/ipc4-fw-reg.h index 7b85a364a6a6c4..b8d1588169c028 100644 --- a/sound/soc/sof/ipc4-fw-reg.h +++ b/sound/soc/sof/ipc4-fw-reg.h @@ -57,7 +57,7 @@ struct sof_ipc4_llp_reading { } __packed __aligned(4); /** - * struct of sof_ipc4_llp_reading_extended - Extended llp info + * struct sof_ipc4_llp_reading_extended - Extended llp info * @llp_reading: Llp information in memory window * @tpd_low: Total processed data (low part) * @tpd_high: Total processed data (high part) diff --git a/sound/soc/sof/ipc4-mtrace.c b/sound/soc/sof/ipc4-mtrace.c index 4eaa6e110a08ce..aab51217cdf61d 100644 --- a/sound/soc/sof/ipc4-mtrace.c +++ b/sound/soc/sof/ipc4-mtrace.c @@ -206,14 +206,17 @@ static ssize_t sof_ipc4_mtrace_dfs_read(struct file *file, char __user *buffer, /* Read data between read pointer and write pointer */ sof_mailbox_read(sdev, log_buffer_offset + read_ptr, log_buffer, avail); } else { + /* avail may have been cut to the user's count above */ + u32 tail = min(avail, log_buffer_size - read_ptr); + /* read from read pointer to end of the slot */ sof_mailbox_read(sdev, log_buffer_offset + read_ptr, log_buffer, - avail - write_ptr); - /* read from slot start to write pointer */ - if (write_ptr) + tail); + /* read the rest from slot start */ + if (avail > tail) sof_mailbox_read(sdev, log_buffer_offset, - (u8 *)(log_buffer) + avail - write_ptr, - write_ptr); + (u8 *)(log_buffer) + tail, + avail - tail); } /* first write the number of bytes we have gathered */ diff --git a/sound/soc/sof/sof-client-ipc-flood-test.c b/sound/soc/sof/sof-client-ipc-flood-test.c index 0e8a0262b795ac..b0d8419addc72b 100644 --- a/sound/soc/sof/sof-client-ipc-flood-test.c +++ b/sound/soc/sof/sof-client-ipc-flood-test.c @@ -157,7 +157,6 @@ static ssize_t sof_ipc_flood_dfs_write(struct file *file, const char __user *buf unsigned long ipc_duration_ms = 0; bool flood_duration_test = false; unsigned long ipc_count = 0; - int err; char *string; int ret; @@ -223,9 +222,7 @@ static ssize_t sof_ipc_flood_dfs_write(struct file *file, const char __user *buf ret = sof_debug_ipc_flood_test(cdev, flood_duration_test, ipc_duration_ms, ipc_count); - err = pm_runtime_put_autosuspend(dev); - if (err < 0) - dev_err_ratelimited(dev, "debugfs write failed to idle %d\n", err); + pm_runtime_put_autosuspend(dev); /* return count if test is successful */ if (ret >= 0) diff --git a/sound/soc/sof/sof-client-ipc-kernel-injector.c b/sound/soc/sof/sof-client-ipc-kernel-injector.c index b5bca9258f4251..16deb117b7b955 100644 --- a/sound/soc/sof/sof-client-ipc-kernel-injector.c +++ b/sound/soc/sof/sof-client-ipc-kernel-injector.c @@ -66,9 +66,7 @@ static ssize_t sof_kernel_msg_inject_dfs_write(struct file *file, const char __u if (!ret) sof_client_ipc_rx_message(cdev, hdr, priv->kernel_buffer); - ret = pm_runtime_put_autosuspend(dev); - if (ret < 0) - dev_err_ratelimited(dev, "debugfs write failed to idle %d\n", ret); + pm_runtime_put_autosuspend(dev); return count; }; diff --git a/sound/soc/sof/sof-client-ipc-msg-injector.c b/sound/soc/sof/sof-client-ipc-msg-injector.c index c98307cf7eeee6..bd10fb39457aae 100644 --- a/sound/soc/sof/sof-client-ipc-msg-injector.c +++ b/sound/soc/sof/sof-client-ipc-msg-injector.c @@ -122,7 +122,7 @@ static int sof_msg_inject_send_message(struct sof_client_dev *cdev) { struct sof_msg_inject_priv *priv = cdev->data; struct device *dev = &cdev->auxdev.dev; - int ret, err; + int ret; ret = pm_runtime_resume_and_get(dev); if (ret < 0 && ret != -EACCES) { @@ -140,9 +140,7 @@ static int sof_msg_inject_send_message(struct sof_client_dev *cdev) dev_err(dev, "IPC message send failed: %d\n", ret); } - err = pm_runtime_put_autosuspend(dev); - if (err < 0) - dev_err_ratelimited(dev, "debugfs write failed to idle %d\n", err); + pm_runtime_put_autosuspend(dev); return ret; } diff --git a/sound/soc/sof/sof-client-probes.c b/sound/soc/sof/sof-client-probes.c index 286486945abd4f..b3ae232e578a6e 100644 --- a/sound/soc/sof/sof-client-probes.c +++ b/sound/soc/sof/sof-client-probes.c @@ -211,7 +211,7 @@ static ssize_t sof_probes_dfs_points_read(struct file *file, char __user *to, int remaining, offset; size_t num_desc; char *buf; - int i, ret, err; + int i, ret; if (priv->extractor_stream_tag == SOF_PROBES_INVALID_NODE_ID) { dev_warn(dev, "no extractor stream running\n"); @@ -258,9 +258,7 @@ static ssize_t sof_probes_dfs_points_read(struct file *file, char __user *to, kfree(desc); pm_error: - err = pm_runtime_put_autosuspend(dev); - if (err < 0) - dev_err_ratelimited(dev, "debugfs read failed to idle %d\n", err); + pm_runtime_put_autosuspend(dev); exit: kfree(buf); @@ -294,7 +292,7 @@ sof_probes_dfs_points_write(struct file *file, const char __user *from, struct sof_probe_point_desc *desc; u32 num_elems, *array; size_t bytes; - int ret, err; + int ret; if (priv->extractor_stream_tag == SOF_PROBES_INVALID_NODE_ID) { dev_warn(dev, "no extractor stream running\n"); @@ -327,9 +325,7 @@ sof_probes_dfs_points_write(struct file *file, const char __user *from, ret = count; } - err = pm_runtime_put_autosuspend(dev); - if (err < 0) - dev_err_ratelimited(dev, "debugfs write failed to idle %d\n", err); + pm_runtime_put_autosuspend(dev); exit: kfree(array); return ret; @@ -360,7 +356,7 @@ sof_probes_dfs_points_remove_write(struct file *file, const char __user *from, struct sof_probes_priv *priv = cdev->data; const struct sof_probes_ipc_ops *ipc = priv->ipc_ops; struct device *dev = &cdev->auxdev.dev; - int ret, err; + int ret; u32 *array; if (priv->extractor_stream_tag == SOF_PROBES_INVALID_NODE_ID) { @@ -385,9 +381,7 @@ sof_probes_dfs_points_remove_write(struct file *file, const char __user *from, ret = count; } - err = pm_runtime_put_autosuspend(dev); - if (err < 0) - dev_err_ratelimited(dev, "debugfs write failed to idle %d\n", err); + pm_runtime_put_autosuspend(dev); exit: kfree(array); return ret; diff --git a/sound/soc/sti/sti_uniperif.c b/sound/soc/sti/sti_uniperif.c index 3fbd9fee94acab..d30d5b3efad6c4 100644 --- a/sound/soc/sti/sti_uniperif.c +++ b/sound/soc/sti/sti_uniperif.c @@ -425,7 +425,7 @@ static int sti_uniperiph_cpu_dai_of(struct device_node *node, uni->irq = platform_get_irq(priv->pdev, 0); if (uni->irq < 0) - return -ENXIO; + return uni->irq; uni->type = dev_data->type; diff --git a/sound/soc/sti/uniperif_player.c b/sound/soc/sti/uniperif_player.c index 23c6f9e513c121..f5abbfd91b114f 100644 --- a/sound/soc/sti/uniperif_player.c +++ b/sound/soc/sti/uniperif_player.c @@ -117,7 +117,6 @@ static irqreturn_t uni_player_irq_handler(int irq, void *dev_id) if (!player->underflow_enabled) { dev_err(player->dev, "unexpected Underflow recovering\n"); - ret = -EPERM; snd_pcm_stream_unlock(player->substream); return ret; } diff --git a/sound/soc/stm/stm32_i2s.c b/sound/soc/stm/stm32_i2s.c index 79465be82cb8b4..e6e861a957dc70 100644 --- a/sound/soc/stm/stm32_i2s.c +++ b/sound/soc/stm/stm32_i2s.c @@ -1255,13 +1255,6 @@ static int stm32_i2s_parse_dt(struct platform_device *pdev, return 0; } -static void stm32_i2s_remove(struct platform_device *pdev) -{ - snd_dmaengine_pcm_unregister(&pdev->dev); - snd_soc_unregister_component(&pdev->dev); - pm_runtime_disable(&pdev->dev); -} - static int stm32_i2s_probe(struct platform_device *pdev) { struct stm32_i2s_data *i2s; @@ -1301,56 +1294,50 @@ static int stm32_i2s_probe(struct platform_device *pdev) if (ret) return ret; - ret = snd_dmaengine_pcm_register(&pdev->dev, &stm32_i2s_pcm_config, 0); + ret = devm_pm_runtime_enable(&pdev->dev); if (ret) return ret; - ret = snd_soc_register_component(&pdev->dev, &stm32_i2s_component, - i2s->dai_drv, 1); - if (ret) { - snd_dmaengine_pcm_unregister(&pdev->dev); + ret = devm_snd_dmaengine_pcm_register(&pdev->dev, &stm32_i2s_pcm_config, 0); + if (ret) + return ret; + + ret = devm_snd_soc_register_component(&pdev->dev, &stm32_i2s_component, + i2s->dai_drv, 1); + if (ret) return ret; - } /* Set SPI/I2S in i2s mode */ ret = regmap_update_bits(i2s->regmap, STM32_I2S_CGFR_REG, I2S_CGFR_I2SMOD, I2S_CGFR_I2SMOD); if (ret) - goto error; + return ret; ret = regmap_read(i2s->regmap, STM32_I2S_IPIDR_REG, &val); if (ret) - goto error; + return ret; if (val == I2S_IPIDR_NUMBER) { ret = regmap_read(i2s->regmap, STM32_I2S_HWCFGR_REG, &val); if (ret) - goto error; + return ret; if (!FIELD_GET(I2S_HWCFGR_I2S_SUPPORT_MASK, val)) { dev_err(&pdev->dev, "Device does not support i2s mode\n"); - ret = -EPERM; - goto error; + return -EPERM; } ret = regmap_read(i2s->regmap, STM32_I2S_VERR_REG, &val); if (ret) - goto error; + return ret; dev_dbg(&pdev->dev, "I2S version: %lu.%lu registered\n", FIELD_GET(I2S_VERR_MAJ_MASK, val), FIELD_GET(I2S_VERR_MIN_MASK, val)); } - pm_runtime_enable(&pdev->dev); - - return ret; - -error: - stm32_i2s_remove(pdev); - - return ret; + return 0; } MODULE_DEVICE_TABLE(of, stm32_i2s_ids); @@ -1384,7 +1371,6 @@ static struct platform_driver stm32_i2s_driver = { .pm = pm_ptr(&stm32_i2s_pm_ops), }, .probe = stm32_i2s_probe, - .remove = stm32_i2s_remove, }; module_platform_driver(stm32_i2s_driver); diff --git a/sound/soc/sunxi/sun8i-codec-analog.c b/sound/soc/sunxi/sun8i-codec-analog.c index 3335855c6311e3..e24fd7bd0613f3 100644 --- a/sound/soc/sunxi/sun8i-codec-analog.c +++ b/sound/soc/sunxi/sun8i-codec-analog.c @@ -323,6 +323,13 @@ static const struct snd_kcontrol_new sun8i_codec_headphone_controls[] = { SUN8I_ADDA_DAC_PA_SRC, SUN8I_ADDA_DAC_PA_SRC_LHPPAMUTE, SUN8I_ADDA_DAC_PA_SRC_RHPPAMUTE, 1, 0), + /* inverted left to the right output, and the reverse */ + SOC_SINGLE("Headphone L to R Inversion Playback Switch", + SUN8I_ADDA_PAEN_HP_CTRL, + SUN8I_ADDA_PAEN_HP_CTRL_LTRNMUTE, 1, 0), + SOC_SINGLE("Headphone R to L Inversion Playback Switch", + SUN8I_ADDA_PAEN_HP_CTRL, + SUN8I_ADDA_PAEN_HP_CTRL_RTLNMUTE, 1, 0), }; static const char * const sun8i_codec_hp_src_enum_text[] = { diff --git a/sound/soc/tegra/tegra210_admaif.c b/sound/soc/tegra/tegra210_admaif.c index 73be3a67db859f..31c0f893eb20d5 100644 --- a/sound/soc/tegra/tegra210_admaif.c +++ b/sound/soc/tegra/tegra210_admaif.c @@ -184,6 +184,20 @@ static const struct reg_default tegra264_admaif_reg_defaults[] = { {(TEGRA_ADMAIF_GLOBAL_CG_0 + TEGRA264_ADMAIF_GLOBAL_BASE), 0x00000003} }; +static const struct reg_default tegra268_admaif_reg_defaults[] = { + ADMAIF_RX_REG_DEFAULTS(1, TEGRA268), + ADMAIF_RX_REG_DEFAULTS(2, TEGRA268), + ADMAIF_RX_REG_DEFAULTS(3, TEGRA268), + ADMAIF_RX_REG_DEFAULTS(4, TEGRA268), + ADMAIF_RX_REG_DEFAULTS(5, TEGRA268), + ADMAIF_TX_REG_DEFAULTS(1, TEGRA268), + ADMAIF_TX_REG_DEFAULTS(2, TEGRA268), + ADMAIF_TX_REG_DEFAULTS(3, TEGRA268), + ADMAIF_TX_REG_DEFAULTS(4, TEGRA268), + ADMAIF_TX_REG_DEFAULTS(5, TEGRA268), + {(TEGRA_ADMAIF_GLOBAL_CG_0 + TEGRA268_ADMAIF_GLOBAL_BASE), 0x00000003} +}; + static bool tegra_admaif_wr_reg(struct device *dev, unsigned int reg) { struct tegra_admaif *admaif = dev_get_drvdata(dev); @@ -342,6 +356,20 @@ static const struct regmap_config tegra264_admaif_regmap_config = { .cache_type = REGCACHE_FLAT, }; +static const struct regmap_config tegra268_admaif_regmap_config = { + .reg_bits = 32, + .reg_stride = 4, + .val_bits = 32, + .max_register = TEGRA264_ADMAIF_LAST_REG, + .writeable_reg = tegra_admaif_wr_reg, + .readable_reg = tegra_admaif_rd_reg, + .volatile_reg = tegra_admaif_volatile_reg, + .reg_defaults = tegra268_admaif_reg_defaults, + .num_reg_defaults = TEGRA268_ADMAIF_CHANNEL_COUNT * 6 + 1, + .reg_default_cb = regmap_default_zero_cb, + .cache_type = REGCACHE_FLAT, +}; + static int tegra_admaif_runtime_suspend(struct device *dev) { struct tegra_admaif *admaif = dev_get_drvdata(dev); @@ -796,6 +824,14 @@ static struct snd_soc_dai_driver tegra264_admaif_cmpnt_dais[] = { DAI("ADMAIF32", TEGRA264_ADMAIF_MAX_CHANNEL), }; +static struct snd_soc_dai_driver tegra268_admaif_cmpnt_dais[] = { + DAI("ADMAIF1", TEGRA268_ADMAIF_MAX_CHANNEL), + DAI("ADMAIF2", TEGRA268_ADMAIF_MAX_CHANNEL), + DAI("ADMAIF3", TEGRA268_ADMAIF_MAX_CHANNEL), + DAI("ADMAIF4", TEGRA268_ADMAIF_MAX_CHANNEL), + DAI("ADMAIF5", TEGRA268_ADMAIF_MAX_CHANNEL), +}; + static const char * const tegra_admaif_stereo_conv_text[] = { "CH0", "CH1", "AVG", }; @@ -908,6 +944,14 @@ static struct snd_kcontrol_new tegra264_admaif_controls[] = { TEGRA_ADMAIF_CIF_CTRL(32), }; +static struct snd_kcontrol_new tegra268_admaif_controls[] = { + TEGRA_ADMAIF_CIF_CTRL(1), + TEGRA_ADMAIF_CIF_CTRL(2), + TEGRA_ADMAIF_CIF_CTRL(3), + TEGRA_ADMAIF_CIF_CTRL(4), + TEGRA_ADMAIF_CIF_CTRL(5), +}; + static const struct snd_soc_component_driver tegra210_admaif_cmpnt = { .controls = tegra210_admaif_controls, .num_controls = ARRAY_SIZE(tegra210_admaif_controls), @@ -938,6 +982,16 @@ static const struct snd_soc_component_driver tegra264_admaif_cmpnt = { .pointer = tegra_pcm_pointer, }; +static const struct snd_soc_component_driver tegra268_admaif_cmpnt = { + .controls = tegra268_admaif_controls, + .num_controls = ARRAY_SIZE(tegra268_admaif_controls), + .pcm_new = tegra_pcm_new, + .open = tegra_pcm_open, + .close = tegra_pcm_close, + .hw_params = tegra_pcm_hw_params, + .pointer = tegra_pcm_pointer, +}; + static const struct tegra_admaif_soc_data soc_data_tegra210 = { .num_ch = TEGRA210_ADMAIF_CHANNEL_COUNT, .max_stream_ch = TEGRA210_ADMAIF_MAX_CHANNEL, @@ -971,10 +1025,22 @@ static const struct tegra_admaif_soc_data soc_data_tegra264 = { .rx_base = TEGRA264_ADMAIF_RX_BASE, }; +static const struct tegra_admaif_soc_data soc_data_tegra268 = { + .num_ch = TEGRA268_ADMAIF_CHANNEL_COUNT, + .max_stream_ch = TEGRA268_ADMAIF_MAX_CHANNEL, + .cmpnt = &tegra268_admaif_cmpnt, + .dais = tegra268_admaif_cmpnt_dais, + .regmap_conf = &tegra268_admaif_regmap_config, + .global_base = TEGRA268_ADMAIF_GLOBAL_BASE, + .tx_base = TEGRA268_ADMAIF_TX_BASE, + .rx_base = TEGRA268_ADMAIF_RX_BASE, +}; + static const struct of_device_id tegra_admaif_of_match[] = { { .compatible = "nvidia,tegra210-admaif", .data = &soc_data_tegra210 }, { .compatible = "nvidia,tegra186-admaif", .data = &soc_data_tegra186 }, { .compatible = "nvidia,tegra264-admaif", .data = &soc_data_tegra264 }, + { .compatible = "nvidia,tegra268-admaif", .data = &soc_data_tegra268 }, {}, }; MODULE_DEVICE_TABLE(of, tegra_admaif_of_match); diff --git a/sound/soc/tegra/tegra210_admaif.h b/sound/soc/tegra/tegra210_admaif.h index fd9877aa95d386..4290f7a049fb2b 100644 --- a/sound/soc/tegra/tegra210_admaif.h +++ b/sound/soc/tegra/tegra210_admaif.h @@ -31,6 +31,12 @@ #define TEGRA264_ADMAIF_TX_BASE 0x1000 #define TEGRA264_ADMAIF_GLOBAL_BASE 0x2000 #define TEGRA264_ADMAIF_MAX_CHANNEL 32 +/* Tegra268 specific */ +#define TEGRA268_ADMAIF_CHANNEL_COUNT 5 +#define TEGRA268_ADMAIF_RX_BASE TEGRA264_ADMAIF_RX_BASE +#define TEGRA268_ADMAIF_TX_BASE TEGRA264_ADMAIF_TX_BASE +#define TEGRA268_ADMAIF_GLOBAL_BASE TEGRA264_ADMAIF_GLOBAL_BASE +#define TEGRA268_ADMAIF_MAX_CHANNEL TEGRA264_ADMAIF_MAX_CHANNEL /* Global registers */ #define TEGRA_ADMAIF_GLOBAL_ENABLE 0x0 #define TEGRA_ADMAIF_GLOBAL_CG_0 0x8 @@ -204,6 +210,18 @@ #define TEGRA264_ADMAIF_TX30_FIFO_CTRL_REG_DEFAULT 0x01800257 #define TEGRA264_ADMAIF_TX31_FIFO_CTRL_REG_DEFAULT 0x0180025a #define TEGRA264_ADMAIF_TX32_FIFO_CTRL_REG_DEFAULT 0x0180025d +/* Default values - Tegra268 */ +#define TEGRA268_ADMAIF_CIF_REG_DEFAULT 0x00003f00 +#define TEGRA268_ADMAIF_RX1_FIFO_CTRL_REG_DEFAULT 0x00000500 +#define TEGRA268_ADMAIF_RX2_FIFO_CTRL_REG_DEFAULT 0x00000507 +#define TEGRA268_ADMAIF_RX3_FIFO_CTRL_REG_DEFAULT 0x0000050e +#define TEGRA268_ADMAIF_RX4_FIFO_CTRL_REG_DEFAULT 0x00000514 +#define TEGRA268_ADMAIF_RX5_FIFO_CTRL_REG_DEFAULT 0x0000051a +#define TEGRA268_ADMAIF_TX1_FIFO_CTRL_REG_DEFAULT 0x03000500 +#define TEGRA268_ADMAIF_TX2_FIFO_CTRL_REG_DEFAULT 0x03000507 +#define TEGRA268_ADMAIF_TX3_FIFO_CTRL_REG_DEFAULT 0x0300050e +#define TEGRA268_ADMAIF_TX4_FIFO_CTRL_REG_DEFAULT 0x03000514 +#define TEGRA268_ADMAIF_TX5_FIFO_CTRL_REG_DEFAULT 0x0300051a enum { DATA_8BIT, diff --git a/sound/soc/xilinx/xlnx_spdif.c b/sound/soc/xilinx/xlnx_spdif.c index 9fdafd45c38125..b233ab1a92dcea 100644 --- a/sound/soc/xilinx/xlnx_spdif.c +++ b/sound/soc/xilinx/xlnx_spdif.c @@ -22,32 +22,42 @@ #define XLNX_SPDIF_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S24_LE) +#define XSPDIF_GLOBAL_IRQ_REG 0x1C +#define XSPDIF_GLOBAL_IRQ_ENABLE_MASK BIT(31) #define XSPDIF_IRQ_STS_REG 0x20 +#define XSPDIF_IRQ_CH_STS_MASK BIT(5) #define XSPDIF_IRQ_ENABLE_REG 0x28 #define XSPDIF_SOFT_RESET_REG 0x40 +#define XSPDIF_SOFT_RESET_VAL 0xA #define XSPDIF_CONTROL_REG 0x44 +#define XSPDIF_CONTROL_ENABLE_MASK BIT(0) +#define XSPDIF_CONTROL_FIFO_FLUSH_MASK BIT(1) +#define XSPDIF_CONTROL_CLK_CFG_MASK GENMASK(5, 2) +#define XSPDIF_CONTROL_CLK_CFG_SHIFT 2 #define XSPDIF_CHAN_0_STS_REG 0x4C -#define XSPDIF_GLOBAL_IRQ_ENABLE_REG 0x1C #define XSPDIF_CH_A_USER_DATA_REG_0 0x64 -#define XSPDIF_CORE_ENABLE_MASK BIT(0) -#define XSPDIF_FIFO_FLUSH_MASK BIT(1) -#define XSPDIF_CH_STS_MASK BIT(5) -#define XSPDIF_GLOBAL_IRQ_ENABLE BIT(31) -#define XSPDIF_CLOCK_CONFIG_BITS_MASK GENMASK(5, 2) -#define XSPDIF_CLOCK_CONFIG_BITS_SHIFT 2 -#define XSPDIF_SOFT_RESET_VALUE 0xA - -#define MAX_CHANNELS 2 -#define AES_SAMPLE_WIDTH 32 -#define CH_STATUS_UPDATE_TIMEOUT 40 +#define XSPDIF_MAX_CHANNELS 2 +#define XSPDIF_AES_SAMPLE_WIDTH 32 +#define XSPDIF_CH_STS_UPDATE_TIMEOUT 40 + +enum xspdif_clk_div { + XSPDIF_CLK_DIV_BY_4, + XSPDIF_CLK_DIV_BY_8, + XSPDIF_CLK_DIV_BY_16, + XSPDIF_CLK_DIV_BY_24, + XSPDIF_CLK_DIV_BY_32, + XSPDIF_CLK_DIV_BY_48, + XSPDIF_CLK_DIV_BY_64, +}; struct spdif_dev_data { u32 mode; - u32 aclk; bool rx_chsts_updated; void __iomem *base; struct clk *axi_clk; + struct clk *axis_clk; + struct clk *aud_clk; wait_queue_head_t chsts_q; }; @@ -57,12 +67,12 @@ static irqreturn_t xlnx_spdifrx_irq_handler(int irq, void *arg) struct spdif_dev_data *ctx = arg; val = readl(ctx->base + XSPDIF_IRQ_STS_REG); - if (val & XSPDIF_CH_STS_MASK) { - writel(val & XSPDIF_CH_STS_MASK, + if (val & XSPDIF_IRQ_CH_STS_MASK) { + writel(val & XSPDIF_IRQ_CH_STS_MASK, ctx->base + XSPDIF_IRQ_STS_REG); val = readl(ctx->base + XSPDIF_IRQ_ENABLE_REG); - writel(val & ~XSPDIF_CH_STS_MASK, + writel(val & ~XSPDIF_IRQ_CH_STS_MASK, ctx->base + XSPDIF_IRQ_ENABLE_REG); ctx->rx_chsts_updated = true; @@ -80,14 +90,14 @@ static int xlnx_spdif_startup(struct snd_pcm_substream *substream, struct spdif_dev_data *ctx = dev_get_drvdata(dai->dev); val = readl(ctx->base + XSPDIF_CONTROL_REG); - val |= XSPDIF_FIFO_FLUSH_MASK; + val |= XSPDIF_CONTROL_FIFO_FLUSH_MASK; writel(val, ctx->base + XSPDIF_CONTROL_REG); if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) { - writel(XSPDIF_CH_STS_MASK, + writel(XSPDIF_IRQ_CH_STS_MASK, ctx->base + XSPDIF_IRQ_ENABLE_REG); - writel(XSPDIF_GLOBAL_IRQ_ENABLE, - ctx->base + XSPDIF_GLOBAL_IRQ_ENABLE_REG); + writel(XSPDIF_GLOBAL_IRQ_ENABLE_MASK, + ctx->base + XSPDIF_GLOBAL_IRQ_REG); } return 0; @@ -98,48 +108,57 @@ static void xlnx_spdif_shutdown(struct snd_pcm_substream *substream, { struct spdif_dev_data *ctx = dev_get_drvdata(dai->dev); - writel(XSPDIF_SOFT_RESET_VALUE, ctx->base + XSPDIF_SOFT_RESET_REG); + writel(XSPDIF_SOFT_RESET_VAL, ctx->base + XSPDIF_SOFT_RESET_REG); } static int xlnx_spdif_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *dai) { - u32 val, clk_div, clk_cfg; + enum xspdif_clk_div clk_cfg; + u32 val, clk_div; struct spdif_dev_data *ctx = dev_get_drvdata(dai->dev); + unsigned long rate; + + rate = clk_get_rate(ctx->aud_clk); + if (!rate) { + dev_err(dai->dev, "aud_clk_i rate is not available\n"); + return -EINVAL; + } - clk_div = DIV_ROUND_CLOSEST(ctx->aclk, MAX_CHANNELS * AES_SAMPLE_WIDTH * + clk_div = DIV_ROUND_CLOSEST(rate, XSPDIF_MAX_CHANNELS * + XSPDIF_AES_SAMPLE_WIDTH * params_rate(params)); switch (clk_div) { case 4: - clk_cfg = 0; + clk_cfg = XSPDIF_CLK_DIV_BY_4; break; case 8: - clk_cfg = 1; + clk_cfg = XSPDIF_CLK_DIV_BY_8; break; case 16: - clk_cfg = 2; + clk_cfg = XSPDIF_CLK_DIV_BY_16; break; case 24: - clk_cfg = 3; + clk_cfg = XSPDIF_CLK_DIV_BY_24; break; case 32: - clk_cfg = 4; + clk_cfg = XSPDIF_CLK_DIV_BY_32; break; case 48: - clk_cfg = 5; + clk_cfg = XSPDIF_CLK_DIV_BY_48; break; case 64: - clk_cfg = 6; + clk_cfg = XSPDIF_CLK_DIV_BY_64; break; default: return -EINVAL; } val = readl(ctx->base + XSPDIF_CONTROL_REG); - val &= ~XSPDIF_CLOCK_CONFIG_BITS_MASK; - val |= clk_cfg << XSPDIF_CLOCK_CONFIG_BITS_SHIFT; + val &= ~XSPDIF_CONTROL_CLK_CFG_MASK; + val |= clk_cfg << XSPDIF_CONTROL_CLK_CFG_SHIFT; writel(val, ctx->base + XSPDIF_CONTROL_REG); return 0; @@ -149,7 +168,7 @@ static int rx_stream_detect(struct snd_soc_dai *dai) { int err; struct spdif_dev_data *ctx = dev_get_drvdata(dai->dev); - unsigned long jiffies = msecs_to_jiffies(CH_STATUS_UPDATE_TIMEOUT); + unsigned long jiffies = msecs_to_jiffies(XSPDIF_CH_STS_UPDATE_TIMEOUT); /* start capture only if stream is detected within 40ms timeout */ err = wait_event_interruptible_timeout(ctx->chsts_q, @@ -176,7 +195,7 @@ static int xlnx_spdif_trigger(struct snd_pcm_substream *substream, int cmd, case SNDRV_PCM_TRIGGER_START: case SNDRV_PCM_TRIGGER_RESUME: case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: - val |= XSPDIF_CORE_ENABLE_MASK; + val |= XSPDIF_CONTROL_ENABLE_MASK; writel(val, ctx->base + XSPDIF_CONTROL_REG); if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) ret = rx_stream_detect(dai); @@ -184,7 +203,7 @@ static int xlnx_spdif_trigger(struct snd_pcm_substream *substream, int cmd, case SNDRV_PCM_TRIGGER_STOP: case SNDRV_PCM_TRIGGER_SUSPEND: case SNDRV_PCM_TRIGGER_PAUSE_PUSH: - val &= ~XSPDIF_CORE_ENABLE_MASK; + val &= ~XSPDIF_CONTROL_ENABLE_MASK; writel(val, ctx->base + XSPDIF_CONTROL_REG); break; default: @@ -260,8 +279,18 @@ static int xlnx_spdif_probe(struct platform_device *pdev) return dev_err_probe(dev, ret, "cannot get SPDIF mode\n"); if (ctx->mode) { + ctx->axis_clk = devm_clk_get_optional_enabled(dev, "s_axis_aclk"); + if (IS_ERR(ctx->axis_clk)) + return dev_err_probe(dev, PTR_ERR(ctx->axis_clk), + "failed to get s_axis_aclk\n"); + dai_drv = &xlnx_spdif_tx_dai; } else { + ctx->axis_clk = devm_clk_get_optional_enabled(dev, "m_axis_aclk"); + if (IS_ERR(ctx->axis_clk)) + return dev_err_probe(dev, PTR_ERR(ctx->axis_clk), + "failed to get m_axis_aclk\n"); + ret = platform_get_irq(pdev, 0); if (ret < 0) return ret; @@ -276,9 +305,10 @@ static int xlnx_spdif_probe(struct platform_device *pdev) dai_drv = &xlnx_spdif_rx_dai; } - ret = device_property_read_u32(dev, "xlnx,aud_clk_i", &ctx->aclk); - if (ret < 0) - return dev_err_probe(dev, ret, "cannot get aud_clk_i value\n"); + ctx->aud_clk = devm_clk_get_enabled(dev, "aud_clk_i"); + if (IS_ERR(ctx->aud_clk)) + return dev_err_probe(dev, PTR_ERR(ctx->aud_clk), + "failed to get aud_clk_i\n"); dev_set_drvdata(dev, ctx); @@ -287,7 +317,7 @@ static int xlnx_spdif_probe(struct platform_device *pdev) if (ret) return ret; - writel(XSPDIF_SOFT_RESET_VALUE, ctx->base + XSPDIF_SOFT_RESET_REG); + writel(XSPDIF_SOFT_RESET_VAL, ctx->base + XSPDIF_SOFT_RESET_REG); dev_info(dev, "%s DAI registered\n", dai_drv->name); return 0; diff --git a/sound/sound_core.c b/sound/sound_core.c index 10db8c69963035..90d59b14245d94 100644 --- a/sound/sound_core.c +++ b/sound/sound_core.c @@ -231,6 +231,21 @@ static struct sound_unit *__sound_remove_unit(struct sound_unit **list, int unit static DEFINE_SPINLOCK(sound_loader_lock); +/* + * Create the sound device and return an error if device creation fails. + */ + +static int sound_device_create(struct sound_unit *s, struct device *dev) +{ + struct device *device; + + device = device_create(&sound_class, dev, + MKDEV(SOUND_MAJOR, s->unit_minor), + NULL, "%s", s->name + 6); + + return PTR_ERR_OR_ZERO(device); +} + /* * Allocate the controlling structure and add it to the sound driver * list. Acquires locks as needed @@ -277,10 +292,20 @@ static int sound_insert_unit(struct sound_unit **list, const struct file_operati } } - device_create(&sound_class, dev, MKDEV(SOUND_MAJOR, s->unit_minor), - NULL, "%s", s->name+6); + r = sound_device_create(s, dev); + if (r) + goto err_remove_unit; + return s->unit_minor; +err_remove_unit: + if (!preclaim_oss) + __unregister_chrdev(SOUND_MAJOR, s->unit_minor, 1, s->name); + + spin_lock(&sound_loader_lock); + __sound_remove_unit(list, s->unit_minor); + spin_unlock(&sound_loader_lock); + fail: kfree(s); return r; diff --git a/sound/synth/emux/emux.c b/sound/synth/emux/emux.c index 2a42d041e1da0b..c2ee40735bf202 100644 --- a/sound/synth/emux/emux.c +++ b/sound/synth/emux/emux.c @@ -105,18 +105,19 @@ int snd_emux_register(struct snd_emux *emu, struct snd_card *card, int index, ch if (emu->sflist == NULL) return -ENOMEM; - err = snd_emux_init_hwdep(emu); - if (err < 0) - return err; - snd_emux_init_voices(emu); - snd_emux_init_seq(emu, card, index); + if (snd_emux_init_seq(emu, card, index) < 0) + return -ENODEV; #if IS_ENABLED(CONFIG_SND_SEQUENCER_OSS) snd_emux_init_seq_oss(emu); #endif snd_emux_init_virmidi(emu, card); + err = snd_emux_init_hwdep(emu); + if (err < 0) + return err; + snd_emux_proc_init(emu, card, index); return 0; } diff --git a/sound/usb/6fire/midi.c b/sound/usb/6fire/midi.c index 279b449936e75d..407f5d73b07dec 100644 --- a/sound/usb/6fire/midi.c +++ b/sound/usb/6fire/midi.c @@ -25,6 +25,7 @@ static void usb6fire_midi_out_handler(struct urb *urb) int ret; guard(spinlock_irqsave)(&rt->out_lock); + rt->out_urb_active = false; if (rt->out) { ret = snd_rawmidi_transmit(rt->out, rt->out_buffer + 4, @@ -35,10 +36,13 @@ static void usb6fire_midi_out_handler(struct urb *urb) urb->transfer_buffer_length = ret + 4; ret = usb_submit_urb(urb, GFP_ATOMIC); - if (ret < 0) + if (ret < 0) { + rt->out = NULL; dev_err(&urb->dev->dev, "midi out urb submit failed: %d\n", ret); + } else + rt->out_urb_active = true; } else /* no more data to transmit */ rt->out = NULL; } @@ -74,6 +78,14 @@ static void usb6fire_midi_out_trigger( if (rt->out) /* we are already transmitting so just return */ return; + rt->out = alsa_sub; + /* + * The urb is still in flight from the previous transmission; + * the completion handler sends the queued data instead. + */ + if (rt->out_urb_active) + return; + ret = snd_rawmidi_transmit(alsa_sub, rt->out_buffer + 4, MIDI_BUFSIZE - 4); if (ret > 0) { @@ -82,13 +94,15 @@ static void usb6fire_midi_out_trigger( urb->transfer_buffer_length = ret + 4; ret = usb_submit_urb(urb, GFP_ATOMIC); - if (ret < 0) + if (ret < 0) { + rt->out = NULL; dev_err(&urb->dev->dev, "midi out urb submit failed: %d\n", ret); - else - rt->out = alsa_sub; - } + } else + rt->out_urb_active = true; + } else + rt->out = NULL; } else if (rt->out == alsa_sub) rt->out = NULL; } diff --git a/sound/usb/6fire/midi.h b/sound/usb/6fire/midi.h index 8716ab8a863ae9..2213614424357c 100644 --- a/sound/usb/6fire/midi.h +++ b/sound/usb/6fire/midi.h @@ -23,6 +23,7 @@ struct midi_runtime { spinlock_t out_lock; struct snd_rawmidi_substream *out; struct urb *out_urb; + bool out_urb_active; /* out urb is still queued in the HCD */ u8 out_serial; /* serial number of out packet */ u8 *out_buffer; int buffer_offset; diff --git a/sound/usb/6fire/pcm.c b/sound/usb/6fire/pcm.c index f5dfb8c3096adf..d6ef8ffa97a9b5 100644 --- a/sound/usb/6fire/pcm.c +++ b/sound/usb/6fire/pcm.c @@ -460,6 +460,15 @@ static void usb6fire_pcm_in_urb_handler(struct urb *usb_urb) if (period_elapsed) snd_pcm_period_elapsed(sub->instance); + /* + * The out urb is submitted again from here, but the previous one may + * still be queued in the HCD. Its transfer buffer is owned by the + * HCD until it completes, so skip it for this period and retry at + * the next capture completion. + */ + if (atomic_xchg(&out_urb->active, 1)) + goto submit_in; + /* setup out urb structure */ for (i = 0; i < PCM_N_PACKETS_PER_URB; i++) { unsigned int frames = 0; @@ -525,8 +534,11 @@ static void usb6fire_pcm_in_urb_handler(struct urb *usb_urb) * the frames of an out urb that was not submitted never reach the * transmitter; the next urb continues the block at the same position */ - if (usb_submit_urb(out_urb->instance, GFP_ATOMIC) < 0) + if (usb_submit_urb(out_urb->instance, GFP_ATOMIC) < 0) { rt->spdif_frame = spdif_frame; + atomic_set(&out_urb->active, 0); + } +submit_in: usb_submit_urb(in_urb->instance, GFP_ATOMIC); } @@ -535,6 +547,8 @@ static void usb6fire_pcm_out_urb_handler(struct urb *usb_urb) struct pcm_urb *urb = usb_urb->context; struct pcm_runtime *rt = urb->chip->pcm; + atomic_set(&urb->active, 0); + if (rt->stream_state == STREAM_STARTING) { rt->stream_wait_cond = true; wake_up(&rt->stream_wait_queue); diff --git a/sound/usb/6fire/pcm.h b/sound/usb/6fire/pcm.h index f1b867b9c46864..b5d1f5106d2c09 100644 --- a/sound/usb/6fire/pcm.h +++ b/sound/usb/6fire/pcm.h @@ -28,6 +28,8 @@ struct pcm_urb { u8 *buffer; struct pcm_urb *peer; + + atomic_t active; /* urb is queued in the HCD */ }; struct pcm_substream { diff --git a/sound/usb/caiaq/audio.c b/sound/usb/caiaq/audio.c index bb6280aa353347..c7d47f0833da24 100644 --- a/sound/usb/caiaq/audio.c +++ b/sound/usb/caiaq/audio.c @@ -332,13 +332,14 @@ static void read_in_urb_mode0(struct snd_usb_caiaqdev *cdev, const struct usb_iso_packet_descriptor *iso) { unsigned char *usb_buf = urb->transfer_buffer + iso->offset; + unsigned int len = rounddown(iso->actual_length, cdev->n_streams); struct snd_pcm_substream *sub; int stream, i; if (all_substreams_zero(cdev->sub_capture)) return; - for (i = 0; i < iso->actual_length;) { + for (i = 0; i < len;) { for (stream = 0; stream < cdev->n_streams; stream++, i++) { sub = cdev->sub_capture[stream]; if (sub) { @@ -360,11 +361,13 @@ static void read_in_urb_mode2(struct snd_usb_caiaqdev *cdev, const struct usb_iso_packet_descriptor *iso) { unsigned char *usb_buf = urb->transfer_buffer + iso->offset; + unsigned int len = rounddown(iso->actual_length, + cdev->n_streams * BYTES_PER_SAMPLE_USB); unsigned char check_byte; struct snd_pcm_substream *sub; int stream, i; - for (i = 0; i < iso->actual_length;) { + for (i = 0; i < len;) { if (i % (cdev->n_streams * BYTES_PER_SAMPLE_USB) == 0) { for (stream = 0; stream < cdev->n_streams; @@ -407,6 +410,8 @@ static void read_in_urb_mode3(struct snd_usb_caiaqdev *cdev, const struct usb_iso_packet_descriptor *iso) { unsigned char *usb_buf = urb->transfer_buffer + iso->offset; + unsigned int len = rounddown(iso->actual_length, cdev->n_streams * + BYTES_PER_SAMPLE_USB * CHANNELS_PER_STREAM); struct device *dev = caiaqdev_to_dev(cdev); int stream, i; @@ -414,7 +419,7 @@ static void read_in_urb_mode3(struct snd_usb_caiaqdev *cdev, if (iso->actual_length % (BYTES_PER_SAMPLE_USB * CHANNELS_PER_STREAM)) return; - for (i = 0; i < iso->actual_length;) { + for (i = 0; i < len;) { for (stream = 0; stream < cdev->n_streams; stream++) { struct snd_pcm_substream *sub = cdev->sub_capture[stream]; char *audio_buf = NULL; @@ -495,10 +500,11 @@ static void fill_out_urb_mode_0(struct snd_usb_caiaqdev *cdev, const struct usb_iso_packet_descriptor *iso) { unsigned char *usb_buf = urb->transfer_buffer + iso->offset; + unsigned int len = rounddown(iso->length, cdev->n_streams); struct snd_pcm_substream *sub; int stream, i; - for (i = 0; i < iso->length;) { + for (i = 0; i < len;) { for (stream = 0; stream < cdev->n_streams; stream++, i++) { sub = cdev->sub_playback[stream]; if (sub) { @@ -516,12 +522,14 @@ static void fill_out_urb_mode_0(struct snd_usb_caiaqdev *cdev, } /* fill in the check bytes */ - if (cdev->spec.data_alignment == 2 && + if (cdev->spec.data_alignment == 2 && i < len && i % (cdev->n_streams * BYTES_PER_SAMPLE_USB) == (cdev->n_streams * CHANNELS_PER_STREAM)) for (stream = 0; stream < cdev->n_streams; stream++, i++) usb_buf[i] = MAKE_CHECKBYTE(cdev, stream, i); } + + memset(usb_buf + len, 0, iso->length - len); } static void fill_out_urb_mode_3(struct snd_usb_caiaqdev *cdev, @@ -529,9 +537,11 @@ static void fill_out_urb_mode_3(struct snd_usb_caiaqdev *cdev, const struct usb_iso_packet_descriptor *iso) { unsigned char *usb_buf = urb->transfer_buffer + iso->offset; + unsigned int len = rounddown(iso->length, cdev->n_streams * + BYTES_PER_SAMPLE_USB * CHANNELS_PER_STREAM); int stream, i; - for (i = 0; i < iso->length;) { + for (i = 0; i < len;) { for (stream = 0; stream < cdev->n_streams; stream++) { struct snd_pcm_substream *sub = cdev->sub_playback[stream]; char *audio_buf = NULL; @@ -565,6 +575,8 @@ static void fill_out_urb_mode_3(struct snd_usb_caiaqdev *cdev, } } } + + memset(usb_buf + len, 0, iso->length - len); } static inline void fill_out_urb(struct snd_usb_caiaqdev *cdev, diff --git a/sound/usb/clock.c b/sound/usb/clock.c index cc77eace7b592d..74f9923e501584 100644 --- a/sound/usb/clock.c +++ b/sound/usb/clock.c @@ -292,9 +292,12 @@ static bool uac_clock_source_is_valid(struct snd_usb_audio *chip, return uac_clock_source_is_valid_quirk(chip, fmt, source_id); } +#define MAX_CLOCK_DEPTH 16 + static int __uac_clock_find_source(struct snd_usb_audio *chip, const struct audioformat *fmt, int entity_id, - unsigned long *visited, bool validate) + unsigned long *visited, bool validate, + int depth) { union uac23_clock_source_desc *source; union uac23_clock_selector_desc *selector; @@ -307,6 +310,13 @@ static int __uac_clock_find_source(struct snd_usb_audio *chip, entity_id &= 0xff; + if (depth >= MAX_CLOCK_DEPTH) { + usb_audio_warn(chip, + "%s(): clock topology is too deep, id %d.\n", + __func__, entity_id); + return -EINVAL; + } + if (test_and_set_bit(entity_id, visited)) { usb_audio_warn(chip, "%s(): recursive clock topology detected, id %d.\n", @@ -381,7 +391,7 @@ static int __uac_clock_find_source(struct snd_usb_audio *chip, cur = ret; ret = __uac_clock_find_source(chip, fmt, sources[ret - 1], - visited, validate); + visited, validate, depth + 1); if (ret > 0) { /* Skip setting clock selector again for some devices */ if (chip->quirk_flags & QUIRK_FLAG_SKIP_CLOCK_SELECTOR || @@ -414,7 +424,7 @@ static int __uac_clock_find_source(struct snd_usb_audio *chip, ret = __uac_clock_find_source(chip, fmt, sources[i - 1], - visited, true); + visited, true, depth + 1); if (ret < 0) continue; @@ -436,7 +446,7 @@ static int __uac_clock_find_source(struct snd_usb_audio *chip, if (multiplier) return __uac_clock_find_source(chip, fmt, GET_VAL(multiplier, proto, bCSourceID), - visited, validate); + visited, validate, depth + 1); return -EINVAL; } @@ -462,7 +472,7 @@ int snd_usb_clock_find_source(struct snd_usb_audio *chip, case UAC_VERSION_2: case UAC_VERSION_3: return __uac_clock_find_source(chip, fmt, fmt->clock, visited, - validate); + validate, 0); default: return -EINVAL; } diff --git a/sound/usb/endpoint.c b/sound/usb/endpoint.c index 8dd0b3525e4b07..02f0049cacf32a 100644 --- a/sound/usb/endpoint.c +++ b/sound/usb/endpoint.c @@ -449,6 +449,9 @@ static void push_back_to_ready_list(struct snd_usb_endpoint *ep, struct snd_urb_ctx *ctx) { guard(spinlock_irqsave)(&ep->lock); + /* don't re-queue after stop_urbs() flushed the list */ + if (!ep_state_running(ep)) + return; /* ctx may still be linked: a stale completion racing a stop/restart. */ if (list_empty(&ctx->ready_list)) list_add_tail(&ctx->ready_list, &ep->ready_playback_urbs); diff --git a/sound/usb/line6/capture.c b/sound/usb/line6/capture.c index 626274e503c7aa..fa98c26cf77d14 100644 --- a/sound/usb/line6/capture.c +++ b/sound/usb/line6/capture.c @@ -284,6 +284,7 @@ const struct snd_pcm_ops snd_line6_capture_ops = { .hw_free = snd_line6_hw_free, .prepare = snd_line6_prepare, .trigger = snd_line6_trigger, + .sync_stop = snd_line6_sync_stop, .pointer = snd_line6_pointer, }; diff --git a/sound/usb/line6/pcm.c b/sound/usb/line6/pcm.c index d17baf7761c67d..34d68a9ce3285e 100644 --- a/sound/usb/line6/pcm.c +++ b/sound/usb/line6/pcm.c @@ -109,29 +109,51 @@ static void line6_unlink_audio_urbs(struct snd_line6_pcm *line6pcm, } /* - Wait until unlinking of all currently active URBs has been finished. -*/ -static void line6_wait_clear_audio_urbs(struct snd_line6_pcm *line6pcm, - struct line6_pcm_stream *pcms) + * Mark all currently active URBs for unlinking and kill them. + * + * The unlink bit is set under the stream lock, so the completion + * callbacks cannot resubmit these URBs any longer. usb_kill_urb() then + * waits for the giveback of every URB, hence the stream buffer is no + * longer referenced by the host controller. This function must be + * called from a sleepable context. + * + * When @idle_only is set, nothing is done if some stream is still running + * on @pcms, and only the URBs that are active at that moment are killed, + * so that a concurrently started stream is never stopped. + */ +static void line6_kill_audio_urbs(struct snd_line6_pcm *line6pcm, + struct line6_pcm_stream *pcms, bool idle_only) { - int timeout = HZ; + unsigned long active; int i; - int alive; - do { - alive = 0; - for (i = 0; i < line6pcm->line6->iso_buffers; i++) { - if (test_bit(i, &pcms->active_urbs)) - alive++; - } - if (!alive) - break; - set_current_state(TASK_UNINTERRUPTIBLE); - schedule_timeout(1); - } while (--timeout > 0); - if (alive) - dev_err(line6pcm->line6->ifcdev, - "timeout: still %d active urbs..\n", alive); + /* May be called when the URB creation failed during the probe */ + if (!pcms->urbs) + return; + + scoped_guard(spinlock_irqsave, &pcms->lock) { + if (idle_only && pcms->running) + return; + active = pcms->active_urbs; + for_each_set_bit(i, &active, line6pcm->line6->iso_buffers) + set_bit(i, &pcms->unlink_urbs); + } + + for_each_set_bit(i, &active, line6pcm->line6->iso_buffers) + if (pcms->urbs[i]) + usb_kill_urb(pcms->urbs[i]); + + /* + * Drop the unlink marks left on URBs that were completed and not + * resubmitted, so that a later stream start can submit the URBs + * again. An URB that is still active keeps its mark. + */ + scoped_guard(spinlock_irqsave, &pcms->lock) { + for_each_set_bit(i, &pcms->unlink_urbs, + line6pcm->line6->iso_buffers) + if (!test_bit(i, &pcms->active_urbs)) + clear_bit(i, &pcms->unlink_urbs); + } } static inline struct line6_pcm_stream * @@ -172,7 +194,7 @@ static void line6_buffer_release(struct snd_line6_pcm *line6pcm, { clear_bit(type, &pstr->opened); if (!pstr->opened) { - line6_wait_clear_audio_urbs(line6pcm, pstr); + line6_kill_audio_urbs(line6pcm, pstr, false); if (pstr == &line6pcm->in) { /* prev_fbuf points into the capture buffer we are about * to free; drop it while no capture URB is in flight. @@ -337,8 +359,7 @@ int line6_pcm_acquire(struct snd_line6_pcm *line6pcm, int type, bool start) ret = line6_buffer_acquire(line6pcm, pstr, dir, type); if (ret < 0) goto error; - if (!pstr->running) - line6_wait_clear_audio_urbs(line6pcm, pstr); + line6_kill_audio_urbs(line6pcm, pstr, true); } if (start) { for (dir = 0; dir < 2; dir++) { @@ -510,10 +531,8 @@ static int snd_line6_new_pcm(struct usb_line6 *line6, struct snd_pcm **pcm_ret) */ void line6_pcm_disconnect(struct snd_line6_pcm *line6pcm) { - line6_unlink_audio_urbs(line6pcm, &line6pcm->out); - line6_unlink_audio_urbs(line6pcm, &line6pcm->in); - line6_wait_clear_audio_urbs(line6pcm, &line6pcm->out); - line6_wait_clear_audio_urbs(line6pcm, &line6pcm->in); + line6_kill_audio_urbs(line6pcm, &line6pcm->out, false); + line6_kill_audio_urbs(line6pcm, &line6pcm->in, false); } /* @@ -592,6 +611,27 @@ int line6_init_pcm(struct usb_line6 *line6, } EXPORT_SYMBOL_GPL(line6_init_pcm); +/* common PCM sync_stop callback */ +int snd_line6_sync_stop(struct snd_pcm_substream *substream) +{ + struct snd_line6_pcm *line6pcm = snd_pcm_substream_chip(substream); + struct line6_pcm_stream *pstr = get_stream(line6pcm, substream->stream); + + guard(mutex)(&line6pcm->state_mutex); + line6_kill_audio_urbs(line6pcm, pstr, true); + /* + * A capture stream may use the playback stream as a helper, and + * snd_line6_trigger() stops it together with the capture stream. + * Stop the leftover playback URBs here as well, so that the helper + * stream can be restarted at the next trigger. + */ + if (substream->stream == SNDRV_PCM_STREAM_CAPTURE && + (line6pcm->line6->properties->capabilities & + LINE6_CAP_IN_NEEDS_OUT)) + line6_kill_audio_urbs(line6pcm, &line6pcm->out, true); + return 0; +} + /* prepare pcm callback */ int snd_line6_prepare(struct snd_pcm_substream *substream) { @@ -599,8 +639,12 @@ int snd_line6_prepare(struct snd_pcm_substream *substream) struct line6_pcm_stream *pstr = get_stream(line6pcm, substream->stream); guard(mutex)(&line6pcm->state_mutex); - if (!pstr->running) - line6_wait_clear_audio_urbs(line6pcm, pstr); + /* + * sync_stop() is called only after this substream itself was + * stopped; other stream types sharing the stream (monitor, impulse + * or the capture helper) may have left URBs unlinking. + */ + line6_kill_audio_urbs(line6pcm, pstr, true); if (!test_and_set_bit(LINE6_FLAG_PREPARED, &line6pcm->flags)) { line6pcm->out.count = 0; diff --git a/sound/usb/line6/pcm.h b/sound/usb/line6/pcm.h index a15913bf2a7aad..21e550948cd810 100644 --- a/sound/usb/line6/pcm.h +++ b/sound/usb/line6/pcm.h @@ -183,6 +183,7 @@ extern int line6_init_pcm(struct usb_line6 *line6, struct line6_pcm_properties *properties); extern int snd_line6_trigger(struct snd_pcm_substream *substream, int cmd); extern int snd_line6_prepare(struct snd_pcm_substream *substream); +extern int snd_line6_sync_stop(struct snd_pcm_substream *substream); extern int snd_line6_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *hw_params); extern int snd_line6_hw_free(struct snd_pcm_substream *substream); diff --git a/sound/usb/line6/playback.c b/sound/usb/line6/playback.c index e93a16f6958e37..10e273f4b77a47 100644 --- a/sound/usb/line6/playback.c +++ b/sound/usb/line6/playback.c @@ -414,6 +414,7 @@ const struct snd_pcm_ops snd_line6_playback_ops = { .hw_free = snd_line6_hw_free, .prepare = snd_line6_prepare, .trigger = snd_line6_trigger, + .sync_stop = snd_line6_sync_stop, .pointer = snd_line6_pointer, }; diff --git a/sound/usb/mixer.c b/sound/usb/mixer.c index 95209ec006b3c6..37850f34caaea8 100644 --- a/sound/usb/mixer.c +++ b/sound/usb/mixer.c @@ -51,6 +51,7 @@ #include "power.h" #define MAX_ID_ELEMS 256 +#define MAX_UNIT_DEPTH 16 struct usb_audio_term { int id; @@ -69,6 +70,8 @@ struct mixer_build { unsigned int buflen; DECLARE_BITMAP(unitbitmap, MAX_ID_ELEMS); DECLARE_BITMAP(termbitmap, MAX_ID_ELEMS); + unsigned int unit_depth; + unsigned int term_depth; struct usb_audio_term oterm; const struct usbmix_name_map *map; const struct usbmix_selector_map *selector_map; @@ -1023,6 +1026,9 @@ static int __check_input_term(struct mixer_build *state, int id, void *p1; unsigned char *hdr; + if (++state->term_depth > MAX_UNIT_DEPTH) + return -EINVAL; + for (;;) { /* a loop in the terminal chain? */ if (test_and_set_bit(id, state->termbitmap)) @@ -1093,6 +1099,7 @@ static int check_input_term(struct mixer_build *state, int id, { memset(term, 0, sizeof(*term)); memset(state->termbitmap, 0, sizeof(state->termbitmap)); + state->term_depth = 0; return __check_input_term(state, id, term); } @@ -3180,7 +3187,7 @@ static int parse_audio_selector_unit(struct mixer_build *state, int unitid, * parse an audio unit recursively */ -static int parse_audio_unit(struct mixer_build *state, int unitid) +static int __parse_audio_unit(struct mixer_build *state, int unitid) { unsigned char *p1; int protocol = state->mixer->protocol; @@ -3240,6 +3247,22 @@ static int parse_audio_unit(struct mixer_build *state, int unitid) } } +static int parse_audio_unit(struct mixer_build *state, int unitid) +{ + int err; + + if (state->unit_depth >= MAX_UNIT_DEPTH) { + usb_audio_err(state->chip, + "unit %d: unit chain is too deep\n", unitid); + return -EINVAL; + } + + state->unit_depth++; + err = __parse_audio_unit(state, unitid); + state->unit_depth--; + return err; +} + static void snd_usb_mixer_free(struct usb_mixer_interface *mixer) { struct usb_mixer_elem_list *list, *next; diff --git a/sound/usb/mixer_maps.c b/sound/usb/mixer_maps.c index 9218ca6314ad79..173bc218366f58 100644 --- a/sound/usb/mixer_maps.c +++ b/sound/usb/mixer_maps.c @@ -486,8 +486,8 @@ static const struct usbmix_name_map aorus_master_alc1220vb_map[] = { {} }; -/* MSI MPG X570S Carbon Max Wifi with ALC4080 */ -static const struct usbmix_name_map msi_mpg_x570s_carbon_max_wifi_alc4080_map[] = { +/* ALC4080/ALC4082 boards with this playback feature unit layout */ +static const struct usbmix_name_map alc408x_map[] = { { 29, "Speaker Playback" }, { 30, "Front Headphone Playback" }, { 32, "IEC958 Playback" }, @@ -562,6 +562,17 @@ static const struct usbmix_name_map avermedia_gc553pro_map[] = { {} }; +/* + * Sony PlayStation Eye: FU 3 advertises per-channel volume for the four + * microphones, but the device answers GET_MIN, GET_MAX and GET_CUR with a + * single zero byte, and SET_CUR is accepted without changing the capture + * level. Skip the control. + */ +static const struct usbmix_name_map sony_ps_eye_map[] = { + { 3, NULL, UAC_FU_VOLUME }, + {} +}; + /* * Control map entries */ @@ -640,6 +651,11 @@ static const struct usbmix_ctl_map usbmix_ctl_maps[] = { .id = USB_ID(0x13e5, 0x0001), .map = scratch_live_map, }, + { + /* Sony PlayStation Eye */ + .id = USB_ID(0x1415, 0x2000), + .map = sony_ps_eye_map, + }, { .id = USB_ID(0x200c, 0x1018), .map = ebox44_map, @@ -770,15 +786,19 @@ static const struct usbmix_ctl_map usbmix_ctl_maps[] = { }, { /* MSI MPG X570S Carbon Max Wifi */ .id = USB_ID(0x0db0, 0x419c), - .map = msi_mpg_x570s_carbon_max_wifi_alc4080_map, + .map = alc408x_map, }, { /* MSI MAG X570S Torpedo Max */ .id = USB_ID(0x0db0, 0xa073), - .map = msi_mpg_x570s_carbon_max_wifi_alc4080_map, + .map = alc408x_map, }, { /* MSI MAG B850M MORTAR WIFI */ .id = USB_ID(0x0db0, 0xcc78), - .map = msi_mpg_x570s_carbon_max_wifi_alc4080_map, + .map = alc408x_map, + }, + { /* ASRock X870E Taichi (Lite) (ALC4082) */ + .id = USB_ID(0x26ce, 0x0a0b), + .map = alc408x_map, }, { /* MSI TRX40 */ .id = USB_ID(0x0db0, 0x543d), diff --git a/sound/usb/mixer_quirks.c b/sound/usb/mixer_quirks.c index 4c7d68311f2048..60ac92a1ca4f9e 100644 --- a/sound/usb/mixer_quirks.c +++ b/sound/usb/mixer_quirks.c @@ -4656,6 +4656,179 @@ static int snd_xiisound_init_fu_pins(struct usb_mixer_interface *mixer) return 0; } +/* + * ASRock X870E Taichi (ALC4082): the rear line (feature unit 29) has only mute, + * however there is an ESS ES9219 DAC behind it that is usable for volume + * control. + */ +#define TAICHI_I2C_READ 0x3d +#define TAICHI_I2C_WRITE 0x3e +#define TAICHI_I2C_INDEX 0x0100 +#define TAICHI_ES9219_I2C_ADDR 0x48 +#define TAICHI_ES9219_REG_VOL_L 0x0f +#define TAICHI_ES9219_REG_VOL_R 0x10 +#define TAICHI_ES9219_PRIV_VOL_L GENMASK(7, 0) +#define TAICHI_ES9219_PRIV_VOL_R GENMASK(15, 8) +#define TAICHI_ES9219_VOL_MAX 0xff + +static int taichi_es9219_read(struct snd_usb_audio *chip, u8 reg, u8 *val) +{ + struct usb_device *dev = chip->dev; + u8 buf[2] = { reg, 0 }; + int err; + + err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), TAICHI_I2C_READ, + USB_RECIP_DEVICE | USB_TYPE_VENDOR | USB_DIR_OUT, + TAICHI_ES9219_I2C_ADDR, TAICHI_I2C_INDEX, + buf, sizeof(buf)); + if (err < 0) + return err; + err = snd_usb_ctl_msg(dev, usb_rcvctrlpipe(dev, 0), TAICHI_I2C_READ, + USB_RECIP_DEVICE | USB_TYPE_VENDOR | USB_DIR_IN, + TAICHI_ES9219_I2C_ADDR, TAICHI_I2C_INDEX, + buf, sizeof(buf)); + if (err < 0) + return err; + if (err < 1) + return -EIO; + *val = buf[0]; + return 0; +} + +static int taichi_es9219_write(struct snd_usb_audio *chip, u8 reg, u8 val) +{ + struct usb_device *dev = chip->dev; + u8 buf[2] = { reg, val }; + int err; + + err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), TAICHI_I2C_WRITE, + USB_RECIP_DEVICE | USB_TYPE_VENDOR | USB_DIR_OUT, + TAICHI_ES9219_I2C_ADDR, TAICHI_I2C_INDEX, + buf, sizeof(buf)); + return err < 0 ? err : 0; +} + +/* The return value follows the kcontrol put contract */ +static int taichi_es9219_vol_update(struct usb_mixer_elem_list *list, + u8 left, u8 right, bool force) +{ + struct snd_usb_audio *chip = list->mixer->chip; + unsigned long *pv = &list->kctl->private_value; + bool update_l = force || left != FIELD_GET(TAICHI_ES9219_PRIV_VOL_L, *pv); + bool update_r = force || right != FIELD_GET(TAICHI_ES9219_PRIV_VOL_R, *pv); + int err; + + if (!update_l && !update_r) + return 0; + + CLASS(snd_usb_lock, pm)(chip); + if (pm.err < 0) + return pm.err; + + if (update_l) { + err = taichi_es9219_write(chip, TAICHI_ES9219_REG_VOL_L, + TAICHI_ES9219_VOL_MAX - left); + if (err < 0) + return err; + FIELD_MODIFY(TAICHI_ES9219_PRIV_VOL_L, pv, left); + } + + if (update_r) { + err = taichi_es9219_write(chip, TAICHI_ES9219_REG_VOL_R, + TAICHI_ES9219_VOL_MAX - right); + if (err < 0) + return err; + FIELD_MODIFY(TAICHI_ES9219_PRIV_VOL_R, pv, right); + } + return 1; +} + +static int taichi_es9219_vol_info(struct snd_kcontrol *kctl, + struct snd_ctl_elem_info *uinfo) +{ + uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER; + uinfo->count = 2; + uinfo->value.integer.min = 0; + uinfo->value.integer.max = TAICHI_ES9219_VOL_MAX; + return 0; +} + +static int taichi_es9219_vol_get(struct snd_kcontrol *kctl, + struct snd_ctl_elem_value *ucontrol) +{ + ucontrol->value.integer.value[0] = FIELD_GET(TAICHI_ES9219_PRIV_VOL_L, + kctl->private_value); + ucontrol->value.integer.value[1] = FIELD_GET(TAICHI_ES9219_PRIV_VOL_R, + kctl->private_value); + return 0; +} + +static int taichi_es9219_vol_put(struct snd_kcontrol *kctl, + struct snd_ctl_elem_value *ucontrol) +{ + struct usb_mixer_elem_list *list = snd_kcontrol_chip(kctl); + long l = ucontrol->value.integer.value[0]; + long r = ucontrol->value.integer.value[1]; + + if (l < 0 || l > TAICHI_ES9219_VOL_MAX || + r < 0 || r > TAICHI_ES9219_VOL_MAX) + return -EINVAL; + + return taichi_es9219_vol_update(list, l, r, false); +} + +static int taichi_es9219_vol_resume(struct usb_mixer_elem_list *list) +{ + unsigned long l = FIELD_GET(TAICHI_ES9219_PRIV_VOL_L, + list->kctl->private_value); + unsigned long r = FIELD_GET(TAICHI_ES9219_PRIV_VOL_R, + list->kctl->private_value); + + return taichi_es9219_vol_update(list, l, r, true); +} + +static const DECLARE_TLV_DB_SCALE(taichi_es9219_db_scale, -12750, 50, 0); + +static const struct snd_kcontrol_new taichi_es9219_vol = { + .iface = SNDRV_CTL_ELEM_IFACE_MIXER, + .name = "Speaker Playback Volume", + .access = SNDRV_CTL_ELEM_ACCESS_READWRITE | + SNDRV_CTL_ELEM_ACCESS_TLV_READ, + .info = taichi_es9219_vol_info, + .get = taichi_es9219_vol_get, + .put = taichi_es9219_vol_put, + .tlv = { .p = taichi_es9219_db_scale }, +}; + +static int taichi_es9219_controls_create(struct usb_mixer_interface *mixer) +{ + struct snd_usb_audio *chip = mixer->chip; + struct usb_mixer_elem_list *list; + u8 l, r; + int err; + + err = taichi_es9219_read(chip, TAICHI_ES9219_REG_VOL_L, &l); + if (err < 0) { + usb_audio_dbg(chip, "ES9219 VOL_L read failed: %d\n", err); + return 0; + } + err = taichi_es9219_read(chip, TAICHI_ES9219_REG_VOL_R, &r); + if (err < 0) { + usb_audio_dbg(chip, "ES9219 VOL_R read failed: %d\n", err); + return 0; + } + + err = add_single_ctl_with_resume(mixer, 0, taichi_es9219_vol_resume, + &taichi_es9219_vol, &list); + if (err < 0) + return err; + + list->kctl->private_value = + FIELD_PREP(TAICHI_ES9219_PRIV_VOL_L, TAICHI_ES9219_VOL_MAX - l) | + FIELD_PREP(TAICHI_ES9219_PRIV_VOL_R, TAICHI_ES9219_VOL_MAX - r); + return 0; +} + int snd_usb_mixer_apply_create_quirk(struct usb_mixer_interface *mixer) { int err = 0; @@ -4797,6 +4970,10 @@ int snd_usb_mixer_apply_create_quirk(struct usb_mixer_interface *mixer) err = dell_dock_mixer_create(mixer); break; + case USB_ID(0x26ce, 0x0a0b): /* ASRock X870E Taichi (Lite) */ + err = taichi_es9219_controls_create(mixer); + break; + case USB_ID(0x2a39, 0x3fd2): /* RME ADI-2 Pro */ case USB_ID(0x2a39, 0x3fd3): /* RME ADI-2 DAC */ case USB_ID(0x2a39, 0x3fd4): /* RME */ diff --git a/sound/usb/quirks.c b/sound/usb/quirks.c index a4eb0d0cdf4ba4..ff2bfe8504f23b 100644 --- a/sound/usb/quirks.c +++ b/sound/usb/quirks.c @@ -2552,6 +2552,9 @@ static const struct usb_audio_quirk_flags_table quirk_flags_table[] = { DEVICE_FLG(0x046d, 0x0aba, /* Logitech PRO X Wireless */ QUIRK_FLAG_MIXER_GET_CUR_OK | QUIRK_FLAG_MIXER_PLAYBACK_MIN_MUTE), + DEVICE_FLG(0x046d, 0x0af7, /* Logitech PRO X 2 LIGHTSPEED */ + QUIRK_FLAG_CTL_MSG_DELAY_1M | QUIRK_FLAG_SKIP_IFACE_SETUP | + QUIRK_FLAG_IFACE_DELAY), DEVICE_FLG(0x0499, 0x1506, /* Yamaha THR5 */ QUIRK_FLAG_GENERIC_IMPLICIT_FB), DEVICE_FLG(0x0499, 0x1509, /* Steinberg UR22 */ @@ -2681,6 +2684,10 @@ static const struct usb_audio_quirk_flags_table quirk_flags_table[] = { QUIRK_FLAG_FIXED_RATE), DEVICE_FLG(0x0fd9, 0x0008, /* Hauppauge HVR-950Q */ QUIRK_FLAG_SHARE_MEDIA_DEVICE | QUIRK_FLAG_ALIGN_TRANSFER), + DEVICE_FLG(0x0fd9, 0x0070, /* Elgato Wave:3 */ + QUIRK_FLAG_GENERIC_IMPLICIT_FB), + DEVICE_FLG(0x0fd9, 0x00a6, /* Elgato XLR Dock */ + QUIRK_FLAG_GENERIC_IMPLICIT_FB), DEVICE_FLG(0x1038, 0x1294, /* SteelSeries Arctis Pro Wireless */ QUIRK_FLAG_MIXER_PLAYBACK_MIN_MUTE), DEVICE_FLG(0x1101, 0x0003, /* Audioengine D1 */ @@ -2706,6 +2713,8 @@ static const struct usb_audio_quirk_flags_table quirk_flags_table[] = { QUIRK_FLAG_PLAYBACK_FIRST | QUIRK_FLAG_GENERIC_IMPLICIT_FB), DEVICE_FLG(0x13e5, 0x0001, /* Serato Phono */ QUIRK_FLAG_IGNORE_CTL_ERROR), + DEVICE_FLG(0x1415, 0x2000, /* Sony PlayStation Eye */ + QUIRK_FLAG_GET_SAMPLE_RATE), DEVICE_FLG(0x152a, 0x85dd, /* SMSL USB DAC */ QUIRK_FLAG_DSD_RAW | QUIRK_FLAG_DISABLE_AUTOSUSPEND | QUIRK_FLAG_SKIP_IFACE_SETUP), @@ -2801,8 +2810,12 @@ static const struct usb_audio_quirk_flags_table quirk_flags_table[] = { QUIRK_FLAG_SET_IFACE_FIRST), DEVICE_FLG(0x25aa, 0x600b, /* TAE1159 */ QUIRK_FLAG_FORCE_IFACE_RESET | QUIRK_FLAG_IFACE_DELAY), + DEVICE_FLG(0x262a, 0x0001, /* Fosi Audio DS2 */ + QUIRK_FLAG_DSD_RAW), DEVICE_FLG(0x262a, 0x9302, /* ddHiFi TC44C */ QUIRK_FLAG_DSD_RAW), + DEVICE_FLG(0x262a, 0x1a0b, /* iBasso Macaron */ + QUIRK_FLAG_DSD_RAW), DEVICE_FLG(0x2772, 0x0502, /* Musical Fidelity M6s DAC */ 0), /* for avoiding QUIRK_FLAG_DSD_RAW with vendor match */ DEVICE_FLG(0x2912, 0x30c8, /* Audioengine D1 */ @@ -3059,7 +3072,7 @@ void snd_usb_init_quirk_flags_parse_string(struct snd_usb_audio *chip, if (!val) return; - for (p = val; p && *p;) { + for (p = strim(val); p && *p;) { /* Each entry consists of VID:PID:flags */ field = strsep(&p, ":"); if (!field) diff --git a/sound/virtio/virtio_pcm_ops.c b/sound/virtio/virtio_pcm_ops.c index 1091100a4c982b..a4b944a8a48482 100644 --- a/sound/virtio/virtio_pcm_ops.c +++ b/sound/virtio/virtio_pcm_ops.c @@ -435,17 +435,26 @@ static int virtsnd_pcm_sync_stop(struct snd_pcm_substream *substream) * substream for playback. * @substream: Kernel ALSA substream. * - * Context: Any context. - * Return: Hardware position in frames inside [0 ... buffer_size) range. + * Context: Any context. Takes and releases the VirtIO substream spinlock. + * Return: Hardware position in frames inside [0 ... buffer_size) range, or + * SNDRV_PCM_POS_XRUN if the device reported an xrun. */ static snd_pcm_uframes_t virtsnd_pcm_pb_pointer(struct snd_pcm_substream *substream) { struct virtio_pcm_substream *vss = snd_pcm_substream_chip(substream); + size_t hw_ptr; + + scoped_guard(spinlock_irqsave, &vss->lock) { + if (vss->xfer_xrun) + return SNDRV_PCM_POS_XRUN; + + hw_ptr = vss->hw_ptr; + } return snd_pcm_indirect_playback_pointer(substream, &vss->pcm_indirect, - vss->hw_ptr); + hw_ptr); } /** @@ -453,17 +462,26 @@ virtsnd_pcm_pb_pointer(struct snd_pcm_substream *substream) * substream for capture. * @substream: Kernel ALSA substream. * - * Context: Any context. - * Return: Hardware position in frames inside [0 ... buffer_size) range. + * Context: Any context. Takes and releases the VirtIO substream spinlock. + * Return: Hardware position in frames inside [0 ... buffer_size) range, or + * SNDRV_PCM_POS_XRUN if the device reported an xrun. */ static snd_pcm_uframes_t virtsnd_pcm_cp_pointer(struct snd_pcm_substream *substream) { struct virtio_pcm_substream *vss = snd_pcm_substream_chip(substream); + size_t hw_ptr; + + scoped_guard(spinlock_irqsave, &vss->lock) { + if (vss->xfer_xrun) + return SNDRV_PCM_POS_XRUN; + + hw_ptr = vss->hw_ptr; + } return snd_pcm_indirect_capture_pointer(substream, &vss->pcm_indirect, - vss->hw_ptr); + hw_ptr); } static void virtsnd_pcm_trans_copy(struct snd_pcm_substream *substream, diff --git a/tools/arch/x86/include/asm/cpufeatures.h b/tools/arch/x86/include/asm/cpufeatures.h index fe84cf4e97d35a..61930f0d457865 100644 --- a/tools/arch/x86/include/asm/cpufeatures.h +++ b/tools/arch/x86/include/asm/cpufeatures.h @@ -76,7 +76,7 @@ #define X86_FEATURE_K8 ( 3*32+ 4) /* Opteron, Athlon64 */ #define X86_FEATURE_ZEN5 ( 3*32+ 5) /* CPU based on Zen5 microarchitecture */ #define X86_FEATURE_ZEN6 ( 3*32+ 6) /* CPU based on Zen6 microarchitecture */ -/* Free ( 3*32+ 7) */ +#define X86_FEATURE_RMPOPT ( 3*32+ 7) /* Support for AMD RMPOPT instruction */ #define X86_FEATURE_CONSTANT_TSC ( 3*32+ 8) /* "constant_tsc" TSC ticks at a constant rate */ /* free: was #define X86_FEATURE_UP ( 3*32+ 9) * "up" SMP kernel running on UP */ #define X86_FEATURE_ART ( 3*32+10) /* "art" Always running timer (ART) */ @@ -238,6 +238,7 @@ // free: was #define X86_FEATURE_PVUNLOCK ( 8*32+20) /* PV unlock function */ #define X86_FEATURE_VCPUPREEMPT ( 8*32+21) /* PV vcpu_is_preempted function */ #define X86_FEATURE_TDX_GUEST ( 8*32+22) /* "tdx_guest" Intel Trust Domain Extensions Guest */ +#define X86_FEATURE_PML ( 8*32+23) /* AMD Page Modification logging */ /* Intel-defined CPU features, CPUID level 0x00000007:0 (EBX), word 9 */ #define X86_FEATURE_FSGSBASE ( 9*32+ 0) /* "fsgsbase" RDFSBASE, WRFSBASE, RDGSBASE, WRGSBASE instructions*/ @@ -430,6 +431,7 @@ #define X86_FEATURE_SUCCOR (17*32+ 1) /* "succor" Uncorrectable error containment and recovery */ #define X86_FEATURE_CPPC_PERF_PRIO (17*32+ 2) /* CPPC Floor Perf support */ #define X86_FEATURE_SMCA (17*32+ 3) /* "smca" Scalable MCA */ +#define X86_FEATURE_BTB_CTX_ISOLATION (17*32+ 4) /* AMD: Branch predictions contexts isolated */ /* Intel-defined CPU features, CPUID level 0x00000007:0 (EDX), word 18 */ #define X86_FEATURE_AVX512_4VNNIW (18*32+ 2) /* "avx512_4vnniw" AVX-512 Neural Network Instructions */ @@ -485,6 +487,8 @@ #define X86_FEATURE_AUTOIBRS (20*32+ 8) /* Automatic IBRS */ #define X86_FEATURE_NO_SMM_CTL_MSR (20*32+ 9) /* SMM_CTL MSR is not present */ +#define X86_FEATURE_L2_TLB_SIZE_X32 (20*32+14) /* L2 TLB sizes are encoded as multiples of 32 */ + #define X86_FEATURE_GP_ON_USER_CPUID (20*32+17) /* User CPUID faulting */ #define X86_FEATURE_PREFETCHI (20*32+20) /* Prefetch Data/Instruction to Cache Level */ diff --git a/tools/arch/x86/include/asm/msr-index.h b/tools/arch/x86/include/asm/msr-index.h index 9c26d4075c5f42..c0914829a925d5 100644 --- a/tools/arch/x86/include/asm/msr-index.h +++ b/tools/arch/x86/include/asm/msr-index.h @@ -114,6 +114,8 @@ #define MSR_IA32_CORE_CAPS_INTEGRITY_CAPS BIT(MSR_IA32_CORE_CAPS_INTEGRITY_CAPS_BIT) #define MSR_IA32_CORE_CAPS_SPLIT_LOCK_DETECT_BIT 5 #define MSR_IA32_CORE_CAPS_SPLIT_LOCK_DETECT BIT(MSR_IA32_CORE_CAPS_SPLIT_LOCK_DETECT_BIT) +#define MSR_IA32_CORE_CAPS_BFF_RESET_BIT 9 +#define MSR_IA32_CORE_CAPS_BFF_RESET BIT(MSR_IA32_CORE_CAPS_BFF_RESET_BIT) #define MSR_PKG_CST_CONFIG_CONTROL 0x000000e2 #define NHM_C3_AUTO_DEMOTE (1UL << 25) @@ -768,6 +770,9 @@ #define MSR_AMD64_SEG_RMP_ENABLED_BIT 0 #define MSR_AMD64_SEG_RMP_ENABLED BIT_ULL(MSR_AMD64_SEG_RMP_ENABLED_BIT) #define MSR_AMD64_RMP_SEGMENT_SHIFT(x) (((x) & GENMASK_ULL(13, 8)) >> 8) +#define MSR_AMD64_RMPOPT_BASE 0xc0010139 +#define MSR_AMD64_RMPOPT_ENABLE_BIT 0 +#define MSR_AMD64_RMPOPT_ENABLE BIT_ULL(MSR_AMD64_RMPOPT_ENABLE_BIT) #define MSR_SVSM_CAA 0xc001f000 @@ -1014,6 +1019,7 @@ #define THERM_INT_HIGH_ENABLE (1 << 0) #define THERM_INT_LOW_ENABLE (1 << 1) #define THERM_INT_PLN_ENABLE (1 << 24) +#define THERM_INT_DPTI_ENABLE (1 << 25) #define MSR_IA32_THERM_STATUS 0x0000019c @@ -1043,6 +1049,7 @@ #define PACKAGE_THERM_STATUS_PROCHOT (1 << 0) #define PACKAGE_THERM_STATUS_POWER_LIMIT (1 << 10) +#define PACKAGE_THERM_STATUS_DPTI_ACK (1 << 25) #define PACKAGE_THERM_STATUS_HFI_UPDATED (1 << 26) #define MSR_IA32_PACKAGE_THERM_INTERRUPT 0x000001b2 diff --git a/tools/arch/x86/include/uapi/asm/svm.h b/tools/arch/x86/include/uapi/asm/svm.h index 010a45c9f6147f..e8067618509215 100644 --- a/tools/arch/x86/include/uapi/asm/svm.h +++ b/tools/arch/x86/include/uapi/asm/svm.h @@ -101,6 +101,7 @@ #define SVM_EXIT_AVIC_INCOMPLETE_IPI 0x401 #define SVM_EXIT_AVIC_UNACCELERATED_ACCESS 0x402 #define SVM_EXIT_VMGEXIT 0x403 +#define SVM_EXIT_PML_FULL 0x407 /* SEV-ES software-defined VMGEXIT events */ #define SVM_VMGEXIT_MMIO_READ 0x80000001ull @@ -236,6 +237,7 @@ { SVM_EXIT_AVIC_INCOMPLETE_IPI, "avic_incomplete_ipi" }, \ { SVM_EXIT_AVIC_UNACCELERATED_ACCESS, "avic_unaccelerated_access" }, \ { SVM_EXIT_VMGEXIT, "vmgexit" }, \ + { SVM_EXIT_PML_FULL, "pml_full" }, \ { SVM_VMGEXIT_MMIO_READ, "vmgexit_mmio_read" }, \ { SVM_VMGEXIT_MMIO_WRITE, "vmgexit_mmio_write" }, \ { SVM_VMGEXIT_NMI_COMPLETE, "vmgexit_nmi_complete" }, \ diff --git a/tools/bootconfig/main.c b/tools/bootconfig/main.c index d3f840c5adce78..c85e58fcb6b0b7 100644 --- a/tools/bootconfig/main.c +++ b/tools/bootconfig/main.c @@ -182,7 +182,7 @@ static int load_xbc_fd(int fd, char **buf, int size) { int ret; - if (size < 0 || size > XBC_DATA_MAX) + if (size < 0 || size > XBC_DATA_MAX_PADDED) return -EINVAL; *buf = malloc(size + 1); @@ -190,8 +190,12 @@ static int load_xbc_fd(int fd, char **buf, int size) return -ENOMEM; ret = read(fd, *buf, size); - if (ret < 0) - return -errno; + if (ret != size) { + ret = ret < 0 ? -errno : -EIO; + free(*buf); + *buf = NULL; + return ret; + } (*buf)[size] = '\0'; return ret; @@ -237,7 +241,7 @@ static int load_xbc_from_initrd(int fd, char **buf) { struct stat stat; int ret; - uint32_t size = 0, csum = 0, rcsum; + uint32_t size = 0, data_size, csum = 0, rcsum; char magic[BOOTCONFIG_MAGIC_LEN]; ret = fstat(fd, &stat); @@ -269,7 +273,7 @@ static int load_xbc_from_initrd(int fd, char **buf) csum = le32toh(csum); /* Wrong size error */ - if (size > XBC_DATA_MAX || + if (size > XBC_DATA_MAX_PADDED || size > stat.st_size - BOOTCONFIG_FOOTER_SIZE) { pr_err("bootconfig size is too big\n"); return -E2BIG; @@ -283,6 +287,12 @@ static int load_xbc_from_initrd(int fd, char **buf) if (ret < 0) return ret; + data_size = xbc_exclude_padding(*buf, size); + if (data_size > XBC_DATA_MAX) { + pr_err("bootconfig size is too big\n"); + return -E2BIG; + } + /* Wrong Checksum */ rcsum = xbc_calc_checksum(*buf, size); if (csum != rcsum) { @@ -290,7 +300,7 @@ static int load_xbc_from_initrd(int fd, char **buf) return -EINVAL; } - ret = init_xbc_with_error(*buf, size); + ret = init_xbc_with_error(*buf, data_size); return ret < 0 ? ret : size; } @@ -499,14 +509,16 @@ static int apply_xbc(const char *path, const char *xbc_path) total_size = size + BOOTCONFIG_FOOTER_SIZE; ret = write(fd, data, total_size); - if (ret < total_size) { - if (ret < 0) - ret = -errno; + if (ret < 0) { + ret = -errno; pr_err("Failed to apply a boot config: %d\n", ret); - if (ret >= 0) - goto out_rollback; - } else - ret = 0; + goto out; + } + if ((size_t)ret != total_size) { + pr_err("Failed to apply a boot config: %d\n", ret); + goto out_rollback; + } + ret = 0; out: close(fd); diff --git a/tools/bootconfig/scripts/bconf2ftrace.sh b/tools/bootconfig/scripts/bconf2ftrace.sh index 850c2073433e12..ba29f7411f62a7 100755 --- a/tools/bootconfig/scripts/bconf2ftrace.sh +++ b/tools/bootconfig/scripts/bconf2ftrace.sh @@ -275,15 +275,26 @@ setup_instance() { # [instance] } # ftrace global configs (kernel.*) -if xbc_has_key "kernel.dump_on_oops"; then - dump_mode=`xbc_get_val "kernel.dump_on_oops" 1` +# Prefer the kernel parameter names and accept the old script keys as fallbacks. +dump_key=kernel.ftrace_dump_on_oops +xbc_has_key "$dump_key" || dump_key=kernel.dump_on_oops +if xbc_has_key "$dump_key"; then + dump_mode=`xbc_get_val "$dump_key" 1` [ "$dump_mode" ] && dump_mode=`eval echo $dump_mode` || dump_mode=1 run_cmd "echo \"$dump_mode\" > /proc/sys/kernel/ftrace_dump_on_oops" fi -set_value_of kernel.fgraph_max_depth $TRACEFS/max_graph_depth -set_array_of kernel.fgraph_filters $TRACEFS/set_graph_function -set_array_of kernel.fgraph_notraces $TRACEFS/set_graph_notrace +graph_depth_key=kernel.ftrace_graph_max_depth +xbc_has_key "$graph_depth_key" || graph_depth_key=kernel.fgraph_max_depth +set_value_of "$graph_depth_key" $TRACEFS/max_graph_depth + +graph_filter_key=kernel.ftrace_graph_filter +xbc_has_key "$graph_filter_key" || graph_filter_key=kernel.fgraph_filters +set_array_of "$graph_filter_key" $TRACEFS/set_graph_function + +graph_notrace_key=kernel.ftrace_graph_notrace +xbc_has_key "$graph_notrace_key" || graph_notrace_key=kernel.fgraph_notraces +set_array_of "$graph_notrace_key" $TRACEFS/set_graph_notrace # Per-instance/per-event configs if ! xbc_has_branch "ftrace" ; then diff --git a/tools/bootconfig/scripts/ftrace2bconf.sh b/tools/bootconfig/scripts/ftrace2bconf.sh index 8eed445c295e34..f62372adbfd598 100755 --- a/tools/bootconfig/scripts/ftrace2bconf.sh +++ b/tools/bootconfig/scripts/ftrace2bconf.sh @@ -46,10 +46,11 @@ emit_kv() { # key =|+= value global_options() { val=`cat $TRACEFS/max_graph_depth` - [ $val != 0 ] && emit_kv kernel.fgraph_max_depth = $val + [ $val != 0 ] && emit_kv kernel.ftrace_graph_max_depth = $val if grep -qv "^#" $TRACEFS/set_graph_function $TRACEFS/set_graph_notrace ; then cat 1>&2 << EOF -# WARN: kernel.fgraph_filters and kernel.fgraph_notrace are not supported, since the wild card expression was expanded and lost from memory. +# WARN: Cannot export kernel.ftrace_graph_filter and kernel.ftrace_graph_notrace. +# Only the expanded function list is available. EOF fi } diff --git a/tools/bootconfig/test-bootconfig.sh b/tools/bootconfig/test-bootconfig.sh index f584f7637e12a5..a93a40d11d278f 100755 --- a/tools/bootconfig/test-bootconfig.sh +++ b/tools/bootconfig/test-bootconfig.sh @@ -118,10 +118,23 @@ dd if=/dev/urandom bs=768 count=32 | base64 -w0 >> $TEMPCONF printf "\"\n" >> $TEMPCONF xfail $BOOTCONF -a $TEMPCONF $INITRD +dd if=$TEMPCONF of=$OUTFILE bs=1 count=32765 +cp $OUTFILE $TEMPCONF +printf "\"\n" >> $TEMPCONF # 32767 bytes + terminal ('\0') = 32768 (> max) +xfail $BOOTCONF -a $TEMPCONF $INITRD + dd if=$TEMPCONF of=$OUTFILE bs=1 count=32764 cp $OUTFILE $TEMPCONF -printf "\"\n" >> $TEMPCONF # add 2 bytes + terminal ('\"\n\0') -xpass $BOOTCONF -a $TEMPCONF $INITRD +printf "\"\n" >> $TEMPCONF # add 2 bytes + terminal ('\"\n\0') = 32767 +# Test max size across all 4 alignment paddings (0..3 bytes) +for sz in 4096 4097 4098 4099; do + dd if=/dev/zero of=$INITRD bs=1 count=$sz 2>/dev/null + xpass $BOOTCONF -a $TEMPCONF $INITRD + $BOOTCONF -l $INITRD > $OUTFILE + xpass cmp $TEMPCONF $OUTFILE + xpass $BOOTCONF -d $INITRD + xpass test $(wc -c < $INITRD) -eq $sz +done echo "Adding same-key values" cat > $TEMPCONF << EOF @@ -220,6 +233,39 @@ xpass $BOOTCONF -a $TEMPCONF $INITRD $BOOTCONF $INITRD > $OUTFILE xpass grep -q "value" $OUTFILE +echo "Unclosed brace error position" +cat > $TEMPCONF << EOF +a { + b = 1 +} +c { + d = 2 +EOF +echo > $INITRD + +xfail $BOOTCONF -a $TEMPCONF $INITRD +$BOOTCONF -a $TEMPCONF $INITRD > $OUTFILE 2>&1 +xpass grep -q "Brace.is.not.closed.at.4:1" $OUTFILE +$BOOTCONF -a samples/bad-tree.bconf $INITRD > $OUTFILE 2>&1 +xpass grep -q "Brace.is.not.closed.at.2:1" $OUTFILE + +echo "Mixed value and subkey depth/length limits" +cat > $TEMPCONF << EOF +k1 = v1 +k1.k2.k3.k4.k5.k6.k7.k8.k9.k10.k11.k12.k13.k14.k15.k16.k17 = v2 +EOF +xfail $BOOTCONF -a $TEMPCONF $INITRD + +awk ' +BEGIN { + printf("root = v\nroot.") + for (i = 0; i < 255; i += 1) + printf("a") + printf(" = v2\n") +} +' > $TEMPCONF +xfail $BOOTCONF -a $TEMPCONF $INITRD + echo "=== expected failure cases ===" for i in samples/bad-* ; do xfail $BOOTCONF -a $i $INITRD diff --git a/tools/build/Makefile.feature b/tools/build/Makefile.feature index 4d37d11f674c5b..c010049d972075 100644 --- a/tools/build/Makefile.feature +++ b/tools/build/Makefile.feature @@ -121,6 +121,7 @@ FEATURE_TESTS_EXTRA := \ libcheck \ libbfd-liberty \ libbfd-liberty-z \ + libbfd-liberty-z-zstd \ libopencsd \ llvm \ libbpf \ @@ -160,7 +161,7 @@ FEATURE_DISPLAY ?= \ # Declare group members of a feature to display the logical OR of the detection # result instead of each member result. # -FEATURE_GROUP_MEMBERS-libbfd = libbfd-liberty libbfd-liberty-z +FEATURE_GROUP_MEMBERS-libbfd = libbfd-liberty libbfd-liberty-z libbfd-liberty-z-zstd # # Declare list of feature dependency packages that provide pkg-config files. diff --git a/tools/build/feature/Makefile b/tools/build/feature/Makefile index 10340a5372242e..359da8b98bc5d1 100644 --- a/tools/build/feature/Makefile +++ b/tools/build/feature/Makefile @@ -20,6 +20,7 @@ FILES= \ test-reallocarray.bin \ test-libbfd-liberty.bin \ test-libbfd-liberty-z.bin \ + test-libbfd-liberty-z-zstd.bin \ test-cplus-demangle.bin \ test-cxa-demangle.bin \ test-libcap.bin \ @@ -249,18 +250,21 @@ $(OUTPUT)test-python-module.bin: $(BUILD) $(FLAGS_PYTHON_EMBED) $(OUTPUT)test-libbfd.bin: - $(BUILD_BFD) || $(BUILD_BFD) -lzstd + $(BUILD_BFD) $(OUTPUT)test-libbfd-threadsafe.bin: - $(BUILD_BFD) || $(BUILD_BFD) -lzstd || $(BUILD_BFD) -liberty || $(BUILD_BFD) -liberty -lz + $(BUILD_BFD) || $(BUILD_BFD) -liberty || $(BUILD_BFD) -liberty -lz || \ + $(BUILD_BFD) -liberty -lz -lzstd $(OUTPUT)test-disassembler-four-args.bin: - $(BUILD_BFD) -lopcodes || $(BUILD_BFD) -lopcodes -lzstd || $(BUILD_BFD) -lopcodes -liberty || \ - $(BUILD_BFD) -lopcodes -liberty -lz + $(BUILD_BFD) -lopcodes || $(BUILD_BFD) -lopcodes -liberty || \ + $(BUILD_BFD) -lopcodes -liberty -lz || \ + $(BUILD_BFD) -lopcodes -liberty -lz -lzstd $(OUTPUT)test-disassembler-init-styled.bin: - $(BUILD_BFD) -lopcodes || $(BUILD_BFD) -lopcodes -liberty || \ - $(BUILD_BFD) -lopcodes -liberty -lz + $(BUILD_BFD) -lopcodes || $(BUILD_BFD) -lopcodes -liberty || \ + $(BUILD_BFD) -lopcodes -liberty -lz || \ + $(BUILD_BFD) -lopcodes -liberty -lz -lzstd $(OUTPUT)test-reallocarray.bin: $(BUILD) @@ -271,6 +275,9 @@ $(OUTPUT)test-libbfd-liberty.bin: $(OUTPUT)test-libbfd-liberty-z.bin: $(CC) $(CFLAGS) -Wall -Werror -o $@ test-libbfd.c -DPACKAGE='"perf"' $(LDFLAGS) -lbfd -ldl -liberty -lz +$(OUTPUT)test-libbfd-liberty-z-zstd.bin: + $(CC) $(CFLAGS) -Wall -Werror -o $@ test-libbfd.c -DPACKAGE='"perf"' $(LDFLAGS) -lbfd -ldl -liberty -lz -lzstd + $(OUTPUT)test-cplus-demangle.bin: $(BUILD) -liberty diff --git a/tools/gpio/gpio-event-mon.c b/tools/gpio/gpio-event-mon.c index b70813b0bf8efa..af223e254bc980 100644 --- a/tools/gpio/gpio-event-mon.c +++ b/tools/gpio/gpio-event-mon.c @@ -124,8 +124,10 @@ int monitor_device(const char *device_name, fprintf(stdout, "\n"); i++; - if (i == loops) + if (i == loops) { + ret = 0; break; + } } exit_line_close: diff --git a/tools/gpio/gpio-hammer.c b/tools/gpio/gpio-hammer.c index 1a21e5460242e6..df6f71e48c59cb 100644 --- a/tools/gpio/gpio-hammer.c +++ b/tools/gpio/gpio-hammer.c @@ -159,10 +159,10 @@ int main(int argc, char **argv) } } - if (i >= GPIOHANDLES_MAX) { + if (i > GPIOHANDLES_MAX) { fprintf(stderr, "Only %d occurrences of '-o' are allowed, %d were found\n", - GPIOHANDLES_MAX, i + 1); + GPIOHANDLES_MAX, i); return -1; } diff --git a/tools/gpio/gpio-watch.c b/tools/gpio/gpio-watch.c index 41e76d24419224..e7733cedcf0d6f 100644 --- a/tools/gpio/gpio-watch.c +++ b/tools/gpio/gpio-watch.c @@ -64,7 +64,7 @@ int main(int argc, char **argv) memset(&chg, 0, sizeof(chg)); rd = read(pfd.fd, &chg, sizeof(chg)); if (rd < 0 || rd != sizeof(chg)) { - if (rd != sizeof(chg)) + if (rd >= 0 && rd != sizeof(chg)) errno = EIO; perror("error reading line change event"); diff --git a/tools/gpio/lsgpio.c b/tools/gpio/lsgpio.c index 52a0be45410c97..de2eccc1347964 100644 --- a/tools/gpio/lsgpio.c +++ b/tools/gpio/lsgpio.c @@ -205,7 +205,7 @@ int main(int argc, char **argv) goto error_out; } - ret = -ENOENT; + ret = 0; while (ent = readdir(dp), ent) { if (check_prefix(ent->d_name, "gpiochip")) { ret = list_device(ent->d_name); @@ -214,7 +214,6 @@ int main(int argc, char **argv) } } - ret = 0; if (closedir(dp) == -1) { perror("scanning devices: Failed to close directory"); ret = -errno; diff --git a/tools/include/linux/gfp.h b/tools/include/linux/gfp.h index 9e957b57b69451..6a10ff5f5be907 100644 --- a/tools/include/linux/gfp.h +++ b/tools/include/linux/gfp.h @@ -5,10 +5,6 @@ #include #include -/* Helper macro to avoid gfp flags if they are the default one */ -#define __default_gfp(a,...) a -#define default_gfp(...) __default_gfp(__VA_ARGS__ __VA_OPT__(,) GFP_KERNEL) - static inline bool gfpflags_allow_blocking(const gfp_t gfp_flags) { return !!(gfp_flags & __GFP_DIRECT_RECLAIM); diff --git a/tools/include/linux/gfp_types.h b/tools/include/linux/gfp_types.h index da47aa089f01c9..c1331bf0b2398c 100644 --- a/tools/include/linux/gfp_types.h +++ b/tools/include/linux/gfp_types.h @@ -134,7 +134,8 @@ enum { * %__GFP_THISNODE forces the allocation to be satisfied from the requested * node with no fallbacks or placement policy enforcements. * - * %__GFP_ACCOUNT causes the allocation to be accounted to kmemcg. + * %__GFP_ACCOUNT causes the allocation to be accounted to the active + * cgroup context. */ #define __GFP_RECLAIMABLE ((__force gfp_t)___GFP_RECLAIMABLE) #define __GFP_WRITE ((__force gfp_t)___GFP_WRITE) @@ -243,7 +244,7 @@ enum { * definitely preferable to use the flag rather than opencode endless * loop around allocator. * Allocating pages from the buddy with __GFP_NOFAIL and order > 1 is - * not supported. Please consider using kvmalloc() instead. + * discouraged. Please consider using kvmalloc() instead if possible. */ #define __GFP_IO ((__force gfp_t)___GFP_IO) #define __GFP_FS ((__force gfp_t)___GFP_FS) @@ -313,7 +314,7 @@ enum { * %ZONE_NORMAL or a lower zone for direct access but can direct reclaim. * * %GFP_KERNEL_ACCOUNT is the same as GFP_KERNEL, except the allocation is - * accounted to kmemcg. + * accounted to the active cgroup context. * * %GFP_NOWAIT is for kernel allocations that should not stall for direct * reclaim, start physical IO or use any filesystem callback. It is very @@ -381,4 +382,8 @@ enum { __GFP_NOMEMALLOC | __GFP_NOWARN) & ~__GFP_RECLAIM) #define GFP_TRANSHUGE (GFP_TRANSHUGE_LIGHT | __GFP_DIRECT_RECLAIM) +/* Helper macro to avoid gfp flags if they are the default one */ +#define __default_gfp(a,b,...) b +#define default_gfp(...) __default_gfp(,##__VA_ARGS__,GFP_KERNEL) + #endif /* __LINUX_GFP_TYPES_H */ diff --git a/tools/include/uapi/linux/bpf.h b/tools/include/uapi/linux/bpf.h index 8d72288343054b..6840ca5b923bf1 100644 --- a/tools/include/uapi/linux/bpf.h +++ b/tools/include/uapi/linux/bpf.h @@ -934,6 +934,7 @@ union bpf_iter_link_info { * by *prog_fd*, and the stream is identified by the *stream_id*. * The data is copied to a buffer pointed to by *stream_buf*, and * filled less than or equal to *stream_buf_len* bytes. + * The caller needs **CAP_PERFMON**. * * Return * Number of bytes read from the stream on success, or -1 if an @@ -953,7 +954,7 @@ union bpf_iter_link_info { * Description * Open a file descriptor for one of the BPF streams associated * with the program identified by *prog_fd*. The stream is selected - * by *stream_id*. + * by *stream_id*. The caller needs **CAP_PERFMON**. * * The returned file descriptor supports **read**\ (2) and * **poll**\ (2). Reads block while the stream is empty unless diff --git a/tools/include/uapi/linux/if_addr.h b/tools/include/uapi/linux/if_addr.h index 7fb630b7fe311a..0a1ad9ebb47bed 100644 --- a/tools/include/uapi/linux/if_addr.h +++ b/tools/include/uapi/linux/if_addr.h @@ -57,6 +57,7 @@ enum { #define IFA_F_NOPREFIXROUTE 0x200 #define IFA_F_MCAUTOJOIN 0x400 #define IFA_F_STABLE_PRIVACY 0x800 +#define IFA_F_GLOBAL 0x1000 struct ifa_cacheinfo { __u32 ifa_prefered; diff --git a/tools/include/uapi/linux/kvm.h b/tools/include/uapi/linux/kvm.h index ac2d77d1496356..8dff2fc1972e97 100644 --- a/tools/include/uapi/linux/kvm.h +++ b/tools/include/uapi/linux/kvm.h @@ -999,6 +999,7 @@ struct kvm_enable_cap { #define KVM_CAP_S390_HPAGE_2G 249 #define KVM_CAP_PPC_COMPAT_CAPS 250 #define KVM_CAP_ARM_PMU_V3_STRICT 251 +#define KVM_CAP_GUEST_MEMFD_MEMORY_ATTRIBUTES 252 struct kvm_irq_routing_irqchip { __u32 irqchip; @@ -1653,6 +1654,21 @@ struct kvm_memory_attributes { __u64 flags; }; +/* Available with KVM_CAP_GUEST_MEMFD_MEMORY_ATTRIBUTES */ +#define KVM_SET_MEMORY_ATTRIBUTES2 _IOWR(KVMIO, 0xd2, struct kvm_memory_attributes2) + +struct kvm_memory_attributes2 { + union { + __u64 address; + __u64 offset; + }; + __u64 size; + __u64 attributes; + __u64 flags; + __u64 error_offset; + __u64 reserved[11]; +}; + #define KVM_MEMORY_ATTRIBUTE_PRIVATE (1ULL << 3) #define KVM_CREATE_GUEST_MEMFD _IOWR(KVMIO, 0xd4, struct kvm_create_guest_memfd) diff --git a/tools/lib/bpf/libbpf.c b/tools/lib/bpf/libbpf.c index fb8a1f07c5b655..5f54a8e6f46fa0 100644 --- a/tools/lib/bpf/libbpf.c +++ b/tools/lib/bpf/libbpf.c @@ -1454,6 +1454,7 @@ static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name, __s32 type_id, datasec_id; const struct btf *btf; struct bpf_map *map; + bool optional; __u32 i; if (shndx == -1) @@ -1468,6 +1469,14 @@ static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name, return -EINVAL; } + /* + * Follow same convention as for programs autoload: + * SEC("?.struct_ops") means map is not created by default. + */ + optional = sec_name[0] == '?'; + /* from now on forget there was ? in section name */ + sec_name += optional; + datasec = btf__type_by_id(btf, datasec_id); vsi = btf_var_secinfos(datasec); for (i = 0; i < btf_vlen(datasec); i++, vsi++) { @@ -1503,14 +1512,8 @@ static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name, return -ENOMEM; map->btf_value_type_id = type_id; - /* Follow same convention as for programs autoload: - * SEC("?.struct_ops") means map is not created by default. - */ - if (sec_name[0] == '?') { + if (optional) map->autocreate = false; - /* from now on forget there was ? in section name */ - sec_name++; - } map->def.type = BPF_MAP_TYPE_STRUCT_OPS; map->def.key_size = sizeof(int); @@ -8407,7 +8410,7 @@ static int libbpf_prepare_prog_load(struct bpf_program *prog, opts->attach_btf_id = btf_type_id; } - if (is_tracing_multi(prog->expected_attach_type)) { + if (prog->type == BPF_PROG_TYPE_TRACING && is_tracing_multi(prog->expected_attach_type)) { int err, btf_obj_fd = 0; err = tracing_multi_mod_fd(prog, &btf_obj_fd); diff --git a/tools/objtool/check.c b/tools/objtool/check.c index 931c5c412f15d8..4ef5bf97d33351 100644 --- a/tools/objtool/check.c +++ b/tools/objtool/check.c @@ -206,9 +206,13 @@ static bool is_rust_noreturn(const struct symbol *func) str_ends_with(func->name, "_4core9panicking9panic_fmt") || str_ends_with(func->name, "_4core9panicking14panic_explicit") || str_ends_with(func->name, "_4core9panicking14panic_nounwind") || + str_ends_with(func->name, "_4core9panicking16todo_default_msg") || + str_ends_with(func->name, "_4core9panicking17panic_default_msg") || str_ends_with(func->name, "_4core9panicking18panic_bounds_check") || str_ends_with(func->name, "_4core9panicking18panic_nounwind_fmt") || str_ends_with(func->name, "_4core9panicking19assert_failed_inner") || + str_ends_with(func->name, "_4core9panicking23unreachable_default_msg") || + str_ends_with(func->name, "_4core9panicking25unimplemented_default_msg") || str_ends_with(func->name, "_4core9panicking30panic_null_pointer_dereference") || str_ends_with(func->name, "_4core9panicking32panic_null_reference_constructed") || str_ends_with(func->name, "_4core9panicking36panic_misaligned_pointer_dereference") || diff --git a/tools/perf/Makefile.config b/tools/perf/Makefile.config index b4764f69f47f4d..78423b0dcc73ac 100644 --- a/tools/perf/Makefile.config +++ b/tools/perf/Makefile.config @@ -896,6 +896,7 @@ ifdef BUILD_NONDISTRO $(call feature_check,libbfd-threadsafe) $(call feature_check,libbfd-liberty) $(call feature_check,libbfd-liberty-z) + $(call feature_check,libbfd-liberty-z-zstd) ifneq ($(feature-libbfd-threadsafe), 1) $(error binutils-dev(el) 2.42 or later is required for non-distro builds) @@ -909,6 +910,8 @@ ifdef BUILD_NONDISTRO EXTLIBS += -lbfd -lopcodes -liberty else ifeq ($(feature-libbfd-liberty-z), 1) EXTLIBS += -lbfd -lopcodes -liberty -lz + else ifeq ($(feature-libbfd-liberty-z-zstd), 1) + EXTLIBS += -lbfd -lopcodes -liberty -lz -lzstd endif CFLAGS += -DHAVE_LIBBFD_SUPPORT diff --git a/tools/perf/Makefile.perf b/tools/perf/Makefile.perf index b74b534e1153ff..4cc5bb3011da4d 100644 --- a/tools/perf/Makefile.perf +++ b/tools/perf/Makefile.perf @@ -798,7 +798,7 @@ $(patsubst perf-%,%.o,$(PROGRAMS)): $(wildcard */*.h) $(LIBAPI): FORCE | $(LIBAPI_OUTPUT) $(Q)$(MAKE) -C $(LIBAPI_DIR) O=$(LIBAPI_OUTPUT) \ - DESTDIR=$(LIBAPI_DESTDIR) prefix= subdir= \ + OUTPUT=$(LIBAPI_OUTPUT)/ DESTDIR=$(LIBAPI_DESTDIR) prefix= subdir= \ $@ install_headers $(LIBAPI)-clean: @@ -816,7 +816,7 @@ $(LIBBPF)-clean: $(LIBPERF): FORCE | $(LIBPERF_OUTPUT) $(Q)$(MAKE) -C $(LIBPERF_DIR) O=$(LIBPERF_OUTPUT) \ - DESTDIR=$(LIBPERF_DESTDIR) prefix= subdir= \ + OUTPUT=$(LIBPERF_OUTPUT)/ DESTDIR=$(LIBPERF_DESTDIR) prefix= subdir= \ $@ install_headers $(LIBPERF)-clean: @@ -825,7 +825,7 @@ $(LIBPERF)-clean: $(LIBSUBCMD): FORCE | $(LIBSUBCMD_OUTPUT) $(Q)$(MAKE) -C $(LIBSUBCMD_DIR) O=$(LIBSUBCMD_OUTPUT) \ - DESTDIR=$(LIBSUBCMD_DESTDIR) prefix= subdir= \ + OUTPUT=$(LIBSUBCMD_OUTPUT)/ DESTDIR=$(LIBSUBCMD_DESTDIR) prefix= subdir= \ $@ install_headers $(LIBSUBCMD)-clean: @@ -834,7 +834,7 @@ $(LIBSUBCMD)-clean: $(LIBSYMBOL): FORCE | $(LIBSYMBOL_OUTPUT) $(Q)$(MAKE) -C $(LIBSYMBOL_DIR) O=$(LIBSYMBOL_OUTPUT) \ - DESTDIR=$(LIBSYMBOL_DESTDIR) prefix= subdir= \ + OUTPUT=$(LIBSYMBOL_OUTPUT)/ DESTDIR=$(LIBSYMBOL_DESTDIR) prefix= subdir= \ $@ install_headers $(LIBSYMBOL)-clean: diff --git a/tools/perf/arch/x86/util/intel-bts.c b/tools/perf/arch/x86/util/intel-bts.c index d44d568a6d2108..9403681297c1da 100644 --- a/tools/perf/arch/x86/util/intel-bts.c +++ b/tools/perf/arch/x86/util/intel-bts.c @@ -299,6 +299,7 @@ static int intel_bts_alloc_snapshot_refs(struct intel_bts_recording *btsr, memcpy(refs, btsr->snapshot_refs, cnt * sz); + free(btsr->snapshot_refs); btsr->snapshot_refs = refs; btsr->snapshot_ref_cnt = new_cnt; diff --git a/tools/perf/arch/x86/util/intel-pt.c b/tools/perf/arch/x86/util/intel-pt.c index a533114c0048cb..4c183ccf4e5b6d 100644 --- a/tools/perf/arch/x86/util/intel-pt.c +++ b/tools/perf/arch/x86/util/intel-pt.c @@ -941,6 +941,7 @@ static int intel_pt_alloc_snapshot_refs(struct intel_pt_recording *ptr, int idx) memcpy(refs, ptr->snapshot_refs, cnt * sz); + free(ptr->snapshot_refs); ptr->snapshot_refs = refs; ptr->snapshot_ref_cnt = new_cnt; diff --git a/tools/perf/builtin-record.c b/tools/perf/builtin-record.c index ad81458989b53c..085d3648a30a33 100644 --- a/tools/perf/builtin-record.c +++ b/tools/perf/builtin-record.c @@ -1580,7 +1580,7 @@ static struct perf_event_header finished_init_event = { static void record__adjust_affinity(struct record *rec, struct mmap *map) { - if (rec->opts.affinity != PERF_AFFINITY_SYS && + if (map->core.cpu.cpu >= 0 && rec->opts.affinity != PERF_AFFINITY_SYS && !bitmap_equal(thread->mask->affinity.bits, map->affinity_mask.bits, thread->mask->affinity.nbits)) { bitmap_zero(thread->mask->affinity.bits, thread->mask->affinity.nbits); @@ -3704,8 +3704,8 @@ static int record__mmap_cpu_mask_init(struct mmap_cpu_mask *mask, struct perf_cp return 0; perf_cpu_map__for_each_cpu_skip_any(cpu, idx, cpus) { - /* Return ENODEV is input cpu is greater than max cpu */ - if ((unsigned long)cpu.cpu > mask->nbits) + /* Return ENODEV if the CPU index is outside the mask. */ + if ((unsigned long)cpu.cpu >= mask->nbits) return -ENODEV; __set_bit(cpu.cpu, mask->bits); } diff --git a/tools/perf/pmu-events/arch/arm64/ampere/ampereonex/memory.json b/tools/perf/pmu-events/arch/arm64/ampere/ampereonex/memory.json index 6c06bc928415de..114f95e41e0d59 100644 --- a/tools/perf/pmu-events/arch/arm64/ampere/ampereonex/memory.json +++ b/tools/perf/pmu-events/arch/arm64/ampere/ampereonex/memory.json @@ -35,9 +35,10 @@ "ArchStdEvent": "MEM_ACCESS_CHECKED_WR" }, { - "PublicDescription": "Flushes due to memory hazards", + "PublicDescription": "This event is deprecated. Refer to new event GPC_FLUSH_MEM_FAULT Flushes due to memory hazards", "EventCode": "0x121", "EventName": "BPU_FLUSH_MEM_FAULT", - "BriefDescription": "Flushes due to memory hazards" + "BriefDescription": "This event is deprecated. Refer to new event GPC_FLUSH_MEM_FAULT", + "Deprecated": "1" } ] diff --git a/tools/perf/pmu-events/jevents.py b/tools/perf/pmu-events/jevents.py index 080e04b51b8c5e..e083f7495e67c5 100755 --- a/tools/perf/pmu-events/jevents.py +++ b/tools/perf/pmu-events/jevents.py @@ -396,7 +396,7 @@ def canonicalize_value(val: str) -> str: event += f',{value}{canonicalize_value(jd[key])}' if filter: event += f',{filter}' - if msr: + if msr and msrval: event += f',{msr}{msrval}' if self.desc and extra_desc: self.desc += extra_desc diff --git a/tools/perf/python/treport.py b/tools/perf/python/treport.py index fb583786b17a57..202d70a923ecf8 100755 --- a/tools/perf/python/treport.py +++ b/tools/perf/python/treport.py @@ -602,6 +602,7 @@ def __init__(self, input_file: str, root: Optional[ProfileNode] = None): """ super().__init__() self.input_file = input_file + self.sub_title = input_file self.root = root if root else ProfileNode("root", parent=None) self.loaded = root is not None # Held when reading or changing the profile, which is built in a @@ -622,7 +623,6 @@ def compose(self) -> ComposeResult: def on_mount(self) -> None: """Start loading the profile unless it was given.""" - self.sub_title = self.input_file if self.loaded: self.update_views() else: diff --git a/tools/perf/python/ttimechart.py b/tools/perf/python/ttimechart.py index d7ba0276a9fb4a..2ec7ad9fcc994e 100755 --- a/tools/perf/python/ttimechart.py +++ b/tools/perf/python/ttimechart.py @@ -1065,6 +1065,7 @@ def __init__(self, data: TimechartData, rows: List[Row], *pos_args, **kwargs) -> self.can_focus = True self.data = data self.rows = rows + self.virtual_size = Size(0, 0) self.cache: Dict[int, List[Cell]] = {} self.cache_key: Tuple[float, float, int, Optional[ThemeColors]] = (0.0, 0.0, 0, None) self.label_style = Style() @@ -1332,6 +1333,7 @@ def __init__(self, input_name: str, power_only: bool, tasks_only: bool, """ super().__init__() self.input_name = input_name + self.sub_title = input_name self.power_only = power_only self.tasks_only = tasks_only self.filters = filters diff --git a/tools/perf/scripts/sync-headers.sh b/tools/perf/scripts/sync-headers.sh index 01e2d108432f01..3ba94102e2799f 100755 --- a/tools/perf/scripts/sync-headers.sh +++ b/tools/perf/scripts/sync-headers.sh @@ -292,13 +292,13 @@ merge_pickup_commits() { git rev-list --no-walk=unsorted --stdin --min-parents=2 2>/dev/null } -# Render commit ids with FORMAT at the usual 12 chars, keeping their order. +# Render commit ids with FORMAT at the usual 16 chars, keeping their order. format_commits() { local format="$1" local ids="$2" [[ -n "$ids" ]] || return 0 - printf '%s\n' "$ids" | git log --no-walk=unsorted --abbrev=12 \ + printf '%s\n' "$ids" | git log --no-walk=unsorted --abbrev=16 \ --format="$format" --stdin 2>/dev/null } @@ -875,7 +875,7 @@ beauty_body_fragment() { printf ' $ diff -u before.txt after.txt\n' fi printf '\n' - diff -u "$before" "$after" | tail -n +3 | sed 's/^/ /' + diff -u "$before" "$after" | tail -n +3 | sed -e '/^@@ /d' -e 's/^/ /' printf '\n' } @@ -914,7 +914,7 @@ process_header() { local kernel_commits="" if [[ -n "$pickup_commits" ]]; then - kernel_commits=$(format_commits ' %h ("%s")' "$pickup_commits") + kernel_commits=$(format_commits ' commit %h ("%s")' "$pickup_commits") fi # A merge can bring content of its own; list it too, it is not the @@ -926,7 +926,7 @@ process_header() { if [[ -n "$kernel_commits" ]]; then kernel_commits+=$'\n' fi - kernel_commits+=$(format_commits ' %h ("%s")' "$merge_commits") + kernel_commits+=$(format_commits ' commit %h ("%s")' "$merge_commits") fi if [[ -n "$kernel_commits" ]]; then @@ -1235,10 +1235,10 @@ process_group() { echo "" echo " Kernel commits since last sync ($tools_path):" if [[ -n "$pickup_commits" ]]; then - format_commits ' %h ("%s")' "$pickup_commits" + format_commits ' commit %h ("%s")' "$pickup_commits" fi if [[ -n "$merge_commits" ]]; then - format_commits ' %h ("%s")' "$merge_commits" + format_commits ' commit %h ("%s")' "$merge_commits" fi local ccs ccs=$(format_commits 'Cc: %an <%ae>' "$pickup_commits" | sort -u) @@ -1290,7 +1290,7 @@ process_group() { warn "No previous sync commit found for $tools_path" fi if [[ -n "$pickup_commits" ]]; then - all_kernel_commits+=$(format_commits ' %h ("%s")' "$pickup_commits") + all_kernel_commits+=$(format_commits ' commit %h ("%s")' "$pickup_commits") all_kernel_commits+=$'\n' local ccs @@ -1306,7 +1306,7 @@ process_group() { merge_commits=$(merge_pickup_commits "$kernel_path" "$tools_path" \ "$sync_point") if [[ -n "$merge_commits" ]]; then - all_kernel_commits+=$(format_commits ' %h ("%s")' "$merge_commits") + all_kernel_commits+=$(format_commits ' commit %h ("%s")' "$merge_commits") all_kernel_commits+=$'\n' fi diff --git a/tools/perf/tests/shell/lib/probe_vfs_getname.sh b/tools/perf/tests/shell/lib/probe_vfs_getname.sh index 57a59ae7d4ae3d..c7fee1f74bee16 100644 --- a/tools/perf/tests/shell/lib/probe_vfs_getname.sh +++ b/tools/perf/tests/shell/lib/probe_vfs_getname.sh @@ -27,6 +27,7 @@ cleanup_probe_vfs_getname() { trap cleanup_probe_vfs_getname exit trap 'exit 1' term int +# shellcheck disable=SC2120 # -v is for manual runs add_probe_vfs_getname() { add_probe_verbose=$1 if [ $had_vfs_getname -eq 1 ] ; then @@ -64,7 +65,11 @@ add_probe_vfs_getname() { } skip_if_no_debuginfo() { - add_probe_vfs_getname -v 2>&1 | grep -E -q "^(Failed to find the path for the kernel|Debuginfo-analysis is not supported)|(file has no debug information)" && return 2 + # Dry run a probe that needs debuginfo. + perf probe -n -v 'getname_flags $params' 2>&1 | grep -q \ + -e "^Failed to find the path for the kernel" \ + -e "^Debuginfo-analysis is not supported" \ + -e "file has no debug information" && return 2 return 1 } diff --git a/tools/perf/tests/shell/record.sh b/tools/perf/tests/shell/record.sh index 01dc3e22fa7381..e4789e2bcf4373 100755 --- a/tools/perf/tests/shell/record.sh +++ b/tools/perf/tests/shell/record.sh @@ -388,7 +388,7 @@ test_system_wide() { echo "Basic --system-wide mode test" local ret=0 perf_record_with_retry "${perfdata}" "check_system_wide" "perf test -w thloop" \ - -aB --synth=no || ret=$? + -aB --synth=no -e cpu-clock || ret=$? if [ $ret -eq 2 ]; then echo "System-wide record [Skipped not supported]" return @@ -471,7 +471,7 @@ test_cgroup() { echo "Cgroup sampling test" local ret=0 perf_record_with_retry "${perfdata}" "check_cgroup" "perf test -w thloop" \ - -aB --synth=cgroup --all-cgroups || ret=$? + -aB --synth=cgroup --all-cgroups -e cpu-clock || ret=$? if [ $ret -eq 2 ]; then echo "Cgroup sampling [Skipped not supported]" return @@ -491,7 +491,7 @@ test_uid() { echo "Uid sampling test" local ret=0 perf_record_with_retry "${perfdata}" "check_uid" "perf test -w thloop" \ - -aB --synth=no --uid "$(id -u)" || ret=$? + -aB --synth=no --uid "$(id -u)" -e cpu-clock || ret=$? if [ $ret -eq 2 ]; then local logfile="${PERF_RECORD_LOGS[${#PERF_RECORD_LOGS[@]}-1]}" if grep -q -E "libbpf.*EPERM|Access to performance monitoring" "$logfile" || \ diff --git a/tools/perf/tests/shell/record_lbr.sh b/tools/perf/tests/shell/record_lbr.sh index 8d51afeb437ba0..6b6af59db87131 100755 --- a/tools/perf/tests/shell/record_lbr.sh +++ b/tools/perf/tests/shell/record_lbr.sh @@ -1,6 +1,6 @@ #!/bin/bash # SPDX-License-Identifier: GPL-2.0 -# perf record LBR tests +# perf record LBR tests (exclusive) set -e diff --git a/tools/perf/tests/shell/record_sideband.sh b/tools/perf/tests/shell/record_sideband.sh index 2182551873be32..f16889e3fa9a75 100755 --- a/tools/perf/tests/shell/record_sideband.sh +++ b/tools/perf/tests/shell/record_sideband.sh @@ -22,7 +22,7 @@ trap trap_cleanup EXIT TERM INT can_cpu_wide() { - if ! perf record -o ${perfdata} -BN --no-bpf-event -C $1 true > /dev/null 2>&1 + if ! perf record -o ${perfdata} -BN --no-bpf-event -e cpu-clock -C $1 true > /dev/null 2>&1 then echo "record sideband test [Skipped cannot record cpu$1]" err=2 @@ -39,7 +39,7 @@ test_system_wide_tracking() can_cpu_wide 1 || return 0 # Record on CPU 0 a task running on CPU 1 - perf record -BN --no-bpf-event -o ${perfdata} -C 0 -- taskset --cpu-list 1 true + perf record -BN --no-bpf-event -e cpu-clock -o ${perfdata} -C 0 -- taskset --cpu-list 1 true # Should get MMAP events from CPU 1 mmap_cnt=`perf script -i ${perfdata} --show-mmap-events -C 1 2>/dev/null | grep MMAP | wc -l` diff --git a/tools/perf/trace/beauty/include/uapi/sound/asound.h b/tools/perf/trace/beauty/include/uapi/sound/asound.h index c11da9656e3811..767c9627324592 100644 --- a/tools/perf/trace/beauty/include/uapi/sound/asound.h +++ b/tools/perf/trace/beauty/include/uapi/sound/asound.h @@ -99,9 +99,10 @@ enum { SNDRV_HWDEP_IFACE_LINE6, /* Line6 USB processors */ SNDRV_HWDEP_IFACE_FW_MOTU, /* MOTU FireWire series */ SNDRV_HWDEP_IFACE_FW_FIREFACE, /* RME Fireface series */ + SNDRV_HWDEP_IFACE_CAIAQ, /* Native Instruments caiaq USB devices */ /* Don't forget to change the following: */ - SNDRV_HWDEP_IFACE_LAST = SNDRV_HWDEP_IFACE_FW_FIREFACE + SNDRV_HWDEP_IFACE_LAST = SNDRV_HWDEP_IFACE_CAIAQ }; struct snd_hwdep_info { diff --git a/tools/perf/trace/beauty/ioctl.c b/tools/perf/trace/beauty/ioctl.c index e19eb6ea361d72..9817f319d09a00 100644 --- a/tools/perf/trace/beauty/ioctl.c +++ b/tools/perf/trace/beauty/ioctl.c @@ -81,9 +81,11 @@ static size_t ioctl__scnprintf_kvm_cmd(int nr, int dir, char *bf, size_t size) { #include "trace/beauty/generated/ioctl/kvm_ioctl_array.c" static DEFINE_STRARRAY(kvm_ioctl_cmds, ""); + static DEFINE_STRARRAY(kvm_ioctl_read_cmds, ""); + struct strarray *s = (dir & _IOC_READ) ? &strarray__kvm_ioctl_read_cmds : &strarray__kvm_ioctl_cmds; - if (nr < strarray__kvm_ioctl_cmds.nr_entries && strarray__kvm_ioctl_cmds.entries[nr] != NULL) - return scnprintf(bf, size, "KVM_%s", strarray__kvm_ioctl_cmds.entries[nr]); + if (nr < s->nr_entries && s->entries[nr] != NULL) + return scnprintf(bf, size, "KVM_%s", s->entries[nr]); return scnprintf(bf, size, "(%#x, %#x, %#x)", 0xAE, nr, dir); } diff --git a/tools/perf/trace/beauty/kvm_ioctl.sh b/tools/perf/trace/beauty/kvm_ioctl.sh index bd0efd45fa9db5..8a3fedc8fcbea6 100755 --- a/tools/perf/trace/beauty/kvm_ioctl.sh +++ b/tools/perf/trace/beauty/kvm_ioctl.sh @@ -6,6 +6,15 @@ printf "static const char *kvm_ioctl_cmds[] = {\n" regex='^#[[:space:]]*define[[:space:]]+KVM_(\w+)[[:space:]]+_IO[RW]*\([[:space:]]*KVMIO[[:space:]]*,[[:space:]]*(0x[[:xdigit:]]+).*' grep -E $regex ${header_dir}/kvm.h | \ + grep -E "_IO(W)?[[:space:]]*\(" | \ + sed -r "s/$regex/\2 \1/g" | \ + grep -E -v " ((ARM|PPC|S390)_|[GS]ET_(DEBUGREGS|PIT2|XSAVE|TSC_KHZ)|CREATE_SPAPR_TCE_64)" | \ + sort | xargs printf "\t[%s] = \"%s\",\n" +printf "};\n" + +printf "static const char *kvm_ioctl_read_cmds[] = {\n" +grep -E $regex ${header_dir}/kvm.h | \ + grep -E "_IO(W)?R[[:space:]]*\(" | \ sed -r "s/$regex/\2 \1/g" | \ grep -E -v " ((ARM|PPC|S390)_|[GS]ET_(DEBUGREGS|PIT2|XSAVE|TSC_KHZ)|CREATE_SPAPR_TCE_64)" | \ sort | xargs printf "\t[%s] = \"%s\",\n" diff --git a/tools/perf/util/hist.c b/tools/perf/util/hist.c index e75a4fcce975a7..364754e9d12aa0 100644 --- a/tools/perf/util/hist.c +++ b/tools/perf/util/hist.c @@ -1055,7 +1055,7 @@ iter_add_next_branch_entry(struct hist_entry_iter *iter, struct addr_location *a * and not events sampled. Thus we use a pseudo period of 1. */ sample->period = 1; - sample->weight = bi->flags.cycles ? bi->flags.cycles : 1; + sample->weight = bi[i].flags.cycles ? bi[i].flags.cycles : 1; he = hists__add_entry(hists, al, iter->parent, &bi[i], NULL, NULL, sample, true); diff --git a/tools/perf/util/kvm-stat-arch/kvm-stat-arm64.c b/tools/perf/util/kvm-stat-arch/kvm-stat-arm64.c index 018b0db0e6e7d2..ff853ef68aa5d3 100644 --- a/tools/perf/util/kvm-stat-arch/kvm-stat-arm64.c +++ b/tools/perf/util/kvm-stat-arch/kvm-stat-arm64.c @@ -36,13 +36,7 @@ static void event_get_key(struct perf_sample *sample, } static bool event_begin(struct perf_sample *sample, - struct event_key *key __maybe_unused) -{ - return evsel__name_is(sample->evsel, kvm_entry_trace(EM_AARCH64)); -} - -static bool event_end(struct perf_sample *sample, - struct event_key *key) + struct event_key *key) { if (evsel__name_is(sample->evsel, kvm_exit_trace(EM_AARCH64))) { event_get_key(sample, key); @@ -51,6 +45,12 @@ static bool event_end(struct perf_sample *sample, return false; } +static bool event_end(struct perf_sample *sample, + struct event_key *key __maybe_unused) +{ + return evsel__name_is(sample->evsel, kvm_entry_trace(EM_AARCH64)); +} + static const struct kvm_events_ops exit_events = { .is_begin_event = event_begin, .is_end_event = event_end, diff --git a/tools/perf/util/mmap.c b/tools/perf/util/mmap.c index 6dcc4a9304b926..d6fbde9699bfcf 100644 --- a/tools/perf/util/mmap.c +++ b/tools/perf/util/mmap.c @@ -292,8 +292,8 @@ int mmap__mmap(struct mmap *map, struct mmap_params *mp, int fd, struct perf_cpu return -1; } - if (mp->affinity != PERF_AFFINITY_SYS && - perf_mmap__setup_affinity_mask(map, mp)) { + if (cpu.cpu >= 0 && mp->affinity != PERF_AFFINITY_SYS && + perf_mmap__setup_affinity_mask(map, mp)) { pr_debug2("failed to alloc mmap affinity mask, error %d\n", errno); return -1; diff --git a/tools/testing/cxl/test/cxl.c b/tools/testing/cxl/test/cxl.c index 3eb1051b1ee8a4..e3bed17ae2538f 100644 --- a/tools/testing/cxl/test/cxl.c +++ b/tools/testing/cxl/test/cxl.c @@ -2436,6 +2436,17 @@ static int cxl_topo_init(void) return cxl_type3_topo_init(); } +static void free_decoder_registry(void) +{ + unsigned long index; + void *entry; + + xa_for_each(&decoder_registry, index, entry) { + xa_erase(&decoder_registry, index); + kfree(entry); + } +} + static __init int cxl_test_init(void) { struct range mappable; @@ -2525,20 +2536,11 @@ static __init int cxl_test_init(void) gen_pool_destroy(cxl_mock_pool); err_gen_pool_create: unregister_cxl_mock_ops(&cxl_mock_ops); + free_decoder_registry(); + xa_destroy(&decoder_registry); return rc; } -static void free_decoder_registry(void) -{ - unsigned long index; - void *entry; - - xa_for_each(&decoder_registry, index, entry) { - xa_erase(&decoder_registry, index); - kfree(entry); - } -} - static __exit void cxl_test_exit(void) { hmem_test_exit(); diff --git a/tools/testing/radix-tree/maple.c b/tools/testing/radix-tree/maple.c index bfe4b8626c429d..846c67e20e82ae 100644 --- a/tools/testing/radix-tree/maple.c +++ b/tools/testing/radix-tree/maple.c @@ -36502,22 +36502,27 @@ static void regression_tests(void) test_spanning_store_regression(); } -void maple_tree_tests(void) +int maple_tree_tests(void) { + int ret; + #if !defined(BENCH) regression_tests(); farmer_tests(); #endif - maple_tree_seed(); + ret = maple_tree_seed(); maple_tree_harvest(); + return ret; } int __weak main(void) { + int ret; + maple_tree_init(); - maple_tree_tests(); + ret = maple_tree_tests(); rcu_barrier(); if (nr_allocated) printf("nr_allocated = %d\n", nr_allocated); - return 0; + return ret ? EXIT_FAILURE : EXIT_SUCCESS; } diff --git a/tools/testing/selftests/alsa/mixer-test.c b/tools/testing/selftests/alsa/mixer-test.c index 966ef83354b979..eabbe8dfd1c9fa 100644 --- a/tools/testing/selftests/alsa/mixer-test.c +++ b/tools/testing/selftests/alsa/mixer-test.c @@ -490,6 +490,21 @@ static bool strend(const char *haystack, const char *needle) return strcmp(haystack + haystack_len - needle_len, needle) == 0; } +static bool ctl_has_db_scale(struct ctl_data *ctl) +{ + unsigned int tlv[256]; + long min, max; + + if (!snd_ctl_elem_info_is_tlv_readable(ctl->info)) + return false; + if (snd_ctl_elem_tlv_read(ctl->card->handle, ctl->id, tlv, sizeof(tlv)) < 0) + return false; + + min = snd_ctl_elem_info_get_min(ctl->info); + max = snd_ctl_elem_info_get_max(ctl->info); + return snd_tlv_get_dB_range(tlv, min, max, &min, &max) == 0; +} + static void test_ctl_name(struct ctl_data *ctl) { bool name_ok = true; @@ -516,6 +531,16 @@ static void test_ctl_name(struct ctl_data *ctl) } } + /* Writeable integer controls with a dB scale should end in Volume */ + if (snd_ctl_elem_info_get_type(ctl->info) == SND_CTL_ELEM_TYPE_INTEGER && + snd_ctl_elem_info_is_writable(ctl->info) && ctl_has_db_scale(ctl)) { + if (!strend(ctl->name, " Volume")) { + ksft_print_msg("%d.%d %s has a dB scale but is not a Volume\n", + ctl->card->card, ctl->elem, ctl->name); + name_ok = false; + } + } + ksft_test_result(name_ok, "name.%s.%d\n", ctl->card->card_name, ctl->elem); } diff --git a/tools/testing/selftests/alsa/seq-ump-test.c b/tools/testing/selftests/alsa/seq-ump-test.c index 55bb7ea5b02f9f..5745cfd522972f 100644 --- a/tools/testing/selftests/alsa/seq-ump-test.c +++ b/tools/testing/selftests/alsa/seq-ump-test.c @@ -4,8 +4,8 @@ * packets between MIDI 1.0 and MIDI 2.0 clients. * * A client sends events to a UMP client, and the test checks the packets - * that the UMP client receives. The converter keeps its RPN/NRPN state - * per destination port and channel, so each test uses new clients. + * that the UMP client receives. The converter keeps its RPN/NRPN and bank + * state per destination port and channel, so each test uses new clients. */ #include #include @@ -145,6 +145,34 @@ static int send_note(struct seq_client *src, struct seq_client *dst, return 0; } +/* send a SYSEX event, with the data after the event in the same write */ +static int send_sysex(struct seq_client *src, struct seq_client *dst, + const unsigned char *data, int len) +{ + struct { + struct snd_seq_event ev; + unsigned char data[32]; + } buf; + int size = sizeof(buf.ev) + len; + + if (len > (int)sizeof(buf.data)) + return -EINVAL; + memset(&buf, 0, sizeof(buf)); + buf.ev.type = SNDRV_SEQ_EVENT_SYSEX; + buf.ev.flags = SNDRV_SEQ_TIME_STAMP_TICK | + SNDRV_SEQ_EVENT_LENGTH_VARIABLE; + buf.ev.queue = SNDRV_SEQ_QUEUE_DIRECT; + buf.ev.source.client = src->id; + buf.ev.source.port = src->port; + buf.ev.dest.client = dst->id; + buf.ev.dest.port = dst->port; + buf.ev.data.ext.len = len; + memcpy(buf.data, data, len); + if (write(src->fd, &buf, size) != size) + return -errno; + return 0; +} + /* send a UMP packet from a UMP client */ static int send_ump(struct seq_client *src, struct seq_client *dst, unsigned int w0, unsigned int w1) @@ -232,6 +260,10 @@ struct event { { SNDRV_SEQ_EVENT_CONTROLLER, ch, param, value } #define C14(ch, param, value) \ { SNDRV_SEQ_EVENT_CONTROL14, ch, param, value } +#define PGM(ch, value) \ + { SNDRV_SEQ_EVENT_PGMCHANGE, ch, 0, value } +#define SYS(type, value) \ + { SNDRV_SEQ_EVENT_##type, 0, 0, value } static int send_events(struct seq_client *src, struct seq_client *dst, const struct event *ev, int n) @@ -284,6 +316,13 @@ static int send_events(struct seq_client *src, struct seq_client *dst, #define SEND_UMP(w0, w1) \ ASSERT_EQ(0, send_ump(&self->src, &self->dst, w0, w1)) +#define SEND_SYSEX(...) do { \ + const unsigned char data[] = { __VA_ARGS__ }; \ + \ + ASSERT_EQ(0, send_sysex(&self->src, &self->dst, data, \ + sizeof(data))); \ +} while (0) + /* RPN 0/1 with Data Entry */ TEST_F(seq_ump, rpn) { @@ -482,6 +521,66 @@ TEST_F(seq_ump, key_pressure) EXPECT_PACKETS({ 0x40a24000, 0 }); } +/* + * A bank select goes with the next program change only, and a later + * bank select LSB keeps the MSB + */ +TEST_F(seq_ump, program_bank) +{ + SEND(CC(0, 0, 1), CC(0, 32, 2), PGM(0, 5)); + SEND(CC(0, 32, 3), PGM(0, 6), PGM(0, 7)); + EXPECT_PACKETS({ 0x40c00001, 0x05000102 }, + { 0x40c00001, 0x06000103 }, + { 0x40c00000, 0x07000000 }); +} + +/* the same with the bank select sent as CONTROL14 */ +TEST_F(seq_ump, c14_program_bank) +{ + SEND(C14(7, 0, (3 << 7) | 4), PGM(7, 9)); + EXPECT_PACKETS({ 0x40c70001, 0x09000304 }); +} + +/* SysEx of up to six data bytes goes in one packet */ +TEST_F(seq_ump, sysex_short) +{ + SEND_SYSEX(0xf0, 0x01, 0x02, 0x03, 0xf7); + SEND_SYSEX(0xf0, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0xf7); + EXPECT_MT_PACKETS(3, { 0x30030102, 0x03000000 }, + { 0x30060102, 0x03040506 }); +} + +/* longer SysEx goes in start, continue and end packets of six data bytes */ +TEST_F(seq_ump, sysex_long) +{ + SEND_SYSEX(0xf0, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xf7); + SEND_SYSEX(0xf0, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0xf7); + EXPECT_MT_PACKETS(3, { 0x30160102, 0x03040506 }, + { 0x30310700, 0 }, + { 0x30160102, 0x03040506 }, + { 0x30260708, 0x090a0b0c }, + { 0x30310d00, 0 }); +} + +/* SysEx sent in two events continues in the second one */ +TEST_F(seq_ump, sysex_split) +{ + SEND_SYSEX(0xf0, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08); + SEND_SYSEX(0x09, 0x0a, 0xf7); + EXPECT_MT_PACKETS(3, { 0x30160102, 0x03040506 }, + { 0x30220708, 0 }, + { 0x3032090a, 0 }); +} + +/* system messages are UMP system packets, with both song position bytes */ +TEST_F(seq_ump, system) +{ + SEND(SYS(SONGPOS, 0x1234), SYS(SONGSEL, 5), SYS(RESET, 0)); + EXPECT_MT_PACKETS(1, { 0x10f23424, 0 }, { 0x10f30500, 0 }, + { 0x10ff0000, 0 }); +} + /* a UMP MIDI 1.0 client gets the CCs as they are, RPN selection included */ TEST(midi1_passthrough) { @@ -620,4 +719,80 @@ TEST_F(seq_pair, ump_midi2_to_midi1_note) { 0x20913c01, 0 }, { 0x20813c00, 0 }); } +TEST_F(seq_pair, ump_midi2_to_midi1_rpn) +{ + int skip = 0; + int err; + + err = open_pair(&self->dst, SNDRV_SEQ_CLIENT_UMP_MIDI_1_0, + &self->src, SNDRV_SEQ_CLIENT_UMP_MIDI_2_0, &skip); + if (skip) + SKIP(return, "UMP sequencer client unavailable: %s", + strerror(-err)); + ASSERT_EQ(0, err); + + SEND_UMP(0x40210001, 0x80000000); + SEND_UMP(0x40310203, 0x12345678); + EXPECT_MT_PACKETS(2, { 0x20b16500, 0 }, { 0x20b16401, 0 }, + { 0x20b10640, 0 }, { 0x20b12600, 0 }, + { 0x20b16302, 0 }, { 0x20b16203, 0 }, + { 0x20b10609, 0 }, { 0x20b1260d, 0 }); +} + +/* the same system messages to a UMP MIDI 1.0 client */ +TEST_F(seq_pair, midi1_system) +{ + int skip = 0; + int err; + + err = open_pair(&self->dst, SNDRV_SEQ_CLIENT_UMP_MIDI_1_0, + &self->src, 0, &skip); + if (skip) + SKIP(return, "UMP sequencer client unavailable: %s", + strerror(-err)); + ASSERT_EQ(0, err); + + SEND(SYS(SONGPOS, 0x1234), SYS(SONGSEL, 5), SYS(RESET, 0)); + EXPECT_MT_PACKETS(1, { 0x10f23424, 0 }, { 0x10f30500, 0 }, + { 0x10ff0000, 0 }); +} + +/* UMP MIDI 1.0 to MIDI 2.0: the bank select CCs go into the program change */ +TEST_F(seq_pair, ump_midi1_to_midi2_program) +{ + int skip = 0; + int err; + + err = open_pair(&self->dst, SNDRV_SEQ_CLIENT_UMP_MIDI_2_0, + &self->src, SNDRV_SEQ_CLIENT_UMP_MIDI_1_0, &skip); + if (skip) + SKIP(return, "UMP sequencer client unavailable: %s", + strerror(-err)); + ASSERT_EQ(0, err); + + SEND_UMP(0x20b00001, 0); + SEND_UMP(0x20b02002, 0); + SEND_UMP(0x20c00500, 0); + EXPECT_PACKETS({ 0x40c00001, 0x05000102 }); +} + +/* UMP MIDI 2.0 to MIDI 1.0: a program change with a bank is three messages */ +TEST_F(seq_pair, ump_midi2_to_midi1_program) +{ + int skip = 0; + int err; + + err = open_pair(&self->dst, SNDRV_SEQ_CLIENT_UMP_MIDI_1_0, + &self->src, SNDRV_SEQ_CLIENT_UMP_MIDI_2_0, &skip); + if (skip) + SKIP(return, "UMP sequencer client unavailable: %s", + strerror(-err)); + ASSERT_EQ(0, err); + + SEND_UMP(0x40c00001, 0x05000102); + SEND_UMP(0x40c00000, 0x06000000); + EXPECT_MT_PACKETS(2, { 0x20b00001, 0 }, { 0x20b02002, 0 }, + { 0x20c00500, 0 }, { 0x20c00600, 0 }); +} + TEST_HARNESS_MAIN diff --git a/tools/testing/selftests/bpf/prog_tests/bpf_iter.c b/tools/testing/selftests/bpf/prog_tests/bpf_iter.c index c69080ca14f5a1..5249b07cd62afe 100644 --- a/tools/testing/selftests/bpf/prog_tests/bpf_iter.c +++ b/tools/testing/selftests/bpf/prog_tests/bpf_iter.c @@ -1100,6 +1100,39 @@ static void test_bpf_array_map(void) bpf_iter_bpf_array_map__destroy(skel); } +static void test_bpf_array_map_rdonly(void) +{ + DECLARE_LIBBPF_OPTS(bpf_iter_attach_opts, opts); + struct bpf_iter_bpf_array_map *skel; + union bpf_iter_link_info linfo = {}; + struct bpf_link *link; + int err; + + skel = bpf_iter_bpf_array_map__open(); + if (!ASSERT_OK_PTR(skel, "bpf_iter_bpf_array_map__open")) + return; + + err = bpf_map__set_map_flags(skel->maps.arraymap1, BPF_F_RDONLY_PROG); + if (!ASSERT_OK(err, "set_map_flags")) + goto out; + + err = bpf_iter_bpf_array_map__load(skel); + if (!ASSERT_OK(err, "bpf_iter_bpf_array_map__load")) + goto out; + + linfo.map.map_fd = bpf_map__fd(skel->maps.arraymap1); + opts.link_info = &linfo; + opts.link_info_len = sizeof(linfo); + link = bpf_program__attach_iter(skel->progs.dump_bpf_array_map, &opts); + err = libbpf_get_error(link); + ASSERT_EQ(err, -EACCES, "attach_rdonly_write_iter"); + if (!err) + bpf_link__destroy(link); + +out: + bpf_iter_bpf_array_map__destroy(skel); +} + static void test_bpf_array_map_iter_fd(void) { struct bpf_iter_bpf_array_map *skel; @@ -1770,6 +1803,8 @@ void test_bpf_iter(void) test_bpf_percpu_hash_map(); if (test__start_subtest("bpf_array_map")) test_bpf_array_map(); + if (test__start_subtest("bpf_array_map_rdonly")) + test_bpf_array_map_rdonly(); if (test__start_subtest("bpf_array_map_iter_fd")) test_bpf_array_map_iter_fd(); if (test__start_subtest("bpf_percpu_array_map")) diff --git a/tools/testing/selftests/bpf/prog_tests/verifier.c b/tools/testing/selftests/bpf/prog_tests/verifier.c index 6a494c38126601..5a31f04677e0f1 100644 --- a/tools/testing/selftests/bpf/prog_tests/verifier.c +++ b/tools/testing/selftests/bpf/prog_tests/verifier.c @@ -131,6 +131,7 @@ #include "verifier_unpriv.skel.h" #include "verifier_unwind.skel.h" #include "verifier_unpriv_perf.skel.h" +#include "verifier_uprobe_write_ctx.skel.h" #include "verifier_value_adj_spill.skel.h" #include "verifier_value.skel.h" #include "verifier_value_illegal_alu.skel.h" @@ -321,6 +322,7 @@ void test_verifier_uninit(void) { RUN(verifier_uninit); } void test_verifier_unpriv(void) { RUN(verifier_unpriv); } void test_verifier_unwind(void) { RUN(verifier_unwind); } void test_verifier_unpriv_perf(void) { RUN(verifier_unpriv_perf); } +void test_verifier_uprobe_write_ctx(void) { RUN(verifier_uprobe_write_ctx); } void test_verifier_value_adj_spill(void) { RUN(verifier_value_adj_spill); } void test_verifier_value(void) { RUN(verifier_value); } void test_verifier_value_illegal_alu(void) { RUN(verifier_value_illegal_alu); } diff --git a/tools/testing/selftests/bpf/progs/bpf_iter_unix.c b/tools/testing/selftests/bpf/progs/bpf_iter_unix.c index 3061b148f3388a..90beada0386d41 100644 --- a/tools/testing/selftests/bpf/progs/bpf_iter_unix.c +++ b/tools/testing/selftests/bpf/progs/bpf_iter_unix.c @@ -7,13 +7,6 @@ char _license[] SEC("license") = "GPL"; -SEC(".maps") struct { - __uint(type, BPF_MAP_TYPE_SOCKMAP); - __uint(max_entries, 1); - __type(key, __u32); - __type(value, __u64); -} sockmap; - static long sock_i_ino(const struct sock *sk) { const struct socket *sk_socket = sk->sk_socket; @@ -82,8 +75,5 @@ int dump_unix(struct bpf_iter__unix *ctx) BPF_SEQ_PRINTF(seq, "\n"); - /* Test for deadlock. */ - bpf_map_update_elem(&sockmap, &(int){0}, sk, 0); - return 0; } diff --git a/tools/testing/selftests/bpf/progs/sock_destroy_prog_fail.c b/tools/testing/selftests/bpf/progs/sock_destroy_prog_fail.c index dd6850b58e2590..7b9f5779a184e2 100644 --- a/tools/testing/selftests/bpf/progs/sock_destroy_prog_fail.c +++ b/tools/testing/selftests/bpf/progs/sock_destroy_prog_fail.c @@ -20,3 +20,14 @@ int BPF_PROG(trace_tcp_destroy_sock, struct sock *sk) return 0; } +SEC("iter/sockmap") +__failure __msg("calling kernel function bpf_sock_destroy is not allowed") +int iter_sockmap_destroy(struct bpf_iter__sockmap *ctx) +{ + struct sock *sk = ctx->sk; + + if (sk) + bpf_sock_destroy((struct sock_common *)sk); + + return 0; +} diff --git a/tools/testing/selftests/bpf/progs/verifier_sockmap_mutate.c b/tools/testing/selftests/bpf/progs/verifier_sockmap_mutate.c index 20332a731d4e4f..0dbbc5ad1de949 100644 --- a/tools/testing/selftests/bpf/progs/verifier_sockmap_mutate.c +++ b/tools/testing/selftests/bpf/progs/verifier_sockmap_mutate.c @@ -10,13 +10,12 @@ char _license[] SEC("license") = "GPL"; -struct sock { +struct bpf_iter__sockmap { + struct sock *sk; } __attribute__((preserve_access_index)); -struct bpf_iter__sockmap { - union { - struct sock *sk; - }; +struct bpf_iter__unix { + struct sock *unix_sk; } __attribute__((preserve_access_index)); struct { @@ -113,6 +112,14 @@ int test_trace_iter(struct bpf_iter__sockmap *ctx) return 0; } +SEC("iter/unix") +__failure __msg("cannot update sockmap in this context") +int test_trace_iter_unix(struct bpf_iter__unix *ctx) +{ + test_sockmap_mutate(ctx->unix_sk); + return 0; +} + SEC("raw_tp/kfree") __failure __msg("cannot update sockmap in this context") int test_raw_tp_delete(const void *ctx __always_unused) diff --git a/tools/testing/selftests/bpf/progs/verifier_uprobe_write_ctx.c b/tools/testing/selftests/bpf/progs/verifier_uprobe_write_ctx.c new file mode 100644 index 00000000000000..f5ed453b179823 --- /dev/null +++ b/tools/testing/selftests/bpf/progs/verifier_uprobe_write_ctx.c @@ -0,0 +1,196 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include "vmlinux.h" +#include +#include "bpf_misc.h" + +/* + * A uprobe prog can write only the registers that ptrace can set to any + * value. The fields the kernel restores on the way to user space (segments, + * flags, privilege state) are read-only. + */ + +#define WRITE_CTX(name, field, sz) \ +__naked void name(void) \ +{ \ + asm volatile (" \ + r2 = 0; \ + *(" #sz " *)(r1 + %[off]) = r2; \ + r0 = 0; \ + exit; \ +" : \ + : __imm_const(off, offsetof(struct pt_regs, field)) \ + : __clobber_all); \ +} + +#define READ_CTX(name, field) \ +__naked void name(void) \ +{ \ + asm volatile (" \ + r0 = *(u64 *)(r1 + %[off]); \ + r0 = 0; \ + exit; \ +" : \ + : __imm_const(off, offsetof(struct pt_regs, field)) \ + : __clobber_all); \ +} + +#if defined(__TARGET_ARCH_x86) + +SEC("uprobe") +__description("uprobe: write ctx->ax") +__success +WRITE_CTX(write_ax, ax, u64) + +SEC("uprobe") +__description("uprobe: write ctx->r15") +__success +WRITE_CTX(write_r15, r15, u64) + +SEC("uprobe") +__description("uprobe: write ctx->di") +__success +WRITE_CTX(write_di, di, u64) + +SEC("uprobe") +__description("uprobe: write ctx->ip") +__success +WRITE_CTX(write_ip, ip, u64) + +SEC("uprobe") +__description("uprobe: write ctx->sp") +__success +WRITE_CTX(write_sp, sp, u64) + +SEC("uprobe") +__description("uprobe: write lower half of ctx->ax") +__success +WRITE_CTX(write_ax_u32, ax, u32) + +SEC("uprobe") +__description("uprobe: write ctx->orig_ax") +__failure __msg("invalid bpf_context access") +WRITE_CTX(write_orig_ax, orig_ax, u64) + +SEC("uprobe") +__description("uprobe: write ctx->cs") +__failure __msg("invalid bpf_context access") +WRITE_CTX(write_cs, cs, u64) + +SEC("uprobe") +__description("uprobe: write lower half of ctx->cs") +__failure __msg("invalid bpf_context access") +WRITE_CTX(write_cs_u32, cs, u32) + +SEC("uprobe") +__description("uprobe: write ctx->flags") +__failure __msg("invalid bpf_context access") +WRITE_CTX(write_flags, flags, u64) + +SEC("uprobe") +__description("uprobe: write ctx->ss") +__failure __msg("invalid bpf_context access") +WRITE_CTX(write_ss, ss, u64) + +SEC("uprobe") +__description("uprobe: read ctx->flags") +__success +READ_CTX(read_flags, flags) + +SEC("kprobe") +__description("kprobe: write ctx->flags") +__failure __msg("invalid bpf_context access") +WRITE_CTX(kprobe_write_flags, flags, u64) + +#elif defined(__TARGET_ARCH_arm64) + +SEC("uprobe") +__description("uprobe: write ctx->regs[0]") +__success +WRITE_CTX(write_x0, regs[0], u64) + +SEC("uprobe") +__description("uprobe: write ctx->regs[30]") +__success +WRITE_CTX(write_x30, regs[30], u64) + +SEC("uprobe") +__description("uprobe: write ctx->sp") +__success +WRITE_CTX(write_sp, sp, u64) + +SEC("uprobe") +__description("uprobe: write ctx->pc") +__success +WRITE_CTX(write_pc, pc, u64) + +SEC("uprobe") +__description("uprobe: write ctx->pstate") +__failure __msg("invalid bpf_context access") +WRITE_CTX(write_pstate, pstate, u64) + +SEC("uprobe") +__description("uprobe: write lower half of ctx->pstate") +__failure __msg("invalid bpf_context access") +WRITE_CTX(write_pstate_u32, pstate, u32) + +SEC("uprobe") +__description("uprobe: write ctx->orig_x0") +__failure __msg("invalid bpf_context access") +WRITE_CTX(write_orig_x0, orig_x0, u64) + +SEC("uprobe") +__description("uprobe: read ctx->pstate") +__success +READ_CTX(read_pstate, pstate) + +#elif defined(__TARGET_ARCH_riscv) + +SEC("uprobe") +__description("uprobe: write ctx->epc") +__success +WRITE_CTX(write_epc, epc, u64) + +SEC("uprobe") +__description("uprobe: write ctx->a0") +__success +WRITE_CTX(write_a0, a0, u64) + +SEC("uprobe") +__description("uprobe: write ctx->t6") +__success +WRITE_CTX(write_t6, t6, u64) + +SEC("uprobe") +__description("uprobe: write ctx->status") +__failure __msg("invalid bpf_context access") +WRITE_CTX(write_status, status, u64) + +SEC("uprobe") +__description("uprobe: write ctx->badaddr") +__failure __msg("invalid bpf_context access") +WRITE_CTX(write_badaddr, badaddr, u64) + +SEC("uprobe") +__description("uprobe: write ctx->cause") +__failure __msg("invalid bpf_context access") +WRITE_CTX(write_cause, cause, u64) + +SEC("uprobe") +__description("uprobe: read ctx->status") +__success +READ_CTX(read_status, status) + +#else + +SEC("uprobe") +__description("uprobe: ctx writes not checked on this arch") +__success +__naked void unsupported(void) +{ + asm volatile ("r0 = 0; exit;" ::: __clobber_all); +} + +#endif + +char _license[] SEC("license") = "GPL"; diff --git a/tools/testing/selftests/bpf/test_kmods/bpf_testmod.c b/tools/testing/selftests/bpf/test_kmods/bpf_testmod.c index 76fbe64755ef95..7c5255ac49a340 100644 --- a/tools/testing/selftests/bpf/test_kmods/bpf_testmod.c +++ b/tools/testing/selftests/bpf/test_kmods/bpf_testmod.c @@ -2500,13 +2500,15 @@ int bpf_kfunc_multi_st_ops_test_1(struct st_ops_args *args, u32 id) return ret; } +static struct bpf_struct_ops testmod_multi_st_ops; + /* Call test_1() of the associated struct_ops map */ int bpf_kfunc_multi_st_ops_test_1_assoc(struct st_ops_args *args, struct bpf_prog_aux *aux) { struct bpf_testmod_multi_st_ops *st_ops; int ret = -1; - st_ops = (struct bpf_testmod_multi_st_ops *)bpf_prog_get_assoc_struct_ops(aux); + st_ops = bpf_prog_get_assoc_struct_ops(aux, &testmod_multi_st_ops); if (st_ops) ret = st_ops->test_1(args); @@ -2584,7 +2586,7 @@ static struct bpf_testmod_multi_st_ops multi_st_ops_cfi_stubs = { .test_1 = bpf_testmod_multi_st_ops__test_1, }; -struct bpf_struct_ops testmod_multi_st_ops = { +static struct bpf_struct_ops testmod_multi_st_ops = { .verifier_ops = &bpf_testmod_verifier_ops, .init = multi_st_ops_init, .init_member = multi_st_ops_init_member, diff --git a/tools/testing/selftests/damon/sysfs_memcg_path_leak.sh b/tools/testing/selftests/damon/sysfs_memcg_path_leak.sh index 34c37129c49fe1..d407dddb879ece 100755 --- a/tools/testing/selftests/damon/sysfs_memcg_path_leak.sh +++ b/tools/testing/selftests/damon/sysfs_memcg_path_leak.sh @@ -1,6 +1,9 @@ #!/bin/bash # SPDX-License-Identifier: GPL-2.0 +# Kselftest framework requirement - SKIP code is 4. +ksft_skip=4 + if [ $EUID -ne 0 ] then echo "Run as root" diff --git a/tools/testing/selftests/drivers/net/stats.py b/tools/testing/selftests/drivers/net/stats.py index b08e4d48b15ce4..e61db30b51817b 100755 --- a/tools/testing/selftests/drivers/net/stats.py +++ b/tools/testing/selftests/drivers/net/stats.py @@ -220,6 +220,28 @@ def check_down(cfg) -> None: netfam.qstats_get({"ifindex": cfg.ifindex, "scope": "queue"}, dump=True) +@ksft_disruptive +def check_down_ts_stats(cfg) -> None: + """Test timestamping stats are not impacted by ifdown""" + + req = {"header": {"dev-index": cfg.ifindex, "flags": {"stats"}}} + try: + stats = ethnl.tsinfo_get(req).get("stats") + except NlError as e: + if e.error == errno.EOPNOTSUPP: + raise KsftSkipEx("timestamping not supported by the device") from e + raise + if not stats: + raise KsftSkipEx("timestamping stats not supported by the device") + + ip(f"link set dev {cfg.dev['ifname']} down") + defer(ip, f"link set dev {cfg.dev['ifname']} up") + + stats2 = ethnl.tsinfo_get(req).get("stats", {}) + for k in stats: + ksft_ge(stats2[k], stats[k], comment=f"{k} went backwards on device down") + + def __run_inf_loop(body): body = body.strip() if body[-1] != ';': @@ -311,7 +333,8 @@ def main() -> None: with NetDrvEnv(__file__, queue_count=100) as cfg: ksft_run([check_pause, check_fec, check_fec_hist, pkt_byte_sum, - qstat_by_ifindex, check_down, procfs_hammer, + qstat_by_ifindex, check_down, check_down_ts_stats, + procfs_hammer, procfs_downup_hammer], args=(cfg, )) ksft_exit() diff --git a/tools/testing/selftests/drivers/s390x/uvdevice/Makefile b/tools/testing/selftests/drivers/s390x/uvdevice/Makefile index 755d164384c46f..586a9aa6fb1581 100644 --- a/tools/testing/selftests/drivers/s390x/uvdevice/Makefile +++ b/tools/testing/selftests/drivers/s390x/uvdevice/Makefile @@ -1,20 +1,13 @@ include ../../../../../build/Build.include -UNAME_M := $(shell uname -m) - -ifneq ($(UNAME_M),s390x) -nothing: -.PHONY: all clean run_tests install -.SILENT: -else +top_srcdir ?= ../../../../../.. +include $(top_srcdir)/scripts/subarch.include +ARCH_PROCESSED := $(or $(ARCH),$(SUBARCH)) +ifneq (,$(filter s390 s390x,$(ARCH_PROCESSED))) TEST_GEN_PROGS := test_uvdevice -top_srcdir ?= ../../../../../.. -LINUX_TOOL_ARCH_INCLUDE = $(top_srcdir)/tools/arch/$(ARCH)/include - -CFLAGS += -Wall -Werror -static $(KHDR_INCLUDES) -I$(LINUX_TOOL_ARCH_INCLUDE) +CFLAGS += -Wall -Werror -static $(KHDR_INCLUDES) +endif include ../../../lib.mk - -endif diff --git a/tools/testing/selftests/filesystems/fuse/write_extend_eof_test.c b/tools/testing/selftests/filesystems/fuse/write_extend_eof_test.c index ca6ce6eca382ef..d6d5de8dac275a 100644 --- a/tools/testing/selftests/filesystems/fuse/write_extend_eof_test.c +++ b/tools/testing/selftests/filesystems/fuse/write_extend_eof_test.c @@ -25,24 +25,46 @@ #include #include #include +#include #include #include #include "../../kselftest_harness.h" #define FUSE_ROOT_ID 1 -#define FILE_INO 2 +#define FILE_INO 2 /* "file", the file being extended */ +#define SRC_INO 3 /* "src", copy_file_range() source */ #define MAX_WRITE (128 * 1024) #define BACKING_SIZE (4 * 1024 * 1024) #define POLLUTE 0xee +/* Called directly: the libc wrapper needs off64_t and a recent enough glibc. */ +static ssize_t sys_copy_file_range(int fd_in, int64_t *off_in, int fd_out, + int64_t *off_out, size_t len, + unsigned int flags) +{ + return syscall(__NR_copy_file_range, fd_in, off_in, fd_out, off_out, + len, flags); +} + +/* Per-file server state. */ +struct backing_file { + unsigned char data[BACKING_SIZE]; /* authoritative bytes */ + uint64_t size; +}; + /* Server-side state, shared with the responder thread. */ struct server { int fd; - unsigned char backing[BACKING_SIZE]; /* authoritative bytes */ - uint64_t size; + unsigned int copy_ops; /* FUSE_COPY_FILE_RANGE* seen */ + struct backing_file file[2]; /* FILE_INO, SRC_INO */ }; +static struct backing_file *lookup_file(struct server *s, uint64_t nodeid) +{ + return &s->file[nodeid == SRC_INO]; +} + static void reply(int fd, uint64_t unique, int error, void *data, size_t len) { struct fuse_out_header oh = { @@ -109,17 +131,22 @@ static void *server_thread(void *arg) out.attr_valid = 3600; fill_attr(&out.attr, ih->nodeid, root ? (S_IFDIR | 0755) : (S_IFREG | 0644), - root ? 0 : s->size); + root ? 0 : lookup_file(s, ih->nodeid)->size); reply(s->fd, ih->unique, 0, &out, sizeof(out)); break; } case FUSE_LOOKUP: { + const char *name = (const char *)(ih + 1); struct fuse_entry_out out = {0}; + uint64_t nodeid; - out.nodeid = FILE_INO; + /* Every name exists; "src" is the second file. */ + nodeid = strcmp(name, "src") ? FILE_INO : SRC_INO; + out.nodeid = nodeid; out.attr_valid = 3600; out.entry_valid = 3600; - fill_attr(&out.attr, FILE_INO, S_IFREG | 0644, s->size); + fill_attr(&out.attr, nodeid, S_IFREG | 0644, + lookup_file(s, nodeid)->size); reply(s->fd, ih->unique, 0, &out, sizeof(out)); break; } @@ -134,6 +161,7 @@ static void *server_thread(void *arg) } case FUSE_READ: { struct fuse_read_in *in = (void *)(ih + 1); + struct backing_file *f = lookup_file(s, ih->nodeid); uint64_t off = in->offset; uint32_t size = in->size; @@ -141,11 +169,12 @@ static void *server_thread(void *arg) size = 0; else if (off + size > BACKING_SIZE) size = BACKING_SIZE - off; - reply(s->fd, ih->unique, 0, s->backing + off, size); + reply(s->fd, ih->unique, 0, f->data + off, size); break; } case FUSE_WRITE: { struct fuse_write_in *in = (void *)(ih + 1); + struct backing_file *f = lookup_file(s, ih->nodeid); struct fuse_write_out out = {0}; uint64_t off = in->offset; uint32_t size = in->size; @@ -155,9 +184,9 @@ static void *server_thread(void *arg) if (off + c > BACKING_SIZE) c = BACKING_SIZE - off; - memcpy(s->backing + off, in + 1, c); - if (off + c > s->size) - s->size = off + c; + memcpy(f->data + off, in + 1, c); + if (off + c > f->size) + f->size = off + c; } out.size = size; reply(s->fd, ih->unique, 0, &out, sizeof(out)); @@ -165,32 +194,70 @@ static void *server_thread(void *arg) } case FUSE_SETATTR: { struct fuse_setattr_in *in = (void *)(ih + 1); + struct backing_file *f = lookup_file(s, ih->nodeid); struct fuse_attr_out out = {0}; if ((in->valid & FATTR_SIZE) && in->size <= BACKING_SIZE) { - if (in->size > s->size) - memset(s->backing + s->size, 0, - in->size - s->size); - s->size = in->size; + if (in->size > f->size) + memset(f->data + f->size, 0, + in->size - f->size); + f->size = in->size; } out.attr_valid = 3600; - fill_attr(&out.attr, ih->nodeid, S_IFREG | 0644, s->size); + fill_attr(&out.attr, ih->nodeid, S_IFREG | 0644, f->size); reply(s->fd, ih->unique, 0, &out, sizeof(out)); break; } case FUSE_FALLOCATE: { struct fuse_fallocate_in *in = (void *)(ih + 1); + struct backing_file *f = lookup_file(s, ih->nodeid); uint64_t end = in->offset + in->length; /* Only plain (size-extending) fallocate is used here. */ if (!(in->mode & FALLOC_FL_KEEP_SIZE) && - end <= BACKING_SIZE && end > s->size) { - memset(s->backing + s->size, 0, end - s->size); - s->size = end; + end <= BACKING_SIZE && end > f->size) { + memset(f->data + f->size, 0, end - f->size); + f->size = end; } reply(s->fd, ih->unique, 0, NULL, 0); break; } + case FUSE_COPY_FILE_RANGE: + case FUSE_COPY_FILE_RANGE_64: { + struct fuse_copy_file_range_in *in = (void *)(ih + 1); + struct backing_file *src = lookup_file(s, ih->nodeid); + struct backing_file *dst; + struct fuse_copy_file_range_out out64 = {0}; + struct fuse_write_out out = {0}; + uint64_t off_in = in->off_in; + uint64_t off_out = in->off_out; + uint64_t len = in->len; + + dst = lookup_file(s, in->nodeid_out); + s->copy_ops++; + if (off_in >= BACKING_SIZE || off_out >= BACKING_SIZE) { + len = 0; + } else { + if (off_in + len > BACKING_SIZE) + len = BACKING_SIZE - off_in; + if (off_out + len > BACKING_SIZE) + len = BACKING_SIZE - off_out; + /* The hole left behind stays zero. */ + memmove(dst->data + off_out, src->data + off_in, + len); + if (off_out + len > dst->size) + dst->size = off_out + len; + } + if (ih->opcode == FUSE_COPY_FILE_RANGE) { + out.size = len; + reply(s->fd, ih->unique, 0, &out, sizeof(out)); + } else { + out64.bytes_copied = len; + reply(s->fd, ih->unique, 0, &out64, + sizeof(out64)); + } + break; + } case FUSE_FLUSH: case FUSE_RELEASE: case FUSE_RELEASEDIR: @@ -337,6 +404,46 @@ TEST_F(fuse, fallocate_extend) assert_tail_zeroed(_metadata, self); } +/* + * Extend via copy_file_range() landing on a page strictly past the old EOF + * page, so neither the copied range nor the flush of either file touches the + * old EOF folio. The source has to be a separate file: copying within one + * file would flush it from the source offset on, and writeback zeroes the + * post-EOF tail on the way out, hiding the bug. + */ +TEST_F(fuse, copy_file_range_extend) +{ + int64_t off_in = 0; + int64_t off_out; + char path[128]; + char *buf; + ssize_t ret; + int src; + + pollute_eof_tail(_metadata, self); + off_out = 5 * self->page; + + snprintf(path, sizeof(path), "%s/src", self->dir); + src = open(path, O_RDWR | O_CREAT | O_TRUNC, 0644); + ASSERT_GE(src, 0); + + buf = malloc(self->page); + ASSERT_NE(NULL, buf); + memset(buf, 'C', self->page); + ASSERT_EQ(self->page, pwrite(src, buf, self->page, 0)); + free(buf); + + ret = sys_copy_file_range(src, &off_in, self->fd, &off_out, + self->page, 0); + ASSERT_EQ(self->page, ret); + close(src); + + /* A splice fallback would extend via the write path instead. */ + ASSERT_NE(0u, self->srv->copy_ops); + + assert_tail_zeroed(_metadata, self); +} + /* A write landing inside the old EOF page must not clobber its own data. */ TEST_F(fuse, extend_into_eof_page_preserves_data) { diff --git a/tools/testing/selftests/kvm/Makefile b/tools/testing/selftests/kvm/Makefile index 03d91f00092f4a..cc279abbb00437 100644 --- a/tools/testing/selftests/kvm/Makefile +++ b/tools/testing/selftests/kvm/Makefile @@ -11,6 +11,6 @@ endif include Makefile.kvm else # Empty targets for unsupported architectures -all: -clean: +all clean run_tests install emit_tests: +.PHONY: all clean run_tests install emit_tests endif diff --git a/tools/testing/selftests/kvm/Makefile.kvm b/tools/testing/selftests/kvm/Makefile.kvm index 17a4256e908191..283c59d7649c67 100644 --- a/tools/testing/selftests/kvm/Makefile.kvm +++ b/tools/testing/selftests/kvm/Makefile.kvm @@ -319,10 +319,16 @@ arm64_hdr_outdir := $(tools_dir)/ endif GEN_HDRS := $(arm64_hdr_outdir)arch/arm64/include/generated/ +GEN_SYSREG_DEFS := $(GEN_HDRS)asm/sysreg-defs.h CFLAGS += -I$(GEN_HDRS) -$(GEN_HDRS): $(wildcard $(arm64_tools_dir)/*) +# The inner Makefile tracks the generator's inputs and leaves the header +# untouched when nothing changed, so dependents rebuild only when it does. +$(GEN_SYSREG_DEFS): FORCE $(MAKE) -C $(arm64_tools_dir) OUTPUT=$(arm64_hdr_outdir) + +FORCE: +.PHONY: FORCE endif no-pie-option := $(call try-run, echo 'int main(void) { return 0; }' | \ @@ -375,10 +381,10 @@ EXTRA_CLEAN += $(GEN_HDRS) \ $(TEST_GEN_OBJ) \ cscope.* -$(LIBKVM_C_OBJ): $(OUTPUT)/%.o: %.c $(GEN_HDRS) +$(LIBKVM_C_OBJ): $(OUTPUT)/%.o: %.c $(GEN_SYSREG_DEFS) $(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c $< -o $@ -$(LIBKVM_S_OBJ): $(OUTPUT)/%.o: %.S $(GEN_HDRS) +$(LIBKVM_S_OBJ): $(OUTPUT)/%.o: %.S $(GEN_SYSREG_DEFS) $(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c $< -o $@ # Compile the string overrides as freestanding to prevent the compiler from @@ -388,10 +394,10 @@ $(LIBKVM_STRING_OBJ): $(OUTPUT)/%.o: %.c $(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c -ffreestanding $< -o $@ $(shell mkdir -p $(sort $(dir $(TEST_GEN_PROGS)))) -$(SPLIT_TEST_GEN_OBJ): $(GEN_HDRS) +$(SPLIT_TEST_GEN_OBJ): $(GEN_SYSREG_DEFS) $(TEST_GEN_PROGS): $(LIBKVM_OBJS) $(TEST_GEN_PROGS_EXTENDED): $(LIBKVM_OBJS) -$(TEST_GEN_OBJ): $(GEN_HDRS) +$(TEST_GEN_OBJ): $(GEN_SYSREG_DEFS) cscope: include_paths = $(LINUX_TOOL_INCLUDE) $(LINUX_HDR_PATH) include lib .. cscope: diff --git a/tools/testing/selftests/kvm/arm64/get-reg-list.c b/tools/testing/selftests/kvm/arm64/get-reg-list.c index 533994687b5d82..912590f9b0c2bc 100644 --- a/tools/testing/selftests/kvm/arm64/get-reg-list.c +++ b/tools/testing/selftests/kvm/arm64/get-reg-list.c @@ -49,6 +49,7 @@ static struct feature_id_reg feat_id_regs[] = { REG_FEAT(POR_EL1, ID_AA64MMFR3_EL1, S1POE, IMP), REG_FEAT(POR_EL0, ID_AA64MMFR3_EL1, S1POE, IMP), REG_FEAT(POR_EL2, ID_AA64MMFR3_EL1, S1POE, IMP), + REG_FEAT(ACCDATA_EL1, ID_AA64ISAR1_EL1, LS64, LS64_ACCDATA), REG_FEAT(HCRX_EL2, ID_AA64MMFR1_EL1, HCX, IMP), REG_FEAT(HFGRTR_EL2, ID_AA64MMFR0_EL1, FGT, IMP), REG_FEAT(HFGWTR_EL2, ID_AA64MMFR0_EL1, FGT, IMP), @@ -517,6 +518,7 @@ static __u64 base_regs[] = { ARM64_SYS_REG(3, 0, 12, 1, 1), /* DISR_EL1 */ ARM64_SYS_REG(3, 0, 13, 0, 1), /* CONTEXTIDR_EL1 */ ARM64_SYS_REG(3, 0, 13, 0, 4), /* TPIDR_EL1 */ + ARM64_SYS_REG(3, 0, 13, 0, 5), /* ACCDATA_EL1 */ ARM64_SYS_REG(3, 0, 14, 1, 0), /* CNTKCTL_EL1 */ ARM64_SYS_REG(3, 2, 0, 0, 0), /* CSSELR_EL1 */ ARM64_SYS_REG(3, 3, 10, 2, 4), /* POR_EL0 */ diff --git a/tools/testing/selftests/kvm/arm64/hello_el2.c b/tools/testing/selftests/kvm/arm64/hello_el2.c index bbe6862c6ab16e..3bd3596f5fb1e4 100644 --- a/tools/testing/selftests/kvm/arm64/hello_el2.c +++ b/tools/testing/selftests/kvm/arm64/hello_el2.c @@ -45,6 +45,7 @@ int main(void) struct kvm_vcpu *vcpu; struct kvm_vm *vm; struct ucall uc; + u64 hcr; TEST_REQUIRE(kvm_check_cap(KVM_CAP_ARM_EL2)); @@ -66,6 +67,20 @@ int main(void) TEST_FAIL("Unhandled ucall: %ld\n", uc.cmd); } + /* + * Verify RES0/RES1 enforcement from userspace rather than inside + * the guest. From the guest's perspective RESx bits may be + * stateful (reading back as written) even though their value is + * ignored, whereas KVM_SET_ONE_REG applies the effective masks + * directly. + */ + hcr = vcpu_get_reg(vcpu, KVM_ARM64_SYS_REG(SYS_HCR_EL2)); + vcpu_set_reg(vcpu, KVM_ARM64_SYS_REG(SYS_HCR_EL2), + (hcr & ~HCR_EL2_E2H) | HCR_EL2_NV1); + hcr = vcpu_get_reg(vcpu, KVM_ARM64_SYS_REG(SYS_HCR_EL2)); + TEST_ASSERT(hcr & HCR_EL2_E2H, "HCR_EL2.E2H should be RES1"); + TEST_ASSERT(!(hcr & HCR_EL2_NV1), "HCR_EL2.NV1 should be RES0"); + kvm_vm_free(vm); return 0; } diff --git a/tools/testing/selftests/kvm/arm64/vgic_lpi_stress.c b/tools/testing/selftests/kvm/arm64/vgic_lpi_stress.c index 45a87ba5a737af..71edefc5aca445 100644 --- a/tools/testing/selftests/kvm/arm64/vgic_lpi_stress.c +++ b/tools/testing/selftests/kvm/arm64/vgic_lpi_stress.c @@ -1,6 +1,6 @@ // SPDX-License-Identifier: GPL-2.0 /* - * vgic_lpi_stress - Stress test for KVM's ITS emulation + * vgic_lpi_stress - Tests for KVM's ITS emulation * * Copyright (c) 2024 Google LLC */ @@ -28,11 +28,17 @@ static struct kvm_vm *vm; static struct kvm_vcpu **vcpus; static int its_fd; -static struct test_data { +enum move_cmd { + MOVE_MOVI, + MOVE_MAPC_MOVALL, +}; + +struct test_data { bool request_vcpus_stop; u32 nr_cpus; u32 nr_devices; u32 nr_event_ids; + enum move_cmd move_cmd; gpa_t device_table; gpa_t collection_table; @@ -42,7 +48,11 @@ static struct test_data { gpa_t lpi_prop_table; gpa_t lpi_pend_tables; -} test_data = { +}; + +static struct test_data test_data; + +static struct test_data stress_args = { .nr_cpus = 1, .nr_devices = 1, .nr_event_ids = 16, @@ -123,13 +133,8 @@ static void guest_setup_gic(void) its_send_sync_cmd(test_data.cmdq_base_va, cpuid); } -static void guest_code(size_t nr_lpis) +static void guest_wait_for_stop(void) { - guest_setup_gic(); - local_irq_enable(); - - GUEST_SYNC(0); - /* * Don't use WFI here to avoid blocking the vCPU thread indefinitely and * never getting the stop signal. @@ -140,6 +145,16 @@ static void guest_code(size_t nr_lpis) GUEST_DONE(); } +static void guest_stress_code(size_t nr_lpis) +{ + guest_setup_gic(); + local_irq_enable(); + + GUEST_SYNC(0); + + guest_wait_for_stop(); +} + static void setup_memslot(void) { gpa_t gpa_base; @@ -294,7 +309,7 @@ static void report_stats(struct timespec delta) pr_info("Rate: %.2f LPIs/sec\n", nr_lpis / time); } -static void run_test(void) +static void run_stress_test(void) { u32 nr_devices = test_data.nr_devices; u32 nr_vcpus = test_data.nr_cpus; @@ -326,10 +341,12 @@ static void run_test(void) for (i = 0; i < nr_vcpus; i++) kvm_pthread_join(vcpu_threads[i], NULL); + pthread_barrier_destroy(&test_setup_barrier); + report_stats(delta); } -static void setup_vm(void) +static void setup_vm(void *guest_code, handler_fn irq_handler) { int i; @@ -342,7 +359,7 @@ static void setup_vm(void) for (i = 0; i < test_data.nr_cpus; i++) vcpu_init_descriptor_tables(vcpus[i]); - vm_install_exception_handler(vm, VECTOR_IRQ_CURRENT, guest_irq_handler); + vm_install_exception_handler(vm, VECTOR_IRQ_CURRENT, irq_handler); setup_memslot(); @@ -358,12 +375,208 @@ static void destroy_vm(void) free(vcpus); } +static void test_lpi_stress(void) +{ + test_data = stress_args; + + setup_vm(guest_stress_code, guest_irq_handler); + + run_stress_test(); + + destroy_vm(); +} + +/* + * Pending move: A is pending at vCPU0's CPU interface and B at vCPU1's, both + * vCPUs with IRQs masked, when vCPU1 moves A to vCPU2. Once unmasked, A must + * be taken on vCPU2 only, and B on vCPU1 only. + */ +#define MOVE_NR_VCPUS 3 +#define MOVE_NR_LPIS 2 +#define MOVE_DEVICE 0 + +/* guest_setup_its_mappings() maps event N to vCPU N's collection */ +#define LPI_A 0 +#define LPI_B 1 +#define SRC_VCPU 0 +#define B_VCPU 1 +#define DST_VCPU 2 + +static atomic_uint lpi_taken[MOVE_NR_VCPUS][MOVE_NR_LPIS]; +static atomic_bool lpi_a_pending, lpi_a_moved, vcpu_unmasked[MOVE_NR_VCPUS]; + +static void guest_count_irq_handler(struct ex_regs *regs) +{ + u32 intid = gic_get_and_ack_irq(); + + if (intid == IAR_SPURIOUS) + return; + + GUEST_ASSERT(intid >= GIC_LPI_OFFSET && intid < GIC_LPI_OFFSET + MOVE_NR_LPIS); + atomic_fetch_add(&lpi_taken[guest_get_vcpuid()][intid - GIC_LPI_OFFSET], 1); + gic_set_eoi(intid); +} + +/* HPPIR shows an LPI pending at this CPU interface even with IRQs masked */ +static bool guest_lpi_pending(u32 lpi) +{ + return (read_sysreg_s(SYS_ICC_HPPIR1_EL1) & GENMASK(23, 0)) == GIC_LPI_OFFSET + lpi; +} + +static void guest_wait_pending(u32 lpi) +{ + while (!guest_lpi_pending(lpi)) + cpu_relax(); +} + +/* An LPI still pending here is taken before the host is told to check */ +static void guest_unmask(u32 lpi) +{ + local_irq_enable(); + + while (guest_lpi_pending(lpi)) + cpu_relax(); + + atomic_store(&vcpu_unmasked[guest_get_vcpuid()], true); +} + +static void guest_move_lpi_a(void) +{ + void *cmdq = test_data.cmdq_base_va; + + if (test_data.move_cmd == MOVE_MOVI) { + its_send_movi_cmd(cmdq, MOVE_DEVICE, LPI_A, DST_VCPU); + } else { + its_send_mapc_cmd(cmdq, DST_VCPU, SRC_VCPU, true); + /* The GICv3 spec's MAPC description requires this SYNC before MOVALL */ + its_send_sync_cmd(cmdq, SRC_VCPU); + its_send_movall_cmd(cmdq, SRC_VCPU, DST_VCPU); + } + + /* Complete the move at both redistributors before vCPU0 unmasks */ + its_send_sync_cmd(cmdq, SRC_VCPU); + its_send_sync_cmd(cmdq, DST_VCPU); +} + +static void guest_pending_move_code(void) +{ + u32 cpuid = guest_get_vcpuid(); + + guest_setup_gic(); + + if (cpuid == DST_VCPU) + local_irq_enable(); + + GUEST_SYNC(0); + + if (cpuid == SRC_VCPU) { + guest_wait_pending(LPI_A); + atomic_store(&lpi_a_pending, true); + + while (!atomic_load(&lpi_a_moved)) + cpu_relax(); + guest_unmask(LPI_A); + } else if (cpuid == B_VCPU) { + guest_wait_pending(LPI_B); + + while (!atomic_load(&lpi_a_pending)) + cpu_relax(); + guest_move_lpi_a(); + atomic_store(&lpi_a_moved, true); + guest_unmask(LPI_B); + } + + guest_wait_for_stop(); +} + +static unsigned int nr_lpis_taken(atomic_uint (*taken)[MOVE_NR_LPIS]) +{ + unsigned int nr = 0; + int vcpu, lpi; + + for (vcpu = 0; vcpu < MOVE_NR_VCPUS; vcpu++) + for (lpi = 0; lpi < MOVE_NR_LPIS; lpi++) + nr += atomic_load(&taken[vcpu][lpi]); + + return nr; +} + +static bool pending_move_done(atomic_uint (*taken)[MOVE_NR_LPIS], atomic_bool *unmasked) +{ + return nr_lpis_taken(taken) >= MOVE_NR_LPIS && + atomic_load(&unmasked[SRC_VCPU]) && atomic_load(&unmasked[B_VCPU]); +} + +static void check_lpi_taken(atomic_uint (*taken)[MOVE_NR_LPIS], int lpi, int want_vcpu) +{ + const char *cmd = test_data.move_cmd == MOVE_MOVI ? "MOVI" : "MAPC+MOVALL"; + unsigned int nr[MOVE_NR_VCPUS]; + bool ok = true; + int vcpu; + + for (vcpu = 0; vcpu < MOVE_NR_VCPUS; vcpu++) { + nr[vcpu] = atomic_load(&taken[vcpu][lpi]); + ok &= nr[vcpu] == (vcpu == want_vcpu); + } + + TEST_ASSERT(ok, "%s: LPI %c taken %u/%u/%u times on vCPU0/1/2, expected once on vCPU%d", + cmd, 'A' + lpi, nr[0], nr[1], nr[2], want_vcpu); +} + +static void run_pending_move_test(void) +{ + atomic_uint (*taken)[MOVE_NR_LPIS] = addr_gva2hva(vm, (gva_t)lpi_taken); + atomic_bool *unmasked = addr_gva2hva(vm, (gva_t)vcpu_unmasked); + pthread_t vcpu_threads[MOVE_NR_VCPUS]; + int i; + + pthread_barrier_init(&test_setup_barrier, NULL, MOVE_NR_VCPUS + 1); + + for (i = 0; i < MOVE_NR_VCPUS; i++) + kvm_pthread_create(&vcpu_threads[i], NULL, vcpu_worker_thread, vcpus[i]); + + pthread_barrier_wait(&test_setup_barrier); + + signal_lpi(MOVE_DEVICE, LPI_A); + signal_lpi(MOVE_DEVICE, LPI_B); + + for (i = 0; i < 10000 && !pending_move_done(taken, unmasked); i++) + usleep(1000); + + /* Check first: a vCPU still waiting for its LPI never sees the stop */ + check_lpi_taken(taken, LPI_A, DST_VCPU); + check_lpi_taken(taken, LPI_B, B_VCPU); + + write_guest_global(vm, test_data.request_vcpus_stop, true); + + for (i = 0; i < MOVE_NR_VCPUS; i++) + kvm_pthread_join(vcpu_threads[i], NULL); + + pthread_barrier_destroy(&test_setup_barrier); +} + +static void test_pending_move(enum move_cmd move_cmd) +{ + test_data = (struct test_data) { + .nr_cpus = MOVE_NR_VCPUS, + .nr_devices = 1, + .nr_event_ids = MOVE_NR_LPIS, + .move_cmd = move_cmd, + }; + + setup_vm(guest_pending_move_code, guest_count_irq_handler); + + run_pending_move_test(); + + destroy_vm(); +} + static void pr_usage(const char *name) { pr_info("%s [-v NR_VCPUS] [-d NR_DEVICES] [-e NR_EVENTS] [-i ITERS] -h\n", name); - pr_info(" -v:\tnumber of vCPUs (default: %u)\n", test_data.nr_cpus); - pr_info(" -d:\tnumber of devices (default: %u)\n", test_data.nr_devices); - pr_info(" -e:\tnumber of event IDs per device (default: %u)\n", test_data.nr_event_ids); + pr_info(" -v:\tnumber of vCPUs (default: %u)\n", stress_args.nr_cpus); + pr_info(" -d:\tnumber of devices (default: %u)\n", stress_args.nr_devices); + pr_info(" -e:\tnumber of event IDs per device (default: %u)\n", stress_args.nr_event_ids); pr_info(" -i:\tnumber of iterations (default: %lu)\n", nr_iterations); } @@ -377,13 +590,13 @@ int main(int argc, char **argv) while ((c = getopt(argc, argv, "hv:d:e:i:")) != -1) { switch (c) { case 'v': - test_data.nr_cpus = atoi(optarg); + stress_args.nr_cpus = atoi(optarg); break; case 'd': - test_data.nr_devices = atoi(optarg); + stress_args.nr_devices = atoi(optarg); break; case 'e': - test_data.nr_event_ids = atoi(optarg); + stress_args.nr_event_ids = atoi(optarg); break; case 'i': nr_iterations = strtoul(optarg, NULL, 0); @@ -395,16 +608,15 @@ int main(int argc, char **argv) } } - nr_threads = test_data.nr_cpus + test_data.nr_devices; + nr_threads = stress_args.nr_cpus + stress_args.nr_devices; if (nr_threads > get_nprocs()) pr_info("WARNING: running %u threads on %d CPUs; performance is degraded.\n", nr_threads, get_nprocs()); - setup_vm(); - - run_test(); + test_lpi_stress(); - destroy_vm(); + test_pending_move(MOVE_MOVI); + test_pending_move(MOVE_MAPC_MOVALL); return 0; } diff --git a/tools/testing/selftests/kvm/include/arm64/gic_v3_its.h b/tools/testing/selftests/kvm/include/arm64/gic_v3_its.h index a43a407e2d5c13..e30a658fbd1c3c 100644 --- a/tools/testing/selftests/kvm/include/arm64/gic_v3_its.h +++ b/tools/testing/selftests/kvm/include/arm64/gic_v3_its.h @@ -14,6 +14,8 @@ void its_send_mapc_cmd(void *cmdq_base, u32 vcpu_id, u32 collection_id, bool val void its_send_mapti_cmd(void *cmdq_base, u32 device_id, u32 event_id, u32 collection_id, u32 intid); void its_send_invall_cmd(void *cmdq_base, u32 collection_id); +void its_send_movi_cmd(void *cmdq_base, u32 device_id, u32 event_id, u32 collection_id); +void its_send_movall_cmd(void *cmdq_base, u32 from_vcpu, u32 to_vcpu); void its_send_sync_cmd(void *cmdq_base, u32 vcpu_id); #endif // __SELFTESTS_GIC_V3_ITS_H__ diff --git a/tools/testing/selftests/kvm/lib/arm64/gic_v3_its.c b/tools/testing/selftests/kvm/lib/arm64/gic_v3_its.c index 1188b578121dd3..811d858f5def65 100644 --- a/tools/testing/selftests/kvm/lib/arm64/gic_v3_its.c +++ b/tools/testing/selftests/kvm/lib/arm64/gic_v3_its.c @@ -159,6 +159,11 @@ static void its_encode_target(struct its_cmd_block *cmd, u64 target_addr) its_mask_encode(&cmd->raw_cmd[2], target_addr >> 16, 51, 16); } +static void its_encode_target2(struct its_cmd_block *cmd, u64 target_addr) +{ + its_mask_encode(&cmd->raw_cmd[3], target_addr >> 16, 51, 16); +} + static void its_encode_collection(struct its_cmd_block *cmd, u16 col) { its_mask_encode(&cmd->raw_cmd[2], col, 15, 0); @@ -253,6 +258,29 @@ void its_send_invall_cmd(void *cmdq_base, u32 collection_id) its_send_cmd(cmdq_base, &cmd); } +void its_send_movi_cmd(void *cmdq_base, u32 device_id, u32 event_id, u32 collection_id) +{ + struct its_cmd_block cmd = {}; + + its_encode_cmd(&cmd, GITS_CMD_MOVI); + its_encode_devid(&cmd, device_id); + its_encode_event_id(&cmd, event_id); + its_encode_collection(&cmd, collection_id); + + its_send_cmd(cmdq_base, &cmd); +} + +void its_send_movall_cmd(void *cmdq_base, u32 from_vcpu, u32 to_vcpu) +{ + struct its_cmd_block cmd = {}; + + its_encode_cmd(&cmd, GITS_CMD_MOVALL); + its_encode_target(&cmd, procnum_to_rdbase(from_vcpu)); + its_encode_target2(&cmd, procnum_to_rdbase(to_vcpu)); + + its_send_cmd(cmdq_base, &cmd); +} + void its_send_sync_cmd(void *cmdq_base, u32 vcpu_id) { struct its_cmd_block cmd = {}; diff --git a/tools/testing/selftests/landlock/cap_test.c b/tools/testing/selftests/landlock/cap_test.c index 3d7fd02e21ed9f..35a419c46764d4 100644 --- a/tools/testing/selftests/landlock/cap_test.c +++ b/tools/testing/selftests/landlock/cap_test.c @@ -12,7 +12,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -738,6 +740,247 @@ TEST(cap_target_userns_independent) EXPECT_EQ(0, close(target_userns_fd)); } +/* + * Capability checks that commoncap makes from hooks other than the capable + * hook. Each test first checks that the operation needs the capability, then + * checks it with the capability effective. Variants cover an unsandboxed + * baseline, a domain that denies the capability, a domain that allows it, and a + * domain that does not handle capabilities. + */ +/* clang-format off */ +FIXTURE(cap_other_hooks) {}; +/* clang-format on */ + +FIXTURE_VARIANT(cap_other_hooks) +{ + const bool is_sandboxed; + const bool handle_caps; + const bool is_allowed; +}; + +/* clang-format off */ +FIXTURE_VARIANT_ADD(cap_other_hooks, unsandboxed) { + .is_sandboxed = false, + .handle_caps = false, + .is_allowed = true, +}; +/* clang-format on */ + +/* clang-format off */ +FIXTURE_VARIANT_ADD(cap_other_hooks, denied) { + .is_sandboxed = true, + .handle_caps = true, + .is_allowed = false, +}; +/* clang-format on */ + +/* clang-format off */ +FIXTURE_VARIANT_ADD(cap_other_hooks, allowed) { + .is_sandboxed = true, + .handle_caps = true, + .is_allowed = true, +}; +/* clang-format on */ + +/* clang-format off */ +FIXTURE_VARIANT_ADD(cap_other_hooks, unhandled) { + .is_sandboxed = true, + .handle_caps = false, + .is_allowed = true, +}; +/* clang-format on */ + +FIXTURE_SETUP(cap_other_hooks) +{ + disable_caps(_metadata); +} + +FIXTURE_TEARDOWN(cap_other_hooks) +{ +} + +/* + * Creates a ruleset that handles capabilities and allows @cap if @allow_cap, + * or, if !@handle_caps, a ruleset that only handles a filesystem access right. + * Returns the ruleset FD, or -1 with errno set. + */ +static int create_variant_ruleset(const bool handle_caps, const bool allow_cap, + const int cap) +{ + const struct landlock_ruleset_attr fs_attr = { + .handled_access_fs = LANDLOCK_ACCESS_FS_READ_FILE, + }; + int ruleset_fd, err; + + if (!handle_caps) + return landlock_create_ruleset(&fs_attr, sizeof(fs_attr), 0); + + ruleset_fd = create_cap_ruleset(); + if (ruleset_fd < 0 || !allow_cap) + return ruleset_fd; + + if (add_cap_rule(ruleset_fd, cap)) { + err = errno; + close(ruleset_fd); + errno = err; + return -1; + } + return ruleset_fd; +} + +static void +enforce_cap_variant(struct __test_metadata *const _metadata, + const FIXTURE_VARIANT(cap_other_hooks) *const variant, + const int cap) +{ + int ruleset_fd; + + if (!variant->is_sandboxed) + return; + + ruleset_fd = create_variant_ruleset(variant->handle_caps, + variant->is_allowed, cap); + ASSERT_LE(0, ruleset_fd); + enforce_ruleset(_metadata, ruleset_fd); + EXPECT_EQ(0, close(ruleset_fd)); +} + +static unsigned long read_sysctl(struct __test_metadata *const _metadata, + const char *const path) +{ + char buf[32]; + ssize_t len; + int fd; + + fd = open(path, O_RDONLY | O_CLOEXEC); + ASSERT_LE(0, fd) + { + TH_LOG("Failed to open %s: %s", path, strerror(errno)); + } + len = read(fd, buf, sizeof(buf) - 1); + ASSERT_LT(0, len); + EXPECT_EQ(0, close(fd)); + + buf[len] = '\0'; + return strtoul(buf, NULL, 10); +} + +/* + * Returns the last page below the vm.mmap_min_addr sysctl, or MAP_FAILED if + * there is none or if the architecture rejects it before the mmap_addr hook + * (e.g. below FIRST_USER_ADDRESS on 32-bit ARM). The caller must not have + * CAP_SYS_RAWIO in its effective set. + */ +static void *get_low_page(struct __test_metadata *const _metadata) +{ + const size_t page_size = sysconf(_SC_PAGESIZE); + unsigned long min_addr; + void *addr, *ret; + + min_addr = read_sysctl(_metadata, "/proc/sys/vm/mmap_min_addr"); + if (!min_addr) + return MAP_FAILED; + + addr = (void *)((min_addr - 1) & ~(page_size - 1)); + ret = mmap(addr, page_size, PROT_READ, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0); + ASSERT_EQ(MAP_FAILED, ret); + if (errno == EINVAL) + return MAP_FAILED; + + ASSERT_EQ(EPERM, errno); + return addr; +} + +/* + * cap_mmap_addr() requires CAP_SYS_RAWIO to map below the vm.mmap_min_addr + * sysctl (dac_mmap_min_addr). + */ +TEST_F(cap_other_hooks, mmap_min_addr) +{ + const size_t page_size = sysconf(_SC_PAGESIZE); + void *low_page, *addr; + + low_page = get_low_page(_metadata); + if (low_page == MAP_FAILED) + SKIP(return, "Cannot map below vm.mmap_min_addr"); + + enforce_cap_variant(_metadata, variant, CAP_SYS_RAWIO); + + addr = mmap(low_page, page_size, PROT_READ, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0); + ASSERT_EQ(MAP_FAILED, addr); + EXPECT_EQ(EPERM, errno); + + set_cap(_metadata, CAP_SYS_RAWIO); + addr = mmap(low_page, page_size, PROT_READ, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0); + if (variant->is_allowed) { + ASSERT_EQ(low_page, addr) + { + TH_LOG("Failed to map below vm.mmap_min_addr: %s", + strerror(errno)); + } + } else { + ASSERT_EQ(MAP_FAILED, addr); + EXPECT_EQ(EPERM, errno); + } + clear_cap(_metadata, CAP_SYS_RAWIO); +} + +static int add_inheritable_cap(const cap_value_t cap) +{ + cap_t cap_p; + int ret, err; + + cap_p = cap_get_proc(); + if (!cap_p) + return -1; + + ret = cap_set_flag(cap_p, CAP_INHERITABLE, 1, &cap, CAP_SET); + if (!ret) + ret = cap_set_proc(cap_p); + err = errno; + cap_free(cap_p); + errno = err; + return ret; +} + +/* + * cap_capset() requires CAP_SETPCAP to add an inheritable capability that is + * not in the permitted set. CAP_NET_RAW is in the bounding set, but + * disable_caps() does not put it in the permitted set. + */ +TEST_F(cap_other_hooks, capset_inheritable) +{ + enforce_cap_variant(_metadata, variant, CAP_SETPCAP); + + ASSERT_EQ(-1, add_inheritable_cap(CAP_NET_RAW)); + EXPECT_EQ(EPERM, errno); + + set_cap(_metadata, CAP_SETPCAP); + if (variant->is_allowed) { + EXPECT_EQ(0, add_inheritable_cap(CAP_NET_RAW)) + { + TH_LOG("Failed to raise CAP_NET_RAW: %s", + strerror(errno)); + } + } else { + ASSERT_EQ(-1, add_inheritable_cap(CAP_NET_RAW)); + EXPECT_EQ(EPERM, errno); + } + clear_cap(_metadata, CAP_SETPCAP); +} + +/* + * cap_vm_enough_memory() lets CAP_SYS_ADMIN use the vm.admin_reserve_kbytes + * reserve, but only with vm.overcommit_memory=2. The Landlock check of this + * reserve has no functional test: it would have to change these system-wide + * settings and set a tight commit limit, which could make allocations of other + * processes fail and would race with them. cap_audit.other_hooks checks that + * this check is not logged. + */ + /* Audit tests */ static int matches_log_cap(int audit_fd, int cap_number) @@ -828,6 +1071,160 @@ TEST_F(cap_audit, denied) EXPECT_EQ(0, records.domain); } +/* + * A privileged denial allocates the domain ID. The following unprivileged-only + * change must not create a hidden Landlock denial, so the domain's deallocation + * record must report exactly one denial. + */ +TEST_F(cap_audit, securebits) +{ + const unsigned long unpriv = SECBIT_EXEC_RESTRICT_FILE | + SECBIT_EXEC_RESTRICT_FILE_LOCKED; + __u64 *domain_id, deallocated_dom = 0; + unsigned long bits; + int err, ruleset_fd, status; + pid_t child; + + domain_id = mmap(NULL, sizeof(*domain_id), PROT_READ | PROT_WRITE, + MAP_SHARED | MAP_ANONYMOUS, -1, 0); + ASSERT_NE(MAP_FAILED, domain_id); + *domain_id = 0; + + ruleset_fd = create_cap_ruleset(); + ASSERT_LE(0, ruleset_fd); + /* Allow the child to replace the audit filter before exiting. */ + ASSERT_EQ(0, add_cap_rule(ruleset_fd, CAP_AUDIT_CONTROL)); + + child = fork(); + ASSERT_LE(0, child); + if (child == 0) { + enforce_ruleset(_metadata, ruleset_fd); + EXPECT_EQ(0, close(ruleset_fd)); + + set_cap(_metadata, CAP_SETPCAP); + bits = prctl(PR_GET_SECUREBITS); + ASSERT_EQ(-1, prctl(PR_SET_SECUREBITS, + bits | SECBIT_NO_CAP_AMBIENT_RAISE)); + EXPECT_EQ(EPERM, errno); + + EXPECT_EQ(0, matches_log_cap(self->audit_fd, CAP_SETPCAP)); + EXPECT_EQ(0, matches_log_domain_allocated(self->audit_fd, + getpid(), domain_id)); + + EXPECT_EQ(0, prctl(PR_SET_SECUREBITS, bits | unpriv)); + clear_cap(_metadata, CAP_SETPCAP); + + /* Receive the asynchronous domain deallocation record. */ + set_cap(_metadata, CAP_AUDIT_CONTROL); + EXPECT_EQ(0, audit_filter_drop(self->audit_fd, AUDIT_ADD_RULE)); + EXPECT_EQ(0, + audit_filter_exe(self->audit_fd, &self->audit_filter, + AUDIT_DEL_RULE)); + clear_cap(_metadata, CAP_AUDIT_CONTROL); + + _exit(_metadata->exit_code); + return; + } + + ASSERT_EQ(child, waitpid(child, &status, 0)); + if (WIFSIGNALED(status) || !WIFEXITED(status) || + WEXITSTATUS(status) != EXIT_SUCCESS) + _metadata->exit_code = KSFT_FAIL; + + EXPECT_NE(0, *domain_id); + err = matches_log_domain_deallocated(self->audit_fd, 1, *domain_id, + &deallocated_dom); + EXPECT_EQ(0, err); + EXPECT_EQ(*domain_id, deallocated_dom); + EXPECT_EQ(0, munmap(domain_id, sizeof(*domain_id))); + EXPECT_EQ(0, close(ruleset_fd)); +} + +/* + * Denials in the capset and mmap_addr paths are audited like capable hook + * denials. The vm_enough_memory hook only withholds the admin reserve, with + * CAP_OPT_NOAUDIT, so an accounted mapping made with CAP_SYS_ADMIN effective + * leaves no record. + */ +TEST_F(cap_audit, other_hooks) +{ + const size_t page_size = sysconf(_SC_PAGESIZE); + struct audit_records records = {}; + void *low_page, *addr; + int ruleset_fd; + __u64 domain_id; + + low_page = get_low_page(_metadata); + ruleset_fd = create_cap_ruleset(); + ASSERT_LE(0, ruleset_fd); + /* Allow CAP_AUDIT_CONTROL for child-side audit cleanup. */ + ASSERT_EQ(0, add_cap_rule(ruleset_fd, CAP_AUDIT_CONTROL)); + enforce_ruleset(_metadata, ruleset_fd); + EXPECT_EQ(0, close(ruleset_fd)); + + set_cap(_metadata, CAP_SETPCAP); + ASSERT_EQ(-1, add_inheritable_cap(CAP_NET_RAW)); + EXPECT_EQ(EPERM, errno); + clear_cap(_metadata, CAP_SETPCAP); + EXPECT_EQ(0, matches_log_cap(self->audit_fd, CAP_SETPCAP)); + EXPECT_EQ(0, matches_log_domain_allocated(self->audit_fd, getpid(), + &domain_id)); + + if (low_page != MAP_FAILED) { + set_cap(_metadata, CAP_SYS_RAWIO); + addr = mmap(low_page, page_size, PROT_READ, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0); + ASSERT_EQ(MAP_FAILED, addr); + EXPECT_EQ(EPERM, errno); + clear_cap(_metadata, CAP_SYS_RAWIO); + EXPECT_EQ(0, matches_log_cap(self->audit_fd, CAP_SYS_RAWIO)); + } + + set_cap(_metadata, CAP_SYS_ADMIN); + addr = mmap(NULL, page_size, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + ASSERT_NE(MAP_FAILED, addr); + clear_cap(_metadata, CAP_SYS_ADMIN); + + ASSERT_EQ(0, audit_count_records(self->audit_fd, &records)); + EXPECT_EQ(0, records.access); + EXPECT_EQ(0, records.domain); +} + +/* Allowed capability uses in the capset and mmap_addr paths. */ +TEST_F(cap_audit, other_hooks_allowed) +{ + const size_t page_size = sysconf(_SC_PAGESIZE); + struct audit_records records = {}; + void *low_page, *addr; + int ruleset_fd; + + low_page = get_low_page(_metadata); + ruleset_fd = create_cap_ruleset(); + ASSERT_LE(0, ruleset_fd); + ASSERT_EQ(0, add_cap_rule(ruleset_fd, CAP_SETPCAP)); + ASSERT_EQ(0, add_cap_rule(ruleset_fd, CAP_SYS_RAWIO)); + /* Allow CAP_AUDIT_CONTROL for child-side audit cleanup. */ + ASSERT_EQ(0, add_cap_rule(ruleset_fd, CAP_AUDIT_CONTROL)); + enforce_ruleset(_metadata, ruleset_fd); + EXPECT_EQ(0, close(ruleset_fd)); + + set_cap(_metadata, CAP_SETPCAP); + EXPECT_EQ(0, add_inheritable_cap(CAP_NET_RAW)); + clear_cap(_metadata, CAP_SETPCAP); + + if (low_page != MAP_FAILED) { + set_cap(_metadata, CAP_SYS_RAWIO); + addr = mmap(low_page, page_size, PROT_READ, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0); + ASSERT_EQ(low_page, addr); + clear_cap(_metadata, CAP_SYS_RAWIO); + } + + ASSERT_EQ(0, audit_count_records(self->audit_fd, &records)); + EXPECT_EQ(0, records.access); +} + TEST_F(cap_audit, allowed) { struct audit_records records = {}; diff --git a/tools/testing/selftests/landlock/common.h b/tools/testing/selftests/landlock/common.h index e29406900c04a6..a6fdfb422fad57 100644 --- a/tools/testing/selftests/landlock/common.h +++ b/tools/testing/selftests/landlock/common.h @@ -36,7 +36,7 @@ static const char bin_wait_pipe_sandbox[] = "./wait-pipe-sandbox"; static void _init_caps(struct __test_metadata *const _metadata, bool drop_all) { cap_t cap_p; - /* Only these three capabilities are useful for the tests. */ + /* Only these capabilities are useful for the tests. */ const cap_value_t caps[] = { /* clang-format off */ CAP_AUDIT_CONTROL, @@ -44,9 +44,11 @@ static void _init_caps(struct __test_metadata *const _metadata, bool drop_all) CAP_MKNOD, CAP_NET_ADMIN, CAP_NET_BIND_SERVICE, + CAP_SETPCAP, CAP_SETUID, CAP_SYS_ADMIN, CAP_SYS_CHROOT, + CAP_SYS_RAWIO, /* clang-format on */ }; const unsigned int noroot = SECBIT_NOROOT | SECBIT_NOROOT_LOCKED; diff --git a/tools/testing/selftests/landlock/fs_test.c b/tools/testing/selftests/landlock/fs_test.c index f725882fa4a78b..48c1f896dc9a0e 100644 --- a/tools/testing/selftests/landlock/fs_test.c +++ b/tools/testing/selftests/landlock/fs_test.c @@ -2612,6 +2612,60 @@ TEST_F_FORK(layout1, refer_denied_by_default4) layer_dir_s1d1_refer); } +/* + * Regression test for layered domains: The two enforced Landlock layers both do + * not restrict the tested "refer" operations on their own, so they should also + * not restrict them when they are layered, regardless of the layer order. + */ +static void test_layering_does_not_break_refer( + struct __test_metadata *const _metadata, + const struct landlock_ruleset_attr *const non_fs_attr, + const bool non_fs_first) +{ + ASSERT_EQ(0, unlink(file1_s1d2)); + + if (non_fs_first) + drop_access_rights(_metadata, non_fs_attr); + + enforce_fs(_metadata, LANDLOCK_ACCESS_FS_REFER, layer_dir_s1d1_refer); + + if (!non_fs_first) + drop_access_rights(_metadata, non_fs_attr); + + EXPECT_EQ(0, test_rename(file1_s1d1, file1_s1d2)); + EXPECT_EQ(0, test_rename(file1_s1d2, file1_s1d1)); + EXPECT_EQ(0, test_exchange(file2_s1d1, file2_s1d2)); + EXPECT_EQ(0, test_exchange(file2_s1d2, file2_s1d1)); +} + +static const struct landlock_ruleset_attr net_attr = { + .handled_access_net = LANDLOCK_ACCESS_NET_BIND_TCP, +}; + +static const struct landlock_ruleset_attr scoped_attr = { + .scoped = LANDLOCK_SCOPE_SIGNAL, +}; + +TEST_F_FORK(layout1, layering_fs_then_net_does_not_break_refer) +{ + test_layering_does_not_break_refer(_metadata, &net_attr, false); +} + +TEST_F_FORK(layout1, layering_net_then_fs_does_not_break_refer) +{ + test_layering_does_not_break_refer(_metadata, &net_attr, true); +} + +TEST_F_FORK(layout1, layering_fs_then_scoped_does_not_break_refer) +{ + test_layering_does_not_break_refer(_metadata, &scoped_attr, false); +} + +TEST_F_FORK(layout1, layering_scoped_then_fs_does_not_break_refer) +{ + test_layering_does_not_break_refer(_metadata, &scoped_attr, true); +} + /* * Tests walking through a denied root mount. */ @@ -2980,8 +3034,8 @@ TEST_F_FORK(layout1, reparent_exdev_layers_rename1) /* * Moving the file2_s1d3 file below dir_s2d3 is denied because the - * second layer does not handle REFER, which is always denied by - * default. + * second layer does not handle REFER, which is always denied as soon as + * any other filesystem access right is handled. */ ASSERT_EQ(-1, rename(file2_s1d3, file1_s2d3)); ASSERT_EQ(EXDEV, errno); @@ -3019,7 +3073,8 @@ TEST_F_FORK(layout1, reparent_exdev_layers_rename2) ASSERT_EQ(EXDEV, errno); /* * Modifying the layout is now denied because the second layer does not - * handle REFER, which is always denied by default. + * handle REFER, which is always denied as soon as any other filesystem + * access right is handled. */ ASSERT_EQ(-1, rename(file2_s1d2, file1_s2d3)); ASSERT_EQ(EXDEV, errno); diff --git a/tools/testing/selftests/landlock/ns_test.c b/tools/testing/selftests/landlock/ns_test.c index 8f387fc47e2171..52206ad94ecad2 100644 --- a/tools/testing/selftests/landlock/ns_test.c +++ b/tools/testing/selftests/landlock/ns_test.c @@ -1897,11 +1897,14 @@ TEST(setns_inherited_fd) /* Audit tests */ +#define REGEX_LANDLOCK_NS_CREATE \ + REGEX_LANDLOCK_PREFIX " blockers=namespace\\.use namespace_op=create" + static int matches_log_ns_create(int audit_fd, __u64 ns_type) { /* A denied creation logs the ID allocated for the new namespace. */ - static const char log_template[] = REGEX_LANDLOCK_PREFIX - " blockers=namespace\\.use namespace_type=0x%x namespace_id=[1-9][0-9]*$"; + static const char log_template[] = REGEX_LANDLOCK_NS_CREATE + " namespace_type=0x%x namespace_id=[1-9][0-9]*$"; char log_match[sizeof(log_template) + 10]; int log_match_len; @@ -1917,12 +1920,12 @@ static int matches_log_ns_create(int audit_fd, __u64 ns_type) static int matches_log_ns_setns(int audit_fd, __u64 ns_type, __u64 ns_id) { static const char log_template[] = REGEX_LANDLOCK_PREFIX - " blockers=namespace\\.use namespace_type=0x%x namespace_id=%llu$"; + " blockers=namespace\\.use namespace_op=%s namespace_type=0x%x namespace_id=%llu$"; char log_match[sizeof(log_template) + 32]; int log_match_len; log_match_len = snprintf(log_match, sizeof(log_match), log_template, - (unsigned int)ns_type, + "enter", (unsigned int)ns_type, (unsigned long long)ns_id); if (log_match_len >= sizeof(log_match)) return -E2BIG; @@ -1958,7 +1961,7 @@ FIXTURE_TEARDOWN(ns_audit) /* * Verifies that a denied namespace creation produces the expected audit record - * with the namespace.use blocker string and namespace_type. + * with the namespace.use blocker string, namespace type, and create operation. */ TEST_F(ns_audit, create_denied) { @@ -2542,6 +2545,11 @@ static void test_ns_trace_denial(struct __test_metadata *const _metadata, EXPECT_STRNE("0", field); if (use_setns) EXPECT_EQ(expected_ns_id, strtoull(field, NULL, 10)); + ret = tracefs_extract_field(buf, + REGEX_DENY_PERMISSION_NAMESPACE(TRACE_TASK), + "namespace_op", field, sizeof(field)); + ASSERT_EQ(0, ret); + EXPECT_STREQ(use_setns ? "enter" : "create", field); free(buf); } @@ -2567,6 +2575,13 @@ TEST_F(ns_trace, deny_setns) test_ns_trace_denial(_metadata, true, false); } +TEST_F(ns_trace, deny_setns_quiet) +{ + if (!self->tracefs_ok) + SKIP(return, "tracefs not available"); + test_ns_trace_denial(_metadata, true, true); +} + /* clang-format off */ FIXTURE(ns_proc_open) { /* clang-format on */ diff --git a/tools/testing/selftests/landlock/trace.h b/tools/testing/selftests/landlock/trace.h index 36e8f16171b0b5..e67f239a85076b 100644 --- a/tools/testing/selftests/landlock/trace.h +++ b/tools/testing/selftests/landlock/trace.h @@ -185,6 +185,7 @@ "same_exec=[01] " \ "logged=[01] " \ "blockers=[a-z_|]* " \ + "namespace_op=\\(create\\|enter\\) " \ "namespace_type=0x[0-9a-f]\\+ " \ "namespace_id=[0-9]\\+$" diff --git a/tools/testing/selftests/lib.mk b/tools/testing/selftests/lib.mk index 881f13ee2c8aca..506cb26510e4d9 100644 --- a/tools/testing/selftests/lib.mk +++ b/tools/testing/selftests/lib.mk @@ -179,11 +179,15 @@ else $(error Error: set INSTALL_PATH to use install) endif -emit_tests: +define EMIT_TESTS for TEST in $(TEST_GEN_PROGS) $(TEST_CUSTOM_PROGS) $(TEST_PROGS); do \ BASENAME_TEST=`basename $$TEST`; \ echo "$(COLLECTION):$$BASENAME_TEST"; \ done +endef + +emit_tests: + +$(EMIT_TESTS) # define if isn't already. It is undefined in make O= case. ifeq ($(RM),) diff --git a/tools/testing/selftests/net/af_unix/scm_pidfd.c b/tools/testing/selftests/net/af_unix/scm_pidfd.c index cbe53fab44fc5a..c26f055a190327 100644 --- a/tools/testing/selftests/net/af_unix/scm_pidfd.c +++ b/tools/testing/selftests/net/af_unix/scm_pidfd.c @@ -1155,4 +1155,55 @@ TEST(so_peerpidfd_thread) close(server); } +/* The lowest free file descriptor, where the next pidfd would land. */ +static int lowest_free_fd(int fd) +{ + int nfd; + + nfd = dup(fd); + if (nfd >= 0) + close(nfd); + return nfd; +} + +/* A short optlen must fail without installing a pidfd. */ +TEST(so_peerpidfd_short_optlen) +{ + const int optnames[] = { SO_PEERPIDFD, SO_PEERPIDFD_THREAD }; + int sv[2], i, free_fd, pidfd; + socklen_t len, optlen; + + ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, sv)); + + for (i = 0; i < ARRAY_SIZE(optnames); i++) { + for (len = 0; len < sizeof(pidfd); len++) { + free_fd = lowest_free_fd(sv[0]); + ASSERT_LE(0, free_fd); + + pidfd = -1; + optlen = len; + ASSERT_EQ(-1, getsockopt(sv[0], SOL_SOCKET, optnames[i], + &pidfd, &optlen)); + ASSERT_EQ(EINVAL, errno); + EXPECT_EQ(len, optlen); + EXPECT_EQ(-1, pidfd); + + /* No pidfd was installed behind our back. */ + ASSERT_EQ(free_fd, lowest_free_fd(sv[0])); + } + + /* A full-sized buffer still gets the pidfd. */ + free_fd = lowest_free_fd(sv[0]); + optlen = sizeof(pidfd); + ASSERT_EQ(0, getsockopt(sv[0], SOL_SOCKET, optnames[i], + &pidfd, &optlen)); + EXPECT_EQ(sizeof(pidfd), optlen); + EXPECT_EQ(free_fd, pidfd); + close(pidfd); + } + + close(sv[0]); + close(sv[1]); +} + TEST_HARNESS_MAIN diff --git a/tools/testing/selftests/net/af_unix/scm_rights.c b/tools/testing/selftests/net/af_unix/scm_rights.c index c165f250220a4a..19aa26c60f3b58 100644 --- a/tools/testing/selftests/net/af_unix/scm_rights.c +++ b/tools/testing/selftests/net/af_unix/scm_rights.c @@ -395,4 +395,79 @@ TEST_F(scm_rights, mixed_lowpoint) close_sockets(6); } +static int count_scm_fds(struct __test_metadata *_metadata, int fd) +{ + char path[64], *line = NULL; + int scm_fds = -1, ret; + size_t unused = 0; + FILE *f; + + snprintf(path, sizeof(path), "/proc/self/fdinfo/%d", fd); + + f = fopen(path, "r"); + ASSERT_NE(NULL, f); + + while (getline(&line, &unused, f) != -1) { + if (strncmp(line, "scm_fds:", 8)) + continue; + + ret = sscanf(line + 8, "%d", &scm_fds); + ASSERT_EQ(1, ret); + + break; + } + + free(line); + + ret = fclose(f); + ASSERT_EQ(0, ret); + + return scm_fds; +} + +TEST(dgram_disconnect_fdinfo) +{ + const FIXTURE_VARIANT(scm_rights) variant = { + .name = "UNIX ", + .type = SOCK_DGRAM, + }; + FIXTURE_DATA(scm_rights) self = {}; + struct sockaddr addr = { + .sa_family = AF_UNSPEC, + }; + int ret; + + ret = unshare(CLONE_NEWNET); + ASSERT_EQ(0, ret); + + create_socketpairs(_metadata, &self, &variant, 2); + + /* 1. Disconnect via connect(AF_UNSPEC) */ + __send_fd(_metadata, &self, &variant, 0, 0); + ASSERT_EQ(2, count_scm_fds(_metadata, self.fd[0])); + + ret = connect(self.fd[0], &addr, sizeof(addr.sa_family)); + ASSERT_EQ(0, ret); + ASSERT_EQ(0, count_scm_fds(_metadata, self.fd[0])); + + /* 2. Dead-peer disconnect via send() */ + __send_fd(_metadata, &self, &variant, 1, 1); + ASSERT_EQ(2, count_scm_fds(_metadata, self.fd[2])); + + ret = close(self.fd[3]); + ASSERT_EQ(0, ret); + + ret = send(self.fd[2], "x", 1, 0); + ASSERT_EQ(-1, ret); + ASSERT_EQ(ECONNREFUSED, errno); + ASSERT_EQ(0, count_scm_fds(_metadata, self.fd[2])); + + ret = close(self.fd[0]); + ASSERT_EQ(0, ret); + ret = close(self.fd[1]); + ASSERT_EQ(0, ret); + ret = close(self.fd[2]); + ASSERT_EQ(0, ret); +} + TEST_HARNESS_MAIN diff --git a/tools/testing/selftests/net/bind_wildcard.c b/tools/testing/selftests/net/bind_wildcard.c index be3298c791b22e..334a0cf87edfc7 100644 --- a/tools/testing/selftests/net/bind_wildcard.c +++ b/tools/testing/selftests/net/bind_wildcard.c @@ -811,4 +811,58 @@ TEST_F(bind_wildcard, reuseport) bind_socket(_metadata, self, variant, i, SO_REUSEPORT); } +/* The SO_REUSEPORT bind cache (tb->fast_*) filled by a v6only [::] socket + * must not let a dual-stack [::] socket skip the conflict check against a + * 0.0.0.0 listener. + */ +TEST(reuseport_v6only_cache) +{ + struct sockaddr_in6 addr6 = { + .sin6_family = AF_INET6, + .sin6_addr = in6addr_any, + }; + struct sockaddr_in addr4 = { + .sin_family = AF_INET, + .sin_addr.s_addr = htonl(INADDR_ANY), + }; + socklen_t addrlen; + int fd[3], ret; + int on = 1; + + ASSERT_EQ(unshare(CLONE_NEWNET), 0); + + /* bind(0.0.0.0:P), listen() */ + fd[0] = socket(AF_INET, SOCK_STREAM, 0); + ASSERT_GT(fd[0], 0); + ASSERT_EQ(bind(fd[0], (struct sockaddr *)&addr4, sizeof(addr4)), 0); + ASSERT_EQ(listen(fd[0], 1), 0); + + addrlen = sizeof(addr4); + ASSERT_EQ(getsockname(fd[0], (struct sockaddr *)&addr4, &addrlen), 0); + addr6.sin6_port = addr4.sin_port; + + /* SO_REUSEPORT + IPV6_V6ONLY, bind([::]:P) fills the cache. */ + fd[1] = socket(AF_INET6, SOCK_STREAM, 0); + ASSERT_GT(fd[1], 0); + ret = setsockopt(fd[1], SOL_IPV6, IPV6_V6ONLY, &on, sizeof(on)); + ASSERT_EQ(ret, 0); + ret = setsockopt(fd[1], SOL_SOCKET, SO_REUSEPORT, &on, sizeof(on)); + ASSERT_EQ(ret, 0); + ASSERT_EQ(bind(fd[1], (struct sockaddr *)&addr6, sizeof(addr6)), 0); + + /* SO_REUSEPORT, bind([::]:P) conflicts with 0.0.0.0:P. */ + fd[2] = socket(AF_INET6, SOCK_STREAM, 0); + ASSERT_GT(fd[2], 0); + ret = setsockopt(fd[2], SOL_SOCKET, SO_REUSEPORT, &on, sizeof(on)); + ASSERT_EQ(ret, 0); + + ret = bind(fd[2], (struct sockaddr *)&addr6, sizeof(addr6)); + ASSERT_EQ(ret, -1); + ASSERT_EQ(errno, EADDRINUSE); + + close(fd[2]); + close(fd[1]); + close(fd[0]); +} + TEST_HARNESS_MAIN diff --git a/tools/testing/selftests/net/netfilter/nft_fib.sh b/tools/testing/selftests/net/netfilter/nft_fib.sh index 04544905c2164d..25e13197f05780 100755 --- a/tools/testing/selftests/net/netfilter/nft_fib.sh +++ b/tools/testing/selftests/net/netfilter/nft_fib.sh @@ -202,6 +202,50 @@ check_fib_counter() { return 0 } +# Count probes matching the expected FIB result, then drop them. +test_fib_suppress() { + local label="$1" expected="$2" + local result="${3:-oifname}" error err=0 + + if ! ip netns exec "$nsrouter" nft -f /dev/stdin < /dev/null 2>&1 + if [ "$result" = type ]; then + case "$expected" in + blackhole) error="Invalid argument" ;; + unreachable) error="No route to host" ;; + prohibit) error="Permission denied" ;; + esac + LC_ALL=C ip -net "$nsrouter" -6 route get dead:1::99 \ + from dead:1::1 2>&1 | + grep -Fxq "RTNETLINK answers: $error" || err=1 + else + ip -net "$nsrouter" -6 route get dead:1::99 from dead:1::1 | + grep -q "dev $expected " || err=1 + fi + if check_fib_type_counter_family ip6 1 "$nsrouter" prerouting \ + "$result" "$label" && + [ "$err" -eq 0 ]; then + echo "PASS: $label" + else + echo "FAIL: $label" + ret=1 + return 1 + fi +} + load_ruleset "$nsrouter" load_ruleset "$ns1" load_ruleset "$ns2" @@ -845,6 +889,52 @@ test_fib_type "default table" ip netns exec "$nsrouter" nft delete table ip filter ip netns exec "$nsrouter" nft delete table ip6 filter +# Keep the earlier IPv6 checks on the path without custom rules. +# The router's logging RPF rules have already been removed here. +if ip -net "$nsrouter" -6 rule add pref 100 to dead:1::99 table 128 \ + suppress_prefixlength 0; then + ip -net "$nsrouter" -6 route add table 128 default dev veth1 || exit 1 + ip -net "$nsrouter" -6 route add table 129 dead:1::/64 \ + dev veth0 || exit 1 + ip -net "$nsrouter" -6 rule add pref 101 to dead:1::99 \ + table 129 || exit 1 + ip netns exec "$nsrouter" nft add table ip6 filter || exit 1 + + test_fib_suppress "suppress default route" veth0 || ret=1 + ip -net "$nsrouter" -6 route add table 128 dead:1::/64 \ + dev veth1 || exit 1 + test_fib_suppress "retain non-default route" veth1 || ret=1 + ip -net "$nsrouter" -6 route del table 128 dead:1::/64 \ + dev veth1 || exit 1 + + for type in blackhole unreachable prohibit; do + ip -net "$nsrouter" -6 route replace "$type" default \ + table 128 || exit 1 + test_fib_suppress "retain $type" "$type" type || ret=1 + done + + if ip -net "$nsrouter" -6 nexthop add id 1 blackhole; then + ip -net "$nsrouter" -6 route replace default nhid 1 \ + table 128 || exit 1 + test_fib_suppress "retain blackhole nexthop" \ + blackhole type || ret=1 + ip -net "$nsrouter" -6 route del table 128 default + ip -net "$nsrouter" -6 nexthop del id 1 + else + echo "SKIP: blackhole nexthop objects unavailable" + [ "$ret" -eq 0 ] && ret=$ksft_skip + ip -net "$nsrouter" -6 route del table 128 default + fi + + ip -net "$nsrouter" -6 rule del pref 100 + ip -net "$nsrouter" -6 rule del pref 101 + ip -net "$nsrouter" -6 route flush table 129 + ip netns exec "$nsrouter" nft delete table ip6 filter +else + echo "SKIP: IPv6 prefix suppression unavailable" + [ "$ret" -eq 0 ] && ret=$ksft_skip +fi + test_fib_vrf exit $ret diff --git a/tools/testing/selftests/net/tls.c b/tools/testing/selftests/net/tls.c index bd2797f9f619df..59e403b5f12cf3 100644 --- a/tools/testing/selftests/net/tls.c +++ b/tools/testing/selftests/net/tls.c @@ -2421,6 +2421,46 @@ TEST_F(tls, rekey_poll_delay) } } +TEST_F(tls, rekey_poll_queued) +{ + char const *test_str = "test_message"; + struct tls_crypto_info_keys tls12; + struct pollfd pfd = { }; + char buf[100]; + int send_len; + + if (self->notls) + SKIP(return, "no TLS support"); + + if (variant->tls_version != TLS_1_3_VERSION) + return; + + /* data followed by a KeyUpdate */ + send_len = strlen(test_str) + 1; + EXPECT_EQ(send(self->fd, test_str, send_len, 0), send_len); + tls_send_keyupdate(_metadata, self->fd); + + /* reading the data decrypts the KeyUpdate and leaves it queued */ + EXPECT_EQ(recv(self->cfd, buf, sizeof(buf), MSG_WAITALL), send_len); + EXPECT_EQ(memcmp(buf, test_str, send_len), 0); + + /* KeyUpdate hasn't been read, expect cfd to be readable */ + pfd.fd = self->cfd; + pfd.events = POLLIN; + EXPECT_EQ(poll(&pfd, 1, 0), 1); + + /* get KeyUpdate */ + tls_recv_keyupdate(_metadata, self->cfd, 0); + + /* update TX key and send with it */ + tls_crypto_info_init(variant->tls_version, variant->cipher_type, &tls12, 1); + EXPECT_EQ(setsockopt(self->fd, SOL_TLS, TLS_TX, &tls12, tls12.len), 0); + EXPECT_EQ(send(self->fd, test_str, send_len, 0), send_len); + + /* key hasn't been updated, expect cfd to be non-readable */ + EXPECT_EQ(poll(&pfd, 1, 0), 0); +} + struct raw_rec { unsigned int plain_len; unsigned char plain_data[100]; diff --git a/tools/testing/selftests/powerpc/Makefile b/tools/testing/selftests/powerpc/Makefile index b175e94e1901db..aeab9366d09bf8 100644 --- a/tools/testing/selftests/powerpc/Makefile +++ b/tools/testing/selftests/powerpc/Makefile @@ -56,11 +56,12 @@ override define INSTALL_RULE done; endef -emit_tests: +override define EMIT_TESTS +@for TARGET in $(SUB_DIRS); do \ BUILD_TARGET=$(OUTPUT)/$$TARGET; \ $(MAKE) OUTPUT=$$BUILD_TARGET COLLECTION=$(COLLECTION)/$$TARGET -s -C $$TARGET $@;\ done; +endef override define CLEAN +@for TARGET in $(SUB_DIRS); do \ diff --git a/tools/testing/selftests/powerpc/pmu/Makefile b/tools/testing/selftests/powerpc/pmu/Makefile index 7e9dbf3d0d092d..3aca10223f0ff5 100644 --- a/tools/testing/selftests/powerpc/pmu/Makefile +++ b/tools/testing/selftests/powerpc/pmu/Makefile @@ -37,7 +37,7 @@ override define RUN_TESTS done; endef -emit_tests: +override define EMIT_TESTS for TEST in $(TEST_GEN_PROGS); do \ BASENAME_TEST=`basename $$TEST`; \ echo "$(COLLECTION):$$BASENAME_TEST"; \ @@ -46,6 +46,7 @@ emit_tests: BUILD_TARGET=$(OUTPUT)/$$TARGET; \ $(MAKE) OUTPUT=$$BUILD_TARGET COLLECTION=$(COLLECTION)/$$TARGET -s -C $$TARGET emit_tests; \ done; +endef DEFAULT_INSTALL_RULE := $(INSTALL_RULE) override define INSTALL_RULE diff --git a/tools/testing/selftests/sched/.gitignore b/tools/testing/selftests/sched/.gitignore index 6996d4654d9241..4e3a0254e0abc5 100644 --- a/tools/testing/selftests/sched/.gitignore +++ b/tools/testing/selftests/sched/.gitignore @@ -1 +1,2 @@ cs_prctl_test +cs_dl_server_test diff --git a/tools/testing/selftests/sched/Makefile b/tools/testing/selftests/sched/Makefile index 099ee9213557ad..fa50d1385bd68d 100644 --- a/tools/testing/selftests/sched/Makefile +++ b/tools/testing/selftests/sched/Makefile @@ -8,7 +8,7 @@ CFLAGS += -O2 -Wall -g -I./ $(KHDR_INCLUDES) -Wl,-rpath=./ \ $(CLANG_FLAGS) LDLIBS += -lpthread -TEST_GEN_FILES := cs_prctl_test -TEST_PROGS := cs_prctl_test +TEST_GEN_FILES := cs_prctl_test cs_dl_server_test +TEST_PROGS := cs_prctl_test cs_dl_server_test include ../lib.mk diff --git a/tools/testing/selftests/sched/config b/tools/testing/selftests/sched/config index 1bb8bf6d7fd4c8..57b2439f75eedd 100644 --- a/tools/testing/selftests/sched/config +++ b/tools/testing/selftests/sched/config @@ -1 +1,3 @@ -# empty +CONFIG_SCHED_CORE=y +CONFIG_SCHED_SMT=y +CONFIG_DEBUG_FS=y diff --git a/tools/testing/selftests/sched/cs_dl_server_test.c b/tools/testing/selftests/sched/cs_dl_server_test.c new file mode 100644 index 00000000000000..38aa005080f1f2 --- /dev/null +++ b/tools/testing/selftests/sched/cs_dl_server_test.c @@ -0,0 +1,402 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Verify that core-scheduling forced idle does not starve the fair deadline + * server. + * + * A CPU is forced idle when it has runnable tasks of its own but its SMT + * sibling runs a task with an incompatible core-sched cookie. If that time is + * charged to the rq's deferred DL servers, the fair server's runtime drains + * while it is throttled, its activation is pushed out every period, and the + * CFS tasks it reserves bandwidth for get next to nothing. + * + * The test pins a cookied SCHED_FIFO spinner to one SMT sibling and an + * uncookied CFS spinner to the other, so the second sibling is forced idle + * whenever the FIFO task runs, and checks that the CFS task still gets a + * sensible fraction of the fair server's reservation. + * + * Copyright (c) 2026 Amazon.com, Inc. or its affiliates. + */ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../kselftest.h" + +#ifndef PR_SCHED_CORE +#define PR_SCHED_CORE 62 +#define PR_SCHED_CORE_GET 0 +#define PR_SCHED_CORE_CREATE 1 /* create unique core_sched cookie */ +#define PR_SCHED_CORE_SHARE_TO 2 /* push core_sched cookie to pid */ +#define PR_SCHED_CORE_SHARE_FROM 3 /* pull core_sched cookie to pid */ +#define PR_SCHED_CORE_MAX 4 +#endif + +enum pid_type {PIDTYPE_PID = 0, PIDTYPE_TGID, PIDTYPE_PGID}; + +#define SIBLINGS_LIST "/sys/devices/system/cpu/cpu0/topology/thread_siblings_list" +#define FAIR_SERVER "/sys/kernel/debug/sched/fair_server" + +#define RUN_TIME 5 /* measurement window, in seconds */ +#define FIFO_PRIO 50 + +/* + * The reservation is only approached, not reached: every slice the fair server + * gets costs the sibling a forced-idle hand-over, and the core-wide pick runs + * at tick granularity. Ask for half of it, which is far above the few hundredths + * of a percent a starved server leaves. + */ +#define MIN_SHARE_OF_RESERVATION 0.5 + +/* Status a spinner child reports to the parent over its readiness pipe. */ +#define CHILD_READY 'R' +#define CHILD_EPERM 'P' +#define CHILD_ERROR 'E' + +/* Tell the parent how setup went; it decides whether to run or to skip. */ +static void signal_status(int fd, char status) +{ + if (write(fd, &status, 1) != 1) { + ksft_perror("write to readiness pipe"); + exit(1); + } + if (status != CHILD_READY) + exit(1); +} + +/* + * Burn CPU until killed. A constant controlling expression keeps the compiler + * from removing the loop, so no volatile is needed to hold it in place. + */ +static void spin_forever(void) +{ + while (1) + ; +} + +static int set_affinity(int cpu) +{ + cpu_set_t mask; + + CPU_ZERO(&mask); + CPU_SET(cpu, &mask); + + return sched_setaffinity(0, sizeof(mask), &mask); +} + +/* + * Read the first two distinct CPU ids out of a cpu list such as "0-1", "0,4" + * or "0,4-5". Returns 0 on success, -1 if the list holds fewer than two ids. + */ +static int parse_sibling_pair(const char *list, int *sib0, int *sib1) +{ + int found = 0, sib[2] = { -1, -1 }; + const char *p = list; + + while (*p && found < 2) { + int first, last, n = 0; + + if (sscanf(p, "%d-%d%n", &first, &last, &n) != 2) { + if (sscanf(p, "%d%n", &first, &n) != 1) + return -1; + last = first; + } + for (; first <= last && found < 2; first++) + sib[found++] = first; + p += n; + if (*p != ',') + break; + p++; + } + + if (found < 2) + return -1; + + *sib0 = sib[0]; + *sib1 = sib[1]; + + return 0; +} + +static int read_sibling_pair(int *sib0, int *sib1) +{ + char list[256]; + FILE *f; + char *s; + + f = fopen(SIBLINGS_LIST, "r"); + if (!f) + return -1; + s = fgets(list, sizeof(list), f); + fclose(f); + if (!s) + return -1; + + return parse_sibling_pair(list, sib0, sib1); +} + +static int read_u64_file(const char *path, unsigned long long *val) +{ + FILE *f; + int ret; + + f = fopen(path, "r"); + if (!f) + return -1; + ret = fscanf(f, "%llu", val); + fclose(f); + + return ret == 1 ? 0 : -1; +} + +/* Read the fair server reservation of @cpu, in nanoseconds. */ +static int read_fair_server(int cpu, unsigned long long *runtime, + unsigned long long *period) +{ + char path[PATH_MAX]; + + snprintf(path, sizeof(path), FAIR_SERVER "/cpu%d/runtime", cpu); + if (read_u64_file(path, runtime)) + return -1; + + snprintf(path, sizeof(path), FAIR_SERVER "/cpu%d/period", cpu); + if (read_u64_file(path, period)) + return -1; + + return 0; +} + +/* CPU time consumed by @pid so far, in seconds, from /proc//stat. */ +static double process_runtime(pid_t pid) +{ + char path[PATH_MAX]; + unsigned long utime, stime; + FILE *f; + int fields; + + snprintf(path, sizeof(path), "/proc/%d/stat", pid); + f = fopen(path, "r"); + if (!f) + return -1; + + /* Skip the first 13 fields and read the 14th and 15th. */ + fields = fscanf(f, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %lu %lu", + &utime, &stime); + fclose(f); + if (fields != 2) + return -1; + + return (double)(utime + stime) / sysconf(_SC_CLK_TCK); +} + +static double monotonic_now(void) +{ + struct timespec ts; + + if (clock_gettime(CLOCK_MONOTONIC, &ts)) + return -1; + + return ts.tv_sec + ts.tv_nsec / 1000000000.0; +} + +/* + * Diagnostic only: how long the FIFO task's CPU was forced idle. Needs + * CONFIG_SCHEDSTATS and schedstats enabled, so it must not gate the result. + */ +static void print_forced_idle(pid_t pid) +{ + char path[PATH_MAX], line[256]; + FILE *f; + + snprintf(path, sizeof(path), "/proc/%d/sched", pid); + f = fopen(path, "r"); + if (!f) + return; + + while (fgets(line, sizeof(line), f)) { + if (strstr(line, "core_forceidle_sum")) { + line[strcspn(line, "\n")] = '\0'; + ksft_print_msg("FIFO task %s\n", line); + break; + } + } + fclose(f); +} + +/* Cookied SCHED_FIFO spinner. Only this task gets a cookie. */ +static void fifo_child(int cpu, int ready_fd) +{ + struct sched_param param = { .sched_priority = FIFO_PRIO }; + + if (set_affinity(cpu)) { + ksft_perror("FIFO child sched_setaffinity"); + signal_status(ready_fd, CHILD_ERROR); + } + if (prctl(PR_SCHED_CORE, PR_SCHED_CORE_CREATE, 0, PIDTYPE_PID, 0)) { + ksft_perror("FIFO child PR_SCHED_CORE_CREATE"); + signal_status(ready_fd, CHILD_ERROR); + } + if (sched_setscheduler(0, SCHED_FIFO, ¶m)) { + if (errno == EPERM) + signal_status(ready_fd, CHILD_EPERM); + ksft_perror("FIFO child sched_setscheduler"); + signal_status(ready_fd, CHILD_ERROR); + } + signal_status(ready_fd, CHILD_READY); + spin_forever(); +} + +/* Uncookied CFS spinner on the FIFO task's SMT sibling. */ +static void cfs_child(int cpu, int ready_fd) +{ + if (set_affinity(cpu)) { + ksft_perror("CFS child sched_setaffinity"); + signal_status(ready_fd, CHILD_ERROR); + } + signal_status(ready_fd, CHILD_READY); + spin_forever(); +} + +static char wait_ready(int fd) +{ + char status; + + if (read(fd, &status, 1) != 1) { + ksft_perror("read from readiness pipe"); + return CHILD_ERROR; + } + + return status; +} + +static void kill_child(pid_t *pid) +{ + if (*pid <= 0) + return; + kill(*pid, SIGKILL); + waitpid(*pid, NULL, 0); + *pid = -1; +} + +int main(void) +{ + double fifo_runtime, cfs_start, cfs_end, t_start, t_end, share, want; + unsigned long long runtime, period; + pid_t fifo_pid = -1, cfs_pid = -1; + int fifo_ready[2], cfs_ready[2]; + unsigned long long cookie; + int sib0, sib1; + char status; + + ksft_print_header(); + ksft_set_plan(1); + + if (read_sibling_pair(&sib0, &sib1)) { + ksft_test_result_skip("CPU0 has no SMT sibling\n"); + ksft_finished(); + } + ksft_print_msg("SMT siblings: CPU%d (FIFO) and CPU%d (CFS)\n", sib0, sib1); + + if (prctl(PR_SCHED_CORE, PR_SCHED_CORE_GET, 0, PIDTYPE_PID, + (unsigned long)&cookie)) { + ksft_test_result_skip("core scheduling unavailable: %s\n", + strerror(errno)); + ksft_finished(); + } + + if (read_fair_server(sib1, &runtime, &period)) { + ksft_test_result_skip("cannot read " FAIR_SERVER "/cpu%d, debugfs not mounted?\n", + sib1); + ksft_finished(); + } + if (!runtime || !period) { + ksft_test_result_skip("fair server on CPU%d is disabled (%llu/%llu)\n", + sib1, runtime, period); + ksft_finished(); + } + ksft_print_msg("CPU%d fair server reservation: %llu/%llu ns = %.3f%%\n", + sib1, runtime, period, 100.0 * runtime / period); + + if (pipe(fifo_ready) || pipe(cfs_ready)) + ksft_exit_fail_perror("pipe"); + + fifo_pid = fork(); + if (!fifo_pid) { + close(fifo_ready[0]); + close(cfs_ready[0]); + close(cfs_ready[1]); + fifo_child(sib0, fifo_ready[1]); + } else if (fifo_pid < 0) { + ksft_exit_fail_perror("fork FIFO child"); + } + close(fifo_ready[1]); + + status = wait_ready(fifo_ready[0]); + close(fifo_ready[0]); + if (status != CHILD_READY) { + kill_child(&fifo_pid); + close(cfs_ready[0]); + close(cfs_ready[1]); + if (status == CHILD_EPERM) { + ksft_test_result_skip("need privileges for SCHED_FIFO\n"); + ksft_finished(); + } + ksft_exit_fail_msg("FIFO child setup failed\n"); + } + + cfs_pid = fork(); + if (!cfs_pid) { + close(cfs_ready[0]); + cfs_child(sib1, cfs_ready[1]); + } else if (cfs_pid < 0) { + kill_child(&fifo_pid); + ksft_exit_fail_perror("fork CFS child"); + } + close(cfs_ready[1]); + + status = wait_ready(cfs_ready[0]); + close(cfs_ready[0]); + if (status != CHILD_READY) { + kill_child(&cfs_pid); + kill_child(&fifo_pid); + ksft_exit_fail_msg("CFS child setup failed\n"); + } + + cfs_start = process_runtime(cfs_pid); + t_start = monotonic_now(); + sleep(RUN_TIME); + t_end = monotonic_now(); + cfs_end = process_runtime(cfs_pid); + fifo_runtime = process_runtime(fifo_pid); + + print_forced_idle(fifo_pid); + kill_child(&cfs_pid); + kill_child(&fifo_pid); + + if (cfs_start < 0 || cfs_end < 0 || fifo_runtime < 0) + ksft_exit_fail_msg("cannot read /proc//stat\n"); + if (t_start < 0 || t_end <= t_start) + ksft_exit_fail_msg("cannot read CLOCK_MONOTONIC\n"); + + share = (cfs_end - cfs_start) / (t_end - t_start); + want = MIN_SHARE_OF_RESERVATION * runtime / period; + + ksft_print_msg("FIFO task ran %.3fs, CFS task ran %.3fs over %.3fs\n", + fifo_runtime, cfs_end - cfs_start, t_end - t_start); + ksft_print_msg("CFS share of CPU%d: %.3f%%, need %.3f%%\n", + sib1, share * 100, want * 100); + + ksft_test_result(share >= want, + "CFS task gets the fair server reservation while forced idle\n"); + + ksft_finished(); +} diff --git a/tools/testing/selftests/sched_ext/Makefile b/tools/testing/selftests/sched_ext/Makefile index c5d3a2eaea7da2..9a776a8a36ff3f 100644 --- a/tools/testing/selftests/sched_ext/Makefile +++ b/tools/testing/selftests/sched_ext/Makefile @@ -199,6 +199,7 @@ auto-test-targets := \ rt_stall \ test_example \ total_bw \ + unlocked_kfunc \ cyclic_kick_wait \ testcase-targets := $(addsuffix .o,$(addprefix $(SCXOBJ_DIR)/,$(auto-test-targets))) diff --git a/tools/testing/selftests/sched_ext/unlocked_kfunc.bpf.c b/tools/testing/selftests/sched_ext/unlocked_kfunc.bpf.c new file mode 100644 index 00000000000000..194993a0ef0734 --- /dev/null +++ b/tools/testing/selftests/sched_ext/unlocked_kfunc.bpf.c @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * A cpu-form scheduler that calls SCX_KF_ALLOW_UNLOCKED kfuncs from ops.init() + * and ops.exit(). ops.dump() calls scx_bpf_dump(). + * + * Copyright (c) 2026 Google LLC. + */ + +#include + +#define SHARED_DSQ 0 + +char _license[] SEC("license") = "GPL"; + +static void drain_dsq(void) +{ + struct task_struct *p; + + bpf_rcu_read_lock(); + bpf_for_each(scx_dsq, p, SHARED_DSQ, 0) { + if (p->pid & 1) + scx_bpf_dsq_reenq_task(BPF_FOR_EACH_ITER, p); + else + scx_bpf_dsq_move(BPF_FOR_EACH_ITER, p, SCX_DSQ_GLOBAL, 0); + } + bpf_rcu_read_unlock(); +} + +static void select_cpu_for_current(void) +{ + struct task_struct *p = bpf_get_current_task_btf(); + bool is_idle; + + bpf_rcu_read_lock(); + scx_bpf_select_cpu_dfl(p, bpf_get_smp_processor_id(), 0, &is_idle); + bpf_rcu_read_unlock(); +} + +s32 BPF_STRUCT_OPS_SLEEPABLE(unlocked_kfunc_init) +{ + s32 ret; + + ret = scx_bpf_create_dsq(SHARED_DSQ, -1); + if (ret) + return ret; + + drain_dsq(); + select_cpu_for_current(); + return 0; +} + +void BPF_STRUCT_OPS(unlocked_kfunc_exit, struct scx_exit_info *ei) +{ + drain_dsq(); + select_cpu_for_current(); +} + +void BPF_STRUCT_OPS(unlocked_kfunc_dump, struct scx_dump_ctx *dctx) +{ + scx_bpf_dump("nr_cpu_ids=%u\n", scx_bpf_nr_cpu_ids()); +} + +SEC(".struct_ops.link") +struct sched_ext_ops unlocked_kfunc_ops = { + .init = (void *)unlocked_kfunc_init, + .exit = (void *)unlocked_kfunc_exit, + .dump = (void *)unlocked_kfunc_dump, + .name = "unlocked_kfunc", +}; diff --git a/tools/testing/selftests/sched_ext/unlocked_kfunc.c b/tools/testing/selftests/sched_ext/unlocked_kfunc.c new file mode 100644 index 00000000000000..0052c608365db1 --- /dev/null +++ b/tools/testing/selftests/sched_ext/unlocked_kfunc.c @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Verify that the BPF verifier rejects SCX_KF_ALLOW_UNLOCKED kfuncs from + * ops.dump() and ops.init_cids(). Unlocked ops such as ops.init() and + * ops.exit() must still be allowed to call them. + * + * Copyright (c) 2026 Google LLC. + */ +#include +#include +#include +#include "scx_test.h" +#include "unlocked_kfunc.bpf.skel.h" +#include "unlocked_kfunc_cid.bpf.skel.h" +#include "unlocked_kfunc_fail_dump.bpf.skel.h" +#include "unlocked_kfunc_fail_init_cids.bpf.skel.h" + +static enum scx_test_status run(void *ctx) +{ + struct unlocked_kfunc *skel; + struct unlocked_kfunc_cid *cid_skel; + struct unlocked_kfunc_fail_dump *fail_dump; + struct unlocked_kfunc_fail_init_cids *fail_init_cids; + int err; + + if (!__COMPAT_struct_has_field("sched_ext_ops_cid", "init_cids") || + !__COMPAT_has_ksym("scx_bpf_dsq_reenq_task")) + return SCX_TEST_SKIP; + + skel = unlocked_kfunc__open(); + SCX_FAIL_IF(!skel, "Failed to open unlocked_kfunc"); + SCX_ENUM_INIT(skel); + err = unlocked_kfunc__load(skel); + unlocked_kfunc__destroy(skel); + SCX_FAIL_IF(err, "Failed to load unlocked_kfunc (%d)", err); + + cid_skel = unlocked_kfunc_cid__open(); + SCX_FAIL_IF(!cid_skel, "Failed to open unlocked_kfunc_cid"); + SCX_ENUM_INIT(cid_skel); + err = unlocked_kfunc_cid__load(cid_skel); + unlocked_kfunc_cid__destroy(cid_skel); + SCX_FAIL_IF(err, "Failed to load unlocked_kfunc_cid (%d)", err); + + fail_dump = unlocked_kfunc_fail_dump__open(); + SCX_FAIL_IF(!fail_dump, "Failed to open unlocked_kfunc_fail_dump"); + SCX_ENUM_INIT(fail_dump); + err = unlocked_kfunc_fail_dump__load(fail_dump); + unlocked_kfunc_fail_dump__destroy(fail_dump); + SCX_FAIL_IF(!err, + "unlocked_kfunc_fail_dump loaded when it should have been rejected"); + SCX_FAIL_IF(err != -EACCES, + "Expected -EACCES loading unlocked_kfunc_fail_dump, got %d", err); + + fail_init_cids = unlocked_kfunc_fail_init_cids__open(); + SCX_FAIL_IF(!fail_init_cids, "Failed to open unlocked_kfunc_fail_init_cids"); + SCX_ENUM_INIT(fail_init_cids); + err = unlocked_kfunc_fail_init_cids__load(fail_init_cids); + unlocked_kfunc_fail_init_cids__destroy(fail_init_cids); + SCX_FAIL_IF(!err, + "unlocked_kfunc_fail_init_cids loaded when it should have been rejected"); + SCX_FAIL_IF(err != -EACCES, + "Expected -EACCES loading unlocked_kfunc_fail_init_cids, got %d", err); + + return SCX_TEST_PASS; +} + +struct scx_test unlocked_kfunc = { + .name = "unlocked_kfunc", + .description = "Verify verifier kfunc restrictions on ops.dump() and ops.init_cids()", + .run = run, +}; + +REGISTER_SCX_TEST(&unlocked_kfunc) diff --git a/tools/testing/selftests/sched_ext/unlocked_kfunc_cid.bpf.c b/tools/testing/selftests/sched_ext/unlocked_kfunc_cid.bpf.c new file mode 100644 index 00000000000000..ffe2f03c42e373 --- /dev/null +++ b/tools/testing/selftests/sched_ext/unlocked_kfunc_cid.bpf.c @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * A cid-form scheduler that calls scx_bpf_cid_override() from ops.init_cids() + * and SCX_KF_ALLOW_UNLOCKED kfuncs from ops.init(). ops.dump() calls + * scx_bpf_dump(). + * + * Copyright (c) 2026 Google LLC. + */ + +#include + +#define SHARED_DSQ 0 +#define MAX_CPUS 512 + +char _license[] SEC("license") = "GPL"; + +struct { + __uint(type, BPF_MAP_TYPE_ARENA); + __uint(map_flags, BPF_F_MMAPABLE); + __uint(max_entries, 1 << 4); +} arena SEC(".maps"); + +s32 __arena_global cpu_to_cid[MAX_CPUS]; +s32 __arena_global shard_start[MAX_CPUS]; + +s32 BPF_STRUCT_OPS_SLEEPABLE(unlocked_kfunc_cid_init_cids) +{ + u32 nr_cpu_ids = scx_bpf_nr_cpu_ids(); + + if (nr_cpu_ids > MAX_CPUS) + return -E2BIG; + + scx_bpf_cid_override(cpu_to_cid, nr_cpu_ids, shard_start, 1); + return 0; +} + +s32 BPF_STRUCT_OPS_SLEEPABLE(unlocked_kfunc_cid_init) +{ + struct task_struct *p; + s32 ret; + + ret = scx_bpf_create_dsq(SHARED_DSQ, -1); + if (ret) + return ret; + + bpf_rcu_read_lock(); + bpf_for_each(scx_dsq, p, SHARED_DSQ, 0) { + if (p->pid & 1) + scx_bpf_dsq_reenq_task(BPF_FOR_EACH_ITER, p); + else + scx_bpf_dsq_move(BPF_FOR_EACH_ITER, p, SCX_DSQ_GLOBAL, 0); + } + bpf_rcu_read_unlock(); + + return 0; +} + +void BPF_STRUCT_OPS(unlocked_kfunc_cid_dump, struct scx_dump_ctx *dctx) +{ + scx_bpf_dump("nr_cids=%u\n", scx_bpf_nr_cids()); +} + +SCX_OPS_CID_DEFINE(unlocked_kfunc_cid_ops, + .init_cids = (void *)unlocked_kfunc_cid_init_cids, + .init = (void *)unlocked_kfunc_cid_init, + .dump = (void *)unlocked_kfunc_cid_dump, + .name = "unlocked_kfunc_cid"); diff --git a/tools/testing/selftests/sched_ext/unlocked_kfunc_fail_dump.bpf.c b/tools/testing/selftests/sched_ext/unlocked_kfunc_fail_dump.bpf.c new file mode 100644 index 00000000000000..70218f48e93aef --- /dev/null +++ b/tools/testing/selftests/sched_ext/unlocked_kfunc_fail_dump.bpf.c @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Verify that the BPF verifier rejects scx_bpf_dsq_move() from ops.dump(). + * + * Copyright (c) 2026 Google LLC. + */ + +#include + +#define SHARED_DSQ 0 + +char _license[] SEC("license") = "GPL"; + +void BPF_STRUCT_OPS(unlocked_kfunc_fail_dump_cb, struct scx_dump_ctx *dctx) +{ + struct task_struct *p; + + bpf_for_each(scx_dsq, p, SHARED_DSQ, 0) + scx_bpf_dsq_move(BPF_FOR_EACH_ITER, p, SCX_DSQ_GLOBAL, 0); +} + +SEC(".struct_ops.link") +struct sched_ext_ops unlocked_kfunc_fail_dump_ops = { + .dump = (void *)unlocked_kfunc_fail_dump_cb, + .name = "unlocked_kfunc_fail_dump", +}; diff --git a/tools/testing/selftests/sched_ext/unlocked_kfunc_fail_init_cids.bpf.c b/tools/testing/selftests/sched_ext/unlocked_kfunc_fail_init_cids.bpf.c new file mode 100644 index 00000000000000..2f2d277aa54fa8 --- /dev/null +++ b/tools/testing/selftests/sched_ext/unlocked_kfunc_fail_init_cids.bpf.c @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Verify that the BPF verifier rejects scx_bpf_create_dsq() from + * ops.init_cids(). + * + * Copyright (c) 2026 Google LLC. + */ + +#include + +#define SHARED_DSQ 0 + +char _license[] SEC("license") = "GPL"; + +s32 BPF_STRUCT_OPS_SLEEPABLE(unlocked_kfunc_fail_init_cids_cb) +{ + return scx_bpf_create_dsq(SHARED_DSQ, -1); +} + +SCX_OPS_CID_DEFINE(unlocked_kfunc_fail_init_cids_ops, + .init_cids = (void *)unlocked_kfunc_fail_init_cids_cb, + .name = "unlocked_kfunc_fail_init_cids"); diff --git a/tools/testing/selftests/ublk/Makefile b/tools/testing/selftests/ublk/Makefile index 1a50d4695c9fa3..8fc3291eaed947 100644 --- a/tools/testing/selftests/ublk/Makefile +++ b/tools/testing/selftests/ublk/Makefile @@ -1,6 +1,6 @@ # SPDX-License-Identifier: GPL-2.0 -CFLAGS += -O3 -Wl,-no-as-needed -Wall -I $(top_srcdir)/usr/include +CFLAGS += -O3 -Wl,-no-as-needed -Wall $(KHDR_INCLUDES) CFLAGS += -D_FILE_OFFSET_BITS=64 ifneq ($(WERROR),0) CFLAGS += -Werror @@ -86,6 +86,7 @@ include ../lib.mk $(OUTPUT)/kublk: $(filter-out $(STANDALONE_UTILS),$(wildcard *.c)) $(OUTPUT)/ublk_cancel_ready: ublk_cancel_ready.c ctrl.c +$(TEST_GEN_PROGS_EXTENDED): | headers check: shellcheck -x -f gcc *.sh diff --git a/tools/testing/shared/maple-shared.h b/tools/testing/shared/maple-shared.h index 2a1e9a8594a283..5f827709773a07 100644 --- a/tools/testing/shared/maple-shared.h +++ b/tools/testing/shared/maple-shared.h @@ -8,6 +8,7 @@ #include "shared.h" #include #include +#include #include "linux/init.h" void maple_rcu_cb(struct rcu_head *head); @@ -20,5 +21,37 @@ do { \ call_rcu(&((_p_struct)->_memb), rcu_cb); \ } while(0); +/* Make WARN() fatal */ +#undef WARN +#undef WARN_ON +#undef WARN_ONCE +#undef WARN_ON_ONCE +#define WARN(condition, format...) ({ \ + int __ret_warn_on = !!(condition); \ + if (unlikely(__ret_warn_on)) { \ + __WARN_printf(format); \ + assert(0); \ + } \ + unlikely(__ret_warn_on); \ +}) +#define WARN_ON(condition) \ + WARN(condition, "assertion failed at %s:%d\n", __FILE__, __LINE__) +#define WARN_ONCE(condition, format...) WARN(condition, format) +#define WARN_ON_ONCE(condition) WARN_ON(condition) + +/* Once state for the debug macros */ +#ifndef __ONCE_LITE_IF +#define __ONCE_LITE_IF(condition) \ + ({ \ + static bool __already_done; \ + bool __ret_once = false; \ + \ + if ((condition) && !__already_done) { \ + __already_done = true; \ + __ret_once = true; \ + } \ + __ret_once; \ + }) +#endif #endif /* __MAPLE_SHARED_H__ */ diff --git a/tools/testing/vma/include/stubs.h b/tools/testing/vma/include/stubs.h index 8d030a3ace8485..9f5b8e996abf68 100644 --- a/tools/testing/vma/include/stubs.h +++ b/tools/testing/vma/include/stubs.h @@ -148,6 +148,10 @@ static inline int userfaultfd_unmap_prep(struct vm_area_struct *vma, return 0; } +static inline void userfaultfd_unmap_abort(struct list_head *uf) +{ +} + static inline void mmap_write_downgrade(struct mm_struct *mm) { } diff --git a/virt/kvm/kvm_main.c b/virt/kvm/kvm_main.c index cf4cb586f1407b..83e727bf6452cd 100644 --- a/virt/kvm/kvm_main.c +++ b/virt/kvm/kvm_main.c @@ -191,7 +191,6 @@ void vcpu_put(struct kvm_vcpu *vcpu) } EXPORT_SYMBOL_FOR_KVM_INTERNAL(vcpu_put); -/* TODO: merge with kvm_arch_vcpu_should_kick */ static bool kvm_request_needs_ipi(struct kvm_vcpu *vcpu, unsigned req) { int mode = kvm_vcpu_exiting_guest_mode(vcpu); @@ -3279,8 +3278,8 @@ static int next_segment(unsigned long len, int offset) } /* Copy @len bytes from guest memory at '(@gfn * PAGE_SIZE) + @offset' to @data */ -static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn, - void *data, int offset, int len) +static int __kvm_read_guest_page(struct kvm *kvm, struct kvm_memory_slot *slot, + gfn_t gfn, void *data, int offset, int len) { int r; unsigned long addr; @@ -3291,7 +3290,7 @@ static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn, addr = gfn_to_hva_memslot_prot(slot, gfn, NULL); if (kvm_is_error_hva(addr)) return -EFAULT; - r = __copy_from_user(data, (void __user *)addr + offset, len); + r = kvm_copy_from_user(kvm, data, (void __user *)addr + offset, len); if (r) return -EFAULT; return 0; @@ -3302,7 +3301,7 @@ int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset, { struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn); - return __kvm_read_guest_page(slot, gfn, data, offset, len); + return __kvm_read_guest_page(kvm, slot, gfn, data, offset, len); } EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_read_guest_page); @@ -3311,7 +3310,7 @@ int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data, { struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn); - return __kvm_read_guest_page(slot, gfn, data, offset, len); + return __kvm_read_guest_page(vcpu->kvm, slot, gfn, data, offset, len); } EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_read_guest_page); @@ -3355,8 +3354,8 @@ int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned l } EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_read_guest); -static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn, - void *data, int offset, unsigned long len) +static int __kvm_read_guest_atomic(struct kvm *kvm, struct kvm_memory_slot *slot, + gfn_t gfn, void *data, int offset, unsigned long len) { int r; unsigned long addr; @@ -3368,7 +3367,7 @@ static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn, if (kvm_is_error_hva(addr)) return -EFAULT; pagefault_disable(); - r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len); + r = kvm_copy_from_user_inatomic(kvm, data, (void __user *)addr + offset, len); pagefault_enable(); if (r) return -EFAULT; @@ -3382,7 +3381,7 @@ int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa, struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn); int offset = offset_in_page(gpa); - return __kvm_read_guest_atomic(slot, gfn, data, offset, len); + return __kvm_read_guest_atomic(vcpu->kvm, slot, gfn, data, offset, len); } EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_read_guest_atomic); @@ -3400,7 +3399,7 @@ static int __kvm_write_guest_page(struct kvm *kvm, addr = gfn_to_hva_memslot(memslot, gfn); if (kvm_is_error_hva(addr)) return -EFAULT; - r = __copy_to_user((void __user *)addr + offset, data, len); + r = kvm_copy_to_user(kvm, (void __user *)addr + offset, data, len); if (r) return -EFAULT; mark_page_dirty_in_slot(kvm, memslot, gfn); @@ -3538,7 +3537,7 @@ int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc, if (unlikely(!ghc->memslot)) return kvm_write_guest(kvm, gpa, data, len); - r = __copy_to_user((void __user *)ghc->hva + offset, data, len); + r = kvm_copy_to_user(kvm, (void __user *)ghc->hva + offset, data, len); if (r) return -EFAULT; mark_page_dirty_in_slot(kvm, ghc->memslot, gpa >> PAGE_SHIFT); @@ -3576,7 +3575,7 @@ int kvm_read_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc, if (unlikely(!ghc->memslot)) return kvm_read_guest(kvm, gpa, data, len); - r = __copy_from_user(data, (void __user *)ghc->hva + offset, len); + r = kvm_copy_from_user(kvm, data, (void __user *)ghc->hva + offset, len); if (r) return -EFAULT; @@ -3908,7 +3907,7 @@ EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_wake_up); /* * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode. */ -void __kvm_vcpu_kick(struct kvm_vcpu *vcpu, bool wait) +void __kvm_vcpu_kick(struct kvm_vcpu *vcpu, int req, bool force) { int me, cpu; @@ -3930,23 +3929,28 @@ void __kvm_vcpu_kick(struct kvm_vcpu *vcpu, bool wait) /* * Note, the vCPU could get migrated to a different pCPU at any point - * after kvm_arch_vcpu_should_kick(), which could result in sending an + * after kvm_request_needs_ipi(), which could result in sending an * IPI to the previous pCPU. But, that's ok because the purpose of the * IPI is to force the vCPU to leave IN_GUEST_MODE, and migrating the - * vCPU also requires it to leave IN_GUEST_MODE. + * vCPU also requires it to leave IN_GUEST_MODE + * + * Note #2, do NOT check if an IPI is needed if @force is true, as the + * check also modifies vcpu->mode and KVM PPC needs to avoid that side + * effect for unknown historical reasons. */ - if (kvm_arch_vcpu_should_kick(vcpu)) { + if (force || kvm_request_needs_ipi(vcpu, req)) { cpu = READ_ONCE(vcpu->cpu); if (cpu != me && (unsigned int)cpu < nr_cpu_ids && cpu_online(cpu)) { /* - * Use a reschedule IPI to kick the vCPU if the caller - * doesn't need to wait for a response, as KVM allows - * kicking vCPUs while IRQs are disabled, but using the - * SMP function call framework with IRQs disabled can - * deadlock due to taking cross-CPU locks. + * Use a reschedule IPI to kick the vCPU if the request + * doesn't need to wait for a response (or there is no + * request), as KVM allows kicking vCPUs while IRQs are + * disabled, but using the SMP function call framework + * with IRQs disabled can deadlock due to taking cross- + * CPU locks. */ - if (wait) - smp_call_function_single(cpu, ack_kick, NULL, wait); + if (req & KVM_REQUEST_WAIT) + smp_call_function_single(cpu, ack_kick, NULL, true); else smp_send_reschedule(cpu); }