diff options
995 files changed, 16794 insertions, 6420 deletions
@@ -365,6 +365,9 @@ Guru Das Srinagesh <linux@gurudas.dev> <gurooodas@gmail.com> Gustavo Padovan <gustavo@las.ic.unicamp.br> Gustavo Padovan <padovan@profusion.mobi> Hamza Mahfooz <hamzamahfooz@linux.microsoft.com> <hamza.mahfooz@amd.com> +Hangbin Liu <hangbin.liu@linux.dev> <liuhangbin@gmail.com> +Hangbin Liu <hangbin.liu@linux.dev> <haliu@redhat.com> +Hangbin Liu <hangbin.liu@linux.dev> <liuhangbin@kylinos.cn> Hanjun Guo <guohanjun@huawei.com> <hanjun.guo@linaro.org> Hans de Goede <hansg@kernel.org> <hdegoede@redhat.com> Hans Verkuil <hverkuil@kernel.org> <hverkuil@xs4all.nl> diff --git a/Documentation/admin-guide/LSM/landlock.rst b/Documentation/admin-guide/LSM/landlock.rst index 718e0d23ffb5..946f3bf89650 100644 --- a/Documentation/admin-guide/LSM/landlock.rst +++ b/Documentation/admin-guide/LSM/landlock.rst @@ -73,8 +73,9 @@ AUDIT_LANDLOCK_ACCESS :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 - :manpage:`setns(2)` operations (zero for creation) + 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) **capability.*** - Capability restrictions (ABI 12+): - capability.use - Capability use was denied; diff --git a/Documentation/admin-guide/kernel-parameters.txt b/Documentation/admin-guide/kernel-parameters.txt index 0b3c140babd9..176648941aec 100644 --- a/Documentation/admin-guide/kernel-parameters.txt +++ b/Documentation/admin-guide/kernel-parameters.txt @@ -6369,13 +6369,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/arch/arm64/gcs.rst b/Documentation/arch/arm64/gcs.rst index 226c0b008456..1e0424f915dc 100644 --- a/Documentation/arch/arm64/gcs.rst +++ b/Documentation/arch/arm64/gcs.rst @@ -179,9 +179,8 @@ intended to be exhaustive. When returning from a signal handler: -* If there is a gcs_context record in the signal frame then the GCS flags - and GCSPR_EL0 will be restored from that context prior to further - validation. +* If there is a gcs_context record in the signal frame then GCSPR_EL0 + will be restored from that context prior to further validation. * If there is no gcs_context record in the signal frame then the GCS configuration will be unchanged. @@ -190,12 +189,8 @@ When returning from a signal handler: point to a valid GCS signal cap record, this will be popped from the GCS prior to signal return. -* If the GCS configuration is locked when returning from a signal then any - attempt to change the GCS configuration will be treated as an error. This - is true even if GCS was not enabled prior to signal entry. - -* GCS may be disabled via signal return but any attempt to enable GCS via - signal return will be rejected. +* The features_enabled in the signal return context will be ignored; any + changes made using the prctl() in the signal handler will be preserved. 6. ptrace extensions diff --git a/Documentation/arch/arm64/silicon-errata.rst b/Documentation/arch/arm64/silicon-errata.rst index afe109afe692..dc4144ac895b 100644 --- a/Documentation/arch/arm64/silicon-errata.rst +++ b/Documentation/arch/arm64/silicon-errata.rst @@ -171,10 +171,18 @@ stable kernels. +----------------+-----------------+-----------------+-----------------------------+ | ARM | Cortex-A715 | #2645198 | ARM64_ERRATUM_2645198 | +----------------+-----------------+-----------------+-----------------------------+ +| ARM | Cortex-A715 | #2738462 | ARM64_ERRATUM_2738461 | ++----------------+-----------------+-----------------+-----------------------------+ | ARM | Cortex-A715 | #3456084 | ARM64_ERRATUM_3194386 | +----------------+-----------------+-----------------+-----------------------------+ +| ARM | Cortex-A720 | #2738461 | ARM64_ERRATUM_2738461 | ++----------------+-----------------+-----------------+-----------------------------+ | ARM | Cortex-A720 | #3456091 | ARM64_ERRATUM_3194386 | +----------------+-----------------+-----------------+-----------------------------+ +| ARM | Cortex-A720 | #4689339 | ARM64_ERRATUM_3821522 | ++----------------+-----------------+-----------------+-----------------------------+ +| ARM | Cortex-A720AE | #4689340 | ARM64_ERRATUM_3821522 | ++----------------+-----------------+-----------------+-----------------------------+ | ARM | Cortex-A725 | #3456106 | ARM64_ERRATUM_3194386 | +----------------+-----------------+-----------------+-----------------------------+ | ARM | Cortex-A725 | #3821522 | ARM64_ERRATUM_3821522 | @@ -233,6 +241,8 @@ stable kernels. +----------------+-----------------+-----------------+-----------------------------+ | ARM | Neoverse-N3 | #3456111 | ARM64_ERRATUM_3194386 | +----------------+-----------------+-----------------+-----------------------------+ +| ARM | Neoverse-N3 | #4689341 | ARM64_ERRATUM_3821522 | ++----------------+-----------------+-----------------+-----------------------------+ | ARM | Neoverse-V1 | #1619801 | N/A | +----------------+-----------------+-----------------+-----------------------------+ | ARM | Neoverse-V1 | #3324341 | ARM64_ERRATUM_3194386 | @@ -257,6 +267,8 @@ stable kernels. +----------------+-----------------+-----------------+-----------------------------+ | ARM | C1-Pro | #4193714 | ARM64_ERRATUM_4193714 | +----------------+-----------------+-----------------+-----------------------------+ +| ARM | C1-Pro | #4689344 | ARM64_ERRATUM_3821522 | ++----------------+-----------------+-----------------+-----------------------------+ | ARM | C1-Ultra | #3683289 | N/A | +----------------+-----------------+-----------------+-----------------------------+ | ARM | C1-Ultra | #4193780 | ARM64_ERRATUM_4118414 | diff --git a/Documentation/bpf/bpf_devel_QA.rst b/Documentation/bpf/bpf_devel_QA.rst index 4729efd657c3..888b29599761 100644 --- a/Documentation/bpf/bpf_devel_QA.rst +++ b/Documentation/bpf/bpf_devel_QA.rst @@ -304,31 +304,13 @@ downstream distributions. Q: Do you accept patches as well for iproute2's BPF loader? ----------------------------------------------------------- -A: Patches for the iproute2's BPF loader have to be sent to: +A: Patches for iproute2, including its BPF loader, are sent to +netdev@vger.kernel.org. For details on iproute2 patch submission, see +"Co-posting iproute2 patches" in Documentation/process/maintainer-netdev.rst. - netdev@vger.kernel.org - -While those patches are not processed by the BPF kernel maintainers, -please keep them in Cc as well, so they can be reviewed. - -The official git repository for iproute2 is run by Stephen Hemminger -and can be found at: - - https://git.kernel.org/pub/scm/linux/kernel/git/shemminger/iproute2.git/ - -The patches need to have a subject prefix of '``[PATCH iproute2 -master]``' or '``[PATCH iproute2 net-next]``'. '``master``' or -'``net-next``' describes the target branch where the patch should be -applied to. Meaning, if kernel changes went into the net-next kernel -tree, then the related iproute2 changes need to go into the iproute2 -net-next branch, otherwise they can be targeted at master branch. The -iproute2 net-next branch will get merged into the master branch after -the current iproute2 version from master has been released. - -Like BPF, the patches end up in patchwork under the netdev project and -are delegated to 'shemminger' for further processing: - - http://patchwork.ozlabs.org/project/netdev/list/?delegate=389 +While iproute2 BPF loader patches are not processed by the BPF kernel +maintainers, please Cc bpf@vger.kernel.org and the BPF maintainers for +review. Q: What is the minimum requirement before I submit my BPF patches? ------------------------------------------------------------------ diff --git a/Documentation/core-api/assoc_array.rst b/Documentation/core-api/assoc_array.rst index 19d89f92bf8d..c5ada1bff06f 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 249101b55cf4..140d7034e219 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 5121685337b5..a0f2649129e0 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/regulator/fcs,fan53555.yaml b/Documentation/devicetree/bindings/regulator/fcs,fan53555.yaml index b35b8f365b0f..1bc22eb43dd9 100644 --- a/Documentation/devicetree/bindings/regulator/fcs,fan53555.yaml +++ b/Documentation/devicetree/bindings/regulator/fcs,fan53555.yaml @@ -20,6 +20,7 @@ properties: - fcs,fan53526 - rockchip,rk8600 - rockchip,rk8602 + - silergy,sym827 - silergy,syr827 - silergy,syr828 - tcs,tcs4525 diff --git a/Documentation/devicetree/bindings/spi/spi-pl022.yaml b/Documentation/devicetree/bindings/spi/spi-pl022.yaml index 680fdfa184d0..9a61cb16e683 100644 --- a/Documentation/devicetree/bindings/spi/spi-pl022.yaml +++ b/Documentation/devicetree/bindings/spi/spi-pl022.yaml @@ -71,6 +71,9 @@ properties: - const: rx - const: tx + power-domains: + maxItems: 1 + resets: maxItems: 1 diff --git a/Documentation/filesystems/erofs.rst b/Documentation/filesystems/erofs.rst index 02caf3b061fe..7f4d55077848 100644 --- a/Documentation/filesystems/erofs.rst +++ b/Documentation/filesystems/erofs.rst @@ -171,13 +171,28 @@ Each mounted filesystem will have a directory in /sys/fs/erofs based on its device name (i.e., /sys/fs/erofs/sda). (see also Documentation/ABI/testing/sysfs-fs-erofs) -On-disk details -=============== +On-disk format +============== + +This section provides a high-level overview. For the latest complete on-disk +format specification, see: + +- https://erofs.docs.kernel.org/en/latest/ondisk/ Summary ------- -Different from other read-only file systems, an EROFS volume is designed -to be as simple as possible:: + +EROFS keeps its on-disk format as simple as possible to minimize metadata +consistency checks, retaining only those that are strictly necessary +at runtime. + +The guiding principle is that malformed or deliberately crafted metadata +may describe a corrupt filesystem, but its effects should remain confined +to the data and metadata exposed to userspace: garbage filesystems return +garbage (meta)data to users, and nothing more. Violating this rule is +unsafe and must be prevented by our on-disk design. + +:: |-> aligned with the block size ____________________________________________________________ @@ -185,16 +200,50 @@ to be as simple as possible:: |_|__|_|_____|__________|_____|______|__________|_____|______| 0 +1K -All data areas should be aligned with the block size, but metadata areas -may not. All metadata can be now observed in two different spaces (views): +Apart from the EROFS superblock, which starts at byte offset 1024, metadata +and data regions have no fixed locations or boundaries and may be interleaved +throughout the image. As a result, inodes do not need to reside in a fixed +central table, allowing incremental builds, although the image creator may +still choose to group all inodes together. + +All data except inline data must be aligned to the filesystem block size +[#unencoded_data]_ to enable efficient block I/O, support memory mapping, +and avoid unnecessary data copies. Metadata does not require block alignment. + +.. [#unencoded_data] Strictly speaking, data refers to unencoded data; + encoded inodes are outside the scope of EROFS core metadata. - 1. Inode metadata space +EROFS core metadata consists only of the superblock, inodes, and directory +entries stored in directory inode data. The physical locations of inode +data are recorded as block numbers to avoid block-alignment checks. - Each valid inode should be aligned with an inode slot, which is a fixed - value (32 bytes) and designed to be kept in line with compact inode size. +Only a few superblock fields, including the root nid (see below), are needed +to parse the filesystem tree. Most of the remaining fields provide filesystem +statistics reported to userspace and should not affect the core filesystem +logic. - Each inode can be directly found with the following formula: - inode offset = meta_blkaddr * block_size + 32 * nid +Encoded inodes, which contain encoded data such as compressed data (including +compressed directories), use a distinct inode "datalayout" number that allows +them to be identified or rejected when reading the inode metadata. Support for +encoded layouts is optional and can be explicitly disabled at runtime if there +are security concerns about parsing compressed data in the kernel. + +There are two metadata views: one for inode metadata and one for shared +extended attributes. Both can also be located in a special hidden inode +called "metabox" (v6.17+), which provides a unified way to compress inode and +xattr metadata: + + 1. Inode metadata view + + Each valid inode is aligned to a 32-byte inode slot, matching the + size of a compact inode. Inodes can be stored either inside or outside + the metabox inode, with a flag in the nid indicating whether they are + stored inside. + + For inodes not in the metabox, each inode can be located directly + using the following formula:: + + inode physical position = meta_blkaddr * block_size + 32 * nid :: @@ -224,8 +273,8 @@ may not. All metadata can be now observed in two different spaces (views): |-> aligned with 4B |-> aligned with 4B - Inode could be 32 or 64 bytes, which can be distinguished from a common - field which all inode versions have -- i_format:: + Inodes can be 32 or 64 bytes, distinguished by the i_format field common + to both formats:: __________________ __________________ | i_format | | i_format | @@ -236,31 +285,44 @@ may not. All metadata can be now observed in two different spaces (views): | | |__________________| 64 bytes - Xattrs, extents, data inline are placed after the corresponding inode with - proper alignment, and they could be optional for different data mappings. - _currently_ total 5 data layouts are supported: + Xattrs, extents, and inline data follow the corresponding inode with + proper alignment. Their presence depends on the inode's datalayout. + Five data layouts are currently supported: == ==================================================================== - 0 flat file data without data inline (no extent); - 1 fixed-sized output data compression (with non-compacted indexes); - 2 flat file data with tail packing data inline (no extent); - 3 fixed-sized output data compression (with compacted indexes, v5.3+); - 4 chunk-based file (v5.15+). + 0 Flat inode data without inline data (no extents) + 1 Encoded inode + 2 Flat inode data with inline tail data (no extents) + 3 Encoded inode (compact indexes) + 4 Chunk-based file (v5.15+) == ==================================================================== - The size of the optional xattrs is indicated by i_xattr_count in inode - header. Large xattrs or xattrs shared by many different files can be - stored in shared xattrs metadata rather than inlined right after inode. + The size of the optional xattrs is indicated by i_xattr_count in the inode + header. Large xattrs or xattrs shared by many files can be stored in + shared xattr metadata rather than inlined immediately after the inode. + + For inodes in the metabox, the remaining nid bits identify the inode slot + within the metabox's inode address space. This data is read through the + metabox inode, with decompression as needed. The metabox inode itself is + located outside the metabox and is identified by metabox_nid in the + superblock. - 2. Shared xattrs metadata space + 2. Shared xattrs metadata view - Shared xattrs space is similar to the above inode space, started with - a specific block indicated by xattr_blkaddr, organized one by one with - proper align. + The shared xattr metadata view is similar to the inode metadata view. + It starts at the block indicated by xattr_blkaddr, with entries stored + sequentially on 4-byte boundaries. Shared xattrs are stored either all + inside or all outside the metabox; this metadata view cannot be selected + individually for each entry. + + Each shared xattr can be located using the following formula:: - Each share xattr can also be directly found by the following formula: xattr offset = xattr_blkaddr * block_size + 4 * xattr_id + When COMPAT_SHARED_EA_IN_METABOX feature is enabled, this offset is within + the metabox inode's address space. Otherwise, it is a physical position + in the filesystem image. + :: |-> aligned by 4 bytes diff --git a/Documentation/filesystems/iomap/design.rst b/Documentation/filesystems/iomap/design.rst index 681e0cbb6944..508e63ce205c 100644 --- a/Documentation/filesystems/iomap/design.rst +++ b/Documentation/filesystems/iomap/design.rst @@ -75,7 +75,10 @@ At a high level, an iomap operation `looks like this 1. For each byte in the operation range... - 1. Obtain a space mapping via ``->iomap_begin`` + 1. Obtain the next space mapping via the ``iomap_iter_next_fn`` callback. + From the second iteration onwards this same callback first finishes + the previous mapping (committing or unreserving space as needed) + and then produces the next one. 2. For each sub-unit of work... @@ -86,7 +89,13 @@ At a high level, an iomap operation `looks like this 3. Increment operation cursor - 4. Release the mapping via ``->iomap_end``, if necessary +iomap repeats this until the range is fully consumed. The ``iomap_iter_next_fn`` +callback returns ``1`` while there is more of the range left to process, +``0`` once it is fully consumed, or a negative errno on error. +Filesystems rarely implement this callback by hand. The ``iomap_iter_next`` +helper implements the finish-then-produce sequence in terms of two smaller +callbacks, ``begin`` and ``end``. See `The Mapping Callback`_ below for more +info. Each iomap operation will be covered in more detail below. This library was covered previously by an `LWN article @@ -189,7 +198,7 @@ The fields are as follows: * **IOMAP_DELALLOC**: A promise to allocate space at a later time ("delayed allocation"). If the filesystem returns IOMAP_F_NEW here and the write fails, the - ``->iomap_end`` function must delete the reservation. + ``end`` function must delete the reservation. The ``addr`` field must be set to ``IOMAP_NULL_ADDR``. * **IOMAP_MAPPED**: The file range maps to specific space on the @@ -208,12 +217,11 @@ The fields are as follows: * **IOMAP_INLINE**: The file range maps to the memory buffer specified by ``inline_data``. - For write operation, the ``->iomap_end`` function presumably - handles persisting the data. + For write operation, the ``end`` function must persist the data. The ``addr`` field must be set to ``IOMAP_NULL_ADDR``. * ``flags`` describe the status of the space mapping. - These flags should be set by the filesystem in ``->iomap_begin``: + These flags should be set by the filesystem in ``begin``: * **IOMAP_F_NEW**: The space under the mapping is newly allocated. Areas that will not be written to must be zeroed. @@ -262,15 +270,15 @@ The fields are as follows: update. These flags can be set by iomap itself during file operations. - The filesystem should supply an ``->iomap_end`` function if it needs + The filesystem should supply an ``end`` function if it needs to observe these flags: * **IOMAP_F_SIZE_CHANGED**: The file size has changed as a result of using this mapping. * **IOMAP_F_STALE**: The mapping was found to be stale. - iomap will call ``->iomap_end`` on this mapping and then - ``->iomap_begin`` to obtain a new mapping. + iomap will call ``end`` on this mapping and then ``begin`` to obtain a + new mapping. Currently, these flags are only set by pagecache operations. @@ -289,41 +297,103 @@ The fields are as follows: * ``private`` is a pointer to `filesystem-private information <https://lore.kernel.org/all/20180619164137.13720-7-hch@lst.de/>`_. - This value will be passed unchanged to ``->iomap_end``. + This value will be passed unchanged to ``end``. * ``validity_cookie`` is a magic freshness value set by the filesystem that should be used to detect stale mappings. For pagecache operations this is critical for correct operation because page faults can occur, which implies that filesystem locks - should not be held between ``->iomap_begin`` and ``->iomap_end``. + should not be held between ``begin`` and ``end``. Filesystems with completely static mappings need not set this value. Only pagecache operations revalidate mappings; see the section about ``iomap_valid`` for details. -``struct iomap_ops`` +The Mapping Callback -------------------- -Every iomap function requires the filesystem to pass an operations -structure to obtain a mapping and (optionally) to release the mapping: +Every iomap operation takes an ``iomap_iter_next_fn`` callback from the +filesystem. iomap calls it once per iteration of the file range: .. code-block:: c - struct iomap_ops { - int (*iomap_begin)(struct inode *inode, loff_t pos, loff_t length, - unsigned flags, struct iomap *iomap, - struct iomap *srcmap); + typedef int (*iomap_iter_next_fn)(const struct iomap_iter *iter, + struct iomap *iomap, struct iomap *srcmap); - int (*iomap_end)(struct inode *inode, loff_t pos, loff_t length, - ssize_t written, unsigned flags, - struct iomap *iomap); - }; +``iomap_iter_next_fn`` +~~~~~~~~~~~~~~~~~~~~~~ + +This must finish the previous mapping, if any, and then produce the next +mapping for the current iteration position described by ``iter``. +The mapping is returned through ``iomap`` (and through ``srcmap`` for +operations that read from one mapping while writing to another; see +``begin`` below). + +The callback returns ``1`` to continue iterating, ``0`` once the file +range has been fully consumed, or a negative errno on error. + +Most filesystems are not expected to implement all of these behaviors +in this callback themselves. They should instead call ``iomap_iter_next`` as +described below. + +``iomap_iter_next`` +~~~~~~~~~~~~~~~~~~~ + +Filesystems rarely need a hand-written ``iomap_iter_next_fn`` callback. The +``iomap_iter_next`` helper implements the finish-then-produce sequence in +terms of two smaller callbacks, ``begin`` and ``end``, so most +``iomap_iter_next_fn`` implementations are simply: + +.. code-block:: c + + static int my_iomap_next(const struct iomap_iter *iter, + struct iomap *iomap, struct iomap *srcmap) + { + return iomap_iter_next(iter, iomap, srcmap, + my_iomap_begin, my_iomap_end); + } + +This boilerplate is normally generated with the ``DEFINE_IOMAP_ITER_NEXT()`` +and ``DEFINE_IOMAP_ITER_NEXT_END()`` macros rather than written by hand. Use +``DEFINE_IOMAP_ITER_NEXT()`` for the common case with no ``end`` callback, and +``DEFINE_IOMAP_ITER_NEXT_END()`` when an ``end`` callback is needed: + +.. code-block:: c + + /* no end() callback */ + static DEFINE_IOMAP_ITER_NEXT(my_iomap_next, my_iomap_begin); + + /* with an end() callback */ + static DEFINE_IOMAP_ITER_NEXT_END(my_iomap_next, my_iomap_begin, + my_iomap_end); + +The macro generates a function with external linkage. Prefix the invocation +with ``static`` for a file-local callback, or leave it non-``static`` and add +a matching declaration to a header when the callback is referenced from +another file. + +``end`` may be ``NULL`` when the filesystem has nothing to finish. +The two callbacks have these prototypes: + +.. code-block:: c + + typedef int (*iomap_begin_fn)(struct inode *inode, loff_t pos, + loff_t length, unsigned flags, + struct iomap *iomap, struct iomap *srcmap); + + typedef int (*iomap_end_fn)(struct inode *inode, loff_t pos, + loff_t length, ssize_t written, + unsigned flags, struct iomap *iomap); + +``iomap_iter_next`` is an inline helper, so when it is called with fixed +``begin`` and ``end`` functions the compiler can inline both into the +filesystem's ``iomap_iter_next_fn`` callback, keeping indirect calls out of the +iteration hot path. The two callbacks are described next. -``->iomap_begin`` -~~~~~~~~~~~~~~~~~ +``begin`` +~~~~~~~~~ -iomap operations call ``->iomap_begin`` to obtain one file mapping for -the range of bytes specified by ``pos`` and ``length`` for the file -``inode``. +The ``begin`` callback obtains one file mapping for the range of bytes +specified by ``pos`` and ``length`` for the file ``inode``. This mapping should be returned through the ``iomap`` pointer. The mapping must cover at least the first byte of the supplied file range, but it does not need to cover the entire requested range. @@ -377,18 +447,18 @@ information via ``srcmap``. Only pagecache and fsdax operations support reading from one mapping and writing to another. -``->iomap_end`` -~~~~~~~~~~~~~~~ +``end`` +~~~~~~~ -After the operation completes, the ``->iomap_end`` function, if present, -is called to signal that iomap is finished with a mapping. +After the operation completes, the ``end`` callback, if present, is called to +signal that iomap is finished with a mapping. Typically, implementations will use this function to tear down any -context that were set up in ``->iomap_begin``. +context that was set up in ``begin``. For example, a write might wish to commit the reservations for the bytes that were operated upon and unreserve any space that was not operated upon. ``written`` might be zero if no bytes were touched. -``flags`` will contain the same value passed to ``->iomap_begin``. +``flags`` will contain the same value passed to ``begin``. iomap ops for reads are not likely to need to supply this function. Both functions should return a negative errno code on error, or zero on @@ -421,8 +491,8 @@ iomap is concerned: accessing the folio until writeback is underway. * The **lower** level primitive is taken by the filesystem in the - ``->iomap_begin`` and ``->iomap_end`` functions to coordinate - access to the file space mapping information. + ``begin`` and ``end`` functions to coordinate access to the file space + mapping information. The fields of the iomap object should be filled out while holding this primitive. The upper level synchronization primitive, if any, remains held diff --git a/Documentation/filesystems/iomap/operations.rst b/Documentation/filesystems/iomap/operations.rst index da982ca7e413..a5784dee0850 100644 --- a/Documentation/filesystems/iomap/operations.rst +++ b/Documentation/filesystems/iomap/operations.rst @@ -17,6 +17,12 @@ Supported File Operations Below are a discussion of the high level file operations that iomap implements. +Each operation takes an ``iomap_iter_next_fn`` callback that supplies the file +mappings, as described in the iomap design document. The per-operation +``flags`` documented below are passed to that callback; references to +``begin`` and ``end`` name the two steps a typical callback is built from +via ``iomap_iter_next``. + Buffered I/O ============ @@ -90,10 +96,10 @@ iomap calls these functions: <https://lore.kernel.org/all/20180619164137.13720-6-hch@lst.de/>`_ that was set up by ``->get_folio``. - - ``iomap_valid``: The filesystem may not hold locks between - ``->iomap_begin`` and ``->iomap_end`` because pagecache operations - can take folio locks, fault on userspace pages, initiate writeback - for memory reclamation, or engage in other time-consuming actions. + - ``iomap_valid``: The filesystem may not hold locks between ``begin`` and + ``end`` because pagecache operations can take folio locks, fault on + userspace pages, initiate writeback for memory reclamation, or engage in + other time-consuming actions. If a file's space mapping data are mutable, it is possible that the mapping for a particular pagecache folio can `change in the time it takes @@ -114,12 +120,12 @@ iomap calls these functions: If the mapping is not valid, the mapping will be sampled again. To support making the validity decision, the filesystem's - ``->iomap_begin`` function may set ``struct iomap::validity_cookie`` + ``begin`` function may set ``struct iomap::validity_cookie`` at the same time that it populates the other iomap fields. A simple validation cookie implementation is a sequence counter. If the filesystem bumps the sequence counter every time it modifies the inode's extent map, it can be placed in the ``struct - iomap::validity_cookie`` during ``->iomap_begin``. + iomap::validity_cookie`` during ``begin``. If the value in the cookie is found to be different to the value the filesystem holds when the mapping is passed back to ``->iomap_valid``, then the iomap should considered stale and the @@ -199,7 +205,7 @@ Buffered Readahead and Reads The ``iomap_readahead`` function initiates readahead to the pagecache. The ``iomap_read_folio`` function reads one folio's worth of data into the pagecache. -The ``flags`` argument to ``->iomap_begin`` will be set to zero. +The ``flags`` argument to ``begin`` will be set to zero. The pagecache takes whatever locks it needs before calling the filesystem. @@ -231,7 +237,7 @@ Buffered Writes The ``iomap_file_buffered_write`` function writes an ``iocb`` to the pagecache. ``IOMAP_WRITE`` or ``IOMAP_WRITE`` | ``IOMAP_NOWAIT`` will be passed as -the ``flags`` argument to ``->iomap_begin``. +the ``flags`` argument to ``begin``. Callers commonly take ``i_rwsem`` in either shared or exclusive mode before calling this function. @@ -241,7 +247,7 @@ mmap Write Faults The ``iomap_page_mkwrite`` function handles a write fault to a folio in the pagecache. ``IOMAP_WRITE | IOMAP_FAULT`` will be passed as the ``flags`` argument -to ``->iomap_begin``. +to ``begin``. Callers commonly take the mmap ``invalidate_lock`` in shared or exclusive mode before calling this function. @@ -256,7 +262,7 @@ such `reservations <https://lore.kernel.org/linux-xfs/20220817093627.GZ3600936@dread.disaster.area/>`_ because writeback will not consume the reservation. The ``iomap_write_delalloc_release`` can be called from a -``->iomap_end`` function to find all the clean areas of the folios +``end`` function to find all the clean areas of the folios caching a fresh (``IOMAP_F_NEW``) delalloc mapping. It takes the ``invalidate_lock``. @@ -274,7 +280,7 @@ Filesystems can call ``iomap_zero_range`` to perform zeroing of the pagecache for non-truncation file operations that are not aligned to the fsblock size. ``IOMAP_ZERO`` will be passed as the ``flags`` argument to -``->iomap_begin``. +``begin``. Callers typically hold ``i_rwsem`` and ``invalidate_lock`` in exclusive mode before calling this function. @@ -285,7 +291,7 @@ Filesystems can call ``iomap_file_unshare`` to force a file sharing storage with another file to preemptively copy the shared data to newly allocate storage. ``IOMAP_WRITE | IOMAP_UNSHARE`` will be passed as the ``flags`` argument -to ``->iomap_begin``. +to ``begin``. Callers typically hold ``i_rwsem`` and ``invalidate_lock`` in exclusive mode before calling this function. @@ -298,7 +304,7 @@ operation. ``truncate_setsize`` or ``truncate_pagecache`` will take care of everything after the EOF block. ``IOMAP_ZERO`` will be passed as the ``flags`` argument to -``->iomap_begin``. +``begin``. Callers typically hold ``i_rwsem`` and ``invalidate_lock`` in exclusive mode before calling this function. @@ -341,8 +347,8 @@ The fields are as follows: though it will `reuse mappings <https://lore.kernel.org/all/20231207072710.176093-15-hch@lst.de/>`_ for runs of contiguous dirty fsblocks within a folio. - Do not return ``IOMAP_INLINE`` mappings here; the ``->iomap_end`` - function must deal with persisting written data. + Do not return ``IOMAP_INLINE`` mappings here; the ``end`` function must + deal with persisting written data. Do not return ``IOMAP_DELALLOC`` mappings here; iomap currently requires mapping to allocated space. Filesystems can skip a potentially expensive mapping lookup if the @@ -428,7 +434,7 @@ writes for files. .. code-block:: c ssize_t iomap_dio_rw(struct kiocb *iocb, struct iov_iter *iter, - const struct iomap_ops *ops, + iomap_iter_next_fn iomap_next, const struct iomap_dio_ops *dops, unsigned int dio_flags, void *private, size_t done_before); @@ -511,7 +517,7 @@ Return Values * ``-ENOTBLK``: Fall back to buffered I/O. iomap itself will return this value if it cannot invalidate the page cache before issuing the I/O to storage. - The ``->iomap_begin`` or ``->iomap_end`` functions may also return + The ``begin`` or ``end`` functions may also return this value. * ``-EIOCBQUEUED``: The asynchronous direct I/O request has been @@ -526,7 +532,7 @@ A direct I/O read initiates a read I/O from the storage device to the caller's buffer. Dirty parts of the pagecache are flushed to storage before initiating the read io. -The ``flags`` value for ``->iomap_begin`` will be ``IOMAP_DIRECT`` with +The ``flags`` value for ``begin`` will be ``IOMAP_DIRECT`` with any combination of the following enhancements: * ``IOMAP_NOWAIT``, as defined previously. @@ -542,7 +548,7 @@ caller's buffer. Dirty parts of the pagecache are flushed to storage before initiating the write io. The pagecache is invalidated both before and after the write io. -The ``flags`` value for ``->iomap_begin`` will be ``IOMAP_DIRECT | +The ``flags`` value for ``begin`` will be ``IOMAP_DIRECT | IOMAP_WRITE`` with any combination of the following enhancements: * ``IOMAP_NOWAIT``, as defined previously. @@ -644,7 +650,7 @@ fsdax Reads A fsdax read performs a memcpy from storage device to the caller's buffer. -The ``flags`` value for ``->iomap_begin`` will be ``IOMAP_DAX`` with any +The ``flags`` value for ``begin`` will be ``IOMAP_DAX`` with any combination of the following enhancements: * ``IOMAP_NOWAIT``, as defined previously. @@ -657,7 +663,7 @@ fsdax Writes A fsdax write initiates a memcpy to the storage device from the caller's buffer. -The ``flags`` value for ``->iomap_begin`` will be ``IOMAP_DAX | +The ``flags`` value for ``begin`` will be ``IOMAP_DAX | IOMAP_WRITE`` with any combination of the following enhancements: * ``IOMAP_NOWAIT``, as defined previously. @@ -680,9 +686,9 @@ fsdax mmap Faults The ``dax_iomap_fault`` function handles read and write faults to fsdax storage. For a read fault, ``IOMAP_DAX | IOMAP_FAULT`` will be passed as the -``flags`` argument to ``->iomap_begin``. +``flags`` argument to ``begin``. For a write fault, ``IOMAP_DAX | IOMAP_FAULT | IOMAP_WRITE`` will be -passed as the ``flags`` argument to ``->iomap_begin``. +passed as the ``flags`` argument to ``begin``. Callers commonly hold the same locks as they do to call their iomap pagecache counterparts. @@ -692,8 +698,8 @@ fsdax Truncation, fallocate, and Unsharing For fsdax files, the following functions are provided to replace their iomap pagecache I/O counterparts. -The ``flags`` argument to ``->iomap_begin`` are the same as the -pagecache counterparts, with ``IOMAP_DAX`` added. +The ``flags`` argument to ``begin`` are the same as the pagecache counterparts, +with ``IOMAP_DAX`` added. * ``dax_file_unshare`` * ``dax_zero_range`` @@ -719,8 +725,7 @@ SEEK_DATA The ``iomap_seek_data`` function implements the SEEK_DATA "whence" value for llseek. -``IOMAP_REPORT`` will be passed as the ``flags`` argument to -``->iomap_begin``. +``IOMAP_REPORT`` will be passed as the ``flags`` argument to ``begin``. For unwritten mappings, the pagecache will be searched. Regions of the pagecache with a folio mapped and uptodate fsblocks @@ -734,8 +739,7 @@ SEEK_HOLE The ``iomap_seek_hole`` function implements the SEEK_HOLE "whence" value for llseek. -``IOMAP_REPORT`` will be passed as the ``flags`` argument to -``->iomap_begin``. +``IOMAP_REPORT`` will be passed as the ``flags`` argument to ``begin``. For unwritten mappings, the pagecache will be searched. Regions of the pagecache with no folio mapped, or a !uptodate fsblock @@ -750,8 +754,7 @@ Swap File Activation The ``iomap_swapfile_activate`` function finds all the base-page aligned regions in a file and sets them up as swap space. The file will be ``fsync()``'d before activation. -``IOMAP_REPORT`` will be passed as the ``flags`` argument to -``->iomap_begin``. +``IOMAP_REPORT`` will be passed as the ``flags`` argument to ``begin``. All mappings must be mapped or unwritten; cannot be dirty or shared, and cannot span multiple block devices. Callers must hold ``i_rwsem`` in exclusive mode; this is already @@ -767,8 +770,7 @@ FS_IOC_FIEMAP The ``iomap_fiemap`` function exports file extent mappings to userspace in the format specified by the ``FS_IOC_FIEMAP`` ioctl. -``IOMAP_REPORT`` will be passed as the ``flags`` argument to -``->iomap_begin``. +``IOMAP_REPORT`` will be passed as the ``flags`` argument to ``begin``. Callers commonly hold ``i_rwsem`` in shared mode before calling this function. diff --git a/Documentation/filesystems/iomap/porting.rst b/Documentation/filesystems/iomap/porting.rst index 3d49a32c0fff..b995f426808a 100644 --- a/Documentation/filesystems/iomap/porting.rst +++ b/Documentation/filesystems/iomap/porting.rst @@ -50,8 +50,14 @@ Build the kernel, run fstests with the ``-g all`` option across a wide variety of your filesystem's supported configurations to build a baseline of which tests pass and which ones fail. -The recommended approach is first to implement ``->iomap_begin`` (and -``->iomap_end`` if necessary) to allow iomap to obtain a read-only +Every iomap operation is driven by an ``iomap_iter_next_fn`` callback. +Filesystems normally do not write one by hand: implement ``begin`` +(and ``end`` if necessary) and generate the callback with the +``DEFINE_IOMAP_ITER_NEXT()`` macro, or ``DEFINE_IOMAP_ITER_NEXT_END()`` if an +``end`` callback is needed. + +The recommended approach is first to implement ``begin`` (and +``end`` if necessary) to allow iomap to obtain a read-only mapping of a file range. In most cases, this is a relatively trivial conversion of the existing ``get_block()`` function for read-only mappings. @@ -62,7 +68,7 @@ If FIEMAP is returning the correct information, it's a good sign that other read-only mapping operations will do the right thing. Next, modify the filesystem's ``get_block(create = false)`` -implementation to use the new ``->iomap_begin`` implementation to map +implementation to use the new ``begin`` implementation to map file space for selected read operations. Hide behind a debugging knob the ability to switch on the iomap mapping functions for selected call paths. @@ -82,14 +88,14 @@ I/O path because of bufferheads. The buffered read I/O paths doesn't need to be converted yet, though the direct I/O read path should be converted in this phase. -At this point, you should look over your ``->iomap_begin`` function. +At this point, you should look over your ``begin`` function. If it switches between large blocks of code based on dispatching of the ``flags`` argument, you should consider breaking it up into per-operation iomap ops with smaller, more cohesive functions. XFS is a good example of this. The next thing to do is implement ``get_blocks(create == true)`` -functionality in the ``->iomap_begin``/``->iomap_end`` methods. +functionality in the ``begin``/``end`` methods. It is strongly recommended to create separate mapping functions and iomap ops for write operations. Then convert the direct I/O write path to iomap, and start running fsx diff --git a/Documentation/filesystems/nfs/localio.rst b/Documentation/filesystems/nfs/localio.rst index 79808b37d745..45c6981da0d8 100644 --- a/Documentation/filesystems/nfs/localio.rst +++ b/Documentation/filesystems/nfs/localio.rst @@ -312,6 +312,18 @@ Module Parameters /sys/module/nfs/parameters/localio_enabled (bool) controls if LOCALIO is enabled, defaults to Y. If client and server are local but 'localio_enabled' is set to N then LOCALIO will not be used. +It is checked on every I/O: setting it to N sends the next I/O of every +client over the network, and setting it back to Y resumes LOCALIO. A +client that probed while it was N is probed again when it is set to Y. + +/sys/module/nfs/parameters/localio_timeout (uint) +sets how many seconds the LOCALIO probe waits for each reply from the +server, defaults to 10, at most 600. A server that does not support +LOCALIO may not answer the probe at all. If no reply comes in time, +the probe gives up without a log message. The client then does not use +LOCALIO. The mount's timeouts do not apply to the probe. Set to 0, the +probe uses the mount's timeouts instead, as an NFS RPC would. A change +applies to the next probe. /sys/module/nfs/parameters/localio_O_DIRECT_semantics (bool) controls if O_DIRECT extends down to the underlying filesystem, defaults diff --git a/Documentation/filesystems/overlayfs.rst b/Documentation/filesystems/overlayfs.rst index 4c241d220bc2..e01f7810c027 100644 --- a/Documentation/filesystems/overlayfs.rst +++ b/Documentation/filesystems/overlayfs.rst @@ -236,14 +236,19 @@ Module options (can also be changed through /sys/module/overlay/parameters/): Mount options: - "redirect_dir=on": - Redirects are enabled. + Redirects are created and followed. - "redirect_dir=follow": Redirects are not created, but followed. +- "redirect_dir=followdata": + Redirects are not created. + Only redirects from lower to lowerdata are followed. - "redirect_dir=nofollow": Redirects are not created and not followed. - "redirect_dir=off": - If "redirect_always_follow" is enabled in the kernel/module config, - this "off" translates to "follow", otherwise it translates to "nofollow". + Redirects are not created. + Which redirects are followed depends on "redirect_always_follow" in the + kernel/module config, on data-only lower layers and on the "userxattr" + mount option. When the NFS export feature is enabled, every copied up directory is indexed by the file handle of the lower inode and a file handle of the @@ -418,8 +423,8 @@ pointed by REDIRECT. This should not be possible on local system as setting "trusted." xattrs will require CAP_SYS_ADMIN. But it should be possible for untrusted layers like from a pen drive. -Note: redirect_dir={off|nofollow|follow[*]} and nfs_export=on mount options -conflict with metacopy=on, and will result in an error. +Note: redirect_dir={off|nofollow|followdata|follow[*]} and nfs_export=on +mount options conflict with metacopy=on, and will result in an error. [*] redirect_dir=follow only conflicts with metacopy=on if upperdir=... is given. @@ -460,10 +465,11 @@ to the absolute path of the "lower data" file in the "data-only" lower layer. Instead of explicitly enabling "metacopy=on" it is sufficient to specify at least one data-only layer to enable redirection of data to a data-only layer. -In this case other forms of metacopy are rejected. Note: this way, data-only -layers may be used together with "userxattr", in which case careful attention -must be given to privileges needed to change the "user.overlay.redirect" xattr -to prevent misuse. +In this case other forms of metacopy are rejected. A data-only layer selects +"redirect_dir=followdata", unless "redirect_dir=follow" or "redirect_dir=on" is +in effect. Note: this way, data-only layers may be used together with +"userxattr", in which case careful attention must be given to privileges needed +to change the "user.overlay.redirect" xattr to prevent misuse. Since kernel version v6.8, "data-only" lower layers can also be added using the "datadir+" mount options and the fsconfig syscall from new mount api. diff --git a/Documentation/filesystems/porting.rst b/Documentation/filesystems/porting.rst index c38f5df755bb..e41466904501 100644 --- a/Documentation/filesystems/porting.rst +++ b/Documentation/filesystems/porting.rst @@ -1418,7 +1418,7 @@ All struct mnt_idmap pointers handed to filesystems are const now. ->create(), ->mkdir(), ->mknod(), ->symlink(), ->rename(), ->setattr(), ->getattr(), ->permission(), ->tmpfile(), ->get_acl(), ->set_acl() and ->fileattr_set() as well as the xattr ->set() handler and the vfs_*() -helpers take a const struct mnt_idmap *. mnt_idmap() and file_mnt_idmap() +helpers take a ``const struct mnt_idmap *``. mnt_idmap() and file_mnt_idmap() return one. The idmapping is immutable so nothing should have modified it anyway. References are taken and dropped via mnt_idmap_get() and mnt_idmap_put() as before, both accept a const pointer. diff --git a/Documentation/networking/net_cachelines/tcp_sock.rst b/Documentation/networking/net_cachelines/tcp_sock.rst index 93c85b621ec2..554e8c14a401 100644 --- a/Documentation/networking/net_cachelines/tcp_sock.rst +++ b/Documentation/networking/net_cachelines/tcp_sock.rst @@ -107,6 +107,7 @@ u32[3] received_ecn_bytes read_mostly read_w u8:4 received_ce_pending read_mostly read_write u32[3] delivered_ecn_bytes read_write u16 pkts_acked_ewma read_write +u32 rcv_collapse_credit read_write tcp_queue_rcv,tcp_data_queue_ofo,tcp_prune_queue u8:2 syn_ect_snt write_mostly read_write u8:2 syn_ect_rcv read_mostly read_write u8:2 accecn_minlen write_mostly read_write diff --git a/Documentation/power/runtime_pm.rst b/Documentation/power/runtime_pm.rst index 40a5c23d5259..f4723ad6e78d 100644 --- a/Documentation/power/runtime_pm.rst +++ b/Documentation/power/runtime_pm.rst @@ -222,11 +222,12 @@ what to do to handle the device). I/O operations as needed. The runtime PM status of the device is then 'active'. - * If the resume callback returns an error code, the PM core regards this as a - fatal error and will refuse to run the helper functions described in - `Section 4`_ for the device, until its status is directly set to either - 'active', or 'suspended' (by means of special helper functions provided by - the PM core for this purpose). + * If the resume callback returns an error code, the PM core sets the + device's runtime PM status back to 'suspended' and returns the error + code from synchronous resume helpers. Unlike most suspend callback + errors, failures in the resume callback are never considered fatal, + so the helper functions described in `Section 4`_ are not blocked and + a subsequent resume request can run the resume callback again. The idle callback (a subsystem-level one, if present, or the driver one) is executed by the PM core whenever the device appears to be idle, which is @@ -250,9 +251,9 @@ call to pm_runtime_autosuspend(). To prevent this suspension (for example, if the callback routine has scheduled a delayed suspend or determined the device cannot be idle), the routine must return a non-zero value (typically -EBUSY or -EAGAIN). Unlike -->runtime_suspend() and ->runtime_resume(), the PM core does not treat negative -return codes from ->runtime_idle() as a fatal device error; any non-zero value -simply stops the PM core from suspending the device. +->runtime_suspend(), the PM core does not treat negative return codes from +->runtime_idle() as a fatal device error, and any non-zero value simply stops +the PM core from suspending the device. Core Guarantees and Synchronization Rules ----------------------------------------- diff --git a/Documentation/process/maintainer-netdev.rst b/Documentation/process/maintainer-netdev.rst index 0c155adccfac..f7945f30cede 100644 --- a/Documentation/process/maintainer-netdev.rst +++ b/Documentation/process/maintainer-netdev.rst @@ -367,6 +367,41 @@ to the mailing list, e.g.:: Posting as one thread is discouraged because it confuses patchwork (as of patchwork 2.2.2). +Co-posting iproute2 patches +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The official git repositories for iproute2 are: + +- iproute2: https://git.kernel.org/pub/scm/network/iproute2/iproute2.git +- iproute2-next: https://git.kernel.org/pub/scm/network/iproute2/iproute2-next.git + +Patches for iproute2 must have a subject prefix of ``[PATCH iproute2]`` +or ``[PATCH iproute2-next]`` to indicate the target repository where the +patch should be applied. If kernel changes target net-next or bpf-next, +then the related iproute2 changes need to target iproute2-next, else they +must target iproute2. The iproute2-next tree will be merged into the +iproute2 tree after the current iproute2 version has been released. + +Patches are tracked in patchwork under the netdevbpf project. iproute2 +patches are delegated to 'shemminger' (Stephen Hemminger), iproute2-next +patches to 'dsa' (David Ahern): + +- iproute2: https://patchwork.kernel.org/project/netdevbpf/list/?delegate=7961&state=* +- iproute2-next: https://patchwork.kernel.org/project/netdevbpf/list/?delegate=123859&state=* + +Send patches to netdev@vger.kernel.org and always include the iproute2 +maintainers in the email Cc: list. See the MAINTAINERS file in the +repository for email addresses and other details: + + https://git.kernel.org/pub/scm/network/iproute2/iproute2.git/tree/MAINTAINERS + +For patches that target iproute2's BPF loader, also include +bpf@vger.kernel.org and the BPF maintainers. + +For more information, see also README.devel in the repository: + + https://git.kernel.org/pub/scm/network/iproute2/iproute2.git/tree/README.devel + Co-posting selftests ~~~~~~~~~~~~~~~~~~~~ diff --git a/Documentation/trace/events-landlock.rst b/Documentation/trace/events-landlock.rst index 9ccf2769a2d5..dc5f05a17c2c 100644 --- a/Documentation/trace/events-landlock.rst +++ b/Documentation/trace/events-landlock.rst @@ -187,8 +187,9 @@ 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 zero for namespace creation and is -the exact target namespace ID for :manpage:`setns(2)`. +``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_capability`` reports the denied ``CAP_*`` number. Like every denial event, both include the denying domain, ``same_exec``, and ``logged``. diff --git a/Documentation/trace/fprobe.rst b/Documentation/trace/fprobe.rst index 46dd46a97c1f..72e0fd9e1808 100644 --- a/Documentation/trace/fprobe.rst +++ b/Documentation/trace/fprobe.rst @@ -101,6 +101,11 @@ handler. If the entry callback function returns !0, the corresponding exit callback will be cancelled. +Since the callbacks run with preemption disabled under ftrace recursion +protection, calling printk() or pr_*() from these callbacks is not safe +and can cause deadlocks on console driver or scheduler locks. Use +trace_printk() instead to log debugging output. + @fp This is the address of `fprobe` data structure related to this handler. You can embed the `fprobe` to your data structure and get it by diff --git a/Documentation/trace/kprobes.rst b/Documentation/trace/kprobes.rst index 5e606730cec6..91b76ed435b1 100644 --- a/Documentation/trace/kprobes.rst +++ b/Documentation/trace/kprobes.rst @@ -31,7 +31,7 @@ can trap at almost any kernel code address [1]_, specifying a handler routine to be invoked when the breakpoint is hit. .. [1] some parts of the kernel code can not be trapped, see - :ref:`kprobes_blacklist`) + :ref:`kprobes_blacklist` There are currently two types of probes: kprobes, and kretprobes (also called return probes). A kprobe can be inserted on virtually @@ -563,8 +563,8 @@ course, has no way to distinguish the deliberately injected faults from the accidental ones. Don't drink and probe. Kprobes makes no attempt to prevent probe handlers from stepping on -each other -- e.g., probing printk() and then calling printk() from a -probe handler. If a probe handler hits a probe, that second probe's +each other -- e.g., probing trace_printk() and then calling trace_printk() +from a probe handler. If a probe handler hits a probe, that second probe's handlers won't be run in that instance, and the kprobe.nmissed member of the second probe will be incremented. @@ -579,6 +579,13 @@ which depends on the architecture and optimization state. (e.g., kretprobe handlers and optimized kprobe handlers run without interrupt disabled on x86/x86-64). In any case, your handler should not yield the CPU (e.g., by attempting to acquire a semaphore, or waiting I/O). +Furthermore, probe handlers should avoid calling printk() or pr_*(). +Because probe handlers execute in atomic/non-preemptible contexts without +being in NMI context (especially when jump-optimized or ftrace-based), +calling printk() may attempt to synchronously acquire console driver locks +or scheduler locks via console_unlock(), risking a deadlock if the probed +or interrupted context already holds those locks. Use trace_printk() +instead to safely output messages to the trace buffer. Since a return probe is implemented by replacing the return address with the trampoline's address, stack backtraces and calls diff --git a/MAINTAINERS b/MAINTAINERS index 222b7fc2c3aa..d738990161bd 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -7585,10 +7585,9 @@ F: drivers/dma/dw-edma/ F: include/linux/dma/edma.h DESIGNWARE USB2 DRD IP DRIVER -M: Minas Harutyunyan <hminas@synopsys.com> +M: Thinh Nguyen <Thinh.Nguyen@synopsys.com> 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 @@ -8362,6 +8361,7 @@ F: drivers/gpu/drm/tiny/hx8357d.c DRM DRIVER FOR HYPERV SYNTHETIC VIDEO DEVICE M: Dexuan Cui <decui@microsoft.com> +M: Hamza Mahfooz <hamzamahfooz@linux.microsoft.com> M: Saurabh Sengar <ssengar@linux.microsoft.com> L: linux-hyperv@vger.kernel.org L: dri-devel@lists.freedesktop.org @@ -14431,7 +14431,6 @@ M: Baoquan He <baoquan.he@linux.dev> M: Mike Rapoport <rppt@kernel.org> M: Pasha Tatashin <pasha.tatashin@soleen.com> M: Pratyush Yadav <pratyush@kernel.org> -R: Dave Young <ruirui.yang@linux.dev> L: kexec@lists.infradead.org S: Maintained T: git git://git.kernel.org/pub/scm/linux/kernel/git/liveupdate/linux.git @@ -18313,6 +18312,7 @@ F: drivers/net/phy/microchip_t1.c MICROCHIP LAN966X ETHERNET DRIVER M: Horatiu Vultur <horatiu.vultur@microchip.com> +M: Daniel Machon <daniel.machon@microchip.com> M: UNGLinuxDriver@microchip.com L: netdev@vger.kernel.org S: Maintained @@ -19634,7 +19634,9 @@ M: Steffen Klassert <steffen.klassert@secunet.com> M: Herbert Xu <herbert@gondor.apana.org.au> M: "David S. Miller" <davem@davemloft.net> L: netdev@vger.kernel.org +L: ipsec@lists.linux.dev S: Maintained +Q: https://patchwork.kernel.org/project/ipsec/list/ T: git git://git.kernel.org/pub/scm/linux/kernel/git/klassert/ipsec.git T: git git://git.kernel.org/pub/scm/linux/kernel/git/klassert/ipsec-next.git F: Documentation/networking/xfrm/ @@ -19800,6 +19802,7 @@ F: Documentation/networking/tls* F: include/net/tls.h F: include/uapi/linux/tls.h F: net/tls/ +F: tools/testing/selftests/drivers/net/hw/tls* F: tools/testing/selftests/net/tls.c NETWORKING [SOCKETS] @@ -24816,7 +24819,7 @@ F: drivers/iommu/s390-iommu.c S390 IUCV NETWORK LAYER M: Alexandra Winter <wintera@linux.ibm.com> -M: Thorsten Winkler <twinkler@linux.ibm.com> +M: Hidayath Khan <hidayath@linux.ibm.com> L: linux-s390@vger.kernel.org L: netdev@vger.kernel.org S: Supported @@ -25604,7 +25607,8 @@ F: drivers/slimbus/ F: include/linux/slimbus.h SFC NETWORK DRIVER -M: Edward Cree <ecree.xilinx@gmail.com> +M: Alex Austin <alex.austin@amd.com> +M: Andy Moreton <andy.moreton@amd.com> L: netdev@vger.kernel.org L: linux-net-drivers@amd.com S: Maintained @@ -26123,9 +26127,8 @@ S: Maintained F: drivers/net/ethernet/natsemi/sonic.* SONICS SILICON BACKPLANE DRIVER (SSB) -M: Michael Buesch <m@bues.ch> L: linux-wireless@vger.kernel.org -S: Maintained +S: Orphan F: drivers/ssb/ F: include/linux/ssb/ @@ -2,7 +2,7 @@ VERSION = 7 PATCHLEVEL = 4 SUBLEVEL = 0 -EXTRAVERSION = -rc2 +EXTRAVERSION = -rc3 NAME = Baby Opossum Posse # *DOCUMENTATION* diff --git a/arch/arm64/Kconfig b/arch/arm64/Kconfig index 1075bc661833..9b08b2457a55 100644 --- a/arch/arm64/Kconfig +++ b/arch/arm64/Kconfig @@ -1051,6 +1051,38 @@ config ARM64_WORKAROUND_BROKEN_AMU_CONSTCNT # making it unreliable. As a result, AMU users should treat it as # unavailable rather than relying on misleading counter values. +config ARM64_WORKAROUND_BROKEN_AMU_CORECNT + bool + # Targeting errata affecting AMEVCNTR00, the AMU core cycle counter. + # On affected CPUs the counter may continue incrementing while core + # remains in WFE with the clocks enabled. + # This may lead to readings of said counter being unreliable. + # How much though depends on the sampling intervals. + +config ARM64_ERRATUM_2738461 + bool "Cortex-A715/Cortex-A720: workaround for AMEVCNTR00 incrementing incorrectly" + depends on ARM64_AMU_EXTN + select ARM64_WORKAROUND_BROKEN_AMU_CORECNT + default y + help + This option adds the workaround for the following errata: + + * ARM Cortex-A715 erratum 2738462 + * ARM Cortex-A720 erratum 2738461 + + On affected cores the AMEVCNTR00 counter (AMU core frequency cycles + counter) may continue incrementing while the core remains in WFE + with the clocks being enabled. + This may result in inaccurate counter readings, with the magnitude + of the discrepancy depending on the sampling interval. + + With this workaround, reads of the affected counter return 0 in + the relevant paths. This causes users of the counter to treat it + as unavailable and is functionally equivalent to firmware disabling + the affected counter. + + If unsure, say Y. + config ARM64_ERRATUM_2457168 bool "Cortex-A510: 2457168: workaround for AMEVCNTR01 incrementing incorrectly" depends on ARM64_AMU_EXTN @@ -1086,14 +1118,20 @@ config ARM64_ERRATUM_2645198 If unsure, say Y. config ARM64_ERRATUM_3821522 - bool "Cortex-A725: 3821522: workaround for possible CNT_CYCLES increment error due to WFE/WFI" + bool "Cortex-*/Neoverse-*/C1-*: workaround for possible CNT_CYCLES increment error due to WFE/WFI" depends on ARM64_AMU_EXTN select ARM64_WORKAROUND_BROKEN_AMU_CONSTCNT default y help - This option adds the workaround for ARM Cortex-A725 erratum 3821522. + This option adds the workaround for the following errata: + + * ARM Cortex-A725 erratum 3821522 + * ARM Cortex-A720 erratum 4689339 + * ARM Cortex-A720AE erratum 4689340 + * ARM Neoverse N3 erratum 4689341 + * ARM C1-Pro erratum 4689344 - On affected A725 cores, the CNT_CYCLES event may incur a significant + On affected cores, the CNT_CYCLES event may incur a significant increment error when entering and subsequently exiting WFx. As a result, the CNT_CYCLES may diverge from the system counter frequency at which it is expected to increment. diff --git a/arch/arm64/include/asm/suspend.h b/arch/arm64/include/asm/suspend.h index a5abf0615594..8e9c97aab15a 100644 --- a/arch/arm64/include/asm/suspend.h +++ b/arch/arm64/include/asm/suspend.h @@ -2,7 +2,7 @@ #ifndef __ASM_SUSPEND_H #define __ASM_SUSPEND_H -#define NR_CTX_REGS 15 +#define NR_CTX_REGS 18 #define NR_CALLEE_SAVED_REGS 12 /* diff --git a/arch/arm64/kernel/cpu_errata.c b/arch/arm64/kernel/cpu_errata.c index 38abd123c740..ca31d33152e9 100644 --- a/arch/arm64/kernel/cpu_errata.c +++ b/arch/arm64/kernel/cpu_errata.c @@ -420,13 +420,33 @@ static const struct midr_range workaround_amu_constcnt_list[] = { MIDR_RANGE(MIDR_CORTEX_A510, 0, 0, 1, 1), #endif #ifdef CONFIG_ARM64_ERRATUM_3821522 + /* Cortex-A720 r0p0 - r0p2 */ + MIDR_RANGE(MIDR_CORTEX_A720, 0, 0, 0, 2), + /* Cortex-A720AE r0p0 - r0p1 */ + MIDR_RANGE(MIDR_CORTEX_A720AE, 0, 0, 0, 1), /* Cortex-A725 r0p0 - r0p2 */ MIDR_RANGE(MIDR_CORTEX_A725, 0, 0, 0, 2), + /* Neoverse N3 r0p0 - r0p1 */ + MIDR_RANGE(MIDR_NEOVERSE_N3, 0, 0, 0, 1), + /* C1-Pro r0p0 - r1p3 */ + MIDR_RANGE(MIDR_C1_PRO, 0, 0, 1, 3), #endif {} }; #endif /* CONFIG_ARM64_WORKAROUND_BROKEN_AMU_CONSTCNT */ +#ifdef CONFIG_ARM64_WORKAROUND_BROKEN_AMU_CORECNT +static const struct midr_range workaround_amu_corecnt_list[] = { +#ifdef CONFIG_ARM64_ERRATUM_2738461 + /* Cortex-A715 r0p0 - r1p3 */ + MIDR_RANGE(MIDR_CORTEX_A715, 0, 0, 1, 3), + /* Cortex-A720 r0p0 - r0p1 */ + MIDR_RANGE(MIDR_CORTEX_A720, 0, 0, 0, 1), +#endif + {} +}; +#endif /* CONFIG_ARM64_WORKAROUND_BROKEN_AMU_CORECNT */ + #ifdef CONFIG_CAVIUM_ERRATUM_23154 static const struct midr_range cavium_erratum_23154_cpus[] = { MIDR_ALL_VERSIONS(MIDR_THUNDERX), @@ -970,6 +990,14 @@ const struct arm64_cpu_capabilities arm64_errata[] = { CAP_MIDR_RANGE_LIST(workaround_amu_constcnt_list) }, #endif +#ifdef CONFIG_ARM64_WORKAROUND_BROKEN_AMU_CORECNT + { + .desc = "Broken AMU AMEVCNTR00 (core cycle counter)", + .capability = ARM64_WORKAROUND_BROKEN_AMU_CORECNT, + .type = ARM64_CPUCAP_WEAK_LOCAL_CPU_FEATURE, + CAP_MIDR_RANGE_LIST(workaround_amu_corecnt_list) + }, +#endif #ifdef CONFIG_ARM64_ERRATUM_2038923 { .desc = "ARM erratum 2038923", diff --git a/arch/arm64/kernel/cpufeature.c b/arch/arm64/kernel/cpufeature.c index 34c5c03c0c9b..c9c9a6889455 100644 --- a/arch/arm64/kernel/cpufeature.c +++ b/arch/arm64/kernel/cpufeature.c @@ -1938,7 +1938,8 @@ static void cpu_amu_enable(struct arm64_cpu_capabilities const *cap) cpumask_set_cpu(smp_processor_id(), &amu_cpus); /* 0 reference values signal broken/disabled counters */ - if (!this_cpu_has_cap(ARM64_WORKAROUND_BROKEN_AMU_CONSTCNT)) + if (!this_cpu_has_cap(ARM64_WORKAROUND_BROKEN_AMU_CONSTCNT) && + !this_cpu_has_cap(ARM64_WORKAROUND_BROKEN_AMU_CORECNT)) update_freq_counters_refs(); } } diff --git a/arch/arm64/kernel/kexec_image.c b/arch/arm64/kernel/kexec_image.c index 78b1f956d8d7..f4ad22447259 100644 --- a/arch/arm64/kernel/kexec_image.c +++ b/arch/arm64/kernel/kexec_image.c @@ -81,6 +81,13 @@ static void *image_load(struct kimage *image, kbuf.mem = KEXEC_BUF_MEM_UNKNOWN; kbuf.memsz = le64_to_cpu(h->image_size); text_offset = le64_to_cpu(h->text_offset); + /* + * A CMA segment is loaded and mapped through page_address(cma), which + * is the CMA base and cannot represent the text_offset adjustment + * below. Load images with a non-zero text_offset from normal memory. + */ + if (text_offset) + image->no_cma = true; kbuf.buf_align = MIN_KIMG_ALIGN; /* Adjust kernel segment with TEXT_OFFSET */ diff --git a/arch/arm64/kernel/ptrace.c b/arch/arm64/kernel/ptrace.c index 7405c76724bf..6a0b3a9b6125 100644 --- a/arch/arm64/kernel/ptrace.c +++ b/arch/arm64/kernel/ptrace.c @@ -573,8 +573,12 @@ static void update_syscall_orig_x0_after_ptrace(struct task_struct *target) if (regs->syscallno == NO_SYSCALL) return; - /* We should only be called when target is in a ptrace stop */ - if (WARN_ON_ONCE(!info)) + /* + * For exit-stops, info is always non-NULL, but that's not true for other + * stops such as non-seized group-stops. In those cases, just return early + * as there's no need to update orig_x0 anyway. + */ + if (!info) return; /* diff --git a/arch/arm64/kernel/signal.c b/arch/arm64/kernel/signal.c index 6a06a4e352b1..80398ac83c3b 100644 --- a/arch/arm64/kernel/signal.c +++ b/arch/arm64/kernel/signal.c @@ -741,36 +741,16 @@ static int preserve_gcs_context(struct gcs_context __user *ctx) static int restore_gcs_context(struct user_ctxs *user) { - u64 gcspr, enabled; + u64 gcspr; int err = 0; if (user->gcs_size != sizeof(*user->gcs)) return -EINVAL; __get_user_error(gcspr, &user->gcs->gcspr, err); - __get_user_error(enabled, &user->gcs->features_enabled, err); if (err) return err; - /* Don't allow unknown modes */ - if (enabled & ~PR_SHADOW_STACK_SUPPORTED_STATUS_MASK) - return -EINVAL; - - err = gcs_check_locked(current, enabled); - if (err != 0) - return err; - - /* Don't allow enabling */ - if (!task_gcs_el0_enabled(current) && - (enabled & PR_SHADOW_STACK_ENABLE)) - return -EINVAL; - - /* If we are disabling disable everything */ - if (!(enabled & PR_SHADOW_STACK_ENABLE)) - enabled = 0; - - current->thread.gcs_el0_mode = enabled; - /* * We let userspace set GCSPR_EL0 to anything here, we will * validate later in gcs_restore_signal(). diff --git a/arch/arm64/kernel/suspend.c b/arch/arm64/kernel/suspend.c index 3691c4c32904..4c281ae6babe 100644 --- a/arch/arm64/kernel/suspend.c +++ b/arch/arm64/kernel/suspend.c @@ -5,6 +5,7 @@ #include <linux/uaccess.h> #include <linux/pgtable.h> #include <linux/cpuidle.h> +#include <linux/sched.h> #include <asm/alternative.h> #include <asm/cacheflush.h> #include <asm/cpufeature.h> @@ -99,6 +100,7 @@ int cpu_suspend(unsigned long arg, int (*fn)(unsigned long)) int ret = 0; unsigned long flags; struct sleep_stack_data state; + bool idle = is_idle_task(current); /* * Some portions of CPU state (e.g. PSTATE.{PAN,DIT}) are initialized @@ -133,7 +135,8 @@ int cpu_suspend(unsigned long arg, int (*fn)(unsigned long)) */ pause_graph_tracing(); - ct_cpuidle_enter(); + if (idle) + ct_cpuidle_enter(); if (__cpu_suspend_enter(&state)) { /* Call the suspend finisher */ @@ -149,9 +152,11 @@ int cpu_suspend(unsigned long arg, int (*fn)(unsigned long)) if (!ret) ret = -EOPNOTSUPP; - ct_cpuidle_exit(); + if (idle) + ct_cpuidle_exit(); } else { - ct_cpuidle_exit(); + if (idle) + ct_cpuidle_exit(); __cpu_suspend_exit(); } diff --git a/arch/arm64/kernel/topology.c b/arch/arm64/kernel/topology.c index 44305b997a02..30a52659f15c 100644 --- a/arch/arm64/kernel/topology.c +++ b/arch/arm64/kernel/topology.c @@ -389,7 +389,8 @@ static void cpu_read_corecnt(void *val) * counter read is properly handled as an error case by the users of the * counter. */ - *(u64 *)val = read_corecnt(); + *(u64 *)val = this_cpu_has_cap(ARM64_WORKAROUND_BROKEN_AMU_CORECNT) ? + 0UL : read_corecnt(); } static void cpu_read_constcnt(void *val) diff --git a/arch/arm64/mm/hugetlbpage.c b/arch/arm64/mm/hugetlbpage.c index 8e799c1fe0aa..ff1f53e435e1 100644 --- a/arch/arm64/mm/hugetlbpage.c +++ b/arch/arm64/mm/hugetlbpage.c @@ -429,9 +429,24 @@ int huge_ptep_set_access_flags(struct vm_area_struct *vma, VM_WARN_ON(!pte_present(pte)); ncontig = num_contig_ptes(huge_page_size(hstate_vma(vma)), &pgsize); - if (!pte_cont(pte)) - return __ptep_set_access_flags_anysz(vma, addr, ptep, pte, - dirty, pgsize); + if (!pte_cont(pte)) { + if (__ptep_set_access_flags_anysz(vma, addr, ptep, pte, + dirty, pgsize)) + return 1; + + /* + * Another CPU may have made the entry writable without + * invalidating our stale read-only TLB entry. To avoid + * indefinitely faulting on this entry, flush it. + */ + if (dirty) + __flush_hugetlb_tlb_range(vma, addr, addr + pgsize, + pgsize, + TLBF_NOWALKCACHE | + TLBF_NOBROADCAST | + TLBF_NONOTIFY); + return 0; + } if (!__cont_access_flags_changed(ptep, pte, ncontig)) return 0; diff --git a/arch/arm64/mm/proc.S b/arch/arm64/mm/proc.S index b1516630904d..99aacf03367d 100644 --- a/arch/arm64/mm/proc.S +++ b/arch/arm64/mm/proc.S @@ -118,6 +118,16 @@ alternative_if ARM64_SME mrs_s x2, SYS_TPIDR2_EL0 str x2, [x0, #112] alternative_else_nop_endif +alternative_if ARM64_HAS_S1POE + mrs x2, REG_POR_EL0 + str x2, [x0, #120] +alternative_else_nop_endif +alternative_if ARM64_HAS_GCS + mrs x2, REG_GCSPR_EL0 + str x2, [x0, #128] + mrs x2, REG_GCSCRE0_EL1 + str x2, [x0, #136] +alternative_else_nop_endif ret SYM_FUNC_END(cpu_do_suspend) @@ -160,6 +170,16 @@ alternative_if ARM64_SME ldr x2, [x0, #112] msr_s SYS_TPIDR2_EL0, x2 alternative_else_nop_endif +alternative_if ARM64_HAS_S1POE + ldr x2, [x0, #120] + msr REG_POR_EL0, x2 +alternative_else_nop_endif +alternative_if ARM64_HAS_GCS + ldr x2, [x0, #128] + msr REG_GCSPR_EL0, x2 + ldr x2, [x0, #136] + msr REG_GCSCRE0_EL1, x2 +alternative_else_nop_endif msr sctlr_el1, x12 set_this_cpu_offset x13 diff --git a/arch/arm64/tools/cpucaps b/arch/arm64/tools/cpucaps index 20cc185649f9..3125695122a0 100644 --- a/arch/arm64/tools/cpucaps +++ b/arch/arm64/tools/cpucaps @@ -133,3 +133,4 @@ WORKAROUND_SPECULATIVE_AT WORKAROUND_SPECULATIVE_SSBS WORKAROUND_SPECULATIVE_UNPRIV_LOAD WORKAROUND_BROKEN_AMU_CONSTCNT +WORKAROUND_BROKEN_AMU_CORECNT diff --git a/arch/loongarch/include/asm/inst.h b/arch/loongarch/include/asm/inst.h index b55aae325300..e061f966f7d1 100644 --- a/arch/loongarch/include/asm/inst.h +++ b/arch/loongarch/include/asm/inst.h @@ -535,6 +535,8 @@ u32 larch_insn_gen_lu32id(enum loongarch_gpr rd, int imm); u32 larch_insn_gen_lu52id(enum loongarch_gpr rd, enum loongarch_gpr rj, int imm); u32 larch_insn_gen_beq(enum loongarch_gpr rd, enum loongarch_gpr rj, int imm); u32 larch_insn_gen_bne(enum loongarch_gpr rd, enum loongarch_gpr rj, int imm); +u32 larch_insn_gen_beqz(enum loongarch_gpr rj, int imm); +u32 larch_insn_gen_bnez(enum loongarch_gpr rj, int imm); u32 larch_insn_gen_jirl(enum loongarch_gpr rd, enum loongarch_gpr rj, int imm); static inline bool signed_imm_check(long val, unsigned int bit) @@ -592,6 +594,25 @@ DEF_EMIT_REG1I20_FORMAT(lu12iw, lu12iw_op) DEF_EMIT_REG1I20_FORMAT(lu32id, lu32id_op) DEF_EMIT_REG1I20_FORMAT(pcaddu18i, pcaddu18i_op) +#define DEF_EMIT_REG1I21_FORMAT(NAME, OP) \ +static inline void emit_##NAME(union loongarch_instruction *insn, \ + enum loongarch_gpr rj, int offset) \ +{ \ + unsigned int immediate_l, immediate_h; \ + \ + immediate_l = offset & 0xffff; \ + offset >>= 16; \ + immediate_h = offset & 0x1f; \ + \ + insn->reg1i21_format.opcode = OP; \ + insn->reg1i21_format.immediate_l = immediate_l; \ + insn->reg1i21_format.rj = rj; \ + insn->reg1i21_format.immediate_h = immediate_h; \ +} + +DEF_EMIT_REG1I21_FORMAT(beqz, beqz_op) +DEF_EMIT_REG1I21_FORMAT(bnez, bnez_op) + #define DEF_EMIT_REG2_FORMAT(NAME, OP) \ static inline void emit_##NAME(union loongarch_instruction *insn, \ enum loongarch_gpr rd, \ diff --git a/arch/loongarch/kernel/inst.c b/arch/loongarch/kernel/inst.c index 0b9228b7c13a..0d5076cfd7d1 100644 --- a/arch/loongarch/kernel/inst.c +++ b/arch/loongarch/kernel/inst.c @@ -428,6 +428,34 @@ u32 larch_insn_gen_bne(enum loongarch_gpr rd, enum loongarch_gpr rj, int imm) return insn.word; } +u32 larch_insn_gen_beqz(enum loongarch_gpr rj, int imm) +{ + union loongarch_instruction insn; + + if ((imm & 3) || imm < -SZ_4M || imm >= SZ_4M) { + pr_warn("The generated beqz instruction is out of range.\n"); + return INSN_BREAK; + } + + emit_beqz(&insn, rj, imm >> 2); + + return insn.word; +} + +u32 larch_insn_gen_bnez(enum loongarch_gpr rj, int imm) +{ + union loongarch_instruction insn; + + if ((imm & 3) || imm < -SZ_4M || imm >= SZ_4M) { + pr_warn("The generated bnez instruction is out of range.\n"); + return INSN_BREAK; + } + + emit_bnez(&insn, rj, imm >> 2); + + return insn.word; +} + u32 larch_insn_gen_jirl(enum loongarch_gpr rd, enum loongarch_gpr rj, int imm) { union loongarch_instruction insn; diff --git a/arch/loongarch/kernel/machine_kexec.c b/arch/loongarch/kernel/machine_kexec.c index 1883cae93bc3..19ccc91b6f2a 100644 --- a/arch/loongarch/kernel/machine_kexec.c +++ b/arch/loongarch/kernel/machine_kexec.c @@ -14,6 +14,7 @@ #include <linux/mm.h> #include <linux/of_fdt.h> #include <linux/reboot.h> +#include <linux/slab.h> #include <linux/sched.h> #include <linux/sched/task_stack.h> @@ -56,6 +57,7 @@ int machine_kexec_prepare(struct kimage *kimage) */ memcpy((void *)KEXEC_CMDLINE_ADDR, (void *)kimage->arch.cmdline_ptr, strlen((char *)kimage->arch.cmdline_ptr) + 1); + kfree((void *)kimage->arch.cmdline_ptr); kimage->arch.cmdline_ptr = (unsigned long)KEXEC_CMDLINE_ADDR; } else { /* Find the command line */ diff --git a/arch/loongarch/kernel/machine_kexec_file.c b/arch/loongarch/kernel/machine_kexec_file.c index 5412aa9f3568..0fe60907b97f 100644 --- a/arch/loongarch/kernel/machine_kexec_file.c +++ b/arch/loongarch/kernel/machine_kexec_file.c @@ -166,6 +166,10 @@ int load_other_segments(struct kimage *image, vfree(headers); goto out_err; } + + if (unlikely(image->elf_headers)) + vfree(image->elf_headers); + image->elf_headers = headers; image->elf_load_addr = kbuf.mem; image->elf_headers_sz = headers_sz; diff --git a/arch/loongarch/kvm/intc/dmsintc.c b/arch/loongarch/kvm/intc/dmsintc.c index ff327b4c05f7..c182185a3d59 100644 --- a/arch/loongarch/kvm/intc/dmsintc.c +++ b/arch/loongarch/kvm/intc/dmsintc.c @@ -146,6 +146,7 @@ static void kvm_dmsintc_destroy(struct kvm_device *dev) return; kfree(dev->kvm->arch.dmsintc); + dev->kvm->arch.dmsintc = NULL; kfree(dev); } diff --git a/arch/loongarch/kvm/intc/eiointc.c b/arch/loongarch/kvm/intc/eiointc.c index 80f78e07c74a..fe0a1918f26f 100644 --- a/arch/loongarch/kvm/intc/eiointc.c +++ b/arch/loongarch/kvm/intc/eiointc.c @@ -675,6 +675,7 @@ static void kvm_eiointc_destroy(struct kvm_device *dev) kvm = dev->kvm; eiointc = kvm->arch.eiointc; + kvm->arch.eiointc = NULL; mutex_lock(&kvm->slots_lock); kvm_io_bus_unregister_dev(kvm, KVM_IOCSR_BUS, &eiointc->device); kvm_io_bus_unregister_dev(kvm, KVM_IOCSR_BUS, &eiointc->device_vext); diff --git a/arch/loongarch/kvm/intc/ipi.c b/arch/loongarch/kvm/intc/ipi.c index 80faa770c0cd..7a2dd72a4952 100644 --- a/arch/loongarch/kvm/intc/ipi.c +++ b/arch/loongarch/kvm/intc/ipi.c @@ -441,6 +441,7 @@ static void kvm_ipi_destroy(struct kvm_device *dev) kvm = dev->kvm; ipi = kvm->arch.ipi; + kvm->arch.ipi = NULL; mutex_lock(&kvm->slots_lock); kvm_io_bus_unregister_dev(kvm, KVM_IOCSR_BUS, &ipi->device); mutex_unlock(&kvm->slots_lock); diff --git a/arch/loongarch/kvm/intc/pch_pic.c b/arch/loongarch/kvm/intc/pch_pic.c index 220fc23ffe8c..044a219035e8 100644 --- a/arch/loongarch/kvm/intc/pch_pic.c +++ b/arch/loongarch/kvm/intc/pch_pic.c @@ -281,16 +281,25 @@ static int kvm_pch_pic_init(struct kvm_device *dev, u64 addr) struct kvm_io_device *device; struct loongarch_pch_pic *s = dev->kvm->arch.pch_pic; - s->pch_pic_base = addr; device = &s->device; + mutex_lock(&kvm->slots_lock); + if (s->device.ops) { + ret = -EEXIST; + goto out; + } + s->pch_pic_base = addr; /* init device by pch pic writing and reading ops */ kvm_iodevice_init(device, &kvm_pch_pic_ops); - mutex_lock(&kvm->slots_lock); /* register pch pic device */ ret = kvm_io_bus_register_dev(kvm, KVM_MMIO_BUS, addr, PCH_PIC_SIZE, device); + if (ret) { + s->pch_pic_base = 0; + s->device.ops = NULL; + } +out: mutex_unlock(&kvm->slots_lock); - return (ret < 0) ? -EFAULT : 0; + return ret; } /* used by user space to get or set pch pic registers */ @@ -444,7 +453,7 @@ static int kvm_pch_pic_create(struct kvm_device *dev, u32 type) ret = kvm_setup_default_irq_routing(kvm); if (ret) - return -ENOMEM; + return ret; s = kzalloc_obj(struct loongarch_pch_pic); if (!s) @@ -483,6 +492,7 @@ static void kvm_pch_pic_destroy(struct kvm_device *dev) kvm = dev->kvm; s = kvm->arch.pch_pic; + kvm->arch.pch_pic = NULL; /* unregister pch pic device and free it's memory */ mutex_lock(&kvm->slots_lock); kvm_io_bus_unregister_dev(kvm, KVM_MMIO_BUS, &s->device); diff --git a/arch/loongarch/net/bpf_jit.c b/arch/loongarch/net/bpf_jit.c index 042930c7ddb2..15af1abb5cb6 100644 --- a/arch/loongarch/net/bpf_jit.c +++ b/arch/loongarch/net/bpf_jit.c @@ -1819,7 +1819,7 @@ static int invoke_bpf_prog(struct jit_ctx *ctx, struct bpf_tramp_image *im, /* update branch with beqz */ if (ctx->image) { int offset = (void *)(&ctx->image[ctx->idx]) - (void *)branch; - *branch = larch_insn_gen_beq(LOONGARCH_GPR_A0, LOONGARCH_GPR_ZERO, offset); + *branch = larch_insn_gen_beqz(LOONGARCH_GPR_A0, offset); } /* arg1: prog */ @@ -2132,9 +2132,10 @@ static int __arch_prepare_bpf_trampoline(struct jit_ctx *ctx, struct bpf_tramp_i emit_insn(ctx, std, regmap[BPF_REG_0], LOONGARCH_GPR_FP, -(retval_off - 8)); } + /* update branches with bnez */ for (i = 0; ctx->image && i < fmod_ret->nr_nodes; i++) { int offset = (void *)(&ctx->image[ctx->idx]) - (void *)branches[i]; - *branches[i] = larch_insn_gen_bne(LOONGARCH_GPR_T1, LOONGARCH_GPR_ZERO, offset); + *branches[i] = larch_insn_gen_bnez(LOONGARCH_GPR_T1, offset); } /* Set "is_return" flag for fsession */ @@ -2489,7 +2490,16 @@ bool bpf_jit_bypass_spec_v4(void) bool bpf_jit_supports_arena(void) { - return true; + /* + * The arena range tree uses kmalloc_nolock(), which requires + * 128-bit atomic cmpxchg; this is provided by not only hardware + * SCQ extension but also assembler support on LoongArch. + */ +#ifdef system_has_cmpxchg128 + return system_has_cmpxchg128(); +#else + return false; +#endif } bool bpf_jit_supports_fsession(void) diff --git a/arch/loongarch/power/hibernate.c b/arch/loongarch/power/hibernate.c index 817270410ef9..3de38ffb11c3 100644 --- a/arch/loongarch/power/hibernate.c +++ b/arch/loongarch/power/hibernate.c @@ -59,6 +59,12 @@ extern int swsusp_asm_resume(void); int swsusp_arch_resume(void) { +#ifdef CONFIG_KFENCE + struct pbe *pbe; + + for (pbe = restore_pblist; pbe; pbe = pbe->next) + pbe->orig_address = __va(virt_to_phys(pbe->orig_address)); +#endif /* Avoid TLB mismatch during and after kernel resume */ local_flush_tlb_all(); return swsusp_asm_resume(); diff --git a/arch/powerpc/kernel/eeh.c b/arch/powerpc/kernel/eeh.c index bb836f02101c..2d7898ef6b8c 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 f930e3395a7f..61152deffc55 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 7a25eaa59e62..58824f5f4c80 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 582ee3fd71c1..44f178e07531 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_64_mmu_hv.c b/arch/powerpc/kvm/book3s_64_mmu_hv.c index 00b8a3f855f4..97740173974c 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 22283d46e8fe..bafe9546087b 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; @@ -4984,7 +4986,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 { /* diff --git a/arch/powerpc/kvm/book3s_hv_nested.c b/arch/powerpc/kvm/book3s_hv_nested.c index a6ff42d7666c..e893fdd24f0a 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_xive.c b/arch/powerpc/kvm/book3s_xive.c index d348365df72d..9d2039ee37b2 100644 --- a/arch/powerpc/kvm/book3s_xive.c +++ b/arch/powerpc/kvm/book3s_xive.c @@ -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 @@ bail: return r; } - vcpu->arch.irq_type = KVMPPC_IRQ_XICS; return 0; } diff --git a/arch/powerpc/perf/vpa-dtl.c b/arch/powerpc/perf/vpa-dtl.c index 3e3d65b6c796..3d34417e6aae 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 6f6743b8e48d..01bcfa258625 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 2df955274652..fb53782da7ec 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 45792ecd5dfd..7a961f2a228f 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/x86/events/amd/uncore.c b/arch/x86/events/amd/uncore.c index 7aa5a5b652a2..c307323f6390 100644 --- a/arch/x86/events/amd/uncore.c +++ b/arch/x86/events/amd/uncore.c @@ -595,7 +595,7 @@ static void amd_uncore_ctx_move(struct amd_uncore *uncore, unsigned int cpu) for (i = 0; i < uncore->num_pmus; i++) { pmu = &uncore->pmus[i]; curr = *per_cpu_ptr(pmu->ctx, cpu); - if (!curr) + if (!curr || curr->cpu != cpu) continue; /* Migrate to a shared sibling if possible */ diff --git a/arch/x86/include/asm/cpufeatures.h b/arch/x86/include/asm/cpufeatures.h index 61930f0d4578..303467a498b8 100644 --- a/arch/x86/include/asm/cpufeatures.h +++ b/arch/x86/include/asm/cpufeatures.h @@ -432,6 +432,7 @@ #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 */ +#define X86_FEATURE_TSA_FILL_NO (17*32+ 5) /* AMD CPU not vulnerable to TSA-FILL */ /* 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 */ diff --git a/arch/x86/kernel/cpu/amd.c b/arch/x86/kernel/cpu/amd.c index 3972966cb023..365bcbf56c76 100644 --- a/arch/x86/kernel/cpu/amd.c +++ b/arch/x86/kernel/cpu/amd.c @@ -416,9 +416,14 @@ static void tsa_init(struct cpuinfo_x86 *c) else pr_debug("%s: current revision: 0x%x\n", __func__, c->microcode); } else { - setup_force_cpu_cap(X86_FEATURE_TSA_SQ_NO); - setup_force_cpu_cap(X86_FEATURE_TSA_L1_NO); + if (!cpu_has(c, X86_FEATURE_ZEN5)) { + setup_force_cpu_cap(X86_FEATURE_TSA_SQ_NO); + setup_force_cpu_cap(X86_FEATURE_TSA_L1_NO); + } } + + if (!cpu_has(c, X86_FEATURE_ZEN5)) + setup_force_cpu_cap(X86_FEATURE_TSA_FILL_NO); } static void bsp_init_amd(struct cpuinfo_x86 *c) @@ -1362,7 +1367,8 @@ static __init int print_s5_reset_status_mmio(void) u32 value; int i; - if (!cpu_feature_enabled(X86_FEATURE_ZEN)) + if (!cpu_feature_enabled(X86_FEATURE_ZEN) || + cpu_feature_enabled(X86_FEATURE_HYPERVISOR)) return 0; addr = ioremap(FCH_PM_BASE + FCH_PM_S5_RESET_STATUS, sizeof(value)); diff --git a/arch/x86/kernel/cpu/common.c b/arch/x86/kernel/cpu/common.c index 9bd50c68cd7e..7e4eb704fe70 100644 --- a/arch/x86/kernel/cpu/common.c +++ b/arch/x86/kernel/cpu/common.c @@ -1340,7 +1340,7 @@ static const struct x86_cpu_id cpu_vuln_blacklist[] __initconst = { VULNBL_AMD(0x17, RETBLEED | SMT_RSB | SRSO | VMSCAPE), VULNBL_HYGON(0x18, RETBLEED | SMT_RSB | SRSO | VMSCAPE), VULNBL_AMD(0x19, SRSO | TSA | VMSCAPE), - VULNBL_AMD(0x1a, SRSO | VMSCAPE), + VULNBL_AMD(0x1a, SRSO | TSA | VMSCAPE), {} }; @@ -1605,7 +1605,8 @@ static void __init cpu_set_bug_bits(struct cpuinfo_x86 *c) if (c->x86_vendor == X86_VENDOR_AMD) { if (!cpu_has(c, X86_FEATURE_TSA_SQ_NO) || - !cpu_has(c, X86_FEATURE_TSA_L1_NO)) { + !cpu_has(c, X86_FEATURE_TSA_L1_NO) || + !cpu_has(c, X86_FEATURE_TSA_FILL_NO)) { if (cpu_matches(cpu_vuln_blacklist, TSA) || /* Enable bug on Zen guests to allow for live migration. */ (cpu_has(c, X86_FEATURE_HYPERVISOR) && cpu_has(c, X86_FEATURE_ZEN))) diff --git a/arch/x86/kernel/cpu/scattered.c b/arch/x86/kernel/cpu/scattered.c index d867ab90d42a..c990245d29d6 100644 --- a/arch/x86/kernel/cpu/scattered.c +++ b/arch/x86/kernel/cpu/scattered.c @@ -65,6 +65,7 @@ static const struct cpuid_bit cpuid_bits[] = { { X86_FEATURE_AMD_WORKLOAD_CLASS, CPUID_EAX, 22, 0x80000021, 0 }, { X86_FEATURE_TSA_SQ_NO, CPUID_ECX, 1, 0x80000021, 0 }, { X86_FEATURE_TSA_L1_NO, CPUID_ECX, 2, 0x80000021, 0 }, + { X86_FEATURE_TSA_FILL_NO, CPUID_ECX, 7, 0x80000021, 0 }, { X86_FEATURE_BTB_CTX_ISOLATION, CPUID_ECX, 8, 0x80000021, 0 }, { X86_FEATURE_PERFMON_V2, CPUID_EAX, 0, 0x80000022, 0 }, { X86_FEATURE_AMD_LBR_V2, CPUID_EAX, 1, 0x80000022, 0 }, diff --git a/arch/x86/kernel/ldt.c b/arch/x86/kernel/ldt.c index 4fa7a86adece..c4bbb4176591 100644 --- a/arch/x86/kernel/ldt.c +++ b/arch/x86/kernel/ldt.c @@ -43,7 +43,7 @@ void load_mm_ldt(struct mm_struct *mm) { struct ldt_struct *ldt; - /* READ_ONCE synchronizes with smp_store_release */ + /* Pairs with WRITE_ONCE() in install_ldt() */ ldt = READ_ONCE(mm->context.ldt); /* @@ -422,8 +422,14 @@ static void install_ldt(struct mm_struct *mm, struct ldt_struct *ldt) { mutex_lock(&mm->context.lock); - /* Synchronizes with READ_ONCE in load_mm_ldt. */ - smp_store_release(&mm->context.ldt, ldt); + /* + * Ensure that new mm user CPUs either see the new LDT value + * or get an IPI. Make the store visible before reading + * mm_cpumask(). New mm users make their mm_cpumask() writes + * visible before reading mm->context.ldt. + */ + WRITE_ONCE(mm->context.ldt, ldt); + smp_mb(); /* Activate the LDT for all CPUs using currents mm. */ on_each_cpu_mask(mm_cpumask(mm), flush_ldt, mm, true); diff --git a/arch/x86/kvm/cpuid.c b/arch/x86/kvm/cpuid.c index adafd6fa2c54..e267454b6c3d 100644 --- a/arch/x86/kvm/cpuid.c +++ b/arch/x86/kvm/cpuid.c @@ -1254,6 +1254,7 @@ void kvm_initialize_cpu_caps(void) kvm_cpu_cap_init(CPUID_8000_0021_ECX, SYNTHESIZED_F(TSA_SQ_NO), SYNTHESIZED_F(TSA_L1_NO), + SYNTHESIZED_F(TSA_FILL_NO), ); kvm_cpu_cap_init(CPUID_8000_0022_EAX, diff --git a/arch/x86/kvm/reverse_cpuid.h b/arch/x86/kvm/reverse_cpuid.h index 89345af0f7ad..b7a559962626 100644 --- a/arch/x86/kvm/reverse_cpuid.h +++ b/arch/x86/kvm/reverse_cpuid.h @@ -77,6 +77,7 @@ /* CPUID level 0x80000021 (ECX) */ #define KVM_X86_FEATURE_TSA_SQ_NO KVM_X86_FEATURE(CPUID_8000_0021_ECX, 1) #define KVM_X86_FEATURE_TSA_L1_NO KVM_X86_FEATURE(CPUID_8000_0021_ECX, 2) +#define KVM_X86_FEATURE_TSA_FILL_NO KVM_X86_FEATURE(CPUID_8000_0021_ECX, 7) struct cpuid_reg { u32 function; @@ -153,6 +154,7 @@ static __always_inline u32 __feature_translate(int x86_feature) KVM_X86_TRANSLATE_FEATURE(TSA_SQ_NO); KVM_X86_TRANSLATE_FEATURE(TSA_L1_NO); KVM_X86_TRANSLATE_FEATURE(MSR_IMM); + KVM_X86_TRANSLATE_FEATURE(TSA_FILL_NO); default: return x86_feature; } diff --git a/arch/x86/video/video-common.c b/arch/x86/video/video-common.c index 8ed82fff7638..b8f83346dfe8 100644 --- a/arch/x86/video/video-common.c +++ b/arch/x86/video/video-common.c @@ -45,7 +45,7 @@ bool video_is_primary_device(struct device *dev) #ifdef CONFIG_SCREEN_INFO numres = screen_info_resources(si, res, ARRAY_SIZE(res)); - if (numres > 0) { + if (numres > 0 && __screen_info_has_lfb(screen_info_video_type(si))) { for (i = 0; i < numres; ++i) { if (!(res[i].flags & IORESOURCE_MEM)) continue; diff --git a/block/fops.c b/block/fops.c index a0ccadaa9c79..084379778413 100644 --- a/block/fops.c +++ b/block/fops.c @@ -467,10 +467,6 @@ static int blkdev_iomap_begin(struct inode *inode, loff_t offset, loff_t length, static DEFINE_IOMAP_ITER_NEXT(blkdev_iomap_next, blkdev_iomap_begin); -static const struct iomap_ops blkdev_iomap_ops = { - .iomap_next = blkdev_iomap_next, -}; - #ifdef CONFIG_BUFFER_HEAD static int blkdev_get_block(struct inode *inode, sector_t iblock, struct buffer_head *bh, int create) @@ -524,13 +520,13 @@ const struct address_space_operations def_blk_aops = { #else /* CONFIG_BUFFER_HEAD */ static int blkdev_read_folio(struct file *file, struct folio *folio) { - iomap_bio_read_folio(folio, &blkdev_iomap_ops); + iomap_bio_read_folio(folio, blkdev_iomap_next); return 0; } static void blkdev_readahead(struct readahead_control *rac) { - iomap_bio_readahead(rac, &blkdev_iomap_ops); + iomap_bio_readahead(rac, blkdev_iomap_next); } static ssize_t blkdev_writeback_range(struct iomap_writepage_ctx *wpc, @@ -736,7 +732,7 @@ static ssize_t blkdev_buffered_write(struct kiocb *iocb, struct iov_iter *from) * i_blkbits/folio order and truncating the page cache. */ inode_lock_shared(inode); - ret = iomap_file_buffered_write(iocb, from, &blkdev_iomap_ops, NULL, + ret = iomap_file_buffered_write(iocb, from, blkdev_iomap_next, NULL, NULL); inode_unlock_shared(inode); return ret; diff --git a/crypto/essiv.c b/crypto/essiv.c index a47a3eab6935..3505b2769d93 100644 --- a/crypto/essiv.c +++ b/crypto/essiv.c @@ -250,7 +250,7 @@ static int essiv_aead_crypt(struct aead_request *req, bool enc) err = enc ? crypto_aead_encrypt(subreq) : crypto_aead_decrypt(subreq); - if (rctx->assoc && err != -EINPROGRESS && err != -EBUSY) + if (err != -EINPROGRESS && err != -EBUSY) kfree(rctx->assoc); return err; } diff --git a/drivers/acpi/apei/ghes.c b/drivers/acpi/apei/ghes.c index 663dc2e601cf..5d888c82efea 100644 --- a/drivers/acpi/apei/ghes.c +++ b/drivers/acpi/apei/ghes.c @@ -899,7 +899,7 @@ EXPORT_SYMBOL_NS_GPL(cxl_cper_kfifo_get, "CXL"); static void ghes_log_hwerr(int sev, guid_t *sec_type) { - if (sev != CPER_SEV_RECOVERABLE) + if (sev != GHES_SEV_RECOVERABLE) return; if (guid_equal(sec_type, &CPER_SEC_PROC_ARM) || diff --git a/drivers/acpi/ec.c b/drivers/acpi/ec.c index a89f10256dbb..db24a9a252a8 100644 --- a/drivers/acpi/ec.c +++ b/drivers/acpi/ec.c @@ -2167,19 +2167,19 @@ static bool acpi_ec_work_in_progress(struct acpi_ec *ec) return ec->events_in_progress + ec->queries_in_progress > 0; } -bool acpi_ec_dispatch_gpe(void) +int acpi_ec_dispatch_gpe(void) { bool work_in_progress = false; if (!first_ec) - return acpi_any_gpe_status_set(U32_MAX); + return -ENODEV; /* * Report wakeup if the status bit is set for any enabled GPE other * than the EC one. */ if (acpi_any_gpe_status_set(first_ec->gpe)) - return true; + return 1; /* * Cancel the SCI wakeup and process all pending events in case there @@ -2207,7 +2207,7 @@ bool acpi_ec_dispatch_gpe(void) spin_unlock_irq(&first_ec->lock); if (!work_in_progress) - return false; + return 0; pm_pr_dbg("ACPI EC GPE dispatched\n"); @@ -2224,7 +2224,7 @@ bool acpi_ec_dispatch_gpe(void) spin_unlock_irq(&first_ec->lock); } while (work_in_progress && !pm_wakeup_pending()); - return false; + return 0; } #endif /* CONFIG_PM_SLEEP */ diff --git a/drivers/acpi/internal.h b/drivers/acpi/internal.h index 011da4ed6a80..472c383eaaec 100644 --- a/drivers/acpi/internal.h +++ b/drivers/acpi/internal.h @@ -237,7 +237,7 @@ void acpi_ec_register_opregions(struct acpi_device *adev); #ifdef CONFIG_PM_SLEEP void acpi_ec_flush_work(void); -bool acpi_ec_dispatch_gpe(void); +int acpi_ec_dispatch_gpe(void); #endif #else @@ -257,9 +257,9 @@ static inline void acpi_ec_remove_query_handler(struct acpi_ec *ec, u8 query_bit static inline void acpi_ec_register_opregions(struct acpi_device *adev) {} static inline void acpi_ec_flush_work(void) {} -static inline bool acpi_ec_dispatch_gpe(void) +static inline int acpi_ec_dispatch_gpe(void) { - return false; + return -EOPNOTSUPP; } #endif diff --git a/drivers/acpi/loongarch/iovt.c b/drivers/acpi/loongarch/iovt.c index 87cee4f0fc80..1e97669eaeea 100644 --- a/drivers/acpi/loongarch/iovt.c +++ b/drivers/acpi/loongarch/iovt.c @@ -18,9 +18,20 @@ struct iovt_fwnode { struct list_head ep_list; }; +static bool checksum_valid; static LIST_HEAD(iovt_fwnode_list); static DEFINE_SPINLOCK(iovt_fwnode_lock); +static u8 acpi_iovt_checksum(u8 *buffer, u32 len) +{ + u8 sum = 0, *end = buffer + len; + + while (buffer < end) + sum += *buffer++; + + return sum; +} + #ifdef CONFIG_PCI static void __init iovt_enable_acs(struct acpi_iovt_iommu *iommu) { @@ -73,10 +84,43 @@ static int __init iovt_get_pci_iommu_fwnode(struct iovt_fwnode *np, u16 segment, return 0; } +static int __init iovt_validate_entries(struct acpi_iovt_iommu *iommu) +{ + int i, done = 1; + struct acpi_iovt_device_entry *ep; + + ep = ACPI_ADD_PTR(struct acpi_iovt_device_entry, iommu, iommu->device_entry_offset); + for (i = 0; i < iommu->device_entry_num; i++) { + switch (ep->type) { + case ACPI_IOVT_DEVICE_ENTRY_START: + if (!done) + return -EINVAL; + + done = 0; + break; + case ACPI_IOVT_DEVICE_ENTRY_END: + if (done) + return -EINVAL; + + done = 1; + break; + case ACPI_IOVT_DEVICE_ENTRY_SINGLE: + default: /* Reserved for future */ + if (!done) + return -EINVAL; + + done = 1; + break; + } + ep = ACPI_ADD_PTR(struct acpi_iovt_device_entry, ep, ep->length); + } + + return done ? 0 : -EINVAL; +} + static int __init iovt_add_iommu(struct acpi_iovt_iommu *iommu) { int i, ret; - bool is_start = false; struct iovt_fwnode *np; struct iovt_device_entry *entry; struct acpi_iovt_device_entry *ep; @@ -110,23 +154,24 @@ static int __init iovt_add_iommu(struct acpi_iovt_iommu *iommu) if (np->flag & ACPI_IOVT_IOMMU_MAGAGE_BY_SEGMENT) goto skip; + if (iovt_validate_entries(iommu) < 0) { + kfree(np); + return -EINVAL; + } + INIT_LIST_HEAD(&np->ep_list); ep = ACPI_ADD_PTR(struct acpi_iovt_device_entry, iommu, iommu->device_entry_offset); for (i = 0; i < iommu->device_entry_num; i++) { switch (ep->type) { case ACPI_IOVT_DEVICE_ENTRY_START: - is_start = true; - entry->start_devid = ep->device_id; - break; - case ACPI_IOVT_DEVICE_ENTRY_END: - if (!is_start) - break; - entry = kzalloc_obj(struct iovt_device_entry, GFP_ATOMIC); if (!entry) return -ENOMEM; - is_start = false; + entry->start_devid = ep->device_id; + break; + case ACPI_IOVT_DEVICE_ENTRY_END: + /* START & END are paired */ entry->end_devid = ep->device_id; list_add_tail(&entry->list, &np->ep_list); break; @@ -135,7 +180,6 @@ static int __init iovt_add_iommu(struct acpi_iovt_iommu *iommu) if (!entry) return -ENOMEM; - is_start = false; entry->start_devid = ep->device_id; entry->end_devid = ep->device_id; list_add_tail(&entry->list, &np->ep_list); @@ -184,7 +228,14 @@ void __init acpi_iovt_init(void) return; } - iovt = (struct acpi_table_iovt *)&hdr; + if (acpi_iovt_checksum((unsigned char *)hdr, hdr->length)) { + pr_err("IOVT invalid checksum\n"); + acpi_put_table(hdr); + return; + } + + checksum_valid = true; + iovt = (struct acpi_table_iovt *)hdr; iommu = ACPI_ADD_PTR(struct acpi_iovt_iommu, iovt, iovt->iommu_offset); for (i = 0; i < iovt->iommu_count; i++) { iovt_enable_acs(iommu); @@ -199,6 +250,9 @@ void __init acpi_iovt_late_init(void) acpi_status status; struct acpi_table_header *hdr; + if (!checksum_valid) + return; + status = acpi_get_table(ACPI_SIG_IOVT, 0, &hdr); if (ACPI_FAILURE(status)) { if (status != AE_NOT_FOUND) diff --git a/drivers/acpi/scan.c b/drivers/acpi/scan.c index 96b8b0dfe339..9218264f8da1 100644 --- a/drivers/acpi/scan.c +++ b/drivers/acpi/scan.c @@ -115,11 +115,7 @@ bool acpi_scan_is_offline(struct acpi_device *adev, bool uevent) bool offline = true; char *envp[] = { "EVENT=offline", NULL }; - /* - * acpi_container_offline() calls this for all of the container's - * children under the container's physical_node_lock lock. - */ - mutex_lock_nested(&adev->physical_node_lock, SINGLE_DEPTH_NESTING); + mutex_lock(&adev->physical_node_lock); list_for_each_entry(pn, &adev->physical_node_list, node) if (device_supports_offline(pn->dev) && !dev_offline(pn->dev)) { @@ -134,6 +130,59 @@ bool acpi_scan_is_offline(struct acpi_device *adev, bool uevent) return offline; } +static struct acpi_device_physical_node * +acpi_find_physical_node(struct acpi_device *adev, struct device *dev) +{ + struct acpi_device_physical_node *pn; + + lockdep_assert_held(&adev->physical_node_lock); + + list_for_each_entry(pn, &adev->physical_node_list, node) + if (pn->dev == dev) + return pn; + + return NULL; +} + +static struct device *acpi_next_offline_pending(struct acpi_device *adev) +{ + struct acpi_device_physical_node *pn; + + lockdep_assert_held(&adev->physical_node_lock); + + /* + * Find the first physical node that is still to be offlined, clear its + * offline_pending flag and return its device with a reference held. + */ + list_for_each_entry(pn, &adev->physical_node_list, node) + if (pn->offline_pending) { + pn->offline_pending = false; + return get_device(pn->dev); + } + + return NULL; +} + +static struct device *acpi_next_put_online(struct acpi_device *adev) +{ + struct acpi_device_physical_node *pn; + + lockdep_assert_held(&adev->physical_node_lock); + + /* + * Find the first physical node that has been offlined by + * acpi_bus_offline(), clear its put_online flag and return its device + * with a reference held. + */ + list_for_each_entry(pn, &adev->physical_node_list, node) + if (pn->put_online) { + pn->put_online = false; + return get_device(pn->dev); + } + + return NULL; +} + static acpi_status acpi_bus_offline(acpi_handle handle, u32 lvl, void *data, void **ret_p) { @@ -141,6 +190,7 @@ static acpi_status acpi_bus_offline(acpi_handle handle, u32 lvl, void *data, struct acpi_device_physical_node *pn; bool second_pass = (bool)data; acpi_status status = AE_OK; + struct device *dev; if (!device) return AE_OK; @@ -153,25 +203,43 @@ static acpi_status acpi_bus_offline(acpi_handle handle, u32 lvl, void *data, mutex_lock(&device->physical_node_lock); list_for_each_entry(pn, &device->physical_node_list, node) { - int ret; - if (second_pass) { /* Skip devices offlined by the first pass. */ - if (pn->put_online) - continue; + pn->offline_pending = !pn->put_online; } else { + pn->offline_pending = true; pn->put_online = false; } - ret = device_offline(pn->dev); + } + + /* + * Drop physical_node_lock around device_offline(), because the latter + * acquires locks, like the CPU hotplug ones, that must not nest under + * it. + */ + while ((dev = acpi_next_offline_pending(device))) { + int ret; + + mutex_unlock(&device->physical_node_lock); + ret = device_offline(dev); + mutex_lock(&device->physical_node_lock); + if (ret >= 0) { - pn->put_online = !ret; + /* The device may have been unbound in the meantime. */ + pn = acpi_find_physical_node(device, dev); + if (pn) + pn->put_online = !ret; } else { - *ret_p = pn->dev; + *ret_p = &device->dev; if (second_pass) { + dev_warn(dev, "Offline failed.\n"); status = AE_ERROR; - break; } } + + put_device(dev); + if (ACPI_FAILURE(status)) + break; } mutex_unlock(&device->physical_node_lock); @@ -183,18 +251,19 @@ static acpi_status acpi_bus_online(acpi_handle handle, u32 lvl, void *data, void **ret_p) { struct acpi_device *device = acpi_fetch_acpi_dev(handle); - struct acpi_device_physical_node *pn; + struct device *dev; if (!device) return AE_OK; mutex_lock(&device->physical_node_lock); - list_for_each_entry(pn, &device->physical_node_list, node) - if (pn->put_online) { - device_online(pn->dev); - pn->put_online = false; - } + while ((dev = acpi_next_put_online(device))) { + mutex_unlock(&device->physical_node_lock); + device_online(dev); + mutex_lock(&device->physical_node_lock); + put_device(dev); + } mutex_unlock(&device->physical_node_lock); @@ -236,7 +305,6 @@ static int acpi_scan_try_to_offline(struct acpi_device *device) (void **)&errdev); if (errdev) { - dev_warn(errdev, "Offline failed.\n"); acpi_bus_online(handle, 0, NULL, NULL); acpi_walk_namespace(ACPI_TYPE_ANY, handle, ACPI_UINT32_MAX, acpi_bus_online, diff --git a/drivers/acpi/sleep.c b/drivers/acpi/sleep.c index a94bac4422d4..641056e0252b 100644 --- a/drivers/acpi/sleep.c +++ b/drivers/acpi/sleep.c @@ -760,6 +760,8 @@ bool acpi_s2idle_wake(void) return pm_wakeup_pending(); while (pm_wakeup_pending()) { + int ret; + /* * If IRQD_WAKEUP_ARMED is set for the SCI at this point, the * SCI has not triggered while suspended, so bail out (the @@ -788,11 +790,16 @@ bool acpi_s2idle_wake(void) /* * Check non-EC GPE wakeups and if there are none, cancel the - * SCI-related wakeup and dispatch the EC GPE. + * SCI-related wakeup and dispatch the EC GPE. If there is no + * EC to consult, check the GPEs armed for wakeup via _Ixx + * methods instead. */ - if (acpi_ec_dispatch_gpe()) { + ret = acpi_ec_dispatch_gpe(); + if (ret > 0) { pm_pr_dbg("ACPI non-EC GPE wakeup\n"); return true; + } else if (ret < 0 && acpi_x86_s2idle_check_ixx_gpes()) { + return true; } acpi_os_wait_events_complete(); diff --git a/drivers/acpi/sleep.h b/drivers/acpi/sleep.h index 9c3cb109c5d2..955e9c22bf0d 100644 --- a/drivers/acpi/sleep.h +++ b/drivers/acpi/sleep.h @@ -20,6 +20,14 @@ extern int acpi_s2idle_prepare(void); extern bool acpi_s2idle_wake(void); extern void acpi_s2idle_restore(void); extern void acpi_s2idle_end(void); +#if defined(CONFIG_X86) && defined(CONFIG_SUSPEND) +extern bool acpi_x86_s2idle_check_ixx_gpes(void); +#else +static inline bool acpi_x86_s2idle_check_ixx_gpes(void) +{ + return acpi_any_gpe_status_set(U32_MAX); +} +#endif extern void acpi_s2idle_setup(void); diff --git a/drivers/acpi/x86/s2idle.c b/drivers/acpi/x86/s2idle.c index c278ea14c0b3..b79bf0fa9a7f 100644 --- a/drivers/acpi/x86/s2idle.c +++ b/drivers/acpi/x86/s2idle.c @@ -24,6 +24,13 @@ #ifdef CONFIG_SUSPEND +/* + * First GPE armed for wake via an _Ixx method, U32_MAX if none. On + * platforms without an ACPI-enumerated EC, this GPE plays the role of + * the EC GPE in acpi_ec_dispatch_gpe(). + */ +static u32 acpi_s2idle_ixx_gpe = U32_MAX; + static void acpi_setup_ixx_gpes(void) { acpi_handle gpe_root; @@ -47,11 +54,65 @@ static void acpi_setup_ixx_gpes(void) acpi_mark_gpe_for_wake(NULL, i); acpi_set_gpe_wake_mask(NULL, i, ACPI_GPE_ENABLE); + if (acpi_s2idle_ixx_gpe == U32_MAX) + acpi_s2idle_ixx_gpe = i; pm_pr_dbg("ACPI: GPE0x%02x armed for wake via %s\n", i, gpe_nr_str); } } +/* + * acpi_x86_s2idle_check_ixx_gpes - Handle an SCI wakeup without an EC + * + * Called to decide whether or not to wake up the system when an SCI has + * triggered during suspend-to-idle on a platform without an EC instance, + * mirroring acpi_ec_dispatch_gpe() with the first GPE armed for wake via + * an _Ixx method playing the role of the EC GPE. + * + * Report a wakeup if the status bit is set for any enabled GPE other than + * the _Ixx one. If no _Ixx GPE has been armed, acpi_s2idle_ixx_gpe is + * U32_MAX and this amounts to checking all of the GPEs, which is the + * previous behavior. + * + * Otherwise, cancel the pending SCI-related wakeup, so it does not cause + * the pm_wakeup_pending() check in the caller to succeed by itself, and + * dispatch the _Ixx GPE if it is active, so the events behind it can be + * processed. If any of those events turn out to be genuine wake events, + * the drivers handling them are expected to call pm_wakeup_event() and + * the caller will catch that via pm_wakeup_pending() after synchronizing + * the event processing. + */ +bool acpi_x86_s2idle_check_ixx_gpes(void) +{ + acpi_event_status status = 0; + + /* + * Report wakeup if the status bit is set for any enabled GPE other + * than the _Ixx one. + */ + if (acpi_any_gpe_status_set(acpi_s2idle_ixx_gpe)) + return true; + + if (acpi_s2idle_ixx_gpe == U32_MAX) + return false; + + /* + * Cancel the SCI wakeup and dispatch the _Ixx GPE in case there are + * any wakeup events behind it. + */ + pm_system_cancel_wakeup(); + + acpi_get_gpe_status(NULL, acpi_s2idle_ixx_gpe, &status); + if (status & ACPI_EVENT_FLAG_STATUS_SET) { + pm_pr_dbg("ACPI _Ixx GPE 0x%02x dispatched\n", + acpi_s2idle_ixx_gpe); + + acpi_dispatch_gpe(NULL, acpi_s2idle_ixx_gpe); + } + + return false; +} + static bool sleep_no_lps0 __read_mostly; module_param(sleep_no_lps0, bool, 0644); MODULE_PARM_DESC(sleep_no_lps0, "Do not use the special LPS0 device interface"); diff --git a/drivers/android/binder/error.rs b/drivers/android/binder/error.rs index 89077c5baeaf..acf0aa09c555 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 f5965e838a96..4ce6fc533203 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); + 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()); - } + 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<Self>, info: &mut TransactionInfo) -> BinderResult { diff --git a/drivers/base/power/runtime.c b/drivers/base/power/runtime.c index 304a2b123420..4e9c23059a40 100644 --- a/drivers/base/power/runtime.c +++ b/drivers/base/power/runtime.c @@ -343,6 +343,9 @@ static void __rpm_put_suppliers(struct device *dev, bool try_to_suspend) list_for_each_entry_rcu(link, &dev->links.suppliers, c_node, device_links_read_lock_held()) { + if (!device_link_test(link, DL_FLAG_PM_RUNTIME)) + continue; + pm_runtime_release_supplier(link); if (try_to_suspend) pm_request_idle(link->supplier); @@ -819,6 +822,12 @@ static int rpm_resume(struct device *dev, int rpmflags) pm_runtime_deactivate_timer(dev); if (dev->power.runtime_status == RPM_ACTIVE) { + /* + * The attempt to resume the device means that it is needed for + * something, so update its last_busy timestamp as in the case + * in which it actually resumes below. + */ + pm_runtime_mark_last_busy(dev); retval = 1; goto out; } @@ -1910,7 +1919,7 @@ void pm_runtime_reinit(struct device *dev) void pm_runtime_remove(struct device *dev) { __pm_runtime_disable(dev, false); - flush_work(&dev->power.work); + cancel_work_sync(&dev->power.work); pm_runtime_reinit(dev); } diff --git a/drivers/base/swnode.c b/drivers/base/swnode.c index 84a77ffa3dc4..cf495e67f076 100644 --- a/drivers/base/swnode.c +++ b/drivers/base/swnode.c @@ -29,6 +29,8 @@ struct swnode { struct fwnode_handle fwnode; const struct software_node *node; int id; + /* Device the managed node's lifetime is tied to. */ + struct device *owner; /* hierarchy */ struct ida child_ids; @@ -37,7 +39,6 @@ struct swnode { struct swnode *parent; unsigned int allocated:1; - unsigned int managed:1; }; static DEFINE_IDA(swnode_root_ids); @@ -1145,7 +1146,7 @@ int device_create_managed_software_node(struct device *dev, if (IS_ERR(fwnode)) return PTR_ERR(fwnode); - to_swnode(fwnode)->managed = true; + to_swnode(fwnode)->owner = dev; set_secondary_fwnode(dev, fwnode); if (device_is_registered(dev)) @@ -1208,7 +1209,7 @@ void software_node_notify_remove(struct device *dev) swnode_put(swnode); - if (swnode->managed) { + if (swnode->owner == dev) { set_secondary_fwnode(dev, NULL); swnode_put(swnode); } diff --git a/drivers/bcma/driver_chipcommon.c b/drivers/bcma/driver_chipcommon.c index fd91a39f02c7..ca268dfcb1e4 100644 --- a/drivers/bcma/driver_chipcommon.c +++ b/drivers/bcma/driver_chipcommon.c @@ -3,7 +3,7 @@ * ChipCommon core driver * * Copyright 2005, Broadcom Corporation - * Copyright 2006, 2007, Michael Buesch <m@bues.ch> + * Copyright 2006, 2007, Michael Buesch * Copyright 2012, Hauke Mehrtens <hauke@hauke-m.de> * * Licensed under the GNU/GPL. See COPYING for details. diff --git a/drivers/bcma/driver_chipcommon_pmu.c b/drivers/bcma/driver_chipcommon_pmu.c index 263ef6fa1d0f..d29950e06b0a 100644 --- a/drivers/bcma/driver_chipcommon_pmu.c +++ b/drivers/bcma/driver_chipcommon_pmu.c @@ -2,7 +2,7 @@ * Broadcom specific AMBA * ChipCommon Power Management Unit driver * - * Copyright 2009, Michael Buesch <m@bues.ch> + * Copyright 2009, Michael Buesch * Copyright 2007, 2011, Broadcom Corporation * Copyright 2011, 2012, Hauke Mehrtens <hauke@hauke-m.de> * diff --git a/drivers/bcma/driver_pci.c b/drivers/bcma/driver_pci.c index 12b2cc9a3fbe..30291954c02f 100644 --- a/drivers/bcma/driver_pci.c +++ b/drivers/bcma/driver_pci.c @@ -3,7 +3,7 @@ * PCI Core * * Copyright 2005, 2011, Broadcom Corporation - * Copyright 2006, 2007, Michael Buesch <m@bues.ch> + * Copyright 2006, 2007, Michael Buesch * Copyright 2011, 2012, Hauke Mehrtens <hauke@hauke-m.de> * * Licensed under the GNU/GPL. See COPYING for details. diff --git a/drivers/bcma/driver_pci_host.c b/drivers/bcma/driver_pci_host.c index f121be2ed813..4a1c3c6af20c 100644 --- a/drivers/bcma/driver_pci_host.c +++ b/drivers/bcma/driver_pci_host.c @@ -3,7 +3,7 @@ * PCI Core in hostmode * * Copyright 2005 - 2011, Broadcom Corporation - * Copyright 2006, 2007, Michael Buesch <m@bues.ch> + * Copyright 2006, 2007, Michael Buesch * Copyright 2011, 2012, Hauke Mehrtens <hauke@hauke-m.de> * * Licensed under the GNU/GPL. See COPYING for details. diff --git a/drivers/block/ublk_drv.c b/drivers/block/ublk_drv.c index 3d322fa1bc83..d415be37d5ed 100644 --- a/drivers/block/ublk_drv.c +++ b/drivers/block/ublk_drv.c @@ -881,7 +881,8 @@ static ssize_t ublk_batch_copy_io_tags(struct ublk_batch_fetch_cmd *fcmd, * by cgroup. */ static unsigned int unprivileged_ublks_max = 64; -static unsigned int unprivileged_ublks_added; /* protected by ublk_ctl_mutex */ +/* checked and incremented under ublk_ctl_mutex, decremented without it */ +static atomic_t unprivileged_ublks_added = ATOMIC_INIT(0); static struct miscdevice ublk_misc; @@ -4405,14 +4406,18 @@ static int ublk_alloc_dev_number(struct ublk_device *ub, int idx) int i = idx; int err; + /* + * Only reserve the id: the device is published by + * ublk_publish_dev_number() once it is fully set up. + */ spin_lock(&ublk_idr_lock); /* allocate id, if @id >= 0, we're requesting that specific id */ if (i >= 0) { - err = idr_alloc(&ublk_index_idr, ub, i, i + 1, GFP_NOWAIT); + err = idr_alloc(&ublk_index_idr, NULL, i, i + 1, GFP_NOWAIT); if (err == -ENOSPC) err = -EEXIST; } else { - err = idr_alloc(&ublk_index_idr, ub, 0, UBLK_MAX_UBLKS, + err = idr_alloc(&ublk_index_idr, NULL, 0, UBLK_MAX_UBLKS, GFP_NOWAIT); } spin_unlock(&ublk_idr_lock); @@ -4423,6 +4428,19 @@ static int ublk_alloc_dev_number(struct ublk_device *ub, int idx) return err; } +/* + * Make the device visible to control commands by its id. Before its char + * device is added, DEL_DEV could find it and remove a char device that was + * never added, and drop the reference that ublk_add_chdev() drops on + * failure. + */ +static void ublk_publish_dev_number(struct ublk_device *ub) +{ + spin_lock(&ublk_idr_lock); + WARN_ON_ONCE(idr_replace(&ublk_index_idr, ub, ub->ub_number) != NULL); + spin_unlock(&ublk_idr_lock); +} + static void ublk_free_dev_number(struct ublk_device *ub) { spin_lock(&ublk_idr_lock); @@ -4469,7 +4487,7 @@ static int ublk_add_chdev(struct ublk_device *ub) goto fail; if (ub->dev_info.flags & UBLK_F_UNPRIVILEGED_DEV) - unprivileged_ublks_added++; + atomic_inc(&unprivileged_ublks_added); return 0; fail: put_device(dev); @@ -4501,15 +4519,9 @@ static int ublk_add_tag_set(struct ublk_device *ub) static void ublk_remove(struct ublk_device *ub) { - bool unprivileged; - ublk_stop_dev(ub); cdev_device_del(&ub->cdev, &ub->cdev_dev); - unprivileged = ub->dev_info.flags & UBLK_F_UNPRIVILEGED_DEV; ublk_put_device(ub); - - if (unprivileged) - unprivileged_ublks_added--; } static struct ublk_device *ublk_get_device_from_id(int idx) @@ -4899,7 +4911,7 @@ static int ublk_ctrl_add_dev(const struct ublksrv_ctrl_cmd *header) ret = -EACCES; if ((info.flags & UBLK_F_UNPRIVILEGED_DEV) && - unprivileged_ublks_added >= unprivileged_ublks_max) + atomic_read(&unprivileged_ublks_added) >= unprivileged_ublks_max) goto out_unlock; ret = -ENOMEM; @@ -4991,6 +5003,8 @@ static int ublk_ctrl_add_dev(const struct ublksrv_ctrl_cmd *header) * ublk_add_chdev() will cleanup everything if it fails. */ ret = ublk_add_chdev(ub); + if (!ret) + ublk_publish_dev_number(ub); goto out_unlock; out_deinit_queues: @@ -5023,23 +5037,23 @@ static int ublk_ctrl_del_dev(struct ublk_device **p_ub, bool wait) { struct ublk_device *ub = *p_ub; int idx = ub->ub_number; - int ret; - - ret = mutex_lock_killable(&ublk_ctl_mutex); - if (ret) - return ret; + bool unprivileged = ub->dev_info.flags & UBLK_F_UNPRIVILEGED_DEV; - if (!test_bit(UB_STATE_DELETED, &ub->state)) { + /* + * Don't take ublk_ctl_mutex: stopping the device may wait for the + * filesystem on its disk indefinitely, and ADD_DEV and DEL_DEV of all + * other ublk devices would wait for that too. ADD_DEV is done with the + * device, it is found by its id only then. + */ + if (!test_and_set_bit(UB_STATE_DELETED, &ub->state)) { ublk_remove(ub); - set_bit(UB_STATE_DELETED, &ub->state); + if (unprivileged) + atomic_dec(&unprivileged_ublks_added); } - mutex_unlock(&ublk_ctl_mutex); - /* - * Drop the reference outside ublk_ctl_mutex: if it is the last one, - * the release frees the tag set, which waits for an SRCU grace period, - * and holding the mutex would serialize concurrent deletions on it. + * If this is the last reference, the release frees the tag set, which + * waits for an SRCU grace period. */ *p_ub = NULL; ublk_put_device(ub); diff --git a/drivers/bluetooth/btqca.c b/drivers/bluetooth/btqca.c index 002307000d3c..60735b70d89a 100644 --- a/drivers/bluetooth/btqca.c +++ b/drivers/bluetooth/btqca.c @@ -943,6 +943,7 @@ int qca_uart_setup(struct hci_dev *hdev, uint8_t baudrate, switch (soc_type) { case QCA_QCA2066: case QCA_QCA6390: + case QCA_WCN3950: case QCA_WCN3991: case QCA_WCN6750: case QCA_WCN6855: diff --git a/drivers/bluetooth/btusb_main.c b/drivers/bluetooth/btusb_main.c index 92a78a7e6039..95398e2ca098 100644 --- a/drivers/bluetooth/btusb_main.c +++ b/drivers/bluetooth/btusb_main.c @@ -1088,6 +1088,8 @@ struct btusb_data { int (*disconnect)(struct hci_dev *hdev); int oob_wake_irq; /* irq for out-of-band wake-on-bt */ + + struct dentry *force_poll_sync_dentry; }; static void btusb_reset(struct hci_dev *hdev) @@ -4820,8 +4822,9 @@ static int btusb_probe(struct usb_interface *intf, usb_set_intfdata(intf, data); - debugfs_create_file("force_poll_sync", 0644, hdev->debugfs, data, - &force_poll_sync_fops); + data->force_poll_sync_dentry = + debugfs_create_file("force_poll_sync", 0644, hdev->debugfs, + data, &force_poll_sync_fops); return 0; @@ -4862,6 +4865,9 @@ static void btusb_disconnect(struct usb_interface *intf) if (!data) return; + debugfs_remove(data->force_poll_sync_dentry); + data->force_poll_sync_dentry = NULL; + hdev = data->hdev; usb_set_intfdata(data->intf, NULL); diff --git a/drivers/bluetooth/hci_qca.c b/drivers/bluetooth/hci_qca.c index e480d38109cf..4cebd0a9998d 100644 --- a/drivers/bluetooth/hci_qca.c +++ b/drivers/bluetooth/hci_qca.c @@ -161,6 +161,7 @@ struct qca_data { struct delayed_work ctrl_memdump_timeout; struct qca_memdump_info *qca_memdump; unsigned long flags; + struct dentry *debugfs_ibs_dir; struct completion drop_ev_comp; wait_queue_head_t suspend_wait_q; enum qca_memdump_states memdump_state; @@ -665,6 +666,7 @@ static void qca_debugfs_init(struct hci_dev *hdev) return; ibs_dir = debugfs_create_dir("ibs", hdev->debugfs); + qca->debugfs_ibs_dir = ibs_dir; /* read only */ mode = 0444; @@ -744,6 +746,9 @@ static int qca_close(struct hci_uart *hu) hu->priv = NULL; + debugfs_remove_recursive(qca->debugfs_ibs_dir); + qca->debugfs_ibs_dir = NULL; + kfree(qca); return 0; diff --git a/drivers/char/tpm/eventlog/acpi.c b/drivers/char/tpm/eventlog/acpi.c index cf02ec646f46..50770cafa835 100644 --- a/drivers/char/tpm/eventlog/acpi.c +++ b/drivers/char/tpm/eventlog/acpi.c @@ -167,10 +167,8 @@ int tpm_read_log_acpi(struct tpm_chip *chip) } ret = devm_add_action(&chip->dev, tpm_bios_log_free, log->bios_event_log); - if (ret) { - log->bios_event_log = NULL; + if (ret) goto err; - } return format; diff --git a/drivers/char/tpm/eventlog/tpm1.c b/drivers/char/tpm/eventlog/tpm1.c index 0397e3361020..f93a358a706e 100644 --- a/drivers/char/tpm/eventlog/tpm1.c +++ b/drivers/char/tpm/eventlog/tpm1.c @@ -178,6 +178,10 @@ static int get_event_name(char *dest, struct tcpa_event *event, } break; case EVENT_TAG: + if (do_endian_conversion(event->event_size) < + sizeof(pc_event->event_id)) + break; + pc_event = (struct tcpa_pc_event *)event_entry; /* ToDo Row data -> Base64 */ @@ -203,6 +207,9 @@ static int get_event_name(char *dest, struct tcpa_event *event, name = tcpa_pc_event_id_strings[do_endian_conversion (pc_event->event_id)]; n_len = strlen(name); + if (do_endian_conversion(event->event_size) < + sizeof(struct tcpa_pc_event) + 20) + break; for (i = 0; i < 20; i++) d_len += sprintf(&data[2*i], "%02x", pc_event->event_data[i]); diff --git a/drivers/char/tpm/tpm-dev-common.c b/drivers/char/tpm/tpm-dev-common.c index 6569212dc6b8..ee91f456f975 100644 --- a/drivers/char/tpm/tpm-dev-common.c +++ b/drivers/char/tpm/tpm-dev-common.c @@ -132,6 +132,7 @@ ssize_t tpm_common_read(struct file *file, char __user *buf, { struct file_priv *priv = file->private_data; ssize_t ret_size = 0; + bool flush = false; int rc; if (!size) @@ -164,9 +165,18 @@ out: if (!priv->response_length) { *off = 0; timer_delete_sync(&priv->user_read_timer); - flush_work(&priv->timeout_work); + flush = true; } mutex_unlock(&priv->buffer_mutex); + + /* + * tpm_timeout_work() takes buffer_mutex, so flush it after dropping + * the mutex to avoid a deadlock; the timer is deleted above, so no new + * timeout work can be queued once the mutex is released. + */ + if (flush) + flush_work(&priv->timeout_work); + return ret_size; } diff --git a/drivers/char/tpm/tpm2-sessions.c b/drivers/char/tpm/tpm2-sessions.c index ca1e2bf424e1..2aaaad69760d 100644 --- a/drivers/char/tpm/tpm2-sessions.c +++ b/drivers/char/tpm/tpm2-sessions.c @@ -527,7 +527,9 @@ static int tpm_buf_append_salt(struct tpm_buf *buf, struct tpm_chip *chip, } crypto_ecdh_encode_key(encoded_key, buf_len, &p); /* this generates a random private key */ - crypto_kpp_set_secret(kpp, encoded_key, buf_len); + rc = crypto_kpp_set_secret(kpp, encoded_key, buf_len); + if (rc) + goto err_free_kpp; /* salt is now the public point of this private key */ req = kpp_request_alloc(kpp, GFP_KERNEL); diff --git a/drivers/char/virtio_console.c b/drivers/char/virtio_console.c index 019bcae81af5..b1b1aaf43e07 100644 --- a/drivers/char/virtio_console.c +++ b/drivers/char/virtio_console.c @@ -891,45 +891,34 @@ static int pipe_to_sg(struct pipe_inode_info *pipe, struct pipe_buffer *buf, { struct sg_list *sgl = sd->u.data; unsigned int offset, len; + struct page *page; + char *src; if (sgl->n == sgl->size) return 0; - /* Try lock this page */ - if (pipe_buf_try_steal(pipe, buf)) { - /* Get reference and unlock page for moving */ - get_page(buf->page); - unlock_page(buf->page); - - len = min(buf->len, sd->len); - sg_set_page(&(sgl->sg[sgl->n]), buf->page, len, buf->offset); - } else { - /* Failback to copying a page */ - struct page *page = alloc_page(GFP_KERNEL); - char *src; - - if (!page) - return -ENOMEM; + page = alloc_page(GFP_KERNEL); + if (!page) + return -ENOMEM; - offset = sd->pos & ~PAGE_MASK; + offset = sd->pos & ~PAGE_MASK; - len = sd->len; - if (len + offset > PAGE_SIZE) - len = PAGE_SIZE - offset; + len = sd->len; + if (len + offset > PAGE_SIZE) + len = PAGE_SIZE - offset; - src = kmap_local_page(buf->page); - memcpy(page_address(page) + offset, src + buf->offset, len); - kunmap_local(src); + src = kmap_local_page(buf->page); + memcpy(page_address(page) + offset, src + buf->offset, len); + kunmap_local(src); - sg_set_page(&(sgl->sg[sgl->n]), page, len, offset); - } + sg_set_page(&sgl->sg[sgl->n], page, len, offset); sgl->n++; sgl->len += len; return len; } -/* Faster zero-copy write by splicing */ +/* Write by splicing, copying the data from the pipe */ static ssize_t port_fops_splice_write(struct pipe_inode_info *pipe, struct file *filp, loff_t *ppos, size_t len, unsigned int flags) diff --git a/drivers/comedi/comedi_fops.c b/drivers/comedi/comedi_fops.c index 9a65dc5d62a4..6d71ceeff6fc 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 a203e27888e2..3d65aef565b3 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 a10cfbd04c72..3764ece90f82 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 5508cdb1b0ba..9238475dda07 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 c3a909abcfa7..b7ab70f34275 100644 --- a/drivers/comedi/drivers/ni_tio.c +++ b/drivers/comedi/drivers/ni_tio.c @@ -800,7 +800,7 @@ static int ni_tio_set_clock_src(struct ni_gpct *counter, GI_PRESCALE_X2(counter_dev->variant) | GI_PRESCALE_X8(counter_dev->variant), bits); } - counter->clock_period_ps = period_ns * 1000; + counter->clock_period_ps = (u64)period_ns * 1000; ni_tio_set_sync_mode(counter); return 0; } diff --git a/drivers/comedi/drivers/vmk80xx.c b/drivers/comedi/drivers/vmk80xx.c index 84dce5184a77..ddb12b48c8a4 100644 --- a/drivers/comedi/drivers/vmk80xx.c +++ b/drivers/comedi/drivers/vmk80xx.c @@ -151,7 +151,7 @@ struct vmk80xx_private { enum vmk80xx_model model; }; -static void vmk80xx_do_bulk_msg(struct comedi_device *dev) +static int vmk80xx_do_bulk_msg(struct comedi_device *dev) { struct vmk80xx_private *devpriv = dev->private; struct usb_device *usb = comedi_to_usb_dev(dev); @@ -161,6 +161,7 @@ static void vmk80xx_do_bulk_msg(struct comedi_device *dev) unsigned int rx_pipe; size_t tx_size; size_t rx_size; + int ret; tx_addr = devpriv->ep_tx->bEndpointAddress; rx_addr = devpriv->ep_rx->bEndpointAddress; @@ -169,11 +170,13 @@ static void vmk80xx_do_bulk_msg(struct comedi_device *dev) tx_size = usb_endpoint_maxp(devpriv->ep_tx); rx_size = usb_endpoint_maxp(devpriv->ep_rx); - usb_bulk_msg(usb, tx_pipe, devpriv->usb_tx_buf, tx_size, NULL, - PACKET_TIMEOUT); + ret = usb_bulk_msg(usb, tx_pipe, devpriv->usb_tx_buf, tx_size, NULL, + PACKET_TIMEOUT); + if (ret) + return ret; - usb_bulk_msg(usb, rx_pipe, devpriv->usb_rx_buf, rx_size, NULL, - PACKET_TIMEOUT); + return usb_bulk_msg(usb, rx_pipe, devpriv->usb_rx_buf, rx_size, NULL, + PACKET_TIMEOUT); } static int vmk80xx_read_packet(struct comedi_device *dev) @@ -183,10 +186,8 @@ static int vmk80xx_read_packet(struct comedi_device *dev) struct usb_endpoint_descriptor *ep; unsigned int pipe; - if (devpriv->model == VMK8061_MODEL) { - vmk80xx_do_bulk_msg(dev); - return 0; - } + if (devpriv->model == VMK8061_MODEL) + return vmk80xx_do_bulk_msg(dev); ep = devpriv->ep_rx; pipe = usb_rcvintpipe(usb, ep->bEndpointAddress); @@ -204,10 +205,8 @@ static int vmk80xx_write_packet(struct comedi_device *dev, int cmd) devpriv->usb_tx_buf[0] = cmd; - if (devpriv->model == VMK8061_MODEL) { - vmk80xx_do_bulk_msg(dev); - return 0; - } + if (devpriv->model == VMK8061_MODEL) + return vmk80xx_do_bulk_msg(dev); ep = devpriv->ep_tx; pipe = usb_sndintpipe(usb, ep->bEndpointAddress); diff --git a/drivers/cpufreq/acpi-cpufreq.c b/drivers/cpufreq/acpi-cpufreq.c index 2e74a000cdc7..f64fa379c6b1 100644 --- a/drivers/cpufreq/acpi-cpufreq.c +++ b/drivers/cpufreq/acpi-cpufreq.c @@ -197,14 +197,13 @@ static unsigned extract_io(struct cpufreq_policy *policy, u32 value) { struct acpi_cpufreq_data *data = policy->driver_data; struct acpi_processor_performance *perf; - int i; + struct cpufreq_frequency_table *pos; perf = to_perf_data(data); - for (i = 0; i < perf->state_count; i++) { - if (value == perf->states[i].status) - return policy->freq_table[i].frequency; - } + cpufreq_for_each_entry(pos, policy->freq_table) + if (value == perf->states[pos->driver_data].status) + return pos->frequency; return 0; } diff --git a/drivers/cpufreq/cpufreq.c b/drivers/cpufreq/cpufreq.c index 54dde8419bdc..24319b214d7b 100644 --- a/drivers/cpufreq/cpufreq.c +++ b/drivers/cpufreq/cpufreq.c @@ -35,6 +35,9 @@ static LIST_HEAD(cpufreq_policy_list); /* Macros to iterate over CPU policies */ +#define for_each_policy(__policy) \ + list_for_each_entry(__policy, &cpufreq_policy_list, policy_list) + #define for_each_suitable_policy(__policy, __active) \ list_for_each_entry(__policy, &cpufreq_policy_list, policy_list) \ if ((__active) == !policy_is_inactive(__policy)) @@ -474,7 +477,7 @@ EXPORT_SYMBOL_GPL(cpufreq_disable_fast_switch); static unsigned int __resolve_freq(struct cpufreq_policy *policy, unsigned int target_freq, unsigned int min, unsigned int max, - unsigned int relation) + unsigned int relation, unsigned int *idx_p) { unsigned int idx; @@ -484,8 +487,9 @@ static unsigned int __resolve_freq(struct cpufreq_policy *policy, return target_freq; idx = cpufreq_frequency_table_target(policy, target_freq, min, max, relation); - policy->cached_resolved_idx = idx; - policy->cached_target_freq = target_freq; + if (idx_p) + *idx_p = idx; + return policy->freq_table[idx].frequency; } @@ -517,7 +521,10 @@ unsigned int cpufreq_driver_resolve_freq(struct cpufreq_policy *policy, if (unlikely(min > max)) min = max; - return __resolve_freq(policy, target_freq, min, max, CPUFREQ_RELATION_LE); + policy->cached_target_freq = __resolve_freq(policy, target_freq, min, max, + CPUFREQ_RELATION_LE, + &policy->cached_resolved_idx); + return policy->cached_target_freq; } EXPORT_SYMBOL_GPL(cpufreq_driver_resolve_freq); @@ -576,6 +583,8 @@ static int policy_set_boost(struct cpufreq_policy *policy, bool enable) { int ret; + lockdep_assert_held_write(&policy->rwsem); + if (policy->boost_enabled == enable) return 0; @@ -1629,6 +1638,8 @@ static int cpufreq_online(unsigned int cpu) */ if (cpufreq_driver->set_boost && policy->boost_supported && (new_policy || !cpufreq_boost_enabled())) { + guard(cpufreq_policy_write)(policy); + ret = policy_set_boost(policy, cpufreq_boost_enabled()); if (ret) { /* If the set_boost fails, the online operation is not affected */ @@ -1956,6 +1967,14 @@ int cpufreq_generic_suspend(struct cpufreq_policy *policy) } EXPORT_SYMBOL(cpufreq_generic_suspend); +static void cpufreq_suspend_policy(struct cpufreq_policy *policy) +{ + guard(cpufreq_policy_write)(policy); + + cpufreq_stop_governor(policy); + policy->suspended = true; +} + /** * cpufreq_suspend() - Suspend CPUFreq governors. * @@ -1978,11 +1997,8 @@ void cpufreq_suspend(void) pr_debug("%s: Suspending Governors\n", __func__); for_each_active_policy(policy) { - if (has_target()) { - scoped_guard(cpufreq_policy_write, policy) { - cpufreq_stop_governor(policy); - } - } + if (has_target()) + cpufreq_suspend_policy(policy); if (cpufreq_driver->suspend && cpufreq_driver->suspend(policy)) pr_err("%s: Failed to suspend driver: %s\n", __func__, @@ -1994,6 +2010,41 @@ suspend: cpus_read_unlock(); } +static void cpufreq_resume_policy(struct cpufreq_policy *policy, bool start) +{ + guard(cpufreq_policy_write)(policy); + + if (!policy->suspended) + return; + + policy->suspended = false; + + if (policy_is_inactive(policy)) { + /* + * The policy was active when it was suspended, so its governor + * is still there. Let the governor go. + */ + cpufreq_exit_governor(policy); + return; + } + + if (!start) + return; + + /* + * Force executing the driver .target() callback, if present, in the + * next invocation of __cpufreq_driver_target() in case policy->cur has + * become stale while suspended, but do it only for drivers without a + * .get() callback for which cpufreq_verify_current_freq() is a NOP. + */ + if (cpufreq_driver->target && !cpufreq_driver->get) + policy->force_target = true; + + if (cpufreq_start_governor(policy)) + pr_err("%s: Failed to start governor for CPU%u's policy\n", + __func__, policy->cpu); +} + /** * cpufreq_resume() - Resume CPUFreq governors. * @@ -2003,11 +2054,12 @@ suspend: void cpufreq_resume(void) { struct cpufreq_policy *policy; - int ret; if (!cpufreq_driver) return; + guard(cpus_read_lock)(); + if (unlikely(!cpufreq_suspended)) return; @@ -2018,19 +2070,18 @@ void cpufreq_resume(void) pr_debug("%s: Resuming Governors\n", __func__); - for_each_active_policy(policy) { - if (cpufreq_driver->resume && cpufreq_driver->resume(policy)) { - pr_err("%s: Failed to resume driver: %s\n", __func__, - cpufreq_driver->name); - } else if (has_target()) { - scoped_guard(cpufreq_policy_write, policy) { - ret = cpufreq_start_governor(policy); - } + for_each_policy(policy) { + int ret = 0; + if (cpufreq_driver->resume && !policy_is_inactive(policy)) { + ret = cpufreq_driver->resume(policy); if (ret) - pr_err("%s: Failed to start governor for CPU%u's policy\n", - __func__, policy->cpu); + pr_err("%s: Failed to resume driver: %s\n", __func__, + cpufreq_driver->name); } + + if (has_target()) + cpufreq_resume_policy(policy, ret == 0); } } @@ -2355,28 +2406,26 @@ int __cpufreq_driver_target(struct cpufreq_policy *policy, unsigned int relation) { unsigned int old_target_freq = target_freq; + unsigned int idx = 0; if (cpufreq_disabled()) return -ENODEV; target_freq = __resolve_freq(policy, target_freq, policy->min, - policy->max, relation); + policy->max, relation, &idx); pr_debug("CPU %u: cur %u kHz -> target %u kHz (req %u kHz, rel %u)\n", policy->cpu, policy->cur, target_freq, old_target_freq, relation); /* - * This might look like a redundant call as we are checking it again - * after finding index. But it is left intentionally for cases where - * exactly same freq is called again and so we can save on few function - * calls. + * Unless invoking the target callback is forced, skip the update if the + * frequency is not really changing. */ - if (target_freq == policy->cur) { - if (!(cpufreq_driver->flags & CPUFREQ_NEED_UPDATE_LIMITS) || - !policy->update_limits) - return 0; - - policy->update_limits = false; + if (policy->force_target) { + /* Avoid forcing the driver callback unnecessarily next time. */ + policy->force_target = false; + } else if (target_freq == policy->cur) { + return 0; } if (cpufreq_driver->target) { @@ -2393,7 +2442,7 @@ int __cpufreq_driver_target(struct cpufreq_policy *policy, if (!cpufreq_driver->target_index) return -EINVAL; - return __target_index(policy, policy->cached_resolved_idx); + return __target_index(policy, idx); } EXPORT_SYMBOL_GPL(__cpufreq_driver_target); @@ -2412,12 +2461,17 @@ __weak struct cpufreq_governor *cpufreq_fallback_governor(void) return NULL; } +static bool cpufreq_is_suspended(struct cpufreq_policy *policy) +{ + return cpufreq_suspended || policy->suspended; +} + static int cpufreq_init_governor(struct cpufreq_policy *policy) { int ret; - /* Don't start any governor operations if we are entering suspend */ - if (cpufreq_suspended) + /* Don't start any governor operations for suspended policies. */ + if (cpufreq_is_suspended(policy)) return 0; /* * Governor might not be initiated here if ACPI _PPC changed @@ -2460,7 +2514,7 @@ static int cpufreq_init_governor(struct cpufreq_policy *policy) static void cpufreq_exit_governor(struct cpufreq_policy *policy) { - if (cpufreq_suspended || !policy->governor) + if (cpufreq_is_suspended(policy) || !policy->governor) return; pr_debug("%s: for CPU %u\n", __func__, policy->cpu); @@ -2475,7 +2529,7 @@ int cpufreq_start_governor(struct cpufreq_policy *policy) { int ret; - if (cpufreq_suspended) + if (cpufreq_is_suspended(policy)) return 0; if (!policy->governor) @@ -2499,7 +2553,7 @@ int cpufreq_start_governor(struct cpufreq_policy *policy) void cpufreq_stop_governor(struct cpufreq_policy *policy) { - if (cpufreq_suspended || !policy->governor) + if (cpufreq_is_suspended(policy) || !policy->governor) return; pr_debug("%s: for CPU %u\n", __func__, policy->cpu); @@ -2510,7 +2564,7 @@ void cpufreq_stop_governor(struct cpufreq_policy *policy) static void cpufreq_governor_limits(struct cpufreq_policy *policy) { - if (cpufreq_suspended || !policy->governor) + if (cpufreq_is_suspended(policy) || !policy->governor) return; pr_debug("%s: for CPU %u\n", __func__, policy->cpu); @@ -2630,6 +2684,7 @@ static int cpufreq_set_policy(struct cpufreq_policy *policy, struct cpufreq_governor *new_gov, unsigned int new_pol) { + bool need_update_limits = cpufreq_driver->flags & CPUFREQ_NEED_UPDATE_LIMITS; struct cpufreq_policy_data new_data; struct cpufreq_governor *old_gov; unsigned int freq; @@ -2666,26 +2721,26 @@ static int cpufreq_set_policy(struct cpufreq_policy *policy, * concurrently by cpufreq_driver_resolve_freq() during the update. */ freq = __resolve_freq(policy, new_data.max, new_data.min, new_data.max, - CPUFREQ_RELATION_H); + CPUFREQ_RELATION_H, NULL); if (freq != policy->max) { WRITE_ONCE(policy->max, freq); - policy->update_limits = true; + if (need_update_limits) + policy->force_target = true; } freq = __resolve_freq(policy, new_data.min, new_data.min, new_data.max, - CPUFREQ_RELATION_L); + CPUFREQ_RELATION_L, NULL); freq = min(freq, policy->max); if (freq != policy->min) { WRITE_ONCE(policy->min, freq); - policy->update_limits = true; + if (need_update_limits) + policy->force_target = true; } trace_cpu_frequency_limits(policy); cpufreq_update_pressure(policy); - policy->cached_target_freq = UINT_MAX; - pr_debug("new min and max freqs are %u - %u kHz\n", policy->min, policy->max); @@ -2711,6 +2766,12 @@ static int cpufreq_set_policy(struct cpufreq_policy *policy, cpufreq_exit_governor(policy); } + /* + * Initialize cached_target_freq while no governor is running to avoid + * racing with cpufreq_driver_resolve_freq(), which updates it. + */ + policy->cached_target_freq = UINT_MAX; + /* start new governor */ policy->governor = new_gov; ret = cpufreq_init_governor(policy); @@ -2747,7 +2808,8 @@ static void cpufreq_policy_refresh(struct cpufreq_policy *policy) * -> ask driver for current freq and notify governors about a change */ if (cpufreq_driver->get && has_target() && - (cpufreq_suspended || WARN_ON(!cpufreq_verify_current_freq(policy, false)))) + (cpufreq_is_suspended(policy) || + WARN_ON(!cpufreq_verify_current_freq(policy, false)))) return; refresh_frequency_limits(policy); @@ -2810,18 +2872,24 @@ int cpufreq_boost_set_sw(struct cpufreq_policy *policy, int state) } EXPORT_SYMBOL_GPL(cpufreq_boost_set_sw); +static DEFINE_MUTEX(cpufreq_boost_mutex); + static int cpufreq_boost_trigger_state(int state) { struct cpufreq_policy *policy; unsigned long flags; + bool boost_enabled; int ret = -EOPNOTSUPP; + guard(mutex)(&cpufreq_boost_mutex); + /* * Don't compare 'cpufreq_driver->boost_enabled' with 'state' here to * make sure all policies are in sync with global boost flag. */ write_lock_irqsave(&cpufreq_driver_lock, flags); + boost_enabled = cpufreq_driver->boost_enabled; cpufreq_driver->boost_enabled = state; write_unlock_irqrestore(&cpufreq_driver_lock, flags); @@ -2830,6 +2898,8 @@ static int cpufreq_boost_trigger_state(int state) if (!policy->boost_supported) continue; + guard(cpufreq_policy_write)(policy); + ret = policy_set_boost(policy, state); if (unlikely(ret)) break; @@ -2841,7 +2911,7 @@ static int cpufreq_boost_trigger_state(int state) return 0; write_lock_irqsave(&cpufreq_driver_lock, flags); - cpufreq_driver->boost_enabled = !state; + cpufreq_driver->boost_enabled = boost_enabled; write_unlock_irqrestore(&cpufreq_driver_lock, flags); pr_err("%s: Cannot %s BOOST\n", diff --git a/drivers/cpufreq/intel_pstate.c b/drivers/cpufreq/intel_pstate.c index 0e6ae4cdda5d..c78dcd681511 100644 --- a/drivers/cpufreq/intel_pstate.c +++ b/drivers/cpufreq/intel_pstate.c @@ -3389,10 +3389,11 @@ static void intel_cpufreq_cpu_exit(struct cpufreq_policy *policy) static int intel_cpufreq_suspend(struct cpufreq_policy *policy) { + struct cpudata *cpu = all_cpu_data[policy->cpu]; + intel_pstate_suspend(policy); if (hwp_active) { - struct cpudata *cpu = all_cpu_data[policy->cpu]; u64 value = READ_ONCE(cpu->hwp_req_cached); /* @@ -3403,6 +3404,17 @@ static int intel_cpufreq_suspend(struct cpufreq_policy *policy) value &= ~HWP_DESIRED_PERF(~0L); wrmsrq_on_cpu(cpu->cpu, MSR_HWP_REQUEST, value); WRITE_ONCE(cpu->hwp_req_cached, value); + } else { + /* + * Invalidate the cached P-state value that may be stale when + * the governor is started again during resume and may prevent + * MSR_IA32_PERF_CTL from being updated. + * + * This does not require synchronization because the core + * prevents frequency updates for suspended policies from + * occurring. + */ + cpu->pstate.current_pstate = 0; } return 0; @@ -3649,12 +3661,12 @@ static struct acpi_platform_list plat_info[] __initdata = { static bool __init intel_pstate_platform_pwr_mgmt_exists(void) { const struct x86_cpu_id *id; - u64 misc_pwr; + u64 misc_pwr = 0; int idx; id = x86_match_cpu(intel_pstate_cpu_oob_ids); if (id) { - rdmsrq(MSR_MISC_PWR_MGMT, misc_pwr); + rdmsrq_safe(MSR_MISC_PWR_MGMT, &misc_pwr); if (misc_pwr & BITMASK_OOB) { pr_debug("Bit 8 or 18 in the MISC_PWR_MGMT MSR set\n"); pr_debug("P states are controlled in Out of Band mode by the firmware/hardware\n"); diff --git a/drivers/crypto/caam/caampkc.c b/drivers/crypto/caam/caampkc.c index ac515ed8c575..2082adaae585 100644 --- a/drivers/crypto/caam/caampkc.c +++ b/drivers/crypto/caam/caampkc.c @@ -880,7 +880,7 @@ static void caam_rsa_free_key(struct caam_rsa_key *key) static void caam_rsa_drop_leading_zeros(const u8 **ptr, size_t *nbytes) { - while (!**ptr && *nbytes) { + while (*nbytes && !**ptr) { (*ptr)++; (*nbytes)--; } @@ -896,22 +896,22 @@ static void caam_rsa_drop_leading_zeros(const u8 **ptr, size_t *nbytes) * @ptr : pointer to {dP, dQ, qInv} CRT member * @nbytes: length in bytes of {dP, dQ, qInv} CRT member * @dstlen: length in bytes of corresponding p or q prime factor + * @dst : pointer to the zero-padded output buffer */ -static u8 *caam_read_rsa_crt(const u8 *ptr, size_t nbytes, size_t dstlen) +static int caam_read_rsa_crt(const u8 *ptr, size_t nbytes, size_t dstlen, + u8 **dst) { - u8 *dst; - caam_rsa_drop_leading_zeros(&ptr, &nbytes); - if (!nbytes) - return NULL; + if (!nbytes || nbytes > dstlen) + return -EINVAL; - dst = kzalloc(dstlen, GFP_KERNEL); - if (!dst) - return NULL; + *dst = kzalloc(dstlen, GFP_KERNEL); + if (!*dst) + return -ENOMEM; - memcpy(dst + (dstlen - nbytes), ptr, nbytes); + memcpy(*dst + (dstlen - nbytes), ptr, nbytes); - return dst; + return 0; } /** @@ -991,6 +991,7 @@ static int caam_rsa_set_priv_key_form(struct caam_rsa_ctx *ctx, size_t p_sz = raw_key->p_sz; size_t q_sz = raw_key->q_sz; unsigned aligned_size; + int ret; rsa_key->p = caam_read_raw_data(raw_key->p, &p_sz); if (!rsa_key->p) @@ -999,57 +1000,39 @@ static int caam_rsa_set_priv_key_form(struct caam_rsa_ctx *ctx, rsa_key->q = caam_read_raw_data(raw_key->q, &q_sz); if (!rsa_key->q) - goto free_p; + return -ENOMEM; rsa_key->q_sz = q_sz; aligned_size = ALIGN(raw_key->p_sz, dma_get_cache_alignment()); rsa_key->tmp1 = kzalloc(aligned_size, GFP_KERNEL); if (!rsa_key->tmp1) - goto free_q; + return -ENOMEM; aligned_size = ALIGN(raw_key->q_sz, dma_get_cache_alignment()); rsa_key->tmp2 = kzalloc(aligned_size, GFP_KERNEL); if (!rsa_key->tmp2) - goto free_tmp1; + return -ENOMEM; rsa_key->priv_form = FORM2; - rsa_key->dp = caam_read_rsa_crt(raw_key->dp, raw_key->dp_sz, p_sz); - if (!rsa_key->dp) - goto free_tmp2; + ret = caam_read_rsa_crt(raw_key->dp, raw_key->dp_sz, p_sz, + &rsa_key->dp); + if (ret) + return ret; - rsa_key->dq = caam_read_rsa_crt(raw_key->dq, raw_key->dq_sz, q_sz); - if (!rsa_key->dq) - goto free_dp; + ret = caam_read_rsa_crt(raw_key->dq, raw_key->dq_sz, q_sz, + &rsa_key->dq); + if (ret) + return ret; - rsa_key->qinv = caam_read_rsa_crt(raw_key->qinv, raw_key->qinv_sz, - q_sz); - if (!rsa_key->qinv) - goto free_dq; + ret = caam_read_rsa_crt(raw_key->qinv, raw_key->qinv_sz, p_sz, + &rsa_key->qinv); + if (ret) + return ret; rsa_key->priv_form = FORM3; return 0; - -free_dq: - kfree_sensitive(rsa_key->dq); - rsa_key->dq = NULL; -free_dp: - kfree_sensitive(rsa_key->dp); - rsa_key->dp = NULL; -free_tmp2: - kfree_sensitive(rsa_key->tmp2); - rsa_key->tmp2 = NULL; -free_tmp1: - kfree_sensitive(rsa_key->tmp1); - rsa_key->tmp1 = NULL; -free_q: - kfree_sensitive(rsa_key->q); - rsa_key->q = NULL; -free_p: - kfree_sensitive(rsa_key->p); - rsa_key->p = NULL; - return -ENOMEM; } static int caam_rsa_set_priv_key(struct crypto_akcipher *tfm, const void *key, @@ -1067,6 +1050,8 @@ static int caam_rsa_set_priv_key(struct crypto_akcipher *tfm, const void *key, if (ret) return ret; + ret = -ENOMEM; + /* Copy key in DMA zone */ rsa_key->d = kmemdup(raw_key.d, raw_key.d_sz, GFP_KERNEL); if (!rsa_key->d) @@ -1103,7 +1088,7 @@ static int caam_rsa_set_priv_key(struct crypto_akcipher *tfm, const void *key, err: caam_rsa_free_key(rsa_key); - return -ENOMEM; + return ret; } static unsigned int caam_rsa_max_size(struct crypto_akcipher *tfm) diff --git a/drivers/crypto/ccp/sev-dev.c b/drivers/crypto/ccp/sev-dev.c index ba0325979f61..52fb208b71ab 100644 --- a/drivers/crypto/ccp/sev-dev.c +++ b/drivers/crypto/ccp/sev-dev.c @@ -1916,6 +1916,8 @@ static int sev_ioctl_do_reset(struct sev_issue_cmd *argp, bool writable) if (!writable) return -EPERM; + mutex_lock(&sev_cmd_mutex); + /* * The SEV spec requires that FACTORY_RESET must be issued in * UNINIT state. Before we go further lets check if any guest is @@ -1927,18 +1929,24 @@ static int sev_ioctl_do_reset(struct sev_issue_cmd *argp, bool writable) */ rc = sev_get_platform_state(&state, &argp->error); if (rc) - return rc; + goto out_unlock; - if (state == SEV_STATE_WORKING) - return -EBUSY; + if (state == SEV_STATE_WORKING) { + rc = -EBUSY; + goto out_unlock; + } if (state == SEV_STATE_INIT) { rc = __sev_platform_shutdown_locked(&argp->error); if (rc) - return rc; + goto out_unlock; } - return __sev_do_cmd_locked(SEV_CMD_FACTORY_RESET, NULL, &argp->error); + rc = __sev_do_cmd_locked(SEV_CMD_FACTORY_RESET, NULL, &argp->error); + +out_unlock: + mutex_unlock(&sev_cmd_mutex); + return rc; } static int sev_ioctl_do_platform_status(struct sev_issue_cmd *argp) @@ -1948,7 +1956,9 @@ static int sev_ioctl_do_platform_status(struct sev_issue_cmd *argp) memset(&data, 0, sizeof(data)); + mutex_lock(&sev_cmd_mutex); ret = __sev_do_cmd_locked(SEV_CMD_PLATFORM_STATUS, &data, &argp->error); + mutex_unlock(&sev_cmd_mutex); if (ret) return ret; @@ -1967,10 +1977,12 @@ static int sev_ioctl_do_pek_pdh_gen(int cmd, struct sev_issue_cmd *argp, bool wr if (!writable) return -EPERM; + mutex_lock(&sev_cmd_mutex); + if (sev->sev_plat_status.state == SEV_STATE_UNINIT) { rc = sev_move_to_init_state(argp, &shutdown_required); if (rc) - return rc; + goto out_unlock; } rc = __sev_do_cmd_locked(cmd, NULL, &argp->error); @@ -1978,6 +1990,9 @@ static int sev_ioctl_do_pek_pdh_gen(int cmd, struct sev_issue_cmd *argp, bool wr if (shutdown_required) __sev_firmware_shutdown(sev, false); +out_unlock: + mutex_unlock(&sev_cmd_mutex); + return rc; } @@ -2016,14 +2031,24 @@ static int sev_ioctl_do_pek_csr(struct sev_issue_cmd *argp, bool writable) data.len = input.length; cmd: + mutex_lock(&sev_cmd_mutex); + if (sev->sev_plat_status.state == SEV_STATE_UNINIT) { ret = sev_move_to_init_state(argp, &shutdown_required); - if (ret) + if (ret) { + mutex_unlock(&sev_cmd_mutex); + /* No shutdown is needed if init fails */ goto e_free_blob; + } } ret = __sev_do_cmd_locked(SEV_CMD_PEK_CSR, &data, &argp->error); + if (shutdown_required) + __sev_firmware_shutdown(sev, false); + + mutex_unlock(&sev_cmd_mutex); + /* * Firmware will returns the length of the CSR blob (either the minimum * required length or the actual length written), return it to the user. @@ -2044,9 +2069,6 @@ cmd: } e_free_blob: - if (shutdown_required) - __sev_firmware_shutdown(sev, false); - kfree(blob); return ret; } @@ -2319,19 +2341,26 @@ static int sev_ioctl_do_pek_import(struct sev_issue_cmd *argp, bool writable) data.oca_cert_address = __psp_pa(oca_blob); data.oca_cert_len = input.oca_cert_len; + mutex_lock(&sev_cmd_mutex); + /* If platform is not in INIT state then transition it to INIT */ if (sev->sev_plat_status.state != SEV_STATE_INIT) { ret = sev_move_to_init_state(argp, &shutdown_required); - if (ret) + if (ret) { + mutex_unlock(&sev_cmd_mutex); + /* No shutdown is needed if init fails */ goto e_free_oca; + } } ret = __sev_do_cmd_locked(SEV_CMD_PEK_CERT_IMPORT, &data, &argp->error); -e_free_oca: if (shutdown_required) __sev_firmware_shutdown(sev, false); + mutex_unlock(&sev_cmd_mutex); + +e_free_oca: kfree(oca_blob); e_free_pek: kfree(pek_blob); @@ -2374,7 +2403,9 @@ static int sev_ioctl_do_get_id2(struct sev_issue_cmd *argp) data.len = 0; } + mutex_lock(&sev_cmd_mutex); ret = __sev_do_cmd_locked(SEV_CMD_GET_ID, &data, &argp->error); + mutex_unlock(&sev_cmd_mutex); /* * Firmware will return the length of the ID value (either the minimum @@ -2432,7 +2463,9 @@ static int sev_ioctl_do_get_id(struct sev_issue_cmd *argp) data->address = __psp_pa(id_blob); data->len = user_size; + mutex_lock(&sev_cmd_mutex); ret = __sev_do_cmd_locked(SEV_CMD_GET_ID, data, &argp->error); + mutex_unlock(&sev_cmd_mutex); if (!ret) { if (copy_to_user((void __user *)argp->data, id_blob, data->len)) ret = -EFAULT; @@ -2494,19 +2527,30 @@ static int sev_ioctl_do_pdh_export(struct sev_issue_cmd *argp, bool writable) data.cert_chain_len = input.cert_chain_len; cmd: + mutex_lock(&sev_cmd_mutex); + /* If platform is not in INIT state then transition it to INIT. */ if (sev->sev_plat_status.state != SEV_STATE_INIT) { if (!writable) { ret = -EPERM; + mutex_unlock(&sev_cmd_mutex); goto e_free_cert; } ret = sev_move_to_init_state(argp, &shutdown_required); - if (ret) + if (ret) { + /* No shutdown is needed if init fails */ + mutex_unlock(&sev_cmd_mutex); goto e_free_cert; + } } ret = __sev_do_cmd_locked(SEV_CMD_PDH_CERT_EXPORT, &data, &argp->error); + if (shutdown_required) + __sev_firmware_shutdown(sev, false); + + mutex_unlock(&sev_cmd_mutex); + /* * Firmware will return the length of the blobs (either the minimum * required length or the actual length written), return 'em to the user. @@ -2537,9 +2581,6 @@ cmd: } e_free_cert: - if (shutdown_required) - __sev_firmware_shutdown(sev, false); - kfree(cert_blob); e_free_pdh: kfree(pdh_blob); @@ -2561,6 +2602,8 @@ static int __sev_do_snp_platform_status(struct sev_user_data_snp_status *status, data = page_address(status_page); + mutex_lock(&sev_cmd_mutex); + /* * SNP_PLATFORM_STATUS can be executed in any SNP state. But if executed * when SNP has been initialized, the status page must be firmware-owned. @@ -2572,6 +2615,7 @@ static int __sev_do_snp_platform_status(struct sev_user_data_snp_status *status, */ if (rmp_mark_pages_firmware(__pa(data), 1, true)) { ret = -EFAULT; + mutex_unlock(&sev_cmd_mutex); goto cleanup; } } @@ -2585,10 +2629,14 @@ static int __sev_do_snp_platform_status(struct sev_user_data_snp_status *status, * in Firmware state on failure. Use snp_reclaim_pages() to * transition either case back to Hypervisor-owned state. */ - if (snp_reclaim_pages(__pa(data), 1, true)) + if (snp_reclaim_pages(__pa(data), 1, true)) { + mutex_unlock(&sev_cmd_mutex); return -EFAULT; + } } + mutex_unlock(&sev_cmd_mutex); + if (ret) goto cleanup; @@ -2625,7 +2673,9 @@ static int sev_ioctl_do_snp_commit(struct sev_issue_cmd *argp) buf.len = sizeof(buf); + mutex_lock(&sev_cmd_mutex); ret = __sev_do_cmd_locked(SEV_CMD_SNP_COMMIT, &buf, &argp->error); + mutex_unlock(&sev_cmd_mutex); return ret; } @@ -2634,6 +2684,7 @@ static int sev_ioctl_do_snp_set_config(struct sev_issue_cmd *argp, bool writable { struct sev_device *sev = psp_master->sev_data; struct sev_user_data_snp_config config; + int ret; if (!argp->data) return -EINVAL; @@ -2647,7 +2698,11 @@ static int sev_ioctl_do_snp_set_config(struct sev_issue_cmd *argp, bool writable if (copy_from_user(&config, (void __user *)argp->data, sizeof(config))) return -EFAULT; - return __sev_do_cmd_locked(SEV_CMD_SNP_CONFIG, &config, &argp->error); + mutex_lock(&sev_cmd_mutex); + ret = __sev_do_cmd_locked(SEV_CMD_SNP_CONFIG, &config, &argp->error); + mutex_unlock(&sev_cmd_mutex); + + return ret; } static int sev_ioctl_do_snp_vlek_load(struct sev_issue_cmd *argp, bool writable) @@ -2679,7 +2734,10 @@ static int sev_ioctl_do_snp_vlek_load(struct sev_issue_cmd *argp, bool writable) input.vlek_wrapped_address = __psp_pa(blob); + mutex_lock(&sev_cmd_mutex); ret = __sev_do_cmd_locked(SEV_CMD_SNP_VLEK_LOAD, &input, &argp->error); + mutex_unlock(&sev_cmd_mutex); + kfree(blob); return ret; @@ -2704,8 +2762,6 @@ static long sev_ioctl(struct file *file, unsigned int ioctl, unsigned long arg) if (input.cmd > SEV_MAX) return -EINVAL; - mutex_lock(&sev_cmd_mutex); - switch (input.cmd) { case SEV_FACTORY_RESET: @@ -2756,7 +2812,6 @@ static long sev_ioctl(struct file *file, unsigned int ioctl, unsigned long arg) if (copy_to_user(argp, &input, sizeof(struct sev_issue_cmd))) ret = -EFAULT; out: - mutex_unlock(&sev_cmd_mutex); return ret; } @@ -3105,9 +3160,7 @@ static int get_v1_svn(struct sev_device *sev) struct sev_user_data_snp_status status; int ret, error = 0; - mutex_lock(&sev_cmd_mutex); ret = __sev_do_snp_platform_status(&status, &error); - mutex_unlock(&sev_cmd_mutex); if (ret < 0) return ret; @@ -3122,9 +3175,7 @@ static int get_v2_svn(struct sev_device *sev) struct sev_snp_tcb_version_turin *tcb; int ret, error = 0; - mutex_lock(&sev_cmd_mutex); ret = __sev_do_snp_platform_status(&status, &error); - mutex_unlock(&sev_cmd_mutex); if (ret < 0) return ret; diff --git a/drivers/dpll/dpll_core.c b/drivers/dpll/dpll_core.c index 8389983f4256..277692d12d3d 100644 --- a/drivers/dpll/dpll_core.c +++ b/drivers/dpll/dpll_core.c @@ -1081,7 +1081,8 @@ int dpll_pin_ref_sync_pair_add(struct dpll_pin *pin, mutex_lock(&dpll_lock); ret = xa_insert(&pin->ref_sync_pins, ref_sync_pin->id, ref_sync_pin, GFP_KERNEL); - __dpll_pin_change_ntf(pin); + if (!ret) + __dpll_pin_change_ntf(pin); mutex_unlock(&dpll_lock); return ret; diff --git a/drivers/firmware/broadcom/bcm47xx_sprom.c b/drivers/firmware/broadcom/bcm47xx_sprom.c index bca03fd85808..9e856d89d56d 100644 --- a/drivers/firmware/broadcom/bcm47xx_sprom.c +++ b/drivers/firmware/broadcom/bcm47xx_sprom.c @@ -1,7 +1,7 @@ /* * Copyright (C) 2004 Florian Schirmer <jolt@tuxbox.org> * Copyright (C) 2006 Felix Fietkau <nbd@openwrt.org> - * Copyright (C) 2006 Michael Buesch <m@bues.ch> + * Copyright (C) 2006 Michael Buesch * Copyright (C) 2010 Waldemar Brodkorb <wbx@openadk.org> * Copyright (C) 2010-2012 Hauke Mehrtens <hauke@hauke-m.de> * diff --git a/drivers/gpio/gpio-aspeed.c b/drivers/gpio/gpio-aspeed.c index 5d94fac3a962..45e90ebaf078 100644 --- a/drivers/gpio/gpio-aspeed.c +++ b/drivers/gpio/gpio-aspeed.c @@ -1041,6 +1041,17 @@ static void aspeed_g4_reg_bit_set(struct aspeed_gpio *gpio, unsigned int offset, void __iomem *addr = aspeed_gpio_g4_bank_reg(gpio, bank, reg); u32 temp; + /* + * The interrupt status register is write-1-to-clear. Write only this + * line's bit so that interrupts pending on the other lines of the bank + * stay latched. + */ + if (reg == reg_irq_status) { + if (val) + iowrite32(GPIO_BIT(offset), addr); + return; + } + if (reg == reg_val) temp = gpio->dcache[GPIO_BANK(offset)]; else @@ -1157,7 +1168,13 @@ static void aspeed_g7_reg_bit_set(struct aspeed_gpio *gpio, unsigned int offset, u32 write_val; if (mask) { - write_val = (ioread32(addr) & ~(mask)) | field_prep(mask, val); + /* + * The interrupt status bit is write-1-to-clear. Keep it zero + * unless it is the field being written, so that updating any + * other field leaves a pending interrupt latched. + */ + write_val = ioread32(addr) & ~(mask | GPIO_G7_CTRL_IRQ_STS); + write_val |= field_prep(mask, val); iowrite32(write_val, addr); } } diff --git a/drivers/gpio/gpio-brcmstb.c b/drivers/gpio/gpio-brcmstb.c index d6524deef60b..2c4575f2df5a 100644 --- a/drivers/gpio/gpio-brcmstb.c +++ b/drivers/gpio/gpio-brcmstb.c @@ -513,6 +513,7 @@ static int brcmstb_gpio_irq_setup(struct platform_device *pdev, out_free_domain: irq_domain_remove(priv->irq_domain); + priv->irq_domain = NULL; return err; } diff --git a/drivers/gpio/gpio-mpc8xxx.c b/drivers/gpio/gpio-mpc8xxx.c index 7b20ca4d7367..312250deb763 100644 --- a/drivers/gpio/gpio-mpc8xxx.c +++ b/drivers/gpio/gpio-mpc8xxx.c @@ -319,6 +319,14 @@ static const struct of_device_id mpc8xxx_gpio_ids[] = { {} }; +static void mpc8xxx_irq_domain_remove(void *data) +{ + struct mpc8xxx_gpio_chip *mpc8xxx_gc = data; + + if (mpc8xxx_gc->irq) + irq_domain_remove(mpc8xxx_gc->irq); +} + static int mpc8xxx_probe(struct platform_device *pdev) { const struct mpc8xxx_gpio_devtype *devtype = NULL; @@ -405,6 +413,11 @@ static int mpc8xxx_probe(struct platform_device *pdev) mpc8xxx_gc->regs + GPIO_DIR); } + /* GPIO chip cleanup still needs the IRQ domain. */ + ret = devm_add_action_or_reset(dev, mpc8xxx_irq_domain_remove, mpc8xxx_gc); + if (ret) + return ret; + ret = devm_gpiochip_add_data(dev, gc, mpc8xxx_gc); if (ret) { dev_err(dev, @@ -437,7 +450,7 @@ static int mpc8xxx_probe(struct platform_device *pdev) if (ret) { dev_err(dev, "failed to devm_request_irq(%d), ret = %d\n", mpc8xxx_gc->irqn, ret); - goto err; + return ret; } ret = devm_device_init_wakeup(dev); @@ -445,19 +458,14 @@ static int mpc8xxx_probe(struct platform_device *pdev) return dev_err_probe(dev, ret, "Failed to init wakeup\n"); return 0; -err: - irq_domain_remove(mpc8xxx_gc->irq); - return ret; } static void mpc8xxx_remove(struct platform_device *pdev) { struct mpc8xxx_gpio_chip *mpc8xxx_gc = platform_get_drvdata(pdev); - if (mpc8xxx_gc->irq) { + if (mpc8xxx_gc->irq) irq_set_chained_handler_and_data(mpc8xxx_gc->irqn, NULL, NULL); - irq_domain_remove(mpc8xxx_gc->irq); - } } static int mpc8xxx_suspend(struct device *dev) diff --git a/drivers/gpio/gpio-mpfs.c b/drivers/gpio/gpio-mpfs.c index 0f1264f5490b..cb48368d5a4a 100644 --- a/drivers/gpio/gpio-mpfs.c +++ b/drivers/gpio/gpio-mpfs.c @@ -138,6 +138,8 @@ static int mpfs_gpio_irq_set_type(struct irq_data *data, unsigned int type) case IRQ_TYPE_LEVEL_LOW: interrupt_type = MPFS_GPIO_TYPE_INT_LEVEL_LOW; break; + default: + return -EINVAL; } regmap_update_bits(mpfs_gpio->regs, MPFS_GPIO_CTRL(gpio_index), diff --git a/drivers/gpio/gpio-mvebu.c b/drivers/gpio/gpio-mvebu.c index 579526ab7600..2591239b1956 100644 --- a/drivers/gpio/gpio-mvebu.c +++ b/drivers/gpio/gpio-mvebu.c @@ -603,6 +603,7 @@ static const struct regmap_config mvebu_gpio_regmap_config = { .reg_bits = 32, .reg_stride = 4, .val_bits = 32, + .use_raw_spinlock = true, }; static const struct regmap_config mvebu_gpio_percpu_regmap_config = { @@ -610,6 +611,7 @@ static const struct regmap_config mvebu_gpio_percpu_regmap_config = { .reg_bits = 32, .reg_stride = 4, .val_bits = 32, + .use_raw_spinlock = true, }; static const struct regmap_config mvebu_pwm_regmap_config = { diff --git a/drivers/gpio/gpio-omap.c b/drivers/gpio/gpio-omap.c index a9734b2a1d60..585c2784bb75 100644 --- a/drivers/gpio/gpio-omap.c +++ b/drivers/gpio/gpio-omap.c @@ -813,8 +813,11 @@ static int omap_gpio_request(struct gpio_chip *chip, unsigned offset) { struct gpio_bank *bank = gpiochip_get_data(chip); unsigned long flags; + int ret; - pm_runtime_get_sync(chip->parent); + ret = pm_runtime_resume_and_get(chip->parent); + if (ret < 0) + return ret; raw_spin_lock_irqsave(&bank->lock, flags); omap_enable_gpio_module(bank, offset); @@ -1459,7 +1462,13 @@ static int omap_gpio_probe(struct platform_device *pdev) platform_set_drvdata(pdev, bank); pm_runtime_enable(dev); - pm_runtime_get_sync(dev); + ret = pm_runtime_resume_and_get(dev); + if (ret < 0) { + pm_runtime_disable(dev); + if (bank->dbck_flag) + clk_unprepare(bank->dbck); + return ret; + } if (bank->is_mpuio) omap_mpuio_init(bank); diff --git a/drivers/gpio/gpio-regmap.c b/drivers/gpio/gpio-regmap.c index 2f5f45b84cc9..ac6ad56f4479 100644 --- a/drivers/gpio/gpio-regmap.c +++ b/drivers/gpio/gpio-regmap.c @@ -572,6 +572,11 @@ struct gpio_regmap *gpio_regmap_register(const struct gpio_regmap_config *config err_remove_gpiochip: gpiochip_remove(chip); + +#ifdef CONFIG_REGMAP_IRQ + if (gpio->irq_chip_data) + regmap_del_irq_chip(gpio->regmap_irq_line, gpio->irq_chip_data); +#endif err_free_bitmap_output: bitmap_free(gpio->fixed_direction_output); err_free_bitmap_dirmask: diff --git a/drivers/gpio/gpio-rockchip.c b/drivers/gpio/gpio-rockchip.c index 77b239a9a601..714604c11d78 100644 --- a/drivers/gpio/gpio-rockchip.c +++ b/drivers/gpio/gpio-rockchip.c @@ -201,20 +201,25 @@ static int rockchip_gpio_set_debounce(struct gpio_chip *gc, { struct rockchip_pin_bank *bank = gpiochip_get_data(gc); const struct rockchip_gpio_regs *reg = bank->gpio_regs; - unsigned long flags, div_reg, freq, max_debounce; + unsigned long flags, div_reg, freq; bool div_debounce_support; unsigned int cur_div_reg; - u64 div; + u64 div, max_debounce; if (bank->gpio_type == GPIO_TYPE_V2 && !IS_ERR(bank->db_clk)) { div_debounce_support = true; freq = clk_get_rate(bank->db_clk); - max_debounce = (GENMASK(23, 0) + 1) * 2 * 1000000 / freq; + if (!freq) + return -EINVAL; + + div = (u64)(GENMASK(23, 0) + 1) * 2 * USEC_PER_SEC; + max_debounce = div64_u64(div, freq); if (debounce > max_debounce) return -EINVAL; - div = debounce * freq; - div_reg = DIV_ROUND_CLOSEST_ULL(div, 2 * USEC_PER_SEC) - 1; + div = (u64)debounce * freq; + div_reg = DIV_ROUND_CLOSEST_ULL(div, 2 * USEC_PER_SEC); + div_reg = div_reg ? div_reg - 1 : 0; } else { div_debounce_support = false; } diff --git a/drivers/gpio/gpio-sa1100.c b/drivers/gpio/gpio-sa1100.c index e4f3bf949b87..1916200ebbd5 100644 --- a/drivers/gpio/gpio-sa1100.c +++ b/drivers/gpio/gpio-sa1100.c @@ -8,6 +8,7 @@ #include <linux/init.h> #include <linux/module.h> #include <linux/io.h> +#include <linux/printk.h> #include <linux/syscore_ops.h> #include <soc/sa1100/pwer.h> #include <mach/hardware.h> @@ -322,7 +323,6 @@ static const int sa1100_gpio_irqs[] __initconst = { void __init sa1100_init_gpio(void) { struct sa1100_gpio_chip *sgc = &sa1100_gpio_chip; - struct gpio_chip *gc = &sgc->chip; int i; /* clear all GPIO edge detects */ @@ -330,10 +330,6 @@ void __init sa1100_init_gpio(void) writel_relaxed(0, sgc->membase + R_GRER); writel_relaxed(-1, sgc->membase + R_GEDR); - software_node_register(&sa1100_gpiochip_node); - gc->fwnode = software_node_fwnode(&sa1100_gpiochip_node); - gpiochip_add_data(gc, NULL); - sa1100_gpio_irqdomain = irq_domain_create_simple(NULL, 28, IRQ_GPIO0, &sa1100_gpio_irqdomain_ops, sgc); @@ -342,3 +338,29 @@ void __init sa1100_init_gpio(void) irq_set_chained_handler_and_data(sa1100_gpio_irqs[i], sa1100_gpio_handler, sgc); } + +static int __init sa1100_gpio_init_chip(void) +{ + struct gpio_chip *gc = &sa1100_gpio_chip.chip; + int error; + + error = software_node_register(&sa1100_gpiochip_node); + if (error) { + pr_err("failed to register sa1100 gpiochip software node: %d\n", + error); + return error; + } + + gc->fwnode = software_node_fwnode(&sa1100_gpiochip_node); + + error = gpiochip_add_data(gc, NULL); + if (error) { + pr_err("failed to add sa1100 gpiochip: %d\n", error); + gc->fwnode = NULL; + software_node_unregister(&sa1100_gpiochip_node); + return error; + } + + return 0; +} +postcore_initcall(sa1100_gpio_init_chip); diff --git a/drivers/gpio/gpio-shared-proxy.c b/drivers/gpio/gpio-shared-proxy.c index 81a841a94096..80412bd4ef25 100644 --- a/drivers/gpio/gpio-shared-proxy.c +++ b/drivers/gpio/gpio-shared-proxy.c @@ -21,9 +21,37 @@ struct gpio_shared_proxy_data { struct gpio_chip gc; struct gpio_shared_desc *shared_desc; struct device *dev; + bool configured; bool voted_change; }; +/* + * A proxy may (re)initialize the line - set its direction and reset the + * default value and the vote tally - only while no other proxy has set the + * direction or voted for a value. Requesting the line is not enough: consumers + * may request concurrently, so counting requests lets every one of them + * conclude that it is not first. + */ +static bool gpio_shared_proxy_may_init(struct gpio_shared_proxy_data *proxy) +{ + unsigned int cfgcnt = proxy->shared_desc->cfgcnt; + + lockdep_assert_held(&proxy->shared_desc->mutex); + + return !cfgcnt || (cfgcnt == 1 && proxy->configured); +} + +static void gpio_shared_proxy_mark_configured(struct gpio_shared_proxy_data *proxy) +{ + lockdep_assert_held(&proxy->shared_desc->mutex); + + if (proxy->configured) + return; + + proxy->configured = true; + proxy->shared_desc->cfgcnt++; +} + static int gpio_shared_proxy_set_unlocked(struct gpio_shared_proxy_data *proxy, int value) { @@ -57,9 +85,16 @@ gpio_shared_proxy_set_unlocked(struct gpio_shared_proxy_data *proxy, int value) } /* Desired value is the default. */ - if (!proxy->voted_change) - /* We didn't vote for change previously, nothing to do. */ + if (!proxy->voted_change) { + /* + * With no votes outstanding the line should be at the + * default, but a GPIOD_ASIS line may have been left at the + * opposite value. Drive it there. + */ + if (!shared_desc->votecnt) + ret = gpiod_set_value_cansleep(desc, shared_desc->def_val); goto out; + } /* We previously voted for change. */ if (shared_desc->votecnt == 1) { @@ -110,13 +145,22 @@ static void gpio_shared_proxy_free(struct gpio_chip *gc, unsigned int offset) if (proxy->voted_change) { ret = gpio_shared_proxy_set_unlocked(proxy, shared_desc->def_val); - if (ret) + if (ret) { dev_err(proxy->dev, "Failed to unset the shared GPIO value on release: %d\n", ret); + /* The consumer is going away regardless, drop its vote */ + shared_desc->votecnt--; + proxy->voted_change = false; + } } proxy->shared_desc->usecnt--; + if (proxy->configured) { + proxy->configured = false; + shared_desc->cfgcnt--; + } + dev_dbg(proxy->dev, "Shared GPIO freed, number of users: %u\n", proxy->shared_desc->usecnt); } @@ -131,7 +175,7 @@ static int gpio_shared_proxy_set_config(struct gpio_chip *gc, guard(mutex)(&shared_desc->mutex); - if (shared_desc->usecnt > 1) { + if (!gpio_shared_proxy_may_init(proxy)) { if (shared_desc->cfg != cfg) { dev_dbg(proxy->dev, "Shared GPIO's configuration already set, accepting changes but users may conflict!!\n"); @@ -155,15 +199,24 @@ static int gpio_shared_proxy_direction_input(struct gpio_chip *gc, struct gpio_shared_proxy_data *proxy = gpiochip_get_data(gc); struct gpio_shared_desc *shared_desc = proxy->shared_desc; struct gpio_desc *desc = shared_desc->desc; - int dir; + int ret, dir; guard(mutex)(&shared_desc->mutex); - if (shared_desc->usecnt == 1) { + if (gpio_shared_proxy_may_init(proxy)) { dev_dbg(proxy->dev, - "Only one user of this shared GPIO, allowing to set direction to input\n"); + "No other user configured this shared GPIO, allowing to set direction to input\n"); - return gpiod_direction_input(desc); + ret = gpiod_direction_input(desc); + if (ret) + return ret; + + /* An input carries no value, drop any vote this proxy cast */ + shared_desc->votecnt = 0; + proxy->voted_change = false; + gpio_shared_proxy_mark_configured(proxy); + + return 0; } dir = gpiod_get_direction(desc); @@ -176,6 +229,8 @@ static int gpio_shared_proxy_direction_input(struct gpio_chip *gc, return -EPERM; } + gpio_shared_proxy_mark_configured(proxy); + return 0; } @@ -189,18 +244,20 @@ static int gpio_shared_proxy_direction_output(struct gpio_chip *gc, guard(mutex)(&shared_desc->mutex); - if (shared_desc->usecnt == 1) { + if (gpio_shared_proxy_may_init(proxy)) { dev_dbg(proxy->dev, - "Only one user of this shared GPIO, allowing to set direction to output with value '%s'\n", + "No other user configured this shared GPIO, allowing to set direction to output with value '%s'\n", str_high_low(value)); ret = gpiod_direction_output(desc, value); if (ret) return ret; + /* Only this proxy can have voted, so the tally is ours to reset */ shared_desc->def_val = value; shared_desc->votecnt = 0; proxy->voted_change = false; + gpio_shared_proxy_mark_configured(proxy); return 0; } @@ -215,7 +272,13 @@ static int gpio_shared_proxy_direction_output(struct gpio_chip *gc, return -EPERM; } - return gpio_shared_proxy_set_unlocked(proxy, value); + ret = gpio_shared_proxy_set_unlocked(proxy, value); + if (ret) + return ret; + + gpio_shared_proxy_mark_configured(proxy); + + return 0; } static int gpio_shared_proxy_get_cansleep(struct gpio_chip *gc, @@ -230,10 +293,21 @@ static int gpio_shared_proxy_set_cansleep(struct gpio_chip *gc, unsigned int offset, int value) { struct gpio_shared_proxy_data *proxy = gpiochip_get_data(gc); + int ret; guard(mutex)(&proxy->shared_desc->mutex); - return gpio_shared_proxy_set_unlocked(proxy, value); + /* + * A GPIOD_ASIS consumer may vote without ever setting the direction; + * count it as configured so a later user can't reset its vote. + */ + ret = gpio_shared_proxy_set_unlocked(proxy, value); + if (ret) + return ret; + + gpio_shared_proxy_mark_configured(proxy); + + return 0; } static int gpio_shared_proxy_get_direction(struct gpio_chip *gc, diff --git a/drivers/gpio/gpio-sodaville.c b/drivers/gpio/gpio-sodaville.c index c1eac5d5dbce..a160bbbe3a41 100644 --- a/drivers/gpio/gpio-sodaville.c +++ b/drivers/gpio/gpio-sodaville.c @@ -166,9 +166,12 @@ static int sdv_register_irqsupport(struct sdv_gpio_chip_data *sd, ct->chip.irq_eoi = irq_gc_eoi; ct->chip.irq_set_type = sdv_gpio_pub_set_type; - irq_setup_generic_chip(sd->gc, IRQ_MSK(SDV_NUM_PUB_GPIOS), - IRQ_GC_INIT_MASK_CACHE, IRQ_NOREQUEST, - IRQ_LEVEL | IRQ_NOPROBE); + ret = devm_irq_setup_generic_chip(&pdev->dev, sd->gc, + IRQ_MSK(SDV_NUM_PUB_GPIOS), + IRQ_GC_INIT_MASK_CACHE, IRQ_NOREQUEST, + IRQ_LEVEL | IRQ_NOPROBE); + if (ret) + return ret; sd->id = irq_domain_create_legacy(dev_fwnode(&pdev->dev), SDV_NUM_PUB_GPIOS, sd->irq_base, 0, &irq_domain_sdv_ops, sd); diff --git a/drivers/gpio/gpio-virtuser.c b/drivers/gpio/gpio-virtuser.c index e05d255b7eb2..5bf5d891c441 100644 --- a/drivers/gpio/gpio-virtuser.c +++ b/drivers/gpio/gpio-virtuser.c @@ -55,9 +55,9 @@ struct gpio_virtuser_line_array_data { struct gpio_virtuser_line_data { struct gpio_virtuser_attr_data ad; char consumer[GPIO_VIRTUSER_NAME_BUF_LEN]; - struct mutex consumer_lock; + struct mutex lock; unsigned int debounce; - atomic_t irq; + int irq; atomic_t irq_count; }; @@ -607,7 +607,7 @@ static ssize_t gpio_virtuser_consumer_read(struct file *file, memset(buf, 0x0, sizeof(buf)); - scoped_guard(mutex, &data->consumer_lock) + scoped_guard(mutex, &data->lock) ret = snprintf(buf, sizeof(buf), "%s\n", data->consumer); return simple_read_from_buffer(user_buf, size, ppos, buf, ret); @@ -635,7 +635,7 @@ static ssize_t gpio_virtuser_consumer_write(struct file *file, if (ret) return ret; - scoped_guard(mutex, &data->consumer_lock) + scoped_guard(mutex, &data->lock) strscpy(data->consumer, buf, sizeof(data->consumer)); return count; @@ -675,7 +675,12 @@ static int gpio_virtuser_interrupts_set(void *data, u64 val) if (val > 1) return -EINVAL; + guard(mutex)(&ld->lock); + if (val) { + if (ld->irq >= 0) + return -EBUSY; + irq = gpiod_to_irq(ld->ad.desc); if (irq < 0) return irq; @@ -689,11 +694,13 @@ static int gpio_virtuser_interrupts_set(void *data, u64 val) if (ret) return ret; - atomic_set(&ld->irq, irq); + ld->irq = irq; } else { - irq = atomic_xchg(&ld->irq, 0); - if (irq) - free_irq(irq, ld); + if (ld->irq < 0) + return -EBUSY; + + free_irq(ld->irq, ld); + ld->irq = -1; } return 0; @@ -793,6 +800,14 @@ static int gpio_virtuser_dbgfs_init_line_array_attrs(struct device *dev, data->ad.dbgfs_dir, data); } +static void gpio_virtuser_free_irq(void *data) +{ + struct gpio_virtuser_line_data *ld = data; + + if (ld->irq >= 0) + free_irq(ld->irq, ld); +} + static int gpio_virtuser_dbgfs_init_line_attrs(struct device *dev, struct gpio_desc *desc, const char *id, @@ -809,14 +824,18 @@ static int gpio_virtuser_dbgfs_init_line_attrs(struct device *dev, data->ad.desc = desc; strscpy(data->consumer, id); - atomic_set(&data->irq, 0); + data->irq = -1; atomic_set(&data->irq_count, 0); + ret = devm_add_action_or_reset(dev, gpio_virtuser_free_irq, data); + if (ret) + return ret; + name = devm_kasprintf(dev, GFP_KERNEL, "gpiod:%s:%u", id, index); if (!name) return -ENOMEM; - ret = devm_mutex_init(dev, &data->consumer_lock); + ret = devm_mutex_init(dev, &data->lock); if (ret) return ret; @@ -927,38 +946,50 @@ static int gpio_virtuser_probe(struct platform_device *pdev) "Failed to get the IDs of GPIOs to request\n"); dbgfs_entry = debugfs_create_dir(dev_name(dev), gpio_virtuser_dbg_root); - ret = devm_add_action_or_reset(dev, gpio_virtuser_debugfs_remove, - dbgfs_entry); - if (ret) - return ret; for (i = 0; i < num_ids; i++) { descs = devm_gpiod_get_array(dev, ids[i], GPIOD_ASIS); - if (IS_ERR(descs)) - return dev_err_probe(dev, PTR_ERR(descs), - "Failed to request the '%s' GPIOs\n", - ids[i]); + if (IS_ERR(descs)) { + ret = dev_err_probe(dev, PTR_ERR(descs), + "Failed to request the '%s' GPIOs\n", + ids[i]); + goto err_remove_debugfs; + } ret = gpio_virtuser_dbgfs_init_line_array_attrs(dev, descs, ids[i], dbgfs_entry); - if (ret) - return dev_err_probe(dev, ret, - "Failed to setup the debugfs array interface for the '%s' GPIOs\n", - ids[i]); + if (ret) { + dev_err_probe(dev, ret, + "Failed to setup the debugfs array interface for the '%s' GPIOs\n", + ids[i]); + goto err_remove_debugfs; + } for (j = 0; j < descs->ndescs; j++) { ret = gpio_virtuser_dbgfs_init_line_attrs(dev, descs->desc[j], ids[i], j, dbgfs_entry); - if (ret) - return dev_err_probe(dev, ret, - "Failed to setup the debugfs line interface for the '%s' GPIOs\n", - ids[i]); + if (ret) { + dev_err_probe(dev, ret, + "Failed to setup the debugfs line interface for the '%s' GPIOs\n", + ids[i]); + goto err_remove_debugfs; + } } } - return 0; + /* + * The debugfs files point to the devres-managed line data allocated + * above. Register the removal last so that it runs first on unbind, + * before any of that data is released. + */ + return devm_add_action_or_reset(dev, gpio_virtuser_debugfs_remove, + dbgfs_entry); + +err_remove_debugfs: + debugfs_remove_recursive(dbgfs_entry); + return ret; } static const struct of_device_id gpio_virtuser_of_match[] = { diff --git a/drivers/gpio/gpiolib-of.c b/drivers/gpio/gpiolib-of.c index f36e4b171fa7..8f8454d59604 100644 --- a/drivers/gpio/gpiolib-of.c +++ b/drivers/gpio/gpiolib-of.c @@ -725,7 +725,7 @@ int of_gpiochip_get_lflags(struct gpio_chip *chip, struct fwnode_reference_args *gpiospec, unsigned long *lflags) { - enum of_gpio_flags xlate_flags; + enum of_gpio_flags xlate_flags = 0; struct of_phandle_args args; struct gpio_desc *desc; diff --git a/drivers/gpio/gpiolib-of.h b/drivers/gpio/gpiolib-of.h index 218cfe5bc4ac..9ca540d93f93 100644 --- a/drivers/gpio/gpiolib-of.h +++ b/drivers/gpio/gpiolib-of.h @@ -46,7 +46,7 @@ static inline bool of_gpiochip_instance_match(struct gpio_chip *gc, static inline int of_gpio_count(const struct fwnode_handle *fwnode, const char *con_id) { - return 0; + return -ENOENT; } static inline int of_gpiochip_get_lflags(struct gpio_chip *chip, struct fwnode_reference_args *gpiospec, diff --git a/drivers/gpio/gpiolib-shared.c b/drivers/gpio/gpiolib-shared.c index 8c9ac9d93304..edb04a5bb987 100644 --- a/drivers/gpio/gpiolib-shared.c +++ b/drivers/gpio/gpiolib-shared.c @@ -635,20 +635,20 @@ static void gpio_shared_release(struct kref *kref) container_of(kref, struct gpio_shared_entry, ref); struct gpio_shared_desc *shared_desc; - guard(mutex)(&entry->lock); - shared_desc = entry->shared_desc; gpio_device_put(shared_desc->desc->gdev); mutex_destroy(&shared_desc->mutex); kfree(shared_desc); entry->shared_desc = NULL; + + mutex_unlock(&entry->lock); } static void gpiod_shared_put(void *data) { struct gpio_shared_entry *entry = data; - kref_put(&entry->ref, gpio_shared_release); + kref_put_mutex(&entry->ref, gpio_shared_release, &entry->lock); } static struct gpio_shared_desc * diff --git a/drivers/gpio/gpiolib-shared.h b/drivers/gpio/gpiolib-shared.h index 618756f6c6aa..ae10506b7029 100644 --- a/drivers/gpio/gpiolib-shared.h +++ b/drivers/gpio/gpiolib-shared.h @@ -41,6 +41,7 @@ struct gpio_shared_desc { struct gpio_desc *desc; unsigned long cfg; unsigned int usecnt; + unsigned int cfgcnt; unsigned int votecnt; int def_val; struct mutex mutex; /* serializes all proxy operations on this descriptor */ diff --git a/drivers/gpio/gpiolib.c b/drivers/gpio/gpiolib.c index 848348f8f1ef..033c6fce4fc8 100644 --- a/drivers/gpio/gpiolib.c +++ b/drivers/gpio/gpiolib.c @@ -154,9 +154,12 @@ static int desc_set_label(struct gpio_desc *desc, const char *label) memcpy(new->str, label, len); } - old = rcu_replace_pointer(desc->label, new, 1); - if (old) - call_srcu(&desc->gdev->desc_srcu, &old->rh, desc_free_label); + scoped_guard(spinlock, &desc->gdev->desc_lock) { + old = rcu_replace_pointer(desc->label, new, + lockdep_is_held(&desc->gdev->desc_lock)); + if (old) + call_srcu(&desc->gdev->desc_srcu, &old->rh, desc_free_label); + } return 0; } @@ -924,7 +927,8 @@ static const struct device_type gpio_dev_type = { /* * An initial reference count has been held in gpiochip_add_data_with_key(). - * The caller should drop the reference via gpio_device_put() on errors. + * A caller that tears the chip down on errors must drop the reference via + * gpio_device_put(). */ static int gpiochip_setup_dev(struct gpio_chip *gc) { @@ -975,7 +979,6 @@ int gpiochip_add_hog(struct gpio_chip *gc, struct fwnode_handle *fwnode) */ u32 cells = 2; - lflags = GPIO_LOOKUP_FLAGS_DEFAULT; dflags = GPIOD_ASIS; name = NULL; @@ -986,6 +989,8 @@ int gpiochip_add_hog(struct gpio_chip *gc, struct fwnode_handle *fwnode) ret = fwnode_property_read_u32(gc_node, "#gpio-cells", &cells); if (ret && is_of_node(fwnode)) return ret; + if (cells < 1 || cells > NR_FWNODE_REFERENCE_ARGS) + return -EINVAL; if (argc % cells) return -EINVAL; @@ -1014,6 +1019,8 @@ int gpiochip_add_hog(struct gpio_chip *gc, struct fwnode_handle *fwnode) fwnode_property_read_string(fwnode, "line-name", &name); for (unsigned int i = 0; i < num_hogs; i++) { + lflags = GPIO_LOOKUP_FLAGS_DEFAULT; + if (is_of_node(fwnode)) { /* * OF-nodes need some additional special handling for @@ -1039,9 +1046,10 @@ int gpiochip_add_hog(struct gpio_chip *gc, struct fwnode_handle *fwnode) } else { /* * GPIO_ACTIVE_LOW is currently the only lookup flag - * supported for non-OF firmware nodes. + * supported for non-OF firmware nodes and it must live + * in the second cell. */ - if (gpios[i * cells + 1]) + if (cells > 1 && gpios[i * cells + 1]) lflags |= GPIO_ACTIVE_LOW; } @@ -1099,12 +1107,16 @@ static void gpiochip_setup_devs(void) continue; } + /* + * The reference taken in gpiochip_add_data_with_key() is + * dropped by gpiochip_remove(): this chip is still registered + * and its driver has not been told about the failure, so the + * reference must be kept here. + */ ret = gpiochip_setup_dev(gc); - if (ret) { - gpio_device_put(gdev); + if (ret) dev_err(&gdev->dev, "Failed to initialize gpio device (%d)\n", ret); - } } } @@ -1201,6 +1213,8 @@ int gpiochip_add_data_with_key(struct gpio_chip *gc, void *data, goto err_free_ida; rcu_assign_pointer(gdev->chip, gc); + spin_lock_init(&gdev->desc_lock); + ret = init_srcu_struct(&gdev->desc_srcu); if (ret) goto err_cleanup_gdev_srcu; @@ -5243,21 +5257,21 @@ struct gpio_descs *__must_check gpiod_get_array(struct device *dev, if (!descs) return ERR_PTR(-ENOMEM); - for (descs->ndescs = 0; descs->ndescs < count; descs->ndescs++) { - desc = gpiod_get_index(dev, con_id, descs->ndescs, flags); + for (int i = 0; i < count; i++) { + desc = gpiod_get_index(dev, con_id, i, flags); if (IS_ERR(desc)) { gpiod_put_array(descs); return ERR_CAST(desc); } - descs->desc[descs->ndescs] = desc; + descs->desc[descs->ndescs++] = desc; gdev = gpiod_to_gpio_device(desc); /* * If pin hardware number of array member 0 is also 0, select * its chip as a candidate for fast bitmap processing path. */ - if (descs->ndescs == 0 && gpiod_hwgpio(desc) == 0) { + if (i == 0 && gpiod_hwgpio(desc) == 0) { struct gpio_descs *array; bitmap_size = BITS_TO_LONGS(gdev->ngpio > count ? @@ -5282,10 +5296,8 @@ struct gpio_descs *__must_check gpiod_get_array(struct device *dev, array_info->desc = descs->desc; array_info->size = count; array_info->gdev = gdev; - bitmap_set(array_info->get_mask, descs->ndescs, - count - descs->ndescs); - bitmap_set(array_info->set_mask, descs->ndescs, - count - descs->ndescs); + bitmap_set(array_info->get_mask, 0, count); + bitmap_set(array_info->set_mask, 0, count); descs->info = array_info; } @@ -5295,38 +5307,35 @@ struct gpio_descs *__must_check gpiod_get_array(struct device *dev, /* Unmark array members which don't belong to the 'fast' chip */ if (array_info->gdev != gdev) { - __clear_bit(descs->ndescs, array_info->get_mask); - __clear_bit(descs->ndescs, array_info->set_mask); + __clear_bit(i, array_info->get_mask); + __clear_bit(i, array_info->set_mask); } /* * Detect array members which belong to the 'fast' chip * but their pins are not in hardware order. */ - else if (gpiod_hwgpio(desc) != descs->ndescs) { + else if (gpiod_hwgpio(desc) != i) { /* * Don't use fast path if all array members processed so * far belong to the same chip as this one but its pin * hardware number is different from its array index. */ - if (bitmap_full(array_info->get_mask, descs->ndescs)) { + if (bitmap_full(array_info->get_mask, i)) { + descs->info = NULL; array_info = NULL; } else { - __clear_bit(descs->ndescs, - array_info->get_mask); - __clear_bit(descs->ndescs, - array_info->set_mask); + __clear_bit(i, array_info->get_mask); + __clear_bit(i, array_info->set_mask); } } else { dflags = READ_ONCE(desc->flags); /* Exclude open drain or open source from fast output */ if (test_bit(GPIOD_FLAG_OPEN_DRAIN, &dflags) || test_bit(GPIOD_FLAG_OPEN_SOURCE, &dflags)) - __clear_bit(descs->ndescs, - array_info->set_mask); + __clear_bit(i, array_info->set_mask); /* Identify 'fast' pins which require invertion */ if (gpiod_is_active_low(desc)) - __set_bit(descs->ndescs, - array_info->invert_mask); + __set_bit(i, array_info->invert_mask); } } if (array_info) diff --git a/drivers/gpio/gpiolib.h b/drivers/gpio/gpiolib.h index 650a702741df..8dd8ea747f8a 100644 --- a/drivers/gpio/gpiolib.h +++ b/drivers/gpio/gpiolib.h @@ -37,6 +37,7 @@ struct fwnode_handle; * @valid_mask: If not %NULL, holds bitmask of GPIOs which are valid to be * used from the chip. * @desc_srcu: ensures consistent state of GPIO descriptors exposed to users + * @desc_lock: synchronizes the updates to descriptor labels * @ngpio: the number of GPIO lines on this GPIO device, equal to the size * of the @descs array. * @can_sleep: indicate whether the GPIO chip driver's callbacks can sleep @@ -71,6 +72,7 @@ struct gpio_device { struct gpio_desc *descs; unsigned long *valid_mask; struct srcu_struct desc_srcu; + spinlock_t desc_lock; unsigned int base; u16 ngpio; bool can_sleep; diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_gem.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_gem.c index fb518667bcaa..b190b6c9adf2 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_gem.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_gem.c @@ -826,8 +826,10 @@ amdgpu_gem_va_update_vm(struct amdgpu_device *adev, /* Always update PDEs after we touched the mappings. */ r = amdgpu_vm_update_pdes(adev, vm, false); - if (r) - goto error; + +error: + if (r && r != -ERESTARTSYS) + DRM_ERROR("Couldn't update BO_VA (%d)\n", r); if ((operation == AMDGPU_VA_OP_MAP || operation == AMDGPU_VA_OP_REPLACE) && @@ -836,27 +838,27 @@ amdgpu_gem_va_update_vm(struct amdgpu_device *adev, /* * For MAP/REPLACE of non per-VM BOs we need to sync to both the * bo_va->last_pt_update and vm->last_update or otherwise we - * potentially miss the PDE updates. + * potentially miss the PDE updates or TLB invalidation. */ fence = dma_fence_unwrap_merge(vm->last_update, + vm->last_tlb_inv, bo_va->last_pt_update); - if (!fence) { - /* As fallback in OOM situations */ - dma_fence_wait(vm->last_update, false); + if (!fence) dma_fence_wait(bo_va->last_pt_update, false); - fence = dma_fence_get_stub(); - } + } else { - fence = dma_fence_get(vm->last_update); + fence = dma_fence_unwrap_merge(vm->last_update, + vm->last_tlb_inv); } - return fence; - -error: - if (r && r != -ERESTARTSYS) - DRM_ERROR("Couldn't update BO_VA (%d)\n", r); + if (!fence) { + /* As fallback in OOM situations */ + dma_fence_wait(vm->last_update, false); + dma_fence_wait(vm->last_tlb_inv, false); + fence = dma_fence_get_stub(); + } - return dma_fence_get(vm->last_update); + return fence; } int amdgpu_gem_va_ioctl(struct drm_device *dev, void *data, diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_gmc.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_gmc.c index 5d4276cd0f7d..efa0bc1e432a 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_gmc.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_gmc.c @@ -1395,6 +1395,40 @@ static ssize_t available_memory_partition_show(struct device *dev, return size; } +void amdgpu_gmc_set_requested_nps_mode(struct amdgpu_device *adev, + enum amdgpu_memory_partition mode) +{ + struct amdgpu_hive_info *hive; + + /* If device is part of hive, all devices in the hive should request the + * same mode. Hence store the requested mode in hive. + */ + hive = amdgpu_get_xgmi_hive(adev); + if (hive) { + atomic_set(&hive->requested_nps_mode, mode); + amdgpu_put_xgmi_hive(hive); + } else { + adev->gmc.requested_nps_mode = mode; + } +} + +enum amdgpu_memory_partition +amdgpu_gmc_get_requested_nps_mode(struct amdgpu_device *adev) +{ + struct amdgpu_hive_info *hive; + enum amdgpu_memory_partition mode; + + hive = amdgpu_get_xgmi_hive(adev); + if (hive) { + mode = atomic_read(&hive->requested_nps_mode); + amdgpu_put_xgmi_hive(hive); + } else { + mode = adev->gmc.requested_nps_mode; + } + + return mode; +} + static ssize_t current_memory_partition_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) @@ -1402,7 +1436,6 @@ static ssize_t current_memory_partition_store(struct device *dev, struct drm_device *ddev = dev_get_drvdata(dev); struct amdgpu_device *adev = drm_to_adev(ddev); enum amdgpu_memory_partition mode; - struct amdgpu_hive_info *hive; int i; mode = UNKNOWN_MEMORY_PARTITION_MODE; @@ -1416,23 +1449,16 @@ static ssize_t current_memory_partition_store(struct device *dev, if (mode == UNKNOWN_MEMORY_PARTITION_MODE) return -EINVAL; - if (mode == adev->gmc.gmc_funcs->query_mem_partition_mode(adev)) { + if (mode == amdgpu_gmc_get_requested_nps_mode(adev)) { dev_info( adev->dev, - "requested NPS mode is same as current NPS mode, skipping\n"); + "requested NPS mode is same as current/already requested NPS mode, skipping\n"); return count; } - /* If device is part of hive, all devices in the hive should request the - * same mode. Hence store the requested mode in hive. - */ - hive = amdgpu_get_xgmi_hive(adev); - if (hive) { - atomic_set(&hive->requested_nps_mode, mode); - amdgpu_put_xgmi_hive(hive); - } else { - adev->gmc.requested_nps_mode = mode; - } + amdgpu_gmc_set_requested_nps_mode(adev, mode); + if (mode == amdgpu_gmc_query_memory_partition(adev)) + return count; dev_info( adev->dev, diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_gmc.h b/drivers/gpu/drm/amd/amdgpu/amdgpu_gmc.h index 76e6f1f96913..89f1ee829eea 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_gmc.h +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_gmc.h @@ -484,6 +484,10 @@ enum amdgpu_memory_partition amdgpu_gmc_get_memory_partition(struct amdgpu_device *adev, u32 *supp_modes); enum amdgpu_memory_partition amdgpu_gmc_query_memory_partition(struct amdgpu_device *adev); +void amdgpu_gmc_set_requested_nps_mode(struct amdgpu_device *adev, + enum amdgpu_memory_partition mode); +enum amdgpu_memory_partition +amdgpu_gmc_get_requested_nps_mode(struct amdgpu_device *adev); int amdgpu_gmc_init_mem_ranges(struct amdgpu_device *adev); void amdgpu_gmc_init_sw_mem_ranges(struct amdgpu_device *adev, struct amdgpu_mem_partition_info *mem_ranges); diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_vce.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_vce.c index dec3c6d9b6ba..11f8fe98aac4 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_vce.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_vce.c @@ -776,6 +776,7 @@ int amdgpu_vce_ring_parse_cs(struct amdgpu_cs_parser *p, uint32_t allocated = 0; uint32_t tmp, handle = 0; uint32_t dummy = 0xffffffff; + uint32_t luma_pitch, chroma_pitch, height; uint32_t *size = &dummy; unsigned int idx; int i, r = 0; @@ -881,19 +882,19 @@ int amdgpu_vce_ring_parse_cs(struct amdgpu_cs_parser *p, goto out; } - uint32_t width, height; - width = amdgpu_ib_get_value(ib, idx + 8); - height = amdgpu_ib_get_value(ib, idx + 10); + luma_pitch = amdgpu_ib_get_value(ib, idx + 8); + chroma_pitch = amdgpu_ib_get_value(ib, idx + 9); + height = amdgpu_ib_get_value(ib, idx + 10); /* encRefYHeightInQw */ - if (width == 0 || height == 0 || - width > 4096 || height > 2304) { - DRM_ERROR("invalid VCE image size: %ux%u\n", - width, height); + if (luma_pitch == 0 || chroma_pitch == 0 || height == 0 || + luma_pitch > 4096 || chroma_pitch > 4096 || height > 2304 / 8) { + DRM_ERROR("invalid VCE ref image size: (%u %u)x%u\n", + luma_pitch, chroma_pitch, height * 8); r = -EINVAL; goto out; } - *size = width * height * 8 * 3 / 2; + *size = luma_pitch * height * 8 + chroma_pitch * height * 8 / 2; break; @@ -922,13 +923,25 @@ int amdgpu_vce_ring_parse_cs(struct amdgpu_cs_parser *p, break; case 0x03000001: /* encode */ + height = amdgpu_ib_get_value(ib, idx + 13); + luma_pitch = amdgpu_ib_get_value(ib, idx + 14); + chroma_pitch = amdgpu_ib_get_value(ib, idx + 15); + + if (luma_pitch == 0 || chroma_pitch == 0 || height == 0 || + luma_pitch > 4096 || chroma_pitch > 4096 || height > 2304) { + DRM_ERROR("invalid VCE image size: (%u %u)x%u\n", + luma_pitch, chroma_pitch, height); + r = -EINVAL; + goto out; + } + r = amdgpu_vce_cs_reloc(p, ib, idx + 10, idx + 9, - *size, 0); + luma_pitch * height, 0); if (r) goto out; r = amdgpu_vce_cs_reloc(p, ib, idx + 12, idx + 11, - *size / 3, 0); + chroma_pitch * height / 2, 0); if (r) goto out; break; diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c index a99c2ef14be9..82b9b2d5d0cf 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c @@ -534,11 +534,15 @@ static int amdgpu_vm_init_entities(struct amdgpu_device *adev, adev->vm_manager.vm_pte_scheds, adev->vm_manager.vm_pte_num_scheds, NULL); if (r) + return r; + + r = drm_sched_entity_init(&vm->delayed, DRM_SCHED_PRIORITY_NORMAL, + adev->vm_manager.vm_pte_scheds, + adev->vm_manager.vm_pte_num_scheds, NULL); + if (r) goto error; - return drm_sched_entity_init(&vm->delayed, DRM_SCHED_PRIORITY_NORMAL, - adev->vm_manager.vm_pte_scheds, - adev->vm_manager.vm_pte_num_scheds, NULL); + return 0; error: drm_sched_entity_destroy(&vm->immediate); @@ -1079,21 +1083,16 @@ static void amdgpu_vm_tlb_seq_cb(struct dma_fence *fence, */ static void amdgpu_vm_tlb_flush(struct amdgpu_vm_update_params *params, - struct dma_fence **fence, + struct dma_fence *fence, struct amdgpu_vm_tlb_seq_struct *tlb_cb) { struct amdgpu_vm *vm = params->vm; tlb_cb->vm = vm; - if (!fence || !*fence) { - amdgpu_vm_tlb_seq_cb(NULL, &tlb_cb->cb); - return; - } - - if (!dma_fence_add_callback(*fence, &tlb_cb->cb, - amdgpu_vm_tlb_seq_cb)) { - dma_fence_put(vm->last_tlb_flush); - vm->last_tlb_flush = dma_fence_get(*fence); + if (fence && !dma_fence_add_callback(fence, &tlb_cb->cb, + amdgpu_vm_tlb_seq_cb)) { + dma_fence_put(vm->last_seq_flush); + vm->last_seq_flush = dma_fence_get(fence); } else { amdgpu_vm_tlb_seq_cb(NULL, &tlb_cb->cb); } @@ -1103,11 +1102,12 @@ amdgpu_vm_tlb_flush(struct amdgpu_vm_update_params *params, * sort out the issues with KIQ/MES TLB invalidation timeouts. */ if (!params->unlocked && vm->need_tlb_fence) { - amdgpu_vm_tlb_fence_create(params->adev, vm, fence); + amdgpu_vm_tlb_fence_create(params->adev, vm, fence, + &vm->last_tlb_inv); /* Makes sure no PD/PT is freed before the flush */ - dma_resv_add_fence(vm->root.bo->tbo.base.resv, *fence, - DMA_RESV_USAGE_BOOKKEEP); + dma_resv_add_fence(vm->root.bo->tbo.base.resv, + vm->last_tlb_inv, DMA_RESV_USAGE_BOOKKEEP); } } @@ -1256,7 +1256,7 @@ int amdgpu_vm_update_range(struct amdgpu_device *adev, struct amdgpu_vm *vm, goto error_free; if (params.needs_flush) { - amdgpu_vm_tlb_flush(¶ms, fence, tlb_cb); + amdgpu_vm_tlb_flush(¶ms, *fence, tlb_cb); tlb_cb = NULL; } @@ -2655,7 +2655,8 @@ int amdgpu_vm_init(struct amdgpu_device *adev, struct amdgpu_vm *vm, vm->last_update = dma_fence_get_stub(); vm->last_unlocked = dma_fence_get_stub(); - vm->last_tlb_flush = dma_fence_get_stub(); + vm->last_seq_flush = dma_fence_get_stub(); + vm->last_tlb_inv = dma_fence_get_stub(); vm->generation = amdgpu_vm_generation(adev, NULL); mutex_init(&vm->eviction_lock); @@ -2699,7 +2700,8 @@ error_free_root: error_free_delayed: dma_fence_put(vm->last_update); - dma_fence_put(vm->last_tlb_flush); + dma_fence_put(vm->last_seq_flush); + dma_fence_put(vm->last_tlb_inv); dma_fence_put(vm->last_unlocked); ttm_lru_bulk_move_fini(&adev->mman.bdev, &vm->lru_bulk_move); amdgpu_vm_fini_entities(vm); @@ -2840,11 +2842,12 @@ void amdgpu_vm_fini(struct amdgpu_device *adev, struct amdgpu_vm *vm) amdgpu_bo_reserve(root, true); dma_fence_wait(vm->last_unlocked, false); dma_fence_put(vm->last_unlocked); - dma_fence_wait(vm->last_tlb_flush, false); + dma_fence_wait(vm->last_seq_flush, false); /* Make sure that all fence callbacks have completed */ - dma_fence_lock_irqsave(vm->last_tlb_flush, flags); - dma_fence_unlock_irqrestore(vm->last_tlb_flush, flags); - dma_fence_put(vm->last_tlb_flush); + dma_fence_lock_irqsave(vm->last_seq_flush, flags); + dma_fence_unlock_irqrestore(vm->last_seq_flush, flags); + dma_fence_put(vm->last_seq_flush); + dma_fence_put(vm->last_tlb_inv); list_for_each_entry_safe(mapping, tmp, &vm->freed, list) { if (mapping->flags & AMDGPU_VM_PAGE_PRT && prt_fini_needed) { diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.h b/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.h index 8e478d3bda1a..713a597027bb 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.h +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.h @@ -328,11 +328,12 @@ struct amdgpu_vm { struct drm_sched_entity immediate; struct drm_sched_entity delayed; - /* Last finished delayed update */ + /* Last TLB seq/fence */ atomic64_t tlb_seq; - struct dma_fence *last_tlb_flush; + struct dma_fence *last_seq_flush; atomic64_t kfd_last_flushed_seq; uint64_t tlb_fence_context; + struct dma_fence *last_tlb_inv; /* How many times we had to re-generate the page tables */ uint64_t generation; @@ -561,7 +562,7 @@ static inline uint64_t amdgpu_vm_tlb_seq(struct amdgpu_vm *vm) * sure that the dma_fence structure isn't freed up. */ rcu_read_lock(); - lock = dma_fence_spinlock(vm->last_tlb_flush); + lock = dma_fence_spinlock(vm->last_seq_flush); rcu_read_unlock(); spin_lock_irqsave(lock, flags); @@ -576,9 +577,9 @@ void amdgpu_vm_update_fault_cache(struct amdgpu_device *adev, uint32_t status, unsigned int vmhub); void amdgpu_vm_tlb_fence_create(struct amdgpu_device *adev, - struct amdgpu_vm *vm, - struct dma_fence **fence); - + struct amdgpu_vm *vm, + struct dma_fence *dep, + struct dma_fence **fence); void amdgpu_vm_print_task_info(struct amdgpu_device *adev, struct amdgpu_task_info *task_info); diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_vm_tlb_fence.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_vm_tlb_fence.c index b0002c898386..180e02de73e9 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_vm_tlb_fence.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_vm_tlb_fence.c @@ -75,7 +75,19 @@ static const struct dma_fence_ops amdgpu_tlb_fence_ops = { .get_timeline_name = amdgpu_tlb_fence_get_timeline_name }; -void amdgpu_vm_tlb_fence_create(struct amdgpu_device *adev, struct amdgpu_vm *vm, +/** + * amdgpu_vm_tlb_fence_create - create a TLB invalidation fence + * @adev: the amdgpu device + * @vm: the vm to use + * @dep: the dependency to wait for + * @fence: the resulting fence + * + * Creates a TLB invalidation fence which signals when all the VMIDs assigned to + * the PASID of the VM are invalidated. + */ +void amdgpu_vm_tlb_fence_create(struct amdgpu_device *adev, + struct amdgpu_vm *vm, + struct dma_fence *dep, struct dma_fence **fence) { struct amdgpu_tlb_fence *f; @@ -86,16 +98,15 @@ void amdgpu_vm_tlb_fence_create(struct amdgpu_device *adev, struct amdgpu_vm *vm * We can't fail since the PDEs and PTEs are already updated, so * just block for the dependency and execute the TLB flush */ - if (*fence) - dma_fence_wait(*fence, false); + if (dep) + dma_fence_wait(dep, false); amdgpu_gmc_flush_gpu_tlb_pasid(adev, vm->pasid, 2, true, 0); - *fence = dma_fence_get_stub(); return; } f->adev = adev; - f->dependency = *fence; + f->dependency = dma_fence_get(dep); f->pasid = vm->pasid; INIT_WORK(&f->work, amdgpu_tlb_fence_work); spin_lock_init(&f->lock); @@ -107,5 +118,6 @@ void amdgpu_vm_tlb_fence_create(struct amdgpu_device *adev, struct amdgpu_vm *vm dma_fence_get(&f->base); schedule_work(&f->work); + dma_fence_put(*fence); *fence = &f->base; } diff --git a/drivers/gpu/drm/amd/amdgpu/gfx_v11_0.c b/drivers/gpu/drm/amd/amdgpu/gfx_v11_0.c index d5f428ac19bf..11388b666037 100644 --- a/drivers/gpu/drm/amd/amdgpu/gfx_v11_0.c +++ b/drivers/gpu/drm/amd/amdgpu/gfx_v11_0.c @@ -691,6 +691,7 @@ static void gfx_v11_0_free_microcode(struct amdgpu_device *adev) amdgpu_ucode_release(&adev->gfx.me_fw); amdgpu_ucode_release(&adev->gfx.rlc_fw); amdgpu_ucode_release(&adev->gfx.mec_fw); + amdgpu_ucode_release(&adev->gfx.imu_fw); kfree(adev->gfx.rlc.register_list_format); } diff --git a/drivers/gpu/drm/amd/amdgpu/gfx_v12_0.c b/drivers/gpu/drm/amd/amdgpu/gfx_v12_0.c index 95f2dbba6585..20ec229ba967 100644 --- a/drivers/gpu/drm/amd/amdgpu/gfx_v12_0.c +++ b/drivers/gpu/drm/amd/amdgpu/gfx_v12_0.c @@ -563,6 +563,7 @@ static void gfx_v12_0_free_microcode(struct amdgpu_device *adev) amdgpu_ucode_release(&adev->gfx.me_fw); amdgpu_ucode_release(&adev->gfx.rlc_fw); amdgpu_ucode_release(&adev->gfx.mec_fw); + amdgpu_ucode_release(&adev->gfx.imu_fw); kfree(adev->gfx.rlc.register_list_format); } diff --git a/drivers/gpu/drm/amd/amdgpu/gfx_v12_1.c b/drivers/gpu/drm/amd/amdgpu/gfx_v12_1.c index 4498e253846f..58f5ff506dc4 100644 --- a/drivers/gpu/drm/amd/amdgpu/gfx_v12_1.c +++ b/drivers/gpu/drm/amd/amdgpu/gfx_v12_1.c @@ -349,6 +349,7 @@ static void gfx_v12_1_free_microcode(struct amdgpu_device *adev) { amdgpu_ucode_release(&adev->gfx.rlc_fw); amdgpu_ucode_release(&adev->gfx.mec_fw); + amdgpu_ucode_release(&adev->gfx.imu_fw); kfree(adev->gfx.rlc.register_list_format); } diff --git a/drivers/gpu/drm/amd/amdgpu/gmc_v9_0.c b/drivers/gpu/drm/amd/amdgpu/gmc_v9_0.c index 822681635a65..1a8ec24c61d2 100644 --- a/drivers/gpu/drm/amd/amdgpu/gmc_v9_0.c +++ b/drivers/gpu/drm/amd/amdgpu/gmc_v9_0.c @@ -1617,6 +1617,7 @@ static int gmc_v9_0_early_init(struct amdgpu_ip_block *ip_block) static int gmc_v9_0_late_init(struct amdgpu_ip_block *ip_block) { struct amdgpu_device *adev = ip_block->adev; + bool nps_switch_support; int r; r = amdgpu_gmc_allocate_vm_inv_eng(adev); @@ -1641,6 +1642,18 @@ static int gmc_v9_0_late_init(struct amdgpu_ip_block *ip_block) amdgpu_ras_reset_error_count(adev, AMDGPU_RAS_BLOCK__HDP); } + nps_switch_support = !adev->gmc.xgmi.connected_to_cpu && + (hweight32(adev->gmc.supported_nps_modes & + AMDGPU_ALL_NPS_MASK) > 1); + /* Initialize requested NPS mode to be the same as current mode */ + if (nps_switch_support) { + enum amdgpu_memory_partition mode = + amdgpu_gmc_get_requested_nps_mode(adev); + if (mode == UNKNOWN_MEMORY_PARTITION_MODE) + amdgpu_gmc_set_requested_nps_mode( + adev, amdgpu_gmc_query_memory_partition(adev)); + } + return amdgpu_irq_get(adev, &adev->gmc.vm_fault, 0); } diff --git a/drivers/gpu/drm/amd/amdgpu/soc21.c b/drivers/gpu/drm/amd/amdgpu/soc21.c index 599d47e1d38b..635f026d629c 100644 --- a/drivers/gpu/drm/amd/amdgpu/soc21.c +++ b/drivers/gpu/drm/amd/amdgpu/soc21.c @@ -599,7 +599,10 @@ static int soc21_common_early_init(struct amdgpu_ip_block *ip_block) adev->cg_flags = AMD_CG_SUPPORT_GFX_CGCG | AMD_CG_SUPPORT_GFX_CGLS | + AMD_CG_SUPPORT_GFX_MGCG | AMD_CG_SUPPORT_REPEATER_FGCG | + AMD_CG_SUPPORT_GFX_FGCG | + AMD_CG_SUPPORT_GFX_PERF_CLK | AMD_CG_SUPPORT_VCN_MGCG | AMD_CG_SUPPORT_JPEG_MGCG | AMD_CG_SUPPORT_ATHUB_MGCG | diff --git a/drivers/gpu/drm/amd/amdgpu/vce_v1_0.c b/drivers/gpu/drm/amd/amdgpu/vce_v1_0.c index 0ba9bab7c921..f8ad4688c58f 100644 --- a/drivers/gpu/drm/amd/amdgpu/vce_v1_0.c +++ b/drivers/gpu/drm/amd/amdgpu/vce_v1_0.c @@ -47,6 +47,9 @@ #define VCE_V1_0_STACK_SIZE (64 * 1024) #define VCE_V1_0_DATA_SIZE (ALIGN(7808 * (AMDGPU_MAX_VCE_HANDLES + 1), VCE_V1_0_ALIGNMENT)) #define VCE_STATUS_VCPU_REPORT_FW_LOADED_MASK 0x02 +#define VCE_STATUS_VCPU_REPORT_AUTO_BUSY_MASK 0x08 +#define VCE_STATUS_VCPU_REPORT_RB0_BUSY_MASK 0x10 +#define VCE_STATUS_VCPU_REPORT_RB1_BUSY_MASK 0x20 static void vce_v1_0_set_ring_funcs(struct amdgpu_device *adev); static void vce_v1_0_set_irq_funcs(struct amdgpu_device *adev); @@ -349,19 +352,29 @@ static int vce_v1_0_mc_resume(struct amdgpu_device *adev) * * @ip_block: amdgpu_ip_block pointer * - * Check whether VCE is busy according to VCE_STATUS. + * Check whether VCE is busy according to VCE_STATUS + * and whether the ring pointers match. + * * Also check whether the SRBM thinks VCE is busy, although - * SRBM_STATUS.VCE_BUSY seems to be bogus because it + * SRBM_STATUS2.VCE_BUSY seems to be bogus because it * appears to mirror the VCE_STATUS.VCPU_REPORT_FW_LOADED bit. */ static bool vce_v1_0_is_idle(struct amdgpu_ip_block *ip_block) { struct amdgpu_device *adev = ip_block->adev; - bool busy = - (RREG32(mmVCE_STATUS) & (VCE_STATUS__JOB_BUSY_MASK | VCE_STATUS__UENC_BUSY_MASK)) || - (RREG32(mmSRBM_STATUS2) & SRBM_STATUS2__VCE_BUSY_MASK); - return !busy; + /* Check whether the rings are busy. */ + if (RREG32(mmVCE_RB_RPTR) != RREG32(mmVCE_RB_WPTR) || + RREG32(mmVCE_RB_RPTR2) != RREG32(mmVCE_RB_WPTR2)) + return false; + + /* Check whether the VCPU is busy. */ + if (RREG32(mmVCE_STATUS) & (VCE_STATUS_VCPU_REPORT_AUTO_BUSY_MASK | + VCE_STATUS_VCPU_REPORT_RB0_BUSY_MASK | + VCE_STATUS_VCPU_REPORT_RB1_BUSY_MASK)) + return false; + + return !(RREG32(mmSRBM_STATUS2) & SRBM_STATUS2__VCE_BUSY_MASK); } static int vce_v1_0_wait_for_idle(struct amdgpu_ip_block *ip_block) diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_chardev.c b/drivers/gpu/drm/amd/amdkfd/kfd_chardev.c index d65ae53c81a5..3984b2c3bf45 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_chardev.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_chardev.c @@ -433,7 +433,7 @@ static int kfd_ioctl_create_queue(struct file *filep, struct kfd_process *p, goto err_bind_process; } - err = kfd_queue_acquire_buffers(pdd, &q_properties); + err = kfd_queue_acquire_buffers(pdd, &q_properties, false); if (err) { pr_debug("failed to acquire user queue buffers\n"); goto err_acquire_queue_buf; @@ -478,7 +478,7 @@ static int kfd_ioctl_create_queue(struct file *filep, struct kfd_process *p, err_create_queue: kfd_queue_unref_bo_vas(pdd, &q_properties); - kfd_queue_release_buffers(pdd, &q_properties); + kfd_queue_release_buffers(pdd, &q_properties, false); err_acquire_queue_buf: err_sdma_engine_id: err_bind_process: @@ -2175,7 +2175,9 @@ static int criu_checkpoint_bos(struct kfd_process *p, bo_bucket->offset = amdgpu_bo_mmap_offset(dumper_bo); for (i = 0; i < p->n_pdds; i++) { - if (amdgpu_amdkfd_bo_mapped_to_dev(p->pdds[i]->drm_priv, kgd_mem)) + /* nothing is mapped on a GPU without a VM */ + if (p->pdds[i]->drm_priv && + amdgpu_amdkfd_bo_mapped_to_dev(p->pdds[i]->drm_priv, kgd_mem)) bo_priv->mapped_gpuids[dev_idx++] = p->pdds[i]->user_gpu_id; } @@ -2861,6 +2863,8 @@ static int criu_resume(struct file *filep, goto exit; } + kfd_criu_resume_queues(target); + ret = amdgpu_amdkfd_criu_resume(target->kgd_process_info); if (ret) pr_err("amdgpu_amdkfd_criu_resume failed for %i\n", args->pid); diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_migrate.c b/drivers/gpu/drm/amd/amdkfd/kfd_migrate.c index 8b96e1fe741a..1eb92ac6eb05 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_migrate.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_migrate.c @@ -297,16 +297,26 @@ svm_migrate_copy_to_vram(struct kfd_node *node, struct svm_range *prange, amdgpu_res_first(prange->ttm_res, ttm_res_offset, npages << PAGE_SHIFT, &cursor); for (i = j = 0; (i < npages) && (mpages < migrate->cpages); i++) { - struct page *spage; + struct page *spage = migrate_pfn_to_page(migrate->src[i]); if (migrate->src[i] & MIGRATE_PFN_MIGRATE) { dst[i] = cursor.start + (j << PAGE_SHIFT); migrate->dst[i] = svm_migrate_addr_to_pfn(adev, dst[i]); - svm_migrate_get_vram_page(prange, migrate->dst[i]); - migrate->dst[i] = migrate_pfn(migrate->dst[i]); - mpages++; + /* + * A reused svm_bo page may still be held by a CPU fault. + * Reinitializing it would free it under this migration, + * so leave this page in system memory. + */ + if (page_ref_count(pfn_to_page(migrate->dst[i]))) { + dst[i] = 0; + migrate->dst[i] = 0; + spage = NULL; + } else { + svm_migrate_get_vram_page(prange, migrate->dst[i]); + migrate->dst[i] = migrate_pfn(migrate->dst[i]); + mpages++; + } } - spage = migrate_pfn_to_page(migrate->src[i]); if (spage && !is_zone_device_page(spage)) { src[i] = dma_map_page(dev, spage, 0, PAGE_SIZE, DMA_BIDIRECTIONAL); diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_priv.h b/drivers/gpu/drm/amd/amdkfd/kfd_priv.h index 288731acc928..436160549386 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_priv.h +++ b/drivers/gpu/drm/amd/amdkfd/kfd_priv.h @@ -1376,6 +1376,8 @@ int kfd_criu_restore_event(struct file *devkfd, uint8_t __user *user_priv_data, uint64_t *priv_data_offset, uint64_t max_priv_data_size); + +int kfd_criu_resume_queues(struct kfd_process *p); /* CRIU - End */ /* Queue Context Management */ @@ -1386,12 +1388,13 @@ void print_queue(struct queue *q); int kfd_queue_buffer_get(struct amdgpu_vm *vm, void __user *addr, struct amdgpu_bo **pbo, u64 expected_size); void kfd_queue_buffer_put(struct amdgpu_bo **bo); -int kfd_queue_acquire_buffers(struct kfd_process_device *pdd, struct queue_properties *properties); -int kfd_queue_release_buffers(struct kfd_process_device *pdd, struct queue_properties *properties); +int kfd_queue_acquire_buffers(struct kfd_process_device *pdd, struct queue_properties *properties, bool is_criu); +int kfd_queue_release_buffers(struct kfd_process_device *pdd, struct queue_properties *properties, bool is_criu); void kfd_queue_unref_bo_va(struct amdgpu_vm *vm, struct amdgpu_bo **bo); int kfd_queue_unref_bo_vas(struct kfd_process_device *pdd, struct queue_properties *properties); void kfd_queue_ctx_save_restore_size(struct kfd_topology_device *dev); +int kfd_queue_buffer_svm_get(struct kfd_process_device *pdd, u64 addr, u64 size); struct mqd_manager *mqd_manager_init_cik(enum KFD_MQD_TYPE type, struct kfd_node *dev); 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 4c4a3a8587f4..b68e884b1c37 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c @@ -227,7 +227,7 @@ void pqm_uninit(struct process_queue_manager *pqm) pqm->process); if (pdd) { kfd_queue_unref_bo_vas(pdd, &pqn->q->properties); - kfd_queue_release_buffers(pdd, &pqn->q->properties); + kfd_queue_release_buffers(pdd, &pqn->q->properties, false); } else { WARN_ON(!pdd); } @@ -572,7 +572,7 @@ int pqm_destroy_queue(struct process_queue_manager *pqm, unsigned int qid) goto err_destroy_queue; } kfd_procfs_del_queue(pqn->q); - kfd_queue_release_buffers(pdd, &pqn->q->properties); + kfd_queue_release_buffers(pdd, &pqn->q->properties, false); pqm_clean_queue_resource(pqm, pqn); uninit_queue(pqn->q); } @@ -1095,9 +1095,17 @@ int kfd_criu_restore_queue(struct kfd_process *p, print_queue_properties(&qp); + ret = kfd_queue_acquire_buffers(pdd, &qp, true); + if (ret) { + pr_err("Failed to acquire user queue buffers err:%d\n", ret); + goto exit; + } + ret = pqm_create_queue(&p->pqm, pdd->dev, &qp, &queue_id, q_data, mqd, ctl_stack, NULL); if (ret) { pr_err("Failed to create new queue err:%d\n", ret); + kfd_queue_unref_bo_vas(pdd, &qp); + kfd_queue_release_buffers(pdd, &qp, true); goto exit; } @@ -1116,6 +1124,38 @@ exit: return ret; } +int kfd_criu_resume_queues(struct kfd_process *p) +{ + int ret, i; + u64 total_cwsr_size; + + for (i = 0; i < p->n_pdds; i++) { + struct kfd_process_device *pdd = p->pdds[i]; + struct kfd_topology_device *topo_dev; + struct queue *q; + + topo_dev = kfd_topology_device_by_id(pdd->dev->id); + + list_for_each_entry(q, &pdd->qpd.queues_list, list) { + total_cwsr_size = q->properties.ctx_save_restore_area_size + + topo_dev->node_props.debug_memory_size; + if (check_mul_overflow(total_cwsr_size, + NUM_XCC(pdd->dev->xcc_mask), + &total_cwsr_size)) + return -EINVAL; + total_cwsr_size = ALIGN(total_cwsr_size, PAGE_SIZE); + + ret = kfd_queue_buffer_svm_get(pdd, q->properties.ctx_save_restore_area_address, + total_cwsr_size); + if (ret) + return ret; + } + + } + + return 0; +} + int pqm_get_queue_checkpoint_info(struct process_queue_manager *pqm, unsigned int qid, uint32_t *mqd_size, diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_queue.c b/drivers/gpu/drm/amd/amdkfd/kfd_queue.c index 6010a5d7a7eb..cd41b10e0873 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_queue.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_queue.c @@ -88,7 +88,7 @@ void uninit_queue(struct queue *q) #if IS_ENABLED(CONFIG_HSA_AMD_SVM) -static int kfd_queue_buffer_svm_get(struct kfd_process_device *pdd, u64 addr, u64 size) +int kfd_queue_buffer_svm_get(struct kfd_process_device *pdd, u64 addr, u64 size) { struct kfd_process *p = pdd->process; struct list_head update_list; @@ -182,7 +182,7 @@ static void kfd_queue_buffer_svm_put(struct kfd_process_device *pdd, u64 addr, u } #else -static int kfd_queue_buffer_svm_get(struct kfd_process_device *pdd, u64 addr, u64 size) +int kfd_queue_buffer_svm_get(struct kfd_process_device *pdd, u64 addr, u64 size) { return -EINVAL; } @@ -239,7 +239,7 @@ static void kfd_queue_put_bos(struct queue_properties *properties) kfd_queue_buffer_put(&properties->cwsr_bo); } -int kfd_queue_acquire_buffers(struct kfd_process_device *pdd, struct queue_properties *properties) +int kfd_queue_acquire_buffers(struct kfd_process_device *pdd, struct queue_properties *properties, bool is_criu) { struct kfd_topology_device *topo_dev; u64 expected_queue_size; @@ -334,6 +334,12 @@ int kfd_queue_acquire_buffers(struct kfd_process_device *pdd, struct queue_prope amdgpu_bo_unreserve(vm->root.bo); + /* CRIU svm buffers are restored at a later stage than queues. They'll be in + * before the queue is actually used, so no risk here + */ + if (is_criu) + return 0; + err = kfd_queue_buffer_svm_get(pdd, properties->ctx_save_restore_area_address, total_cwsr_size); if (err) @@ -362,7 +368,7 @@ out_err_release: return err; } -int kfd_queue_release_buffers(struct kfd_process_device *pdd, struct queue_properties *properties) +int kfd_queue_release_buffers(struct kfd_process_device *pdd, struct queue_properties *properties, bool is_criu) { struct kfd_topology_device *topo_dev; u64 total_cwsr_size; @@ -380,7 +386,8 @@ int kfd_queue_release_buffers(struct kfd_process_device *pdd, struct queue_prope return -EINVAL; total_cwsr_size = ALIGN(total_cwsr_size, PAGE_SIZE); - kfd_queue_buffer_svm_put(pdd, properties->ctx_save_restore_area_address, total_cwsr_size); + if (!is_criu) + kfd_queue_buffer_svm_put(pdd, properties->ctx_save_restore_area_address, total_cwsr_size); return 0; } diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_svm.c b/drivers/gpu/drm/amd/amdkfd/kfd_svm.c index ed5e3318877b..7fd331612f08 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_svm.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_svm.c @@ -4245,15 +4245,14 @@ int kfd_criu_restore_svm(struct kfd_process *p, svm_priv_data_size = sizeof(struct kfd_criu_svm_range_priv_data) + svm_attrs_size; + if (*priv_data_offset + svm_priv_data_size > max_priv_data_size) + return -EINVAL; + criu_svm_md = kzalloc(svm_object_md_size, GFP_KERNEL); if (!criu_svm_md) { pr_err("failed to allocate memory to store svm metadata\n"); return -ENOMEM; } - if (*priv_data_offset + svm_priv_data_size > max_priv_data_size) { - ret = -EINVAL; - goto exit; - } ret = copy_from_user(&criu_svm_md->data, user_priv_ptr + *priv_data_offset, svm_priv_data_size); diff --git a/drivers/gpu/drm/amd/display/dc/dml2_0/dml21/inc/bounding_boxes/utm_qos_model_dchub_v2.h b/drivers/gpu/drm/amd/display/dc/dml2_0/dml21/inc/bounding_boxes/utm_qos_model_dchub_v2.h index ebca5ddda284..32049c17c080 100644 --- a/drivers/gpu/drm/amd/display/dc/dml2_0/dml21/inc/bounding_boxes/utm_qos_model_dchub_v2.h +++ b/drivers/gpu/drm/amd/display/dc/dml2_0/dml21/inc/bounding_boxes/utm_qos_model_dchub_v2.h @@ -58,27 +58,27 @@ static inline void dchub_v2_get_sop_total_available_bandwidth_KBps( { const struct utm_soc_operating_point *sop = &model->sops[sop_index]; const struct utm_qos_model_socbb *socbb = &model->socbb; - uint64_t dram_available_bandwidth_KBps_nominal; - uint64_t fabric_available_bandwidth_KBps_nominal; - uint64_t dram_available_bandwidth_KBps_urgent; - uint64_t fabric_available_bandwidth_KBps_urgent; + double dram_available_bandwidth_KBps_nominal; + double fabric_available_bandwidth_KBps_nominal; + double dram_available_bandwidth_KBps_urgent; + double fabric_available_bandwidth_KBps_urgent; - dram_available_bandwidth_KBps_nominal = (uint64_t) sop->uclk_khz + dram_available_bandwidth_KBps_nominal = (double) sop->uclk_khz * socbb->dram_channel_count * socbb->dram_channel_width_bytes * socbb->dram_transactions_per_clock - * socbb->dram_derate_percent_nominal / 100; - dram_available_bandwidth_KBps_urgent = (uint64_t) sop->uclk_khz + * socbb->dram_derate_percent_nominal / 100.0; + dram_available_bandwidth_KBps_urgent = (double) sop->uclk_khz * socbb->dram_channel_count * socbb->dram_channel_width_bytes * socbb->dram_transactions_per_clock - * socbb->dram_derate_percent_urgent / 100; - fabric_available_bandwidth_KBps_nominal = (uint64_t) sop->fclk_khz + * socbb->dram_derate_percent_urgent / 100.0; + fabric_available_bandwidth_KBps_nominal = (double) sop->fclk_khz * socbb->fabric_datapath_to_dcn_data_return_bytes - * socbb->fabric_derate_percent_nominal / 100; - fabric_available_bandwidth_KBps_urgent = (uint64_t) sop->fclk_khz + * socbb->fabric_derate_percent_nominal / 100.0; + fabric_available_bandwidth_KBps_urgent = (double) sop->fclk_khz * socbb->fabric_datapath_to_dcn_data_return_bytes - * socbb->fabric_derate_percent_urgent / 100; + * socbb->fabric_derate_percent_urgent / 100.0; total_available_bandwidth->nominal_bandwidth_KBps = dram_available_bandwidth_KBps_nominal < fabric_available_bandwidth_KBps_nominal ? @@ -99,8 +99,8 @@ static inline bool dchub_v2_is_qos_bandwidth_supported_by_sop( { struct utm_qos_model_dchub_memory_path_bandwidth_v2 available_bandwidth = {0}; const struct utm_qos_model_dchub_v2 *dchub = model->dchub_v2; - uint64_t nominal_available_bandwidth_KBps; - uint64_t urgent_available_bandwidth_KBps; + double nominal_available_bandwidth_KBps; + double urgent_available_bandwidth_KBps; if (nominal_utm_budget_percent > dchub->max_nominal_utm_budget_percent || nominal_utm_budget_percent < dchub->min_nominal_utm_budget_percent || @@ -112,9 +112,9 @@ static inline bool dchub_v2_is_qos_bandwidth_supported_by_sop( nominal_available_bandwidth_KBps = available_bandwidth.nominal_bandwidth_KBps; urgent_available_bandwidth_KBps = available_bandwidth.urgent_bandwidth_KBps; - if ((nominal_available_bandwidth_KBps * nominal_utm_budget_percent / 100) < qos_bandwidth->nominal_bandwidth_KBps) + if ((nominal_available_bandwidth_KBps * nominal_utm_budget_percent / 100.0) < qos_bandwidth->nominal_bandwidth_KBps) return false; - else if ((urgent_available_bandwidth_KBps * urgent_utm_budget_percent / 100) < qos_bandwidth->urgent_bandwidth_KBps) + else if ((urgent_available_bandwidth_KBps * urgent_utm_budget_percent / 100.0) < qos_bandwidth->urgent_bandwidth_KBps) return false; else return true; diff --git a/drivers/gpu/drm/amd/display/dc/dml2_0/dml21/inc/bounding_boxes/utm_qos_model_dchub_v3.h b/drivers/gpu/drm/amd/display/dc/dml2_0/dml21/inc/bounding_boxes/utm_qos_model_dchub_v3.h index 9390cad31691..fef7b1dc3060 100644 --- a/drivers/gpu/drm/amd/display/dc/dml2_0/dml21/inc/bounding_boxes/utm_qos_model_dchub_v3.h +++ b/drivers/gpu/drm/amd/display/dc/dml2_0/dml21/inc/bounding_boxes/utm_qos_model_dchub_v3.h @@ -50,4 +50,4 @@ struct utm_qos_model_dchub_v3 { sops[UTM_QOS_MODEL_V3_MAX_LOAD_LEVEL_COUNT][UTM_QOS_MODEL_V3_MAX_SOP_COUNT]; }; -#endif /* #ifndef UTM_QOS_MODEL_DCHUB_V3_H */
\ No newline at end of file +#endif /* #ifndef UTM_QOS_MODEL_DCHUB_V3_H */ diff --git a/drivers/gpu/drm/amd/include/asic_reg/vce/vce_1_0_sh_mask.h b/drivers/gpu/drm/amd/include/asic_reg/vce/vce_1_0_sh_mask.h index 1f82d6f5abde..13c15c2138b3 100644 --- a/drivers/gpu/drm/amd/include/asic_reg/vce/vce_1_0_sh_mask.h +++ b/drivers/gpu/drm/amd/include/asic_reg/vce/vce_1_0_sh_mask.h @@ -63,8 +63,6 @@ #define VCE_SOFT_RESET__ECPU_SOFT_RESET__SHIFT 0x00000000 #define VCE_SOFT_RESET__FME_SOFT_RESET_MASK 0x00000004L #define VCE_SOFT_RESET__FME_SOFT_RESET__SHIFT 0x00000002 -#define VCE_STATUS__JOB_BUSY_MASK 0x00000001L -#define VCE_STATUS__JOB_BUSY__SHIFT 0x00000000 #define VCE_STATUS__UENC_BUSY_MASK 0x00000100L #define VCE_STATUS__UENC_BUSY__SHIFT 0x00000008 #define VCE_STATUS__VCPU_REPORT_MASK 0x000000feL diff --git a/drivers/gpu/drm/amd/pm/swsmu/smu15/smu_v15_0.c b/drivers/gpu/drm/amd/pm/swsmu/smu15/smu_v15_0.c index 4be864e4f0e6..e7a74b732639 100644 --- a/drivers/gpu/drm/amd/pm/swsmu/smu15/smu_v15_0.c +++ b/drivers/gpu/drm/amd/pm/swsmu/smu15/smu_v15_0.c @@ -1457,7 +1457,7 @@ int smu_v15_0_od_edit_dpm_table(struct smu_context *smu, return -EINVAL; } - ret = smu_cmn_send_smc_msg_with_param(smu, SMU_MSG_SetHardMinGfxClk, + ret = smu_cmn_send_smc_msg_with_param(smu, SMU_MSG_SetSoftMinGfxclk, smu->gfx_actual_hard_min_freq, NULL); if (ret) { diff --git a/drivers/gpu/drm/bridge/sii902x.c b/drivers/gpu/drm/bridge/sii902x.c index a1e34d2bb3da..299f5b7bffa1 100644 --- a/drivers/gpu/drm/bridge/sii902x.c +++ b/drivers/gpu/drm/bridge/sii902x.c @@ -890,9 +890,15 @@ static int sii902x_audio_codec_init(struct sii902x *sii902x, } codec_data.max_i2s_channels = 2 * num_lanes; - for (i = 0; i < num_lanes; i++) + for (i = 0; i < num_lanes; i++) { + if (lanes[i] >= ARRAY_SIZE(i2s_lane_id)) + return dev_err_probe(dev, -EINVAL, + "invalid sil,i2s-data-lanes value %u\n", + lanes[i]); + sii902x->audio.i2s_fifo_sequence[i] |= audio_fifo_id[i] | i2s_lane_id[lanes[i]] | SII902X_TPI_I2S_FIFO_ENABLE; + } sii902x->audio.mclk = devm_clk_get_optional(dev, "mclk"); if (IS_ERR(sii902x->audio.mclk)) { diff --git a/drivers/gpu/drm/bridge/ssd2825.c b/drivers/gpu/drm/bridge/ssd2825.c index 71877699dfab..9216cee09115 100644 --- a/drivers/gpu/drm/bridge/ssd2825.c +++ b/drivers/gpu/drm/bridge/ssd2825.c @@ -475,6 +475,7 @@ static void ssd2825_bridge_atomic_pre_enable(struct drm_bridge *bridge, struct drm_atomic_commit *state) { struct ssd2825_priv *priv = bridge_to_ssd2825(bridge); + struct drm_bridge *next_bridge = priv->output.bridge; struct mipi_dsi_device *dsi_dev = priv->output.dev; const struct drm_crtc_state *crtc_state; const struct drm_display_mode *mode; @@ -569,6 +570,14 @@ static void ssd2825_bridge_atomic_pre_enable(struct drm_bridge *bridge, /* Initial DSI configuration register set */ ssd2825_write_reg(priv, SSD2825_CONFIGURATION_REG, config); ssd2825_write_reg(priv, SSD2825_VC_CTRL_REG, 0); + + /* + * The SSD2825 requires that the next bridge be enabled first; + * otherwise, the SSD2825 cannot complete its configuration and + * there will be no output. + */ + if (next_bridge->funcs && next_bridge->funcs->atomic_enable) + next_bridge->funcs->atomic_enable(next_bridge, state); } static void ssd2825_bridge_atomic_enable(struct drm_bridge *bridge, diff --git a/drivers/gpu/drm/display/drm_hdmi_helper.c b/drivers/gpu/drm/display/drm_hdmi_helper.c index f85cce3d6254..278cfda38e18 100644 --- a/drivers/gpu/drm/display/drm_hdmi_helper.c +++ b/drivers/gpu/drm/display/drm_hdmi_helper.c @@ -470,6 +470,28 @@ static bool drm_scdc_sink_supports_scrambling(struct drm_connector *connector) info->hdmi.scdc.scrambling.supported; } +static void drm_connector_hdmi_reset_sink_scrambling(struct drm_connector *connector) +{ + struct drm_device *dev = connector->dev; + u8 config; + int ret; + + if (!connector->ddc || !drm_scdc_sink_supports_scrambling(connector)) + return; + + ret = drm_scdc_readb(connector->ddc, SCDC_TMDS_CONFIG, &config); + if (ret) { + drm_dbg_kms(dev, "Failed to read TMDS config: %d\n", ret); + return; + } + + if (config & SCDC_SCRAMBLING_ENABLE) + drm_scdc_set_scrambling(connector, false); + + if (config & SCDC_TMDS_BIT_CLOCK_RATIO_BY_40) + drm_scdc_set_high_tmds_clock_ratio(connector, false); +} + static int drm_connector_hdmi_try_scrambling_setup(struct drm_connector *connector) { bool done; @@ -522,6 +544,11 @@ static void drm_connector_hdmi_scdc_work(struct work_struct *work) * the sink side and retry the operation, as some displays refuse to set the * scrambling bit right away. * + * When @conn_state doesn't require scrambling, the sink-side SCDC status is + * reset instead, so that a sink left scrambling by a state the driver did not + * control, e.g. set up by the firmware before boot, doesn't end up out of sync + * with the source. + * * The work item is cancelled by drm_connector_hdmi_disable_scrambling(), hence * source drivers must ensure the display pipeline is shut down on unbind, e.g. * via drm_atomic_helper_shutdown(). Otherwise the work may outlive the driver's @@ -541,8 +568,14 @@ int drm_connector_hdmi_enable_scrambling(struct drm_connector *connector, if (!conn_state) return -EINVAL; - if (!conn_state->hdmi.scrambler_needed) + if (!conn_state->hdmi.scrambler_needed) { + /* + * Resync the sink here, where it is known to be connected + * and its capabilities have been parsed. + */ + drm_connector_hdmi_reset_sink_scrambling(connector); return 0; + } if (!drm_connector_hdmi_scrambler_supported(connector)) { drm_dbg_kms(dev, "Source doesn't support scrambling.\n"); @@ -581,8 +614,7 @@ int drm_connector_hdmi_enable_scrambling(struct drm_connector *connector, WRITE_ONCE(hdmi->scrambler_enabled, false); cancel_delayed_work_sync(&hdmi->scdc_work); - drm_scdc_set_scrambling(connector, false); - drm_scdc_set_high_tmds_clock_ratio(connector, false); + drm_connector_hdmi_reset_sink_scrambling(connector); } return ret; @@ -619,12 +651,7 @@ int drm_connector_hdmi_disable_scrambling(struct drm_connector *connector) if (hdmi->scdc_work_initialized) cancel_delayed_work_sync(&hdmi->scdc_work); - if (connector->ddc && - connector->status == connector_status_connected && - drm_scdc_sink_supports_scrambling(connector)) { - drm_scdc_set_scrambling(connector, false); - drm_scdc_set_high_tmds_clock_ratio(connector, false); - } + drm_connector_hdmi_reset_sink_scrambling(connector); return hdmi->funcs->scrambler_disable(connector); } @@ -653,9 +680,8 @@ EXPORT_SYMBOL(drm_connector_hdmi_disable_scrambling); int drm_connector_hdmi_sync_scdc(struct drm_connector *connector, bool plugged, struct drm_modeset_acquire_ctx *ctx) { - struct drm_connector_hdmi *hdmi = &connector->hdmi; - struct drm_device *dev = connector->dev; struct drm_connector_state *conn_state; + struct drm_device *dev; struct drm_crtc *crtc; u8 config; int ret; @@ -663,6 +689,8 @@ int drm_connector_hdmi_sync_scdc(struct drm_connector *connector, bool plugged, if (!connector || !plugged || !ctx) return 0; + dev = connector->dev; + /* * This is normally part of .detect_ctx() call path, which already holds * connection_mutex through @ctx. However, re-acquiring it with the @@ -674,14 +702,21 @@ int drm_connector_hdmi_sync_scdc(struct drm_connector *connector, bool plugged, /* TODO: Also handle HDMI 2.1 FRL link training */ - if (!drm_connector_hdmi_scrambler_supported(connector) || - !READ_ONCE(hdmi->scrambler_enabled)) - return 0; - conn_state = connector->state; if (!conn_state) return 0; + /* + * Rely on the committed connector state rather than on the current + * scrambler status: a source driver may force scrambler_enabled at + * init to get a disable at boot (e.g. vc4), and that value would + * remain stale until the first disable actually happens, leading to + * a spurious CRTC reset whenever the active mode needs no scrambling. + */ + if (!drm_connector_hdmi_scrambler_supported(connector) || + !conn_state->hdmi.scrambler_needed) + return 0; + crtc = conn_state->crtc; if (!crtc) return 0; diff --git a/drivers/gpu/drm/gud/gud_drv.c b/drivers/gpu/drm/gud/gud_drv.c index ea98f641c0b9..55510bf62009 100644 --- a/drivers/gpu/drm/gud/gud_drv.c +++ b/drivers/gpu/drm/gud/gud_drv.c @@ -329,10 +329,17 @@ 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 remainder; - u64 ratio = div64_u64_rem(gdrm->stats_length, gdrm->stats_actual_length, - &remainder); - u64 ratio_frac = div64_u64(remainder * 10, gdrm->stats_actual_length); + u64 ratio, ratio_frac; + + if (!actual_length) { + seq_puts(m, "Compression ratio: n/a\n"); + return 0; + } + + ratio = div64_u64_rem(gdrm->stats_length, actual_length, &remainder); + ratio_frac = div64_u64(remainder * 10, actual_length); seq_printf(m, "Compression ratio: %llu.%llu\n", ratio, ratio_frac); } diff --git a/drivers/gpu/drm/i915/display/intel_ddi.c b/drivers/gpu/drm/i915/display/intel_ddi.c index a0aff087fafa..d7c7ef22b73c 100644 --- a/drivers/gpu/drm/i915/display/intel_ddi.c +++ b/drivers/gpu/drm/i915/display/intel_ddi.c @@ -4723,10 +4723,10 @@ static void intel_ddi_encoder_reset(struct drm_encoder *encoder) intel_dp->reset_link_params = true; intel_dp_invalidate_source_oui(intel_dp); - intel_pps_encoder_reset(intel_dp); - if (intel_encoder_is_tc(&dig_port->base)) intel_tc_port_init_mode(dig_port); + + intel_pps_encoder_reset(intel_dp); } static int intel_ddi_encoder_late_register(struct drm_encoder *_encoder) @@ -5053,6 +5053,8 @@ static enum hpd_pin xelpd_hpd_pin(struct intel_display *display, enum port port) return HPD_PORT_D + port - PORT_D_XELPD; else if (port >= PORT_TC1) return HPD_PORT_TC1 + port - PORT_TC1; + else if (intel_phy_is_tc(display, intel_port_to_phy(display, port))) + return HPD_PORT_TC1 + intel_port_to_tc(display, port) - TC_PORT_1; else return HPD_PORT_A + port - PORT_A; } diff --git a/drivers/gpu/drm/i915/display/intel_display.c b/drivers/gpu/drm/i915/display/intel_display.c index f79caeb5a82e..b897678a93c0 100644 --- a/drivers/gpu/drm/i915/display/intel_display.c +++ b/drivers/gpu/drm/i915/display/intel_display.c @@ -1904,6 +1904,11 @@ bool intel_phy_is_combo(struct intel_display *display, enum phy phy) return false; } +static bool intel_phy_is_edp_on_tc(struct intel_display *display, enum phy phy) +{ + return DISPLAY_RUNTIME_INFO(display)->edp_typec_support && phy == PHY_B; +} + /* * This function returns true if the DDI port respective to the PHY enumeration * is a Type-C capable port. @@ -1924,6 +1929,9 @@ bool intel_phy_is_tc(struct intel_display *display, enum phy phy) if (display->platform.dgfx) return false; + if (intel_phy_is_edp_on_tc(display, phy)) + return true; + if (DISPLAY_VER(display) >= 13) return phy >= PHY_F && phy <= PHY_I; else if (display->platform.tigerlake) @@ -1974,6 +1982,9 @@ enum phy intel_port_to_phy(struct intel_display *display, enum port port) */ enum tc_port intel_port_to_tc(struct intel_display *display, enum port port) { + if (intel_phy_is_edp_on_tc(display, intel_port_to_phy(display, port))) + return TC_PORT_1; + if (DISPLAY_VER(display) >= 12) return TC_PORT_1 + port - PORT_TC1; else diff --git a/drivers/gpu/drm/i915/display/intel_dp_aux.c b/drivers/gpu/drm/i915/display/intel_dp_aux.c index 3cb07b0a901c..36800cf19c50 100644 --- a/drivers/gpu/drm/i915/display/intel_dp_aux.c +++ b/drivers/gpu/drm/i915/display/intel_dp_aux.c @@ -270,22 +270,6 @@ intel_dp_aux_xfer(struct intel_dp *intel_dp, for (i = 0; i < ARRAY_SIZE(ch_data); i++) ch_data[i] = intel_dp->aux_ch_data_reg(intel_dp, i); - intel_digital_port_lock(encoder); - /* - * Abort transfers on a disconnected port as required by - * DP 1.4a link CTS 4.2.1.5, also avoiding the long AUX - * timeouts that would otherwise happen. - */ - if (!intel_dp_is_edp(intel_dp) && - !intel_digital_port_connected_locked(&dig_port->base)) { - ret = -ENXIO; - goto out_unlock; - } - - aux_domain = intel_aux_power_domain(dig_port); - - aux_wakeref = intel_display_power_get(display, aux_domain); - /* * The PPS state needs to be locked for: * - eDP on all platforms, since AUX transfers on eDP need VDD power @@ -308,6 +292,21 @@ intel_dp_aux_xfer(struct intel_dp *intel_dp, */ vdd = intel_pps_vdd_on_unlocked(intel_dp); + intel_digital_port_lock(encoder); + /* + * Abort transfers on a disconnected port as required by + * DP 1.4a link CTS 4.2.1.5, also avoiding the long AUX + * timeouts that would otherwise happen. + */ + if (!intel_dp_is_edp(intel_dp) && + !intel_digital_port_connected_locked(&dig_port->base)) { + ret = -ENXIO; + goto out_unlock; + } + + aux_domain = intel_aux_power_domain(dig_port); + aux_wakeref = intel_display_power_get(display, aux_domain); + /* * dp aux is extremely sensitive to irq latency, hence request the * lowest possible wakeup latency and so prevent the cpu from going into @@ -453,16 +452,16 @@ done: out: cpu_latency_qos_update_request(&intel_dp->pm_qos, PM_QOS_DEFAULT_VALUE); + intel_display_power_put_async(display, aux_domain, aux_wakeref); +out_unlock: + intel_digital_port_unlock(encoder); + if (vdd) intel_pps_vdd_off_unlocked(intel_dp, false); if (pps_wakeref) intel_pps_unlock(intel_dp, pps_wakeref); - intel_display_power_put_async(display, aux_domain, aux_wakeref); -out_unlock: - intel_digital_port_unlock(encoder); - return ret; } diff --git a/drivers/gpu/drm/i915/display/intel_dpll_mgr.c b/drivers/gpu/drm/i915/display/intel_dpll_mgr.c index bfd6f0a19725..ac9d3f110274 100644 --- a/drivers/gpu/drm/i915/display/intel_dpll_mgr.c +++ b/drivers/gpu/drm/i915/display/intel_dpll_mgr.c @@ -207,7 +207,8 @@ enum intel_dpll_id icl_tc_port_to_pll_id(enum tc_port tc_port) enum intel_dpll_id mtl_port_to_pll_id(struct intel_display *display, enum port port) { - if (port >= PORT_TC1) + if (port >= PORT_TC1 || + intel_phy_is_tc(display, intel_port_to_phy(display, port))) return icl_tc_port_to_pll_id(intel_port_to_tc(display, port)); switch (port) { diff --git a/drivers/gpu/drm/i915/display/intel_fbdev.c b/drivers/gpu/drm/i915/display/intel_fbdev.c index 219ee17de3f6..c09246a9865c 100644 --- a/drivers/gpu/drm/i915/display/intel_fbdev.c +++ b/drivers/gpu/drm/i915/display/intel_fbdev.c @@ -75,9 +75,10 @@ static struct intel_frontbuffer *to_frontbuffer(struct intel_fbdev *ifbdev) return ifbdev->fb->frontbuffer; } -static void intel_fbdev_invalidate(struct intel_fbdev *ifbdev) +/* The console operation has already completed, hence flush not invalidate. */ +static void intel_fbdev_flush(struct intel_fbdev *ifbdev) { - intel_frontbuffer_invalidate(to_frontbuffer(ifbdev), ORIGIN_CPU); + intel_frontbuffer_flush(to_frontbuffer(ifbdev), ORIGIN_CPU); } FB_GEN_DEFAULT_DEFERRED_IOMEM_OPS(intel_fbdev, @@ -91,7 +92,7 @@ static int intel_fbdev_set_par(struct fb_info *info) ret = drm_fb_helper_set_par(info); if (ret == 0) - intel_fbdev_invalidate(ifbdev); + intel_fbdev_flush(ifbdev); return ret; } @@ -103,7 +104,7 @@ static int intel_fbdev_blank(int blank, struct fb_info *info) ret = drm_fb_helper_blank(blank, info); if (ret == 0) - intel_fbdev_invalidate(ifbdev); + intel_fbdev_flush(ifbdev); return ret; } @@ -116,7 +117,7 @@ static int intel_fbdev_pan_display(struct fb_var_screeninfo *var, ret = drm_fb_helper_pan_display(var, info); if (ret == 0) - intel_fbdev_invalidate(ifbdev); + intel_fbdev_flush(ifbdev); return ret; } @@ -180,7 +181,7 @@ static void intelfb_restore(struct drm_fb_helper *fb_helper) { struct intel_fbdev *ifbdev = to_intel_fbdev(fb_helper); - intel_fbdev_invalidate(ifbdev); + intel_fbdev_flush(ifbdev); } static void intelfb_set_suspend(struct drm_fb_helper *fb_helper, bool suspend) diff --git a/drivers/gpu/drm/i915/display/intel_pps.c b/drivers/gpu/drm/i915/display/intel_pps.c index d4c98b150fa2..8f1bfe434097 100644 --- a/drivers/gpu/drm/i915/display/intel_pps.c +++ b/drivers/gpu/drm/i915/display/intel_pps.c @@ -23,6 +23,7 @@ #include "intel_pps.h" #include "intel_pps_regs.h" #include "intel_quirks.h" +#include "intel_tc.h" static void vlv_steal_power_sequencer(struct intel_display *display, enum pipe pipe); @@ -758,6 +759,9 @@ bool intel_pps_vdd_on_unlocked(struct intel_dp *intel_dp) if (edp_have_panel_vdd(intel_dp)) return need_to_disable; + if (intel_encoder_is_tc(&dig_port->base)) + intel_tc_port_get_link(dig_port, 1); + drm_WARN_ON(display->drm, intel_dp->pps.vdd_wakeref); intel_dp->pps.vdd_wakeref = intel_display_power_get(display, intel_aux_power_domain(dig_port)); @@ -864,6 +868,9 @@ static void intel_pps_vdd_off_sync_unlocked(struct intel_dp *intel_dp) intel_display_power_put(display, intel_aux_power_domain(dig_port), fetch_and_zero(&intel_dp->pps.vdd_wakeref)); + + if (intel_encoder_is_tc(&dig_port->base)) + intel_tc_port_put_link(dig_port); } void intel_pps_vdd_off_sync(struct intel_dp *intel_dp) @@ -1066,6 +1073,9 @@ void intel_pps_off_unlocked(struct intel_dp *intel_dp) intel_display_power_put(display, intel_aux_power_domain(dig_port), fetch_and_zero(&intel_dp->pps.vdd_wakeref)); + + if (intel_encoder_is_tc(&dig_port->base)) + intel_tc_port_put_link(dig_port); } void intel_pps_off(struct intel_dp *intel_dp) @@ -1334,6 +1344,10 @@ static void pps_vdd_init(struct intel_dp *intel_dp) "[ENCODER:%d:%s] %s VDD left on by BIOS, adjusting state tracking\n", dig_port->base.base.base.id, dig_port->base.base.name, pps_name(intel_dp)); + + if (intel_encoder_is_tc(&dig_port->base)) + intel_tc_port_get_link(dig_port, 1); + drm_WARN_ON(display->drm, intel_dp->pps.vdd_wakeref); intel_dp->pps.vdd_wakeref = intel_display_power_get(display, intel_aux_power_domain(dig_port)); diff --git a/drivers/gpu/drm/i915/display/intel_psr.c b/drivers/gpu/drm/i915/display/intel_psr.c index 17542d812486..0ae347fe6cd1 100644 --- a/drivers/gpu/drm/i915/display/intel_psr.c +++ b/drivers/gpu/drm/i915/display/intel_psr.c @@ -3645,12 +3645,6 @@ static void _psr_flush_handle(struct intel_dp *intel_dp) intel_psr_exit(intel_dp); } else if (intel_dp->psr.psr2_sel_fetch_enabled) { /* Selective fetch prior LNL */ - if (intel_dp->psr.psr2_sel_fetch_cff_enabled) { - /* can we turn CFF off? */ - if (intel_dp->psr.busy_frontbuffer_bits == 0) - intel_dp->psr.psr2_sel_fetch_cff_enabled = false; - } - /* * Still keep cff bit enabled as we don't have proper SU * configuration in case update is sent for any reason after @@ -3669,9 +3663,6 @@ static void _psr_flush_handle(struct intel_dp *intel_dp) */ intel_psr_force_update(intel_dp); } - - if (!intel_dp->psr.active && !intel_dp->psr.busy_frontbuffer_bits) - queue_work(display->wq.unordered, &intel_dp->psr.work); } /** @@ -3704,28 +3695,39 @@ void intel_psr_flush(struct intel_display *display, pipe_frontbuffer_bits &= INTEL_FRONTBUFFER_ALL_MASK(intel_dp->psr.pipe); + + if (pipe_frontbuffer_bits == 0) + goto unlock; + intel_dp->psr.busy_frontbuffer_bits &= ~pipe_frontbuffer_bits; - /* - * If the PSR is paused by an explicit intel_psr_paused() call, - * we have to ensure that the PSR is not activated until - * intel_psr_resume() is called. - */ if (intel_dp->psr.pause_counter) - goto unlock; + goto rearm; - if (origin == ORIGIN_FLIP || - (origin == ORIGIN_CURSOR_UPDATE && - !intel_dp->psr.psr2_sel_fetch_enabled)) { + if (origin == ORIGIN_FLIP || origin == ORIGIN_CURSOR_UPDATE) psr2_dc3co_flush_locked(intel_dp, frontbuffer_bits); - goto unlock; - } - if (pipe_frontbuffer_bits == 0) - goto unlock; + if (origin == ORIGIN_FLIP) + goto rearm; /* By definition flush = invalidate + flush */ _psr_flush_handle(intel_dp); + +rearm: + if (!intel_dp->psr.busy_frontbuffer_bits) { + if (intel_dp->psr.psr2_sel_fetch_cff_enabled) + intel_dp->psr.psr2_sel_fetch_cff_enabled = false; + + /* + * If the PSR is paused by an explicit + * intel_psr_paused() call, we have to ensure that the + * PSR is not activated until intel_psr_resume() is + * called. + */ + if (!intel_dp->psr.active && !intel_dp->psr.pause_counter) + queue_work(display->wq.unordered, &intel_dp->psr.work); + } + unlock: mutex_unlock(&intel_dp->psr.lock); } diff --git a/drivers/gpu/drm/i915/display/intel_tc.c b/drivers/gpu/drm/i915/display/intel_tc.c index f2d86b29c415..f878494bcb38 100644 --- a/drivers/gpu/drm/i915/display/intel_tc.c +++ b/drivers/gpu/drm/i915/display/intel_tc.c @@ -1669,7 +1669,7 @@ void intel_tc_port_sanitize_mode(struct intel_digital_port *dig_port, mutex_lock(&tc->lock); - drm_WARN_ON(display->drm, tc->link_refcount != 1); + drm_WARN_ON(display->drm, tc->link_refcount < 1); if (!tc_port_has_active_streams(tc, crtc_state)) { /* * TBT-alt is the default mode in any case the PHY ownership is not @@ -1683,7 +1683,12 @@ void intel_tc_port_sanitize_mode(struct intel_digital_port *dig_port, "Port %s: PHY left in %s mode on disabled port, disconnecting it\n", tc->port_name, tc_port_mode_name(tc->init_mode)); - tc_phy_disconnect(tc); + /* + * A link reference taken during a preceding (eDP) connector initialization will be + * dropped later, also disconnecting the PHY. + */ + if (tc->link_refcount == 1) + tc_phy_disconnect(tc); __intel_tc_port_put_link(tc); } diff --git a/drivers/gpu/drm/meson/meson_encoder_dsi.c b/drivers/gpu/drm/meson/meson_encoder_dsi.c index faa309cb97a6..912cd676bbe2 100644 --- a/drivers/gpu/drm/meson/meson_encoder_dsi.c +++ b/drivers/gpu/drm/meson/meson_encoder_dsi.c @@ -65,9 +65,9 @@ static void meson_encoder_dsi_atomic_enable(struct drm_bridge *bridge, /* ENCL clock setup is handled by CCF */ meson_venc_mipi_dsi_mode_set(priv, &crtc_state->adjusted_mode); - meson_encl_load_gamma(priv); writel_relaxed(0, priv->io_base + _REG(ENCL_VIDEO_EN)); + meson_encl_load_gamma(priv); writel_bits_relaxed(ENCL_VIDEO_MODE_ADV_VFIFO_EN, ENCL_VIDEO_MODE_ADV_VFIFO_EN, priv->io_base + _REG(ENCL_VIDEO_MODE_ADV)); diff --git a/drivers/gpu/drm/nouveau/include/nvkm/engine/falcon.h b/drivers/gpu/drm/nouveau/include/nvkm/engine/falcon.h index 341f133dc38c..eb8adaf07fe5 100644 --- a/drivers/gpu/drm/nouveau/include/nvkm/engine/falcon.h +++ b/drivers/gpu/drm/nouveau/include/nvkm/engine/falcon.h @@ -63,6 +63,7 @@ struct nvkm_falcon_func { int (*select)(struct nvkm_falcon *); u32 addr2; u32 riscv_irqmask; + u32 riscv_irqdest; bool reset_pmc; int (*reset_eng)(struct nvkm_falcon *); int (*reset_prep)(struct nvkm_falcon *); diff --git a/drivers/gpu/drm/nouveau/nouveau_display.c b/drivers/gpu/drm/nouveau/nouveau_display.c index d71dcfc6ee66..07882624a7f6 100644 --- a/drivers/gpu/drm/nouveau/nouveau_display.c +++ b/drivers/gpu/drm/nouveau/nouveau_display.c @@ -354,6 +354,11 @@ static const struct drm_mode_config_funcs nouveau_mode_config_funcs = { .fb_create = nouveau_user_framebuffer_create, }; +static const struct drm_mode_config_funcs nouveau_mode_config_funcs_atomic = { + .fb_create = nouveau_user_framebuffer_create, + .atomic_commit = drm_atomic_helper_commit, + .atomic_check = drm_atomic_helper_check, +}; struct nouveau_drm_prop_enum_list { u8 gen_mask; @@ -654,7 +659,11 @@ nouveau_display_create(struct drm_device *dev) drm_mode_create_scaling_mode_property(dev); drm_mode_create_dvi_i_properties(dev); - dev->mode_config.funcs = &nouveau_mode_config_funcs; + /* this only gets set if the driver has the ATOMIC flag */ + if (drm_drv_uses_atomic_modeset(dev)) + dev->mode_config.funcs = &nouveau_mode_config_funcs_atomic; + else + dev->mode_config.funcs = &nouveau_mode_config_funcs; dev->mode_config.min_width = 0; dev->mode_config.min_height = 0; diff --git a/drivers/gpu/drm/nouveau/nvkm/subdev/gsp/ga100.c b/drivers/gpu/drm/nouveau/nvkm/subdev/gsp/ga100.c index d5126fe39d27..10e2813a0163 100644 --- a/drivers/gpu/drm/nouveau/nvkm/subdev/gsp/ga100.c +++ b/drivers/gpu/drm/nouveau/nvkm/subdev/gsp/ga100.c @@ -27,6 +27,7 @@ ga100_gsp_flcn = { .enable = gm200_flcn_enable, .addr2 = 0x1000, .riscv_irqmask = 0x2b4, + .riscv_irqdest = 0x2b8, .reset_eng = gp102_flcn_reset_eng, .reset_wait_mem_scrubbing = gm200_flcn_reset_wait_mem_scrubbing, .bind_inst = gm200_flcn_bind_inst, diff --git a/drivers/gpu/drm/nouveau/nvkm/subdev/gsp/ga102.c b/drivers/gpu/drm/nouveau/nvkm/subdev/gsp/ga102.c index b6b3eb6f4c00..96fa26fa6122 100644 --- a/drivers/gpu/drm/nouveau/nvkm/subdev/gsp/ga102.c +++ b/drivers/gpu/drm/nouveau/nvkm/subdev/gsp/ga102.c @@ -140,6 +140,7 @@ ga102_gsp_flcn = { .select = ga102_flcn_select, .addr2 = 0x1000, .riscv_irqmask = 0x528, + .riscv_irqdest = 0x52c, .reset_eng = gp102_flcn_reset_eng, .reset_prep = ga102_flcn_reset_prep, .reset_wait_mem_scrubbing = ga102_flcn_reset_wait_mem_scrubbing, diff --git a/drivers/gpu/drm/nouveau/nvkm/subdev/gsp/rm/r535/gsp.c b/drivers/gpu/drm/nouveau/nvkm/subdev/gsp/rm/r535/gsp.c index 63aa30f94747..fe590a045d70 100644 --- a/drivers/gpu/drm/nouveau/nvkm/subdev/gsp/rm/r535/gsp.c +++ b/drivers/gpu/drm/nouveau/nvkm/subdev/gsp/rm/r535/gsp.c @@ -64,7 +64,9 @@ r535_gsp_intr(struct nvkm_inth *inth) u32 intr = nvkm_falcon_rd32(&gsp->falcon, 0x0008); u32 inte = nvkm_falcon_rd32(&gsp->falcon, gsp->falcon.func->addr2 + gsp->falcon.func->riscv_irqmask); - u32 stat = intr & inte; + u32 dest = nvkm_falcon_rd32(&gsp->falcon, gsp->falcon.func->addr2 + + gsp->falcon.func->riscv_irqdest); + u32 stat = intr & inte & dest; if (!stat) { nvkm_debug(subdev, "inte %08x %08x\n", intr, inte); diff --git a/drivers/gpu/drm/nouveau/nvkm/subdev/gsp/tu102.c b/drivers/gpu/drm/nouveau/nvkm/subdev/gsp/tu102.c index 11a37963bd4e..823532758afd 100644 --- a/drivers/gpu/drm/nouveau/nvkm/subdev/gsp/tu102.c +++ b/drivers/gpu/drm/nouveau/nvkm/subdev/gsp/tu102.c @@ -420,6 +420,7 @@ tu102_gsp_flcn = { .enable = gm200_flcn_enable, .addr2 = 0x1000, .riscv_irqmask = 0x2b4, + .riscv_irqdest = 0x2b8, .reset_eng = gp102_flcn_reset_eng, .reset_wait_mem_scrubbing = gm200_flcn_reset_wait_mem_scrubbing, .bind_inst = gm200_flcn_bind_inst, diff --git a/drivers/gpu/drm/panfrost/panfrost_gpu.c b/drivers/gpu/drm/panfrost/panfrost_gpu.c index 6081b27829e1..5c3fee65c9e3 100644 --- a/drivers/gpu/drm/panfrost/panfrost_gpu.c +++ b/drivers/gpu/drm/panfrost/panfrost_gpu.c @@ -94,11 +94,10 @@ int panfrost_gpu_soft_reset(struct panfrost_device *pfdev) GPU_IRQ_CLEAN_CACHES_COMPLETED); /* - * All in-flight jobs should have released their cycle - * counter references upon reset, but let us make sure + * Even though all in-flight jobs should have released their cycle counter + * references upon reset, perfcnt's might still hang about. */ - if (drm_WARN_ON(&pfdev->base, atomic_read(&pfdev->cycle_counter.use_count) != 0)) - atomic_set(&pfdev->cycle_counter.use_count, 0); + atomic_set(&pfdev->cycle_counter.use_count, 0); return 0; } diff --git a/drivers/gpu/drm/panfrost/panfrost_perfcnt.c b/drivers/gpu/drm/panfrost/panfrost_perfcnt.c index 3e65589a1093..9e9c2e953036 100644 --- a/drivers/gpu/drm/panfrost/panfrost_perfcnt.c +++ b/drivers/gpu/drm/panfrost/panfrost_perfcnt.c @@ -17,6 +17,7 @@ #include "panfrost_device.h" #include "panfrost_features.h" #include "panfrost_gem.h" +#include "panfrost_gpu.h" #include "panfrost_issues.h" #include "panfrost_job.h" #include "panfrost_mmu.h" @@ -52,6 +53,7 @@ static void panfrost_perfcnt_hw_disable(struct panfrost_device *pfdev) gpu_write(pfdev, GPU_PRFCNT_TILER_EN, 0); if (perfcnt->owns_as_ref) { + panfrost_cycle_counter_put(pfdev); panfrost_mmu_as_put(pfdev, perfcnt->mapping->mmu); perfcnt->owns_as_ref = false; } @@ -84,6 +86,7 @@ static int panfrost_perfcnt_hw_enable(struct panfrost_device *pfdev) return ret; perfcnt->owns_as_ref = true; + panfrost_cycle_counter_get(pfdev); as = ret; cfg = GPU_PERFCNT_CFG_AS(as) | @@ -145,18 +148,17 @@ static int panfrost_perfcnt_dump_locked(struct panfrost_device *pfdev, u32 *stat */ ret = wait_for_completion_interruptible_timeout(&pfdev->perfcnt->dump_comp, msecs_to_jiffies(1000)); - if (!ret) ret = -ETIMEDOUT; - /* We need to restore perfcnt state so the next successful dump can relay it to UM */ - if (ret < 0) { - perfcnt->state |= *state; - *state = 0; - return ret; - } - scoped_guard(rwsem_read, &pfdev->reset.lock) { + /* Restore perfcnt state so the next successful dump can relay it to UM */ + if (ret < 0) { + perfcnt->state |= *state; + *state = 0; + return ret; + } + *state |= perfcnt->state; /* UM must re-enable their session before requesting new dumps. */ diff --git a/drivers/gpu/drm/scheduler/sched_rq.c b/drivers/gpu/drm/scheduler/sched_rq.c index 23f46ec610e7..6f67a146d99c 100644 --- a/drivers/gpu/drm/scheduler/sched_rq.c +++ b/drivers/gpu/drm/scheduler/sched_rq.c @@ -345,6 +345,13 @@ void drm_sched_rq_pop_entity(struct drm_sched_entity *entity) lockdep_assert_held(&entity->lock); + /* + * If entity is getting torn down via drm_sched_entity_kill() we need + * to ensure it does not get re-added to the tree behind it's back. + */ + if (entity->stopped) + return; + spin_lock(&rq->lock); /* diff --git a/drivers/gpu/drm/vc4/vc4_hvs.c b/drivers/gpu/drm/vc4/vc4_hvs.c index b1fb096858cc..537aaa992129 100644 --- a/drivers/gpu/drm/vc4/vc4_hvs.c +++ b/drivers/gpu/drm/vc4/vc4_hvs.c @@ -1677,15 +1677,6 @@ static int vc4_hvs_bind(struct device *dev, struct device *master, void *data) struct device_node *node; unsigned int max_rate; - node = rpi_firmware_find_node(); - if (!node) - return -EINVAL; - - firmware = rpi_firmware_get(node); - of_node_put(node); - if (!firmware) - return -EPROBE_DEFER; - hvs->core_clk = devm_clk_get(&pdev->dev, (vc4->gen >= VC4_GEN_6_C) ? "core" : NULL); if (IS_ERR(hvs->core_clk)) { @@ -1700,6 +1691,15 @@ static int vc4_hvs_bind(struct device *dev, struct device *master, void *data) return PTR_ERR(hvs->disp_clk); } + node = rpi_firmware_find_node(); + if (!node) + return -EINVAL; + + firmware = rpi_firmware_get(node); + of_node_put(node); + if (!firmware) + return -EPROBE_DEFER; + max_rate = rpi_firmware_clk_get_max_rate(firmware, RPI_FIRMWARE_CORE_CLK_ID); rpi_firmware_put(firmware); diff --git a/drivers/gpu/drm/vc4/vc4_irq.c b/drivers/gpu/drm/vc4/vc4_irq.c index c00a3e7c1358..ff405d3c1d4c 100644 --- a/drivers/gpu/drm/vc4/vc4_irq.c +++ b/drivers/gpu/drm/vc4/vc4_irq.c @@ -53,10 +53,6 @@ #include "vc4_regs.h" #include "vc4_trace.h" -#define V3D_DRIVER_IRQS (V3D_INT_OUTOMEM | \ - V3D_INT_FLDONE | \ - V3D_INT_FRDONE) - static void vc4_overflow_mem_work(struct work_struct *work) { @@ -249,6 +245,7 @@ void vc4_irq_enable(struct drm_device *dev) { struct vc4_dev *vc4 = to_vc4_dev(dev); + u32 mask = V3D_INT_FLDONE | V3D_INT_FRDONE; if (WARN_ON_ONCE(vc4->gen > VC4_GEN_4)) return; @@ -256,10 +253,20 @@ vc4_irq_enable(struct drm_device *dev) if (!vc4->v3d) return; - /* Enable the render done interrupts. The out-of-memory interrupt is - * enabled as soon as we have a binner BO allocated. + /* Arming the OOM interrupt before there is a binner BO would raise an + * interrupt nothing can clear. */ - V3D_WRITE(V3D_INTENA, V3D_INT_FLDONE | V3D_INT_FRDONE); + if (vc4->bin_bo) + mask |= V3D_INT_OUTOMEM; + + /* Clear any pending interrupts someone might have left around for us. */ + V3D_WRITE(V3D_INTCTL, mask); + + /* Enable our set of interrupts, masking out any others. */ + V3D_WRITE(V3D_INTDIS, ~mask); + V3D_WRITE(V3D_INTENA, mask); + + enable_irq(vc4->irq); } void @@ -274,14 +281,14 @@ vc4_irq_disable(struct drm_device *dev) return; /* Disable sending interrupts for our driver's IRQs. */ - V3D_WRITE(V3D_INTDIS, V3D_DRIVER_IRQS); - - /* Clear any pending interrupts we might have left. */ - V3D_WRITE(V3D_INTCTL, V3D_DRIVER_IRQS); + V3D_WRITE(V3D_INTDIS, ~0); /* Finish any interrupt handler still in flight. */ disable_irq(vc4->irq); + /* Clear any pending interrupts we might have left. */ + V3D_WRITE(V3D_INTCTL, ~0); + cancel_work_sync(&vc4->overflow_mem_work); } @@ -324,15 +331,12 @@ void vc4_irq_reset(struct drm_device *dev) if (WARN_ON_ONCE(vc4->gen > VC4_GEN_4)) return; - /* Acknowledge any stale IRQs. */ - V3D_WRITE(V3D_INTCTL, V3D_DRIVER_IRQS); - - /* - * Turn all our interrupts on. Binner out of memory is the only - * one we expect to trigger at this point, since the reset cleared - * the overflow memory address and none has been supplied yet. + /* bin_bo_alloc() may arm OUTOMEM between the bin_bo check and the + * INTDIS write in vc4_irq_enable(), which would then mask it again. */ - V3D_WRITE(V3D_INTENA, V3D_DRIVER_IRQS); + scoped_guard(mutex, &vc4->bin_bo_lock) { + vc4_irq_enable(dev); + } spin_lock_irqsave(&vc4->job_lock, irqflags); vc4_cancel_bin_job(dev); diff --git a/drivers/gpu/drm/vc4/vc4_v3d.c b/drivers/gpu/drm/vc4/vc4_v3d.c index 5c1c99533b30..86e8b6d2e6a1 100644 --- a/drivers/gpu/drm/vc4/vc4_v3d.c +++ b/drivers/gpu/drm/vc4/vc4_v3d.c @@ -302,11 +302,15 @@ static int bin_bo_alloc(struct vc4_dev *vc4) int vc4_v3d_bin_bo_get(struct vc4_dev *vc4, bool *used) { - int ret = 0; + int ret; if (WARN_ON_ONCE(vc4->gen > VC4_GEN_4)) return -ENODEV; + ret = vc4_v3d_pm_get(vc4); + if (ret) + return ret; + mutex_lock(&vc4->bin_bo_lock); if (used && *used) @@ -322,6 +326,7 @@ int vc4_v3d_bin_bo_get(struct vc4_dev *vc4, bool *used) complete: mutex_unlock(&vc4->bin_bo_lock); + vc4_v3d_pm_put(vc4); return ret; } @@ -373,7 +378,6 @@ static int vc4_v3d_runtime_resume(struct device *dev) vc4_v3d_init_hw(&vc4->base); vc4_irq_enable(&vc4->base); - enable_irq(vc4->irq); return 0; } diff --git a/drivers/gpu/drm/xe/Kconfig b/drivers/gpu/drm/xe/Kconfig index 502c7b3c1f16..049d2f25d0e6 100644 --- a/drivers/gpu/drm/xe/Kconfig +++ b/drivers/gpu/drm/xe/Kconfig @@ -10,6 +10,7 @@ config DRM_XE # the shmem_readpage() which depends upon tmpfs select SHMEM select TMPFS + select CONFIGFS_FS select DRM_BUDDY select DRM_CLIENT_SELECTION select DRM_KMS_HELPER diff --git a/drivers/gpu/drm/xe/regs/xe_gt_regs.h b/drivers/gpu/drm/xe/regs/xe_gt_regs.h index 650f117c3e13..1937b9e08d50 100644 --- a/drivers/gpu/drm/xe/regs/xe_gt_regs.h +++ b/drivers/gpu/drm/xe/regs/xe_gt_regs.h @@ -107,6 +107,7 @@ #define GAMSTLB_CTRL2 XE_REG_MCR(0x4788) #define STLB_SINGLE_BANK_MODE REG_BIT(11) +#define XE2_LMEM_CFG_MCR XE_REG_MCR(0x48b0) #define XE2_LMEM_CFG XE_REG(0x48b0) #define XE2_GAMWALK_CTRL 0x47e4 diff --git a/drivers/gpu/drm/xe/regs/xe_lrc_layout.h b/drivers/gpu/drm/xe/regs/xe_lrc_layout.h index 6f7abc0181b5..a2795aa9fd71 100644 --- a/drivers/gpu/drm/xe/regs/xe_lrc_layout.h +++ b/drivers/gpu/drm/xe/regs/xe_lrc_layout.h @@ -45,4 +45,7 @@ #define INDIRECT_CTX_RING_START_UDW (0x08 + 1) #define INDIRECT_CTX_RING_CTL (0x0a + 1) +#define CTX_INDIRECT_CTX_OFFSET_MASK REG_GENMASK(15, 6) +#define CTX_INDIRECT_CTX_OFFSET_DEFAULT REG_FIELD_PREP(CTX_INDIRECT_CTX_OFFSET_MASK, 0xd) + #endif diff --git a/drivers/gpu/drm/xe/xe_amc.c b/drivers/gpu/drm/xe/xe_amc.c index edd50bf8261e..d6fe59669a74 100644 --- a/drivers/gpu/drm/xe/xe_amc.c +++ b/drivers/gpu/drm/xe/xe_amc.c @@ -15,9 +15,11 @@ #include "regs/xe_i2c_regs.h" #include "xe_amc.h" +#include "xe_any.h" #include "xe_device.h" #include "xe_i2c.h" #include "xe_mmio.h" +#include "xe_pm.h" /** * DOC: Add-In Management Controller (AMC) @@ -108,11 +110,14 @@ static void xe_amc_work(struct work_struct *work) { const struct amc_request *request = &amc_get_alert_reason; struct xe_amc *amc = from_work(amc, work, work); + struct xe_device *xe = xe_any_to_xe(amc->i2c->drm_dev); u8 alert_reason = AMC_ALERT_UNKNOWN; struct amc_response response; struct i2c_client *client; int ret; + xe_pm_runtime_get(xe); + client = amc->i2c->client[XE_I2C_CLIENT_AMC]; if (IS_ERR_OR_NULL(client)) goto out_reassert_interrupt; @@ -160,12 +165,15 @@ out_reassert_interrupt: case AMC_ALERT_OOB_RESET: case AMC_ALERT_CATERR: dev_warn(amc->i2c->drm_dev, "AMC Alert: %s\n", amc_alert[alert_reason]); - xe_device_declare_wedged(i2c_client_to_xe_device(client)); + xe_device_declare_wedged(i2c_client_to_xe_device(client), + DRM_WEDGE_RECOVERY_REBIND | DRM_WEDGE_RECOVERY_BUS_RESET); break; default: dev_warn(amc->i2c->drm_dev, "unknown AMC alert: %d\n", alert_reason); break; } + + xe_pm_runtime_put(xe); } void xe_amc_handle_alert(struct xe_i2c *i2c) diff --git a/drivers/gpu/drm/xe/xe_configfs.h b/drivers/gpu/drm/xe/xe_configfs.h index 10a00d6bbf8f..d726800de26a 100644 --- a/drivers/gpu/drm/xe/xe_configfs.h +++ b/drivers/gpu/drm/xe/xe_configfs.h @@ -14,7 +14,6 @@ struct pci_dev; -#if IS_ENABLED(CONFIG_CONFIGFS_FS) int xe_configfs_init(void); void xe_configfs_exit(void); void xe_configfs_check_device(struct pci_dev *pdev); @@ -36,34 +35,5 @@ u32 xe_configfs_get_ctx_restore_post_bb(struct pci_dev *pdev, unsigned int xe_configfs_get_max_vfs(struct pci_dev *pdev); bool xe_configfs_admin_only_pf(struct pci_dev *pdev); #endif -#else -static inline int xe_configfs_init(void) { return 0; } -static inline void xe_configfs_exit(void) { } -static inline void xe_configfs_check_device(struct pci_dev *pdev) { } -static inline bool xe_configfs_get_survivability_mode(struct pci_dev *pdev) { return false; } -static inline bool xe_configfs_primary_gt_allowed(struct pci_dev *pdev) { return true; } -static inline bool xe_configfs_media_gt_allowed(struct pci_dev *pdev) { return true; } -static inline u64 xe_configfs_get_engines_allowed(struct pci_dev *pdev) { return U64_MAX; } -static inline bool xe_configfs_get_psmi_enabled(struct pci_dev *pdev) { return false; } -static inline bool xe_configfs_get_enable_multi_queue(struct pci_dev *pdev) { return true; } -static inline u32 xe_configfs_get_migrate_ulls_period_ms(struct pci_dev *pdev) { return 5; } -static inline bool xe_configfs_get_disable_vram_page_offline(struct pci_dev *pdev) { return false; } -static inline u32 xe_configfs_get_ctx_restore_mid_bb(struct pci_dev *pdev, - enum xe_engine_class class, - const u32 **cs) { return 0; } -static inline u32 xe_configfs_get_ctx_restore_post_bb(struct pci_dev *pdev, - enum xe_engine_class class, - const u32 **cs) { return 0; } -#ifdef CONFIG_PCI_IOV -static inline unsigned int xe_configfs_get_max_vfs(struct pci_dev *pdev) -{ - return xe_modparam.max_vfs; -} -static inline bool xe_configfs_admin_only_pf(struct pci_dev *pdev) -{ - return XE_DEFAULT_ADMIN_ONLY_PF; -} -#endif -#endif #endif diff --git a/drivers/gpu/drm/xe/xe_device.c b/drivers/gpu/drm/xe/xe_device.c index 7e6027f49a4c..c41533644c92 100644 --- a/drivers/gpu/drm/xe/xe_device.c +++ b/drivers/gpu/drm/xe/xe_device.c @@ -690,6 +690,16 @@ static int xe_device_vram_alloc(struct xe_device *xe) return 0; } +static void wedged_work(struct work_struct *work); +static void xe_device_wedged_fini(struct drm_device *drm, void *arg); + +static int xe_device_wedged_init(struct xe_device *xe) +{ + INIT_WORK(&xe->wedged.work, wedged_work); + + return drmm_add_action_or_reset(&xe->drm, xe_device_wedged_fini, xe); +} + /** * xe_device_probe_early: Device early probe * @xe: xe device instance @@ -758,6 +768,10 @@ int xe_device_probe_early(struct xe_device *xe) if (err) return err; + err = xe_device_wedged_init(xe); + if (err) + return err; + return 0; } ALLOW_ERROR_INJECTION(xe_device_probe_early, ERRNO); /* See xe_pci_probe() */ @@ -888,7 +902,9 @@ int xe_device_probe(struct xe_device *xe) xe_uid_probe(xe); - xe_pat_init_early(xe); + err = xe_pat_init_early(xe); + if (err) + return err; err = xe_sriov_init(xe); if (err) @@ -1088,10 +1104,6 @@ int xe_device_probe(struct xe_device *xe) detect_preproduction_hw(xe); - err = drmm_add_action_or_reset(&xe->drm, xe_device_wedged_fini, xe); - if (err) - goto err_unregister_display; - /* * Process and log any errors detected by hardware. Possible results can * include declaring the device as wedged, which must be done only after @@ -1371,16 +1383,12 @@ u64 xe_device_uncanonicalize_addr(struct xe_device *xe, u64 address) * firmware and restore device to normal operation. */ -/** - * xe_device_set_wedged_method - Set wedged recovery method - * @xe: xe device instance - * @method: recovery method to set - * - * Set wedged recovery method to be sent in drm wedged uevent. - */ -void xe_device_set_wedged_method(struct xe_device *xe, unsigned long method) +static void wedged_work(struct work_struct *work) { - xe->wedged.method = method; + struct xe_device *xe = container_of(work, struct xe_device, wedged.work); + + /* Notify userspace of wedged device */ + drm_dev_wedged_event(&xe->drm, xe->wedged.method, NULL); } #define WEDGED_URL "https://docs.kernel.org/gpu/drm-uapi.html#device-wedging" @@ -1389,11 +1397,10 @@ void xe_device_set_wedged_method(struct xe_device *xe, unsigned long method) /** * xe_device_declare_wedged - Declare device wedged * @xe: xe device instance + * @method: method(s) to be used for recovery * * This is a final state that can only be cleared with the recovery method - * specified in the drm wedged uevent. The method can be set using - * xe_device_set_wedged_method before declaring the device as wedged. If no method - * is set, reprobe (unbind/re-bind) will be sent by default. + * specified in the drm wedged uevent. * * In this state every IOCTL will be blocked so the GT cannot be used. * In general it will be called upon any critical error such as gt reset @@ -1404,7 +1411,7 @@ void xe_device_set_wedged_method(struct xe_device *xe, unsigned long method) * snapshot capture. In this mode, GT reset won't be attempted so the state of * the issue is preserved for further debugging. */ -void xe_device_declare_wedged(struct xe_device *xe) +void xe_device_declare_wedged(struct xe_device *xe, unsigned long method) { struct xe_gt *gt; u8 id; @@ -1423,26 +1430,21 @@ void xe_device_declare_wedged(struct xe_device *xe) "For recovery procedure, refer to %s\n" "Please file a _new_ bug report at %s\n", WEDGED_URL, XE_BUG_URL); - } - for_each_gt(gt, xe, id) - xe_gt_declare_wedged(gt); + for_each_initialized_gt(gt, xe, id) + xe_gt_declare_wedged(gt); - if (xe_device_wedged(xe)) { /* * XE_WEDGED_MODE_UPON_ANY_HANG_NO_RESET is intended for debugging * hangs, so wedge the device with 'none' recovery method and have * it available to the user for debugging. */ if (xe->wedged.mode == XE_WEDGED_MODE_UPON_ANY_HANG_NO_RESET) - xe_device_set_wedged_method(xe, DRM_WEDGE_RECOVERY_NONE); - /* If no wedge recovery method is set, use default */ - else if (!xe->wedged.method) - xe_device_set_wedged_method(xe, DRM_WEDGE_RECOVERY_REBIND | - DRM_WEDGE_RECOVERY_BUS_RESET); + xe->wedged.method = DRM_WEDGE_RECOVERY_NONE; + else + xe->wedged.method = method; - /* Notify userspace of wedged device */ - drm_dev_wedged_event(&xe->drm, xe->wedged.method, NULL); + schedule_work(&xe->wedged.work); } } diff --git a/drivers/gpu/drm/xe/xe_device.h b/drivers/gpu/drm/xe/xe_device.h index 6d3d6d5eba29..3ce1481d0e57 100644 --- a/drivers/gpu/drm/xe/xe_device.h +++ b/drivers/gpu/drm/xe/xe_device.h @@ -139,6 +139,10 @@ static inline bool xe_device_uc_enabled(struct xe_device *xe) for_each_gt((gt__), (tile__)->xe, (id__)) \ for_each_if((gt__)->tile == (tile__)) +#define for_each_initialized_gt(gt__, xe__, id__) \ + for_each_gt((gt__), (xe__), (id__)) \ + for_each_if(READ_ONCE((gt__)->initialized)) + static inline struct xe_force_wake *gt_to_fw(struct xe_gt *gt) { return >->pm.fw; @@ -260,8 +264,7 @@ static inline bool xe_debug_page_size_mode_is_mixed(struct xe_device *xe) } #endif -void xe_device_set_wedged_method(struct xe_device *xe, unsigned long method); -void xe_device_declare_wedged(struct xe_device *xe); +void xe_device_declare_wedged(struct xe_device *xe, unsigned long method); int xe_device_validate_wedged_mode(struct xe_device *xe, unsigned int mode); const char *xe_wedged_mode_to_string(enum xe_wedged_mode mode); diff --git a/drivers/gpu/drm/xe/xe_device_types.h b/drivers/gpu/drm/xe/xe_device_types.h index 41f703a87916..5aa52975ebb4 100644 --- a/drivers/gpu/drm/xe/xe_device_types.h +++ b/drivers/gpu/drm/xe/xe_device_types.h @@ -227,6 +227,8 @@ struct xe_device { u8 has_sriov:1; /** @info.has_sysctrl: Supports System Controller */ u8 has_sysctrl:1; + /** @info.has_temp_sentinel: Device has temperature-unavailable sentinels */ + u8 has_temp_sentinel:1; /** @info.has_usm: Device has unified shared memory support */ u8 has_usm:1; /** @info.has_64bit_timestamp: Device supports 64-bit timestamps */ @@ -560,6 +562,8 @@ struct xe_device { unsigned long method; /** @wedged.inconsistent_reset: Inconsistent reset policy state between GTs */ bool inconsistent_reset; + /** @wedged.work: Worker to defer non-atomic calls */ + struct work_struct work; } wedged; /** @devres_group: devres group */ diff --git a/drivers/gpu/drm/xe/xe_drm_ras.c b/drivers/gpu/drm/xe/xe_drm_ras.c index 7f3695707611..30cf40ee5fe4 100644 --- a/drivers/gpu/drm/xe/xe_drm_ras.c +++ b/drivers/gpu/drm/xe/xe_drm_ras.c @@ -16,6 +16,17 @@ static const char * const error_components[] = DRM_XE_RAS_ERROR_COMPONENT_NAMES; static const char * const error_severity[] = DRM_XE_RAS_ERROR_SEVERITY_NAMES; +static bool drm_ras_counter_is_valid(u32 severity, u32 component) +{ + if (!in_range(severity, DRM_XE_RAS_ERR_SEV_CORRECTABLE, DRM_XE_RAS_ERR_SEV_MAX)) + return false; + + if (!in_range(component, DRM_XE_RAS_ERR_COMP_CORE_COMPUTE, DRM_XE_RAS_ERR_COMP_MAX - 1)) + return false; + + return true; +} + static int query_error_counter(struct xe_device *xe, enum drm_xe_ras_error_severity severity, u32 error_id, const char **name, u32 *val) @@ -231,7 +242,7 @@ null_info: void xe_drm_ras_event(struct xe_device *xe, u32 component, u32 severity, u32 value) { struct xe_drm_ras *ras = &xe->ras; - struct xe_drm_ras_counter *info = ras->info[severity]; + struct xe_drm_ras_counter *info; struct drm_ras_node *node; int ret; @@ -239,7 +250,11 @@ void xe_drm_ras_event(struct xe_device *xe, u32 component, u32 severity, u32 val if (!xe->info.has_drm_ras) return; + if (!drm_ras_counter_is_valid(severity, component)) + return; + node = &ras->node[severity]; + info = ras->info[severity]; if (!info || !info[component].name) return; diff --git a/drivers/gpu/drm/xe/xe_gpu_scheduler_types.h b/drivers/gpu/drm/xe/xe_gpu_scheduler_types.h index 63d9bf92583c..78ef2e8ded4f 100644 --- a/drivers/gpu/drm/xe/xe_gpu_scheduler_types.h +++ b/drivers/gpu/drm/xe/xe_gpu_scheduler_types.h @@ -47,7 +47,10 @@ struct xe_gpu_scheduler { const struct xe_sched_backend_ops *ops; /** @msgs: list of messages to be processed in @work_process_msg */ struct list_head msgs; - /** @msg_lock: Message lock */ + /** + * @msg_lock: Protects @msgs and guc->suspend_pending (indicates a + * suspend message is in flight) of exec queues on this scheduler. + */ spinlock_t msg_lock; /** @work_process_msg: processes messages */ struct work_struct work_process_msg; diff --git a/drivers/gpu/drm/xe/xe_gsc.c b/drivers/gpu/drm/xe/xe_gsc.c index 524ac56bdcc7..2bbe0f20ff8d 100644 --- a/drivers/gpu/drm/xe/xe_gsc.c +++ b/drivers/gpu/drm/xe/xe_gsc.c @@ -340,7 +340,8 @@ static int gsc_er_complete(struct xe_gt *gt) * declare the device as wedged. */ xe_gt_err(gt, "GSC ER timed out!\n"); - xe_device_declare_wedged(gt_to_xe(gt)); + xe_device_declare_wedged(gt_to_xe(gt), + DRM_WEDGE_RECOVERY_REBIND | DRM_WEDGE_RECOVERY_BUS_RESET); return -EIO; } diff --git a/drivers/gpu/drm/xe/xe_gt.c b/drivers/gpu/drm/xe/xe_gt.c index 775c826b68b4..286aee5775c0 100644 --- a/drivers/gpu/drm/xe/xe_gt.c +++ b/drivers/gpu/drm/xe/xe_gt.c @@ -175,6 +175,7 @@ static void xe_gt_enable_comp_1wcoh(struct xe_gt *gt) } static void gt_reset_worker(struct work_struct *w); +static void gt_wedge_worker(struct work_struct *w); static int emit_job_sync(struct xe_exec_queue *q, struct xe_bb *bb, long timeout_jiffies, bool force_reset) @@ -546,6 +547,8 @@ int xe_gt_init_early(struct xe_gt *gt) xe_gt_mcr_init_early(gt); xe_pat_init(gt); + INIT_WORK(>->reset.worker, gt_reset_worker); + INIT_WORK(>->wedge.worker, gt_wedge_worker); return 0; } @@ -630,8 +633,26 @@ static int gt_init_with_gt_forcewake(struct xe_gt *gt) return 0; } +static void gt_worker_disable(void *arg) +{ + struct xe_gt *gt = arg; + + WRITE_ONCE(gt->initialized, false); + + if (disable_work_sync(>->reset.worker)) + /* + * If gt_reset_worker was halted from executing, take care of + * releasing the rpm reference here. + */ + xe_pm_runtime_put(gt_to_xe(gt)); + + if (disable_work_sync(>->wedge.worker)) + xe_pm_runtime_put(gt_to_xe(gt)); +} + static int gt_init_with_all_forcewake(struct xe_gt *gt) { + struct xe_device *xe = gt_to_xe(gt); int err; CLASS(xe_force_wake, fw_ref)(gt_to_fw(gt), XE_FORCEWAKE_ALL); @@ -692,11 +713,15 @@ static int gt_init_with_all_forcewake(struct xe_gt *gt) xe_gt_apply_ccs_mode(gt); } - if (IS_SRIOV_PF(gt_to_xe(gt)) && xe_gt_is_main_type(gt)) - xe_lmtt_init_hw(>_to_tile(gt)->sriov.pf.lmtt); - - if (IS_SRIOV_PF(gt_to_xe(gt))) + if (IS_SRIOV_PF(gt_to_xe(gt))) { + xe_lmtt_init_hw(gt); xe_gt_sriov_pf_init_hw(gt); + } + + /* Last action registered here so devres drains resets before teardown */ + err = devm_add_action_or_reset(xe->drm.dev, gt_worker_disable, gt); + if (err) + return err; return 0; } @@ -706,12 +731,7 @@ static void xe_gt_fini(void *arg) struct xe_gt *gt = arg; int i; - if (disable_work_sync(>->reset.worker)) - /* - * If gt_reset_worker was halted from executing, take care of - * releasing the rpm reference here. - */ - xe_pm_runtime_put(gt_to_xe(gt)); + gt_worker_disable(gt); for (i = 0; i < XE_ENGINE_CLASS_MAX; ++i) xe_hw_fence_irq_finish(>->fence_irq[i]); @@ -724,8 +744,6 @@ int xe_gt_init(struct xe_gt *gt) int err; int i; - INIT_WORK(>->reset.worker, gt_reset_worker); - for (i = 0; i < XE_ENGINE_CLASS_MAX; ++i) { gt->ring_ops[i] = xe_ring_ops_get(gt, i); xe_hw_fence_irq_init(>->fence_irq[i]); @@ -754,8 +772,10 @@ int xe_gt_init(struct xe_gt *gt) xe_force_wake_init_engines(gt, gt_to_fw(gt)); err = gt_init_with_all_forcewake(gt); - if (err) + if (err) { + gt_worker_disable(gt); return err; + } xe_gt_record_user_engines(gt); @@ -769,6 +789,8 @@ int xe_gt_init(struct xe_gt *gt) return err; } + /* Must be last */ + WRITE_ONCE(gt->initialized, true); return 0; } @@ -894,11 +916,10 @@ static int do_gt_restart(struct xe_gt *gt) if (err) return err; - if (IS_SRIOV_PF(gt_to_xe(gt)) && xe_gt_is_main_type(gt)) - xe_lmtt_init_hw(>_to_tile(gt)->sriov.pf.lmtt); - - if (IS_SRIOV_PF(gt_to_xe(gt))) + if (IS_SRIOV_PF(gt_to_xe(gt))) { + xe_lmtt_init_hw(gt); xe_gt_sriov_pf_init_hw(gt); + } xe_mocs_init(gt); @@ -986,7 +1007,8 @@ err_out: err_fail: xe_log_err_fatal(gt, GT, err, "reset failed\n"); - xe_device_declare_wedged(gt_to_xe(gt)); + xe_device_declare_wedged(gt_to_xe(gt), + DRM_WEDGE_RECOVERY_REBIND | DRM_WEDGE_RECOVERY_BUS_RESET); err_pm_put: xe_pm_runtime_put(gt_to_xe(gt)); } @@ -1189,6 +1211,15 @@ struct xe_hw_engine *xe_gt_any_hw_engine(struct xe_gt *gt) return NULL; } +static void gt_wedge_worker(struct work_struct *w) +{ + struct xe_gt *gt = container_of(w, typeof(*gt), wedge.worker); + + xe_uc_declare_wedged(>->uc); + xe_tlb_inval_reset(>->tlb_inval); + xe_pm_runtime_put(gt_to_xe(gt)); +} + /** * xe_gt_declare_wedged() - Declare GT wedged * @gt: the GT object @@ -1198,8 +1229,12 @@ struct xe_hw_engine *xe_gt_any_hw_engine(struct xe_gt *gt) */ void xe_gt_declare_wedged(struct xe_gt *gt) { - xe_gt_assert(gt, gt_to_xe(gt)->wedged.mode); + struct xe_device *xe = gt_to_xe(gt); - xe_uc_declare_wedged(>->uc); - xe_tlb_inval_reset(>->tlb_inval); + xe_gt_assert(gt, xe->wedged.mode); + xe_uc_reset_prepare(>->uc); + + xe_pm_runtime_get_noresume(xe); + if (!queue_work(gt->ordered_wq, >->wedge.worker)) + xe_pm_runtime_put(xe); } diff --git a/drivers/gpu/drm/xe/xe_gt_sriov_vf.c b/drivers/gpu/drm/xe/xe_gt_sriov_vf.c index 37899fcf5b22..28ec83bb8100 100644 --- a/drivers/gpu/drm/xe/xe_gt_sriov_vf.c +++ b/drivers/gpu/drm/xe/xe_gt_sriov_vf.c @@ -1462,7 +1462,7 @@ static void vf_post_migration_recovery(struct xe_gt *gt) fail: vf_post_migration_abort(gt); xe_gt_sriov_err(gt, "migration recovery failed (%pe)\n", ERR_PTR(err)); - xe_device_declare_wedged(xe); + xe_device_declare_wedged(xe, DRM_WEDGE_RECOVERY_REBIND | DRM_WEDGE_RECOVERY_BUS_RESET); return; queue: diff --git a/drivers/gpu/drm/xe/xe_gt_types.h b/drivers/gpu/drm/xe/xe_gt_types.h index 628911346455..c00a7c171f80 100644 --- a/drivers/gpu/drm/xe/xe_gt_types.h +++ b/drivers/gpu/drm/xe/xe_gt_types.h @@ -233,6 +233,12 @@ struct xe_gt { struct work_struct worker; } reset; + /** @wedge: state for GT wedge */ + struct { + /** @wedge.worker: worker for GT wedge to be done async */ + struct work_struct worker; + } wedge; + /** @tlb_inval: TLB invalidation state */ struct xe_tlb_inval tlb_inval; @@ -419,6 +425,9 @@ struct xe_gt { /** @eu_stall: EU stall counters subsystem per gt info */ struct xe_eu_stall_gt *eu_stall; + + /** @initialized: GT is initialized */ + bool initialized; }; #endif diff --git a/drivers/gpu/drm/xe/xe_guc.c b/drivers/gpu/drm/xe/xe_guc.c index 763a3dbca606..957120db8fdc 100644 --- a/drivers/gpu/drm/xe/xe_guc.c +++ b/drivers/gpu/drm/xe/xe_guc.c @@ -1840,7 +1840,6 @@ void xe_guc_declare_wedged(struct xe_guc *guc) { xe_gt_assert(guc_to_gt(guc), guc_to_xe(guc)->wedged.mode); - xe_guc_reset_prepare(guc); xe_guc_ct_stop(&guc->ct); xe_guc_submit_wedge(guc); } diff --git a/drivers/gpu/drm/xe/xe_guc_exec_queue_types.h b/drivers/gpu/drm/xe/xe_guc_exec_queue_types.h index d27826b36649..74b711abe257 100644 --- a/drivers/gpu/drm/xe/xe_guc_exec_queue_types.h +++ b/drivers/gpu/drm/xe/xe_guc_exec_queue_types.h @@ -52,7 +52,10 @@ struct xe_guc_exec_queue { u16 id; /** @suspend_wait: wait queue used to wait on pending suspends */ wait_queue_head_t suspend_wait; - /** @suspend_pending: a suspend of the exec_queue is pending */ + /** + * @suspend_pending: a suspend of the exec_queue is pending. + * Protected by @sched.msg_lock. + */ bool suspend_pending; /** * @suspend_count: Reference count of active suspend requests. The diff --git a/drivers/gpu/drm/xe/xe_guc_submit.c b/drivers/gpu/drm/xe/xe_guc_submit.c index 0b231228bde8..01f79f8883ba 100644 --- a/drivers/gpu/drm/xe/xe_guc_submit.c +++ b/drivers/gpu/drm/xe/xe_guc_submit.c @@ -1453,7 +1453,7 @@ static bool guc_submit_hint_wedged(struct xe_guc *guc) if (xe_device_wedged(xe)) return true; - xe_device_declare_wedged(xe); + xe_device_declare_wedged(xe, DRM_WEDGE_RECOVERY_REBIND | DRM_WEDGE_RECOVERY_BUS_RESET); return true; } @@ -1599,6 +1599,7 @@ guc_exec_queue_timedout_job(struct drm_sched_job *drm_job) int err = -ETIME; pid_t pid = -1; bool wedged = false, wedge_device = false, skip_timeout_check; + int idx; xe_gt_assert(guc_to_gt(guc), !exec_queue_destroyed(q)); @@ -1614,6 +1615,11 @@ guc_exec_queue_timedout_job(struct drm_sched_job *drm_job) vf_recovery(guc)) return DRM_GPU_SCHED_STAT_NO_HANG; + if (!drm_dev_enter(&xe->drm, &idx)) { + xe_sched_job_set_error(job, -ENODEV); + return DRM_GPU_SCHED_STAT_NO_HANG; + } + /* Kill the run_job entry point */ if (xe_exec_queue_is_multi_queue(q)) xe_guc_exec_queue_group_stop(q); @@ -1780,12 +1786,14 @@ trigger_reset: } if (wedge_device) - xe_device_declare_wedged(gt_to_xe(q->gt)); + xe_device_declare_wedged(gt_to_xe(q->gt), + DRM_WEDGE_RECOVERY_REBIND | DRM_WEDGE_RECOVERY_BUS_RESET); /* * We want the job added back to the pending list so it gets freed; this * is what DRM_GPU_SCHED_STAT_NO_HANG does. */ + drm_dev_exit(idx); return DRM_GPU_SCHED_STAT_NO_HANG; rearm: @@ -1799,6 +1807,7 @@ rearm: else xe_sched_submission_start(sched); handle_vf_resume: + drm_dev_exit(idx); return DRM_GPU_SCHED_STAT_NO_HANG; } @@ -1935,16 +1944,11 @@ static void __guc_exec_queue_process_msg_set_sched_props(struct xe_sched_msg *ms kfree(msg); } -static void __suspend_fence_signal(struct xe_exec_queue *q) +static void suspend_wait_wake(struct xe_exec_queue *q) { struct xe_guc *guc = exec_queue_to_guc(q); struct xe_device *xe = guc_to_xe(guc); - if (!q->guc->suspend_pending) - return; - - WRITE_ONCE(q->guc->suspend_pending, false); - /* * We use a GuC shared wait queue for VFs because the VF resfix start * interrupt must be able to wake all instances of suspend_wait. This @@ -1957,6 +1961,15 @@ static void __suspend_fence_signal(struct xe_exec_queue *q) wake_up(&q->guc->suspend_wait); } +static void __suspend_fence_signal(struct xe_exec_queue *q) +{ + if (!q->guc->suspend_pending) + return; + + WRITE_ONCE(q->guc->suspend_pending, false); + suspend_wait_wake(q); +} + static void suspend_fence_signal(struct xe_exec_queue *q) { struct xe_guc *guc = exec_queue_to_guc(q); @@ -2210,7 +2223,13 @@ static void guc_exec_queue_kill(struct xe_exec_queue *q) { trace_xe_exec_queue_kill(q); set_exec_queue_killed(q); - __suspend_fence_signal(q); + /* + * Do not signal the suspend fence here, the queue may still be running + * on the hardware. Only wake any suspend waiter so it observes the + * killed state instead of waiting out the full timeout, suspend_pending + * stays set until the queue is torn down. + */ + suspend_wait_wake(q); xe_guc_exec_queue_trigger_cleanup(q); } @@ -2399,7 +2418,12 @@ static bool __guc_exec_queue_resume(struct xe_exec_queue *q) bool last; xe_sched_msg_lock(sched); - xe_gt_assert(guc_to_gt(guc), !ge->suspend_pending); + /* + * A killed, banned or wedged queue keeps suspend_pending set until it + * is torn down, so only assert the flag is clear otherwise. + */ + xe_gt_assert(guc_to_gt(guc), !ge->suspend_pending || + exec_queue_killed_or_banned_or_wedged(q)); xe_gt_assert(guc_to_gt(guc), ge->suspend_count > 0); last = (--ge->suspend_count == 0); if (last) { @@ -2469,8 +2493,10 @@ static void guc_exec_queue_suspend_timeout_ban(struct xe_exec_queue *q) /* * The GuC failed to respond to the suspend within the timeout. This is * not recoverable for this context, so ban it and tear it down via - * cleanup rather than leave it suspended forever. __suspend_fence_signal - * clears suspend_pending and wakes any waiter. + * cleanup rather than leave it suspended forever. The suspend fence is + * not signalled here, the queue may still be running on the hardware, + * so suspend_pending stays set until teardown. The waiter that timed + * out is the caller, so no wake up is needed either. * * @q is the primary here; it owns the group's GuC context, so a failure * to suspend it wedges the whole group. Ban and tear down the entire @@ -2478,11 +2504,9 @@ static void guc_exec_queue_suspend_timeout_ban(struct xe_exec_queue *q) */ if (xe_exec_queue_is_multi_queue(q)) { set_exec_queue_group_banned(q); - __suspend_fence_signal(q); xe_guc_exec_queue_group_trigger_cleanup(q); } else { set_exec_queue_banned(q); - __suspend_fence_signal(q); xe_guc_exec_queue_trigger_cleanup(q); } } @@ -2505,9 +2529,9 @@ static int guc_exec_queue_wait_suspend_done(struct xe_exec_queue *q, bool blocki int ret; /* - * Likely don't need to check exec_queue_killed() as we clear - * suspend_pending upon kill but to be paranoid but races in which - * suspend_pending is set after kill also check kill here. + * A kill does not clear suspend_pending, the queue may still be running + * on the hardware, so exec_queue_killed() is what ends the wait in that + * case and the queue is torn down asynchronously. */ #define WAIT_COND \ (!READ_ONCE(q->guc->suspend_pending) || exec_queue_killed(q) || \ @@ -2716,10 +2740,12 @@ static void guc_exec_queue_stop(struct xe_guc *guc, struct xe_exec_queue *q) if (exec_queue_destroyed(q)) do_destroy = true; } + xe_sched_msg_lock(sched); if (q->guc->suspend_pending) { set_exec_queue_suspended(q); suspend_fence_signal(q); } + xe_sched_msg_unlock(sched); atomic_and(EXEC_QUEUE_STATE_WEDGED | EXEC_QUEUE_STATE_BANNED | EXEC_QUEUE_STATE_KILLED | EXEC_QUEUE_STATE_DESTROYED | EXEC_QUEUE_STATE_SUSPENDED, @@ -3333,33 +3359,50 @@ static void handle_sched_done(struct xe_guc *guc, struct xe_exec_queue *q, smp_wmb(); wake_up_all(&guc->ct.wq); } else { + bool was_pending; + xe_gt_assert(guc_to_gt(guc), runnable_state == 0); xe_gt_assert(guc_to_gt(guc), exec_queue_pending_disable(q)); - if (q->guc->suspend_pending) { + /* + * A TDR stops the scheduler, which can trap a queued SUSPEND + * message, and then issues a disable of its own. suspend_pending + * is still set in that case, so only attribute this SCHED_DONE + * to a suspend if the SUSPEND message actually ran, i.e. it + * marked the queue suspended before disabling scheduling. The + * trapped message completes the suspend once submission + * restarts. + */ + xe_sched_msg_lock(&q->guc->sched); + was_pending = q->guc->suspend_pending && exec_queue_suspended(q); + if (was_pending) { clear_exec_queue_pending_disable(q); suspend_fence_signal(q); - } else { - if (exec_queue_banned(q)) { - smp_wmb(); - wake_up_all(&guc->ct.wq); - } - if (exec_queue_destroyed(q)) { - /* - * Make sure to clear the pending_disable only - * after sampling the destroyed state. We want - * to ensure we don't trigger the unregister too - * early with something intending to only - * disable scheduling. The caller doing the - * destroy must wait for an ongoing - * pending_disable before marking as destroyed. - */ - clear_exec_queue_pending_disable(q); + } + xe_sched_msg_unlock(&q->guc->sched); + + if (!was_pending) { + /* + * Make sure to clear the pending_disable only after + * sampling the destroyed state. We want to ensure we + * don't trigger the unregister too early with something + * intending to only disable scheduling. The caller + * doing the destroy must wait for an ongoing + * pending_disable before marking as destroyed. + */ + bool destroyed = exec_queue_destroyed(q); + + clear_exec_queue_pending_disable(q); + if (destroyed) deregister_exec_queue(guc, q); - } else { - clear_exec_queue_pending_disable(q); - } } + + /* + * Wake after pending_disable is cleared, not before, so waiters + * such as the TDR see the updated state on the first re-check. + */ + smp_wmb(); + wake_up_all(&guc->ct.wq); } } @@ -3561,7 +3604,7 @@ int xe_guc_uncorrectable_error_handler(struct xe_guc *guc, u32 *msg, u32 len) guc_id = msg[0]; if (guc_id == GUC_ID_UNKNOWN) { - xe_gt_err(gt, "GuC: Uncorrectable local error with unknown GuC id\n"); + xe_gt_err_ratelimited(gt, "GuC: Uncorrectable local error with unknown GuC id\n"); return 0; } @@ -3569,9 +3612,19 @@ int xe_guc_uncorrectable_error_handler(struct xe_guc *guc, u32 *msg, u32 len) if (unlikely(!q)) return -EPROTO; - xe_gt_err(gt, - "GuC: Uncorrectable local error! guc_id=%d class=%s, logical_mask=0x%x", - guc_id, xe_hw_engine_class_to_str(q->class), q->logical_mask); + /* + * On CRI, the hardware cannot distinguish GT translation faults + * from true RAS conditions. Demote to debug to avoid false + * positive hardware error logs. + */ + if (gt_to_xe(gt)->info.platform == XE_CRESCENTISLAND) + xe_gt_dbg(gt, + "GuC: Uncorrectable local error! guc_id=%d class=%s, logical_mask=0x%x", + guc_id, xe_hw_engine_class_to_str(q->class), q->logical_mask); + else + xe_gt_err(gt, + "GuC: Uncorrectable local error! guc_id=%d class=%s, logical_mask=0x%x", + guc_id, xe_hw_engine_class_to_str(q->class), q->logical_mask); trace_xe_guc_uncorrectable_error(q); diff --git a/drivers/gpu/drm/xe/xe_hw_engine.c b/drivers/gpu/drm/xe/xe_hw_engine.c index 9680d2a5adec..f7d5d1101c6e 100644 --- a/drivers/gpu/drm/xe/xe_hw_engine.c +++ b/drivers/gpu/drm/xe/xe_hw_engine.c @@ -275,11 +275,22 @@ static const struct engine_info engine_infos[] = { static void hw_engine_fini(void *arg) { struct xe_hw_engine *hwe = arg; + struct xe_gt *gt = hwe->gt; + + if (gt) { + struct xe_device *xe = gt_to_xe(gt); + unsigned long flags; - if (hwe->exl_port) - xe_execlist_port_destroy(hwe->exl_port); + if (hwe->exl_port) + xe_execlist_port_destroy(hwe->exl_port); - hwe->gt = NULL; + spin_lock_irqsave(&xe->irq.lock, flags); + hwe->name = NULL; + hwe->gt = NULL; + spin_unlock_irqrestore(&xe->irq.lock, flags); + } else { + hwe->name = NULL; + } } /** diff --git a/drivers/gpu/drm/xe/xe_hw_error.c b/drivers/gpu/drm/xe/xe_hw_error.c index 5f2abc9485ff..f726179c22e3 100644 --- a/drivers/gpu/drm/xe/xe_hw_error.c +++ b/drivers/gpu/drm/xe/xe_hw_error.c @@ -14,6 +14,7 @@ #include "xe_drm_ras.h" #include "xe_hw_error.h" #include "xe_mmio.h" +#include "xe_pm.h" #include "xe_survivability_mode.h" #define GT_HW_ERROR_MAX_ERR_BITS 16 @@ -170,6 +171,7 @@ static void csc_hw_error_work(struct work_struct *work) struct xe_tile *tile = container_of(work, typeof(*tile), csc_hw_error_work); struct xe_device *xe = tile_to_xe(tile); + guard(xe_pm_runtime)(xe); xe_survivability_mode_runtime_enable(xe); } diff --git a/drivers/gpu/drm/xe/xe_hwmon.c b/drivers/gpu/drm/xe/xe_hwmon.c index e11e429b98c7..20c1cfffc5a0 100644 --- a/drivers/gpu/drm/xe/xe_hwmon.c +++ b/drivers/gpu/drm/xe/xe_hwmon.c @@ -104,6 +104,13 @@ enum sensor_attr_power { /* Index of memory controller in READ_THERMAL_DATA output */ #define TEMP_INDEX_MCTRL 2 +/* Mailbox sentinel reported for an unavailable temperature sensor */ +#define TEMP_MBX_INVALID 0xFF + +/* Mailbox temperature is sign-magnitude: bit 7 sign, bits 6:0 magnitude. */ +#define TEMP_MBX_SIGN BIT(7) +#define TEMP_MBX_MAG GENMASK(6, 0) + /* Maximum characters in hwmon label name */ #define MAX_LABEL_SIZE 16 @@ -134,13 +141,17 @@ struct xe_hwmon_thermal_info { union { /** @limit: temperatures limits */ u8 limit[TEMP_LIMIT_MAX]; - /** @data: temperature limits in dwords */ - u32 data[DIV_ROUND_UP(TEMP_LIMIT_MAX, sizeof(u32))]; + /** @data: temperature limits as little-endian dwords */ + __le32 data[DIV_ROUND_UP(TEMP_LIMIT_MAX, sizeof(u32))]; }; /** @count: no of temperature sensors available for the platform */ u8 count; - /** @value: signed value from each sensor */ - s8 value[U8_MAX]; + union { + /** @value: per-sensor raw mailbox temperature; bit7=sign, bits6:0=magnitude */ + u8 value[U8_MAX + 1]; + /** @dword: sensor values as little-endian dwords, u32-aligned for pcode reads */ + __le32 dword[DIV_ROUND_UP(U8_MAX + 1, sizeof(u32))]; + }; /** @vram_label: vram label names */ char vram_label[MAX_VRAM_CHANNELS][MAX_LABEL_SIZE]; }; @@ -165,8 +176,8 @@ struct xe_hwmon { struct xe_hwmon_energy_info ei[CHANNEL_MAX]; /** @fi: Fan info for fanN_input */ struct xe_hwmon_fan_info fi[FAN_MAX]; - /** @boot_power_limit_read: is boot power limits read */ - bool boot_power_limit_read; + /** @read_power_limit_from_pcode: pcode accepted power limits write for the channel */ + bool read_power_limit_from_pcode[CHANNEL_MAX]; /** @pl1_on_boot: power limit PL1 on boot */ u32 pl1_on_boot[CHANNEL_MAX]; /** @pl2_on_boot: power limit PL2 on boot */ @@ -175,9 +186,9 @@ struct xe_hwmon { struct xe_hwmon_thermal_info temp; }; -static inline int prepare_power_limit_param2(const struct xe_hwmon *hwmon) +static inline int prepare_power_limit_param2(const struct xe_hwmon *hwmon, int channel) { - if (hwmon->boot_power_limit_read) { + if (hwmon->read_power_limit_from_pcode[channel]) { if (hwmon->xe->info.platform >= XE_CRESCENTISLAND) return READ_PL_ACCEPTED; else @@ -198,7 +209,8 @@ static int xe_hwmon_pcode_read_power_limit(const struct xe_hwmon *hwmon, u32 att (channel == CHANNEL_CARD) ? READ_PSYSGPU_POWER_LIMIT : READ_PACKAGE_POWER_LIMIT, - prepare_power_limit_param2(hwmon)), &val0, &val1); + prepare_power_limit_param2(hwmon, channel)), + &val0, &val1); if (ret) { drm_dbg(&hwmon->xe->drm, "read failed ch %d val0 0x%08x, val1 0x%08x, ret %d\n", @@ -213,14 +225,14 @@ static int xe_hwmon_pcode_read_power_limit(const struct xe_hwmon *hwmon, u32 att else if (attr == PL2_HWMON_ATTR) *uval = (val1 & PWR_LIM_EN) ? val1 : 0; else if (attr == hwmon_power_label) - *uval = (val0 & PWR_LIM_EN) ? 1 : (val1 & PWR_LIM_EN) ? 1 : 0; + *uval = (val0 | val1) & PWR_LIM_EN; else *uval = 0; return ret; } -static int xe_hwmon_pcode_rmw_power_limit(const struct xe_hwmon *hwmon, u32 attr, u8 channel, +static int xe_hwmon_pcode_rmw_power_limit(struct xe_hwmon *hwmon, u32 attr, u8 channel, u32 clr, u32 set) { struct xe_tile *root_tile = xe_device_get_root_tile(hwmon->xe); @@ -231,10 +243,13 @@ static int xe_hwmon_pcode_rmw_power_limit(const struct xe_hwmon *hwmon, u32 attr (channel == CHANNEL_CARD) ? READ_PSYSGPU_POWER_LIMIT : READ_PACKAGE_POWER_LIMIT, - prepare_power_limit_param2(hwmon)), &val0, &val1); - if (ret) - drm_dbg(&hwmon->xe->drm, "read failed ch %d val0 0x%08x, val1 0x%08x, ret %d\n", + prepare_power_limit_param2(hwmon, channel)), + &val0, &val1); + if (ret) { + drm_err(&hwmon->xe->drm, "read failed ch %d val0 0x%08x, val1 0x%08x, ret %d\n", channel, val0, val1, ret); + return ret; + } if (attr == PL1_HWMON_ATTR) val0 = (val0 & ~clr) | set; @@ -248,9 +263,36 @@ static int xe_hwmon_pcode_rmw_power_limit(const struct xe_hwmon *hwmon, u32 attr WRITE_PSYSGPU_POWER_LIMIT : WRITE_PACKAGE_POWER_LIMIT, 0), val0, val1, PCODE_DEFAULT_TIMEOUT_MS); - if (ret) + if (ret) { drm_dbg(&hwmon->xe->drm, "write failed ch %d val0 0x%08x, val1 0x%08x, ret %d\n", channel, val0, val1, ret); + return ret; + } + + /* Read from pcode once it holds a driver-written limit */ + if (!hwmon->read_power_limit_from_pcode[channel]) + hwmon->read_power_limit_from_pcode[channel] = true; + + return 0; +} + +static int xe_hwmon_pcode_set_default_power_limits(struct xe_hwmon *hwmon) +{ + int ret = 0; + + ret |= xe_hwmon_pcode_rmw_power_limit(hwmon, PL1_HWMON_ATTR, CHANNEL_CARD, + PWR_LIM | PWR_LIM_TIME, + hwmon->pl1_on_boot[CHANNEL_CARD]); + ret |= xe_hwmon_pcode_rmw_power_limit(hwmon, PL1_HWMON_ATTR, CHANNEL_PKG, + PWR_LIM | PWR_LIM_TIME, + hwmon->pl1_on_boot[CHANNEL_PKG]); + ret |= xe_hwmon_pcode_rmw_power_limit(hwmon, PL2_HWMON_ATTR, CHANNEL_CARD, + PWR_LIM | PWR_LIM_TIME, + hwmon->pl2_on_boot[CHANNEL_CARD]); + ret |= xe_hwmon_pcode_rmw_power_limit(hwmon, PL2_HWMON_ATTR, CHANNEL_PKG, + PWR_LIM | PWR_LIM_TIME, + hwmon->pl2_on_boot[CHANNEL_PKG]); + return ret; } @@ -394,7 +436,9 @@ static int xe_hwmon_power_max_write(struct xe_hwmon *hwmon, u32 attr, int channe if (hwmon->xe->info.has_mbx_power_limits) { drm_dbg(&hwmon->xe->drm, "disabling %s on channel %d\n", PWR_ATTR_TO_STR(attr), channel); - xe_hwmon_pcode_rmw_power_limit(hwmon, attr, channel, PWR_LIM_EN, 0); + 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); } else { reg_val = xe_mmio_rmw32(mmio, rapl_limit, PWR_LIM_EN, 0); @@ -679,15 +723,19 @@ xe_hwmon_power_max_interval_store(struct device *dev, struct device_attribute *a mutex_lock(&hwmon->hwmon_lock); - if (hwmon->xe->info.has_mbx_power_limits) - xe_hwmon_pcode_rmw_power_limit(hwmon, power_attr, channel, PWR_LIM_TIME, rxy); - else + ret = count; + if (hwmon->xe->info.has_mbx_power_limits) { + ret = xe_hwmon_pcode_rmw_power_limit(hwmon, power_attr, channel, PWR_LIM_TIME, rxy); + if (!ret) + ret = count; + } else { r = xe_mmio_rmw32(mmio, xe_hwmon_get_reg(hwmon, REG_PKG_RAPL_LIMIT, channel), PWR_LIM_TIME, rxy); + } mutex_unlock(&hwmon->hwmon_lock); - return count; + return ret; } /* PSYS PL1 */ @@ -786,16 +834,17 @@ static const struct hwmon_channel_info * const hwmon_info[] = { static int xe_hwmon_pcode_read_thermal_info(struct xe_hwmon *hwmon) { struct xe_tile *root_tile = xe_device_get_root_tile(hwmon->xe); - u32 config = 0; + u32 config = 0, data0 = 0, data1 = 0; int ret; ret = xe_pcode_read(root_tile, PCODE_MBOX(PCODE_THERMAL_INFO, READ_THERMAL_LIMITS, 0), - &hwmon->temp.data[0], &hwmon->temp.data[1]); + &data0, &data1); if (ret) return ret; - drm_dbg(&hwmon->xe->drm, "thermal info read val 0x%x val1 0x%x\n", - hwmon->temp.data[0], hwmon->temp.data[1]); + drm_dbg(&hwmon->xe->drm, "thermal info read val 0x%x val1 0x%x\n", data0, data1); + hwmon->temp.data[0] = cpu_to_le32(data0); + hwmon->temp.data[1] = cpu_to_le32(data1); ret = xe_pcode_read(root_tile, PCODE_MBOX(PCODE_THERMAL_INFO, READ_THERMAL_CONFIG, 0), &config, NULL); @@ -808,26 +857,74 @@ static int xe_hwmon_pcode_read_thermal_info(struct xe_hwmon *hwmon) return ret; } +static inline bool mmio_temp_valid(const struct xe_hwmon *hwmon, u32 value) +{ + /* + * On platforms lacking temperature sentinel support, a value of 0 is treated + * as invalid. While 0°C is theoretically possible, it is highly unlikely for + * a discrete GPU in normal environments, making it a reasonable fallback + * indicator for invalid or uninitialized temperature readings. + * All-ones is returned when the device is off the bus, so reject it too. + */ + if (value == U32_MAX) + return false; + + return hwmon->xe->info.has_temp_sentinel || value != 0; +} + +/* Mailbox temperature is sign-magnitude (bit 7 sign, bits 6:0 magnitude). */ +static inline bool mbx_temp_valid(const struct xe_hwmon *hwmon, u8 value) +{ + if (value == TEMP_MBX_INVALID) + return false; + + return hwmon->xe->info.has_temp_sentinel || value != 0; +} + +/* Decode an 8-bit sign-magnitude mailbox temperature to degrees Celsius. */ +static int mbx_temp_decode(u8 value) +{ + int temp = value & TEMP_MBX_MAG; + + return (value & TEMP_MBX_SIGN) ? -temp : temp; +} + static int get_mc_temp(struct xe_hwmon *hwmon, long *val) { struct xe_tile *root_tile = xe_device_get_root_tile(hwmon->xe); - u32 *dword = (u32 *)hwmon->temp.value; + int ret, i, count = 0; s32 average = 0; - int ret, i; - for (i = 0; i < DIV_ROUND_UP(TEMP_LIMIT_MAX, sizeof(u32)); i++) { + guard(mutex)(&hwmon->hwmon_lock); + + for (i = 0; i < DIV_ROUND_UP(hwmon->temp.count, sizeof(u32)); i++) { + u32 data = 0; + ret = xe_pcode_read(root_tile, PCODE_MBOX(PCODE_THERMAL_INFO, READ_THERMAL_DATA, i), - (dword + i), NULL); + &data, NULL); if (ret) return ret; - drm_dbg(&hwmon->xe->drm, "thermal data for group %d val 0x%x\n", i, dword[i]); + drm_dbg(&hwmon->xe->drm, "thermal data for group %d val 0x%x\n", i, data); + hwmon->temp.dword[i] = cpu_to_le32(data); } - for (i = TEMP_INDEX_MCTRL; i < hwmon->temp.count - 1; i++) - average += hwmon->temp.value[i]; + for (i = TEMP_INDEX_MCTRL; i < hwmon->temp.count - 1; i++) { + if (!mbx_temp_valid(hwmon, hwmon->temp.value[i])) + continue; + average += mbx_temp_decode(hwmon->temp.value[i]); + count++; + } + + if (!count) { + drm_dbg(&hwmon->xe->drm, "Memory controller temperature unavailable!\n"); + return -ENXIO; + } + + average /= count; + + if (val) + *val = average * MILLIDEGREE_PER_DEGREE; - average /= (hwmon->temp.count - TEMP_INDEX_MCTRL - 1); - *val = average * MILLIDEGREE_PER_DEGREE; return 0; } @@ -847,7 +944,7 @@ static int get_pcie_temp(struct xe_hwmon *hwmon, long *val) data = REG_FIELD_GET(PCIE_SENSOR_MASK, data); data = REG_FIELD_GET(TEMP_MASK, data); - *val = (s8)data * MILLIDEGREE_PER_DEGREE; + *val = mbx_temp_decode(data) * MILLIDEGREE_PER_DEGREE; return 0; } @@ -1511,22 +1608,11 @@ xe_hwmon_get_preregistration_info(struct xe_hwmon *hwmon) } else { drm_info(&hwmon->xe->drm, "Using mailbox commands for power limits\n"); /* Write default limits to read from pcode from now on. */ - xe_hwmon_pcode_rmw_power_limit(hwmon, PL1_HWMON_ATTR, - CHANNEL_CARD, PWR_LIM | PWR_LIM_TIME, - hwmon->pl1_on_boot[CHANNEL_CARD]); - xe_hwmon_pcode_rmw_power_limit(hwmon, PL1_HWMON_ATTR, - CHANNEL_PKG, PWR_LIM | PWR_LIM_TIME, - hwmon->pl1_on_boot[CHANNEL_PKG]); - xe_hwmon_pcode_rmw_power_limit(hwmon, PL2_HWMON_ATTR, - CHANNEL_CARD, PWR_LIM | PWR_LIM_TIME, - hwmon->pl2_on_boot[CHANNEL_CARD]); - xe_hwmon_pcode_rmw_power_limit(hwmon, PL2_HWMON_ATTR, - CHANNEL_PKG, PWR_LIM | PWR_LIM_TIME, - hwmon->pl2_on_boot[CHANNEL_PKG]); + if (xe_hwmon_pcode_set_default_power_limits(hwmon)) + drm_warn(&hwmon->xe->drm, "Failed to set default power limits\n"); hwmon->scl_shift_power = PWR_UNIT; hwmon->scl_shift_energy = ENERGY_UNIT; hwmon->scl_shift_time = TIME_UNIT; - hwmon->boot_power_limit_read = true; } } else { drm_info(&hwmon->xe->drm, "Using register for power limits\n"); diff --git a/drivers/gpu/drm/xe/xe_irq.c b/drivers/gpu/drm/xe/xe_irq.c index 9e49e2241da4..b394c8edf89c 100644 --- a/drivers/gpu/drm/xe/xe_irq.c +++ b/drivers/gpu/drm/xe/xe_irq.c @@ -908,6 +908,7 @@ static irqreturn_t xe_irq_msix_default_hwe_handler(int irq, void *arg) struct xe_hw_engine *hwe; enum xe_hw_engine_id id; struct xe_tile *tile; + unsigned long flags; struct xe_gt *gt; if (!atomic_read(&xe->irq.enabled)) @@ -922,8 +923,10 @@ static irqreturn_t xe_irq_msix_default_hwe_handler(int irq, void *arg) if (gt->tile != tile) continue; + spin_lock_irqsave(&xe->irq.lock, flags); for_each_hw_engine(hwe, gt, id) xe_memirq_hwe_handler(memirq, hwe); + spin_unlock_irqrestore(&xe->irq.lock, flags); } } diff --git a/drivers/gpu/drm/xe/xe_late_bind_fw.c b/drivers/gpu/drm/xe/xe_late_bind_fw.c index 768442ca7da6..1bddfaf0fb9f 100644 --- a/drivers/gpu/drm/xe/xe_late_bind_fw.c +++ b/drivers/gpu/drm/xe/xe_late_bind_fw.c @@ -335,19 +335,19 @@ static int __xe_late_bind_fw_init(struct xe_late_bind *late_bind, u32 fw_id) if (fw->size > XE_LB_MAX_PAYLOAD_SIZE) { drm_err(&xe->drm, "Firmware %s size %zu is larger than max pay load size %u\n", lb_fw->blob_path, fw->size, XE_LB_MAX_PAYLOAD_SIZE); - release_firmware(fw); - return -ENODATA; + ret = -ENODATA; + goto release_fw; } ret = parse_lb_layout(lb_fw, fw->data, fw->size, "LTES"); if (ret) - return ret; + goto release_fw; lb_fw->payload_size = fw->size; lb_fw->payload = drmm_kzalloc(&xe->drm, lb_fw->payload_size, GFP_KERNEL); if (!lb_fw->payload) { - release_firmware(fw); - return -ENOMEM; + ret = -ENOMEM; + goto release_fw; } drm_info(&xe->drm, "Using %s firmware from %s version %u.%u.%u.%u\n", @@ -356,10 +356,11 @@ static int __xe_late_bind_fw_init(struct xe_late_bind *late_bind, u32 fw_id) lb_fw->version.hotfix, lb_fw->version.build); memcpy((void *)lb_fw->payload, fw->data, lb_fw->payload_size); - release_firmware(fw); INIT_WORK(&lb_fw->work, xe_late_bind_work); - return 0; +release_fw: + release_firmware(fw); + return ret; } static int xe_late_bind_fw_init(struct xe_late_bind *late_bind) diff --git a/drivers/gpu/drm/xe/xe_lmtt.c b/drivers/gpu/drm/xe/xe_lmtt.c index 0c726eda9390..8a5a434931b0 100644 --- a/drivers/gpu/drm/xe/xe_lmtt.c +++ b/drivers/gpu/drm/xe/xe_lmtt.c @@ -12,7 +12,8 @@ #include "xe_assert.h" #include "xe_bo.h" -#include "xe_tlb_inval.h" +#include "xe_gt.h" +#include "xe_gt_mcr.h" #include "xe_lmtt.h" #include "xe_map.h" #include "xe_mert.h" @@ -21,6 +22,7 @@ #include "xe_sriov.h" #include "xe_tile.h" #include "xe_tile_sriov_printk.h" +#include "xe_tlb_inval.h" /** * DOC: Local Memory Translation Table @@ -210,14 +212,43 @@ fail: return err; } -static void lmtt_setup_dir_ptr(struct xe_lmtt *lmtt) +static void lmtt_setup_dir_ptr_gt(struct xe_gt *gt, u32 config) +{ + struct xe_device *xe = gt_to_xe(gt); + struct xe_reg_mcr reg_mcr; + struct xe_reg reg; + u32 val_read; + + if (GRAPHICS_VER(xe) < 20) { + reg = LMEM_CFG; + xe_mmio_write32(>->mmio, reg, config); + return; + } + + if (xe_gt_is_main_type(gt)) { + reg_mcr = XE2_LMEM_CFG_MCR; + xe_gt_mcr_multicast_write(gt, reg_mcr, config); + val_read = xe_gt_mcr_unicast_read_any(gt, reg_mcr); + xe_gt_assert_msg(gt, val_read == config, "LMEM_CFG_MCR: %#x != %#x\n", + config, val_read); + } else { + reg = XE2_LMEM_CFG; + xe_mmio_write32(>->mmio, reg, config); + + if (MEDIA_VER(xe) >= 35) { + val_read = xe_mmio_read32(>->mmio, reg); + xe_gt_assert_msg(gt, val_read == config, "LMEM_CFG: %#x != %#x\n", + config, val_read); + } + } +} + +static void lmtt_setup_dir_ptr(struct xe_lmtt *lmtt, struct xe_gt *gt) { struct xe_tile *tile = lmtt_to_tile(lmtt); struct xe_device *xe = tile_to_xe(tile); dma_addr_t offset = xe_bo_main_addr(lmtt->pd->bo, XE_PAGE_SIZE); - struct xe_gt *gt; u32 config; - u8 id; lmtt_debug(lmtt, "DIR offset %pad\n", &offset); lmtt_assert(lmtt, xe_bo_is_vram(lmtt->pd->bo)); @@ -225,31 +256,32 @@ static void lmtt_setup_dir_ptr(struct xe_lmtt *lmtt) config = LMEM_EN | REG_FIELD_PREP(LMTT_DIR_PTR, offset / SZ_64K); - for_each_gt_on_tile(gt, tile, id) - xe_mmio_write32(>->mmio, - GRAPHICS_VER(xe) >= 20 ? XE2_LMEM_CFG : LMEM_CFG, - config); + lmtt_setup_dir_ptr_gt(gt, config); - if (xe_device_has_mert(xe) && xe_tile_is_root(tile)) + if (xe_device_has_mert(xe) && xe_tile_is_root(tile) && + xe_gt_is_main_type(gt)) xe_mmio_write32(&tile->mmio, MERT_LMEM_CFG, config); } /** * xe_lmtt_init_hw - Perform LMTT hardware initialization. - * @lmtt: the &xe_lmtt to initialize + * @gt: the &xe_gt for which lmtt is initialized * * This function is a second step of the LMTT initialization. - * This function registers LMTT Root Directory prepared in xe_lmtt_init(). + * This function registers LMTT Root Directory prepared in xe_lmtt_init() + * on the given GT. * * This function shall be called after every hardware reset. * This function shall be called only when running as a PF driver. */ -void xe_lmtt_init_hw(struct xe_lmtt *lmtt) +void xe_lmtt_init_hw(struct xe_gt *gt) { + struct xe_lmtt *lmtt = >_to_tile(gt)->sriov.pf.lmtt; + if (!lmtt->pd) return; - lmtt_setup_dir_ptr(lmtt); + lmtt_setup_dir_ptr(lmtt, gt); } static int lmtt_invalidate_hw(struct xe_lmtt *lmtt) diff --git a/drivers/gpu/drm/xe/xe_lmtt.h b/drivers/gpu/drm/xe/xe_lmtt.h index 8fa387b38c52..5ef065dd573c 100644 --- a/drivers/gpu/drm/xe/xe_lmtt.h +++ b/drivers/gpu/drm/xe/xe_lmtt.h @@ -9,12 +9,13 @@ #include <linux/types.h> struct xe_bo; +struct xe_gt; struct xe_lmtt; struct xe_lmtt_ops; #ifdef CONFIG_PCI_IOV int xe_lmtt_init(struct xe_lmtt *lmtt); -void xe_lmtt_init_hw(struct xe_lmtt *lmtt); +void xe_lmtt_init_hw(struct xe_gt *gt); void xe_lmtt_invalidate_hw(struct xe_lmtt *lmtt); int xe_lmtt_prepare_pages(struct xe_lmtt *lmtt, unsigned int vfid, u64 range); int xe_lmtt_populate_pages(struct xe_lmtt *lmtt, unsigned int vfid, struct xe_bo *bo, u64 offset); @@ -23,7 +24,7 @@ u64 xe_lmtt_estimate_pt_size(struct xe_lmtt *lmtt, u64 size); u64 xe_lmtt_page_size(struct xe_lmtt *lmtt); #else static inline int xe_lmtt_init(struct xe_lmtt *lmtt) { return 0; } -static inline void xe_lmtt_init_hw(struct xe_lmtt *lmtt) { } +static inline void xe_lmtt_init_hw(struct xe_gt *gt) { } #endif #endif diff --git a/drivers/gpu/drm/xe/xe_lrc.c b/drivers/gpu/drm/xe/xe_lrc.c index de9a9560ecf3..fdcc1cbd03bb 100644 --- a/drivers/gpu/drm/xe/xe_lrc.c +++ b/drivers/gpu/drm/xe/xe_lrc.c @@ -1469,15 +1469,15 @@ setup_indirect_ctx(struct xe_lrc *lrc, struct xe_hw_engine *hwe) finish_bo(&state); kfree(state.buffer); - /* - * Enable INDIRECT_CTX leaving INDIRECT_CTX_OFFSET at its default: it - * varies per engine class, but the default is good enough - */ xe_lrc_write_ctx_reg(lrc, CTX_CS_INDIRECT_CTX, (xe_bo_ggtt_addr(lrc->bo) + state.offset) | /* Size in CLs. */ (state.written * sizeof(u32) / 64)); + if (GRAPHICS_VER(lrc_to_xe(lrc)) < 20) + xe_lrc_write_ctx_reg(lrc, + CTX_CS_INDIRECT_CTX_OFFSET, + CTX_INDIRECT_CTX_OFFSET_DEFAULT); return 0; } diff --git a/drivers/gpu/drm/xe/xe_memirq.c b/drivers/gpu/drm/xe/xe_memirq.c index 9dfe965cb46e..1073132f2ded 100644 --- a/drivers/gpu/drm/xe/xe_memirq.c +++ b/drivers/gpu/drm/xe/xe_memirq.c @@ -555,6 +555,7 @@ void xe_memirq_handler(struct xe_memirq *memirq) struct xe_hw_engine *hwe; enum xe_hw_engine_id id; struct iosys_map map; + unsigned long flags; unsigned int gtid; struct xe_gt *gt; @@ -568,8 +569,10 @@ void xe_memirq_handler(struct xe_memirq *memirq) if (gt->tile != tile) continue; + spin_lock_irqsave(&xe->irq.lock, flags); for_each_hw_engine(hwe, gt, id) xe_memirq_hwe_handler(memirq, hwe); + spin_unlock_irqrestore(&xe->irq.lock, flags); } /* GuC and media GuC (if present) must be checked separately */ diff --git a/drivers/gpu/drm/xe/xe_mert.c b/drivers/gpu/drm/xe/xe_mert.c index 32700c19a1df..934be933d57f 100644 --- a/drivers/gpu/drm/xe/xe_mert.c +++ b/drivers/gpu/drm/xe/xe_mert.c @@ -74,7 +74,8 @@ static void mert_handle_cat_error(struct xe_device *xe) break; case CATERR_UNMAPPED_GGTT: xe_sriov_err(xe, "MERT: CAT_ERR: Access to an unmapped GGTT!\n"); - xe_device_declare_wedged(xe); + xe_device_declare_wedged(xe, + DRM_WEDGE_RECOVERY_REBIND | DRM_WEDGE_RECOVERY_BUS_RESET); break; case CATERR_LMTT_FAULT: xe_sriov_dbg_ratelimited(xe, "MERT: CAT_ERR: VF%u LMTT fault!\n", vfid); @@ -82,7 +83,8 @@ static void mert_handle_cat_error(struct xe_device *xe) break; default: xe_sriov_err(xe, "MERT: Unexpected CAT_ERR code=%#x!\n", code); - xe_device_declare_wedged(xe); + xe_device_declare_wedged(xe, + DRM_WEDGE_RECOVERY_REBIND | DRM_WEDGE_RECOVERY_BUS_RESET); break; } } diff --git a/drivers/gpu/drm/xe/xe_pat.c b/drivers/gpu/drm/xe/xe_pat.c index a5fe1beec652..0ac64a6a3098 100644 --- a/drivers/gpu/drm/xe/xe_pat.c +++ b/drivers/gpu/drm/xe/xe_pat.c @@ -590,7 +590,13 @@ static const struct xe_pat_ops xe3p_xpc_pat_ops = { .entry_dump = xe3p_xpc_pat_entry_dump, }; -void xe_pat_init_early(struct xe_device *xe) +/** + * xe_pat_init_early() - Init early pat table operation. + * @xe: the &xe_device + * + * Return: 0 on success or a negative error code on failure. + */ +int xe_pat_init_early(struct xe_device *xe) { xe->pat.idx[XE_CACHE_WB_COMPRESSION] = XE_PAT_INVALID_IDX; xe->pat.idx[XE_CACHE_NONE_COMPRESSION] = XE_PAT_INVALID_IDX; @@ -688,12 +694,15 @@ void xe_pat_init_early(struct xe_device *xe) */ drm_err(&xe->drm, "Missing PAT table for platform with graphics version %d.%02d!\n", GRAPHICS_VER(xe), GRAPHICS_VERx100(xe) % 100); + return -ENODATA; } + xe_assert(xe, xe->pat.ops); xe_assert(xe, xe->pat.ops->dump); xe_assert(xe, xe->pat.ops->program_graphics); xe_assert(xe, MEDIA_VER(xe) < 13 || xe->pat.ops->program_media); xe_assert(xe, GRAPHICS_VER(xe) < 20 || xe->pat.ops->entry_dump); + return 0; } void xe_pat_init(struct xe_gt *gt) diff --git a/drivers/gpu/drm/xe/xe_pat.h b/drivers/gpu/drm/xe/xe_pat.h index 7060f66e1d63..6398c3ab4805 100644 --- a/drivers/gpu/drm/xe/xe_pat.h +++ b/drivers/gpu/drm/xe/xe_pat.h @@ -42,8 +42,10 @@ struct xe_pat_table_entry { /** * xe_pat_init_early - SW initialization, setting up data based on device * @xe: xe device + * + * Return: 0 on success or a negative error code on failure. */ -void xe_pat_init_early(struct xe_device *xe); +int xe_pat_init_early(struct xe_device *xe); /** * xe_pat_init - Program HW PAT table diff --git a/drivers/gpu/drm/xe/xe_pci.c b/drivers/gpu/drm/xe/xe_pci.c index 8d8f00d5dcc4..12ff5c902547 100644 --- a/drivers/gpu/drm/xe/xe_pci.c +++ b/drivers/gpu/drm/xe/xe_pci.c @@ -486,6 +486,7 @@ static const struct xe_device_desc cri_desc = { .has_soc_remapper_telem = true, .has_sriov = true, .has_sysctrl = true, + .has_temp_sentinel = true, .max_gt_per_tile = 2, MULTI_LRC_MASK, .require_force_probe = true, @@ -817,6 +818,7 @@ static int xe_info_init_early(struct xe_device *xe, xe->info.has_sriov = xe_configfs_primary_gt_allowed(to_pci_dev(xe->drm.dev)) && desc->has_sriov; xe->info.has_sysctrl = desc->has_sysctrl; + xe->info.has_temp_sentinel = desc->has_temp_sentinel; xe->info.skip_guc_pc = desc->skip_guc_pc; xe->info.skip_pcode = desc->skip_pcode; xe->info.needs_scratch = desc->needs_scratch; @@ -1449,6 +1451,9 @@ static int xe_pci_runtime_resume(struct device *dev) struct xe_device *xe = pdev_to_xe_device(pdev); int err; + if (xe->d3cold.allowed) + d3cold_toggle(pdev, D3COLD_DISABLE); + err = pci_set_power_state(pdev, PCI_D0); if (err) return err; diff --git a/drivers/gpu/drm/xe/xe_pci_error.c b/drivers/gpu/drm/xe/xe_pci_error.c index 79ce0c671549..a5c8fd67738c 100644 --- a/drivers/gpu/drm/xe/xe_pci_error.c +++ b/drivers/gpu/drm/xe/xe_pci_error.c @@ -30,8 +30,10 @@ static void prepare_device_for_reset(struct pci_dev *pdev) xe_device_set_in_reset(xe); - for_each_gt(gt, xe, id) + for_each_gt(gt, xe, id) { xe_gt_declare_wedged(gt); + flush_work(>->wedge.worker); + } pci_disable_device(pdev); } @@ -86,7 +88,7 @@ static pci_ers_result_t xe_pci_error_mmio_enabled(struct pci_dev *pdev) /* User wants to debug the error, prevent reset */ if (xe->wedged.mode == XE_WEDGED_MODE_UPON_ANY_HANG_NO_RESET) { - xe_device_declare_wedged(xe); + xe_device_declare_wedged(xe, DRM_WEDGE_RECOVERY_NONE); return PCI_ERS_RESULT_DISCONNECT; } diff --git a/drivers/gpu/drm/xe/xe_pci_types.h b/drivers/gpu/drm/xe/xe_pci_types.h index 448bbe5ba1d7..15eedac8467a 100644 --- a/drivers/gpu/drm/xe/xe_pci_types.h +++ b/drivers/gpu/drm/xe/xe_pci_types.h @@ -61,6 +61,7 @@ struct xe_device_desc { u8 has_soc_remapper_telem:1; u8 has_sriov:1; u8 has_sysctrl:1; + u8 has_temp_sentinel:1; u8 needs_scratch:1; u8 skip_guc_pc:1; u8 skip_pcode:1; diff --git a/drivers/gpu/drm/xe/xe_pm.c b/drivers/gpu/drm/xe/xe_pm.c index 4f1035ab1eb2..d95f0d128ed4 100644 --- a/drivers/gpu/drm/xe/xe_pm.c +++ b/drivers/gpu/drm/xe/xe_pm.c @@ -241,15 +241,15 @@ int xe_pm_resume(struct xe_device *xe) drm_dbg(&xe->drm, "Resuming device\n"); trace_xe_pm_resume(xe, __builtin_return_address(0)); - for_each_gt(gt, xe, id) - xe_gt_idle_disable_c6(gt); + err = xe_pcode_ready(xe, true); + if (err) + return err; for_each_tile(tile, xe, id) xe_wa_apply_tile_workarounds(tile); - err = xe_pcode_ready(xe, true); - if (err) - return err; + for_each_gt(gt, xe, id) + xe_gt_idle_disable_c6(gt); xe_display_pm_resume_early(xe); @@ -687,6 +687,7 @@ out: */ int xe_pm_runtime_resume(struct xe_device *xe) { + struct xe_tile *tile; struct xe_gt *gt; u8 id; int err = 0; @@ -698,13 +699,16 @@ int xe_pm_runtime_resume(struct xe_device *xe) xe_rpm_lockmap_acquire(xe); if (xe->d3cold.allowed) { - for_each_gt(gt, xe, id) - xe_gt_idle_disable_c6(gt); - err = xe_pcode_ready(xe, true); if (err) goto out; + for_each_tile(tile, xe, id) + xe_wa_apply_tile_workarounds(tile); + + for_each_gt(gt, xe, id) + xe_gt_idle_disable_c6(gt); + xe_display_pm_resume_early(xe); /* diff --git a/drivers/gpu/drm/xe/xe_ras.c b/drivers/gpu/drm/xe/xe_ras.c index 7a85735c57d5..fe16a4106060 100644 --- a/drivers/gpu/drm/xe/xe_ras.c +++ b/drivers/gpu/drm/xe/xe_ras.c @@ -321,8 +321,7 @@ static u8 handle_core_compute_errors(struct xe_ras_error_array *arr) static void punit_error_handler(struct xe_device *xe) { - xe_device_set_wedged_method(xe, DRM_WEDGE_RECOVERY_COLD_RESET); - xe_device_declare_wedged(xe); + xe_device_declare_wedged(xe, DRM_WEDGE_RECOVERY_COLD_RESET); } static u8 handle_soc_internal_errors(struct xe_device *xe, struct xe_ras_error_array *arr) diff --git a/drivers/gpu/drm/xe/xe_shrinker.c b/drivers/gpu/drm/xe/xe_shrinker.c index deb4378c1ec1..4e4da76936f4 100644 --- a/drivers/gpu/drm/xe/xe_shrinker.c +++ b/drivers/gpu/drm/xe/xe_shrinker.c @@ -113,6 +113,9 @@ static int __xe_shrinker_walk(struct xe_shrinker *shrinker, continue; lret = xe_bo_shrink(ctx, ttm_bo, flags, scanned); + /* Like the TTM LRU walk, skip bos we can't shrink now. */ + if (lret == -EBUSY) + continue; if (lret < 0) { ret = lret; goto out; diff --git a/drivers/gpu/drm/xe/xe_survivability_mode.c b/drivers/gpu/drm/xe/xe_survivability_mode.c index 45d44ebe288b..ca031576fecb 100644 --- a/drivers/gpu/drm/xe/xe_survivability_mode.c +++ b/drivers/gpu/drm/xe/xe_survivability_mode.c @@ -446,8 +446,7 @@ void xe_survivability_mode_runtime_enable(struct xe_device *xe) survivability->type = XE_SURVIVABILITY_TYPE_RUNTIME; xe_log_err(xe, SURVIVABILITY, 0, "Runtime Mode enabled!\n"); - xe_device_set_wedged_method(xe, DRM_WEDGE_RECOVERY_VENDOR); - xe_device_declare_wedged(xe); + xe_device_declare_wedged(xe, DRM_WEDGE_RECOVERY_VENDOR); xe_log_err(xe, SURVIVABILITY, 0, "Firmware flash required!\n"); xe_info(xe, "Please refer to the userspace documentation for more details how to flash the firmware on %s!\n", diff --git a/drivers/gpu/drm/xe/xe_svm.c b/drivers/gpu/drm/xe/xe_svm.c index 909a602d091e..bc6902b5bf57 100644 --- a/drivers/gpu/drm/xe/xe_svm.c +++ b/drivers/gpu/drm/xe/xe_svm.c @@ -347,6 +347,7 @@ static void xe_vma_set_default_attributes(struct xe_vma *vma) struct xe_vma_mem_attr default_attr = { .preferred_loc.devmem_fd = DRM_XE_PREFERRED_LOC_DEFAULT_DEVICE, .preferred_loc.migration_policy = DRM_XE_MIGRATE_ALL_PAGES, + .default_pat_index = vma->attr.default_pat_index, .pat_index = vma->attr.default_pat_index, .atomic_access = DRM_XE_ATOMIC_UNDEFINED, .purgeable_state = XE_MADV_PURGEABLE_WILLNEED, diff --git a/drivers/gpu/drm/xe/xe_sync.c b/drivers/gpu/drm/xe/xe_sync.c index a3268465868e..48a38d64a42a 100644 --- a/drivers/gpu/drm/xe/xe_sync.c +++ b/drivers/gpu/drm/xe/xe_sync.c @@ -6,6 +6,7 @@ #include "xe_sync.h" #include <linux/dma-fence-array.h> +#include <linux/dma-fence-unwrap.h> #include <linux/error-injection.h> #include <linux/kthread.h> #include <linux/sched/mm.h> @@ -234,11 +235,35 @@ ALLOW_ERROR_INJECTION(xe_sync_entry_parse, ERRNO); int xe_sync_entry_add_deps(struct xe_sync_entry *sync, struct xe_sched_job *job) { - if (sync->fence) - return drm_sched_job_add_dependency(&job->drm, - dma_fence_get(sync->fence)); + struct dma_fence_unwrap iter; + struct dma_fence *fence; + int err = 0; - return 0; + if (!sync->fence) + return 0; + + /* + * Unwrap fence containers (e.g. dma_fence_chain from a timeline + * syncobj) so the scheduler sees the underlying fences. That lets it + * drop dependencies on jobs from the same entity and only wait for + * jobs on the same scheduler to be scheduled, rather than waiting for + * the container, which forces a full GPU completion wait and drains + * the queue. + */ + dma_fence_unwrap_for_each(fence, &iter, sync->fence) { + /* + * There is no dma_fence_unwrap_stop() helper to drop the + * reference the iterator holds, so keep iterating without + * doing anything once an error has occurred. + */ + if (err || dma_fence_is_signaled(fence)) + continue; + + err = drm_sched_job_add_dependency(&job->drm, + dma_fence_get(fence)); + } + + return err; } /** diff --git a/drivers/gpu/drm/xe/xe_ttm_vram_mgr.c b/drivers/gpu/drm/xe/xe_ttm_vram_mgr.c index 9a514d983e90..f28550b29f6b 100644 --- a/drivers/gpu/drm/xe/xe_ttm_vram_mgr.c +++ b/drivers/gpu/drm/xe/xe_ttm_vram_mgr.c @@ -243,9 +243,9 @@ static void xe_ttm_vram_retry_queued_pages(struct xe_ttm_vram_mgr *mgr) continue; } --mgr->n_queued_pages; - list_del_rcu(&pos->queued_link); + list_del(&pos->queued_link); ++mgr->n_offlined_pages; - list_add_rcu(&pos->offlined_link, &mgr->offlined_pages); + list_add(&pos->offlined_link, &mgr->offlined_pages); } } @@ -394,17 +394,17 @@ static void xe_ttm_vram_free_bad_pages(struct xe_ttm_vram_mgr *mgr) struct xe_ttm_vram_offline_resource *pos, *n; list_for_each_entry_safe(pos, n, &mgr->offlined_pages, offlined_link) { - list_del_rcu(&pos->offlined_link); + list_del(&pos->offlined_link); xe_ttm_vram_buddy_free(mgr, &pos->blocks, pos->used_visible_size); --mgr->n_offlined_pages; - kfree_rcu(pos, rcu); + kfree(pos); } list_for_each_entry_safe(pos, n, &mgr->queued_pages, queued_link) { - list_del_rcu(&pos->queued_link); + list_del(&pos->queued_link); /* queued entries have no buddy reservation yet */ xe_ttm_vram_buddy_free(mgr, &pos->blocks, 0); --mgr->n_queued_pages; - kfree_rcu(pos, rcu); + kfree(pos); } } @@ -687,6 +687,19 @@ static int xe_ttm_vram_purge_page(struct xe_device *xe, struct xe_bo *bo) goto out; } + /* + * The caller's user+pinned check was lockless (mgr->lock only), so an + * external pin can race in before we get here. Re-validate now that + * we hold the reservation lock and reject the purge instead of + * unpinning a BO userspace still expects to be resident. Request SBR + * the same way the caller's own critical-BO check does. + */ + if (xe_bo_is_user(bo) && xe_bo_is_pinned(bo)) { + xe_bo_unlock(bo); + ret = -EIO; + goto out; + } + xe_bo_set_purgeable_state(bo, XE_MADV_PURGEABLE_DONTNEED); ttm_bo_unmap_virtual(&bo->ttm); /* nuke CPU mmap + VRAM IO mappings */ if (xe_bo_is_pinned(bo)) @@ -810,7 +823,7 @@ static int xe_ttm_vram_reserve_page_at_addr(struct xe_device *xe, u64 addr, } /* Queue free(to-be-purged) pages */ ++vram_mgr->n_queued_pages; - list_add_rcu(&nentry->queued_link, &vram_mgr->queued_pages); + list_add(&nentry->queued_link, &vram_mgr->queued_pages); } else { /* Immediately offline unoccupied pages */ /* Queue free(to-be-reserved) pages */ @@ -824,11 +837,11 @@ static int xe_ttm_vram_reserve_page_at_addr(struct xe_device *xe, u64 addr, "Page at addr:0x%llx still busy (%d), deferring reservation\n", addr, ret); ++vram_mgr->n_queued_pages; - list_add_rcu(&nentry->queued_link, &vram_mgr->queued_pages); + list_add(&nentry->queued_link, &vram_mgr->queued_pages); return 0; } ++vram_mgr->n_offlined_pages; - list_add_rcu(&nentry->offlined_link, &vram_mgr->offlined_pages); + list_add(&nentry->offlined_link, &vram_mgr->offlined_pages); return ret; } } @@ -851,6 +864,13 @@ static int xe_ttm_vram_reserve_page_at_addr(struct xe_device *xe, u64 addr, */ ret = xe_ttm_vram_purge_page(xe, pbo); xe_bo_put(pbo); + if (ret == -EIO) { + /* Raced into an external pin after the lockless check above */ + drm_err(&xe->drm, + "%s: addr: 0x%llx became externally pinned, requesting SBR\n", + __func__, addr); + return ret; + } if (ret) drm_warn(&xe->drm, "Purge failed at addr:0x%llx, ret:%d\n", addr, ret); } @@ -968,11 +988,12 @@ int xe_ttm_vram_inject_fault(struct xe_device *xe) struct gpu_buddy *mm = &vram_mgr->mm; u64 addr; - if (vr->actual_physical_size < PAGE_SIZE) + /* Stay within the buddy-managed range; CCS/GSM/DSM sit beyond usable_size */ + if (vr->usable_size < PAGE_SIZE) return -ENOSPC; - addr = vr->actual_physical_size - PAGE_SIZE; - while (addr < vr->actual_physical_size) { + addr = ALIGN_DOWN(vr->usable_size - PAGE_SIZE, PAGE_SIZE); + while (addr < vr->usable_size) { struct gpu_buddy_block *block; bool found = false; @@ -1025,16 +1046,16 @@ static int vram_bad_pages_show(struct seq_file *m, void *unused) continue; mgr = to_xe_ttm_vram_mgr(man); - rcu_read_lock(); + mutex_lock(&mgr->lock); - list_for_each_entry_rcu(pos, &mgr->offlined_pages, offlined_link) { + list_for_each_entry(pos, &mgr->offlined_pages, offlined_link) { u64 pfn; pfn = (pos->addr + vr->dpa_base) >> PAGE_SHIFT; seq_printf(m, "0x%016llx : 0x%016lx : R\n", pfn, PAGE_SIZE); } - list_for_each_entry_rcu(pos, &mgr->queued_pages, queued_link) { + list_for_each_entry(pos, &mgr->queued_pages, queued_link) { u64 pfn; pfn = (pos->addr + vr->dpa_base) >> PAGE_SHIFT; @@ -1042,7 +1063,7 @@ static int vram_bad_pages_show(struct seq_file *m, void *unused) pfn, PAGE_SIZE, pos->status ? 'F' : 'P'); } - rcu_read_unlock(); + mutex_unlock(&mgr->lock); } return 0; diff --git a/drivers/gpu/drm/xe/xe_ttm_vram_mgr_types.h b/drivers/gpu/drm/xe/xe_ttm_vram_mgr_types.h index efcf3e1d4e80..8741b5de6c37 100644 --- a/drivers/gpu/drm/xe/xe_ttm_vram_mgr_types.h +++ b/drivers/gpu/drm/xe/xe_ttm_vram_mgr_types.h @@ -81,8 +81,6 @@ struct xe_ttm_vram_offline_resource { u64 addr; /** @status: buddy reservation status */ enum xe_page_reserve_status status; - /** @rcu: RCU head for deferred freeing */ - struct rcu_head rcu; }; #endif diff --git a/drivers/gpu/drm/xe/xe_tuning.c b/drivers/gpu/drm/xe/xe_tuning.c index dc079f1e74e5..024dd2e71b17 100644 --- a/drivers/gpu/drm/xe/xe_tuning.c +++ b/drivers/gpu/drm/xe/xe_tuning.c @@ -122,7 +122,7 @@ static const struct xe_rtp_table_sr engine_tunings = XE_RTP_TABLE_SR( }, { XE_RTP_NAME("Tuning: Disable NULL query for Anyhit Shader"), XE_RTP_RULES(GRAPHICS_VERSION_RANGE(2000, XE_RTP_END_VERSION_UNDEFINED), - FUNC(xe_rtp_match_first_render_or_compute)), + ENGINE_CLASS(RENDER)), XE_RTP_ACTIONS(SET(RT_CTRL, DIS_NULL_QUERY)) }, { XE_RTP_NAME("Tuning: disable HW reporting of ctx switch to GHWSP"), diff --git a/drivers/gpu/drm/xe/xe_uc_fw.c b/drivers/gpu/drm/xe/xe_uc_fw.c index 459ddb1730a8..df1a697b6f27 100644 --- a/drivers/gpu/drm/xe/xe_uc_fw.c +++ b/drivers/gpu/drm/xe/xe_uc_fw.c @@ -141,7 +141,7 @@ struct fw_blobs_by_type { /* for the GSC FW we match the compatibility version and not the release one */ #define XE_GSC_FIRMWARE_DEFS(fw_def, major_ver) \ - fw_def(NOVALAKE_S, GT_TYPE_ANY, major_ver(xe, gsc, nvl, 108, 0, 0)) \ + fw_def(NOVALAKE_S, GT_TYPE_ANY, major_ver(xe, gsc, nvl, 108, 1, 0)) \ fw_def(PANTHERLAKE, GT_TYPE_ANY, major_ver(xe, gsc, ptl, 105, 1, 0)) \ fw_def(LUNARLAKE, GT_TYPE_ANY, major_ver(xe, gsc, lnl, 104, 1, 0)) \ fw_def(METEORLAKE, GT_TYPE_ANY, major_ver(i915, gsc, mtl, 102, 1, 0)) diff --git a/drivers/gpu/drm/xe/xe_vm.c b/drivers/gpu/drm/xe/xe_vm.c index d25de5652767..6bc320f7caf4 100644 --- a/drivers/gpu/drm/xe/xe_vm.c +++ b/drivers/gpu/drm/xe/xe_vm.c @@ -272,8 +272,15 @@ int xe_vm_add_compute_exec_queue(struct xe_vm *vm, struct xe_exec_queue *q) * Check to see if a preemption on VM is in flight or userptr * invalidation, if so trigger this preempt fence to sync state with * other preempt fences on the VM. + * + * Also trigger it if eviction or rebinding is pending. BOs evicted + * before the first exec queue was added had no preempt fence to + * trigger. Suspend this queue until the rebind worker restores + * the mappings. */ - wait = __xe_vm_userptr_needs_repin(vm) || preempt_fences_waiting(vm); + wait = __xe_vm_userptr_needs_repin(vm) || preempt_fences_waiting(vm) || + !list_empty(&vm->gpuvm.evict.list) || + !list_empty(&vm->rebind_list); if (wait) dma_fence_enable_signaling(pfence); @@ -701,7 +708,7 @@ static void xe_vm_clear_fault_entries(struct xe_vm *vm) vm->faults.len = 0; } -static int xe_vma_ops_alloc(struct xe_vma_ops *vops, bool array_of_binds) +static noinline int xe_vma_ops_alloc(struct xe_vma_ops *vops, bool array_of_binds) { int i; diff --git a/drivers/gpu/drm/xe/xe_vm_madvise.c b/drivers/gpu/drm/xe/xe_vm_madvise.c index 5c7aefc641ee..a835cc55658f 100644 --- a/drivers/gpu/drm/xe/xe_vm_madvise.c +++ b/drivers/gpu/drm/xe/xe_vm_madvise.c @@ -659,11 +659,8 @@ int xe_vm_madvise_ioctl(struct drm_device *dev, void *data, struct drm_file *fil err = -EINVAL; goto free_vmas; } - } - if (args->type == DRM_XE_MEM_RANGE_ATTR_PAT) { - if (!check_pat_args_are_sane(xe, &madvise_range, - args->pat_index.val)) { + if (!check_pat_args_are_sane(xe, &madvise_range, pat_index)) { err = -EINVAL; goto free_vmas; } diff --git a/drivers/gpu/drm/xe/xe_wa.c b/drivers/gpu/drm/xe/xe_wa.c index c71318b901d6..bd556412c294 100644 --- a/drivers/gpu/drm/xe/xe_wa.c +++ b/drivers/gpu/drm/xe/xe_wa.c @@ -581,8 +581,9 @@ static const struct xe_rtp_table_sr engine_was = XE_RTP_TABLE_SR( XE_RTP_ACTIONS(SET(TDL_CHICKEN, QID_WAIT_FOR_THREAD_NOT_RUN_DISABLE)) }, { XE_RTP_NAME("16023105232"), - XE_RTP_RULES(MEDIA_VERSION_RANGE(1301, 3000), OR, - GRAPHICS_VERSION_RANGE(2001, 3001)), + /* IP versions need to be in sync with the respective entry in xe_wa_oob.rules. */ + XE_RTP_RULES(MEDIA_VERSION_RANGE(1301, 3002), OR, + GRAPHICS_VERSION_RANGE(2001, 3005)), XE_RTP_ACTIONS(SET(RING_PSMI_CTL(0), RC_SEMA_IDLE_MSG_DISABLE, XE_RTP_ACTION_FLAG(ENGINE_BASE))) }, diff --git a/drivers/gpu/drm/xe/xe_wa_oob.rules b/drivers/gpu/drm/xe/xe_wa_oob.rules index f35181fc4e49..842f42679c23 100644 --- a/drivers/gpu/drm/xe/xe_wa_oob.rules +++ b/drivers/gpu/drm/xe/xe_wa_oob.rules @@ -44,6 +44,7 @@ 18013179988 GRAPHICS_VERSION(1255) GRAPHICS_VERSION_RANGE(1270, 1274) 1508761755 GRAPHICS_VERSION(1255) +# IP versions need to be in sync with the respective entry in xe_wa.c. 16023105232 GRAPHICS_VERSION_RANGE(2001, 3005) MEDIA_VERSION_RANGE(1301, 3002) 16026508708 GRAPHICS_VERSION_RANGE(1200, 3005) diff --git a/drivers/hwmon/aht10.c b/drivers/hwmon/aht10.c index 89d18793137c..1a7580bf18b7 100644 --- a/drivers/hwmon/aht10.c +++ b/drivers/hwmon/aht10.c @@ -222,7 +222,7 @@ static int aht10_read_values(struct aht10_data *data) static ssize_t aht10_interval_write(struct aht10_data *data, long val) { - data->min_poll_interval = ms_to_ktime(clamp_val(val, 2000, LONG_MAX)); + data->min_poll_interval = ms_to_ktime(clamp_val(val, 2000, INT_MAX)); return 0; } diff --git a/drivers/hwmon/gpio-fan.c b/drivers/hwmon/gpio-fan.c index d95a00f1c863..55c812442b4f 100644 --- a/drivers/hwmon/gpio-fan.c +++ b/drivers/hwmon/gpio-fan.c @@ -528,8 +528,6 @@ static void gpio_fan_stop(void *data) mutex_lock(&fan_data->lock); set_fan_speed(data, 0); mutex_unlock(&fan_data->lock); - - pm_runtime_disable(fan_data->dev); } static int gpio_fan_probe(struct platform_device *pdev) @@ -556,6 +554,11 @@ static int gpio_fan_probe(struct platform_device *pdev) return dev_err_probe(dev, PTR_ERR(fan_data->supply), "Failed to get fan-supply"); + pm_runtime_set_suspended(dev); + err = devm_pm_runtime_enable(dev); + if (err) + return err; + /* Configure control GPIOs if available. */ if (fan_data->gpios && fan_data->num_gpios > 0) { if (!fan_data->speed || fan_data->num_speed <= 1) @@ -563,6 +566,12 @@ static int gpio_fan_probe(struct platform_device *pdev) err = fan_ctrl_init(fan_data); if (err) return err; + /* If current GPIO state is active, mark RPM as active as well */ + if (fan_data->speed_index > 0) { + err = pm_runtime_resume_and_get(dev); + if (err) + return err; + } err = devm_add_action_or_reset(dev, gpio_fan_stop, fan_data); if (err) return err; @@ -583,17 +592,6 @@ static int gpio_fan_probe(struct platform_device *pdev) return err; } - pm_runtime_set_suspended(&pdev->dev); - pm_runtime_enable(&pdev->dev); - /* If current GPIO state is active, mark RPM as active as well */ - if (fan_data->speed_index > 0) { - int ret; - - ret = pm_runtime_resume_and_get(&pdev->dev); - if (ret) - return ret; - } - /* Optional cooling device register for Device tree platforms */ fan_data->cdev = devm_thermal_of_child_cooling_device_register(dev, np, "gpio-fan", diff --git a/drivers/hwmon/max31760.c b/drivers/hwmon/max31760.c index d88c1eff9146..cf9ee0ed1389 100644 --- a/drivers/hwmon/max31760.c +++ b/drivers/hwmon/max31760.c @@ -27,8 +27,8 @@ #define REG_TACH(ch) (0x52 + (ch) * 2) #define REG_TEMP_INPUT(ch) (0x56 + (ch) * 2) -#define REG_TEMP_MAX(ch) (0x06 + (ch) * 2) -#define REG_TEMP_CRIT(ch) (0x0A + (ch) * 2) +#define REG_TEMP_MAX(ch) ((ch) ? 0x0C : 0x06) +#define REG_TEMP_CRIT(ch) ((ch) ? 0x08 : 0x0A) #define TEMP11_FROM_REG(reg) ((reg) / 32 * 125) #define TEMP11_TO_REG(val) (DIV_ROUND_CLOSEST(clamp_val((val), -128000, \ @@ -68,8 +68,9 @@ static const int max31760_pwm_freq[] = {33, 150, 1500, 25000}; static int tach_to_rpm(u16 tach) { + /* The count is 0 until the first measurement */ if (tach == 0) - tach = 1; + return 0; return 60 * 100000 / tach / 2; } @@ -533,8 +534,9 @@ static int max31760_probe(struct i2c_client *client) dev_set_drvdata(dev, state); - /* Set alert output to comparator mode */ - ret = regmap_set_bits(state->regmap, REG_CR2, CR2_ALERTS); + /* Leave standby mode, set alert output to comparator mode */ + ret = regmap_update_bits(state->regmap, REG_CR2, CR2_STBY | CR2_ALERTS, + CR2_ALERTS); if (ret) return dev_err_probe(dev, ret, "cannot write register\n"); diff --git a/drivers/hwmon/nct6775-core.c b/drivers/hwmon/nct6775-core.c index 6e97e4f08b90..3515a962adac 100644 --- a/drivers/hwmon/nct6775-core.c +++ b/drivers/hwmon/nct6775-core.c @@ -1188,15 +1188,13 @@ bool nct6775_reg_is_word_sized(struct nct6775_data *data, u16 reg) case nct6106: return reg == 0x20 || reg == 0x22 || reg == 0x24 || (reg >= 0x59 && reg < 0x69 && (reg & 1)) || - reg == 0xe0 || reg == 0xe2 || reg == 0xe4 || - reg == 0x111 || reg == 0x121 || reg == 0x131; + reg == 0xe0 || reg == 0xe2 || reg == 0xe4; case nct6116: case nct6126: return reg == 0x20 || reg == 0x22 || reg == 0x24 || reg == 0x26 || reg == 0x28 || reg == 0x59 || reg == 0x5b || reg == 0xe0 || reg == 0xe2 || reg == 0xe4 || reg == 0xe6 || - reg == 0xe8 || reg == 0x111 || reg == 0x121 || reg == 0x131 || - reg == 0x191 || reg == 0x1a1; + reg == 0xe8; case nct6775: return (((reg & 0xff00) == 0x100 || (reg & 0xff00) == 0x200) && diff --git a/drivers/hwmon/pmbus/mp2975.c b/drivers/hwmon/pmbus/mp2975.c index a11ec6756990..2ad6b7d831c8 100644 --- a/drivers/hwmon/pmbus/mp2975.c +++ b/drivers/hwmon/pmbus/mp2975.c @@ -109,10 +109,7 @@ struct mp2975_data { int vout_scale; int max_phases[MP2975_PAGE_NUM]; int vid_step[MP2975_PAGE_NUM]; - int vref[MP2975_PAGE_NUM]; - int vref_off[MP2975_PAGE_NUM]; int vout_max[MP2975_PAGE_NUM]; - int vout_ov_fixed[MP2975_PAGE_NUM]; int curr_sense_gain[MP2975_PAGE_NUM]; }; @@ -460,12 +457,77 @@ static int mp2973_write_word_data(struct i2c_client *client, int page, return pmbus_write_word_data(client, 0, PMBUS_SMBALERT_MASK, ret); } +/* + * Let the PMBus core change the page, so that the page it caches matches the + * device. The core does not issue PAGE commands for a single rail + * configuration, thus change the page directly then. + */ +static int +mp2975_page_set(struct i2c_client *client, struct mp2975_data *data, int page) +{ + if (data->info.pages > 1) + return pmbus_set_page(client, page, 0xff); + + return i2c_smbus_write_byte_data(client, PMBUS_PAGE, page); +} + +/* + * Voltage reference is available on page 3 only. The callers read a register + * of the rail through the core first, thus the core caches the rail page. + */ +static int +mp2975_vref_get(struct i2c_client *client, struct mp2975_data *data, int page) +{ + int ret, vref; + + ret = mp2975_page_set(client, data, 3); + if (ret < 0) + return ret; + + vref = i2c_smbus_read_word_data(client, page ? MP2975_MFR_READ_VREF_R2 : + MP2975_MFR_READ_VREF_R1); + + ret = mp2975_page_set(client, data, page); + if (ret < 0) + return ret; + + return (vref < 0) ? vref : vref * data->vid_step[page]; +} + +static int +mp2975_ovp2_offset_get(int ovp_th_set) +{ + switch ((ovp_th_set & GENMASK(5, 3)) >> 3) { + case 1: + return 140; + case 2: + return 220; + case 4: + return 400; + default: + return -EINVAL; + } +} + +static int +mp2975_vout_ovp2_get(struct i2c_client *client, struct mp2975_data *data, + int page, int vref_off) +{ + int vref; + + vref = mp2975_vref_get(client, data, page); + if (vref < 0) + return vref; + + return vref + DIV_ROUND_CLOSEST(vref_off * data->vout_scale, 10); +} + static int mp2975_read_word_data(struct i2c_client *client, int page, int phase, int reg) { const struct pmbus_driver_info *info = pmbus_get_driver_info(client); struct mp2975_data *data = to_mp2975_data(info); - int ret; + int ret, ovp1, vref_off, uv_off; switch (reg) { case PMBUS_OT_FAULT_LIMIT: @@ -482,19 +544,35 @@ static int mp2975_read_word_data(struct i2c_client *client, int page, break; case PMBUS_VOUT_OV_FAULT_LIMIT: /* - * Register provides two values for over-voltage protection - * threshold for fixed (ovp2) and tracking (ovp1) modes. The - * minimum of these two values is provided as over-voltage - * fault alarm. + * Device provides dual over-voltage protection. OVP1 is + * referred to the maximum reference voltage, while OVP2 is + * referred to the current voltage reference, which is changed + * at runtime. Protection is tripped by any of them, thus the + * minimum of the two is exposed as over-voltage fault alarm, + * and OVP2 is obtained on each read. */ ret = mp2975_read_word_helper(client, page, phase, MP2975_MFR_OVP_TH_SET, - GENMASK(2, 0)); + GENMASK(5, 0)); if (ret < 0) return ret; - ret = min_t(int, data->vout_max[page] + 50 * (ret + 1), - data->vout_ov_fixed[page]); + ovp1 = data->vout_max[page] + 50 * ((ret & GENMASK(2, 0)) + 1); + + /* OVP1 still applies if the OVP2 threshold is unknown. */ + vref_off = mp2975_ovp2_offset_get(ret); + if (vref_off < 0) { + dev_warn_once(&client->dev, + "unsupported OVP2 selector, reporting OVP1 threshold\n"); + ret = ovp1; + break; + } + + ret = mp2975_vout_ovp2_get(client, data, page, vref_off); + if (ret < 0) + return ret; + + ret = min_t(int, ovp1, ret); break; case PMBUS_VOUT_UV_FAULT_LIMIT: ret = mp2975_read_word_helper(client, page, phase, @@ -503,8 +581,17 @@ static int mp2975_read_word_data(struct i2c_client *client, int page, if (ret < 0) return ret; - ret = DIV_ROUND_CLOSEST(data->vref[page] * 10 - 50 * - (ret + 1) * data->vout_scale, 10); + uv_off = 50 * (ret + 1) * data->vout_scale; + + ret = mp2975_vref_get(client, data, page); + if (ret < 0) + return ret; + + /* + * Offset can exceed the voltage reference, while a negative + * value would be reported as a read error. + */ + ret = max_t(int, DIV_ROUND_CLOSEST(ret * 10 - uv_off, 10), 0); break; case PMBUS_VIRT_READ_POUT_MAX: ret = mp2975_read_word_helper(client, page, phase, @@ -754,60 +841,6 @@ mp2975_current_sense_gain_get(struct i2c_client *client, } static int -mp2975_vref_get(struct i2c_client *client, struct mp2975_data *data, - struct pmbus_driver_info *info) -{ - int ret; - - ret = i2c_smbus_write_byte_data(client, PMBUS_PAGE, 3); - if (ret < 0) - return ret; - - /* Get voltage reference value for rail 1. */ - ret = i2c_smbus_read_word_data(client, MP2975_MFR_READ_VREF_R1); - if (ret < 0) - return ret; - - data->vref[0] = ret * data->vid_step[0]; - - /* Get voltage reference value for rail 2, if connected. */ - if (data->info.pages == MP2975_PAGE_NUM) { - ret = i2c_smbus_read_word_data(client, MP2975_MFR_READ_VREF_R2); - if (ret < 0) - return ret; - - data->vref[1] = ret * data->vid_step[1]; - } - return 0; -} - -static int -mp2975_vref_offset_get(struct i2c_client *client, struct mp2975_data *data, - int page) -{ - int ret; - - ret = i2c_smbus_read_word_data(client, MP2975_MFR_OVP_TH_SET); - if (ret < 0) - return ret; - - switch ((ret & GENMASK(5, 3)) >> 3) { - case 1: - data->vref_off[page] = 140; - break; - case 2: - data->vref_off[page] = 220; - break; - case 4: - data->vref_off[page] = 400; - break; - default: - return -EINVAL; - } - return 0; -} - -static int mp2975_vout_max_get(struct i2c_client *client, struct mp2975_data *data, struct pmbus_driver_info *info, int page) { @@ -911,25 +944,6 @@ mp2975_vout_per_rail_config_get(struct i2c_client *client, ret = mp2975_vout_max_get(client, data, info, i); if (ret < 0) return ret; - - /* Skip if reading Vref is unsupported */ - if (data->chip_id != mp2975) - continue; - - /* Obtain voltage reference offsets. */ - ret = mp2975_vref_offset_get(client, data, i); - if (ret < 0) - return ret; - - /* - * Set over-voltage fixed value. Thresholds are provided as - * fixed value, and tracking value. The minimum of them are - * exposed as over-voltage critical threshold. - */ - data->vout_ov_fixed[i] = data->vref[i] + - DIV_ROUND_CLOSEST(data->vref_off[i] * - data->vout_scale, - 10); } return 0; @@ -1042,11 +1056,6 @@ static int mp2975_probe(struct i2c_client *client) if (ret) return ret; - /* Obtain voltage reference values. */ - ret = mp2975_vref_get(client, data, info); - if (ret) - return ret; - /* Obtain vout over-voltage scales. */ ret = mp2975_vout_ov_scale_get(client, data, info); if (ret < 0) @@ -1063,7 +1072,21 @@ static int mp2975_probe(struct i2c_client *client) if (ret) return ret; - return pmbus_do_probe(client, info); + ret = pmbus_do_probe(client, info); + if (ret) + return ret; + + /* + * Vout over- and under-voltage fault limits are relative to the + * voltage reference, which is changed at runtime. Do not allow the + * PMBus core to cache them. + */ + if (data->chip_id == mp2975) { + pmbus_set_update(client, PMBUS_VOUT_OV_FAULT_LIMIT, true); + pmbus_set_update(client, PMBUS_VOUT_UV_FAULT_LIMIT, true); + } + + return 0; } static const struct of_device_id mp2975_of_match[] = { diff --git a/drivers/hwmon/scmi-hwmon.c b/drivers/hwmon/scmi-hwmon.c index d4195d14a983..91a63e92c3ed 100644 --- a/drivers/hwmon/scmi-hwmon.c +++ b/drivers/hwmon/scmi-hwmon.c @@ -228,8 +228,8 @@ static int scmi_thermal_sensor_register(struct device *dev, static int scmi_hwmon_probe(struct scmi_device *sdev) { - int i, idx; u16 nr_sensors; + int i, idx, ret; enum hwmon_sensor_types type; struct scmi_sensors *scmi_sensors; const struct scmi_sensor_info *sensor; @@ -297,8 +297,12 @@ static int scmi_hwmon_probe(struct scmi_device *sdev) if (!nr_count[type]) continue; - scmi_hwmon_add_chan_info(scmi_hwmon_chan, dev, nr_count[type], - type, hwmon_attributes[type]); + ret = scmi_hwmon_add_chan_info(scmi_hwmon_chan, dev, + nr_count[type], type, + hwmon_attributes[type]); + if (ret) + return ret; + *ptr_scmi_ci++ = scmi_hwmon_chan++; scmi_sensors->info[type] = @@ -321,6 +325,12 @@ static int scmi_hwmon_probe(struct scmi_device *sdev) case ENERGY: type = scmi_types[sensor->type]; idx = --nr_count[type]; + ret = sensor_ops->config_set(ph, sensor->id, sensor_config); + if (ret) { + dev_err(dev, "Error enabling sensor %s. err=%d\n", + sensor->name, ret); + continue; + } *(scmi_sensors->info[type] + idx) = sensor; break; } @@ -333,19 +343,10 @@ static int scmi_hwmon_probe(struct scmi_device *sdev) return PTR_ERR(hwdev); for (i = 0; i < nr_count_temp; i++) { - int ret; - sensor = *(scmi_sensors->info[hwmon_temp] + i); if (!sensor) continue; - ret = sensor_ops->config_set(ph, i, sensor_config); - if (ret) { - dev_err(dev, "Error enabling sensor %s. err=%d\n", - sensor->name, ret); - continue; - } - /* * Warn on any misconfiguration related to thermal zones but * bail out of probing only on memory errors. diff --git a/drivers/hwmon/sy7636a-hwmon.c b/drivers/hwmon/sy7636a-hwmon.c index d51daaf63d63..f01f368d68e5 100644 --- a/drivers/hwmon/sy7636a-hwmon.c +++ b/drivers/hwmon/sy7636a-hwmon.c @@ -29,7 +29,7 @@ static int sy7636a_read(struct device *dev, enum hwmon_sensor_types type, if (ret) return ret; - *temp = reg_val * 1000; + *temp = (s8)reg_val * 1000; return 0; } diff --git a/drivers/iio/accel/Kconfig b/drivers/iio/accel/Kconfig index 141ac984247c..c6fce69ac470 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 8518ee23e114..03b140303520 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 7ac885d94d7f..27adcdd31201 100644 --- a/drivers/iio/accel/kxsd9.c +++ b/drivers/iio/accel/kxsd9.c @@ -478,8 +478,8 @@ void kxsd9_common_remove(struct device *dev) struct iio_dev *indio_dev = dev_get_drvdata(dev); struct kxsd9_state *st = iio_priv(indio_dev); - iio_triggered_buffer_cleanup(indio_dev); iio_device_unregister(indio_dev); + iio_triggered_buffer_cleanup(indio_dev); pm_runtime_get_sync(dev); pm_runtime_put_noidle(dev); pm_runtime_disable(dev); diff --git a/drivers/iio/adc/ad7780.c b/drivers/iio/adc/ad7780.c index 1cfad70320fe..c1428f30241c 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 c2688307bbba..10aa40ca35e7 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 b0f44c144f20..937c8b09ad45 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 44e014da9722..69fafb4aa4ea 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 452c30cf04f2..085fdaffb9cd 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 53ac2f4f383e..e46e90400bdc 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 6d60952dd33f..494b5d1c13a2 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 be12bb6781cb..308d431e6217 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 76bad554f028..4120adc12e89 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 3a6a09ffa526..c01292a15a29 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 298b2fe48a19..abe26ba212f5 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 551b86236abc..2839714f5bc8 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 9e7c26e37880..cb7713646e21 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 8c9e81a77e68..b3a784d3e67d 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 5222c2dce7d5..eac8a613dd53 100644 --- a/drivers/iio/common/scmi_sensors/scmi_iio.c +++ b/drivers/iio/common/scmi_sensors/scmi_iio.c @@ -14,6 +14,7 @@ #include <linux/iio/sysfs.h> #include <linux/kernel.h> #include <linux/kthread.h> +#include <linux/math64.h> #include <linux/module.h> #include <linux/mutex.h> #include <linux/scmi_protocol.h> @@ -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 1e21ad2a050d..4c15447ccb6b 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 3fa7acc69aeb..94d51af83042 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 c5392df029c3..30c23df6294e 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 b007f46d3fd6..0958b7d31a92 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 5c7582f3a4f9..8cf7e4e176a9 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 7cec81ff5685..aa7d4f25c393 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 2bf9fc29d7d2..5bff2a3a44bc 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 38c3f3b398d4..7265a3c3de05 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 8ef48daf1822..8d2e65e32ef9 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 d67a43843799..c77926f6db62 100644 --- a/drivers/iio/industrialio-acpi.c +++ b/drivers/iio/industrialio-acpi.c @@ -6,6 +6,7 @@ #include <linux/export.h> #include <linux/iio/iio.h> #include <linux/sprintf.h> +#include <linux/string.h> /** * 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 76926fee0f84..1078ffa8e06a 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 929343e42d83..00dfc2037c19 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 ef3ed9635a1e..f56d31404c25 100644 --- a/drivers/iio/light/tsl2591.c +++ b/drivers/iio/light/tsl2591.c @@ -16,6 +16,7 @@ #include <linux/interrupt.h> #include <linux/iopoll.h> #include <linux/kernel.h> +#include <linux/math64.h> #include <linux/module.h> #include <linux/mutex.h> #include <linux/pm_runtime.h> @@ -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 ce1bd42b0c7c..f1cc75245001 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 6f40cba4b1ba..7f028d7f1f1e 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 f4dae7ba1335..b651f01e1b5d 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 03415cc2c9b3..234e3ce63ff7 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 0199a6351a46..2a6da557f22e 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 79ba46d8a0aa..2585b9c6fb69 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 255a36976ac4..1c8ba28c030a 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 ed83d809ecf5..2a9b37df8f62 100644 --- a/drivers/iio/proximity/sx9360.c +++ b/drivers/iio/proximity/sx9360.c @@ -14,10 +14,12 @@ #include <linux/interrupt.h> #include <linux/kernel.h> #include <linux/log2.h> +#include <linux/math64.h> #include <linux/module.h> #include <linux/pm.h> #include <linux/property.h> #include <linux/regmap.h> +#include <linux/units.h> #include <linux/iio/iio.h> @@ -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 dadce9b44227..26522b6c5a2d 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 5e3262e461f4..ae67daff6df5 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 27d6ab5f5d7a..4f79da1f905e 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/iommu/amd/init.c b/drivers/iommu/amd/init.c index 3dd4ff145e55..58f63298493b 100644 --- a/drivers/iommu/amd/init.c +++ b/drivers/iommu/amd/init.c @@ -1752,6 +1752,21 @@ static int __init init_iommu_from_acpi(struct amd_iommu *iommu, return 0; } +/* + * Apply workaround for Zen1 to Zen5(BRH) generation of processors. + * References: CVE-2024-21963 + */ +static bool __init amd_iommu_force_max_dev_table(void) +{ + if (boot_cpu_data.x86 >= 0x17 && boot_cpu_data.x86 <= 0x1a) { + if (cpu_feature_enabled(X86_FEATURE_ZEN6)) + return false; + else + return true; + } + return false; +} + /* Allocate PCI segment data structure */ static struct amd_iommu_pci_seg *__init alloc_pci_segment(u16 id, struct acpi_table_header *ivrs_base) @@ -1774,9 +1789,15 @@ static struct amd_iommu_pci_seg *__init alloc_pci_segment(u16 id, pci_seg->last_bdf = last_bdf; DUMP_printk("PCI segment : 0x%0x, last bdf : 0x%04x\n", id, last_bdf); - pci_seg->dev_table_size = - max(roundup_pow_of_two((last_bdf + 1) * DEV_TABLE_ENTRY_SIZE), - SZ_4K); + if (amd_iommu_force_max_dev_table()) { + pr_info("Force device table to maximum size\n"); + pci_seg->dev_table_size = SZ_2M; + } else { + pci_seg->dev_table_size = + max(roundup_pow_of_two((last_bdf + 1) * + DEV_TABLE_ENTRY_SIZE), + SZ_4K); + } pci_seg->id = id; init_llist_head(&pci_seg->dev_data_list); diff --git a/drivers/iommu/iommufd/pages.c b/drivers/iommu/iommufd/pages.c index 2f6153108add..fcdbde007a9a 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/md/dm-cache-metadata.c b/drivers/md/dm-cache-metadata.c index 179b76173255..461044dca367 100644 --- a/drivers/md/dm-cache-metadata.c +++ b/drivers/md/dm-cache-metadata.c @@ -766,6 +766,7 @@ static struct dm_cache_metadata *metadata_open(struct block_device *bdev, return ERR_PTR(-ENOMEM); } + INIT_LIST_HEAD(&cmd->list); cmd->version = metadata_version; refcount_set(&cmd->ref_count, 1); init_rwsem(&cmd->root_lock); @@ -1432,7 +1433,8 @@ static int __load_mappings(struct dm_cache_metadata *cmd, from_cblock(cmd->cache_blocks), &cmd->dirty_cursor); if (r) { - dm_array_cursor_end(&cmd->hint_cursor); + if (hints_valid) + dm_array_cursor_end(&cmd->hint_cursor); dm_array_cursor_end(&cmd->mapping_cursor); return r; } diff --git a/drivers/md/dm-cache-target.c b/drivers/md/dm-cache-target.c index d292a44c921e..850c4b651f09 100644 --- a/drivers/md/dm-cache-target.c +++ b/drivers/md/dm-cache-target.c @@ -17,6 +17,7 @@ #include <linux/jiffies.h> #include <linux/init.h> #include <linux/kstrtox.h> +#include <linux/math64.h> #include <linux/mempool.h> #include <linux/module.h> #include <linux/rwsem.h> @@ -2383,9 +2384,7 @@ static int create_cache_policy(struct cache *cache, struct cache_args *ca, static bool too_many_discard_blocks(sector_t discard_block_size, sector_t origin_size) { - (void) sector_div(origin_size, discard_block_size); - - return origin_size > MAX_DISCARD_BLOCKS; + return div64_u64(origin_size, discard_block_size) > MAX_DISCARD_BLOCKS; } static sector_t calculate_discard_block_size(sector_t cache_block_size, @@ -2422,6 +2421,7 @@ static int cache_create(struct cache_args *ca, struct cache **result) struct cache *cache; struct dm_target *ti = ca->ti; dm_block_t origin_blocks; + sector_t discard_block_size; struct dm_cache_metadata *cmd; bool may_format = ca->features.mode == CM_WRITE; @@ -2521,9 +2521,15 @@ static int cache_create(struct cache_args *ca, struct cache **result) } clear_bitset(cache->dirty_bitset, from_cblock(cache->cache_size)); - cache->discard_block_size = + discard_block_size = calculate_discard_block_size(cache->sectors_per_block, cache->origin_sectors); + if (discard_block_size > U32_MAX) { + *error = "Discard block size exceeds 32 bits"; + r = -EOVERFLOW; + goto bad; + } + cache->discard_block_size = discard_block_size; cache->discard_nr_blocks = to_dblock(dm_sector_div_up(cache->origin_sectors, cache->discard_block_size)); cache->discard_bitset = alloc_bitset(from_dblock(cache->discard_nr_blocks)); @@ -2544,6 +2550,7 @@ static int cache_create(struct cache_args *ca, struct cache **result) if (IS_ERR(cache->copier)) { *error = "could not create kcopyd client"; r = PTR_ERR(cache->copier); + cache->copier = NULL; goto bad; } diff --git a/drivers/md/dm-crypt.c b/drivers/md/dm-crypt.c index a7655bba7ce3..02038a9cd21d 100644 --- a/drivers/md/dm-crypt.c +++ b/drivers/md/dm-crypt.c @@ -1982,8 +1982,9 @@ static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io, int async) /* crypt_convert should have filled the clone bio */ BUG_ON(io->ctx.iter_out.bi_size); - if ((likely(!async) && test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags)) || - test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags)) { + if (likely(!async) && + (test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags) || + test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags))) { dm_submit_bio_remap(io->base_bio, clone); return; } @@ -2847,8 +2848,11 @@ static int crypt_ctr_auth_cipher(struct crypt_config *cc, char *cipher_api) char *start, *end, *mac_alg = NULL; struct crypto_ahash *mac; - if (!strstarts(cipher_api, "authenc(")) + if (!strstarts(cipher_api, "authenc(")) { + if (test_bit(CRYPT_KEY_MAC_SIZE_SET, &cc->cipher_flags)) + return -EINVAL; return 0; + } start = strchr(cipher_api, '('); end = strchr(cipher_api, ','); @@ -3229,6 +3233,14 @@ static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv) ti->error = "Cannot allocate encryption context"; return -ENOMEM; } + + ret = percpu_counter_init(&cc->n_allocated_pages, 0, GFP_KERNEL); + if (ret < 0) { + ti->error = "Cannot initialize page counter"; + kfree_sensitive(cc); + return ret; + } + cc->key_size = key_size; cc->sector_size = (1 << SECTOR_SHIFT); cc->sector_shift = 0; @@ -3240,10 +3252,6 @@ static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv) crypt_calculate_pages_per_client(); spin_unlock(&dm_crypt_clients_lock); - ret = percpu_counter_init(&cc->n_allocated_pages, 0, GFP_KERNEL); - if (ret < 0) - goto bad; - /* Optional parameters need to be read before cipher constructor */ if (argc > 5) { ret = crypt_ctr_optional(ti, argc - 5, &argv[5]); diff --git a/drivers/md/dm-integrity.c b/drivers/md/dm-integrity.c index 802b377613b0..6968e38888db 100644 --- a/drivers/md/dm-integrity.c +++ b/drivers/md/dm-integrity.c @@ -2908,6 +2908,11 @@ static void integrity_commit(struct work_struct *w) spin_lock_irq(&ic->endio_wait.lock); flushes = bio_list_get(&ic->flush_bio_list); + if (unlikely(dm_integrity_failed(ic))) { + wake_up_locked(&ic->endio_wait); + spin_unlock_irq(&ic->endio_wait.lock); + goto release_flush_bios; + } if (unlikely(ic->mode != 'J')) { spin_unlock_irq(&ic->endio_wait.lock); dm_integrity_flush_buffers(ic, true); @@ -3888,6 +3893,24 @@ static bool superblock_changed(struct dm_integrity_c *ic) memcmp(ic->sb->salt, ic->sb_copy->salt, SALT_SIZE) != 0; } +/* + * The superblock is authenticated only if fix_hmac and journal_mac are used, + * so SB_FLAG_DIRTY_BITMAP may have been set by someone who doesn't know the + * key. Apply the policy that the constructor applies to SB_FLAG_RECALCULATING. + */ +static bool dm_integrity_may_recalc_dirty_bitmap(struct dm_integrity_c *ic) +{ + if (!ic->internal_hash) { + DMERR("Dirty bitmap found, but internal_hash is not used"); + return false; + } + if (dm_integrity_disable_recalculate(ic)) { + DMERR("Dirty bitmap found, but HMAC recalculation requires \"legacy_recalculate\""); + return false; + } + return true; +} + static void dm_integrity_resume(struct dm_target *ti) { struct dm_integrity_c *ic = ti->private; @@ -3977,8 +4000,10 @@ static void dm_integrity_resume(struct dm_target *ti) if (!(ic->sb->log2_blocks_per_bitmap_bit == ic->log2_blocks_per_bitmap_bit && block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors, BITMAP_OP_TEST_ALL_CLEAR)) || ic->reset_recalculate_flag) { - ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING); - ic->sb->recalc_sector = cpu_to_le64(0); + if (dm_integrity_may_recalc_dirty_bitmap(ic)) { + ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING); + ic->sb->recalc_sector = cpu_to_le64(0); + } } init_journal(ic, 0, ic->journal_sections, 0); replay_journal(ic); @@ -5409,7 +5434,6 @@ try_smaller_buffer: r = create_journal(ic, &ti->error); if (r) goto bad; - } if (ic->mode == 'B') { diff --git a/drivers/md/dm-ioctl.c b/drivers/md/dm-ioctl.c index 8f945f0aeda5..4a7cb0926c17 100644 --- a/drivers/md/dm-ioctl.c +++ b/drivers/md/dm-ioctl.c @@ -1794,7 +1794,7 @@ static void retrieve_deps(struct dm_table *table, deps->count = count; count = 0; list_for_each_entry(dd, dm_table_get_devices(table), list) - deps->dev[count++] = huge_encode_dev(dd->dm_dev->bdev->bd_dev); + deps->dev[count++] = huge_encode_dev(dd->bdev->bd_dev); param->data_size = param->data_start + needed; } diff --git a/drivers/md/dm-log-userspace-base.c b/drivers/md/dm-log-userspace-base.c index 3ca35aa4e057..48daa41728d6 100644 --- a/drivers/md/dm-log-userspace-base.c +++ b/drivers/md/dm-log-userspace-base.c @@ -294,9 +294,11 @@ static int userspace_ctr(struct dm_dirty_log *log, struct dm_target *ti, } r = dm_get_device(ti, devices_rdata, dm_table_get_mode(ti->table), &lc->log_dev); - if (r) + if (r) { DMERR("Failed to register %s with device-mapper", devices_rdata); + goto out; + } } if (lc->integrated_flush) { @@ -315,6 +317,8 @@ static int userspace_ctr(struct dm_dirty_log *log, struct dm_target *ti, out: kfree(devices_rdata); if (r) { + if (lc->log_dev) + dm_put_device(lc->ti, lc->log_dev); mempool_exit(&lc->flush_entry_pool); kfree(lc); kfree(ctr_str); diff --git a/drivers/md/dm-mpath.c b/drivers/md/dm-mpath.c index ae9318f5f21b..d2e94b96d2e4 100644 --- a/drivers/md/dm-mpath.c +++ b/drivers/md/dm-mpath.c @@ -797,7 +797,8 @@ static void queue_if_no_path_timeout_work(struct timer_list *t) static void enable_nopath_timeout(struct multipath *m) { unsigned long queue_if_no_path_timeout = - READ_ONCE(queue_if_no_path_timeout_secs) * HZ; + min_t(unsigned long, READ_ONCE(queue_if_no_path_timeout_secs), + MAX_JIFFY_OFFSET / HZ) * HZ; lockdep_assert_held(&m->lock); @@ -1085,8 +1086,9 @@ static int parse_hw_handler(struct dm_arg_set *as, struct multipath *m) if (hw_argc > 1) { char *p; - int i, j, len = 4; + int i, j, len; + len = snprintf(NULL, 0, "%d", hw_argc - 1) + 1; for (i = 0; i <= hw_argc - 2; i++) len += strlen(as->argv[i]) + 1; p = m->hw_handler_params = kzalloc(len, GFP_KERNEL); diff --git a/drivers/md/dm-pcache/backing_dev.c b/drivers/md/dm-pcache/backing_dev.c index 23002beb192a..84b4e76367fa 100644 --- a/drivers/md/dm-pcache/backing_dev.c +++ b/drivers/md/dm-pcache/backing_dev.c @@ -336,9 +336,9 @@ struct pcache_backing_dev_req *backing_dev_req_create(struct pcache_backing_dev return backing_req; } -void backing_dev_flush(struct pcache_backing_dev *backing_dev) +int backing_dev_flush(struct pcache_backing_dev *backing_dev) { - blkdev_issue_flush(backing_dev->dm_dev->bdev); + return blkdev_issue_flush(backing_dev->dm_dev->bdev); } int pcache_backing_init(void) diff --git a/drivers/md/dm-pcache/backing_dev.h b/drivers/md/dm-pcache/backing_dev.h index b371cba483b9..8422e5e76e29 100644 --- a/drivers/md/dm-pcache/backing_dev.h +++ b/drivers/md/dm-pcache/backing_dev.h @@ -120,7 +120,7 @@ struct pcache_backing_dev_req *backing_dev_req_alloc(struct pcache_backing_dev * struct pcache_backing_dev_req_opts *opts); void backing_dev_req_init(struct pcache_backing_dev_req *backing_req, struct pcache_backing_dev_req_opts *opts); -void backing_dev_flush(struct pcache_backing_dev *backing_dev); +int backing_dev_flush(struct pcache_backing_dev *backing_dev); int pcache_backing_init(void); void pcache_backing_exit(void); diff --git a/drivers/md/dm-pcache/cache_writeback.c b/drivers/md/dm-pcache/cache_writeback.c index c8a4c8110a58..e09560f172dd 100644 --- a/drivers/md/dm-pcache/cache_writeback.c +++ b/drivers/md/dm-pcache/cache_writeback.c @@ -18,12 +18,18 @@ static void writeback_ctx_end(struct pcache_cache *cache, int ret) return; if (!cache->writeback_ctx.ret) { - backing_dev_flush(cache->backing_dev); - - mutex_lock(&cache->dirty_tail_lock); - cache_pos_advance(&cache->dirty_tail, cache->writeback_ctx.advance); - cache_encode_dirty_tail(cache); - mutex_unlock(&cache->dirty_tail_lock); + ret = backing_dev_flush(cache->backing_dev); + if (ret) { + pcache_dev_err(CACHE_TO_PCACHE(cache), + "failed to flush backing device: %d", ret); + cache->writeback_ctx.ret = ret; + } else { + mutex_lock(&cache->dirty_tail_lock); + cache_pos_advance(&cache->dirty_tail, + cache->writeback_ctx.advance); + cache_encode_dirty_tail(cache); + mutex_unlock(&cache->dirty_tail_lock); + } } queue_delayed_work(cache_get_wq(cache), &cache->writeback_work, 0); } @@ -76,8 +82,16 @@ static inline bool is_cache_clean(struct pcache_cache *cache, struct pcache_cach void cache_writeback_exit(struct pcache_cache *cache) { + int ret; + cancel_delayed_work_sync(&cache->writeback_work); - backing_dev_flush(cache->backing_dev); + + ret = backing_dev_flush(cache->backing_dev); + if (ret) + pcache_dev_err(CACHE_TO_PCACHE(cache), + "failed to flush backing device during exit: %d", + ret); + cache_tree_exit(&cache->writeback_key_tree); } diff --git a/drivers/md/dm-raid.c b/drivers/md/dm-raid.c index ac019a0f5a92..e44d92462aff 100644 --- a/drivers/md/dm-raid.c +++ b/drivers/md/dm-raid.c @@ -2420,7 +2420,8 @@ static int super_init_validation(struct raid_set *rs, struct md_rdev *rdev) */ if (!test_bit(FirstUse, &r->flags) && (r->raid_disk >= 0)) { role = le32_to_cpu(sb2->array_position); - if (role < 0) + /* Bound @role before it indexes the failed_devices stack bitmap. */ + if (role < 0 || role >= rs->raid_disks) continue; if (role != r->raid_disk) { @@ -3333,7 +3334,7 @@ static void raid_dtr(struct dm_target *ti) rs->md.dm_gendisk = NULL; mddev_unlock(&rs->md); - if (work_pending(&rs->md.event_work)) + if (rs->md.event_work.func) flush_work(&rs->md.event_work); raid_set_free(rs); } diff --git a/drivers/md/dm-snap.c b/drivers/md/dm-snap.c index 797c432594d8..6968e806eb84 100644 --- a/drivers/md/dm-snap.c +++ b/drivers/md/dm-snap.c @@ -1358,8 +1358,10 @@ static int snapshot_ctr(struct dm_target *ti, unsigned int argc, char **argv) ti->private = s; ti->num_flush_bios = num_flush_bios; - if (s->discard_zeroes_cow) + if (s->discard_zeroes_cow) { ti->num_discard_bios = (s->discard_passdown_origin ? 2 : 1); + ti->max_discard_granularity = true; + } ti->per_io_data_size = sizeof(struct dm_snap_tracked_chunk); /* Add snapshot to the list of snapshots for this origin */ @@ -1946,8 +1948,8 @@ static void zero_exception(struct dm_snapshot *s, struct dm_exception *e, static bool io_overlaps_chunk(struct dm_snapshot *s, struct bio *bio) { - return bio->bi_iter.bi_size == - (s->store->chunk_size << SECTOR_SHIFT); + return bio->bi_iter.bi_size == (s->store->chunk_size << SECTOR_SHIFT) && + !(bio->bi_iter.bi_sector & s->store->chunk_mask); } static int snapshot_map(struct dm_target *ti, struct bio *bio) @@ -2007,11 +2009,13 @@ static int snapshot_map(struct dm_target *ti, struct bio *bio) e = dm_lookup_exception(&s->complete, chunk); if (e) { remap_exception(s, e, bio, chunk); - if (unlikely(bio_op(bio) == REQ_OP_DISCARD) && - io_overlaps_chunk(s, bio)) { + if (unlikely(bio_op(bio) == REQ_OP_DISCARD)) { dm_exception_table_unlock(&lock); up_read(&s->lock); - zero_exception(s, e, bio, chunk); + if (io_overlaps_chunk(s, bio)) + zero_exception(s, e, bio, chunk); + else + bio_endio(bio); r = DM_MAPIO_SUBMITTED; /* discard is not issued */ goto out; } @@ -2414,7 +2418,7 @@ static void snapshot_io_hints(struct dm_target *ti, struct queue_limits *limits) snap = snap_src; /* All discards are split on chunk_size boundary */ - limits->discard_granularity = snap->store->chunk_size; + limits->discard_granularity = snap->store->chunk_size << SECTOR_SHIFT; limits->max_hw_discard_sectors = snap->store->chunk_size; up_read(&_origins_lock); diff --git a/drivers/md/dm-sysfs.c b/drivers/md/dm-sysfs.c index 22bc70923a83..c9f81231df7b 100644 --- a/drivers/md/dm-sysfs.c +++ b/drivers/md/dm-sysfs.c @@ -128,9 +128,20 @@ static const struct kobj_type dm_ktype = { */ int dm_sysfs_init(struct mapped_device *md) { - return kobject_init_and_add(dm_kobject(md), &dm_ktype, - &disk_to_dev(dm_disk(md))->kobj, - "%s", "dm"); + struct kobject *kobj = dm_kobject(md); + int r; + + /* The kobject must be zeroed before calling kobject_init */ + memset(kobj, 0, sizeof(struct kobject)); + r = kobject_init_and_add(kobj, &dm_ktype, + &disk_to_dev(dm_disk(md))->kobj, + "%s", "dm"); + if (unlikely(r)) { + /* Weird semantics - we must call kobject_put on failure */ + dm_sysfs_exit(md); + return r; + } + return 0; } /* diff --git a/drivers/md/dm-table.c b/drivers/md/dm-table.c index 2e8d0436386f..48f25ab6b7fa 100644 --- a/drivers/md/dm-table.c +++ b/drivers/md/dm-table.c @@ -165,14 +165,16 @@ int dm_table_create(struct dm_table **result, blk_mode_t mode, static void free_devices(struct list_head *devices, struct mapped_device *md) { - struct list_head *tmp, *next; + struct dm_dev_internal *dd, *dd_next; + struct dm_dev_ref *ref, *ref_next; - list_for_each_safe(tmp, next, devices) { - struct dm_dev_internal *dd = - list_entry(tmp, struct dm_dev_internal, list); - DMWARN("%s: dm_table_destroy: dm_put_device call missing for %s", - dm_device_name(md), dd->dm_dev->name); - dm_put_table_device(md, dd->dm_dev); + list_for_each_entry_safe(dd, dd_next, devices, list) { + list_for_each_entry_safe(ref, ref_next, &dd->refs, list) { + DMWARN("%s: dm_table_destroy: dm_put_device call missing for %s", + dm_device_name(md), ref->dm_dev->name); + dm_put_table_device(md, ref->dm_dev); + kfree(ref); + } kfree(dd); } } @@ -218,13 +220,28 @@ static struct dm_dev_internal *find_device(struct list_head *l, dev_t dev) struct dm_dev_internal *dd; list_for_each_entry(dd, l, list) - if (dd->dm_dev->bdev->bd_dev == dev) + if (dd->bdev->bd_dev == dev) return dd; return NULL; } /* + * See if the device is already open with a mode that covers the + * requested one. + */ +static struct dm_dev_ref *find_ref(struct dm_dev_internal *dd, blk_mode_t mode) +{ + struct dm_dev_ref *ref; + + list_for_each_entry(ref, &dd->refs, list) + if ((ref->dm_dev->mode & mode) == mode) + return ref; + + return NULL; +} + +/* * If possible, this checks an area of a destination device is invalid. */ static int device_area_is_invalid(struct dm_target *ti, struct dm_dev *dev, @@ -304,31 +321,6 @@ static int device_area_is_invalid(struct dm_target *ti, struct dm_dev *dev, } /* - * This upgrades the mode on an already open dm_dev, being - * careful to leave things as they were if we fail to reopen the - * device and not to touch the existing bdev field in case - * it is accessed concurrently. - */ -static int upgrade_mode(struct dm_dev_internal *dd, blk_mode_t new_mode, - struct mapped_device *md) -{ - int r; - struct dm_dev *old_dev, *new_dev; - - old_dev = dd->dm_dev; - - r = dm_get_table_device(md, dd->dm_dev->bdev->bd_dev, - dd->dm_dev->mode | new_mode, &new_dev); - if (r) - return r; - - dd->dm_dev = new_dev; - dm_put_table_device(md, old_dev); - - return 0; -} - -/* * Note: the __ref annotation is because this function can call the __init * marked early_lookup_bdev when called during early boot code from dm-init.c. */ @@ -360,7 +352,9 @@ EXPORT_SYMBOL(dm_devt_from_path); /* * Add a device to the list, or just increment the usage count if - * it's already present. + * it's already present with a mode that covers the requested one. + * Otherwise open the device again with the requested mode, so the + * dm_devs returned earlier stay valid. */ int dm_get_device(struct dm_target *ti, const char *path, blk_mode_t mode, struct dm_dev **result) @@ -368,6 +362,7 @@ int dm_get_device(struct dm_target *ti, const char *path, blk_mode_t mode, int r; dev_t dev; struct dm_dev_internal *dd; + struct dm_dev_ref *ref; struct dm_table *t = ti->table; BUG_ON(!t); @@ -380,30 +375,46 @@ int dm_get_device(struct dm_target *ti, const char *path, blk_mode_t mode, return -EINVAL; dd = find_device(&t->devices, dev); - if (!dd) { + if (dd) { + ref = find_ref(dd, mode); + if (ref) { + refcount_inc(&ref->count); + goto out; + } + } else { dd = kmalloc_obj(*dd); if (!dd) return -ENOMEM; + INIT_LIST_HEAD(&dd->refs); + } - r = dm_get_table_device(t->md, dev, mode, &dd->dm_dev); - if (r) { - kfree(dd); - return r; - } + ref = kmalloc_obj(*ref); + if (!ref) { + r = -ENOMEM; + goto bad; + } - refcount_set(&dd->count, 1); - list_add(&dd->list, &t->devices); - goto out; + r = dm_get_table_device(t->md, dev, mode, &ref->dm_dev); + if (r) { + kfree(ref); + goto bad; + } + refcount_set(&ref->count, 1); - } else if (dd->dm_dev->mode != (mode | dd->dm_dev->mode)) { - r = upgrade_mode(dd, mode, t->md); - if (r) - return r; + /* A device in the list always has at least one ref */ + if (list_empty(&dd->refs)) { + dd->bdev = ref->dm_dev->bdev; + list_add(&dd->list, &t->devices); } - refcount_inc(&dd->count); + list_add_tail(&ref->list, &dd->refs); out: - *result = dd->dm_dev; + *result = ref->dm_dev; return 0; + +bad: + if (list_empty(&dd->refs)) + kfree(dd); + return r; } EXPORT_SYMBOL(dm_get_device); @@ -453,23 +464,28 @@ static int dm_set_device_limits(struct dm_target *ti, struct dm_dev *dev, */ void dm_put_device(struct dm_target *ti, struct dm_dev *d) { - int found = 0; struct list_head *devices = &ti->table->devices; struct dm_dev_internal *dd; + struct dm_dev_ref *ref; - list_for_each_entry(dd, devices, list) { - if (dd->dm_dev == d) { - found = 1; - break; - } - } - if (!found) { - DMERR("%s: device %s not in table devices list", - dm_device_name(ti->table->md), d->name); + list_for_each_entry(dd, devices, list) + list_for_each_entry(ref, &dd->refs, list) + if (ref->dm_dev == d) + goto found; + + DMERR("%s: device %s not in table devices list", + dm_device_name(ti->table->md), d->name); + return; + +found: + if (!refcount_dec_and_test(&ref->count)) return; - } - if (refcount_dec_and_test(&dd->count)) { - dm_put_table_device(ti->table->md, d); + + dm_put_table_device(ti->table->md, d); + list_del(&ref->list); + kfree(ref); + + if (list_empty(&dd->refs)) { list_del(&dd->list); kfree(dd); } diff --git a/drivers/md/dm-thin-metadata.c b/drivers/md/dm-thin-metadata.c index e60e1326376a..03df0b1aab78 100644 --- a/drivers/md/dm-thin-metadata.c +++ b/drivers/md/dm-thin-metadata.c @@ -1225,10 +1225,13 @@ static int __create_snap(struct dm_pool_metadata *pmd, __close_device(td); if (r) - goto bad; + goto bad2; return 0; +bad2: + list_del(&td->list); + kfree(td); bad: dm_btree_remove(&pmd->tl_info, pmd->root, &key, &pmd->root); dm_btree_remove(&pmd->details_info, pmd->details_root, diff --git a/drivers/md/dm-thin.c b/drivers/md/dm-thin.c index 358ed77ffb2b..0b65c1b09f47 100644 --- a/drivers/md/dm-thin.c +++ b/drivers/md/dm-thin.c @@ -1703,6 +1703,7 @@ static void break_up_discard_bio(struct thin_c *tc, dm_block_t begin, dm_block_t (void) build_key(tc->td, PHYSICAL, data_begin, data_begin + len, &data_key); if (bio_detain(tc->pool, &data_key, NULL, &data_cell)) { /* contention, we'll give up with this range */ + virt_begin += len; data_begin += len; continue; } @@ -2542,7 +2543,9 @@ static void set_pool_mode(struct pool *pool, enum pool_mode new_mode) struct pool_c *pt = pool->ti->private; bool needs_check = dm_pool_metadata_needs_check(pool->pmd); enum pool_mode old_mode = get_pool_mode(pool); - unsigned long no_space_timeout = READ_ONCE(no_space_timeout_secs) * HZ; + unsigned long no_space_timeout = + min_t(unsigned long, READ_ONCE(no_space_timeout_secs), + MAX_JIFFY_OFFSET / HZ) * HZ; /* * Never allow the pool to transition to PM_WRITE mode if user @@ -3146,7 +3149,7 @@ static int parse_pool_features(struct dm_arg_set *as, struct pool_features *pf, const char *arg_name; static const struct dm_arg _args[] = { - {0, 4, "Invalid number of pool feature arguments"}, + {0, 5, "Invalid number of pool feature arguments"}, }; /* diff --git a/drivers/md/dm-verity-target.c b/drivers/md/dm-verity-target.c index 60cf906c0361..306ed1f6c118 100644 --- a/drivers/md/dm-verity-target.c +++ b/drivers/md/dm-verity-target.c @@ -171,6 +171,15 @@ static void verity_hash_at_level(struct dm_verity *v, sector_t block, int level, } /* + * Skip verity work in response to I/O error when system is shutting down. + */ +static inline bool verity_is_system_shutting_down(void) +{ + return system_state == SYSTEM_HALT || system_state == SYSTEM_POWER_OFF + || system_state == SYSTEM_RESTART; +} + +/* * Handle verification errors. */ static int verity_handle_err(struct dm_verity *v, enum verity_block_type type, @@ -219,6 +228,15 @@ out: if (v->mode == DM_VERITY_MODE_LOGGING) return 0; + /* + * Devices may already be quiesced (e.g. UFS set offline by its + * shutdown hook), so a failure here does not imply corruption. Fail + * the I/O but do not restart or panic, which would also override the + * reboot reason of the shutdown already in progress. + */ + if (verity_is_system_shutting_down()) + return 1; + if (v->mode == DM_VERITY_MODE_RESTART) kernel_restart("dm-verity device corrupted"); @@ -593,15 +611,6 @@ error: return r; } -/* - * Skip verity work in response to I/O error when system is shutting down. - */ -static inline bool verity_is_system_shutting_down(void) -{ - return system_state == SYSTEM_HALT || system_state == SYSTEM_POWER_OFF - || system_state == SYSTEM_RESTART; -} - static void restart_io_error(struct work_struct *w) { kernel_restart("dm-verity device has I/O error"); diff --git a/drivers/md/dm-zone.c b/drivers/md/dm-zone.c index 35916c6e490e..9ddbb67e97e5 100644 --- a/drivers/md/dm-zone.c +++ b/drivers/md/dm-zone.c @@ -33,6 +33,8 @@ static int dm_blk_do_report_zones(struct mapped_device *md, struct dm_table *t, nr_zones - args->zone_idx); if (ret < 0) return ret; + if (!ret) + return -EIO; } while (args->zone_idx < nr_zones && args->next_sector < get_capacity(md->disk)); diff --git a/drivers/md/dm-zoned-reclaim.c b/drivers/md/dm-zoned-reclaim.c index c041413c729e..152cb8788114 100644 --- a/drivers/md/dm-zoned-reclaim.c +++ b/drivers/md/dm-zoned-reclaim.c @@ -288,7 +288,13 @@ static int dmz_reclaim_rnd_data(struct dmz_reclaim *zrc, struct dm_zone *dzone) again: szone = dmz_alloc_zone(zmd, zrc->dev_idx, alloc_flags | DMZ_ALLOC_RECLAIM); - if (!szone && alloc_flags == DMZ_ALLOC_SEQ && dmz_nr_cache_zones(zmd)) { + /* + * If no free sequential zone is available, a cache zone can still be + * moved into a free random zone of the zoned device, which frees cache + * space. Do not do this for a random zone: moving it into another + * random zone frees nothing and, on an idle target, repeats forever. + */ + if (!szone && alloc_flags == DMZ_ALLOC_SEQ && dmz_is_cache(dzone)) { alloc_flags = DMZ_ALLOC_RND; goto again; } @@ -537,6 +543,16 @@ static void dmz_reclaim_work(struct work_struct *work) dmz_nr_rnd_zones(zmd, zrc->dev_idx)); ret = dmz_do_reclaim(zrc); + if (ret == -ENOSPC || ret == -EBUSY) { + /* + * No zone to copy into (-ENOSPC) or no zone to reclaim + * (-EBUSY): retrying at once cannot make progress and would + * spin. Poll again after the idle period instead, without + * postponing work that an allocation has already queued. + */ + queue_delayed_work(zrc->wq, &zrc->work, DMZ_IDLE_PERIOD); + return; + } if (ret && ret != -EINTR) { if (!dmz_check_dev(zmd)) return; diff --git a/drivers/md/dm.c b/drivers/md/dm.c index 1881d86111fb..38eaae8ac9b4 100644 --- a/drivers/md/dm.c +++ b/drivers/md/dm.c @@ -983,7 +983,7 @@ static void __dm_io_complete(struct dm_io *io, bool first_stage) if (requeued) return; - if (unlikely(requeue_flush_with_data)) { + if (unlikely(requeue_flush_with_data) && !io_error) { /* * Preflush done for flush with data, reissue * without REQ_PREFLUSH. @@ -991,7 +991,7 @@ static void __dm_io_complete(struct dm_io *io, bool first_stage) bio->bi_opf &= ~REQ_PREFLUSH; queue_io(md, bio); } else { - /* done with normal IO or empty flush */ + /* done with normal IO, empty flush or failed preflush */ if (io_error) bio->bi_status = io_error; bio_endio(bio); @@ -1588,7 +1588,7 @@ static void __send_empty_flush(struct clone_info *ci) */ clone = alloc_tio(ci, NULL, 0, &len, GFP_NOIO); atomic_add(1, &ci->io->io_count); - bio_set_dev(clone, dd->dm_dev->bdev); + bio_set_dev(clone, dd->bdev); clone->bi_end_io = clone_endio; dm_submit_bio_remap(clone, NULL); } @@ -1929,8 +1929,13 @@ static blk_status_t __send_zone_reset_all(struct clone_info *ci) break; } - /* Release the reference that alloc_io() took for submission. */ - atomic_sub(1, &ci->io->io_count); + /* + * Release the reference that alloc_io() took for submission. On error, + * that reference was not consumed: dm_split_and_process_bio() releases + * it on the error path, so do not release it here a second time. + */ + if (sts == BLK_STS_OK) + atomic_dec(&ci->io->io_count); return sts; } @@ -2606,13 +2611,17 @@ int dm_setup_md_queue(struct mapped_device *md, struct dm_table *t) WARN_ON_ONCE(type == DM_TYPE_NONE); + /* A failed setup may have left the queue initialized or the disk dead. */ + if (md->tag_set || test_bit(GD_DEAD, &md->disk->state)) + return -ENODEV; + if (type == DM_TYPE_REQUEST_BASED) { - md->disk->fops = &dm_rq_blk_dops; r = dm_mq_init_request_queue(md, t); if (r) { DMERR("Cannot initialize queue for request-based dm mapped device"); return r; } + md->disk->fops = &dm_rq_blk_dops; } r = dm_calculate_queue_limits(t, &limits); diff --git a/drivers/md/dm.h b/drivers/md/dm.h index 7a795979ec72..34f58060243f 100644 --- a/drivers/md/dm.h +++ b/drivers/md/dm.h @@ -37,10 +37,26 @@ /* * List of devices that a metadevice uses and should open/close. + * There is one dm_dev_internal per device. It holds one dm_dev_ref + * for each mode that the targets opened the device with. */ struct dm_dev_internal { struct list_head list; - refcount_t count; + struct block_device *bdev; + struct list_head refs; +}; + +/* + * One open of a device with one mode, shared by the targets of a table. + * dm_get_device() reuses a dm_dev_ref whose mode covers the requested + * mode, and adds a new one only when none does. So the dm_dev_refs of + * a device have different modes, and a table holds each table_device + * at most once. table_device->count is still the number of tables that + * use the table_device. + */ +struct dm_dev_ref { + struct list_head list; + refcount_t count; /* dm_get_device() calls that returned dm_dev */ struct dm_dev *dm_dev; }; diff --git a/drivers/md/persistent-data/dm-btree-remove.c b/drivers/md/persistent-data/dm-btree-remove.c index 2357ff9b53f3..18f53c672202 100644 --- a/drivers/md/persistent-data/dm-btree-remove.c +++ b/drivers/md/persistent-data/dm-btree-remove.c @@ -253,7 +253,9 @@ static int __rebalance2(struct dm_btree_info *info, struct btree_node *parent, /* * Merge */ - node_copy(left, right, -nr_right); + ret = node_copy(left, right, -nr_right); + if (unlikely(ret)) + return ret; left->header.nr_entries = cpu_to_le32(nr_left + nr_right); delete_at(parent, r->index); @@ -315,13 +317,16 @@ static int delete_center_node(struct dm_btree_info *info, struct btree_node *par { uint32_t max_entries = le32_to_cpu(left->header.max_entries); unsigned int shift = min(max_entries - nr_left, nr_center); + int ret; if (nr_left + shift > max_entries) { DMERR("node shift out of bounds"); return -EINVAL; } - node_copy(left, center, -shift); + ret = node_copy(left, center, -shift); + if (unlikely(ret)) + return ret; left->header.nr_entries = cpu_to_le32(nr_left + shift); if (shift != nr_center) { @@ -333,7 +338,9 @@ static int delete_center_node(struct dm_btree_info *info, struct btree_node *par } node_shift(right, shift); - node_copy(center, right, shift); + ret = node_copy(center, right, shift); + if (unlikely(ret)) + return ret; right->header.nr_entries = cpu_to_le32(nr_right + shift); } *key_ptr(parent, r->index) = right->keys[0]; diff --git a/drivers/md/persistent-data/dm-btree.c b/drivers/md/persistent-data/dm-btree.c index dd02eee4a23c..abfbbab8c7c6 100644 --- a/drivers/md/persistent-data/dm-btree.c +++ b/drivers/md/persistent-data/dm-btree.c @@ -1582,7 +1582,13 @@ int dm_btree_cursor_begin(struct dm_btree_info *info, dm_block_t root, if (r) return r; - return find_leaf(c); + r = find_leaf(c); + if (unlikely(r)) { + dm_btree_cursor_end(c); + return r; + } + + return 0; } EXPORT_SYMBOL_GPL(dm_btree_cursor_begin); diff --git a/drivers/md/persistent-data/dm-space-map-common.c b/drivers/md/persistent-data/dm-space-map-common.c index 22a551c407da..833aefb0ab99 100644 --- a/drivers/md/persistent-data/dm-space-map-common.c +++ b/drivers/md/persistent-data/dm-space-map-common.c @@ -1190,17 +1190,20 @@ static dm_block_t disk_ll_max_entries(struct ll_disk *ll) static int disk_ll_commit(struct ll_disk *ll) { - int r = 0; + int r; unsigned int i; for (i = 0; i < IE_CACHE_SIZE; i++) { struct ie_cache *iec = ll->ie_cache + i; - if (iec->valid && iec->dirty) + if (iec->valid && iec->dirty) { r = ie_cache_writeback(ll, iec); + if (unlikely(r)) + return r; + } } - return r; + return 0; } int sm_ll_new_disk(struct ll_disk *ll, struct dm_transaction_manager *tm) diff --git a/drivers/memstick/core/memstick.c b/drivers/memstick/core/memstick.c index 0d15f48ef51d..6a80570ee01d 100644 --- a/drivers/memstick/core/memstick.c +++ b/drivers/memstick/core/memstick.c @@ -100,7 +100,6 @@ static void memstick_device_remove(struct device *dev) if (dev->driver && drv->remove) { drv->remove(card); - card->dev.driver = NULL; } put_device(dev); diff --git a/drivers/misc/bcm-vk/bcm_vk_sg.c b/drivers/misc/bcm-vk/bcm_vk_sg.c index 8662bb865129..b237a5332b7f 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 6afef0788b90..d03aeb8dea8f 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 b9a67629496b..3972f9504f12 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 9fa69acf28d5..ffaf5be3b605 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 790a4647811b..cfdef9531ab1 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/vmw_vmci/vmci_event.c b/drivers/misc/vmw_vmci/vmci_event.c index c3ef3b98c432..57d3a63678ac 100644 --- a/drivers/misc/vmw_vmci/vmci_event.c +++ b/drivers/misc/vmw_vmci/vmci_event.c @@ -213,7 +213,12 @@ int vmci_event_unsubscribe(u32 sub_id) if (!s) return VMCI_ERROR_NOT_FOUND; - kvfree_rcu_mightsleep(s); + /* + * Wait for event_deliver(): the caller is going to free what the + * callback works on. + */ + synchronize_rcu(); + kfree(s); return VMCI_SUCCESS; } diff --git a/drivers/mmc/host/jz4740_mmc.c b/drivers/mmc/host/jz4740_mmc.c index 6a3c26b7c82d..923cf1450de5 100644 --- a/drivers/mmc/host/jz4740_mmc.c +++ b/drivers/mmc/host/jz4740_mmc.c @@ -1151,12 +1151,13 @@ static void jz4740_mmc_remove(struct platform_device *pdev) { struct jz4740_mmc_host *host = platform_get_drvdata(pdev); + /* The card's driver may still send commands as it goes */ + mmc_remove_host(host->mmc); + timer_delete_sync(&host->timeout_timer); jz4740_mmc_set_irq_enabled(host, 0xff, false); jz4740_mmc_reset(host); - mmc_remove_host(host->mmc); - free_irq(host->irq, host); if (host->use_dma) diff --git a/drivers/mmc/host/meson-gx-mmc.c b/drivers/mmc/host/meson-gx-mmc.c index ceda79a9a59d..d2b9b5df9596 100644 --- a/drivers/mmc/host/meson-gx-mmc.c +++ b/drivers/mmc/host/meson-gx-mmc.c @@ -125,6 +125,7 @@ #define SD_EMMC_CFG_RESP_TIMEOUT 256 /* in clock cycles */ #define SD_EMMC_CMD_TIMEOUT 1024 /* in ms */ #define SD_EMMC_CMD_TIMEOUT_DATA 4096 /* in ms */ +#define SD_EMMC_CMD_TIMEOUT_MAX 32768 /* in ms, 2^15: limit of CMD_CFG_TIMEOUT_MASK */ #define SD_EMMC_CFG_CMD_GAP 16 /* in clock cycles */ #define SD_EMMC_DESC_BUF_LEN PAGE_SIZE @@ -212,7 +213,21 @@ static unsigned int meson_mmc_get_timeout_msecs(struct mmc_data *data) timeout = roundup_pow_of_two(timeout); - return min(timeout, 32768U); /* max. 2^15 ms */ + return min_t(unsigned int, timeout, SD_EMMC_CMD_TIMEOUT_MAX); +} + +/* For R1b the controller waits for busy to be released within this timeout. */ +static unsigned int meson_mmc_get_cmd_timeout_msecs(struct mmc_command *cmd) +{ + unsigned int timeout = cmd->busy_timeout; + + if (!timeout) + return SD_EMMC_CMD_TIMEOUT; + + timeout = clamp_t(unsigned int, timeout, SD_EMMC_CMD_TIMEOUT, + SD_EMMC_CMD_TIMEOUT_MAX); + + return roundup_pow_of_two(timeout); } static struct mmc_command *meson_mmc_get_next_command(struct mmc_command *cmd) @@ -841,7 +856,7 @@ static void meson_mmc_start_cmd(struct mmc_host *mmc, struct mmc_command *cmd) cmd_data = host->bounce_dma_addr & CMD_DATA_MASK; } else { cmd_cfg |= FIELD_PREP(CMD_CFG_TIMEOUT_MASK, - ilog2(SD_EMMC_CMD_TIMEOUT)); + ilog2(meson_mmc_get_cmd_timeout_msecs(cmd))); } /* Last descriptor */ @@ -1080,8 +1095,8 @@ static int meson_mmc_card_busy(struct mmc_host *mmc) regval = readl(host->regs + SD_EMMC_STATUS); - /* We are only interrested in lines 0 to 3, so mask the other ones */ - return !(FIELD_GET(STATUS_DATI, regval) & 0xf); + /* The card signals busy on DAT0 alone. */ + return !(FIELD_GET(STATUS_DATI, regval) & BIT(0)); } static int meson_mmc_voltage_switch(struct mmc_host *mmc, struct mmc_ios *ios) @@ -1168,6 +1183,9 @@ static int meson_mmc_probe(struct platform_device *pdev) mmc->caps |= MMC_CAP_CMD23; + /* The longest busy wait the CMD_CFG timeout field can hold. */ + mmc->max_busy_timeout = SD_EMMC_CMD_TIMEOUT_MAX; + if (mmc->caps & MMC_CAP_SDIO_IRQ) mmc->caps2 |= MMC_CAP2_SDIO_IRQ_NOTHREAD; diff --git a/drivers/mmc/host/mmci.c b/drivers/mmc/host/mmci.c index 9f99b85f176e..f5ee793ddad6 100644 --- a/drivers/mmc/host/mmci.c +++ b/drivers/mmc/host/mmci.c @@ -2477,11 +2477,13 @@ static int mmci_probe(struct amba_device *dev, ret = mmc_add_host(mmc); if (ret) - goto clk_disable; + goto dma_release; pm_runtime_put(&dev->dev); return 0; +dma_release: + mmci_dma_release(host); clk_disable: clk_disable_unprepare(host->clk); return ret; diff --git a/drivers/mmc/host/omap.c b/drivers/mmc/host/omap.c index 77ff91825815..36df578298c3 100644 --- a/drivers/mmc/host/omap.c +++ b/drivers/mmc/host/omap.c @@ -214,7 +214,7 @@ static void mmc_omap_select_slot(struct mmc_omap_slot *slot, int claimed) host->mmc = slot->mmc; spin_unlock_irqrestore(&host->slot_lock, flags); no_claim: - timer_delete(&host->clk_timer); + timer_delete_sync(&host->clk_timer); if (host->current_slot != slot || !claimed) mmc_omap_fclk_offdelay(host->current_slot); @@ -273,7 +273,7 @@ static void mmc_omap_release_slot(struct mmc_omap_slot *slot, int clk_enabled) /* Keeps clock running for at least 8 cycles on valid freq */ mod_timer(&host->clk_timer, jiffies + HZ/10); else { - timer_delete(&host->clk_timer); + timer_delete_sync(&host->clk_timer); mmc_omap_fclk_offdelay(slot); mmc_omap_fclk_enable(host, 0); } diff --git a/drivers/mmc/host/sdhci-brcmstb.c b/drivers/mmc/host/sdhci-brcmstb.c index 78198e99c3d3..db857f2273e2 100644 --- a/drivers/mmc/host/sdhci-brcmstb.c +++ b/drivers/mmc/host/sdhci-brcmstb.c @@ -490,6 +490,7 @@ static int sdhci_brcmstb_probe(struct platform_device *pdev) struct sdhci_brcmstb_priv *priv; u32 actual_clock_mhz; struct sdhci_host *host; + struct resource *boot_res; struct clk *clk; struct clk *base_clk = NULL; int res; @@ -533,9 +534,13 @@ static int sdhci_brcmstb_probe(struct platform_device *pdev) /* map non-standard BOOT registers if present */ if (host->mmc->caps & MMC_CAP_NONREMOVABLE) { - priv->boot_regs = devm_platform_get_and_ioremap_resource(pdev, 2, NULL); - if (IS_ERR(priv->boot_regs)) - priv->boot_regs = NULL; + boot_res = platform_get_resource(pdev, IORESOURCE_MEM, 2); + if (boot_res) { + priv->boot_regs = devm_ioremap_resource(&pdev->dev, + boot_res); + if (IS_ERR(priv->boot_regs)) + priv->boot_regs = NULL; + } } /* diff --git a/drivers/mmc/host/sdhci-esdhc-imx.c b/drivers/mmc/host/sdhci-esdhc-imx.c index dc138d34035b..e972de42b444 100644 --- a/drivers/mmc/host/sdhci-esdhc-imx.c +++ b/drivers/mmc/host/sdhci-esdhc-imx.c @@ -1142,6 +1142,20 @@ static void esdhc_reset_tuning(struct sdhci_host *host) } } +static void sdhci_esdhc_imx_set_ios(struct mmc_host *mmc, struct mmc_ios *ios) +{ + /* + * This controller has no driver-type control: esdhc_writew_le() + * discards the driver-type field when writing SDHCI_HOST_CONTROL2. + * The programmed value is therefore irrelevant, but SDHCI rejects + * non-SD values such as 4 (eMMC 40 ohm, from fixed-emmc-driver-type). + * Force an always-valid Type B. + */ + ios->drv_type = MMC_SET_DRIVER_TYPE_B; + + sdhci_set_ios(mmc, ios); +} + static void usdhc_init_card(struct mmc_host *mmc, struct mmc_card *card) { struct sdhci_host *host = mmc_priv(mmc); @@ -1952,6 +1966,9 @@ static int sdhci_esdhc_imx_probe(struct platform_device *pdev) host->max_timeout_count = 0xF; } + /* No SDHCI driver type control */ + host->mmc_host_ops.set_ios = sdhci_esdhc_imx_set_ios; + if (imx_data->socdata->flags & ESDHC_FLAG_MAN_TUNING) sdhci_esdhc_ops.platform_execute_tuning = esdhc_executing_tuning; diff --git a/drivers/mmc/host/sunxi-mmc.c b/drivers/mmc/host/sunxi-mmc.c index fe4c0f6d73f3..437fdadb5950 100644 --- a/drivers/mmc/host/sunxi-mmc.c +++ b/drivers/mmc/host/sunxi-mmc.c @@ -1354,8 +1354,13 @@ static int sunxi_mmc_resource_request(struct sunxi_mmc_host *host, goto error_disable_mmc; } - return devm_request_threaded_irq(&pdev->dev, host->irq, sunxi_mmc_irq, - sunxi_mmc_handle_manual_stop, 0, "sunxi-mmc", host); + ret = devm_request_threaded_irq(&pdev->dev, host->irq, sunxi_mmc_irq, + sunxi_mmc_handle_manual_stop, 0, + "sunxi-mmc", host); + if (ret) + goto error_disable_mmc; + + return 0; error_disable_mmc: sunxi_mmc_disable(host); @@ -1385,9 +1390,11 @@ static int sunxi_mmc_probe(struct platform_device *pdev) host->sg_cpu = dma_alloc_coherent(&pdev->dev, PAGE_SIZE, &host->sg_dma, GFP_KERNEL); - if (!host->sg_cpu) - return dev_err_probe(&pdev->dev, -ENOMEM, - "Failed to allocate DMA descriptor mem\n"); + if (!host->sg_cpu) { + ret = dev_err_probe(&pdev->dev, -ENOMEM, + "Failed to allocate DMA descriptor mem\n"); + goto error_disable_mmc; + } if (host->cfg->ccu_has_timings_switch) { /* @@ -1467,7 +1474,7 @@ static int sunxi_mmc_probe(struct platform_device *pdev) ret = mmc_add_host(mmc); if (ret) - goto error_free_dma; + goto error_disable_rpm; dev_info(&pdev->dev, "initialized, max. request size: %u KB%s\n", mmc->max_req_size >> 10, @@ -1475,8 +1482,13 @@ static int sunxi_mmc_probe(struct platform_device *pdev) return 0; +error_disable_rpm: + pm_runtime_disable(&pdev->dev); error_free_dma: dma_free_coherent(&pdev->dev, PAGE_SIZE, host->sg_cpu, host->sg_dma); +error_disable_mmc: + disable_irq(host->irq); + sunxi_mmc_disable(host); return ret; } diff --git a/drivers/net/amt.c b/drivers/net/amt.c index 81d26ef82cf5..8b9fc3d11ece 100644 --- a/drivers/net/amt.c +++ b/drivers/net/amt.c @@ -2147,13 +2147,12 @@ static void amt_mldv1_leave_handler(struct amt_dev *amt, struct sk_buff *skb, struct amt_tunnel_list *tunnel) { struct mld_msg *mld = (struct mld_msg *)icmp6_hdr(skb); - struct iphdr *iph = ip_hdr(skb); + struct ipv6hdr *ip6h = ipv6_hdr(skb); struct amt_group_node *gnode; union amt_addr group, host; memcpy(&group.ip6, &mld->mld_mca, sizeof(struct in6_addr)); - memset(&host, 0, sizeof(union amt_addr)); - host.ip4 = iph->saddr; + memcpy(&host.ip6, &ip6h->saddr, sizeof(struct in6_addr)); gnode = amt_lookup_group(tunnel, &group, &host, true); if (gnode) { @@ -3404,22 +3403,6 @@ static struct rtnl_link_ops amt_link_ops __read_mostly = { .fill_info = amt_fill_info, }; -static struct net_device *amt_lookup_upper_dev(struct net_device *dev) -{ - struct net_device *upper_dev; - struct amt_dev *amt; - - for_each_netdev(dev_net(dev), upper_dev) { - if (netif_is_amt(upper_dev)) { - amt = netdev_priv(upper_dev); - if (amt->stream_dev == dev) - return upper_dev; - } - } - - return NULL; -} - static int amt_device_event(struct notifier_block *unused, unsigned long event, void *ptr) { @@ -3429,26 +3412,34 @@ static int amt_device_event(struct notifier_block *unused, LIST_HEAD(list); int new_mtu; - upper_dev = amt_lookup_upper_dev(dev); - if (!upper_dev) - return NOTIFY_DONE; - amt = netdev_priv(upper_dev); + /* amt_dellink() leaves each device on the netns device list until + * unregister_netdevice_many(), so the walk stays valid. + */ + for_each_netdev(dev_net(dev), upper_dev) { + if (!netif_is_amt(upper_dev)) + continue; + amt = netdev_priv(upper_dev); + if (amt->stream_dev != dev) + continue; - switch (event) { - case NETDEV_UNREGISTER: - amt_dellink(amt->dev, &list); - unregister_netdevice_many(&list); - break; - case NETDEV_CHANGEMTU: - if (amt->mode == AMT_MODE_RELAY) - new_mtu = dev->mtu - AMT_RELAY_HLEN; - else - new_mtu = dev->mtu - AMT_GW_HLEN; + switch (event) { + case NETDEV_UNREGISTER: + amt_dellink(amt->dev, &list); + break; + case NETDEV_CHANGEMTU: + if (amt->mode == AMT_MODE_RELAY) + new_mtu = dev->mtu - AMT_RELAY_HLEN; + else + new_mtu = dev->mtu - AMT_GW_HLEN; - dev_set_mtu(amt->dev, new_mtu); - break; + dev_set_mtu(amt->dev, new_mtu); + break; + } } + if (event == NETDEV_UNREGISTER) + unregister_netdevice_many(&list); + return NOTIFY_DONE; } diff --git a/drivers/net/bonding/bond_main.c b/drivers/net/bonding/bond_main.c index a1c156c145b2..e9f5e753f677 100644 --- a/drivers/net/bonding/bond_main.c +++ b/drivers/net/bonding/bond_main.c @@ -2305,7 +2305,7 @@ skip_mac_set: SLAVE_NL_ERR(bond_dev, slave_dev, extack, "Slave does not support XDP"); res = -EOPNOTSUPP; - goto err_sysfs_del; + goto err_dec_slave_cnt; } } else if (bond->xdp_prog) { struct netdev_bpf xdp = { @@ -2319,14 +2319,14 @@ skip_mac_set: SLAVE_NL_ERR(bond_dev, slave_dev, extack, "Slave has XDP program loaded, please unload before enslaving"); res = -EOPNOTSUPP; - goto err_sysfs_del; + goto err_dec_slave_cnt; } res = dev_xdp_propagate(slave_dev, &xdp); if (res < 0) { /* ndo_bpf() sets extack error message */ slave_dbg(bond_dev, slave_dev, "Error %d calling ndo_bpf\n", res); - goto err_sysfs_del; + goto err_dec_slave_cnt; } if (bond->xdp_prog) bpf_prog_inc(bond->xdp_prog); @@ -2348,6 +2348,9 @@ skip_mac_set: return 0; /* Undo stages on error */ +err_dec_slave_cnt: + WRITE_ONCE(bond->slave_cnt, bond->slave_cnt - 1); + err_sysfs_del: bond_sysfs_slave_del(new_slave); diff --git a/drivers/net/dsa/microchip/ksz_common.c b/drivers/net/dsa/microchip/ksz_common.c index 86f1cc30805b..78af51c182b9 100644 --- a/drivers/net/dsa/microchip/ksz_common.c +++ b/drivers/net/dsa/microchip/ksz_common.c @@ -4023,6 +4023,7 @@ int ksz_switch_register(struct ksz_device *dev) mutex_init(&dev->regmap_mutex); mutex_init(&dev->alu_mutex); mutex_init(&dev->vlan_mutex); + mutex_init(&dev->lock_irq); ret = ksz_switch_detect(dev); if (ret) diff --git a/drivers/net/dsa/motorcomm/chip.c b/drivers/net/dsa/motorcomm/chip.c index b9f130ca7481..c753c746490a 100644 --- a/drivers/net/dsa/motorcomm/chip.c +++ b/drivers/net/dsa/motorcomm/chip.c @@ -1405,6 +1405,9 @@ yt921x_dsa_port_bridge_join(struct dsa_switch *ds, int port, struct netlink_ext_ack *extack) { struct yt921x_priv *priv = dsa_to_yt921x_priv(ds); + struct yt921x_port *pp = &priv->ports[port]; + struct net_device *brport_dev; + struct dsa_port *dp; u16 ports_mask; int res; @@ -1414,7 +1417,12 @@ yt921x_dsa_port_bridge_join(struct dsa_switch *ds, int port, ports_mask = dsa_bridge_ports(ds, bridge.dev); ports_mask |= priv->cpu_ports_mask; + dp = dsa_to_port(ds, port); + brport_dev = dsa_port_to_bridge_port(dp); + mutex_lock(&priv->reg_lock); + pp->isolated = br_port_flag_is_set(brport_dev, BR_ISOLATED); + pp->hairpin = br_port_flag_is_set(brport_dev, BR_HAIRPIN_MODE); res = yt921x_bridge_join(priv, port, ports_mask); mutex_unlock(&priv->reg_lock); diff --git a/drivers/net/dsa/motorcomm/tc.c b/drivers/net/dsa/motorcomm/tc.c index 9dbd61e48fee..e3f057ed580f 100644 --- a/drivers/net/dsa/motorcomm/tc.c +++ b/drivers/net/dsa/motorcomm/tc.c @@ -1030,55 +1030,54 @@ yt921x_acl_rule_ext_parse_flow_action(struct yt921x_acl_rule_ext *ruleext, const struct flow_rule *rule = flow_cls_offload_flow_rule(cls); const struct flow_action *flow_action = &rule->action; struct netlink_ext_ack *extack = cls->common.extack; - enum flow_action_id redir_act = NUM_FLOW_ACTIONS; const struct flow_action_entry *act; u32 *action = ruleext->r.action; bool seen_priority = false; - const char *reason = NULL; bool seen_police = false; + bool terminal = false; + bool redir = false; + const char *reason; unsigned int i; int res; memset(action, 0, 3 * sizeof(*action)); - flow_action_for_each(i, act, flow_action) + flow_action_for_each(i, act, flow_action) { + /* The flow action entry carries no mirred control, so there + * is no way to tell whether software would continue past a + * redirect and apply the actions after it. Leave the list to + * software instead of guessing a hardware verdict. + */ + if (redir) { + reason = "Action after redirect"; + goto fallback; + } + switch (act->id) { case FLOW_ACTION_ACCEPT: + action[2] |= YT921X_ACL_ACTc_FWD_EN | + YT921X_ACL_ACTc_FWD_FWD; + terminal = true; + break; case FLOW_ACTION_DROP: - case FLOW_ACTION_REDIRECT: - if (redir_act != NUM_FLOW_ACTIONS && - redir_act != act->id) { - reason = "Different redirect actions"; + action[2] |= YT921X_ACL_ACTc_FWD_EN | + YT921X_ACL_ACTc_FWD_REDIR; + terminal = true; + break; + case FLOW_ACTION_REDIRECT: { + struct dsa_port *to_dp; + + to_dp = dsa_port_from_netdev(act->dev); + if (IS_ERR(to_dp) || to_dp->ds != &priv->ds) { + reason = "Redirect to non-local port"; goto fallback; } - redir_act = act->id; - - switch (act->id) { - case FLOW_ACTION_ACCEPT: - action[2] |= YT921X_ACL_ACTc_FWD_EN | - YT921X_ACL_ACTc_FWD_FWD; - break; - case FLOW_ACTION_DROP: - action[2] |= YT921X_ACL_ACTc_FWD_EN | - YT921X_ACL_ACTc_FWD_REDIR; - break; - case FLOW_ACTION_REDIRECT: { - struct dsa_port *to_dp; - to_dp = dsa_port_from_netdev(act->dev); - if (IS_ERR(to_dp) || to_dp->ds != &priv->ds) { - reason = "Redirect to non-local port"; - goto fallback; - } - - action[2] |= YT921X_ACL_ACTc_FWD_EN | - YT921X_ACL_ACTc_FWD_REDIR | - YT921X_ACL_ACTc_FWD_REDIR_DPORTn(to_dp->index); - break; - } - default: - break; - } + action[2] |= YT921X_ACL_ACTc_FWD_EN | + YT921X_ACL_ACTc_FWD_REDIR | + YT921X_ACL_ACTc_FWD_REDIR_DPORTn(to_dp->index); + redir = true; break; + } case FLOW_ACTION_PRIORITY: if (seen_priority) { action[0] &= ~YT921X_ACL_ACTa_PRIO_EN; @@ -1122,6 +1121,7 @@ yt921x_acl_rule_ext_parse_flow_action(struct yt921x_acl_rule_ext *ruleext, break; } default: + reason = "Unsupported by HW"; fallback: if (cls->common.skip_sw) { NL_SET_ERR_MSG_FMT_MOD(extack, @@ -1131,15 +1131,18 @@ fallback: } fallthrough; case FLOW_ACTION_TRAP: - redir_act = FLOW_ACTION_TRAP; - action[2] &= ~YT921X_ACL_ACTc_FWD_REDIR_DPORTS_M & ~YT921X_ACL_ACTc_FWD_M; action[2] |= YT921X_ACL_ACTc_FWD_EN | YT921X_ACL_ACTc_FWD_TRAP; + terminal = true; break; } + if (terminal) + break; + } + ruleext->r.sw_assisted = !cls->common.skip_sw; return 0; } @@ -1223,7 +1226,7 @@ static u16 yt921x_acl_activated_ports(const struct yt921x_priv *priv) static unsigned int yt921x_acl_find(const struct yt921x_priv *priv, enum tc_setup_type type, - unsigned long tag) + unsigned long tag, u16 ports_mask) { for (unsigned int blkid = 0; blkid < YT921X_ACL_BLK_NUM; blkid++) { const struct yt921x_acl_blk *aclblk = priv->acl_blks[blkid]; @@ -1233,7 +1236,10 @@ yt921x_acl_find(const struct yt921x_priv *priv, enum tc_setup_type type, for (unsigned int i = 0; i < YT921X_ACL_ENT_PER_BLK; i++) if (aclblk->rules[i] && aclblk->rules[i]->tag == tag && - aclblk->rules[i]->type == type) + aclblk->rules[i]->type == type && + FIELD_GET(YT921X_ACL_KEYb_SPORTS_M, + aclblk->rules[i]->entries[0].key[1]) == + ports_mask) return YT921X_ACL_ENT_PER_BLK * blkid + i; } @@ -1361,7 +1367,7 @@ yt921x_acl_commit(struct yt921x_priv *priv, unsigned int entid, u8 entsmask) static int yt921x_acl_del(struct yt921x_priv *priv, enum tc_setup_type type, - unsigned long tag) + unsigned long tag, u16 ports_mask) { struct yt921x_acl_rule *aclrule; struct yt921x_acl_blk *aclblk; @@ -1375,7 +1381,7 @@ yt921x_acl_del(struct yt921x_priv *priv, enum tc_setup_type type, int res; int ret; - entid = yt921x_acl_find(priv, type, tag); + entid = yt921x_acl_find(priv, type, tag, ports_mask); if (entid == UINT_MAX) return -ENOENT; @@ -1550,7 +1556,7 @@ yt921x_dsa_cls_flower_del(struct dsa_switch *ds, int port, int res; mutex_lock(&priv->reg_lock); - res = yt921x_acl_del(priv, TC_SETUP_CLSFLOWER, cls->cookie); + res = yt921x_acl_del(priv, TC_SETUP_CLSFLOWER, cls->cookie, BIT(port)); mutex_unlock(&priv->reg_lock); return res; diff --git a/drivers/net/ethernet/amazon/ena/ena_netdev.c b/drivers/net/ethernet/amazon/ena/ena_netdev.c index 7eb6456ed0d5..ecc6f1d827f9 100644 --- a/drivers/net/ethernet/amazon/ena/ena_netdev.c +++ b/drivers/net/ethernet/amazon/ena/ena_netdev.c @@ -986,7 +986,7 @@ static struct sk_buff *ena_rx_skb(struct ena_ring *rx_ring, page_offset = rx_info->page_offset; buf_addr = page_address(rx_info->page) + page_offset; - if (len <= rx_ring->rx_copybreak) { + if (len <= rx_ring->rx_copybreak && likely(descs == 1)) { skb = ena_alloc_skb(rx_ring, NULL, len); if (unlikely(!skb)) return NULL; @@ -1009,6 +1009,10 @@ static struct sk_buff *ena_rx_skb(struct ena_ring *rx_ring, buf_len = SKB_DATA_ALIGN(len + buf_offset + tailroom); + skb = ena_alloc_skb(rx_ring, buf_addr, buf_len); + if (unlikely(!skb)) + return NULL; + /* If XDP isn't loaded try to reuse part of the RX buffer */ reuse_rx_buf_page = !is_xdp_loaded && ena_try_rx_buf_page_reuse(rx_info, buf_len, len, pkt_offset); @@ -1016,10 +1020,6 @@ static struct sk_buff *ena_rx_skb(struct ena_ring *rx_ring, if (!reuse_rx_buf_page) ena_unmap_rx_buff_attrs(rx_ring, rx_info, DMA_ATTR_SKIP_CPU_SYNC); - skb = ena_alloc_skb(rx_ring, buf_addr, buf_len); - if (unlikely(!skb)) - return NULL; - /* Populate skb's linear part */ skb_reserve(skb, buf_offset); skb_put(skb, len); @@ -1293,7 +1293,8 @@ static int ena_clean_rx_irq(struct ena_ring *rx_ring, struct napi_struct *napi, skb_record_rx_queue(skb, rx_ring->qid); - if (rx_ring->ena_bufs[0].len <= rx_ring->rx_copybreak) + if (rx_ring->ena_bufs[0].len <= rx_ring->rx_copybreak && + ena_rx_ctx.descs == 1) rx_copybreak_pkt++; total_len += skb->len; diff --git a/drivers/net/ethernet/broadcom/bnxt/bnxt.c b/drivers/net/ethernet/broadcom/bnxt/bnxt.c index 5a081bbbfe2d..6846a27bfef4 100644 --- a/drivers/net/ethernet/broadcom/bnxt/bnxt.c +++ b/drivers/net/ethernet/broadcom/bnxt/bnxt.c @@ -14837,7 +14837,10 @@ static int bnxt_get_registered_vfs(struct bnxt *bp) void bnxt_fw_reset(struct bnxt *bp) { bnxt_ulp_stop(bp); - bnxt_lock_sp(bp); + if (BNXT_PF(bp)) + bnxt_rtnl_lock_sp(bp); + else + bnxt_lock_sp(bp); if (test_bit(BNXT_STATE_OPEN, &bp->state) && !test_bit(BNXT_STATE_IN_FW_RESET, &bp->state)) { struct bnxt_ptp_cfg *ptp = bp->ptp_cfg; @@ -14883,7 +14886,10 @@ void bnxt_fw_reset(struct bnxt *bp) bnxt_queue_fw_reset_work(bp, tmo); } fw_reset_exit: - bnxt_unlock_sp(bp); + if (BNXT_PF(bp)) + bnxt_rtnl_unlock_sp(bp); + else + bnxt_unlock_sp(bp); } static void bnxt_chk_missed_irq(struct bnxt *bp) @@ -15546,9 +15552,8 @@ static void bnxt_fw_reset_task(struct work_struct *work) bp->fw_reset_timestamp = jiffies; netdev_lock(bp->dev); if (test_bit(BNXT_STATE_ABORT_ERR, &bp->state)) { - bnxt_fw_reset_abort(bp, rc); netdev_unlock(bp->dev); - goto ulp_start; + goto fw_reset_abort; } bnxt_fw_reset_close(bp); if (bp->fw_cap & BNXT_FW_CAP_ERR_RECOVER_RELOAD) { @@ -15681,9 +15686,11 @@ fw_reset_abort_status: netdev_err(bp->dev, "fw_health_status 0x%x\n", sts); } fw_reset_abort: + rtnl_lock(); netdev_lock(bp->dev); bnxt_fw_reset_abort(bp, rc); netdev_unlock(bp->dev); + rtnl_unlock(); ulp_start: if (!rc) bnxt_ulp_start(bp); diff --git a/drivers/net/ethernet/google/gve/gve.h b/drivers/net/ethernet/google/gve/gve.h index b7ce6e8632db..e509488a3d3e 100644 --- a/drivers/net/ethernet/google/gve/gve.h +++ b/drivers/net/ethernet/google/gve/gve.h @@ -871,6 +871,10 @@ struct gve_ctrl_ops { int (*report_link_speed)(struct gve_priv *priv); }; +struct gve_ring_err_stats { + u64 rx_alloc_fails; +}; + struct gve_priv { struct net_device *dev; struct gve_tx_ring *tx; /* array of tx_cfg.num_queues */ @@ -957,9 +961,17 @@ struct gve_priv { struct workqueue_struct *gve_wq; struct work_struct service_task; struct work_struct stats_report_task; + /* Protects the priv->tx/priv->rx arrays, the in-place rewrite of + * priv->rx[idx] and the queue counts against stats readers that do + * not hold the netdev instance lock. + * Also protects base_net_stats and base_ring_err_stats. + */ + spinlock_t stats_lock; unsigned long service_task_flags; unsigned long state_flags; + struct gve_ring_err_stats base_ring_err_stats; + struct rtnl_link_stats64 base_net_stats; struct gve_stats_report *stats_report; u64 stats_report_len; dma_addr_t stats_report_bus; /* dma address for the stats report */ diff --git a/drivers/net/ethernet/google/gve/gve_adminq.c b/drivers/net/ethernet/google/gve/gve_adminq.c index 8b215fca9c1b..2c848f0c23dc 100644 --- a/drivers/net/ethernet/google/gve/gve_adminq.c +++ b/drivers/net/ethernet/google/gve/gve_adminq.c @@ -191,7 +191,9 @@ void gve_parse_device_option(struct gve_priv *priv, *dev_op_modify_ring = (void *)(option + 1); /* device has not provided min ring size */ - if (option_length == GVE_DEVICE_OPTION_NO_MIN_RING_SIZE) + if (option_length == GVE_DEVICE_OPTION_NO_MIN_RING_SIZE || + be16_to_cpu((*dev_op_modify_ring)->min_rx_ring_size) == 0 || + be16_to_cpu((*dev_op_modify_ring)->min_tx_ring_size) == 0) priv->device_info.default_min_ring_size = true; break; case GVE_DEV_OPT_ID_FLOW_STEERING: diff --git a/drivers/net/ethernet/google/gve/gve_main.c b/drivers/net/ethernet/google/gve/gve_main.c index a943c042893b..0ee69bc11d83 100644 --- a/drivers/net/ethernet/google/gve/gve_main.c +++ b/drivers/net/ethernet/google/gve/gve_main.c @@ -17,6 +17,7 @@ #include <linux/sched.h> #include <linux/timer.h> #include <linux/workqueue.h> +#include <net/netdev_lock.h> #include <net/netdev_queues.h> #include <net/sch_generic.h> #include <net/xdp_sock_drv.h> @@ -61,15 +62,44 @@ static netdev_tx_t gve_start_xmit(struct sk_buff *skb, struct net_device *dev) return gve_tx_dqo(skb, dev); } -static void gve_get_stats(struct net_device *dev, struct rtnl_link_stats64 *s) +static void gve_add_base_stats(struct gve_priv *priv, + struct rtnl_link_stats64 *s) +{ + struct rtnl_link_stats64 *base_stats = &priv->base_net_stats; + + s->rx_packets += base_stats->rx_packets; + s->rx_bytes += base_stats->rx_bytes; + s->tx_packets += base_stats->tx_packets; + s->tx_bytes += base_stats->tx_bytes; +} + +static void gve_add_tx_ring_range_stats(struct gve_priv *priv, int start_ring, + int end_ring, u64 *packets, u64 *bytes) +{ + int ring; + + for (ring = start_ring; ring < end_ring; ring++) { + struct gve_tx_ring *tx = &priv->tx[ring]; + unsigned int start; + u64 pkts, byts; + + do { + start = u64_stats_fetch_begin(&tx->statss); + pkts = tx->pkt_done; + byts = tx->bytes_done; + } while (u64_stats_fetch_retry(&tx->statss, start)); + *packets += pkts; + *bytes += byts; + } +} + +static void gve_get_ring_stats(struct gve_priv *priv, + struct rtnl_link_stats64 *s) { - struct gve_priv *priv = netdev_priv(dev); unsigned int start; u64 packets, bytes; - int num_tx_queues; int ring; - num_tx_queues = gve_num_tx_queues(priv); if (priv->rx) { for (ring = 0; ring < priv->rx_cfg.num_queues; ring++) { do { @@ -83,21 +113,44 @@ static void gve_get_stats(struct net_device *dev, struct rtnl_link_stats64 *s) s->rx_bytes += bytes; } } - if (priv->tx) { - for (ring = 0; ring < num_tx_queues; ring++) { - do { - start = - u64_stats_fetch_begin(&priv->tx[ring].statss); - packets = priv->tx[ring].pkt_done; - bytes = priv->tx[ring].bytes_done; - } while (u64_stats_fetch_retry(&priv->tx[ring].statss, - start)); - s->tx_packets += packets; - s->tx_bytes += bytes; - } + if (priv->tx) + gve_add_tx_ring_range_stats(priv, 0, gve_num_tx_queues(priv), + &s->tx_packets, &s->tx_bytes); +} + +static void gve_get_ring_err_stats(struct gve_priv *priv, + struct gve_ring_err_stats *err_stats) +{ + int ring; + + if (!priv->rx) + return; + + for (ring = 0; ring < priv->rx_cfg.num_queues; ring++) { + struct gve_rx_ring *rx = &priv->rx[ring]; + unsigned int start; + u64 rx_alloc_fails; + + do { + start = u64_stats_fetch_begin(&rx->statss); + rx_alloc_fails = rx->rx_skb_alloc_fail + + rx->rx_buf_alloc_fail; + } while (u64_stats_fetch_retry(&rx->statss, start)); + + err_stats->rx_alloc_fails += rx_alloc_fails; } } +static void gve_get_stats(struct net_device *dev, struct rtnl_link_stats64 *s) +{ + struct gve_priv *priv = netdev_priv(dev); + + spin_lock_bh(&priv->stats_lock); + gve_get_ring_stats(priv, s); + gve_add_base_stats(priv, s); + spin_unlock_bh(&priv->stats_lock); +} + static int gve_alloc_flow_rule_caches(struct gve_priv *priv) { struct gve_flow_rules_cache *flow_rules_cache = &priv->flow_rules_cache; @@ -641,9 +694,16 @@ static void gve_queues_mem_remove(struct gve_priv *priv) struct gve_rx_alloc_rings_cfg rx_alloc_cfg = {0}; gve_get_curr_alloc_cfgs(priv, &tx_alloc_cfg, &rx_alloc_cfg); - gve_queues_mem_free(priv, &tx_alloc_cfg, &rx_alloc_cfg); + + spin_lock_bh(&priv->stats_lock); + gve_get_ring_stats(priv, &priv->base_net_stats); + gve_get_ring_err_stats(priv, &priv->base_ring_err_stats); + priv->tx = NULL; priv->rx = NULL; + spin_unlock_bh(&priv->stats_lock); + + gve_queues_mem_free(priv, &tx_alloc_cfg, &rx_alloc_cfg); } static void gve_free_control_plane_resources(struct gve_priv *priv) @@ -1370,6 +1430,37 @@ static void gve_queues_stop(struct gve_priv *priv) gve_rx_stop_rings(priv, priv->rx_cfg.num_queues); } +static void gve_handle_link_status(struct gve_priv *priv) +{ + bool link_up; + + netdev_assert_locked(priv->dev); + + if (!gve_get_napi_enabled(priv)) + return; + + link_up = READ_ONCE(priv->link_up); + if (link_up == netif_carrier_ok(priv->dev)) + return; + + if (link_up) { + netdev_info(priv->dev, "Device link is up.\n"); + netif_carrier_on(priv->dev); + } else { + netdev_info(priv->dev, "Device link is down.\n"); + netif_carrier_off(priv->dev); + } +} + +static void gve_turnup_and_check_status(struct gve_priv *priv) +{ + const struct gve_ctrl_ops *ops = priv->ctrl_ops; + + gve_turnup(priv); + ops->report_link_status(priv); + gve_handle_link_status(priv); +} + /* The passed-in queue memory is stored into priv and the queues are made live. * No memory is allocated. Passed-in memory is freed on errors. */ @@ -1381,6 +1472,7 @@ static int gve_queues_start(struct gve_priv *priv, int err; /* Record new resources into priv */ + spin_lock_bh(&priv->stats_lock); priv->tx = tx_alloc_cfg->tx; priv->rx = rx_alloc_cfg->rx; @@ -1394,10 +1486,11 @@ static int gve_queues_start(struct gve_priv *priv, priv->rx_pages_per_qpl = rx_alloc_cfg->pages_per_qpl; priv->header_split_enabled = rx_alloc_cfg->enable_header_split; priv->rx_cfg.packet_buffer_size = rx_alloc_cfg->packet_buffer_size; + gve_init_sync_stats(priv); + spin_unlock_bh(&priv->stats_lock); gve_tx_start_rings(priv, gve_num_tx_queues(priv)); gve_rx_start_rings(priv, rx_alloc_cfg->qcfg_rx->num_queues); - gve_init_sync_stats(priv); err = netif_set_real_num_tx_queues(dev, priv->tx_cfg.num_queues); if (err) @@ -1431,7 +1524,11 @@ static int gve_queues_start(struct gve_priv *priv, round_jiffies(jiffies + msecs_to_jiffies(priv->stats_report_timer_period))); - gve_turnup(priv); + gve_turnup_and_check_status(priv); + /* Also kick the service task. When the queues come back up after + * gve_reset() or resume, this handles a reset requested while the + * service task was disabled. + */ queue_work(priv->gve_wq, &priv->service_task); priv->interface_up_cnt++; return 0; @@ -1507,26 +1604,6 @@ reset: return err; } -static void gve_handle_link_status(struct gve_priv *priv) -{ - bool link_up; - - if (!gve_get_napi_enabled(priv)) - return; - - link_up = READ_ONCE(priv->link_up); - if (link_up == netif_carrier_ok(priv->dev)) - return; - - if (link_up) { - netdev_info(priv->dev, "Device link is up.\n"); - netif_carrier_on(priv->dev); - } else { - netdev_info(priv->dev, "Device link is down.\n"); - netif_carrier_off(priv->dev); - } -} - static int gve_configure_rings_xdp(struct gve_priv *priv, u16 num_xdp_rings) { @@ -2001,15 +2078,6 @@ static void gve_turnup(struct gve_priv *priv) gve_set_napi_enabled(priv); } -static void gve_turnup_and_check_status(struct gve_priv *priv) -{ - const struct gve_ctrl_ops *ops = priv->ctrl_ops; - - gve_turnup(priv); - ops->report_link_status(priv); - gve_handle_link_status(priv); -} - static struct gve_notify_block *gve_get_tx_notify_block(struct gve_priv *priv, unsigned int txqueue) { @@ -2264,6 +2332,7 @@ void gve_handle_report_stats(struct gve_priv *priv) if (!gve_get_report_stats(priv)) return; + spin_lock_bh(&priv->stats_lock); be64_add_cpu(&priv->stats_report->written_count, 1); /* tx stats */ if (priv->tx) { @@ -2328,6 +2397,7 @@ void gve_handle_report_stats(struct gve_priv *priv) }; } } + spin_unlock_bh(&priv->stats_lock); } /* Handle NIC status register changes, reset requests and report stats */ @@ -2341,8 +2411,14 @@ static void gve_service_task(struct work_struct *work) gve_handle_status(priv, status); gve_handle_reset(priv); + + /* Serialize with the synchronous link status updates, which all run + * under the netdev instance lock. + */ + netdev_lock(priv->dev); ops->report_link_status(priv); gve_handle_link_status(priv); + netdev_unlock(priv->dev); } static void gve_set_netdev_xdp_features(struct gve_priv *priv) @@ -2677,8 +2753,20 @@ static int gve_rx_queue_stop(struct net_device *dev, void *per_q_mem, int idx) gve_turnup_and_check_status(priv); gve_per_q_mem = (struct gve_rx_ring *)per_q_mem; + spin_lock_bh(&priv->stats_lock); + priv->base_net_stats.rx_packets += priv->rx[idx].rpackets; + priv->base_net_stats.rx_bytes += priv->rx[idx].rbytes; + priv->base_ring_err_stats.rx_alloc_fails += + priv->rx[idx].rx_skb_alloc_fail + + priv->rx[idx].rx_buf_alloc_fail; *gve_per_q_mem = priv->rx[idx]; memset(&priv->rx[idx], 0, sizeof(priv->rx[idx])); + spin_unlock_bh(&priv->stats_lock); + + gve_per_q_mem->rpackets = 0; + gve_per_q_mem->rbytes = 0; + gve_per_q_mem->rx_skb_alloc_fail = 0; + gve_per_q_mem->rx_buf_alloc_fail = 0; return 0; } @@ -2732,7 +2820,9 @@ static int gve_rx_queue_start(struct net_device *dev, return -EAGAIN; gve_per_q_mem = (struct gve_rx_ring *)per_q_mem; + spin_lock_bh(&priv->stats_lock); priv->rx[idx] = *gve_per_q_mem; + spin_unlock_bh(&priv->stats_lock); /* Single-queue creation requires quiescence on all queues */ gve_turndown(priv); @@ -2768,7 +2858,9 @@ abort: * which needs the rtnl lock, will not run till this func returns and * its caller gives up the lock. */ + spin_lock_bh(&priv->stats_lock); memset(&priv->rx[idx], 0, sizeof(priv->rx[idx])); + spin_unlock_bh(&priv->stats_lock); return err; } @@ -2784,9 +2876,15 @@ static void gve_get_rx_queue_stats(struct net_device *dev, int idx, struct netdev_queue_stats_rx *rx_stats) { struct gve_priv *priv = netdev_priv(dev); - struct gve_rx_ring *rx = &priv->rx[idx]; + struct gve_rx_ring *rx; unsigned int start; + spin_lock_bh(&priv->stats_lock); + if (!priv->rx) + goto unlock; + + rx = &priv->rx[idx]; + do { start = u64_stats_fetch_begin(&rx->statss); rx_stats->packets = rx->rpackets; @@ -2794,32 +2892,62 @@ static void gve_get_rx_queue_stats(struct net_device *dev, int idx, rx_stats->alloc_fail = rx->rx_skb_alloc_fail + rx->rx_buf_alloc_fail; } while (u64_stats_fetch_retry(&rx->statss, start)); + +unlock: + spin_unlock_bh(&priv->stats_lock); } static void gve_get_tx_queue_stats(struct net_device *dev, int idx, struct netdev_queue_stats_tx *tx_stats) { struct gve_priv *priv = netdev_priv(dev); - struct gve_tx_ring *tx = &priv->tx[idx]; + struct gve_tx_ring *tx; unsigned int start; + spin_lock_bh(&priv->stats_lock); + if (!priv->tx) + goto unlock; + + tx = &priv->tx[idx]; + do { start = u64_stats_fetch_begin(&tx->statss); tx_stats->packets = tx->pkt_done; tx_stats->bytes = tx->bytes_done; } while (u64_stats_fetch_retry(&tx->statss, start)); + +unlock: + spin_unlock_bh(&priv->stats_lock); } static void gve_get_base_stats(struct net_device *dev, struct netdev_queue_stats_rx *rx, struct netdev_queue_stats_tx *tx) { - rx->packets = 0; - rx->bytes = 0; - rx->alloc_fail = 0; + const struct gve_ring_err_stats *base_err_stats; + const struct rtnl_link_stats64 *base_stats; + struct gve_priv *priv; - tx->packets = 0; - tx->bytes = 0; + priv = netdev_priv(dev); + base_stats = &priv->base_net_stats; + base_err_stats = &priv->base_ring_err_stats; + + spin_lock_bh(&priv->stats_lock); + rx->packets = base_stats->rx_packets; + rx->bytes = base_stats->rx_bytes; + rx->alloc_fail = base_err_stats->rx_alloc_fails; + + tx->packets = base_stats->tx_packets; + tx->bytes = base_stats->tx_bytes; + /* XDP TX rings are not exposed as netdev queues, so report their live + * counters here to keep the device totals consistent with + * ndo_get_stats64. + */ + if (priv->tx) + gve_add_tx_ring_range_stats(priv, priv->tx_cfg.num_queues, + gve_num_tx_queues(priv), + &tx->packets, &tx->bytes); + spin_unlock_bh(&priv->stats_lock); } static const struct netdev_stat_ops gve_stat_ops = { @@ -2933,6 +3061,7 @@ static int gve_probe(struct pci_dev *pdev, const struct pci_device_id *ent) } INIT_WORK(&priv->service_task, gve_service_task); INIT_WORK(&priv->stats_report_task, gve_stats_report_task); + spin_lock_init(&priv->stats_lock); priv->tx_cfg.max_queues = max_tx_queues; priv->rx_cfg.max_queues = max_rx_queues; diff --git a/drivers/net/ethernet/intel/i40e/i40e_xsk.c b/drivers/net/ethernet/intel/i40e/i40e_xsk.c index 51a05ce4c7ce..5f5f33b2a097 100644 --- a/drivers/net/ethernet/intel/i40e/i40e_xsk.c +++ b/drivers/net/ethernet/intel/i40e/i40e_xsk.c @@ -320,22 +320,19 @@ static struct sk_buff *i40e_construct_skb_zc(struct i40e_ring *rx_ring, goto out; for (int i = 0; i < nr_frags; i++) { - struct skb_shared_info *skinfo = skb_shinfo(skb); skb_frag_t *frag = &sinfo->frags[i]; + unsigned int frag_size = skb_frag_size(frag); struct page *page; - void *addr; page = dev_alloc_page(); if (!page) { dev_kfree_skb(skb); - return NULL; + skb = NULL; + goto out; } - addr = page_to_virt(page); - memcpy(addr, skb_frag_page(frag), skb_frag_size(frag)); - - __skb_fill_page_desc_noacc(skinfo, skinfo->nr_frags++, - addr, 0, skb_frag_size(frag)); + memcpy(page_to_virt(page), skb_frag_address(frag), frag_size); + skb_add_rx_frag(skb, i, page, 0, frag_size, PAGE_SIZE); } out: @@ -354,7 +351,6 @@ static void i40e_handle_xdp_result_zc(struct i40e_ring *rx_ring, struct sk_buff *skb; *rx_packets = 1; - *rx_bytes = xdp_get_buff_len(xdp_buff); if (likely(xdp_res == I40E_XDP_REDIR) || xdp_res == I40E_XDP_TX) return; @@ -469,21 +465,30 @@ int i40e_clean_rx_irq_zc(struct i40e_ring *rx_ring, int budget) xsk_buff_set_size(bi, size); xsk_buff_dma_sync_for_cpu(bi); - if (!first) + if (++next_to_process == count) + next_to_process = 0; + + if (!first) { first = bi; - else if (!xsk_buff_add_frag(first, bi)) { + } else if (!xsk_buff_add_frag(first, bi)) { + /* Drop what has been gathered so far. xp_free() skips + * @bi if it duplicates a buffer that is already on a + * pool list. Remaining buffers of this packet, if any, + * will be processed as a new packet. + */ xsk_buff_free(first); - break; + xsk_buff_free(bi); + next_to_clean = next_to_process; + first = NULL; + continue; } - if (++next_to_process == count) - next_to_process = 0; - if (i40e_is_non_eop(rx_ring, rx_desc)) continue; xsk_buff_to_i40e_ctx(first)->desc = rx_desc; + rx_bytes = xdp_get_buff_len(first); xdp_res = i40e_run_xdp_zc(rx_ring, first, xdp_prog); i40e_handle_xdp_result_zc(rx_ring, first, rx_desc, &rx_packets, &rx_bytes, xdp_res, &failure); diff --git a/drivers/net/ethernet/intel/ice/ice_adapter.c b/drivers/net/ethernet/intel/ice/ice_adapter.c index 536923b6ae97..aa2d8addae5b 100644 --- a/drivers/net/ethernet/intel/ice/ice_adapter.c +++ b/drivers/net/ethernet/intel/ice/ice_adapter.c @@ -72,6 +72,7 @@ static struct ice_adapter *ice_adapter_new(struct pci_dev *pdev) spin_lock_init(&adapter->txq_ctx_lock); for (int i = 0; i < ARRAY_SIZE(adapter->cpi_phy_lock); i++) mutex_init(&adapter->cpi_phy_lock[i]); + mutex_init(&adapter->cgu_synce_lock); refcount_set(&adapter->refcount, 1); spin_lock_init(&adapter->ports.lock); @@ -85,6 +86,7 @@ static void ice_adapter_free(struct ice_adapter *adapter) WARN_ON(!list_empty(&adapter->ports.list)); for (int i = 0; i < ARRAY_SIZE(adapter->cpi_phy_lock); i++) mutex_destroy(&adapter->cpi_phy_lock[i]); + mutex_destroy(&adapter->cgu_synce_lock); cleanup_srcu_struct(&adapter->ports.srcu); diff --git a/drivers/net/ethernet/intel/ice/ice_adapter.h b/drivers/net/ethernet/intel/ice/ice_adapter.h index c61bd645e460..fd5585005d91 100644 --- a/drivers/net/ethernet/intel/ice/ice_adapter.h +++ b/drivers/net/ethernet/intel/ice/ice_adapter.h @@ -41,6 +41,8 @@ struct ice_port_list { * @txq_ctx_lock: Spinlock protecting access to the GLCOMM_QTX_CNTX_CTL register * @cpi_phy_lock: Per-PHY mutex serializing CPI REQ/ACK transactions. * Index 0 = PHY0, index 1 = PHY1. Used on E825C devices. + * @cgu_synce_lock: Mutex serializing changes of the CGU registers R10 and R11, + * which all PFs reach. Used on E825C devices. * @ctrl_pf: Control PF of the adapter * @ports: Ports list * @index: 64-bit index cached for collision detection on 32bit systems @@ -53,6 +55,8 @@ struct ice_adapter { spinlock_t txq_ctx_lock; /* Serialize CPI REQ/ACK transactions per PHY (E825C only) */ struct mutex cpi_phy_lock[ICE_E825_MAX_PHYS]; + /* Serialize changes of the SyncE CGU registers (E825C only) */ + struct mutex cgu_synce_lock; struct ice_pf *ctrl_pf; struct ice_port_list ports; diff --git a/drivers/net/ethernet/intel/ice/ice_dpll.c b/drivers/net/ethernet/intel/ice/ice_dpll.c index ade1fb3dd067..5148e419f49a 100644 --- a/drivers/net/ethernet/intel/ice/ice_dpll.c +++ b/drivers/net/ethernet/intel/ice/ice_dpll.c @@ -2027,7 +2027,7 @@ ice_dpll_phase_offset_get(const struct dpll_pin *pin, void *pin_priv, * * DPLL subsystem callback. Set proper signals to recover clock from port. * - * Context: Called under pf->dplls.lock + * Context: Called under pf->dplls.lock, acquires adapter->cgu_synce_lock * Return: * * 0 - success * * negative - error @@ -2035,14 +2035,15 @@ ice_dpll_phase_offset_get(const struct dpll_pin *pin, void *pin_priv, static int ice_dpll_synce_update_e825c(struct ice_hw *hw, bool ena, u32 port_num, enum ice_synce_clk output) { + struct ice_pf *pf = hw->back; int err; + mutex_lock(&pf->adapter->cgu_synce_lock); /* configure the mux to deliver proper signal to DPLL from the MUX */ err = ice_tspll_cfg_bypass_mux_e825c(hw, ena, port_num, output); - if (err) - return err; - - err = ice_tspll_cfg_synce_ethdiv_e825c(hw, output); + if (!err) + err = ice_tspll_cfg_synce_ethdiv_e825c(hw, output); + mutex_unlock(&pf->adapter->cgu_synce_lock); if (err) return err; diff --git a/drivers/net/ethernet/intel/ice/ice_dpll.h b/drivers/net/ethernet/intel/ice/ice_dpll.h index bce0bea9a664..3f9a993129ac 100644 --- a/drivers/net/ethernet/intel/ice/ice_dpll.h +++ b/drivers/net/ethernet/intel/ice/ice_dpll.h @@ -158,6 +158,7 @@ struct ice_dpll { * txclk_notify_rwsem (read) * -> pf->dplls.lock * -> ctrl_pf->dplls.lock + * -> adapter->cgu_synce_lock * * - @lock serializes all DPLL state mutations on this PF. When the * controlling PF's lock must also be taken (e.g. updating the shared @@ -169,6 +170,9 @@ struct ice_dpll { * dpll_*_change_ntf() calls. ice_dpll_deinit() takes the write side * standalone (not nested under any other lock) to drain in-flight * readers before pins and the TXC DPLL device are freed. + * - adapter->cgu_synce_lock serializes changes of the CGU registers R10 and + * R11. All E825C PFs reach one CGU, so @lock, which is per PF, does not + * cover them. */ struct ice_dplls { struct kthread_worker *kworker; diff --git a/drivers/net/ethernet/intel/ice/ice_ptp.c b/drivers/net/ethernet/intel/ice/ice_ptp.c index 20561ba99e72..8908b4f3db35 100644 --- a/drivers/net/ethernet/intel/ice/ice_ptp.c +++ b/drivers/net/ethernet/intel/ice/ice_ptp.c @@ -1350,6 +1350,7 @@ void ice_ptp_link_change(struct ice_pf *pf, bool linkup) int pin, err; mutex_lock(&pf->dplls.lock); + mutex_lock(&pf->adapter->cgu_synce_lock); for (pin = 0; pin < ICE_SYNCE_CLK_NUM; pin++) { enum ice_synce_clk clk_pin; bool active; @@ -1368,14 +1369,19 @@ void ice_ptp_link_change(struct ice_pf *pf, bool linkup) break; } + /* The divider is shared, set it only for our port */ + if (!active) + continue; + err = ice_tspll_cfg_synce_ethdiv_e825c(hw, clk_pin); - if (active && err) { + if (err) { dev_err_once(ice_pf_to_dev(pf), "Failed to configure SyncE ETH divider for pin %d, err %d\n", pin, err); break; } } + mutex_unlock(&pf->adapter->cgu_synce_lock); mutex_unlock(&pf->dplls.lock); if (linkup) diff --git a/drivers/net/ethernet/intel/ice/ice_tspll.c b/drivers/net/ethernet/intel/ice/ice_tspll.c index 85bacb7c3a79..0bfbea435295 100644 --- a/drivers/net/ethernet/intel/ice/ice_tspll.c +++ b/drivers/net/ethernet/intel/ice/ice_tspll.c @@ -746,6 +746,7 @@ int ice_tspll_init(struct ice_hw *hw) * * Check if given port is selected as recovered clock source for given output. * + * Context: Called under pf->dplls.lock and adapter->cgu_synce_lock * Return: * * 0 - success * * negative - error @@ -774,8 +775,7 @@ int ice_tspll_bypass_mux_active_e825c(struct ice_hw *hw, u8 port, bool *active, return -EINVAL; } - if (active_clk == port % hw->ptp.ports_per_phy + - ICE_CGU_BYPASS_MUX_OFFSET_E825C) + if (active_clk == port + ICE_CGU_BYPASS_MUX_OFFSET_E825C) *active = true; else *active = false; @@ -792,7 +792,7 @@ int ice_tspll_bypass_mux_active_e825c(struct ice_hw *hw, u8 port, bool *active, * * Set reference clock source and output clock selection. * - * Context: Called under pf->dplls.lock + * Context: Called under pf->dplls.lock and adapter->cgu_synce_lock * Return: * * 0 - success * * negative - error @@ -898,7 +898,7 @@ static int ice_tspll_get_div_e825c(u16 link_speed, unsigned int *divider) * * Set the correct CGU divider for RCLKA or RCLKB. * - * Context: Called under pf->dplls.lock + * Context: Called under pf->dplls.lock and adapter->cgu_synce_lock * Return: * * 0 - success * * negative - error diff --git a/drivers/net/ethernet/intel/ice/ice_xsk.c b/drivers/net/ethernet/intel/ice/ice_xsk.c index 0643017541c3..0c1ce3e86a45 100644 --- a/drivers/net/ethernet/intel/ice/ice_xsk.c +++ b/drivers/net/ethernet/intel/ice/ice_xsk.c @@ -493,6 +493,11 @@ static int ice_xmit_xdp_tx_zc(struct xdp_buff *xdp, tx_desc->cmd_type_offset_bsz |= cpu_to_le64(ICE_TX_DESC_CMD_EOP << ICE_TXD_QW1_CMD_S); + /* Each frag is now freed via its own Tx buffer. Completing the head + * must not release what is on the pool's frag list at that time. + */ + xdp_buff_clear_frags_flag(head); + return ICE_XDP_TX; busy: @@ -592,6 +597,7 @@ int ice_clean_rx_irq_zc(struct ice_rx_ring *rx_ring, struct sk_buff *skb; u16 stat_err_bits; u16 vlan_tci; + u32 xdp_len; rx_desc = ICE_RX_DESC(rx_ring, ntc); @@ -618,8 +624,11 @@ int ice_clean_rx_irq_zc(struct ice_rx_ring *rx_ring, if (!first) { first = xdp; - } else if (likely(size) && !xsk_buff_add_frag(first, xdp)) { + } else if (unlikely(!size)) { + xsk_buff_free(xdp); + } else if (!xsk_buff_add_frag(first, xdp)) { xsk_buff_free(first); + xsk_buff_free(xdp); first = NULL; } @@ -631,6 +640,7 @@ int ice_clean_rx_irq_zc(struct ice_rx_ring *rx_ring, ((struct libeth_xdp_buff *)first)->desc = rx_desc; + xdp_len = xdp_get_buff_len(first); xdp_res = ice_run_xdp_zc(rx_ring, first, xdp_prog, xdp_ring, xsk_pool); if (likely(xdp_res & (ICE_XDP_TX | ICE_XDP_REDIR))) { @@ -645,7 +655,7 @@ int ice_clean_rx_irq_zc(struct ice_rx_ring *rx_ring, goto construct_skb; } - total_rx_bytes += xdp_get_buff_len(first); + total_rx_bytes += xdp_len; total_rx_packets++; first = NULL; @@ -902,6 +912,11 @@ void ice_xsk_clean_rx_ring(struct ice_rx_ring *rx_ring) if (xdp_rxq_info_is_reg(&rx_ring->xdp_rxq)) xdp_rxq_info_unreg(&rx_ring->xdp_rxq); + if (rx_ring->xsk) { + xsk_buff_free(&rx_ring->xsk->base); + rx_ring->xsk = NULL; + } + while (ntc != ntu) { struct xdp_buff *xdp = *ice_xdp_buf(rx_ring, ntc); diff --git a/drivers/net/ethernet/intel/idpf/xsk.c b/drivers/net/ethernet/intel/idpf/xsk.c index d95d3efdfd36..5a0a1d8a7a86 100644 --- a/drivers/net/ethernet/intel/idpf/xsk.c +++ b/drivers/net/ethernet/intel/idpf/xsk.c @@ -134,6 +134,11 @@ void idpf_xsk_clear_queue(void *q, enum virtchnl2_queue_type type) if (!idpf_queue_has_clear(XSK, rxq)) return; + if (rxq->xsk) { + libeth_xsk_buff_free_slow(rxq->xsk); + rxq->xsk = NULL; + } + rxq->pool = NULL; break; case VIRTCHNL2_QUEUE_TYPE_RX_BUFFER: diff --git a/drivers/net/ethernet/marvell/octeontx2/af/rvu.h b/drivers/net/ethernet/marvell/octeontx2/af/rvu.h index fb4870cd18e9..a6183674c35f 100644 --- a/drivers/net/ethernet/marvell/octeontx2/af/rvu.h +++ b/drivers/net/ethernet/marvell/octeontx2/af/rvu.h @@ -76,8 +76,6 @@ static inline int rvu_pcifunc_pf_mask(struct pci_dev *pdev) #define RVU_AFPF 25 -#ifdef CONFIG_DEBUG_FS - struct dump_ctx { int lf; int id; @@ -112,7 +110,6 @@ struct rvu_debugfs { int npa_qsize_id; int nix_qsize_id; }; -#endif struct rvu_work { struct work_struct work; @@ -649,9 +646,7 @@ struct rvu { int mcs_blk_cnt; int cpt_pf_num; -#ifdef CONFIG_DEBUG_FS struct rvu_debugfs rvu_dbg; -#endif struct rvu_devlink *rvu_dl; /* RVU switch implementation over NPC with DMAC rules */ diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en/params.c b/drivers/net/ethernet/mellanox/mlx5/core/en/params.c index 5caf7820a136..159f79302a08 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en/params.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en/params.c @@ -911,10 +911,11 @@ static void mlx5e_build_rx_cq_param(struct mlx5_core_dev *mdev, static u8 rq_end_pad_mode(struct mlx5_core_dev *mdev, struct mlx5e_params *params) { - bool lro_en = params->packet_merge.type == MLX5E_PACKET_MERGE_LRO; + bool no_pad = params->packet_merge.type == MLX5E_PACKET_MERGE_LRO || + params->packet_merge.type == MLX5E_PACKET_MERGE_SHAMPO; bool ro = MLX5_CAP_GEN(mdev, relaxed_ordering_write); - return ro && lro_en ? + return ro && no_pad ? MLX5_WQ_END_PAD_MODE_NONE : MLX5_WQ_END_PAD_MODE_ALIGN; } diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ipsec.c b/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ipsec.c index 7e991a09b3ff..fa6cb51fdb93 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ipsec.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ipsec.c @@ -771,53 +771,72 @@ static int mlx5e_xfrm_add_state(struct net_device *dev, struct xfrm_state *x, struct netlink_ext_ack *extack) { + bool is_acq = x->xso.flags & XFRM_DEV_OFFLOAD_FLAG_ACQ; struct mlx5e_ipsec_sa_entry *sa_entry = NULL; bool allow_tunnel_mode = false; + struct mlx5_core_dev *mdev; struct mlx5e_ipsec *ipsec; struct mlx5e_priv *priv; gfp_t gfp; int err; priv = netdev_priv(dev); - if (!priv->ipsec) - return -EOPNOTSUPP; + /* Profile cleanup can memset an already NULL mdev. */ + mdev = data_race(READ_ONCE(priv->mdev)); + /* NULL only during a profile change, which is an eswitch operation. */ + if (!mdev) { + NL_SET_ERR_MSG_MOD(extack, "Eswitch busy, can't add state"); + return -EBUSY; + } + + if (!is_acq) { + err = mlx5_eswitch_block_mode(mdev, false); + if (err) + return err; + } ipsec = priv->ipsec; - gfp = (x->xso.flags & XFRM_DEV_OFFLOAD_FLAG_ACQ) ? GFP_ATOMIC : GFP_KERNEL; + if (!ipsec) { + err = -EOPNOTSUPP; + goto unblock_mode; + } + + gfp = is_acq ? GFP_ATOMIC : GFP_KERNEL; sa_entry = kzalloc_obj(*sa_entry, gfp); - if (!sa_entry) - return -ENOMEM; + if (!sa_entry) { + err = -ENOMEM; + goto unblock_mode; + } sa_entry->x = x; sa_entry->dev = dev; sa_entry->ipsec = ipsec; /* Check if this SA is originated from acquire flow temporary SA */ - if (x->xso.flags & XFRM_DEV_OFFLOAD_FLAG_ACQ) { + if (is_acq) { x->xso.offload_handle = (unsigned long)sa_entry; return 0; } - err = mlx5e_xfrm_validate_state(priv->mdev, x, extack); + err = mlx5e_xfrm_validate_state(mdev, x, extack); if (err) goto err_xfrm; - if (!mlx5_eswitch_block_ipsec(priv->mdev)) { + if (!mlx5_eswitch_block_ipsec(mdev)) { err = -EBUSY; goto err_xfrm; } - err = mlx5_eswitch_block_mode(priv->mdev); - if (err) - goto unblock_ipsec; - if (x->props.mode == XFRM_MODE_TUNNEL && x->xso.type == XFRM_DEV_OFFLOAD_PACKET) { - allow_tunnel_mode = mlx5e_ipsec_fs_tunnel_allowed(sa_entry); + err = mlx5e_ipsec_fs_tunnel_allowed(sa_entry); + if (err < 0) + goto unblock_ipsec; + allow_tunnel_mode = err; if (!allow_tunnel_mode) { NL_SET_ERR_MSG_MOD(extack, "Packet offload tunnel mode is disabled due to encap settings"); err = -EINVAL; - goto unblock_mode; + goto unblock_ipsec; } } @@ -874,9 +893,9 @@ static int mlx5e_xfrm_add_state(struct net_device *dev, x->xso.offload_handle = (unsigned long)sa_entry; if (allow_tunnel_mode) - mlx5_eswitch_unblock_encap(priv->mdev); + mlx5_eswitch_unblock_encap(mdev); - mlx5_eswitch_unblock_mode(priv->mdev); + mlx5_eswitch_unblock_mode(mdev); return 0; @@ -892,14 +911,15 @@ release_work: kfree(sa_entry->work); unblock_encap: if (allow_tunnel_mode) - mlx5_eswitch_unblock_encap(priv->mdev); -unblock_mode: - mlx5_eswitch_unblock_mode(priv->mdev); + mlx5_eswitch_unblock_encap(mdev); unblock_ipsec: - mlx5_eswitch_unblock_ipsec(priv->mdev); + mlx5_eswitch_unblock_ipsec(mdev); err_xfrm: kfree(sa_entry); NL_SET_ERR_MSG_WEAK_MOD(extack, "Device failed to offload this state"); +unblock_mode: + if (!is_acq) + mlx5_eswitch_unblock_mode(mdev); return err; } @@ -1265,27 +1285,45 @@ static int mlx5e_xfrm_add_policy(struct xfrm_policy *x, { struct net_device *netdev = x->xdo.dev; struct mlx5e_ipsec_pol_entry *pol_entry; + struct mlx5_core_dev *mdev; struct mlx5e_priv *priv; int err; priv = netdev_priv(netdev); + /* Profile cleanup can memset an already NULL mdev. */ + mdev = data_race(READ_ONCE(priv->mdev)); + if (!mdev) { + NL_SET_ERR_MSG_MOD(extack, "Eswitch busy, can't add policy"); + return -EBUSY; + } + + /* Block esw mode changes until the policy holds its own block. */ + err = mlx5_eswitch_block_mode(mdev, false); + if (err) { + NL_SET_ERR_MSG_MOD(extack, "Eswitch busy, can't add policy"); + return err; + } + if (!priv->ipsec) { NL_SET_ERR_MSG_MOD(extack, "Device doesn't support IPsec packet offload"); - return -EOPNOTSUPP; + err = -EOPNOTSUPP; + goto unblock_mode; } - err = mlx5e_xfrm_validate_policy(priv->mdev, x, extack); + err = mlx5e_xfrm_validate_policy(mdev, x, extack); if (err) - return err; + goto unblock_mode; pol_entry = kzalloc_obj(*pol_entry); - if (!pol_entry) - return -ENOMEM; + if (!pol_entry) { + err = -ENOMEM; + goto unblock_mode; + } pol_entry->x = x; pol_entry->ipsec = priv->ipsec; - if (!mlx5_eswitch_block_ipsec(priv->mdev)) { + if (!mlx5_eswitch_block_ipsec(mdev)) { err = -EBUSY; goto ipsec_busy; } @@ -1296,13 +1334,16 @@ static int mlx5e_xfrm_add_policy(struct xfrm_policy *x, goto err_fs; x->xdo.offload_handle = (unsigned long)pol_entry; + mlx5_eswitch_unblock_mode(mdev); return 0; err_fs: - mlx5_eswitch_unblock_ipsec(priv->mdev); + mlx5_eswitch_unblock_ipsec(mdev); ipsec_busy: kfree(pol_entry); NL_SET_ERR_MSG_MOD(extack, "Device failed to offload this policy"); +unblock_mode: + mlx5_eswitch_unblock_mode(mdev); return err; } diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ipsec.h b/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ipsec.h index abcbd38db9db..f4b2d7b950c0 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ipsec.h +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ipsec.h @@ -320,7 +320,7 @@ void mlx5e_accel_ipsec_fs_del_rule(struct mlx5e_ipsec_sa_entry *sa_entry); int mlx5e_accel_ipsec_fs_add_pol(struct mlx5e_ipsec_pol_entry *pol_entry); void mlx5e_accel_ipsec_fs_del_pol(struct mlx5e_ipsec_pol_entry *pol_entry); void mlx5e_accel_ipsec_fs_modify(struct mlx5e_ipsec_sa_entry *sa_entry); -bool mlx5e_ipsec_fs_tunnel_allowed(struct mlx5e_ipsec_sa_entry *sa_entry); +int mlx5e_ipsec_fs_tunnel_allowed(struct mlx5e_ipsec_sa_entry *sa_entry); int mlx5_ipsec_create_sa_ctx(struct mlx5e_ipsec_sa_entry *sa_entry); void mlx5_ipsec_free_sa_ctx(struct mlx5e_ipsec_sa_entry *sa_entry); diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ipsec_fs.c b/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ipsec_fs.c index 8ffa8068e90a..5c69e89b13a7 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ipsec_fs.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ipsec_fs.c @@ -720,6 +720,16 @@ static void ipsec_rx_sa_selector_destroy(struct mlx5_core_dev *mdev, mlx5_destroy_flow_table(rx->ft.sa_sel); } +static void +ipsec_rx_status_pass_dest_put(struct mlx5e_ipsec *ipsec, + struct mlx5e_ipsec_rx *rx, + u32 family) +{ + mlx5_ipsec_fs_roce_rx_destroy(ipsec->roce, family, ipsec->mdev); + if (rx == ipsec->rx_esw) + mlx5_esw_ipsec_rx_status_pass_dest_put(ipsec); +} + static void rx_destroy(struct mlx5_core_dev *mdev, struct mlx5e_ipsec *ipsec, struct mlx5e_ipsec_rx *rx, u32 family) { @@ -739,13 +749,7 @@ static void rx_destroy(struct mlx5_core_dev *mdev, struct mlx5e_ipsec *ipsec, ipsec_rx_policy_destroy(rx); - mlx5_ipsec_fs_roce_rx_destroy(ipsec->roce, family, mdev); - -#ifdef CONFIG_MLX5_ESWITCH - if (rx == ipsec->rx_esw) - mlx5_chains_put_table(esw_chains(ipsec->mdev->priv.eswitch), - 0, 1, 0); -#endif + ipsec_rx_status_pass_dest_put(ipsec, rx, family); } static void ipsec_rx_create_attr_set(struct mlx5e_ipsec *ipsec, @@ -1068,9 +1072,12 @@ static int rx_create(struct mlx5_core_dev *mdev, struct mlx5e_ipsec *ipsec, goto err_fs_ft_sa_sel; /* Create FT */ - if (mlx5_ipsec_device_caps(mdev) & MLX5_IPSEC_CAP_TUNNEL) - rx->allow_tunnel_mode = - mlx5_eswitch_block_encap(mdev, rx == ipsec->rx_esw); + if (mlx5_ipsec_device_caps(mdev) & MLX5_IPSEC_CAP_TUNNEL) { + err = mlx5_eswitch_block_encap(mdev, rx == ipsec->rx_esw); + if (err < 0) + goto err_fs_ft; + rx->allow_tunnel_mode = err; + } if (rx->allow_tunnel_mode) flags = MLX5_FLOW_TABLE_TUNNEL_EN_REFORMAT; @@ -1115,7 +1122,7 @@ err_fs_ft: err_fs_ft_sa_sel: mlx5_destroy_flow_table(rx->ft.status); err_fs_ft_status: - mlx5_ipsec_fs_roce_rx_destroy(ipsec->roce, family, mdev); + ipsec_rx_status_pass_dest_put(ipsec, rx, family); return err; } @@ -1127,7 +1134,7 @@ static int rx_get(struct mlx5_core_dev *mdev, struct mlx5e_ipsec *ipsec, if (rx->ft.refcnt) goto skip; - err = mlx5_eswitch_block_mode(mdev); + err = mlx5_eswitch_block_mode(mdev, true); if (err) return err; @@ -1311,9 +1318,12 @@ static int tx_create(struct mlx5e_ipsec *ipsec, struct mlx5e_ipsec_tx *tx, if (err) goto err_status_rule; - if (mlx5_ipsec_device_caps(mdev) & MLX5_IPSEC_CAP_TUNNEL) - tx->allow_tunnel_mode = - mlx5_eswitch_block_encap(mdev, tx == ipsec->tx_esw); + if (mlx5_ipsec_device_caps(mdev) & MLX5_IPSEC_CAP_TUNNEL) { + err = mlx5_eswitch_block_encap(mdev, tx == ipsec->tx_esw); + if (err < 0) + goto err_encap; + tx->allow_tunnel_mode = err; + } if (tx->allow_tunnel_mode) flags = MLX5_FLOW_TABLE_TUNNEL_EN_REFORMAT; @@ -1383,6 +1393,7 @@ err_sa_miss: err_sa_ft: if (tx->allow_tunnel_mode) mlx5_eswitch_unblock_encap(mdev); +err_encap: mlx5_del_flow_rules(tx->status.rule); err_status_rule: mlx5_destroy_flow_table(tx->ft.status); @@ -1416,7 +1427,7 @@ static int tx_get(struct mlx5_core_dev *mdev, struct mlx5e_ipsec *ipsec, if (tx->ft.refcnt) goto skip; - err = mlx5_eswitch_block_mode(mdev); + err = mlx5_eswitch_block_mode(mdev, true); if (err) return err; @@ -2183,7 +2194,6 @@ static int tx_add_rule(struct mlx5e_ipsec_sa_entry *sa_entry) } setup_fte_no_frags(spec); - setup_fte_upper_proto_match(spec, &attrs->upspec); switch (attrs->type) { case XFRM_DEV_OFFLOAD_CRYPTO: @@ -2196,6 +2206,7 @@ static int tx_add_rule(struct mlx5e_ipsec_sa_entry *sa_entry) setup_fte_reg_a(spec); break; case XFRM_DEV_OFFLOAD_PACKET: + setup_fte_upper_proto_match(spec, &attrs->upspec); setup_fte_reg_c4(spec, attrs->reqid); err = setup_pkt_reformat(ipsec, attrs, &flow_act); if (err) @@ -2574,45 +2585,26 @@ void mlx5e_accel_ipsec_fs_read_stats(struct mlx5e_priv *priv, void *ipsec_stats) } } -#ifdef CONFIG_MLX5_ESWITCH static int mlx5e_ipsec_block_tc_offload(struct mlx5_core_dev *mdev) { - struct mlx5_eswitch *esw = mdev->priv.eswitch; - int err = 0; + int ret = 0; - if (esw) { - err = mlx5_esw_lock(esw); - if (err) - return err; - } - - if (mdev->num_block_ipsec) { - err = -EBUSY; - goto unlock; - } - - mdev->num_block_tc++; - -unlock: - if (esw) - mlx5_esw_unlock(esw); - - return err; -} -#else -static int mlx5e_ipsec_block_tc_offload(struct mlx5_core_dev *mdev) -{ - if (mdev->num_block_ipsec) - return -EBUSY; + spin_lock_bh(&mdev->offload_block.lock); + if (mdev->offload_block.num_block_ipsec) + ret = -EBUSY; + else + mdev->offload_block.num_block_tc++; + spin_unlock_bh(&mdev->offload_block.lock); - mdev->num_block_tc++; - return 0; + return ret; } -#endif static void mlx5e_ipsec_unblock_tc_offload(struct mlx5_core_dev *mdev) { - mdev->num_block_tc--; + spin_lock_bh(&mdev->offload_block.lock); + if (!WARN_ON_ONCE(!mdev->offload_block.num_block_tc)) + mdev->offload_block.num_block_tc--; + spin_unlock_bh(&mdev->offload_block.lock); } int mlx5e_accel_ipsec_fs_add_rule(struct mlx5e_ipsec_sa_entry *sa_entry) @@ -2850,7 +2842,7 @@ void mlx5e_accel_ipsec_fs_modify(struct mlx5e_ipsec_sa_entry *sa_entry) memcpy(sa_entry, &sa_entry_shadow, sizeof(*sa_entry)); } -bool mlx5e_ipsec_fs_tunnel_allowed(struct mlx5e_ipsec_sa_entry *sa_entry) +int mlx5e_ipsec_fs_tunnel_allowed(struct mlx5e_ipsec_sa_entry *sa_entry) { struct mlx5e_ipsec *ipsec = sa_entry->ipsec; struct xfrm_state *x = sa_entry->x; diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ktls.c b/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ktls.c index 337201f12895..3cc1213c2f68 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ktls.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ktls.c @@ -139,7 +139,11 @@ int mlx5e_ktls_set_feature_rx(struct net_device *netdev, bool enable) err = mlx5e_accel_fs_tcp_create(priv->fs); if (!err && !priv->ktls_rx_was_enabled) { priv->ktls_rx_was_enabled = true; - mlx5e_safe_reopen_channels(priv); + err = mlx5e_safe_reopen_channels(priv); + if (err) { + priv->ktls_rx_was_enabled = false; + mlx5e_accel_fs_tcp_destroy(priv->fs); + } } } else { mlx5e_accel_fs_tcp_destroy(priv->fs); diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_main.c b/drivers/net/ethernet/mellanox/mlx5/core/en_main.c index c3c2c5720c6f..d8563f863844 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_main.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_main.c @@ -5489,7 +5489,7 @@ static void mlx5e_get_queue_stats_rx(struct net_device *dev, int i, struct mlx5e_rq_stats *xskrq_stats; struct mlx5e_rq_stats *rq_stats; - if (mlx5e_is_uplink_rep(priv) || !mlx5e_stats_nch_read(priv)) + if (mlx5e_is_uplink_rep(priv) || i >= mlx5e_stats_nch_read(priv)) return; channel_stats = priv->channel_stats[i]; @@ -5521,6 +5521,9 @@ static void mlx5e_get_queue_stats_tx(struct net_device *dev, int i, * inactive sqs. */ sq_stats = priv->txq2sq_stats[i]; + if (!sq_stats) + return; + stats->packets = sq_stats->packets; stats->bytes = sq_stats->bytes; @@ -6038,9 +6041,7 @@ static int mlx5e_nic_init(struct mlx5_core_dev *mdev, priv->dfs_root = debugfs_create_dir("nic", mlx5_debugfs_get_dev_root(mdev)); - fs = mlx5e_fs_init(priv->profile, mdev, - !test_bit(MLX5E_STATE_DESTROYING, &priv->state), - priv->dfs_root); + fs = mlx5e_fs_init(priv->profile, mdev, false, priv->dfs_root); if (!fs) { err = -ENOMEM; mlx5_core_err(mdev, "FS initialization failed, %d\n", err); @@ -6382,7 +6383,7 @@ int mlx5e_priv_init(struct mlx5e_priv *priv, node = dev_to_node(mlx5_core_dma_dev(mdev)); /* priv init */ - priv->mdev = mdev; + WRITE_ONCE(priv->mdev, mdev); priv->netdev = netdev; priv->max_nch = nch; priv->max_opened_tc = 1; @@ -6467,6 +6468,8 @@ void mlx5e_priv_cleanup(struct mlx5e_priv *priv) mlx5e_mqprio_rl_free(priv->mqprio_rl); } + /* Clear atomically before memset() for lockless XFRM readers. */ + WRITE_ONCE(priv->mdev, NULL); memset(priv, 0, sizeof(*priv)); if (destroying) /* restore destroying bit, to allow unload */ set_bit(MLX5E_STATE_DESTROYING, &priv->state); @@ -6555,10 +6558,6 @@ int mlx5e_attach_netdev(struct mlx5e_priv *priv) int err; clear_bit(MLX5E_STATE_DESTROYING, &priv->state); - if (priv->fs) - mlx5e_fs_set_rx_mode_active(priv->fs, - !test_bit(MLX5E_STATE_DESTROYING, - &priv->state)); /* Validate the max_wqe_size_sq capability. */ if (WARN_ON_ONCE(mlx5e_get_max_sq_wqebbs(priv->mdev) < MLX5E_MAX_TX_WQEBBS)) { @@ -6619,6 +6618,9 @@ int mlx5e_attach_netdev(struct mlx5e_priv *priv) if (err) goto err_cleanup_tx; + if (priv->fs) + mlx5e_fs_set_rx_mode_active(priv->fs, true); + if (profile->enable) { err = profile->enable(priv); if (err) @@ -6630,6 +6632,10 @@ int mlx5e_attach_netdev(struct mlx5e_priv *priv) return 0; err_cleanup_rx: + if (priv->fs) { + mlx5e_fs_set_rx_mode_active(priv->fs, false); + cancel_work_sync(&priv->set_rx_mode_work); + } profile->cleanup_rx(priv); err_cleanup_tx: profile->cleanup_tx(priv); @@ -6637,10 +6643,6 @@ err_cleanup_tx: out: mlx5e_reset_channels(priv->netdev); set_bit(MLX5E_STATE_DESTROYING, &priv->state); - if (priv->fs) - mlx5e_fs_set_rx_mode_active(priv->fs, - !test_bit(MLX5E_STATE_DESTROYING, - &priv->state)); cancel_work_sync(&priv->update_stats_work); return err; } @@ -6651,9 +6653,7 @@ void mlx5e_detach_netdev(struct mlx5e_priv *priv) set_bit(MLX5E_STATE_DESTROYING, &priv->state); if (priv->fs) - mlx5e_fs_set_rx_mode_active(priv->fs, - !test_bit(MLX5E_STATE_DESTROYING, - &priv->state)); + mlx5e_fs_set_rx_mode_active(priv->fs, false); if (profile->disable) profile->disable(priv); diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_rep.c b/drivers/net/ethernet/mellanox/mlx5/core/en_rep.c index 36277710a8a1..c7b4a8a82773 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_rep.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_rep.c @@ -238,6 +238,7 @@ static MLX5E_DECLARE_STATS_GRP_OP_UPDATE_STATS(vport_rep) MLX5_GET_CTR(out, transmitted_ib_unicast.octets) + MLX5_GET_CTR(out, transmitted_eth_unicast.octets) + MLX5_GET_CTR(out, transmitted_ib_multicast.octets) + + MLX5_GET_CTR(out, transmitted_eth_multicast.octets) + MLX5_GET_CTR(out, transmitted_eth_broadcast.octets); rep_stats->vport_tx_bytes = diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_tc.c b/drivers/net/ethernet/mellanox/mlx5/core/en_tc.c index 708b7987ea4c..1d35c97aea0b 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_tc.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_tc.c @@ -4005,6 +4005,7 @@ parse_branch_ctrl(struct flow_action_entry *act, struct mlx5e_tc_act *tc_act, err_branch_false: free_branch_attr(flow, attr->branch_true); + attr->branch_true = NULL; out_err: return err; } @@ -4836,16 +4837,19 @@ static bool is_tc_ipsec_order_check_needed(struct net_device *filter, struct mlx static int mlx5e_tc_block_ipsec_offload(struct net_device *filter, struct mlx5e_priv *priv) { struct mlx5_core_dev *mdev = priv->mdev; + int ret = 0; if (!is_tc_ipsec_order_check_needed(filter, priv)) return 0; - if (mdev->num_block_tc) - return -EBUSY; - - mdev->num_block_ipsec++; + spin_lock_bh(&mdev->offload_block.lock); + if (mdev->offload_block.num_block_tc) + ret = -EBUSY; + else + mdev->offload_block.num_block_ipsec++; + spin_unlock_bh(&mdev->offload_block.lock); - return 0; + return ret; } static void mlx5e_tc_unblock_ipsec_offload(struct net_device *filter, struct mlx5e_priv *priv) @@ -4853,7 +4857,10 @@ static void mlx5e_tc_unblock_ipsec_offload(struct net_device *filter, struct mlx if (!is_tc_ipsec_order_check_needed(filter, priv)) return; - priv->mdev->num_block_ipsec--; + spin_lock_bh(&priv->mdev->offload_block.lock); + if (!WARN_ON_ONCE(!priv->mdev->offload_block.num_block_ipsec)) + priv->mdev->offload_block.num_block_ipsec--; + spin_unlock_bh(&priv->mdev->offload_block.lock); } int mlx5e_configure_flower(struct net_device *dev, struct mlx5e_priv *priv, diff --git a/drivers/net/ethernet/mellanox/mlx5/core/esw/bridge.c b/drivers/net/ethernet/mellanox/mlx5/core/esw/bridge.c index b4cf3c5ac0dd..9fac6f985a86 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/esw/bridge.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/esw/bridge.c @@ -1867,26 +1867,27 @@ int mlx5_esw_bridge_port_mdb_add(struct net_device *dev, u16 vport_num, u16 esw_ port = mlx5_esw_bridge_port_lookup(vport_num, esw_owner_vhca_id, br_offloads); if (!port) { - esw_warn(br_offloads->esw->dev, + /* MDB is added asynchronously from the switchdev deferred + * queue while port might have been deleted concurrently. + */ + esw_info(br_offloads->esw->dev, "Failed to lookup bridge port to add MDB (MAC=%pM,vport=%u)\n", addr, vport_num); - NL_SET_ERR_MSG_FMT_MOD(extack, - "Failed to lookup bridge port to add MDB (MAC=%pM,vport=%u)", - addr, vport_num); - return -EINVAL; + return -EOPNOTSUPP; } bridge = port->bridge; if (bridge->flags & MLX5_ESW_BRIDGE_VLAN_FILTERING_FLAG && vid) { vlan = mlx5_esw_bridge_vlan_lookup(vid, port); if (!vlan) { - esw_warn(br_offloads->esw->dev, + /* MDB is added asynchronously from the switchdev + * deferred queue while vlan might have been deleted + * concurrently. + */ + esw_info(br_offloads->esw->dev, "Failed to lookup bridge port vlan metadata to create MDB (MAC=%pM,vid=%u,vport=%u)\n", addr, vid, vport_num); - NL_SET_ERR_MSG_FMT_MOD(extack, - "Failed to lookup vlan metadata for MDB (MAC=%pM,vid=%u,vport=%u)", - addr, vid, vport_num); - return -EINVAL; + return -EOPNOTSUPP; } } diff --git a/drivers/net/ethernet/mellanox/mlx5/core/esw/ipsec_fs.c b/drivers/net/ethernet/mellanox/mlx5/core/esw/ipsec_fs.c index ab50d2c734ed..f8c97954b6ea 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/esw/ipsec_fs.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/esw/ipsec_fs.c @@ -34,12 +34,23 @@ void mlx5_esw_ipsec_rx_create_attr_set(struct mlx5e_ipsec *ipsec, int mlx5_esw_ipsec_rx_status_pass_dest_get(struct mlx5e_ipsec *ipsec, struct mlx5_flow_destination *dest) { - dest->type = MLX5_FLOW_DESTINATION_TYPE_FLOW_TABLE; - dest->ft = mlx5_chains_get_table(esw_chains(ipsec->mdev->priv.eswitch), 0, 1, 0); + struct mlx5_flow_table *ft; + + ft = mlx5_chains_get_table(esw_chains(ipsec->mdev->priv.eswitch), + 0, 1, 0); + if (IS_ERR(ft)) + return PTR_ERR(ft); + dest->type = MLX5_FLOW_DESTINATION_TYPE_FLOW_TABLE; + dest->ft = ft; return 0; } +void mlx5_esw_ipsec_rx_status_pass_dest_put(struct mlx5e_ipsec *ipsec) +{ + mlx5_chains_put_table(esw_chains(ipsec->mdev->priv.eswitch), 0, 1, 0); +} + int mlx5_esw_ipsec_rx_setup_modify_header(struct mlx5e_ipsec_sa_entry *sa_entry, struct mlx5_flow_act *flow_act) { diff --git a/drivers/net/ethernet/mellanox/mlx5/core/esw/ipsec_fs.h b/drivers/net/ethernet/mellanox/mlx5/core/esw/ipsec_fs.h index 514c15258b1d..bb6f2423078b 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/esw/ipsec_fs.h +++ b/drivers/net/ethernet/mellanox/mlx5/core/esw/ipsec_fs.h @@ -12,6 +12,7 @@ void mlx5_esw_ipsec_rx_create_attr_set(struct mlx5e_ipsec *ipsec, struct mlx5e_ipsec_rx_create_attr *attr); int mlx5_esw_ipsec_rx_status_pass_dest_get(struct mlx5e_ipsec *ipsec, struct mlx5_flow_destination *dest); +void mlx5_esw_ipsec_rx_status_pass_dest_put(struct mlx5e_ipsec *ipsec); int mlx5_esw_ipsec_rx_setup_modify_header(struct mlx5e_ipsec_sa_entry *sa_entry, struct mlx5_flow_act *flow_act); void mlx5_esw_ipsec_rx_id_mapping_remove(struct mlx5e_ipsec_sa_entry *sa_entry); @@ -32,6 +33,11 @@ static inline int mlx5_esw_ipsec_rx_status_pass_dest_get(struct mlx5e_ipsec *ips return -EINVAL; } +static inline +void mlx5_esw_ipsec_rx_status_pass_dest_put(struct mlx5e_ipsec *ipsec) +{ +} + static inline int mlx5_esw_ipsec_rx_setup_modify_header(struct mlx5e_ipsec_sa_entry *sa_entry, struct mlx5_flow_act *flow_act) { diff --git a/drivers/net/ethernet/mellanox/mlx5/core/eswitch.c b/drivers/net/ethernet/mellanox/mlx5/core/eswitch.c index 2d289fb1353b..76f808e06a88 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/eswitch.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/eswitch.c @@ -1514,13 +1514,9 @@ int mlx5_esw_pf_enable_hca(struct mlx5_core_dev *dev, u16 vport_num) struct mlx5_vport *vport; int err; - if (!mlx5_core_is_ecpf(dev) || !mlx5_esw_allowed(esw)) + if (!mlx5_core_is_ecpf(dev)) return 0; - vport = mlx5_eswitch_get_vport(esw, vport_num); - if (IS_ERR(vport)) - return PTR_ERR(vport); - /* Once vport and representor are ready, take the PF out of * initializing state. Enabling HCA clears the iser->initializing * bit and PF driver loading can progress. @@ -1529,7 +1525,11 @@ int mlx5_esw_pf_enable_hca(struct mlx5_core_dev *dev, u16 vport_num) if (err) return err; - vport->pf_activated = true; + if (mlx5_esw_allowed(esw)) { + vport = mlx5_eswitch_get_vport(esw, vport_num); + if (!IS_ERR(vport)) + vport->pf_activated = true; + } return 0; } @@ -1540,18 +1540,18 @@ int mlx5_esw_pf_disable_hca(struct mlx5_core_dev *dev, u16 vport_num) struct mlx5_vport *vport; int err; - if (!mlx5_core_is_ecpf(dev) || !mlx5_esw_allowed(esw)) + if (!mlx5_core_is_ecpf(dev)) return 0; - vport = mlx5_eswitch_get_vport(esw, vport_num); - if (IS_ERR(vport)) - return PTR_ERR(vport); - err = mlx5_cmd_pf_disable_hca(dev, vport_num); if (err) return err; - vport->pf_activated = false; + if (mlx5_esw_allowed(esw)) { + vport = mlx5_eswitch_get_vport(esw, vport_num); + if (!IS_ERR(vport)) + vport->pf_activated = false; + } return 0; } @@ -3051,12 +3051,36 @@ int mlx5_esw_lock(struct mlx5_eswitch *esw) return 0; } +static void esw_mode_lock(struct mlx5_eswitch *esw) +{ + down_write(&esw->mode_lock); +} + +static void esw_mode_unlock(struct mlx5_eswitch *esw) +{ + up_write(&esw->mode_lock); +} + +/* Lock the eswitch and wait for an operation in progress to finish. */ +void mlx5_esw_lock_wait(struct mlx5_eswitch *esw) +{ + down_write(&esw->mode_lock); + wait_var_event_any_lock(&esw->eswitch_operation_in_progress, + !esw->eswitch_operation_in_progress, + esw, esw_mode, TASK_UNINTERRUPTIBLE); +} + /** * mlx5_esw_unlock() - Release write lock on esw mode lock * @esw: eswitch device. + * + * Also wakes up mlx5_esw_lock_wait() waiters, so it must be used to release + * mode_lock after clearing eswitch_operation_in_progress. */ void mlx5_esw_unlock(struct mlx5_eswitch *esw) { + wake_up_var_locked(&esw->eswitch_operation_in_progress, + &esw->mode_lock); up_write(&esw->mode_lock); } diff --git a/drivers/net/ethernet/mellanox/mlx5/core/eswitch.h b/drivers/net/ethernet/mellanox/mlx5/core/eswitch.h index e9cbcd73b23f..48eb6acc1e87 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/eswitch.h +++ b/drivers/net/ethernet/mellanox/mlx5/core/eswitch.h @@ -948,6 +948,7 @@ void mlx5_esw_get(struct mlx5_core_dev *dev); void mlx5_esw_put(struct mlx5_core_dev *dev); int mlx5_esw_try_lock(struct mlx5_eswitch *esw); int mlx5_esw_lock(struct mlx5_eswitch *esw); +void mlx5_esw_lock_wait(struct mlx5_eswitch *esw); void mlx5_esw_unlock(struct mlx5_eswitch *esw); void esw_vport_change_handle_locked(struct mlx5_vport *vport); @@ -967,10 +968,10 @@ void mlx5_eswitch_unload_reps(struct mlx5_eswitch *esw); bool mlx5_eswitch_is_peer(struct mlx5_eswitch *esw, struct mlx5_eswitch *peer_esw); -bool mlx5_eswitch_block_encap(struct mlx5_core_dev *dev, bool from_fdb); +int mlx5_eswitch_block_encap(struct mlx5_core_dev *dev, bool from_fdb); void mlx5_eswitch_unblock_encap(struct mlx5_core_dev *dev); -int mlx5_eswitch_block_mode(struct mlx5_core_dev *dev); +int mlx5_eswitch_block_mode(struct mlx5_core_dev *dev, bool check_users); void mlx5_eswitch_unblock_mode(struct mlx5_core_dev *dev); static inline int mlx5_eswitch_num_vfs(struct mlx5_eswitch *esw) @@ -1071,17 +1072,21 @@ mlx5_eswitch_reload_ib_reps(struct mlx5_eswitch *esw) static inline void mlx5_eswitch_unload_reps(struct mlx5_eswitch *esw) {} -static inline bool +static inline int mlx5_eswitch_block_encap(struct mlx5_core_dev *dev, bool from_fdb) { - return true; + return 1; } static inline void mlx5_eswitch_unblock_encap(struct mlx5_core_dev *dev) { } -static inline int mlx5_eswitch_block_mode(struct mlx5_core_dev *dev) { return 0; } +static inline int mlx5_eswitch_block_mode(struct mlx5_core_dev *dev, + bool check_users) +{ + return 0; +} static inline void mlx5_eswitch_unblock_mode(struct mlx5_core_dev *dev) {} static inline bool mlx5_eswitch_block_ipsec(struct mlx5_core_dev *dev) { diff --git a/drivers/net/ethernet/mellanox/mlx5/core/eswitch_offloads.c b/drivers/net/ethernet/mellanox/mlx5/core/eswitch_offloads.c index c712848b202d..474784131091 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/eswitch_offloads.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/eswitch_offloads.c @@ -2457,8 +2457,8 @@ void mlx5_esw_reps_unblock(struct mlx5_eswitch *esw) static void esw_mode_change(struct mlx5_eswitch *esw, u16 mode) { + mlx5_devcom_comp_assert_locked(esw->dev->priv.hca_devcom_comp); mlx5_esw_reps_unblock(esw); - mlx5_devcom_comp_lock(esw->dev->priv.hca_devcom_comp); if (esw->dev->priv.flags & MLX5_PRIV_FLAGS_DISABLE_IB_ADEV || mlx5_core_mp_enabled(esw->dev)) { esw->mode = mode; @@ -2471,7 +2471,6 @@ static void esw_mode_change(struct mlx5_eswitch *esw, u16 mode) esw->dev->priv.flags &= ~MLX5_PRIV_FLAGS_DISABLE_IB_ADEV; out: mlx5_rescan_drivers_locked(esw->dev); - mlx5_devcom_comp_unlock(esw->dev->priv.hca_devcom_comp); mlx5_esw_reps_block(esw); } @@ -4366,7 +4365,7 @@ static int esw_inline_mode_to_devlink(u8 mlx5_mode, u8 *mode) return 0; } -int mlx5_eswitch_block_mode(struct mlx5_core_dev *dev) +int mlx5_eswitch_block_mode(struct mlx5_core_dev *dev, bool check_users) { struct mlx5_eswitch *esw = dev->priv.eswitch; int err; @@ -4374,8 +4373,11 @@ int mlx5_eswitch_block_mode(struct mlx5_core_dev *dev) if (!mlx5_esw_allowed(esw)) return 0; - /* Take TC into account */ - err = mlx5_esw_try_lock(esw); + /* Temporary reservations may reuse tables while TC users exist. */ + if (check_users) + err = mlx5_esw_try_lock(esw); + else + err = mlx5_esw_lock(esw); if (err < 0) return err; @@ -4442,7 +4444,7 @@ static bool mlx5_devlink_switchdev_active_mode_change(struct mlx5_eswitch *esw, !esw->offloads_inactive) return false; - down_write(&esw->mode_lock); + mlx5_esw_lock_wait(esw); esw->offloads_inactive = !esw->offloads_inactive; esw->eswitch_operation_in_progress = true; up_write(&esw->mode_lock); @@ -4454,34 +4456,30 @@ static bool mlx5_devlink_switchdev_active_mode_change(struct mlx5_eswitch *esw, down_write(&esw->mode_lock); esw->eswitch_operation_in_progress = false; - up_write(&esw->mode_lock); + mlx5_esw_unlock(esw); return true; } -#define MLX5_ESW_HOLD_TIMEOUT_MS 7000 -#define MLX5_ESW_HOLD_RETRY_DELAY_MS 500 - void mlx5_eswitch_safe_aux_devs_remove(struct mlx5_core_dev *dev) { - unsigned long timeout; - bool hold_esw = true; + struct mlx5_eswitch *esw = dev->priv.eswitch; - /* Wait for any concurrent eswitch mode transition to complete. */ - if (!mlx5_esw_hold(dev)) { - timeout = jiffies + msecs_to_jiffies(MLX5_ESW_HOLD_TIMEOUT_MS); - while (!mlx5_esw_hold(dev)) { - if (!time_before(jiffies, timeout)) { - hold_esw = false; - break; - } - msleep(MLX5_ESW_HOLD_RETRY_DELAY_MS); - } - } - if (hold_esw) { - if (mlx5_eswitch_mode(dev) == MLX5_ESWITCH_OFFLOADS) - mlx5_core_reps_aux_devs_remove(dev); - mlx5_esw_release(dev); - } + if (!mlx5_esw_allowed(esw)) + return; + + /* Wait for any concurrent eswitch mode transition to complete. + * Deadlock risk if ever called from within an operation in progress. + */ + mlx5_esw_lock_wait(esw); + esw->eswitch_operation_in_progress = true; + up_write(&esw->mode_lock); + + if (mlx5_eswitch_mode(dev) == MLX5_ESWITCH_OFFLOADS) + mlx5_core_reps_aux_devs_remove(dev); + + down_write(&esw->mode_lock); + esw->eswitch_operation_in_progress = false; + mlx5_esw_unlock(esw); } int mlx5_devlink_eswitch_mode_set(struct devlink *devlink, u16 mode, @@ -4508,10 +4506,11 @@ int mlx5_devlink_eswitch_mode_set(struct devlink *devlink, u16 mode, return 0; mlx5_lag_disable_change(esw->dev); + mlx5_devcom_comp_lock(esw->dev->priv.hca_devcom_comp); err = mlx5_esw_try_lock(esw); if (err < 0) { NL_SET_ERR_MSG_MOD(extack, "Can't change mode, E-Switch is busy"); - goto enable_lag; + goto unlock_hca; } cur_mlx5_mode = err; err = 0; @@ -4574,7 +4573,8 @@ skip: esw->eswitch_operation_in_progress = false; unlock: mlx5_esw_unlock(esw); -enable_lag: +unlock_hca: + mlx5_devcom_comp_unlock(esw->dev->priv.hca_devcom_comp); mlx5_lag_enable_change(esw->dev); /* Shared FDB activation is creating LAG which is changing reps. */ if (!err) @@ -4655,7 +4655,7 @@ int mlx5_devlink_eswitch_inline_mode_set(struct devlink *devlink, u8 mode, if (IS_ERR(esw)) return PTR_ERR(esw); - down_write(&esw->mode_lock); + mlx5_esw_lock_wait(esw); switch (MLX5_CAP_ETH(dev, wqe_inline_mode)) { case MLX5_CAP_INLINE_MODE_NOT_REQUIRED: @@ -4693,7 +4693,7 @@ int mlx5_devlink_eswitch_inline_mode_set(struct devlink *devlink, u8 mode, down_write(&esw->mode_lock); esw->eswitch_operation_in_progress = false; - up_write(&esw->mode_lock); + mlx5_esw_unlock(esw); return 0; out: @@ -4712,25 +4712,31 @@ int mlx5_devlink_eswitch_inline_mode_get(struct devlink *devlink, u8 *mode) return esw_inline_mode_to_devlink(esw->offloads.inline_mode, mode); } -bool mlx5_eswitch_block_encap(struct mlx5_core_dev *dev, bool from_fdb) +/* Return 1 if allowed, 0 if disallowed by the configuration, or -EBUSY + * if an eswitch operation is in progress. + */ +int mlx5_eswitch_block_encap(struct mlx5_core_dev *dev, bool from_fdb) { struct mlx5_eswitch *esw = dev->priv.eswitch; enum devlink_eswitch_encap_mode encap; - bool allow_tunnel = false; + int ret; if (!mlx5_esw_allowed(esw)) - return true; + return 1; + + ret = mlx5_esw_lock(esw); + if (ret) + return ret; - down_write(&esw->mode_lock); encap = esw->offloads.encap; if (esw->mode == MLX5_ESWITCH_LEGACY || (encap == DEVLINK_ESWITCH_ENCAP_MODE_NONE && !from_fdb)) { - allow_tunnel = true; + ret = 1; esw->offloads.num_block_encap++; } - up_write(&esw->mode_lock); + mlx5_esw_unlock(esw); - return allow_tunnel; + return ret; } void mlx5_eswitch_unblock_encap(struct mlx5_core_dev *dev) @@ -4757,7 +4763,7 @@ int mlx5_devlink_eswitch_encap_mode_set(struct devlink *devlink, if (IS_ERR(esw)) return PTR_ERR(esw); - down_write(&esw->mode_lock); + mlx5_esw_lock_wait(esw); if (encap != DEVLINK_ESWITCH_ENCAP_MODE_NONE && (!MLX5_CAP_ESW_FLOWTABLE_FDB(dev, reformat) || @@ -4813,7 +4819,7 @@ int mlx5_devlink_eswitch_encap_mode_set(struct devlink *devlink, esw->eswitch_operation_in_progress = false; unlock: - up_write(&esw->mode_lock); + mlx5_esw_unlock(esw); return err; } diff --git a/drivers/net/ethernet/mellanox/mlx5/core/ipoib/ipoib.h b/drivers/net/ethernet/mellanox/mlx5/core/ipoib/ipoib.h index d67d5a72bb41..8c0039c5425e 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/ipoib/ipoib.h +++ b/drivers/net/ethernet/mellanox/mlx5/core/ipoib/ipoib.h @@ -82,7 +82,7 @@ void mlx5i_pkey_qpn_ht_cleanup(struct net_device *netdev); int mlx5i_pkey_add_qpn(struct net_device *netdev, u32 qpn); int mlx5i_pkey_del_qpn(struct net_device *netdev, u32 qpn); -/* Get the net-device corresponding to the given underlay QPN */ +/* Get the net-device for a QPN. Caller must hold rcu_read_lock(). */ struct net_device *mlx5i_pkey_get_netdev(struct net_device *netdev, u32 qpn); /* Shared ndo functions */ diff --git a/drivers/net/ethernet/mellanox/mlx5/core/ipoib/ipoib_vlan.c b/drivers/net/ethernet/mellanox/mlx5/core/ipoib/ipoib_vlan.c index 4120afd097c3..5edc39247525 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/ipoib/ipoib_vlan.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/ipoib/ipoib_vlan.c @@ -31,6 +31,7 @@ */ #include <linux/hash.h> +#include <linux/rculist.h> #include "ipoib.h" #define MLX5I_MAX_LOG_PKEY_SUP 7 @@ -39,11 +40,12 @@ struct qpn_to_netdev { struct net_device *netdev; struct hlist_node hlist; u32 underlay_qpn; + struct rcu_head rcu; }; struct mlx5i_pkey_qpn_ht { struct hlist_head buckets[1 << MLX5I_MAX_LOG_PKEY_SUP]; - spinlock_t ht_lock; /* Synchronise with NAPI */ + spinlock_t ht_lock; /* Serialize hash table updates */ }; int mlx5i_pkey_qpn_ht_init(struct net_device *netdev) @@ -68,13 +70,14 @@ void mlx5i_pkey_qpn_ht_cleanup(struct net_device *netdev) kfree(ipriv->qpn_htbl); } -static struct qpn_to_netdev *mlx5i_find_qpn_to_netdev_node(struct hlist_head *buckets, - u32 qpn) +static struct qpn_to_netdev * +mlx5i_find_qpn_to_netdev_node(struct mlx5i_pkey_qpn_ht *ht, u32 qpn) { - struct hlist_head *h = &buckets[hash_32(qpn, MLX5I_MAX_LOG_PKEY_SUP)]; + struct hlist_head *h = &ht->buckets[hash_32(qpn, MLX5I_MAX_LOG_PKEY_SUP)]; struct qpn_to_netdev *node; - hlist_for_each_entry(node, h, hlist) { + hlist_for_each_entry_rcu(node, h, hlist, + lockdep_is_held(&ht->ht_lock)) { if (node->underlay_qpn == qpn) return node; } @@ -96,7 +99,7 @@ int mlx5i_pkey_add_qpn(struct net_device *netdev, u32 qpn) new_node->netdev = netdev; new_node->underlay_qpn = qpn; spin_lock_bh(&ht->ht_lock); - hlist_add_head(&new_node->hlist, &ht->buckets[key]); + hlist_add_head_rcu(&new_node->hlist, &ht->buckets[key]); spin_unlock_bh(&ht->ht_lock); return 0; @@ -109,16 +112,17 @@ int mlx5i_pkey_del_qpn(struct net_device *netdev, u32 qpn) struct mlx5i_pkey_qpn_ht *ht = ipriv->qpn_htbl; struct qpn_to_netdev *node; - node = mlx5i_find_qpn_to_netdev_node(ht->buckets, qpn); + spin_lock_bh(&ht->ht_lock); + node = mlx5i_find_qpn_to_netdev_node(ht, qpn); if (!node) { + spin_unlock_bh(&ht->ht_lock); mlx5_core_warn(epriv->mdev, "QPN to netdev delete from HT failed\n"); return -EINVAL; } - spin_lock_bh(&ht->ht_lock); - hlist_del_init(&node->hlist); + hlist_del_rcu(&node->hlist); spin_unlock_bh(&ht->ht_lock); - kfree(node); + kfree_rcu(node, rcu); return 0; } @@ -128,7 +132,7 @@ struct net_device *mlx5i_pkey_get_netdev(struct net_device *netdev, u32 qpn) struct mlx5i_priv *ipriv = netdev_priv(netdev); struct qpn_to_netdev *node; - node = mlx5i_find_qpn_to_netdev_node(ipriv->qpn_htbl->buckets, qpn); + node = mlx5i_find_qpn_to_netdev_node(ipriv->qpn_htbl, qpn); if (!node) return NULL; diff --git a/drivers/net/ethernet/mellanox/mlx5/core/lag/lag.c b/drivers/net/ethernet/mellanox/mlx5/core/lag/lag.c index 4907e0de0b8f..9330aab24c02 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/lag/lag.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/lag/lag.c @@ -1172,7 +1172,6 @@ int mlx5_deactivate_lag(struct mlx5_lag *ldev) "Failed to deactivate VF LAG; driver restart required\n" "Make sure all VFs are unbound prior to VF LAG activation or deactivation\n"); } - return err; } if (test_bit(MLX5_LAG_MODE_FLAG_HASH_BASED, &flags)) { @@ -1182,7 +1181,7 @@ int mlx5_deactivate_lag(struct mlx5_lag *ldev) if (mlx5_lag_has_drop_rule(ldev)) mlx5_lag_drop_rule_cleanup(ldev); - return 0; + return err; } bool mlx5_lag_check_prereq(struct mlx5_lag *ldev) diff --git a/drivers/net/ethernet/mellanox/mlx5/core/lag/mpesw.c b/drivers/net/ethernet/mellanox/mlx5/core/lag/mpesw.c index abf72026c751..549d31812c2f 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/lag/mpesw.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/lag/mpesw.c @@ -227,7 +227,7 @@ static int mlx5_lag_mpesw_queue_work(struct mlx5_core_dev *dev, int err = 0; if (!ldev) - return 0; + return -EOPNOTSUPP; work = kzalloc_obj(*work); if (!work) diff --git a/drivers/net/ethernet/mellanox/mlx5/core/lib/clock.c b/drivers/net/ethernet/mellanox/mlx5/core/lib/clock.c index 5df786133e4b..c3e53d219496 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/lib/clock.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/lib/clock.c @@ -80,6 +80,7 @@ enum { }; struct mlx5_clock_dev_state { + bool loaded; struct mlx5_core_dev *mdev; struct mlx5_devcom_comp_dev *compdev; struct mlx5_nb pps_nb; @@ -89,7 +90,7 @@ struct mlx5_clock_dev_state { struct mlx5_clock_priv { struct mlx5_clock clock; struct mlx5_core_dev *mdev; - struct mutex lock; /* protect mdev and used in PTP callbacks */ + struct mutex lock; /* protect mdev and serialize hardware callbacks */ struct mlx5_core_dev *event_mdev; }; @@ -100,9 +101,6 @@ static struct mlx5_clock_priv *clock_priv(struct mlx5_clock *clock) static void mlx5_clock_lockdep_assert(struct mlx5_clock *clock) { - if (!clock->shared) - return; - lockdep_assert(lockdep_is_held(&clock_priv(clock)->lock)); } @@ -115,20 +113,24 @@ static struct mlx5_core_dev *mlx5_clock_mdev_get(struct mlx5_clock *clock) static void mlx5_clock_lock(struct mlx5_clock *clock) { - if (!clock->shared) - return; - mutex_lock(&clock_priv(clock)->lock); } static void mlx5_clock_unlock(struct mlx5_clock *clock) { - if (!clock->shared) - return; - mutex_unlock(&clock_priv(clock)->lock); } +static struct mlx5_core_dev * +mlx5_clock_active_mdev_get(struct mlx5_clock *clock) +{ + struct mlx5_clock_priv *cpriv = clock_priv(clock); + + mlx5_clock_lockdep_assert(clock); + + return cpriv->mdev->clock_state->loaded ? cpriv->mdev : NULL; +} + static bool mlx5_real_time_mode(struct mlx5_core_dev *mdev) { return (mlx5_is_real_time_rq(mdev) || mlx5_is_real_time_sq(mdev)); @@ -333,7 +335,11 @@ static int mlx5_ptp_getcrosststamp(struct ptp_clock_info *ptp, int err; mlx5_clock_lock(clock); - mdev = mlx5_clock_mdev_get(clock); + mdev = mlx5_clock_active_mdev_get(clock); + if (!mdev) { + err = -EAGAIN; + goto unlock; + } if (!mlx5_is_ptm_source_time_available(mdev)) { err = -EBUSY; @@ -359,7 +365,11 @@ static int mlx5_ptp_getcrosscycles(struct ptp_clock_info *ptp, int err; mlx5_clock_lock(clock); - mdev = mlx5_clock_mdev_get(clock); + mdev = mlx5_clock_active_mdev_get(clock); + if (!mdev) { + err = -EAGAIN; + goto unlock; + } if (!mlx5_is_ptm_source_time_available(mdev)) { err = -EBUSY; @@ -411,6 +421,12 @@ static u64 read_internal_timer(struct cyclecounter *cc) return mlx5_read_time(mdev, NULL, false) & cc->mask; } +static void mlx5_timer_snapshot(struct mlx5_timer *timer) +{ + timer->saved_phc_ns = timer->tc.nsec; + timer->saved_boot_ns = ktime_get_boottime_ns(); +} + static void mlx5_update_clock_info_page(struct mlx5_core_dev *mdev) { struct mlx5_ib_clock_info *clock_info = mdev->clock_info; @@ -418,6 +434,9 @@ static void mlx5_update_clock_info_page(struct mlx5_core_dev *mdev) struct mlx5_timer *timer; u32 sign; + timer = &clock->timer; + mlx5_timer_snapshot(timer); + if (!clock_info) return; @@ -425,7 +444,6 @@ static void mlx5_update_clock_info_page(struct mlx5_core_dev *mdev) smp_store_mb(clock_info->sign, sign | MLX5_IB_CLOCK_INFO_KERNEL_UPDATING); - timer = &clock->timer; clock_info->cycles = timer->tc.cycle_last; clock_info->mult = timer->cycles.mult; clock_info->nsec = timer->tc.nsec; @@ -471,10 +489,9 @@ static long mlx5_timestamp_overflow(struct ptp_clock_info *ptp_info) clock = container_of(ptp_info, struct mlx5_clock, ptp_info); mlx5_clock_lock(clock); - mdev = mlx5_clock_mdev_get(clock); + mdev = mlx5_clock_active_mdev_get(clock); timer = &clock->timer; - - if (mdev->state == MLX5_DEVICE_STATE_INTERNAL_ERROR) + if (!mdev || mdev->state == MLX5_DEVICE_STATE_INTERNAL_ERROR) goto out; write_seqlock_irqsave(&clock->lock, flags); @@ -531,8 +548,13 @@ static int mlx5_ptp_settime(struct ptp_clock_info *ptp, const struct timespec64 int err; mlx5_clock_lock(clock); - mdev = mlx5_clock_mdev_get(clock); + mdev = mlx5_clock_active_mdev_get(clock); + if (!mdev) { + err = -EAGAIN; + goto unlock; + } err = mlx5_clock_settime(mdev, clock, ts); +unlock: mlx5_clock_unlock(clock); return err; @@ -550,26 +572,40 @@ struct timespec64 mlx5_ptp_gettimex_real_time(struct mlx5_core_dev *mdev, return ts; } -static int mlx5_ptp_gettimex(struct ptp_clock_info *ptp, struct timespec64 *ts, - struct ptp_system_timestamp *sts) +static void mlx5_clock_gettimex(struct mlx5_core_dev *mdev, + struct mlx5_clock *clock, struct timespec64 *ts, + struct ptp_system_timestamp *sts) { - struct mlx5_clock *clock = container_of(ptp, struct mlx5_clock, ptp_info); - struct mlx5_core_dev *mdev; u64 cycles, ns; - mlx5_clock_lock(clock); - mdev = mlx5_clock_mdev_get(clock); if (mlx5_real_time_mode(mdev)) { *ts = mlx5_ptp_gettimex_real_time(mdev, sts); - goto out; + return; } cycles = mlx5_read_time(mdev, sts, false); ns = mlx5_timecounter_cyc2time(clock, cycles); *ts = ns_to_timespec64(ns); -out: +} + +static int mlx5_ptp_gettimex(struct ptp_clock_info *ptp, struct timespec64 *ts, + struct ptp_system_timestamp *sts) +{ + struct mlx5_clock *clock = + container_of(ptp, struct mlx5_clock, ptp_info); + struct mlx5_core_dev *mdev; + int err = 0; + + mlx5_clock_lock(clock); + mdev = mlx5_clock_active_mdev_get(clock); + if (!mdev) { + err = -EAGAIN; + goto unlock; + } + mlx5_clock_gettimex(mdev, clock, ts, sts); +unlock: mlx5_clock_unlock(clock); - return 0; + return err; } static int mlx5_ptp_getcyclesx(struct ptp_clock_info *ptp, @@ -580,14 +616,20 @@ static int mlx5_ptp_getcyclesx(struct ptp_clock_info *ptp, ptp_info); struct mlx5_core_dev *mdev; u64 cycles; + int err = 0; mlx5_clock_lock(clock); - mdev = mlx5_clock_mdev_get(clock); + mdev = mlx5_clock_active_mdev_get(clock); + if (!mdev) { + err = -EAGAIN; + goto unlock; + } cycles = mlx5_read_time(mdev, sts, false); *ts = ns_to_timespec64(cycles); +unlock: mlx5_clock_unlock(clock); - return 0; + return err; } static int mlx5_ptp_adjtime_real_time(struct mlx5_core_dev *mdev, s64 delta) @@ -620,7 +662,11 @@ static int mlx5_ptp_adjtime(struct ptp_clock_info *ptp, s64 delta) int err = 0; mlx5_clock_lock(clock); - mdev = mlx5_clock_mdev_get(clock); + mdev = mlx5_clock_active_mdev_get(clock); + if (!mdev) { + err = -EAGAIN; + goto unlock; + } if (mlx5_modify_mtutc_allowed(mdev)) { err = mlx5_ptp_adjtime_real_time(mdev, delta); @@ -630,6 +676,7 @@ static int mlx5_ptp_adjtime(struct ptp_clock_info *ptp, s64 delta) } write_seqlock_irqsave(&clock->lock, flags); + timecounter_read(&timer->tc); timecounter_adjtime(&timer->tc, delta); mlx5_update_clock_info_page(mdev); write_sequnlock_irqrestore(&clock->lock, flags); @@ -646,8 +693,13 @@ static int mlx5_ptp_adjphase(struct ptp_clock_info *ptp, s32 delta) int err; mlx5_clock_lock(clock); - mdev = mlx5_clock_mdev_get(clock); + mdev = mlx5_clock_active_mdev_get(clock); + if (!mdev) { + err = -EAGAIN; + goto unlock; + } err = mlx5_ptp_adjtime_real_time(mdev, delta); +unlock: mlx5_clock_unlock(clock); return err; @@ -683,7 +735,11 @@ static int mlx5_ptp_adjfine(struct ptp_clock_info *ptp, long scaled_ppm) u32 mult; mlx5_clock_lock(clock); - mdev = mlx5_clock_mdev_get(clock); + mdev = mlx5_clock_active_mdev_get(clock); + if (!mdev) { + err = -EAGAIN; + goto unlock; + } if (mlx5_modify_mtutc_allowed(mdev)) { err = mlx5_ptp_freq_adj_real_time(mdev, scaled_ppm); @@ -744,7 +800,11 @@ static int mlx5_extts_configure(struct ptp_clock_info *ptp, } mlx5_clock_lock(clock); - mdev = mlx5_clock_mdev_get(clock); + mdev = mlx5_clock_active_mdev_get(clock); + if (!mdev) { + err = -EAGAIN; + goto unlock; + } if (!MLX5_PPS_CAP(mdev)) { err = -EOPNOTSUPP; @@ -917,7 +977,11 @@ static int mlx5_perout_configure(struct ptp_clock_info *ptp, return -EBUSY; mlx5_clock_lock(clock); - mdev = mlx5_clock_mdev_get(clock); + mdev = mlx5_clock_active_mdev_get(clock); + if (!mdev) { + err = -EAGAIN; + goto unlock; + } rt_mode = mlx5_real_time_mode(mdev); if (!MLX5_PPS_CAP(mdev)) { @@ -1151,7 +1215,7 @@ static u64 perout_conf_next_event_timer(struct mlx5_core_dev *mdev, struct timespec64 ts; s64 target_ns; - mlx5_ptp_gettimex(&clock->ptp_info, &ts, NULL); + mlx5_clock_gettimex(mdev, clock, &ts, NULL); ts_next_sec(&ts); target_ns = timespec64_to_ns(&ts); @@ -1222,8 +1286,8 @@ static void mlx5_timecounter_init(struct mlx5_core_dev *mdev) timer->nominal_c_mult = timer->cycles.mult; timer->cycles.mask = CLOCKSOURCE_MASK(41); - timecounter_init(&timer->tc, &timer->cycles, - ktime_to_ns(ktime_get_real())); + timecounter_init(&timer->tc, &timer->cycles, ktime_get_real_ns()); + mlx5_timer_snapshot(timer); } static void mlx5_init_overflow_period(struct mlx5_core_dev *mdev) @@ -1381,9 +1445,6 @@ static void mlx5_init_clock_dev(struct mlx5_core_dev *mdev) clock->ptp); clock->ptp = NULL; } - - if (clock->ptp) - ptp_schedule_worker(clock->ptp, 0); } static void mlx5_destroy_clock_dev(struct mlx5_core_dev *mdev) @@ -1530,22 +1591,53 @@ static void mlx5_clock_arm_pps_in_event(struct mlx5_clock *clock, !clock->pps_info.pin_armed[i]) continue; - if (new_mdev) { + if (new_mdev) mlx5_set_mtppse(new_mdev, i, 0, MLX5_EVENT_MODE_REPETETIVE); - cpriv->event_mdev = new_mdev; - } else { - cpriv->event_mdev = NULL; - } if (old_mdev) mlx5_set_mtppse(old_mdev, i, 0, MLX5_EVENT_MODE_DISABLE); } + cpriv->event_mdev = new_mdev; +} + +static void mlx5_set_timecounter(struct mlx5_core_dev *mdev, u64 ns) +{ + struct mlx5_clock *clock = mdev->clock; + struct mlx5_timer *timer; + unsigned long flags; + + timer = &clock->timer; + mlx5_clock_lockdep_assert(clock); + + write_seqlock_irqsave(&clock->lock, flags); + timecounter_init(&timer->tc, &timer->cycles, ns); + mlx5_update_clock_info_page(mdev); + write_sequnlock_irqrestore(&clock->lock, flags); +} + +static void mlx5_save_timecounter(struct mlx5_core_dev *mdev) +{ + struct mlx5_clock *clock = mdev->clock; + struct mlx5_timer *timer; + unsigned long flags; + + timer = &clock->timer; + mlx5_clock_lockdep_assert(clock); + + if (mdev->state == MLX5_DEVICE_STATE_INTERNAL_ERROR) + return; + + write_seqlock_irqsave(&clock->lock, flags); + timecounter_read(&timer->tc); + mlx5_update_clock_info_page(mdev); + write_sequnlock_irqrestore(&clock->lock, flags); } void mlx5_clock_load(struct mlx5_core_dev *mdev) { struct mlx5_clock *clock = mdev->clock; struct mlx5_clock_priv *cpriv; + bool start; if (!MLX5_CAP_GEN(mdev, device_frequency_khz)) return; @@ -1554,18 +1646,32 @@ void mlx5_clock_load(struct mlx5_core_dev *mdev) MLX5_NB_INIT(&mdev->clock_state->pps_nb, mlx5_pps_event, PPS_EVENT); mlx5_eq_notifier_register(mdev, &mdev->clock_state->pps_nb); - if (!clock->shared) { - mlx5_clock_arm_pps_in_event(clock, mdev, NULL); - return; - } - cpriv = clock_priv(clock); - mlx5_devcom_comp_lock(mdev->clock_state->compdev); + if (clock->shared) + mlx5_devcom_comp_lock(mdev->clock_state->compdev); mlx5_clock_lock(clock); - if (mdev == cpriv->mdev && mdev != cpriv->event_mdev) + start = !cpriv->mdev->clock_state->loaded; + mdev->clock_state->loaded = true; + if (start) { + struct mlx5_timer *timer = &clock->timer; + u64 ns; + + cpriv->mdev = mdev; + if (mlx5_real_time_mode(mdev)) + ns = mlx5_read_time(mdev, NULL, true); + else + ns = timer->saved_phc_ns + + ktime_get_boottime_ns() - timer->saved_boot_ns; + + mlx5_set_timecounter(mdev, ns); mlx5_clock_arm_pps_in_event(clock, mdev, cpriv->event_mdev); + } mlx5_clock_unlock(clock); - mlx5_devcom_comp_unlock(mdev->clock_state->compdev); + + if (start && clock->ptp) + ptp_schedule_worker(clock->ptp, 0); + if (clock->shared) + mlx5_devcom_comp_unlock(mdev->clock_state->compdev); } void mlx5_clock_unload(struct mlx5_core_dev *mdev) @@ -1573,30 +1679,42 @@ void mlx5_clock_unload(struct mlx5_core_dev *mdev) struct mlx5_core_dev *peer_dev, *next = NULL; struct mlx5_clock *clock = mdev->clock; struct mlx5_devcom_comp_dev *pos; + struct mlx5_clock_priv *cpriv; + bool stop; if (!MLX5_CAP_GEN(mdev, device_frequency_khz)) return; - if (!clock->shared) { - mlx5_clock_arm_pps_in_event(clock, NULL, mdev); - goto out; - } - - mlx5_devcom_comp_lock(mdev->clock_state->compdev); - mlx5_devcom_for_each_peer_entry(mdev->clock_state->compdev, peer_dev, pos) { - if (peer_dev->clock && peer_dev != mdev) { - next = peer_dev; - break; + if (clock->shared) { + mlx5_devcom_comp_lock(mdev->clock_state->compdev); + mlx5_devcom_for_each_peer_entry(mdev->clock_state->compdev, + peer_dev, pos) { + if (peer_dev->clock == clock && + peer_dev->clock_state->loaded) { + next = peer_dev; + break; + } } } mlx5_clock_lock(clock); - if (mdev == clock_priv(clock)->event_mdev) + cpriv = clock_priv(clock); + mdev->clock_state->loaded = false; + if (mdev == cpriv->mdev && next) + cpriv->mdev = next; + if (mdev == cpriv->event_mdev) mlx5_clock_arm_pps_in_event(clock, next, mdev); + stop = !cpriv->mdev->clock_state->loaded; + if (!mlx5_real_time_mode(cpriv->mdev)) + mlx5_save_timecounter(cpriv->mdev); mlx5_clock_unlock(clock); - mlx5_devcom_comp_unlock(mdev->clock_state->compdev); -out: + /* Keep devcom locked to prevent a peer from restarting the worker. */ + if (stop && clock->ptp) + ptp_cancel_worker_sync(clock->ptp); + if (clock->shared) + mlx5_devcom_comp_unlock(mdev->clock_state->compdev); + mlx5_eq_notifier_unregister(mdev, &mdev->clock_state->pps_nb); cancel_work_sync(&mdev->clock_state->out_work); } diff --git a/drivers/net/ethernet/mellanox/mlx5/core/lib/clock.h b/drivers/net/ethernet/mellanox/mlx5/core/lib/clock.h index aff3aed62c74..86ae447a23ed 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/lib/clock.h +++ b/drivers/net/ethernet/mellanox/mlx5/core/lib/clock.h @@ -50,6 +50,8 @@ struct mlx5_timer { struct timecounter tc; u32 nominal_c_mult; unsigned long overflow_period; + u64 saved_phc_ns; + u64 saved_boot_ns; }; struct mlx5_clock { diff --git a/drivers/net/ethernet/mellanox/mlx5/core/lib/macsec_fs.c b/drivers/net/ethernet/mellanox/mlx5/core/lib/macsec_fs.c index 7d785c937d43..4892175ca577 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/lib/macsec_fs.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/lib/macsec_fs.c @@ -764,13 +764,9 @@ err_alloc_dev: return err; } -static void macsec_fs_tx_del_rule(struct mlx5_macsec_fs *macsec_fs, - struct mlx5_macsec_tx_rule *tx_rule, - void *macdev) +static void macsec_fs_tx_free_rule(struct mlx5_macsec_fs *macsec_fs, + struct mlx5_macsec_tx_rule *tx_rule) { - macsec_fs_id_del(&macsec_fs->macsec_devices_list, tx_rule->fs_id, macdev, - &macsec_fs->sci_hash, true); - if (tx_rule->rule) { mlx5_del_flow_rules(tx_rule->rule); tx_rule->rule = NULL; @@ -791,6 +787,15 @@ static void macsec_fs_tx_del_rule(struct mlx5_macsec_fs *macsec_fs, macsec_fs_tx_ft_put(macsec_fs); } +static void macsec_fs_tx_del_rule(struct mlx5_macsec_fs *macsec_fs, + struct mlx5_macsec_tx_rule *tx_rule, + void *macdev) +{ + macsec_fs_id_del(&macsec_fs->macsec_devices_list, tx_rule->fs_id, macdev, + &macsec_fs->sci_hash, true); + macsec_fs_tx_free_rule(macsec_fs, tx_rule); +} + #define MLX5_REFORMAT_PARAM_ADD_MACSEC_OFFSET_4_BYTES 1 static union mlx5_macsec_rule * @@ -883,7 +888,7 @@ macsec_fs_tx_add_rule(struct mlx5_macsec_fs *macsec_fs, goto out_spec; err: - macsec_fs_tx_del_rule(macsec_fs, tx_rule, macsec_ctx->secy->netdev); + macsec_fs_tx_free_rule(macsec_fs, tx_rule); macsec_rule = NULL; out_spec: kvfree(spec); @@ -1648,15 +1653,11 @@ static void macsec_fs_rx_ft_put(struct mlx5_macsec_fs *macsec_fs) macsec_fs_rx_destroy(macsec_fs); } -static void macsec_fs_rx_del_rule(struct mlx5_macsec_fs *macsec_fs, - struct mlx5_macsec_rx_rule *rx_rule, - void *macdev, u32 fs_id) +static void macsec_fs_rx_free_rule(struct mlx5_macsec_fs *macsec_fs, + struct mlx5_macsec_rx_rule *rx_rule) { int i; - macsec_fs_id_del(&macsec_fs->macsec_devices_list, fs_id, macdev, - &macsec_fs->fs_id_hash, false); - for (i = 0; i < RX_NUM_OF_RULES_PER_SA; ++i) { if (rx_rule->rule[i]) { mlx5_del_flow_rules(rx_rule->rule[i]); @@ -1674,6 +1675,15 @@ static void macsec_fs_rx_del_rule(struct mlx5_macsec_fs *macsec_fs, macsec_fs_rx_ft_put(macsec_fs); } +static void macsec_fs_rx_del_rule(struct mlx5_macsec_fs *macsec_fs, + struct mlx5_macsec_rx_rule *rx_rule, + void *macdev, u32 fs_id) +{ + macsec_fs_id_del(&macsec_fs->macsec_devices_list, fs_id, macdev, + &macsec_fs->fs_id_hash, false); + macsec_fs_rx_free_rule(macsec_fs, rx_rule); +} + static void macsec_fs_rx_setup_fte(struct mlx5_flow_spec *spec, struct mlx5_flow_act *flow_act, struct mlx5_macsec_rule_attrs *attrs, @@ -1833,7 +1843,7 @@ macsec_fs_rx_add_rule(struct mlx5_macsec_fs *macsec_fs, return macsec_rule; err: - macsec_fs_rx_del_rule(macsec_fs, rx_rule, macsec_ctx->secy->netdev, fs_id); + macsec_fs_rx_free_rule(macsec_fs, rx_rule); macsec_rule = NULL; out_spec: kvfree(spec); diff --git a/drivers/net/ethernet/mellanox/mlx5/core/main.c b/drivers/net/ethernet/mellanox/mlx5/core/main.c index 1a45474ce03d..0439fcfb9ce5 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/main.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/main.c @@ -1814,6 +1814,7 @@ int mlx5_mdev_init(struct mlx5_core_dev *dev, int profile_idx) lockdep_register_key(&dev->lock_key); mutex_init(&dev->intf_state_mutex); lockdep_set_class(&dev->intf_state_mutex, &dev->lock_key); + spin_lock_init(&dev->offload_block.lock); mutex_init(&dev->mlx5e_res.uplink_netdev_lock); mutex_init(&dev->wc_state_lock); diff --git a/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws.c b/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws.c index 812b2f3cddcf..cbcbc2b62809 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws.c @@ -523,13 +523,13 @@ mlx5_fs_get_action_aso_meter(struct mlx5_fs_hws_context *fs_ctx, } static void mlx5_fs_put_action_aso_meter(struct mlx5_fs_hws_context *fs_ctx, - struct mlx5_exe_aso *exe_aso) + u32 base_id) { struct mlx5_fs_hws_data *meter_hws_data; struct xarray *meters_xa; meters_xa = &fs_ctx->hws_pool.aso_meters; - meter_hws_data = xa_load(meters_xa, exe_aso->base_id); + meter_hws_data = xa_load(meters_xa, base_id); if (!meter_hws_data) return; return mlx5_fs_put_hws_action(meter_hws_data); @@ -704,7 +704,7 @@ static void mlx5_fs_destroy_fs_action(struct mlx5_flow_root_namespace *ns, mlx5_fc_put_hws_action(fs_action->counter); break; case MLX5HWS_ACTION_TYP_ASO_METER: - mlx5_fs_put_action_aso_meter(fs_ctx, fs_action->exe_aso); + mlx5_fs_put_action_aso_meter(fs_ctx, fs_action->aso_base_id); break; case MLX5HWS_ACTION_TYP_SAMPLER: mlx5_fs_put_dest_action_sampler(fs_ctx, fs_action->sampler_id); @@ -937,7 +937,7 @@ static int mlx5_fs_fte_get_hws_actions(struct mlx5_flow_root_namespace *ns, fte_action->exe_aso.flow_meter.init_color; (*ractions)[num_actions++].action = tmp_action; fs_actions[num_fs_actions].action = tmp_action; - fs_actions[num_fs_actions++].exe_aso = &fte_action->exe_aso; + fs_actions[num_fs_actions++].aso_base_id = fte_action->exe_aso.base_id; } if (fte_action->action & MLX5_FLOW_CONTEXT_ACTION_DROP) { diff --git a/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws.h b/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws.h index cf068fb5bdbf..4fdeea9fdd12 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws.h +++ b/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws.h @@ -57,7 +57,7 @@ struct mlx5_fs_hws_rule_action { struct mlx5hws_action *action; union { struct mlx5_fc *counter; - struct mlx5_exe_aso *exe_aso; + u32 aso_base_id; u32 sampler_id; }; }; diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_csr.h b/drivers/net/ethernet/meta/fbnic/fbnic_csr.h index cbb25d11638c..c371ac9f78c1 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_csr.h +++ b/drivers/net/ethernet/meta/fbnic/fbnic_csr.h @@ -441,6 +441,7 @@ enum { #define FBNIC_TMI_SOP_PROT_CTRL 0x04400 /* 0x11000 */ #define FBNIC_TMI_DROP_CTRL 0x04401 /* 0x11004 */ #define FBNIC_TMI_DROP_CTRL_EN CSR_BIT(0) +#define FBNIC_TMI_DROP_CTRL_CMPL_DIS CSR_BIT(1) #define FBNIC_TMI_DROP_PKTS 0x04402 /* 0x11008 */ #define FBNIC_TMI_DROP_BYTE_L 0x04403 /* 0x1100c */ #define FBNIC_TMI_ILLEGAL_PTP_REQS 0x04409 /* 0x11024 */ @@ -955,6 +956,10 @@ enum { /* PUL User Registers */ #define FBNIC_CSR_START_PUL_USER 0x31000 /* CSR section delimiter */ +#define FBNIC_PUL_USER_IP_LINK_RST_STATUS \ + 0x31030 /* 0xc40c0 */ +#define FBNIC_PUL_USER_IP_LINK_RST_STATUS_AW_FLUSH_DONE CSR_BIT(7) +#define FBNIC_PUL_USER_IP_LINK_RST_STATUS_AR_FLUSH_DONE CSR_BIT(8) #define FBNIC_PUL_OB_TLP_HDR_AW_CFG 0x3103d /* 0xc40f4 */ #define FBNIC_PUL_OB_TLP_HDR_AW_CFG_FLUSH_MODE CSR_BIT(20) #define FBNIC_PUL_OB_TLP_HDR_AW_CFG_FLUSH CSR_BIT(19) diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_fw.c b/drivers/net/ethernet/meta/fbnic/fbnic_fw.c index 49b8813a3564..e00d626f6438 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_fw.c +++ b/drivers/net/ethernet/meta/fbnic/fbnic_fw.c @@ -7,6 +7,7 @@ #include <linux/dev_printk.h> #include <linux/dma-mapping.h> #include <linux/gfp.h> +#include <linux/iopoll.h> #include <linux/types.h> #include "fbnic.h" @@ -176,10 +177,25 @@ static void fbnic_mbx_unmap_and_free_msg(struct fbnic_dev *fbd, int mbx_idx, static void fbnic_mbx_clean_desc_ring(struct fbnic_dev *fbd, int mbx_idx) { + u32 flush_done, val; int i; fbnic_mbx_reset_desc_ring(fbd, mbx_idx); + /* Arming the flush only starts it. Wait for the outbound path to + * retire the requests it still holds before the buffers they may + * target are unmapped and freed. A lost link reads back as all ones, + * which ends the poll on the first pass. + */ + flush_done = mbx_idx == FBNIC_IPC_MBX_RX_IDX ? + FBNIC_PUL_USER_IP_LINK_RST_STATUS_AW_FLUSH_DONE : + FBNIC_PUL_USER_IP_LINK_RST_STATUS_AR_FLUSH_DONE; + if (read_poll_timeout_atomic(fbnic_rd32, val, val & flush_done, 2, + 1000, false, fbd, + FBNIC_PUL_USER_IP_LINK_RST_STATUS)) + dev_warn(fbd->dev, "Outbound flush did not complete: %08x\n", + val); + for (i = FBNIC_IPC_MBX_DESC_LEN; i--;) fbnic_mbx_unmap_and_free_msg(fbd, mbx_idx, i); } diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_netdev.c b/drivers/net/ethernet/meta/fbnic/fbnic_netdev.c index 8a6703afca38..52244219d166 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_netdev.c +++ b/drivers/net/ethernet/meta/fbnic/fbnic_netdev.c @@ -86,11 +86,11 @@ static int fbnic_stop(struct net_device *netdev) { struct fbnic_net *fbn = netdev_priv(netdev); + fbnic_down(fbn); + fbnic_mac_free_irq(fbn->fbd); phylink_suspend(fbn->phylink, fbnic_bmc_present(fbn->fbd)); - fbnic_down(fbn); - fbnic_time_stop(fbn); fbnic_fw_xmit_ownership_msg(fbn->fbd, false); diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_pci.c b/drivers/net/ethernet/meta/fbnic/fbnic_pci.c index ad234bb0f75d..09ae797b1f0d 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_pci.c +++ b/drivers/net/ethernet/meta/fbnic/fbnic_pci.c @@ -181,10 +181,15 @@ static int fbnic_fw_config_after_crash(struct fbnic_dev *fbd) return -1; } + /* The rx mode work rewrites the same shadow under the instance lock + * alone, and this runs from the service task under RTNL only. + */ + netdev_lock(fbd->netdev); fbnic_rpc_reset_valid_entries(fbd); netif_addr_lock_bh(fbd->netdev); __fbnic_set_rx_mode(fbd, &fbd->netdev->uc, &fbd->netdev->mc); netif_addr_unlock_bh(fbd->netdev); + netdev_unlock(fbd->netdev); return 0; } @@ -229,18 +234,25 @@ static void fbnic_service_task(struct work_struct *work) fbnic_fw_check_heartbeat(fbd); - fbnic_health_check(fbd); - - fbnic_bmc_rpc_check(fbd); - if (netif_carrier_ok(fbd->netdev)) { netdev_lock(fbd->netdev); fbnic_napi_depletion_check(fbd->netdev); netdev_unlock(fbd->netdev); } - if (netif_running(netdev)) + /* fbnic_service_task_stop() does not wait for a pass that is already + * blocked on RTNL, so one can run after ndo_stop. Leave host state + * alone in that case, and do not re-arm; __fbnic_open() reclaims and + * rebuilds it. The PM path calls ndo_stop with the device detached but + * still running; fbnic_up() starts the task again on resume. + */ + if (netif_running(netdev) && netif_device_present(netdev)) { + fbnic_health_check(fbd); + + fbnic_bmc_rpc_check(fbd); + schedule_delayed_work(&fbd->service_task, HZ); + } rtnl_unlock(); } @@ -453,6 +465,12 @@ static int fbnic_pm_suspend(struct device *dev) netdev_unlock(netdev); rtnl_unlock(); + /* ndo_stop could not wait for a pass already blocked on RTNL. That + * pass no longer re-arms, but wait for it to finish before the + * mailbox, IRQs and MMIO go away. + */ + cancel_delayed_work_sync(&fbd->service_task); + null_uc_addr: fbnic_fw_log_disable(fbd); @@ -553,19 +571,26 @@ static void __fbnic_pm_attach(struct device *dev) struct net_device *netdev = fbd->netdev; struct fbnic_net *fbn; - rtnl_lock(); - fbnic_reset_hw_stats(fbd); - rtnl_unlock(); - if (fbnic_init_failure(fbd)) return; fbn = netdev_priv(netdev); + /* Hold RTNL until the device is attached, so the service task pass + * fbnic_up() schedules cannot run until it will see it present. + */ + rtnl_lock(); + netdev_lock(netdev); + + fbnic_reset_hw_stats(fbd); + if (netif_running(netdev)) fbnic_up(fbn); netif_device_attach(netdev); + + netdev_unlock(netdev); + rtnl_unlock(); } static int __maybe_unused fbnic_pm_resume(struct device *dev) diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c b/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c index 0bcee152d47c..07d4b2e92362 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +++ b/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c @@ -2349,15 +2349,19 @@ void fbnic_disable(struct fbnic_net *fbn) static void fbnic_tx_flush(struct fbnic_dev *fbd) { + u32 drop_ctrl = FBNIC_TMI_DROP_CTRL_EN | FBNIC_TMI_DROP_CTRL_CMPL_DIS; + netdev_warn(fbd->netdev, "triggering Tx flush\n"); - fbnic_rmw32(fbd, FBNIC_TMI_DROP_CTRL, FBNIC_TMI_DROP_CTRL_EN, - FBNIC_TMI_DROP_CTRL_EN); + /* Drop packets and retire their PTP completions */ + fbnic_rmw32(fbd, FBNIC_TMI_DROP_CTRL, drop_ctrl, drop_ctrl); } static void fbnic_tx_flush_off(struct fbnic_dev *fbd) { - fbnic_rmw32(fbd, FBNIC_TMI_DROP_CTRL, FBNIC_TMI_DROP_CTRL_EN, 0); + u32 drop_ctrl = FBNIC_TMI_DROP_CTRL_EN | FBNIC_TMI_DROP_CTRL_CMPL_DIS; + + fbnic_rmw32(fbd, FBNIC_TMI_DROP_CTRL, drop_ctrl, 0); } struct fbnic_idle_regs { diff --git a/drivers/net/ethernet/microsoft/mana/mana_bpf.c b/drivers/net/ethernet/microsoft/mana/mana_bpf.c index 7c55f8724441..494267b3069a 100644 --- a/drivers/net/ethernet/microsoft/mana/mana_bpf.c +++ b/drivers/net/ethernet/microsoft/mana/mana_bpf.c @@ -78,7 +78,8 @@ int mana_xdp_xmit(struct net_device *ndev, int n, struct xdp_frame **frames, } u32 mana_run_xdp(struct net_device *ndev, struct mana_rxq *rxq, - struct xdp_buff *xdp, void *buf_va, uint pkt_len) + struct xdp_buff *xdp, void *buf_va, bool from_pool, + uint pkt_len) { struct mana_stats_rx *rx_stats; struct bpf_prog *prog; @@ -90,7 +91,11 @@ u32 mana_run_xdp(struct net_device *ndev, struct mana_rxq *rxq, if (!prog) goto out; - xdp_init_buff(xdp, PAGE_SIZE, &rxq->xdp_rxq); + /* A redirected buffer is freed by its memory model, so a buffer not + * from the page pool must not claim MEM_TYPE_PAGE_POOL. + */ + xdp_init_buff(xdp, PAGE_SIZE, + from_pool ? &rxq->xdp_rxq : &rxq->xdp_rxq_shared); xdp_prepare_buff(xdp, buf_va, rxq->headroom, pkt_len, true); act = bpf_prog_run_xdp(prog, xdp); diff --git a/drivers/net/ethernet/microsoft/mana/mana_en.c b/drivers/net/ethernet/microsoft/mana/mana_en.c index 5340a7662cd5..7e9223143fc7 100644 --- a/drivers/net/ethernet/microsoft/mana/mana_en.c +++ b/drivers/net/ethernet/microsoft/mana/mana_en.c @@ -2157,7 +2157,7 @@ static void mana_rx_skb(void *buf_va, bool from_pool, return; } - act = mana_run_xdp(ndev, rxq, &xdp, buf_va, pkt_len); + act = mana_run_xdp(ndev, rxq, &xdp, buf_va, from_pool, pkt_len); if (act == XDP_REDIRECT && !rxq->xdp_rc) return; @@ -2179,10 +2179,9 @@ static void mana_rx_skb(void *buf_va, bool from_pool, skb_checksum_none_assert(skb); skb_record_rx_queue(skb, rxq_idx); - if ((ndev->features & NETIF_F_RXCSUM) && cqe->rx_iphdr_csum_succeed) { - if (cqe->rx_tcp_csum_succeed || cqe->rx_udp_csum_succeed) - skb->ip_summed = CHECKSUM_UNNECESSARY; - } + if ((ndev->features & NETIF_F_RXCSUM) && + (cqe->rx_tcp_csum_succeed || cqe->rx_udp_csum_succeed)) + skb->ip_summed = CHECKSUM_UNNECESSARY; if (cqe->rx_hashtype != 0 && (ndev->features & NETIF_F_RXHASH)) { if (cqe->rx_hashtype & MANA_HASH_L4) @@ -2957,6 +2956,9 @@ static void mana_destroy_rxq(struct mana_port_context *apc, if (xdp_rxq_info_is_reg(&rxq->xdp_rxq)) xdp_rxq_info_unreg(&rxq->xdp_rxq); + if (xdp_rxq_info_is_reg(&rxq->xdp_rxq_shared)) + xdp_rxq_info_unreg(&rxq->xdp_rxq_shared); + if (rxq->rxobj != INVALID_MANA_HANDLE) mana_destroy_wq_obj(apc, GDMA_RQ, rxq->rxobj); @@ -3241,6 +3243,12 @@ static struct mana_rxq *mana_create_rxq(struct mana_port_context *apc, WARN_ON(xdp_rxq_info_reg_mem_model(&rxq->xdp_rxq, MEM_TYPE_PAGE_POOL, rxq->page_pool)); + /* The pre-allocated buffers (mana_pre_alloc_rxbufs) are plain pages */ + WARN_ON(xdp_rxq_info_reg(&rxq->xdp_rxq_shared, ndev, rxq_idx, + cq->napi.napi_id)); + WARN_ON(xdp_rxq_info_reg_mem_model(&rxq->xdp_rxq_shared, + MEM_TYPE_PAGE_SHARED, NULL)); + /* Initialize the DIM work before enabling NAPI, so that a poll * cannot reach net_dim() with an uninitialized cq->dim.work. */ diff --git a/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c b/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c index 3014f9c7c3e6..25894771e9e9 100644 --- a/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +++ b/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c @@ -5587,7 +5587,7 @@ static void stmmac_dispatch_skb_zc(struct stmmac_priv *priv, u32 queue, napi_gro_receive(&ch->rxtx_napi, skb); u64_stats_update_begin(&rxq_stats->napi_syncp); - u64_stats_inc(&rxq_stats->napi.rx_pkt_n); + u64_stats_inc(&rxq_stats->napi.rx_packets); u64_stats_add(&rxq_stats->napi.rx_bytes, len); u64_stats_update_end(&rxq_stats->napi_syncp); } diff --git a/drivers/net/ethernet/stmicro/stmmac/stmmac_ptp.c b/drivers/net/ethernet/stmicro/stmmac/stmmac_ptp.c index a37405534beb..31a66e855d6b 100644 --- a/drivers/net/ethernet/stmicro/stmmac/stmmac_ptp.c +++ b/drivers/net/ethernet/stmicro/stmmac/stmmac_ptp.c @@ -277,6 +277,7 @@ const struct ptp_clock_info stmmac_ptp_clock_ops = { .n_per_out = 0, /* will be overwritten in stmmac_ptp_register */ .n_pins = 0, .pps = 0, + .supported_extts_flags = PTP_RISING_EDGE | PTP_STRICT_FLAGS, .adjfine = stmmac_adjust_freq, .adjtime = stmmac_adjust_time, .gettimex64 = stmmac_get_timex, @@ -294,6 +295,7 @@ const struct ptp_clock_info dwmac1000_ptp_clock_ops = { .n_per_out = 0, .n_pins = 0, .pps = 0, + .supported_extts_flags = PTP_RISING_EDGE | PTP_STRICT_FLAGS, .adjfine = stmmac_adjust_freq, .adjtime = stmmac_adjust_time, .gettimex64 = stmmac_get_timex, diff --git a/drivers/net/ethernet/ti/am65-cpts.c b/drivers/net/ethernet/ti/am65-cpts.c index 431a62032ed7..3ce3b2245efb 100644 --- a/drivers/net/ethernet/ti/am65-cpts.c +++ b/drivers/net/ethernet/ti/am65-cpts.c @@ -811,6 +811,28 @@ static struct ptp_clock_info am65_ptp_info = { .do_aux_work = am65_cpts_ts_work, }; +/* The CPTS decodes the message type of an event using the PTPv2 header + * layout. For PTPv1 that nibble is part of versionPTP and always reads 0, + * while am65_skb_get_mtype_seqid() takes the message type from the PTPv1 + * control field. For PTPv1 take the message type from the skb, but keep + * the event type, port number and sequence id of the event so that an + * event only matches a packet of the same direction on the same port. + */ +static u32 am65_cpts_event_mtype_seqid(struct am65_cpts_event *event, + u32 skb_mtype_seqid, + unsigned int ptp_class) +{ + u32 mtype_seqid = event->event1; + + if (ptp_class & PTP_CLASS_V1) { + mtype_seqid &= ~AM65_CPTS_EVENT_1_MESSAGE_TYPE_MASK; + mtype_seqid |= skb_mtype_seqid & + AM65_CPTS_EVENT_1_MESSAGE_TYPE_MASK; + } + + return mtype_seqid; +} + static bool am65_cpts_match_tx_ts(struct am65_cpts *cpts, struct am65_cpts_event *event) { @@ -820,7 +842,6 @@ static bool am65_cpts_match_tx_ts(struct am65_cpts *cpts, bool found = false; u32 mtype_seqid; - mtype_seqid = event->event1; __skb_queue_head_init(&txq_list); spin_lock_irqsave(&cpts->txq.lock, flags); @@ -833,11 +854,9 @@ static bool am65_cpts_match_tx_ts(struct am65_cpts *cpts, struct am65_cpts_skb_cb_data *skb_cb = (struct am65_cpts_skb_cb_data *)skb->cb; - if ((ptp_classify_raw(skb) & PTP_CLASS_V1) && - ((mtype_seqid & AM65_CPTS_EVENT_1_SEQUENCE_ID_MASK) == - (skb_cb->skb_mtype_seqid & AM65_CPTS_EVENT_1_SEQUENCE_ID_MASK))) - mtype_seqid = skb_cb->skb_mtype_seqid; - + mtype_seqid = am65_cpts_event_mtype_seqid(event, + skb_cb->skb_mtype_seqid, + ptp_classify_raw(skb)); if (mtype_seqid == skb_cb->skb_mtype_seqid) { u64 ns = event->timestamp; diff --git a/drivers/net/gtp.c b/drivers/net/gtp.c index 1dd32e979cf5..85d1b0c46ecf 100644 --- a/drivers/net/gtp.c +++ b/drivers/net/gtp.c @@ -561,16 +561,19 @@ static int gtp0_handle_echo_resp(struct gtp_dev *gtp, struct sk_buff *skb) msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC); if (!msg) - return -ENOMEM; + return -1; ret = gtp_genl_fill_echo(msg, 0, 0, 0, GTP_CMD_ECHOREQ, echo); if (ret < 0) { nlmsg_free(msg); - return ret; + return -1; } - return genlmsg_multicast_netns(>p_genl_family, dev_net(gtp->dev), - msg, 0, GTP_GENL_MCGRP, GFP_ATOMIC); + genlmsg_multicast_netns(>p_genl_family, dev_net(gtp->dev), + msg, 0, GTP_GENL_MCGRP, GFP_ATOMIC); + consume_skb(skb); + + return 0; } static int gtp_proto_to_family(__u16 proto) @@ -748,16 +751,19 @@ static int gtp1u_handle_echo_resp(struct gtp_dev *gtp, struct sk_buff *skb) msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC); if (!msg) - return -ENOMEM; + return -1; ret = gtp_genl_fill_echo(msg, 0, 0, 0, GTP_CMD_ECHOREQ, echo); if (ret < 0) { nlmsg_free(msg); - return ret; + return -1; } - return genlmsg_multicast_netns(>p_genl_family, dev_net(gtp->dev), - msg, 0, GTP_GENL_MCGRP, GFP_ATOMIC); + genlmsg_multicast_netns(>p_genl_family, dev_net(gtp->dev), + msg, 0, GTP_GENL_MCGRP, GFP_ATOMIC); + consume_skb(skb); + + return 0; } static int gtp_parse_exthdrs(struct sk_buff *skb, unsigned int *hdrlen) diff --git a/drivers/net/hyperv/rndis_filter.c b/drivers/net/hyperv/rndis_filter.c index 9b6e974c4102..962251327506 100644 --- a/drivers/net/hyperv/rndis_filter.c +++ b/drivers/net/hyperv/rndis_filter.c @@ -401,12 +401,12 @@ static inline void *rndis_get_ppi(struct net_device *ndev, /* Validate ppi_offset and ppi_size */ if (ppi->size > len) { netdev_err(ndev, "Invalid ppi size: %u\n", ppi->size); - continue; + return NULL; } if (ppi->ppi_offset >= ppi->size) { netdev_err(ndev, "Invalid ppi_offset: %u\n", ppi->ppi_offset); - continue; + return NULL; } if (ppi->type == type && ppi->internal == internal) { @@ -414,7 +414,7 @@ static inline void *rndis_get_ppi(struct net_device *ndev, if (ppi->size - ppi->ppi_offset < ppi_size) { netdev_err(ndev, "Invalid ppi: size %u ppi_offset %u\n", ppi->size, ppi->ppi_offset); - continue; + return NULL; } return (void *)((ulong)ppi + ppi->ppi_offset); } diff --git a/drivers/net/ipvlan/ipvlan_core.c b/drivers/net/ipvlan/ipvlan_core.c index 7ad12dc7845c..d2afc2ec896e 100644 --- a/drivers/net/ipvlan/ipvlan_core.c +++ b/drivers/net/ipvlan/ipvlan_core.c @@ -438,7 +438,8 @@ static noinline_for_stack int ipvlan_process_v4_outbound(struct sk_buff *skb) .flowi4_mark = skb->mark, }; - if (!pskb_network_may_pull(skb, sizeof(struct iphdr))) + if (!pskb_network_may_pull(skb, sizeof(struct iphdr)) || + skb_cow_head(skb, 0)) goto err; ip4h = ip_hdr(skb); @@ -504,7 +505,8 @@ static int ipvlan_process_v6_outbound(struct sk_buff *skb) struct net_device *dev = skb->dev; int err, ret = NET_XMIT_DROP; - if (!pskb_network_may_pull(skb, sizeof(struct ipv6hdr))) { + if (!pskb_network_may_pull(skb, sizeof(struct ipv6hdr)) || + skb_cow_head(skb, 0)) { DEV_STATS_INC(dev, tx_errors); kfree_skb(skb); return ret; diff --git a/drivers/net/macsec.c b/drivers/net/macsec.c index 87f3f4bdb026..240ba0ae07d1 100644 --- a/drivers/net/macsec.c +++ b/drivers/net/macsec.c @@ -408,8 +408,10 @@ static bool macsec_validate_skb(struct sk_buff *skb, u16 icv_len, bool xpn) int len = skb->len - 2 * ETH_ALEN; int extra_len = macsec_extra_len(!!(h->tci_an & MACSEC_TCI_SC)) + icv_len; - /* a) It comprises at least 17 octets */ - if (skb->len <= 16) + /* a) It comprises at least 17 octets. The SecTAG and ICV must + * also leave a complete Ethernet header. + */ + if (skb->len < ETH_HLEN + extra_len) return false; /* b) MACsec EtherType: already checked */ @@ -1331,9 +1333,12 @@ drop_direct: nosci: /* 10.6.1 if the SC is not found */ cbit = !!(hdr->tci_an & MACSEC_TCI_C); - if (!cbit) - macsec_finalize_skb(skb, MACSEC_DEFAULT_ICV_LEN, - macsec_extra_len(macsec_skb_cb(skb)->has_sci)); + if (!cbit) { + len = macsec_extra_len(macsec_skb_cb(skb)->has_sci); + if (skb->len < ETH_HLEN + len + MACSEC_DEFAULT_ICV_LEN) + goto drop_nosc; + macsec_finalize_skb(skb, MACSEC_DEFAULT_ICV_LEN, len); + } list_for_each_entry_rcu(macsec, &rxd->secys, secys) { struct sk_buff *nskb; diff --git a/drivers/net/phy/phy-c45.c b/drivers/net/phy/phy-c45.c index 870920311f9a..828af4c4e9d4 100644 --- a/drivers/net/phy/phy-c45.c +++ b/drivers/net/phy/phy-c45.c @@ -104,6 +104,36 @@ int genphy_c45_pma_baset1_setup_master_slave(struct phy_device *phydev) } EXPORT_SYMBOL_GPL(genphy_c45_pma_baset1_setup_master_slave); +/* Type selection value for the BASE-T1 PMA/PMD control register (1.2100, + * 802.3-2022 Table 45-178) matching the forced speed. 10 Mbit/s is ambiguous + * between 10BASE-T1L and 10BASE-T1S, so the supported link modes decide. + * 2.5G, 5G and 10GBASE-T1 are not handled as there are no link modes for them + * yet. + */ +static int genphy_c45_baset1_type_sel(struct phy_device *phydev) +{ + switch (phydev->speed) { + case SPEED_10: + if (linkmode_test_bit(ETHTOOL_LINK_MODE_10baseT1L_Full_BIT, + phydev->supported)) + return MDIO_PMA_PMD_BT1_CTRL_TYPE_SEL_10BT1L; + if (linkmode_test_bit(ETHTOOL_LINK_MODE_10baseT1S_Full_BIT, + phydev->supported) || + linkmode_test_bit(ETHTOOL_LINK_MODE_10baseT1S_Half_BIT, + phydev->supported) || + linkmode_test_bit(ETHTOOL_LINK_MODE_10baseT1S_P2MP_Half_BIT, + phydev->supported)) + return MDIO_PMA_PMD_BT1_CTRL_TYPE_SEL_10BT1S; + return -EINVAL; + case SPEED_100: + return MDIO_PMA_PMD_BT1_CTRL_TYPE_SEL_100BT1; + case SPEED_1000: + return MDIO_PMA_PMD_BT1_CTRL_TYPE_SEL_1000BT1; + default: + return -EINVAL; + } +} + /** * genphy_c45_pma_setup_forced - configures a forced speed * @phydev: target phy_device struct @@ -166,6 +196,16 @@ int genphy_c45_pma_setup_forced(struct phy_device *phydev) return -EINVAL; } + /* Resolve the type before the first write, so a speed without a + * matching type leaves the PHY untouched. + */ + bt1_ctrl = 0; + if (genphy_c45_baset1_able(phydev)) { + bt1_ctrl = genphy_c45_baset1_type_sel(phydev); + if (bt1_ctrl < 0) + return bt1_ctrl; + } + ret = phy_write_mmd(phydev, MDIO_MMD_PMAPMD, MDIO_CTRL1, ctrl1); if (ret < 0) return ret; @@ -179,12 +219,8 @@ int genphy_c45_pma_setup_forced(struct phy_device *phydev) if (ret < 0) return ret; - bt1_ctrl = 0; - if (phydev->speed == SPEED_1000) - bt1_ctrl = MDIO_PMA_PMD_BT1_CTRL_STRAP_B1000; - ret = phy_modify_mmd(phydev, MDIO_MMD_PMAPMD, MDIO_PMA_PMD_BT1_CTRL, - MDIO_PMA_PMD_BT1_CTRL_STRAP, bt1_ctrl); + MDIO_PMA_PMD_BT1_CTRL_TYPE_SEL, bt1_ctrl); if (ret < 0) return ret; } diff --git a/drivers/net/team/team_core.c b/drivers/net/team/team_core.c index 957cc7885d2f..cfb833c307c1 100644 --- a/drivers/net/team/team_core.c +++ b/drivers/net/team/team_core.c @@ -1365,11 +1365,8 @@ static int team_port_add(struct team *team, struct net_device *port_dev, /* set allmulti level to new slave */ if (dev->flags & IFF_ALLMULTI) { err = dev_set_allmulti(port_dev, 1); - if (err) { - if (dev->flags & IFF_PROMISC) - dev_set_promiscuity(port_dev, -1); + if (err) goto err_set_slave_allmulti; - } } err = team_dev_type_check_change(dev, port_dev); @@ -1397,7 +1394,11 @@ static int team_port_add(struct team *team, struct net_device *port_dev, return 0; err_set_dev_type: + if (dev->flags & IFF_ALLMULTI) + dev_set_allmulti(port_dev, -1); err_set_slave_allmulti: + if (dev->flags & IFF_PROMISC) + dev_set_promiscuity(port_dev, -1); err_set_slave_promisc: __team_option_inst_del_port(team, port); diff --git a/drivers/net/tun.c b/drivers/net/tun.c index dcec7311e601..86fd44e10755 100644 --- a/drivers/net/tun.c +++ b/drivers/net/tun.c @@ -615,7 +615,7 @@ static void __tun_detach(struct tun_file *tfile, bool clean) } synchronize_net(); - tun_flow_delete_by_queue(tun, tun->numqueues + 1); + tun_flow_delete_by_queue(tun, tun->numqueues); /* Drop read queue */ tun_queue_purge(tfile); spin_lock_bh(&ntfile->tx_ring.consumer_lock); @@ -1500,6 +1500,12 @@ static struct sk_buff *tun_napi_alloc_frags(struct tun_file *tfile, if (!skb) return ERR_PTR(-ENOMEM); + /* An skb recycled by napi_reuse_skb() keeps the protocol of a + * previous frame. eth_type_trans() sets it after the virtio + * header checks, which must not see a stale one. + */ + skb->protocol = 0; + linear = iov_iter_single_seg_count(it); err = __skb_grow(skb, linear); if (err) @@ -1944,7 +1950,8 @@ static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile, break; } - if (tun_vnet_hdr_tnl_to_skb(tun->flags, features, skb, &hdr)) { + if (tun_vnet_hdr_tnl_to_skb(tun->flags, features, skb, &hdr, + (tun->flags & TUN_TYPE_MASK) == IFF_TAP)) { atomic_long_inc(&tun->rx_frame_errors); err = -EINVAL; goto free_skb; @@ -2621,7 +2628,11 @@ build: tnl_hdr = (struct virtio_net_hdr_v1_hash_tunnel *)gso; skb->dev = tun->dev; skb_set_network_header(skb, ETH_HLEN); - if (tun_vnet_hdr_tnl_to_skb(tun->flags, features, skb, tnl_hdr)) { + /* Frames always start with an Ethernet header here, as the + * eth_type_trans() call below expects. + */ + if (tun_vnet_hdr_tnl_to_skb(tun->flags, features, skb, tnl_hdr, + true)) { atomic_long_inc(&tun->rx_frame_errors); kfree_skb(skb); ret = -EINVAL; @@ -3362,6 +3373,10 @@ static long __tun_chr_ioctl(struct file *file, unsigned int cmd, netif_info(tun, drv, tun->dev, "Linktype set failed because interface is up\n"); ret = -EBUSY; + } else if ((unsigned short)arg == ARPHRD_IEEE802154 || + (unsigned short)arg == ARPHRD_IEEE802154_MONITOR || + (unsigned short)arg == ARPHRD_6LOWPAN) { + ret = -EINVAL; } else { ret = call_netdevice_notifiers(NETDEV_PRE_TYPE_CHANGE, tun->dev); diff --git a/drivers/net/tun_vnet.h b/drivers/net/tun_vnet.h index f4c652b1fa44..3364e08dd6e0 100644 --- a/drivers/net/tun_vnet.h +++ b/drivers/net/tun_vnet.h @@ -197,9 +197,10 @@ static inline netdev_features_t tun_vnet_hdr_guest_features(int vnet_hdr_sz) static inline int tun_vnet_hdr_tnl_to_skb(unsigned int flags, netdev_features_t features, struct sk_buff *skb, - const struct virtio_net_hdr_v1_hash_tunnel *hdr) + const struct virtio_net_hdr_v1_hash_tunnel *hdr, + bool has_eth) { - return virtio_net_hdr_tnl_to_skb(skb, hdr, + return virtio_net_hdr_tnl_to_skb(skb, hdr, has_eth, features & NETIF_F_GSO_UDP_TUNNEL, features & NETIF_F_GSO_UDP_TUNNEL_CSUM, tun_vnet_is_little_endian(flags)); diff --git a/drivers/net/usb/cdc_ncm.c b/drivers/net/usb/cdc_ncm.c index 19db5a668dcb..e92dc7f011ea 100644 --- a/drivers/net/usb/cdc_ncm.c +++ b/drivers/net/usb/cdc_ncm.c @@ -1125,7 +1125,7 @@ static struct usb_cdc_ncm_ndp16 *cdc_ncm_ndp16(struct cdc_ncm_ctx *ctx, struct s cdc_ncm_align_tail(skb, ctx->tx_ndp_modulus, 0, ctx->tx_curr_size); /* verify that there is room for the NDP and the datagram (reserve) */ - if ((ctx->tx_curr_size - skb->len - reserve) < ctx->max_ndp_size) + if (skb->len + reserve + ctx->max_ndp_size > ctx->tx_curr_size) return NULL; /* link to it */ @@ -1180,7 +1180,7 @@ static struct usb_cdc_ncm_ndp32 *cdc_ncm_ndp32(struct cdc_ncm_ctx *ctx, struct s cdc_ncm_align_tail(skb, ctx->tx_ndp_modulus, 0, ctx->tx_curr_size); /* verify that there is room for the NDP and the datagram (reserve) */ - if ((ctx->tx_curr_size - skb->len - reserve) < ctx->max_ndp_size) + if (skb->len + reserve + ctx->max_ndp_size > ctx->tx_curr_size) return NULL; /* link to it */ diff --git a/drivers/net/usb/lan78xx.c b/drivers/net/usb/lan78xx.c index aa0613f4bd68..f7126d802b4b 100644 --- a/drivers/net/usb/lan78xx.c +++ b/drivers/net/usb/lan78xx.c @@ -4593,13 +4593,12 @@ static void lan78xx_disconnect(struct usb_interface *intf) net = dev->net; + unregister_netdev(net); + rtnl_lock(); - phylink_stop(dev->phylink); phylink_disconnect_phy(dev->phylink); rtnl_unlock(); - unregister_netdev(net); - timer_shutdown_sync(&dev->stat_monitor); set_bit(EVENT_DEV_DISCONNECT, &dev->flags); cancel_delayed_work_sync(&dev->wq); @@ -5371,6 +5370,12 @@ static int lan78xx_resume(struct usb_interface *intf) out: mutex_unlock(&dev->dev_mutex); + if (!ret && dev_open) { + rtnl_lock(); + phylink_resume(dev->phylink); + rtnl_unlock(); + } + return ret; } @@ -5385,15 +5390,7 @@ static int lan78xx_reset_resume(struct usb_interface *intf) if (ret < 0) return ret; - ret = lan78xx_resume(intf); - if (ret < 0) - return ret; - - rtnl_lock(); - phylink_resume(dev->phylink); - rtnl_unlock(); - - return 0; + return lan78xx_resume(intf); } static const struct usb_device_id products[] = { diff --git a/drivers/net/virtio_net.c b/drivers/net/virtio_net.c index dd2c41ef6fbe..ed20e76fbc4c 100644 --- a/drivers/net/virtio_net.c +++ b/drivers/net/virtio_net.c @@ -2533,7 +2533,7 @@ static void virtnet_receive_done(struct virtnet_info *vi, struct receive_queue * skb->dev = dev; skb_set_network_header(skb, ETH_HLEN); - if (virtio_net_hdr_tnl_to_skb(skb, &hdr->tnl_hdr, vi->rx_tnl, + if (virtio_net_hdr_tnl_to_skb(skb, &hdr->tnl_hdr, true, vi->rx_tnl, vi->rx_tnl_csum, virtio_is_little_endian(vi->vdev))) { net_warn_ratelimited("%s: bad gso: type: %x, size: %u, flags %x tunnel %d tnl csum %d\n", diff --git a/drivers/net/wireless/ath/ath10k/core.c b/drivers/net/wireless/ath/ath10k/core.c index 7c2939cbde5f..a749ae582b0a 100644 --- a/drivers/net/wireless/ath/ath10k/core.c +++ b/drivers/net/wireless/ath/ath10k/core.c @@ -2985,6 +2985,7 @@ int ath10k_core_start(struct ath10k *ar, enum ath10k_firmware_mode mode, clear_bit(ATH10K_FLAG_CRASH_FLUSH, &ar->dev_flags); ar->running_fw = fw; + ar->thermal.broken = false; if (!test_bit(ATH10K_FW_FEATURE_NON_BMI, ar->running_fw->fw_file.fw_features)) { diff --git a/drivers/net/wireless/ath/ath10k/thermal.c b/drivers/net/wireless/ath/ath10k/thermal.c index 9bb486f8e920..9ff7de0abd12 100644 --- a/drivers/net/wireless/ath/ath10k/thermal.c +++ b/drivers/net/wireless/ath/ath10k/thermal.c @@ -75,6 +75,12 @@ static ssize_t ath10k_thermal_show_temp(struct device *dev, goto out; } + /* Don't stall every read on firmware that never answers */ + if (ar->thermal.broken) { + ret = -EOPNOTSUPP; + goto out; + } + reinit_completion(&ar->thermal.wmi_sync); ret = ath10k_wmi_pdev_get_temperature(ar); if (ret) { @@ -90,7 +96,8 @@ static ssize_t ath10k_thermal_show_temp(struct device *dev, time_left = wait_for_completion_timeout(&ar->thermal.wmi_sync, ATH10K_THERMAL_SYNC_TIMEOUT_HZ); if (!time_left) { - ath10k_warn(ar, "failed to synchronize thermal read\n"); + ath10k_warn(ar, "failed to synchronize thermal read, not asking again until the firmware restarts\n"); + ar->thermal.broken = true; ret = -ETIMEDOUT; goto out; } diff --git a/drivers/net/wireless/ath/ath10k/thermal.h b/drivers/net/wireless/ath/ath10k/thermal.h index 1f4de9fbf2b3..d1fb5b958c37 100644 --- a/drivers/net/wireless/ath/ath10k/thermal.h +++ b/drivers/net/wireless/ath/ath10k/thermal.h @@ -19,6 +19,8 @@ struct ath10k_thermal { /* protected by conf_mutex */ u32 throttle_state; u32 quiet_period; + /* the running firmware did not answer a temperature request */ + bool broken; /* temperature value in Celsius degree * protected by data_lock */ diff --git a/drivers/net/wireless/ath/ath12k/ahb.c b/drivers/net/wireless/ath/ath12k/ahb.c index 2c55aae06dd0..e5bbfca2b2ac 100644 --- a/drivers/net/wireless/ath/ath12k/ahb.c +++ b/drivers/net/wireless/ath/ath12k/ahb.c @@ -602,8 +602,8 @@ static int ath12k_ahb_ext_grp_napi_poll(struct napi_struct *napi, int budget) work_done = ath12k_dp_service_srng(dp, irq_grp, budget); if (work_done < budget) { - napi_complete_done(napi, work_done); - ath12k_ahb_ext_grp_enable(irq_grp); + if (likely(napi_complete_done(napi, work_done))) + ath12k_ahb_ext_grp_enable(irq_grp); } if (work_done > budget) @@ -619,9 +619,10 @@ static irqreturn_t ath12k_ahb_ext_interrupt_handler(int irq, void *arg) /* last interrupt received for this group */ irq_grp->timestamp = jiffies; - ath12k_ahb_ext_grp_disable(irq_grp); - - napi_schedule(&irq_grp->napi); + if (napi_schedule_prep(&irq_grp->napi)) { + ath12k_ahb_ext_grp_disable(irq_grp); + __napi_schedule(&irq_grp->napi); + } return IRQ_HANDLED; } diff --git a/drivers/net/wireless/ath/ath12k/core.c b/drivers/net/wireless/ath/ath12k/core.c index 25987bc58556..353fb9c5a69d 100644 --- a/drivers/net/wireless/ath/ath12k/core.c +++ b/drivers/net/wireless/ath/ath12k/core.c @@ -2062,7 +2062,8 @@ exit: goto invalid_group; } - ab->device_id = ag->num_probed++; + ag->num_probed++; + ab->device_id = wsi->index; ag->ab[ab->device_id] = ab; ab->ag = ag; diff --git a/drivers/net/wireless/ath/ath12k/dp_mon.c b/drivers/net/wireless/ath/ath12k/dp_mon.c index 709507d44d8e..ae14e118fe36 100644 --- a/drivers/net/wireless/ath/ath12k/dp_mon.c +++ b/drivers/net/wireless/ath/ath12k/dp_mon.c @@ -186,7 +186,7 @@ ath12k_dp_mon_fill_rx_rate(struct ath12k_pdev_dp *dp_pdev, } static void ath12k_dp_mon_rx_msdus_set_payload(struct ath12k_base *ab, - struct sk_buff *head_msdu, + struct sk_buff *msdu, struct sk_buff *tail_msdu) { u32 rx_pkt_offset, l2_hdr_offset, total_offset; @@ -200,7 +200,7 @@ static void ath12k_dp_mon_rx_msdus_set_payload(struct ath12k_base *ab, else total_offset = rx_pkt_offset + l2_hdr_offset; - skb_pull(head_msdu, total_offset); + skb_pull(msdu, total_offset); } struct sk_buff * @@ -261,7 +261,7 @@ ath12k_dp_mon_rx_merg_msdus(struct ath12k_pdev_dp *dp_pdev, head_frag_list = NULL; while (msdu) { - ath12k_dp_mon_rx_msdus_set_payload(ab, head_msdu, tail_msdu); + ath12k_dp_mon_rx_msdus_set_payload(ab, msdu, tail_msdu); if (!head_frag_list) head_frag_list = msdu; @@ -296,7 +296,7 @@ ath12k_dp_mon_rx_merg_msdus(struct ath12k_pdev_dp *dp_pdev, msdu = head_msdu; while (msdu) { - ath12k_dp_mon_rx_msdus_set_payload(ab, head_msdu, tail_msdu); + ath12k_dp_mon_rx_msdus_set_payload(ab, msdu, tail_msdu); if (qos_pkt) { dest = skb_push(msdu, sizeof(__le16)); if (!dest) diff --git a/drivers/net/wireless/ath/ath12k/mac.c b/drivers/net/wireless/ath/ath12k/mac.c index 01f8c6572f65..7872e7cb3c06 100644 --- a/drivers/net/wireless/ath/ath12k/mac.c +++ b/drivers/net/wireless/ath/ath12k/mac.c @@ -3366,6 +3366,7 @@ static void ath12k_peer_assoc_h_eht(struct ath12k *ar, u32 *rx_mcs, *tx_mcs; u16 *eht_mcs_mask; u8 max_nss = 0; + u8 mcs15; lockdep_assert_wiphy(ath12k_ar_to_hw(ar)->wiphy); @@ -3416,6 +3417,16 @@ static void ath12k_peer_assoc_h_eht(struct ath12k *ar, memcpy(arg->peer_eht_cap_phy, eht_cap->eht_cap_elem.phy_cap_info, sizeof(eht_cap->eht_cap_elem.phy_cap_info)); + /* + * Firmware rate control enables EHT-MCS15 based only on the peer's + * MCS15 support bits, so keep only the ones we support ourselves. + */ + mcs15 = u8_get_bits(eht_cap->eht_cap_elem.phy_cap_info[6] & + own_eht_cap->eht_cap_elem.phy_cap_info[6], + IEEE80211_EHT_PHY_CAP6_MCS15_SUPP_MASK); + u8p_replace_bits(&((u8 *)arg->peer_eht_cap_phy)[6], mcs15, + IEEE80211_EHT_PHY_CAP6_MCS15_SUPP_MASK); + rx_mcs = arg->peer_eht_rx_mcs_set; tx_mcs = arg->peer_eht_tx_mcs_set; @@ -7845,7 +7856,7 @@ int ath12k_mac_op_sta_state(struct ieee80211_hw *hw, ath12k_hw_warn(ah, "failed to verify assoc link setting with link id %u\n", link_id); ret = -EINVAL; - goto exit; + goto free_unassign_link; } arsta->is_assoc_link = true; @@ -7903,7 +7914,7 @@ int ath12k_mac_op_sta_state(struct ieee80211_hw *hw, if (old_state == IEEE80211_STA_NOTEXIST && new_state == IEEE80211_STA_NONE) - goto peer_delete; + goto free_unassign_link; else goto exit; } @@ -7943,6 +7954,8 @@ int ath12k_mac_op_sta_state(struct ieee80211_hw *hw, ret = 0; goto exit; +free_unassign_link: + ath12k_mac_free_unassign_link_sta(ah, ahsta, link_id); peer_delete: ath12k_dp_peer_delete(&ah->dp_hw, sta->addr, sta); ml_peer_id_clear: diff --git a/drivers/net/wireless/ath/ath12k/wifi7/hal_qcc2072.c b/drivers/net/wireless/ath/ath12k/wifi7/hal_qcc2072.c index 7cf00fda996f..7ea7559e882c 100644 --- a/drivers/net/wireless/ath/ath12k/wifi7/hal_qcc2072.c +++ b/drivers/net/wireless/ath/ath12k/wifi7/hal_qcc2072.c @@ -402,32 +402,32 @@ static void ath12k_hal_extract_rx_desc_data_qcc2072(struct hal_rx_desc_data *rx_ rx_desc_data->is_last_msdu = ath12k_hal_rx_desc_get_last_msdu_qcc2072(ldesc); rx_desc_data->l3_pad_bytes = ath12k_hal_rx_desc_get_l3_pad_bytes_qcc2072(ldesc); rx_desc_data->enctype = ath12k_hal_rx_desc_get_encrypt_type_qcc2072(rx_desc); - rx_desc_data->decap_type = ath12k_hal_rx_desc_get_decap_type_qcc2072(rx_desc); + rx_desc_data->decap_type = ath12k_hal_rx_desc_get_decap_type_qcc2072(ldesc); rx_desc_data->mesh_ctrl_present = - ath12k_hal_rx_desc_get_mesh_ctl_qcc2072(rx_desc); + ath12k_hal_rx_desc_get_mesh_ctl_qcc2072(ldesc); rx_desc_data->seq_ctl_valid = ath12k_hal_rx_desc_get_mpdu_seq_ctl_vld_qcc2072(rx_desc); rx_desc_data->fc_valid = ath12k_hal_rx_desc_get_mpdu_fc_valid_qcc2072(rx_desc); rx_desc_data->seq_no = ath12k_hal_rx_desc_get_mpdu_start_seq_no_qcc2072(rx_desc); rx_desc_data->msdu_len = ath12k_hal_rx_desc_get_msdu_len_qcc2072(ldesc); - rx_desc_data->sgi = ath12k_hal_rx_desc_get_msdu_sgi_qcc2072(rx_desc); - rx_desc_data->is_from_ds = ath12k_wifi7_hal_rx_h_from_ds_qcc2072(rx_desc); - rx_desc_data->is_to_ds = ath12k_wifi7_hal_rx_h_to_ds_qcc2072(rx_desc); - rx_desc_data->rate_mcs = ath12k_hal_rx_desc_get_msdu_rate_mcs_qcc2072(rx_desc); - rx_desc_data->bw = ath12k_hal_rx_desc_get_msdu_rx_bw_qcc2072(rx_desc); - rx_desc_data->phy_meta_data = ath12k_hal_rx_desc_get_msdu_freq_qcc2072(rx_desc); - rx_desc_data->pkt_type = ath12k_hal_rx_desc_get_msdu_pkt_type_qcc2072(rx_desc); - rx_desc_data->nss = hweight8(ath12k_hal_rx_desc_get_msdu_nss_qcc2072(rx_desc)); + rx_desc_data->sgi = ath12k_hal_rx_desc_get_msdu_sgi_qcc2072(ldesc); + rx_desc_data->is_from_ds = ath12k_wifi7_hal_rx_h_from_ds_qcc2072(ldesc); + rx_desc_data->is_to_ds = ath12k_wifi7_hal_rx_h_to_ds_qcc2072(ldesc); + rx_desc_data->rate_mcs = ath12k_hal_rx_desc_get_msdu_rate_mcs_qcc2072(ldesc); + rx_desc_data->bw = ath12k_hal_rx_desc_get_msdu_rx_bw_qcc2072(ldesc); + rx_desc_data->phy_meta_data = ath12k_hal_rx_desc_get_msdu_freq_qcc2072(ldesc); + rx_desc_data->pkt_type = ath12k_hal_rx_desc_get_msdu_pkt_type_qcc2072(ldesc); + rx_desc_data->nss = hweight8(ath12k_hal_rx_desc_get_msdu_nss_qcc2072(ldesc)); rx_desc_data->tid = ath12k_hal_rx_desc_get_mpdu_tid_qcc2072(rx_desc); rx_desc_data->peer_id = ath12k_hal_rx_desc_get_mpdu_peer_id_qcc2072(rx_desc); rx_desc_data->addr2_present = ath12k_hal_rx_desc_mac_addr2_valid_qcc2072(rx_desc); rx_desc_data->addr2 = ath12k_hal_rx_desc_mpdu_start_addr2_qcc2072(rx_desc); - rx_desc_data->is_mcbc = ath12k_hal_rx_desc_is_da_mcbc_qcc2072(rx_desc); + rx_desc_data->is_mcbc = ath12k_hal_rx_desc_is_da_mcbc_qcc2072(ldesc); rx_desc_data->msdu_done = ath12k_hal_rx_h_msdu_done_qcc2072(ldesc); - rx_desc_data->l4_csum_fail = ath12k_hal_rx_h_l4_cksum_fail_qcc2072(rx_desc); - rx_desc_data->ip_csum_fail = ath12k_hal_rx_h_ip_cksum_fail_qcc2072(rx_desc); - rx_desc_data->is_decrypted = ath12k_hal_rx_h_is_decrypted_qcc2072(rx_desc); - rx_desc_data->err_bitmap = ath12k_hal_rx_h_mpdu_err_qcc2072(rx_desc); + rx_desc_data->l4_csum_fail = ath12k_hal_rx_h_l4_cksum_fail_qcc2072(ldesc); + rx_desc_data->ip_csum_fail = ath12k_hal_rx_h_ip_cksum_fail_qcc2072(ldesc); + rx_desc_data->is_decrypted = ath12k_hal_rx_h_is_decrypted_qcc2072(ldesc); + rx_desc_data->err_bitmap = ath12k_hal_rx_h_mpdu_err_qcc2072(ldesc); } static int ath12k_hal_srng_create_config_qcc2072(struct ath12k_hal *hal) diff --git a/drivers/net/wireless/ath/ath12k/wifi7/hal_qcn9274.c b/drivers/net/wireless/ath/ath12k/wifi7/hal_qcn9274.c index 052b59265af8..355cf50d2785 100644 --- a/drivers/net/wireless/ath/ath12k/wifi7/hal_qcn9274.c +++ b/drivers/net/wireless/ath/ath12k/wifi7/hal_qcn9274.c @@ -922,32 +922,32 @@ void ath12k_hal_extract_rx_desc_data_qcn9274(struct hal_rx_desc_data *rx_desc_da rx_desc_data->is_last_msdu = ath12k_hal_rx_desc_get_last_msdu_qcn9274(ldesc); rx_desc_data->l3_pad_bytes = ath12k_hal_rx_desc_get_l3_pad_bytes_qcn9274(ldesc); rx_desc_data->enctype = ath12k_hal_rx_desc_get_encrypt_type_qcn9274(rx_desc); - rx_desc_data->decap_type = ath12k_hal_rx_desc_get_decap_type_qcn9274(rx_desc); + rx_desc_data->decap_type = ath12k_hal_rx_desc_get_decap_type_qcn9274(ldesc); rx_desc_data->mesh_ctrl_present = - ath12k_hal_rx_desc_get_mesh_ctl_qcn9274(rx_desc); + ath12k_hal_rx_desc_get_mesh_ctl_qcn9274(ldesc); rx_desc_data->seq_ctl_valid = ath12k_hal_rx_desc_get_mpdu_seq_ctl_vld_qcn9274(rx_desc); rx_desc_data->fc_valid = ath12k_hal_rx_desc_get_mpdu_fc_valid_qcn9274(rx_desc); - rx_desc_data->is_from_ds = ath12k_wifi7_hal_rx_h_from_ds_qcn9274(rx_desc); - rx_desc_data->is_to_ds = ath12k_wifi7_hal_rx_h_to_ds_qcn9274(rx_desc); + rx_desc_data->is_from_ds = ath12k_wifi7_hal_rx_h_from_ds_qcn9274(ldesc); + rx_desc_data->is_to_ds = ath12k_wifi7_hal_rx_h_to_ds_qcn9274(ldesc); rx_desc_data->seq_no = ath12k_hal_rx_desc_get_mpdu_start_seq_no_qcn9274(rx_desc); rx_desc_data->msdu_len = ath12k_hal_rx_desc_get_msdu_len_qcn9274(ldesc); - rx_desc_data->sgi = ath12k_hal_rx_desc_get_msdu_sgi_qcn9274(rx_desc); - rx_desc_data->rate_mcs = ath12k_hal_rx_desc_get_msdu_rate_mcs_qcn9274(rx_desc); - rx_desc_data->bw = ath12k_hal_rx_desc_get_msdu_rx_bw_qcn9274(rx_desc); - rx_desc_data->phy_meta_data = ath12k_hal_rx_desc_get_msdu_freq_qcn9274(rx_desc); - rx_desc_data->pkt_type = ath12k_hal_rx_desc_get_msdu_pkt_type_qcn9274(rx_desc); - rx_desc_data->nss = hweight8(ath12k_hal_rx_desc_get_msdu_nss_qcn9274(rx_desc)); - rx_desc_data->tid = ath12k_hal_rx_desc_get_mpdu_tid_qcn9274(rx_desc); + rx_desc_data->sgi = ath12k_hal_rx_desc_get_msdu_sgi_qcn9274(ldesc); + rx_desc_data->rate_mcs = ath12k_hal_rx_desc_get_msdu_rate_mcs_qcn9274(ldesc); + rx_desc_data->bw = ath12k_hal_rx_desc_get_msdu_rx_bw_qcn9274(ldesc); + rx_desc_data->phy_meta_data = ath12k_hal_rx_desc_get_msdu_freq_qcn9274(ldesc); + rx_desc_data->pkt_type = ath12k_hal_rx_desc_get_msdu_pkt_type_qcn9274(ldesc); + rx_desc_data->nss = hweight8(ath12k_hal_rx_desc_get_msdu_nss_qcn9274(ldesc)); + rx_desc_data->tid = ath12k_hal_rx_desc_get_mpdu_tid_qcn9274(ldesc); rx_desc_data->peer_id = ath12k_hal_rx_desc_get_mpdu_peer_id_qcn9274(rx_desc); rx_desc_data->addr2_present = ath12k_hal_rx_desc_mac_addr2_valid_qcn9274(rx_desc); rx_desc_data->addr2 = ath12k_hal_rx_desc_mpdu_start_addr2_qcn9274(rx_desc); - rx_desc_data->is_mcbc = ath12k_hal_rx_desc_is_da_mcbc_qcn9274(rx_desc); + rx_desc_data->is_mcbc = ath12k_hal_rx_desc_is_da_mcbc_qcn9274(ldesc); rx_desc_data->msdu_done = ath12k_hal_rx_h_msdu_done_qcn9274(ldesc); - rx_desc_data->l4_csum_fail = ath12k_hal_rx_h_l4_cksum_fail_qcn9274(rx_desc); - rx_desc_data->ip_csum_fail = ath12k_hal_rx_h_ip_cksum_fail_qcn9274(rx_desc); - rx_desc_data->is_decrypted = ath12k_hal_rx_h_is_decrypted_qcn9274(rx_desc); - rx_desc_data->err_bitmap = ath12k_hal_rx_h_mpdu_err_qcn9274(rx_desc); + rx_desc_data->l4_csum_fail = ath12k_hal_rx_h_l4_cksum_fail_qcn9274(ldesc); + rx_desc_data->ip_csum_fail = ath12k_hal_rx_h_ip_cksum_fail_qcn9274(ldesc); + rx_desc_data->is_decrypted = ath12k_hal_rx_h_is_decrypted_qcn9274(ldesc); + rx_desc_data->err_bitmap = ath12k_hal_rx_h_mpdu_err_qcn9274(ldesc); } static u16 ath12k_hal_reo_status_dec_tlv_hdr_qcn9274(void *tlv, void **desc) diff --git a/drivers/net/wireless/ath/ath12k/wifi7/hal_wcn7850.c b/drivers/net/wireless/ath/ath12k/wifi7/hal_wcn7850.c index 61be8443e46e..abe982faeb2b 100644 --- a/drivers/net/wireless/ath/ath12k/wifi7/hal_wcn7850.c +++ b/drivers/net/wireless/ath/ath12k/wifi7/hal_wcn7850.c @@ -604,32 +604,32 @@ void ath12k_hal_extract_rx_desc_data_wcn7850(struct hal_rx_desc_data *rx_desc_da rx_desc_data->is_last_msdu = ath12k_hal_rx_desc_get_last_msdu_wcn7850(ldesc); rx_desc_data->l3_pad_bytes = ath12k_hal_rx_desc_get_l3_pad_bytes_wcn7850(ldesc); rx_desc_data->enctype = ath12k_hal_rx_desc_get_encrypt_type_wcn7850(rx_desc); - rx_desc_data->decap_type = ath12k_hal_rx_desc_get_decap_type_wcn7850(rx_desc); + rx_desc_data->decap_type = ath12k_hal_rx_desc_get_decap_type_wcn7850(ldesc); rx_desc_data->mesh_ctrl_present = - ath12k_hal_rx_desc_get_mesh_ctl_wcn7850(rx_desc); + ath12k_hal_rx_desc_get_mesh_ctl_wcn7850(ldesc); rx_desc_data->seq_ctl_valid = ath12k_hal_rx_desc_get_mpdu_seq_ctl_vld_wcn7850(rx_desc); rx_desc_data->fc_valid = ath12k_hal_rx_desc_get_mpdu_fc_valid_wcn7850(rx_desc); rx_desc_data->seq_no = ath12k_hal_rx_desc_get_mpdu_start_seq_no_wcn7850(rx_desc); rx_desc_data->msdu_len = ath12k_hal_rx_desc_get_msdu_len_wcn7850(ldesc); - rx_desc_data->sgi = ath12k_hal_rx_desc_get_msdu_sgi_wcn7850(rx_desc); - rx_desc_data->is_from_ds = ath12k_wifi7_hal_rx_h_from_ds_wcn7850(rx_desc); - rx_desc_data->is_to_ds = ath12k_wifi7_hal_rx_h_to_ds_wcn7850(rx_desc); - rx_desc_data->rate_mcs = ath12k_hal_rx_desc_get_msdu_rate_mcs_wcn7850(rx_desc); - rx_desc_data->bw = ath12k_hal_rx_desc_get_msdu_rx_bw_wcn7850(rx_desc); - rx_desc_data->phy_meta_data = ath12k_hal_rx_desc_get_msdu_freq_wcn7850(rx_desc); - rx_desc_data->pkt_type = ath12k_hal_rx_desc_get_msdu_pkt_type_wcn7850(rx_desc); - rx_desc_data->nss = hweight8(ath12k_hal_rx_desc_get_msdu_nss_wcn7850(rx_desc)); + rx_desc_data->sgi = ath12k_hal_rx_desc_get_msdu_sgi_wcn7850(ldesc); + rx_desc_data->is_from_ds = ath12k_wifi7_hal_rx_h_from_ds_wcn7850(ldesc); + rx_desc_data->is_to_ds = ath12k_wifi7_hal_rx_h_to_ds_wcn7850(ldesc); + rx_desc_data->rate_mcs = ath12k_hal_rx_desc_get_msdu_rate_mcs_wcn7850(ldesc); + rx_desc_data->bw = ath12k_hal_rx_desc_get_msdu_rx_bw_wcn7850(ldesc); + rx_desc_data->phy_meta_data = ath12k_hal_rx_desc_get_msdu_freq_wcn7850(ldesc); + rx_desc_data->pkt_type = ath12k_hal_rx_desc_get_msdu_pkt_type_wcn7850(ldesc); + rx_desc_data->nss = hweight8(ath12k_hal_rx_desc_get_msdu_nss_wcn7850(ldesc)); rx_desc_data->tid = ath12k_hal_rx_desc_get_mpdu_tid_wcn7850(rx_desc); rx_desc_data->peer_id = ath12k_hal_rx_desc_get_mpdu_peer_id_wcn7850(rx_desc); rx_desc_data->addr2_present = ath12k_hal_rx_desc_mac_addr2_valid_wcn7850(rx_desc); rx_desc_data->addr2 = ath12k_hal_rx_desc_mpdu_start_addr2_wcn7850(rx_desc); - rx_desc_data->is_mcbc = ath12k_hal_rx_desc_is_da_mcbc_wcn7850(rx_desc); + rx_desc_data->is_mcbc = ath12k_hal_rx_desc_is_da_mcbc_wcn7850(ldesc); rx_desc_data->msdu_done = ath12k_hal_rx_h_msdu_done_wcn7850(ldesc); - rx_desc_data->l4_csum_fail = ath12k_hal_rx_h_l4_cksum_fail_wcn7850(rx_desc); - rx_desc_data->ip_csum_fail = ath12k_hal_rx_h_ip_cksum_fail_wcn7850(rx_desc); - rx_desc_data->is_decrypted = ath12k_hal_rx_h_is_decrypted_wcn7850(rx_desc); - rx_desc_data->err_bitmap = ath12k_hal_rx_h_mpdu_err_wcn7850(rx_desc); + rx_desc_data->l4_csum_fail = ath12k_hal_rx_h_l4_cksum_fail_wcn7850(ldesc); + rx_desc_data->ip_csum_fail = ath12k_hal_rx_h_ip_cksum_fail_wcn7850(ldesc); + rx_desc_data->is_decrypted = ath12k_hal_rx_h_is_decrypted_wcn7850(ldesc); + rx_desc_data->err_bitmap = ath12k_hal_rx_h_mpdu_err_wcn7850(ldesc); } int ath12k_hal_srng_create_config_wcn7850(struct ath12k_hal *hal) diff --git a/drivers/net/wireless/ath/ath9k/htc_drv_main.c b/drivers/net/wireless/ath/ath9k/htc_drv_main.c index 0d6272ac0dac..6578114a4019 100644 --- a/drivers/net/wireless/ath/ath9k/htc_drv_main.c +++ b/drivers/net/wireless/ath/ath9k/htc_drv_main.c @@ -1098,11 +1098,8 @@ static int ath9k_htc_add_interface(struct ieee80211_hw *hw, ath9k_htc_set_opmode(priv); - if ((priv->ah->opmode == NL80211_IFTYPE_AP) && - !test_bit(ATH_OP_ANI_RUN, &common->op_flags)) { + if (priv->ah->opmode == NL80211_IFTYPE_AP) ath9k_hw_set_tsfadjust(priv->ah, true); - ath9k_htc_start_ani(priv); - } ath_dbg(common, CONFIG, "Attach a VIF of type: %d at idx: %d\n", vif->type, avp->index); @@ -1554,6 +1551,9 @@ static void ath9k_htc_bss_info_changed(struct ieee80211_hw *hw, ath9k_htc_set_tsfadjust(priv, vif); priv->cur_beacon_conf.enable_beacon = 1; ath9k_htc_beacon_config(priv, vif); + if (priv->ah->opmode == NL80211_IFTYPE_AP && + !test_bit(ATH_OP_ANI_RUN, &common->op_flags)) + ath9k_htc_start_ani(priv); } if ((changed & BSS_CHANGED_BEACON_ENABLED) && !bss_conf->enable_beacon) { diff --git a/drivers/net/wireless/broadcom/b43/debugfs.c b/drivers/net/wireless/broadcom/b43/debugfs.c index 173ef5db90fc..c6d4a290418a 100644 --- a/drivers/net/wireless/broadcom/b43/debugfs.c +++ b/drivers/net/wireless/broadcom/b43/debugfs.c @@ -5,7 +5,7 @@ debugfs driver debugging code - Copyright (c) 2005-2007 Michael Buesch <m@bues.ch> + Copyright (c) 2005-2007 Michael Buesch */ diff --git a/drivers/net/wireless/broadcom/b43/dma.c b/drivers/net/wireless/broadcom/b43/dma.c index 05da6987a845..be62144c524d 100644 --- a/drivers/net/wireless/broadcom/b43/dma.c +++ b/drivers/net/wireless/broadcom/b43/dma.c @@ -5,7 +5,7 @@ DMA ringbuffer and descriptor allocation/management - Copyright (c) 2005, 2006 Michael Buesch <m@bues.ch> + Copyright (c) 2005, 2006 Michael Buesch Some code in this file is derived from the b44.c driver Copyright (C) 2002 David S. Miller diff --git a/drivers/net/wireless/broadcom/b43/leds.c b/drivers/net/wireless/broadcom/b43/leds.c index bfe1be345844..0e6447c33ee8 100644 --- a/drivers/net/wireless/broadcom/b43/leds.c +++ b/drivers/net/wireless/broadcom/b43/leds.c @@ -6,7 +6,7 @@ Copyright (c) 2005 Martin Langer <martin-langer@gmx.de>, Copyright (c) 2005 Stefano Brivio <stefano.brivio@polimi.it> - Copyright (c) 2005-2007 Michael Buesch <m@bues.ch> + Copyright (c) 2005-2007 Michael Buesch Copyright (c) 2005 Danny van Dyk <kugelfang@gentoo.org> Copyright (c) 2005 Andreas Jaggi <andreas.jaggi@waterwave.ch> diff --git a/drivers/net/wireless/broadcom/b43/lo.c b/drivers/net/wireless/broadcom/b43/lo.c index f86e8969673f..020d5af0ebdf 100644 --- a/drivers/net/wireless/broadcom/b43/lo.c +++ b/drivers/net/wireless/broadcom/b43/lo.c @@ -7,7 +7,7 @@ Copyright (c) 2005 Martin Langer <martin-langer@gmx.de>, Copyright (c) 2005, 2006 Stefano Brivio <stefano.brivio@polimi.it> - Copyright (c) 2005-2007 Michael Buesch <m@bues.ch> + Copyright (c) 2005-2007 Michael Buesch Copyright (c) 2005, 2006 Danny van Dyk <kugelfang@gentoo.org> Copyright (c) 2005, 2006 Andreas Jaggi <andreas.jaggi@waterwave.ch> diff --git a/drivers/net/wireless/broadcom/b43/main.c b/drivers/net/wireless/broadcom/b43/main.c index 3825b6ad9f4f..e4f76e638a89 100644 --- a/drivers/net/wireless/broadcom/b43/main.c +++ b/drivers/net/wireless/broadcom/b43/main.c @@ -5,7 +5,7 @@ Copyright (c) 2005 Martin Langer <martin-langer@gmx.de> Copyright (c) 2005 Stefano Brivio <stefano.brivio@polimi.it> - Copyright (c) 2005-2009 Michael Buesch <m@bues.ch> + Copyright (c) 2005-2009 Michael Buesch Copyright (c) 2005 Danny van Dyk <kugelfang@gentoo.org> Copyright (c) 2005 Andreas Jaggi <andreas.jaggi@waterwave.ch> Copyright (c) 2010-2011 RafaÅ‚ MiÅ‚ecki <zajec5@gmail.com> diff --git a/drivers/net/wireless/broadcom/b43/main.h b/drivers/net/wireless/broadcom/b43/main.h index d94ab86e8495..d59ec5a7579b 100644 --- a/drivers/net/wireless/broadcom/b43/main.h +++ b/drivers/net/wireless/broadcom/b43/main.h @@ -5,7 +5,7 @@ Copyright (c) 2005 Martin Langer <martin-langer@gmx.de>, Stefano Brivio <stefano.brivio@polimi.it> - Michael Buesch <m@bues.ch> + Michael Buesch Danny van Dyk <kugelfang@gentoo.org> Andreas Jaggi <andreas.jaggi@waterwave.ch> diff --git a/drivers/net/wireless/broadcom/b43/phy_common.c b/drivers/net/wireless/broadcom/b43/phy_common.c index 285490f6f0a1..e132b9bbcbec 100644 --- a/drivers/net/wireless/broadcom/b43/phy_common.c +++ b/drivers/net/wireless/broadcom/b43/phy_common.c @@ -6,7 +6,7 @@ Copyright (c) 2005 Martin Langer <martin-langer@gmx.de>, Copyright (c) 2005-2007 Stefano Brivio <stefano.brivio@polimi.it> - Copyright (c) 2005-2008 Michael Buesch <m@bues.ch> + Copyright (c) 2005-2008 Michael Buesch Copyright (c) 2005, 2006 Danny van Dyk <kugelfang@gentoo.org> Copyright (c) 2005, 2006 Andreas Jaggi <andreas.jaggi@waterwave.ch> diff --git a/drivers/net/wireless/broadcom/b43/phy_g.c b/drivers/net/wireless/broadcom/b43/phy_g.c index 9e292a349674..3af50a755cf7 100644 --- a/drivers/net/wireless/broadcom/b43/phy_g.c +++ b/drivers/net/wireless/broadcom/b43/phy_g.c @@ -6,7 +6,7 @@ Copyright (c) 2005 Martin Langer <martin-langer@gmx.de>, Copyright (c) 2005-2007 Stefano Brivio <stefano.brivio@polimi.it> - Copyright (c) 2005-2008 Michael Buesch <m@bues.ch> + Copyright (c) 2005-2008 Michael Buesch Copyright (c) 2005, 2006 Danny van Dyk <kugelfang@gentoo.org> Copyright (c) 2005, 2006 Andreas Jaggi <andreas.jaggi@waterwave.ch> diff --git a/drivers/net/wireless/broadcom/b43/phy_lp.c b/drivers/net/wireless/broadcom/b43/phy_lp.c index 3bbee377a14e..6c90b84df91e 100644 --- a/drivers/net/wireless/broadcom/b43/phy_lp.c +++ b/drivers/net/wireless/broadcom/b43/phy_lp.c @@ -4,7 +4,7 @@ Broadcom B43 wireless driver IEEE 802.11a/g LP-PHY driver - Copyright (c) 2008-2009 Michael Buesch <m@bues.ch> + Copyright (c) 2008-2009 Michael Buesch Copyright (c) 2009 Gábor Stefanik <netrolller.3d@gmail.com> diff --git a/drivers/net/wireless/broadcom/b43/phy_n.c b/drivers/net/wireless/broadcom/b43/phy_n.c index 0972070846bb..007940f3996e 100644 --- a/drivers/net/wireless/broadcom/b43/phy_n.c +++ b/drivers/net/wireless/broadcom/b43/phy_n.c @@ -4,7 +4,7 @@ Broadcom B43 wireless driver IEEE 802.11n PHY support - Copyright (c) 2008 Michael Buesch <m@bues.ch> + Copyright (c) 2008 Michael Buesch Copyright (c) 2010-2011 RafaÅ‚ MiÅ‚ecki <zajec5@gmail.com> diff --git a/drivers/net/wireless/broadcom/b43/pio.c b/drivers/net/wireless/broadcom/b43/pio.c index 8358b1d5c298..08dba9f3d5fd 100644 --- a/drivers/net/wireless/broadcom/b43/pio.c +++ b/drivers/net/wireless/broadcom/b43/pio.c @@ -5,7 +5,7 @@ PIO data transfer - Copyright (c) 2005-2008 Michael Buesch <m@bues.ch> + Copyright (c) 2005-2008 Michael Buesch */ diff --git a/drivers/net/wireless/broadcom/b43/radio_2055.c b/drivers/net/wireless/broadcom/b43/radio_2055.c index be841f891900..7f3ca19a123f 100644 --- a/drivers/net/wireless/broadcom/b43/radio_2055.c +++ b/drivers/net/wireless/broadcom/b43/radio_2055.c @@ -4,7 +4,7 @@ Broadcom B43 wireless driver IEEE 802.11n PHY and radio device data tables - Copyright (c) 2008 Michael Buesch <m@bues.ch> + Copyright (c) 2008 Michael Buesch Copyright (c) 2010 RafaÅ‚ MiÅ‚ecki <zajec5@gmail.com> diff --git a/drivers/net/wireless/broadcom/b43/rfkill.c b/drivers/net/wireless/broadcom/b43/rfkill.c index f0c968703613..bf6391b5d10e 100644 --- a/drivers/net/wireless/broadcom/b43/rfkill.c +++ b/drivers/net/wireless/broadcom/b43/rfkill.c @@ -4,7 +4,7 @@ Broadcom B43 wireless driver RFKILL support - Copyright (c) 2007 Michael Buesch <m@bues.ch> + Copyright (c) 2007 Michael Buesch */ diff --git a/drivers/net/wireless/broadcom/b43/sdio.c b/drivers/net/wireless/broadcom/b43/sdio.c index dda8d894aebe..35cf31e7d5b6 100644 --- a/drivers/net/wireless/broadcom/b43/sdio.c +++ b/drivers/net/wireless/broadcom/b43/sdio.c @@ -5,7 +5,7 @@ * SDIO over Sonics Silicon Backplane bus glue for b43. * * Copyright (C) 2009 Albert Herranz - * Copyright (C) 2009 Michael Buesch <m@bues.ch> + * Copyright (C) 2009 Michael Buesch */ #include <linux/kernel.h> diff --git a/drivers/net/wireless/broadcom/b43/sysfs.c b/drivers/net/wireless/broadcom/b43/sysfs.c index 261b2b746a9c..c8bd1bce7791 100644 --- a/drivers/net/wireless/broadcom/b43/sysfs.c +++ b/drivers/net/wireless/broadcom/b43/sysfs.c @@ -5,7 +5,7 @@ SYSFS support routines - Copyright (c) 2006 Michael Buesch <m@bues.ch> + Copyright (c) 2006 Michael Buesch */ diff --git a/drivers/net/wireless/broadcom/b43/tables.c b/drivers/net/wireless/broadcom/b43/tables.c index 25c891e2cbfa..9b2bfa30f082 100644 --- a/drivers/net/wireless/broadcom/b43/tables.c +++ b/drivers/net/wireless/broadcom/b43/tables.c @@ -5,7 +5,7 @@ Copyright (c) 2005 Martin Langer <martin-langer@gmx.de>, Copyright (c) 2005-2007 Stefano Brivio <stefano.brivio@polimi.it> - Copyright (c) 2006, 2006 Michael Buesch <m@bues.ch> + Copyright (c) 2006, 2006 Michael Buesch Copyright (c) 2005 Danny van Dyk <kugelfang@gentoo.org> Copyright (c) 2005 Andreas Jaggi <andreas.jaggi@waterwave.ch> diff --git a/drivers/net/wireless/broadcom/b43/tables_lpphy.c b/drivers/net/wireless/broadcom/b43/tables_lpphy.c index fb70a1e3544b..2bd3dfaa47f6 100644 --- a/drivers/net/wireless/broadcom/b43/tables_lpphy.c +++ b/drivers/net/wireless/broadcom/b43/tables_lpphy.c @@ -4,7 +4,7 @@ Broadcom B43 wireless driver IEEE 802.11a/g LP-PHY and radio device data tables - Copyright (c) 2009 Michael Buesch <m@bues.ch> + Copyright (c) 2009 Michael Buesch Copyright (c) 2009 Gábor Stefanik <netrolller.3d@gmail.com> diff --git a/drivers/net/wireless/broadcom/b43/tables_nphy.c b/drivers/net/wireless/broadcom/b43/tables_nphy.c index ecd660b9c75a..6b48943d950a 100644 --- a/drivers/net/wireless/broadcom/b43/tables_nphy.c +++ b/drivers/net/wireless/broadcom/b43/tables_nphy.c @@ -4,7 +4,7 @@ Broadcom B43 wireless driver IEEE 802.11n PHY data tables - Copyright (c) 2008 Michael Buesch <m@bues.ch> + Copyright (c) 2008 Michael Buesch Copyright (c) 2010 RafaÅ‚ MiÅ‚ecki <zajec5@gmail.com> diff --git a/drivers/net/wireless/broadcom/b43/wa.c b/drivers/net/wireless/broadcom/b43/wa.c index f9209b863e35..222d88c45a17 100644 --- a/drivers/net/wireless/broadcom/b43/wa.c +++ b/drivers/net/wireless/broadcom/b43/wa.c @@ -6,7 +6,7 @@ PHY workarounds. Copyright (c) 2005-2007 Stefano Brivio <stefano.brivio@polimi.it> - Copyright (c) 2005-2007 Michael Buesch <m@bues.ch> + Copyright (c) 2005-2007 Michael Buesch */ diff --git a/drivers/net/wireless/broadcom/b43/xmit.c b/drivers/net/wireless/broadcom/b43/xmit.c index f0b082596637..4f9e1ebd55b7 100644 --- a/drivers/net/wireless/broadcom/b43/xmit.c +++ b/drivers/net/wireless/broadcom/b43/xmit.c @@ -7,7 +7,7 @@ Copyright (C) 2005 Martin Langer <martin-langer@gmx.de> Copyright (C) 2005 Stefano Brivio <stefano.brivio@polimi.it> - Copyright (C) 2005, 2006 Michael Buesch <m@bues.ch> + Copyright (C) 2005, 2006 Michael Buesch Copyright (C) 2005 Danny van Dyk <kugelfang@gentoo.org> Copyright (C) 2005 Andreas Jaggi <andreas.jaggi@waterwave.ch> diff --git a/drivers/net/wireless/broadcom/b43legacy/debugfs.c b/drivers/net/wireless/broadcom/b43legacy/debugfs.c index 7ce8bcf12f0a..1e44e04a0105 100644 --- a/drivers/net/wireless/broadcom/b43legacy/debugfs.c +++ b/drivers/net/wireless/broadcom/b43legacy/debugfs.c @@ -5,7 +5,7 @@ debugfs driver debugging code - Copyright (c) 2005-2007 Michael Buesch <m@bues.ch> + Copyright (c) 2005-2007 Michael Buesch */ diff --git a/drivers/net/wireless/broadcom/b43legacy/dma.c b/drivers/net/wireless/broadcom/b43legacy/dma.c index 6c3d847242bb..0659af58e7c1 100644 --- a/drivers/net/wireless/broadcom/b43legacy/dma.c +++ b/drivers/net/wireless/broadcom/b43legacy/dma.c @@ -5,7 +5,7 @@ DMA ringbuffer and descriptor allocation/management - Copyright (c) 2005, 2006 Michael Buesch <m@bues.ch> + Copyright (c) 2005, 2006 Michael Buesch Some code in this file is derived from the b44.c driver Copyright (C) 2002 David S. Miller diff --git a/drivers/net/wireless/broadcom/b43legacy/ilt.c b/drivers/net/wireless/broadcom/b43legacy/ilt.c index f62d6886a003..78bc0e78c575 100644 --- a/drivers/net/wireless/broadcom/b43legacy/ilt.c +++ b/drivers/net/wireless/broadcom/b43legacy/ilt.c @@ -5,7 +5,7 @@ Copyright (c) 2005 Martin Langer <martin-langer@gmx.de>, Stefano Brivio <stefano.brivio@polimi.it> - Michael Buesch <m@bues.ch> + Michael Buesch Danny van Dyk <kugelfang@gentoo.org> Andreas Jaggi <andreas.jaggi@waterwave.ch> diff --git a/drivers/net/wireless/broadcom/b43legacy/leds.c b/drivers/net/wireless/broadcom/b43legacy/leds.c index 79e6fd205bfb..43c75472d06f 100644 --- a/drivers/net/wireless/broadcom/b43legacy/leds.c +++ b/drivers/net/wireless/broadcom/b43legacy/leds.c @@ -6,7 +6,7 @@ Copyright (c) 2005 Martin Langer <martin-langer@gmx.de>, Copyright (c) 2005 Stefano Brivio <stefano.brivio@polimi.it> - Copyright (c) 2005-2007 Michael Buesch <m@bues.ch> + Copyright (c) 2005-2007 Michael Buesch Copyright (c) 2005 Danny van Dyk <kugelfang@gentoo.org> Copyright (c) 2005 Andreas Jaggi <andreas.jaggi@waterwave.ch> diff --git a/drivers/net/wireless/broadcom/b43legacy/main.c b/drivers/net/wireless/broadcom/b43legacy/main.c index dfff3710dea3..a960b49b2943 100644 --- a/drivers/net/wireless/broadcom/b43legacy/main.c +++ b/drivers/net/wireless/broadcom/b43legacy/main.c @@ -5,7 +5,7 @@ * * Copyright (c) 2005 Martin Langer <martin-langer@gmx.de> * Copyright (c) 2005-2008 Stefano Brivio <stefano.brivio@polimi.it> - * Copyright (c) 2005, 2006 Michael Buesch <m@bues.ch> + * Copyright (c) 2005, 2006 Michael Buesch * Copyright (c) 2005 Danny van Dyk <kugelfang@gentoo.org> * Copyright (c) 2005 Andreas Jaggi <andreas.jaggi@waterwave.ch> * Copyright (c) 2007 Larry Finger <Larry.Finger@lwfinger.net> diff --git a/drivers/net/wireless/broadcom/b43legacy/main.h b/drivers/net/wireless/broadcom/b43legacy/main.h index 85edbc8c121a..420683ecbd10 100644 --- a/drivers/net/wireless/broadcom/b43legacy/main.h +++ b/drivers/net/wireless/broadcom/b43legacy/main.h @@ -5,7 +5,7 @@ Copyright (c) 2005 Martin Langer <martin-langer@gmx.de>, Copyright (c) 2005 Stefano Brivio <stefano.brivio@polimi.it> - Copyright (c) 2005, 2006 Michael Buesch <m@bues.ch> + Copyright (c) 2005, 2006 Michael Buesch Copyright (c) 2005 Danny van Dyk <kugelfang@gentoo.org> Copyright (c) 2005 Andreas Jaggi <andreas.jaggi@waterwave.ch> Copyright (c) 2007 Larry Finger <Larry.Finger@lwfinger.net> diff --git a/drivers/net/wireless/broadcom/b43legacy/phy.c b/drivers/net/wireless/broadcom/b43legacy/phy.c index c1395e622759..5be36c9ba414 100644 --- a/drivers/net/wireless/broadcom/b43legacy/phy.c +++ b/drivers/net/wireless/broadcom/b43legacy/phy.c @@ -5,7 +5,7 @@ Copyright (c) 2005 Martin Langer <martin-langer@gmx.de>, Stefano Brivio <stefano.brivio@polimi.it> - Michael Buesch <m@bues.ch> + Michael Buesch Danny van Dyk <kugelfang@gentoo.org> Andreas Jaggi <andreas.jaggi@waterwave.ch> Copyright (c) 2007 Larry Finger <Larry.Finger@lwfinger.net> diff --git a/drivers/net/wireless/broadcom/b43legacy/phy.h b/drivers/net/wireless/broadcom/b43legacy/phy.h index bb2c492dab36..b45d731429b0 100644 --- a/drivers/net/wireless/broadcom/b43legacy/phy.h +++ b/drivers/net/wireless/broadcom/b43legacy/phy.h @@ -5,7 +5,7 @@ Copyright (c) 2005 Martin Langer <martin-langer@gmx.de>, Stefano Brivio <stefano.brivio@polimi.it> - Michael Buesch <m@bues.ch> + Michael Buesch Danny van Dyk <kugelfang@gentoo.org> Andreas Jaggi <andreas.jaggi@waterwave.ch> Copyright (c) 2007 Larry Finger <Larry.Finger@lwfinger.net> diff --git a/drivers/net/wireless/broadcom/b43legacy/pio.c b/drivers/net/wireless/broadcom/b43legacy/pio.c index 0274fe47ca7e..d1e271c4ef71 100644 --- a/drivers/net/wireless/broadcom/b43legacy/pio.c +++ b/drivers/net/wireless/broadcom/b43legacy/pio.c @@ -5,7 +5,7 @@ PIO Transmission - Copyright (c) 2005 Michael Buesch <m@bues.ch> + Copyright (c) 2005 Michael Buesch */ diff --git a/drivers/net/wireless/broadcom/b43legacy/radio.c b/drivers/net/wireless/broadcom/b43legacy/radio.c index 8d7eb89c1628..d46a42a05a66 100644 --- a/drivers/net/wireless/broadcom/b43legacy/radio.c +++ b/drivers/net/wireless/broadcom/b43legacy/radio.c @@ -5,7 +5,7 @@ Copyright (c) 2005 Martin Langer <martin-langer@gmx.de>, Stefano Brivio <stefano.brivio@polimi.it> - Michael Buesch <m@bues.ch> + Michael Buesch Danny van Dyk <kugelfang@gentoo.org> Andreas Jaggi <andreas.jaggi@waterwave.ch> Copyright (c) 2007 Larry Finger <Larry.Finger@lwfinger.net> diff --git a/drivers/net/wireless/broadcom/b43legacy/radio.h b/drivers/net/wireless/broadcom/b43legacy/radio.h index ee8b2c8d1602..d833690d17b8 100644 --- a/drivers/net/wireless/broadcom/b43legacy/radio.h +++ b/drivers/net/wireless/broadcom/b43legacy/radio.h @@ -5,7 +5,7 @@ Copyright (c) 2005 Martin Langer <martin-langer@gmx.de>, Stefano Brivio <stefano.brivio@polimi.it> - Michael Buesch <m@bues.ch> + Michael Buesch Danny van Dyk <kugelfang@gentoo.org> Andreas Jaggi <andreas.jaggi@waterwave.ch> diff --git a/drivers/net/wireless/broadcom/b43legacy/rfkill.c b/drivers/net/wireless/broadcom/b43legacy/rfkill.c index 1f532105052e..b8e3f2734cd7 100644 --- a/drivers/net/wireless/broadcom/b43legacy/rfkill.c +++ b/drivers/net/wireless/broadcom/b43legacy/rfkill.c @@ -4,7 +4,7 @@ Broadcom B43 wireless driver RFKILL support - Copyright (c) 2007 Michael Buesch <m@bues.ch> + Copyright (c) 2007 Michael Buesch */ diff --git a/drivers/net/wireless/broadcom/b43legacy/sysfs.c b/drivers/net/wireless/broadcom/b43legacy/sysfs.c index d988fe541bf7..a29df7481191 100644 --- a/drivers/net/wireless/broadcom/b43legacy/sysfs.c +++ b/drivers/net/wireless/broadcom/b43legacy/sysfs.c @@ -5,7 +5,7 @@ SYSFS support routines - Copyright (c) 2006 Michael Buesch <m@bues.ch> + Copyright (c) 2006 Michael Buesch */ diff --git a/drivers/net/wireless/broadcom/b43legacy/xmit.c b/drivers/net/wireless/broadcom/b43legacy/xmit.c index ee199d4eaf03..c97b8be744c6 100644 --- a/drivers/net/wireless/broadcom/b43legacy/xmit.c +++ b/drivers/net/wireless/broadcom/b43legacy/xmit.c @@ -7,7 +7,7 @@ Copyright (C) 2005 Martin Langer <martin-langer@gmx.de> Copyright (C) 2005 Stefano Brivio <stefano.brivio@polimi.it> - Copyright (C) 2005, 2006 Michael Buesch <m@bues.ch> + Copyright (C) 2005, 2006 Michael Buesch Copyright (C) 2005 Danny van Dyk <kugelfang@gentoo.org> Copyright (C) 2005 Andreas Jaggi <andreas.jaggi@waterwave.ch> Copyright (C) 2007 Larry Finger <Larry.Finger@lwfinger.net> diff --git a/drivers/net/wireless/morsemicro/mm81x/mac.c b/drivers/net/wireless/morsemicro/mm81x/mac.c index 6f1feb24fe6a..cd0bb4d21acf 100644 --- a/drivers/net/wireless/morsemicro/mm81x/mac.c +++ b/drivers/net/wireless/morsemicro/mm81x/mac.c @@ -2005,6 +2005,23 @@ static void mm81x_rx_h_add_rt_s1g_tlv(struct sk_buff *skb, rx_status->flag |= RX_FLAG_RADIOTAP_TLV_AT_END; } +/* + * This is a hack to workaround how our firmware reports frequencies. + * For any 1MHz frames report them directly (i.e during scanning), else + * report the 1MHz control channel we are tuned to. + */ +static void mm81x_rx_h_fill_freq(struct mm81x *mors, u32 rx_khz, + struct ieee80211_rx_status *rx_status) +{ + struct ieee80211_channel *chan = mors->chandef.chan; + + if (rx_status->bw != RATE_INFO_BW_1) + rx_khz = ieee80211_channel_to_khz(chan); + + rx_status->freq = KHZ_TO_MHZ(rx_khz); + rx_status->freq_offset = (rx_khz % 1000) ? 1 : 0; +} + static void mm81x_rx_h_fill_status(struct mm81x *mors, struct mm81x_skb_rx_status *hdr_rx_status, struct ieee80211_rx_status *rx_status, @@ -2018,11 +2035,10 @@ static void mm81x_rx_h_fill_status(struct mm81x *mors, rx_status->signal = le16_to_cpu(hdr_rx_status->rssi); rx_status->encoding = RX_ENC_S1G; rx_status->band = NL80211_BAND_S1GHZ; - rx_status->freq = KHZ100_TO_MHZ(freq_100khz); - rx_status->freq_offset = (freq_100khz % 10) ? 1 : 0; rx_status->nss = NSS_IDX_TO_NSS(mm81x_ratecode_nss_index_get(ratecode)); rx_status->rate_idx = mm81x_ratecode_mcs_index_get(ratecode); rx_status->bw = mm81x_rx_h_rc_bw_to_rx_bw(ratecode); + mm81x_rx_h_fill_freq(mors, KHZ100_TO_KHZ(freq_100khz), rx_status); rx_status->mactime = timestamp; rx_status->flag |= RX_FLAG_MACTIME_IS_RTAP_TS64; diff --git a/drivers/net/wireless/nxp/nxpwifi/11ax.c b/drivers/net/wireless/nxp/nxpwifi/11ax.c index dc1e747383ec..be38a034be32 100644 --- a/drivers/net/wireless/nxp/nxpwifi/11ax.c +++ b/drivers/net/wireless/nxp/nxpwifi/11ax.c @@ -204,38 +204,61 @@ int nxpwifi_ret_11ax_cfg(struct nxpwifi_private *priv, { struct host_cmd_11ax_cfg *he_cfg = &resp->params.ax_cfg; struct nxpwifi_ie_types_header *header; - u16 left_len, tlv_type, tlv_len; + u16 resp_size, left_len, tlv_type, tlv_len; + struct nxpwifi_11ax_he_cap_cfg *he_cap; u8 ext_id; - struct nxpwifi_11ax_he_cap_cfg *he_cap = &ax_cfg->he_cap_cfg; - left_len = le16_to_cpu(resp->size) - sizeof(*he_cfg) - S_DS_GEN; + if (!ax_cfg) + return 0; + + he_cap = &ax_cfg->he_cap_cfg; + resp_size = le16_to_cpu(resp->size); + if (resp_size < S_DS_GEN + sizeof(*he_cfg)) + return -EINVAL; + + left_len = resp_size - S_DS_GEN - sizeof(*he_cfg); header = (struct nxpwifi_ie_types_header *)he_cfg->tlv; while (left_len > sizeof(*header)) { tlv_type = le16_to_cpu(header->type); tlv_len = le16_to_cpu(header->len); - if (tlv_type == TLV_TYPE_EXTENSION_ID) { - ext_id = *((u8 *)header + sizeof(*header) + 1); + if (sizeof(*header) + tlv_len > left_len) + return -EINVAL; + + if (tlv_type == TLV_TYPE_EXTENSION_ID && tlv_len >= 1) { + ext_id = *((u8 *)header + sizeof(*header)); if (ext_id == WLAN_EID_EXT_HE_CAPABILITY) { + u8 *user_cap, *user_cap_len; + size_t user_cap_size; + + if (he_cfg->band_config & BIT(1)) { + user_cap = priv->user_he_cap; + user_cap_len = &priv->user_he_cap_len; + user_cap_size = + sizeof(priv->user_he_cap); + } else { + user_cap = priv->user_2g_he_cap; + user_cap_len = + &priv->user_2g_he_cap_len; + user_cap_size = + sizeof(priv->user_2g_he_cap); + } + + if (tlv_len > sizeof(*he_cap) - + offsetof(struct nxpwifi_11ax_he_cap_cfg, + ext_id) || + sizeof(*header) + tlv_len > user_cap_size) + return -EINVAL; + he_cap->id = tlv_type; he_cap->len = tlv_len; memcpy((u8 *)&he_cap->ext_id, - (u8 *)header + sizeof(*header) + 1, + (u8 *)header + sizeof(*header), tlv_len); - if (he_cfg->band_config & BIT(1)) { - memcpy(priv->user_he_cap, - (u8 *)header, - sizeof(*header) + tlv_len); - priv->user_he_cap_len = - sizeof(*header) + tlv_len; - } else { - memcpy(priv->user_2g_he_cap, - (u8 *)header, - sizeof(*header) + tlv_len); - priv->user_2g_he_cap_len = - sizeof(*header) + tlv_len; - } + memcpy(user_cap, (u8 *)header, + sizeof(*header) + tlv_len); + *user_cap_len = sizeof(*header) + tlv_len; } } @@ -346,6 +369,9 @@ int nxpwifi_ret_11ax_cmd(struct nxpwifi_private *priv, struct host_cmd_11ax_cmd *he_cmd = &resp->params.ax_cmd; struct nxpwifi_ie_types_data *tlv; + if (!ax_cmd) + return 0; + ax_cmd->sub_id = le16_to_cpu(he_cmd->sub_id); switch (ax_cmd->sub_command) { @@ -584,6 +610,9 @@ int nxpwifi_ret_twt_cfg(struct nxpwifi_private *priv, struct host_cmd_twt_cfg *twt_cfg_cmd = &resp->params.twt_cfg; u16 action; + if (!twt_cfg) + return 0; + action = le16_to_cpu(twt_cfg_cmd->action); twt_cfg->sub_id = le16_to_cpu(twt_cfg_cmd->sub_id); diff --git a/drivers/net/wireless/nxp/nxpwifi/scan.c b/drivers/net/wireless/nxp/nxpwifi/scan.c index f3becafb9c23..4eeba6700aa7 100644 --- a/drivers/net/wireless/nxp/nxpwifi/scan.c +++ b/drivers/net/wireless/nxp/nxpwifi/scan.c @@ -1873,26 +1873,32 @@ void nxpwifi_cancel_scan(struct nxpwifi_adapter *adapter) { struct nxpwifi_private *priv; int i; + bool cancel = false; nxpwifi_cancel_pending_scan_cmd(adapter); + spin_lock_bh(&adapter->nxpwifi_cmd_lock); if (adapter->scan_processing) { - spin_lock_bh(&adapter->nxpwifi_cmd_lock); adapter->scan_processing = false; - spin_unlock_bh(&adapter->nxpwifi_cmd_lock); - for (i = 0; i < adapter->priv_num; i++) { - priv = adapter->priv[i]; - if (priv->scan_request) { - struct cfg80211_scan_info info = { - .aborted = true, - }; + cancel = true; + } + spin_unlock_bh(&adapter->nxpwifi_cmd_lock); - nxpwifi_dbg(adapter, INFO, - "info: aborting scan\n"); - cfg80211_scan_done(priv->scan_request, &info); - priv->scan_request = NULL; - priv->scan_aborting = false; - } + if (!cancel) + return; + + for (i = 0; i < adapter->priv_num; i++) { + priv = adapter->priv[i]; + if (priv->scan_request) { + struct cfg80211_scan_info info = { + .aborted = true, + }; + + nxpwifi_dbg(adapter, INFO, + "info: aborting scan\n"); + cfg80211_scan_done(priv->scan_request, &info); + priv->scan_request = NULL; + priv->scan_aborting = false; } } } @@ -2017,12 +2023,22 @@ int nxpwifi_ret_802_11_scan(struct nxpwifi_private *priv, * was received. */ if (tsf_tlv) - memcpy(&fw_tsf, &tsf_tlv->tsf_data[idx * TSF_DATA_SIZE], - sizeof(fw_tsf)); + if ((idx + 1) * TSF_DATA_SIZE <= + le16_to_cpu(tsf_tlv->header.len)) + memcpy(&fw_tsf, + &tsf_tlv->tsf_data[idx * + TSF_DATA_SIZE], + sizeof(fw_tsf)); if (chan_band_tlv) { - chan_band = &chan_band_tlv->chan_band_param[idx]; - radio_type = &chan_band->radio_type; + if ((idx + 1) * sizeof(*chan_band) <= + le16_to_cpu(chan_band_tlv->header.len)) { + chan_band = + &chan_band_tlv->chan_band_param[idx]; + radio_type = &chan_band->radio_type; + } else { + radio_type = NULL; + } } else { radio_type = NULL; } diff --git a/drivers/net/wireless/nxp/nxpwifi/util.c b/drivers/net/wireless/nxp/nxpwifi/util.c index cf94fba22f79..7dd122f3c7f5 100644 --- a/drivers/net/wireless/nxp/nxpwifi/util.c +++ b/drivers/net/wireless/nxp/nxpwifi/util.c @@ -623,6 +623,10 @@ int nxpwifi_recv_packet_to_monif(struct nxpwifi_private *priv, has_ext = rxpd->flags & RXPD_FLAG_EXTRA_HEADER; + if (has_ext && + rx_pkt_offset < sizeof(*rxpd) + sizeof(ext)) + return -EINVAL; + if (has_ext) memcpy((void *)&ext, (void *)(rxpd + 1), sizeof(ext)); diff --git a/drivers/net/wireless/realtek/rtw88/main.c b/drivers/net/wireless/realtek/rtw88/main.c index 0f23498b5c96..b72173964bdd 100644 --- a/drivers/net/wireless/realtek/rtw88/main.c +++ b/drivers/net/wireless/realtek/rtw88/main.c @@ -2177,6 +2177,9 @@ int rtw_core_init(struct rtw_dev *rtwdev) spin_lock_init(&rtwdev->txq_lock); spin_lock_init(&rtwdev->tx_report.q_lock); + spin_lock_init(&rtwdev->hiq_lock); + rtwdev->hiq_budget = RTW_TX_HIQ_BUDGET_MAX; + rtwdev->hiq_refill = jiffies; mutex_init(&rtwdev->mutex); mutex_init(&rtwdev->hal.tx_power_mutex); diff --git a/drivers/net/wireless/realtek/rtw88/main.h b/drivers/net/wireless/realtek/rtw88/main.h index d59f6e323adf..c14c834c27fd 100644 --- a/drivers/net/wireless/realtek/rtw88/main.h +++ b/drivers/net/wireless/realtek/rtw88/main.h @@ -2104,6 +2104,11 @@ struct rtw_dev { struct rtw_tx_report tx_report; + /* protects hiq_budget and hiq_refill */ + spinlock_t hiq_lock; + u32 hiq_budget; + unsigned long hiq_refill; + struct { /* indicate the mail box to use with fw */ u8 last_box_num; diff --git a/drivers/net/wireless/realtek/rtw88/sdio.c b/drivers/net/wireless/realtek/rtw88/sdio.c index dc2fd0f8f9ff..83e9b301ae9b 100644 --- a/drivers/net/wireless/realtek/rtw88/sdio.c +++ b/drivers/net/wireless/realtek/rtw88/sdio.c @@ -1308,6 +1308,9 @@ static int rtw_sdio_tx_write(struct rtw_dev *rtwdev, u16 q_map = skb_get_queue_mapping(skb); struct rtw_sdio_tx_data *tx_data; + if (queue == RTW_TX_QUEUE_HI0 && !rtw_tx_bmc_use_hiq(rtwdev, skb)) + queue = rtw_tx_ac_to_hwq(q_map); + rtw_sdio_tx_skb_prepare(rtwdev, pkt_info, skb, queue); tx_data = rtw_sdio_get_tx_data(skb); diff --git a/drivers/net/wireless/realtek/rtw88/tx.c b/drivers/net/wireless/realtek/rtw88/tx.c index 701ed7c4f3f7..82c1af94f1cc 100644 --- a/drivers/net/wireless/realtek/rtw88/tx.c +++ b/drivers/net/wireless/realtek/rtw88/tx.c @@ -2,6 +2,8 @@ /* Copyright(c) 2018-2019 Realtek Corporation */ +#include <linux/ip.h> +#include <linux/udp.h> #include "main.h" #include "tx.h" #include "fw.h" @@ -745,3 +747,60 @@ enum rtw_tx_queue_type rtw_tx_queue_mapping(struct sk_buff *skb) return queue; } EXPORT_SYMBOL(rtw_tx_queue_mapping); + +static bool rtw_tx_bmc_needs_dtim(struct sk_buff *skb) +{ + struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); + struct udphdr *udphdr; + + if (info->control.flags & IEEE80211_TX_CTRL_PORT_CTRL_PROTO) + return true; + + if (skb->protocol == htons(ETH_P_ARP)) + return true; + + if (skb->protocol == htons(ETH_P_IP) && + ip_hdr(skb)->protocol == IPPROTO_UDP) { + udphdr = udp_hdr(skb); + + return udphdr->dest == htons(67) || udphdr->dest == htons(68); + } + + return false; +} + +static bool rtw_tx_hiq_take_budget(struct rtw_dev *rtwdev) +{ + unsigned long flags, elapsed, add; + bool ok; + + spin_lock_irqsave(&rtwdev->hiq_lock, flags); + + elapsed = jiffies - rtwdev->hiq_refill; + add = elapsed / RTW_TX_HIQ_REFILL_INTERVAL; + if (add) { + rtwdev->hiq_budget = min_t(unsigned long, rtwdev->hiq_budget + add, + RTW_TX_HIQ_BUDGET_MAX); + + /* keep the unfinished part of the interval for the next unit */ + rtwdev->hiq_refill = jiffies - elapsed % RTW_TX_HIQ_REFILL_INTERVAL; + } + + ok = rtwdev->hiq_budget > 0; + if (ok) + rtwdev->hiq_budget--; + + spin_unlock_irqrestore(&rtwdev->hiq_lock, flags); + + return ok; +} + +bool rtw_tx_bmc_use_hiq(struct rtw_dev *rtwdev, struct sk_buff *skb) +{ + struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); + + return (info->flags & IEEE80211_TX_CTL_SEND_AFTER_DTIM) && + rtw_tx_bmc_needs_dtim(skb) && + rtw_tx_hiq_take_budget(rtwdev); +} +EXPORT_SYMBOL(rtw_tx_bmc_use_hiq); diff --git a/drivers/net/wireless/realtek/rtw88/tx.h b/drivers/net/wireless/realtek/rtw88/tx.h index 168f48e87853..a68ba3b12159 100644 --- a/drivers/net/wireless/realtek/rtw88/tx.h +++ b/drivers/net/wireless/realtek/rtw88/tx.h @@ -10,6 +10,9 @@ #define RTW_TX_PROBE_TIMEOUT_SHORT msecs_to_jiffies(500) #define RTW_TX_PROBE_TIMEOUT_LONG msecs_to_jiffies(2500) +#define RTW_TX_HIQ_REFILL_INTERVAL (HZ / 10) +#define RTW_TX_HIQ_BUDGET_MAX 16 + struct rtw_tx_desc { __le32 w0; __le32 w1; @@ -115,6 +118,7 @@ rtw_tx_write_data_h2c_get(struct rtw_dev *rtwdev, enum rtw_tx_queue_type rtw_tx_ac_to_hwq(enum ieee80211_ac_numbers ac); enum rtw_tx_queue_type rtw_tx_queue_mapping(struct sk_buff *skb); +bool rtw_tx_bmc_use_hiq(struct rtw_dev *rtwdev, struct sk_buff *skb); static inline void fill_txdesc_checksum_common(u8 *txdesc, size_t words) diff --git a/drivers/net/wireless/realtek/rtw88/usb.c b/drivers/net/wireless/realtek/rtw88/usb.c index 715a2ce342d9..13adbd415158 100644 --- a/drivers/net/wireless/realtek/rtw88/usb.c +++ b/drivers/net/wireless/realtek/rtw88/usb.c @@ -2,10 +2,8 @@ /* Copyright(c) 2018-2019 Realtek Corporation */ -#include <linux/ip.h> #include <linux/module.h> #include <linux/mutex.h> -#include <linux/udp.h> #include <linux/usb.h> #include "main.h" #include "debug.h" @@ -564,61 +562,10 @@ static int rtw_usb_write_data_h2c(struct rtw_dev *rtwdev, u8 *buf, u32 size) return rtw_usb_write_data(rtwdev, &pkt_info, buf); } -static bool rtw_usb_bmc_needs_dtim(struct sk_buff *skb) -{ - struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); - struct udphdr *udphdr; - - if (info->control.flags & IEEE80211_TX_CTRL_PORT_CTRL_PROTO) - return true; - - if (skb->protocol == htons(ETH_P_ARP)) - return true; - - if (skb->protocol == htons(ETH_P_IP) && - ip_hdr(skb)->protocol == IPPROTO_UDP) { - udphdr = udp_hdr(skb); - - return udphdr->dest == htons(67) || udphdr->dest == htons(68); - } - - return false; -} - -#define RTW_USB_HIQ_REFILL_INTERVAL (HZ / 10) /* one unit of budget per 100 ms */ -#define RTW_USB_HIQ_BUDGET_MAX 16 - -static bool rtw_usb_hiq_take_budget(struct rtw_usb *rtwusb) -{ - unsigned long flags, elapsed, add; - bool ok; - - spin_lock_irqsave(&rtwusb->hiq_lock, flags); - - elapsed = jiffies - rtwusb->hiq_refill; - add = elapsed / RTW_USB_HIQ_REFILL_INTERVAL; - if (add) { - rtwusb->hiq_budget = min_t(unsigned long, rtwusb->hiq_budget + add, - RTW_USB_HIQ_BUDGET_MAX); - - /* keep the unfinished part of the interval for the next unit */ - rtwusb->hiq_refill = jiffies - elapsed % RTW_USB_HIQ_REFILL_INTERVAL; - } - - ok = rtwusb->hiq_budget > 0; - if (ok) - rtwusb->hiq_budget--; - - spin_unlock_irqrestore(&rtwusb->hiq_lock, flags); - - return ok; -} - -static u8 rtw_usb_tx_queue_mapping_to_qsel(struct rtw_usb *rtwusb, +static u8 rtw_usb_tx_queue_mapping_to_qsel(struct rtw_dev *rtwdev, struct sk_buff *skb) { struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data; - struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); __le16 fc = hdr->frame_control; u8 qsel; @@ -626,8 +573,7 @@ static u8 rtw_usb_tx_queue_mapping_to_qsel(struct rtw_usb *rtwusb, qsel = TX_DESC_QSEL_MGMT; else if (is_broadcast_ether_addr(hdr->addr1) || is_multicast_ether_addr(hdr->addr1)) - qsel = (info->flags & IEEE80211_TX_CTL_SEND_AFTER_DTIM) && - rtw_usb_bmc_needs_dtim(skb) && rtw_usb_hiq_take_budget(rtwusb) ? + qsel = rtw_tx_bmc_use_hiq(rtwdev, skb) ? TX_DESC_QSEL_HIGH : skb->priority; else if (skb_get_queue_mapping(skb) <= IEEE80211_AC_BK) qsel = skb->priority; @@ -647,7 +593,7 @@ static int rtw_usb_tx_write(struct rtw_dev *rtwdev, u8 *pkt_desc; int ep; - pkt_info->qsel = rtw_usb_tx_queue_mapping_to_qsel(rtwusb, skb); + pkt_info->qsel = rtw_usb_tx_queue_mapping_to_qsel(rtwdev, skb); pkt_desc = skb_push(skb, chip->tx_pkt_desc_sz); memset(pkt_desc, 0, chip->tx_pkt_desc_sz); ep = qsel_to_ep(rtwusb, pkt_info->qsel); @@ -1088,10 +1034,6 @@ static int rtw_usb_init_tx(struct rtw_dev *rtwdev) struct rtw_usb *rtwusb = rtw_get_usb_priv(rtwdev); int i; - spin_lock_init(&rtwusb->hiq_lock); - rtwusb->hiq_budget = RTW_USB_HIQ_BUDGET_MAX; - rtwusb->hiq_refill = jiffies; - rtwusb->txwq = create_singlethread_workqueue("rtw88_usb: tx wq"); if (!rtwusb->txwq) { rtw_err(rtwdev, "failed to create TX work queue\n"); diff --git a/drivers/net/wireless/realtek/rtw88/usb.h b/drivers/net/wireless/realtek/rtw88/usb.h index 94ff21dd0846..9b695b688b24 100644 --- a/drivers/net/wireless/realtek/rtw88/usb.h +++ b/drivers/net/wireless/realtek/rtw88/usb.h @@ -75,11 +75,6 @@ struct rtw_usb { u8 out_ep[RTW_USB_EP_MAX]; int qsel_to_ep[TX_DESC_QSEL_MAX]; - /* protects hiq_budget and hiq_refill */ - spinlock_t hiq_lock; - u32 hiq_budget; - unsigned long hiq_refill; - struct workqueue_struct *txwq, *rxwq; struct sk_buff_head tx_queue[RTW_USB_EP_MAX]; diff --git a/drivers/net/wireless/virtual/mac80211_hwsim_main.c b/drivers/net/wireless/virtual/mac80211_hwsim_main.c index e53714b81ec2..49ec2948c68a 100644 --- a/drivers/net/wireless/virtual/mac80211_hwsim_main.c +++ b/drivers/net/wireless/virtual/mac80211_hwsim_main.c @@ -6179,7 +6179,7 @@ static int mac80211_hwsim_new_radio(struct genl_info *info, for (i = 0; i < ARRAY_SIZE(data->link_data); i++) { hrtimer_setup(&data->link_data[i].beacon_timer, mac80211_hwsim_beacon, - CLOCK_MONOTONIC, HRTIMER_MODE_ABS_SOFT); + CLOCK_BOOTTIME, HRTIMER_MODE_ABS_SOFT); data->link_data[i].link_id = i; } @@ -7293,7 +7293,7 @@ static int mac80211_hwsim_netlink_notify(struct notifier_block *nb, { struct netlink_notify *notify = _notify; - if (state != NETLINK_URELEASE) + if (state != NETLINK_URELEASE || notify->protocol != NETLINK_GENERIC) return NOTIFY_DONE; remove_user_radios(notify->portid, hwsim_net_get_netgroup(notify->net)); diff --git a/drivers/net/xen-netback/netback.c b/drivers/net/xen-netback/netback.c index 3cdb7fd659db..dc229756bdc2 100644 --- a/drivers/net/xen-netback/netback.c +++ b/drivers/net/xen-netback/netback.c @@ -1530,12 +1530,17 @@ static inline bool tx_dealloc_work_todo(struct xenvif_queue *queue) void xenvif_unmap_frontend_data_rings(struct xenvif_queue *queue) { - if (queue->tx.sring) + if (queue->tx.sring) { xenbus_unmap_ring_vfree(xenvif_to_xenbus_device(queue->vif), queue->tx.sring); - if (queue->rx.sring) + queue->tx.sring = NULL; + } + + if (queue->rx.sring) { xenbus_unmap_ring_vfree(xenvif_to_xenbus_device(queue->vif), queue->rx.sring); + queue->rx.sring = NULL; + } } int xenvif_map_frontend_data_rings(struct xenvif_queue *queue, diff --git a/drivers/net/xen-netback/xenbus.c b/drivers/net/xen-netback/xenbus.c index a826fa24258b..74c2745086bb 100644 --- a/drivers/net/xen-netback/xenbus.c +++ b/drivers/net/xen-netback/xenbus.c @@ -731,6 +731,7 @@ static void connect(struct backend_info *be) unsigned int queue_index; unsigned int requested_num_queues; struct xenvif_queue *queue; + unsigned int num_queues; /* Check whether the frontend requested multiple queues * and read the number requested. @@ -837,14 +838,15 @@ static void connect(struct backend_info *be) return; err: - if (be->vif->num_queues > 0) + num_queues = be->vif->num_queues; + if (num_queues > 0) xenvif_disconnect_data(be->vif); /* Clean up existing queues */ + be->vif->num_queues = 0; synchronize_net(); - for (queue_index = 0; queue_index < be->vif->num_queues; ++queue_index) + for (queue_index = 0; queue_index < num_queues; ++queue_index) xenvif_deinit_queue(&be->vif->queues[queue_index]); vfree(be->vif->queues); be->vif->queues = NULL; - be->vif->num_queues = 0; xenvif_disconnect_ctrl(be->vif); return; } diff --git a/drivers/power/sequencing/core.c b/drivers/power/sequencing/core.c index d7a545bb4ed2..a40021526c8d 100644 --- a/drivers/power/sequencing/core.c +++ b/drivers/power/sequencing/core.c @@ -270,6 +270,11 @@ static void pwrseq_device_put(struct pwrseq_device *pwrseq) * @target: Reference to the target this descriptor allows to control. * @powered_on: Power state set by the holder of the descriptor (not necessarily * corresponding to the actual power state of the device). + * + * Note: The user that requested the descriptor from the provider is + * responsible for the serialization of access to it. Concurrent threads must + * not access the descriptor structure without synchronization as power + * sequencing core does not provide any per-descriptor locking. */ struct pwrseq_desc { struct pwrseq_device *pwrseq; diff --git a/drivers/power/sequencing/pwrseq-pcie-m2.c b/drivers/power/sequencing/pwrseq-pcie-m2.c index 9c8066129359..cdadb6617762 100644 --- a/drivers/power/sequencing/pwrseq-pcie-m2.c +++ b/drivers/power/sequencing/pwrseq-pcie-m2.c @@ -296,7 +296,7 @@ static int pwrseq_pcie_m2_create_serdev_one(struct pwrseq_pcie_m2_ctx *ctx, struct serdev_controller *serdev_ctrl; struct device *dev = ctx->dev; struct pwrseq_pci_dev *pci_dev; - int ret; + int ret = 0; struct device_node *serdev_parent __free(device_node) = of_graph_get_remote_node(dev_of_node(ctx->dev), 3, 0); @@ -308,16 +308,14 @@ static int pwrseq_pcie_m2_create_serdev_one(struct pwrseq_pcie_m2_ctx *ctx, return 0; /* Bail out if the device was already attached to this controller */ - if (serdev_ctrl->serdev) { - serdev_controller_put(serdev_ctrl); - return 0; - } + if (serdev_ctrl->serdev) + goto err_put_ctrl; /* Bail out if the serdev device was already created for the PCI dev */ scoped_guard(mutex, &ctx->list_lock) { list_for_each_entry(pci_dev, &ctx->pci_devices, list) { if (pci_dev->pdev == pdev) - return 0; + goto err_put_ctrl; } } @@ -533,6 +531,14 @@ err_remove_serdev: return ret; } +static void pwrseq_pcie_m2_free_regulators(void *data) +{ + struct pwrseq_pcie_m2_ctx *ctx = data; + + regulator_bulk_free(ctx->num_vregs, ctx->regs); + kfree(ctx->regs); +} + static int pwrseq_pcie_m2_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; @@ -563,19 +569,19 @@ static int pwrseq_pcie_m2_probe(struct platform_device *pdev) ctx->num_vregs = ret; + ret = devm_add_action_or_reset(dev, pwrseq_pcie_m2_free_regulators, ctx); + if (ret) + return ret; + ctx->w_disable1_gpio = devm_gpiod_get_optional(dev, "w-disable1", GPIOD_OUT_HIGH); - if (IS_ERR(ctx->w_disable1_gpio)) { - ret = dev_err_probe(dev, PTR_ERR(ctx->w_disable1_gpio), + if (IS_ERR(ctx->w_disable1_gpio)) + return dev_err_probe(dev, PTR_ERR(ctx->w_disable1_gpio), "Failed to get the W_DISABLE_1# GPIO\n"); - goto err_free_regulators; - } ctx->w_disable2_gpio = devm_gpiod_get_optional(dev, "w-disable2", GPIOD_OUT_HIGH); - if (IS_ERR(ctx->w_disable2_gpio)) { - ret = dev_err_probe(dev, PTR_ERR(ctx->w_disable2_gpio), + if (IS_ERR(ctx->w_disable2_gpio)) + return dev_err_probe(dev, PTR_ERR(ctx->w_disable2_gpio), "Failed to get the W_DISABLE_2# GPIO\n"); - goto err_free_regulators; - } config.parent = dev; config.owner = THIS_MODULE; @@ -584,20 +590,21 @@ static int pwrseq_pcie_m2_probe(struct platform_device *pdev) config.targets = ctx->pdata->targets; ctx->pwrseq = devm_pwrseq_device_register(dev, &config); - if (IS_ERR(ctx->pwrseq)) { - ret = dev_err_probe(dev, PTR_ERR(ctx->pwrseq), + if (IS_ERR(ctx->pwrseq)) + return dev_err_probe(dev, PTR_ERR(ctx->pwrseq), "Failed to register the power sequencer\n"); - goto err_free_regulators; - } - mutex_init(&ctx->list_lock); + ret = devm_mutex_init(dev, &ctx->list_lock); + if (ret) + return ret; + INIT_LIST_HEAD(&ctx->pci_devices); ctx->dev = dev; /* Create serdev for available PCI devices (if required) */ ret = pwrseq_pcie_m2_create_serdev(ctx); if (ret) - goto err_destroy_mutex; + return ret; /* * Register a notifier for creating protocol devices for @@ -605,17 +612,7 @@ static int pwrseq_pcie_m2_probe(struct platform_device *pdev) */ ret = pwrseq_pcie_m2_register_notifier(ctx); if (ret) - goto err_remove_serdev; - - return 0; - -err_remove_serdev: - pwrseq_pcie_m2_remove_serdev(ctx, NULL); -err_destroy_mutex: - mutex_destroy(&ctx->list_lock); -err_free_regulators: - regulator_bulk_free(ctx->num_vregs, ctx->regs); - kfree(ctx->regs); + pwrseq_pcie_m2_remove_serdev(ctx, NULL); return ret; } @@ -626,10 +623,6 @@ static void pwrseq_pcie_m2_remove(struct platform_device *pdev) bus_unregister_notifier(&pci_bus_type, &ctx->nb); pwrseq_pcie_m2_remove_serdev(ctx, NULL); - mutex_destroy(&ctx->list_lock); - - regulator_bulk_free(ctx->num_vregs, ctx->regs); - kfree(ctx->regs); } static const struct of_device_id pwrseq_pcie_m2_of_match[] = { diff --git a/drivers/power/sequencing/pwrseq-qcom-wcn.c b/drivers/power/sequencing/pwrseq-qcom-wcn.c index 1145942615d6..e51b655add01 100644 --- a/drivers/power/sequencing/pwrseq-qcom-wcn.c +++ b/drivers/power/sequencing/pwrseq-qcom-wcn.c @@ -427,7 +427,7 @@ static const char *const pwrseq_wcn7850_vregs[] = { static const struct pwrseq_qcom_wcn_pdata pwrseq_wcn7850_of_data = { .vregs = pwrseq_wcn7850_vregs, .num_vregs = ARRAY_SIZE(pwrseq_wcn7850_vregs), - .pwup_delay_ms = 50, + .pwup_delay_ms = 100, .targets = pwrseq_qcom_wcn_targets, }; diff --git a/drivers/powercap/intel_rapl_common.c b/drivers/powercap/intel_rapl_common.c index 70cab5f08bc6..f58649ff4f53 100644 --- a/drivers/powercap/intel_rapl_common.c +++ b/drivers/powercap/intel_rapl_common.c @@ -1139,21 +1139,23 @@ static struct rapl_pmu rapl_pmu; /* PMU helpers */ -static void set_pmu_cpumask(struct rapl_package *rp, cpumask_var_t mask) +static int get_pmu_cpu(struct rapl_package *rp) { int cpu; if (!rp->has_pmu) - return; + return nr_cpu_ids; /* Only TPMI & MSR RAPL are supported for now */ if (rp->priv->type != RAPL_IF_TPMI && rp->priv->type != RAPL_IF_MSR) - return; + return nr_cpu_ids; /* TPMI/MSR RAPL uses any CPU in the package for PMU */ for_each_online_cpu(cpu) if (topology_physical_package_id(cpu) == rp->id) - cpumask_set_cpu(cpu, mask); + return cpu; + + return nr_cpu_ids; } static bool is_rp_pmu_cpu(struct rapl_package *rp, int cpu) @@ -1435,6 +1437,7 @@ static ssize_t cpumask_show(struct device *dev, { struct rapl_package *rp; cpumask_var_t cpu_mask; + int cpu; int ret; if (!alloc_cpumask_var(&cpu_mask, GFP_KERNEL)) @@ -1446,7 +1449,9 @@ static ssize_t cpumask_show(struct device *dev, /* Choose a cpu for each RAPL Package */ list_for_each_entry(rp, &rapl_packages, plist) { - set_pmu_cpumask(rp, cpu_mask); + cpu = get_pmu_cpu(rp); + if (cpu < nr_cpu_ids) + cpumask_set_cpu(cpu, cpu_mask); } cpus_read_unlock(); diff --git a/drivers/ptp/ptp_kvm_x86.c b/drivers/ptp/ptp_kvm_x86.c index 6cea4fe39bcf..811758bd8b0d 100644 --- a/drivers/ptp/ptp_kvm_x86.c +++ b/drivers/ptp/ptp_kvm_x86.c @@ -36,7 +36,7 @@ int kvm_arch_ptp_init(void) clock_pair = page_address(p); ret = set_memory_decrypted((unsigned long)clock_pair, 1); if (ret) { - __free_page(p); + /* The page may be left shared, so leak it. */ clock_pair = NULL; goto nofree; } @@ -68,8 +68,9 @@ nofree: void kvm_arch_ptp_exit(void) { if (cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT)) { - WARN_ON(set_memory_encrypted((unsigned long)clock_pair, 1)); - free_page((unsigned long)clock_pair); + /* Leak the page if it cannot be made private again. */ + if (!WARN_ON(set_memory_encrypted((unsigned long)clock_pair, 1))) + free_page((unsigned long)clock_pair); clock_pair = NULL; } } diff --git a/drivers/regulator/fan53555.c b/drivers/regulator/fan53555.c index f3fd5a988a1f..374cd1caa058 100644 --- a/drivers/regulator/fan53555.c +++ b/drivers/regulator/fan53555.c @@ -118,6 +118,7 @@ enum { }; enum { + SILERGY_SYM827 = 1, SILERGY_SYR82X = 8, SILERGY_SYR83X = 9, }; @@ -412,6 +413,10 @@ static int fan53555_voltages_setup_silergy(struct fan53555_device_info *di) { /* Init voltage range and step */ switch (di->chip_id) { + case SILERGY_SYM827: + di->vsel_min = 600000; + di->vsel_step = 12500; + break; case SILERGY_SYR82X: case SILERGY_SYR83X: di->vsel_min = 712500; @@ -685,6 +690,9 @@ static const struct of_device_id __maybe_unused fan53555_dt_ids[] = { .compatible = "rockchip,rk8602", .data = (void *)RK8602_VENDOR_ROCKCHIP }, { + .compatible = "silergy,sym827", + .data = (void *)FAN53555_VENDOR_SILERGY, + }, { .compatible = "silergy,syr827", .data = (void *)FAN53555_VENDOR_SILERGY, }, { @@ -794,6 +802,9 @@ static const struct i2c_device_id fan53555_id[] = { .name = "rk8602", .driver_data = RK8602_VENDOR_ROCKCHIP }, { + .name = "sym827", + .driver_data = FAN53555_VENDOR_SILERGY + }, { .name = "syr827", .driver_data = FAN53555_VENDOR_SILERGY }, { diff --git a/drivers/s390/block/dasd.c b/drivers/s390/block/dasd.c index 2ffe404b890f..3a55c937d0d6 100644 --- a/drivers/s390/block/dasd.c +++ b/drivers/s390/block/dasd.c @@ -1396,6 +1396,7 @@ int dasd_start_IO(struct dasd_ccw_req *cqr) cqr->status = DASD_CQR_ERROR; return -EIO; } + dasd_start_IO_prepare(cqr); cqr->startclk = get_tod_clock(); cqr->starttime = jiffies; cqr->retries--; @@ -2576,7 +2577,7 @@ static inline int _dasd_term_running_cqr(struct dasd_device *device) return rc; } -int dasd_sleep_on_immediatly(struct dasd_ccw_req *cqr) +int dasd_sleep_on_immediately(struct dasd_ccw_req *cqr) { struct dasd_device *device; int rc; @@ -2628,7 +2629,7 @@ int dasd_sleep_on_immediatly(struct dasd_ccw_req *cqr) return rc; } -EXPORT_SYMBOL(dasd_sleep_on_immediatly); +EXPORT_SYMBOL(dasd_sleep_on_immediately); /* * Cancels a request that was started with dasd_sleep_on_req. diff --git a/drivers/s390/block/dasd_alias.c b/drivers/s390/block/dasd_alias.c index 8d6c16d35c22..1ffcfcfe4565 100644 --- a/drivers/s390/block/dasd_alias.c +++ b/drivers/s390/block/dasd_alias.c @@ -750,7 +750,7 @@ static int reset_summary_unit_check(struct alias_lcu *lcu, cqr->buildclk = get_tod_clock(); cqr->status = DASD_CQR_FILLED; - rc = dasd_sleep_on_immediatly(cqr); + rc = dasd_sleep_on_immediately(cqr); return rc; } diff --git a/drivers/s390/block/dasd_eckd.c b/drivers/s390/block/dasd_eckd.c index 9d1b11020b4e..7e60d5b3b343 100644 --- a/drivers/s390/block/dasd_eckd.c +++ b/drivers/s390/block/dasd_eckd.c @@ -845,20 +845,29 @@ static int dasd_eckd_compare_path_uid(struct dasd_device *device, return memcmp(&device_uid, &path_uid, sizeof(struct dasd_uid)); } +/* + * The RCD buffer has to start with EBCDIC "V1.0" to show support for + * virtual device SNEQ. The RCD data is written into the same buffer, so + * a failed attempt may already have overwritten the magic. Re-initialize + * it before every start, including restarts by ERP requests. + */ +static void dasd_eckd_rcd_prepare_io(struct dasd_ccw_req *cqr) +{ + struct ccw1 *ccw = cqr->cpaddr; + __u8 *rcd_buffer = dma32_to_virt(ccw->cda); + + rcd_buffer[0] = 0xE5; + rcd_buffer[1] = 0xF1; + rcd_buffer[2] = 0x4B; + rcd_buffer[3] = 0xF0; +} + static void dasd_eckd_fill_rcd_cqr(struct dasd_device *device, struct dasd_ccw_req *cqr, __u8 *rcd_buffer, __u8 lpm) { struct ccw1 *ccw; - /* - * buffer has to start with EBCDIC "V1.0" to show - * support for virtual device SNEQ - */ - rcd_buffer[0] = 0xE5; - rcd_buffer[1] = 0xF1; - rcd_buffer[2] = 0x4B; - rcd_buffer[3] = 0xF0; ccw = cqr->cpaddr; ccw->cmd_code = DASD_ECKD_CCW_RCD; @@ -875,33 +884,10 @@ static void dasd_eckd_fill_rcd_cqr(struct dasd_device *device, cqr->retries = 256; cqr->buildclk = get_tod_clock(); cqr->status = DASD_CQR_FILLED; + cqr->prepare_io = dasd_eckd_rcd_prepare_io; set_bit(DASD_CQR_VERIFY_PATH, &cqr->flags); } -/* - * Wakeup helper for read_conf - * if the cqr is not done and needs some error recovery - * the buffer has to be re-initialized with the EBCDIC "V1.0" - * to show support for virtual device SNEQ - */ -static void read_conf_cb(struct dasd_ccw_req *cqr, void *data) -{ - struct ccw1 *ccw; - __u8 *rcd_buffer; - - if (cqr->status != DASD_CQR_DONE) { - ccw = cqr->cpaddr; - rcd_buffer = dma32_to_virt(ccw->cda); - memset(rcd_buffer, 0, sizeof(*rcd_buffer)); - - rcd_buffer[0] = 0xE5; - rcd_buffer[1] = 0xF1; - rcd_buffer[2] = 0x4B; - rcd_buffer[3] = 0xF0; - } - dasd_wakeup_cb(cqr, data); -} - static int dasd_eckd_read_conf_immediately(struct dasd_device *device, struct dasd_ccw_req *cqr, __u8 *rcd_buffer, @@ -921,8 +907,7 @@ static int dasd_eckd_read_conf_immediately(struct dasd_device *device, clear_bit(DASD_CQR_FLAGS_USE_ERP, &cqr->flags); set_bit(DASD_CQR_ALLOW_SLOCK, &cqr->flags); cqr->retries = 5; - cqr->callback = read_conf_cb; - rc = dasd_sleep_on_immediatly(cqr); + rc = dasd_sleep_on_immediately(cqr); return rc; } @@ -959,7 +944,6 @@ static int dasd_eckd_read_conf_lpm(struct dasd_device *device, goto out_error; } dasd_eckd_fill_rcd_cqr(device, cqr, rcd_buf, lpm); - cqr->callback = read_conf_cb; ret = dasd_sleep_on(cqr); /* * on success we update the user input parms @@ -2780,7 +2764,8 @@ dasd_eckd_build_check_tcw(struct dasd_device *base, struct format_data_t *fdata, return cqr; out_err: - dasd_sfree_request(cqr, startdev); + start_priv->count--; + dasd_ffree_request(cqr, startdev); return ERR_PTR(rc); } @@ -6008,7 +5993,7 @@ __context_unsafe(/* Conditional locking */) cqr->buildclk = get_tod_clock(); cqr->status = DASD_CQR_FILLED; - rc = dasd_sleep_on_immediatly(cqr); + rc = dasd_sleep_on_immediately(cqr); if (!rc) clear_bit(DASD_FLAG_IS_RESERVED, &device->flags); @@ -6064,7 +6049,7 @@ __context_unsafe(/* Conditional locking */) cqr->buildclk = get_tod_clock(); cqr->status = DASD_CQR_FILLED; - rc = dasd_sleep_on_immediatly(cqr); + rc = dasd_sleep_on_immediately(cqr); if (!rc) set_bit(DASD_FLAG_IS_RESERVED, &device->flags); @@ -6119,7 +6104,7 @@ __context_unsafe(/* Conditional locking */) cqr->buildclk = get_tod_clock(); cqr->status = DASD_CQR_FILLED; - rc = dasd_sleep_on_immediatly(cqr); + rc = dasd_sleep_on_immediately(cqr); if (!rc) set_bit(DASD_FLAG_IS_RESERVED, &device->flags); @@ -6183,7 +6168,7 @@ __context_unsafe(/* Conditional locking */) cqr->status = DASD_CQR_FILLED; cqr->lpm = usrparm.path_mask; - rc = dasd_sleep_on_immediatly(cqr); + rc = dasd_sleep_on_immediately(cqr); /* verify that I/O processing didn't modify the path mask */ if (!rc && usrparm.path_mask && (cqr->lpm != usrparm.path_mask)) rc = -EIO; @@ -6815,7 +6800,7 @@ retry: cqr->block = NULL; cqr->expires = 10 * HZ; set_bit(DASD_CQR_VERIFY_PATH, &cqr->flags); - /* dasd_sleep_on_immediatly does not do complex error + /* dasd_sleep_on_immediately does not do complex error * recovery so clear erp flag and set retry counter to * do basic erp */ clear_bit(DASD_CQR_FLAGS_USE_ERP, &cqr->flags); @@ -6847,7 +6832,7 @@ retry: cqr->buildclk = get_tod_clock(); cqr->status = DASD_CQR_FILLED; - rc = dasd_sleep_on_immediatly(cqr); + rc = dasd_sleep_on_immediately(cqr); if (rc == 0) { prssdp = (struct dasd_psf_prssd_data *) cqr->data; message_buf = (struct dasd_rssd_messages *) diff --git a/drivers/s390/block/dasd_int.h b/drivers/s390/block/dasd_int.h index ef4930432c09..53c450036fe1 100644 --- a/drivers/s390/block/dasd_int.h +++ b/drivers/s390/block/dasd_int.h @@ -147,6 +147,8 @@ struct dasd_ccw_req { void *data; /* pointer to data area */ struct irb irb; /* device status in case of an error */ struct dasd_ccw_req *refers; /* ERP-chain queueing. */ + /* optional prepare function called before every start_io, must not sleep */ + void (*prepare_io)(struct dasd_ccw_req *cqr); void *function; /* originating ERP action */ void *mem_chunk; @@ -892,6 +894,19 @@ static inline void *dasd_get_callback_data(struct dasd_ccw_req *cqr) return cqr->callback_data; } +/* + * Walk down the ERP chain to the original CQR and call its + * prepare_io function if set. + */ +static inline void dasd_start_IO_prepare(struct dasd_ccw_req *cqr) +{ + /* ERP requests use the prepare function of the original request */ + while (cqr->refers) + cqr = cqr->refers; + if (cqr->prepare_io) + cqr->prepare_io(cqr); +} + static inline bool dasd_req_conflict(struct dasd_ccw_req *cqr1, struct dasd_ccw_req *cqr2) { @@ -998,7 +1013,7 @@ void dasd_schedule_device_bh(struct dasd_device *); void dasd_schedule_block_bh(struct dasd_block *); int dasd_sleep_on(struct dasd_ccw_req *); int dasd_sleep_on_queue(struct list_head *); -int dasd_sleep_on_immediatly(struct dasd_ccw_req *); +int dasd_sleep_on_immediately(struct dasd_ccw_req *); int dasd_sleep_on_queue_interruptible(struct list_head *); int dasd_sleep_on_interruptible(struct dasd_ccw_req *); void dasd_device_set_timer(struct dasd_device *, int); diff --git a/drivers/s390/block/dasd_ioctl.c b/drivers/s390/block/dasd_ioctl.c index e5b8b413f5ab..2f2ec2bea333 100644 --- a/drivers/s390/block/dasd_ioctl.c +++ b/drivers/s390/block/dasd_ioctl.c @@ -303,7 +303,9 @@ static int dasd_ioctl_check_format(struct block_device *bdev, void __user *argp) goto out_err; } - if (copy_from_user(&cdata, argp, sizeof(cdata))) { + /* copy only input fields, clear the rest */ + memset(&cdata, 0, sizeof(cdata)); + if (copy_from_user(&cdata.expect, argp, sizeof(cdata.expect))) { rc = -EFAULT; goto out_err; } diff --git a/drivers/spi/spi-axi-spi-engine.c b/drivers/spi/spi-axi-spi-engine.c index ead5b295e680..9cfee409f15c 100644 --- a/drivers/spi/spi-axi-spi-engine.c +++ b/drivers/spi/spi-axi-spi-engine.c @@ -818,6 +818,8 @@ static int spi_engine_optimize_message(struct spi_message *msg) p = kzalloc_flex(*p, instructions, p_dry.length + 1); if (!p) return -ENOMEM; + /* spi_engine_program_add_cmd() counts the instructions as it adds them. */ + p->length = 0; spi_engine_compile_message(msg, false, p); diff --git a/drivers/spi/spi-tegra210-quad.c b/drivers/spi/spi-tegra210-quad.c index f68c46f06ce7..87c0e80f0551 100644 --- a/drivers/spi/spi-tegra210-quad.c +++ b/drivers/spi/spi-tegra210-quad.c @@ -237,6 +237,17 @@ struct tegra_qspi { bool is_packed; bool use_dma; + /* + * Set while a streaming mapping created by + * tegra_qspi_dma_map_xfer() is outstanding, together with the + * length that was handed to dma_map_single(). is_curr_dma_xfer + * only records that the last armed chunk took the DMA path, + * which is not the same thing: a chunk whose mapping failed + * leaves the DMA path flagged with nothing mapped. + */ + bool is_dma_mapped; + unsigned int dma_map_len; + u32 command1_reg; u32 dma_control_reg; u32 def_command1_reg; @@ -606,24 +617,32 @@ static int tegra_qspi_dma_map_xfer(struct tegra_qspi *tqspi, struct spi_transfer if (t->rx_buf) { t->rx_dma = dma_map_single(tqspi->rx_dma_dev, (void *)rx_buf, len, DMA_FROM_DEVICE); if (dma_mapping_error(tqspi->rx_dma_dev, t->rx_dma)) { - dma_unmap_single(tqspi->tx_dma_dev, t->tx_dma, len, DMA_TO_DEVICE); + if (t->tx_buf) + dma_unmap_single(tqspi->tx_dma_dev, t->tx_dma, + len, DMA_TO_DEVICE); return -ENOMEM; } } + tqspi->dma_map_len = len; + tqspi->is_dma_mapped = true; + return 0; } static void tegra_qspi_dma_unmap_xfer(struct tegra_qspi *tqspi, struct spi_transfer *t) { - unsigned int len; - - len = DIV_ROUND_UP(tqspi->curr_dma_words * tqspi->bytes_per_word, 4) * 4; + if (!tqspi->is_dma_mapped) + return; if (t->tx_buf) - dma_unmap_single(tqspi->tx_dma_dev, t->tx_dma, len, DMA_TO_DEVICE); + dma_unmap_single(tqspi->tx_dma_dev, t->tx_dma, + tqspi->dma_map_len, DMA_TO_DEVICE); if (t->rx_buf) - dma_unmap_single(tqspi->rx_dma_dev, t->rx_dma, len, DMA_FROM_DEVICE); + dma_unmap_single(tqspi->rx_dma_dev, t->rx_dma, + tqspi->dma_map_len, DMA_FROM_DEVICE); + + tqspi->is_dma_mapped = false; } static int tegra_qspi_start_dma_based_transfer(struct tegra_qspi *tqspi, struct spi_transfer *t) @@ -1260,8 +1279,17 @@ static int tegra_qspi_handle_timeout(struct tegra_qspi *tqspi) * loaded the cache but before we masked). */ refreshed = smp_load_acquire(&tqspi->trans_status); - if (refreshed) + if (refreshed) { status = refreshed; + /* + * The drain observed a real ISR completion. Prefer the + * ISR-published status_reg / tx_status / rx_status over + * the pre-drain lost-IRQ snapshot, which may have been + * taken after the ISR W1C-ed the hardware error bits and + * therefore holds cleared values. + */ + lost_irq_snapshot = false; + } if (!(status & QSPI_RDY)) { retval = -ETIMEDOUT; @@ -1479,10 +1507,12 @@ static int tegra_qspi_combined_seq_xfer(struct tegra_qspi *tqspi, dev_err(tqspi->dev, "transfer timeout\n"); /* Abort transfer by resetting pio/dma bit */ - if (tqspi->is_curr_dma_xfer) + if (tqspi->is_curr_dma_xfer) { tegra_qspi_dma_stop(tqspi); - else + tegra_qspi_dma_unmap_xfer(tqspi, xfer); + } else { tegra_qspi_pio_stop(tqspi); + } /* Reset controller if timeout happens */ tegra_qspi_reset(tqspi); @@ -1596,8 +1626,10 @@ static int tegra_qspi_non_combined_seq_xfer(struct tegra_qspi *tqspi, WARN_ON(1); dev_err(tqspi->dev, "transfer timeout\n"); - if (tqspi->is_curr_dma_xfer) + if (tqspi->is_curr_dma_xfer) { tegra_qspi_dma_stop(tqspi); + tegra_qspi_dma_unmap_xfer(tqspi, xfer); + } tegra_qspi_handle_error(tqspi); ret = -EIO; diff --git a/drivers/spi/spi-virtio.c b/drivers/spi/spi-virtio.c index 26f9711c99b3..2eeb79ff5aa2 100644 --- a/drivers/spi/spi-virtio.c +++ b/drivers/spi/spi-virtio.c @@ -315,10 +315,8 @@ static int virtio_spi_find_vqs(struct virtio_spi_priv *priv) } /* Function must not be called before virtio_spi_find_vqs() has been run */ -static void virtio_spi_del_vq(void *data) +static void virtio_spi_del_vq(struct virtio_device *vdev) { - struct virtio_device *vdev = data; - virtio_reset_device(vdev); vdev->config->del_vqs(vdev); } @@ -347,21 +345,26 @@ static int virtio_spi_probe(struct virtio_device *vdev) if (ret) return dev_err_probe(&vdev->dev, ret, "Cannot setup virtqueues\n"); - /* Register cleanup for virtqueues using devm */ - ret = devm_add_action_or_reset(&vdev->dev, virtio_spi_del_vq, vdev); - if (ret) - return dev_err_probe(&vdev->dev, ret, "Cannot register virtqueue cleanup\n"); - virtio_device_ready(vdev); - /* Use devm version to register controller */ - ret = devm_spi_register_controller(&vdev->dev, ctrl); - if (ret) + ret = spi_register_controller(ctrl); + if (ret) { + virtio_spi_del_vq(vdev); return dev_err_probe(&vdev->dev, ret, "Cannot register controller\n"); + } return 0; } +static void virtio_spi_remove(struct virtio_device *vdev) +{ + struct spi_controller *ctrl = dev_get_drvdata(&vdev->dev); + + spi_unregister_controller(ctrl); + + virtio_spi_del_vq(vdev); +} + static int virtio_spi_freeze(struct device *dev) { struct spi_controller *ctrl = dev_get_drvdata(dev); @@ -415,6 +418,7 @@ static struct virtio_driver virtio_spi_driver = { }, .id_table = virtio_spi_id_table, .probe = virtio_spi_probe, + .remove = virtio_spi_remove, }; module_virtio_driver(virtio_spi_driver); diff --git a/drivers/ssb/b43_pci_bridge.c b/drivers/ssb/b43_pci_bridge.c index 9c7316b5685f..5bd56b78c561 100644 --- a/drivers/ssb/b43_pci_bridge.c +++ b/drivers/ssb/b43_pci_bridge.c @@ -5,7 +5,7 @@ * because of its small size we include it in the SSB core * instead of creating a standalone module. * - * Copyright 2007 Michael Buesch <m@bues.ch> + * Copyright 2007 Michael Buesch * * Licensed under the GNU/GPL. See COPYING for details. */ diff --git a/drivers/ssb/bridge_pcmcia_80211.c b/drivers/ssb/bridge_pcmcia_80211.c index 689ff069ff37..60898ba1e0c2 100644 --- a/drivers/ssb/bridge_pcmcia_80211.c +++ b/drivers/ssb/bridge_pcmcia_80211.c @@ -1,7 +1,7 @@ /* * Broadcom 43xx PCMCIA-SSB bridge module * - * Copyright (c) 2007 Michael Buesch <m@bues.ch> + * Copyright (c) 2007 Michael Buesch * * Licensed under the GNU/GPL. See COPYING for details. */ diff --git a/drivers/ssb/driver_chipcommon.c b/drivers/ssb/driver_chipcommon.c index a8d2525e7af9..f51ee760e1fa 100644 --- a/drivers/ssb/driver_chipcommon.c +++ b/drivers/ssb/driver_chipcommon.c @@ -3,7 +3,7 @@ * Broadcom ChipCommon core driver * * Copyright 2005, Broadcom Corporation - * Copyright 2006, 2007, Michael Buesch <m@bues.ch> + * Copyright 2006, 2007, Michael Buesch * Copyright 2012, Hauke Mehrtens <hauke@hauke-m.de> * * Licensed under the GNU/GPL. See COPYING for details. diff --git a/drivers/ssb/driver_chipcommon_pmu.c b/drivers/ssb/driver_chipcommon_pmu.c index 888069e10659..c93141bf93e3 100644 --- a/drivers/ssb/driver_chipcommon_pmu.c +++ b/drivers/ssb/driver_chipcommon_pmu.c @@ -2,7 +2,7 @@ * Sonics Silicon Backplane * Broadcom ChipCommon Power Management Unit driver * - * Copyright 2009, Michael Buesch <m@bues.ch> + * Copyright 2009, Michael Buesch * Copyright 2007, Broadcom Corporation * * Licensed under the GNU/GPL. See COPYING for details. diff --git a/drivers/ssb/driver_extif.c b/drivers/ssb/driver_extif.c index bc275968fcc6..7fe777938e88 100644 --- a/drivers/ssb/driver_extif.c +++ b/drivers/ssb/driver_extif.c @@ -3,7 +3,7 @@ * Broadcom EXTIF core driver * * Copyright 2005, Broadcom Corporation - * Copyright 2006, 2007, Michael Buesch <m@bues.ch> + * Copyright 2006, 2007, Michael Buesch * Copyright 2006, 2007, Felix Fietkau <nbd@openwrt.org> * Copyright 2007, Aurelien Jarno <aurelien@aurel32.net> * diff --git a/drivers/ssb/driver_gige.c b/drivers/ssb/driver_gige.c index 0aca0711807b..822ea364397d 100644 --- a/drivers/ssb/driver_gige.c +++ b/drivers/ssb/driver_gige.c @@ -3,7 +3,7 @@ * Broadcom Gigabit Ethernet core driver * * Copyright 2008, Broadcom Corporation - * Copyright 2008, Michael Buesch <m@bues.ch> + * Copyright 2008, Michael Buesch * * Licensed under the GNU/GPL. See COPYING for details. */ diff --git a/drivers/ssb/driver_mipscore.c b/drivers/ssb/driver_mipscore.c index 354486b7ed3a..7afd9a421f72 100644 --- a/drivers/ssb/driver_mipscore.c +++ b/drivers/ssb/driver_mipscore.c @@ -3,7 +3,7 @@ * Broadcom MIPS core driver * * Copyright 2005, Broadcom Corporation - * Copyright 2006, 2007, Michael Buesch <m@bues.ch> + * Copyright 2006, 2007, Michael Buesch * * Licensed under the GNU/GPL. See COPYING for details. */ diff --git a/drivers/ssb/driver_pcicore.c b/drivers/ssb/driver_pcicore.c index d11b4242b6d2..8a9f930b77c3 100644 --- a/drivers/ssb/driver_pcicore.c +++ b/drivers/ssb/driver_pcicore.c @@ -3,7 +3,7 @@ * Broadcom PCI-core driver * * Copyright 2005, Broadcom Corporation - * Copyright 2006, 2007, Michael Buesch <m@bues.ch> + * Copyright 2006, 2007, Michael Buesch * * Licensed under the GNU/GPL. See COPYING for details. */ diff --git a/drivers/ssb/embedded.c b/drivers/ssb/embedded.c index 8254ed25e063..2a72102d6d7a 100644 --- a/drivers/ssb/embedded.c +++ b/drivers/ssb/embedded.c @@ -3,7 +3,7 @@ * Embedded systems support code * * Copyright 2005-2008, Broadcom Corporation - * Copyright 2006-2008, Michael Buesch <m@bues.ch> + * Copyright 2006-2008, Michael Buesch * Copyright 2012, Hauke Mehrtens <hauke@hauke-m.de> * * Licensed under the GNU/GPL. See COPYING for details. diff --git a/drivers/ssb/host_soc.c b/drivers/ssb/host_soc.c index 3b438480515c..fc4a9b020267 100644 --- a/drivers/ssb/host_soc.c +++ b/drivers/ssb/host_soc.c @@ -3,7 +3,7 @@ * Subsystem core * * Copyright 2005, Broadcom Corporation - * Copyright 2006, 2007, Michael Buesch <m@bues.ch> + * Copyright 2006, 2007, Michael Buesch * * Licensed under the GNU/GPL. See COPYING for details. */ diff --git a/drivers/ssb/main.c b/drivers/ssb/main.c index b2d339eb57d5..6aa3d73e185d 100644 --- a/drivers/ssb/main.c +++ b/drivers/ssb/main.c @@ -3,7 +3,7 @@ * Subsystem core * * Copyright 2005, Broadcom Corporation - * Copyright 2006, 2007, Michael Buesch <m@bues.ch> + * Copyright 2006, 2007, Michael Buesch * * Licensed under the GNU/GPL. See COPYING for details. */ diff --git a/drivers/ssb/pci.c b/drivers/ssb/pci.c index 7be74a97de2b..0e5b34e5be28 100644 --- a/drivers/ssb/pci.c +++ b/drivers/ssb/pci.c @@ -1,7 +1,7 @@ /* * Sonics Silicon Backplane PCI-Hostbus related functions. * - * Copyright (C) 2005-2006 Michael Buesch <m@bues.ch> + * Copyright (C) 2005-2006 Michael Buesch * Copyright (C) 2005 Martin Langer <martin-langer@gmx.de> * Copyright (C) 2005 Stefano Brivio <st3@riseup.net> * Copyright (C) 2005 Danny van Dyk <kugelfang@gentoo.org> diff --git a/drivers/ssb/pcihost_wrapper.c b/drivers/ssb/pcihost_wrapper.c index 5b6b5e0e4433..ae8cc9dce650 100644 --- a/drivers/ssb/pcihost_wrapper.c +++ b/drivers/ssb/pcihost_wrapper.c @@ -6,7 +6,7 @@ * Copyright (c) 2005 Stefano Brivio <st3@riseup.net> * Copyright (c) 2005 Danny van Dyk <kugelfang@gentoo.org> * Copyright (c) 2005 Andreas Jaggi <andreas.jaggi@waterwave.ch> - * Copyright (c) 2005-2007 Michael Buesch <m@bues.ch> + * Copyright (c) 2005-2007 Michael Buesch * * Licensed under the GNU/GPL. See COPYING for details. */ diff --git a/drivers/ssb/pcmcia.c b/drivers/ssb/pcmcia.c index 45502098e0c7..e244819327d4 100644 --- a/drivers/ssb/pcmcia.c +++ b/drivers/ssb/pcmcia.c @@ -3,7 +3,7 @@ * PCMCIA-Hostbus related functions * * Copyright 2006 Johannes Berg <johannes@sipsolutions.net> - * Copyright 2007-2008 Michael Buesch <m@bues.ch> + * Copyright 2007-2008 Michael Buesch * * Licensed under the GNU/GPL. See COPYING for details. */ diff --git a/drivers/ssb/scan.c b/drivers/ssb/scan.c index 4161e5d1f276..8c0ec41e5f61 100644 --- a/drivers/ssb/scan.c +++ b/drivers/ssb/scan.c @@ -2,7 +2,7 @@ * Sonics Silicon Backplane * Bus scanning * - * Copyright (C) 2005-2007 Michael Buesch <m@bues.ch> + * Copyright (C) 2005-2007 Michael Buesch * Copyright (C) 2005 Martin Langer <martin-langer@gmx.de> * Copyright (C) 2005 Stefano Brivio <st3@riseup.net> * Copyright (C) 2005 Danny van Dyk <kugelfang@gentoo.org> diff --git a/drivers/ssb/sdio.c b/drivers/ssb/sdio.c index 66c5c2169704..8b6745edc704 100644 --- a/drivers/ssb/sdio.c +++ b/drivers/ssb/sdio.c @@ -6,7 +6,7 @@ * * Based on drivers/ssb/pcmcia.c * Copyright 2006 Johannes Berg <johannes@sipsolutions.net> - * Copyright 2007-2008 Michael Buesch <m@bues.ch> + * Copyright 2007-2008 Michael Buesch * * Licensed under the GNU/GPL. See COPYING for details. * diff --git a/drivers/ssb/sprom.c b/drivers/ssb/sprom.c index 8a61a0438c85..33f728718c67 100644 --- a/drivers/ssb/sprom.c +++ b/drivers/ssb/sprom.c @@ -2,7 +2,7 @@ * Sonics Silicon Backplane * Common SPROM support routines * - * Copyright (C) 2005-2008 Michael Buesch <m@bues.ch> + * Copyright (C) 2005-2008 Michael Buesch * Copyright (C) 2005 Martin Langer <martin-langer@gmx.de> * Copyright (C) 2005 Stefano Brivio <st3@riseup.net> * Copyright (C) 2005 Danny van Dyk <kugelfang@gentoo.org> diff --git a/drivers/thunderbolt/stream.c b/drivers/thunderbolt/stream.c index 4f9a57b77bfa..c9e1987a6924 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/tty/serial/8250/8250_exar.c b/drivers/tty/serial/8250/8250_exar.c index 2737a09cf8be..42e55a8f8c69 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 e9599c5c2fea..68ce5972c296 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 f94a54cc57ca..fc9ac24340e6 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 a4e45e3923ae..0a3fb63991c1 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 6ccc6a8b653b..cd2575a3aef7 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 256d85e398d1..0831bd5ee3dc 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 9da58ffa02d5..cf1886ab1d2b 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 738536014742..7ce8f2f993e2 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 c0deec0e6af4..b06d2649be34 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 2fc48cd63f6c..f2f7cdd3a54c 100644 --- a/drivers/tty/serial/serial_port.c +++ b/drivers/tty/serial/serial_port.c @@ -23,8 +23,8 @@ /* Only considers pending TX for now. Caller must take care of locking */ static int __serial_port_busy(struct uart_port *port) { - return !uart_tx_stopped(port) && - !kfifo_is_empty(&port->state->port.xmit_fifo); + return port->x_char || (!uart_tx_stopped(port) && + !kfifo_is_empty(&port->state->port.xmit_fifo)); } static int serial_port_runtime_resume(struct device *dev) diff --git a/drivers/tty/tty_io.c b/drivers/tty/tty_io.c index 1a6c8a1bc764..150052f6d9db 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 d59d51dafa55..51d6d42519cf 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 7dbc0072a40a..6a6eb8b2a6de 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/usb/class/cdc-acm.c b/drivers/usb/class/cdc-acm.c index 489575d40bd1..666969ffd194 100644 --- a/drivers/usb/class/cdc-acm.c +++ b/drivers/usb/class/cdc-acm.c @@ -294,6 +294,7 @@ static void acm_process_notification(struct acm *acm, unsigned char *buf) unsigned long flags; struct usb_cdc_notification *dr = (struct usb_cdc_notification *)buf; unsigned char *data = buf + sizeof(struct usb_cdc_notification); + struct tty_struct *tty; switch (dr->bNotificationType) { case USB_CDC_NOTIFY_NETWORK_CONNECTION: @@ -320,12 +321,17 @@ static void acm_process_notification(struct acm *acm, unsigned char *buf) difference = acm->ctrlin ^ newctrl; - if ((difference & USB_CDC_SERIAL_STATE_DCD) && acm->port.tty) { - struct tty_ldisc *ld = tty_ldisc_ref(acm->port.tty); - if (ld) { - if (ld->ops->dcd_change) - ld->ops->dcd_change(acm->port.tty, newctrl & USB_CDC_SERIAL_STATE_DCD); - tty_ldisc_deref(ld); + if (difference & USB_CDC_SERIAL_STATE_DCD) { + tty = tty_port_tty_get(&acm->port); + if (tty) { + struct tty_ldisc *ld = tty_ldisc_ref(tty); + + if (ld) { + if (ld->ops->dcd_change) + ld->ops->dcd_change(tty, newctrl & USB_CDC_SERIAL_STATE_DCD); + tty_ldisc_deref(ld); + } + tty_kref_put(tty); } } diff --git a/drivers/usb/dwc3/core.h b/drivers/usb/dwc3/core.h index f3dabb37f806..267c922ca11b 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-xilinx.c b/drivers/usb/dwc3/dwc3-xilinx.c index c9fb8c259493..095bc3dde0fa 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 @@ err_pm_set_suspended: 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 46a34c4a046b..cf5a47b71efc 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 ee837235630a..a76f669a796c 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 @@ out: 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); diff --git a/drivers/usb/dwc3/trace.h b/drivers/usb/dwc3/trace.h index 5253da23d8b0..0caaa0b396d1 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/function/f_mass_storage.c b/drivers/usb/gadget/function/f_mass_storage.c index e3c9b7ab9f39..52314a00d8e6 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 63fb6ee70a3d..48cda34399e8 100644 --- a/drivers/usb/gadget/function/f_midi.c +++ b/drivers/usb/gadget/function/f_midi.c @@ -420,6 +420,7 @@ static void f_midi_disable(struct usb_function *f) struct f_midi *midi = func_to_midi(f); struct usb_composite_dev *cdev = f->config->cdev; struct usb_request *req = NULL; + unsigned long flags; DBG(cdev, "disable\n"); @@ -431,8 +432,10 @@ static void f_midi_disable(struct usb_function *f) usb_ep_disable(midi->out_ep); /* release IN requests */ + spin_lock_irqsave(&midi->transmit_lock, flags); while (kfifo_get(&midi->in_req_fifo, &req)) free_ep_req(midi->in_ep, req); + spin_unlock_irqrestore(&midi->transmit_lock, flags); f_midi_drop_out_substreams(midi); } @@ -661,6 +664,7 @@ static int f_midi_do_transmit(struct f_midi *midi, struct usb_ep *ep) ERROR(midi, "%s failed to queue req: %d\n", midi->in_ep->name, err); req->length = 0; /* Re-use request next time. */ + return err; } else { /* Upon success, put request at the back of the queue. */ kfifo_skip(&midi->in_req_fifo); diff --git a/drivers/usb/gadget/function/f_ncm.c b/drivers/usb/gadget/function/f_ncm.c index 7f4324981eb3..7e945668f017 100644 --- a/drivers/usb/gadget/function/f_ncm.c +++ b/drivers/usb/gadget/function/f_ncm.c @@ -1148,6 +1148,7 @@ static enum hrtimer_restart ncm_tx_timeout(struct hrtimer *data) { struct f_ncm *ncm = container_of(data, struct f_ncm, task_timer); struct net_device *netdev = READ_ONCE(ncm->netdev); + netdev_tx_t ret; if (netdev) { /* XXX This allowance of a NULL skb argument to ndo_start_xmit @@ -1158,7 +1159,11 @@ static enum hrtimer_restart ncm_tx_timeout(struct hrtimer *data) * * This will call directly into u_ether's eth_start_xmit() */ - netdev->netdev_ops->ndo_start_xmit(NULL, netdev); + ret = netdev->netdev_ops->ndo_start_xmit(NULL, netdev); + if (ret == NETDEV_TX_BUSY) { + hrtimer_forward_now(data, TX_TIMEOUT_NSECS); + return HRTIMER_RESTART; + } } return HRTIMER_NORESTART; } diff --git a/drivers/usb/gadget/function/storage_common.c b/drivers/usb/gadget/function/storage_common.c index 75831f2c7abe..51a70f2abe57 100644 --- a/drivers/usb/gadget/function/storage_common.c +++ b/drivers/usb/gadget/function/storage_common.c @@ -415,7 +415,8 @@ ssize_t fsg_store_ro(struct fsg_lun *curlun, struct rw_semaphore *filesem, } EXPORT_SYMBOL_GPL(fsg_store_ro); -ssize_t fsg_store_nofua(struct fsg_lun *curlun, const char *buf, size_t count) +ssize_t fsg_store_nofua(struct fsg_lun *curlun, struct rw_semaphore *filesem, + const char *buf, size_t count) { bool nofua; int ret; @@ -425,8 +426,10 @@ ssize_t fsg_store_nofua(struct fsg_lun *curlun, const char *buf, size_t count) return ret; /* Sync data when switching from async mode to sync */ - if (!nofua && curlun->nofua) + if (!nofua && curlun->nofua) { + guard(rwsem_read)(filesem); fsg_lun_fsync_sub(curlun); + } curlun->nofua = nofua; diff --git a/drivers/usb/gadget/function/storage_common.h b/drivers/usb/gadget/function/storage_common.h index e73a30cc553f..e66b753d7cbd 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_serial.c b/drivers/usb/gadget/function/u_serial.c index cdd1dfc666c4..0a304f508bc3 100644 --- a/drivers/usb/gadget/function/u_serial.c +++ b/drivers/usb/gadget/function/u_serial.c @@ -70,10 +70,28 @@ * gserial->ioport == usb_ep->driver_data ... gs_port * gs_port->port_usb ... gserial * - * gs_port <---> tty_struct ... links will be null when the TTY file - * isn't opened; managed by gs_open()/gs_close() - * gserial->port_tty ... tty_struct - * tty_struct->driver_data ... gserial + * gs_port <---> tty_struct: + * tty->driver_data refers to gs_port from install through cleanup, + * pinning the port via tty_port reference counting. + * gs_port->port.tty exists only while the port is open. + * + * Each entry in ports[] is guarded by ports[i].lock and models three states: + * - Free: !port && !reserved + * - Published: port && reserved + * - Retiring: !port && reserved + * + * A minor remains reserved until gs_port_destruct() runs upon final tty_port + * release, preventing minor reuse while cleanup of the installed TTY is still + * underway. The owner reference is retained through device unregister so the + * destructor releases the reservation only after device teardown is complete. + * + * open_close_failures tracks failed gs_open() calls where port->port.count + * was not incremented. The TTY core calls gs_close() on open failure to tear + * down the tty; tracking failures as aggregate credits allows gs_close() to + * consume a credit and exit without decrementing port->port.count. Credits + * are aggregate rather than paired with individual files (another gs_close() + * can consume a failed open's credit before that file's own close runs). + * It is protected by tty_lock. */ /* RX and TX queues can buffer QUEUE_SIZE packets before they hit the @@ -128,6 +146,7 @@ struct gs_port { wait_queue_head_t close_wait; bool suspended; /* port suspended */ bool start_delayed; /* delay start when suspended */ + unsigned int open_close_failures; /* protected by tty_lock */ struct async_icount icount; /* REVISIT this state ... */ @@ -135,8 +154,9 @@ struct gs_port { }; static struct portmaster { - struct mutex lock; /* protect open/close */ + struct mutex lock; /* protect open/close and port slot */ struct gs_port *port; + bool reserved; } ports[MAX_U_SERIAL_PORTS]; #define GS_CLOSE_TIMEOUT 15 /* seconds */ @@ -603,22 +623,60 @@ static int gserial_wakeup_host(struct gserial *gser) /* TTY Driver */ +static int gs_install(struct tty_driver *driver, struct tty_struct *tty) +{ + struct gs_port *port; + struct tty_port *tport; + int ret; + + mutex_lock(&ports[tty->index].lock); + port = ports[tty->index].port; + if (!port) { + mutex_unlock(&ports[tty->index].lock); + return -ENODEV; + } + + tport = tty_port_get(&port->port); + if (!tport) { + mutex_unlock(&ports[tty->index].lock); + return -ENODEV; + } + + ret = tty_port_install(tport, driver, tty); + if (ret) { + mutex_unlock(&ports[tty->index].lock); + tty_port_put(tport); + return ret; + } + + tty->driver_data = port; + mutex_unlock(&ports[tty->index].lock); + + return 0; +} + +static void gs_cleanup(struct tty_struct *tty) +{ + tty_port_put(tty->port); +} + /* - * gs_open sets up the link between a gs_port and its associated TTY. - * That link is broken *only* by TTY close(), and all driver methods - * know that. + * gs_open associates an open TTY with its gs_port. + * + * There are two TTY-to-port relationships: port->port.tty exists from the + * first successful open until final close, while tty->driver_data is assigned + * during gs_install() and remains valid through gs_cleanup(). */ static int gs_open(struct tty_struct *tty, struct file *file) { int port_num = tty->index; - struct gs_port *port; + struct gs_port *port = tty->driver_data; int status = 0; mutex_lock(&ports[port_num].lock); - port = ports[port_num].port; - if (!port) { + if (ports[port_num].port != port) { status = -ENODEV; - goto out; + goto fail_unlock; } spin_lock_irq(&port->port_lock); @@ -638,7 +696,7 @@ static int gs_open(struct tty_struct *tty, struct file *file) if (status) { pr_debug("gs_open: ttyGS%d (%p,%p) no buffer\n", port_num, tty, file); - goto out; + goto fail_unlock; } spin_lock_irq(&port->port_lock); @@ -648,7 +706,6 @@ static int gs_open(struct tty_struct *tty, struct file *file) if (port->port.count++) goto exit_unlock_port; - tty->driver_data = port; port->port.tty = tty; /* if connected, start the I/O stream */ @@ -672,7 +729,11 @@ static int gs_open(struct tty_struct *tty, struct file *file) exit_unlock_port: spin_unlock_irq(&port->port_lock); -out: + mutex_unlock(&ports[port_num].lock); + return status; + +fail_unlock: + port->open_close_failures++; mutex_unlock(&ports[port_num].lock); return status; } @@ -695,6 +756,14 @@ static void gs_close(struct tty_struct *tty, struct file *file) struct gs_port *port = tty->driver_data; struct gserial *gser; + if (!port) + return; + + if (port->open_close_failures > 0) { + port->open_close_failures--; + return; + } + spin_lock_irq(&port->port_lock); if (port->port.count != 1) { @@ -909,8 +978,10 @@ static int gs_get_icount(struct tty_struct *tty, } static const struct tty_operations gs_tty_ops = { + .install = gs_install, .open = gs_open, .close = gs_close, + .cleanup = gs_cleanup, .write = gs_write, .put_char = gs_put_char, .flush_chars = gs_flush_chars, @@ -1203,14 +1274,41 @@ static void gs_console_exit(struct gs_port *port) #endif -static int +static void gs_port_destruct(struct tty_port *tport) +{ + struct gs_port *port = container_of(tport, struct gs_port, port); + unsigned int port_num = port->port_num; + + mutex_lock(&ports[port_num].lock); + if (WARN_ON(ports[port_num].port)) + ports[port_num].port = NULL; + WARN_ON(!ports[port_num].reserved); + if (gs_tty_driver) + gs_tty_driver->ports[port_num] = NULL; + ports[port_num].reserved = false; + mutex_unlock(&ports[port_num].lock); + + kfifo_free(&port->port_write_buf); + kfree(port); +} + +static const struct tty_port_operations gs_port_ops = { + .destruct = gs_port_destruct, +}; + +static struct gs_port * gs_port_alloc(unsigned port_num, struct usb_cdc_line_coding *coding) { struct gs_port *port; int ret = 0; mutex_lock(&ports[port_num].lock); - if (ports[port_num].port) { + if (WARN_ON_ONCE(ports[port_num].port && !ports[port_num].reserved)) { + ret = -EBUSY; + goto out; + } + + if (ports[port_num].reserved) { ret = -EBUSY; goto out; } @@ -1222,6 +1320,7 @@ gs_port_alloc(unsigned port_num, struct usb_cdc_line_coding *coding) } tty_port_init(&port->port); + port->port.ops = &gs_port_ops; spin_lock_init(&port->port_lock); init_waitqueue_head(&port->drain_wait); init_waitqueue_head(&port->close_wait); @@ -1235,10 +1334,14 @@ gs_port_alloc(unsigned port_num, struct usb_cdc_line_coding *coding) port->port_num = port_num; port->port_line_coding = *coding; + ports[port_num].reserved = true; ports[port_num].port = port; + mutex_unlock(&ports[port_num].lock); + return port; + out: mutex_unlock(&ports[port_num].lock); - return ret; + return ERR_PTR(ret); } static int gs_closed(struct gs_port *port) @@ -1258,8 +1361,7 @@ static void gserial_free_port(struct gs_port *port) /* wait for old opens to finish */ wait_event(port->close_wait, gs_closed(port)); WARN_ON(port->port_usb != NULL); - tty_port_destroy(&port->port); - kfree(port); + tty_port_put(&port->port); } void gserial_free_line(unsigned char port_num) @@ -1276,15 +1378,15 @@ void gserial_free_line(unsigned char port_num) ports[port_num].port = NULL; mutex_unlock(&ports[port_num].lock); - gserial_free_port(port); tty_unregister_device(gs_tty_driver, port_num); + gserial_free_port(port); } EXPORT_SYMBOL_GPL(gserial_free_line); int gserial_alloc_line_no_console(unsigned char *line_num) { struct usb_cdc_line_coding coding; - struct gs_port *port; + struct gs_port *port = ERR_PTR(-EBUSY); struct device *tty_dev; int ret; int port_num; @@ -1295,19 +1397,20 @@ int gserial_alloc_line_no_console(unsigned char *line_num) coding.bDataBits = USB_CDC_1_STOP_BITS; for (port_num = 0; port_num < MAX_U_SERIAL_PORTS; port_num++) { - ret = gs_port_alloc(port_num, &coding); - if (ret == -EBUSY) - continue; - if (ret) + port = gs_port_alloc(port_num, &coding); + if (IS_ERR(port)) { + ret = PTR_ERR(port); + if (ret == -EBUSY) + continue; return ret; + } break; } - if (ret) - return ret; + if (IS_ERR(port)) + return PTR_ERR(port); /* ... and sysfs class devices, so mdev/udev make /dev/ttyGS* */ - port = ports[port_num].port; tty_dev = tty_port_register_device(&port->port, gs_tty_driver, port_num, NULL); if (IS_ERR(tty_dev)) { @@ -1316,14 +1419,15 @@ int gserial_alloc_line_no_console(unsigned char *line_num) ret = PTR_ERR(tty_dev); mutex_lock(&ports[port_num].lock); + WARN_ON(ports[port_num].port != port); ports[port_num].port = NULL; mutex_unlock(&ports[port_num].lock); - gserial_free_port(port); - goto err; + tty_port_put(&port->port); + return ret; } + *line_num = port_num; -err: - return ret; + return 0; } EXPORT_SYMBOL_GPL(gserial_alloc_line_no_console); diff --git a/drivers/usb/host/bcma-hcd.c b/drivers/usb/host/bcma-hcd.c index 9b7bb8bad35f..a6aa77189535 100644 --- a/drivers/usb/host/bcma-hcd.c +++ b/drivers/usb/host/bcma-hcd.c @@ -7,7 +7,7 @@ * Copyright 2015 Felix Fietkau <nbd@openwrt.org> * * Based on ssb-ohci driver - * Copyright 2007 Michael Buesch <m@bues.ch> + * Copyright 2007 Michael Buesch * * Derived from the OHCI-PCI driver * Copyright 1999 Roman Weissgaerber diff --git a/drivers/usb/host/pci-quirks.c b/drivers/usb/host/pci-quirks.c index f670e7aab984..1dbfd697a582 100644 --- a/drivers/usb/host/pci-quirks.c +++ b/drivers/usb/host/pci-quirks.c @@ -1195,10 +1195,11 @@ static void quirk_usb_handoff_xhci(struct pci_dev *pdev) && pdev->device == 0x0014)) { val = (val | XHCI_HC_OS_OWNED) & ~XHCI_HC_BIOS_OWNED; writel(val, base + ext_cap_offset); - } - - /* If the BIOS owns the HC, signal that the OS wants it, and wait */ - if (val & XHCI_HC_BIOS_OWNED) { + } else { + /* + * Perform the standard handoff and leave OS ownership set to + * keep the BIOS at bay during subsequent suspends. + */ writel(val | XHCI_HC_OS_OWNED, base + ext_cap_offset); /* Wait for 1 second with 10 microsecond polling interval */ @@ -1210,7 +1211,9 @@ static void quirk_usb_handoff_xhci(struct pci_dev *pdev) dev_warn(&pdev->dev, "xHCI BIOS handoff failed (BIOS bug ?) %08x\n", val); - writel(val & ~XHCI_HC_BIOS_OWNED, base + ext_cap_offset); + writel((val | XHCI_HC_OS_OWNED) & + ~XHCI_HC_BIOS_OWNED, + base + ext_cap_offset); } } diff --git a/drivers/usb/host/ssb-hcd.c b/drivers/usb/host/ssb-hcd.c index ec3627295a6d..56d785c587c0 100644 --- a/drivers/usb/host/ssb-hcd.c +++ b/drivers/usb/host/ssb-hcd.c @@ -6,7 +6,7 @@ * Copyright 2011-2012 Hauke Mehrtens <hauke@hauke-m.de> * * Based on ssb-ohci driver - * Copyright 2007 Michael Buesch <m@bues.ch> + * Copyright 2007 Michael Buesch * * Derived from the OHCI-PCI driver * Copyright 1999 Roman Weissgaerber diff --git a/drivers/usb/host/xhci-hub.c b/drivers/usb/host/xhci-hub.c index 470bafe1802b..55430b673f1e 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 af8d4b74c4ba..75577f441cdd 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 c23434001e9c..a1fa188680f5 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,33 +1012,64 @@ 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) { xhci_dbg(xhci, "Reset ep command for ep_index %d already pending\n", ep->ep_index); 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 30ac1bc4559b..fc1b0a6b0429 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/misc/usbtest.c b/drivers/usb/misc/usbtest.c index 8759df49be28..e2f5e6be353a 100644 --- a/drivers/usb/misc/usbtest.c +++ b/drivers/usb/misc/usbtest.c @@ -466,6 +466,9 @@ static int simple_io( int retval = 0; unsigned long expire; + if (vary && !max) + return -EINVAL; + urb->context = &completion; while (retval == 0 && iterations-- > 0) { init_completion(&completion); diff --git a/drivers/usb/serial/garmin_gps.c b/drivers/usb/serial/garmin_gps.c index 8020149f5658..a7c18a8fdf59 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 eaa8f00716c8..0fd68faa8427 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,38 +1441,16 @@ 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 * * Purpose: Let user call ioctl() to get info when the UART physically @@ -1499,6 +1486,7 @@ static int edge_tiocmset(struct tty_struct *tty, struct edgeport_port *edge_port = usb_get_serial_port_data(port); unsigned int mcr; + mutex_lock(&edge_port->mutex); mcr = edge_port->shadowMCR; if (set & TIOCM_RTS) mcr |= MCR_RTS; @@ -1517,6 +1505,7 @@ static int edge_tiocmset(struct tty_struct *tty, edge_port->shadowMCR = mcr; send_cmd_write_uart_register(edge_port, MCR, edge_port->shadowMCR); + mutex_unlock(&edge_port->mutex); return 0; } @@ -1530,6 +1519,7 @@ static int edge_tiocmget(struct tty_struct *tty) unsigned int mcr; msr = edge_port->shadowMSR; + mutex_lock(&edge_port->mutex); mcr = edge_port->shadowMCR; result = ((mcr & MCR_DTR) ? TIOCM_DTR: 0) /* 0x002 */ | ((mcr & MCR_RTS) ? TIOCM_RTS: 0) /* 0x004 */ @@ -1537,6 +1527,7 @@ static int edge_tiocmget(struct tty_struct *tty) | ((msr & EDGEPORT_MSR_CD) ? TIOCM_CAR: 0) /* 0x040 */ | ((msr & EDGEPORT_MSR_RI) ? TIOCM_RI: 0) /* 0x080 */ | ((msr & EDGEPORT_MSR_DSR) ? TIOCM_DSR: 0); /* 0x100 */ + mutex_unlock(&edge_port->mutex); return result; } @@ -1752,9 +1743,9 @@ static void process_rcvd_status(struct edgeport_serial *edge_serial, { struct usb_serial_port *port; struct edgeport_port *edge_port; - struct tty_struct *tty; struct device *dev; __u8 code = edge_serial->rxStatusCode; + unsigned long flags; /* switch the port pointer to the one being currently talked about */ if (edge_serial->rxPort >= edge_serial->serial->num_ports) @@ -1798,24 +1789,22 @@ static void process_rcvd_status(struct edgeport_serial *edge_serial, } if (code == IOSP_STATUS_OPEN_RSP) { + spin_lock_irqsave(&edge_port->ep_lock, flags); + /* reject stray open responses to avoid FIFO corruption */ + if (!edge_port->openPending) { + spin_unlock_irqrestore(&edge_port->ep_lock, flags); + return; + } edge_port->txCredits = GET_TX_BUFFER_SIZE(byte3); edge_port->maxTxCredits = edge_port->txCredits; dev_dbg(dev, "%s - Port %u Open Response Initial MSR = %02x TxBufferSize = %d\n", __func__, edge_serial->rxPort, byte2, edge_port->txCredits); handle_new_msr(edge_port, byte2); - /* send the current line settings to the port so we are - in sync with any further termios calls */ - tty = tty_port_tty_get(&edge_port->port->port); - if (tty) { - change_port_settings(tty, - edge_port, &tty->termios); - tty_kref_put(tty); - } - /* we have completed the open */ edge_port->openPending = false; - edge_port->open = true; + spin_unlock_irqrestore(&edge_port->ep_lock, flags); + wake_up(&edge_port->wait_open); return; } @@ -2143,24 +2132,21 @@ static int write_cmd_usb(struct edgeport_port *edge_port, if (!urb) return -ENOMEM; - atomic_inc(&CmdUrbs); - dev_dbg(dev, "%s - ALLOCATE URB %p (outstanding %d)\n", - __func__, urb, atomic_read(&CmdUrbs)); - usb_fill_bulk_urb(urb, edge_serial->serial->dev, usb_sndbulkpipe(edge_serial->serial->dev, edge_serial->bulk_out_endpoint), buffer, length, edge_bulk_out_cmd_callback, edge_port); edge_port->commandPending = true; + usb_anchor_urb(urb, &edge_serial->cmd_anchor); status = usb_submit_urb(urb, GFP_ATOMIC); if (status) { /* something went wrong */ dev_err(dev, "%s - usb_submit_urb(write command) failed, status = %d\n", __func__, status); + usb_unanchor_urb(urb); usb_free_urb(urb); - atomic_dec(&CmdUrbs); return status; } @@ -2325,18 +2311,12 @@ static int send_cmd_write_uart_register(struct edgeport_port *edge_port, } -/***************************************************************************** - * change_port_settings - * This routine is called to set the UART on the device to match the - * specified new settings. - *****************************************************************************/ - -static void change_port_settings(struct tty_struct *tty, - struct edgeport_port *edge_port, const struct ktermios *old_termios) +static void edge_set_termios(struct tty_struct *tty, struct usb_serial_port *port, + const struct ktermios *old_termios) { - struct device *dev = &edge_port->port->dev; - struct edgeport_serial *edge_serial = - usb_get_serial_data(edge_port->port->serial); + struct edgeport_serial *edge_serial = usb_get_serial_data(port->serial); + struct edgeport_port *edge_port = usb_get_serial_port_data(port); + struct device *dev = &port->dev; int baud; unsigned cflag; __u8 mask = 0xff; @@ -2347,12 +2327,6 @@ static void change_port_settings(struct tty_struct *tty, __u8 txFlow; int status; - if (!edge_port->open && - !edge_port->openPending) { - dev_dbg(dev, "%s - port not opened\n", __func__); - return; - } - cflag = tty->termios.c_cflag; switch (cflag & CSIZE) { @@ -2468,12 +2442,14 @@ static void change_port_settings(struct tty_struct *tty, return; /* set up the MCR register and send it to the EdgePort */ + mutex_lock(&edge_port->mutex); edge_port->shadowMCR = MCR_MASTER_IE; if (cflag & CBAUD) edge_port->shadowMCR |= (MCR_DTR | MCR_RTS); status = send_cmd_write_uart_register(edge_port, MCR, edge_port->shadowMCR); + mutex_unlock(&edge_port->mutex); if (status != 0) return; @@ -2486,7 +2462,7 @@ static void change_port_settings(struct tty_struct *tty, dev_dbg(dev, "%s - baud rate = %d\n", __func__, baud); status = send_cmd_write_baud_rate(edge_port, baud); - if (status == -1) { + if (status == -1 && old_termios) { /* Speed change was not possible - put back the old speed */ baud = tty_termios_baud_rate(old_termios); tty_encode_baud_rate(tty, baud, baud); @@ -2724,6 +2700,7 @@ static int edge_startup(struct usb_serial *serial) spin_lock_init(&edge_serial->es_lock); edge_serial->serial = serial; + init_usb_anchor(&edge_serial->cmd_anchor); usb_set_serial_data(serial, edge_serial); /* get the name for the device from the device */ @@ -2928,6 +2905,8 @@ static void edge_disconnect(struct usb_serial *serial) { struct edgeport_serial *edge_serial = usb_get_serial_data(serial); + usb_kill_anchored_urbs(&edge_serial->cmd_anchor); + if (edge_serial->is_epic) { usb_kill_urb(edge_serial->interrupt_read_urb); usb_kill_urb(edge_serial->read_urb); @@ -2965,6 +2944,12 @@ static int edge_port_probe(struct usb_serial_port *port) return -ENOMEM; spin_lock_init(&edge_port->ep_lock); + mutex_init(&edge_port->mutex); + + init_waitqueue_head(&edge_port->wait_open); + init_waitqueue_head(&edge_port->wait_chase); + init_waitqueue_head(&edge_port->wait_command); + edge_port->port = port; usb_set_serial_port_data(port, edge_port); diff --git a/drivers/usb/serial/oti6858.c b/drivers/usb/serial/oti6858.c index c6364e8ff71f..005fe19c3cd4 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 f2cc7f364d20..c6aa5dfe468b 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 78c4d3c19a8e..f2189b994ed7 100644 --- a/drivers/usb/serial/upd78f0730.c +++ b/drivers/usb/serial/upd78f0730.c @@ -201,10 +201,9 @@ static int upd78f0730_tiocmget(struct tty_struct *tty) return res; } -static int upd78f0730_tiocmset(struct tty_struct *tty, +static int upd78f0730_port_tiocmset(struct usb_serial_port *port, unsigned int set, unsigned int clear) { - struct usb_serial_port *port = tty->driver_data; struct upd78f0730_port_private *private; struct upd78f0730_set_dtr_rts request; struct device *dev = &port->dev; @@ -238,6 +237,13 @@ static int upd78f0730_tiocmset(struct tty_struct *tty, return res; } +static int upd78f0730_tiocmset(struct tty_struct *tty, unsigned int set, unsigned int clear) +{ + struct usb_serial_port *port = tty->driver_data; + + return upd78f0730_port_tiocmset(port, set, clear); +} + static int upd78f0730_break_ctl(struct tty_struct *tty, int break_state) { struct upd78f0730_port_private *private; @@ -267,7 +273,6 @@ static int upd78f0730_break_ctl(struct tty_struct *tty, int break_state) static void upd78f0730_dtr_rts(struct usb_serial_port *port, int on) { - struct tty_struct *tty = port->port.tty; unsigned int set = 0; unsigned int clear = 0; @@ -276,7 +281,7 @@ static void upd78f0730_dtr_rts(struct usb_serial_port *port, int on) else clear = TIOCM_DTR | TIOCM_RTS; - upd78f0730_tiocmset(tty, set, clear); + upd78f0730_port_tiocmset(port, set, clear); } static speed_t upd78f0730_get_baud_rate(struct tty_struct *tty) diff --git a/drivers/usb/storage/uas-detect.h b/drivers/usb/storage/uas-detect.h index 4d3b49e5b87a..523a17cf0a3c 100644 --- a/drivers/usb/storage/uas-detect.h +++ b/drivers/usb/storage/uas-detect.h @@ -78,6 +78,8 @@ static int uas_use_uas_driver(struct usb_interface *intf, * ASM1051 - with broken (*) uas support * ASM1053 - with working uas support, but problems with large xfers * ASM1153 - with working uas support + * ASMT135x - broken uas support, shares the ASM1153 MaxPower == 0 + * signature, identify it by its product string * * Devices with these chips re-use a number of device-ids over the * entire line, so the device-id is useless to determine if we're @@ -99,7 +101,11 @@ static int uas_use_uas_driver(struct usb_interface *intf, (le16_to_cpu(udev->descriptor.idProduct) == 0x5106 || le16_to_cpu(udev->descriptor.idProduct) == 0x55aa)) { if (udev->actconfig->desc.bMaxPower == 0) { - /* ASM1153, do nothing */ + if (udev->product && strstr(udev->product, "ASMT135")) { + /* ASMT135x, broken uas */ + flags |= US_FL_IGNORE_UAS; + } + /* else ASM1153, do nothing */ } else if (udev->speed < USB_SPEED_SUPER) { /* No streams info, assume ASM1051 */ flags |= US_FL_IGNORE_UAS; diff --git a/drivers/usb/typec/mux/fsa4480.c b/drivers/usb/typec/mux/fsa4480.c index 88783f9ed44c..c3c629212574 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 00b2a1784e6c..d1856a3fd60c 100644 --- a/drivers/usb/typec/mux/nb7vpq904m.c +++ b/drivers/usb/typec/mux/nb7vpq904m.c @@ -396,6 +396,7 @@ static int nb7vpq904m_probe(struct i2c_client *client) return -ENOMEM; nb7->client = client; + i2c_set_clientdata(client, nb7); nb7->regmap = devm_regmap_init_i2c(client, &nb7_regmap); if (IS_ERR(nb7->regmap)) { diff --git a/drivers/usb/typec/ucsi/debugfs.c b/drivers/usb/typec/ucsi/debugfs.c index 77a0dd75edd3..3cffd3778c67 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 5aab8ab9f013..9e453d216c16 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 @@ err_unregister: 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 1996f04ed5e6..140d34e90c7c 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 2d079d7177ac..aae358f23268 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) @@ -198,6 +226,13 @@ static const struct dmi_system_id ucsi_acpi_quirks[] = { }, { .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"), DMI_MATCH(DMI_PRODUCT_FAMILY, "LG gram PC"), DMI_MATCH(DMI_PRODUCT_NAME, "90Q"), diff --git a/drivers/w1/masters/ds2482.c b/drivers/w1/masters/ds2482.c index eee9df238f6a..700c11aecbad 100644 --- a/drivers/w1/masters/ds2482.c +++ b/drivers/w1/masters/ds2482.c @@ -103,6 +103,7 @@ struct ds2482_data; struct ds2482_w1_chan { struct ds2482_data *pdev; u8 channel; + bool spu; /* strong pullup after the next byte */ struct w1_bus_master w1_bm; }; @@ -336,6 +337,19 @@ static void ds2482_w1_write_byte(void *data, u8 byte) if (pdev->w1_count > 1) ds2482_set_channel(pdev, pchan->channel); + if (pchan->spu) { + pchan->spu = false; + /* the wait above and this one are crucial, otherwise devices + * might not be powered long enough, causing e.g. a w1_therm + * sensor to provide wrong conversion results + */ + /* note: it seems like both SPU and APU have to be set! */ + ds2482_send_cmd_data(pdev, DS2482_CMD_WRITE_CONFIG, + ds2482_calculate_config(DS2482_REG_CFG_SPU | + DS2482_REG_CFG_APU)); + ds2482_wait_1wire_idle(pdev); + } + /* Send the write byte command */ ds2482_send_cmd_data(pdev, DS2482_CMD_1WIRE_WRITE_BYTE, byte); @@ -420,27 +434,19 @@ static u8 ds2482_w1_reset_bus(void *data) static u8 ds2482_w1_set_pullup(void *data, int delay) { struct ds2482_w1_chan *pchan = data; - struct ds2482_data *pdev = pchan->pdev; - u8 retval = 1; /* if delay is non-zero activate the pullup, * the strong pullup will be automatically deactivated * by the master, so do not explicitly deactive it + * + * The setting is used up by the next byte on any channel of the chip: + * ds2482_w1_write_byte() makes it, in one go with the byte. */ - if (delay) { - /* both waits are crucial, otherwise devices might not be - * powered long enough, causing e.g. a w1_therm sensor to - * provide wrong conversion results - */ - ds2482_wait_1wire_idle(pdev); - /* note: it seems like both SPU and APU have to be set! */ - retval = ds2482_send_cmd_data(pdev, DS2482_CMD_WRITE_CONFIG, - ds2482_calculate_config(DS2482_REG_CFG_SPU | - DS2482_REG_CFG_APU)); - ds2482_wait_1wire_idle(pdev); - } + if (!delay) + return 1; - return retval; + pchan->spu = true; + return 0; } diff --git a/drivers/w1/slaves/w1_ds2805.c b/drivers/w1/slaves/w1_ds2805.c index 9c86b7985d0b..bfcc02ecbdb9 100644 --- a/drivers/w1/slaves/w1_ds2805.c +++ b/drivers/w1/slaves/w1_ds2805.c @@ -102,7 +102,7 @@ static ssize_t w1_f0d_read_bin(struct file *filp, struct kobject *kobj, if (count == 0) return 0; - mutex_lock(&sl->master->mutex); + mutex_lock(&sl->master->bus_mutex); /* read directly from the EEPROM in chunks of W1_F0D_READ_MAXLEN */ while (todo > 0) { @@ -123,7 +123,7 @@ static ssize_t w1_f0d_read_bin(struct file *filp, struct kobject *kobj, off += W1_F0D_READ_MAXLEN; } - mutex_unlock(&sl->master->mutex); + mutex_unlock(&sl->master->bus_mutex); return count; } @@ -211,7 +211,7 @@ static ssize_t w1_f0d_write_bin(struct file *filp, struct kobject *kobj, if (count == 0) return 0; - mutex_lock(&sl->master->mutex); + mutex_lock(&sl->master->bus_mutex); /* Can only write data in blocks of the size of the scratchpad */ addr = off; @@ -256,7 +256,7 @@ static ssize_t w1_f0d_write_bin(struct file *filp, struct kobject *kobj, } out_up: - mutex_unlock(&sl->master->mutex); + mutex_unlock(&sl->master->bus_mutex); return count; } diff --git a/drivers/w1/slaves/w1_ds28e04.c b/drivers/w1/slaves/w1_ds28e04.c index 3b3c0789e1ad..30fb8415b659 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 d96b224e2215..d8751b29f420 100644 --- a/drivers/w1/slaves/w1_therm.c +++ b/drivers/w1/slaves/w1_therm.c @@ -907,6 +907,19 @@ static inline bool bulk_read_support(struct w1_slave *sl) } /** + * 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 @@ mt_unlock: 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 c16946642789..4eb785c643c9 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 19a0ea28e9f3..3fcc9ee56727 100644 --- a/drivers/w1/w1_int.c +++ b/drivers/w1/w1_int.c @@ -176,6 +176,13 @@ void __w1_remove_master_device(struct w1_master *dev) mutex_unlock(&w1_mlock); set_bit(W1_ABORT_SEARCH, &dev->flags); + + /* + * This waits for the callbacks, which take the locks below. One of + * them wakes the thread up. + */ + w1_destroy_master_attributes(dev); + kthread_stop(dev->thread); mutex_lock(&dev->mutex); @@ -185,7 +192,6 @@ void __w1_remove_master_device(struct w1_master *dev) w1_slave_detach(sl); mutex_lock(&dev->list_mutex); } - w1_destroy_master_attributes(dev); mutex_unlock(&dev->list_mutex); mutex_unlock(&dev->mutex); atomic_dec(&dev->refcnt); diff --git a/drivers/w1/w1_netlink.c b/drivers/w1/w1_netlink.c index e6b59d921076..40fbb96a793e 100644 --- a/drivers/w1/w1_netlink.c +++ b/drivers/w1/w1_netlink.c @@ -478,15 +478,17 @@ static void w1_process_cb(struct w1_master *dev, struct w1_async_cmd *async_cmd) if (!cmd || err) w1_netlink_queue_status(node->block, node->msg, cmd, err); + dev->priv = NULL; + mutex_unlock(&dev->bus_mutex); + /* ref taken in w1_search_slave or w1_search_master_id when building - * the block + * the block. If it is the last one, the slave is removed, which waits + * for users of the bus. */ if (sl) w1_unref_slave(sl); else atomic_dec(&dev->refcnt); - dev->priv = NULL; - mutex_unlock(&dev->bus_mutex); mutex_lock(&dev->list_mutex); list_del(&async_cmd->async_entry); diff --git a/drivers/watchdog/gunyah_wdt.c b/drivers/watchdog/gunyah_wdt.c index e3c2a2131624..35958594e17c 100644 --- a/drivers/watchdog/gunyah_wdt.c +++ b/drivers/watchdog/gunyah_wdt.c @@ -62,19 +62,12 @@ static int gunyah_wdt_call(unsigned long func_id, unsigned long arg1, return gunyah_error_remap(res.a0); } -static int gunyah_wdt_start(struct watchdog_device *wdd) +static int gunyah_wdt_enable(struct watchdog_device *wdd) { - unsigned int timeout_ms; + unsigned int timeout_ms = wdd->timeout * 1000; struct device *dev = wdd->parent; int ret; - ret = gunyah_wdt_call(GUNYAH_WDT_CONTROL, WDT_CTRL_DISABLE, 0); - if (ret && watchdog_active(wdd)) { - dev_err(dev, "%s: Failed to stop gunyah wdt %d\n", __func__, ret); - return ret; - } - - timeout_ms = wdd->timeout * 1000; ret = gunyah_wdt_call(GUNYAH_WDT_SET_TIME, timeout_ms, timeout_ms); if (ret) { dev_err(dev, "%s: Failed to set timeout for gunyah wdt %d\n", @@ -89,6 +82,20 @@ static int gunyah_wdt_start(struct watchdog_device *wdd) return ret; } +static int gunyah_wdt_start(struct watchdog_device *wdd) +{ + struct device *dev = wdd->parent; + int ret; + + ret = gunyah_wdt_call(GUNYAH_WDT_CONTROL, WDT_CTRL_DISABLE, 0); + if (ret && watchdog_active(wdd)) { + dev_err(dev, "%s: Failed to stop gunyah wdt %d\n", __func__, ret); + return ret; + } + + return gunyah_wdt_enable(wdd); +} + static int gunyah_wdt_stop(struct watchdog_device *wdd) { return gunyah_wdt_call(GUNYAH_WDT_CONTROL, WDT_CTRL_DISABLE, 0); @@ -224,7 +231,7 @@ static int gunyah_wdt_resume(struct device *dev) struct watchdog_device *wdd = dev_get_drvdata(dev); if (watchdog_active(wdd)) - gunyah_wdt_start(wdd); + gunyah_wdt_enable(wdd); return 0; } diff --git a/drivers/watchdog/meson_gxbb_wdt.c b/drivers/watchdog/meson_gxbb_wdt.c index 705f8c02b4ed..a88fe8cbeef5 100644 --- a/drivers/watchdog/meson_gxbb_wdt.c +++ b/drivers/watchdog/meson_gxbb_wdt.c @@ -124,7 +124,8 @@ static int __maybe_unused meson_gxbb_wdt_resume(struct device *dev) { struct meson_gxbb_wdt *data = dev_get_drvdata(dev); - if (watchdog_active(&data->wdt_dev)) + if (watchdog_active(&data->wdt_dev) || + watchdog_hw_running(&data->wdt_dev)) meson_gxbb_wdt_start(&data->wdt_dev); return 0; @@ -134,7 +135,8 @@ static int __maybe_unused meson_gxbb_wdt_suspend(struct device *dev) { struct meson_gxbb_wdt *data = dev_get_drvdata(dev); - if (watchdog_active(&data->wdt_dev)) + if (watchdog_active(&data->wdt_dev) || + watchdog_hw_running(&data->wdt_dev)) meson_gxbb_wdt_stop(&data->wdt_dev); return 0; diff --git a/drivers/watchdog/mtk_wdt.c b/drivers/watchdog/mtk_wdt.c index 03d47bf4a94c..f8602d61a084 100644 --- a/drivers/watchdog/mtk_wdt.c +++ b/drivers/watchdog/mtk_wdt.c @@ -540,6 +540,18 @@ static int mtk_wdt_probe(struct platform_device *pdev) mtk_wdt->reset_by_toprgu = of_property_read_bool(dev->of_node, "mediatek,reset-by-toprgu"); + wdt_data = of_device_get_match_data(dev); + if (wdt_data) { + mtk_wdt->toprgu_sw_rst_num = wdt_data->toprgu_sw_rst_num; + mtk_wdt->toprgu_sw_rst_tb = wdt_data->toprgu_sw_rst_tb; + mtk_wdt->has_swsysrst_en = wdt_data->has_swsysrst_en; + + err = toprgu_register_reset_controller(pdev, + wdt_data->toprgu_sw_rst_num); + if (err) + return err; + } + mtk_wdt_init(&mtk_wdt->wdt_dev); watchdog_stop_on_reboot(&mtk_wdt->wdt_dev); @@ -553,18 +565,6 @@ static int mtk_wdt_probe(struct platform_device *pdev) dev_info(dev, "Watchdog enabled (timeout=%d sec, nowayout=%d)\n", mtk_wdt->wdt_dev.timeout, nowayout); - wdt_data = of_device_get_match_data(dev); - if (wdt_data) { - mtk_wdt->toprgu_sw_rst_num = wdt_data->toprgu_sw_rst_num; - mtk_wdt->toprgu_sw_rst_tb = wdt_data->toprgu_sw_rst_tb; - mtk_wdt->has_swsysrst_en = wdt_data->has_swsysrst_en; - - err = toprgu_register_reset_controller(pdev, - wdt_data->toprgu_sw_rst_num); - if (err) - return err; - } - return 0; } @@ -572,7 +572,8 @@ static int mtk_wdt_suspend(struct device *dev) { struct mtk_wdt_dev *mtk_wdt = dev_get_drvdata(dev); - if (watchdog_active(&mtk_wdt->wdt_dev)) + if (watchdog_active(&mtk_wdt->wdt_dev) || + watchdog_hw_running(&mtk_wdt->wdt_dev)) mtk_wdt_stop(&mtk_wdt->wdt_dev); return 0; @@ -582,7 +583,8 @@ static int mtk_wdt_resume(struct device *dev) { struct mtk_wdt_dev *mtk_wdt = dev_get_drvdata(dev); - if (watchdog_active(&mtk_wdt->wdt_dev)) { + if (watchdog_active(&mtk_wdt->wdt_dev) || + watchdog_hw_running(&mtk_wdt->wdt_dev)) { mtk_wdt_start(&mtk_wdt->wdt_dev); mtk_wdt_ping(&mtk_wdt->wdt_dev); } diff --git a/drivers/watchdog/npcm_wdt.c b/drivers/watchdog/npcm_wdt.c index 4d8f21287144..07ea810fb8c9 100644 --- a/drivers/watchdog/npcm_wdt.c +++ b/drivers/watchdog/npcm_wdt.c @@ -145,13 +145,11 @@ static int npcm_wdt_ping(struct watchdog_device *wdd) return 0; } -static int npcm_wdt_start(struct watchdog_device *wdd) +static void __npcm_wdt_start(struct watchdog_device *wdd) { struct npcm_wdt *wdt = to_npcm_wdt(wdd); u32 val; - clk_prepare_enable(wdt->clk); - if (wdd->timeout < 2) val = 0x800; else if (wdd->timeout < 3) @@ -176,6 +174,15 @@ static int npcm_wdt_start(struct watchdog_device *wdd) val |= NPCM_WTRE | NPCM_WTE | NPCM_WTR | NPCM_WTIE; writel(val, wdt->reg); +} + +static int npcm_wdt_start(struct watchdog_device *wdd) +{ + struct npcm_wdt *wdt = to_npcm_wdt(wdd); + + clk_prepare_enable(wdt->clk); + + __npcm_wdt_start(wdd); return 0; } @@ -216,7 +223,7 @@ static int npcm_wdt_set_timeout(struct watchdog_device *wdd, wdd->timeout = 2750; if (watchdog_active(wdd)) - npcm_wdt_start(wdd); + __npcm_wdt_start(wdd); return 0; } diff --git a/drivers/watchdog/omap_wdt.c b/drivers/watchdog/omap_wdt.c index 669d9ad9cf25..c60bc678262c 100644 --- a/drivers/watchdog/omap_wdt.c +++ b/drivers/watchdog/omap_wdt.c @@ -277,6 +277,8 @@ static int omap_wdt_probe(struct platform_device *pdev) ret = watchdog_register_device(&wdev->wdog); if (ret) { + if (wdev->omap_wdt_users) + omap_wdt_stop(&wdev->wdog); pm_runtime_put(wdev->dev); pm_runtime_disable(wdev->dev); return ret; @@ -286,9 +288,6 @@ static int omap_wdt_probe(struct platform_device *pdev) readl_relaxed(wdev->base + OMAP_WATCHDOG_REV) & 0xFF, wdev->wdog.timeout); - if (early_enable) - omap_wdt_start(&wdev->wdog); - pm_runtime_put(wdev->dev); return 0; diff --git a/drivers/watchdog/orion_wdt.c b/drivers/watchdog/orion_wdt.c index 828b4d7bfeb0..83a24f58011e 100644 --- a/drivers/watchdog/orion_wdt.c +++ b/drivers/watchdog/orion_wdt.c @@ -232,6 +232,9 @@ static int armada370_start(struct watchdog_device *wdt_dev) /* Set watchdog duration */ writel(dev->clk_rate * wdt_dev->timeout, dev->reg + dev->data->wdt_counter_offset); + if (dev->wdt.info->options & WDIOF_PRETIMEOUT) + writel(dev->clk_rate * (wdt_dev->timeout - wdt_dev->pretimeout), + dev->reg + TIMER1_VAL_OFF); /* Clear the watchdog expiration bit */ atomic_io_modify(dev->reg + TIMER_A370_STATUS, WDT_A370_EXPIRED, 0); diff --git a/drivers/watchdog/rzv2h_wdt.c b/drivers/watchdog/rzv2h_wdt.c index 4353fa677778..c1c01ee7432c 100644 --- a/drivers/watchdog/rzv2h_wdt.c +++ b/drivers/watchdog/rzv2h_wdt.c @@ -175,7 +175,7 @@ static int rzv2h_wdt_stop(struct watchdog_device *wdev) if (priv->of_data->wdtdcr) rzt2h_wdt_wdtdcr_count_stop(priv); - pm_runtime_put(wdev->parent); + pm_runtime_put_sync(wdev->parent); return 0; } @@ -257,20 +257,12 @@ static const struct watchdog_ops rzv2h_wdt_ops = { static int rzt2h_wdt_wdtdcr_init(struct platform_device *pdev, struct rzv2h_wdt_priv *priv) { - int ret; - priv->wdtdcr = devm_platform_ioremap_resource(pdev, 1); if (IS_ERR(priv->wdtdcr)) return PTR_ERR(priv->wdtdcr); - ret = pm_runtime_resume_and_get(&pdev->dev); - if (ret) - return ret; - rzt2h_wdt_wdtdcr_count_stop(priv); - pm_runtime_put(&pdev->dev); - return 0; } diff --git a/drivers/watchdog/sbsa_gwdt.c b/drivers/watchdog/sbsa_gwdt.c index c6957184fe14..537c48b883b3 100644 --- a/drivers/watchdog/sbsa_gwdt.c +++ b/drivers/watchdog/sbsa_gwdt.c @@ -72,12 +72,16 @@ #define SBSA_GWDT_WCS_WS0 BIT(1) #define SBSA_GWDT_WCS_WS1 BIT(2) -#define SBSA_GWDT_VERSION_MASK GENMASK(3, 0) -#define SBSA_GWDT_VERSION_SHIFT 16 +#define SBSA_GWDT_VERSION_MASK GENMASK(3, 0) +#define SBSA_GWDT_VERSION_SHIFT 16 -#define SBSA_GWDT_IMPL_MASK GENMASK(11, 0) -#define SBSA_GWDT_IMPL_SHIFT 0 -#define SBSA_GWDT_IMPL_MEDIATEK 0x426 +#define SBSA_GWDT_REVISION_MASK GENMASK(3, 0) +#define SBSA_GWDT_REVISION_SHIFT 12 +#define SBSA_GWDT_REV_RACE_WA 0x0 + +#define SBSA_GWDT_IMPL_MASK GENMASK(11, 0) +#define SBSA_GWDT_IMPL_SHIFT 0 +#define SBSA_GWDT_IMPL_MEDIATEK 0x426 /** * struct sbsa_gwdt - Internal representation of the SBSA GWDT @@ -239,15 +243,17 @@ static int sbsa_gwdt_keepalive(struct watchdog_device *wdd) static void sbsa_gwdt_get_version(struct watchdog_device *wdd) { struct sbsa_gwdt *gwdt = watchdog_get_drvdata(wdd); - int iidr, ver, impl; + int iidr, ver, rev, impl; iidr = readl(gwdt->control_base + SBSA_GWDT_W_IIDR); ver = (iidr >> SBSA_GWDT_VERSION_SHIFT) & SBSA_GWDT_VERSION_MASK; + rev = (iidr >> SBSA_GWDT_REVISION_SHIFT) & SBSA_GWDT_REVISION_MASK; impl = (iidr >> SBSA_GWDT_IMPL_SHIFT) & SBSA_GWDT_IMPL_MASK; gwdt->version = ver; gwdt->need_ws0_race_workaround = - !action && (impl == SBSA_GWDT_IMPL_MEDIATEK); + !action && (impl == SBSA_GWDT_IMPL_MEDIATEK) && + (rev == SBSA_GWDT_REV_RACE_WA); } static int sbsa_gwdt_start(struct watchdog_device *wdd) diff --git a/drivers/watchdog/sc1200wdt.c b/drivers/watchdog/sc1200wdt.c index 34cd57420c86..12af8c736d0f 100644 --- a/drivers/watchdog/sc1200wdt.c +++ b/drivers/watchdog/sc1200wdt.c @@ -343,6 +343,7 @@ static const struct pnp_device_id scl200wdt_pnp_devices[] = { { .id = "NSC0800" }, { } }; +MODULE_DEVICE_TABLE(pnp, scl200wdt_pnp_devices); static int scl200wdt_pnp_probe(struct pnp_dev *dev, const struct pnp_device_id *dev_id) diff --git a/drivers/watchdog/sp5100_tco.c b/drivers/watchdog/sp5100_tco.c index 4c8c73cae2bd..96ff3c5d116e 100644 --- a/drivers/watchdog/sp5100_tco.c +++ b/drivers/watchdog/sp5100_tco.c @@ -407,16 +407,13 @@ static int sp5100_tco_setupdevice_mmio(struct device *dev, struct sp5100_tco *tco = watchdog_get_drvdata(wdd); const char *dev_name = SB800_DEVNAME; u32 mmio_addr = 0, alt_mmio_addr = 0; - struct resource *res; void __iomem *addr; int ret; u32 val; - res = request_mem_region_muxed(EFCH_PM_ACPI_MMIO_PM_ADDR, - EFCH_PM_ACPI_MMIO_PM_SIZE, - "sp5100_tco"); - - if (!res) { + if (!request_mem_region_muxed(EFCH_PM_ACPI_MMIO_PM_ADDR, + EFCH_PM_ACPI_MMIO_PM_SIZE, + "sp5100_tco")) { dev_err(dev, "Memory region 0x%08x already in use\n", EFCH_PM_ACPI_MMIO_PM_ADDR); @@ -467,8 +464,8 @@ out: if (addr) iounmap(addr); - release_resource(res); - kfree(res); + release_mem_region(EFCH_PM_ACPI_MMIO_PM_ADDR, + EFCH_PM_ACPI_MMIO_PM_SIZE); return ret; } diff --git a/drivers/xen/gntdev.c b/drivers/xen/gntdev.c index 49957e3ab49d..385ba47d093b 100644 --- a/drivers/xen/gntdev.c +++ b/drivers/xen/gntdev.c @@ -670,15 +670,19 @@ static long gntdev_ioctl_map_grant_ref(struct gntdev_priv *priv, mutex_lock(&priv->lock); gntdev_add_map(priv, map); op.index = map->index << PAGE_SHIFT; + mutex_unlock(&priv->lock); if (copy_to_user(u, &op, sizeof(op)) != 0) { - list_del(&map->next); + mutex_lock(&priv->lock); + map = gntdev_find_map_index(priv, op.index >> PAGE_SHIFT, + op.count); + if (map) + list_del(&map->next); mutex_unlock(&priv->lock); gntdev_put_map(priv, map); return -EFAULT; } - mutex_unlock(&priv->lock); return 0; } diff --git a/drivers/xen/grant-table.c b/drivers/xen/grant-table.c index 604c4eea5930..957500dd309a 100644 --- a/drivers/xen/grant-table.c +++ b/drivers/xen/grant-table.c @@ -38,6 +38,7 @@ #include <linux/sched.h> #include <linux/mm.h> #include <linux/slab.h> +#include <linux/sched/task_stack.h> #include <linux/vmalloc.h> #include <linux/uaccess.h> #include <linux/io.h> @@ -1063,6 +1064,9 @@ int gnttab_dma_alloc_pages(struct gnttab_dma_alloc_args *args) size_t size; int i, ret; + if (WARN_ON(xen_pv_domain())) + return -EINVAL; + if (args->nr_pages < 0 || args->nr_pages > (INT_MAX >> PAGE_SHIFT)) return -ENOMEM; @@ -1090,11 +1094,27 @@ int gnttab_dma_alloc_pages(struct gnttab_dma_alloc_args *args) xenmem_reservation_scrub_page(page); } - xenmem_reservation_va_mapping_reset(args->nr_pages, args->pages); - ret = xenmem_reservation_decrease(args->nr_pages, args->frames); if (ret != args->nr_pages) { pr_debug("Failed to decrease reservation for DMA buffer\n"); + if (ret >= 0) { + /* Free the part where decrease didn't work. */ + size_t done = ret << PAGE_SHIFT; + + if (args->coherent) + dma_free_coherent(args->dev, size - done, + args->vaddr + done, + args->dev_bus_addr + done); + else + dma_free_wc(args->dev, size - done, + args->vaddr + done, + args->dev_bus_addr + done); + + if (!ret) /* Nothing else to do? */ + return -EFAULT; + + args->nr_pages = ret; + } ret = -EFAULT; goto fail; } @@ -1120,6 +1140,9 @@ int gnttab_dma_free_pages(struct gnttab_dma_alloc_args *args) size_t size; int i, ret; + if (WARN_ON(xen_pv_domain())) + return -EINVAL; + gnttab_pages_clear_private(args->nr_pages, args->pages); for (i = 0; i < args->nr_pages; i++) @@ -1128,14 +1151,16 @@ int gnttab_dma_free_pages(struct gnttab_dma_alloc_args *args) ret = xenmem_reservation_increase(args->nr_pages, args->frames); if (ret != args->nr_pages) { pr_debug("Failed to increase reservation for DMA buffer\n"); - ret = -EFAULT; + /* Can only free what has been re-filled. */ + if (!ret) + return -ENOMEM; + if (ret > 0) + args->nr_pages = ret; + ret = -ENOMEM; } else { ret = 0; } - xenmem_reservation_va_mapping_update(args->nr_pages, args->pages, - args->frames); - size = args->nr_pages << PAGE_SHIFT; if (args->coherent) dma_free_coherent(args->dev, size, @@ -1360,12 +1385,21 @@ static void unmap_refs_callback(int result, int gnttab_unmap_refs_sync(struct gntab_unmap_queue_data *item) { struct unmap_refs_callback_data data; + bool on_stack = object_is_on_stack(item); init_completion(&data.completion); item->data = &data; item->done = &unmap_refs_callback; - gnttab_unmap_refs_async(item); + /* blkback keeps @item, and so its retry work, on the stack. */ + if (on_stack) + INIT_DELAYED_WORK_ONSTACK(&item->gnttab_work, gnttab_unmap_work); + else + INIT_DELAYED_WORK(&item->gnttab_work, gnttab_unmap_work); + item->age = 0; + __gnttab_unmap_refs_async(item); wait_for_completion(&data.completion); + if (on_stack) + destroy_delayed_work_on_stack(&item->gnttab_work); return data.result; } diff --git a/drivers/xen/platform-pci.c b/drivers/xen/platform-pci.c index f2438232518c..a12ac57274a6 100644 --- a/drivers/xen/platform-pci.c +++ b/drivers/xen/platform-pci.c @@ -95,6 +95,7 @@ static int platform_pci_probe(struct pci_dev *pdev, const struct pci_device_id *ent) { int i, ret; + int requested_bars = 0; long ioaddr; long mmio_addr, mmio_len; unsigned int max_nr_gframes; @@ -115,16 +116,18 @@ static int platform_pci_probe(struct pci_dev *pdev, if (mmio_addr == 0 || ioaddr == 0) { dev_err(&pdev->dev, "no resources found\n"); ret = -ENOENT; - goto pci_out; + goto out; } ret = pci_request_region(pdev, 1, DRV_NAME); if (ret < 0) - goto pci_out; + goto out; + requested_bars |= BIT(1); ret = pci_request_region(pdev, 0, DRV_NAME); if (ret < 0) - goto mem_out; + goto out; + requested_bars |= BIT(0); platform_mmio = mmio_addr; platform_mmiolen = mmio_len; @@ -165,11 +168,8 @@ irq_out: if (!xen_have_vector_callback) free_irq(pdev->irq, pdev); out: - pci_release_region(pdev, 0); -mem_out: - pci_release_region(pdev, 1); -pci_out: pci_disable_device(pdev); + pci_release_selected_regions(pdev, requested_bars); return ret; } diff --git a/drivers/xen/privcmd.c b/drivers/xen/privcmd.c index 5e56fbc93447..221b31611343 100644 --- a/drivers/xen/privcmd.c +++ b/drivers/xen/privcmd.c @@ -901,10 +901,25 @@ struct privcmd_kernel_irqfd { poll_table pt; }; +static bool irqfd_is_active(struct privcmd_kernel_irqfd *kirqfd) +{ + lockdep_assert_held(&irqfds_lock); + + return !list_empty(&kirqfd->list); +} + static void irqfd_deactivate(struct privcmd_kernel_irqfd *kirqfd) { lockdep_assert_held(&irqfds_lock); + /* + * Both the deassign ioctl and the eventfd wakeup path can reach + * this function. list_del_init() marks the irqfd inactive, so + * only the first caller may queue the shutdown work. + */ + if (!irqfd_is_active(kirqfd)) + return; + list_del_init(&kirqfd->list); queue_work(irqfd_cleanup_wq, &kirqfd->shutdown); } diff --git a/drivers/xen/pvcalls-back.c b/drivers/xen/pvcalls-back.c index ba62651a7f33..d97c5eca5f35 100644 --- a/drivers/xen/pvcalls-back.c +++ b/drivers/xen/pvcalls-back.c @@ -337,7 +337,7 @@ static struct sock_mapping *pvcalls_new_active_socket( ret = xenbus_map_ring_valloc(fedata->dev, &ref, 1, &page); if (ret < 0) - goto out; + goto out_map; map->ring = page; map->ring_order = map->ring->ring_order; /* first read the order, then map the data ring */ @@ -345,19 +345,19 @@ static struct sock_mapping *pvcalls_new_active_socket( if (map->ring_order > MAX_RING_ORDER) { pr_warn("%s frontend requested ring_order %u, which is > MAX (%u)\n", __func__, map->ring_order, MAX_RING_ORDER); - goto out; + goto out_unmap_ring; } ret = xenbus_map_ring_valloc(fedata->dev, map->ring->ref, (1 << map->ring_order), &page); if (ret < 0) - goto out; + goto out_unmap_ring; map->bytes = page; ret = bind_interdomain_evtchn_to_irqhandler_lateeoi( fedata->dev, evtchn, pvcalls_back_conn_event, 0, "pvcalls-backend", map); if (ret < 0) - goto out; + goto out_unmap_bytes; map->irq = ret; map->data.in = map->bytes; @@ -365,7 +365,7 @@ static struct sock_mapping *pvcalls_new_active_socket( map->ioworker.wq = alloc_ordered_workqueue("pvcalls_io", 0); if (!map->ioworker.wq) - goto out; + goto out_unbind; atomic_set(&map->io, 1); INIT_WORK(&map->ioworker.register_work, pvcalls_back_ioworker); @@ -381,11 +381,16 @@ static struct sock_mapping *pvcalls_new_active_socket( write_unlock_bh(&map->sock->sk->sk_callback_lock); return map; -out: - down(&fedata->socket_lock); - list_del(&map->list); - pvcalls_back_release_active(fedata->dev, fedata, map); - up(&fedata->socket_lock); + +out_unbind: + unbind_from_irqhandler(map->irq, map); +out_unmap_bytes: + xenbus_unmap_ring_vfree(fedata->dev, map->bytes); +out_unmap_ring: + xenbus_unmap_ring_vfree(fedata->dev, (void *)map->ring); +out_map: + sock_release(sock); + kfree(map); return NULL; } @@ -447,6 +452,7 @@ static int pvcalls_back_release_active(struct xenbus_device *dev, atomic_set(&map->release, 1); flush_work(&map->ioworker.register_work); + destroy_workqueue(map->ioworker.wq); xenbus_unmap_ring_vfree(dev, map->bytes); xenbus_unmap_ring_vfree(dev, (void *)map->ring); diff --git a/fs/adfs/dir_fplus.c b/fs/adfs/dir_fplus.c index 4a15924014da..c68c301d8903 100644 --- a/fs/adfs/dir_fplus.c +++ b/fs/adfs/dir_fplus.c @@ -192,6 +192,8 @@ adfs_fplus_getnext(struct adfs_dir *dir, struct object_info *obj) obj->indaddr = le32_to_cpu(bde.bigdirindaddr); obj->attr = le32_to_cpu(bde.bigdirattr); obj->name_len = le32_to_cpu(bde.bigdirobnamelen); + if (obj->name_len > ADFS_MAX_NAME_LEN - 4) /* leave room for ,xyz suffix */ + return -EIO; offset = adfs_fplus_offset(h, le32_to_cpu(h->bigdirentries)); offset += le32_to_cpu(bde.bigdirobnameptr); @@ -961,7 +961,7 @@ void exit_aio(struct mm_struct *mm) if (!table) return; - atomic_set(&wait.count, table->nr); + atomic_set(&wait.count, table->nr + 1); init_completion(&wait.comp); skipped = 0; @@ -985,7 +985,7 @@ void exit_aio(struct mm_struct *mm) kill_ioctx(mm, ctx, &wait); } - if (!atomic_sub_and_test(skipped, &wait.count)) { + if (!atomic_sub_and_test(skipped + 1, &wait.count)) { /* Wait until all IO for the context are done. */ wait_for_completion(&wait.comp); } diff --git a/fs/backing-file.c b/fs/backing-file.c index 5780f60662d0..c601b27f0fd3 100644 --- a/fs/backing-file.c +++ b/fs/backing-file.c @@ -115,8 +115,13 @@ struct backing_aio { static struct kmem_cache *backing_aio_cachep; +/* + * RWF_NOAPPEND stays set in ki_flags. Pass it on, because the backing file is + * in append mode as well and a new kiocb for it starts with IOCB_APPEND. + */ #define BACKING_IOCB_MASK \ - (IOCB_NOWAIT | IOCB_HIPRI | IOCB_DSYNC | IOCB_SYNC | IOCB_APPEND) + (IOCB_NOWAIT | IOCB_HIPRI | IOCB_DSYNC | IOCB_SYNC | IOCB_APPEND | \ + (__force int) RWF_NOAPPEND) static rwf_t iocb_to_rw_flags(int flags) { diff --git a/fs/btrfs/bio.c b/fs/btrfs/bio.c index 2c6234f6182f..2e12a6d7e16f 100644 --- a/fs/btrfs/bio.c +++ b/fs/btrfs/bio.c @@ -624,6 +624,8 @@ static void run_one_async_done(struct btrfs_work *work, bool do_free) /* If an error occurred we just want to clean up the bio and move on. */ if (bio->bi_status) { + btrfs_put_bioc(async->bioc); + btrfs_bio_counter_dec(async->bbio->inode->root->fs_info); btrfs_bio_end_io(async->bbio, bio->bi_status); return; } @@ -762,6 +764,7 @@ static bool btrfs_submit_chunk(struct btrfs_bio *bbio, int mirror_num) split = btrfs_split_bio(fs_info, bbio, map_length); if (IS_ERR(split)) { status = errno_to_blk_status(PTR_ERR(split)); + btrfs_put_bioc(bioc); btrfs_bio_counter_dec(fs_info); goto end_bbio; } @@ -822,6 +825,7 @@ done: return map_length == length; fail: + btrfs_put_bioc(bioc); btrfs_bio_counter_dec(fs_info); /* * We have split the original bbio, now we have to end both the current diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c index 9a98e291769c..f923d27f1bf2 100644 --- a/fs/btrfs/block-group.c +++ b/fs/btrfs/block-group.c @@ -3727,7 +3727,7 @@ void btrfs_free_reserved_bytes(struct btrfs_block_group *cache, u64 num_bytes, if (bg_ro) space_info->bytes_readonly += num_bytes; else if (btrfs_is_zoned(cache->fs_info)) - space_info->bytes_zone_unusable += num_bytes; + btrfs_space_info_update_bytes_zone_unusable(space_info, num_bytes); space_info->bytes_reserved -= num_bytes; space_info->max_extent_size = 0; diff --git a/fs/btrfs/direct-io.c b/fs/btrfs/direct-io.c index ed3914257d39..90919d79d069 100644 --- a/fs/btrfs/direct-io.c +++ b/fs/btrfs/direct-io.c @@ -807,10 +807,6 @@ static void btrfs_dio_submit_io(const struct iomap_iter *iter, struct bio *bio, static DEFINE_IOMAP_ITER_NEXT_END(btrfs_dio_iomap_next, btrfs_dio_iomap_begin, btrfs_dio_iomap_end); -static const struct iomap_ops btrfs_dio_iomap_ops = { - .iomap_next = btrfs_dio_iomap_next, -}; - static const struct iomap_dio_ops btrfs_dio_ops = { .submit_io = btrfs_dio_submit_io, .bio_set = &btrfs_dio_bioset, @@ -821,7 +817,7 @@ static ssize_t btrfs_dio_read(struct kiocb *iocb, struct iov_iter *iter, { struct btrfs_dio_data data = { 0 }; - return iomap_dio_rw(iocb, iter, &btrfs_dio_iomap_ops, &btrfs_dio_ops, + return iomap_dio_rw(iocb, iter, btrfs_dio_iomap_next, &btrfs_dio_ops, IOMAP_DIO_PARTIAL | IOMAP_DIO_FSBLOCK_ALIGNED, &data, done_before); } @@ -858,7 +854,7 @@ static struct iomap_dio *btrfs_dio_write(struct kiocb *iocb, struct iov_iter *it dio_flags |= IOMAP_DIO_BOUNCE; } - return __iomap_dio_rw(iocb, iter, &btrfs_dio_iomap_ops, &btrfs_dio_ops, + return __iomap_dio_rw(iocb, iter, btrfs_dio_iomap_next, &btrfs_dio_ops, dio_flags, &data, done_before); } diff --git a/fs/btrfs/disk-io.c b/fs/btrfs/disk-io.c index c628c5081d92..910087409346 100644 --- a/fs/btrfs/disk-io.c +++ b/fs/btrfs/disk-io.c @@ -1169,6 +1169,8 @@ static struct btrfs_root *btrfs_get_global_root(struct btrfs_fs_info *fs_info, return btrfs_grab_root(fs_info->stripe_root); case BTRFS_REMAP_TREE_OBJECTID: return btrfs_grab_root(fs_info->remap_root); + case BTRFS_DATA_RELOC_TREE_OBJECTID: + return btrfs_grab_root(fs_info->data_reloc_root); default: return NULL; } @@ -1304,8 +1306,15 @@ static struct btrfs_root *btrfs_get_root_ref(struct btrfs_fs_info *fs_info, * * This is namely for free-space-tree and quota tree, which can change * at runtime and should only be grabbed from fs_info. + * + * The data reloc tree is also such a tree. It is loaded at mount time + * by read_data_reloc_root() and never inserted into the radix tree, as + * radix tree keys are of type `unsigned long`, which is 32 bits wide + * on 32-bit platforms. + * Casting the objectid to `unsigned long` can therefore result in a + * conflict with a subvolume. */ - if (!btrfs_is_fstree(objectid) && objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) + if (!btrfs_is_fstree(objectid)) return ERR_PTR(-ENOENT); again: root = btrfs_lookup_fs_root(fs_info, objectid); @@ -1409,6 +1418,39 @@ struct btrfs_root *btrfs_get_new_fs_root(struct btrfs_fs_info *fs_info, return btrfs_get_root_ref(fs_info, objectid, anon_dev, true); } +/* Read and initialize the data reloc tree. */ +static struct btrfs_root *read_data_reloc_root(struct btrfs_fs_info *fs_info) +{ + struct btrfs_key key = { + .objectid = BTRFS_DATA_RELOC_TREE_OBJECTID, + .type = BTRFS_ROOT_ITEM_KEY, + .offset = (u64)-1, + }; + struct btrfs_root *root; + int ret; + + root = btrfs_read_tree_root(fs_info->tree_root, &key); + if (IS_ERR(root)) + return root; + + if (btrfs_root_refs(&root->root_item) == 0) { + ret = -ENOENT; + goto fail; + } + + /* + * This tree can share blocks with some other fs tree during + * relocation and we need a proper setup by btrfs_init_fs_root(). + */ + ret = btrfs_init_fs_root(root, 0); + if (ret) + goto fail; + return root; +fail: + btrfs_put_root(root); + return ERR_PTR(ret); +} + /* * Return a root for the given objectid. * @@ -2275,12 +2317,7 @@ static int btrfs_read_roots(struct btrfs_fs_info *fs_info) PTR_ERR(root)); } } else { - /* - * This tree can share blocks with some other fs tree during - * relocation and we need a proper setup by btrfs_get_fs_root(). - */ - root = btrfs_get_fs_root(tree_root->fs_info, - BTRFS_DATA_RELOC_TREE_OBJECTID, true); + root = read_data_reloc_root(fs_info); if (IS_ERR(root)) { if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) { location.objectid = BTRFS_DATA_RELOC_TREE_OBJECTID; @@ -3815,8 +3852,6 @@ fail_block_groups: btrfs_put_block_group_cache(fs_info); fail_tree_roots: - if (fs_info->data_reloc_root) - btrfs_drop_and_free_fs_root(fs_info, fs_info->data_reloc_root); free_root_pointers(fs_info, true); invalidate_and_check_btree_folios(fs_info); diff --git a/fs/btrfs/ioctl.c b/fs/btrfs/ioctl.c index f94aa4939a86..6ba883db107b 100644 --- a/fs/btrfs/ioctl.c +++ b/fs/btrfs/ioctl.c @@ -5161,8 +5161,12 @@ static int btrfs_ioctl_subvol_sync(struct btrfs_fs_info *fs_info, void __user *a return -ENOENT; wait_for_deletion = true; - ASSERT(root_flags & BTRFS_ROOT_SUBVOL_DEAD, "root_flags=0x%llx", - root_flags); + if (unlikely(!(root_flags & BTRFS_ROOT_SUBVOL_DEAD))) { + btrfs_err(fs_info, + "subvol %llu has refs 0 without DEAD flag", + args.subvolid); + return -EUCLEAN; + } sched_ret = schedule_timeout_interruptible(HZ); /* Early wake up or error. */ if (sched_ret != 0) diff --git a/fs/btrfs/tree-checker.c b/fs/btrfs/tree-checker.c index 9cd79d97b9b5..a2aa4013e082 100644 --- a/fs/btrfs/tree-checker.c +++ b/fs/btrfs/tree-checker.c @@ -1766,7 +1766,11 @@ static int check_extent_item(struct extent_buffer *leaf, inline_refs += btrfs_shared_data_ref_count(leaf, sref); break; case BTRFS_EXTENT_OWNER_REF_KEY: - WARN_ON(!btrfs_fs_incompat(fs_info, SIMPLE_QUOTA)); + if (unlikely(!btrfs_fs_incompat(fs_info, SIMPLE_QUOTA))) { + extent_err(leaf, slot, + "extent owner ref without simple quota"); + return -EUCLEAN; + } break; default: extent_err(leaf, slot, "unknown inline ref type: %u", diff --git a/fs/btrfs/volumes.h b/fs/btrfs/volumes.h index 6eddda239221..1c4cfb21ad12 100644 --- a/fs/btrfs/volumes.h +++ b/fs/btrfs/volumes.h @@ -708,9 +708,8 @@ static inline enum btrfs_map_op btrfs_op(const struct bio *bio) static inline unsigned long btrfs_chunk_item_size(int num_stripes) { - ASSERT(num_stripes); - return sizeof(struct btrfs_chunk) + - sizeof(struct btrfs_stripe) * (num_stripes - 1); + return offsetof(struct btrfs_chunk, stripe) + + sizeof(struct btrfs_stripe) * num_stripes; } /* diff --git a/fs/btrfs/zoned.c b/fs/btrfs/zoned.c index 63a3aaca97b8..bdadc704c8cb 100644 --- a/fs/btrfs/zoned.c +++ b/fs/btrfs/zoned.c @@ -1122,11 +1122,13 @@ u64 btrfs_find_allocatable_zones(struct btrfs_device *device, u64 hole_start, return pos; } -static bool btrfs_dev_set_active_zone(struct btrfs_device *device, u64 pos) +static bool btrfs_dev_set_active_zone(struct btrfs_device *device, u64 pos, bool *new) { struct btrfs_zoned_device_info *zone_info = device->zone_info; unsigned int zno = (pos >> zone_info->zone_size_shift); + *new = false; + /* We can use any number of zones */ if (zone_info->max_active_zones == 0) return true; @@ -1138,23 +1140,29 @@ static bool btrfs_dev_set_active_zone(struct btrfs_device *device, u64 pos) if (test_and_set_bit(zno, zone_info->active_zones)) { /* Someone already set the bit */ atomic_inc(&zone_info->active_zones_left); + } else { + *new = true; } } return true; } -static void btrfs_dev_clear_active_zone(struct btrfs_device *device, u64 pos) +static bool btrfs_dev_clear_active_zone(struct btrfs_device *device, u64 pos) { struct btrfs_zoned_device_info *zone_info = device->zone_info; unsigned int zno = (pos >> zone_info->zone_size_shift); /* We can use any number of zones */ if (zone_info->max_active_zones == 0) - return; + return false; - if (test_and_clear_bit(zno, zone_info->active_zones)) + if (test_and_clear_bit(zno, zone_info->active_zones)) { atomic_inc(&zone_info->active_zones_left); + return true; + } + + return false; } int btrfs_reset_device_zone(struct btrfs_device *device, u64 physical, @@ -1376,11 +1384,13 @@ static int btrfs_load_zone_info(struct btrfs_fs_info *fs_info, int zone_idx, return 0; } + ASSERT(!test_bit(BTRFS_FS_OPEN, &fs_info->flags)); + up_read(&dev_replace->rwsem); + nofs_flag = memalloc_nofs_save(); ret = btrfs_get_dev_zone(device, info->physical, &zone); memalloc_nofs_restore(nofs_flag); if (ret) { - up_read(&dev_replace->rwsem); if (ret != -EIO && ret != -EOPNOTSUPP) return ret; info->alloc_offset = WP_MISSING_DEV; @@ -1392,7 +1402,6 @@ static int btrfs_load_zone_info(struct btrfs_fs_info *fs_info, int zone_idx, "zoned: unexpected conventional zone %llu on device %s (devid %llu)", zone.start << SECTOR_SHIFT, rcu_dereference(device->name), device->devid); - up_read(&dev_replace->rwsem); return -EIO; } @@ -1420,8 +1429,6 @@ static int btrfs_load_zone_info(struct btrfs_fs_info *fs_info, int zone_idx, break; } - up_read(&dev_replace->rwsem); - return 0; } @@ -2407,6 +2414,7 @@ bool btrfs_zone_activate(struct btrfs_block_group *block_group) u64 physical; const bool is_data = (block_group->flags & BTRFS_BLOCK_GROUP_DATA); bool ret; + bool new; int i; if (!btrfs_is_zoned(block_group->fs_info)) @@ -2460,12 +2468,12 @@ bool btrfs_zone_activate(struct btrfs_block_group *block_group) goto out_unlock; } - if (!btrfs_dev_set_active_zone(device, physical)) { + if (!btrfs_dev_set_active_zone(device, physical, &new)) { /* Cannot activate the zone */ ret = false; goto out_unlock; } - if (!is_data) + if (!is_data && new) zinfo->reserved_active_zones--; } @@ -2499,8 +2507,16 @@ static void wait_eb_writebacks(struct btrfs_block_group *block_group) continue; if (eb->start >= end) break; + /* + * Skip if we can't get the refcount for the extent buffer, + * i.e. because it was already written back. Otherwise an eb + * disappering underneath us can cause a use-after-free. + */ + if (!refcount_inc_not_zero(&eb->refs)) + continue; rcu_read_unlock(); wait_on_extent_buffer_writeback(eb); + free_extent_buffer(eb); rcu_read_lock(); } rcu_read_unlock(); @@ -2512,6 +2528,7 @@ static int call_zone_finish(struct btrfs_block_group *block_group, struct btrfs_device *device = stripe->dev; const u64 physical = stripe->physical; struct btrfs_zoned_device_info *zinfo = device->zone_info; + bool cleared; int ret; if (!device->bdev) @@ -2533,9 +2550,9 @@ static int call_zone_finish(struct btrfs_block_group *block_group, return ret; } - if (!(block_group->flags & BTRFS_BLOCK_GROUP_DATA)) + cleared = btrfs_dev_clear_active_zone(device, physical); + if (!(block_group->flags & BTRFS_BLOCK_GROUP_DATA) && cleared) zinfo->reserved_active_zones++; - btrfs_dev_clear_active_zone(device, physical); return 0; } @@ -2583,9 +2600,10 @@ static int do_zone_finish(struct btrfs_block_group *block_group, bool fully_writ /* Ensure all writes in this block group finish */ btrfs_wait_block_group_reservations(block_group); - /* No need to wait for NOCOW writers. Zoned mode does not allow that */ - btrfs_wait_ordered_roots(fs_info, U64_MAX, block_group); - /* Wait for extent buffers to be written. */ + /* + * No need to wait for NOCOW writers, as zoned mode does not + * allow that, only wait for extent buffers to be written. + */ if (is_metadata) wait_eb_writebacks(block_group); @@ -3114,6 +3132,8 @@ int btrfs_reset_unused_block_groups(struct btrfs_space_info *space_info, u64 num { struct btrfs_fs_info *fs_info = space_info->fs_info; const sector_t zone_size_sectors = fs_info->zone_size >> SECTOR_SHIFT; + LIST_HEAD(retry_list); + int ret = 0; if (!btrfs_is_zoned(fs_info)) return 0; @@ -3155,11 +3175,10 @@ int btrfs_reset_unused_block_groups(struct btrfs_space_info *space_info, u64 num } if (!found) { spin_unlock(&fs_info->unused_bgs_lock); - return 0; + goto out; } list_del_init(&bg->bg_list); - btrfs_put_block_group(bg); spin_unlock(&fs_info->unused_bgs_lock); /* @@ -3173,7 +3192,6 @@ int btrfs_reset_unused_block_groups(struct btrfs_space_info *space_info, u64 num for (int i = 0; i < map->num_stripes; i++) { struct btrfs_io_stripe *stripe = &map->stripes[i]; unsigned int nofs_flags; - int ret; nofs_flags = memalloc_nofs_save(); ret = blkdev_zone_mgmt(stripe->dev->bdev, REQ_OP_ZONE_RESET, @@ -3183,7 +3201,7 @@ int btrfs_reset_unused_block_groups(struct btrfs_space_info *space_info, u64 num if (ret) { up_read(&fs_info->dev_replace.rwsem); - return ret; + goto requeue; } } up_read(&fs_info->dev_replace.rwsem); @@ -3194,7 +3212,7 @@ int btrfs_reset_unused_block_groups(struct btrfs_space_info *space_info, u64 num if (bg->ro) { spin_unlock(&bg->lock); spin_unlock(&space_info->lock); - continue; + goto requeue; } reclaimed = bg->alloc_offset; @@ -3218,17 +3236,33 @@ int btrfs_reset_unused_block_groups(struct btrfs_space_info *space_info, u64 num ASSERT(reclaimed == bg->zone_capacity, "reclaimed=%llu bg->zone_capacity=%llu", reclaimed, bg->zone_capacity); bg->free_space_ctl->free_space += reclaimed; - space_info->bytes_zone_unusable -= reclaimed; + btrfs_space_info_update_bytes_zone_unusable(space_info, -reclaimed); spin_unlock(&bg->lock); btrfs_return_free_space(space_info, reclaimed); spin_unlock(&space_info->lock); + btrfs_put_block_group(bg); + if (num_bytes <= reclaimed) break; num_bytes -= reclaimed; + continue; + +requeue: + list_add_tail(&bg->bg_list, &retry_list); + + if (ret) + goto out; } - return 0; +out: + if (!list_empty(&retry_list)) { + spin_lock(&fs_info->unused_bgs_lock); + list_splice_tail(&retry_list, &fs_info->unused_bgs); + spin_unlock(&fs_info->unused_bgs_lock); + } + + return ret; } void btrfs_show_zoned_stats(struct btrfs_fs_info *fs_info, struct seq_file *seq) diff --git a/fs/btrfs/zstd.c b/fs/btrfs/zstd.c index cc92d0b1b948..9b7c7f43527f 100644 --- a/fs/btrfs/zstd.c +++ b/fs/btrfs/zstd.c @@ -347,7 +347,8 @@ void zstd_put_workspace(struct btrfs_fs_info *fs_info, struct list_head *ws) /* A node is only taken off the lru if we are the corresponding level */ if (clip_level(workspace->req_level) == workspace->level) { /* Hide a max level workspace from reclaim */ - if (list_empty(&zwsm->idle_ws[ZSTD_BTRFS_MAX_LEVEL - 1])) { + if (workspace->level == ZSTD_BTRFS_MAX_LEVEL - 1 && + list_empty(&zwsm->idle_ws[ZSTD_BTRFS_MAX_LEVEL - 1])) { INIT_LIST_HEAD(&workspace->lru_list); } else { workspace->last_used = jiffies; diff --git a/fs/buffer.c b/fs/buffer.c index 5d3852b726d6..f951559e7d32 100644 --- a/fs/buffer.c +++ b/fs/buffer.c @@ -621,12 +621,15 @@ void write_boundary_block(struct block_device *bdev, * @bh: The buffer to mark dirty. * @mmb: The list of buffers to add the buffer to. * - * Mark the buffer dirty and add it to the list if it is not already on - * a list. + * Mark the buffer dirty, add it to the list if it is not already on a list + * and set I_METADATA_WRITEBACK on the inode so that fsync() and eviction + * write it out. */ void mmb_mark_buffer_dirty(struct buffer_head *bh, struct mapping_metadata_bhs *mmb) { + struct inode *inode = mmb->mapping->host; + mark_buffer_dirty(bh); if (!bh->b_mmb) { spin_lock(&mmb->lock); @@ -641,6 +644,15 @@ void mmb_mark_buffer_dirty(struct buffer_head *bh, list_move_tail(&bh->b_assoc_buffers, &mmb->list); spin_unlock(&mmb->lock); } + /* + * The inode itself may never have been dirtied, so attach it to a wb + * before setting the bit or writeback_single_inode() has nothing to + * lock when evict() syncs it. + */ + spin_lock(&inode->i_lock); + inode_attach_wb(inode, NULL); + inode_state_set(inode, I_METADATA_WRITEBACK); + spin_unlock(&inode->i_lock); } EXPORT_SYMBOL(mmb_mark_buffer_dirty); diff --git a/fs/coda/file.c b/fs/coda/file.c index 6ca8bfcb58f2..c9fba41f7cea 100644 --- a/fs/coda/file.c +++ b/fs/coda/file.c @@ -71,6 +71,7 @@ coda_file_write_iter(struct kiocb *iocb, struct iov_iter *to) struct file *host_file = cfi->cfi_container; loff_t ki_pos = iocb->ki_pos; size_t count = iov_iter_count(to); + rwf_t flags = (iocb->ki_flags & IOCB_APPEND) ? RWF_APPEND : RWF_NOAPPEND; ssize_t ret; ret = venus_access_intent(coda_inode->i_sb, coda_i2f(coda_inode), @@ -80,7 +81,7 @@ coda_file_write_iter(struct kiocb *iocb, struct iov_iter *to) goto finish_write; inode_lock(coda_inode); - ret = vfs_iter_write(cfi->cfi_container, to, &iocb->ki_pos, 0); + ret = vfs_iter_write(cfi->cfi_container, to, &iocb->ki_pos, flags); coda_inode->i_size = file_inode(host_file)->i_size; coda_inode->i_blocks = (coda_inode->i_size + 511) >> 9; inode_set_mtime_to_ts(coda_inode, inode_set_ctime_current(coda_inode)); @@ -1485,7 +1485,7 @@ out_unlock: } int dax_file_unshare(struct inode *inode, loff_t pos, loff_t len, - const struct iomap_ops *ops) + iomap_iter_next_fn next) { struct iomap_iter iter = { .inode = inode, @@ -1499,7 +1499,7 @@ int dax_file_unshare(struct inode *inode, loff_t pos, loff_t len, return 0; iter.len = min(len, size - pos); - while ((ret = iomap_iter(&iter, ops)) > 0) + while ((ret = iomap_iter(&iter, next)) > 0) iter.status = dax_unshare_iter(&iter); return ret; } @@ -1577,7 +1577,7 @@ static int dax_zero_iter(struct iomap_iter *iter, bool *did_zero) } int dax_zero_range(struct inode *inode, loff_t pos, loff_t len, bool *did_zero, - const struct iomap_ops *ops) + iomap_iter_next_fn next) { struct iomap_iter iter = { .inode = inode, @@ -1587,14 +1587,14 @@ int dax_zero_range(struct inode *inode, loff_t pos, loff_t len, bool *did_zero, }; int ret; - while ((ret = iomap_iter(&iter, ops)) > 0) + while ((ret = iomap_iter(&iter, next)) > 0) iter.status = dax_zero_iter(&iter, did_zero); return ret; } EXPORT_SYMBOL_GPL(dax_zero_range); int dax_truncate_page(struct inode *inode, loff_t pos, bool *did_zero, - const struct iomap_ops *ops) + iomap_iter_next_fn next) { unsigned int blocksize = i_blocksize(inode); unsigned int off = pos & (blocksize - 1); @@ -1602,7 +1602,7 @@ int dax_truncate_page(struct inode *inode, loff_t pos, bool *did_zero, /* Block boundary? Nothing to do */ if (!off) return 0; - return dax_zero_range(inode, pos, blocksize - off, did_zero, ops); + return dax_zero_range(inode, pos, blocksize - off, did_zero, next); } EXPORT_SYMBOL_GPL(dax_truncate_page); @@ -1727,7 +1727,8 @@ static int dax_iomap_iter(struct iomap_iter *iomi, struct iov_iter *iter) * dax_iomap_rw - Perform I/O to a DAX file * @iocb: The control block for this I/O * @iter: The addresses to do I/O from or to - * @ops: iomap ops passed from the file system + * @next: Callback passed from the file system for advancing to next + * iteration * * This function performs read and write operations to directly mapped * persistent memory. The callers needs to take care of read/write exclusion @@ -1735,7 +1736,7 @@ static int dax_iomap_iter(struct iomap_iter *iomi, struct iov_iter *iter) */ ssize_t dax_iomap_rw(struct kiocb *iocb, struct iov_iter *iter, - const struct iomap_ops *ops) + iomap_iter_next_fn next) { struct iomap_iter iomi = { .inode = iocb->ki_filp->f_mapping->host, @@ -1762,7 +1763,7 @@ dax_iomap_rw(struct kiocb *iocb, struct iov_iter *iter, if (iocb->ki_flags & IOCB_NOWAIT) iomi.flags |= IOMAP_NOWAIT; - while ((ret = iomap_iter(&iomi, ops)) > 0) + while ((ret = iomap_iter(&iomi, next)) > 0) iomi.status = dax_iomap_iter(&iomi, iter); done = iomi.pos - iocb->ki_pos; @@ -1890,7 +1891,7 @@ static vm_fault_t dax_fault_iter(struct vm_fault *vmf, } static vm_fault_t dax_iomap_pte_fault(struct vm_fault *vmf, unsigned long *pfnp, - int *iomap_errp, const struct iomap_ops *ops) + int *iomap_errp, iomap_iter_next_fn next) { struct address_space *mapping = vmf->vma->vm_file->f_mapping; XA_STATE(xas, &mapping->i_pages, vmf->pgoff); @@ -1935,7 +1936,7 @@ static vm_fault_t dax_iomap_pte_fault(struct vm_fault *vmf, unsigned long *pfnp, goto unlock_entry; } - while ((error = iomap_iter(&iter, ops)) > 0) { + while ((error = iomap_iter(&iter, next)) > 0) { if (WARN_ON_ONCE(iomap_length(&iter) < PAGE_SIZE)) { iter.status = -EIO; /* fs corruption? */ continue; @@ -2000,7 +2001,7 @@ static bool dax_fault_check_fallback(struct vm_fault *vmf, struct xa_state *xas, } static vm_fault_t dax_iomap_pmd_fault(struct vm_fault *vmf, unsigned long *pfnp, - const struct iomap_ops *ops) + iomap_iter_next_fn next) { struct address_space *mapping = vmf->vma->vm_file->f_mapping; XA_STATE_ORDER(xas, &mapping->i_pages, vmf->pgoff, PMD_ORDER); @@ -2057,7 +2058,7 @@ static vm_fault_t dax_iomap_pmd_fault(struct vm_fault *vmf, unsigned long *pfnp, } iter.pos = (loff_t)xas.xa_index << PAGE_SHIFT; - while (iomap_iter(&iter, ops) > 0) { + while (iomap_iter(&iter, next) > 0) { if (iomap_length(&iter) < PMD_SIZE) continue; /* actually breaks out of the loop */ @@ -2079,7 +2080,7 @@ out: } #else static vm_fault_t dax_iomap_pmd_fault(struct vm_fault *vmf, unsigned long *pfnp, - const struct iomap_ops *ops) + iomap_iter_next_fn next) { return VM_FAULT_FALLBACK; } @@ -2091,7 +2092,7 @@ static vm_fault_t dax_iomap_pmd_fault(struct vm_fault *vmf, unsigned long *pfnp, * @order: Order of the page to fault in * @pfnp: PFN to insert for synchronous faults if fsync is required * @iomap_errp: Storage for detailed error code in case of error - * @ops: Iomap ops passed from the file system + * @next: The iomap iteration function for the filesystem * * When a page fault occurs, filesystems may call this helper in * their fault handler for DAX files. dax_iomap_fault() assumes the caller @@ -2100,12 +2101,12 @@ static vm_fault_t dax_iomap_pmd_fault(struct vm_fault *vmf, unsigned long *pfnp, */ vm_fault_t dax_iomap_fault(struct vm_fault *vmf, unsigned int order, unsigned long *pfnp, int *iomap_errp, - const struct iomap_ops *ops) + iomap_iter_next_fn next) { if (order == 0) - return dax_iomap_pte_fault(vmf, pfnp, iomap_errp, ops); + return dax_iomap_pte_fault(vmf, pfnp, iomap_errp, next); else if (order == PMD_ORDER) - return dax_iomap_pmd_fault(vmf, pfnp, ops); + return dax_iomap_pmd_fault(vmf, pfnp, next); else return VM_FAULT_FALLBACK; } @@ -2235,7 +2236,7 @@ out_unlock: int dax_dedupe_file_range_compare(struct inode *src, loff_t srcoff, struct inode *dst, loff_t dstoff, loff_t len, bool *same, - const struct iomap_ops *ops) + iomap_iter_next_fn next) { struct iomap_iter src_iter = { .inode = src, @@ -2251,8 +2252,8 @@ int dax_dedupe_file_range_compare(struct inode *src, loff_t srcoff, }; int ret, status; - while ((ret = iomap_iter(&src_iter, ops)) > 0 && - (ret = iomap_iter(&dst_iter, ops)) > 0) { + while ((ret = iomap_iter(&src_iter, next)) > 0 && + (ret = iomap_iter(&dst_iter, next)) > 0) { status = dax_range_compare_iter(&src_iter, &dst_iter, min(src_iter.len, dst_iter.len), same); if (status < 0) @@ -2265,9 +2266,10 @@ int dax_dedupe_file_range_compare(struct inode *src, loff_t srcoff, int dax_remap_file_range_prep(struct file *file_in, loff_t pos_in, struct file *file_out, loff_t pos_out, loff_t *len, unsigned int remap_flags, - const struct iomap_ops *ops) + iomap_iter_next_fn next) { return __generic_remap_file_range_prep(file_in, pos_in, file_out, - pos_out, len, remap_flags, ops); + pos_out, len, remap_flags, + next); } EXPORT_SYMBOL_GPL(dax_remap_file_range_prep); diff --git a/fs/dcache.c b/fs/dcache.c index 720b32cb2e03..ba17f49f8a63 100644 --- a/fs/dcache.c +++ b/fs/dcache.c @@ -46,7 +46,8 @@ * dcache_hash_bucket lock protects: * - the dcache hash table * s_roots_lock protects: - * - the s_roots list (see __d_move()/dentry_unlist()/d_obtain_root()) + * - the s_roots list (see __d_move()/dentry_unlist()/d_obtain_root()/ + * dput_to_list()) * dentry->d_sb->s_dentry_lru_lock protects: * - the dcache lru lists and counters * d_lock protects: @@ -1118,7 +1119,18 @@ void dput_to_list(struct dentry *dentry, struct list_head *list) { if (likely(fast_dput(dentry))) return; - __move_to_shrink_list(dentry, list); + /* + * The list owner need not pin the superblock, so make a disconnected + * root a secondary one for shrink_dcache_for_umount() to find. + */ + if (__move_to_shrink_list(dentry, list) && + unlikely(IS_ROOT(dentry) && hlist_unhashed(&dentry->d_sib))) { + struct super_block *sb = dentry->d_sb; + + spin_lock(&sb->s_roots_lock); + hlist_add_head(&dentry->d_sib, &sb->s_roots); + spin_unlock(&sb->s_roots_lock); + } spin_unlock(&dentry->d_lock); } @@ -1606,21 +1618,25 @@ int path_has_submounts(const struct path *parent) } EXPORT_SYMBOL(path_has_submounts); +/* odd while d_set_mounted() runs, d_invalidate() waits on it */ +static __cacheline_aligned_in_smp DEFINE_SEQLOCK(d_set_mounted_lock); + /* * Called by mount code to set a mountpoint and check if the mountpoint is * reachable (e.g. NFS can unhash a directory dentry and then the complete * subtree can become unreachable). * * Only one of d_invalidate() and d_set_mounted() must succeed. For - * this reason take rename_lock and d_lock on dentry and ancestors. - * Likewise for dont_mount() which marks a dentry that is being removed - * under d_lock. + * this reason take rename_lock, d_set_mounted_lock and d_lock on dentry + * and ancestors. Likewise for dont_mount() which marks a dentry that + * is being removed under d_lock. */ int d_set_mounted(struct dentry *dentry) { struct dentry *p; int ret = -ENOENT; read_seqlock_excl(&rename_lock); + write_seqlock(&d_set_mounted_lock); for (p = dentry->d_parent; !IS_ROOT(p); p = p->d_parent) { /* Need exclusion wrt. d_invalidate() */ spin_lock(&p->d_lock); @@ -1638,8 +1654,9 @@ int d_set_mounted(struct dentry *dentry) ret = 0; } } - spin_unlock(&dentry->d_lock); + spin_unlock(&dentry->d_lock); out: + write_sequnlock(&d_set_mounted_lock); read_sequnlock_excl(&rename_lock); return ret; } @@ -1828,8 +1845,13 @@ static void do_one_tree(struct dentry *dentry) d_walk(dentry, dentry, umount_check); spin_lock(&dentry->d_lock); __d_drop(dentry); - /* A busy root survives the dput() below so don't leave it on ->s_roots. */ - if (unlikely(!hlist_unhashed(&dentry->d_sib))) + /* + * A busy root survives the dput() below so don't leave it on ->s_roots. + * An idle one stays until dentry_unlist() so that umount can wait for + * a racing eviction, see lock_for_kill(). + */ + if (unlikely(dentry->d_lockref.count > 1 && + !hlist_unhashed(&dentry->d_sib))) unlink_secondary_root(dentry); spin_unlock(&dentry->d_lock); dput(dentry); @@ -1892,6 +1914,7 @@ static enum d_walk_ret find_submount(void *_data, struct dentry *dentry) void d_invalidate(struct dentry *dentry) { bool had_submounts = false; + unsigned seq; spin_lock(&dentry->d_lock); if (d_unhashed(dentry)) { spin_unlock(&dentry->d_lock); @@ -1904,6 +1927,11 @@ void d_invalidate(struct dentry *dentry) if (!dentry->d_inode) return; + /* wait for a d_set_mounted() that saw us hashed to set its flag */ + do { + seq = read_seqbegin(&d_set_mounted_lock); + } while (read_seqretry(&d_set_mounted_lock, seq)); + shrink_dcache_parent(dentry); for (;;) { struct dentry *victim = NULL; diff --git a/fs/erofs/data.c b/fs/erofs/data.c index 968303afd620..e0b4ab96bc1e 100644 --- a/fs/erofs/data.c +++ b/fs/erofs/data.c @@ -60,6 +60,7 @@ int erofs_init_metabuf(struct erofs_buf *buf, struct super_block *sb, struct erofs_sb_info *sbi = EROFS_SB(sb); buf->mc = false; + buf->off = 0; if (in_metabox) { if (unlikely(!sbi->metabox_inode)) return -EFSCORRUPTED; @@ -374,10 +375,6 @@ static int erofs_iomap_end(struct inode *inode, loff_t pos, loff_t length, static DEFINE_IOMAP_ITER_NEXT_END(erofs_iomap_next, erofs_iomap_begin, erofs_iomap_end); -static const struct iomap_ops erofs_iomap_ops = { - .iomap_next = erofs_iomap_next, -}; - int erofs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo, u64 start, u64 len) { @@ -385,9 +382,9 @@ int erofs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo, if (!IS_ENABLED(CONFIG_EROFS_FS_ZIP)) return -EOPNOTSUPP; return iomap_fiemap(inode, fieinfo, start, len, - &z_erofs_iomap_report_ops); + z_erofs_iomap_next_report); } - return iomap_fiemap(inode, fieinfo, start, len, &erofs_iomap_ops); + return iomap_fiemap(inode, fieinfo, start, len, erofs_iomap_next); } /* @@ -408,7 +405,7 @@ static int erofs_read_folio(struct file *file, struct folio *folio) }; trace_erofs_read_folio(iter_ctx.realinode, folio, true); - iomap_read_folio(&erofs_iomap_ops, &read_ctx, &iter_ctx); + iomap_read_folio(erofs_iomap_next, &read_ctx, &iter_ctx); if (need_iput) iput(iter_ctx.realinode); return 0; @@ -429,14 +426,14 @@ static void erofs_readahead(struct readahead_control *rac) trace_erofs_readahead(iter_ctx.realinode, readahead_index(rac), readahead_count(rac), true); - iomap_readahead(&erofs_iomap_ops, &read_ctx, &iter_ctx); + iomap_readahead(erofs_iomap_next, &read_ctx, &iter_ctx); if (need_iput) iput(iter_ctx.realinode); } static sector_t erofs_bmap(struct address_space *mapping, sector_t block) { - return iomap_bmap(mapping, block, &erofs_iomap_ops); + return iomap_bmap(mapping, block, erofs_iomap_next); } static ssize_t erofs_file_read_iter(struct kiocb *iocb, struct iov_iter *to) @@ -448,14 +445,14 @@ static ssize_t erofs_file_read_iter(struct kiocb *iocb, struct iov_iter *to) return 0; if (IS_ENABLED(CONFIG_FS_DAX) && IS_DAX(inode)) - return dax_iomap_rw(iocb, to, &erofs_iomap_ops); + return dax_iomap_rw(iocb, to, erofs_iomap_next); if ((iocb->ki_flags & IOCB_DIRECT) && inode->i_sb->s_bdev) { struct erofs_iomap_iter_ctx iter_ctx = { .realinode = inode, }; - return iomap_dio_rw(iocb, to, &erofs_iomap_ops, + return iomap_dio_rw(iocb, to, erofs_iomap_next, NULL, 0, &iter_ctx, 0); } return filemap_read(iocb, to, 0); @@ -474,7 +471,7 @@ const struct address_space_operations erofs_aops = { static vm_fault_t erofs_dax_huge_fault(struct vm_fault *vmf, unsigned int order) { - return dax_iomap_fault(vmf, order, NULL, NULL, &erofs_iomap_ops); + return dax_iomap_fault(vmf, order, NULL, NULL, erofs_iomap_next); } static vm_fault_t erofs_dax_fault(struct vm_fault *vmf) @@ -506,18 +503,18 @@ static int erofs_file_mmap_prepare(struct vm_area_desc *desc) loff_t erofs_file_llseek(struct file *file, loff_t offset, int whence) { struct inode *inode = file->f_mapping->host; - const struct iomap_ops *ops = &erofs_iomap_ops; + iomap_iter_next_fn next = erofs_iomap_next; if (erofs_inode_is_data_compressed(EROFS_I(inode)->datalayout)) { if (!IS_ENABLED(CONFIG_EROFS_FS_ZIP)) return generic_file_llseek(file, offset, whence); - ops = &z_erofs_iomap_report_ops; + next = z_erofs_iomap_next_report; } if (whence == SEEK_HOLE) - offset = iomap_seek_hole(inode, offset, ops); + offset = iomap_seek_hole(inode, offset, next); else if (whence == SEEK_DATA) - offset = iomap_seek_data(inode, offset, ops); + offset = iomap_seek_data(inode, offset, next); else return generic_file_llseek(file, offset, whence); diff --git a/fs/erofs/internal.h b/fs/erofs/internal.h index 8363c0c051f6..c16dfa752cf9 100644 --- a/fs/erofs/internal.h +++ b/fs/erofs/internal.h @@ -397,9 +397,10 @@ struct erofs_iomap_iter_ctx { struct inode *realinode; }; -extern const struct iomap_ops z_erofs_iomap_report_ops; extern const struct iomap_read_ops erofs_fileio_iomap_read_ops; +DECLARE_IOMAP_ITER_NEXT(z_erofs_iomap_next_report); + int erofs_setup_managed_cache(struct super_block *sb); #ifdef CONFIG_EROFS_FS_BACKED_BY_FILE int erofs_read_meta_folio(struct file *file, struct folio *folio); diff --git a/fs/erofs/super.c b/fs/erofs/super.c index ce05557bd998..e92a7fa90ae3 100644 --- a/fs/erofs/super.c +++ b/fs/erofs/super.c @@ -122,6 +122,17 @@ void *erofs_read_metadata(struct super_block *sb, struct erofs_buf *buf, return buffer; } +/* see the comment in erofs_fc_fill_super() */ +static bool erofs_is_stacked_file(struct file *file) +{ + struct inode *inode = file_inode(file); + struct super_block *sb = inode->i_sb; + + return (sb->s_op == &erofs_sops && !sb->s_bdev) || sb->s_stack_depth || + (IS_ENABLED(CONFIG_EROFS_FS_PAGE_CACHE_SHARE) && + inode->i_fop == &erofs_ishare_fops); +} + static int erofs_init_device(struct erofs_buf *buf, struct super_block *sb, struct erofs_device_info *dif, erofs_off_t *pos) { @@ -161,6 +172,11 @@ static int erofs_init_device(struct erofs_buf *buf, struct super_block *sb, } else if (!S_ISREG(file_inode(file)->i_mode)) { fput(file); return -EINVAL; + } else if (erofs_is_stacked_file(file)) { + erofs_err(sb, "%s: file-backed devices cannot be on stacked fses", + dif->path); + fput(file); + return -EINVAL; } if (!dif->dax_dev && test_opt(&sbi->opt, DAX_ALWAYS)) { erofs_info(sb, "DAX unsupported by %s. Turning off DAX.", @@ -700,10 +716,11 @@ static int erofs_fc_fill_super(struct super_block *sb, struct fs_context *fc) * EROFS is the only fs supporting file-backed mounts for now. * It MUST change if another fs plans to support them, which * may also require adjusting FILESYSTEM_MAX_STACK_DEPTH. + * Files shared by inode_share may be read through a + * file-backed EROFS in the same domain, so treat them as + * stacked too. */ - inode = file_inode(sbi->dif0.file); - if ((inode->i_sb->s_op == &erofs_sops && - !inode->i_sb->s_bdev) || inode->i_sb->s_stack_depth) { + if (erofs_is_stacked_file(sbi->dif0.file)) { erofs_err(sb, "file-backed mounts cannot be applied to stacked fses"); return -ENOTBLK; } diff --git a/fs/erofs/zmap.c b/fs/erofs/zmap.c index f8981fc74246..e0d5987b742b 100644 --- a/fs/erofs/zmap.c +++ b/fs/erofs/zmap.c @@ -830,9 +830,4 @@ static int z_erofs_iomap_begin_report(struct inode *inode, loff_t offset, return 0; } -static DEFINE_IOMAP_ITER_NEXT(z_erofs_iomap_next_report, - z_erofs_iomap_begin_report); - -const struct iomap_ops z_erofs_iomap_report_ops = { - .iomap_next = z_erofs_iomap_next_report, -}; +DEFINE_IOMAP_ITER_NEXT(z_erofs_iomap_next_report, z_erofs_iomap_begin_report); diff --git a/fs/eventpoll.c b/fs/eventpoll.c index 7a32c70bf2ad..b959af04772c 100644 --- a/fs/eventpoll.c +++ b/fs/eventpoll.c @@ -2144,10 +2144,17 @@ static int ep_send_events(struct eventpoll *ep, /* * Always short-circuit for fatal signals to allow threads to make a * timely exit without the chance of finding more events available and - * fetching repeatedly. + * fetching repeatedly. The wakeup that got us here may have been the + * only one for the events on ->rdllist, so pass it on to the next + * waiter, as ep_done_scan() would have. */ - if (fatal_signal_pending(current)) + if (fatal_signal_pending(current)) { + spin_lock_irq(&ep->lock); + if (!list_empty(&ep->rdllist)) + wake_up(&ep->wq); + spin_unlock_irq(&ep->lock); return -EINTR; + } init_poll_funcptr(&pt, NULL); diff --git a/fs/exfat/file.c b/fs/exfat/file.c index 1386149916bb..435bbef288b8 100644 --- a/fs/exfat/file.c +++ b/fs/exfat/file.c @@ -828,7 +828,7 @@ static ssize_t exfat_fallback_buffered_write(struct kiocb *iocb, inode_dio_wait(file_inode(iocb->ki_filp)); - written = iomap_file_buffered_write(iocb, from, &exfat_write_iomap_ops, + written = iomap_file_buffered_write(iocb, from, exfat_write_iomap_next, NULL, NULL); if (written < 0) return written; @@ -850,7 +850,7 @@ static ssize_t exfat_dio_write_iter(struct kiocb *iocb, struct iov_iter *from) { ssize_t ret; - ret = iomap_dio_rw(iocb, from, &exfat_write_iomap_ops, + ret = iomap_dio_rw(iocb, from, exfat_write_iomap_next, &exfat_write_dio_ops, 0, NULL, 0); if (ret == -ENOTBLK) ret = 0; @@ -921,7 +921,7 @@ static ssize_t exfat_file_write_iter(struct kiocb *iocb, struct iov_iter *iter) */ inode_dio_wait(inode); ret = iomap_file_buffered_write(iocb, iter, - &exfat_write_iomap_ops, NULL, NULL); + exfat_write_iomap_next, NULL, NULL); } if (ret != -EIOCBQUEUED && end > i_size_read(inode)) exfat_write_failed(inode); @@ -957,7 +957,7 @@ static ssize_t exfat_file_read_iter(struct kiocb *iocb, struct iov_iter *iter) if (iocb->ki_flags & IOCB_DIRECT) { file_accessed(iocb->ki_filp); - ret = iomap_dio_rw(iocb, iter, &exfat_iomap_ops, NULL, 0, + ret = iomap_dio_rw(iocb, iter, exfat_iomap_next, NULL, 0, NULL, 0); } else { ret = generic_file_read_iter(iocb, iter); @@ -1016,7 +1016,7 @@ static vm_fault_t exfat_page_mkwrite(struct vm_fault *vmf) file_update_time(vmf->vma->vm_file); filemap_invalidate_lock_shared(inode->i_mapping); - ret = iomap_page_mkwrite(vmf, &exfat_iomap_ops, NULL); + ret = iomap_page_mkwrite(vmf, exfat_iomap_next, NULL); filemap_invalidate_unlock_shared(inode->i_mapping); sb_end_pagefault(inode->i_sb); inode_unlock(inode); @@ -1073,12 +1073,12 @@ static loff_t exfat_file_llseek(struct file *file, loff_t offset, int whence) switch (whence) { case SEEK_HOLE: inode_lock_shared(inode); - offset = iomap_seek_hole(inode, offset, &exfat_iomap_ops); + offset = iomap_seek_hole(inode, offset, exfat_iomap_next); inode_unlock_shared(inode); break; case SEEK_DATA: inode_lock_shared(inode); - offset = iomap_seek_data(inode, offset, &exfat_iomap_ops); + offset = iomap_seek_data(inode, offset, exfat_iomap_next); inode_unlock_shared(inode); break; default: diff --git a/fs/exfat/inode.c b/fs/exfat/inode.c index 5129df1e79b4..c1d15d4fc5e7 100644 --- a/fs/exfat/inode.c +++ b/fs/exfat/inode.c @@ -249,7 +249,7 @@ static int exfat_read_folio(struct file *file, struct folio *folio) .ops = &exfat_iomap_bio_read_ops, }; - iomap_read_folio(&exfat_iomap_ops, &ctx, NULL); + iomap_read_folio(exfat_iomap_next, &ctx, NULL); return 0; } @@ -271,7 +271,7 @@ static void exfat_readahead(struct readahead_control *rac) valid_size < pos + readahead_length(rac)) return; - iomap_readahead(&exfat_iomap_ops, &ctx, NULL); + iomap_readahead(exfat_iomap_next, &ctx, NULL); } static int exfat_writepages(struct address_space *mapping, @@ -294,7 +294,7 @@ static sector_t exfat_aop_bmap(struct address_space *mapping, sector_t block) sector_t blocknr; inode_lock_shared(mapping->host); - blocknr = iomap_bmap(mapping, block, &exfat_iomap_ops); + blocknr = iomap_bmap(mapping, block, exfat_iomap_next); inode_unlock_shared(mapping->host); return blocknr; } diff --git a/fs/exfat/iomap.c b/fs/exfat/iomap.c index e50ecbfbfbe0..4e6f3ed9dcc8 100644 --- a/fs/exfat/iomap.c +++ b/fs/exfat/iomap.c @@ -179,15 +179,11 @@ static int exfat_write_iomap_begin(struct inode *inode, loff_t offset, loff_t le * Zero the invalid bytes from valid_size to the end of the block * to prevent stale data from being exposed through the page cache. */ - return iomap_truncate_page(inode, valid_size, NULL, &exfat_iomap_ops, + return iomap_truncate_page(inode, valid_size, NULL, exfat_iomap_next, NULL, NULL); } -static DEFINE_IOMAP_ITER_NEXT(exfat_iomap_next, exfat_iomap_begin); - -const struct iomap_ops exfat_iomap_ops = { - .iomap_next = exfat_iomap_next, -}; +DEFINE_IOMAP_ITER_NEXT(exfat_iomap_next, exfat_iomap_begin); #ifdef CONFIG_SWAP static int exfat_swap_iomap_begin(struct inode *inode, loff_t offset, @@ -204,10 +200,6 @@ static int exfat_swap_iomap_begin(struct inode *inode, loff_t offset, static DEFINE_IOMAP_ITER_NEXT(exfat_swap_iomap_next, exfat_swap_iomap_begin); - -static const struct iomap_ops exfat_swap_iomap_ops = { - .iomap_next = exfat_swap_iomap_next, -}; #endif /* @@ -245,12 +237,8 @@ static int exfat_write_iomap_end(struct inode *inode, loff_t pos, loff_t length, return written; } -static DEFINE_IOMAP_ITER_NEXT_END(exfat_write_iomap_next, - exfat_write_iomap_begin, exfat_write_iomap_end); - -const struct iomap_ops exfat_write_iomap_ops = { - .iomap_next = exfat_write_iomap_next, -}; +DEFINE_IOMAP_ITER_NEXT_END(exfat_write_iomap_next, exfat_write_iomap_begin, + exfat_write_iomap_end); /* * exfat_writeback_range - Map folio during writeback @@ -327,7 +315,7 @@ int exfat_iomap_swap_activate(struct swap_info_struct *sis, { #ifdef CONFIG_SWAP return iomap_swapfile_activate(sis, file, span, - &exfat_swap_iomap_ops); + exfat_swap_iomap_next); #else return -EIO; #endif diff --git a/fs/exfat/iomap.h b/fs/exfat/iomap.h index fd8a913f7794..519132367b65 100644 --- a/fs/exfat/iomap.h +++ b/fs/exfat/iomap.h @@ -6,9 +6,11 @@ #ifndef _LINUX_EXFAT_IOMAP_H #define _LINUX_EXFAT_IOMAP_H +#include <linux/iomap.h> + extern const struct iomap_dio_ops exfat_write_dio_ops; -extern const struct iomap_ops exfat_iomap_ops; -extern const struct iomap_ops exfat_write_iomap_ops; +DECLARE_IOMAP_ITER_NEXT(exfat_iomap_next); +DECLARE_IOMAP_ITER_NEXT(exfat_write_iomap_next); extern const struct iomap_writeback_ops exfat_writeback_ops; extern const struct iomap_read_ops exfat_iomap_bio_read_ops; diff --git a/fs/ext2/ext2.h b/fs/ext2/ext2.h index 7bdada93dd06..b46649c510a5 100644 --- a/fs/ext2/ext2.h +++ b/fs/ext2/ext2.h @@ -18,6 +18,7 @@ #include <linux/rbtree.h> #include <linux/mm.h> #include <linux/highmem.h> +#include <linux/iomap.h> /* XXX Here for now... not interested in restructing headers JUST now */ @@ -782,7 +783,7 @@ extern const struct file_operations ext2_file_operations; /* inode.c */ extern void ext2_set_file_ops(struct inode *inode); extern const struct address_space_operations ext2_aops; -extern const struct iomap_ops ext2_iomap_ops; +DECLARE_IOMAP_ITER_NEXT(ext2_iomap_next); /* namei.c */ extern const struct inode_operations ext2_dir_inode_operations; diff --git a/fs/ext2/file.c b/fs/ext2/file.c index 8ddc149d4884..f4607a039b0b 100644 --- a/fs/ext2/file.c +++ b/fs/ext2/file.c @@ -55,7 +55,7 @@ static ssize_t ext2_dio_read_iter(struct kiocb *iocb, struct iov_iter *to) trace_ext2_dio_read_begin(iocb, to, 0); inode_lock_shared(inode); - ret = iomap_dio_rw(iocb, to, &ext2_iomap_ops, NULL, 0, NULL, 0); + ret = iomap_dio_rw(iocb, to, ext2_iomap_next, NULL, 0, NULL, 0); inode_unlock_shared(inode); trace_ext2_dio_read_end(iocb, to, ret); @@ -119,7 +119,7 @@ static ssize_t ext2_dio_write_iter(struct kiocb *iocb, struct iov_iter *from) (!IS_ALIGNED(iocb->ki_pos | iov_iter_alignment(from), blocksize))) flags |= IOMAP_DIO_FORCE_WAIT; - ret = iomap_dio_rw(iocb, from, &ext2_iomap_ops, &ext2_dio_write_ops, + ret = iomap_dio_rw(iocb, from, ext2_iomap_next, &ext2_dio_write_ops, flags, NULL, 0); /* ENOTBLK is magic return value for fallback to buffered-io */ diff --git a/fs/ext2/inode.c b/fs/ext2/inode.c index 1989258aef8a..9a5416fcd8ab 100644 --- a/fs/ext2/inode.c +++ b/fs/ext2/inode.c @@ -93,8 +93,6 @@ void ext2_evict_inode(struct inode * inode) if (inode->i_blocks) ext2_truncate_blocks(inode, 0); ext2_xattr_delete_inode(inode); - } else { - mmb_sync(&EXT2_I(inode)->i_metadata_bhs); } mmb_invalidate(&EXT2_I(inode)->i_metadata_bhs); clear_inode(inode); @@ -863,12 +861,7 @@ ext2_iomap_end(struct inode *inode, loff_t offset, loff_t length, return 0; } -static DEFINE_IOMAP_ITER_NEXT_END(ext2_iomap_next, ext2_iomap_begin, - ext2_iomap_end); - -const struct iomap_ops ext2_iomap_ops = { - .iomap_next = ext2_iomap_next, -}; +DEFINE_IOMAP_ITER_NEXT_END(ext2_iomap_next, ext2_iomap_begin, ext2_iomap_end); int ext2_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo, u64 start, u64 len) @@ -887,7 +880,7 @@ int ext2_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo, if (i_size == 0) i_size = 1; len = min_t(u64, len, i_size); - ret = iomap_fiemap(inode, fieinfo, start, len, &ext2_iomap_ops); + ret = iomap_fiemap(inode, fieinfo, start, len, ext2_iomap_next); inode_unlock(inode); return ret; @@ -1271,46 +1264,59 @@ static int ext2_setsize(struct inode *inode, loff_t newsize) return 0; } -static struct ext2_inode *ext2_get_inode(struct super_block *sb, ino_t ino, - struct buffer_head **p) +/* + * Find the inode table block that holds inode @ino and the offset of the + * inode in that block. + */ +static int ext2_inode_block(struct super_block *sb, ino_t ino, + unsigned long *block, unsigned long *offset) { - struct buffer_head * bh; unsigned long block_group; - unsigned long block; - unsigned long offset; struct ext2_group_desc * gdp; - *p = NULL; if ((ino != EXT2_ROOT_INO && ino < EXT2_FIRST_INO(sb)) || - ino > le32_to_cpu(EXT2_SB(sb)->s_es->s_inodes_count)) - goto Einval; + ino > le32_to_cpu(EXT2_SB(sb)->s_es->s_inodes_count)) { + ext2_error(sb, __func__, "bad inode number: %lu", + (unsigned long) ino); + return -EINVAL; + } block_group = (ino - 1) / EXT2_INODES_PER_GROUP(sb); gdp = ext2_get_group_desc(sb, block_group, NULL); if (!gdp) - goto Egdp; + return -EIO; /* * Figure out the offset within the block group inode table */ - offset = ((ino - 1) % EXT2_INODES_PER_GROUP(sb)) * EXT2_INODE_SIZE(sb); - block = le32_to_cpu(gdp->bg_inode_table) + - (offset >> EXT2_BLOCK_SIZE_BITS(sb)); + *offset = ((ino - 1) % EXT2_INODES_PER_GROUP(sb)) * EXT2_INODE_SIZE(sb); + *block = le32_to_cpu(gdp->bg_inode_table) + + (*offset >> EXT2_BLOCK_SIZE_BITS(sb)); + *offset &= (EXT2_BLOCK_SIZE(sb) - 1); + return 0; +} + +static struct ext2_inode *ext2_get_inode(struct super_block *sb, ino_t ino, + struct buffer_head **p) +{ + struct buffer_head *bh; + unsigned long block; + unsigned long offset; + int err; + + *p = NULL; + err = ext2_inode_block(sb, ino, &block, &offset); + if (err) + return ERR_PTR(err); if (!(bh = sb_bread(sb, block))) goto Eio; *p = bh; - offset &= (EXT2_BLOCK_SIZE(sb) - 1); return (struct ext2_inode *) (bh->b_data + offset); -Einval: - ext2_error(sb, "ext2_get_inode", "bad inode number: %lu", - (unsigned long) ino); - return ERR_PTR(-EINVAL); Eio: ext2_error(sb, "ext2_get_inode", "unable to read inode block - inode=%lu, block=%lu", (unsigned long) ino, block); -Egdp: return ERR_PTR(-EIO); } @@ -1572,19 +1578,22 @@ int ext2_write_inode(struct inode *inode, struct writeback_control *wbc) int ext2_sync_inode_metadata(struct inode *inode, struct writeback_control *wbc) { struct buffer_head *bh; - struct ext2_inode *raw_inode = ext2_get_inode(inode->i_sb, inode->i_ino, - &bh); + unsigned long block, offset; int err = 0; - if (IS_ERR(raw_inode)) + if (ext2_inode_block(inode->i_sb, inode->i_ino, &block, &offset)) return -EIO; err = mmb_sync(&EXT2_I(inode)->i_metadata_bhs); if (err) { ext2_error(inode->i_sb, __func__, "Error syncing inode metadata ino=%lu\n", (unsigned long)inode->i_ino); - goto out; + return err; } + /* A block that isn't cached is neither dirty nor under writeback. */ + bh = sb_find_get_block_nonatomic(inode->i_sb, block); + if (!bh) + return 0; sync_dirty_buffer(bh); if (buffer_write_io_error(bh)) { ext2_error(inode->i_sb, __func__, @@ -1592,7 +1601,6 @@ int ext2_sync_inode_metadata(struct inode *inode, struct writeback_control *wbc) (unsigned long)inode->i_ino); err = -EIO; } -out: brelse(bh); return err; } diff --git a/fs/ext4/ext4.h b/fs/ext4/ext4.h index f38fec3167fb..bf0325ecbec7 100644 --- a/fs/ext4/ext4.h +++ b/fs/ext4/ext4.h @@ -20,6 +20,7 @@ #include <linux/refcount.h> #include <linux/types.h> #include <linux/blkdev.h> +#include <linux/iomap.h> #include <linux/magic.h> #include <linux/jbd2.h> #include <linux/quota.h> @@ -4105,10 +4106,11 @@ static inline void ext4_clear_io_unwritten_flag(ext4_io_end_t *io_end) io_end->flag &= ~EXT4_IO_END_UNWRITTEN; } -extern const struct iomap_ops ext4_iomap_ops; -extern const struct iomap_ops ext4_iomap_report_ops; -extern const struct iomap_ops ext4_iomap_buffered_write_ops; -extern const struct iomap_ops ext4_iomap_buffered_da_write_ops; +DECLARE_IOMAP_ITER_NEXT(ext4_iomap_next); +DECLARE_IOMAP_ITER_NEXT(ext4_iomap_next_report); +DECLARE_IOMAP_ITER_NEXT(ext4_iomap_buffered_write_next); +DECLARE_IOMAP_ITER_NEXT(ext4_iomap_buffered_da_write_next); + extern const struct iomap_write_ops ext4_iomap_write_ops; int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length, diff --git a/fs/ext4/extents.c b/fs/ext4/extents.c index ad0d80e33f60..cd35e88bc372 100644 --- a/fs/ext4/extents.c +++ b/fs/ext4/extents.c @@ -5315,10 +5315,6 @@ static int ext4_iomap_xattr_begin(struct inode *inode, loff_t offset, static DEFINE_IOMAP_ITER_NEXT(ext4_iomap_xattr_next, ext4_iomap_xattr_begin); -static const struct iomap_ops ext4_iomap_xattr_ops = { - .iomap_next = ext4_iomap_xattr_next, -}; - static int ext4_fiemap_check_ranges(struct inode *inode, u64 start, u64 *len) { u64 maxbytes = ext4_get_maxbytes(inode); @@ -5361,10 +5357,10 @@ int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo, if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) { fieinfo->fi_flags &= ~FIEMAP_FLAG_XATTR; error = iomap_fiemap(inode, fieinfo, start, len, - &ext4_iomap_xattr_ops); + ext4_iomap_xattr_next); } else { error = iomap_fiemap(inode, fieinfo, start, len, - &ext4_iomap_report_ops); + ext4_iomap_next_report); } unlock: inode_unlock_shared(inode); diff --git a/fs/ext4/file.c b/fs/ext4/file.c index 50d3c92709c8..ad8985c529c6 100644 --- a/fs/ext4/file.c +++ b/fs/ext4/file.c @@ -93,7 +93,7 @@ static ssize_t ext4_dio_read_iter(struct kiocb *iocb, struct iov_iter *to) ret = iomap_dio_read_simple(iocb, to, ext4_iomap_begin); if (ret == -ENOTBLK) - ret = iomap_dio_rw(iocb, to, &ext4_iomap_ops, NULL, 0, NULL, 0); + ret = iomap_dio_rw(iocb, to, ext4_iomap_next, NULL, 0, NULL, 0); inode_unlock_shared(inode); file_accessed(iocb->ki_filp); @@ -121,7 +121,7 @@ static ssize_t ext4_dax_read_iter(struct kiocb *iocb, struct iov_iter *to) /* Fallback to buffered IO in case we cannot support DAX */ return generic_file_read_iter(iocb, to); } - ret = dax_iomap_rw(iocb, to, &ext4_iomap_ops); + ret = dax_iomap_rw(iocb, to, ext4_iomap_next); inode_unlock_shared(inode); file_accessed(iocb->ki_filp); @@ -334,14 +334,14 @@ static ssize_t ext4_iomap_buffered_write(struct kiocb *iocb, struct iov_iter *from) { struct inode *inode = file_inode(iocb->ki_filp); - const struct iomap_ops *iomap_ops; + iomap_iter_next_fn next; if (test_opt(inode->i_sb, DELALLOC) && !ext4_nonda_switch(inode->i_sb)) - iomap_ops = &ext4_iomap_buffered_da_write_ops; + next = ext4_iomap_buffered_da_write_next; else - iomap_ops = &ext4_iomap_buffered_write_ops; + next = ext4_iomap_buffered_write_next; - return iomap_file_buffered_write(iocb, from, iomap_ops, + return iomap_file_buffered_write(iocb, from, next, &ext4_iomap_write_ops, NULL); } @@ -663,7 +663,7 @@ static ssize_t ext4_dio_write_iter(struct kiocb *iocb, struct iov_iter *from) goto out; } - ret = iomap_dio_rw(iocb, from, &ext4_iomap_ops, &ext4_dio_write_ops, + ret = iomap_dio_rw(iocb, from, ext4_iomap_next, &ext4_dio_write_ops, dio_flags, NULL, 0); if (ret == -ENOTBLK) ret = 0; @@ -767,7 +767,7 @@ ext4_dax_write_iter(struct kiocb *iocb, struct iov_iter *from) ext4_journal_stop(handle); } - ret = dax_iomap_rw(iocb, from, &ext4_iomap_ops); + ret = dax_iomap_rw(iocb, from, ext4_iomap_next); if (extend) { ret = ext4_handle_inode_extension(inode, offset, ret, count); @@ -855,7 +855,7 @@ retry: } else { filemap_invalidate_lock_shared(mapping); } - result = dax_iomap_fault(vmf, order, &pfn, &error, &ext4_iomap_ops); + result = dax_iomap_fault(vmf, order, &pfn, &error, ext4_iomap_next); if (write) { ext4_journal_stop(handle); @@ -1034,13 +1034,13 @@ loff_t ext4_llseek(struct file *file, loff_t offset, int whence) case SEEK_HOLE: inode_lock_shared(inode); offset = iomap_seek_hole(inode, offset, - &ext4_iomap_report_ops); + ext4_iomap_next_report); inode_unlock_shared(inode); break; case SEEK_DATA: inode_lock_shared(inode); offset = iomap_seek_data(inode, offset, - &ext4_iomap_report_ops); + ext4_iomap_next_report); inode_unlock_shared(inode); break; } diff --git a/fs/ext4/inode.c b/fs/ext4/inode.c index 10cd85d4c721..e3129353d4ed 100644 --- a/fs/ext4/inode.c +++ b/fs/ext4/inode.c @@ -250,8 +250,6 @@ void ext4_evict_inode(struct inode *inode) if (EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL) ext4_evict_ea_inode(inode); if (inode->i_nlink) { - struct mapping_metadata_bhs *mmb; - /* * If there's dirty page will lead to data loss, user * could see stale data. @@ -261,9 +259,6 @@ void ext4_evict_inode(struct inode *inode) ext4_warning_inode(inode, "data will be lost"); truncate_inode_pages_final(&inode->i_data); - mmb = ext4_i_metadata_bhs(inode); - if (mmb) - mmb_sync(mmb); goto no_delete; } @@ -3519,7 +3514,7 @@ static sector_t ext4_bmap(struct address_space *mapping, sector_t block) filemap_write_and_wait(mapping); } - ret = iomap_bmap(mapping, block, &ext4_iomap_ops); + ret = iomap_bmap(mapping, block, ext4_iomap_next); out: inode_unlock_shared(inode); @@ -3994,11 +3989,7 @@ out: return 0; } -static DEFINE_IOMAP_ITER_NEXT(ext4_iomap_next, ext4_iomap_begin); - -const struct iomap_ops ext4_iomap_ops = { - .iomap_next = ext4_iomap_next, -}; +DEFINE_IOMAP_ITER_NEXT(ext4_iomap_next, ext4_iomap_begin); static int ext4_iomap_begin_report(struct inode *inode, loff_t offset, loff_t length, unsigned int flags, @@ -4051,11 +4042,7 @@ set_iomap: return 0; } -static DEFINE_IOMAP_ITER_NEXT(ext4_iomap_next_report, ext4_iomap_begin_report); - -const struct iomap_ops ext4_iomap_report_ops = { - .iomap_next = ext4_iomap_next_report, -}; +DEFINE_IOMAP_ITER_NEXT(ext4_iomap_next_report, ext4_iomap_begin_report); static int ext4_iomap_map_blocks(struct inode *inode, loff_t offset, loff_t length, struct ext4_map_blocks *map, @@ -4260,45 +4247,29 @@ again: static DEFINE_IOMAP_ITER_NEXT(ext4_iomap_zero_next, ext4_iomap_zero_begin); -static const struct iomap_ops ext4_iomap_zero_ops = { - .iomap_next = ext4_iomap_zero_next, -}; - /* * Since we always allocate unwritten extents, there is no need for * iomap_end to clean up allocated blocks on a short write. */ -static DEFINE_IOMAP_ITER_NEXT(ext4_iomap_buffered_write_next, - ext4_iomap_buffered_write_begin); - -const struct iomap_ops ext4_iomap_buffered_write_ops = { - .iomap_next = ext4_iomap_buffered_write_next, -}; +DEFINE_IOMAP_ITER_NEXT(ext4_iomap_buffered_write_next, + ext4_iomap_buffered_write_begin); -static DEFINE_IOMAP_ITER_NEXT_END(ext4_iomap_buffered_da_write_next, - ext4_iomap_buffered_da_write_begin, - ext4_iomap_buffered_da_write_end); - -const struct iomap_ops ext4_iomap_buffered_da_write_ops = { - .iomap_next = ext4_iomap_buffered_da_write_next, -}; +DEFINE_IOMAP_ITER_NEXT_END(ext4_iomap_buffered_da_write_next, + ext4_iomap_buffered_da_write_begin, + ext4_iomap_buffered_da_write_end); static DEFINE_IOMAP_ITER_NEXT(ext4_iomap_buffered_read_next, ext4_iomap_buffered_read_begin); -static const struct iomap_ops ext4_iomap_buffered_read_ops = { - .iomap_next = ext4_iomap_buffered_read_next, -}; - static int ext4_iomap_read_folio(struct file *file, struct folio *folio) { - iomap_bio_read_folio(folio, &ext4_iomap_buffered_read_ops); + iomap_bio_read_folio(folio, ext4_iomap_buffered_read_next); return 0; } static void ext4_iomap_readahead(struct readahead_control *rac) { - iomap_bio_readahead(rac, &ext4_iomap_buffered_read_ops); + iomap_bio_readahead(rac, ext4_iomap_buffered_read_next); } @@ -4561,7 +4532,7 @@ static int ext4_iomap_swap_activate(struct swap_info_struct *sis, struct file *file, sector_t *span) { return iomap_swapfile_activate(sis, file, span, - &ext4_iomap_report_ops); + ext4_iomap_next_report); } static const struct address_space_operations ext4_aops = { @@ -4827,7 +4798,7 @@ static int ext4_block_iomap_zero_range(struct inode *inode, loff_t from, !rwsem_is_locked(&inode->i_mapping->invalidate_lock)); ret = iomap_zero_range(inode, from, length, did_zero, - &ext4_iomap_zero_ops, &ext4_iomap_write_ops, + ext4_iomap_zero_next, &ext4_iomap_write_ops, NULL); if (ret) return ret; @@ -4866,7 +4837,7 @@ static int ext4_block_zero_range(struct inode *inode, if (IS_DAX(inode)) { return dax_zero_range(inode, from, length, did_zero, - &ext4_iomap_ops); + ext4_iomap_next); } else if (ext4_should_journal_data(inode)) { return ext4_block_journalled_zero_range(inode, from, length, did_zero); @@ -5876,7 +5847,8 @@ int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc) /* * ext4_get_inode_loc_noio() is a best-effort variant of ext4_get_inode_loc(). * It looks up the inode table block in the buffer cache and returns -EAGAIN if - * the block is not present or not uptodate, without starting any I/O. + * the block is not present or not uptodate, without starting any I/O. It may + * sleep on the folio lock of the block. */ int ext4_get_inode_loc_noio(struct inode *inode, struct ext4_iloc *iloc) { @@ -5912,7 +5884,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(sb, block); + bh = sb_find_get_block_nonatomic(sb, block); if (!bh) return -EAGAIN; if (!ext4_buffer_uptodate(bh)) { @@ -6820,22 +6792,24 @@ int ext4_sync_inode_metadata(struct inode *inode, struct writeback_control *wbc) if (WARN_ON_ONCE(EXT4_SB(inode->i_sb)->s_journal)) return -EFSCORRUPTED; - err = __ext4_get_inode_loc_noinmem(inode, &iloc); - if (err) - return err; mmb = READ_ONCE(EXT4_I(inode)->i_metadata_bhs); if (mmb) { err = mmb_sync(mmb); if (err) - goto out; + return err; } + /* A block that isn't cached is neither dirty nor under writeback. */ + err = ext4_get_inode_loc_noio(inode, &iloc); + if (err == -EAGAIN) + return 0; + if (err) + return err; sync_dirty_buffer(iloc.bh); if (buffer_write_io_error(iloc.bh)) { ext4_error_inode_block(inode, iloc.bh->b_blocknr, EIO, "IO error syncing inode"); err = -EIO; } -out: brelse(iloc.bh); return err; } @@ -7829,18 +7803,18 @@ out_error: static vm_fault_t ext4_iomap_page_mkwrite(struct vm_fault *vmf) { struct inode *inode = file_inode(vmf->vma->vm_file); - const struct iomap_ops *iomap_ops; + iomap_iter_next_fn next; /* * ext4_nonda_switch() could writeback this folio, so have to * call it before lock folio. */ if (test_opt(inode->i_sb, DELALLOC) && !ext4_nonda_switch(inode->i_sb)) - iomap_ops = &ext4_iomap_buffered_da_write_ops; + next = ext4_iomap_buffered_da_write_next; else - iomap_ops = &ext4_iomap_buffered_write_ops; + next = ext4_iomap_buffered_write_next; - return iomap_page_mkwrite(vmf, iomap_ops, NULL); + return iomap_page_mkwrite(vmf, next, NULL); } vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf) diff --git a/fs/f2fs/data.c b/fs/f2fs/data.c index 28fd8afff5d4..7c5aa95b7da8 100644 --- a/fs/f2fs/data.c +++ b/fs/f2fs/data.c @@ -4853,8 +4853,4 @@ static int f2fs_iomap_begin(struct inode *inode, loff_t offset, loff_t length, return 0; } -static DEFINE_IOMAP_ITER_NEXT(f2fs_iomap_next, f2fs_iomap_begin); - -const struct iomap_ops f2fs_iomap_ops = { - .iomap_next = f2fs_iomap_next, -}; +DEFINE_IOMAP_ITER_NEXT(f2fs_iomap_next, f2fs_iomap_begin); diff --git a/fs/f2fs/f2fs.h b/fs/f2fs/f2fs.h index f7423b3f6e4a..6941891d7cae 100644 --- a/fs/f2fs/f2fs.h +++ b/fs/f2fs/f2fs.h @@ -25,6 +25,7 @@ #include <linux/quotaops.h> #include <linux/part_stat.h> #include <linux/rw_hint.h> +#include <linux/iomap.h> #include <linux/fscrypt.h> #include <linux/fsverity.h> @@ -4397,7 +4398,7 @@ int f2fs_init_post_read_processing(void); void f2fs_destroy_post_read_processing(void); int f2fs_init_wq(struct f2fs_sb_info *sbi); void f2fs_destroy_wq(struct f2fs_sb_info *sbi); -extern const struct iomap_ops f2fs_iomap_ops; +DECLARE_IOMAP_ITER_NEXT(f2fs_iomap_next); /* * gc.c diff --git a/fs/f2fs/file.c b/fs/f2fs/file.c index e2c0f5083313..cf095978fad4 100644 --- a/fs/f2fs/file.c +++ b/fs/f2fs/file.c @@ -5245,7 +5245,7 @@ static ssize_t f2fs_dio_read_iter(struct kiocb *iocb, struct iov_iter *to) * F2FS_DIO_READ counter will be decremented correctly in all cases. */ inc_cache_count(sbi, F2FS_DIO_READ); - dio = __iomap_dio_rw(iocb, to, &f2fs_iomap_ops, + dio = __iomap_dio_rw(iocb, to, f2fs_iomap_next, &f2fs_iomap_dio_read_ops, 0, NULL, 0); if (IS_ERR_OR_NULL(dio)) { ret = PTR_ERR_OR_ZERO(dio); @@ -5584,7 +5584,7 @@ static ssize_t f2fs_dio_write_iter(struct kiocb *iocb, struct iov_iter *from, dio_flags = 0; if (pos + count > inode->i_size) dio_flags |= IOMAP_DIO_FORCE_WAIT; - dio = __iomap_dio_rw(iocb, from, &f2fs_iomap_ops, + dio = __iomap_dio_rw(iocb, from, f2fs_iomap_next, &f2fs_iomap_dio_write_ops, dio_flags, iocb, 0); if (IS_ERR_OR_NULL(dio)) { ret = PTR_ERR_OR_ZERO(dio); diff --git a/fs/fat/inode.c b/fs/fat/inode.c index 353c91f0a843..642e690632d8 100644 --- a/fs/fat/inode.c +++ b/fs/fat/inode.c @@ -695,7 +695,6 @@ static void fat_evict_inode(struct inode *inode) inode->i_size = 0; fat_truncate_blocks(inode, 0); } else { - mmb_sync(&MSDOS_I(inode)->i_metadata_bhs); fat_free_eofblocks(inode); } diff --git a/fs/file.c b/fs/file.c index 4cd40dfa6129..fd08d34874ac 100644 --- a/fs/file.c +++ b/fs/file.c @@ -1387,14 +1387,18 @@ static inline bool file_needs_f_pos_lock(struct file *file) bool file_seek_cur_needs_f_lock(struct file *file) { - if (!(file->f_mode & FMODE_ATOMIC_POS) && !file->f_op->iterate_shared) - return false; - /* + * Files that go through f_pos_lock when they are shared, i.e. + * FMODE_ATOMIC_POS files and directories, don't need f_lock for a + * SEEK_CUR. Everything else does, since nothing else serializes + * the f_pos update. + * * Note that we are not guaranteed to be called after fdget_pos() on * this file obj, in which case the caller is expected to provide the * appropriate locking. */ + if ((file->f_mode & FMODE_ATOMIC_POS) || file->f_op->iterate_shared) + return false; return true; } diff --git a/fs/fuse/args.h b/fs/fuse/args.h index 5173264a1261..36ef0c6d5999 100644 --- a/fs/fuse/args.h +++ b/fs/fuse/args.h @@ -36,7 +36,6 @@ struct fuse_args { bool user_pages:1; bool out_argvar:1; bool page_zeroing:1; - bool page_replace:1; bool may_block:1; bool is_ext:1; bool is_pinned:1; diff --git a/fs/fuse/dax.c b/fs/fuse/dax.c index cae217ff89ba..e20a5ae6fecc 100644 --- a/fs/fuse/dax.c +++ b/fs/fuse/dax.c @@ -656,10 +656,6 @@ static int fuse_iomap_end(struct inode *inode, loff_t pos, loff_t length, static DEFINE_IOMAP_ITER_NEXT_END(fuse_iomap_next, fuse_iomap_begin, fuse_iomap_end); -static const struct iomap_ops fuse_iomap_ops = { - .iomap_next = fuse_iomap_next, -}; - static void fuse_wait_dax_page(struct inode *inode) { filemap_invalidate_unlock(inode->i_mapping); @@ -687,7 +683,7 @@ ssize_t fuse_vdax_read_iter(struct kiocb *iocb, struct iov_iter *to) inode_lock_shared(inode); } - ret = dax_iomap_rw(iocb, to, &fuse_iomap_ops); + ret = dax_iomap_rw(iocb, to, fuse_iomap_next); inode_unlock_shared(inode); /* TODO file_accessed(iocb->f_filp) */ @@ -742,7 +738,7 @@ ssize_t fuse_vdax_write_iter(struct kiocb *iocb, struct iov_iter *from) if (file_extending_write(iocb, from)) ret = fuse_dax_direct_write(iocb, from); else - ret = dax_iomap_rw(iocb, from, &fuse_iomap_ops); + ret = dax_iomap_rw(iocb, from, fuse_iomap_next); out: inode_unlock(inode); @@ -777,7 +773,7 @@ retry: * to populate page cache or access memory we are trying to free. */ filemap_invalidate_lock_shared(inode->i_mapping); - ret = dax_iomap_fault(vmf, order, &pfn, &error, &fuse_iomap_ops); + ret = dax_iomap_fault(vmf, order, &pfn, &error, fuse_iomap_next); if ((ret & VM_FAULT_ERROR) && error == -EAGAIN) { error = 0; retry = true; diff --git a/fs/fuse/dev.c b/fs/fuse/dev.c index 3641abb90d6b..9b23ebc5702c 100644 --- a/fs/fuse/dev.c +++ b/fs/fuse/dev.c @@ -1099,128 +1099,6 @@ static int fuse_copy_do(struct fuse_copy_state *cs, void **val, unsigned *size) return ncpy; } -static int fuse_check_folio(struct folio *folio) -{ - if (folio_mapped(folio) || - folio->mapping != NULL || - (folio->flags.f & PAGE_FLAGS_CHECK_AT_PREP & - ~(1 << PG_locked | - 1 << PG_referenced | - 1 << PG_lru | - 1 << PG_active | - 1 << PG_workingset | - 1 << PG_reclaim | - 1 << PG_waiters | - LRU_GEN_MASK | LRU_REFS_MASK))) { - dump_page(&folio->page, "fuse: trying to steal weird page"); - return 1; - } - return 0; -} - -/* - * Attempt to steal a page from the splice() pipe and move it into the - * pagecache. If successful, the pointer in @pagep will be updated. The - * folio that was originally in @pagep will lose a reference and the new - * folio returned in @pagep will carry a reference. - */ -static int fuse_try_move_folio(struct fuse_copy_state *cs, struct folio **foliop) -{ - int err; - struct folio *oldfolio = *foliop; - struct folio *newfolio; - struct pipe_buffer *buf = cs->pipebufs; - - folio_get(oldfolio); - err = unlock_request(cs->req); - if (err) - goto out_put_old; - - fuse_copy_finish(cs); - - err = pipe_buf_confirm(cs->pipe, buf); - if (err) - goto out_put_old; - - BUG_ON(!cs->nr_segs); - cs->currbuf = buf; - cs->len = buf->len; - cs->pipebufs++; - cs->nr_segs--; - - if (cs->len != folio_size(oldfolio)) - goto out_fallback; - - newfolio = page_folio(buf->page); - - if (folio_test_large(newfolio)) - goto out_fallback; - - /* - * This is a new and locked page, it shouldn't be mapped or - * have any special flags on it - */ - if (WARN_ON(folio_mapped(oldfolio))) - goto out_fallback; - if (WARN_ON(folio_has_private(oldfolio))) - goto out_fallback; - if (WARN_ON(folio_test_dirty(oldfolio) || - folio_test_writeback(oldfolio))) - goto out_fallback; - if (WARN_ON(folio_test_mlocked(oldfolio))) - goto out_fallback; - - if (!pipe_buf_try_steal(cs->pipe, buf)) - goto out_fallback; - - folio_clear_uptodate(newfolio); - folio_clear_mappedtodisk(newfolio); - - if (fuse_check_folio(newfolio) != 0) - goto out_fallback_unlock; - - err = lock_request(cs->req); - if (err) - goto out_fallback_unlock; - - replace_page_cache_folio(oldfolio, newfolio); - - folio_get(newfolio); - - if (!(buf->flags & PIPE_BUF_FLAG_LRU)) - folio_add_lru(newfolio); - - /* - * Release while we have extra ref on stolen page. Otherwise - * anon_pipe_buf_release() might think the page can be reused. - */ - pipe_buf_release(cs->pipe, buf); - - *foliop = newfolio; - folio_unlock(oldfolio); - /* Drop ref for ap->pages[] array */ - folio_put(oldfolio); - cs->len = 0; - - err = 0; -out_put_old: - /* Drop ref obtained in this function */ - folio_put(oldfolio); - return err; - -out_fallback_unlock: - folio_unlock(newfolio); -out_fallback: - cs->pg = buf->page; - cs->offset = buf->offset; - - err = lock_request(cs->req); - if (!err) - err = 1; - - goto out_put_old; -} - static int fuse_ref_folio(struct fuse_copy_state *cs, struct folio *folio, unsigned offset, unsigned count) { @@ -1230,7 +1108,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); @@ -1275,16 +1155,9 @@ int fuse_copy_folio(struct fuse_copy_state *cs, struct folio **foliop, return fuse_ref_folio(cs, folio, offset, count); } } else if (!cs->len) { - if (cs->move_folios && folio && - offset == 0 && count == folio_size(folio)) { - err = fuse_try_move_folio(cs, foliop); - if (err <= 0) - return err; - } else { - err = fuse_copy_fill(cs); - if (err) - return err; - } + err = fuse_copy_fill(cs); + if (err) + return err; } if (folio) { void *mapaddr = kmap_local_folio(folio, offset); @@ -1756,7 +1629,7 @@ static ssize_t fuse_dev_splice_read(struct file *in, loff_t *ppos, * Need to be careful about this. Having buf->ops in module * code can Oops if the buffer persists after module unload. */ - bufs[page_nr].ops = &nosteal_pipe_buf_ops; + bufs[page_nr].ops = &default_pipe_buf_ops; bufs[page_nr].flags = 0; ret = add_to_pipe(pipe, &bufs[page_nr++]); if (unlikely(ret < 0)) @@ -1920,9 +1793,6 @@ static ssize_t fuse_dev_do_write(struct fuse_dev *fud, if (!smp_load_acquire(&fch->initialized) || !fch->connected) goto copy_finish; - /* Don't try to move folios (yet) */ - cs->move_folios = false; - err = fuse_notify(fch->conn, oh.error, nbytes - sizeof(oh), cs); goto copy_finish; } @@ -1966,8 +1836,6 @@ static ssize_t fuse_dev_do_write(struct fuse_dev *fud, set_bit(FR_LOCKED, &req->flags); spin_unlock(&fpq->lock); cs->req = req; - if (!req->args->page_replace) - cs->move_folios = false; if (oh.error) err = nbytes != sizeof(oh) ? -EINVAL : 0; @@ -2068,7 +1936,6 @@ static ssize_t fuse_dev_splice_write(struct pipe_inode_info *pipe, goto out_free; *obuf = *ibuf; - obuf->flags &= ~PIPE_BUF_FLAG_GIFT; obuf->len = rem; ibuf->offset += obuf->len; ibuf->len -= obuf->len; @@ -2083,9 +1950,6 @@ static ssize_t fuse_dev_splice_write(struct pipe_inode_info *pipe, cs.nr_segs = nbuf; cs.pipe = pipe; - if (flags & SPLICE_F_MOVE) - cs.move_folios = true; - ret = fuse_dev_do_write(fud, &cs, len); pipe_lock(pipe); diff --git a/fs/fuse/ext_map.c b/fs/fuse/ext_map.c index 746cb679c1b8..9b605ecdab5e 100644 --- a/fs/fuse/ext_map.c +++ b/fs/fuse/ext_map.c @@ -210,9 +210,8 @@ static int fuse_ext_map_iomap_begin(struct inode *inode, loff_t offset, loff_t l return 0; } -static const struct iomap_ops fuse_ext_map_iomap_ops = { - .iomap_begin = fuse_ext_map_iomap_begin, -}; +static DEFINE_IOMAP_ITER_NEXT(fuse_ext_map_iomap_next, + fuse_ext_map_iomap_begin); static vm_fault_t fuse_ext_map_huge_fault(struct vm_fault *vmf, unsigned int order) { @@ -234,7 +233,7 @@ static vm_fault_t fuse_ext_map_huge_fault(struct vm_fault *vmf, unsigned int ord filemap_invalidate_lock_shared(inode->i_mapping); - ret = dax_iomap_fault(vmf, order, &pfn, NULL, &fuse_ext_map_iomap_ops); + ret = dax_iomap_fault(vmf, order, &pfn, NULL, fuse_ext_map_iomap_next); if (ret & VM_FAULT_NEEDDSYNC) ret = dax_finish_sync_fault(vmf, order, pfn); @@ -283,7 +282,7 @@ ssize_t fuse_ext_map_read_iter(struct kiocb *iocb, struct iov_iter *to) if (!IS_ENABLED(CONFIG_FS_DAX)) return -EIO; - res = dax_iomap_rw(iocb, to, &fuse_ext_map_iomap_ops); + res = dax_iomap_rw(iocb, to, fuse_ext_map_iomap_next); file_accessed(iocb->ki_filp); return res; @@ -309,7 +308,7 @@ ssize_t fuse_ext_map_write_iter(struct kiocb *iocb, struct iov_iter *from) if (!IS_ENABLED(CONFIG_FS_DAX)) return -EIO; - return dax_iomap_rw(iocb, from, &fuse_ext_map_iomap_ops); + return dax_iomap_rw(iocb, from, fuse_ext_map_iomap_next); } int fuse_ext_map_mmap(struct file *file, struct vm_area_struct *vma) diff --git a/fs/fuse/file.c b/fs/fuse/file.c index d5e1cb53d86a..1dc517edfac8 100644 --- a/fs/fuse/file.c +++ b/fs/fuse/file.c @@ -923,10 +923,6 @@ static int fuse_iomap_begin(struct inode *inode, loff_t offset, loff_t length, static DEFINE_IOMAP_ITER_NEXT(fuse_iomap_next, fuse_iomap_begin); -static const struct iomap_ops fuse_iomap_ops = { - .iomap_next = fuse_iomap_next, -}; - struct fuse_fill_read_data { struct file *file; @@ -1036,7 +1032,7 @@ static int fuse_read_folio(struct file *file, struct folio *folio) return -EIO; } - iomap_read_folio(&fuse_iomap_ops, &ctx, NULL); + iomap_read_folio(fuse_iomap_next, &ctx, NULL); fuse_invalidate_atime(inode); return 0; } @@ -1096,7 +1092,6 @@ static void fuse_send_readpages(struct fuse_io_args *ia, struct file *file, ap->args.out_pages = true; ap->args.page_zeroing = true; - ap->args.page_replace = true; /* * Don't overflow end offset. @@ -1146,7 +1141,7 @@ static void fuse_readahead(struct readahead_control *rac) if (fuse_is_bad(inode)) return; - iomap_readahead(&fuse_iomap_ops, &ctx, NULL); + iomap_readahead(fuse_iomap_next, &ctx, NULL); if (data.ia) fuse_send_readpages(data.ia, data.file, data.nr_bytes, fc->async_read); @@ -1570,7 +1565,7 @@ static ssize_t fuse_cache_write_iter(struct kiocb *iocb, struct iov_iter *from) * and granular dirty tracking for large folios. */ written = iomap_file_buffered_write(iocb, from, - &fuse_iomap_ops, + fuse_iomap_next, &fuse_iomap_write_ops, file); } else { diff --git a/fs/fuse/fuse_dev_i.h b/fs/fuse/fuse_dev_i.h index 4b412a76225f..a90ce26ded31 100644 --- a/fs/fuse/fuse_dev_i.h +++ b/fs/fuse/fuse_dev_i.h @@ -326,7 +326,6 @@ struct fuse_copy_state { unsigned int len; unsigned int offset; bool write:1; - bool move_folios:1; bool is_uring:1; /* set when the payload is zero-copied. folios are filled in place */ bool skip_folio_copy:1; diff --git a/fs/fuse/virtio_fs.c b/fs/fuse/virtio_fs.c index e44539832a5c..ff872c7c0762 100644 --- a/fs/fuse/virtio_fs.c +++ b/fs/fuse/virtio_fs.c @@ -1053,7 +1053,8 @@ static void virtio_fs_cleanup_vqs(struct virtio_device *vdev) } /* Map a window offset to a page frame number. The window offset will have - * been produced by .iomap_next(), which maps a file offset to a window offset. + * been produced by fuse_iomap_next(), which maps a file offset to a window + * offset. */ static long virtio_fs_direct_access(struct dax_device *dax_dev, pgoff_t pgoff, long nr_pages, enum dax_access_mode mode, diff --git a/fs/gfs2/aops.c b/fs/gfs2/aops.c index ee11d494e47c..d31615f49754 100644 --- a/fs/gfs2/aops.c +++ b/fs/gfs2/aops.c @@ -425,7 +425,7 @@ static int gfs2_read_folio(struct file *file, struct folio *folio) if (!gfs2_is_jdata(ip) || (i_blocksize(inode) == PAGE_SIZE && !folio_buffers(folio))) { - iomap_bio_read_folio(folio, &gfs2_iomap_ops); + iomap_bio_read_folio(folio, gfs2_iomap_next); } else if (gfs2_is_stuffed(ip)) { error = stuffed_read_folio(ip, folio); } else { @@ -500,7 +500,7 @@ static void gfs2_readahead(struct readahead_control *rac) else if (gfs2_is_jdata(ip)) mpage_readahead(rac, gfs2_block_map); else - iomap_bio_readahead(rac, &gfs2_iomap_ops); + iomap_bio_readahead(rac, gfs2_iomap_next); } /** @@ -572,7 +572,7 @@ static sector_t gfs2_bmap(struct address_space *mapping, sector_t lblock) return 0; if (!gfs2_is_stuffed(ip)) - dblock = iomap_bmap(mapping, lblock, &gfs2_iomap_ops); + dblock = iomap_bmap(mapping, lblock, gfs2_iomap_next); gfs2_glock_dq_uninit(&i_gh); diff --git a/fs/gfs2/bmap.c b/fs/gfs2/bmap.c index 264170f91c5d..09884f698d91 100644 --- a/fs/gfs2/bmap.c +++ b/fs/gfs2/bmap.c @@ -1205,12 +1205,7 @@ static int gfs2_iomap_end(struct inode *inode, loff_t pos, loff_t length, return 0; } -static DEFINE_IOMAP_ITER_NEXT_END(gfs2_iomap_next, gfs2_iomap_begin, - gfs2_iomap_end); - -const struct iomap_ops gfs2_iomap_ops = { - .iomap_next = gfs2_iomap_next, -}; +DEFINE_IOMAP_ITER_NEXT_END(gfs2_iomap_next, gfs2_iomap_begin, gfs2_iomap_end); /** * gfs2_block_map - Map one or more blocks of an inode to a disk block @@ -1325,7 +1320,7 @@ static int gfs2_block_zero_range(struct inode *inode, loff_t from, loff_t length if (from >= inode->i_size) return 0; length = min(length, inode->i_size - from); - return iomap_zero_range(inode, from, length, NULL, &gfs2_iomap_ops, + return iomap_zero_range(inode, from, length, NULL, gfs2_iomap_next, &gfs2_iomap_write_ops, NULL); } diff --git a/fs/gfs2/bmap.h b/fs/gfs2/bmap.h index e3d6efdfd890..cceb47950b7b 100644 --- a/fs/gfs2/bmap.h +++ b/fs/gfs2/bmap.h @@ -43,7 +43,7 @@ static inline void gfs2_write_calc_reserv(const struct gfs2_inode *ip, } } -extern const struct iomap_ops gfs2_iomap_ops; +DECLARE_IOMAP_ITER_NEXT(gfs2_iomap_next); extern const struct iomap_write_ops gfs2_iomap_write_ops; extern const struct iomap_writeback_ops gfs2_writeback_ops; diff --git a/fs/gfs2/file.c b/fs/gfs2/file.c index 1efd0679badd..cea24d5de91c 100644 --- a/fs/gfs2/file.c +++ b/fs/gfs2/file.c @@ -851,7 +851,7 @@ retry: goto out_uninit; pagefault_disable(); to->nofault = true; - ret = iomap_dio_rw(iocb, to, &gfs2_iomap_ops, NULL, + ret = iomap_dio_rw(iocb, to, gfs2_iomap_next, NULL, IOMAP_DIO_PARTIAL, NULL, read); to->nofault = false; pagefault_enable(); @@ -917,7 +917,7 @@ retry: goto out_unlock; from->nofault = true; - ret = iomap_dio_rw(iocb, from, &gfs2_iomap_ops, NULL, + ret = iomap_dio_rw(iocb, from, gfs2_iomap_next, NULL, IOMAP_DIO_PARTIAL, NULL, written); from->nofault = false; if (ret <= 0) { @@ -1069,7 +1069,7 @@ retry: goto out_unlock; pagefault_disable(); - ret = iomap_file_buffered_write(iocb, from, &gfs2_iomap_ops, + ret = iomap_file_buffered_write(iocb, from, gfs2_iomap_next, &gfs2_iomap_write_ops, NULL); pagefault_enable(); if (ret > 0) diff --git a/fs/gfs2/inode.c b/fs/gfs2/inode.c index 2c2dc459c037..75fb1a0c9142 100644 --- a/fs/gfs2/inode.c +++ b/fs/gfs2/inode.c @@ -2229,7 +2229,7 @@ retry: goto out; pagefault_disable(); - ret = iomap_fiemap(inode, fieinfo, start, len, &gfs2_iomap_ops); + ret = iomap_fiemap(inode, fieinfo, start, len, gfs2_iomap_next); pagefault_enable(); gfs2_glock_dq_uninit(&gh); @@ -2254,7 +2254,7 @@ loff_t gfs2_seek_data(struct file *file, loff_t offset) inode_lock_shared(inode); ret = gfs2_glock_nq_init(gl, LM_ST_SHARED, 0, &gh); if (!ret) - ret = iomap_seek_data(inode, offset, &gfs2_iomap_ops); + ret = iomap_seek_data(inode, offset, gfs2_iomap_next); gfs2_glock_dq_uninit(&gh); inode_unlock_shared(inode); @@ -2273,7 +2273,7 @@ loff_t gfs2_seek_hole(struct file *file, loff_t offset) inode_lock_shared(inode); ret = gfs2_glock_nq_init(gl, LM_ST_SHARED, 0, &gh); if (!ret) - ret = iomap_seek_hole(inode, offset, &gfs2_iomap_ops); + ret = iomap_seek_hole(inode, offset, gfs2_iomap_next); gfs2_glock_dq_uninit(&gh); inode_unlock_shared(inode); diff --git a/fs/hpfs/file.c b/fs/hpfs/file.c index 6a629ab956fc..ef7eb601be09 100644 --- a/fs/hpfs/file.c +++ b/fs/hpfs/file.c @@ -158,10 +158,6 @@ static int hpfs_iomap_begin(struct inode *inode, loff_t offset, loff_t length, static DEFINE_IOMAP_ITER_NEXT(hpfs_iomap_next, hpfs_iomap_begin); -static const struct iomap_ops hpfs_iomap_ops = { - .iomap_next = hpfs_iomap_next, -}; - static int hpfs_read_folio(struct file *file, struct folio *folio) { return mpage_read_folio(folio, hpfs_get_block); @@ -238,7 +234,7 @@ static int hpfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo, inode_lock(inode); len = min_t(u64, len, i_size_read(inode)); - ret = iomap_fiemap(inode, fieinfo, start, len, &hpfs_iomap_ops); + ret = iomap_fiemap(inode, fieinfo, start, len, hpfs_iomap_next); inode_unlock(inode); return ret; diff --git a/fs/inode.c b/fs/inode.c index f63535ee3629..de207f2f95a9 100644 --- a/fs/inode.c +++ b/fs/inode.c @@ -817,6 +817,14 @@ static void evict(struct inode *inode) inode_wait_for_writeback(inode); spin_unlock(&inode->i_lock); + /* + * fsync() can't find what I_METADATA_WRITEBACK tracks anymore once the + * inode is gone, so write it out unless the inode is being deleted. + */ + if (inode->i_nlink && + (inode_state_read_once(inode) & I_METADATA_WRITEBACK)) + sync_inode_metadata(inode, 1); + if (op->evict_inode) { op->evict_inode(inode); } else { @@ -952,9 +960,12 @@ static enum lru_status inode_lru_isolate(struct list_head *item, * they're already on the LRU, and this can make them * unreclaimable for a while. Remove them lazily here; iput, * sync, or the last page cache deletion will requeue them. + * Nothing requeues them for I_METADATA_WRITEBACK, evict() writes + * that out instead. */ if (icount_read(inode) || - (inode_state_read(inode) & ~I_REFERENCED) || + (inode_state_read(inode) & + ~(I_REFERENCED | I_METADATA_WRITEBACK)) || !mapping_shrinkable(&inode->i_data)) { list_lru_isolate(lru, &inode->i_lru); spin_unlock(&inode->i_lock); @@ -2858,9 +2869,10 @@ struct timespec64 timestamp_truncate(struct timespec64 t, struct inode *inode) { struct super_block *sb = inode->i_sb; unsigned int gran = sb->s_time_gran; + time64_t seconds = t.tv_sec; t.tv_sec = clamp(t.tv_sec, sb->s_time_min, sb->s_time_max); - if (unlikely(t.tv_sec == sb->s_time_max || t.tv_sec == sb->s_time_min)) + if (unlikely(t.tv_sec != seconds)) t.tv_nsec = 0; /* Avoid division in the common cases 1 ns and 1 s. */ diff --git a/fs/internal.h b/fs/internal.h index 967c8556c17f..3f2fbac40f8e 100644 --- a/fs/internal.h +++ b/fs/internal.h @@ -8,7 +8,6 @@ struct super_block; struct file_system_type; struct iomap; -struct iomap_ops; struct linux_binprm; struct path; struct mount; diff --git a/fs/ioctl.c b/fs/ioctl.c index 1c152c2b1b67..ecc2a4cfe610 100644 --- a/fs/ioctl.c +++ b/fs/ioctl.c @@ -7,6 +7,7 @@ #include <linux/syscalls.h> #include <linux/mm.h> +#include <linux/minmax.h> #include <linux/capability.h> #include <linux/compat.h> #include <linux/file.h> @@ -550,8 +551,8 @@ static int do_vfs_ioctl(struct file *filp, unsigned int fd, if (!S_ISREG(inode->i_mode) || IS_ANON_FILE(inode)) return vfs_ioctl(filp, cmd, arg); - return put_user(i_size_read(inode) - filp->f_pos, - (int __user *)argp); + return put_user(clamp_t(loff_t, i_size_read(inode) - filp->f_pos, + INT_MIN, INT_MAX), (int __user *)argp); case FS_IOC_GETFLAGS: return ioctl_getflags(filp, argp); diff --git a/fs/iomap/buffered-io.c b/fs/iomap/buffered-io.c index d6e2f1ded5ca..6d843b168d5f 100644 --- a/fs/iomap/buffered-io.c +++ b/fs/iomap/buffered-io.c @@ -648,8 +648,8 @@ static int iomap_read_folio_iter(struct iomap_iter *iter, return 0; } -void iomap_read_folio(const struct iomap_ops *ops, - struct iomap_read_folio_ctx *ctx, void *private) +void iomap_read_folio(iomap_iter_next_fn next, struct iomap_read_folio_ctx *ctx, + void *private) { struct folio *folio = ctx->cur_folio; struct iomap_iter iter = { @@ -672,7 +672,7 @@ void iomap_read_folio(const struct iomap_ops *ops, fsverity_readahead(ctx->vi, folio->index, folio_nr_pages(folio)); - while ((ret = iomap_iter(&iter, ops)) > 0) { + while ((ret = iomap_iter(&iter, next)) > 0) { iter.status = iomap_read_folio_iter(&iter, ctx, &bytes_submitted); if (ctx->read_ctx && ctx->ops->submit_read) @@ -711,22 +711,22 @@ static int iomap_readahead_iter(struct iomap_iter *iter, /** * iomap_readahead - Attempt to read pages from a file. - * @ops: The operations vector for the filesystem. + * @next: The iomap iteration function for the filesystem. * @ctx: The ctx used for issuing readahead. * @private: The filesystem-specific information for issuing iomap_iter. * * This function is for filesystems to call to implement their readahead * address_space operation. * - * Context: The @ops callbacks may submit I/O (eg to read the addresses of + * Context: The @next callback may submit I/O (eg to read the addresses of * blocks from disc), and may wait for it. The caller may be trying to * access a different page, and so sleeping excessively should be avoided. * It may allocate memory, but should avoid costly allocations. This * function is called with memalloc_nofs set, so allocations will not cause * the filesystem to be reentered. */ -void iomap_readahead(const struct iomap_ops *ops, - struct iomap_read_folio_ctx *ctx, void *private) +void iomap_readahead(iomap_iter_next_fn next, struct iomap_read_folio_ctx *ctx, + void *private) { struct readahead_control *rac = ctx->rac; struct iomap_iter iter = { @@ -748,7 +748,7 @@ void iomap_readahead(const struct iomap_ops *ops, fsverity_readahead(ctx->vi, readahead_index(rac), readahead_count(rac)); - while (iomap_iter(&iter, ops) > 0) { + while (iomap_iter(&iter, next) > 0) { iter.status = iomap_readahead_iter(&iter, ctx, &cur_bytes_submitted); if (ctx->read_ctx && ctx->ops->submit_read) @@ -1293,7 +1293,7 @@ retry: ssize_t iomap_file_buffered_write(struct kiocb *iocb, struct iov_iter *i, - const struct iomap_ops *ops, + iomap_iter_next_fn next, const struct iomap_write_ops *write_ops, void *private) { struct iomap_iter iter = { @@ -1314,7 +1314,7 @@ iomap_file_buffered_write(struct kiocb *iocb, struct iov_iter *i, if (iocb->ki_flags & IOCB_DONTCACHE) iter.flags |= IOMAP_DONTCACHE; - while ((ret = iomap_iter(&iter, ops)) > 0) + while ((ret = iomap_iter(&iter, next)) > 0) iter.status = iomap_write_iter(&iter, i, write_ops); if (unlikely(iter.pos == iocb->ki_pos)) @@ -1326,7 +1326,7 @@ iomap_file_buffered_write(struct kiocb *iocb, struct iov_iter *i, EXPORT_SYMBOL_GPL(iomap_file_buffered_write); int iomap_fsverity_write(struct file *file, loff_t pos, size_t length, - const void *buf, const struct iomap_ops *ops, + const void *buf, iomap_iter_next_fn next, const struct iomap_write_ops *write_ops) { int ret; @@ -1343,7 +1343,7 @@ int iomap_fsverity_write(struct file *file, loff_t pos, size_t length, iov_iter_kvec(&iiter, WRITE, &kvec, 1, length); - ret = iomap_file_buffered_write(&iocb, &iiter, ops, write_ops, NULL); + ret = iomap_file_buffered_write(&iocb, &iiter, next, write_ops, NULL); if (ret < 0) return ret; return ret == length ? 0 : -EIO; @@ -1615,7 +1615,7 @@ static int iomap_unshare_iter(struct iomap_iter *iter, int iomap_file_unshare(struct inode *inode, loff_t pos, loff_t len, - const struct iomap_ops *ops, + iomap_iter_next_fn next, const struct iomap_write_ops *write_ops) { struct iomap_iter iter = { @@ -1630,7 +1630,7 @@ iomap_file_unshare(struct inode *inode, loff_t pos, loff_t len, return 0; iter.len = min(len, size - pos); - while ((ret = iomap_iter(&iter, ops)) > 0) + while ((ret = iomap_iter(&iter, next)) > 0) iter.status = iomap_unshare_iter(&iter, write_ops); return ret; } @@ -1743,7 +1743,7 @@ EXPORT_SYMBOL_GPL(iomap_fill_dirty_folios); int iomap_zero_range(struct inode *inode, loff_t pos, loff_t len, bool *did_zero, - const struct iomap_ops *ops, + iomap_iter_next_fn next, const struct iomap_write_ops *write_ops, void *private) { struct folio_batch fbatch; @@ -1768,7 +1768,7 @@ iomap_zero_range(struct inode *inode, loff_t pos, loff_t len, bool *did_zero, */ range_dirty = filemap_range_needs_writeback(mapping, iter.pos, iter.pos + iter.len - 1); - while ((ret = iomap_iter(&iter, ops)) > 0) { + while ((ret = iomap_iter(&iter, next)) > 0) { const struct iomap *srcmap = iomap_iter_srcmap(&iter); if (!(iter.iomap.flags & IOMAP_F_FOLIO_BATCH) && @@ -1794,7 +1794,7 @@ EXPORT_SYMBOL_GPL(iomap_zero_range); int iomap_truncate_page(struct inode *inode, loff_t pos, bool *did_zero, - const struct iomap_ops *ops, + iomap_iter_next_fn next, const struct iomap_write_ops *write_ops, void *private) { unsigned int blocksize = i_blocksize(inode); @@ -1803,7 +1803,7 @@ iomap_truncate_page(struct inode *inode, loff_t pos, bool *did_zero, /* Block boundary? Nothing to do */ if (!off) return 0; - return iomap_zero_range(inode, pos, blocksize - off, did_zero, ops, + return iomap_zero_range(inode, pos, blocksize - off, did_zero, next, write_ops, private); } EXPORT_SYMBOL_GPL(iomap_truncate_page); @@ -1828,7 +1828,7 @@ static int iomap_folio_mkwrite_iter(struct iomap_iter *iter, return iomap_iter_advance(iter, length); } -vm_fault_t iomap_page_mkwrite(struct vm_fault *vmf, const struct iomap_ops *ops, +vm_fault_t iomap_page_mkwrite(struct vm_fault *vmf, iomap_iter_next_fn next, void *private) { struct iomap_iter iter = { @@ -1845,7 +1845,7 @@ vm_fault_t iomap_page_mkwrite(struct vm_fault *vmf, const struct iomap_ops *ops, goto out_unlock; iter.pos = folio_pos(folio); iter.len = ret; - while ((ret = iomap_iter(&iter, ops)) > 0) + while ((ret = iomap_iter(&iter, next)) > 0) iter.status = iomap_folio_mkwrite_iter(&iter, folio); if (ret < 0) diff --git a/fs/iomap/direct-io.c b/fs/iomap/direct-io.c index ad041ac3252a..f00b0841fdd0 100644 --- a/fs/iomap/direct-io.c +++ b/fs/iomap/direct-io.c @@ -695,7 +695,7 @@ static int iomap_dio_iter(struct iomap_iter *iter, struct iomap_dio *dio) */ struct iomap_dio * __iomap_dio_rw(struct kiocb *iocb, struct iov_iter *iter, - const struct iomap_ops *ops, const struct iomap_dio_ops *dops, + iomap_iter_next_fn next, const struct iomap_dio_ops *dops, unsigned int dio_flags, void *private, size_t done_before) { struct inode *inode = file_inode(iocb->ki_filp); @@ -819,7 +819,7 @@ __iomap_dio_rw(struct kiocb *iocb, struct iov_iter *iter, inode_dio_begin(inode); blk_start_plug(&plug); - while ((ret = iomap_iter(&iomi, ops)) > 0) { + while ((ret = iomap_iter(&iomi, next)) > 0) { iomi.status = iomap_dio_iter(&iomi, dio); /* @@ -909,12 +909,12 @@ EXPORT_SYMBOL_GPL(__iomap_dio_rw); ssize_t iomap_dio_rw(struct kiocb *iocb, struct iov_iter *iter, - const struct iomap_ops *ops, const struct iomap_dio_ops *dops, + iomap_iter_next_fn next, const struct iomap_dio_ops *dops, unsigned int dio_flags, void *private, size_t done_before) { struct iomap_dio *dio; - dio = __iomap_dio_rw(iocb, iter, ops, dops, dio_flags, private, + dio = __iomap_dio_rw(iocb, iter, next, dops, dio_flags, private, done_before); if (IS_ERR_OR_NULL(dio)) return PTR_ERR_OR_ZERO(dio); diff --git a/fs/iomap/fiemap.c b/fs/iomap/fiemap.c index 54b824b7edb5..a9e33c7af910 100644 --- a/fs/iomap/fiemap.c +++ b/fs/iomap/fiemap.c @@ -56,7 +56,7 @@ advance: } int iomap_fiemap(struct inode *inode, struct fiemap_extent_info *fi, - u64 start, u64 len, const struct iomap_ops *ops) + u64 start, u64 len, iomap_iter_next_fn next) { struct iomap_iter iter = { .inode = inode, @@ -73,7 +73,7 @@ int iomap_fiemap(struct inode *inode, struct fiemap_extent_info *fi, if (ret) return ret; - while ((ret = iomap_iter(&iter, ops)) > 0) + while ((ret = iomap_iter(&iter, next)) > 0) iter.status = iomap_fiemap_iter(&iter, fi, &prev); /* inode with no (attribute) mapping will give ENOENT */ @@ -92,7 +92,7 @@ EXPORT_SYMBOL_GPL(iomap_fiemap); /* legacy ->bmap interface. 0 is the error return (!) */ sector_t iomap_bmap(struct address_space *mapping, sector_t bno, - const struct iomap_ops *ops) + iomap_iter_next_fn next) { struct iomap_iter iter = { .inode = mapping->host, @@ -107,7 +107,7 @@ iomap_bmap(struct address_space *mapping, sector_t bno, return 0; bno = 0; - while ((ret = iomap_iter(&iter, ops)) > 0) { + while ((ret = iomap_iter(&iter, next)) > 0) { if (iter.iomap.type == IOMAP_MAPPED) bno = iomap_sector(&iter.iomap, iter.pos) >> blkshift; /* leave iter.status unset to abort loop */ diff --git a/fs/iomap/iter.c b/fs/iomap/iter.c index fd8791c4963b..771b60fd1022 100644 --- a/fs/iomap/iter.c +++ b/fs/iomap/iter.c @@ -101,7 +101,7 @@ EXPORT_SYMBOL_GPL(iomap_iter_continue); /** * iomap_iter - iterate over ranges in a file * @iter: iteration structure - * @ops: iomap ops provided by the filesystem + * @next: the iomap iteration function for the filesystem * * Iterate over filesystem-provided space mappings for the provided file range. * @@ -113,18 +113,13 @@ EXPORT_SYMBOL_GPL(iomap_iter_continue); * of the loop body: leave @iter.status unchanged, or set it to a negative * errno. */ -int iomap_iter(struct iomap_iter *iter, const struct iomap_ops *ops) +int iomap_iter(struct iomap_iter *iter, iomap_iter_next_fn next) { int ret; - trace_iomap_iter(iter, ops, _RET_IP_); - - if (ops->iomap_next) - ret = ops->iomap_next(iter, &iter->iomap, &iter->srcmap); - else - ret = iomap_iter_next(iter, &iter->iomap, &iter->srcmap, - ops->iomap_begin, ops->iomap_end); + trace_iomap_iter(iter, next, _RET_IP_); + ret = next(iter, &iter->iomap, &iter->srcmap); iter->status = 0; if (ret > 0) iomap_iter_done(iter); diff --git a/fs/iomap/seek.c b/fs/iomap/seek.c index 6cbc587c93da..6fd3173d25f5 100644 --- a/fs/iomap/seek.c +++ b/fs/iomap/seek.c @@ -27,7 +27,7 @@ static int iomap_seek_hole_iter(struct iomap_iter *iter, } loff_t -iomap_seek_hole(struct inode *inode, loff_t pos, const struct iomap_ops *ops) +iomap_seek_hole(struct inode *inode, loff_t pos, iomap_iter_next_fn next) { loff_t size = i_size_read(inode); struct iomap_iter iter = { @@ -42,7 +42,7 @@ iomap_seek_hole(struct inode *inode, loff_t pos, const struct iomap_ops *ops) return -ENXIO; iter.len = size - pos; - while ((ret = iomap_iter(&iter, ops)) > 0) + while ((ret = iomap_iter(&iter, next)) > 0) iter.status = iomap_seek_hole_iter(&iter, &pos); if (ret < 0) return ret; @@ -73,7 +73,7 @@ static int iomap_seek_data_iter(struct iomap_iter *iter, } loff_t -iomap_seek_data(struct inode *inode, loff_t pos, const struct iomap_ops *ops) +iomap_seek_data(struct inode *inode, loff_t pos, iomap_iter_next_fn next) { loff_t size = i_size_read(inode); struct iomap_iter iter = { @@ -88,7 +88,7 @@ iomap_seek_data(struct inode *inode, loff_t pos, const struct iomap_ops *ops) return -ENXIO; iter.len = size - pos; - while ((ret = iomap_iter(&iter, ops)) > 0) + while ((ret = iomap_iter(&iter, next)) > 0) iter.status = iomap_seek_data_iter(&iter, &pos); if (ret < 0) return ret; diff --git a/fs/iomap/swapfile.c b/fs/iomap/swapfile.c index 0db77c449467..c59f67a7de09 100644 --- a/fs/iomap/swapfile.c +++ b/fs/iomap/swapfile.c @@ -139,7 +139,7 @@ static int iomap_swapfile_iter(struct iomap_iter *iter, */ int iomap_swapfile_activate(struct swap_info_struct *sis, struct file *swap_file, sector_t *pagespan, - const struct iomap_ops *ops) + iomap_iter_next_fn next) { struct inode *inode = swap_file->f_mapping->host; struct iomap_iter iter = { @@ -163,7 +163,7 @@ int iomap_swapfile_activate(struct swap_info_struct *sis, if (ret) return ret; - while ((ret = iomap_iter(&iter, ops)) > 0) + while ((ret = iomap_iter(&iter, next)) > 0) iter.status = iomap_swapfile_iter(&iter, &iter.iomap, &isi); if (ret < 0) return ret; diff --git a/fs/iomap/trace.h b/fs/iomap/trace.h index e1ea8392cf47..d36a77b854aa 100644 --- a/fs/iomap/trace.h +++ b/fs/iomap/trace.h @@ -218,9 +218,9 @@ TRACE_EVENT(iomap_add_to_ioend, ); TRACE_EVENT(iomap_iter, - TP_PROTO(struct iomap_iter *iter, const void *ops, + TP_PROTO(struct iomap_iter *iter, const void *next, unsigned long caller), - TP_ARGS(iter, ops, caller), + TP_ARGS(iter, next, caller), TP_STRUCT__entry( __field(dev_t, dev) __field(u64, ino) @@ -228,7 +228,7 @@ TRACE_EVENT(iomap_iter, __field(u64, length) __field(int, status) __field(unsigned int, flags) - __field(const void *, ops) + __field(const void *, next) __field(unsigned long, caller) ), TP_fast_assign( @@ -238,10 +238,10 @@ TRACE_EVENT(iomap_iter, __entry->length = iomap_length(iter); __entry->status = iter->status; __entry->flags = iter->flags; - __entry->ops = ops; + __entry->next = next; __entry->caller = caller; ), - TP_printk("dev %d:%d ino 0x%llx pos 0x%llx length 0x%llx status %d flags %s (0x%x) ops %ps caller %pS", + TP_printk("dev %d:%d ino 0x%llx pos 0x%llx length 0x%llx status %d flags %s (0x%x) next %ps caller %pS", MAJOR(__entry->dev), MINOR(__entry->dev), __entry->ino, __entry->pos, @@ -249,7 +249,7 @@ TRACE_EVENT(iomap_iter, __entry->status, __print_flags(__entry->flags, "|", IOMAP_FLAGS_STRINGS), __entry->flags, - __entry->ops, + __entry->next, (void *)__entry->caller) ); diff --git a/fs/libfs.c b/fs/libfs.c index 96a6e9b1535f..46e0205154e7 100644 --- a/fs/libfs.c +++ b/fs/libfs.c @@ -263,17 +263,18 @@ static long dentry2offset(struct dentry *dentry) return (long)dentry->d_fsdata; } -static struct lock_class_key simple_offset_lock_class; - /** * simple_offset_init - initialize an offset_ctx * @octx: directory offset map to be initialized + * @dir: the directory @octx belongs to * + * The directory's i_rwsem is the lock of the offset map. Writers hold it + * exclusive, offset_readdir() holds it shared. */ -void simple_offset_init(struct offset_ctx *octx) +void simple_offset_init(struct offset_ctx *octx, struct inode *dir) { - mt_init_flags(&octx->mt, MT_FLAGS_ALLOC_RANGE); - lockdep_set_class(&octx->mt.ma_lock, &simple_offset_lock_class); + mt_init_flags(&octx->mt, MT_FLAGS_ALLOC_RANGE | MT_FLAGS_LOCK_EXTERN); + mt_set_external_lock(&octx->mt, &dir->i_rwsem); octx->next_offset = DIR_OFFSET_MIN; } @@ -282,6 +283,12 @@ void simple_offset_init(struct offset_ctx *octx) * @octx: directory offset ctx to be updated * @dentry: new dentry being added * + * The offset map holds no reference to @dentry. Once positive, @dentry + * must be pinned with d_make_persistent() for as long as it is in the + * map, and entries may only be added, removed or renamed with the + * directory's i_rwsem held exclusive: offset_readdir() emits straight + * from the map under the shared lock. + * * Returns zero on success. @octx and the dentry's offset are updated. * Otherwise, a negative errno value is returned. */ @@ -290,12 +297,13 @@ int simple_offset_add(struct offset_ctx *octx, struct dentry *dentry) unsigned long offset; int ret; + MA_STATE(mas, &octx->mt, 0, 0); + if (dentry2offset(dentry) != 0) return -EBUSY; - ret = mtree_alloc_cyclic(&octx->mt, &offset, dentry, DIR_OFFSET_MIN, - DIR_OFFSET_MAX, &octx->next_offset, - GFP_KERNEL); + ret = mas_alloc_cyclic(&mas, &offset, dentry, DIR_OFFSET_MIN, + DIR_OFFSET_MAX, &octx->next_offset, GFP_KERNEL); if (unlikely(ret < 0)) return ret == -EBUSY ? -ENOSPC : ret; @@ -308,7 +316,9 @@ static int simple_offset_replace(struct offset_ctx *octx, struct dentry *dentry, { int ret; - ret = mtree_store(&octx->mt, offset, dentry, GFP_KERNEL); + MA_STATE(mas, &octx->mt, offset, offset); + + ret = mas_store_gfp(&mas, dentry, GFP_KERNEL); if (ret) return ret; offset_set(dentry, offset); @@ -323,13 +333,14 @@ static int simple_offset_replace(struct offset_ctx *octx, struct dentry *dentry, */ void simple_offset_remove(struct offset_ctx *octx, struct dentry *dentry) { - long offset; + long offset = dentry2offset(dentry); + + MA_STATE(mas, &octx->mt, offset, offset); - offset = dentry2offset(dentry); if (offset == 0) return; - mtree_erase(&octx->mt, offset); + mas_erase(&mas); offset_set(dentry, 0); } @@ -387,16 +398,20 @@ int simple_offset_rename_exchange(struct inode *old_dir, long new_index = dentry2offset(new_dentry); int ret; + MA_STATE(old_mas, &old_ctx->mt, old_index, old_index); + MA_STATE(new_mas, &new_ctx->mt, new_index, new_index); + if (WARN_ON(!old_index || !new_index)) return -EINVAL; - ret = mtree_store(&new_ctx->mt, new_index, old_dentry, GFP_KERNEL); + ret = mas_store_gfp(&new_mas, old_dentry, GFP_KERNEL); if (WARN_ON(ret)) return ret; - ret = mtree_store(&old_ctx->mt, old_index, new_dentry, GFP_KERNEL); + ret = mas_store_gfp(&old_mas, new_dentry, GFP_KERNEL); if (WARN_ON(ret)) { - mtree_store(&new_ctx->mt, new_index, new_dentry, GFP_KERNEL); + mas_set(&new_mas, new_index); + mas_store_gfp(&new_mas, new_dentry, GFP_KERNEL); return ret; } @@ -411,11 +426,14 @@ int simple_offset_rename_exchange(struct inode *old_dir, * @octx: directory offset ctx that is about to be destroyed * * During fs teardown (eg. umount), a directory's offset map might still - * contain entries. xa_destroy() cleans out anything that remains. + * contain entries. __mt_destroy() cleans out anything that remains. + * Nothing can reach the map of a directory that is being destroyed, so + * this runs without the directory's i_rwsem. */ void simple_offset_destroy(struct offset_ctx *octx) { - mtree_destroy(&octx->mt); + mt_on_stack(octx->mt); + __mt_destroy(&octx->mt); } /** @@ -446,51 +464,6 @@ static loff_t offset_dir_llseek(struct file *file, loff_t offset, int whence) return vfs_setpos(file, offset, LONG_MAX); } -static struct dentry *find_positive_dentry(struct dentry *parent, - struct dentry *dentry, - bool next) -{ - struct dentry *found = NULL; - - spin_lock(&parent->d_lock); - if (next) - dentry = d_next_sibling(dentry); - else if (!dentry) - dentry = d_first_child(parent); - hlist_for_each_entry_from(dentry, d_sib) { - if (!simple_positive(dentry)) - continue; - spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED); - if (simple_positive(dentry)) - found = dget_dlock(dentry); - spin_unlock(&dentry->d_lock); - if (likely(found)) - break; - } - spin_unlock(&parent->d_lock); - return found; -} - -static noinline_for_stack struct dentry * -offset_dir_lookup(struct dentry *parent, loff_t offset) -{ - struct inode *inode = d_inode(parent); - struct offset_ctx *octx = inode->i_op->get_offset_ctx(inode); - struct dentry *child, *found = NULL; - - MA_STATE(mas, &octx->mt, offset, offset); - - if (offset == DIR_OFFSET_FIRST) - found = find_positive_dentry(parent, NULL, false); - else { - rcu_read_lock(); - child = mas_find_rev(&mas, DIR_OFFSET_MIN); - found = find_positive_dentry(parent, child, false); - rcu_read_unlock(); - } - return found; -} - static bool offset_dir_emit(struct dir_context *ctx, struct dentry *dentry) { struct inode *inode = d_inode(dentry); @@ -499,32 +472,30 @@ static bool offset_dir_emit(struct dir_context *ctx, struct dentry *dentry) inode->i_ino, fs_umode_to_dtype(inode->i_mode)); } +/* + * Emit entries in descending offset order. The directory's i_rwsem is the + * lock of the offset tree and the persistent dentries in it only change + * with it held exclusive. We hold it shared, so @mas stays valid across + * dir_emit() and the dentries need no references. + */ static void offset_iterate_dir(struct file *file, struct dir_context *ctx) { - struct dentry *dir = file->f_path.dentry; + struct inode *inode = file_inode(file); + struct offset_ctx *octx = inode->i_op->get_offset_ctx(inode); + loff_t start = ctx->pos == DIR_OFFSET_FIRST ? DIR_OFFSET_MAX : ctx->pos; struct dentry *dentry; - dentry = offset_dir_lookup(dir, ctx->pos); - if (!dentry) - goto out_eod; - while (true) { - struct dentry *next; + MA_STATE(mas, &octx->mt, start, start); + for (;;) { + dentry = mas_find_rev(&mas, DIR_OFFSET_MIN); + if (!dentry) + break; + VFS_WARN_ON_ONCE(!(dentry->d_flags & DCACHE_PERSISTENT)); ctx->pos = dentry2offset(dentry); if (!offset_dir_emit(ctx, dentry)) - break; - - next = find_positive_dentry(dir, dentry, true); - dput(dentry); - - if (!next) - goto out_eod; - dentry = next; + return; } - dput(dentry); - return; - -out_eod: ctx->pos = DIR_OFFSET_EOD; } @@ -559,7 +530,7 @@ static int offset_readdir(struct file *file, struct dir_context *ctx) if (!dir_emit_dots(file, ctx)) return 0; - if (ctx->pos != DIR_OFFSET_EOD) + if (ctx->pos < DIR_OFFSET_EOD) offset_iterate_dir(file, ctx); return 0; } diff --git a/fs/minix/bitmap.c b/fs/minix/bitmap.c index 0ac96c88e74d..3d5691111183 100644 --- a/fs/minix/bitmap.c +++ b/fs/minix/bitmap.c @@ -121,21 +121,35 @@ unsigned long minix_count_free_blocks(struct super_block *sb) << sbi->s_log_zone_size); } -struct minix_inode * -minix_V1_raw_inode(struct super_block *sb, ino_t ino, struct buffer_head **bh) +/* Return the block that holds inode @ino or 0 if @ino is out of range. */ +int minix_inode_block(struct super_block *sb, ino_t ino) { - int block; struct minix_sb_info *sbi = minix_sb(sb); - struct minix_inode *p; + int inodes_per_block; if (!ino || ino > sbi->s_ninodes) { printk("Bad inode number on dev %s: %ld is out of range\n", sb->s_id, (long)ino); - return NULL; + return 0; } + if (sbi->s_version == MINIX_V1) + inodes_per_block = MINIX_INODES_PER_BLOCK; + else + inodes_per_block = sb->s_blocksize / sizeof(struct minix2_inode); + return 2 + sbi->s_imap_blocks + sbi->s_zmap_blocks + + (ino - 1) / inodes_per_block; +} + +struct minix_inode * +minix_V1_raw_inode(struct super_block *sb, ino_t ino, struct buffer_head **bh) +{ + int block; + struct minix_inode *p; + + block = minix_inode_block(sb, ino); + if (!block) + return NULL; ino--; - block = 2 + sbi->s_imap_blocks + sbi->s_zmap_blocks + - ino / MINIX_INODES_PER_BLOCK; *bh = sb_bread(sb, block); if (!*bh) { printk("Unable to read inode block\n"); @@ -149,19 +163,14 @@ struct minix2_inode * minix_V2_raw_inode(struct super_block *sb, ino_t ino, struct buffer_head **bh) { int block; - struct minix_sb_info *sbi = minix_sb(sb); struct minix2_inode *p; int minix2_inodes_per_block = sb->s_blocksize / sizeof(struct minix2_inode); *bh = NULL; - if (!ino || ino > sbi->s_ninodes) { - printk("Bad inode number on dev %s: %ld is out of range\n", - sb->s_id, (long)ino); + block = minix_inode_block(sb, ino); + if (!block) return NULL; - } ino--; - block = 2 + sbi->s_imap_blocks + sbi->s_zmap_blocks + - ino / minix2_inodes_per_block; *bh = sb_bread(sb, block); if (!*bh) { printk("Unable to read inode block\n"); diff --git a/fs/minix/inode.c b/fs/minix/inode.c index 670179173645..9fb938ec5868 100644 --- a/fs/minix/inode.c +++ b/fs/minix/inode.c @@ -50,8 +50,6 @@ static void minix_evict_inode(struct inode *inode) if (!inode->i_nlink) { inode->i_size = 0; minix_truncate(inode); - } else { - mmb_sync(&minix_i(inode)->i_metadata_bhs); } mmb_invalidate(&minix_i(inode)->i_metadata_bhs); clear_inode(inode); @@ -702,24 +700,24 @@ static int minix_sync_inode_metadata(struct inode *inode, { int err = 0; struct buffer_head *bh; - void *raw_inode; + int block; - if (INODE_VERSION(inode) == MINIX_V1) - raw_inode = minix_V1_raw_inode(inode->i_sb, inode->i_ino, &bh); - else - raw_inode = minix_V2_raw_inode(inode->i_sb, inode->i_ino, &bh); - if (!raw_inode) + block = minix_inode_block(inode->i_sb, inode->i_ino); + if (!block) return -EIO; err = mmb_sync(&minix_i(inode)->i_metadata_bhs); if (err) - goto out; + return err; + /* A block that isn't cached is neither dirty nor under writeback. */ + bh = sb_find_get_block_nonatomic(inode->i_sb, block); + if (!bh) + return 0; sync_dirty_buffer(bh); if (buffer_write_io_error(bh)) { printk("IO error syncing minix inode [%s:%08llx]\n", inode->i_sb->s_id, inode->i_ino); err = -EIO; } -out: brelse(bh); return err; } diff --git a/fs/minix/minix.h b/fs/minix/minix.h index db92cf9e0e1b..67d8e2a7dc06 100644 --- a/fs/minix/minix.h +++ b/fs/minix/minix.h @@ -47,6 +47,7 @@ void __minix_error_inode(struct inode *inode, const char *function, unsigned int line, const char *fmt, ...); struct inode *minix_iget(struct super_block *, unsigned long); +int minix_inode_block(struct super_block *sb, ino_t ino); struct minix_inode *minix_V1_raw_inode(struct super_block *, ino_t, struct buffer_head **); struct minix2_inode *minix_V2_raw_inode(struct super_block *, ino_t, struct buffer_head **); struct inode *minix_new_inode(const struct inode *, umode_t); diff --git a/fs/namespace.c b/fs/namespace.c index 010ed5d68d22..aecd05ac0170 100644 --- a/fs/namespace.c +++ b/fs/namespace.c @@ -3296,7 +3296,7 @@ static struct mnt_namespace *create_new_namespace(struct path *path, } new_ns->root = new_ns_root; - ns_tree_add_raw(new_ns); + ns_tree_add(new_ns); return new_ns; } @@ -4394,8 +4394,6 @@ static struct mnt_namespace *alloc_mnt_ns(struct user_namespace *user_ns, bool a dec_mnt_namespaces(ucounts); return ERR_PTR(ret); } - ns_tree_gen_id(new_ns); - new_ns->is_anon = anon; refcount_set(&new_ns->passive, 1); new_ns->mounts = RB_ROOT; @@ -4499,7 +4497,7 @@ struct mnt_namespace *copy_mnt_ns(u64 flags, struct mnt_namespace *ns, p = next_mnt(skip_mnt_tree(p), old); } } - ns_tree_add_raw(new_ns); + ns_tree_add(new_ns); return new_ns; } diff --git a/fs/netfs/read_retry.c b/fs/netfs/read_retry.c index 5bd8dee5a834..bfaaebea12df 100644 --- a/fs/netfs/read_retry.c +++ b/fs/netfs/read_retry.c @@ -28,6 +28,7 @@ static void netfs_retry_read_subrequests(struct netfs_io_request *rreq) struct netfs_io_subrequest *subreq; struct netfs_io_stream *stream = &rreq->io_streams[0]; struct list_head *next; + int ret; _enter("R=%x", rreq->debug_id); @@ -140,8 +141,11 @@ static void netfs_retry_read_subrequests(struct netfs_io_request *rreq) /* Renegotiate max_len (rsize) */ stream->sreq_max_len = subreq->len; - if (rreq->netfs_ops->prepare_read && - rreq->netfs_ops->prepare_read(subreq) < 0) { + ret = 0; + if (rreq->netfs_ops->prepare_read) + ret = rreq->netfs_ops->prepare_read(subreq); + if (ret < 0) { + subreq->error = ret; trace_netfs_sreq(subreq, netfs_sreq_trace_reprep_failed); __set_bit(NETFS_SREQ_FAILED, &subreq->flags); goto abandon; @@ -221,7 +225,9 @@ static void netfs_retry_read_subrequests(struct netfs_io_request *rreq) part = netfs_limit_iter(&source, 0, part, stream->sreq_max_segs); netfs_stat(&netfs_n_rh_download); - if (rreq->netfs_ops->prepare_read(subreq) < 0) { + ret = rreq->netfs_ops->prepare_read(subreq); + if (ret < 0) { + subreq->error = ret; trace_netfs_sreq(subreq, netfs_sreq_trace_reprep_failed); __set_bit(NETFS_SREQ_FAILED, &subreq->flags); goto abandon; @@ -257,10 +263,13 @@ abandon: if (!test_bit(NETFS_SREQ_FAILED, &subreq->flags) && !test_bit(NETFS_SREQ_NEED_RETRY, &subreq->flags)) continue; - subreq->error = -ENOMEM; + if (!subreq->error || + !test_bit(NETFS_SREQ_FAILED, &subreq->flags)) + subreq->error = -ENOMEM; __set_bit(NETFS_SREQ_FAILED, &subreq->flags); __clear_bit(NETFS_SREQ_NEED_RETRY, &subreq->flags); } + netfs_wake_collector(rreq); } /* diff --git a/fs/netfs/write_issue.c b/fs/netfs/write_issue.c index b8237e1314d8..f23364116421 100644 --- a/fs/netfs/write_issue.c +++ b/fs/netfs/write_issue.c @@ -268,7 +268,9 @@ void netfs_reissue_write(struct netfs_io_stream *stream, iov_iter_truncate(&subreq->io_iter, size); subreq->retry_count++; - subreq->error = 0; + /* Keep prepare_write() errno; do_issue_write() terminates FAILED. */ + if (!test_bit(NETFS_SREQ_FAILED, &subreq->flags)) + subreq->error = 0; __clear_bit(NETFS_SREQ_MADE_PROGRESS, &subreq->flags); __set_bit(NETFS_SREQ_IN_PROGRESS, &subreq->flags); netfs_stat(&netfs_n_wh_retry_write_subreq); diff --git a/fs/nfs/delegation.h b/fs/nfs/delegation.h index fba4699952b8..cd6142939d34 100644 --- a/fs/nfs/delegation.h +++ b/fs/nfs/delegation.h @@ -95,6 +95,8 @@ void nfs4_inode_make_writeable(struct inode *inode); void nfs_update_delegated_atime(struct inode *inode); void nfs_update_delegated_mtime(struct inode *inode); void nfs_update_delegated_mtime_locked(struct inode *inode); +void nfs_delegated_ctime_raise(struct inode *inode, + const struct nfs_fattr *fattr); static inline int nfs_have_read_or_write_delegation(struct inode *inode) { diff --git a/fs/nfs/dir.c b/fs/nfs/dir.c index 08a940e63152..49437037f948 100644 --- a/fs/nfs/dir.c +++ b/fs/nfs/dir.c @@ -1253,6 +1253,8 @@ static int nfs_readdir(struct file *file, struct dir_context *ctx) spin_lock(&file->f_lock); desc->dir_cookie = dir_ctx->dir_cookie; desc->folio_index = dir_ctx->page_index; + desc->current_index = (loff_t)desc->folio_index * + nfs_readdir_array_maxentries(); desc->last_cookie = dir_ctx->last_cookie; desc->attr_gencount = dir_ctx->attr_gencount; desc->eof = dir_ctx->eof; @@ -2735,7 +2737,7 @@ static bool nfs_rename_is_unsafe_cross_dir(struct dentry *old_dentry, { struct nfs_server *server = NFS_SB(old_dentry->d_sb); - if (old_dentry->d_parent != new_dentry->d_parent) + if (old_dentry->d_parent == new_dentry->d_parent) return false; if (server->fh_expire_type & NFS_FH_RENAME_UNSAFE) return !(server->fh_expire_type & NFS_FH_NOEXPIRE_WITH_OPEN); diff --git a/fs/nfs/flexfilelayout/flexfilelayout.c b/fs/nfs/flexfilelayout/flexfilelayout.c index 9492d6bc1d1a..5c289737366f 100644 --- a/fs/nfs/flexfilelayout/flexfilelayout.c +++ b/fs/nfs/flexfilelayout/flexfilelayout.c @@ -11,6 +11,7 @@ #include <linux/nfs_mount.h> #include <linux/nfs_page.h> #include <linux/module.h> +#include <linux/bitmap.h> #include <linux/file.h> #include <linux/sched/mm.h> @@ -340,6 +341,7 @@ static void _ff_layout_free_lseg(struct nfs4_ff_layout_segment *fls) { if (fls) { ff_layout_free_mirror_array(fls); + bitmap_free(fls->cancelled_stripes); kfree(fls); } } @@ -653,6 +655,12 @@ ff_layout_alloc_lseg(struct pnfs_layout_hdr *lh, fls->mirror_array[i]->report_interval = be32_to_cpup(p); out_sort_mirrors: + fls->cancelled_stripes = bitmap_zalloc( + fls->mirror_array_cnt * dss_count, gfp_flags); + if (!fls->cancelled_stripes) { + rc = -ENOMEM; + goto out_err_free; + } ff_layout_sort_mirrors(fls); ret = &fls->generic_hdr; dprintk("<-- %s (success)\n", __func__); @@ -2582,6 +2590,10 @@ static void ff_layout_cancel_io(struct pnfs_layout_segment *lseg, if (devid && memcmp(&mirror->dss[dss_id].devid, devid, sizeof(*devid)) != 0) continue; + /* Do not cancel a stripe again while this lseg drains. */ + if (test_and_set_bit(idx * mirror->dss_count + dss_id, + flseg->cancelled_stripes)) + continue; rcu_read_lock(); mirror_ds = rcu_dereference(mirror->dss[dss_id].mirror_ds); if (IS_ERR_OR_NULL(mirror_ds) || @@ -2599,10 +2611,9 @@ static void ff_layout_cancel_io(struct pnfs_layout_segment *lseg, clnt = ds_clp->cl_rpcclient; if (!clnt) goto next; - if (!rpc_cancel_tasks(clnt, -ECANCELED, - ff_layout_match_io, lseg)) - goto next; - rpc_clnt_disconnect(clnt); + rpc_cancel_tasks_and_disconnect(clnt, -ECANCELED, + ff_layout_match_io, + lseg); next: nfs4_ff_layout_put_deviceid(mirror_ds); } diff --git a/fs/nfs/flexfilelayout/flexfilelayout.h b/fs/nfs/flexfilelayout/flexfilelayout.h index 09c3cd6964fd..5d5587fded76 100644 --- a/fs/nfs/flexfilelayout/flexfilelayout.h +++ b/fs/nfs/flexfilelayout/flexfilelayout.h @@ -109,6 +109,7 @@ struct nfs4_ff_layout_segment { u64 stripe_unit; u32 flags; u32 mirror_array_cnt; + unsigned long *cancelled_stripes; struct nfs4_ff_layout_mirror *mirror_array[] __counted_by(mirror_array_cnt); }; diff --git a/fs/nfs/inode.c b/fs/nfs/inode.c index e0a2e92952af..5a682f74d7d1 100644 --- a/fs/nfs/inode.c +++ b/fs/nfs/inode.c @@ -629,28 +629,52 @@ nfs_fattr_fixup_delegated(struct inode *inode, struct nfs_fattr *fattr) } } +/* + * With delegated timestamps, the client's coarse clock can trail the + * server's fine-grained ctime cached from an OPEN or SETATTR reply. The + * server won't move ctime backward when the times are returned, so a + * new stamp must land after the cached ctime. + */ +static struct timespec64 nfs_delegated_stamp(struct inode *inode) +{ + struct timespec64 ctime = inode_get_ctime(inode); + struct timespec64 now = current_time(inode); + + if (timespec64_compare(&now, &ctime) <= 0) { + now = ctime; + timespec64_add_ns(&now, 1); + } + return now; +} + +/* + * The server stamped c/mtime itself (e.g. for a size change). Raise the + * cached ctime to the server's so that the next delegated stamp lands + * after it. + */ +void nfs_delegated_ctime_raise(struct inode *inode, + const struct nfs_fattr *fattr) +{ + struct timespec64 ctime = inode_get_ctime(inode); + + if ((fattr->valid & NFS_ATTR_FATTR_CTIME) && + timespec64_compare(&fattr->ctime, &ctime) > 0) + inode_set_ctime_to_ts(inode, fattr->ctime); +} +EXPORT_SYMBOL_GPL(nfs_delegated_ctime_raise); + static void nfs_set_timestamps_to_ts(struct inode *inode, struct iattr *attr) { unsigned int cache_flags = 0; if (attr->ia_valid & ATTR_MTIME_SET) { - struct timespec64 ctime = inode_get_ctime(inode); - struct timespec64 mtime = inode_get_mtime(inode); - struct timespec64 now; - bool updated = false; - - now = inode_set_ctime_current(inode); - if (!timespec64_equal(&now, &ctime)) - updated = true; - + /* The stamp is always after the old ctime */ + inode_set_ctime_to_ts(inode, nfs_delegated_stamp(inode)); inode_set_mtime_to_ts(inode, attr->ia_mtime); - if (!timespec64_equal(&now, &mtime)) - updated = true; - - inode_maybe_inc_iversion(inode, updated); + inode_maybe_inc_iversion(inode, true); cache_flags |= NFS_INO_INVALID_CTIME | NFS_INO_INVALID_MTIME; } - if (attr->ia_valid & ATTR_ATIME_SET) { + if (attr->ia_valid & ATTR_ATIME) { inode_set_atime_to_ts(inode, attr->ia_atime); cache_flags |= NFS_INO_INVALID_ATIME; } @@ -665,7 +689,11 @@ static void nfs_update_atime(struct inode *inode) static void nfs_update_mtime(struct inode *inode) { - inode_update_time(inode, FS_UPD_CMTIME, 0); + struct timespec64 now = nfs_delegated_stamp(inode); + + /* Not inode_update_time(): lockless readers would see its stamp */ + inode_set_ctime_to_ts(inode, now); + inode_set_mtime_to_ts(inode, now); NFS_I(inode)->cache_validity &= ~(NFS_INO_INVALID_CTIME | NFS_INO_INVALID_MTIME); } @@ -684,6 +712,7 @@ void nfs_update_delegated_mtime_locked(struct inode *inode) nfs_have_directory_delegation(inode)) nfs_update_mtime(inode); } +EXPORT_SYMBOL_GPL(nfs_update_delegated_mtime_locked); void nfs_update_delegated_mtime(struct inode *inode) { @@ -746,7 +775,7 @@ nfs_setattr(const struct mnt_idmap *idmap, struct dentry *dentry, } else if (nfs_have_delegated_atime(inode) && attr->ia_valid & ATTR_ATIME && !(attr->ia_valid & ATTR_MTIME)) { - if (!(attr->ia_valid & ATTR_ATIME_SET)) { + if (!(attr->ia_valid & (ATTR_ATIME_SET | ATTR_TIMES_SET))) { nfs_update_delegated_atime(inode); attr->ia_valid &= ~ATTR_ATIME; } @@ -808,10 +837,14 @@ static int nfs_vmtruncate(struct inode * inode, loff_t offset) nfs_ooo_clear(NFS_I(inode)); } NFS_I(inode)->cache_validity &= ~NFS_INO_INVALID_SIZE; + /* + * Stamp in the same i_lock section that checked the delegation and + * raised ctime, before a delegation return can start. + */ + nfs_update_delegated_mtime_locked(inode); spin_unlock(&inode->i_lock); truncate_pagecache(inode, offset); - nfs_update_delegated_mtime_locked(inode); spin_lock(&inode->i_lock); out: return err; @@ -837,6 +870,8 @@ void nfs_setattr_update_inode(struct inode *inode, struct iattr *attr, if ((attr->ia_valid & ATTR_SIZE) != 0) { if (!nfs_have_delegated_mtime(inode)) nfs_set_cache_invalid(inode, NFS_INO_INVALID_MTIME); + else + nfs_delegated_ctime_raise(inode, fattr); nfs_set_cache_invalid(inode, NFS_INO_INVALID_BLOCKS); nfs_inc_stats(inode, NFSIOS_SETATTRTRUNC); nfs_vmtruncate(inode, attr->ia_size); diff --git a/fs/nfs/localio.c b/fs/nfs/localio.c index cdada6cbb13b..7f8d794581a3 100644 --- a/fs/nfs/localio.c +++ b/fs/nfs/localio.c @@ -25,6 +25,7 @@ #include <linux/nfs_xdr.h> #include "internal.h" +#include "netns.h" #include "pnfs.h" #include "nfstrace.h" @@ -55,7 +56,50 @@ struct nfs_local_fsync_ctx { }; static bool localio_enabled __read_mostly = true; -module_param(localio_enabled, bool, 0644); + +static void nfs_local_probe_all(void); + +/* + * localio_enabled is checked on every I/O, so turning it off stops LOCALIO + * at once and turning it back on resumes it for clients that use it. A + * client that probed while it was off was disabled, and nothing probes it + * again: turning it on probes every client that does not use LOCALIO. + */ +static int localio_enabled_set(const char *val, const struct kernel_param *kp) +{ + bool was = READ_ONCE(localio_enabled); + int ret; + + ret = param_set_bool(val, kp); + if (!ret && !was && READ_ONCE(localio_enabled)) + nfs_local_probe_all(); + return ret; +} + +static const struct kernel_param_ops localio_enabled_ops = { + .set = localio_enabled_set, + .get = param_get_bool, +}; +module_param_cb(localio_enabled, &localio_enabled_ops, &localio_enabled, 0644); + +/* + * Seconds the LOCALIO probe waits for each reply. With 0, the probe uses + * the NFS client's timeouts instead. + */ +static unsigned int localio_timeout __read_mostly = 10; + +static int localio_timeout_set(const char *val, const struct kernel_param *kp) +{ + return param_set_uint_minmax(val, kp, 0, 600); +} + +static const struct kernel_param_ops localio_timeout_ops = { + .set = localio_timeout_set, + .get = param_get_uint, +}; +module_param_cb(localio_timeout, &localio_timeout_ops, &localio_timeout, 0644); +MODULE_PARM_DESC(localio_timeout, + "LOCALIO probe timeout in seconds (default 10), 0 to use the mount's default"); static void nfs_local_do_read(struct nfs_local_kiocb *iocb, const struct rpc_call_ops *call_ops); @@ -131,13 +175,45 @@ const struct rpc_program nfslocalio_program = { /* * nfs_init_localioclient - Initialise an NFS localio client connection + * + * A server that does not support LOCALIO may not answer its RPCs at all. + * The probe shares the NFS client's transport and runs beside its RPCs. + * With localio_timeout set, it gets a quiet, soft timeout of that many + * seconds of its own, whatever timeouts the mount uses. With 0, it uses + * the NFS client's timeouts, as an NFS RPC would. */ static struct rpc_clnt *nfs_init_localioclient(struct nfs_client *clp) { - struct rpc_clnt *rpcclient_localio; + unsigned int timeout_secs = READ_ONCE(localio_timeout); + struct rpc_clnt *parent = clp->cl_rpcclient; + struct rpc_clnt *probe = NULL, *rpcclient_localio; - rpcclient_localio = rpc_bind_new_program(clp->cl_rpcclient, - &nfslocalio_program, 1); + /* + * rpc_bind_new_program() pings the new program with the timeout of + * the client it clones, so set the probe's timeout on a private + * clone first. The clone's cl_timeout points at the transport's + * timeout: give it its own copy rather than write through it. + */ + if (timeout_secs) { + probe = rpc_clone_client(parent); + if (IS_ERR(probe)) + return probe; + probe->cl_timeout_default = (struct rpc_timeout) { + .to_initval = timeout_secs * HZ, + .to_maxval = timeout_secs * HZ, + .to_retries = 0, + }; + probe->cl_timeout = &probe->cl_timeout_default; + probe->cl_softrtry = 1; + probe->cl_noretranstimeo = 0; + probe->cl_chatty = 0; + parent = probe; + } + + rpcclient_localio = rpc_bind_new_program(parent, &nfslocalio_program, 1); + /* The new client holds a reference to its parent, the probe clone */ + if (probe) + rpc_shutdown_client(probe); dprintk_rcu("%s: server (%s) %s NFS LOCALIO.\n", __func__, rpc_peeraddr2str(clp->cl_rpcclient, RPC_DISPLAY_ADDR), @@ -203,18 +279,49 @@ void nfs_local_probe_async_work(struct work_struct *work) struct nfs_client *clp = container_of(work, struct nfs_client, cl_local_probe_work); - if (!refcount_inc_not_zero(&clp->cl_count)) - return; nfs_local_probe(clp); + /* The reference nfs_local_probe_async() took for this work */ nfs_put_client(clp); } +/* + * The work is part of the client, so it holds a reference on the client + * from when it is queued until it has run: the last nfs_put_client() + * cannot free the client under a queued probe. + */ void nfs_local_probe_async(struct nfs_client *clp) { - queue_work(nfsiod_workqueue, &clp->cl_local_probe_work); + if (!refcount_inc_not_zero(&clp->cl_count)) + return; + if (!queue_work(nfsiod_workqueue, &clp->cl_local_probe_work)) + nfs_put_client(clp); /* already queued, with its reference */ } EXPORT_SYMBOL_GPL(nfs_local_probe_async); +/* Probe every client, in every namespace, that does not use LOCALIO. */ +static void nfs_local_probe_all(void) +{ + struct nfs_client *clp; + struct net *net; + + /* Set on the module command line: there are no clients yet. */ + if (!nfs_net_id) + return; + + down_read(&net_rwsem); + for_each_net(net) { + struct nfs_net *nn = net_generic(net, nfs_net_id); + + spin_lock(&nn->nfs_client_lock); + list_for_each_entry(clp, &nn->nfs_client_list, cl_share_link) + if (clp->cl_cons_state == NFS_CS_READY && + !nfs_client_is_local(clp)) + nfs_local_probe_async(clp); + spin_unlock(&nn->nfs_client_lock); + } + up_read(&net_rwsem); +} + static inline void nfs_local_file_put(struct nfsd_file *localio) { /* nfs_to_nfsd_file_put_local() expects an __rcu pointer diff --git a/fs/nfs/nfs42proc.c b/fs/nfs/nfs42proc.c index ab86246fc364..09b4a6ecad88 100644 --- a/fs/nfs/nfs42proc.c +++ b/fs/nfs/nfs42proc.c @@ -380,6 +380,7 @@ out: * @pos: destination offset * @len: copy length * @oldsize: length of the file prior to clone/copy + * @fattr: destination attributes from the reply, or NULL * * Punch a hole in the inode page cache, so that the NFS client will * know to retrieve new data. @@ -387,7 +388,7 @@ out: * invalid cached values for change attribute, ctime, mtime and space used. */ static void nfs42_copy_dest_done(struct file *file, loff_t pos, loff_t len, - loff_t oldsize) + loff_t oldsize, const struct nfs_fattr *fattr) { struct inode *inode = file_inode(file); struct address_space *mapping = file->f_mapping; @@ -405,8 +406,12 @@ static void nfs42_copy_dest_done(struct file *file, loff_t pos, loff_t len, NFS_INO_INVALID_CTIME | NFS_INO_INVALID_MTIME | NFS_INO_INVALID_BLOCKS); + /* The server may have stamped c/mtime; stamp after it */ + if (fattr && nfs_have_delegated_mtime(inode)) + nfs_delegated_ctime_raise(inode, fattr); + /* Before a refresh can see the times invalid and take the server's */ + nfs_update_delegated_mtime_locked(inode); spin_unlock(&inode->i_lock); - nfs_update_delegated_mtime(inode); } static ssize_t _nfs42_proc_copy(struct file *src, @@ -506,7 +511,8 @@ static ssize_t _nfs42_proc_copy(struct file *src, goto out; } - nfs42_copy_dest_done(dst, pos_dst, res->write_res.count, oldsize_dst); + nfs42_copy_dest_done(dst, pos_dst, res->write_res.count, oldsize_dst, + NULL); nfs_invalidate_atime(src_inode); status = res->write_res.count; out: @@ -1311,8 +1317,17 @@ static int _nfs42_proc_clone(struct rpc_message *msg, struct file *src_f, /* a zero-length count means clone to EOF in src */ if (count == 0 && res.dst_fattr->valid & NFS_ATTR_FATTR_SIZE) count = nfs_size_to_loff_t(res.dst_fattr->size) - dst_offset; - nfs42_copy_dest_done(dst_f, dst_offset, count, oldsize_dst); - status = nfs_post_op_update_inode(dst_inode, res.dst_fattr); + nfs42_copy_dest_done(dst_f, dst_offset, count, oldsize_dst, + res.dst_fattr); + /* + * nfs_post_op_update_inode() would mark ctime invalid, so the + * reply's ctime would overwrite the delegated stamp. + */ + if (nfs_have_delegated_mtime(dst_inode)) + status = nfs_refresh_inode(dst_inode, res.dst_fattr); + else + status = nfs_post_op_update_inode(dst_inode, + res.dst_fattr); } kfree(res.dst_fattr); diff --git a/fs/nfs/nfs4proc.c b/fs/nfs/nfs4proc.c index e1018b03c1cb..6759fa61b9b4 100644 --- a/fs/nfs/nfs4proc.c +++ b/fs/nfs/nfs4proc.c @@ -1722,6 +1722,8 @@ static void nfs_set_open_stateid_locked(struct nfs4_state *state, { DEFINE_WAIT(wait); int status = 0; + unsigned long deadline = jiffies + 5 * HZ; + signed long remaining; for (;;) { if (nfs_stateid_is_sequential(state, stateid)) @@ -1756,7 +1758,8 @@ static void nfs_set_open_stateid_locked(struct nfs4_state *state, if (!fatal_signal_pending(current) && !nfs_current_task_exiting()) { - if (schedule_timeout(5*HZ) == 0) + remaining = (long)(deadline - jiffies); + if (remaining <= 0 || schedule_timeout(remaining) == 0) status = -EAGAIN; else status = 0; @@ -3093,6 +3096,8 @@ static int _nfs4_open_and_get_state(struct nfs4_opendata *opendata, if (server->caps & NFS_CAP_POSIX_LOCK) set_bit(NFS_STATE_POSIX_LOCKS, &state->flags); if (opendata->o_res.rflags & NFS4_OPEN_RESULT_MAY_NOTIFY_LOCK) + server->nfs_client->cl_may_notify_lock = true; + if (server->nfs_client->cl_may_notify_lock) set_bit(NFS_STATE_MAY_NOTIFY_LOCK, &state->flags); if (opendata->o_res.rflags & NFS4_OPEN_RESULT_PRESERVE_UNLINKED) set_bit(NFS_INO_PRESERVE_UNLINKED, &NFS_I(state->inode)->flags); @@ -7287,8 +7292,15 @@ static int nfs4_proc_unlck(struct nfs4_state *state, int cmd, struct file_lock * if (status != 0) goto out; /* Is this a delegated lock? */ - if (test_bit(NFS_LOCK_INITIALIZED, &lsp->ls_flags) == 0) + if (test_bit(NFS_LOCK_INITIALIZED, &lsp->ls_flags) == 0) { + struct nfs_client *clp = NFS_SERVER(inode)->nfs_client; + struct cb_notify_lock_args cbnl = { .cbnl_valid = false }; + + /* The server never saw it, so it will not notify waiters */ + nfs_copy_fh(&cbnl.cbnl_fh, NFS_FH(inode)); + __wake_up(&clp->cl_lock_waitq, TASK_NORMAL, 0, &cbnl); goto out; + } alloc_seqid = NFS_SERVER(inode)->nfs_client->cl_mvops->alloc_seqid; seqid = alloc_seqid(&lsp->ls_seqid, GFP_KERNEL); status = -ENOMEM; @@ -7708,8 +7720,14 @@ nfs4_wake_lock_waiter(wait_queue_entry_t *wait, unsigned int mode, int flags, vo struct nfs_lowner *lowner = &cbnl->cbnl_owner, *wowner = &waiter->owner; - /* Only wake if the callback was for the same owner. */ - if (lowner->id != wowner->id || lowner->s_dev != wowner->s_dev) + /* + * Only wake the owner a CB_NOTIFY_LOCK names. A lock cached + * under a delegation is released locally, and the releasing + * thread cannot tell which waiter wants it, so those wakeups + * (cbnl_valid false) name only the inode and wake them all. + */ + if (cbnl->cbnl_valid && + (lowner->id != wowner->id || lowner->s_dev != wowner->s_dev)) return 0; /* Make sure it's for the right inode */ diff --git a/fs/nfs/pnfs.c b/fs/nfs/pnfs.c index 6dc00233e837..14f4a4b12ffd 100644 --- a/fs/nfs/pnfs.c +++ b/fs/nfs/pnfs.c @@ -2086,7 +2086,7 @@ static bool pnfs_within_mdsthreshold(struct nfs_open_context *ctx, break; } if (size_set && io_set) { - if (size && io) + if (size || io) ret = true; } else if (size || io) ret = true; diff --git a/fs/nilfs2/file.c b/fs/nilfs2/file.c index 30dd8e5ebe5b..d1bf52b00349 100644 --- a/fs/nilfs2/file.c +++ b/fs/nilfs2/file.c @@ -149,7 +149,7 @@ static ssize_t nilfs_file_read_iter(struct kiocb *iocb, struct iov_iter *to) if (iocb->ki_flags & IOCB_DIRECT) { inode_lock_shared(inode); - ret = iomap_dio_rw(iocb, to, &nilfs_iomap_ops, + ret = iomap_dio_rw(iocb, to, nilfs_iomap_next, NULL, 0, NULL, 0); inode_unlock_shared(inode); } else diff --git a/fs/nilfs2/iomap.c b/fs/nilfs2/iomap.c index e130ed63abd9..c00189ade861 100644 --- a/fs/nilfs2/iomap.c +++ b/fs/nilfs2/iomap.c @@ -67,6 +67,4 @@ static int nilfs_iomap_begin(struct inode *inode, loff_t offset, return 0; } -const struct iomap_ops nilfs_iomap_ops = { - .iomap_begin = nilfs_iomap_begin, -}; +DEFINE_IOMAP_ITER_NEXT(nilfs_iomap_next, nilfs_iomap_begin); diff --git a/fs/nilfs2/iomap.h b/fs/nilfs2/iomap.h index adef3e22346d..5f9c05bd1230 100644 --- a/fs/nilfs2/iomap.h +++ b/fs/nilfs2/iomap.h @@ -8,6 +8,8 @@ #ifndef _NILFS_IOMAP_H #define _NILFS_IOMAP_H -extern const struct iomap_ops nilfs_iomap_ops; +#include <linux/iomap.h> + +DECLARE_IOMAP_ITER_NEXT(nilfs_iomap_next); #endif /* _NILFS_IOMAP_H */ diff --git a/fs/ntfs/aops.c b/fs/ntfs/aops.c index ad781674fef1..cb3d5443ee1d 100644 --- a/fs/ntfs/aops.c +++ b/fs/ntfs/aops.c @@ -103,7 +103,7 @@ static int ntfs_read_folio(struct file *file, struct folio *folio) return ntfs_read_compressed_block(folio); } - iomap_read_folio(&ntfs_read_iomap_ops, &ctx, NULL); + iomap_read_folio(ntfs_read_iomap_next, &ctx, NULL); return 0; } @@ -247,7 +247,7 @@ static void ntfs_readahead(struct readahead_control *rac) if (!NInoNonResident(ni) || NInoEncrypted(ni) || NInoCompressed(ni) || NInoWofCompressed(ni)) return; - iomap_readahead(&ntfs_read_iomap_ops, &ctx, NULL); + iomap_readahead(ntfs_read_iomap_next, &ctx, NULL); } static int ntfs_writepages(struct address_space *mapping, @@ -301,7 +301,7 @@ static int ntfs_swap_activate(struct swap_info_struct *sis, return -EOPNOTSUPP; return iomap_swapfile_activate(sis, swap_file, span, - &ntfs_read_iomap_ops); + ntfs_read_iomap_next); } const struct address_space_operations ntfs_aops = { diff --git a/fs/ntfs/dir.c b/fs/ntfs/dir.c index fce10baa2b93..9fb5bb3d3512 100644 --- a/fs/ntfs/dir.c +++ b/fs/ntfs/dir.c @@ -309,6 +309,20 @@ found_it: ia_mapping = ia_vi->i_mapping; descend_into_child_node: /* + * The child node has to be inside $INDEX_ALLOCATION. A directory that + * lacks the attribute gets an empty index inode that is not + * non-resident, and reading a folio from it locks the mft record that + * is already locked here. + */ + if (!NInoNonResident(NTFS_I(ia_vi)) || vcn < 0 || + (u64)vcn >= (u64)i_size_read(ia_vi) >> dir_ni->itype.index.vcn_size_bits) { + ntfs_error(sb, + "Child node vcn %lld is outside $INDEX_ALLOCATION in directory inode 0x%llx.", + vcn, dir_ni->mft_no); + err = -EIO; + goto err_out; + } + /* * Convert vcn to index into the index allocation attribute in units * of PAGE_SIZE and map the page cache page, reading it from * disk if necessary. diff --git a/fs/ntfs/file.c b/fs/ntfs/file.c index b2f5882d9990..1861d0f07fef 100644 --- a/fs/ntfs/file.c +++ b/fs/ntfs/file.c @@ -686,12 +686,12 @@ loff_t ntfs_file_llseek(struct file *file, loff_t offset, int whence) switch (whence) { case SEEK_HOLE: inode_lock_shared(inode); - offset = iomap_seek_hole(inode, offset, &ntfs_seek_iomap_ops); + offset = iomap_seek_hole(inode, offset, ntfs_seek_iomap_next); inode_unlock_shared(inode); break; case SEEK_DATA: inode_lock_shared(inode); - offset = iomap_seek_data(inode, offset, &ntfs_seek_iomap_ops); + offset = iomap_seek_data(inode, offset, ntfs_seek_iomap_next); inode_unlock_shared(inode); break; default: @@ -728,7 +728,7 @@ ssize_t ntfs_file_read_iter(struct kiocb *iocb, struct iov_iter *to) } file_accessed(iocb->ki_filp); - ret = iomap_dio_rw(iocb, to, &ntfs_read_iomap_ops, NULL, 0, + ret = iomap_dio_rw(iocb, to, ntfs_read_iomap_next, NULL, 0, NULL, 0); } else { ret = generic_file_read_iter(iocb, to); @@ -770,7 +770,7 @@ static ssize_t ntfs_dio_write_iter(struct kiocb *iocb, struct iov_iter *from) { ssize_t ret; - ret = iomap_dio_rw(iocb, from, &ntfs_dio_iomap_ops, + ret = iomap_dio_rw(iocb, from, ntfs_dio_iomap_next, &ntfs_write_dio_ops, 0, NULL, 0); if (ret == -ENOTBLK) ret = 0; @@ -798,7 +798,7 @@ static ssize_t ntfs_dio_write_iter(struct kiocb *iocb, struct iov_iter *from) inode_dio_wait(file_inode(iocb->ki_filp)); written = iomap_file_buffered_write(iocb, from, - &ntfs_write_iomap_ops, &ntfs_iomap_folio_ops, + ntfs_write_iomap_next, &ntfs_iomap_folio_ops, NULL); if (written < 0) { ret = written; @@ -930,7 +930,7 @@ ssize_t ntfs_file_write_iter(struct kiocb *iocb, struct iov_iter *from) if (NInoNonResident(ni) && iocb->ki_flags & IOCB_DIRECT) ret = ntfs_dio_write_iter(iocb, from); else - ret = iomap_file_buffered_write(iocb, from, &ntfs_write_iomap_ops, + ret = iomap_file_buffered_write(iocb, from, ntfs_write_iomap_next, &ntfs_iomap_folio_ops, NULL); out: if (ret < 0 && ret != -EIOCBQUEUED) { @@ -1017,7 +1017,7 @@ static vm_fault_t ntfs_filemap_page_mkwrite(struct vm_fault *vmf) * exclusively while invalidating pagecache and changing extents. */ filemap_invalidate_lock_shared(mapping); - ret = iomap_page_mkwrite(vmf, &ntfs_page_mkwrite_iomap_ops, NULL); + ret = iomap_page_mkwrite(vmf, ntfs_page_mkwrite_iomap_next, NULL); filemap_invalidate_unlock_shared(mapping); sb_end_pagefault(inode->i_sb); return ret; @@ -1072,7 +1072,7 @@ int ntfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo, if (NInoWofCompressed(NTFS_I(inode))) return -EOPNOTSUPP; - return iomap_fiemap(inode, fieinfo, start, len, &ntfs_read_iomap_ops); + return iomap_fiemap(inode, fieinfo, start, len, ntfs_read_iomap_next); } static const char *ntfs_get_link(struct dentry *dentry, struct inode *inode, @@ -1322,7 +1322,7 @@ static int ntfs_punch_hole(struct ntfs_inode *ni, int mode, loff_t offset, ntfs_cluster_to_bytes(vol, start_vcn + 1), end_offset); err = iomap_zero_range(vi, offset, to - offset, - NULL, &ntfs_seek_iomap_ops, + NULL, ntfs_seek_iomap_next, &ntfs_iomap_folio_ops, NULL); if (err < 0) goto out; @@ -1338,7 +1338,7 @@ static int ntfs_punch_hole(struct ntfs_inode *ni, int mode, loff_t offset, from = ntfs_cluster_to_bytes(vol, end_vcn - 1); if (from < ni->initialized_size) { err = iomap_zero_range(vi, from, end_offset - from, - NULL, &ntfs_seek_iomap_ops, + NULL, ntfs_seek_iomap_next, &ntfs_iomap_folio_ops, NULL); if (err < 0) goto out; diff --git a/fs/ntfs/index.c b/fs/ntfs/index.c index 322cb371dbb3..b4462f760e3b 100644 --- a/fs/ntfs/index.c +++ b/fs/ntfs/index.c @@ -43,9 +43,11 @@ static int ntfs_index_entry_inconsistent(const struct ntfs_volume *vol, } else { if (collation_rule == COLLATION_FILE_NAME) { - if ((offsetof(struct index_entry, key.file_name.file_name) + - ie->key.file_name.file_name_length * sizeof(__le16)) > - le16_to_cpu(ie->length)) { + if (le16_to_cpu(ie->key_length) < + offsetof(struct file_name_attr, file_name) || + (offsetof(struct file_name_attr, file_name) + + ie->key.file_name.file_name_length * sizeof(__le16)) > + le16_to_cpu(ie->key_length)) { ntfs_error(vol->sb, "File name overflow from index entry in inode %lld\n", (long long)inum); @@ -99,12 +101,30 @@ static s64 ntfs_ib_pos_to_vcn(struct ntfs_index_context *icx, s64 pos) return pos >> icx->vcn_size_bits; } +/* Open the index allocation inode if no earlier step of the operation did. */ +static int ntfs_icx_ia_ensure(struct ntfs_index_context *icx) +{ + if (!icx->ia_ni) { + icx->ia_ni = ntfs_ia_open(icx, icx->idx_ni); + if (!icx->ia_ni) + return -EIO; + } + /* Without $INDEX_ALLOCATION the index inode is an empty resident stub. */ + if (!NInoNonResident(icx->ia_ni)) + return -EIO; + return 0; +} + static int ntfs_ib_write(struct ntfs_index_context *icx, struct index_block *ib) { s64 ret, vcn = le64_to_cpu(ib->index_block_vcn); ntfs_debug("vcn: %lld\n", vcn); + ret = ntfs_icx_ia_ensure(icx); + if (ret) + return ret; + ret = pre_write_mst_fixup((struct ntfs_record *)ib, icx->block_size); if (ret) return -EIO; @@ -805,6 +825,10 @@ static int ntfs_ib_read(struct ntfs_index_context *icx, s64 vcn, struct index_bl ntfs_debug("vcn: %lld\n", vcn); + ret = ntfs_icx_ia_ensure(icx); + if (ret) + return ret; + pos = ntfs_ib_vcn_to_pos(icx, vcn); ret = ntfs_inode_attr_pread(VFS_I(icx->ia_ni), pos, icx->block_size, (u8 *)dst); diff --git a/fs/ntfs/inode.c b/fs/ntfs/inode.c index 62dd5bd5bb81..b799e6668a69 100644 --- a/fs/ntfs/inode.c +++ b/fs/ntfs/inode.c @@ -2596,7 +2596,7 @@ static int __ntfs_extend_initialized_size(struct inode *vi, if (old_init_size < offset) { err = iomap_zero_range(vi, old_init_size, offset - old_init_size, - NULL, &ntfs_seek_iomap_ops, + NULL, ntfs_seek_iomap_next, &ntfs_iomap_folio_ops, NULL); if (err) goto out; diff --git a/fs/ntfs/iomap.c b/fs/ntfs/iomap.c index 6e51cce3aeba..b459d3e6e5fa 100644 --- a/fs/ntfs/iomap.c +++ b/fs/ntfs/iomap.c @@ -293,12 +293,8 @@ static int ntfs_read_iomap_end(struct inode *inode, loff_t pos, loff_t length, return written; } -static DEFINE_IOMAP_ITER_NEXT_END(ntfs_read_iomap_next, - ntfs_read_iomap_begin, ntfs_read_iomap_end); - -const struct iomap_ops ntfs_read_iomap_ops = { - .iomap_next = ntfs_read_iomap_next, -}; +DEFINE_IOMAP_ITER_NEXT_END(ntfs_read_iomap_next, ntfs_read_iomap_begin, + ntfs_read_iomap_end); /* * Check that the cached iomap still matches the NTFS runlist before @@ -351,15 +347,7 @@ static int ntfs_zero_read_iomap_end(struct inode *inode, loff_t pos, loff_t leng static DEFINE_IOMAP_ITER_NEXT_END(ntfs_zero_read_iomap_next, ntfs_seek_iomap_begin, ntfs_zero_read_iomap_end); -static const struct iomap_ops ntfs_zero_read_iomap_ops = { - .iomap_next = ntfs_zero_read_iomap_next, -}; - -static DEFINE_IOMAP_ITER_NEXT(ntfs_seek_iomap_next, ntfs_seek_iomap_begin); - -const struct iomap_ops ntfs_seek_iomap_ops = { - .iomap_next = ntfs_seek_iomap_next, -}; +DEFINE_IOMAP_ITER_NEXT(ntfs_seek_iomap_next, ntfs_seek_iomap_begin); int ntfs_dio_zero_range(struct inode *inode, loff_t offset, loff_t length) { @@ -378,7 +366,7 @@ static int ntfs_zero_range(struct inode *inode, loff_t offset, loff_t length) return iomap_zero_range(inode, offset, length, NULL, - &ntfs_zero_read_iomap_ops, + ntfs_zero_read_iomap_next, &ntfs_zero_iomap_folio_ops, NULL); } @@ -499,7 +487,7 @@ remap_rl: ntfs_error(vol->sb, "Failed to merge runlists"); up_write(&ni->runlist.lock); mutex_unlock(&mrec_ni->mrec_lock); - kvfree(rlc); + kfree(rlc); return PTR_ERR(rl); } @@ -782,12 +770,8 @@ static int ntfs_write_iomap_end(struct inode *inode, loff_t pos, loff_t length, return written; } -static DEFINE_IOMAP_ITER_NEXT_END(ntfs_write_iomap_next, - ntfs_write_iomap_begin, ntfs_write_iomap_end); - -const struct iomap_ops ntfs_write_iomap_ops = { - .iomap_next = ntfs_write_iomap_next, -}; +DEFINE_IOMAP_ITER_NEXT_END(ntfs_write_iomap_next, ntfs_write_iomap_begin, + ntfs_write_iomap_end); static int ntfs_page_mkwrite_iomap_begin(struct inode *inode, loff_t offset, loff_t length, unsigned int flags, @@ -797,13 +781,9 @@ static int ntfs_page_mkwrite_iomap_begin(struct inode *inode, loff_t offset, NTFS_IOMAP_FLAGS_MKWRITE); } -static DEFINE_IOMAP_ITER_NEXT_END(ntfs_page_mkwrite_iomap_next, +DEFINE_IOMAP_ITER_NEXT_END(ntfs_page_mkwrite_iomap_next, ntfs_page_mkwrite_iomap_begin, ntfs_write_iomap_end); -const struct iomap_ops ntfs_page_mkwrite_iomap_ops = { - .iomap_next = ntfs_page_mkwrite_iomap_next, -}; - static int ntfs_dio_iomap_begin(struct inode *inode, loff_t offset, loff_t length, unsigned int flags, struct iomap *iomap, struct iomap *srcmap) @@ -812,12 +792,8 @@ static int ntfs_dio_iomap_begin(struct inode *inode, loff_t offset, NTFS_IOMAP_FLAGS_DIO); } -static DEFINE_IOMAP_ITER_NEXT_END(ntfs_dio_iomap_next, - ntfs_dio_iomap_begin, ntfs_write_iomap_end); - -const struct iomap_ops ntfs_dio_iomap_ops = { - .iomap_next = ntfs_dio_iomap_next, -}; +DEFINE_IOMAP_ITER_NEXT_END(ntfs_dio_iomap_next, ntfs_dio_iomap_begin, + ntfs_write_iomap_end); static ssize_t ntfs_writeback_range(struct iomap_writepage_ctx *wpc, struct folio *folio, u64 offset, unsigned int len, u64 end_pos) diff --git a/fs/ntfs/iomap.h b/fs/ntfs/iomap.h index 3abc1d493e91..fec8b907c48f 100644 --- a/fs/ntfs/iomap.h +++ b/fs/ntfs/iomap.h @@ -12,11 +12,11 @@ #include "volume.h" #include "inode.h" -extern const struct iomap_ops ntfs_write_iomap_ops; -extern const struct iomap_ops ntfs_read_iomap_ops; -extern const struct iomap_ops ntfs_seek_iomap_ops; -extern const struct iomap_ops ntfs_page_mkwrite_iomap_ops; -extern const struct iomap_ops ntfs_dio_iomap_ops; +DECLARE_IOMAP_ITER_NEXT(ntfs_write_iomap_next); +DECLARE_IOMAP_ITER_NEXT(ntfs_read_iomap_next); +DECLARE_IOMAP_ITER_NEXT(ntfs_seek_iomap_next); +DECLARE_IOMAP_ITER_NEXT(ntfs_page_mkwrite_iomap_next); +DECLARE_IOMAP_ITER_NEXT(ntfs_dio_iomap_next); extern const struct iomap_writeback_ops ntfs_writeback_ops; extern const struct iomap_write_ops ntfs_iomap_folio_ops; extern int ntfs_dio_zero_range(struct inode *inode, loff_t offset, loff_t length); diff --git a/fs/ntfs/named_stream.c b/fs/ntfs/named_stream.c index 95a3c05f9821..70c589207713 100644 --- a/fs/ntfs/named_stream.c +++ b/fs/ntfs/named_stream.c @@ -1632,6 +1632,10 @@ int ntfs_ioctl_list_streams(struct file *filp, unsigned long arg) ubuf = (void __user *)arg + sizeof(hdr); mutex_lock(&ni->mrec_lock); + if (NInoBeingDeleted(ni) || !inode->i_nlink) { + mutex_unlock(&ni->mrec_lock); + return -ENOENT; + } actx = ntfs_attr_get_search_ctx(ni, NULL); if (!actx) { mutex_unlock(&ni->mrec_lock); @@ -1731,7 +1735,7 @@ int ntfs_ioctl_list_streams(struct file *filp, unsigned long arg) } entry_size = ALIGN(name_offset + name_len, 8); - if (offset > required - entry_size) { + if (offset > required || entry_size > required - offset) { ret = -EOVERFLOW; kfree(sn); sn = NULL; diff --git a/fs/ntfs3/file.c b/fs/ntfs3/file.c index 1624f9b014e0..6c84a3e1c7fe 100644 --- a/fs/ntfs3/file.c +++ b/fs/ntfs3/file.c @@ -319,7 +319,7 @@ static int ntfs_extend_initialized_size(struct file *file, } err = iomap_zero_range(inode, valid, new_valid - valid, NULL, - &ntfs_iomap_ops, &ntfs_iomap_folio_ops, NULL); + ntfs_iomap_next, &ntfs_iomap_folio_ops, NULL); if (err) { ni->i_valid = valid; ntfs_inode_warn(inode, @@ -558,7 +558,7 @@ static long ntfs_fallocate(struct file *file, int mode, loff_t vbo, loff_t len) /* Zero head of punch. */ if (tmp > from) { err = iomap_zero_range(inode, from, tmp - from, NULL, - &ntfs_iomap_ops, + ntfs_iomap_next, &ntfs_iomap_folio_ops, NULL); if (err) goto out; @@ -576,7 +576,7 @@ static long ntfs_fallocate(struct file *file, int mode, loff_t vbo, loff_t len) /* Zero tail of punch. */ if (vbo < end_a && end_a < end) { err = iomap_zero_range(inode, end_a, end - end_a, NULL, - &ntfs_iomap_ops, + ntfs_iomap_next, &ntfs_iomap_folio_ops, NULL); if (err) goto out; @@ -896,7 +896,7 @@ static ssize_t ntfs_file_read_iter(struct kiocb *iocb, struct iov_iter *iter) goto out; } - ret = iomap_dio_rw(iocb, iter, &ntfs_iomap_ops, NULL, dio_flags, + ret = iomap_dio_rw(iocb, iter, ntfs_iomap_next, NULL, dio_flags, NULL, 0); if (ret <= 0) @@ -1313,7 +1313,7 @@ static ssize_t ntfs_file_write_iter(struct kiocb *iocb, struct iov_iter *from) !ntfs_should_use_dio(iocb, from)) { iocb->ki_flags &= ~IOCB_DIRECT; - ret = iomap_file_buffered_write(iocb, from, &ntfs_iomap_ops, + ret = iomap_file_buffered_write(iocb, from, ntfs_iomap_next, &ntfs_iomap_folio_ops, NULL); inode_unlock(inode); @@ -1330,7 +1330,7 @@ static ssize_t ntfs_file_write_iter(struct kiocb *iocb, struct iov_iter *from) goto out; } - ret = iomap_dio_rw(iocb, from, &ntfs_iomap_ops, NULL, + ret = iomap_dio_rw(iocb, from, ntfs_iomap_next, NULL, IOMAP_DIO_FORCE_WAIT, NULL, 0); if (ret == -ENOTBLK) { @@ -1343,7 +1343,7 @@ static ssize_t ntfs_file_write_iter(struct kiocb *iocb, struct iov_iter *from) vbo = iocb->ki_pos; iocb->ki_flags &= ~IOCB_DIRECT; - err = iomap_file_buffered_write(iocb, from, &ntfs_iomap_ops, + err = iomap_file_buffered_write(iocb, from, ntfs_iomap_next, &ntfs_iomap_folio_ops, NULL); if (err < 0) { ret = err; @@ -1493,7 +1493,7 @@ int ntfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo, inode_lock_shared(inode); - err = iomap_fiemap(inode, fieinfo, start, len, &ntfs_iomap_ops); + err = iomap_fiemap(inode, fieinfo, start, len, ntfs_iomap_next); inode_unlock_shared(inode); return err; diff --git a/fs/ntfs3/inode.c b/fs/ntfs3/inode.c index 43d5e83403aa..45f894d182dd 100644 --- a/fs/ntfs3/inode.c +++ b/fs/ntfs3/inode.c @@ -788,7 +788,7 @@ static sector_t ntfs_bmap(struct address_space *mapping, sector_t block) ni_allocate_da_blocks(ni); } - return iomap_bmap(mapping, block, &ntfs_iomap_ops); + return iomap_bmap(mapping, block, ntfs_iomap_next); } static void ntfs_iomap_read_end_io(struct bio *bio) @@ -860,7 +860,7 @@ static int ntfs_read_folio(struct file *file, struct folio *folio) return err; } - iomap_read_folio(&ntfs_iomap_ops, &ctx, NULL); + iomap_read_folio(ntfs_iomap_next, &ctx, NULL); return 0; } @@ -884,7 +884,7 @@ static void ntfs_readahead(struct readahead_control *rac) return; } - iomap_readahead(&ntfs_iomap_ops, &ctx, NULL); + iomap_readahead(ntfs_iomap_next, &ctx, NULL); } int ntfs_set_size(struct inode *inode, u64 new_size) @@ -2336,12 +2336,7 @@ const struct address_space_operations ntfs_aops_cmpr = { .invalidate_folio = iomap_invalidate_folio, }; -static DEFINE_IOMAP_ITER_NEXT_END(ntfs_iomap_next, ntfs_iomap_begin, - ntfs_iomap_end); - -const struct iomap_ops ntfs_iomap_ops = { - .iomap_next = ntfs_iomap_next, -}; +DEFINE_IOMAP_ITER_NEXT_END(ntfs_iomap_next, ntfs_iomap_begin, ntfs_iomap_end); const struct iomap_write_ops ntfs_iomap_folio_ops = { .put_folio = ntfs_iomap_put_folio, diff --git a/fs/ntfs3/ntfs_fs.h b/fs/ntfs3/ntfs_fs.h index f400cf94d05b..16e7eab3e16d 100644 --- a/fs/ntfs3/ntfs_fs.h +++ b/fs/ntfs3/ntfs_fs.h @@ -12,6 +12,7 @@ #include <linux/blkdev.h> #include <linux/buffer_head.h> #include <linux/fs.h> +#include <linux/iomap.h> #include <linux/highmem.h> #include <linux/kernel.h> #include <linux/hex.h> @@ -814,7 +815,7 @@ int ntfs_create_inode(const struct mnt_idmap *idmap, struct inode *dir, int ntfs_link_inode(struct inode *inode, struct dentry *dentry); int ntfs_unlink_inode(struct inode *dir, const struct dentry *dentry); void ntfs_evict_inode(struct inode *inode); -extern const struct iomap_ops ntfs_iomap_ops; +DECLARE_IOMAP_ITER_NEXT(ntfs_iomap_next); extern const struct iomap_write_ops ntfs_iomap_folio_ops; extern const struct inode_operations ntfs_link_inode_operations; extern const struct address_space_operations ntfs_aops; diff --git a/fs/overlayfs/dir.c b/fs/overlayfs/dir.c index e0a164e22d67..8fec18dc5fc7 100644 --- a/fs/overlayfs/dir.c +++ b/fs/overlayfs/dir.c @@ -368,7 +368,7 @@ static bool ovl_type_origin(struct dentry *dentry) } static int ovl_create_upper(struct dentry *dentry, struct inode *inode, - struct ovl_cattr *attr) + struct ovl_cattr *attr, bool origin) { struct ovl_fs *ofs = OVL_FS(dentry->d_sb); struct dentry *upperdir = ovl_dentry_upper(dentry->d_parent); @@ -393,7 +393,7 @@ static int ovl_create_upper(struct dentry *dentry, struct inode *inode, ovl_set_opaque(dentry, newdentry); } - ovl_dir_modified(dentry->d_parent, false); + ovl_dir_modified(dentry->d_parent, origin); err = ovl_instantiate(dentry, inode, newdentry, !!attr->hardlink, NULL); if (err) goto out_cleanup; @@ -491,7 +491,7 @@ static int ovl_set_upper_acl(struct ovl_fs *ofs, struct dentry *upperdentry, } static int ovl_create_over_whiteout(struct dentry *dentry, struct inode *inode, - struct ovl_cattr *cattr) + struct ovl_cattr *cattr, bool origin) { struct ovl_fs *ofs = OVL_FS(dentry->d_sb); struct dentry *workdir = ovl_workdir(dentry); @@ -582,7 +582,7 @@ static int ovl_create_over_whiteout(struct dentry *dentry, struct inode *inode, if (err) goto out_cleanup_unlocked; } - ovl_dir_modified(dentry->d_parent, false); + ovl_dir_modified(dentry->d_parent, origin); err = ovl_instantiate(dentry, inode, newdentry, hardlink, NULL); if (err) { ovl_cleanup(ofs, upperdir, newdentry); @@ -647,12 +647,12 @@ DEFINE_CLASS(ovl_override_creator_creds, static int ovl_create_handle_whiteouts(struct dentry *dentry, struct inode *inode, - struct ovl_cattr *attr) + struct ovl_cattr *attr, bool origin) { if (!ovl_dentry_is_whiteout(dentry)) - return ovl_create_upper(dentry, inode, attr); + return ovl_create_upper(dentry, inode, attr, origin); - return ovl_create_over_whiteout(dentry, inode, attr); + return ovl_create_over_whiteout(dentry, inode, attr, origin); } static int ovl_create_or_link(struct dentry *dentry, struct inode *inode, @@ -687,12 +687,14 @@ static int ovl_create_or_link(struct dentry *dentry, struct inode *inode, */ if (attr->hardlink) - return ovl_create_handle_whiteouts(dentry, inode, attr); + return ovl_create_handle_whiteouts(dentry, inode, attr, + origin); scoped_class(ovl_override_creator_creds, cred, original_creds, dentry, inode, attr->mode) { if (IS_ERR(cred)) return PTR_ERR(cred); - return ovl_create_handle_whiteouts(dentry, inode, attr); + return ovl_create_handle_whiteouts(dentry, inode, attr, + origin); } } return err; diff --git a/fs/overlayfs/namei.c b/fs/overlayfs/namei.c index 64d63b260709..ddf60254888a 100644 --- a/fs/overlayfs/namei.c +++ b/fs/overlayfs/namei.c @@ -27,6 +27,7 @@ struct ovl_lookup_data { bool last; char *redirect; char *upperredirect; + char *lowerdata_redirect; int metacopy; /* Referring to last redirect xattr */ bool absolute_redirect; @@ -39,13 +40,12 @@ static int ovl_check_redirect(const struct path *path, struct ovl_lookup_data *d char *buf; struct ovl_fs *ofs = OVL_FS(d->sb); - d->absolute_redirect = false; buf = ovl_get_redirect_xattr(ofs, path, prelen + strlen(post)); if (IS_ERR_OR_NULL(buf)) return PTR_ERR(buf); - if (buf[0] == '/') { - d->absolute_redirect = true; + d->absolute_redirect = buf[0] == '/'; + if (d->absolute_redirect) { /* * One of the ancestor path elements in an absolute path * lookup in ovl_lookup_layer() could have been opaque and @@ -1047,6 +1047,14 @@ out: out_err: pr_warn_ratelimited("lazy lowerdata lookup failed (%pd2, err=%i)\n", dentry, err); + /* + * The data of a metacopy file is missing or is not a regular file in + * the data-only layers: the layers are corrupted. Do not return the + * error of the lookup (e.g. ENOENT) to the caller, it would make the + * file look like it does not exist. + */ + if (err != -ENOMEM) + err = -EIO; goto out; } @@ -1079,7 +1087,8 @@ static bool ovl_check_follow_redirect(struct ovl_lookup_data *d) pr_warn_ratelimited("refusing to follow metacopy origin for (%pd2)\n", d->dentry); return false; } - if ((d->redirect || d->upperredirect) && !ovl_redirect_follow(ofs)) { + /* Check follow to lower layer, redirects to lowerdata are not checked here */ + if ((d->redirect || d->upperredirect) && !ovl_redirect_follow_lower(ofs)) { pr_warn_ratelimited("refusing to follow redirect for (%pd2)\n", d->dentry); return false; } @@ -1097,13 +1106,26 @@ struct ovl_lookup_ctx { unsigned int ctr; }; +/* + * Without metacopy=on, the absolute redirect of a lower metacopy file is + * followed only into the data-only layers. + */ +static bool ovl_is_lowerdata_redirect(struct ovl_lookup_ctx *ctx, + struct ovl_lookup_data *d) +{ + struct ovl_fs *ofs = OVL_FS(d->sb); + + return ofs->numdatalayer && !ofs->config.metacopy && ctx->ctr && + d->metacopy && d->absolute_redirect; +} + static int ovl_lookup_layers(struct ovl_lookup_ctx *ctx, struct ovl_lookup_data *d) { struct dentry *dentry = ctx->dentry; struct ovl_fs *ofs = OVL_FS(dentry->d_sb); struct ovl_entry *poe = OVL_E(dentry->d_parent); struct ovl_entry *roe = OVL_E(dentry->d_sb->s_root); - bool check_redirect = (ovl_redirect_follow(ofs) || ofs->numdatalayer); + bool check_redirect = ovl_redirect_follow(ofs); struct dentry *upperdir; struct dentry *this; struct dentry *origin = NULL; @@ -1234,6 +1256,10 @@ static int ovl_lookup_layers(struct ovl_lookup_ctx *ctx, struct ovl_lookup_data ctx->ctr++; } + /* Lookup of lowerdata in the data-only layers only */ + if (ovl_is_lowerdata_redirect(ctx, d)) + d->stop = true; + if (d->stop) break; @@ -1251,6 +1277,8 @@ static int ovl_lookup_layers(struct ovl_lookup_ctx *ctx, struct ovl_lookup_data if (d->metacopy && ctx->ctr && ofs->numdatalayer && d->absolute_redirect) { d->metacopy = 0; ctx->ctr++; + d->lowerdata_redirect = d->redirect; + d->redirect = NULL; } else if (!ovl_check_follow_redirect(d)) { err = -EPERM; return err; @@ -1367,24 +1395,32 @@ static int ovl_lookup_layers(struct ovl_lookup_ctx *ctx, struct ovl_lookup_data }; /* Store lowerdata redirect for lazy lookup */ - if (ctx->ctr > 1 && !d->is_dir && !ctx->stack[ctx->ctr - 1].dentry) { - oip.lowerdata_redirect = d->redirect; - d->redirect = NULL; - } + if (d->lowerdata_redirect) + oip.lowerdata_redirect = d->lowerdata_redirect; inode = ovl_get_inode(dentry->d_sb, &oip); if (IS_ERR(inode)) return PTR_ERR(inode); + d->lowerdata_redirect = NULL; + ctx->inode = inode; if (ctx->upperdentry && !uppermetacopy) ovl_set_flag(OVL_UPPERDATA, ctx->inode); if (metacopy_size > OVL_METACOPY_MIN_SIZE) ovl_set_flag(OVL_HAS_DIGEST, ctx->inode); - } - ovl_dentry_init_reval(dentry, ctx->upperdentry, OVL_I_E(ctx->inode)); + /* + * ovl_get_inode() puts ctx->upperdentry if it finds a cached + * inode, e.g. for another hard link, so use the upper dentry + * of the inode. + */ + ovl_dentry_init_reval(dentry, ovl_i_dentry_upper(inode), + OVL_I_E(inode)); + } else { + ovl_dentry_init_reval(dentry, NULL, NULL); + } return 0; } @@ -1394,7 +1430,7 @@ struct dentry *ovl_lookup(struct inode *dir, struct dentry *dentry, { struct ovl_fs *ofs = OVL_FS(dentry->d_sb); struct ovl_entry *poe = OVL_E(dentry->d_parent); - bool check_redirect = (ovl_redirect_follow(ofs) || ofs->numdatalayer); + bool check_redirect = ovl_redirect_follow(ofs); int err; struct ovl_lookup_ctx ctx = { .dentry = dentry, @@ -1419,6 +1455,7 @@ struct dentry *ovl_lookup(struct inode *dir, struct dentry *dentry, dput(ctx.index); ovl_stack_free(ctx.stack, ctx.ctr); kfree(d.redirect); + kfree(d.lowerdata_redirect); if (err) { ovl_free_entry(ctx.oe); diff --git a/fs/overlayfs/overlayfs.h b/fs/overlayfs/overlayfs.h index e42543d4c108..646f8ffc40ae 100644 --- a/fs/overlayfs/overlayfs.h +++ b/fs/overlayfs/overlayfs.h @@ -76,9 +76,15 @@ enum ovl_entry_flag { }; enum { - OVL_REDIRECT_OFF, /* "off" mode is never used. In effect */ - OVL_REDIRECT_FOLLOW, /* ...it translates to either "follow" */ - OVL_REDIRECT_NOFOLLOW, /* ...or "nofollow". */ + /* + * "off" mode is never used after mount options are verified. + * In effect it translates to either "follow", "nofollow" or + * "followdata" (with data-only layers). + */ + OVL_REDIRECT_OFF, + OVL_REDIRECT_FOLLOW, + OVL_REDIRECT_FOLLOWDATA, + OVL_REDIRECT_NOFOLLOW, OVL_REDIRECT_ON, }; @@ -582,6 +588,7 @@ static inline int ovl_set_impure_dir(struct dentry *dentry) bool ovl_inuse_trylock(struct dentry *dentry); void ovl_inuse_unlock(struct dentry *dentry); bool ovl_is_inuse(struct dentry *dentry); +void ovl_inuse_unlock_all(struct ovl_fs *ofs); bool ovl_need_index(struct dentry *dentry); int ovl_nlink_start(struct dentry *dentry); void ovl_nlink_end(struct dentry *dentry); @@ -632,11 +639,20 @@ static inline char ovl_get_opaquedir_val(struct ovl_fs *ofs, return ovl_get_dir_xattr_val(ofs, path, OVL_XATTR_OPAQUE); } +/* Are redirects followed into lower layers? */ +static inline bool ovl_redirect_follow_lower(struct ovl_fs *ofs) +{ + return ofs->config.redirect_mode == OVL_REDIRECT_FOLLOW || + ofs->config.redirect_mode == OVL_REDIRECT_ON; +} + +/* Are redirects followed into lower or lowerdata layers? */ static inline bool ovl_redirect_follow(struct ovl_fs *ofs) { return ofs->config.redirect_mode != OVL_REDIRECT_NOFOLLOW; } +/* Are redirects created in upper dir? */ static inline bool ovl_redirect_dir(struct ovl_fs *ofs) { return ofs->config.redirect_mode == OVL_REDIRECT_ON; diff --git a/fs/overlayfs/ovl_entry.h b/fs/overlayfs/ovl_entry.h index ac07e8769f9b..5b2f1b930daa 100644 --- a/fs/overlayfs/ovl_entry.h +++ b/fs/overlayfs/ovl_entry.h @@ -24,6 +24,8 @@ struct ovl_config { struct ovl_sb { struct super_block *sb; dev_t pseudo_dev; + /* Idmap of the first lower layer on this fs */ + const struct mnt_idmap *lower_idmap; /* Unusable (conflicting) uuid */ bool bad_uuid; /* Used as a lower layer (but maybe also as upper) */ diff --git a/fs/overlayfs/params.c b/fs/overlayfs/params.c index 5a15e5478a6b..d1ca4a9094f2 100644 --- a/fs/overlayfs/params.c +++ b/fs/overlayfs/params.c @@ -107,21 +107,40 @@ static int ovl_xino_def(void) const struct constant_table ovl_parameter_redirect_dir[] = { { "off", OVL_REDIRECT_OFF }, { "follow", OVL_REDIRECT_FOLLOW }, + { "followdata", OVL_REDIRECT_FOLLOWDATA }, { "nofollow", OVL_REDIRECT_NOFOLLOW }, { "on", OVL_REDIRECT_ON }, {} }; -static const char *ovl_redirect_mode(struct ovl_config *config) +static const char *ovl_redirect_mode_name(int redirect_mode) { - return ovl_parameter_redirect_dir[config->redirect_mode].name; + return ovl_parameter_redirect_dir[redirect_mode].name; } +const char *ovl_redirect_mode(struct ovl_config *config) +{ + return ovl_redirect_mode_name(config->redirect_mode); +} + +int ovl_redirect_follow_mode(bool follow_lower, size_t nr_data) +{ + if (ovl_redirect_always_follow && follow_lower) + return OVL_REDIRECT_FOLLOW; + + /* Data-only layers cannot be used without following redirects to them */ + return nr_data ? OVL_REDIRECT_FOLLOWDATA : OVL_REDIRECT_NOFOLLOW; +} + +/* + * The default for show_options() is resolved as if there are no data-only layers, + * so that redirect_dir=followdata, which is auto selected with data-only layers, + * is displayed in mount options. + */ static int ovl_redirect_mode_def(void) { - return ovl_redirect_dir_def ? OVL_REDIRECT_ON : - ovl_redirect_always_follow ? OVL_REDIRECT_FOLLOW : - OVL_REDIRECT_NOFOLLOW; + return ovl_redirect_dir_def ? OVL_REDIRECT_ON : + ovl_redirect_follow_mode(true, 0); } static const struct constant_table ovl_parameter_verity[] = { @@ -659,11 +678,6 @@ static int ovl_parse_param(struct fs_context *fc, struct fs_parameter *param) break; case Opt_redirect_dir: config->redirect_mode = result.uint_32; - if (config->redirect_mode == OVL_REDIRECT_OFF) { - config->redirect_mode = ovl_redirect_always_follow ? - OVL_REDIRECT_FOLLOW : - OVL_REDIRECT_NOFOLLOW; - } ctx->set.redirect = true; break; case Opt_index: @@ -819,7 +833,13 @@ int ovl_init_fs_context(struct fs_context *fc) if (!ofs) goto out_err; - ofs->config.redirect_mode = ovl_redirect_mode_def(); + /* + * The module default determines only if new redirects are created in + * upper dir. If they are not, the redirect follow mode will be + * determined after parsing mount options. + */ + ofs->config.redirect_mode = ovl_redirect_dir_def ? + OVL_REDIRECT_ON : OVL_REDIRECT_OFF; ofs->config.index = ovl_index_def; ofs->config.uuid = ovl_uuid_def(); ofs->config.nfs_export = ovl_nfs_export_def; @@ -845,15 +865,12 @@ void ovl_free_fs(struct ovl_fs *ofs) struct vfsmount **mounts; unsigned i; + ovl_inuse_unlock_all(ofs); iput(ofs->workbasedir_trap); iput(ofs->workdir_trap); dput(ofs->whiteout); dput(ofs->workdir); - if (ofs->workdir_locked) - ovl_inuse_unlock(ofs->workbasedir); dput(ofs->workbasedir); - if (ofs->upperdir_locked) - ovl_inuse_unlock(ovl_upper_mnt(ofs)->mnt_root); /* Reuse ofs->config.lowerdirs as a vfsmount array before freeing it */ mounts = (struct vfsmount **) ofs->config.lowerdirs; @@ -880,6 +897,11 @@ int ovl_fs_params_verify(const struct ovl_fs_context *ctx, struct ovl_config *config) { struct ovl_opt_set set = ctx->set; + /* The requested redirect_dir=, for reporting conflicts with it */ + int redirect_opt = config->redirect_mode; + /* The redirect follow mode for redirect_dir=off and for the default */ + int follow_mode = ovl_redirect_follow_mode(!config->userxattr, + ctx->nr_data); /* Workdir/index are useless in non-upper mount */ if (!config->upperdir) { @@ -907,6 +929,13 @@ int ovl_fs_params_verify(const struct ovl_fs_context *ctx, } /* + * Resolve redirect_dir=off to the default redirect follow mode. + * With userxattr, redirects are not followed to lower by default. + */ + if (config->redirect_mode == OVL_REDIRECT_OFF) + config->redirect_mode = follow_mode; + + /* * This is to make the logic below simpler. It doesn't make any other * difference, since redirect_dir=on is only used for upper. */ @@ -917,7 +946,7 @@ int ovl_fs_params_verify(const struct ovl_fs_context *ctx, if (config->metacopy && config->redirect_mode != OVL_REDIRECT_ON) { if (set.metacopy && set.redirect) { pr_err("conflicting options: metacopy=on,redirect_dir=%s\n", - ovl_redirect_mode(config)); + ovl_redirect_mode_name(redirect_opt)); return -EINVAL; } if (set.redirect) { @@ -926,7 +955,7 @@ int ovl_fs_params_verify(const struct ovl_fs_context *ctx, * in this conflict. */ pr_info("disabling metacopy due to redirect_dir=%s\n", - ovl_redirect_mode(config)); + ovl_redirect_mode_name(redirect_opt)); config->metacopy = false; } else { /* Automatically enable redirect otherwise. */ @@ -934,6 +963,16 @@ int ovl_fs_params_verify(const struct ovl_fs_context *ctx, } } + /* Resolve nfs_export -> !data-only layers dependency */ + if (config->nfs_export && ctx->nr_data) { + if (set.nfs_export) { + pr_err("NFS export is not supported with data-only layers\n"); + return -EINVAL; + } + pr_info("disabling nfs_export due to data-only layers\n"); + config->nfs_export = false; + } + /* Resolve nfs_export -> index dependency */ if (config->nfs_export && !config->index) { if (!config->upperdir && @@ -991,9 +1030,10 @@ int ovl_fs_params_verify(const struct ovl_fs_context *ctx, /* Resolve userxattr -> !redirect && !metacopy dependency */ if (config->userxattr) { if (set.redirect && - config->redirect_mode != OVL_REDIRECT_NOFOLLOW) { + config->redirect_mode != OVL_REDIRECT_NOFOLLOW && + config->redirect_mode != OVL_REDIRECT_FOLLOWDATA) { pr_err("conflicting options: userxattr,redirect_dir=%s\n", - ovl_redirect_mode(config)); + ovl_redirect_mode_name(redirect_opt)); return -EINVAL; } if (config->metacopy && set.metacopy) { @@ -1006,10 +1046,21 @@ int ovl_fs_params_verify(const struct ovl_fs_context *ctx, * options must be explicitly enabled if used together with * userxattr. */ - config->redirect_mode = OVL_REDIRECT_NOFOLLOW; + if (!set.redirect) + config->redirect_mode = follow_mode; config->metacopy = false; } + /* Data-only layers are reached through redirects */ + if (ctx->nr_data && config->redirect_mode == OVL_REDIRECT_NOFOLLOW) { + pr_err("redirect_dir=nofollow is not supported with data-only layers\n"); + return -EINVAL; + } + if (!ctx->nr_data && config->redirect_mode == OVL_REDIRECT_FOLLOWDATA) { + pr_err("redirect_dir=followdata requires data-only layers\n"); + return -EINVAL; + } + /* * Fail if we don't have trusted xattr capability and a feature was * explicitly requested that requires them. diff --git a/fs/overlayfs/params.h b/fs/overlayfs/params.h index ffd53cdd8482..3a514a21b14c 100644 --- a/fs/overlayfs/params.h +++ b/fs/overlayfs/params.h @@ -42,3 +42,5 @@ int ovl_fs_params_verify(const struct ovl_fs_context *ctx, struct ovl_config *config); int ovl_show_options(struct seq_file *m, struct dentry *dentry); const char *ovl_xino_mode(struct ovl_config *config); +const char *ovl_redirect_mode(struct ovl_config *config); +int ovl_redirect_follow_mode(bool follow_lower, size_t nr_data); diff --git a/fs/overlayfs/super.c b/fs/overlayfs/super.c index 8bc970748b96..e61aab1999d3 100644 --- a/fs/overlayfs/super.c +++ b/fs/overlayfs/super.c @@ -701,7 +701,7 @@ static int ovl_create_volatile_dirty(struct ovl_fs *ofs) } static int ovl_make_workdir(struct super_block *sb, struct ovl_fs *ofs, - const struct path *workpath) + const struct path *workpath, size_t nr_data) { struct vfsmount *mnt = ovl_upper_mnt(ofs); struct dentry *workdir; @@ -765,9 +765,11 @@ static int ovl_make_workdir(struct super_block *sb, struct ovl_fs *ofs, if (err) { pr_warn("failed to set xattr on upper\n"); ofs->noxattr = true; - if (ovl_redirect_follow(ofs)) { - ofs->config.redirect_mode = OVL_REDIRECT_NOFOLLOW; - pr_warn("...falling back to redirect_dir=nofollow.\n"); + if (ovl_redirect_follow_lower(ofs)) { + ofs->config.redirect_mode = + ovl_redirect_follow_mode(false, nr_data); + pr_warn("...falling back to redirect_dir=%s.\n", + ovl_redirect_mode(&ofs->config)); } if (ofs->config.metacopy) { ofs->config.metacopy = false; @@ -844,7 +846,7 @@ out: static int ovl_get_workdir(struct super_block *sb, struct ovl_fs *ofs, const struct path *upperpath, - const struct path *workpath) + const struct path *workpath, size_t nr_data) { int err; @@ -873,7 +875,7 @@ static int ovl_get_workdir(struct super_block *sb, struct ovl_fs *ofs, if (err) return err; - return ovl_make_workdir(sb, ofs, workpath); + return ovl_make_workdir(sb, ofs, workpath, nr_data); } static int ovl_get_indexdir(struct super_block *sb, struct ovl_fs *ofs, @@ -1142,6 +1144,29 @@ static int ovl_get_layers(struct super_block *sb, struct ovl_fs *ofs, } /* + * Lower file handles identify the lower fs, but not the layer, + * so with different idmaps on the same lower fs, index and + * nfs_export may decode a file handle through a layer with the + * wrong idmap. Following copy up origin without index is only + * used for st_ino, which does not depend on the idmap. + */ + if (i < nr_merged_lower && + (ofs->config.index || ofs->config.nfs_export)) { + const struct mnt_idmap *idmap = mnt_idmap(mnt); + struct ovl_sb *fs = &ofs->fs[fsid]; + + if (!fs->lower_idmap) { + fs->lower_idmap = idmap; + } else if (fs->lower_idmap != idmap) { + pr_err("lower layer '%pd2' conflicts with idmap of another lower layer on the same fs, mount with '-o index=off,nfs_export=off' to override.\n", + l->path.dentry); + iput(trap); + kern_unmount(mnt); + return -EINVAL; + } + } + + /* * Make lower layers R/O. That way fchmod/fchown on lower file * will fail instead of modifying lower fs. */ @@ -1485,7 +1510,8 @@ static int ovl_fill_super_creds(struct fs_context *fc, struct super_block *sb) } } - err = ovl_get_workdir(sb, ofs, &ctx->upper, &ctx->work); + err = ovl_get_workdir(sb, ofs, &ctx->upper, &ctx->work, + ctx->nr_data); if (err) return err; @@ -1619,13 +1645,23 @@ out_err: return err; } +static void ovl_kill_sb(struct super_block *sb) +{ + struct ovl_fs *ofs = OVL_FS(sb); + + /* Nothing can modify them now, do not hold them across the sync */ + if (ofs) + ovl_inuse_unlock_all(ofs); + kill_anon_super(sb); +} + struct file_system_type ovl_fs_type = { .owner = THIS_MODULE, .name = "overlay", .init_fs_context = ovl_init_fs_context, .parameters = ovl_parameter_spec, .fs_flags = FS_USERNS_MOUNT | FS_ALLOW_IDMAP, - .kill_sb = kill_anon_super, + .kill_sb = ovl_kill_sb, }; MODULE_ALIAS_FS("overlay"); diff --git a/fs/overlayfs/util.c b/fs/overlayfs/util.c index 788c6870d67d..fd4b1fcf57ad 100644 --- a/fs/overlayfs/util.c +++ b/fs/overlayfs/util.c @@ -1059,6 +1059,18 @@ bool ovl_is_inuse(struct dentry *dentry) return inuse; } +void ovl_inuse_unlock_all(struct ovl_fs *ofs) +{ + if (ofs->workdir_locked) { + ovl_inuse_unlock(ofs->workbasedir); + ofs->workdir_locked = false; + } + if (ofs->upperdir_locked) { + ovl_inuse_unlock(ovl_upper_mnt(ofs)->mnt_root); + ofs->upperdir_locked = false; + } +} + /* * Does this overlay dentry need to be indexed on copy up? */ diff --git a/fs/pidfs.c b/fs/pidfs.c index 114d2713a79e..d1aa0229866a 100644 --- a/fs/pidfs.c +++ b/fs/pidfs.c @@ -591,6 +591,14 @@ static long pidfd_ioctl(struct file *file, unsigned int cmd, unsigned long arg) return -EINVAL; /* + * Require the target to be visible in the caller's pid namespace + * for operations that grant access to its resources, mirroring + * procfs and PIDFD_GET_INFO. + */ + if (!pid_in_current_pidns(pidfd_pid(file))) + return -EREMOTE; + + /* * We're trying to open a file descriptor to the namespace so perform a * filesystem cred ptrace check. Hold @task's exec_update_lock for the * duration of the ptrace check and the namespace lookup so that the diff --git a/fs/pipe.c b/fs/pipe.c index 4fa69192e6fb..4c1122597a3c 100644 --- a/fs/pipe.c +++ b/fs/pipe.c @@ -222,48 +222,6 @@ static void anon_pipe_buf_release(struct pipe_inode_info *pipe, anon_pipe_put_page(pipe, page); } -static bool anon_pipe_buf_try_steal(struct pipe_inode_info *pipe, - struct pipe_buffer *buf) -{ - struct page *page = buf->page; - - if (page_count(page) != 1) - return false; - memcg_kmem_uncharge_page(page, 0); - __SetPageLocked(page); - return true; -} - -/** - * generic_pipe_buf_try_steal - attempt to take ownership of a &pipe_buffer - * @pipe: the pipe that the buffer belongs to - * @buf: the buffer to attempt to steal - * - * Description: - * This function attempts to steal the &struct page attached to - * @buf. If successful, this function returns 0 and returns with - * the page locked. The caller may then reuse the page for whatever - * he wishes; the typical use is insertion into a different file - * page cache. - */ -bool generic_pipe_buf_try_steal(struct pipe_inode_info *pipe, - struct pipe_buffer *buf) -{ - struct page *page = buf->page; - - /* - * A reference of one is golden, that means that the owner of this - * page is the only one holding a reference to it. lock the page - * and return OK. - */ - if (page_count(page) == 1) { - lock_page(page); - return true; - } - return false; -} -EXPORT_SYMBOL(generic_pipe_buf_try_steal); - /** * generic_pipe_buf_get - get a reference to a &struct pipe_buffer * @pipe: the pipe that the buffer belongs to @@ -297,7 +255,6 @@ EXPORT_SYMBOL(generic_pipe_buf_release); static const struct pipe_buf_operations anon_pipe_buf_ops = { .release = anon_pipe_buf_release, - .try_steal = anon_pipe_buf_try_steal, .get = generic_pipe_buf_get, }; diff --git a/fs/proc/proc_sysctl.c b/fs/proc/proc_sysctl.c index 6c0859c66563..eeebf813668e 100644 --- a/fs/proc/proc_sysctl.c +++ b/fs/proc/proc_sysctl.c @@ -557,6 +557,8 @@ static ssize_t proc_sys_call_handler(struct kiocb *iocb, struct iov_iter *iter, struct ctl_table_header *head = grab_header(inode); const struct ctl_table *table = PROC_I(inode)->sysctl_entry; size_t count = iov_iter_count(iter); + /* ->write_iter() must never report more than the iterator held */ + size_t orig_count = count; char *kbuf; ssize_t error; @@ -607,7 +609,8 @@ static ssize_t proc_sys_call_handler(struct kiocb *iocb, struct iov_iter *iter, goto out_free_buf; } - error = count; + /* the write path consumed at most the original iterator length */ + error = write ? min(count, orig_count) : count; out_free_buf: kvfree(kbuf); out: diff --git a/fs/read_write.c b/fs/read_write.c index 676728310899..b15522cf96cd 100644 --- a/fs/read_write.c +++ b/fs/read_write.c @@ -333,45 +333,25 @@ loff_t default_llseek(struct file *file, loff_t offset, int whence) { struct inode *inode = file_inode(file); loff_t retval; + int ret; retval = inode_lock_killable(inode); if (retval) return retval; - switch (whence) { - case SEEK_END: - offset += i_size_read(inode); - break; - case SEEK_CUR: - if (offset == 0) { - retval = file->f_pos; - goto out; - } - offset += file->f_pos; - break; - case SEEK_DATA: - /* - * In the generic case the entire file is data, so as - * long as offset isn't at the end of the file then the - * offset is data. - */ - if (offset >= inode->i_size) { - retval = -ENXIO; - goto out; - } - break; - case SEEK_HOLE: - /* - * There is a virtual hole at the end of the file, so - * as long as offset isn't i_size or larger, return - * i_size. - */ - if (offset >= inode->i_size) { - retval = -ENXIO; - goto out; - } - offset = inode->i_size; - break; + + ret = must_set_pos(file, &offset, whence, i_size_read(inode)); + if (ret < 0) { + retval = ret; + goto out; + } + if (ret == 0) { + retval = offset; + goto out; } + + if (whence == SEEK_CUR) + offset += file->f_pos; + retval = -EINVAL; if (offset >= 0 || unsigned_offsets(file)) { if (offset != file->f_pos) diff --git a/fs/remap_range.c b/fs/remap_range.c index 6eb7d845de5d..7d269837f63f 100644 --- a/fs/remap_range.c +++ b/fs/remap_range.c @@ -277,7 +277,7 @@ int __generic_remap_file_range_prep(struct file *file_in, loff_t pos_in, struct file *file_out, loff_t pos_out, loff_t *len, unsigned int remap_flags, - const struct iomap_ops *dax_read_ops) + iomap_iter_next_fn dax_read_next) { struct inode *inode_in = file_inode(file_in); struct inode *inode_out = file_inode(file_out); @@ -340,10 +340,10 @@ __generic_remap_file_range_prep(struct file *file_in, loff_t pos_in, if (!IS_DAX(inode_in)) ret = vfs_dedupe_file_range_compare(file_in, pos_in, file_out, pos_out, *len, &is_same); - else if (dax_read_ops) + else if (dax_read_next) ret = dax_dedupe_file_range_compare(inode_in, pos_in, inode_out, pos_out, *len, &is_same, - dax_read_ops); + dax_read_next); else return -EINVAL; if (ret) diff --git a/fs/smb/client/cifs_fs_sb.h b/fs/smb/client/cifs_fs_sb.h index d6494e1d93cc..b322718d9199 100644 --- a/fs/smb/client/cifs_fs_sb.h +++ b/fs/smb/client/cifs_fs_sb.h @@ -57,6 +57,7 @@ struct cifs_sb_info { atomic_t active; atomic_t mnt_cifs_flags; atomic_t outstanding_rreq; /* nr of rreqs not yet fully deinitialized */ + atomic_t umount_aborts; /* nr of umount -f attempts */ struct delayed_work prune_tlinks; struct rcu_head rcu; @@ -68,6 +69,7 @@ struct cifs_sb_info { * (cifs_autodisable_serverino) in order to match new mounts. */ bool mnt_cifs_serverino_autodisabled; + bool exiting; /* umount -f committed: stop retries */ /* * Available once the mount has completed. */ diff --git a/fs/smb/client/cifsacl.c b/fs/smb/client/cifsacl.c index f9f61c758a75..d8f30c35cbe5 100644 --- a/fs/smb/client/cifsacl.c +++ b/fs/smb/client/cifsacl.c @@ -385,7 +385,7 @@ id_to_sid(unsigned int cid, uint sidtype, struct smb_sid *ssid) goto out_revert_creds; } else if (sidkey->datalen < CIFS_SID_BASE_SIZE) { rc = smb_EIO1(smb_eio_trace_malformed_sid_key, sidkey->datalen); - cifs_dbg(FYI, "%s: Downcall contained malformed key (datalen=%hu)\n", + cifs_dbg(FYI, "%s: Downcall contained malformed key (datalen=%u)\n", __func__, sidkey->datalen); goto invalidate_key; } @@ -403,7 +403,7 @@ id_to_sid(unsigned int cid, uint sidtype, struct smb_sid *ssid) if (ksid_size > sidkey->datalen) { rc = smb_EIO2(smb_eio_trace_malformed_ksid_key, ksid_size, sidkey->datalen); - cifs_dbg(FYI, "%s: Downcall contained malformed key (datalen=%hu, ksid_size=%u)\n", + cifs_dbg(FYI, "%s: Downcall contained malformed key (datalen=%u, ksid_size=%u)\n", __func__, sidkey->datalen, ksid_size); goto invalidate_key; } @@ -498,7 +498,7 @@ try_upcall_to_get_id: */ BUILD_BUG_ON(sizeof(uid_t) != sizeof(gid_t)); if (sidkey->datalen != sizeof(uid_t)) { - cifs_dbg(FYI, "%s: Downcall contained malformed key (datalen=%hu)\n", + cifs_dbg(FYI, "%s: Downcall contained malformed key (datalen=%u)\n", __func__, sidkey->datalen); key_invalidate(sidkey); goto out_key_put; @@ -1134,7 +1134,10 @@ static void populate_new_aces(char *nacl_base, * updated in the inode. */ - if (!memcmp(pownersid, pgrpsid, sizeof(struct smb_sid))) { + if (pownersid->num_subauth == pgrpsid->num_subauth && + !memcmp(pownersid, pgrpsid, + CIFS_SID_BASE_SIZE + + pownersid->num_subauth * sizeof(__le32))) { /* * Case when owner and group SIDs are the same. * Set the more restrictive of the two modes. diff --git a/fs/smb/client/cifsacl.h b/fs/smb/client/cifsacl.h index 31b51a8fc256..ebc1b7c08c6a 100644 --- a/fs/smb/client/cifsacl.h +++ b/fs/smb/client/cifsacl.h @@ -93,18 +93,4 @@ struct owner_group_sids { struct owner_sid group; } __packed; -/* - * Minimum security identifier can be one for system defined Users - * and Groups such as NULL SID and World or Built-in accounts such - * as Administrator and Guest and consists of - * Revision + Num (Sub)Auths + Authority + Domain (one Subauthority) - */ -#define MIN_SID_LEN (1 + 1 + 6 + 4) /* in bytes */ - -/* - * Minimum security descriptor can be one without any SACL and DACL and can - * consist of revision, type, and two sids of minimum size for owner and group - */ -#define MIN_SEC_DESC_LEN (sizeof(struct smb_ntsd) + (2 * MIN_SID_LEN)) - #endif /* _CIFSACL_H */ diff --git a/fs/smb/client/cifsfs.c b/fs/smb/client/cifsfs.c index bf199a5ca084..8cff7857b450 100644 --- a/fs/smb/client/cifsfs.c +++ b/fs/smb/client/cifsfs.c @@ -164,6 +164,7 @@ struct workqueue_struct *cifsoplockd_wq; struct workqueue_struct *deferredclose_wq; struct workqueue_struct *serverclose_wq; struct workqueue_struct *cfid_put_wq; +struct workqueue_struct *cifs_writeback_wq; __u32 cifs_lock_secret; /* @@ -293,9 +294,115 @@ out_no_root: return rc; } +struct cifs_tcon_ref { + struct list_head list; + struct tcon_link *tlink; + struct cifs_tcon *tcon; + bool shared; +}; + +static bool used_by_other_mounts(struct cifs_tcon *tcon, + struct list_head *tcons) +{ + struct cifs_tcon_ref *ref; + int n = 0; + + list_for_each_entry(ref, tcons, list) + n += ref->tcon == tcon; + + guard(spinlock)(&tcon->tc_lock); + return tcon->mnt_refs - tcon->mnt_unlinked > n; +} + +static void get_sb_tcons(struct cifs_sb_info *cifs_sb, struct list_head *tcons) +{ + struct rb_root *root = &cifs_sb->tlink_tree; + struct cifs_tcon_ref *ref; + struct tcon_link *tlink; + struct cifs_tcon *tcon; + struct rb_node *node; + + guard(spinlock)(&cifs_sb->tlink_tree_lock); + for (node = rb_first(root); node; node = rb_next(node)) { + tlink = rb_entry(node, struct tcon_link, tl_rbnode); + tcon = tlink_tcon(tlink); + if (IS_ERR_OR_NULL(tcon)) + continue; + + ref = kmalloc_obj(struct cifs_tcon_ref, GFP_ATOMIC); + if (!ref) + break; + + ref->tlink = cifs_get_tlink(tlink); + ref->tcon = tcon; + list_add_tail(&ref->list, tcons); + } + list_for_each_entry(ref, tcons, list) + ref->shared = used_by_other_mounts(ref->tcon, tcons); +} + +static void put_sb_tcons(struct list_head *tcons) +{ + struct cifs_tcon_ref *ref, *tmp; + + list_for_each_entry_safe(ref, tmp, tcons, list) { + cifs_put_tlink(ref->tlink); + list_del(&ref->list); + kfree(ref); + } +} + +/* + * While a forced unmount tears a superblock down, keep its tcons from + * reconnecting or replaying so the teardown (flushing close and oplock work, + * sending the tree disconnect) can't hang on a server that is gone. It is a + * count, not a flag, so a tcon shared with another mount only has its retries + * suppressed for the duration of this teardown; one no mount uses any more + * stays dying until it is freed. + */ +static void set_tcons_dying(struct cifs_sb_info *cifs_sb, + struct list_head *tcons) +{ + struct cifs_tcon_ref *ref; + + get_sb_tcons(cifs_sb, tcons); + list_for_each_entry(ref, tcons, list) { + atomic_inc(&ref->tcon->dying); + cifs_wake_ses_waiters(ref->tcon->ses); + } +} + +static void clear_tcons_dying(struct list_head *tcons) +{ + struct cifs_tcon_ref *ref; + + flush_workqueue(serverclose_wq); + list_for_each_entry(ref, tcons, list) { + guard(spinlock)(&ref->tcon->tc_lock); + if (ref->tcon->mnt_refs) + atomic_dec(&ref->tcon->dying); + } + put_sb_tcons(tcons); +} + static void cifs_kill_sb(struct super_block *sb) { struct cifs_sb_info *cifs_sb = CIFS_SB(sb); + LIST_HEAD(tcons); + bool force; + + force = atomic_read(&cifs_sb->umount_aborts); + + /* + * Reaching here after a umount -f means the mount is going away for + * good, so stop retrying I/O that can no longer complete (e.g. + * writeback to a server that is gone) rather than looping forever on + * a hard mount and hanging the teardown below. + */ + if (force) { + WRITE_ONCE(cifs_sb->exiting, true); + set_tcons_dying(cifs_sb, &tcons); + } /* * We need to release all dentries for the cached directories @@ -329,6 +436,9 @@ static void cifs_kill_sb(struct super_block *sb) kill_anon_super(sb); cifs_umount(cifs_sb); + + if (force) + clear_tcons_dying(&tcons); } static int @@ -827,46 +937,46 @@ cifs_show_options(struct seq_file *s, struct dentry *root) return 0; } +static void abort_reconnect(struct cifs_tcon *tcon) +{ + scoped_guard(spinlock, &tcon->tc_lock) + trace_smb3_tcon_ref(tcon->debug_id, tcon->tc_count, + netfs_trace_tcon_ref_see_umount); + + atomic_inc(&tcon->umount_aborts); + if (tcon->ses && tcon->ses->server) { + cifs_dbg(FYI, "wake up tasks now - umount begin not complete\n"); + cifs_wake_ses_waiters(tcon->ses); + msleep(1); /* yield */ + /* we have to kick the requests once more */ + cifs_wake_ses_waiters(tcon->ses); + msleep(1); + } +} + static void cifs_umount_begin(struct super_block *sb) { struct cifs_sb_info *cifs_sb = CIFS_SB(sb); - struct cifs_tcon *tcon; + struct cifs_tcon_ref *ref; + LIST_HEAD(tcons); if (cifs_sb == NULL) return; - tcon = cifs_sb_master_tcon(cifs_sb); + atomic_inc(&cifs_sb->umount_aborts); - spin_lock(&cifs_tcp_ses_lock); - spin_lock(&tcon->tc_lock); - trace_smb3_tcon_ref(tcon->debug_id, tcon->tc_count, - netfs_trace_tcon_ref_see_umount); - if ((tcon->tc_count > 1) || (tcon->status == TID_EXITING)) { - /* we have other mounts to same share or we have - already tried to umount this and woken up - all waiting network requests, nothing to do */ - spin_unlock(&tcon->tc_lock); - spin_unlock(&cifs_tcp_ses_lock); - return; - } /* - * can not set tcon->status to TID_EXITING yet since we don't know if umount -f will - * fail later (e.g. due to open files). TID_EXITING will be set just before tdis req sent + * Abort the reconnect waits of the master tcon and of any per-user + * tcons of a multiuser mount that no other mount uses, pinning their + * tlinks so that they stay alive, and aren't pruned, while we abort and + * sleep outside the tree lock. */ - spin_unlock(&tcon->tc_lock); - spin_unlock(&cifs_tcp_ses_lock); - - if (tcon->ses && tcon->ses->server) { - cifs_dbg(FYI, "wake up tasks now - umount begin not complete\n"); - wake_up_all(&tcon->ses->server->request_q); - wake_up_all(&tcon->ses->server->response_q); - msleep(1); /* yield */ - /* we have to kick the requests once more */ - wake_up_all(&tcon->ses->server->response_q); - msleep(1); + get_sb_tcons(cifs_sb, &tcons); + list_for_each_entry(ref, &tcons, list) { + if (!ref->shared) + abort_reconnect(ref->tcon); } - - return; + put_sb_tcons(&tcons); } static int cifs_freeze(struct super_block *sb) @@ -2123,9 +2233,16 @@ init_cifs(void) goto out_destroy_serverclose_wq; } + cifs_writeback_wq = alloc_workqueue("cifswritebackd", + WQ_UNBOUND | WQ_MEM_RECLAIM, 0); + if (!cifs_writeback_wq) { + rc = -ENOMEM; + goto out_destroy_cfid_put_wq; + } + rc = cifs_init_inodecache(); if (rc) - goto out_destroy_cfid_put_wq; + goto out_destroy_writeback_wq; rc = cifs_init_netfs(); if (rc) @@ -2196,6 +2313,8 @@ out_destroy_netfs: cifs_destroy_netfs(); out_destroy_inodecache: cifs_destroy_inodecache(); +out_destroy_writeback_wq: + destroy_workqueue(cifs_writeback_wq); out_destroy_cfid_put_wq: destroy_workqueue(cfid_put_wq); out_destroy_serverclose_wq: @@ -2241,6 +2360,7 @@ exit_cifs(void) destroy_workqueue(fileinfo_put_wq); destroy_workqueue(serverclose_wq); destroy_workqueue(cfid_put_wq); + destroy_workqueue(cifs_writeback_wq); destroy_workqueue(cifsiod_wq); } diff --git a/fs/smb/client/cifsglob.h b/fs/smb/client/cifsglob.h index d3ca688b6aba..4e16347886ed 100644 --- a/fs/smb/client/cifsglob.h +++ b/fs/smb/client/cifsglob.h @@ -585,7 +585,7 @@ struct smb_version_operations { unsigned int (*wp_retry_size)(struct inode *); /* get mtu credits */ int (*wait_mtu_credits)(struct TCP_Server_Info *, size_t, - size_t *, struct cifs_credits *); + size_t *, struct cifs_credits *, bool nowait); /* adjust previously taken mtu credits to request size */ int (*adjust_credits)(struct TCP_Server_Info *server, struct cifs_io_subrequest *subreq, @@ -887,6 +887,14 @@ has_credits(struct TCP_Server_Info *server, int *credits, int num_credits) return num >= num_credits; } +static inline bool +credits_or_conn_down(struct TCP_Server_Info *server, int *credits, + int num_credits, bool nowait) +{ + return has_credits(server, credits, num_credits) || + (nowait && READ_ONCE(server->tcpStatus) == CifsNeedReconnect); +} + static inline void add_credits(struct TCP_Server_Info *server, struct cifs_credits *credits, const int optype) @@ -1196,6 +1204,10 @@ struct cifs_tcon { struct list_head tcon_list; int debug_id; /* Debugging for tracing */ int tc_count; + int mnt_refs; /* refs held by mounts, under tc_lock */ + int mnt_unlinked; /* mnt_refs of tlinks being built */ + atomic_t umount_aborts; /* nr of umount -f attempts */ + atomic_t dying; /* umount -f: stop reconnects/replays */ struct list_head rlist; /* reconnect list */ spinlock_t tc_lock; /* protect anything here that is not protected */ atomic_t num_local_opens; /* num of all opens including disconnected */ @@ -1407,6 +1419,9 @@ struct cifs_open_parms { umode_t mode; bool reconnect:1; bool replay:1; /* indicates that this open is for a replay */ + bool no_replay:1; /* don't replay this open internally */ + bool pending:1; /* in/out: last built create had no answer */ + bool no_reconnect_wait:1; /* fail fast, don't wait for reconnect */ struct kvec *ea_cctx; __le32 lease_flags; }; @@ -1458,6 +1473,10 @@ struct cifsFileInfo { int count; spinlock_t file_info_lock; /* protects four flag/count fields above */ struct mutex fh_mutex; /* prevents reopen race after dead ses*/ + unsigned int reopens; + bool reopen_fresh; /* durable handle gone: reopen opens afresh */ + bool reopen_replay; /* reopen replays its last create */ + int reopen_access; /* desired access of that create */ struct cifs_search_info srch_inf; struct work_struct oplock_break; /* work for oplock breaks */ struct work_struct put; /* work for the final part of _put */ @@ -1482,6 +1501,16 @@ struct cifs_io_request { struct netfs_io_request rreq; struct cifsFileInfo *cfile; pid_t pid; + int umount_aborts; + bool reopen_gave_up; + bool replay; + atomic_t bad_reopens; /* 0 or bad gen + 1 */ + int reopen_err; + int reopen_pass_err; + struct mutex reopen_lock; /* serializes reopens */ + unsigned long retry_deadline; + unsigned int cur_sleep; + unsigned int slept; }; /* asynchronous read support */ @@ -1496,8 +1525,11 @@ struct cifs_io_subrequest { int result; bool have_xid; bool replay; + bool deferred; /* issue in a worker */ + unsigned int reopens; unsigned int retries; /* number of retries so far */ unsigned int cur_sleep; /* time to sleep before replay */ + unsigned long retry_deadline; struct kvec iov[2]; struct TCP_Server_Info *server; #ifdef CONFIG_CIFS_SMB_DIRECT @@ -1891,6 +1923,8 @@ enum cifs_find_flags { FIND_WITH_DELETE = (1U << 1), FIND_NO_PENDING_DELETE = (1U << 2), FIND_OPEN_FLAGS = (1U << 3), + FIND_NO_DIRECT = (1U << 4), + FIND_NO_REOPEN = (1U << 5), }; #define MID_FREE 0 @@ -1933,6 +1967,7 @@ enum cifs_find_flags { #define CIFS_COMPRESS_REQ 0x4000 /* compress request before sending */ #define CIFS_INTERRUPTIBLE_WAIT 0x8000 /* Interruptible wait (e.g. lock request) */ #define CIFS_WINDOWS_LOCK 0x10000 /* We're trying to get a Windows lock */ +#define CIFS_NO_RECONNECT_WAIT 0x20000 /* don't wait if conn is down */ /* Security Flags: indicate type of session setup needed */ #define CIFSSEC_MAY_SIGN 0x00001 @@ -2141,6 +2176,7 @@ extern struct workqueue_struct *cifsoplockd_wq; extern struct workqueue_struct *deferredclose_wq; extern struct workqueue_struct *serverclose_wq; extern struct workqueue_struct *cfid_put_wq; +extern struct workqueue_struct *cifs_writeback_wq; extern __u32 cifs_lock_secret; extern mempool_t *cifs_sm_req_poolp; @@ -2373,6 +2409,18 @@ static inline void cifs_reset_oplock(struct cifsInodeInfo *cinode) WRITE_ONCE(cinode->oplock, 0); } +static inline bool cifs_tcon_dying(struct cifs_tcon *tcon) +{ + return atomic_read(&tcon->dying) || + (!tcon->ipc && !tcon->dummy && !READ_ONCE(tcon->mnt_refs)); +} + +static inline bool cifs_tcon_retry(struct cifs_tcon *tcon, int aborts) +{ + return tcon->retry && atomic_read(&tcon->umount_aborts) == aborts && + !cifs_tcon_dying(tcon); +} + static inline bool cifs_forced_shutdown(const struct cifs_sb_info *sbi) { return cifs_sb_flags(sbi) & CIFS_MOUNT_SHUTDOWN; diff --git a/fs/smb/client/cifsproto.h b/fs/smb/client/cifsproto.h index f9ea35597bc2..15123c7b9373 100644 --- a/fs/smb/client/cifsproto.h +++ b/fs/smb/client/cifsproto.h @@ -112,7 +112,8 @@ int __smb_send_rqst(struct TCP_Server_Info *server, int num_rqst, int wait_for_free_request(struct TCP_Server_Info *server, const int flags, unsigned int *instance); int cifs_wait_mtu_credits(struct TCP_Server_Info *server, size_t size, - size_t *num, struct cifs_credits *credits); + size_t *num, struct cifs_credits *credits, + bool nowait); static inline int send_cancel(struct cifs_ses *ses, struct TCP_Server_Info *server, @@ -137,6 +138,8 @@ bool is_size_safe_to_change(struct cifsInodeInfo *cifsInode, __u64 end_of_file, bool from_readdir); void cifs_write_subrequest_terminated(struct cifs_io_subrequest *wdata, ssize_t result); +bool cifs_io_stopped(struct cifs_io_subrequest *subreq); +bool cifs_io_should_replay(struct cifs_io_subrequest *subreq); struct cifsFileInfo *find_writable_file(struct cifsInodeInfo *cifs_inode, int flags); int __cifs_get_writable_file(struct cifsInodeInfo *cifs_inode, @@ -241,7 +244,7 @@ int cifs_match_super(struct super_block *sb, struct fs_context *fc); int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx); void cifs_umount(struct cifs_sb_info *cifs_sb); void cifs_mark_open_files_invalid(struct cifs_tcon *tcon); -void cifs_reopen_persistent_handles(struct cifs_tcon *tcon); +bool cifs_reopen_persistent_handles(struct cifs_tcon *tcon); bool cifs_find_lock_conflict(struct cifsFileInfo *cfile, __u64 offset, __u64 length, __u8 type, __u16 flags, @@ -440,7 +443,10 @@ static inline int cifs_create_options(struct cifs_sb_info *cifs_sb, int options) return options; } -int cifs_wait_for_server_reconnect(struct TCP_Server_Info *server, bool retry); +void cifs_wake_ses_waiters(struct cifs_ses *ses); +int cifs_wait_for_server_reconnect(struct TCP_Server_Info *server, + struct cifs_tcon *tcon, int aborts, + bool nowait); static inline void cifs_put_smb_ses(struct cifs_ses *ses) { diff --git a/fs/smb/client/cifssmb.c b/fs/smb/client/cifssmb.c index 2936b38de98f..68f05a52605f 100644 --- a/fs/smb/client/cifssmb.c +++ b/fs/smb/client/cifssmb.c @@ -73,6 +73,7 @@ cifs_reconnect_tcon(struct cifs_tcon *tcon, int smb_command) { struct TCP_Server_Info *server; struct cifs_ses *ses; + int aborts; int rc; /* @@ -83,6 +84,8 @@ cifs_reconnect_tcon(struct cifs_tcon *tcon, int smb_command) if (!tcon) return 0; + aborts = atomic_read(&tcon->umount_aborts); + ses = tcon->ses; server = ses->server; @@ -102,7 +105,7 @@ cifs_reconnect_tcon(struct cifs_tcon *tcon, int smb_command) spin_unlock(&tcon->tc_lock); again: - rc = cifs_wait_for_server_reconnect(server, tcon->retry); + rc = cifs_wait_for_server_reconnect(server, tcon, aborts, false); if (rc) return rc; @@ -127,7 +130,7 @@ again: case CifsNeedReconnect: spin_unlock(&server->srv_lock); mutex_unlock(&ses->session_mutex); - if (!tcon->retry) + if (!cifs_tcon_retry(tcon, aborts)) return -EHOSTDOWN; goto again; default: @@ -159,7 +162,7 @@ again: rc = cifs_negotiate_protocol(0, ses, server); if (rc) { mutex_unlock(&ses->session_mutex); - if (!tcon->retry) + if (!cifs_tcon_retry(tcon, aborts)) return -EHOSTDOWN; goto again; } @@ -1939,12 +1942,14 @@ cifs_writev_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid) break; case MID_REQUEST_SUBMITTED: trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_req_submitted); - __set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags); + if (wdata->rreq->origin != NETFS_WRITEBACK) + __set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags); result = -EAGAIN; break; case MID_RETRY_NEEDED: trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_retry_needed); - __set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags); + if (wdata->rreq->origin != NETFS_WRITEBACK) + __set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags); result = -EAGAIN; break; case MID_RESPONSE_MALFORMED: diff --git a/fs/smb/client/connect.c b/fs/smb/client/connect.c index e68fffb2ab2e..750b5bb72dc7 100644 --- a/fs/smb/client/connect.c +++ b/fs/smb/client/connect.c @@ -352,6 +352,7 @@ cifs_abort_connection(struct TCP_Server_Info *server) mid_execute_callback(server, mid); release_mid(server, mid); } + wake_up_all(&server->request_q); } static bool cifs_tcp_ses_needs_reconnect(struct TCP_Server_Info *server, int num_targets) @@ -2200,7 +2201,8 @@ void __cifs_put_smb_ses(struct cifs_ses *ses) kref_put(&ses->chans[i].iface->refcount, release_iface); ses->chans[i].iface = NULL; } - cifs_put_tcp_session(ses->chans[i].server, 0); + if (ses->chans[i].server) + cifs_put_tcp_session(ses->chans[i].server, 0); ses->chans[i].server = NULL; } @@ -2610,18 +2612,21 @@ static int match_tcon(struct cifs_tcon *tcon, struct smb3_fs_context *ctx) } static struct cifs_tcon * -cifs_find_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx) +cifs_find_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx, + bool unlinked) { struct cifs_tcon *tcon; spin_lock(&cifs_tcp_ses_lock); list_for_each_entry(tcon, &ses->tcon_list, tcon_list) { spin_lock(&tcon->tc_lock); - if (!match_tcon(tcon, ctx)) { + if (!match_tcon(tcon, ctx) || cifs_tcon_dying(tcon)) { spin_unlock(&tcon->tc_lock); continue; } ++tcon->tc_count; + ++tcon->mnt_refs; + tcon->mnt_unlinked += unlinked; trace_smb3_tcon_ref(tcon->debug_id, tcon->tc_count, netfs_trace_tcon_ref_get_find); spin_unlock(&tcon->tc_lock); @@ -2695,10 +2700,47 @@ cifs_put_tcon(struct cifs_tcon *tcon, enum smb3_tcon_ref_trace trace) #endif } +void cifs_wake_ses_waiters(struct cifs_ses *ses) +{ + guard(spinlock)(&ses->chan_lock); + for (size_t i = 0; i < ses->chan_count; i++) { + struct TCP_Server_Info *server = ses->chans[i].server; + + if (!server) + continue; + wake_up_all(&server->request_q); + wake_up_all(&server->response_q); + } +} + +static void drop_mnt_ref(struct cifs_tcon *tcon) +{ + scoped_guard(spinlock, &tcon->tc_lock) { + if (--tcon->mnt_refs) + return; + } + cifs_wake_ses_waiters(tcon->ses); +} + +static void put_mnt_tcon(struct cifs_tcon *tcon, enum smb3_tcon_ref_trace trace) +{ + drop_mnt_ref(tcon); + cifs_put_tcon(tcon, trace); +} + +static void erase_tlink(struct cifs_sb_info *cifs_sb, struct tcon_link *tlink) +{ + clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags); + rb_erase(&tlink->tl_rbnode, &cifs_sb->tlink_tree); + if (!IS_ERR(tlink_tcon(tlink))) + drop_mnt_ref(tlink_tcon(tlink)); +} + /** * cifs_get_tcon - get a tcon matching @ctx data from @ses * @ses: smb session to issue the request on * @ctx: the superblock configuration context to use for building the + * @unlinked: the mount reference is for a tlink not yet in a superblock's tree * * - tcon refcount is the number of mount points using the tcon. * - ses refcount is the number of tcon using the session. @@ -2718,13 +2760,13 @@ cifs_put_tcon(struct cifs_tcon *tcon, enum smb3_tcon_ref_trace trace) * decrement the ses refcount. */ static struct cifs_tcon * -cifs_get_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx) +cifs_get_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx, bool unlinked) { struct cifs_tcon *tcon; bool nohandlecache; int rc, xid; - tcon = cifs_find_tcon(ses, ctx); + tcon = cifs_find_tcon(ses, ctx, unlinked); if (tcon) { /* * tcon has refcount already incremented but we need to @@ -2750,6 +2792,8 @@ cifs_get_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx) rc = -ENOMEM; goto out_fail; } + tcon->mnt_refs = 1; + tcon->mnt_unlinked = unlinked; tcon->nohandlecache = nohandlecache; if (ctx->snapshot_time) { @@ -3576,7 +3620,7 @@ void cifs_mount_put_conns(struct cifs_mount_ctx *mnt_ctx) int rc = 0; if (mnt_ctx->tcon) - cifs_put_tcon(mnt_ctx->tcon, netfs_trace_tcon_ref_put_mnt_ctx); + put_mnt_tcon(mnt_ctx->tcon, netfs_trace_tcon_ref_put_mnt_ctx); else if (mnt_ctx->ses) cifs_put_smb_ses(mnt_ctx->ses); else if (mnt_ctx->server) @@ -3656,7 +3700,7 @@ int cifs_mount_get_tcon(struct cifs_mount_ctx *mnt_ctx) cifs_sb = mnt_ctx->cifs_sb; /* search for existing tcon to this server share */ - tcon = cifs_get_tcon(mnt_ctx->ses, ctx); + tcon = cifs_get_tcon(mnt_ctx->ses, ctx, false); if (IS_ERR(tcon)) { rc = PTR_ERR(tcon); tcon = NULL; @@ -4032,8 +4076,7 @@ cifs_umount(struct cifs_sb_info *cifs_sb) while ((node = rb_first(root))) { tlink = rb_entry(node, struct tcon_link, tl_rbnode); cifs_get_tlink(tlink); - clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags); - rb_erase(node, root); + erase_tlink(cifs_sb, tlink); spin_unlock(&cifs_sb->tlink_tree_lock); cifs_put_tlink(tlink); @@ -4321,7 +4364,7 @@ cifs_construct_tcon(struct cifs_sb_info *cifs_sb, kuid_t fsuid) } #endif - tcon = cifs_get_tcon(ses, ctx); + tcon = cifs_get_tcon(ses, ctx, true); if (IS_ERR(tcon)) { cifs_put_smb_ses(ses); goto out; @@ -4424,6 +4467,7 @@ cifs_sb_tlink(struct cifs_sb_info *cifs_sb) { struct tcon_link *tlink, *newtlink; kuid_t fsuid = current_fsuid(); + struct cifs_tcon *tcon; int err; if (!(cifs_sb_flags(cifs_sb) & CIFS_MOUNT_MULTIUSER)) @@ -4481,7 +4525,16 @@ wait_for_construction: goto wait_for_construction; } - tlink->tl_tcon = cifs_construct_tcon(cifs_sb, fsuid); + tcon = cifs_construct_tcon(cifs_sb, fsuid); + scoped_guard(spinlock, &cifs_sb->tlink_tree_lock) { + tlink->tl_tcon = tcon; + if (!IS_ERR(tcon)) { + scoped_guard(spinlock, &tcon->tc_lock) + tcon->mnt_unlinked--; + if (!test_bit(TCON_LINK_IN_TREE, &tlink->tl_flags)) + drop_mnt_ref(tcon); + } + } clear_bit(TCON_LINK_PENDING, &tlink->tl_flags); wake_up_bit(&tlink->tl_flags, TCON_LINK_PENDING); @@ -4530,8 +4583,7 @@ cifs_prune_tlinks(struct work_struct *work) continue; cifs_get_tlink(tlink); - clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags); - rb_erase(tmp, root); + erase_tlink(cifs_sb, tlink); spin_unlock(&cifs_sb->tlink_tree_lock); cifs_put_tlink(tlink); diff --git a/fs/smb/client/dfs.c b/fs/smb/client/dfs.c index b7143335d70a..57c90a2512a3 100644 --- a/fs/smb/client/dfs.c +++ b/fs/smb/client/dfs.c @@ -33,7 +33,7 @@ int dfs_parse_target_referral(const char *full_path, const struct dfs_info3_para if (WARN_ON_ONCE(!ref->node_name || ref->path_consumed < 0)) return -EINVAL; - if (strlen(full_path) - ref->path_consumed) { + if ((size_t)ref->path_consumed < strlen(full_path)) { prepath = full_path + ref->path_consumed; /* skip initial delimiter */ if (*prepath == '/' || *prepath == '\\') @@ -103,6 +103,7 @@ static int setup_dfs_ref(struct dfs_info3_param *tgt, struct dfs_ref_walk *rw) struct cifs_sb_info *cifs_sb = rw->mnt_ctx->cifs_sb; struct smb3_fs_context *ctx = rw->mnt_ctx->fs_ctx; char *ref_path, *full_path; + const char *raw_path; int rc; set_root_smb_session(rw->mnt_ctx); @@ -114,9 +115,10 @@ static int setup_dfs_ref(struct dfs_info3_param *tgt, struct dfs_ref_walk *rw) if (!tgt || (tgt->server_type == DFS_TYPE_LINK && DFS_INTERLINK(tgt->flags))) - ref_path = dfs_get_path(cifs_sb, ctx->UNC); + raw_path = ctx->UNC; else - ref_path = dfs_get_path(cifs_sb, full_path); + raw_path = full_path; + ref_path = dfs_get_path(cifs_sb, raw_path); if (IS_ERR(ref_path)) { rc = PTR_ERR(ref_path); kfree(full_path); @@ -125,9 +127,7 @@ static int setup_dfs_ref(struct dfs_info3_param *tgt, struct dfs_ref_walk *rw) ref_walk_path(rw) = ref_path; ref_walk_fpath(rw) = full_path; - return dfs_get_referral(rw->mnt_ctx, - ref_walk_path(rw) + 1, - ref_walk_tl(rw)); + return dfs_get_referral(rw->mnt_ctx, raw_path + 1, ref_walk_tl(rw)); } static int __dfs_referral_walk(struct dfs_ref_walk *rw) diff --git a/fs/smb/client/file.c b/fs/smb/client/file.c index 0767eb5f4687..f51653cb6432 100644 --- a/fs/smb/client/file.c +++ b/fs/smb/client/file.c @@ -37,7 +37,261 @@ #include "cached_dir.h" #include <trace/events/netfs.h> -static int cifs_reopen_file(struct cifsFileInfo *cfile, bool can_flush); +/* flags for cifs_reopen_file() */ +#define CIFS_REOPEN_BOUND BIT(0) /* caller bounds the retries */ +#define CIFS_REOPEN_NOWAIT BIT(1) /* fail fast, skip reconnect wait */ + +static int cifs_reopen_file(struct cifsFileInfo *cfile, bool can_flush, + unsigned int flags); + +bool cifs_io_stopped(struct cifs_io_subrequest *subreq) +{ + struct super_block *sb = subreq->rreq->inode->i_sb; + struct cifs_sb_info *cifs_sb = CIFS_SB(sb); + int aborts; + + if (cifs_forced_shutdown(cifs_sb) || READ_ONCE(cifs_sb->exiting)) + return true; + aborts = atomic_read(&cifs_sb->umount_aborts); + if (aborts != subreq->req->umount_aborts) + return true; + return aborts && rwsem_is_contended(&sb->s_umount); +} + +static bool cifs_writeback_retry_expired(struct cifs_io_subrequest *subreq, + struct cifs_tcon *tcon) +{ + struct TCP_Server_Info *server = tcon->ses->server; + unsigned long window; + + if (tcon->retry) + return false; + if (!subreq->retry_deadline) { + window = max(3U, server->retrans) * server->echo_interval; + subreq->retry_deadline = (jiffies + window) | 1; + } + return time_after(jiffies, subreq->retry_deadline); +} + +bool cifs_io_should_replay(struct cifs_io_subrequest *subreq) +{ + struct cifs_tcon *tcon = tlink_tcon(subreq->req->cfile->tlink); + + if (cifs_io_stopped(subreq)) + return false; + if (subreq->rreq->origin == NETFS_WRITEBACK) { + if (cifs_writeback_retry_expired(subreq, tcon)) + return false; + smb2_replay_backoff(&subreq->cur_sleep); + return true; + } + return smb2_should_replay(tcon, &subreq->retries, &subreq->cur_sleep); +} + +static bool cifs_io_aborted(struct cifs_io_subrequest *subreq) +{ + struct cifs_tcon *tcon = tlink_tcon(subreq->req->cfile->tlink); + + if (!cifs_io_stopped(subreq)) + return false; + return subreq->subreq.retry_count || subreq->replay || + READ_ONCE(subreq->server->tcpStatus) == CifsNeedReconnect || + tcon->need_reconnect; +} + +static bool cifs_writeback_transient(int rc) +{ + if (is_replayable_error(rc) || is_interrupt_error(rc)) + return true; + + switch (rc) { + case -ENOMEM: + case -EHOSTDOWN: + case -ENETRESET: + case -ESHUTDOWN: + case -EREMCHG: + case -EBADF: + return true; + } + return false; +} + +static int cifs_writeback_error(struct netfs_io_subrequest *subreq, int rc) +{ + if (subreq->rreq->origin == NETFS_WRITEBACK && + cifs_writeback_transient(rc)) + return -EIO; + return rc; +} + +static bool cifs_writeback_dying(struct netfs_io_subrequest *subreq) +{ + return subreq->rreq->origin == NETFS_WRITEBACK && + fatal_signal_pending(current); +} + +static unsigned int cifs_ses_reconnects(struct cifs_ses *ses) +{ + unsigned int n = 0; + + guard(spinlock)(&ses->chan_lock); + for (size_t i = 0; i < ses->chan_count; i++) { + struct TCP_Server_Info *server = ses->chans[i].server; + + if (server) + n += READ_ONCE(server->reconnect_instance); + } + return n; +} + +static bool cifs_tcon_reconnecting(struct cifs_tcon *tcon) +{ + struct cifs_ses *ses = tcon->ses; + + if (tcon->need_reconnect) + return true; + + guard(spinlock)(&ses->chan_lock); + for (size_t i = 0; i < ses->chan_count; i++) { + struct TCP_Server_Info *server = ses->chans[i].server; + + if (server && READ_ONCE(server->tcpStatus) == CifsNeedReconnect) + return true; + } + return false; +} + +static int cifs_reopen_file_retry(struct cifsFileInfo *cfile, bool can_flush, + struct cifs_io_subrequest *subreq) +{ + struct cifs_tcon *tcon = tlink_tcon(cfile->tlink); + struct cifs_ses *ses = tcon->ses; + unsigned int reconnects; + bool free_retry = true; + bool retrying = false; + int rc; + + for (;;) { + if ((retrying && cifs_io_stopped(subreq)) || + cifs_io_aborted(subreq)) + return -EIO; + retrying = true; + reconnects = cifs_ses_reconnects(ses); + rc = cifs_reopen_file(cfile, can_flush, CIFS_REOPEN_BOUND); + if (!rc || !is_replayable_error(rc)) + return rc; + if (free_retry && !cifs_io_stopped(subreq) && + (cifs_ses_reconnects(ses) != reconnects || + cifs_tcon_reconnecting(tcon))) { + free_retry = false; + continue; + } + if (!cifs_io_should_replay(subreq)) + return rc; + msleep(subreq->cur_sleep); + } +} + +/* + * Record, as generation + 1 (0 means none), the newest reopen generation of a + * handle that a writeback subrequest found bad (-EBADF). Subrequests of the + * same request can fail concurrently on different channels, so keep the newest. + */ +static void cifs_mark_bad_handle(struct cifs_io_request *req, unsigned int gen) +{ + int cur = atomic_read(&req->bad_reopens); + int want = gen + 1; + + while (want > cur && !atomic_try_cmpxchg(&req->bad_reopens, &cur, want)) + ; +} + +static bool cifs_bad_handle_pending(struct cifs_io_request *req) +{ + unsigned int bad = atomic_read(&req->bad_reopens); + + return bad && bad - 1 == READ_ONCE(req->cfile->reopens); +} + +static void __cifs_invalidate_bad_handle(struct cifs_io_request *req) +{ + unsigned int bad = atomic_read(&req->bad_reopens); + struct cifsFileInfo *cfile = req->cfile; + + lockdep_assert_held(&cfile->fh_mutex); + if (bad && bad - 1 == cfile->reopens) + cfile->invalidHandle = true; +} + +static void cifs_invalidate_bad_handle(struct cifs_io_request *req) +{ + if (!cifs_bad_handle_pending(req)) + return; + guard(mutex)(&req->cfile->fh_mutex); + __cifs_invalidate_bad_handle(req); +} + +static bool cifs_try_invalidate_bad_handle(struct cifs_io_request *req) +{ + if (!cifs_bad_handle_pending(req)) + return true; + if (!mutex_trylock(&req->cfile->fh_mutex)) + return false; + __cifs_invalidate_bad_handle(req); + mutex_unlock(&req->cfile->fh_mutex); + return true; +} + +static int cifs_reopen_failed(struct cifs_io_request *req) +{ + if (READ_ONCE(req->reopen_gave_up)) + return -EIO; + return READ_ONCE(req->reopen_err); +} + +static int cifs_reopen_writeback(struct cifs_io_subrequest *wdata) +{ + struct cifs_io_request *req = wdata->req; + struct cifsFileInfo *cfile = req->cfile; + int rc; + + if (cifs_io_aborted(wdata)) + return -EIO; + + guard(mutex)(&req->reopen_lock); + if (!cifs_bad_handle_pending(req) && !cfile->invalidHandle) + return 0; + + rc = cifs_reopen_failed(req); + if (rc) + return rc; + + rc = req->reopen_pass_err; + if (!rc) { + if (!cifs_try_invalidate_bad_handle(req)) + rc = -EAGAIN; + else if (cfile->invalidHandle) + rc = cifs_reopen_file(cfile, false, + CIFS_REOPEN_BOUND | + CIFS_REOPEN_NOWAIT); + if (!rc) + return 0; + if (!cifs_writeback_transient(rc)) { + WRITE_ONCE(req->reopen_err, rc); + return rc; + } + req->reopen_pass_err = rc; + } + + if (!cifs_io_should_replay(wdata)) { + WRITE_ONCE(req->reopen_gave_up, true); + return -EIO; + } + + trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_retry_needed); + __set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags); + return rc; +} /* * Prepare a subrequest to upload to the server. We need to allocate credits @@ -52,6 +306,8 @@ static void cifs_prepare_write(struct netfs_io_subrequest *subreq) struct TCP_Server_Info *server; struct cifsFileInfo *open_file = req->cfile; struct cifs_sb_info *cifs_sb = CIFS_SB(wdata->rreq->inode->i_sb); + bool writeback = subreq->rreq->origin == NETFS_WRITEBACK; + bool reprepared = wdata->have_xid; size_t wsize = req->rreq.wsize; int rc; @@ -62,29 +318,68 @@ static void cifs_prepare_write(struct netfs_io_subrequest *subreq) server = cifs_pick_channel(tlink_tcon(open_file->tlink)->ses); wdata->server = server; + wdata->deferred = false; + + if (reprepared) { + req->retry_deadline = wdata->retry_deadline; + req->cur_sleep = wdata->cur_sleep; + req->replay = wdata->replay; + } else if (subreq->retry_count) { + wdata->retry_deadline = req->retry_deadline; + wdata->cur_sleep = req->cur_sleep; + wdata->replay = req->replay; + } + + if (cifs_io_aborted(wdata) || + (reprepared && cifs_io_stopped(wdata))) { + subreq->error = -EIO; + return netfs_prepare_write_failed(subreq); + } if (cifs_sb->ctx->wsize == 0) cifs_negotiate_wsize(server, cifs_sb->ctx, tlink_tcon(req->cfile->tlink)); -retry: - if (open_file->invalidHandle) { - rc = cifs_reopen_file(open_file, false); - if (rc < 0) { - if (rc == -EAGAIN) - goto retry; + if (writeback && + (cifs_bad_handle_pending(req) || open_file->invalidHandle)) { + rc = cifs_reopen_failed(req); + if (rc) { subreq->error = rc; return netfs_prepare_write_failed(subreq); } + goto defer; + } + + if (cifs_writeback_dying(subreq)) + goto defer; + + if (!writeback) { + cifs_invalidate_bad_handle(req); + if (open_file->invalidHandle) { + rc = cifs_reopen_file_retry(open_file, false, wdata); + if (rc < 0) { + subreq->error = rc; + return netfs_prepare_write_failed(subreq); + } + } } rc = server->ops->wait_mtu_credits(server, wsize, &stream->sreq_max_len, - &wdata->credits); + &wdata->credits, writeback); if (rc < 0) { - subreq->error = rc; + if (cifs_writeback_dying(subreq) || + (writeback && rc == -EAGAIN)) + goto defer; + subreq->error = cifs_writeback_error(subreq, rc); return netfs_prepare_write_failed(subreq); } + goto out; +defer: + wdata->deferred = true; + wdata->credits = (struct cifs_credits){}; + stream->sreq_max_len = min_t(size_t, wsize, SMB2_MAX_BUFFER_SIZE); +out: wdata->credits.rreq_debug_id = subreq->rreq->debug_id; wdata->credits.rreq_debug_index = subreq->debug_index; wdata->credits.in_flight_check = 1; @@ -108,7 +403,7 @@ retry: /* * Issue a subrequest to upload to the server. */ -static void cifs_issue_write(struct netfs_io_subrequest *subreq) +static void __cifs_issue_write(struct netfs_io_subrequest *subreq) { struct cifs_io_subrequest *wdata = container_of(subreq, struct cifs_io_subrequest, subreq); @@ -120,28 +415,142 @@ static void cifs_issue_write(struct netfs_io_subrequest *subreq) goto fail; } + rc = -EIO; + if (cifs_io_aborted(wdata)) + goto fail; + rc = adjust_credits(wdata->server, wdata, cifs_trace_rw_credits_issue_write_adjust); if (rc) goto fail; rc = -EAGAIN; - if (wdata->req->cfile->invalidHandle) + if (wdata->req->cfile->invalidHandle || + (wdata->credits.value && + wdata->credits.instance != + READ_ONCE(wdata->server->reconnect_instance))) goto fail; + /* pairs with smp_store_release() in cifs_reopen_file() */ + wdata->reopens = smp_load_acquire(&wdata->req->cfile->reopens); wdata->server->ops->async_writev(wdata); out: return; fail: - if (rc == -EAGAIN) + if (rc == -EAGAIN) { trace_netfs_sreq(subreq, netfs_sreq_trace_retry); - else + __set_bit(NETFS_SREQ_NEED_RETRY, &subreq->flags); + } else { trace_netfs_sreq(subreq, netfs_sreq_trace_fail); + } add_credits_and_wake_if(wdata->server, &wdata->credits, 0); cifs_write_subrequest_terminated(wdata, rc); goto out; } +static void cifs_issue_write_worker(struct work_struct *work) +{ + struct cifs_io_subrequest *wdata; + struct cifsFileInfo *cfile; + int rc = 0; + + wdata = container_of(work, struct cifs_io_subrequest, subreq.work); + cfile = wdata->req->cfile; + if (cifs_bad_handle_pending(wdata->req) || cfile->invalidHandle) + rc = cifs_reopen_writeback(wdata); + if (rc) { + add_credits_and_wake_if(wdata->server, &wdata->credits, 0); + cifs_write_subrequest_terminated(wdata, rc); + return; + } + __cifs_issue_write(&wdata->subreq); +} + +static void cifs_issue_write(struct netfs_io_subrequest *subreq) +{ + struct cifs_io_subrequest *wdata = + container_of(subreq, struct cifs_io_subrequest, subreq); + struct cifs_io_request *req = wdata->req; + + if (wdata->cur_sleep > req->slept) { + msleep(wdata->cur_sleep - req->slept); + req->slept = wdata->cur_sleep; + } + + if (unlikely(wdata->deferred || cifs_writeback_dying(subreq))) { + subreq->work.func = cifs_issue_write_worker; + WARN_ON_ONCE(!queue_work(cifs_writeback_wq, &subreq->work)); + return; + } + __cifs_issue_write(subreq); +} + +static void cifs_share_retry_state(struct netfs_io_subrequest *from, + struct netfs_io_subrequest *stop, + struct list_head *head) +{ + struct netfs_io_subrequest *subreq = from; + struct cifs_io_subrequest *wdata; + unsigned long deadline = 0; + unsigned int sleep = 0; + bool replay = false; + + list_for_each_entry_from(subreq, head, rreq_link) { + if (subreq == stop) + break; + wdata = container_of(subreq, struct cifs_io_subrequest, subreq); + if (wdata->retry_deadline && + (!deadline || time_before(wdata->retry_deadline, deadline))) + deadline = wdata->retry_deadline; + sleep = max(sleep, wdata->cur_sleep); + replay |= wdata->replay; + } + + subreq = from; + list_for_each_entry_from(subreq, head, rreq_link) { + if (subreq == stop) + break; + wdata = container_of(subreq, struct cifs_io_subrequest, subreq); + wdata->retry_deadline = deadline; + wdata->cur_sleep = sleep; + wdata->replay = replay; + } +} + +static void cifs_retry_request(struct netfs_io_request *wreq, + struct netfs_io_stream *stream) +{ + struct netfs_io_subrequest *subreq, *from = NULL; + struct cifs_io_request *req = + container_of(wreq, struct cifs_io_request, rreq); + uoff_t end = 0; + + req->slept = 0; + req->reopen_pass_err = 0; + if (!stream) + return; + + guard(spinlock)(&wreq->lock); + list_for_each_entry(subreq, &stream->subrequests, rreq_link) { + if (from && test_bit(NETFS_SREQ_NEED_RETRY, &subreq->flags) && + !test_bit(NETFS_SREQ_BOUNDARY, &subreq->flags) && + subreq->start + subreq->transferred == end) { + end += subreq->len; + continue; + } + if (from) + cifs_share_retry_state(from, subreq, + &stream->subrequests); + from = NULL; + if (test_bit(NETFS_SREQ_NEED_RETRY, &subreq->flags)) { + from = subreq; + end = subreq->start + subreq->len; + } + } + if (from) + cifs_share_retry_state(from, NULL, &stream->subrequests); +} + static void cifs_netfs_invalidate_cache(struct netfs_io_request *wreq) { cifs_invalidate_cache(wreq->inode, 0); @@ -157,6 +566,7 @@ static int cifs_prepare_read(struct netfs_io_subrequest *subreq) struct cifs_io_request *req = container_of(subreq->rreq, struct cifs_io_request, rreq); struct TCP_Server_Info *server; struct cifs_sb_info *cifs_sb = CIFS_SB(rreq->inode->i_sb); + bool reprepared = rdata->have_xid; size_t size; int rc = 0; @@ -168,12 +578,22 @@ static int cifs_prepare_read(struct netfs_io_subrequest *subreq) server = cifs_pick_channel(tlink_tcon(req->cfile->tlink)->ses); rdata->server = server; + if (cifs_io_aborted(rdata) || + (reprepared && cifs_io_stopped(rdata))) + return -EIO; + if (cifs_sb->ctx->rsize == 0) cifs_negotiate_rsize(server, cifs_sb->ctx, tlink_tcon(req->cfile->tlink)); + if (req->cfile->invalidHandle) { + rc = cifs_reopen_file_retry(req->cfile, true, rdata); + if (rc) + return rc; + } + rc = server->ops->wait_mtu_credits(server, cifs_sb->ctx->rsize, - &size, &rdata->credits); + &size, &rdata->credits, false); if (rc) return rc; @@ -218,18 +638,27 @@ static void cifs_issue_read(struct netfs_io_subrequest *subreq) __func__, rreq->debug_id, subreq->debug_index, rreq->mapping, subreq->transferred, subreq->len); + rc = -EIO; + if (cifs_io_aborted(rdata)) + goto failed; + rc = adjust_credits(server, rdata, cifs_trace_rw_credits_issue_read_adjust); if (rc) - goto failed; + goto not_sent; - if (req->cfile->invalidHandle) { - do { - rc = cifs_reopen_file(req->cfile, true); - } while (rc == -EAGAIN); - if (rc) + if (rdata->replay && rdata->cur_sleep) { + msleep(rdata->cur_sleep); + rc = -EIO; + if (cifs_io_aborted(rdata)) goto failed; } + rc = -EAGAIN; + if (req->cfile->invalidHandle || + (rdata->credits.value && + rdata->credits.instance != READ_ONCE(server->reconnect_instance))) + goto not_sent; + if (subreq->rreq->origin != NETFS_UNBUFFERED_READ && subreq->rreq->origin != NETFS_DIO_READ) __set_bit(NETFS_SREQ_CLEAR_TAIL, &subreq->flags); @@ -240,6 +669,11 @@ static void cifs_issue_read(struct netfs_io_subrequest *subreq) goto failed; return; +not_sent: + if (rc == -EAGAIN) { + trace_netfs_sreq(subreq, netfs_sreq_trace_retry); + __set_bit(NETFS_SREQ_NEED_RETRY, &subreq->flags); + } failed: add_credits_and_wake_if(rdata->server, &rdata->credits, 0); subreq->error = rc; @@ -255,9 +689,17 @@ static void cifs_begin_writeback(struct netfs_io_request *wreq) struct cifs_io_request *req = container_of(wreq, struct cifs_io_request, rreq); int ret; - ret = cifs_get_writable_file(CIFS_I(wreq->inode), FIND_ANY, &req->cfile); + ret = cifs_get_writable_file(CIFS_I(wreq->inode), + FIND_NO_REOPEN | FIND_NO_DIRECT, + &req->cfile); if (ret) { - cifs_dbg(VFS, "No writable handle in writepages ret=%d\n", ret); + ret = cifs_get_writable_file(CIFS_I(wreq->inode), + FIND_NO_REOPEN, &req->cfile); + } + if (ret) { + cifs_dbg(VFS, "%s: couldn't find writable handle: %d\n", + __func__, ret); + mapping_set_error(wreq->mapping, -EIO); return; } @@ -276,6 +718,8 @@ static int cifs_init_request(struct netfs_io_request *rreq, struct file *file) rreq->rsize = cifs_sb->ctx->rsize; rreq->wsize = cifs_sb->ctx->wsize; req->pid = current->tgid; // Ummm... This may be a workqueue + req->umount_aborts = atomic_read(&cifs_sb->umount_aborts); + mutex_init(&req->reopen_lock); if (file) { open_file = file->private_data; @@ -364,6 +808,7 @@ const struct netfs_request_ops cifs_req_ops = { .begin_writeback = cifs_begin_writeback, .prepare_write = cifs_prepare_write, .issue_write = cifs_issue_write, + .retry_request = cifs_retry_request, .invalidate_cache = cifs_netfs_invalidate_cache, }; @@ -1274,8 +1719,18 @@ cifs_relock_file(struct cifsFileInfo *cfile) return rc; } +static bool reopen_aborted(struct cifs_tcon *tcon, int aborts) +{ + struct TCP_Server_Info *server; + + if (atomic_read(&tcon->umount_aborts) == aborts) + return false; + server = cifs_pick_channel(tcon->ses); + return server && READ_ONCE(server->tcpStatus) == CifsNeedReconnect; +} + static int -cifs_reopen_file(struct cifsFileInfo *cfile, bool can_flush) +cifs_reopen_file(struct cifsFileInfo *cfile, bool can_flush, unsigned int flags) { int rc = -EACCES; unsigned int xid; @@ -1292,18 +1747,31 @@ cifs_reopen_file(struct cifsFileInfo *cfile, bool can_flush) int create_options = CREATE_NOT_DIR; struct cifs_open_parms oparms; int rdwr_for_fscache = 0; + int aborts; + bool fresh; + tcon = tlink_tcon(cfile->tlink); + aborts = atomic_read(&tcon->umount_aborts); xid = get_xid(); - mutex_lock(&cfile->fh_mutex); + if (!(flags & CIFS_REOPEN_NOWAIT)) { + mutex_lock(&cfile->fh_mutex); + } else if (!mutex_trylock(&cfile->fh_mutex)) { + free_xid(xid); + return -EAGAIN; + } if (!cfile->invalidHandle) { mutex_unlock(&cfile->fh_mutex); free_xid(xid); return 0; } + if (reopen_aborted(tcon, aborts)) { + mutex_unlock(&cfile->fh_mutex); + free_xid(xid); + return -EHOSTDOWN; + } inode = d_inode(cfile->dentry); cifs_sb = CIFS_SB(inode->i_sb); - tcon = tlink_tcon(cfile->tlink); server = tcon->ses->server; /* @@ -1359,6 +1827,10 @@ cifs_reopen_file(struct cifsFileInfo *cfile, bool can_flush) if (cifs_fscache_enabled(inode) && (cfile->f_flags & O_ACCMODE) == O_WRONLY) rdwr_for_fscache = 1; + if (cfile->reopen_replay && rdwr_for_fscache == 1 && + !(cfile->reopen_access & GENERIC_READ)) + rdwr_for_fscache = 2; + desired_access = cifs_convert_flags(cfile->f_flags, rdwr_for_fscache); create_options |= cifs_open_create_options(cfile->f_flags, create_options); @@ -1367,15 +1839,21 @@ cifs_reopen_file(struct cifsFileInfo *cfile, bool can_flush) server->ops->get_lease_key(inode, &cfile->fid); retry_open: + fresh = cfile->reopen_fresh; oparms = (struct cifs_open_parms) { .tcon = tcon, .cifs_sb = cifs_sb, - .desired_access = desired_access, + .desired_access = cfile->reopen_replay ? + cfile->reopen_access : desired_access, .create_options = cifs_create_options(cifs_sb, create_options), .disposition = disposition, .path = full_path, .fid = &cfile->fid, - .reconnect = true, + .reconnect = !fresh, + .replay = cfile->reopen_replay, + .pending = cfile->reopen_replay, + .no_replay = !!(flags & CIFS_REOPEN_BOUND), + .no_reconnect_wait = !!(flags & CIFS_REOPEN_NOWAIT), }; /* @@ -1385,14 +1863,28 @@ retry_open: * version of file size can be stale. If we knew for sure that inode was * not dirty locally we could do this. */ - rc = server->ops->open(xid, &oparms, &oplock, NULL); - if (rc == -ENOENT && oparms.reconnect == false) { - /* durable handle timeout is expired - open the file again */ + if (reopen_aborted(tcon, aborts)) + rc = -EHOSTDOWN; + else rc = server->ops->open(xid, &oparms, &oplock, NULL); - /* indicate that we need to relock the file */ - oparms.reconnect = true; + if (rc == -ENOENT && !fresh && !oparms.reconnect && !oparms.pending) { + /* durable handle timeout is expired - open the file again */ + fresh = true; + oparms.desired_access = desired_access; + oparms.replay = false; + if (reopen_aborted(tcon, aborts)) + rc = -EHOSTDOWN; + else + rc = server->ops->open(xid, &oparms, &oplock, NULL); } - if (rc == -EACCES && rdwr_for_fscache == 1) { + cfile->reopen_fresh = rc && fresh; + cfile->reopen_replay = rc && oparms.pending; + if (cfile->reopen_replay) + cfile->reopen_access = oparms.desired_access; + /* indicate that we need to relock the file */ + if (fresh) + oparms.reconnect = true; + if (rc == -EACCES && rdwr_for_fscache == 1 && !oparms.pending) { desired_access = cifs_convert_flags(cfile->f_flags, 0); rdwr_for_fscache = 2; goto retry_open; @@ -1411,6 +1903,8 @@ retry_open: #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY reopen_success: #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */ + /* pairs with smp_load_acquire() in __cifs_issue_write() */ + smp_store_release(&cfile->reopens, cfile->reopens + 1); cfile->invalidHandle = false; mutex_unlock(&cfile->fh_mutex); cinode = CIFS_I(inode); @@ -1546,14 +2040,16 @@ int cifs_close(struct inode *inode, struct file *file) return 0; } -void +bool cifs_reopen_persistent_handles(struct cifs_tcon *tcon) { struct cifsFileInfo *open_file, *tmp; LIST_HEAD(tmp_list); + bool retry = false; + int rc; if (!tcon->use_persistent || !tcon->need_reopen_files) - return; + return false; tcon->need_reopen_files = false; @@ -1570,11 +2066,17 @@ cifs_reopen_persistent_handles(struct cifs_tcon *tcon) spin_unlock(&tcon->open_file_lock); list_for_each_entry_safe(open_file, tmp, &tmp_list, rlist) { - if (cifs_reopen_file(open_file, false /* do not flush */)) + /* do not flush */ + rc = cifs_reopen_file(open_file, false, + CIFS_REOPEN_BOUND | CIFS_REOPEN_NOWAIT); + if (rc) { tcon->need_reopen_files = true; + retry |= is_replayable_error(rc); + } list_del_init(&open_file->rlist); cifsFileInfo_put(open_file); } + return retry; } int cifs_closedir(struct inode *inode, struct file *file) @@ -2235,7 +2737,7 @@ cifs_get_hardlink_path(struct cifs_tcon *tcon, struct inode *inode, spin_lock(&cinode->open_file_lock); list_for_each_entry(open_file, &cinode->openFileList, flist) { - if (file->f_flags == open_file->f_flags) { + if (open_file->dentry != file_dentry(file)) { rc = -EINVAL; break; } @@ -2629,6 +3131,20 @@ void cifs_write_subrequest_terminated(struct cifs_io_subrequest *wdata, ssize_t spin_unlock(&inode->i_lock); } + if (wreq->origin == NETFS_WRITEBACK && + !test_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags) && + cifs_writeback_transient(result) && cifs_io_should_replay(wdata)) { + if (result == -EBADF) + cifs_mark_bad_handle(wdata->req, wdata->reopens); + wdata->replay = true; + trace_netfs_sreq(&wdata->subreq, + netfs_sreq_trace_io_retry_needed); + __set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags); + } + + if (result < 0 && + !test_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags)) + result = cifs_writeback_error(&wdata->subreq, result); netfs_write_subrequest_terminated(&wdata->subreq, result); } @@ -2722,7 +3238,7 @@ int __cifs_get_writable_file(struct cifsInodeInfo *cifs_inode, } if (test_bit(CIFS_INO_TMPFILE, &cifs_inode->flags)) - find_flags = FIND_ANY; + find_flags &= FIND_NO_REOPEN | FIND_NO_DIRECT; cifs_sb = CIFS_SB(cifs_inode); @@ -2752,6 +3268,9 @@ refind_writable: !open_flags_match(cifs_inode, open_flags, open_file->f_flags)) continue; + if ((find_flags & FIND_NO_DIRECT) && + (open_file->f_flags & O_DIRECT)) + continue; if (OPEN_FMODE(open_file->f_flags) & FMODE_WRITE) { if (!open_file->invalidHandle) { /* found a good writable file */ @@ -2779,7 +3298,11 @@ refind_writable: spin_unlock(&cifs_inode->open_file_lock); if (inv_file) { - rc = cifs_reopen_file(inv_file, false); + if (find_flags & FIND_NO_REOPEN) { + *ret_file = inv_file; + return 0; + } + rc = cifs_reopen_file(inv_file, false, 0); if (!rc) { *ret_file = inv_file; return 0; @@ -2880,6 +3403,45 @@ cifs_get_readable_path(struct cifs_tcon *tcon, const char *name, return -ENOENT; } +static int cifs_wait_writeback_killable(struct address_space *mapping, + loff_t start, loff_t end) +{ + pgoff_t end_index = end >> PAGE_SHIFT; + pgoff_t index = start >> PAGE_SHIFT; + struct folio_batch fbatch; + int rc = 0; + + folio_batch_init(&fbatch); + while (!rc && + filemap_get_folios_tag(mapping, &index, end_index, + PAGECACHE_TAG_WRITEBACK, &fbatch)) { + for (unsigned int i = 0; + !rc && i < folio_batch_count(&fbatch); i++) + rc = folio_wait_writeback_killable(fbatch.folios[i]); + folio_batch_release(&fbatch); + cond_resched(); + } + return rc; +} + +static int cifs_file_write_and_wait_killable(struct file *file, + loff_t start, loff_t end) +{ + struct address_space *mapping = file->f_mapping; + int rc, rc2; + + if (end < start) + return 0; + + rc = filemap_fdatawrite_range(mapping, start, end); + if (cifs_wait_writeback_killable(mapping, start, end)) + return -EINTR; + rc2 = file_check_and_advance_wb_err(file); + if (!rc) + rc = rc2; + return rc; +} + /* * Flush data on a strict file. */ @@ -2891,7 +3453,7 @@ int cifs_strict_fsync(struct file *file, loff_t start, loff_t end, unsigned int xid; int rc; - rc = file_write_and_wait_range(file, start, end); + rc = cifs_file_write_and_wait_killable(file, start, end); if (rc) { trace_cifs_fsync_err(inode->i_ino, rc); return rc; @@ -2923,7 +3485,7 @@ int cifs_fsync(struct file *file, loff_t start, loff_t end, int datasync) struct inode *inode = file_inode(file); struct cifs_sb_info *cifs_sb = CIFS_SB(file); - rc = file_write_and_wait_range(file, start, end); + rc = cifs_file_write_and_wait_killable(file, start, end); if (rc) { trace_cifs_fsync_err(file_inode(file)->i_ino, rc); return rc; @@ -2964,11 +3526,19 @@ fsync_exit: */ int cifs_flush(struct file *file, fl_owner_t id) { + struct address_space *mapping = file->f_mapping; struct inode *inode = file_inode(file); - int rc = 0; + int rc = 0, rc2; - if (file->f_mode & FMODE_WRITE) - rc = filemap_write_and_wait(inode->i_mapping); + if (file->f_mode & FMODE_WRITE) { + rc = filemap_fdatawrite(mapping); + if (fatal_signal_pending(current) || + cifs_wait_writeback_killable(mapping, 0, LLONG_MAX)) + return 0; + rc2 = filemap_check_errors(mapping); + if (!rc) + rc = rc2; + } cifs_dbg(FYI, "Flush inode %p file %p rc %d\n", inode, file, rc); if (rc) { @@ -3357,6 +3927,14 @@ void cifs_oplock_break(struct work_struct *work) __u64 persistent_fid, volatile_fid; __u16 net_fid; + /* + * Dropping the handle reference below also drops the dentry + * reference that pins this inode, and cinode is still needed to + * acknowledge the break and to report it as complete. Hold the inode + * until that is done. + */ + ihold(inode); + wait_on_bit(&cinode->flags, CIFS_INODE_PENDING_WRITERS, TASK_UNINTERRUPTIBLE); @@ -3444,6 +4022,7 @@ oplock_break_ack: cifs_put_tlink(tlink); out: cifs_done_oplock_break(cinode); + iput(inode); } #ifdef CONFIG_SWAP diff --git a/fs/smb/client/misc.c b/fs/smb/client/misc.c index ec28f102ea08..4d0df73d15d7 100644 --- a/fs/smb/client/misc.c +++ b/fs/smb/client/misc.c @@ -1073,7 +1073,17 @@ int cifs_inval_name_dfs_link_error(const unsigned int xid, } #endif -int cifs_wait_for_server_reconnect(struct TCP_Server_Info *server, bool retry) +static bool reco_wait_done(struct TCP_Server_Info *server, + struct cifs_tcon *tcon, int aborts) +{ + return server->tcpStatus != CifsNeedReconnect || + atomic_read(&tcon->umount_aborts) != aborts || + cifs_tcon_dying(tcon); +} + +int cifs_wait_for_server_reconnect(struct TCP_Server_Info *server, + struct cifs_tcon *tcon, int aborts, + bool nowait) { int timeout = 10; int rc; @@ -1083,6 +1093,10 @@ int cifs_wait_for_server_reconnect(struct TCP_Server_Info *server, bool retry) spin_unlock(&server->srv_lock); return 0; } + if (nowait) { + spin_unlock(&server->srv_lock); + return -EAGAIN; + } timeout *= server->nr_targets; spin_unlock(&server->srv_lock); @@ -1096,7 +1110,9 @@ int cifs_wait_for_server_reconnect(struct TCP_Server_Info *server, bool retry) */ do { rc = wait_event_interruptible_timeout(server->response_q, - (server->tcpStatus != CifsNeedReconnect), + reco_wait_done(server, + tcon, + aborts), timeout * HZ); if (rc < 0) { cifs_dbg(FYI, "%s: aborting reconnect due to received signal\n", @@ -1111,7 +1127,7 @@ int cifs_wait_for_server_reconnect(struct TCP_Server_Info *server, bool retry) return 0; } spin_unlock(&server->srv_lock); - } while (retry); + } while (cifs_tcon_retry(tcon, aborts)); cifs_dbg(FYI, "%s: gave up waiting on reconnect\n", __func__); return -EHOSTDOWN; diff --git a/fs/smb/client/sess.c b/fs/smb/client/sess.c index c1fc90726e2d..fe006e9f2e10 100644 --- a/fs/smb/client/sess.c +++ b/fs/smb/client/sess.c @@ -666,8 +666,8 @@ int decode_ntlmssp_challenge(char *bcc_ptr, int blob_len, } if (memcmp(pblob->Signature, "NTLMSSP", 8)) { - cifs_dbg(VFS, "blob signature incorrect %s\n", - pblob->Signature); + cifs_dbg(VFS, "%s: blob signature incorrect: %8phN\n", + __func__, pblob->Signature); return -EINVAL; } if (pblob->MessageType != NtLmChallenge) { diff --git a/fs/smb/client/smb2file.c b/fs/smb/client/smb2file.c index fb2fccbe8667..764cfd894ad0 100644 --- a/fs/smb/client/smb2file.c +++ b/fs/smb/client/smb2file.c @@ -175,6 +175,7 @@ int smb2_open_file(const unsigned int xid, struct cifs_open_parms *oparms, struct cifs_fid *fid = oparms->fid; struct network_resiliency_req nr_ioctl_req; bool retry_without_read_attributes = false; + bool reconnect = oparms->reconnect; smb2_path = cifs_convert_path_to_utf16(oparms->path, oparms->cifs_sb); if (smb2_path == NULL) @@ -186,23 +187,30 @@ int smb2_open_file(const unsigned int xid, struct cifs_open_parms *oparms, * FILE_READ_ATTRIBUTES when not needed and prevent calling code path * for retry_without_read_attributes. */ - if (!(oparms->desired_access & FILE_READ_ATTRIBUTES) && - !(oparms->desired_access & GENERIC_READ) && + if (!(oparms->desired_access & GENERIC_READ) && !(oparms->desired_access & GENERIC_EXECUTE) && !(oparms->desired_access & GENERIC_ALL) && !(oparms->desired_access & MAXIMUM_ALLOWED)) { - oparms->desired_access |= FILE_READ_ATTRIBUTES; - retry_without_read_attributes = true; + if (oparms->replay) { + retry_without_read_attributes = + oparms->desired_access & FILE_READ_ATTRIBUTES; + } else if (!(oparms->desired_access & FILE_READ_ATTRIBUTES)) { + oparms->desired_access |= FILE_READ_ATTRIBUTES; + retry_without_read_attributes = true; + } } smb2_oplock = SMB2_OPLOCK_LEVEL_BATCH; rc = SMB2_open(xid, oparms, smb2_path, &smb2_oplock, data, NULL, &err_iov, &err_buftype); - if (rc == -EACCES && retry_without_read_attributes) { + if (rc == -EACCES && retry_without_read_attributes && + !oparms->pending) { free_rsp_buf(err_buftype, err_iov.iov_base); memset(&err_iov, 0, sizeof(err_iov)); err_buftype = CIFS_NO_BUFFER; oparms->desired_access &= ~FILE_READ_ATTRIBUTES; + oparms->reconnect = reconnect; + oparms->replay = false; rc = SMB2_open(xid, oparms, smb2_path, &smb2_oplock, data, NULL, &err_iov, &err_buftype); } diff --git a/fs/smb/client/smb2ops.c b/fs/smb/client/smb2ops.c index dc55cd512616..298f549bd7ed 100644 --- a/fs/smb/client/smb2ops.c +++ b/fs/smb/client/smb2ops.c @@ -244,7 +244,7 @@ smb2_get_credits(struct mid_q_entry *mid) static int smb2_wait_mtu_credits(struct TCP_Server_Info *server, size_t size, - size_t *num, struct cifs_credits *credits) + size_t *num, struct cifs_credits *credits, bool nowait) { int rc = 0; unsigned int scredits, in_flight; @@ -258,6 +258,10 @@ smb2_wait_mtu_credits(struct TCP_Server_Info *server, size_t size, spin_unlock(&server->srv_lock); return -ENOENT; } + if (nowait && server->tcpStatus == CifsNeedReconnect) { + spin_unlock(&server->srv_lock); + return -EAGAIN; + } spin_unlock(&server->srv_lock); spin_lock(&server->req_lock); @@ -265,7 +269,8 @@ smb2_wait_mtu_credits(struct TCP_Server_Info *server, size_t size, spin_unlock(&server->req_lock); cifs_num_waiters_inc(server); rc = wait_event_killable(server->request_q, - has_credits(server, &server->credits, 1)); + credits_or_conn_down(server, &server->credits, + 1, nowait)); cifs_num_waiters_dec(server); if (rc) return rc; @@ -2933,15 +2938,12 @@ bool smb2_should_replay(struct cifs_tcon *tcon, if (!pretries || !pcur_sleep) return false; + /* the tcon is being torn down; stop replaying */ + if (cifs_tcon_dying(tcon)) + return false; + if (tcon->retry || (*pretries)++ < tcon->ses->server->retrans) { - /* Update sleep time for exponential backoff */ - if (!(*pcur_sleep)) - (*pcur_sleep) = 1; - else { - (*pcur_sleep) = ((*pcur_sleep) << 1); - if ((*pcur_sleep) > CIFS_MAX_SLEEP) - (*pcur_sleep) = CIFS_MAX_SLEEP; - } + smb2_replay_backoff(pcur_sleep); return true; } diff --git a/fs/smb/client/smb2pdu.c b/fs/smb/client/smb2pdu.c index f85595136ef8..b26bfb4bd91a 100644 --- a/fs/smb/client/smb2pdu.c +++ b/fs/smb/client/smb2pdu.c @@ -248,11 +248,14 @@ int smb3_update_ses_channels(struct cifs_ses *ses, struct TCP_Server_Info *serve static int smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon, - struct TCP_Server_Info *server, bool from_reconnect) + struct TCP_Server_Info *server, bool from_reconnect, + bool nowait) { + bool hold_server_ref = false; struct cifs_ses *ses; - int xid; int rc = 0; + int aborts; + int xid; /* * SMB2s NegProt, SessSetup, Logoff do not have tcon yet so @@ -262,6 +265,8 @@ smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon, if (tcon == NULL) return 0; + aborts = atomic_read(&tcon->umount_aborts); + if (smb2_command == SMB2_TREE_CONNECT) return 0; @@ -308,6 +313,10 @@ smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon, spin_unlock(&server->srv_lock); return -EAGAIN; } + if (nowait) { + spin_unlock(&server->srv_lock); + return -EAGAIN; + } } /* if server is marked for termination, cifsd will cleanup */ @@ -318,7 +327,7 @@ smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon, spin_unlock(&server->srv_lock); again: - rc = cifs_wait_for_server_reconnect(server, tcon->retry); + rc = cifs_wait_for_server_reconnect(server, tcon, aborts, nowait); if (rc) return rc; @@ -346,7 +355,9 @@ again: case CifsNeedReconnect: spin_unlock(&server->srv_lock); mutex_unlock(&ses->session_mutex); - if (!tcon->retry) + if (nowait) + return -EAGAIN; + if (!cifs_tcon_retry(tcon, aborts)) return -EHOSTDOWN; goto again; default: @@ -377,7 +388,9 @@ again: rc = cifs_negotiate_protocol(0, ses, server); if (rc) { mutex_unlock(&ses->session_mutex); - if (!tcon->retry) + if (nowait) + return -EAGAIN; + if (!cifs_tcon_retry(tcon, aborts)) return -EHOSTDOWN; goto again; } @@ -470,6 +483,20 @@ skip_sess_setup: * treat this as server not supporting multichannel */ + /* + * If server is a secondary channel, + * cifs_chan_skip_or_disable() called below may + * drop its last reference, so hold our own + * reference until the reconnect work below has + * been queued. + */ + spin_lock(&cifs_tcp_ses_lock); + if (server->srv_count) { + server->srv_count++; + hold_server_ref = true; + } + spin_unlock(&cifs_tcp_ses_lock); + rc = smb3_update_ses_channels(ses, server, from_reconnect, true /* disable_mchan */); @@ -498,6 +525,8 @@ skip_add_channels: if (smb2_command != SMB2_INTERNAL_CMD) cifs_queue_server_reconn(server); + if (hold_server_ref) + cifs_put_tcp_session(server, from_reconnect); atomic_inc(&tconInfoReconnectCount); out: @@ -589,7 +618,22 @@ static int smb2_plain_req_init(__le16 smb2_command, struct cifs_tcon *tcon, { int rc; - rc = smb2_reconnect(smb2_command, tcon, server, false); + rc = smb2_reconnect(smb2_command, tcon, server, false, false); + if (rc) + return rc; + + return __smb2_plain_req_init(smb2_command, tcon, server, request_buf, + total_len); +} + +/* As smb2_plain_req_init(), but fail fast instead of waiting for reconnect. */ +static int smb2_io_req_init(__le16 smb2_command, struct cifs_tcon *tcon, + struct TCP_Server_Info *server, + void **request_buf, unsigned int *total_len) +{ + int rc; + + rc = smb2_reconnect(smb2_command, tcon, server, false, true); if (rc) return rc; @@ -3144,8 +3188,12 @@ SMB2_open_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server, __le16 *copy_path; int rc; - rc = smb2_plain_req_init(SMB2_CREATE, tcon, server, - (void **) &req, &total_len); + if (oparms->no_reconnect_wait) + rc = smb2_io_req_init(SMB2_CREATE, tcon, server, + (void **) &req, &total_len); + else + rc = smb2_plain_req_init(SMB2_CREATE, tcon, server, + (void **) &req, &total_len); if (rc) return rc; @@ -3329,14 +3377,25 @@ SMB2_open(const unsigned int xid, struct cifs_open_parms *oparms, __le16 *path, int flags = 0; int retries = 0, cur_sleep = 0; struct smb2_file_all_info *file_info = buf ? &buf->fi : NULL; + bool reconnect = oparms->reconnect; + bool replay = oparms->replay; + bool unanswered = replay; + bool answered; + bool sent; replay_again: /* reinitialize for possible replay */ + answered = false; + sent = false; resp_buftype = CIFS_NO_BUFFER; memset(&rsp_iov, 0, sizeof(rsp_iov)); flags = 0; server = cifs_pick_channel(ses); - oparms->replay = !!(retries); + /* reissue the same create: a durable reconnect clears ->reconnect */ + oparms->reconnect = reconnect; + /* with no_replay the caller owns oparms->replay */ + if (!oparms->no_replay) + oparms->replay = unanswered; cifs_dbg(FYI, "create/open\n"); if (!ses || !server) @@ -3344,6 +3403,8 @@ replay_again: if (smb3_encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; + if (oparms->no_reconnect_wait) + flags |= CIFS_NO_RECONNECT_WAIT; memset(&rqst, 0, sizeof(struct smb_rqst)); memset(&iov, 0, sizeof(iov)); @@ -3354,21 +3415,22 @@ replay_again: &rqst, oplock, oparms, path); if (rc) goto creat_exit; + sent = true; trace_smb3_open_enter(xid, tcon->tid, tcon->ses->Suid, oparms->path, oparms->create_options, oparms->desired_access); - if (retries) { - /* Back-off before retry */ - if (cur_sleep) - msleep(cur_sleep); + /* Back-off before retry */ + if (cur_sleep) + msleep(cur_sleep); + if (oparms->replay) smb2_set_replay(server, &rqst); - } rc = cifs_send_recv(xid, ses, server, &rqst, &resp_buftype, flags, &rsp_iov); rsp = (struct smb2_create_rsp *)rsp_iov.iov_base; + answered = rsp; if (rc != 0) { cifs_stats_fail_inc(tcon, SMB2_CREATE_HE); @@ -3425,10 +3487,27 @@ creat_exit: SMB2_open_free(&rqst); free_rsp_buf(resp_buftype, rsp); - if (is_replayable_error(rc) && - smb2_should_replay(tcon, &retries, &cur_sleep)) + if (sent) { + if (!rc || (answered && (!oparms->replay || + !is_replayable_error(rc)))) + unanswered = false; + else if (!answered && !is_interrupt_error(rc)) + unanswered = true; + oparms->pending = unanswered; + } + + if (!oparms->no_replay && is_replayable_error(rc) && + smb2_should_replay(tcon, &retries, &cur_sleep)) { + if (err_iov && answered && !rsp) { + free_rsp_buf(*buftype, err_iov->iov_base); + *err_iov = (struct kvec){}; + *buftype = CIFS_NO_BUFFER; + } goto replay_again; + } + if (!oparms->no_replay) + oparms->replay = replay; return rc; } @@ -3439,11 +3518,12 @@ SMB2_ioctl_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server, char *in_data, u32 indatalen, __u32 max_response_size) { - struct smb2_ioctl_req *req; struct kvec *iov = rqst->rq_iov; + struct smb2_ioctl_req *req; + u32 in_buf_len = indatalen; unsigned int total_len; - int rc; char *in_data_buf; + int rc; rc = smb2_ioctl_req_init(opcode, tcon, server, (void **) &req, &total_len); @@ -3451,15 +3531,18 @@ SMB2_ioctl_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server, return rc; if (indatalen) { + if (smb3_encryption_required(tcon)) + in_buf_len = ALIGN(indatalen, 8); /* * indatalen is usually small at a couple of bytes max, so * just allocate through generic pool */ - in_data_buf = kmemdup(in_data, indatalen, GFP_NOFS); + in_data_buf = kzalloc(in_buf_len, GFP_NOFS); if (!in_data_buf) { cifs_small_buf_release(req); return -ENOMEM; } + memcpy(in_data_buf, in_data, indatalen); } req->CtlCode = cpu_to_le32(opcode); @@ -3483,7 +3566,7 @@ SMB2_ioctl_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server, rqst->rq_nvec = 2; iov[0].iov_len = total_len - 1; iov[1].iov_base = in_data_buf; - iov[1].iov_len = indatalen; + iov[1].iov_len = in_buf_len; } else { rqst->rq_nvec = 1; iov[0].iov_len = total_len; @@ -4023,6 +4106,14 @@ replay_again: ses->Suid, info_class, (__u32)info_type); if (dlen) { + rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset), + le32_to_cpu(rsp->OutputBufferLength), + &rsp_iov, min_len); + if (rc) { + *dlen = 0; + goto qinf_exit; + } + *dlen = le32_to_cpu(rsp->OutputBufferLength); if (!*data) { *data = kmalloc(*dlen, GFP_KERNEL); @@ -4077,7 +4168,8 @@ SMB2_query_acl(const unsigned int xid, struct cifs_tcon *tcon, return query_info(xid, tcon, persistent_fid, volatile_fid, 0, SMB2_O_INFO_SECURITY, extra_info, - SMB2_MAX_BUFFER_SIZE, MIN_SEC_DESC_LEN, data, plen); + SMB2_MAX_BUFFER_SIZE, sizeof(struct smb_ntsd), + data, plen); } int @@ -4354,10 +4446,12 @@ void smb2_reconnect_server(struct work_struct *work) spin_unlock(&cifs_tcp_ses_lock); list_for_each_entry_safe(tcon, tcon2, &tmp_list, rlist) { - rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon, server, true); + rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon, server, true, + true); if (!rc) { cifs_renegotiate_iosize(server, tcon); - cifs_reopen_persistent_handles(tcon); + if (cifs_reopen_persistent_handles(tcon)) + resched = true; } else resched = true; list_del_init(&tcon->rlist); @@ -4386,7 +4480,8 @@ void smb2_reconnect_server(struct work_struct *work) /* now reconnect sessions for necessary channels */ list_for_each_entry_safe(ses, ses2, &tmp_ses_list, rlist) { tcon->ses = ses; - rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon, server, true); + rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon, server, true, + true); if (rc) resched = true; list_del_init(&ses->rlist); @@ -4695,6 +4790,7 @@ smb2_readv_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid) struct smb_rqst rqst = { .rq_iov = &rdata->iov[0], .rq_nvec = 1 }; unsigned int rreq_debug_id = rdata->rreq->debug_id; unsigned int subreq_debug_index = rdata->subreq.debug_index; + bool cut_short = false; if (rdata->got_bytes) { rqst.rq_iter = rdata->subreq.io_iter; @@ -4743,6 +4839,7 @@ smb2_readv_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid) trace_netfs_sreq(&rdata->subreq, netfs_sreq_trace_io_retry_needed); do_retry: __set_bit(NETFS_SREQ_NEED_RETRY, &rdata->subreq.flags); + cut_short = true; rdata->result = -EAGAIN; if (server->sign && rdata->got_bytes) /* reset bytes number since we can not check a sign */ @@ -4815,9 +4912,7 @@ do_retry: /* see if we need to retry */ if (is_replayable_error(rdata->result) && - smb2_should_replay(tcon, - &rdata->retries, - &rdata->cur_sleep)) + (cut_short || cifs_io_should_replay(rdata))) rdata->replay = true; trace_smb3_rw_credits(rreq_debug_id, subreq_debug_index, rdata->credits.value, @@ -4880,12 +4975,8 @@ smb2_async_readv(struct cifs_io_subrequest *rdata) shdr = (struct smb2_hdr *)buf; - if (rdata->replay) { - /* Back-off before retry */ - if (rdata->cur_sleep) - msleep(rdata->cur_sleep); + if (rdata->replay) smb2_set_replay(server, &rqst); - } if (rdata->credits.value > 0) { shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(io_parms.length, @@ -4926,9 +5017,7 @@ async_readv_out: out: /* if the send error is retryable, let netfs know about it */ if (is_replayable_error(rc) && - smb2_should_replay(tcon, - &rdata->retries, - &rdata->cur_sleep)) { + cifs_io_should_replay(rdata)) { rdata->replay = true; trace_netfs_sreq(&rdata->subreq, netfs_sreq_trace_io_retry_needed); __set_bit(NETFS_SREQ_NEED_RETRY, &rdata->subreq.flags); @@ -5060,6 +5149,7 @@ smb2_writev_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid) }; unsigned int rreq_debug_id = wdata->rreq->debug_id; unsigned int subreq_debug_index = wdata->subreq.debug_index; + bool cut_short = false; ssize_t result = 0; size_t written = 0; @@ -5073,10 +5163,7 @@ smb2_writev_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid) credits.instance = server->reconnect_instance; result = smb2_check_receive(mid, server, 0); if (result != 0) { - if (is_replayable_error(result)) { - trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_retry_needed); - __set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags); - } else { + if (!is_replayable_error(result)) { wdata->subreq.error = result; trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_bad); } @@ -5105,12 +5192,9 @@ smb2_writev_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid) break; case MID_REQUEST_SUBMITTED: trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_req_submitted); - __set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags); - result = -EAGAIN; - break; + fallthrough; case MID_RETRY_NEEDED: - trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_retry_needed); - __set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags); + cut_short = true; result = -EAGAIN; break; case MID_RESPONSE_MALFORMED: @@ -5164,11 +5248,17 @@ smb2_writev_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid) wdata->credits.value = 0; /* see if we need to retry */ - if (is_replayable_error(wdata->result) && - smb2_should_replay(tcon, - &wdata->retries, - &wdata->cur_sleep)) + if (is_replayable_error(result) && + ((cut_short && wdata->rreq->origin != NETFS_WRITEBACK && + !cifs_io_stopped(wdata)) || + cifs_io_should_replay(wdata))) { wdata->replay = true; + trace_netfs_sreq(&wdata->subreq, + netfs_sreq_trace_io_retry_needed); + __set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags); + } else if (cut_short && cifs_io_stopped(wdata)) { + result = -EIO; + } cifs_write_subrequest_terminated(wdata, result ?: written); release_mid(server, mid); @@ -5209,8 +5299,14 @@ smb2_async_writev(struct cifs_io_subrequest *wdata) }; io_parms = &_io_parms; - rc = smb2_plain_req_init(SMB2_WRITE, tcon, server, - (void **) &req, &total_len); + if (wdata->subreq.rreq->origin == NETFS_WRITEBACK) { + flags |= CIFS_NO_RECONNECT_WAIT; + rc = smb2_io_req_init(SMB2_WRITE, tcon, server, + (void **) &req, &total_len); + } else { + rc = smb2_plain_req_init(SMB2_WRITE, tcon, server, + (void **) &req, &total_len); + } if (rc) goto out; @@ -5286,12 +5382,8 @@ smb2_async_writev(struct cifs_io_subrequest *wdata) } #endif - if (wdata->replay) { - /* Back-off before retry */ - if (wdata->cur_sleep) - msleep(wdata->cur_sleep); + if (wdata->replay) smb2_set_replay(server, &rqst); - } cifs_dbg(FYI, "async write at %llu %u bytes iter=%zx\n", io_parms->offset, io_parms->length, iov_iter_count(&wdata->subreq.io_iter)); @@ -5339,9 +5431,7 @@ async_writev_out: out: /* if the send error is retryable, let netfs know about it */ if (is_replayable_error(rc) && - smb2_should_replay(tcon, - &wdata->retries, - &wdata->cur_sleep)) { + cifs_io_should_replay(wdata)) { wdata->replay = true; trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_retry_needed); __set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags); diff --git a/fs/smb/client/smb2proto.h b/fs/smb/client/smb2proto.h index c79e5cb2ce26..b2acff8938f3 100644 --- a/fs/smb/client/smb2proto.h +++ b/fs/smb/client/smb2proto.h @@ -121,6 +121,15 @@ unsigned long smb_rqst_len(struct TCP_Server_Info *server, void smb2_set_next_command(struct cifs_tcon *tcon, struct smb_rqst *rqst); void smb2_set_related(struct smb_rqst *rqst); void smb2_set_replay(struct TCP_Server_Info *server, struct smb_rqst *rqst); + +static inline void smb2_replay_backoff(int *pcur_sleep) +{ + if (!*pcur_sleep) + *pcur_sleep = 1; + else + *pcur_sleep = min(*pcur_sleep << 1, CIFS_MAX_SLEEP); +} + bool smb2_should_replay(struct cifs_tcon *tcon, int *pretries, int *pcur_sleep); diff --git a/fs/smb/client/transport.c b/fs/smb/client/transport.c index d0d0159c1061..c51f99d7be4b 100644 --- a/fs/smb/client/transport.c +++ b/fs/smb/client/transport.c @@ -430,6 +430,7 @@ wait_for_free_credits(struct TCP_Server_Info *server, const int num_credits, const int timeout, const int flags, unsigned int *instance) { + bool nowait = flags & CIFS_NO_RECONNECT_WAIT; long rc; int *credits; int optype; @@ -478,6 +479,10 @@ wait_for_free_credits(struct TCP_Server_Info *server, const int num_credits, spin_unlock(&server->srv_lock); return -ENOENT; } + if (nowait && server->tcpStatus == CifsNeedReconnect) { + spin_unlock(&server->srv_lock); + return -EAGAIN; + } spin_unlock(&server->srv_lock); spin_lock(&server->req_lock); @@ -487,7 +492,8 @@ wait_for_free_credits(struct TCP_Server_Info *server, const int num_credits, cifs_num_waiters_inc(server); rc = wait_event_killable_timeout(server->request_q, - has_credits(server, credits, num_credits), t); + credits_or_conn_down(server, credits, + num_credits, nowait), t); cifs_num_waiters_dec(server); if (!rc) { spin_lock(&server->req_lock); @@ -527,8 +533,9 @@ wait_for_free_credits(struct TCP_Server_Info *server, const int num_credits, cifs_num_waiters_inc(server); rc = wait_event_killable_timeout( server->request_q, - has_credits(server, credits, - MAX_COMPOUND + 1), + credits_or_conn_down(server, credits, + MAX_COMPOUND + 1, + nowait), t); cifs_num_waiters_dec(server); if (!rc) { @@ -595,6 +602,10 @@ wait_for_compound_request(struct TCP_Server_Info *server, int num, credits = server->ops->get_credits_field(server, flags & CIFS_OP_MASK); + if ((flags & CIFS_NO_RECONNECT_WAIT) && + READ_ONCE(server->tcpStatus) == CifsNeedReconnect) + return -EAGAIN; + spin_lock(&server->req_lock); scredits = *credits; in_flight = server->in_flight; @@ -618,6 +629,9 @@ wait_for_compound_request(struct TCP_Server_Info *server, int num, */ if (server->in_flight == 0) { spin_unlock(&server->req_lock); + if ((flags & CIFS_NO_RECONNECT_WAIT) && + READ_ONCE(server->tcpStatus) == CifsNeedReconnect) + return -EAGAIN; trace_smb3_insufficient_credits(server->current_mid, server->conn_id, server->hostname, scredits, num, in_flight); @@ -634,7 +648,7 @@ wait_for_compound_request(struct TCP_Server_Info *server, int num, int cifs_wait_mtu_credits(struct TCP_Server_Info *server, size_t size, - size_t *num, struct cifs_credits *credits) + size_t *num, struct cifs_credits *credits, bool nowait) { *num = size; credits->value = 0; diff --git a/fs/smb/server/mgmt/user_config.h b/fs/smb/server/mgmt/user_config.h index cc460b4ff7d3..e116b2ee9917 100644 --- a/fs/smb/server/mgmt/user_config.h +++ b/fs/smb/server/mgmt/user_config.h @@ -67,4 +67,9 @@ struct ksmbd_user *ksmbd_alloc_user(struct ksmbd_login_response *resp, void ksmbd_free_user(struct ksmbd_user *user); bool ksmbd_anonymous_user(struct ksmbd_user *user); bool ksmbd_compare_user(struct ksmbd_user *u1, struct ksmbd_user *u2); + +static inline bool ksmbd_user_authenticated(struct ksmbd_user *user) +{ + return user && !user_guest(user) && !ksmbd_anonymous_user(user); +} #endif /* __USER_CONFIG_MANAGEMENT_H__ */ diff --git a/fs/smb/server/smb2pdu.c b/fs/smb/server/smb2pdu.c index db10c099219d..fe17d4061237 100644 --- a/fs/smb/server/smb2pdu.c +++ b/fs/smb/server/smb2pdu.c @@ -2365,6 +2365,17 @@ static int ntlm_authenticate(struct ksmbd_work *work, return -EKEYREJECTED; } ksmbd_free_user(user); + } else if (sess->user) { + /* + * Reauthentication of an expired session: as for a valid + * session, and as krb5_authenticate() does, it must be by the + * same user. Replacing sess->user would also leak the old one. + */ + if (!ksmbd_compare_user(sess->user, user)) { + ksmbd_free_user(user); + return -EKEYREJECTED; + } + ksmbd_free_user(user); } else { sess->user = user; } @@ -3541,7 +3552,8 @@ next: static noinline int smb2_set_stream_name_xattr(const struct path *path, struct ksmbd_file *fp, - char *stream_name, int s_type) + char *stream_name, int s_type, + bool *created) { const struct mnt_idmap *idmap = mnt_idmap(path->mnt); size_t xattr_stream_size; @@ -3605,6 +3617,8 @@ static noinline int smb2_set_stream_name_xattr(const struct path *path, rc = ksmbd_vfs_setxattr(idmap, path, xattr_stream_name, NULL, 0, 0, false); if (rc < 0) pr_err("Failed to store XATTR stream name :%d\n", rc); + else + *created = true; return 0; } @@ -4335,7 +4349,8 @@ static int smb2_handle_app_instance_id(struct ksmbd_work *work, /* Authorize the referenced open even if its name changes meanwhile. */ old_path = &old_fp->filp->f_path; rc = smb_check_perm_dacl(conn, old_path, &maximal_access, 0, - work->sess->user->uid, false); + work->sess->user->uid, + ksmbd_user_authenticated(work->sess->user), false); if (rc) { /* Access denial prevents takeover, not the CREATE itself. */ ksmbd_put_durable_fd(old_fp); @@ -4394,6 +4409,7 @@ int smb2_open(struct ksmbd_work *work) char *stream_name = NULL; bool file_present = false, created = false, already_permitted = false; bool app_instance_id_checked = false, app_instance_closed; + bool stream_created = false; int share_ret, need_truncate = 0; u64 time, alloc_size = 0; umode_t posix_mode = 0; @@ -4856,14 +4872,17 @@ resolve_path: if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) { rc = smb_check_perm_dacl(conn, &path, &daccess, req->DesiredAccess, - sess->user->uid, false); + sess->user->uid, + ksmbd_user_authenticated(sess->user), false); if (rc) goto err_out; if (maximal_access_ctxt) { maximal_access = FILE_MAXIMAL_ACCESS_LE; rc = smb_check_perm_dacl(conn, &path, &maximal_access, - 0, sess->user->uid, false); + 0, sess->user->uid, + ksmbd_user_authenticated(sess->user), + false); if (rc) goto err_out; @@ -4961,16 +4980,32 @@ resolve_path: if ((daccess & FILE_DELETE_LE) || (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) { - rc = inode_permission(idmap, - d_inode(path.dentry->d_parent), - MAY_EXEC | MAY_WRITE); + struct dentry *parent = dget_parent(path.dentry); + struct inode *parent_inode = d_inode(parent); + + if (parent_inode) + rc = inode_permission(idmap, parent_inode, + MAY_EXEC | MAY_WRITE); + else + rc = -ENOENT; + dput(parent); if (rc) goto err_out; } } } - rc = ksmbd_query_inode_status(path.dentry->d_parent); + { + struct dentry *parent = dget_parent(path.dentry); + + if (!d_inode(parent)) { + dput(parent); + rc = -ENOENT; + goto err_out; + } + rc = ksmbd_query_inode_status(parent); + dput(parent); + } if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) { rc = -EBUSY; goto err_out; @@ -5053,10 +5088,17 @@ resolve_path: if (created) { int posix_acl_rc; struct inode *inode = d_inode(path.dentry); + struct inode *parent_inode; + struct dentry *parent; - posix_acl_rc = ksmbd_vfs_inherit_posix_acl(idmap, - &path, - d_inode(path.dentry->d_parent)); + parent = dget_parent(path.dentry); + parent_inode = d_inode(parent); + if (parent_inode) + posix_acl_rc = ksmbd_vfs_inherit_posix_acl(idmap, &path, + parent_inode); + else + posix_acl_rc = -ENOENT; + dput(parent); if (posix_acl_rc) ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc); @@ -5138,7 +5180,8 @@ resolve_path: rc = smb2_set_stream_name_xattr(&path, fp, stream_name, - s_type); + s_type, + &stream_created); if (rc) goto err_out; file_info = FILE_CREATED; @@ -5146,13 +5189,25 @@ resolve_path: fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE)); + need_truncate = !S_ISDIR(file_inode(filp)->i_mode) && + open_flags & O_TRUNC && !fp->attrib_only && !stream_name; + /* + * Count the FILE_WRITE_DATA that MS-FSA 2.1.5.1.2 grants an overwrite, + * supersede included, or a new named stream on an existing file. + * An attribute-only open of the file is not truncated, and the + * synthesized AFP_AfpInfo stream is not created by the client. + */ + fp->implied_write = need_truncate || + (stream_name && + (open_flags & O_TRUNC || + (file_present && stream_created))); fp->is_posix_ctxt = posix_ctxt; fp->posix_append = posix_ctxt && !!(open_flags & O_APPEND); /* fp should be searchable through ksmbd_inode.m_fp_list - * after daccess, saccess, attrib_only, and stream are - * initialized. + * after daccess, saccess, attrib_only, implied_write, and + * stream are initialized. */ down_write(&fp->f_ci->m_lock); list_add(&fp->node, &fp->f_ci->m_fp_list); @@ -5173,11 +5228,8 @@ resolve_path: if (file_present || created) path_put(&path); - if (!S_ISDIR(file_inode(filp)->i_mode) && open_flags & O_TRUNC && - !fp->attrib_only && !stream_name) { + if (need_truncate) smb_break_all_oplock(work, fp); - need_truncate = 1; - } share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp); if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) || @@ -6333,6 +6385,7 @@ static int process_query_dir_entries(struct smb2_query_dir_private *priv) rc = smb_check_perm_dacl(priv->work->conn, &path, &daccess, daccess, priv->work->sess->user->uid, + ksmbd_user_authenticated(priv->work->sess->user), true); if (rc) { dput(dent); diff --git a/fs/smb/server/smb_common.c b/fs/smb/server/smb_common.c index f9fb3741ada3..e7a987af64ba 100644 --- a/fs/smb/server/smb_common.c +++ b/fs/smb/server/smb_common.c @@ -695,10 +695,24 @@ static void smb_shared_mode_error(int error, struct ksmbd_file *prev_fp, prev_fp->saccess, curr_fp->daccess); } +/* + * Sharing checks use fp->daccess plus the FILE_WRITE_DATA that MS-FSA + * grants an open that overwrites data or creates a named stream. + * fp->daccess keeps the open's own access. + */ +__le32 ksmbd_sharing_daccess(const struct ksmbd_file *fp) +{ + if (fp->implied_write) + return fp->daccess | FILE_WRITE_DATA_LE; + return fp->daccess; +} + int ksmbd_smb_check_shared_mode(struct file *filp, struct ksmbd_file *curr_fp) { int rc = 0; struct ksmbd_file *prev_fp; + __le32 curr_access = ksmbd_sharing_daccess(curr_fp); + __le32 access; /* * Lookup fp in master fp list, and check desired access and @@ -719,6 +733,24 @@ int ksmbd_smb_check_shared_mode(struct file *filp, struct ksmbd_file *curr_fp) if (prev_fp->attrib_only != curr_fp->attrib_only) continue; + /* + * MS-FSA checks sharing per stream, so a named stream open's + * implied write is not a write against the primary stream. + * It still decides whether the pair is checked. + */ + access = curr_access; + if (ksmbd_stream_fd(curr_fp) && !ksmbd_stream_fd(prev_fp)) + access = curr_fp->daccess; + + /* + * Two opens conflict only if both hold a right in + * FILE_SHARE_CHECKED_ACCESS_LE (MS-FSA 2.1.5.1.2.1 and + * 2.1.5.1.2.2) + */ + if (!(ksmbd_sharing_daccess(prev_fp) & FILE_SHARE_CHECKED_ACCESS_LE) || + !(curr_access & FILE_SHARE_CHECKED_ACCESS_LE)) + continue; + if (!(prev_fp->saccess & FILE_SHARE_DELETE_LE) && curr_fp->daccess & FILE_DELETE_LE) { smb_shared_mode_error(SHARE_DELETE_ERROR, @@ -745,7 +777,7 @@ int ksmbd_smb_check_shared_mode(struct file *filp, struct ksmbd_file *curr_fp) } if (!(prev_fp->saccess & FILE_SHARE_WRITE_LE) && - curr_fp->daccess & (FILE_WRITE_DATA_LE | FILE_APPEND_DATA_LE)) { + access & (FILE_WRITE_DATA_LE | FILE_APPEND_DATA_LE)) { smb_shared_mode_error(SHARE_WRITE_ERROR, prev_fp, curr_fp); diff --git a/fs/smb/server/smb_common.h b/fs/smb/server/smb_common.h index a9cc09e31721..d3d19f1a23ea 100644 --- a/fs/smb/server/smb_common.h +++ b/fs/smb/server/smb_common.h @@ -69,6 +69,10 @@ FILE_EXECUTE | FILE_DELETE_CHILD | \ FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES) +/* Rights that make an open take part in sharing checks */ +#define FILE_SHARE_CHECKED_ACCESS_LE (FILE_EXECUTE_LE | FILE_READ_DATA_LE | \ + FILE_WRITE_DATA_LE | FILE_APPEND_DATA_LE | FILE_DELETE_LE) + #define SMB_COM_NEGOTIATE 0x72 /* See MS-CIFS 2.2.2.1 */ /* See MS-CIFS 2.2.3.1 */ @@ -284,6 +288,7 @@ int ksmbd_extract_shortname(struct ksmbd_conn *conn, int ksmbd_smb_negotiate_common(struct ksmbd_work *work, unsigned int command); +__le32 ksmbd_sharing_daccess(const struct ksmbd_file *fp); int ksmbd_smb_check_shared_mode(struct file *filp, struct ksmbd_file *curr_fp); int __ksmbd_override_fsids(struct ksmbd_work *work, struct ksmbd_share_config *share); diff --git a/fs/smb/server/smbacl.c b/fs/smb/server/smbacl.c index ab76c5c9e0ea..6b5f22d6280c 100644 --- a/fs/smb/server/smbacl.c +++ b/fs/smb/server/smbacl.c @@ -7,6 +7,7 @@ */ #include <linux/fs.h> +#include <linux/dcache.h> #include <kunit/visibility.h> #include <linux/slab.h> #include <linux/string.h> @@ -1207,7 +1208,7 @@ int smb_inherit_dacl(struct ksmbd_conn *conn, struct smb_acl *parent_pdacl; struct smb_ntsd *parent_pntsd = NULL; struct smb_sid owner_sid, group_sid; - struct dentry *parent = path->dentry->d_parent; + struct dentry *parent; const struct mnt_idmap *idmap = mnt_idmap(path->mnt); int inherited_flags = 0, flags = 0, i, nt_size = 0, pdacl_size; int rc = 0, pntsd_type, ppntsd_size, acl_len, aces_size; @@ -1217,8 +1218,14 @@ int smb_inherit_dacl(struct ksmbd_conn *conn, char *aces_base; bool is_dir = S_ISDIR(d_inode(path->dentry)->i_mode); + parent = dget_parent(path->dentry); + if (!d_inode(parent)) { + dput(parent); + return -ENOENT; + } ppntsd_size = ksmbd_vfs_get_sd_xattr(conn, idmap, parent, &parent_pntsd); + dput(parent); if (ppntsd_size <= 0) return -ENOENT; @@ -1459,9 +1466,49 @@ bool smb_inherit_flags(int flags, bool is_dir) return false; } +/* Whether the caller's credentials hold the group of an S-1-22-2-<gid> SID */ +static bool smb_sid_in_group(const struct smb_sid *sid) +{ + gid_t gid; + + if (sid->num_subauth != sid_unix_groups.num_subauth + 1 || + compare_sids(sid, &sid_unix_groups)) + return false; + gid = le32_to_cpu(sid->sub_auth[sid->num_subauth - 1]); + /* + * ksmbd_override_fsids() builds the caller's credentials with + * make_kgid(&init_user_ns, ...), so the group membership test must + * compare in that space. Applying the mount idmap here (as when + * resolving a SID to an on-disk gid) would mismatch on idmapped + * mounts. + */ + return in_group_p(make_kgid(&init_user_ns, gid)); +} + +/* Whether two SIDs are the same SID */ +static bool smb_sid_equal(const struct smb_sid *a, const struct smb_sid *b) +{ + return a->num_subauth == b->num_subauth && !compare_sids(a, b); +} + +/* + * compare_sids() compares only the sub-authorities both SIDs have, so it + * also matches a shorter or longer SID, such as S-1-3 or S-1-3-4-777 + */ +static bool smb_sid_is_owner_rights(const struct smb_sid *sid) +{ + return sid->num_subauth == sid_owner_rights.num_subauth && + !compare_sids(sid, &sid_owner_rights); +} + +static unsigned int smb_parent_derived_rights(struct ksmbd_conn *conn, + const struct path *path, int uid, + bool authenticated, + unsigned int want); + int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path, __le32 *pdaccess, __le32 raw_daccess, int uid, - bool strict) + bool authenticated, bool strict) { const struct mnt_idmap *idmap = mnt_idmap(path->mnt); struct smb_ntsd *pntsd = NULL; @@ -1475,13 +1522,23 @@ int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path, int granted = requested; struct smb_ace *ace; int i, found = 0; - unsigned int access_bits = 0, denied = 0; + unsigned int access_bits = 0, denied = 0, grp_granted = 0; + unsigned int grp_allowed = 0, grp_denied = 0, bits; struct smb_ace *others_ace = NULL; - bool or_ace = false; + bool or_ace = false, obj_deny = false, au_ace = false, member, counted; + bool grp_ace = false; struct posix_acl_entry *pa_entry; unsigned int sid_type = SIDOWNER; unsigned short ace_size; bool is_owner, owner_rights = false; + bool maximal = *pdaccess & FILE_MAXIMAL_ACCESS_LE; + /* + * MAXIMUM_ALLOWED requests that are not strict match every session + * against Authenticated Users and do not count ACEs for the + * caller's groups. Strict ones match SIDs as explicit requests do. + */ + bool open_max = maximal && !strict; + bool authusers = authenticated || open_max; vfsuid_t vfsuid; ksmbd_debug(SMB, "check permission using windows acl\n"); @@ -1515,14 +1572,17 @@ int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path, /* * An empty (present, zero-ACE) DACL grants no access to * anyone except the object owner's implicit READ_CONTROL - * and WRITE_DAC (MS-DTYP 2.4.5). Deny every other caller, - * deny the owner any access beyond those two bits, and do - * not let trailing bytes after a zero-ACE DACL become an - * implicit grant. + * and WRITE_DAC (MS-DTYP 2.5.3.2), besides what the parent + * grants. Deny every other right, and do not let trailing + * bytes after a zero-ACE DACL become an implicit grant. */ if (is_owner) allowed = READ_CONTROL | WRITE_DAC; - if (*pdaccess & FILE_MAXIMAL_ACCESS_LE) + if (!strict) + allowed |= smb_parent_derived_rights(conn, path, uid, + authenticated, + requested & ~allowed); + if (maximal) requested |= allowed; if (!allowed || requested & ~allowed) rc = -EACCES; @@ -1531,62 +1591,116 @@ int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path, goto err_out; } - if (*pdaccess & FILE_MAXIMAL_ACCESS_LE) { - ace = (struct smb_ace *)((char *)pdacl + sizeof(struct smb_acl)); - aces_size = pdacl_size - sizeof(struct smb_acl); - for (i = 0; i < le16_to_cpu(pdacl->num_aces); i++) { - if (aces_size < offsetof(struct smb_ace, sid) + - CIFS_SID_BASE_SIZE) - break; - ace_size = le16_to_cpu(ace->size); - if (ace_size > aces_size || - ace_size < offsetof(struct smb_ace, sid) + - CIFS_SID_BASE_SIZE) - break; - aces_size -= ace_size; + /* + * Evaluate the DACL in order (MS-DTYP 2.5.3.2). access_bits collects + * the result for the ACEs that apply to the caller, without its groups + * for a MAXIMUM_ALLOWED request that is not strict. grp_granted + * collects what ACEs for the caller's groups, or OWNER RIGHTS for the + * owner, grant. It is used when the SID lookup and POSIX ACL fallback + * below do not decide. + */ + ace = (struct smb_ace *)((char *)pdacl + sizeof(struct smb_acl)); + aces_size = pdacl_size - sizeof(struct smb_acl); + for (i = 0; i < le16_to_cpu(pdacl->num_aces); i++) { + if (aces_size < offsetof(struct smb_ace, sid) + + CIFS_SID_BASE_SIZE) + break; + ace_size = le16_to_cpu(ace->size); + if (ace_size > aces_size || + ace_size < offsetof(struct smb_ace, sid) + + CIFS_SID_BASE_SIZE) + break; + aces_size -= ace_size; - if (ace->sid.num_subauth > SID_MAX_SUB_AUTHORITIES || - ace_size < offsetof(struct smb_ace, sid) + - CIFS_SID_BASE_SIZE + - sizeof(__le32) * ace->sid.num_subauth) - break; + if (ace->sid.num_subauth > SID_MAX_SUB_AUTHORITIES || + ace_size < offsetof(struct smb_ace, sid) + + CIFS_SID_BASE_SIZE + + sizeof(__le32) * ace->sid.num_subauth) + break; - if (!compare_sids(&sid_owner_rights, &ace->sid)) { - owner_rights = true; - if (!is_owner) - goto next_ace; - } + if ((ace->type == ACCESS_DENIED_OBJECT_ACE_TYPE || + ace->type == ACCESS_DENIED_CALLBACK_OBJECT_ACE_TYPE) && + !(ace->flags & INHERIT_ONLY_ACE)) + obj_deny = true; - if (ace->flags & INHERIT_ONLY_ACE || - (compare_sids(&sid, &ace->sid) && - compare_sids(&sid_unix_NFS_mode, &ace->sid) && - compare_sids(&sid_everyone, &ace->sid) && - compare_sids(&sid_authusers, &ace->sid) && - compare_sids(&sid_owner_rights, &ace->sid))) + if (!compare_sids(&sid_owner_rights, &ace->sid)) { + owner_rights = true; + if (!is_owner) goto next_ace; + } - switch (ace->type) { - case ACCESS_ALLOWED_ACE_TYPE: - access_bits |= le32_to_cpu(ace->access_req); - break; - case ACCESS_DENIED_ACE_TYPE: - case ACCESS_DENIED_CALLBACK_ACE_TYPE: - denied |= ~access_bits & - le32_to_cpu(ace->access_req); + member = smb_sid_in_group(&ace->sid); + /* The grp_ masks count groups and OWNER RIGHTS only */ + counted = member || + (is_owner && smb_sid_is_owner_rights(&ace->sid)); + if (ace->flags & INHERIT_ONLY_ACE || + (compare_sids(&sid, &ace->sid) && + compare_sids(&sid_unix_NFS_mode, &ace->sid) && + compare_sids(&sid_everyone, &ace->sid) && + (!authusers || + compare_sids(&sid_authusers, &ace->sid)) && + compare_sids(&sid_owner_rights, &ace->sid) && + !member)) + goto next_ace; + /* Other requests count only SIDs that match exactly */ + if (!open_max && !member && + !smb_sid_equal(&sid, &ace->sid) && + !smb_sid_equal(&sid_everyone, &ace->sid) && + !(authusers && smb_sid_equal(&sid_authusers, &ace->sid)) && + !smb_sid_is_owner_rights(&ace->sid)) + goto next_ace; + + bits = le32_to_cpu(ace->access_req); + switch (ace->type) { + case ACCESS_ALLOWED_ACE_TYPE: + grp_ace |= counted; + if (counted) + grp_allowed |= bits; + /* An open's MAXIMUM_ALLOWED takes no group grants */ + if (open_max && member) break; - } -next_ace: - ace = (struct smb_ace *)((char *)ace + le16_to_cpu(ace->size)); + if (counted) + grp_granted |= bits; + access_bits |= bits; + break; + case ACCESS_DENIED_ACE_TYPE: + case ACCESS_DENIED_CALLBACK_ACE_TYPE: + grp_ace |= counted; + if (counted) + grp_denied |= ~grp_allowed & bits; + /* nor group denials */ + if (!(open_max && member)) + denied |= ~access_bits & bits; + break; } +next_ace: + ace = (struct smb_ace *)((char *)ace + le16_to_cpu(ace->size)); + } + + /* Keep only file rights, not MAXIMUM_ALLOWED or generic bits */ + grp_granted &= GENERIC_ALL_FLAGS & ~grp_denied; + if (maximal) { if (is_owner && !owner_rights) access_bits |= READ_CONTROL | WRITE_DAC | FILE_READ_ATTRIBUTES | DELETE; access_bits &= ~denied; + /* An object deny ACE could deny the parent's rights */ + if (!open_max && obj_deny) + access_bits = 0; if ((raw_daccess & FILE_GENERIC_EXECUTE_LE) && S_ISREG(d_inode(path->dentry)->i_mode) && (access_bits & GENERIC_READ_FLAGS) == GENERIC_READ_FLAGS) access_bits |= FILE_EXECUTE; granted = requested | access_bits; + } else if (!obj_deny) { + /* An explicit request takes the ordered result */ + access_bits &= ~denied; + } else { + /* + * ksmbd does not parse object deny ACEs, so with one present an + * explicit request keeps the answer of the ACE found below + */ + access_bits = 0; } ace = (struct smb_ace *)((char *)pdacl + sizeof(struct smb_acl)); @@ -1616,15 +1730,26 @@ next_ace: !(ace->flags & INHERIT_ONLY_ACE)) or_ace = true; if (!compare_sids(&sid_everyone, &ace->sid) || - !compare_sids(&sid_authusers, &ace->sid)) + (authusers && + !compare_sids(&sid_authusers, &ace->sid))) others_ace = ace; + if (!compare_sids(&sid_authusers, &ace->sid)) + au_ace = true; ace = (struct smb_ace *)((char *)ace + le16_to_cpu(ace->size)); } if (IS_ENABLED(CONFIG_FS_POSIX_ACL)) { posix_acls = get_inode_acl(d_inode(path->dentry), ACL_TYPE_ACCESS); - if (!IS_ERR_OR_NULL(posix_acls) && !found && !others_ace) { + /* + * An Authenticated Users ACE keeps the POSIX ACL from deciding, + * also for sessions that it does not match. For a strict + * MAXIMUM_ALLOWED request, ACEs for the caller's groups or + * OWNER RIGHTS decide before the POSIX ACL, unless the DACL has + * an object deny ACE, which ksmbd does not parse. + */ + if (!IS_ERR_OR_NULL(posix_acls) && !found && !others_ace && + !au_ace && !(strict && maximal && grp_ace && !obj_deny)) { unsigned int id = -1; pa_entry = posix_acls->a_entries; @@ -1646,6 +1771,15 @@ next_ace: if (!access_bits) access_bits = SET_MINIMUM_RIGHTS; + /* + * Only ACEs for the caller's groups, + * or OWNER RIGHTS for the owner, apply + * here. The POSIX ACL entry does not + * grant an explicitly requested right + * that they deny first in DACL order. + */ + access_bits &= ~(grp_denied & + requested); posix_acl_release(posix_acls); goto check_access_bits; } @@ -1668,7 +1802,19 @@ next_ace: */ if (is_owner && !or_ace) allowed = READ_CONTROL | WRITE_DAC; - if (*pdaccess & FILE_MAXIMAL_ACCESS_LE) + /* + * Add what ACEs for the caller's groups, or OWNER + * RIGHTS for the owner, grant in DACL order, unless an + * object deny ACE, which ksmbd does not parse, could + * apply. + */ + if (!obj_deny) + allowed |= grp_granted; + if (!strict) + allowed |= smb_parent_derived_rights(conn, path, uid, + authenticated, + requested & ~allowed); + if (maximal) requested |= allowed; if (!allowed || requested & ~allowed) { ksmbd_debug(SMB, "Can't find corresponding sid\n"); @@ -1680,7 +1826,7 @@ next_ace: } } - if (!(*pdaccess & FILE_MAXIMAL_ACCESS_LE)) { + if (!maximal && obj_deny) { switch (ace->type) { case ACCESS_ALLOWED_ACE_TYPE: access_bits = le32_to_cpu(ace->access_req); @@ -1714,6 +1860,45 @@ err_out: } EXPORT_SYMBOL_IF_KUNIT(smb_check_perm_dacl); +/* + * Return the rights in @want that @path gets from its parent directory: + * DELETE if the parent's DACL grants FILE_DELETE_CHILD, and + * FILE_READ_ATTRIBUTES if it grants FILE_LIST_DIRECTORY + * (MS-FSA 2.1.5.1.2.1). A parent with no DACL, or with one that ksmbd + * cannot read, gives nothing. Callers pass only rights that the request + * names. + */ +static unsigned int smb_parent_derived_rights(struct ksmbd_conn *conn, + const struct path *path, int uid, + bool authenticated, + unsigned int want) +{ + struct path parent = { .mnt = path->mnt }; + __le32 granted = FILE_MAXIMAL_ACCESS_LE; + unsigned int rights = 0; + int rc; + + if (!(want & (DELETE | FILE_READ_ATTRIBUTES))) + return 0; + + /* The root of the mount, or a disconnected dentry, has no parent */ + if (path->dentry == path->mnt->mnt_root || IS_ROOT(path->dentry)) + return 0; + + parent.dentry = dget_parent(path->dentry); + /* Strict, so the parent's own parent is not consulted */ + rc = smb_check_perm_dacl(conn, &parent, &granted, 0, uid, + authenticated, true); + dput(parent.dentry); + if (rc || granted == FILE_MAXIMAL_ACCESS_LE) + return 0; + if (granted & FILE_DELETE_CHILD_LE) + rights |= DELETE; + if (granted & FILE_LIST_DIRECTORY_LE) + rights |= FILE_READ_ATTRIBUTES; + return rights & want; +} + int set_info_sec(struct ksmbd_conn *conn, struct ksmbd_tree_connect *tcon, const struct path *path, struct smb_ntsd *pntsd, int ntsd_len, bool type_check, bool get_write, bool posix_open, diff --git a/fs/smb/server/smbacl.h b/fs/smb/server/smbacl.h index 3342cebab333..bbd35948a379 100644 --- a/fs/smb/server/smbacl.h +++ b/fs/smb/server/smbacl.h @@ -97,7 +97,7 @@ int smb_inherit_dacl(struct ksmbd_conn *conn, const struct path *path, unsigned int uid, unsigned int gid); int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path, __le32 *pdaccess, __le32 raw_daccess, int uid, - bool strict); + bool authenticated, bool strict); int set_info_sec(struct ksmbd_conn *conn, struct ksmbd_tree_connect *tcon, const struct path *path, struct smb_ntsd *pntsd, int ntsd_len, bool type_check, bool get_write, bool posix_open, diff --git a/fs/smb/server/tests/smbacl_kunit.c b/fs/smb/server/tests/smbacl_kunit.c index 33496b4d31a3..bf28439a7696 100644 --- a/fs/smb/server/tests/smbacl_kunit.c +++ b/fs/smb/server/tests/smbacl_kunit.c @@ -229,7 +229,7 @@ static void ksmbd_smb_check_perm_dacl_boundary_test(struct kunit *test) goto out; rc = smb_check_perm_dacl(NULL, &file->f_path, &daccess, - cpu_to_le32(FILE_READ_DATA), 0, false); + cpu_to_le32(FILE_READ_DATA), 0, true, false); /* * The post-boundary ACE (ACE #2, beyond pdacl->size) grants @@ -271,7 +271,7 @@ ksmbd_smb_check_perm_dacl_maximal_boundary_test(struct kunit *test) goto out; rc = smb_check_perm_dacl(NULL, &file->f_path, &daccess, - FILE_MAXIMAL_ACCESS_LE, 0, false); + FILE_MAXIMAL_ACCESS_LE, 0, true, false); KUNIT_EXPECT_EQ(test, 0, rc); if (rc) goto out; diff --git a/fs/smb/server/vfs.c b/fs/smb/server/vfs.c index 1f2bc76f0d09..cb3f4f5fe9cf 100644 --- a/fs/smb/server/vfs.c +++ b/fs/smb/server/vfs.c @@ -367,6 +367,10 @@ int ksmbd_vfs_read(struct ksmbd_work *work, struct ksmbd_file *fp, size_t count, if (ksmbd_stream_fd(fp)) return ksmbd_vfs_stream_read(fp, rbuf, pos, count); + /* The access granted on open can include FILE_EXECUTE for a write-only file */ + if (!(filp->f_mode & FMODE_READ)) + return -EACCES; + if (!fp->is_posix_ctxt) { int ret; diff --git a/fs/smb/server/vfs_cache.c b/fs/smb/server/vfs_cache.c index f9079c529d07..c846023e5ada 100644 --- a/fs/smb/server/vfs_cache.c +++ b/fs/smb/server/vfs_cache.c @@ -420,7 +420,12 @@ bool ksmbd_has_stream_without_delete_share(struct ksmbd_file *fp) if (file_inode(fp->filp) != file_inode(prev_fp->filp)) continue; - if (!(prev_fp->saccess & FILE_SHARE_DELETE_LE)) { + /* + * A stream open with no right in FILE_SHARE_CHECKED_ACCESS_LE, + * implied writes included, never conflicts. + */ + if (!(prev_fp->saccess & FILE_SHARE_DELETE_LE) && + ksmbd_sharing_daccess(prev_fp) & FILE_SHARE_CHECKED_ACCESS_LE) { ret = true; break; } diff --git a/fs/smb/server/vfs_cache.h b/fs/smb/server/vfs_cache.h index a0239ec178d8..57c81287efe6 100644 --- a/fs/smb/server/vfs_cache.h +++ b/fs/smb/server/vfs_cache.h @@ -131,6 +131,8 @@ struct ksmbd_file { bool is_nt_open; bool attrib_only; + /* writes data on open, see ksmbd_sharing_daccess() */ + bool implied_write; bool allocation_size_set; char client_guid[16]; diff --git a/fs/splice.c b/fs/splice.c index e6d43329ed3f..5397ded643a7 100644 --- a/fs/splice.c +++ b/fs/splice.c @@ -56,63 +56,6 @@ static noinline void pipe_clear_nowait(struct file *file) } /* - * Attempt to steal a page from a pipe buffer. This should perhaps go into - * a vm helper function, it's already simplified quite a bit by the - * addition of remove_mapping(). If success is returned, the caller may - * attempt to reuse this page for another destination. - */ -static bool page_cache_pipe_buf_try_steal(struct pipe_inode_info *pipe, - struct pipe_buffer *buf) -{ - struct folio *folio = page_folio(buf->page); - struct address_space *mapping; - - folio_lock(folio); - - mapping = folio_mapping(folio); - if (mapping) { - WARN_ON(!folio_test_uptodate(folio)); - - /* - * At least for ext2 with nobh option, we need to wait on - * writeback completing on this folio, since we'll remove it - * from the pagecache. Otherwise truncate wont wait on the - * folio, allowing the disk blocks to be reused by someone else - * before we actually wrote our data to them. fs corruption - * ensues. - */ - folio_wait_writeback(folio); - - if (!filemap_release_folio(folio, GFP_KERNEL)) - goto out_unlock; - - /* - * If we succeeded in removing the mapping, set LRU flag - * and return good. - */ - if (remove_mapping(mapping, folio)) { - buf->flags |= PIPE_BUF_FLAG_LRU; - return true; - } - } - - /* - * Raced with truncate or failed to remove folio from current - * address space, unlock and return failure. - */ -out_unlock: - folio_unlock(folio); - return false; -} - -static void page_cache_pipe_buf_release(struct pipe_inode_info *pipe, - struct pipe_buffer *buf) -{ - put_page(buf->page); - buf->flags &= ~PIPE_BUF_FLAG_LRU; -} - -/* * Check whether the contents of buf is OK to access. Since the content * is a page cache page, IO may be in flight. */ @@ -154,24 +97,12 @@ error: const struct pipe_buf_operations page_cache_pipe_buf_ops = { .confirm = page_cache_pipe_buf_confirm, - .release = page_cache_pipe_buf_release, - .try_steal = page_cache_pipe_buf_try_steal, + .release = generic_pipe_buf_release, .get = generic_pipe_buf_get, }; -static bool user_page_pipe_buf_try_steal(struct pipe_inode_info *pipe, - struct pipe_buffer *buf) -{ - if (!(buf->flags & PIPE_BUF_FLAG_GIFT)) - return false; - - buf->flags |= PIPE_BUF_FLAG_LRU; - return generic_pipe_buf_try_steal(pipe, buf); -} - static const struct pipe_buf_operations user_page_pipe_buf_ops = { - .release = page_cache_pipe_buf_release, - .try_steal = user_page_pipe_buf_try_steal, + .release = generic_pipe_buf_release, .get = generic_pipe_buf_get, }; @@ -400,16 +331,9 @@ EXPORT_SYMBOL(copy_splice_read); const struct pipe_buf_operations default_pipe_buf_ops = { .release = generic_pipe_buf_release, - .try_steal = generic_pipe_buf_try_steal, .get = generic_pipe_buf_get, }; - -/* Pipe buffer operations for a socket and similar. */ -const struct pipe_buf_operations nosteal_pipe_buf_ops = { - .release = generic_pipe_buf_release, - .get = generic_pipe_buf_get, -}; -EXPORT_SYMBOL(nosteal_pipe_buf_ops); +EXPORT_SYMBOL(default_pipe_buf_ops); static void wakeup_pipe_writers(struct pipe_inode_info *pipe) { @@ -737,9 +661,12 @@ iter_file_splice_write(struct pipe_inode_info *pipe, struct file *out, sd.pos = kiocb.ki_pos; if (ret <= 0) break; - WARN_ONCE(ret > sd.total_len - left, - "Splice Exceeded! ret=%zd tot=%zu left=%zu\n", - ret, sd.total_len, left); + if (unlikely(ret > sd.total_len - left)) { + WARN_ONCE(1, + "Splice Exceeded! ret=%zd tot=%zu left=%zu\n", + ret, sd.total_len, left); + ret = sd.total_len - left; + } sd.num_spliced += ret; sd.total_len -= ret; @@ -863,9 +790,9 @@ ssize_t splice_to_socket(struct pipe_inode_info *pipe, struct file *out, bvec_set_page(&bvec[bc++], buf->page, seg, buf->offset); remain -= seg; + tail++; if (remain == 0 || bc >= ARRAY_SIZE(bvec)) break; - tail++; } if (!bc) @@ -1469,12 +1396,10 @@ static ssize_t __do_splice(struct file *in, loff_t __user *off_in, } static ssize_t iter_to_pipe(struct iov_iter *from, - struct pipe_inode_info *pipe, - unsigned int flags) + struct pipe_inode_info *pipe) { struct pipe_buffer buf = { .ops = &user_page_pipe_buf_ops, - .flags = flags }; size_t total = 0; ssize_t ret = 0; @@ -1564,10 +1489,6 @@ static ssize_t vmsplice_to_pipe(struct file *file, struct iov_iter *iter, { struct pipe_inode_info *pipe; ssize_t ret = 0; - unsigned buf_flag = 0; - - if (flags & SPLICE_F_GIFT) - buf_flag = PIPE_BUF_FLAG_GIFT; pipe = get_pipe_info(file, true); if (!pipe) @@ -1578,7 +1499,7 @@ static ssize_t vmsplice_to_pipe(struct file *file, struct iov_iter *iter, pipe_lock(pipe); ret = wait_for_space(pipe, flags); if (!ret) - ret = iter_to_pipe(iter, pipe, buf_flag); + ret = iter_to_pipe(iter, pipe); pipe_unlock(pipe); if (ret > 0) { wakeup_pipe_readers(pipe); @@ -1839,11 +1760,7 @@ retry: } *obuf = *ibuf; - /* - * Don't inherit the gift and merge flags, we need to - * prevent multiple steals of this page. - */ - obuf->flags &= ~PIPE_BUF_FLAG_GIFT; + /* The page is shared with ipipe: don't append to it */ obuf->flags &= ~PIPE_BUF_FLAG_CAN_MERGE; obuf->len = len; @@ -1956,11 +1873,7 @@ retry: *obuf = *ibuf; - /* - * Don't inherit the gift and merge flag, we need to prevent - * multiple steals of this page. - */ - obuf->flags &= ~PIPE_BUF_FLAG_GIFT; + /* The page is shared with ipipe: don't append to it */ obuf->flags &= ~PIPE_BUF_FLAG_CAN_MERGE; if (obuf->len > len) diff --git a/fs/stat.c b/fs/stat.c index a2e63c6c45b7..34d786c1de3e 100644 --- a/fs/stat.c +++ b/fs/stat.c @@ -710,8 +710,7 @@ cp_statx(const struct kstat *stat, struct statx __user *buffer) /* STATX_CHANGE_COOKIE is kernel-only for now */ tmp.stx_mask = stat->result_mask & ~STATX_CHANGE_COOKIE; tmp.stx_blksize = stat->blksize; - /* STATX_ATTR_CHANGE_MONOTONIC is kernel-only for now */ - tmp.stx_attributes = stat->attributes & ~STATX_ATTR_CHANGE_MONOTONIC; + tmp.stx_attributes = stat->attributes & ~STATX_ATTR_INTERNAL_MASK; tmp.stx_nlink = stat->nlink; tmp.stx_uid = from_kuid_munged(current_user_ns(), stat->uid); tmp.stx_gid = from_kgid_munged(current_user_ns(), stat->gid); @@ -719,7 +718,8 @@ cp_statx(const struct kstat *stat, struct statx __user *buffer) tmp.stx_ino = stat->ino; tmp.stx_size = stat->size; tmp.stx_blocks = stat->blocks; - tmp.stx_attributes_mask = stat->attributes_mask; + tmp.stx_attributes_mask = stat->attributes_mask & + ~STATX_ATTR_INTERNAL_MASK; tmp.stx_atime.tv_sec = stat->atime.tv_sec; tmp.stx_atime.tv_nsec = stat->atime.tv_nsec; tmp.stx_btime.tv_sec = stat->btime.tv_sec; diff --git a/fs/udf/inode.c b/fs/udf/inode.c index c425096a22ba..29900065673c 100644 --- a/fs/udf/inode.c +++ b/fs/udf/inode.c @@ -152,8 +152,6 @@ void udf_evict_inode(struct inode *inode) } } truncate_inode_pages_final(&inode->i_data); - if (!want_delete) - mmb_sync(&iinfo->i_metadata_bhs); mmb_invalidate(&iinfo->i_metadata_bhs); clear_inode(inode); kfree(iinfo->i_data); @@ -1747,25 +1745,24 @@ void udf_update_extra_perms(struct inode *inode, umode_t mode) int udf_sync_inode_metadata(struct inode *inode, struct writeback_control *wbc) { struct buffer_head *bh; + unsigned long block; int err = 0; - bh = sb_getblk(inode->i_sb, - udf_get_lb_pblock(inode->i_sb, - &UDF_I(inode)->i_location, 0)); - if (!bh) - return -EIO; - - sync_dirty_buffer(bh); - if (buffer_write_io_error(bh)) { - udf_warn(inode->i_sb, "IO error syncing udf inode [%08llx]\n", - inode->i_ino); - err = -EIO; - goto out; + block = udf_get_lb_pblock(inode->i_sb, &UDF_I(inode)->i_location, 0); + /* A block that isn't cached is neither dirty nor under writeback. */ + bh = sb_find_get_block_nonatomic(inode->i_sb, block); + if (bh) { + sync_dirty_buffer(bh); + if (buffer_write_io_error(bh)) { + udf_warn(inode->i_sb, "IO error syncing udf inode [%08llx]\n", + inode->i_ino); + err = -EIO; + } + brelse(bh); + if (err) + return err; } - err = mmb_sync(&UDF_I(inode)->i_metadata_bhs); -out: - brelse(bh); - return err; + return mmb_sync(&UDF_I(inode)->i_metadata_bhs); } static void udf_adjust_time(struct udf_inode_info *iinfo, struct timespec64 time) diff --git a/fs/xfs/xfs_aops.c b/fs/xfs/xfs_aops.c index c30e688cfc9f..1db6f3640c53 100644 --- a/fs/xfs/xfs_aops.c +++ b/fs/xfs/xfs_aops.c @@ -575,7 +575,7 @@ xfs_vm_bmap( */ if (xfs_is_cow_inode(ip) || XFS_IS_REALTIME_INODE(ip)) return 0; - return iomap_bmap(mapping, block, &xfs_read_iomap_ops); + return iomap_bmap(mapping, block, xfs_read_iomap_next); } static void @@ -614,7 +614,7 @@ xfs_vm_read_folio( struct iomap_read_folio_ctx ctx = { .cur_folio = folio }; ctx.ops = xfs_get_iomap_read_ops(folio->mapping); - iomap_read_folio(&xfs_read_iomap_ops, &ctx, NULL); + iomap_read_folio(xfs_read_iomap_next, &ctx, NULL); return 0; } @@ -625,7 +625,7 @@ xfs_vm_readahead( struct iomap_read_folio_ctx ctx = { .rac = rac }; ctx.ops = xfs_get_iomap_read_ops(rac->mapping), - iomap_readahead(&xfs_read_iomap_ops, &ctx, NULL); + iomap_readahead(xfs_read_iomap_next, &ctx, NULL); } static int @@ -671,7 +671,7 @@ xfs_vm_swap_activate( sis->bdev = xfs_inode_buftarg(ip)->bt_bdev; return iomap_swapfile_activate(sis, swap_file, span, - &xfs_read_iomap_ops); + xfs_read_iomap_next); } const struct address_space_operations xfs_address_space_operations = { diff --git a/fs/xfs/xfs_file.c b/fs/xfs/xfs_file.c index 396aca8c66a9..d61ea8e2c8e4 100644 --- a/fs/xfs/xfs_file.c +++ b/fs/xfs/xfs_file.c @@ -208,12 +208,12 @@ xfs_file_dio_read( if (ret) return ret; if (mapping_stable_writes(iocb->ki_filp->f_mapping)) { - ret = iomap_dio_rw(iocb, to, &xfs_read_iomap_ops, + ret = iomap_dio_rw(iocb, to, xfs_read_iomap_next, &xfs_dio_read_bounce_ops, 0, NULL, 0); } else { ret = iomap_dio_read_simple(iocb, to, xfs_read_iomap_begin); if (ret == -ENOTBLK) - ret = iomap_dio_rw(iocb, to, &xfs_read_iomap_ops, NULL, + ret = iomap_dio_rw(iocb, to, xfs_read_iomap_next, NULL, 0, NULL, 0); } xfs_iunlock(ip, XFS_IOLOCK_SHARED); @@ -237,7 +237,7 @@ xfs_file_dax_read( ret = xfs_ilock_iocb(iocb, XFS_IOLOCK_SHARED); if (ret) return ret; - ret = dax_iomap_rw(iocb, to, &xfs_read_iomap_ops); + ret = dax_iomap_rw(iocb, to, xfs_read_iomap_next); xfs_iunlock(ip, XFS_IOLOCK_SHARED); file_accessed(iocb->ki_filp); @@ -687,7 +687,7 @@ xfs_file_dio_write_aligned( struct xfs_inode *ip, struct kiocb *iocb, struct iov_iter *from, - const struct iomap_ops *ops, + iomap_iter_next_fn next, const struct iomap_dio_ops *dops, struct xfs_zone_alloc_ctx *ac) { @@ -722,7 +722,7 @@ xfs_file_dio_write_aligned( if (mapping_stable_writes(iocb->ki_filp->f_mapping)) dio_flags |= IOMAP_DIO_BOUNCE; trace_xfs_file_direct_write(iocb, from); - ret = iomap_dio_rw(iocb, from, ops, dops, dio_flags, ac, 0); + ret = iomap_dio_rw(iocb, from, next, dops, dio_flags, ac, 0); out_unlock: if (iolock) xfs_iunlock(ip, iolock); @@ -745,7 +745,7 @@ xfs_file_dio_write_zoned( if (ret < 0) return ret; ret = xfs_file_dio_write_aligned(ip, iocb, from, - &xfs_zoned_direct_write_iomap_ops, + xfs_zoned_direct_write_iomap_next, &xfs_dio_zoned_write_ops, &ac); xfs_zoned_space_unreserve(ip->i_mount, &ac); return ret; @@ -770,16 +770,16 @@ xfs_file_dio_write_atomic( unsigned int iolock = XFS_IOLOCK_SHARED; ssize_t ret, ocount = iov_iter_count(from); unsigned int dio_flags = 0; - const struct iomap_ops *dops; + iomap_iter_next_fn next; /* * HW offload should be faster, so try that first if it is already * known that the write length is not too large. */ if (ocount > xfs_inode_buftarg(ip)->bt_awu_max) - dops = &xfs_atomic_write_cow_iomap_ops; + next = xfs_atomic_write_cow_iomap_next; else - dops = &xfs_direct_write_iomap_ops; + next = xfs_direct_write_iomap_next; retry: ret = xfs_ilock_iocb_for_write(iocb, &iolock); @@ -799,18 +799,19 @@ retry: trace_xfs_file_direct_write(iocb, from); if (mapping_stable_writes(iocb->ki_filp->f_mapping)) dio_flags |= IOMAP_DIO_BOUNCE; - ret = iomap_dio_rw(iocb, from, dops, &xfs_dio_write_ops, dio_flags, + ret = iomap_dio_rw(iocb, from, next, &xfs_dio_write_ops, dio_flags, NULL, 0); /* - * The retry mechanism is based on the ->iomap_next method returning - * -ENOPROTOOPT, which would be when the REQ_ATOMIC-based write is not - * possible. The REQ_ATOMIC-based method is typically not possible if - * the write spans multiple extents or the disk blocks are misaligned. + * The retry mechanism is based on the iomap_iter_next_fn callback + * returning -ENOPROTOOPT, which would be when the REQ_ATOMIC-based + * write is not possible. The REQ_ATOMIC-based method is typically not + * possible if the write spans multiple extents or the disk blocks are + * misaligned. */ - if (ret == -ENOPROTOOPT && dops == &xfs_direct_write_iomap_ops) { + if (ret == -ENOPROTOOPT && next == xfs_direct_write_iomap_next) { xfs_iunlock(ip, iolock); - dops = &xfs_atomic_write_cow_iomap_ops; + next = xfs_atomic_write_cow_iomap_next; goto retry; } @@ -893,7 +894,7 @@ retry_exclusive: flags |= IOMAP_DIO_BOUNCE; trace_xfs_file_direct_write(iocb, from); - ret = iomap_dio_rw(iocb, from, &xfs_direct_write_iomap_ops, + ret = iomap_dio_rw(iocb, from, xfs_direct_write_iomap_next, &xfs_dio_write_ops, flags, NULL, 0); /* @@ -933,7 +934,7 @@ xfs_file_dio_write( if (iocb->ki_flags & IOCB_ATOMIC) return xfs_file_dio_write_atomic(ip, iocb, from); return xfs_file_dio_write_aligned(ip, iocb, from, - &xfs_direct_write_iomap_ops, &xfs_dio_write_ops, NULL); + xfs_direct_write_iomap_next, &xfs_dio_write_ops, NULL); } static noinline ssize_t @@ -957,7 +958,7 @@ xfs_file_dax_write( pos = iocb->ki_pos; trace_xfs_file_dax_write(iocb, from); - ret = dax_iomap_rw(iocb, from, &xfs_dax_write_iomap_ops); + ret = dax_iomap_rw(iocb, from, xfs_dax_write_iomap_next); if (ret > 0 && iocb->ki_pos > i_size_read(inode)) { i_size_write(inode, iocb->ki_pos); error = xfs_setfilesize(ip, pos, ret); @@ -1000,7 +1001,7 @@ write_retry: trace_xfs_file_buffered_write(iocb, from); ret = iomap_file_buffered_write(iocb, from, - &xfs_buffered_write_iomap_ops, &xfs_iomap_write_ops, + xfs_buffered_write_iomap_next, &xfs_iomap_write_ops, NULL); /* @@ -1081,7 +1082,7 @@ xfs_file_buffered_write_zoned( retry: trace_xfs_file_buffered_write(iocb, from); ret = iomap_file_buffered_write(iocb, from, - &xfs_buffered_write_iomap_ops, &xfs_iomap_write_ops, + xfs_buffered_write_iomap_next, &xfs_iomap_write_ops, &ac); if (ret == -ENOSPC && !cleared_space) { /* @@ -1890,10 +1891,10 @@ xfs_file_llseek( default: return generic_file_llseek(file, offset, whence); case SEEK_HOLE: - offset = iomap_seek_hole(inode, offset, &xfs_seek_iomap_ops); + offset = iomap_seek_hole(inode, offset, xfs_seek_iomap_next); break; case SEEK_DATA: - offset = iomap_seek_data(inode, offset, &xfs_seek_iomap_ops); + offset = iomap_seek_data(inode, offset, xfs_seek_iomap_next); break; } @@ -1917,8 +1918,8 @@ xfs_dax_fault_locked( } ret = dax_iomap_fault(vmf, order, &pfn, NULL, (write_fault && !vmf->cow_page) ? - &xfs_dax_write_iomap_ops : - &xfs_read_iomap_ops); + xfs_dax_write_iomap_next : + xfs_read_iomap_next); if (ret & VM_FAULT_NEEDDSYNC) ret = dax_finish_sync_fault(vmf, order, pfn); return ret; @@ -1982,7 +1983,7 @@ __xfs_write_fault( if (IS_DAX(inode)) ret = xfs_dax_fault_locked(vmf, order, true); else - ret = iomap_page_mkwrite(vmf, &xfs_buffered_write_iomap_ops, + ret = iomap_page_mkwrite(vmf, xfs_buffered_write_iomap_next, ac); xfs_iunlock(ip, lock_mode); diff --git a/fs/xfs/xfs_iomap.c b/fs/xfs/xfs_iomap.c index c3465204b8d5..50eae7ff6145 100644 --- a/fs/xfs/xfs_iomap.c +++ b/fs/xfs/xfs_iomap.c @@ -1059,13 +1059,9 @@ out_unlock: return error; } -static DEFINE_IOMAP_ITER_NEXT(xfs_direct_write_iomap_next, +DEFINE_IOMAP_ITER_NEXT(xfs_direct_write_iomap_next, xfs_direct_write_iomap_begin); -const struct iomap_ops xfs_direct_write_iomap_ops = { - .iomap_next = xfs_direct_write_iomap_next, -}; - #ifdef CONFIG_XFS_RT /* * This is really simple. The space has already been reserved before taking the @@ -1109,12 +1105,9 @@ xfs_zoned_direct_write_iomap_begin( return 0; } -static DEFINE_IOMAP_ITER_NEXT(xfs_zoned_direct_write_iomap_next, +DEFINE_IOMAP_ITER_NEXT(xfs_zoned_direct_write_iomap_next, xfs_zoned_direct_write_iomap_begin); -const struct iomap_ops xfs_zoned_direct_write_iomap_ops = { - .iomap_next = xfs_zoned_direct_write_iomap_next, -}; #endif /* CONFIG_XFS_RT */ #ifdef DEBUG @@ -1297,13 +1290,9 @@ out_unlock: return error; } -static DEFINE_IOMAP_ITER_NEXT(xfs_atomic_write_cow_iomap_next, +DEFINE_IOMAP_ITER_NEXT(xfs_atomic_write_cow_iomap_next, xfs_atomic_write_cow_iomap_begin); -const struct iomap_ops xfs_atomic_write_cow_iomap_ops = { - .iomap_next = xfs_atomic_write_cow_iomap_next, -}; - static int xfs_dax_write_iomap_end( struct inode *inode, @@ -1324,13 +1313,9 @@ xfs_dax_write_iomap_end( return xfs_reflink_end_cow(ip, pos, written); } -static DEFINE_IOMAP_ITER_NEXT_END(xfs_dax_write_iomap_next, +DEFINE_IOMAP_ITER_NEXT_END(xfs_dax_write_iomap_next, xfs_direct_write_iomap_begin, xfs_dax_write_iomap_end); -const struct iomap_ops xfs_dax_write_iomap_ops = { - .iomap_next = xfs_dax_write_iomap_next, -}; - /* * Convert a hole to a delayed allocation. */ @@ -2213,13 +2198,9 @@ xfs_buffered_write_iomap_end( return 0; } -static DEFINE_IOMAP_ITER_NEXT_END(xfs_buffered_write_iomap_next, +DEFINE_IOMAP_ITER_NEXT_END(xfs_buffered_write_iomap_next, xfs_buffered_write_iomap_begin, xfs_buffered_write_iomap_end); -const struct iomap_ops xfs_buffered_write_iomap_ops = { - .iomap_next = xfs_buffered_write_iomap_next, -}; - int xfs_read_iomap_begin( struct inode *inode, @@ -2261,11 +2242,7 @@ xfs_read_iomap_begin( shared ? IOMAP_F_SHARED : 0, seq); } -static DEFINE_IOMAP_ITER_NEXT(xfs_read_iomap_next, xfs_read_iomap_begin); - -const struct iomap_ops xfs_read_iomap_ops = { - .iomap_next = xfs_read_iomap_next, -}; +DEFINE_IOMAP_ITER_NEXT(xfs_read_iomap_next, xfs_read_iomap_begin); static int xfs_seek_iomap_begin( @@ -2351,11 +2328,7 @@ out_unlock: return error; } -static DEFINE_IOMAP_ITER_NEXT(xfs_seek_iomap_next, xfs_seek_iomap_begin); - -const struct iomap_ops xfs_seek_iomap_ops = { - .iomap_next = xfs_seek_iomap_next, -}; +DEFINE_IOMAP_ITER_NEXT(xfs_seek_iomap_next, xfs_seek_iomap_begin); static int xfs_xattr_iomap_begin( @@ -2400,11 +2373,7 @@ out_unlock: return xfs_bmbt_to_iomap(ip, iomap, &imap, flags, IOMAP_F_XATTR, seq); } -static DEFINE_IOMAP_ITER_NEXT(xfs_xattr_iomap_next, xfs_xattr_iomap_begin); - -const struct iomap_ops xfs_xattr_iomap_ops = { - .iomap_next = xfs_xattr_iomap_next, -}; +DEFINE_IOMAP_ITER_NEXT(xfs_xattr_iomap_next, xfs_xattr_iomap_begin); int xfs_zero_range( @@ -2420,9 +2389,9 @@ xfs_zero_range( if (IS_DAX(inode)) return dax_zero_range(inode, pos, len, did_zero, - &xfs_dax_write_iomap_ops); + xfs_dax_write_iomap_next); return iomap_zero_range(inode, pos, len, did_zero, - &xfs_buffered_write_iomap_ops, &xfs_iomap_write_ops, + xfs_buffered_write_iomap_next, &xfs_iomap_write_ops, ac); } @@ -2437,8 +2406,8 @@ xfs_truncate_page( if (IS_DAX(inode)) return dax_truncate_page(inode, pos, did_zero, - &xfs_dax_write_iomap_ops); + xfs_dax_write_iomap_next); return iomap_truncate_page(inode, pos, did_zero, - &xfs_buffered_write_iomap_ops, &xfs_iomap_write_ops, + xfs_buffered_write_iomap_next, &xfs_iomap_write_ops, ac); } diff --git a/fs/xfs/xfs_iomap.h b/fs/xfs/xfs_iomap.h index 8fc0c6fc8bea..071fff666507 100644 --- a/fs/xfs/xfs_iomap.h +++ b/fs/xfs/xfs_iomap.h @@ -70,14 +70,14 @@ int xfs_read_iomap_begin(struct inode *inode, loff_t offset, loff_t length, unsigned flags, struct iomap *iomap, struct iomap *srcmap); -extern const struct iomap_ops xfs_buffered_write_iomap_ops; -extern const struct iomap_ops xfs_direct_write_iomap_ops; -extern const struct iomap_ops xfs_zoned_direct_write_iomap_ops; -extern const struct iomap_ops xfs_read_iomap_ops; -extern const struct iomap_ops xfs_seek_iomap_ops; -extern const struct iomap_ops xfs_xattr_iomap_ops; -extern const struct iomap_ops xfs_dax_write_iomap_ops; -extern const struct iomap_ops xfs_atomic_write_cow_iomap_ops; +DECLARE_IOMAP_ITER_NEXT(xfs_buffered_write_iomap_next); +DECLARE_IOMAP_ITER_NEXT(xfs_direct_write_iomap_next); +DECLARE_IOMAP_ITER_NEXT(xfs_zoned_direct_write_iomap_next); +DECLARE_IOMAP_ITER_NEXT(xfs_read_iomap_next); +DECLARE_IOMAP_ITER_NEXT(xfs_seek_iomap_next); +DECLARE_IOMAP_ITER_NEXT(xfs_xattr_iomap_next); +DECLARE_IOMAP_ITER_NEXT(xfs_dax_write_iomap_next); +DECLARE_IOMAP_ITER_NEXT(xfs_atomic_write_cow_iomap_next); extern const struct iomap_write_ops xfs_iomap_write_ops; #endif /* __XFS_IOMAP_H__*/ diff --git a/fs/xfs/xfs_iops.c b/fs/xfs/xfs_iops.c index d307ec97fac8..6c5633db30da 100644 --- a/fs/xfs/xfs_iops.c +++ b/fs/xfs/xfs_iops.c @@ -1256,10 +1256,10 @@ xfs_vn_fiemap( if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) { fieinfo->fi_flags &= ~FIEMAP_FLAG_XATTR; error = iomap_fiemap(inode, fieinfo, start, length, - &xfs_xattr_iomap_ops); + xfs_xattr_iomap_next); } else { error = iomap_fiemap(inode, fieinfo, start, length, - &xfs_read_iomap_ops); + xfs_read_iomap_next); } xfs_iunlock(XFS_I(inode), XFS_IOLOCK_SHARED); diff --git a/fs/xfs/xfs_reflink.c b/fs/xfs/xfs_reflink.c index 104542b10d9e..c5c796e2b83d 100644 --- a/fs/xfs/xfs_reflink.c +++ b/fs/xfs/xfs_reflink.c @@ -1724,7 +1724,7 @@ xfs_reflink_remap_prep( pos_out, len, remap_flags); else ret = dax_remap_file_range_prep(file_in, pos_in, file_out, - pos_out, len, remap_flags, &xfs_read_iomap_ops); + pos_out, len, remap_flags, xfs_read_iomap_next); if (ret || *len == 0) goto out_unlock; @@ -1919,10 +1919,10 @@ xfs_reflink_unshare( if (IS_DAX(inode)) error = dax_file_unshare(inode, offset, len, - &xfs_dax_write_iomap_ops); + xfs_dax_write_iomap_next); else error = iomap_file_unshare(inode, offset, len, - &xfs_buffered_write_iomap_ops, + xfs_buffered_write_iomap_next, &xfs_iomap_write_ops); if (error) goto out; diff --git a/fs/zonefs/file.c b/fs/zonefs/file.c index 5b34849be7a2..319d9502ba56 100644 --- a/fs/zonefs/file.c +++ b/fs/zonefs/file.c @@ -59,10 +59,6 @@ static int zonefs_read_iomap_begin(struct inode *inode, loff_t offset, static DEFINE_IOMAP_ITER_NEXT(zonefs_read_iomap_next, zonefs_read_iomap_begin); -static const struct iomap_ops zonefs_read_iomap_ops = { - .iomap_next = zonefs_read_iomap_next, -}; - static int zonefs_write_iomap_begin(struct inode *inode, loff_t offset, loff_t length, unsigned int flags, struct iomap *iomap, struct iomap *srcmap) @@ -111,19 +107,15 @@ static int zonefs_write_iomap_begin(struct inode *inode, loff_t offset, static DEFINE_IOMAP_ITER_NEXT(zonefs_write_iomap_next, zonefs_write_iomap_begin); -static const struct iomap_ops zonefs_write_iomap_ops = { - .iomap_next = zonefs_write_iomap_next, -}; - static int zonefs_read_folio(struct file *unused, struct folio *folio) { - iomap_bio_read_folio(folio, &zonefs_read_iomap_ops); + iomap_bio_read_folio(folio, zonefs_read_iomap_next); return 0; } static void zonefs_readahead(struct readahead_control *rac) { - iomap_bio_readahead(rac, &zonefs_read_iomap_ops); + iomap_bio_readahead(rac, zonefs_read_iomap_next); } /* @@ -184,7 +176,7 @@ static int zonefs_swap_activate(struct swap_info_struct *sis, } return iomap_swapfile_activate(sis, swap_file, span, - &zonefs_read_iomap_ops); + zonefs_read_iomap_next); } const struct address_space_operations zonefs_file_aops = { @@ -314,7 +306,7 @@ static vm_fault_t zonefs_filemap_page_mkwrite(struct vm_fault *vmf) /* Serialize against truncates */ filemap_invalidate_lock_shared(inode->i_mapping); - ret = iomap_page_mkwrite(vmf, &zonefs_write_iomap_ops, NULL); + ret = iomap_page_mkwrite(vmf, zonefs_write_iomap_next, NULL); filemap_invalidate_unlock_shared(inode->i_mapping); sb_end_pagefault(inode->i_sb); @@ -530,7 +522,7 @@ static ssize_t zonefs_file_dio_write(struct kiocb *iocb, struct iov_iter *from) * page invalidation. Overwrite that error code with EBUSY so that * the user can make sense of the error. */ - ret = iomap_dio_rw(iocb, from, &zonefs_write_iomap_ops, + ret = iomap_dio_rw(iocb, from, zonefs_write_iomap_next, &zonefs_write_dio_ops, 0, NULL, 0); if (ret == -ENOTBLK) ret = -EBUSY; @@ -580,7 +572,7 @@ static ssize_t zonefs_file_buffered_write(struct kiocb *iocb, if (ret <= 0) goto inode_unlock; - ret = iomap_file_buffered_write(iocb, from, &zonefs_write_iomap_ops, + ret = iomap_file_buffered_write(iocb, from, zonefs_write_iomap_next, NULL, NULL); if (ret == -EIO) zonefs_io_error(inode, true); @@ -675,7 +667,7 @@ static ssize_t zonefs_file_read_iter(struct kiocb *iocb, struct iov_iter *to) goto inode_unlock; } file_accessed(iocb->ki_filp); - ret = iomap_dio_rw(iocb, to, &zonefs_read_iomap_ops, + ret = iomap_dio_rw(iocb, to, zonefs_read_iomap_next, &zonefs_read_dio_ops, 0, NULL, 0); } else { ret = generic_file_read_iter(iocb, to); diff --git a/include/acpi/acpi_bus.h b/include/acpi/acpi_bus.h index f59b2de865e6..fad52a96d613 100644 --- a/include/acpi/acpi_bus.h +++ b/include/acpi/acpi_bus.h @@ -327,6 +327,7 @@ struct acpi_device_physical_node { struct device *dev; unsigned int node_id; bool put_online:1; + bool offline_pending:1; }; struct acpi_device_properties { diff --git a/include/asm-generic/tlb.h b/include/asm-generic/tlb.h index 3f4a180b48f3..4bba02fd5d54 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. diff --git a/include/linux/assoc_array_priv.h b/include/linux/assoc_array_priv.h index dca733ef6750..37a9f76e1505 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/cpufreq.h b/include/linux/cpufreq.h index d3d0d9d02aa4..be1eaa43aeb0 100644 --- a/include/linux/cpufreq.h +++ b/include/linux/cpufreq.h @@ -146,8 +146,11 @@ struct cpufreq_policy { /* Per policy boost supported flag. */ bool boost_supported; - /* Pending policy->min/max update for the driver */ - bool update_limits; + /* Force passing target frequency to the driver. */ + bool force_target; + + /* The policy has been suspended. */ + bool suspended; /* Cached frequency lookup from cpufreq_driver_resolve_freq. */ unsigned int cached_target_freq; diff --git a/include/linux/dax.h b/include/linux/dax.h index a3af0c63c61b..2e0797e4d408 100644 --- a/include/linux/dax.h +++ b/include/linux/dax.h @@ -3,6 +3,7 @@ #define _LINUX_DAX_H #include <linux/fs.h> +#include <linux/iomap.h> #include <linux/mm.h> #include <linux/radix-tree.h> @@ -10,9 +11,6 @@ typedef unsigned long dax_entry_t; struct dax_device; struct gendisk; -struct iomap_ops; -struct iomap_iter; -struct iomap; enum dax_access_mode { DAX_ACCESS, @@ -200,11 +198,11 @@ static inline void dax_unlock_mapping_entry(struct address_space *mapping, #endif int dax_file_unshare(struct inode *inode, loff_t pos, loff_t len, - const struct iomap_ops *ops); + iomap_iter_next_fn next); int dax_zero_range(struct inode *inode, loff_t pos, loff_t len, bool *did_zero, - const struct iomap_ops *ops); + iomap_iter_next_fn next); int dax_truncate_page(struct inode *inode, loff_t pos, bool *did_zero, - const struct iomap_ops *ops); + iomap_iter_next_fn next); static inline bool dax_page_is_idle(struct page *page) { @@ -253,10 +251,10 @@ int dax_holder_notify_failure(struct dax_device *dax_dev, u64 off, u64 len, void dax_flush(struct dax_device *dax_dev, void *addr, size_t size); ssize_t dax_iomap_rw(struct kiocb *iocb, struct iov_iter *iter, - const struct iomap_ops *ops); + iomap_iter_next_fn next); vm_fault_t dax_iomap_fault(struct vm_fault *vmf, unsigned int order, unsigned long *pfnp, int *errp, - const struct iomap_ops *ops); + iomap_iter_next_fn next); vm_fault_t dax_finish_sync_fault(struct vm_fault *vmf, unsigned int order, unsigned long pfn); int dax_delete_mapping_entry(struct address_space *mapping, pgoff_t index); @@ -275,11 +273,11 @@ void dax_break_layout_final(struct inode *inode); int dax_dedupe_file_range_compare(struct inode *src, loff_t srcoff, struct inode *dest, loff_t destoff, loff_t len, bool *is_same, - const struct iomap_ops *ops); + iomap_iter_next_fn next); int dax_remap_file_range_prep(struct file *file_in, loff_t pos_in, struct file *file_out, loff_t pos_out, loff_t *len, unsigned int remap_flags, - const struct iomap_ops *ops); + iomap_iter_next_fn next); static inline bool dax_mapping(struct address_space *mapping) { return mapping->host && IS_DAX(mapping->host); diff --git a/include/linux/entry-common.h b/include/linux/entry-common.h index fa2854fed1f2..15278416f886 100644 --- a/include/linux/entry-common.h +++ b/include/linux/entry-common.h @@ -62,7 +62,7 @@ void trace_syscall_enter(struct pt_regs *regs); void trace_syscall_exit(struct pt_regs *regs, long ret); void syscall_enter_audit(struct pt_regs *regs); -static __always_inline long syscall_trace_enter(struct pt_regs *regs, unsigned long work, +static __always_inline bool syscall_trace_enter(struct pt_regs *regs, unsigned long work, long syscall) { /* @@ -202,7 +202,7 @@ do { \ \ instrumentation_begin(); \ local_irq_enable(); \ - long _ret = syscall_enter_from_user_mode_work(regs, syscall); \ + bool _ret = syscall_enter_from_user_mode_work(regs, syscall); \ instrumentation_end(); \ \ _ret; \ diff --git a/include/linux/fs.h b/include/linux/fs.h index 99caef43ff3c..5b3a100aba77 100644 --- a/include/linux/fs.h +++ b/include/linux/fs.h @@ -70,7 +70,8 @@ struct fsnotify_mark_connector; struct fs_context; struct fs_parameter_spec; struct file_kattr; -struct iomap_ops; +struct iomap_iter; +struct iomap; struct delegated_inode; extern void __init inode_init(void); @@ -2083,7 +2084,9 @@ int remap_verify_area(struct file *file, loff_t pos, loff_t len, bool write); int __generic_remap_file_range_prep(struct file *file_in, loff_t pos_in, struct file *file_out, loff_t pos_out, loff_t *len, unsigned int remap_flags, - const struct iomap_ops *dax_read_ops); + int (*dax_read_next)(const struct iomap_iter *iter, + struct iomap *iomap, + struct iomap *srcmap)); int generic_remap_file_range_prep(struct file *file_in, loff_t pos_in, struct file *file_out, loff_t pos_out, loff_t *count, unsigned int remap_flags); @@ -3332,7 +3335,7 @@ struct offset_ctx { unsigned long next_offset; }; -void simple_offset_init(struct offset_ctx *octx); +void simple_offset_init(struct offset_ctx *octx, struct inode *dir); int simple_offset_add(struct offset_ctx *octx, struct dentry *dentry); void simple_offset_remove(struct offset_ctx *octx, struct dentry *dentry); void simple_offset_rename(struct inode *old_dir, struct dentry *old_dentry, diff --git a/include/linux/fs/super_types.h b/include/linux/fs/super_types.h index 72f4288e16c5..6ce105fe8359 100644 --- a/include/linux/fs/super_types.h +++ b/include/linux/fs/super_types.h @@ -173,7 +173,7 @@ struct super_block { struct unicode_map *s_encoding; __u16 s_encoding_flags; #endif - struct hlist_head s_roots; /* alternate root dentries for NFS */ + struct hlist_head s_roots; /* alternate root dentries for NFS and ex-mountpoints */ spinlock_t s_roots_lock; struct mount *s_mounts; /* list of mounts; _not_ for fs use */ struct block_device *s_bdev; /* can go away once we use an accessor for @s_bdev_file */ diff --git a/include/linux/iio/common/inv_sensors_timestamp.h b/include/linux/iio/common/inv_sensors_timestamp.h index 4f08204ede3b..91690778ae88 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/iomap.h b/include/linux/iomap.h index 5254430844b2..78a1b7603a4f 100644 --- a/include/linux/iomap.h +++ b/include/linux/iomap.h @@ -195,7 +195,7 @@ struct iomap_write_ops { }; /* - * Flags for iomap_begin / iomap_end. No flag implies a read. + * Flags for iomap_next. No flag implies a read. */ #define IOMAP_WRITE (1 << 0) /* writing, must allocate blocks */ #define IOMAP_ZERO (1 << 1) /* zeroing operation, may skip holes */ @@ -239,12 +239,6 @@ typedef int (*iomap_iter_end_fn)(struct inode *inode, loff_t pos, loff_t length, typedef int (*iomap_iter_next_fn)(const struct iomap_iter *iter, struct iomap *iomap, struct iomap *srcmap); -struct iomap_ops { - iomap_iter_begin_fn iomap_begin; - iomap_iter_end_fn iomap_end; - iomap_iter_next_fn iomap_next; -}; - /** * struct iomap_iter - Iterate through a range of a file * @inode: Set at the start of the iteration and should not change. @@ -256,7 +250,7 @@ struct iomap_ops { * incremental iter advance. * @status: Status of the most recent iteration. Zero on success or a negative * errno on error. - * @flags: Zero or more of the iomap_begin flags above. + * @flags: Zero or more of the iomap_iter_next flags above. * @iomap: Map describing the I/O iteration * @srcmap: Source map for COW operations */ @@ -273,7 +267,7 @@ struct iomap_iter { void *private; }; -int iomap_iter(struct iomap_iter *iter, const struct iomap_ops *ops); +int iomap_iter(struct iomap_iter *iter, iomap_iter_next_fn next); int iomap_iter_advance(struct iomap_iter *iter, u64 count); /** @@ -341,7 +335,7 @@ int iomap_iter_continue(const struct iomap_iter *iter, struct iomap *iomap, * @begin: callback that produces a mapping for the current position * @end: optional callback that finishes the previous mapping, or NULL * - * Inline helper that implements the common body of an ->iomap_next() + * Inline helper that implements the common body of an iomap_iter_next_fn * callback: it finishes the previous mapping via @end (if present), decides * via iomap_iter_continue() whether to keep going, and obtains the next * mapping via @begin. @@ -396,6 +390,14 @@ int name(const struct iomap_iter *iter, struct iomap *iomap, \ DEFINE_IOMAP_ITER_NEXT_END(name, begin_fn, NULL) /* + * Forward-declare an iomap_iter_next_fn callback generated by + * DEFINE_IOMAP_ITER_NEXT(). + */ +#define DECLARE_IOMAP_ITER_NEXT(name) \ +int name(const struct iomap_iter *iter, struct iomap *iomap, \ + struct iomap *srcmap) + +/* * Return the file offset for the first unchanged block after a short write. * * If nothing was written, round @pos down to point at the first block in @@ -429,15 +431,15 @@ static inline bool iomap_want_unshare_iter(const struct iomap_iter *iter) } ssize_t iomap_file_buffered_write(struct kiocb *iocb, struct iov_iter *from, - const struct iomap_ops *ops, + iomap_iter_next_fn next, const struct iomap_write_ops *write_ops, void *private); int iomap_fsverity_write(struct file *file, loff_t pos, size_t length, - const void *buf, const struct iomap_ops *ops, + const void *buf, iomap_iter_next_fn next, const struct iomap_write_ops *write_ops); -void iomap_read_folio(const struct iomap_ops *ops, - struct iomap_read_folio_ctx *ctx, void *private); -void iomap_readahead(const struct iomap_ops *ops, - struct iomap_read_folio_ctx *ctx, void *private); +void iomap_read_folio(iomap_iter_next_fn next, struct iomap_read_folio_ctx *ctx, + void *private); +void iomap_readahead(iomap_iter_next_fn next, struct iomap_read_folio_ctx *ctx, + void *private); bool iomap_is_partially_uptodate(struct folio *, size_t from, size_t count); struct folio *iomap_get_folio(struct iomap_iter *iter, loff_t pos, size_t len); bool iomap_release_folio(struct folio *folio, gfp_t gfp_flags); @@ -445,17 +447,17 @@ void iomap_invalidate_folio(struct folio *folio, size_t offset, size_t len); bool iomap_dirty_folio(struct address_space *mapping, struct folio *folio); void iomap_folio_mark_uptodate(struct folio *folio); int iomap_file_unshare(struct inode *inode, loff_t pos, loff_t len, - const struct iomap_ops *ops, + iomap_iter_next_fn next, const struct iomap_write_ops *write_ops); unsigned int iomap_fill_dirty_folios(struct iomap_iter *iter, loff_t *start, loff_t end, unsigned int *iomap_flags); int iomap_zero_range(struct inode *inode, loff_t pos, loff_t len, - bool *did_zero, const struct iomap_ops *ops, + bool *did_zero, iomap_iter_next_fn next, const struct iomap_write_ops *write_ops, void *private); int iomap_truncate_page(struct inode *inode, loff_t pos, bool *did_zero, - const struct iomap_ops *ops, + iomap_iter_next_fn next, const struct iomap_write_ops *write_ops, void *private); -vm_fault_t iomap_page_mkwrite(struct vm_fault *vmf, const struct iomap_ops *ops, +vm_fault_t iomap_page_mkwrite(struct vm_fault *vmf, iomap_iter_next_fn next, void *private); typedef void (*iomap_punch_t)(struct inode *inode, loff_t offset, loff_t length, struct iomap *iomap); @@ -464,13 +466,13 @@ void iomap_write_delalloc_release(struct inode *inode, loff_t start_byte, iomap_punch_t punch); int iomap_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo, - u64 start, u64 len, const struct iomap_ops *ops); + u64 start, u64 len, iomap_iter_next_fn next); loff_t iomap_seek_hole(struct inode *inode, loff_t offset, - const struct iomap_ops *ops); + iomap_iter_next_fn next); loff_t iomap_seek_data(struct inode *inode, loff_t offset, - const struct iomap_ops *ops); + iomap_iter_next_fn next); sector_t iomap_bmap(struct address_space *mapping, sector_t bno, - const struct iomap_ops *ops); + iomap_iter_next_fn next); /* * Flags for iomap_ioend->io_flags. @@ -711,10 +713,10 @@ struct iomap_dio_ops { #define IOMAP_DIO_BOUNCE (1 << 4) ssize_t iomap_dio_rw(struct kiocb *iocb, struct iov_iter *iter, - const struct iomap_ops *ops, const struct iomap_dio_ops *dops, + iomap_iter_next_fn next, const struct iomap_dio_ops *dops, unsigned int dio_flags, void *private, size_t done_before); struct iomap_dio *__iomap_dio_rw(struct kiocb *iocb, struct iov_iter *iter, - const struct iomap_ops *ops, const struct iomap_dio_ops *dops, + iomap_iter_next_fn next, const struct iomap_dio_ops *dops, unsigned int dio_flags, void *private, size_t done_before); ssize_t iomap_dio_complete(struct iomap_dio *dio); void iomap_dio_bio_end_io(struct bio *bio); @@ -790,9 +792,9 @@ struct swap_info_struct; int iomap_swapfile_activate(struct swap_info_struct *sis, struct file *swap_file, sector_t *pagespan, - const struct iomap_ops *ops); + iomap_iter_next_fn next); #else -# define iomap_swapfile_activate(sis, swapfile, pagespan, ops) (-EIO) +# define iomap_swapfile_activate(sis, swapfile, pagespan, next) (-EIO) #endif /* CONFIG_SWAP */ extern struct bio_set iomap_ioend_bioset; @@ -806,25 +808,25 @@ void iomap_bio_submit_read_endio(const struct iomap_iter *iter, extern const struct iomap_read_ops iomap_bio_read_ops; static inline void iomap_bio_read_folio(struct folio *folio, - const struct iomap_ops *ops) + iomap_iter_next_fn next) { struct iomap_read_folio_ctx ctx = { .ops = &iomap_bio_read_ops, .cur_folio = folio, }; - iomap_read_folio(ops, &ctx, NULL); + iomap_read_folio(next, &ctx, NULL); } static inline void iomap_bio_readahead(struct readahead_control *rac, - const struct iomap_ops *ops) + iomap_iter_next_fn next) { struct iomap_read_folio_ctx ctx = { .ops = &iomap_bio_read_ops, .rac = rac, }; - iomap_readahead(ops, &ctx, NULL); + iomap_readahead(next, &ctx, NULL); } #endif /* CONFIG_BLOCK */ diff --git a/include/linux/key.h b/include/linux/key.h index 115db6e60254..420412aab926 100644 --- a/include/linux/key.h +++ b/include/linux/key.h @@ -37,6 +37,9 @@ struct net; #undef KEY_DEBUGGING +/* Maximum length of a key description, including the trailing NUL */ +#define KEY_MAX_DESC_SIZE 4096 + #define KEY_POS_VIEW 0x01000000 /* possessor can view a key's attributes */ #define KEY_POS_READ 0x02000000 /* possessor can read key payload / view keyring */ #define KEY_POS_WRITE 0x04000000 /* possessor can update key payload / add link to keyring */ @@ -216,8 +219,8 @@ struct key { kuid_t uid; kgid_t gid; key_perm_t perm; /* access permissions */ - unsigned short quotalen; /* length added to quota */ - unsigned short datalen; /* payload data length + unsigned int quotalen; /* length added to quota */ + unsigned int datalen; /* payload data length * - may not match RCU dereferenced payload * - payload should contain own length */ diff --git a/include/linux/mlx5/driver.h b/include/linux/mlx5/driver.h index abb99371ff13..84e9f6bdb7c1 100644 --- a/include/linux/mlx5/driver.h +++ b/include/linux/mlx5/driver.h @@ -789,8 +789,12 @@ struct mlx5_core_dev { u32 vsc_addr; struct mlx5_hv_vhca *hv_vhca; struct mlx5_hwmon *hwmon; - u64 num_block_tc; - u64 num_block_ipsec; + struct { + /* Protects the fields below. */ + spinlock_t lock; + u64 num_block_tc; + u64 num_block_ipsec; + } offload_block; #ifdef CONFIG_MLX5_MACSEC struct mlx5_macsec_fs *macsec_fs; /* MACsec notifier chain to sync MACsec core and IB database */ diff --git a/include/linux/mm.h b/include/linux/mm.h index 6af3b7008f1a..daf07b2d208f 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; diff --git a/include/linux/mmzone.h b/include/linux/mmzone.h index ecd1ebd49756..72ffb2959c4f 100644 --- a/include/linux/mmzone.h +++ b/include/linux/mmzone.h @@ -1439,7 +1439,6 @@ struct zoneref { * * zonelist_zone() - Return the struct zone * for an entry in _zonerefs * zonelist_zone_idx() - Return the index of the zone for an entry - * zonelist_node_idx() - Return the index of the node for an entry */ struct zonelist { struct zoneref _zonerefs[MAX_ZONES_PER_ZONELIST + 1]; @@ -1855,7 +1854,8 @@ extern struct zone *next_zone(struct zone *zone); static inline struct zone *zonelist_zone(struct zoneref *zoneref) { - return zoneref->zone; + /* Memory hotplug rewrites zonelists in place. */ + return READ_ONCE(zoneref->zone); } static inline int zonelist_zone_idx(const struct zoneref *zoneref) @@ -1863,11 +1863,6 @@ static inline int zonelist_zone_idx(const struct zoneref *zoneref) return zoneref->zone_idx; } -static inline int zonelist_node_idx(const struct zoneref *zoneref) -{ - return zone_to_nid(zoneref->zone); -} - struct zoneref *__next_zones_zonelist(struct zoneref *z, enum zone_type highest_zoneidx, const nodemask_t *nodes); diff --git a/include/linux/netdevice_xmit.h b/include/linux/netdevice_xmit.h index cc232508e695..286ae5a6101e 100644 --- a/include/linux/netdevice_xmit.h +++ b/include/linux/netdevice_xmit.h @@ -18,8 +18,8 @@ struct netdev_xmit { u8 sched_mirred_nest; struct net_device *sched_mirred_dev[MIRRED_NEST_LIMIT]; #endif -#if IS_ENABLED(CONFIG_NF_DUP_NETDEV) - u8 nf_dup_skb_recursion; +#if IS_ENABLED(CONFIG_NETFILTER) + u8 nf_xmit_skb_recursion; #endif }; diff --git a/include/linux/nfs_fs_sb.h b/include/linux/nfs_fs_sb.h index 416c6f39f31d..6e1b0332f2de 100644 --- a/include/linux/nfs_fs_sb.h +++ b/include/linux/nfs_fs_sb.h @@ -120,6 +120,7 @@ struct nfs_client { #define NFS_SP4_MACH_CRED_COMMIT 6 /* COMMIT */ #define NFS_SP4_MACH_CRED_PNFS_CLEANUP 7 /* LAYOUTRETURN */ wait_queue_head_t cl_lock_waitq; + bool cl_may_notify_lock; #endif /* CONFIG_NFS_V4 */ /* Our own IP address, as a null-terminated string. diff --git a/include/linux/ns_common.h b/include/linux/ns_common.h index c8e227a3f9e2..e8b2bf0da5ed 100644 --- a/include/linux/ns_common.h +++ b/include/linux/ns_common.h @@ -9,7 +9,8 @@ #include <uapi/linux/nsfs.h> bool is_current_namespace(struct ns_common *ns); -int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_operations *ops, int inum); +int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_operations *ops, + int inum, u64 ns_id); void __ns_common_free(struct ns_common *ns); struct ns_common *__must_check ns_owner(struct ns_common *ns); @@ -41,17 +42,18 @@ static __always_inline bool is_ns_init_id(const struct ns_common *ns) .ns_owner_root.ns_list_head = LIST_HEAD_INIT(nsname.ns.ns_owner_root.ns_list_head), \ } -#define ns_common_init(__ns) \ - __ns_common_init(to_ns_common(__ns), \ - ns_common_type(__ns), \ - to_ns_operations(__ns), \ - (((__ns) == ns_init_ns(__ns)) ? ns_init_inum(__ns) : 0)) +#define ns_common_init(__ns) \ + __ns_common_init(to_ns_common(__ns), \ + ns_common_type(__ns), \ + to_ns_operations(__ns), \ + (((__ns) == ns_init_ns(__ns)) ? ns_init_inum(__ns) : 0), \ + (((__ns) == ns_init_ns(__ns)) ? ns_init_id(__ns) : 0)) #define ns_common_init_inum(__ns, __inum) \ __ns_common_init(to_ns_common(__ns), \ ns_common_type(__ns), \ to_ns_operations(__ns), \ - __inum) + __inum, 0) #define ns_common_free(__ns) __ns_common_free(to_ns_common((__ns))) diff --git a/include/linux/nstree.h b/include/linux/nstree.h index 5b64d4572881..eeed713804be 100644 --- a/include/linux/nstree.h +++ b/include/linux/nstree.h @@ -41,43 +41,22 @@ void ns_tree_node_del(struct ns_tree_node *node, struct ns_tree_root *root); struct user_namespace *: &(user_ns_tree), \ struct uts_namespace *: &(uts_ns_tree)) -#define ns_tree_gen_id(__ns) \ - __ns_tree_gen_id(to_ns_common(__ns), \ - (((__ns) == ns_init_ns(__ns)) ? ns_init_id(__ns) : 0)) - u64 __ns_tree_gen_id(struct ns_common *ns, u64 id); -void __ns_tree_add_raw(struct ns_common *ns, struct ns_tree_root *ns_tree); +void __ns_tree_add(struct ns_common *ns, struct ns_tree_root *ns_tree); void __ns_tree_remove(struct ns_common *ns, struct ns_tree_root *ns_tree); struct ns_common *ns_tree_lookup_rcu(u64 ns_id, int ns_type); struct ns_common *__ns_tree_adjoined_rcu(struct ns_common *ns, struct ns_tree_root *ns_tree, bool previous); -static inline void __ns_tree_add(struct ns_common *ns, struct ns_tree_root *ns_tree, u64 id) -{ - __ns_tree_gen_id(ns, id); - __ns_tree_add_raw(ns, ns_tree); -} - -/** - * ns_tree_add_raw - Add a namespace to a namespace - * @__ns: Namespace to add - * - * This function adds a namespace to the appropriate namespace tree - * without assigning a id. - */ -#define ns_tree_add_raw(__ns) __ns_tree_add_raw(to_ns_common(__ns), to_ns_tree(__ns)) - /** * ns_tree_add - Add a namespace to a namespace tree * @__ns: Namespace to add * - * This function assigns a new id to the namespace and adds it to the - * appropriate namespace tree and list. + * This function adds a namespace to the appropriate namespace tree and + * list. The namespace must already have been assigned an id. */ -#define ns_tree_add(__ns) \ - __ns_tree_add(to_ns_common(__ns), to_ns_tree(__ns), \ - (((__ns) == ns_init_ns(__ns)) ? ns_init_id(__ns) : 0)) +#define ns_tree_add(__ns) __ns_tree_add(to_ns_common(__ns), to_ns_tree(__ns)) /** * ns_tree_remove - Remove a namespace from a namespace tree diff --git a/include/linux/pgtable.h b/include/linux/pgtable.h index 780fe849ff8b..66d369870a74 100644 --- a/include/linux/pgtable.h +++ b/include/linux/pgtable.h @@ -12,6 +12,7 @@ #ifdef CONFIG_MMU #include <linux/mm_types.h> +#include <linux/minmax.h> #include <linux/bug.h> #include <linux/errno.h> #include <asm-generic/pgtable_uffd.h> @@ -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/pipe_fs_i.h b/include/linux/pipe_fs_i.h index 6402930282e5..95f6236c5c5b 100644 --- a/include/linux/pipe_fs_i.h +++ b/include/linux/pipe_fs_i.h @@ -4,9 +4,7 @@ #define PIPE_DEF_BUFFERS 16 -#define PIPE_BUF_FLAG_LRU 0x01 /* page is on the LRU */ #define PIPE_BUF_FLAG_ATOMIC 0x02 /* was atomically mapped */ -#define PIPE_BUF_FLAG_GIFT 0x04 /* page is a gift */ #define PIPE_BUF_FLAG_PACKET 0x08 /* read() as a packet */ #define PIPE_BUF_FLAG_CAN_MERGE 0x10 /* can merge buffers */ #define PIPE_BUF_FLAG_WHOLE 0x20 /* read() must return entire buffer or error */ @@ -127,16 +125,6 @@ struct pipe_inode_info { #endif }; -/* - * Note on the nesting of these functions: - * - * ->confirm() - * ->try_steal() - * - * That is, ->try_steal() must be called on a confirmed buffer. See below for - * the meaning of each operation. Also see the kerneldoc in fs/pipe.c for the - * pipe and generic variants of these hooks. - */ struct pipe_buf_operations { /* * ->confirm() verifies that the data in the pipe buffer is there @@ -154,16 +142,6 @@ struct pipe_buf_operations { void (*release)(struct pipe_inode_info *, struct pipe_buffer *); /* - * Attempt to take ownership of the pipe buffer and its contents. - * ->try_steal() returns %true for success, in which case the contents - * of the pipe (the buf->page) is locked and now completely owned by the - * caller. The page may then be transferred to a different mapping, the - * most often used case is insertion into different file address space - * cache. - */ - bool (*try_steal)(struct pipe_inode_info *, struct pipe_buffer *); - - /* * Get a reference to the pipe buffer. */ bool (*get)(struct pipe_inode_info *, struct pipe_buffer *); @@ -304,19 +282,6 @@ static inline int pipe_buf_confirm(struct pipe_inode_info *pipe, return buf->ops->confirm(pipe, buf); } -/** - * pipe_buf_try_steal - attempt to take ownership of a pipe_buffer - * @pipe: the pipe that the buffer belongs to - * @buf: the buffer to attempt to steal - */ -static inline bool pipe_buf_try_steal(struct pipe_inode_info *pipe, - struct pipe_buffer *buf) -{ - if (!buf->ops->try_steal) - return false; - return buf->ops->try_steal(pipe, buf); -} - /* Differs from PIPE_BUF in that PIPE_SIZE is the length of the actual memory allocation, whereas PIPE_BUF makes atomicity guarantees. */ #define PIPE_SIZE PAGE_SIZE @@ -335,11 +300,8 @@ void free_pipe_info(struct pipe_inode_info *); /* Generic pipe buffer ops functions */ bool generic_pipe_buf_get(struct pipe_inode_info *, struct pipe_buffer *); -bool generic_pipe_buf_try_steal(struct pipe_inode_info *, struct pipe_buffer *); void generic_pipe_buf_release(struct pipe_inode_info *, struct pipe_buffer *); -extern const struct pipe_buf_operations nosteal_pipe_buf_ops; - unsigned long account_pipe_buffers(struct user_struct *user, unsigned long old, unsigned long new); bool too_many_pipe_buffers_soft(unsigned long user_bufs); diff --git a/include/linux/ssb/ssb_driver_chipcommon.h b/include/linux/ssb/ssb_driver_chipcommon.h index c44335b011be..17345729eb73 100644 --- a/include/linux/ssb/ssb_driver_chipcommon.h +++ b/include/linux/ssb/ssb_driver_chipcommon.h @@ -9,7 +9,7 @@ * gpio interface, extbus, and support for serial and parallel flashes. * * Copyright 2005, Broadcom Corporation - * Copyright 2006, Michael Buesch <m@bues.ch> + * Copyright 2006, Michael Buesch */ /** ChipCommon core registers. **/ diff --git a/include/linux/stat.h b/include/linux/stat.h index 9c5709132862..4f0a4af7a067 100644 --- a/include/linux/stat.h +++ b/include/linux/stat.h @@ -69,4 +69,7 @@ struct kstat { /* file attribute values */ #define STATX_ATTR_CHANGE_MONOTONIC 0x8000000000000000ULL /* version monotonically increases */ +/* mask of STATX_ATTR_* bits that is private to the kernel */ +#define STATX_ATTR_INTERNAL_MASK (STATX_ATTR_CHANGE_MONOTONIC) + #endif diff --git a/include/linux/sunrpc/sched.h b/include/linux/sunrpc/sched.h index 0dbdf3722537..dbaad8b5f181 100644 --- a/include/linux/sunrpc/sched.h +++ b/include/linux/sunrpc/sched.h @@ -230,6 +230,10 @@ unsigned long rpc_cancel_tasks(struct rpc_clnt *clnt, int error, bool (*fnmatch)(const struct rpc_task *, const void *), const void *data); +unsigned long rpc_cancel_tasks_and_disconnect(struct rpc_clnt *clnt, int error, + bool (*fnmatch)(const struct rpc_task *, + const void *), + const void *data); void rpc_execute(struct rpc_task *); void rpc_init_priority_wait_queue(struct rpc_wait_queue *, const char *); void rpc_init_wait_queue(struct rpc_wait_queue *, const char *); diff --git a/include/linux/sunrpc/xprt.h b/include/linux/sunrpc/xprt.h index 005730623f3b..780eaa157a9f 100644 --- a/include/linux/sunrpc/xprt.h +++ b/include/linux/sunrpc/xprt.h @@ -112,6 +112,11 @@ struct rpc_rqst { ktime_t rq_xtime; /* transmit time stamp */ int rq_ntrans; + bool rq_disconnect_on_release; + /* + * protected by rq_xprt->transport_lock + * while the request is active + */ #if defined(CONFIG_SUNRPC_BACKCHANNEL) struct lwq_node rq_bc_list; /* Callback service list */ diff --git a/include/linux/tcp.h b/include/linux/tcp.h index 5a4c61fc240e..e6b79cf4798f 100644 --- a/include/linux/tcp.h +++ b/include/linux/tcp.h @@ -366,6 +366,7 @@ struct tcp_sock { u32 rcv_rtt_last_tsecr; u32 delivered_ecn_bytes[3]; u16 pkts_acked_ewma;/* Pkts acked EWMA for AccECN cep heuristic */ + u32 rcv_collapse_credit; /* memory queued since last collapse */ struct { u32 rtt_us; u32 seq; @@ -621,13 +622,13 @@ static inline void fastopen_queue_tune(struct sock *sk, int backlog) static inline void tcp_move_syn(struct tcp_sock *tp, struct request_sock *req) { - tp->saved_syn = req->saved_syn; - req->saved_syn = NULL; + tp->saved_syn = unrcu_pointer(req->saved_syn); + RCU_INIT_POINTER(req->saved_syn, NULL); } static inline void tcp_saved_syn_free(struct tcp_sock *tp) { - kfree(tp->saved_syn); + kfree_rcu(tp->saved_syn, rcu); tp->saved_syn = NULL; } diff --git a/include/linux/uio.h b/include/linux/uio.h index 638c1116e912..76e4103b9ec4 100644 --- a/include/linux/uio.h +++ b/include/linux/uio.h @@ -373,11 +373,11 @@ struct iovec *iovec_from_user(const struct iovec __user *uvector, unsigned long nr_segs, unsigned long fast_segs, struct iovec *fast_iov, bool compat); ssize_t import_iovec(int type, const struct iovec __user *uvec, - unsigned nr_segs, unsigned fast_segs, struct iovec **iovp, - struct iov_iter *i); + unsigned long nr_segs, unsigned int fast_segs, + struct iovec **iovp, struct iov_iter *i); ssize_t __import_iovec(int type, const struct iovec __user *uvec, - unsigned nr_segs, unsigned fast_segs, struct iovec **iovp, - struct iov_iter *i, bool compat); + unsigned long nr_segs, unsigned int fast_segs, + struct iovec **iovp, struct iov_iter *i, bool compat); int import_ubuf(int type, void __user *buf, size_t len, struct iov_iter *i); static inline void iov_iter_ubuf(struct iov_iter *i, unsigned int direction, diff --git a/include/linux/virtio_net.h b/include/linux/virtio_net.h index d6466f96cdd0..fc9667176f23 100644 --- a/include/linux/virtio_net.h +++ b/include/linux/virtio_net.h @@ -5,7 +5,10 @@ #include <linux/if_vlan.h> #include <linux/ip.h> #include <linux/ipv6.h> +#include <linux/netdevice.h> #include <linux/udp.h> +#include <net/ip.h> +#include <net/ipv6.h> #include <net/tcp.h> #include <uapi/linux/tcp.h> #include <uapi/linux/virtio_net.h> @@ -48,6 +51,145 @@ static inline int virtio_net_hdr_set_proto(struct sk_buff *skb, return 0; } +/* TODO: nothing virtio specific here, move to ip.h */ + +/* + * Pull and minimally validate the IPv4 header at @nhoff. + * Returns the header and stores the transport header offset in + * @thoff, or NULL if truncated or malformed. The whole header, + * options included, is guaranteed linear on return. + */ +static inline struct iphdr *virtio_net_ip4_parse(struct sk_buff *skb, + unsigned int nhoff, + unsigned int *thoff) +{ + unsigned int ihl; + struct iphdr *iph; + + if (!pskb_may_pull(skb, nhoff + sizeof(struct iphdr))) + return NULL; + + iph = (struct iphdr *)(skb->data + nhoff); + if (iph->version != 4 || + iph->ihl < sizeof(struct iphdr) / sizeof(u32)) + return NULL; + + ihl = iph->ihl * sizeof(u32); + *thoff = nhoff + ihl; + /* Pull the options as well: the transport header offset + * returned above must be within the linear data. iph goes + * stale across the pull. + */ + if (!pskb_may_pull(skb, nhoff + ihl)) + return NULL; + + return (struct iphdr *)(skb->data + nhoff); +} + +/* Where does the L3 header start, and what protocol is it? + * With @has_eth, the frame starts with an Ethernet header, possibly + * followed by VLAN tags. Otherwise the L3 header starts at the network + * header offset the caller set up. + * + * The caller knows how the frame will be parsed later: the device + * type does not tell, as tun can change it with TUNSETLINK. + */ +static inline bool +virtio_net_l3_start(struct sk_buff *skb, bool has_eth, int *nhoff, + __be16 *proto) +{ + if (has_eth) { + __be16 h_proto; + + if (!pskb_may_pull(skb, ETH_HLEN)) + return false; + h_proto = eth_hdr(skb)->h_proto; + /* skb->protocol is a sender claim, and parts of the + * stack parse the packet per it: when it disagrees with + * the frame we do not know which view the packet will + * be parsed as, so do not validate. + */ + if (skb->protocol && skb->protocol != h_proto) + return false; + *nhoff = ETH_HLEN; + *proto = h_proto; + if (eth_type_vlan(*proto)) { + *proto = __vlan_get_protocol(skb, *proto, nhoff); + if (!*proto) + return false; + } + } else { + const struct iphdr *iph; + + *nhoff = skb_network_offset(skb); + /* An unset network header shows up as an offset + * outside of the packet. + */ + if (*nhoff < 0 || (unsigned int)*nhoff >= skb->len) + return false; + /* No L2 header to cross-check with: take the protocol + * from the IP version at the network header. + */ + if (!pskb_may_pull(skb, *nhoff + 1)) + return false; + iph = (const struct iphdr *)(skb->data + *nhoff); + if (iph->version == 4) + *proto = htons(ETH_P_IP); + else if (iph->version == 6) + *proto = htons(ETH_P_IPV6); + else + return false; + if (skb->protocol && skb->protocol != *proto) + return false; + } + return true; +} + +/* Walk the L3 header at @nhoff: where does its transport header + * start, and which protocol is it? Returns false if the header + * is truncated, malformed or fragmented. + */ +static inline bool +virtio_net_l4_start(struct sk_buff *skb, unsigned int nhoff, __be16 proto, + unsigned int *thoff, int *ip_proto) +{ + if (proto == htons(ETH_P_IP)) { + const struct iphdr *iph = virtio_net_ip4_parse(skb, nhoff, thoff); + + if (!iph || ip_is_fragment(iph)) + return false; + *ip_proto = iph->protocol; + return true; + } + + if (proto == htons(ETH_P_IPV6)) { + const struct ipv6hdr *iph; + int flags = IP6_FH_F_AUTH; + + if (!pskb_may_pull(skb, nhoff + sizeof(*iph))) + return false; + iph = (const void *)(skb->data + nhoff); + if (iph->version != 6) + return false; + *thoff = nhoff + sizeof(*iph); + *ip_proto = iph->nexthdr; + if (*ip_proto != IPPROTO_TCP && *ip_proto != IPPROTO_UDP) { + *thoff = nhoff; + /* Find the transport header behind any + * extension headers. IP6_FH_F_AUTH stops + * the walk at AH, so frames with AH are rejected. + */ + *ip_proto = ipv6_find_hdr(skb, thoff, -1, NULL, + &flags); + if (*ip_proto < 0 || flags & IP6_FH_F_FRAG) + return false; + } + return true; + } + + return false; +} + static inline int __virtio_net_hdr_to_skb(struct sk_buff *skb, const struct virtio_net_hdr *hdr, bool little_endian, u8 hdr_gso_type) @@ -282,9 +424,33 @@ static inline unsigned int virtio_l3min(bool is_ipv6) return is_ipv6 ? sizeof(struct ipv6hdr) : sizeof(struct iphdr); } +/* Do the tunnel offsets match the outer headers in the frame? + * The L3 header the tunnel claims must be the one the frame + * carries, with UDP following it at @outer_th. + */ +static inline bool +virtio_net_tnl_offsets_ok(struct sk_buff *skb, bool has_eth, bool outer_isv6, + unsigned int outer_th) +{ + int nhoff; + __be16 proto; + unsigned int thoff; + int ip_proto; + + if (!virtio_net_l3_start(skb, has_eth, &nhoff, &proto)) + return false; + if (outer_isv6 != (proto == htons(ETH_P_IPV6))) + return false; + if (!virtio_net_l4_start(skb, nhoff, proto, &thoff, &ip_proto)) + return false; + + return ip_proto == IPPROTO_UDP && outer_th == thoff; +} + static inline int virtio_net_hdr_tnl_to_skb(struct sk_buff *skb, const struct virtio_net_hdr_v1_hash_tunnel *vhdr, + bool has_eth, bool tnl_hdr_negotiated, bool tnl_csum_negotiated, bool little_endian) @@ -338,6 +504,9 @@ virtio_net_hdr_tnl_to_skb(struct sk_buff *skb, if (ret) return ret; + if (!virtio_net_tnl_offsets_ok(skb, has_eth, outer_isv6, outer_th)) + return -EINVAL; + /* In case of USO, the inner protocol is still unknown and * `inner_isv6` is just a guess, additional parsing is needed. * The previous validation ensures that accessing an ipv4 inner @@ -453,7 +622,10 @@ virtio_net_hdr_tnl_from_skb(const struct sk_buff *skb, if (feature_hdrlen && hdr->hdr_len) __virtio_net_set_tnl_hdrlen(skb, hdr); - if (skb->protocol == htons(ETH_P_IPV6)) + /* skb->protocol is the VLAN protocol when the tag is in the + * packet data. + */ + if (vlan_get_protocol(skb) == htons(ETH_P_IPV6)) hdr->gso_type |= VIRTIO_NET_HDR_GSO_UDP_TUNNEL_IPV6; else hdr->gso_type |= VIRTIO_NET_HDR_GSO_UDP_TUNNEL_IPV4; @@ -461,8 +633,11 @@ virtio_net_hdr_tnl_from_skb(const struct sk_buff *skb, if (skb_shinfo(skb)->gso_type & SKB_GSO_UDP_TUNNEL_CSUM) hdr->flags |= VIRTIO_NET_HDR_F_UDP_TUNNEL_CSUM; - inner_nh = skb->inner_network_header - skb_headroom(skb); - outer_th = skb->transport_header - skb_headroom(skb); + /* Like csum_start, the offsets must account for a VLAN tag + * the caller inserts in the frame. + */ + inner_nh = skb->inner_network_header - skb_headroom(skb) + vlan_hlen; + outer_th = skb->transport_header - skb_headroom(skb) + vlan_hlen; vhdr->inner_nh_offset = cpu_to_le16(inner_nh); vhdr->outer_th_offset = cpu_to_le16(outer_th); return 0; diff --git a/include/net/bluetooth/hci_core.h b/include/net/bluetooth/hci_core.h index 908acbad7177..6fb713d5e4be 100644 --- a/include/net/bluetooth/hci_core.h +++ b/include/net/bluetooth/hci_core.h @@ -2367,8 +2367,6 @@ static inline struct smp_irk *hci_get_irk(struct hci_dev *hdev, static inline int hci_check_conn_params(u16 min, u16 max, u16 latency, u16 to_multiplier) { - u16 max_latency; - if (min > max) { BT_WARN("min %d > max %d", min, max); return -EINVAL; @@ -2394,19 +2392,14 @@ static inline int hci_check_conn_params(u16 min, u16 max, u16 latency, return -EINVAL; } - if (max >= to_multiplier * 8) { - BT_WARN("max %d >= to_multiplier %d * 8", max, to_multiplier); - return -EINVAL; - } - - max_latency = (to_multiplier * 4 / max) - 1; if (latency > 499) { BT_WARN("latency %d > 499", latency); return -EINVAL; } - if (latency > max_latency) { - BT_WARN("latency %d > max_latency %d", latency, max_latency); + if ((latency + 1) * max >= to_multiplier * 4) { + BT_WARN("latency %d, max %d and timeout %d are incompatible", + latency, max, to_multiplier); return -EINVAL; } diff --git a/include/net/bluetooth/l2cap.h b/include/net/bluetooth/l2cap.h index 54eddcdd341f..2a05bda8ab43 100644 --- a/include/net/bluetooth/l2cap.h +++ b/include/net/bluetooth/l2cap.h @@ -756,6 +756,7 @@ enum { FLAG_DEFER_SETUP, FLAG_LE_CONN_REQ_SENT, FLAG_ECRED_CONN_REQ_SENT, + FLAG_ECRED_RECONF_REQ_SENT, FLAG_PENDING_SECURITY, FLAG_HOLD_HCI_CONN, FLAG_DEL, diff --git a/include/net/cipso_ipv4.h b/include/net/cipso_ipv4.h index d6780d7903f4..b41672221797 100644 --- a/include/net/cipso_ipv4.h +++ b/include/net/cipso_ipv4.h @@ -185,12 +185,12 @@ int cipso_v4_sock_setattr(struct sock *sk, const struct cipso_v4_doi *doi_def, const struct netlbl_lsm_secattr *secattr, bool sk_locked); -void cipso_v4_sock_delattr(struct sock *sk); +int cipso_v4_sock_delattr(struct sock *sk); int cipso_v4_sock_getattr(struct sock *sk, struct netlbl_lsm_secattr *secattr); int cipso_v4_req_setattr(struct request_sock *req, const struct cipso_v4_doi *doi_def, const struct netlbl_lsm_secattr *secattr); -void cipso_v4_req_delattr(struct request_sock *req); +int cipso_v4_req_delattr(struct request_sock *req); int cipso_v4_skbuff_setattr(struct sk_buff *skb, const struct cipso_v4_doi *doi_def, const struct netlbl_lsm_secattr *secattr); @@ -221,8 +221,9 @@ static inline int cipso_v4_sock_setattr(struct sock *sk, return -ENOSYS; } -static inline void cipso_v4_sock_delattr(struct sock *sk) +static inline int cipso_v4_sock_delattr(struct sock *sk) { + return 0; } static inline int cipso_v4_sock_getattr(struct sock *sk, @@ -238,9 +239,9 @@ static inline int cipso_v4_req_setattr(struct request_sock *req, return -ENOSYS; } -static inline void cipso_v4_req_delattr(struct request_sock *req) +static inline int cipso_v4_req_delattr(struct request_sock *req) { - return; + return 0; } static inline int cipso_v4_skbuff_setattr(struct sk_buff *skb, diff --git a/include/net/dst_metadata.h b/include/net/dst_metadata.h index f45d1e3163f0..02fffbb85099 100644 --- a/include/net/dst_metadata.h +++ b/include/net/dst_metadata.h @@ -116,6 +116,8 @@ static inline int skb_metadata_dst_cmp(const struct sk_buff *skb_a, return memcmp(&a->u.port_info, &b->u.port_info, sizeof(a->u.port_info)); case METADATA_IP_TUNNEL: + if (a->u.tun_info.options_len != b->u.tun_info.options_len) + return 1; return memcmp(&a->u.tun_info, &b->u.tun_info, sizeof(a->u.tun_info) + a->u.tun_info.options_len); diff --git a/include/net/gro.h b/include/net/gro.h index 2300b6da05b2..7a19d4486456 100644 --- a/include/net/gro.h +++ b/include/net/gro.h @@ -160,9 +160,19 @@ static inline bool skb_gro_may_pull(const struct sk_buff *skb, return likely(hlen <= NAPI_GRO_CB(skb)->frag0_len); } +/* A pull can release the page fragment frag0 points to, or reallocate + * skb->head, even if it fails. Call this before the pull, to make sure later + * skb_gro_header() and skb_gro_network_header() calls no longer use frag0. + */ +static inline void skb_gro_frag0_invalidate(struct sk_buff *skb) +{ + NAPI_GRO_CB(skb)->frag0_len = 0; +} + static inline void *skb_gro_header_slow(struct sk_buff *skb, unsigned int hlen, unsigned int offset) { + skb_gro_frag0_invalidate(skb); if (!pskb_may_pull(skb, hlen)) return NULL; @@ -351,7 +361,13 @@ static inline void skb_gro_remcsum_cleanup(struct sk_buff *skb, void *ptr; size_t plen = grc->offset + sizeof(u16); - if (!grc->delta) + /* Once merged, grc->offset can not be trusted: the frags or head + * of this skb now belong to the GRO packet, or skb->data was pulled + * past the headers before adding it to a frag_list. + * skb_gro_receive_list() does not merge packets with an adjusted + * checksum, other merged packets do not use their headers anymore. + */ + if (!grc->delta || NAPI_GRO_CB(skb)->same_flow) return; ptr = skb_gro_header(skb, plen, grc->offset); diff --git a/include/net/gso.h b/include/net/gso.h index fe3260b381d4..119fc4c170e1 100644 --- a/include/net/gso.h +++ b/include/net/gso.h @@ -19,7 +19,7 @@ struct skb_gso_cb { int encap_level; __wsum csum; __u16 csum_start; - /* Number of IPv4/IPv6 GSO handler entries for this packet. */ + /* Number of IPv4/IPv6/NSH GSO handler entries for this packet. */ u8 recursion_counter; /* Max MSS segs per output skb, 0 = no limit */ u8 max_segs; diff --git a/include/net/inet_common.h b/include/net/inet_common.h index 3d747896be30..0f088a213c38 100644 --- a/include/net/inet_common.h +++ b/include/net/inet_common.h @@ -25,7 +25,7 @@ int inet_release(struct socket *sock); int inet_stream_connect(struct socket *sock, struct sockaddr_unsized *uaddr, int addr_len, int flags); int __inet_stream_connect(struct socket *sock, struct sockaddr_unsized *uaddr, - int addr_len, int flags, int is_sendmsg); + int addr_len, int flags, bool defer_connect); int inet_dgram_connect(struct socket *sock, struct sockaddr_unsized *uaddr, int addr_len, int flags); int inet_accept(struct socket *sock, struct socket *newsock, diff --git a/include/net/libeth/xsk.h b/include/net/libeth/xsk.h index a452b7828ce4..249b1c740788 100644 --- a/include/net/libeth/xsk.h +++ b/include/net/libeth/xsk.h @@ -77,11 +77,17 @@ libeth_xsk_tx_queue_bulk(struct libeth_xdp_tx_bulk *bq, if (!libeth_xsk_tx_queue_head(bq, xdp)) goto out; - for (const struct libeth_xdp_buff *head = xdp; ; ) { + for (struct libeth_xdp_buff *head = xdp; ; ) { xdp = container_of(xsk_buff_get_frag(&head->base), typeof(*xdp), base); - if (!xdp) + if (!xdp) { + /* Each frag is now freed via its own SQE. Freeing + * the head must not release what is on the pool's + * frag list at that time. + */ + xdp_buff_clear_frags_flag(&head->base); break; + } if (unlikely(bq->count == LIBETH_XDP_TX_BULK) && unlikely(!flush_bulk(bq, LIBETH_XDP_TX_XSK))) { diff --git a/include/net/mac80211.h b/include/net/mac80211.h index a1a6409b44c1..b74c15207cb9 100644 --- a/include/net/mac80211.h +++ b/include/net/mac80211.h @@ -1772,7 +1772,8 @@ enum mac80211_rx_encoding { * @zero_length_psdu_type: radiotap type of the 0-length PSDU * @link_id: id of the link used to receive the packet. Set and used by * mac80211 internally, it uses @freq set by the driver to identify the - * correct link per vif. + * correct link per vif. Set to %IEEE80211_LINK_UNSPECIFIED for non-MLD + * or if link information is not applicable. */ struct ieee80211_rx_status { u64 mactime; diff --git a/include/net/mana/mana.h b/include/net/mana/mana.h index 09725e3256fa..218d540bc994 100644 --- a/include/net/mana/mana.h +++ b/include/net/mana/mana.h @@ -421,6 +421,8 @@ struct mana_rxq { struct bpf_prog __rcu *bpf_prog; struct xdp_rxq_info xdp_rxq; + /* For buffers not from the page pool (from_pool == false) */ + struct xdp_rxq_info xdp_rxq_shared; void *xdp_save_va; /* for reusing */ bool xdp_flush; int xdp_rc; /* XDP redirect return code */ @@ -696,7 +698,8 @@ void mana_xdp_tx(struct sk_buff *skb, struct net_device *ndev); int mana_xdp_xmit(struct net_device *ndev, int n, struct xdp_frame **frames, u32 flags); u32 mana_run_xdp(struct net_device *ndev, struct mana_rxq *rxq, - struct xdp_buff *xdp, void *buf_va, uint pkt_len); + struct xdp_buff *xdp, void *buf_va, bool from_pool, + uint pkt_len); struct bpf_prog *mana_xdp_get(struct mana_port_context *apc); void mana_chn_setxdp(struct mana_port_context *apc, struct bpf_prog *prog); int mana_bpf(struct net_device *ndev, struct netdev_bpf *bpf); diff --git a/include/net/net_namespace.h b/include/net/net_namespace.h index c29a22ca178f..4a4d72080acd 100644 --- a/include/net/net_namespace.h +++ b/include/net/net_namespace.h @@ -72,6 +72,7 @@ struct net { unsigned int dev_base_seq; /* protected by rtnl_mutex */ atomic_t dev_mc_genid; /* dev->mc membership changes */ + atomic_t dev_unreg_pending; /* devices in netdev_run_todo() */ u32 ifindex; spinlock_t nsid_lock; diff --git a/include/net/netfilter/nf_dup_netdev.h b/include/net/netfilter/nf_dup_netdev.h index f6b05bd80c3f..a39411264614 100644 --- a/include/net/netfilter/nf_dup_netdev.h +++ b/include/net/netfilter/nf_dup_netdev.h @@ -9,41 +9,6 @@ void nf_dup_netdev_egress(const struct nft_pktinfo *pkt, int oif); void nf_fwd_netdev_egress(const struct nft_pktinfo *pkt, int oif); -#define NF_RECURSION_LIMIT 2 - -#ifndef CONFIG_PREEMPT_RT -static inline bool nf_dev_xmit_recursion(void) -{ - return unlikely(__this_cpu_read(softnet_data.xmit.nf_dup_skb_recursion) > - NF_RECURSION_LIMIT); -} - -static inline void nf_dev_xmit_recursion_inc(void) -{ - __this_cpu_inc(softnet_data.xmit.nf_dup_skb_recursion); -} - -static inline void nf_dev_xmit_recursion_dec(void) -{ - __this_cpu_dec(softnet_data.xmit.nf_dup_skb_recursion); -} -#else -static inline bool nf_dev_xmit_recursion(void) -{ - return unlikely(current->net_xmit.nf_dup_skb_recursion > NF_RECURSION_LIMIT); -} - -static inline void nf_dev_xmit_recursion_inc(void) -{ - current->net_xmit.nf_dup_skb_recursion++; -} - -static inline void nf_dev_xmit_recursion_dec(void) -{ - current->net_xmit.nf_dup_skb_recursion--; -} -#endif - struct nft_offload_ctx; struct nft_flow_rule; diff --git a/include/net/netfilter/nf_queue.h b/include/net/netfilter/nf_queue.h index 86021c55ba3c..4a8cefd8398d 100644 --- a/include/net/netfilter/nf_queue.h +++ b/include/net/netfilter/nf_queue.h @@ -23,6 +23,7 @@ struct nf_queue_entry { struct net_device *physout; #endif struct nf_hook_state state; + bool in_nf_duplicate; bool nf_ct_is_unconfirmed; u16 size; /* sizeof(entry) + saved route keys */ diff --git a/include/net/netfilter/nf_recursion.h b/include/net/netfilter/nf_recursion.h new file mode 100644 index 000000000000..1ac65f7793f1 --- /dev/null +++ b/include/net/netfilter/nf_recursion.h @@ -0,0 +1,42 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _NF_RECURSION_H_ +#define _NF_RECURSION_H_ + +#include <linux/netdevice.h> + +#define NF_RECURSION_LIMIT 2 + +#ifndef CONFIG_PREEMPT_RT +static inline bool nf_dev_xmit_recursion(void) +{ + return unlikely(__this_cpu_read(softnet_data.xmit.nf_xmit_skb_recursion) > + NF_RECURSION_LIMIT); +} + +static inline void nf_dev_xmit_recursion_inc(void) +{ + __this_cpu_inc(softnet_data.xmit.nf_xmit_skb_recursion); +} + +static inline void nf_dev_xmit_recursion_dec(void) +{ + __this_cpu_dec(softnet_data.xmit.nf_xmit_skb_recursion); +} +#else +static inline bool nf_dev_xmit_recursion(void) +{ + return unlikely(current->net_xmit.nf_xmit_skb_recursion > NF_RECURSION_LIMIT); +} + +static inline void nf_dev_xmit_recursion_inc(void) +{ + current->net_xmit.nf_xmit_skb_recursion++; +} + +static inline void nf_dev_xmit_recursion_dec(void) +{ + current->net_xmit.nf_xmit_skb_recursion--; +} +#endif + +#endif /* _NF_RECURSION_H_ */ diff --git a/include/net/netlabel.h b/include/net/netlabel.h index 02914b1df38b..f896b9d52ed1 100644 --- a/include/net/netlabel.h +++ b/include/net/netlabel.h @@ -477,7 +477,7 @@ int netlbl_sock_setattr(struct sock *sk, u16 family, const struct netlbl_lsm_secattr *secattr, bool sk_locked); -void netlbl_sock_delattr(struct sock *sk); +int netlbl_sock_delattr(struct sock *sk); int netlbl_sock_getattr(struct sock *sk, struct netlbl_lsm_secattr *secattr); int netlbl_conn_setattr(struct sock *sk, @@ -485,7 +485,7 @@ int netlbl_conn_setattr(struct sock *sk, const struct netlbl_lsm_secattr *secattr); int netlbl_req_setattr(struct request_sock *req, const struct netlbl_lsm_secattr *secattr); -void netlbl_req_delattr(struct request_sock *req); +int netlbl_req_delattr(struct request_sock *req); int netlbl_skbuff_setattr(struct sk_buff *skb, u16 family, const struct netlbl_lsm_secattr *secattr); @@ -626,8 +626,9 @@ static inline int netlbl_sock_setattr(struct sock *sk, { return -ENOSYS; } -static inline void netlbl_sock_delattr(struct sock *sk) +static inline int netlbl_sock_delattr(struct sock *sk) { + return 0; } static inline int netlbl_sock_getattr(struct sock *sk, struct netlbl_lsm_secattr *secattr) @@ -645,9 +646,9 @@ static inline int netlbl_req_setattr(struct request_sock *req, { return -ENOSYS; } -static inline void netlbl_req_delattr(struct request_sock *req) +static inline int netlbl_req_delattr(struct request_sock *req) { - return; + return 0; } static inline int netlbl_skbuff_setattr(struct sk_buff *skb, u16 family, diff --git a/include/net/request_sock.h b/include/net/request_sock.h index 5a9c826a7092..faa6dc49cea8 100644 --- a/include/net/request_sock.h +++ b/include/net/request_sock.h @@ -39,6 +39,7 @@ struct request_sock_ops { }; struct saved_syn { + struct rcu_head rcu; u32 mac_hdrlen; u32 network_hdrlen; u32 tcp_hdrlen; @@ -68,7 +69,7 @@ struct request_sock { struct timer_list rsk_timer; const struct request_sock_ops *rsk_ops; struct sock *sk; - struct saved_syn *saved_syn; + struct saved_syn __rcu *saved_syn; u32 secid; u32 peer_secid; u32 timeout; diff --git a/include/net/sock.h b/include/net/sock.h index 173b37b2b8bb..3144efad8c36 100644 --- a/include/net/sock.h +++ b/include/net/sock.h @@ -2218,10 +2218,13 @@ sk_dst_get(const struct sock *sk) static inline void __dst_negative_advice(struct sock *sk) { - struct dst_entry *dst = __sk_dst_get(sk); + struct dst_entry *dst; + rcu_read_lock(); + dst = __sk_dst_get(sk); if (dst && dst->ops->negative_advice) dst->ops->negative_advice(sk, dst); + rcu_read_unlock(); } static inline void dst_negative_advice(struct sock *sk) @@ -2284,6 +2287,14 @@ struct dst_entry *__sk_dst_check(struct sock *sk, u32 cookie); struct dst_entry *sk_dst_check(struct sock *sk, u32 cookie); +/* This helper checks if a socket is a full socket, + * ie _not_ a timewait or request socket. + */ +static inline bool sk_fullsock(const struct sock *sk) +{ + return (1 << sk->sk_state) & ~(TCPF_TIME_WAIT | TCPF_NEW_SYN_RECV); +} + static inline void sk_dst_confirm(struct sock *sk) { if (!READ_ONCE(sk->sk_dst_pending_confirm)) @@ -2295,7 +2306,8 @@ static inline void sock_confirm_neigh(struct sk_buff *skb, struct neighbour *n) if (skb_get_dst_pending_confirm(skb)) { struct sock *sk = skb->sk; - if (sk && READ_ONCE(sk->sk_dst_pending_confirm)) + if (sk && sk_fullsock(sk) && + READ_ONCE(sk->sk_dst_pending_confirm)) WRITE_ONCE(sk->sk_dst_pending_confirm, 0); neigh_confirm(n); } @@ -3028,14 +3040,6 @@ skb_sk_is_prefetched(struct sk_buff *skb) #endif /* CONFIG_INET */ } -/* This helper checks if a socket is a full socket, - * ie _not_ a timewait or request socket. - */ -static inline bool sk_fullsock(const struct sock *sk) -{ - return (1 << sk->sk_state) & ~(TCPF_TIME_WAIT | TCPF_NEW_SYN_RECV); -} - static inline bool sk_is_refcounted(struct sock *sk) { diff --git a/include/net/tcp.h b/include/net/tcp.h index 3560adddf821..5c9203aae834 100644 --- a/include/net/tcp.h +++ b/include/net/tcp.h @@ -1554,6 +1554,15 @@ static inline unsigned int tcp_packets_in_flight(const struct tcp_sock *tp) #define TCP_INFINITE_SSTHRESH 0x7fffffff +/* Default and maximum snd_cwnd_clamp, in packets. + * A peer can not advertise more than 65535 << 14 bytes, so a larger + * cwnd is useless with any MSS of 1024 bytes or more. + * Congestion control modules multiply cwnd by u32 factors up to 2047 + * (cwnd * (BICTCP_BETA_SCALE + beta) in CUBIC), and CUBIC's + * bictcp_update() expects cwnd to stay below about one million packets. + */ +#define TCP_MAX_SND_CWND (1U << 20) + static inline u32 tcp_snd_cwnd(const struct tcp_sock *tp) { return tp->snd_cwnd; diff --git a/include/net/tcp_ao.h b/include/net/tcp_ao.h index 9a2333e62e99..edf4c9bc5ef5 100644 --- a/include/net/tcp_ao.h +++ b/include/net/tcp_ao.h @@ -303,7 +303,8 @@ static inline enum skb_drop_reason tcp_inbound_ao_hash(struct sock *sk, const struct request_sock *req, int l3index, const struct tcp_ao_hdr *aoh) { - return SKB_NOT_DROPPED_YET; + NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPAOKEYNOTFOUND); + return SKB_DROP_REASON_TCP_AOUNEXPECTED; } static inline struct tcp_ao_key *tcp_ao_do_lookup(const struct sock *sk, diff --git a/include/net/tls.h b/include/net/tls.h index e57bef58851e..0b001b8ab1c3 100644 --- a/include/net/tls.h +++ b/include/net/tls.h @@ -139,6 +139,7 @@ struct tls_sw_context_rx { u8 zc_capable:1; u8 reader_contended:1; bool key_update_pending; + u8 empty_run; struct tls_strparser strp; diff --git a/include/net/xdp_sock_drv.h b/include/net/xdp_sock_drv.h index d94aeb506379..a40ad3f90f13 100644 --- a/include/net/xdp_sock_drv.h +++ b/include/net/xdp_sock_drv.h @@ -153,6 +153,7 @@ static inline void xsk_buff_free(struct xdp_buff *xdp) } xdp_get_shared_info_from_buff(xdp)->nr_frags = 0; + xdp_buff_clear_frags_flag(xdp); out: xp_free(xskb); } @@ -160,15 +161,18 @@ out: static inline bool xsk_buff_add_frag(struct xdp_buff *head, struct xdp_buff *xdp) { + struct xdp_buff_xsk *frag = container_of(xdp, struct xdp_buff_xsk, xdp); const void *data = xdp->data; - struct xdp_buff_xsk *frag; + + /* Duplicate fill ring entries map to the same xskb in aligned mode */ + if (unlikely(xdp == head || !list_empty(&frag->list_node))) + return false; if (!__xdp_buff_add_frag(head, virt_to_netmem(data), offset_in_page(data), xdp->data_end - data, xdp->frame_sz, false)) return false; - frag = container_of(xdp, struct xdp_buff_xsk, xdp); list_add_tail(&frag->list_node, &frag->pool->xskb_list); return true; @@ -222,7 +226,8 @@ static inline void xsk_buff_set_size(struct xdp_buff *xdp, u32 size) xdp->data = xdp->data_hard_start + XDP_PACKET_HEADROOM; xdp->data_meta = xdp->data; xdp->data_end = xdp->data + size; - xdp->flags = 0; + /* Frags flag is cleared when the frags of a head are released */ + xdp->flags &= XDP_FLAGS_HAS_FRAGS; } static inline dma_addr_t xsk_buff_raw_get_dma(struct xsk_buff_pool *pool, diff --git a/include/trace/events/landlock.h b/include/trace/events/landlock.h index 6d9d9e7c7ca2..b6fdc6e2eef8 100644 --- a/include/trace/events/landlock.h +++ b/include/trace/events/landlock.h @@ -987,7 +987,8 @@ TRACE_EVENT(landlock_deny_access_net, * @logged: Whether this denial was selected for audit logging. * @blockers: Request type and final missing permission subset (never NULL). * @namespace_type: CLONE_NEW* namespace type that was denied. - * @namespace_id: Namespace ID, or 0 when creation was denied. + * @namespace_id: Namespace ID, not directly visible from user space when + * creation was denied. * * Emitted when a Landlock domain denies namespace use. */ diff --git a/include/trace/events/oom.h b/include/trace/events/oom.h index 9f0a5d1482c4..cbcf6fe4cc61 100644 --- a/include/trace/events/oom.h +++ b/include/trace/events/oom.h @@ -33,7 +33,7 @@ TRACE_EVENT(oom_score_adj_update, TRACE_EVENT(reclaim_retry_zone, - TP_PROTO(struct zoneref *zoneref, + TP_PROTO(struct zone *zone, int order, unsigned long reclaimable, unsigned long available, @@ -41,7 +41,7 @@ TRACE_EVENT(reclaim_retry_zone, int no_progress_loops, bool wmark_check), - TP_ARGS(zoneref, order, reclaimable, available, min_wmark, no_progress_loops, wmark_check), + TP_ARGS(zone, order, reclaimable, available, min_wmark, no_progress_loops, wmark_check), TP_STRUCT__entry( __field( int, node) @@ -55,8 +55,8 @@ TRACE_EVENT(reclaim_retry_zone, ), TP_fast_assign( - __entry->node = zonelist_node_idx(zoneref); - __entry->zone_idx = zonelist_zone_idx(zoneref); + __entry->node = zone_to_nid(zone); + __entry->zone_idx = zone_idx(zone); __entry->order = order; __entry->reclaimable = reclaimable; __entry->available = available; diff --git a/include/uapi/linux/mdio.h b/include/uapi/linux/mdio.h index 06f4bc3c20c7..2806f60ed105 100644 --- a/include/uapi/linux/mdio.h +++ b/include/uapi/linux/mdio.h @@ -417,8 +417,17 @@ #define MDIO_AN_10BT1_AN_STAT_LPA_EEE_T1L 0x4000 /* 10BASE-T1L LP EEE ability advertisement */ /* BASE-T1 PMA/PMD control register */ -#define MDIO_PMA_PMD_BT1_CTRL_STRAP 0x000F /* Type selection (Strap) */ -#define MDIO_PMA_PMD_BT1_CTRL_STRAP_B1000 0x0001 /* Select 1000BASE-T1 */ +#define MDIO_PMA_PMD_BT1_CTRL_TYPE_SEL 0x000F /* Type selection */ +#define MDIO_PMA_PMD_BT1_CTRL_TYPE_SEL_100BT1 0x0000 /* Select 100BASE-T1 */ +#define MDIO_PMA_PMD_BT1_CTRL_TYPE_SEL_1000BT1 0x0001 /* Select 1000BASE-T1 */ +#define MDIO_PMA_PMD_BT1_CTRL_TYPE_SEL_10BT1L 0x0002 /* Select 10BASE-T1L */ +#define MDIO_PMA_PMD_BT1_CTRL_TYPE_SEL_10BT1S 0x0003 /* Select 10BASE-T1S */ +#define MDIO_PMA_PMD_BT1_CTRL_TYPE_SEL_2P5GBT1 0x0004 /* Select 2.5GBASE-T1 */ +#define MDIO_PMA_PMD_BT1_CTRL_TYPE_SEL_5GBT1 0x0005 /* Select 5GBASE-T1 */ +#define MDIO_PMA_PMD_BT1_CTRL_TYPE_SEL_10GBT1 0x0006 /* Select 10GBASE-T1 */ +/* Legacy names, kept for userspace */ +#define MDIO_PMA_PMD_BT1_CTRL_STRAP MDIO_PMA_PMD_BT1_CTRL_TYPE_SEL +#define MDIO_PMA_PMD_BT1_CTRL_STRAP_B1000 MDIO_PMA_PMD_BT1_CTRL_TYPE_SEL_1000BT1 #define MDIO_PMA_PMD_BT1_CTRL_CFG_MST 0x4000 /* MASTER-SLAVE config value */ /* 1000BASE-T1 PCS control register */ diff --git a/include/uapi/linux/nl80211.h b/include/uapi/linux/nl80211.h index b56a96f57bec..dae8fb894a79 100644 --- a/include/uapi/linux/nl80211.h +++ b/include/uapi/linux/nl80211.h @@ -6,7 +6,7 @@ * Copyright 2006-2010 Johannes Berg <johannes@sipsolutions.net> * Copyright 2008 Michael Wu <flamingice@sourmilk.net> * Copyright 2008 Luis Carlos Cobo <luisca@cozybit.com> - * Copyright 2008 Michael Buesch <m@bues.ch> + * Copyright 2008 Michael Buesch * Copyright 2008, 2009 Luis R. Rodriguez <lrodriguez@atheros.com> * Copyright 2008 Jouni Malinen <jouni.malinen@atheros.com> * Copyright 2008 Colin McCabe <colin@cozybit.com> diff --git a/include/vdso/unaligned.h b/include/vdso/unaligned.h index 9076483c9fbb..726fd15efc82 100644 --- a/include/vdso/unaligned.h +++ b/include/vdso/unaligned.h @@ -4,6 +4,20 @@ #include <linux/compiler_types.h> +#ifdef CONFIG_VDSO_UNALIGNED_PACKED + +#define __get_unaligned_t(type, ptr) ({ \ + const struct { type x; } __packed * __get_pptr = (typeof(__get_pptr))(ptr); \ + __get_pptr->x; \ +}) + +#define __put_unaligned_t(type, val, ptr) do { \ + struct { type x; } __packed * __put_pptr = (typeof(__put_pptr))(ptr); \ + __put_pptr->x = (val); \ +} while (0) + +#else /* !CONFIG_VDSO_UNALIGNED_PACKED */ + /** * __get_unaligned_t - read an unaligned value from memory. * @type: the type to load from the pointer. @@ -41,4 +55,6 @@ sizeof(__put_unaligned_val)); \ } while (0) +#endif /* CONFIG_VDSO_UNALIGNED_PACKED */ + #endif /* __VDSO_UNALIGNED_H */ diff --git a/init/Kconfig b/init/Kconfig index 4013781e0a02..c8a7cfa60a6e 100644 --- a/init/Kconfig +++ b/init/Kconfig @@ -884,6 +884,7 @@ config MEMCG select EVENTFD select SLAB_OBJ_EXT select VM_EVENT_COUNTERS + select BLK_CGROUP if BLOCK help Provides control over the memory footprint of tasks in a cgroup. diff --git a/init/do_mounts_rd.c b/init/do_mounts_rd.c index 48bfab2fc62f..448a734a0f62 100644 --- a/init/do_mounts_rd.c +++ b/init/do_mounts_rd.c @@ -258,6 +258,11 @@ done: fput(in_file); noclose_input: fput(out_file); + /* + * The image only reaches the ramdisk when the deferred __fput() + * syncs the block device. Flush it before mount_root() reads it. + */ + init_flush_fput(); out: kfree(buf); init_unlink("/dev/ram"); diff --git a/io_uring/io_uring.h b/io_uring/io_uring.h index a0ed03fab123..c8592f4ef510 100644 --- a/io_uring/io_uring.h +++ b/io_uring/io_uring.h @@ -140,6 +140,7 @@ struct io_wait_queue { #ifdef CONFIG_NET_RX_BUSY_POLL ktime_t napi_busy_poll_dt; + ktime_t napi_busy_poll_end; bool napi_prefer_busy_poll; #endif }; diff --git a/io_uring/napi.c b/io_uring/napi.c index d299c89cfc3d..0724c608777d 100644 --- a/io_uring/napi.c +++ b/io_uring/napi.c @@ -128,19 +128,15 @@ static inline void io_napi_remove_stale(struct io_ring_ctx *ctx, bool is_stale) __io_napi_remove_stale(ctx); } -static inline bool io_napi_busy_loop_timeout(ktime_t start_time, - ktime_t bp) +static inline bool io_napi_busy_loop_timeout(struct io_wait_queue *iowq) { - if (bp) { - ktime_t end_time = ktime_add(start_time, bp); - ktime_t now = net_to_ktime(busy_loop_current_time()); - - return ktime_after(now, end_time); - } - - return true; + if (!iowq->napi_busy_poll_dt) + return true; + return ktime_after(net_to_ktime(busy_loop_current_time()), + iowq->napi_busy_poll_end); } +/* Uses an absolute deadline, so the napi loop can be re-entered */ static bool io_napi_busy_loop_should_end(void *data, unsigned long start_time) { @@ -150,8 +146,7 @@ static bool io_napi_busy_loop_should_end(void *data, return true; if (io_should_wake(iowq) || io_has_work(iowq->ctx)) return true; - if (io_napi_busy_loop_timeout(net_to_ktime(start_time), - iowq->napi_busy_poll_dt)) + if (io_napi_busy_loop_timeout(iowq)) return true; return false; @@ -209,13 +204,16 @@ __io_napi_do_busy_loop(struct io_ring_ctx *ctx, static void io_napi_blocking_busy_loop(struct io_ring_ctx *ctx, struct io_wait_queue *iowq) { - unsigned long start_time = busy_loop_current_time(); + ktime_t now = net_to_ktime(busy_loop_current_time()); bool (*loop_end)(void *, unsigned long) = NULL; void *loop_end_arg = NULL; bool is_stale = false; - /* Singular lists use a different napi loop end check function and are - * only executed once. + iowq->napi_busy_poll_end = ktime_add(now, iowq->napi_busy_poll_dt); + + /* + * A single NAPI is held by __napi_busy_loop() for the whole spin. It + * may return early on need_resched(), loop until our own deadline. */ if (list_is_singular(&ctx->napi_list)) { loop_end = io_napi_busy_loop_should_end; @@ -226,8 +224,7 @@ static void io_napi_blocking_busy_loop(struct io_ring_ctx *ctx, do { is_stale = __io_napi_do_busy_loop(ctx, loop_end, loop_end_arg); - } while (!io_napi_busy_loop_should_end(iowq, start_time) && - !loop_end_arg); + } while (!io_napi_busy_loop_should_end(iowq, 0)); } io_napi_remove_stale(ctx, is_stale); diff --git a/ipc/namespace.c b/ipc/namespace.c index b54d23fd83d7..69a7c94d51dc 100644 --- a/ipc/namespace.c +++ b/ipc/namespace.c @@ -66,7 +66,6 @@ static struct ipc_namespace *create_ipc_ns(struct user_namespace *user_ns, if (err) goto fail_free; - ns_tree_gen_id(ns); ns->user_ns = get_user_ns(user_ns); ns->ucounts = ucounts; @@ -87,7 +86,7 @@ static struct ipc_namespace *create_ipc_ns(struct user_namespace *user_ns, sem_init_ns(ns); shm_init_ns(ns); - ns_tree_add_raw(ns); + ns_tree_add(ns); return ns; diff --git a/kernel/bpf/bpf_lsm.c b/kernel/bpf/bpf_lsm.c index f58dce888ff4..468e63dbd922 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_namespace_init) +BTF_ID(func, bpf_lsm_namespace_free) #ifdef CONFIG_SECURITY_NETWORK BTF_ID(func, bpf_lsm_sk_alloc_security) BTF_ID(func, bpf_lsm_sk_free_security) diff --git a/kernel/cgroup/cgroup.c b/kernel/cgroup/cgroup.c index a284225f8dc9..b3657e72db99 100644 --- a/kernel/cgroup/cgroup.c +++ b/kernel/cgroup/cgroup.c @@ -4806,19 +4806,21 @@ void cgroup_file_notify(struct cgroup_file *cfile) if (!READ_ONCE(cfile->kn)) return; - last = READ_ONCE(cfile->notified_at); - next = last + CGROUP_FILE_NOTIFY_MIN_INTV; - if (time_in_range(jiffies, last, next)) { - timer_reduce(&cfile->notify_timer, next); - if (timer_pending(&cfile->notify_timer)) - return; - } + if (timer_pending(&cfile->notify_timer)) + return; spin_lock_irqsave(&cfile->lock, flags); if (cfile->kn) { - kn = cfile->kn; - kernfs_get(kn); - WRITE_ONCE(cfile->notified_at, jiffies); + last = cfile->notified_at; + next = last + CGROUP_FILE_NOTIFY_MIN_INTV; + + if (time_in_range(jiffies, last, next)) { + timer_reduce(&cfile->notify_timer, next); + } else { + kn = cfile->kn; + kernfs_get(kn); + cfile->notified_at = jiffies; + } } spin_unlock_irqrestore(&cfile->lock, flags); diff --git a/kernel/cgroup/cpuset.c b/kernel/cgroup/cpuset.c index 3219f927c35e..db32d330cfbc 100644 --- a/kernel/cgroup/cpuset.c +++ b/kernel/cgroup/cpuset.c @@ -1244,17 +1244,17 @@ static bool isolated_cpu_update(int new_prs, int cpu) } /* - * isolated_cpus_update - Update the isolated_cpus mask - * @old_prs: old partition_root_state - * @new_prs: new partition_root_state - * @xcpus: exclusive CPUs with state change + * isolated_cpus_update - Set the isolation state of @xcpus + * @new_prs: partition root state that @xcpus will belong to + * @xcpus: exclusive CPUs whose isolation state may change + * + * CPUs isolated at boot time are kept isolated. */ -static void isolated_cpus_update(int old_prs, int new_prs, struct cpumask *xcpus) +static void isolated_cpus_update(int new_prs, struct cpumask *xcpus) { bool updated = false; int cpu; - WARN_ON_ONCE(old_prs == new_prs); lockdep_assert_held(&callback_lock); lockdep_assert_held(&cpuset_mutex); for_each_cpu(cpu, xcpus) @@ -1264,45 +1264,6 @@ static void isolated_cpus_update(int old_prs, int new_prs, struct cpumask *xcpus } /* - * isolated_cpus_release - Remove the relevant CPUs in @xcpus from isolated_cpus - * @cs: the current cpuset - * @xcpus: the set of effective xcpus to be considered for removal - * - * This function is called when an isolated partition is invalidated or when - * some of its effective xcpus are to be removed from isolated_cpus due to - * changes in parent cpuset. The given @xcpus must be modifiable as the function - * will update its value to determine the right set of CPUs to be removed. - */ -static void isolated_cpus_release(struct cpuset *cs, struct cpumask *xcpus) -{ - struct cpuset *ancestor = parent_cs(cs); - struct cpuset *iancestor = NULL; - - /* - * Search the furthest isolated partition root ancestor available - * until top_cpuset or a remote partition root is hit. - */ - for (; ancestor; ancestor = parent_cs(ancestor)) { - if (ancestor->partition_root_state == PRS_ISOLATED) - iancestor = ancestor; - if (is_remote_partition(ancestor)) - break; - } - - /* - * If a furthest isolated partition acnestor is found, use it to - * determine which of the CPUs in @xcpus should be removed from - * isolated_cpus. Otherwise, all of them will be removed. - */ - if (iancestor && !cpumask_andnot(xcpus, xcpus, iancestor->effective_xcpus)) - return; /* No CPU should be removed from isolated_cpus */ - - spin_lock_irq(&callback_lock); - isolated_cpus_update(PRS_ISOLATED, PRS_ROOT, xcpus); - spin_unlock_irq(&callback_lock); -} - -/* * partition_xcpus_add - Add new exclusive CPUs to partition * @new_prs: new partition_root_state * @parent: parent cpuset @@ -1315,16 +1276,17 @@ static void partition_xcpus_add(int new_prs, struct cpuset *parent, { WARN_ON_ONCE(new_prs < 0); lockdep_assert_held(&callback_lock); + + if (cpumask_empty(xcpus)) + return; + if (!parent) parent = &top_cpuset; - if (parent == &top_cpuset) cpumask_or(subpartitions_cpus, subpartitions_cpus, xcpus); - if (new_prs != parent->partition_root_state) - isolated_cpus_update(parent->partition_root_state, new_prs, - xcpus); + isolated_cpus_update(new_prs, xcpus); cpumask_andnot(parent->effective_cpus, parent->effective_cpus, xcpus); } @@ -1342,15 +1304,18 @@ static void partition_xcpus_del(int old_prs, struct cpuset *parent, { WARN_ON_ONCE(old_prs < 0); lockdep_assert_held(&callback_lock); + + if (cpumask_empty(xcpus)) + return; + if (!parent) parent = &top_cpuset; if (parent == &top_cpuset) cpumask_andnot(subpartitions_cpus, subpartitions_cpus, xcpus); - if (old_prs != parent->partition_root_state) - isolated_cpus_update(old_prs, parent->partition_root_state, - xcpus); + /* CPUs given back, including those of descendants, take parent's state */ + isolated_cpus_update(parent->partition_root_state, xcpus); cpumask_or(parent->effective_cpus, parent->effective_cpus, xcpus); cpumask_and(parent->effective_cpus, parent->effective_cpus, cpu_active_mask); @@ -1449,6 +1414,48 @@ out: return res; } +/** + * validate_partition - Validate a cpuset partition configuration + * @cs: The cpuset to validate + * @parent: Parent partition of @cs, NULL for remote partition + * @new_prs: The proposed new partition root state + * @new_excpus: The new effective exclusive CPUs mask to validate + * @del: exclusive CPUs to be deleted from @cs, can be NULL + * + * A remote partition gets its CPUs from top_cpuset, so top_cpuset is used + * as the parent when @parent is NULL. + * + * The housekeeping check is skipped if @parent is not a valid partition + * root as @cs can't be a valid local partition in that case. + * + * Return: PRS error code (0 if valid, non-zero error code if invalid) + */ +static enum prs_errcode validate_partition(struct cpuset *cs, + struct cpuset *parent, int new_prs, + struct cpumask *new_excpus, + struct cpumask *del) +{ + int parent_prs; + + if (new_prs == PRS_MEMBER) + return PERR_NONE; + + if (cpumask_empty(new_excpus)) + return PERR_INVCPUS; + + if (!parent) + parent = &top_cpuset; + parent_prs = parent->partition_root_state; + if (parent_prs > 0 && + prstate_housekeeping_conflict(new_prs, parent_prs, new_excpus, del)) + return PERR_HKEEPING; + + if (tasks_nocpu_error(parent, cs, new_excpus)) + return PERR_NOCPUS; + + return PERR_NONE; +} + /* * cpuset_update_sd_hk_unlock - Rebuild sched domains, update HK & unlock * @@ -1605,6 +1612,7 @@ static void compute_partition_effective_cpumask(struct cpuset *cs, struct cgroup_subsys_state *css; struct cpuset *child; bool populated = partition_is_populated(cs, NULL); + static cpumask_t xcpus; /* Protected by cpuset_mutex */ /* * Check child partition roots to see if they should be invalidated @@ -1633,14 +1641,15 @@ static void compute_partition_effective_cpumask(struct cpuset *cs, int parent_prs = cs->partition_root_state; /* - * Invalidate child partition and update isolated_cpus - * if necessary. + * Invalidate child partition. Its CPUs still owned by + * cs take the isolation state of cs. effective_xcpus + * of cs may not be updated yet, so recompute it. */ spin_lock_irq(&callback_lock); WRITE_ONCE(child->prs_err, PERR_NOCPUS); - if ((old_prs == PRS_ISOLATED) && (parent_prs == PRS_ROOT)) - isolated_cpus_update(PRS_ISOLATED, PRS_ROOT, - child->effective_xcpus); + compute_excpus(cs, &xcpus); + cpumask_and(&xcpus, &xcpus, child->effective_xcpus); + isolated_cpus_update(parent_prs, &xcpus); child->partition_root_state = -old_prs; spin_unlock_irq(&callback_lock); notify_partition_change(child, old_prs); @@ -1824,7 +1833,6 @@ static void remote_cpus_update(struct cpuset *cs, struct cpumask *xcpus, * left in the top cpuset. */ if (adding) { - WARN_ON_ONCE(cpumask_intersects(tmp->addmask, subpartitions_cpus)); if (!capable(CAP_SYS_ADMIN)) WRITE_ONCE(cs->prs_err, PERR_ACCESS); else if (cpumask_intersects(tmp->addmask, subpartitions_cpus) || @@ -1967,18 +1975,10 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd, if ((cmd == partcmd_enable) || (cmd == partcmd_enablei)) { new_prs = (cmd == partcmd_enable) ? PRS_ROOT : PRS_ISOLATED; - /* - * Enabling partition root is not allowed if its - * effective_xcpus is empty. - */ - if (cpumask_empty(tmp->delmask)) - return PERR_INVCPUS; - - if (prstate_housekeeping_conflict(new_prs, parent_prs, tmp->delmask, NULL)) - return PERR_HKEEPING; - - if (nocpu) - return PERR_NOCPUS; + part_error = validate_partition(cs, parent, new_prs, + tmp->delmask, NULL); + if (part_error) + return part_error; /* * This function will only be called when all the preliminary @@ -2083,21 +2083,8 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd, * * A partition error happens when parent has tasks and all * its effective CPUs will have to be distributed out. - * - * For an isolated partition with a shrunk root partition parent - * we may need to return some or all of its isolated CPUs. */ nocpu |= cpumask_empty(tmp->delmask); - if ((parent_prs == PRS_ROOT) && (old_prs == PRS_ISOLATED)) { - cpumask_clear(tmp->addmask); - if (nocpu) - cpumask_copy(tmp->addmask, cs->effective_xcpus); - else if (!cpumask_subset(cs->effective_xcpus, parent->effective_xcpus)) - cpumask_andnot(tmp->addmask, cs->effective_xcpus, - parent->effective_xcpus); - if (!cpumask_empty(tmp->addmask)) - isolated_cpus_release(cs, tmp->addmask); - } if (nocpu) { part_error = PERR_NOCPUS; if (is_partition_valid(cs)) @@ -2106,11 +2093,34 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd, parent->effective_xcpus); } else if ((parent_prs == PRS_ISOLATED) && ((old_prs == PRS_ROOT) || (old_prs == -PRS_ROOT))) { + /* Parent partition state changed to PRS_ISOLATED */ part_error = PERR_ISOPARENT; if (old_prs == PRS_ROOT) { cpumask_copy(tmp->addmask, cs->effective_xcpus); adding = true; } + } else if (is_partition_valid(cs) && + !cpumask_equal(tmp->delmask, cs->effective_xcpus)) { + /* + * If there is an expansion of parent's effective_xcpus, + * we may take more xcpus from parent. The parent's + * effective_cpus should still have active CPUs or nocpu + * should have been set. We also need to do a + * housekeeping check for an isolated child with root + * parent to make sure that it won't exhaust all the + * active housekeeping CPUs. + */ + cpumask_andnot(tmp->addmask, cs->effective_xcpus, tmp->delmask); + if ((parent_prs == PRS_ROOT) && (old_prs == PRS_ISOLATED) && + prstate_housekeeping_conflict(old_prs, parent_prs, + tmp->delmask, tmp->addmask)) { + adding = cpumask_and(tmp->addmask, cs->effective_xcpus, + tmp->delmask); + part_error = PERR_HKEEPING; + } else { + deleting = cpumask_andnot(tmp->delmask, tmp->delmask, + cs->effective_xcpus); + } } else if (is_partition_invalid(cs)) { struct cgroup_subsys_state *css; struct cpuset *child; @@ -2143,12 +2153,6 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd, else part_error = PERR_NOTEXCL; } - /* - * When both cs and parent remain valid, parent's - * compute_partition_effective_cpumask() call would have removed - * cs's effective_xcpus from the parent's effective_cpus. So - * there is no need to adjust parent's effective_cpus here. - */ } write_error: @@ -2320,18 +2324,12 @@ update_parent_effective: /* * When parent is not a valid partition root, * child partition roots become invalid too. - * - * For a to be invalidated isolated partition, - * call return_isolated_cpus() to remove the - * relevant CPUs from isolated_cpus. + * The isolation state of their CPUs has been + * settled when the parent gave them back. */ if (is_partition_valid(cp)) new_prs = -old_prs; - if (old_prs == PRS_ISOLATED) { - cpumask_copy(tmp->delmask, cp->effective_xcpus); - isolated_cpus_release(cp, tmp->delmask); - } WRITE_ONCE(cp->prs_err, is_partition_invalid(parent) ? PERR_INVPARENT : PERR_NOTPART); @@ -2347,12 +2345,12 @@ get_css: update_parent_effective_cpumask(cp, partcmd_update, NULL, tmp); /* * Capture current partition_root_state as it may have - * changed. Recompute effective cpumask if changed. + * changed. Always recompute effective cpumask as tmp->new_cpus + * may be clobbered when update_sibling_cpumasks() is called + * within update_parent_effective_cpumask(). */ new_prs = cp->partition_root_state; - if (new_prs != old_prs) { - compute_effective_cpumask(tmp->new_cpus, cp, parent); - } + compute_effective_cpumask(tmp->new_cpus, cp, parent); } spin_lock_irq(&callback_lock); @@ -2464,32 +2462,6 @@ static int parse_cpuset_cpulist(const char *buf, struct cpumask *out_mask) } /** - * validate_partition - Validate a cpuset partition configuration - * @cs: The cpuset to validate - * @trialcs: The trial cpuset containing proposed configuration changes - * - * If any validation check fails, the appropriate error code is set in the - * cpuset's prs_err field. - * - * Return: PRS error code (0 if valid, non-zero error code if invalid) - */ -static enum prs_errcode validate_partition(struct cpuset *cs, struct cpuset *trialcs) -{ - struct cpuset *parent = parent_cs(cs); - - if (cs_is_member(trialcs)) - return PERR_NONE; - - if (cpumask_empty(trialcs->effective_xcpus)) - return PERR_INVCPUS; - - if (tasks_nocpu_error(parent, cs, trialcs->effective_xcpus)) - return PERR_NOCPUS; - - return PERR_NONE; -} - -/** * partition_cpus_change - Handle partition state changes due to CPU mask updates * @cs: The target cpuset being modified * @trialcs: The trial cpuset containing proposed configuration changes @@ -2502,33 +2474,24 @@ static void partition_cpus_change(struct cpuset *cs, struct cpuset *trialcs, struct tmpmasks *tmp) { enum prs_errcode prs_err; - int parent_prs = is_remote_partition(cs) - ? PRS_ROOT : parent_cs(cs)->partition_root_state; + struct cpuset *parent = is_remote_partition(cs) ? NULL : parent_cs(cs); if (cs_is_member(cs)) return; - prs_err = validate_partition(cs, trialcs); - if (!prs_err && (parent_prs > 0) && - !cpumask_empty(trialcs->effective_xcpus)) { - int prs = cs->partition_root_state; - - /* - * Check for housekeeping conflict by passing the whole - * effective_xcpus as well as those CPUs that are to be - * removed from cs as delmask. - */ - if (prs > 0) - cpumask_andnot(tmp->delmask, cs->effective_xcpus, - trialcs->effective_xcpus); - else - cpumask_clear(tmp->delmask); - - if (prstate_housekeeping_conflict(prs, parent_prs, - trialcs->effective_xcpus, tmp->delmask)) - prs_err = PERR_HKEEPING; - } + /* + * Check for housekeeping conflict by passing the whole + * effective_xcpus as well as those CPUs that are to be + * removed from cs as delmask. + */ + if (is_partition_valid(cs)) + cpumask_andnot(tmp->delmask, cs->effective_xcpus, + trialcs->effective_xcpus); + else + cpumask_clear(tmp->delmask); + prs_err = validate_partition(cs, parent, trialcs->partition_root_state, + trialcs->effective_xcpus, tmp->delmask); if (prs_err) { WRITE_ONCE(cs->prs_err, prs_err); trialcs->prs_err = prs_err; @@ -2593,8 +2556,11 @@ static int update_cpumask(struct cpuset *cs, struct cpuset *trialcs, spin_lock_irq(&callback_lock); cpumask_copy(cs->cpus_allowed, trialcs->cpus_allowed); cpumask_copy(cs->effective_xcpus, trialcs->effective_xcpus); - if ((old_prs > 0) && !is_partition_valid(cs)) + if (old_prs && !is_partition_valid(cs)) { reset_partition_data(cs); + /* effective_xcpus may be cleared, update the subtree too */ + force = true; + } spin_unlock_irq(&callback_lock); /* effective_cpus/effective_xcpus will be updated here */ @@ -2658,8 +2624,11 @@ static int update_exclusive_cpumask(struct cpuset *cs, struct cpuset *trialcs, spin_lock_irq(&callback_lock); cpumask_copy(cs->exclusive_cpus, trialcs->exclusive_cpus); cpumask_copy(cs->effective_xcpus, trialcs->effective_xcpus); - if ((old_prs > 0) && !is_partition_valid(cs)) + if (old_prs && !is_partition_valid(cs)) { reset_partition_data(cs); + /* effective_xcpus may be cleared, update the subtree too */ + force = true; + } spin_unlock_irq(&callback_lock); /* @@ -3042,12 +3011,32 @@ static int update_prstate(struct cpuset *cs, int new_prs) cs->effective_xcpus, NULL)) err = PERR_HKEEPING; else if (parent_prs == PRS_ISOLATED) - err = PERR_ISOPARENT; + err = PERR_ISOPARENT; /* old_prs should be isolated */ - if (!err) - isolcpus_updated = true; - else + if (err) { disable_partition = true; + } else { + struct cgroup_subsys_state *css; + struct cpuset *child; + + /* + * Need to scan child partitions, if present, and + * exclude their effective_xcpus from cs. In the case + * of switching to isolated partition with child root + * partitions, those child partitions will be + * invalidated in update_cpumasks_hier(). + */ + isolcpus_updated = true; + cpumask_copy(tmpmask.new_cpus, cs->effective_xcpus); + rcu_read_lock(); + cpuset_for_each_child(child, css, cs) { + if (!is_partition_valid(child)) + continue; + cpumask_andnot(tmpmask.new_cpus, tmpmask.new_cpus, + child->effective_xcpus); + } + rcu_read_unlock(); + } } else { /* * Switching back to member is always allowed even if it @@ -3081,7 +3070,7 @@ out: if (!is_partition_valid(cs)) reset_partition_data(cs); else if (isolcpus_updated) - isolated_cpus_update(old_prs, new_prs, cs->effective_xcpus); + isolated_cpus_update(new_prs, tmpmask.new_cpus); spin_unlock_irq(&callback_lock); /* Force update if partition is disabled & update effective_xcpus */ @@ -3856,11 +3845,20 @@ static void cpuset_fork(struct task_struct *task) rcu_read_unlock(); if (cs == oldcs) { + unsigned int seq; + if (cs == &top_cpuset) return; set_cpus_allowed_ptr(task, current->cpus_ptr); - task->mems_allowed = current->mems_allowed; + /* + * A cpuset.mems update can update current->mems_allowed + * concurrently, so retry it again if it really happens. + */ + do { + seq = read_mems_allowed_begin(); + task->mems_allowed = current->mems_allowed; + } while (read_mems_allowed_retry(seq)); return; } @@ -4017,10 +4015,10 @@ static void cpuset_hotplug_update_tasks(struct cpuset *cs, struct tmpmasks *tmp) partcmd = partcmd_invalidate; /* * On the other hand, an invalid partition root may be transitioned - * back to a regular one with a non-empty effective xcpus. + * back to a regular one if its effective xcpus has an active CPU. */ else if (is_partition_valid(parent) && is_partition_invalid(cs) && - !cpumask_empty(cs->effective_xcpus)) + cpumask_intersects(cs->effective_xcpus, cpu_active_mask)) partcmd = partcmd_update; if (partcmd >= 0) { diff --git a/kernel/cgroup/legacy_freezer.c b/kernel/cgroup/legacy_freezer.c index 8545e0d1ba3d..1792523d119a 100644 --- a/kernel/cgroup/legacy_freezer.c +++ b/kernel/cgroup/legacy_freezer.c @@ -265,7 +265,7 @@ static void update_if_frozen(struct cgroup_subsys_state *css) rcu_read_unlock(); /* are all tasks frozen? */ - css_task_iter_start(css, 0, &it); + css_task_iter_start(css, CSS_TASK_ITER_WITH_DEAD, &it); while ((task = css_task_iter_next(&it))) { if (freezing(task) && !frozen(task)) @@ -309,7 +309,7 @@ static void freeze_cgroup(struct freezer *freezer) struct css_task_iter it; struct task_struct *task; - css_task_iter_start(&freezer->css, 0, &it); + css_task_iter_start(&freezer->css, CSS_TASK_ITER_WITH_DEAD, &it); while ((task = css_task_iter_next(&it))) freeze_task(task); css_task_iter_end(&it); @@ -320,7 +320,7 @@ static void unfreeze_cgroup(struct freezer *freezer) struct css_task_iter it; struct task_struct *task; - css_task_iter_start(&freezer->css, 0, &it); + css_task_iter_start(&freezer->css, CSS_TASK_ITER_WITH_DEAD, &it); while ((task = css_task_iter_next(&it))) __thaw_task(task); css_task_iter_end(&it); @@ -382,6 +382,24 @@ static void freezer_change_state(struct freezer *freezer, bool freeze) * CGROUP_FREEZING_PARENT. */ mutex_lock(&freezer_mutex); + + /* + * A dead cgroup must not be frozen. + * + * rmdir thaws the cgroup from freezer_css_killed(), but freezer.state + * stays writable until rmdir removes it a moment later. A FROZEN write + * in that gap would freeze the cgroup again, and nothing could thaw it + * after that. + * + * A freezer.state write doesn't take cgroup_mutex, but testing + * cgroup_is_dead() without it is safe. rmdir marks the cgroup dead + * before the thaw, so a write that takes freezer_mutex after the thaw + * sees it dead. One that takes it before the thaw may still see the + * cgroup alive, but the thaw then undoes its freeze. + */ + if (freeze && data_race(cgroup_is_dead(freezer->css.cgroup))) + goto out_unlock; + rcu_read_lock(); css_for_each_descendant_pre(pos, &freezer->css) { struct freezer *pos_f = css_freezer(pos); @@ -403,10 +421,25 @@ static void freezer_change_state(struct freezer *freezer, bool freeze) css_put(pos); } rcu_read_unlock(); +out_unlock: mutex_unlock(&freezer_mutex); cpus_read_unlock(); } +/** + * freezer_css_killed - Thaw a freezer cgroup being removed + * @css: css being killed + * + * Exiting tasks hidden from cgroup.procs can still be in the cgroup when it is + * removed, and a frozen one has nothing left to thaw it once freezer.state is + * gone. Thaw the cgroup as a THAWED write to it would. A frozen ancestor keeps + * the tasks frozen through CGROUP_FREEZING_PARENT until the ancestor is thawed. + */ +static void freezer_css_killed(struct cgroup_subsys_state *css) +{ + freezer_change_state(css_freezer(css), false); +} + static ssize_t freezer_write(struct kernfs_open_file *of, char *buf, size_t nbytes, loff_t off) { @@ -466,6 +499,7 @@ static struct cftype files[] = { struct cgroup_subsys freezer_cgrp_subsys = { .css_alloc = freezer_css_alloc, .css_online = freezer_css_online, + .css_killed = freezer_css_killed, .css_offline = freezer_css_offline, .css_free = freezer_css_free, .attach = freezer_attach, diff --git a/kernel/events/core.c b/kernel/events/core.c index f5f2261f1fe6..e870f12c3ad8 100644 --- a/kernel/events/core.c +++ b/kernel/events/core.c @@ -1072,8 +1072,13 @@ static void perf_cgroup_switch(struct task_struct *task) * must not be done before ctxswout due * to update_cgrp_time_from_cpuctx() in * ctx_sched_out() + * + * ctx_sched_out() can consume a pending disable and drop the last cgroup + * event, which clear the cpuctx->cgrp. Cgroup tracking follow active cgroup + * event, so do not resurrect it */ - cpuctx->cgrp = cgrp; + if (cpuctx->ctx.nr_cgroups) + cpuctx->cgrp = cgrp; /* * set cgrp before ctxsw in to allow * perf_cgroup_set_timestamp() in ctx_sched_in() @@ -1332,14 +1337,19 @@ static int perf_mux_hrtimer_restart(struct perf_cpu_pmu_context *cpc) return 0; } -static int perf_mux_hrtimer_restart_ipi(void *arg) +static __always_inline struct perf_cpu_pmu_context *this_cpc(struct pmu *pmu) { - return perf_mux_hrtimer_restart(arg); + return *this_cpu_ptr(pmu->cpu_pmu_context); } -static __always_inline struct perf_cpu_pmu_context *this_cpc(struct pmu *pmu) +static int perf_mux_hrtimer_interval_ipi(void *arg) { - return *this_cpu_ptr(pmu->cpu_pmu_context); + struct pmu *pmu = arg; + struct perf_cpu_pmu_context *cpc = this_cpc(pmu); + int ms = pmu->hrtimer_interval_ms; + + cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * ms); + return perf_mux_hrtimer_restart(cpc); } void perf_pmu_disable(struct pmu *pmu) @@ -12780,13 +12790,8 @@ perf_event_mux_interval_ms_store(struct device *dev, /* update all cpuctx for this PMU */ cpus_read_lock(); - for_each_online_cpu(cpu) { - struct perf_cpu_pmu_context *cpc; - cpc = *per_cpu_ptr(pmu->cpu_pmu_context, cpu); - cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer); - - cpu_function_call(cpu, perf_mux_hrtimer_restart_ipi, cpc); - } + for_each_online_cpu(cpu) + cpu_function_call(cpu, perf_mux_hrtimer_interval_ipi, pmu); cpus_read_unlock(); mutex_unlock(&mux_interval_mutex); diff --git a/kernel/events/hw_breakpoint.c b/kernel/events/hw_breakpoint.c index 789add0c185a..7a606213f33d 100644 --- a/kernel/events/hw_breakpoint.c +++ b/kernel/events/hw_breakpoint.c @@ -968,8 +968,7 @@ static int hw_breakpoint_event_init(struct perf_event *bp) static int hw_breakpoint_add(struct perf_event *bp, int flags) { - if (!(flags & PERF_EF_START)) - bp->hw.state = PERF_HES_STOPPED; + bp->hw.state = (flags & PERF_EF_START) ? 0 : PERF_HES_STOPPED; if (is_sampling_event(bp)) { bp->hw.last_period = bp->hw.sample_period; diff --git a/kernel/kprobes.c b/kernel/kprobes.c index 2441b9e39343..f14f7ff45961 100644 --- a/kernel/kprobes.c +++ b/kernel/kprobes.c @@ -552,17 +552,13 @@ static unsigned long optimizer_passes; #define OPTIMIZE_DELAY 5 -/* - * Note: gen->cooling_list is not checked here because it is strictly - * an in-flight holding list for dispatched generations, so it is always - * empty in optprobe_cur_gen. - */ static bool optprobe_has_queued_probes(void) { struct optprobe_generation *gen = &optprobe_gens[optprobe_cur_gen]; return !list_empty(&gen->optimizing_list) || !list_empty(&gen->unoptimizing_list) || + !list_empty(&gen->cooling_list) || !list_empty(&gen->freeing_list); } @@ -612,6 +608,7 @@ static void do_unoptimize_kprobes(struct list_head *unopt_list, struct list_head *cooling_list) { struct optimized_kprobe *op, *tmp; + LIST_HEAD(unoptimized); lockdep_assert_held(&text_mutex); /* @@ -626,15 +623,21 @@ static void do_unoptimize_kprobes(struct list_head *unopt_list, */ lockdep_assert_cpus_held(); - if (!list_empty(unopt_list)) - arch_unoptimize_kprobes(unopt_list, free_list); + if (list_empty(unopt_list)) + return; - /* Loop on 'free_list' for disarming and removing from kprobe hash list */ - list_for_each_entry_safe(op, tmp, free_list, list) { + arch_unoptimize_kprobes(unopt_list, &unoptimized); + + /* Loop on newly unoptimized probes for disarming and hash list removal */ + list_for_each_entry_safe(op, tmp, &unoptimized, list) { /* Switching from detour code to origin */ op->kp.flags &= ~KPROBE_FLAG_OPTIMIZED; - /* Disarm probes if marked disabled and not gone */ - if (kprobe_disabled(&op->kp) && !kprobe_gone(&op->kp)) + /* + * Disarm probes if marked disabled and not gone. Unhashed probes + * were disarmed before they were unhashed. + */ + if (kprobe_disabled(&op->kp) && !kprobe_gone(&op->kp) && + !hlist_unhashed(&op->kp.hlist)) arch_disarm_kprobe(&op->kp); if (kprobe_unused(&op->kp)) { /* @@ -643,6 +646,7 @@ static void do_unoptimize_kprobes(struct list_head *unopt_list, * (reclaiming is done by do_free_cleaned_kprobes().) */ hlist_del_init_rcu(&op->kp.hlist); + list_move(&op->list, free_list); } else { /* * Keep on cooling_list until the quiescence period @@ -725,10 +729,17 @@ static void optprobe_finalize_generation(struct optprobe_generation *gen) list_move(&op->list, &optprobe_gens[optprobe_cur_gen].freeing_list); kick_kprobe_optimizer(); } else { + struct kprobe *_p; + /* Still in use; now safely disarmed */ list_del_init(&op->list); - if (!kprobe_disabled(&op->kp)) + if (!kprobe_disabled(&op->kp)) { optimize_kprobe(&op->kp); + } else { + _p = get_optimized_kprobe(op->kp.addr); + if (unlikely(_p)) + optimize_kprobe(_p); + } } } @@ -1002,9 +1013,10 @@ static void unoptimize_kprobe(struct kprobe *p, bool force) * for cooling down (or freeing if unused). */ force_unoptimize_kprobe(op); + /* Disarm probes if marked disabled and not gone */ + if (kprobe_disabled(&op->kp) && !kprobe_gone(&op->kp)) + arch_disarm_kprobe(&op->kp); if (kprobe_unused(&op->kp)) { - if (!kprobe_gone(&op->kp)) - arch_disarm_kprobe(&op->kp); hlist_del_init_rcu(&op->kp.hlist); list_move(&op->list, &cur->freeing_list); } else { @@ -1039,10 +1051,11 @@ static void unoptimize_kprobe(struct kprobe *p, bool force) if (force) { /* Forcibly update the code: this is a special case */ force_unoptimize_kprobe(op); + list_add(&op->list, &cur->cooling_list); } else { list_add(&op->list, &cur->unoptimizing_list); - kick_kprobe_optimizer(); } + kick_kprobe_optimizer(); } /* Cancel unoptimizing for reusing */ @@ -1056,6 +1069,10 @@ static int reuse_unused_kprobe(struct kprobe *ap) */ op = container_of(ap, struct optimized_kprobe, kp); WARN_ON_ONCE(list_empty(&op->list)); + /* Already disarmed, the caller arms it only for an enabled probe */ + if (optprobe_queued_cooling(op)) + return 0; + /* Enable the probe again */ ap->flags &= ~KPROBE_FLAG_DISABLED; /* Optimize it again. (remove from 'op->list') */ @@ -1253,6 +1270,19 @@ static void __init kprobe_sysctls_init(void) } #endif /* CONFIG_SYSCTL */ +/* Return true if the probe is queued on unoptimizing lists */ +static bool kprobe_queued_unopt(struct kprobe *p) +{ + struct optimized_kprobe *op; + + if (kprobe_aggrprobe(p)) { + op = container_of(p, struct optimized_kprobe, kp); + if (optprobe_queued_unopt(op)) + return true; + } + return false; +} + /* Put a breakpoint for a probe. */ static void __arm_kprobe(struct kprobe *p) { @@ -1266,21 +1296,11 @@ static void __arm_kprobe(struct kprobe *p) /* Fallback to unoptimized kprobe */ unoptimize_kprobe(_p, true); - arch_arm_kprobe(p); + if (!kprobe_queued_unopt(p)) + arch_arm_kprobe(p); optimize_kprobe(p); /* Try to optimize (add kprobe to a list) */ -} - -/* Return true if the probe is queued on unoptimizing lists */ -static bool kprobe_queued_unopt(struct kprobe *p) -{ - struct optimized_kprobe *op; - - if (kprobe_aggrprobe(p)) { - op = container_of(p, struct optimized_kprobe, kp); - if (optprobe_queued_unopt(op)) - return true; - } - return false; + if (unlikely(kprobe_queued_unopt(p))) + unoptimize_kprobe(p, true); } /* Remove the breakpoint of a probe. */ @@ -1435,9 +1455,14 @@ static int __disarm_kprobe_ftrace(struct kprobe *p, struct ftrace_ops *ops, (*cnt)--; ret = ftrace_set_filter_ip(ops, (unsigned long)p->addr, 1, 0); - WARN_ONCE(ret < 0, "Failed to disarm kprobe-ftrace at %pS (error %d)\n", - p->addr, ret); - return ret; + if (WARN_ONCE(ret < 0, "Failed to disarm kprobe-ftrace at %pS (error %d)\n", + p->addr, ret)) { + if (*cnt == 0) + register_ftrace_function(ops); + (*cnt)++; + return ret; + } + return 0; } static int disarm_kprobe_ftrace(struct kprobe *p) @@ -1566,16 +1591,13 @@ void kprobe_busy_end(void) } /* Add the new probe to 'ap->list'. */ -static int add_new_kprobe(struct kprobe *ap, struct kprobe *p) +static void add_new_kprobe(struct kprobe *ap, struct kprobe *p) { - if (p->post_handler) + /* A reused cooling probe is already unoptimized */ + if (p->post_handler && !kprobe_unused(ap)) unoptimize_kprobe(ap, true); /* Fall back to normal kprobe */ list_add_rcu(&p->list, &ap->list); - if (p->post_handler && !ap->post_handler) - ap->post_handler = aggr_post_handler; - - return 0; } /* @@ -1608,6 +1630,8 @@ static int register_aggr_kprobe(struct kprobe *orig_p, struct kprobe *p) { int ret = 0; struct kprobe *ap = orig_p; + bool reset_post_handler = false; + bool ftrace_switch_ops = false; scoped_guard(cpus_read_lock) { /* For preparing optimization, jump_label_text_reserved() is called */ @@ -1654,18 +1678,50 @@ static int register_aggr_kprobe(struct kprobe *orig_p, struct kprobe *p) | KPROBE_FLAG_DISABLED; } + if (p->post_handler && !ap->post_handler) { + reset_post_handler = true; + if (kprobe_ftrace(ap) && !kprobes_all_disarmed && + !kprobe_disabled(ap)) + ftrace_switch_ops = true; + else + ap->post_handler = aggr_post_handler; + } + /* Copy the insn slot of 'p' to 'ap'. */ copy_kprobe(ap, p); - ret = add_new_kprobe(ap, p); + if (!ftrace_switch_ops) + add_new_kprobe(ap, p); + } + + if (ftrace_switch_ops) { + /* + * Must switch ftrace ops outside of text_mutex and cpus_read_lock + * to prevent deadlocks when ftrace code modification acquires text_mutex. + */ + ret = disarm_kprobe_ftrace(ap); + if (ret) + return ret; + + ap->post_handler = aggr_post_handler; + ret = arm_kprobe_ftrace(ap); + if (ret) { + ap->post_handler = NULL; + if (arm_kprobe_ftrace(ap)) + ap->flags |= KPROBE_FLAG_DISABLED; + return ret; + } + add_new_kprobe(ap, p); } - if (ret == 0 && kprobe_disabled(ap) && !kprobe_disabled(p)) { + if (kprobe_disabled(ap) && !kprobe_disabled(p)) { ap->flags &= ~KPROBE_FLAG_DISABLED; if (!kprobes_all_disarmed) { /* Arm the breakpoint again. */ ret = arm_kprobe(ap); if (ret) { ap->flags |= KPROBE_FLAG_DISABLED; + if (reset_post_handler) + ap->post_handler = NULL; list_del_rcu(&p->list); synchronize_rcu(); } @@ -1793,52 +1849,61 @@ _kprobe_addr(kprobe_opcode_t *addr, const char *symbol_name, return addr; } -static kprobe_opcode_t *kprobe_addr(struct kprobe *p) -{ - bool on_func_entry; - - return _kprobe_addr(p->addr, p->symbol_name, p->offset, &on_func_entry); -} - /* * Check the 'p' is valid and return the aggregator kprobe * at the same address. */ -static struct kprobe *__get_valid_kprobe(struct kprobe *p) +static struct kprobe *__get_valid_kprobe_at(struct kprobe *p, kprobe_opcode_t *addr) { + struct hlist_head *head; struct kprobe *ap, *list_p; lockdep_assert_held(&kprobe_mutex); - ap = get_kprobe(p->addr); - if (unlikely(!ap)) + if (unlikely(!addr)) return NULL; - if (p == ap) - return ap; - - list_for_each_entry(list_p, &ap->list, list) - if (list_p == p) - /* kprobe p is a valid probe */ + head = &kprobe_table[hash_ptr(addr, KPROBE_HASH_BITS)]; + hlist_for_each_entry_rcu(ap, head, hlist, + lockdep_is_held(&kprobe_mutex)) { + if (ap == p) { + p->addr = addr; return ap; + } + if (ap->addr == addr && kprobe_aggrprobe(ap)) { + list_for_each_entry(list_p, &ap->list, list) { + if (list_p == p) { + p->addr = addr; + return ap; + } + } + } + } return NULL; } -/* - * Warn and return error if the kprobe is being re-registered since - * there must be a software bug. - */ -static inline int warn_kprobe_rereg(struct kprobe *p) +static inline struct kprobe *__get_valid_kprobe(struct kprobe *p) +{ + return __get_valid_kprobe_at(p, p->addr); +} + +/* Return error if the kprobe is being re-registered */ +static inline int check_kprobe_rereg_at(struct kprobe *p, kprobe_opcode_t *addr) { guard(mutex)(&kprobe_mutex); - if (WARN_ON_ONCE(__get_valid_kprobe(p))) + if (__get_valid_kprobe_at(p, addr)) return -EINVAL; return 0; } +static inline int check_kprobe_rereg(struct kprobe *p) +{ + return check_kprobe_rereg_at(p, p->addr); +} + static int check_ftrace_location(struct kprobe *p) { unsigned long addr = (unsigned long)p->addr; @@ -1946,6 +2011,8 @@ static int __register_kprobe(struct kprobe *p) if (ret) { hlist_del_rcu(&p->hlist); synchronize_rcu(); + arch_remove_kprobe(p); + return ret; } } @@ -1967,7 +2034,7 @@ int register_kprobe(struct kprobe *p) return PTR_ERR(addr); p->addr = addr; - ret = warn_kprobe_rereg(p); + ret = check_kprobe_rereg(p); if (ret) return ret; @@ -2503,20 +2570,19 @@ int register_kretprobe(struct kretprobe *rp) int ret; int i; void *addr; + bool on_func_entry; - ret = kprobe_on_func_entry(rp->kp.addr, rp->kp.symbol_name, rp->kp.offset); - if (ret) - return ret; + addr = _kprobe_addr(rp->kp.addr, rp->kp.symbol_name, rp->kp.offset, &on_func_entry); + if (IS_ERR(addr)) + return PTR_ERR(addr); - /* If only 'rp->kp.addr' is specified, check reregistering kprobes */ - if (rp->kp.addr && warn_kprobe_rereg(&rp->kp)) + if (!on_func_entry) return -EINVAL; - if (kretprobe_blacklist_size) { - addr = kprobe_addr(&rp->kp); - if (IS_ERR(addr)) - return PTR_ERR(addr); + if (check_kprobe_rereg_at(&rp->kp, addr)) + return -EINVAL; + if (kretprobe_blacklist_size) { for (i = 0; kretprobe_blacklist[i].name != NULL; i++) { if (kretprobe_blacklist[i].addr == addr) return -EINVAL; @@ -2603,8 +2669,10 @@ void unregister_kretprobes(struct kretprobe **rps, int num) for (i = 0; i < num; i++) { guard(mutex)(&kprobe_mutex); - if (__unregister_kprobe_top(&rps[i]->kp) < 0) + if (__unregister_kprobe_top(&rps[i]->kp) < 0) { rps[i]->kp.addr = NULL; + continue; + } #ifdef CONFIG_KRETPROBE_ON_RETHOOK rethook_free(rps[i]->rh); #else @@ -2616,7 +2684,9 @@ void unregister_kretprobes(struct kretprobe **rps, int num) for (i = 0; i < num; i++) { if (rps[i]->kp.addr) { __unregister_kprobe_bottom(&rps[i]->kp); -#ifndef CONFIG_KRETPROBE_ON_RETHOOK +#ifdef CONFIG_KRETPROBE_ON_RETHOOK + rps[i]->rh = NULL; +#else free_rp_inst(rps[i]); #endif } diff --git a/kernel/liveupdate/kexec_handover.c b/kernel/liveupdate/kexec_handover.c index 6f1f55fe3181..42c6609a1766 100644 --- a/kernel/liveupdate/kexec_handover.c +++ b/kernel/liveupdate/kexec_handover.c @@ -1643,7 +1643,7 @@ EXPORT_SYMBOL_GPL(kho_restore_free); */ bool is_kho_boot(void) { - return !!kho_get_fdt(); + return !!kho_in.fdt_phys; } EXPORT_SYMBOL_GPL(is_kho_boot); diff --git a/kernel/liveupdate/luo_session.c b/kernel/liveupdate/luo_session.c index f48e9a4185f9..74bc66929f4b 100644 --- a/kernel/liveupdate/luo_session.c +++ b/kernel/liveupdate/luo_session.c @@ -177,16 +177,6 @@ static int luo_session_insert(struct luo_session_header *sh, guard(rwsem_write)(&sh->rwsem); /* - * For outgoing we should make sure there is room in serialization array - * for new session. - */ - if (sh == &luo_session_global.outgoing) { - err = kho_block_set_grow(&sh->block_set, sh->count + 1); - if (err) - return err; - } - - /* * For small number of sessions this loop won't hurt performance * but if we ever start using a lot of sessions, this might * become a bottle neck during deserialization time, as it would @@ -196,6 +186,17 @@ static int luo_session_insert(struct luo_session_header *sh, if (!strncmp(it->name, session->name, sizeof(it->name))) return -EEXIST; } + + /* + * For outgoing we should make sure there is room in serialization array + * for new session. + */ + if (sh == &luo_session_global.outgoing) { + err = kho_block_set_grow(&sh->block_set, sh->count + 1); + if (err) + return err; + } + list_add_tail(&session->list, &sh->list); sh->count++; diff --git a/kernel/nscommon.c b/kernel/nscommon.c index e72426bba29a..4438c6b663f9 100644 --- a/kernel/nscommon.c +++ b/kernel/nscommon.c @@ -54,7 +54,8 @@ static void ns_debug(struct ns_common *ns, const struct proc_ns_operations *ops) } #endif -int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_operations *ops, int inum) +int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_operations *ops, + int inum, u64 ns_id) { int ret = 0; @@ -64,7 +65,6 @@ int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_ope ns->ns_security = NULL; #endif ns->ops = ops; - ns->ns_id = 0; ns->ns_type = ns_type; ns_tree_node_init(&ns->ns_tree_node); ns_tree_node_init(&ns->ns_unified_node); @@ -82,6 +82,9 @@ int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_ope if (ret) return ret; + /* Allocate the id before the LSM hook so it can track the namespace by it. */ + __ns_tree_gen_id(ns, ns_id); + ret = security_namespace_init(ns); if (ret) { if (!inum) diff --git a/kernel/nstree.c b/kernel/nstree.c index a756ae2e7881..44e07d0fa8e5 100644 --- a/kernel/nstree.c +++ b/kernel/nstree.c @@ -194,7 +194,7 @@ static int ns_cmp_owner(struct rb_node *a, const struct rb_node *b) return ns_id_cmp(node_to_ns_owner(a)->ns_id, node_to_ns_owner(b)->ns_id); } -void __ns_tree_add_raw(struct ns_common *ns, struct ns_tree_root *ns_tree) +void __ns_tree_add(struct ns_common *ns, struct ns_tree_root *ns_tree) { struct rb_node *node; const struct proc_ns_operations *ops = ns->ops; diff --git a/kernel/rcu/tasks.h b/kernel/rcu/tasks.h index fcac7361ec51..743f777b4c18 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 b6cfee4e5039..8448a7c578e8 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 1a088d4576f5..5ed660f099a5 100644 --- a/kernel/sched/core.c +++ b/kernel/sched/core.c @@ -6297,7 +6297,6 @@ pick_next_task(struct rq *rq, struct rq_flags *rf) __must_hold(__rq_lockp(rq)) { struct task_struct *next, *p, *max; - const struct cpumask *smt_mask; bool fi_before = false; bool core_clock_updated = (rq == rq->core); unsigned long cookie; @@ -6344,8 +6343,6 @@ pick_next_task(struct rq *rq, struct rq_flags *rf) prev_balance(rq, rf); - smt_mask = cpu_smt_mask(cpu); - restart: need_sync |= !!rq->core->core_cookie; @@ -6413,7 +6410,7 @@ restart: * Tie-break prio towards the current CPU */ max = NULL; - for_each_cpu_wrap(i, smt_mask, cpu) { + for_each_core_cpu_wrap(i, rq) { rq_i = cpu_rq(i); /* @@ -6446,7 +6443,7 @@ restart: * For each thread: try and find a runnable task that matches @max or * force idle. */ - for_each_cpu(i, smt_mask) { + for_each_core_cpu(i, rq) { rq_i = cpu_rq(i); p = rq_i->core_pick; @@ -6491,7 +6488,7 @@ restart: * their task. This ensures there is no inter-sibling overlap between * non-matching user state. */ - for_each_cpu(i, smt_mask) { + for_each_core_cpu(i, rq) { rq_i = cpu_rq(i); /* diff --git a/kernel/sched/core_sched.c b/kernel/sched/core_sched.c index 43e0bde3038e..d56be1c31435 100644 --- a/kernel/sched/core_sched.c +++ b/kernel/sched/core_sched.c @@ -241,7 +241,6 @@ out: /* REQUIRES: rq->core's clock recently updated. */ void __sched_core_account_forceidle(struct rq *rq) { - const struct cpumask *smt_mask = cpu_smt_mask(cpu_of(rq)); u64 delta, now = rq_clock(rq->core); struct rq *rq_i; struct task_struct *p; @@ -273,7 +272,7 @@ void __sched_core_account_forceidle(struct rq *rq) delta = div_u64(delta, rq->core->core_forceidle_occupation); } - for_each_cpu(i, smt_mask) { + for_each_core_cpu(i, rq) { rq_i = cpu_rq(i); p = rq_i->core_pick ?: rq_i->curr; diff --git a/kernel/sched/ext/cid.c b/kernel/sched/ext/cid.c index 8e04a8494e11..0cc397055f57 100644 --- a/kernel/sched/ext/cid.c +++ b/kernel/sched/ext/cid.c @@ -64,7 +64,13 @@ static void calc_shard_layout(const struct cpumask *llc_cpus, u32 shard_size, for_each_cpu(cpu, llc_cpus) { nr_cpus++; - if (cpumask_first(topology_sibling_cpumask(cpu)) == cpu) + /* + * scx_cid_init() forms each core from the siblings in + * @llc_cpus. The sibling mask may include cpus outside + * @llc_cpus, so count a core at its first sibling in @llc_cpus. + */ + if (cpumask_first_and(topology_sibling_cpumask(cpu), + llc_cpus) == cpu) nr_cores++; } diff --git a/kernel/sched/ext/ext.c b/kernel/sched/ext/ext.c index f74ffb3b1aca..10de6bd865e8 100644 --- a/kernel/sched/ext/ext.c +++ b/kernel/sched/ext/ext.c @@ -462,6 +462,14 @@ static bool rq_is_open(struct rq *rq, u64 enq_flags) */ /* + * A local insertion can raise next_class to ext while the donor is + * still idle. Keep the rq open so that the local DSQ head is not + * unnecessarily reenqueued before the CPU can pick it. + */ + if (rq->donor == rq->idle) + return true; + + /* * If we're in the dispatch path holding rq lock, $donor may or may not * be ready depending on whether the on-going dispatch decides to extend * $donor's slice. We say yes here and resolve it at the end of dispatch. @@ -580,12 +588,14 @@ enum scx_dsq_iter_flags { /* iterate in the reverse dispatch order */ SCX_DSQ_ITER_REV = 1U << 16, + __SCX_DSQ_ITER_DRAINED = 1U << 28, __SCX_DSQ_ITER_HAS_REENQ = 1U << 29, __SCX_DSQ_ITER_HAS_SLICE = 1U << 30, __SCX_DSQ_ITER_HAS_VTIME = 1U << 31, __SCX_DSQ_ITER_USER_FLAGS = SCX_DSQ_ITER_REV, __SCX_DSQ_ITER_ALL_FLAGS = __SCX_DSQ_ITER_USER_FLAGS | + __SCX_DSQ_ITER_DRAINED | __SCX_DSQ_ITER_HAS_REENQ | __SCX_DSQ_ITER_HAS_SLICE | __SCX_DSQ_ITER_HAS_VTIME, @@ -2225,11 +2235,11 @@ static void direct_dispatch(struct scx_sched *sch, struct task_struct *p, bool scx_rq_online(struct rq *rq) { /* - * Test both cpu_active() and %SCX_RQ_ONLINE. %SCX_RQ_ONLINE follows the - * core's rq online state. cpu_active() test guarantees that, if this - * function returns %true, %SCX_RQ_ONLINE will stay set until the - * current scheduling operation is complete even if we aren't locking - * @rq. + * Test both cpu_active() and %SCX_RQ_ONLINE. %SCX_RQ_ONLINE is set + * after the root's ops.cpu_online() and cleared when the cpu goes down. + * cpu_active() test guarantees that, if this function returns %true, + * %SCX_RQ_ONLINE will stay set until the current scheduling operation + * is complete even if we aren't locking @rq. */ return likely((rq->scx.flags & SCX_RQ_ONLINE) && cpu_active(cpu_of(rq))); } @@ -2420,7 +2430,7 @@ static void set_task_runnable(struct rq *rq, struct task_struct *p) } /* - * list_add_tail() must be used. scx_bypass() and rq_offline_scx() + * list_add_tail() must be used. scx_bypass() and drain_offline_rq() * depend on tasks being appended to the runnable_list. */ list_add_tail(&p->scx.runnable_node, &rq->scx.runnable_list); @@ -3399,6 +3409,12 @@ static enum scx_dsp_verdict dispatch_one(struct rq *rq, struct task_struct *prev rq->scx.cpu_released = false; } + /* the ecaps sync may have dropped the rq lock */ + if (scx_dsp_prev_stale(rq, prev)) { + verdict = SCX_DSP_RETRY; + goto has_tasks; + } + if (prev->sched_class == &ext_sched_class) { update_curr_scx(rq); @@ -3441,6 +3457,10 @@ static enum scx_dsp_verdict dispatch_one(struct rq *rq, struct task_struct *prev } verdict = scx_dispatch_sched(root_sch, rq, prev, false); + + /* scx_dispatch_sched() may have dropped the rq lock */ + if (scx_dsp_prev_stale(rq, prev)) + verdict = SCX_DSP_RETRY; if (verdict != SCX_DSP_NONE) goto has_tasks; @@ -4296,12 +4316,37 @@ static void set_cpus_allowed_scx(struct task_struct *p, scx_call_op_set_cpumask(sch, task_rq(p), p, (struct cpumask *)p->cpus_ptr); } +static void drain_offline_rq(struct rq *rq) +{ + struct task_struct *p, *n; + + scx_rescue_flush(rq); + + /* + * An offline CPU no longer calls ops.dispatch(). Re-enqueue its tasks + * onto the local DSQ so that they run here and balance_push() moves + * them off. + */ + list_for_each_entry_safe_reverse(p, n, &rq->scx.runnable_list, scx.runnable_node) { + if (p->scx.dsq == &rq->scx.local_dsq) + continue; + guard(sched_change)(p, DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK); + } +} + static void handle_hotplug(struct rq *rq, bool online) { struct scx_sched *sch = scx_root_protected(); s32 cpu = cpu_of(rq); s32 cpu_or_cid = cpu; + if (!online) { + guard(rq_lock_irqsave)(rq); + update_rq_clock(rq); + rq->scx.flags &= ~SCX_RQ_ONLINE; + drain_offline_rq(rq); + } + atomic_long_inc(&scx_hotplug_seq); scx_update_frozen_cpus(cpu, online); @@ -4310,8 +4355,14 @@ static void handle_hotplug(struct rq *rq, bool online) * stable here. Note that we can't depend on scx_enabled() test as the * hotplug ops need to be enabled before __scx_enabled is set. */ - if (unlikely(!sch)) + if (unlikely(!sch)) { + /* no root to notify, set %SCX_RQ_ONLINE right away */ + if (online) { + guard(rq_lock_irqsave)(rq); + rq->scx.flags |= SCX_RQ_ONLINE; + } return; + } if (scx_enabled()) scx_idle_update_selcpu_topology(&sch->ops); @@ -4362,8 +4413,22 @@ static void handle_hotplug(struct rq *rq, bool online) "cpu %d going %s, exiting scheduler", cpu, online ? "online" : "offline"); - if (online) + if (online) { + /* + * The cpu must not call ops.enqueue() or ops.dispatch() before + * the root's ops.cpu_online(). The core's rq online state can't + * gate them, as the sched domain rebuild in + * sched_cpu_activate() can put @rq online before this function + * runs. Set %SCX_RQ_ONLINE here. + * + * scx_online_ecaps() queues a reseed whose ecaps ops run in + * dispatch context on the cpu and can insert into its local + * DSQ. Set the flag first. + */ + scoped_guard (rq_lock_irqsave, rq) + rq->scx.flags |= SCX_RQ_ONLINE; scx_online_ecaps(rq); + } } void scx_rq_activate(struct rq *rq) @@ -4376,35 +4441,6 @@ void scx_rq_deactivate(struct rq *rq) handle_hotplug(rq, false); } -static void rq_online_scx(struct rq *rq) -{ - rq->scx.flags |= SCX_RQ_ONLINE; -} - -static void rq_offline_scx(struct rq *rq) -{ - struct task_struct *p, *n; - - rq->scx.flags &= ~SCX_RQ_ONLINE; - - /* sched domain rebuilds call rq_offline with the CPU staying alive */ - if (cpu_active(cpu_of(rq))) - return; - - scx_rescue_flush(rq); - - /* - * An offline CPU no longer calls ops.dispatch(). Re-enqueue its tasks - * onto the local DSQ so that they run here and balance_push() moves - * them off. - */ - list_for_each_entry_safe_reverse(p, n, &rq->scx.runnable_list, scx.runnable_node) { - if (p->scx.dsq == &rq->scx.local_dsq) - continue; - guard(sched_change)(p, DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK); - } -} - static bool check_rq_for_timeouts(struct rq *rq) { struct scx_sched *sch; @@ -4728,6 +4764,7 @@ void __scx_disable_and_exit_task(struct scx_sched *sch, struct task_struct *p) args.cancelled = true; break; case SCX_TASK_READY: + scx_reset_task_fields(task_rq(p), p); break; case SCX_TASK_ENABLED: scx_disable_task(sch, p); @@ -5876,9 +5913,6 @@ DEFINE_SCHED_CLASS(ext) = { .task_woken = task_woken_scx, .set_cpus_allowed = set_cpus_allowed_scx, - .rq_online = rq_online_scx, - .rq_offline = rq_offline_scx, - .task_tick = task_tick_scx, .switching_to = switching_to_scx, @@ -7779,10 +7813,17 @@ void scx_flush_disable_work(struct scx_sched *sch) { int kind; + /* + * scx_disable_workfn() sets SCX_EXIT_DONE before tearing down. Read + * exit_kind with acquire ordering (paired with atomic_try_cmpxchg() in + * scx_disable_workfn()) before syncing and flushing so that, once DONE + * is seen, the following flush observes the queued work and waits for + * the teardown to finish. + */ do { + kind = atomic_read_acquire(&sch->exit_kind); irq_work_sync(&sch->disable_irq_work); kthread_flush_work(&sch->disable_work); - kind = atomic_read(&sch->exit_kind); } while (kind != SCX_EXIT_NONE && kind != SCX_EXIT_DONE); } @@ -11028,13 +11069,24 @@ __bpf_kfunc int bpf_iter_scx_dsq_new(struct bpf_iter_scx_dsq *it, u64 dsq_id, __bpf_kfunc struct task_struct *bpf_iter_scx_dsq_next(struct bpf_iter_scx_dsq *it) { struct bpf_iter_scx_dsq_kern *kit = (void *)it; + struct task_struct *p; - if (!kit->dsq) + if (!kit->dsq || (kit->cursor.flags & __SCX_DSQ_ITER_DRAINED)) return NULL; guard(raw_spinlock_irqsave)(&kit->dsq->lock); - return nldsq_cursor_next_task(&kit->cursor, kit->dsq); + p = nldsq_cursor_next_task(&kit->cursor, kit->dsq); + /* + * nldsq_cursor_next_task() unlinks the cursor and starts from the DSQ + * head when it is called again. The verifier relies on an iterator + * which returned NULL to keep returning NULL (see + * process_iter_next_call()), so remember the drained state. + */ + if (!p) + kit->cursor.flags |= __SCX_DSQ_ITER_DRAINED; + + return p; } /** @@ -11107,7 +11159,7 @@ __bpf_kfunc struct task_struct *scx_bpf_dsq_peek(u64 dsq_id, /** * scx_bpf_dsq_reenq - Re-enqueue tasks on a DSQ * @dsq_id: DSQ to re-enqueue - * @reenq_flags: %SCX_RENQ_* + * @reenq_flags: %SCX_REENQ_* * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs * * Iterate over all of the tasks currently enqueued on the DSQ identified by @@ -11117,8 +11169,9 @@ __bpf_kfunc struct task_struct *scx_bpf_dsq_peek(u64 dsq_id, * - Local DSQs (%SCX_DSQ_LOCAL or %SCX_DSQ_LOCAL_ON | $cpu) * - User DSQs * - * Re-enqueues are performed asynchronously. Can be called from anywhere. A - * re-enqueue of an inactive cpu's local DSQ is ignored. + * Re-enqueues are performed asynchronously. Can be called from any context + * except NMI. A call from NMI aborts the scheduler. A re-enqueue of an inactive + * cpu's local DSQ is ignored. * * %SCX_DSQ_LOCAL resolves to the local DSQ of the rq the current scheduler * operation is locked to - e.g. the rq being dispatched for in ops.dispatch() - @@ -11215,9 +11268,10 @@ __bpf_kfunc bool scx_bpf_dsq_reenq_task(struct bpf_iter_scx_dsq *it__iter, * scx_bpf_reenqueue_local___v2 - Re-enqueue tasks on a local DSQ * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs * - * Iterate over all of the tasks currently enqueued on the local DSQ of the - * caller's CPU, and re-enqueue them in the BPF scheduler. Can be called from - * anywhere. + * Iterate over all of the tasks currently enqueued on the local DSQ of the rq + * the current scheduler operation is locked to, or the calling CPU's when no rq + * is locked, and re-enqueue them in the BPF scheduler. Can be called from any + * context except NMI. A call from NMI aborts the scheduler. * * This is now a special case of scx_bpf_dsq_reenq() and may be removed in the * future. @@ -12134,6 +12188,11 @@ static const struct btf_kfunc_id_set scx_kfunc_set_any = { * when scx_locked_rq() returns NULL. Taking it while the context already holds * an rq lock, the same one or another cpu's, can deadlock. * + * scx_bpf_destroy_dsq() takes a user DSQ lock. So do + * bpf_iter_scx_dsq_next() and bpf_iter_scx_dsq_destroy(), the latter only + * after a successful next() has linked the cursor. A tracing program can + * run while that lock is already held and recursively acquire it. + * * Before returning, scx_bpf_sub_grant() and scx_bpf_sub_revoke() invoke * ops.sub_caps_updated() of the sub-schedulers whose caps changed, so those ops * run in the tracing program's context. No SCX op expects to run from an @@ -12148,6 +12207,9 @@ BTF_ID_FLAGS(func, scx_bpf_cpuperf_set, KF_IMPLICIT_ARGS) BTF_ID_FLAGS(func, scx_bpf_cidperf_set, KF_IMPLICIT_ARGS) BTF_ID_FLAGS(func, scx_bpf_sub_grant, KF_IMPLICIT_ARGS) BTF_ID_FLAGS(func, scx_bpf_sub_revoke, KF_IMPLICIT_ARGS) +BTF_ID_FLAGS(func, scx_bpf_destroy_dsq, KF_IMPLICIT_ARGS) +BTF_ID_FLAGS(func, bpf_iter_scx_dsq_next, KF_ITER_NEXT | KF_RET_NULL) +BTF_ID_FLAGS(func, bpf_iter_scx_dsq_destroy, KF_ITER_DESTROY) BTF_KFUNCS_END(scx_kfunc_ids_no_tracing) /* diff --git a/kernel/sched/ext/inlines.h b/kernel/sched/ext/inlines.h index 1e39d12678c4..8de281a5c9c6 100644 --- a/kernel/sched/ext/inlines.h +++ b/kernel/sched/ext/inlines.h @@ -18,9 +18,32 @@ enum scx_dsp_verdict { SCX_DSP_NONE, /* nothing to run */ SCX_DSP_LOCAL, /* local DSQ has tasks */ SCX_DSP_PREV, /* keep running @prev */ - SCX_DSP_RETRY, /* pick helpers only: restart the pick */ + SCX_DSP_RETRY, /* restart the pick */ }; +/** + * scx_dsp_prev_stale - Test whether dispatch's @prev went stale + * @rq: rq being dispatched for + * @prev: @rq's donor when dispatch started + * + * @prev can stop being @rq's donor while dispatch has the rq lock dropped. With + * proxy execution, @prev may not be the running task, and another CPU can reset + * the donor to rq->curr. With core scheduling, the core pick runs dispatch for + * the sibling rqs too, and a sibling can switch @prev out. Dispatch restarts + * the pick when that happened and doesn't hand the old donor to the BPF + * scheduler. + * + * With proxy execution alone, the donor only ever changes to rq->curr during a + * pick. Only __schedule() on this CPU sets a different donor, after the pick, + * so the restarted pick takes rq->curr as @prev and can't go stale again. Under + * core scheduling, the restart goes through the core pick, which already + * retries whenever dispatch dropped the lock. + */ +static inline bool scx_dsp_prev_stale(struct rq *rq, struct task_struct *prev) +{ + return (sched_proxy_exec() || sched_core_enabled(rq)) && unlikely(prev != rq->donor); +} + /* * One user of this function is scx_bpf_sub_dispatch() which can be called * recursively as sub-sched dispatches nest. Always inline to reduce stack usage @@ -33,8 +56,7 @@ scx_dispatch_sched(struct scx_sched *sch, struct rq *rq, struct scx_dsp_ctx *dspc = &this_cpu_ptr(sch->pcpu)->dsp_ctx; int nr_loops = SCX_DSP_MAX_LOOPS; s32 cpu = cpu_of(rq); - bool prev_on_sch = (prev->sched_class == &ext_sched_class) && - scx_task_on_sched(sch, prev); + bool prev_on_sch; if (scx_consume_global_dsq(sch, rq)) return SCX_DSP_LOCAL; @@ -82,7 +104,7 @@ scx_dispatch_sched(struct scx_sched *sch, struct rq *rq, /* * scx_rq_online() can't be used. Its cpu_active() test goes false * before CPU hotplug waits for an RCU grace period, and - * rq_offline_scx() moves this CPU's tasks to the local DSQ only after + * handle_hotplug() moves this CPU's tasks to the local DSQ only after * the wait. The grace period can depend on those tasks running. */ if (unlikely(!SCX_HAS_OP(sch, dispatch)) || !(rq->scx.flags & SCX_RQ_ONLINE)) @@ -106,6 +128,11 @@ scx_dispatch_sched(struct scx_sched *sch, struct rq *rq, rq->scx.sub_dispatch_prev = prev; #endif + /* the dispatch so far may have dropped the rq lock */ + prev_on_sch = !scx_dsp_prev_stale(rq, prev) && + prev->sched_class == &ext_sched_class && + scx_task_on_sched(sch, prev); + SCX_CALL_OP(sch, dispatch, rq, scx_cpu_arg(cpu), prev_on_sch ? prev : NULL); @@ -116,7 +143,9 @@ scx_dispatch_sched(struct scx_sched *sch, struct rq *rq, scx_flush_dispatch_buf(sch, rq); - if ((prev->scx.flags & SCX_TASK_QUEUED) && prev->scx.slice) + /* ops.dispatch() and the flush may have dropped the rq lock */ + if (!scx_dsp_prev_stale(rq, prev) && + (prev->scx.flags & SCX_TASK_QUEUED) && prev->scx.slice) return SCX_DSP_PREV; if (rq->scx.local_dsq.nr) return SCX_DSP_LOCAL; diff --git a/kernel/sched/ext/internal.h b/kernel/sched/ext/internal.h index ff0a3d508533..58652370da5a 100644 --- a/kernel/sched/ext/internal.h +++ b/kernel/sched/ext/internal.h @@ -869,6 +869,10 @@ struct sched_ext_ops { * @sub_attach: Attach a sub-scheduler * @args: argument container, see the struct definition * + * The sub-scheduler's cgroup is online for the whole call. If it goes + * offline after the sub-scheduler is accepted, ops.sub_detach() + * follows. + * * Return 0 to accept the sub-scheduler. -errno to reject. */ s32 (*sub_attach)(struct scx_sub_attach_args *args); diff --git a/kernel/sched/ext/sub.c b/kernel/sched/ext/sub.c index b5d92d89629b..d2a20114eaa2 100644 --- a/kernel/sched/ext/sub.c +++ b/kernel/sched/ext/sub.c @@ -918,10 +918,11 @@ struct scx_dispatch_q *__scx_resolve_local_dsq(struct scx_sched *sch, struct rq return &rq->scx.local_dsq; /* - * The task must run on this CPU regardless of caps: the rq is draining - * offline (BPF scheduler bypassed), the task is migration-disabled, or a - * migration is pending. Admit despite the missing caps and count it. - * Refuse preemptions. + * The task must run on this CPU regardless of caps: ops.enqueue() is + * skipped while the CPU is going down or before the root's + * ops.cpu_online(), the task is migration-disabled, or a migration is + * pending. Admit despite the missing caps and count it. Refuse + * preemptions. */ if (unlikely(!scx_rq_online(rq) || is_migration_disabled(p) || p->migration_pending)) { @@ -2340,8 +2341,21 @@ void scx_sub_enable_workfn(struct kthread_work *work) .cgroup_path = sch->cgrp_path, }; + /* + * The cgroup stays online across ops.sub_attach(), so the parent never + * sees an attach for a cgroup that rmdir already removed. + */ + cgroup_lock(); + if (!(cgrp->self.flags & CSS_ONLINE)) { + cgroup_unlock(); + scx_error(sch, "cgroup is not online"); + ret = -ENODEV; + goto err_disable; + } ret = SCX_CALL_OP_RET(parent, sub_attach, NULL, &sub_attach_args); + cgroup_unlock(); + if (ret) { ret = scx_ops_sanitize_err(sch, "sub_attach", ret); scx_error(sch, "parent rejected (%d)", ret); diff --git a/kernel/sched/fair.c b/kernel/sched/fair.c index 79f6b3a4fd7f..0c8af1cac2d5 100644 --- a/kernel/sched/fair.c +++ b/kernel/sched/fair.c @@ -1469,6 +1469,12 @@ static bool exceed_llc_capacity(struct sched_cache_group *grp, int cpu) return false; } +/* Are the running threads (in SMT siblings) below ~80% of the LLC's CPUs? */ +static inline bool fits_llc_nr(u64 nr_threads, unsigned int nr_cpus) +{ + return nr_threads * 5 < (u64)nr_cpus * 4; +} + static bool invalid_llc_nr(struct sched_cache_group *grp, struct task_struct *p, int cpu) { @@ -1485,8 +1491,8 @@ static bool invalid_llc_nr(struct sched_cache_group *grp, struct task_struct *p, if (scale == INT_MAX) return false; - return !fits_capacity((READ_ONCE(grp->nr_running_avg) * cpu_smt_num_threads), - (scale * per_cpu(sd_llc_size, cpu))); + return !fits_llc_nr(READ_ONCE(grp->nr_running_avg) * cpu_smt_num_threads, + scale * per_cpu(sd_llc_size, cpu)); } /* diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h index 1d76950dbb0a..220927453a88 100644 --- a/kernel/sched/sched.h +++ b/kernel/sched/sched.h @@ -781,19 +781,20 @@ struct cfs_rq { /* scx_rq->flags, protected by the rq lock */ enum scx_rq_flags { /* - * Set while the core has the rq online, see rq_online_scx() and - * rq_offline_scx(). A hotplugged cpu starts scheduling before - * rq_online_scx(). ops.enqueue() and ops.dispatch() are called for the - * cpu only while it is set, see scx_rq_online() and - * scx_dispatch_sched(). + * Set right after the root's ops.cpu_online() when a cpu comes up and + * cleared when the cpu goes down, see handle_hotplug(). A hotplugged + * cpu starts scheduling before %SCX_RQ_ONLINE is set. ops.enqueue() and + * ops.dispatch() are called for the cpu only while the flag is set, see + * scx_rq_online() and scx_dispatch_sched(). */ SCX_RQ_ONLINE = 1 << 0, SCX_RQ_CAN_STOP_TICK = 1 << 1, /* * Set while the root considers the cpu online, from its * ops.cpu_online() until its ops.cpu_offline(). ecaps are delivered - * only while it is set. %SCX_RQ_ONLINE follows the core's rq state - * instead, which changes ahead of the root's view on both edges. + * only while it is set. %SCX_RQ_ONLINE can't gate them, as a cpu going + * down clears it before the ecaps loss is reported, see + * scx_offline_ecaps(). */ SCX_RQ_OPS_ONLINE = 1 << 2, SCX_RQ_CLK_VALID = 1 << 5, /* RQ clock is fresh and valid */ @@ -1534,6 +1535,25 @@ static inline raw_spinlock_t *__rq_lockp(struct rq *rq) return &rq->__lock; } +/* + * A CPU coming online is set in cpu_smt_mask() before + * sched_core_cpu_starting() links its rq->core to the core leader. + * Until then it does not share the core-wide lock, so it must not be + * touched as part of the core. + */ +static inline bool sched_core_sibling(struct rq *rq, struct rq *rq_i) +{ + return rq_i->core == rq->core; +} + +#define for_each_core_cpu(i, rq) \ + for_each_cpu(i, cpu_smt_mask(rq->cpu)) \ + if (sched_core_sibling(rq, cpu_rq(i))) + +#define for_each_core_cpu_wrap(i, rq) \ + for_each_cpu_wrap(i, cpu_smt_mask(rq->cpu), rq->cpu) \ + if (sched_core_sibling(rq, cpu_rq(i))) + extern bool cfs_prio_less(const struct task_struct *a, const struct task_struct *b, bool fi); @@ -4289,7 +4309,7 @@ extern void balance_callbacks(struct rq *rq, struct balance_callback *head); * Typically this must be called while holding task_rq_lock, since most/all * properties are serialized under those locks. There are currently two * exceptions to this rule in sched/ext which only hold rq->lock: scx_bypass() - * and rq_offline_scx(). + * and drain_offline_rq(). */ /* diff --git a/kernel/sched/syscalls.c b/kernel/sched/syscalls.c index 45a127deeadd..0ec401af80d1 100644 --- a/kernel/sched/syscalls.c +++ b/kernel/sched/syscalls.c @@ -318,8 +318,8 @@ static inline void __setscheduler_dl_pi(int newprio, int policy, static int uclamp_validate(struct task_struct *p, const struct sched_attr *attr) { - int util_min = p->uclamp_req[UCLAMP_MIN].value; - int util_max = p->uclamp_req[UCLAMP_MAX].value; + unsigned int util_min = p->uclamp_req[UCLAMP_MIN].value; + unsigned int util_max = p->uclamp_req[UCLAMP_MAX].value; if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MIN) { util_min = attr->sched_util_min; @@ -628,7 +628,7 @@ change: * the entire root_domain to become SCHED_DEADLINE. We * will also fail if there's no bandwidth available. */ - if (!cpumask_subset(span, p->cpus_ptr) || + if (!cpumask_subset(span, &p->cpus_mask) || rq->rd->dl_bw.bw == 0) { retval = -EPERM; goto unlock; @@ -640,8 +640,10 @@ change: if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) { policy = oldpolicy = -1; task_rq_unlock(rq, p, &rf); - if (cpuset_locked) + if (cpuset_locked) { cpuset_unlock(); + cpuset_locked = false; + } goto recheck; } diff --git a/kernel/time/timekeeping.c b/kernel/time/timekeeping.c index dcf47f1ffdcf..be72cfd2b1ca 100644 --- a/kernel/time/timekeeping.c +++ b/kernel/time/timekeeping.c @@ -1600,6 +1600,9 @@ int get_device_system_crosststamp(int (*get_time_fn) do { seq = read_seqcount_begin(&tkd->seq); + if (!tk->clock_valid) + return -ENODEV; + /* * Try to synchronously capture device time and a system * counter value calling back into the device driver @@ -1775,6 +1778,7 @@ static int __timekeeping_inject_offset(struct tk_data *tkd, const struct timespe struct tk_read_base *tkr_mono = &tks->tkr_mono; ktime_t now, offs; + tk_update_ktime_data(tks); /* Get the current time */ now = ktime_add_ns(tkr_mono->base, timekeeping_get_ns(tkr_mono)); /* Add the relative offset change */ @@ -2700,7 +2704,13 @@ void update_wall_time(void) void getboottime64(struct timespec64 *ts) { struct timekeeper *tk = &tk_core.timekeeper; - ktime_t t = ktime_sub(tk->offs_real, tk->offs_boot); + unsigned int seq; + ktime_t t; + + do { + seq = read_seqcount_begin(&tk_core.seq); + t = ktime_sub(tk->offs_real, tk->offs_boot); + } while (read_seqcount_retry(&tk_core.seq, seq)); *ts = ktime_to_timespec64(t); } diff --git a/kernel/trace/trace_eprobe.c b/kernel/trace/trace_eprobe.c index 998e6390937a..f65393fb1c10 100644 --- a/kernel/trace/trace_eprobe.c +++ b/kernel/trace/trace_eprobe.c @@ -94,14 +94,18 @@ static int eprobe_dyn_event_show(struct seq_file *m, struct dyn_event *ev) static int unregister_trace_eprobe(struct trace_eprobe *ep) { - /* If other probes are on the event, just unregister eprobe */ - if (trace_probe_has_sibling(&ep->tp)) - goto unreg; - /* Enabled event can not be unregistered */ if (trace_probe_is_enabled(&ep->tp)) return -EBUSY; + /* If there's a reference to the dynamic event */ + if (trace_event_dyn_busy(trace_probe_event_call(&ep->tp))) + return -EBUSY; + + /* If other probes are on the event, just unregister eprobe */ + if (trace_probe_has_sibling(&ep->tp)) + goto unreg; + /* Will fail if probe is being used by ftrace or perf */ if (trace_probe_unregister_event_call(&ep->tp)) return -EBUSY; @@ -330,21 +334,21 @@ get_event_field(struct fetch_insn *code, void *rec) switch (field->size) { case 1: if (field->is_signed) - val = *(char *)addr; + val = *(s8 *)addr; else - val = *(unsigned char *)addr; + val = *(u8 *)addr; break; case 2: if (field->is_signed) - val = *(short *)addr; + val = *(s16 *)addr; else - val = *(unsigned short *)addr; + val = *(u16 *)addr; break; case 4: if (field->is_signed) - val = *(int *)addr; + val = *(s32 *)addr; else - val = *(unsigned int *)addr; + val = *(u32 *)addr; break; default: if (field->size == sizeof(long)) { @@ -644,37 +648,32 @@ static int enable_trace_eprobe(struct trace_event_call *call, { struct trace_probe *tp; struct trace_eprobe *ep; - bool enabled; int ret = 0; int cnt = 0; + if (WARN_ON_ONCE(!file)) + return -EINVAL; + tp = trace_probe_primary_from_call(call); if (WARN_ON_ONCE(!tp)) return -ENODEV; - enabled = trace_probe_is_enabled(tp); /* This also changes "enabled" state */ - if (file) { - ret = trace_probe_add_file(tp, file); - if (ret) - return ret; - } else - trace_probe_set_flag(tp, TP_FLAG_PROFILE); - - if (enabled) - return 0; + ret = trace_probe_add_file(tp, file); + if (ret) + return ret; + /* The trigger lives in the instance of the file, add it for each file */ for_each_trace_eprobe_tp(ep, tp) { ret = enable_eprobe(ep, file); if (ret) break; - enabled = true; cnt++; } if (ret) { /* Failed to enable one of them. Roll back all */ - if (enabled) { + if (cnt) { /* * It's a bug if one failed for something other than memory * not being available but another eprobe succeeded. @@ -687,10 +686,7 @@ static int enable_trace_eprobe(struct trace_event_call *call, break; } } - if (file) - trace_probe_remove_file(tp, file); - else - trace_probe_clear_flag(tp, TP_FLAG_PROFILE); + trace_probe_remove_file(tp, file); } return ret; @@ -702,33 +698,21 @@ static int disable_trace_eprobe(struct trace_event_call *call, struct trace_probe *tp; struct trace_eprobe *ep; + if (WARN_ON_ONCE(!file)) + return -EINVAL; + tp = trace_probe_primary_from_call(call); if (WARN_ON_ONCE(!tp)) return -ENODEV; - if (file) { - if (!trace_probe_get_file_link(tp, file)) - return -ENOENT; - if (!trace_probe_has_single_file(tp)) - goto out; - trace_probe_clear_flag(tp, TP_FLAG_TRACE); - } else - trace_probe_clear_flag(tp, TP_FLAG_PROFILE); + if (!trace_probe_get_file_link(tp, file)) + return -ENOENT; - if (!trace_probe_is_enabled(tp)) { - for_each_trace_eprobe_tp(ep, tp) - disable_eprobe(ep, file->tr); - } + for_each_trace_eprobe_tp(ep, tp) + disable_eprobe(ep, file->tr); - out: - if (file) - /* - * Synchronization is done in below function. For perf event, - * file == NULL and perf_trace_event_unreg() calls - * tracepoint_synchronize_unregister() to ensure synchronize - * event. We don't need to care about it. - */ - trace_probe_remove_file(tp, file); + /* Synchronization is done in below function. */ + trace_probe_remove_file(tp, file); return 0; } @@ -778,7 +762,8 @@ find_and_get_event(const char *system, const char *event_name) (TRACE_EVENT_FL_IGNORE_ENABLE | TRACE_EVENT_FL_KPROBE | TRACE_EVENT_FL_UPROBE | - TRACE_EVENT_FL_EPROBE)) + TRACE_EVENT_FL_EPROBE | + TRACE_EVENT_FL_FPROBE)) continue; if (!tp_event->class->system || strcmp(system, tp_event->class->system)) diff --git a/kernel/trace/trace_event_perf.c b/kernel/trace/trace_event_perf.c index 5b272856e5ab..a549897ee408 100644 --- a/kernel/trace/trace_event_perf.c +++ b/kernel/trace/trace_event_perf.c @@ -354,8 +354,7 @@ int perf_trace_add(struct perf_event *p_event, int flags) struct trace_event_call *tp_event = p_event->tp_event; struct hw_perf_event *hwc = &p_event->hw; - if (!(flags & PERF_EF_START)) - p_event->hw.state = PERF_HES_STOPPED; + hwc->state = (flags & PERF_EF_START) ? 0 : PERF_HES_STOPPED; if (is_sampling_event(p_event)) { hwc->last_period = hwc->sample_period; diff --git a/kernel/trace/trace_fprobe.c b/kernel/trace/trace_fprobe.c index 4e9034ebc3fb..9ab0871a6461 100644 --- a/kernel/trace/trace_fprobe.c +++ b/kernel/trace/trace_fprobe.c @@ -853,10 +853,6 @@ static void __unregister_trace_fprobe(struct trace_fprobe *tf) /* Unregister a trace_probe and probe_event */ static int unregister_trace_fprobe(struct trace_fprobe *tf) { - /* If other probes are on the event, just unregister fprobe */ - if (trace_probe_has_sibling(&tf->tp)) - goto unreg; - /* Enabled event can not be unregistered */ if (trace_probe_is_enabled(&tf->tp)) return -EBUSY; @@ -865,6 +861,10 @@ static int unregister_trace_fprobe(struct trace_fprobe *tf) if (trace_event_dyn_busy(trace_probe_event_call(&tf->tp))) return -EBUSY; + /* If other probes are on the event, just unregister fprobe */ + if (trace_probe_has_sibling(&tf->tp)) + goto unreg; + /* Will fail if probe is being used by ftrace or perf */ if (unregister_fprobe_event(tf)) return -EBUSY; @@ -933,7 +933,10 @@ static int append_trace_fprobe_event(struct trace_fprobe *tf, struct trace_fprob if (ret) return ret; - ret = trace_fprobe_verify_target(tf); + if (trace_probe_is_enabled(&tf->tp)) + ret = __register_trace_fprobe(tf); + else + ret = trace_fprobe_verify_target(tf); if (ret) trace_probe_unlink(&tf->tp); else @@ -1520,13 +1523,8 @@ static int disable_trace_fprobe(struct trace_event_call *call, trace_probe_clear_flag(tp, TP_FLAG_PROFILE); if (!trace_probe_is_enabled(tp)) { - list_for_each_entry(tf, trace_probe_probe_list(tp), tp.list) { - unregister_fprobe(&tf->fp); - if (tf->tuser) { - tracepoint_user_put(tf->tuser); - tf->tuser = NULL; - } - } + list_for_each_entry(tf, trace_probe_probe_list(tp), tp.list) + __unregister_trace_fprobe(tf); } out: diff --git a/kernel/trace/trace_kprobe.c b/kernel/trace/trace_kprobe.c index e41a7c113646..1dd6a6942eb7 100644 --- a/kernel/trace/trace_kprobe.c +++ b/kernel/trace/trace_kprobe.c @@ -548,10 +548,6 @@ static void __unregister_trace_kprobe(struct trace_kprobe *tk) /* Unregister a trace_probe and probe_event */ static int unregister_trace_kprobe(struct trace_kprobe *tk) { - /* If other probes are on the event, just unregister kprobe */ - if (trace_probe_has_sibling(&tk->tp)) - goto unreg; - /* Enabled event can not be unregistered */ if (trace_probe_is_enabled(&tk->tp)) return -EBUSY; @@ -560,6 +556,10 @@ static int unregister_trace_kprobe(struct trace_kprobe *tk) if (trace_event_dyn_busy(trace_probe_event_call(&tk->tp))) return -EBUSY; + /* If other probes are on the event, just unregister kprobe */ + if (trace_probe_has_sibling(&tk->tp)) + goto unreg; + /* Will fail if probe is being used by ftrace or perf */ if (unregister_kprobe_event(tk)) return -EBUSY; @@ -2017,6 +2017,9 @@ static __init void setup_boot_kprobe_events(void) char *p, *cmd = kprobe_boot_events_buf; int ret; + if (!kprobe_boot_events_buf[0]) + return; + strreplace(kprobe_boot_events_buf, ',', ' '); while (cmd && *cmd != '\0') { diff --git a/kernel/trace/trace_probe.c b/kernel/trace/trace_probe.c index ba580d0d0f6a..cff55dcae36f 100644 --- a/kernel/trace/trace_probe.c +++ b/kernel/trace/trace_probe.c @@ -411,6 +411,9 @@ static bool btf_type_is_char_ptr(struct btf *btf, const struct btf_type *type) const struct btf_type *real_type; u32 intdata; + if (BTF_INFO_KIND(type->info) != BTF_KIND_PTR) + return false; + real_type = btf_type_skip_modifiers(btf, type->type, NULL); if (!real_type) return false; @@ -435,6 +438,11 @@ static bool btf_type_is_char_array(struct btf *btf, const struct btf_type *type) array = (const struct btf_array *)(type + 1); real_type = btf_type_skip_modifiers(btf, array->type, NULL); + if (!real_type) + return false; + + if (BTF_INFO_KIND(real_type->info) != BTF_KIND_INT) + return false; intdata = btf_type_int(real_type); return !(BTF_INT_ENCODING(intdata) & BTF_INT_SIGNED) @@ -486,6 +494,18 @@ static const char *fetch_type_from_btf_type(struct btf *btf, { u32 intdata; + if (ctx->last_bitsize) { + u32 bits = ctx->last_bitsize + ctx->last_bitoffs; + + if (bits <= 8) + return "u8"; + if (bits <= 16) + return "u16"; + if (bits <= 32) + return "u32"; + return "u64"; + } + /* TODO: const char * could be converted as a string */ switch (BTF_INFO_KIND(type->info)) { case BTF_KIND_ENUM: @@ -520,10 +540,6 @@ static const char *fetch_type_from_btf_type(struct btf *btf, case 64: return "u64"; } - /* bitfield, size is encoded in the type */ - ctx->last_bitsize = BTF_INT_BITS(intdata); - ctx->last_bitoffs += BTF_INT_OFFSET(intdata); - return "u64"; } } /* TODO: support other types */ @@ -653,6 +669,12 @@ static int get_bitoffset_of_field(char **pfieldname, const struct btf_type **pty /* Add anonymous structure/union offset */ bitoffs += anon_offs; + type = btf_type_skip_modifiers(btf, field->type, NULL); + if (!type) { + trace_probe_log_err(ctx->offset, BAD_BTF_TID); + return -EINVAL; + } + /* Accumulate the bit-offsets of the dot-connected fields */ if (btf_type_kflag(container_type)) { bitoffs += BTF_MEMBER_BIT_OFFSET(field->offset); @@ -660,12 +682,15 @@ static int get_bitoffset_of_field(char **pfieldname, const struct btf_type **pty } else { bitoffs += field->offset; ctx->last_bitsize = 0; - } + if (BTF_INFO_KIND(type->info) == BTF_KIND_INT) { + u32 intdata = btf_type_int(type); - type = btf_type_skip_modifiers(btf, field->type, NULL); - if (!type) { - trace_probe_log_err(ctx->offset, BAD_BTF_TID); - return -EINVAL; + bitoffs += BTF_INT_OFFSET(intdata); + if ((bitoffs % 8) || + BTF_INT_BITS(intdata) != BYTES_TO_BITS(type->size) || + !is_power_of_2(type->size)) + ctx->last_bitsize = BTF_INT_BITS(intdata); + } } if (next) @@ -858,13 +883,22 @@ static const struct fetch_type *find_fetch_type_from_btf_type( } static int parse_btf_bitfield(struct fetch_insn **pcode, + const struct fetch_type *t, struct traceprobe_parse_context *ctx) { struct fetch_insn *code = *pcode; - if ((ctx->last_bitsize % 8 == 0) && ctx->last_bitoffs == 0) + if ((ctx->last_bitsize == 0 || + ctx->last_bitsize == BYTES_TO_BITS(t->size)) && + ctx->last_bitoffs == 0) return 0; + if (ctx->last_bitsize == 0 || + BYTES_TO_BITS(t->size) < (ctx->last_bitsize + ctx->last_bitoffs)) { + trace_probe_log_err(ctx->offset, BAD_BITFIELD); + return -EINVAL; + } + code++; if (code->op != FETCH_OP_NOP) { trace_probe_log_err(ctx->offset, TOO_MANY_OPS); @@ -873,9 +907,13 @@ static int parse_btf_bitfield(struct fetch_insn **pcode, *pcode = code; code->op = FETCH_OP_MOD_BF; - code->lshift = 64 - (ctx->last_bitsize + ctx->last_bitoffs); - code->rshift = 64 - ctx->last_bitsize; - code->basesize = 64 / 8; +#ifdef __BIG_ENDIAN_BITFIELD + code->lshift = ctx->last_bitoffs; +#else + code->lshift = BYTES_TO_BITS(t->size) - (ctx->last_bitsize + ctx->last_bitoffs); +#endif + code->rshift = BYTES_TO_BITS(t->size) - ctx->last_bitsize; + code->basesize = t->size; return 0; } @@ -1085,6 +1123,7 @@ static int parse_btf_arg(char *varname, } static int parse_btf_bitfield(struct fetch_insn **pcode, + const struct fetch_type *t, struct traceprobe_parse_context *ctx) { trace_probe_log_err(ctx->offset, NOSUP_BTFARG); @@ -1917,6 +1956,8 @@ static int finalize_fetch_insn(struct fetch_insn *code, /* Store operation */ if (parg->type->is_string) { + bool is_uderef; + /* Check bad combination of the type and the last fetch_insn. */ if (!strcmp(parg->type->name, "symstr")) { if (code->op != FETCH_OP_REG && code->op != FETCH_OP_STACK && @@ -1936,6 +1977,7 @@ static int finalize_fetch_insn(struct fetch_insn *code, } } + is_uderef = (code->op == FETCH_OP_UDEREF); if (!strcmp(parg->type->name, "symstr") || (code->op == FETCH_OP_IMM || code->op == FETCH_OP_COMM || code->op == FETCH_OP_IMMSTR) || code->op == FETCH_OP_TP_ARG || @@ -1948,6 +1990,12 @@ static int finalize_fetch_insn(struct fetch_insn *code, * For the symstr, it doesn't need to dereference, thus * it just get the value. */ + if (parg->count && (code->op != FETCH_OP_DEREF && + code->op != FETCH_OP_UDEREF)) { + trace_probe_log_err(ctx->offset + type_offset, + BAD_STRING); + return -EINVAL; + } code++; if (code->op != FETCH_OP_NOP) { trace_probe_log_err(ctx->offset, TOO_MANY_OPS); @@ -1956,8 +2004,7 @@ static int finalize_fetch_insn(struct fetch_insn *code, } /* If op == DEREF, replace it with STRING */ - if (!strcmp(parg->type->name, "ustring") || - code->op == FETCH_OP_UDEREF) + if (!strcmp(parg->type->name, "ustring") || is_uderef) code->op = FETCH_OP_ST_USTRING; else if (!strcmp(parg->type->name, "symstr")) code->op = FETCH_OP_ST_SYMSTR; @@ -1995,7 +2042,7 @@ static int finalize_fetch_insn(struct fetch_insn *code, } else if (IS_ENABLED(CONFIG_PROBE_EVENTS_BTF_ARGS) && ctx->last_type) { /* If user not specified the type, try parsing BTF bitfield. */ - ret = parse_btf_bitfield(&code, ctx); + ret = parse_btf_bitfield(&code, parg->type, ctx); if (ret) return ret; } diff --git a/kernel/trace/trace_probe_tmpl.h b/kernel/trace/trace_probe_tmpl.h index 8db12f758fda..8acc0f0ebd7a 100644 --- a/kernel/trace/trace_probe_tmpl.h +++ b/kernel/trace/trace_probe_tmpl.h @@ -87,15 +87,27 @@ fetch_store_symstrlen(unsigned long addr) static nokprobe_inline int fetch_store_symstring(unsigned long addr, void *dest, void *base) { + char namebuf[KSYM_SYMBOL_LEN]; int maxlen = get_loc_len(*(u32 *)dest); void *__dest; + int len; if (unlikely(!maxlen)) return -ENOMEM; __dest = get_loc_data(dest, base); + len = sprint_symbol(namebuf, addr); + if (len < 0) { + *(u32 *)dest = make_data_loc(0, __dest - base); + return 0; + } + + len = min(len, maxlen - 1); + memcpy(__dest, namebuf, len); + ((char *)__dest)[len] = '\0'; + *(u32 *)dest = make_data_loc(len + 1, __dest - base); - return sprint_symbol(__dest, addr); + return len + 1; } /* common part of process_fetch_insn*/ diff --git a/kernel/trace/trace_uprobe.c b/kernel/trace/trace_uprobe.c index 22cc3c8181b8..fb7991543db7 100644 --- a/kernel/trace/trace_uprobe.c +++ b/kernel/trace/trace_uprobe.c @@ -396,13 +396,17 @@ static int unregister_trace_uprobe(struct trace_uprobe *tu) { int ret; - if (trace_probe_has_sibling(&tu->tp)) - goto unreg; + /* Enabled event can not be unregistered */ + if (trace_probe_is_enabled(&tu->tp)) + return -EBUSY; /* If there's a reference to the dynamic event */ if (trace_event_dyn_busy(trace_probe_event_call(&tu->tp))) return -EBUSY; + if (trace_probe_has_sibling(&tu->tp)) + goto unreg; + ret = unregister_uprobe_event(tu); if (ret) return ret; @@ -443,6 +447,28 @@ static bool trace_uprobe_has_same_uprobe(struct trace_uprobe *orig, return false; } +typedef bool (*filter_func_t)(struct uprobe_consumer *self, struct mm_struct *mm); + +#ifdef CONFIG_PERF_EVENTS +static bool uprobe_perf_filter(struct uprobe_consumer *uc, struct mm_struct *mm); +#else +#define uprobe_perf_filter NULL +#endif + +static int trace_uprobe_enable(struct trace_uprobe *tu, filter_func_t filter) +{ + struct inode *inode = d_real_inode(tu->path.dentry); + struct uprobe *uprobe; + + tu->consumer.filter = filter; + uprobe = uprobe_register(inode, tu->offset, tu->ref_ctr_offset, &tu->consumer); + if (IS_ERR(uprobe)) + return PTR_ERR(uprobe); + + tu->uprobe = uprobe; + return 0; +} + static int append_trace_uprobe(struct trace_uprobe *tu, struct trace_uprobe *to) { int ret; @@ -462,10 +488,22 @@ static int append_trace_uprobe(struct trace_uprobe *tu, struct trace_uprobe *to) /* Append to existing event */ ret = trace_probe_append(&tu->tp, &to->tp); - if (!ret) - dyn_event_add(&tu->devent, trace_probe_event_call(&tu->tp)); + if (ret) + return ret; - return ret; + if (trace_probe_is_enabled(&tu->tp)) { + ret = trace_uprobe_enable(tu, + trace_probe_test_flag(&tu->tp, TP_FLAG_PROFILE) ? + uprobe_perf_filter : NULL); + if (ret) { + trace_probe_unlink(&tu->tp); + return ret; + } + } + + dyn_event_add(&tu->devent, trace_probe_event_call(&tu->tp)); + + return 0; } /* @@ -663,7 +701,7 @@ static int __trace_uprobe_create(int argc, const char **argv) } if (!event) { - char *tail; + char *tail __free(kfree) = NULL; char *ptr; tail = kstrdup(kbasename(filename), GFP_KERNEL); @@ -679,7 +717,6 @@ static int __trace_uprobe_create(int argc, const char **argv) return -ENOMEM; snprintf(buf, MAX_EVENT_NAME_LEN, "%c_%s_0x%lx", 'p', tail, offset); event = buf; - kfree(tail); } argc -= 2; @@ -1101,22 +1138,6 @@ print_uprobe_event(struct trace_iterator *iter, int flags, struct trace_event *e return trace_handle_return(s); } -typedef bool (*filter_func_t)(struct uprobe_consumer *self, struct mm_struct *mm); - -static int trace_uprobe_enable(struct trace_uprobe *tu, filter_func_t filter) -{ - struct inode *inode = d_real_inode(tu->path.dentry); - struct uprobe *uprobe; - - tu->consumer.filter = filter; - uprobe = uprobe_register(inode, tu->offset, tu->ref_ctr_offset, &tu->consumer); - if (IS_ERR(uprobe)) - return PTR_ERR(uprobe); - - tu->uprobe = uprobe; - return 0; -} - static void __probe_event_disable(struct trace_probe *tp) { struct trace_uprobe *tu; diff --git a/kernel/tsacct.c b/kernel/tsacct.c index 5c153106e642..48320684c7c0 100644 --- a/kernel/tsacct.c +++ b/kernel/tsacct.c @@ -24,7 +24,7 @@ void bacct_add_tsk(struct user_namespace *user_ns, const struct cred *tcred; u64 utime, stime, utimescaled, stimescaled; u64 now_ns, delta; - time64_t btime; + struct timespec64 btime; BUILD_BUG_ON(TS_COMM_LEN < TASK_COMM_LEN); @@ -39,9 +39,11 @@ void bacct_add_tsk(struct user_namespace *user_ns, do_div(delta, NSEC_PER_USEC); stats->ac_etime = delta; /* Convert to seconds for btime (note y2106 limit) */ - btime = ktime_get_real_seconds() - div_u64(delta, USEC_PER_SEC); - stats->ac_btime = clamp_t(time64_t, btime, 0, U32_MAX); - stats->ac_btime64 = btime; + getboottime64(&btime); + btime = timespec64_add(btime, ns_to_timespec64(tsk->start_boottime)); + stats->ac_btime = clamp_t(time64_t, btime.tv_sec, 0, U32_MAX); + /* Setting the clock back after suspend can make btime negative. */ + stats->ac_btime64 = max_t(time64_t, btime.tv_sec, 0); if (tsk->flags & PF_EXITING) stats->ac_exitcode = tsk->exit_code; diff --git a/kernel/watch_queue.c b/kernel/watch_queue.c index 453dcf613205..e2bdd5fb0db1 100644 --- a/kernel/watch_queue.c +++ b/kernel/watch_queue.c @@ -77,13 +77,9 @@ static void watch_queue_pipe_buf_release(struct pipe_inode_info *pipe, generic_pipe_buf_release(pipe, buf); } -// No try_steal function => no stealing -#define watch_queue_pipe_buf_try_steal NULL - /* New data written to a pipe may be appended to a buffer with this type. */ static const struct pipe_buf_operations watch_queue_pipe_buf_ops = { .release = watch_queue_pipe_buf_release, - .try_steal = watch_queue_pipe_buf_try_steal, .get = generic_pipe_buf_get, }; diff --git a/lib/assoc_array.c b/lib/assoc_array.c index b6c9723e12ce..f19888ec3e09 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 @@ found_slot_for_multiple_occupancy: } } } +} - 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 @@ all_leaves_cluster_together: 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 @@ all_leaves_cluster_together: /* 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 @@ found_leaf: * 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; + struct assoc_array_node *new_n; + struct assoc_array_ptr *new_parent; + int keylen; - pr_devel("-->%s()\n", __func__); + new_parent = w->new_n ? assoc_array_node_to_ptr(w->new_n) : NULL; - 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; - - new_root = new_parent = NULL; - new_ptr_pp = &new_root; - cursor = array->root; - -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 @@ retry_compress: 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 @@ retry_compress: 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 @@ retry_compress: 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 @@ retry_compress: */ ptr = new_n->back_pointer; if (!ptr) - goto gc_complete; - - 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; + return NULL; - if (new_n->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT) { - struct assoc_array_node *n; + if (!assoc_array_ptr_is_shortcut(ptr)) + return ptr; - 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; - } + new_s = assoc_array_ptr_to_shortcut(ptr); + new_parent = new_s->back_pointer; + slot = new_s->parent_slot; - n = assoc_array_ptr_to_node(new_parent); - n->slots[slot] = assoc_array_node_to_ptr(new_n); + 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; } - } else { - new_parent = ptr; + + assoc_array_ptr_to_node(new_parent)->slots[slot] = + assoc_array_node_to_ptr(new_n); } - new_n = assoc_array_ptr_to_node(new_parent); + return new_parent; +} -ascend_old_tree: - ptr = node->back_pointer; +/* + * 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; + + w->new_n = assoc_array_ptr_to_node(parent); + + 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 819685d6c68d..948c8c10e4b9 100644 --- a/lib/bootconfig.c +++ b/lib/bootconfig.c @@ -428,9 +428,9 @@ int __init xbc_node_compose_key_after(struct xbc_node *root, node = xbc_node_get_parent(node); while (node && node != root) { - keys[depth++] = xbc_node_index(node); if (depth == XBC_DEPTH_MAX) return -ERANGE; + keys[depth++] = xbc_node_index(node); node = xbc_node_get_parent(node); } if (!node && root) @@ -793,16 +793,17 @@ static int __init __xbc_parse_value(char **__v, char **__n) return xbc_parse_error("No value delimiter", p); if (*p) p++; - break; + goto skip_trim; } if (strchr(",;\n#}", c)) { *p++ = '\0'; - v = strim(v); break; } } if (quotes) return xbc_parse_error("No closing quotes", p); + v = strim(v); +skip_trim: if (c == '#') { p = skip_comment(p); c = '\n'; /* A comment must be treated as a newline */ diff --git a/lib/errseq.c b/lib/errseq.c index 13a2581c5a87..ea4ff9cc2166 100644 --- a/lib/errseq.c +++ b/lib/errseq.c @@ -162,7 +162,8 @@ EXPORT_SYMBOL(errseq_check); * points to. If it does, then just return 0. * * If it doesn't, then the value has changed. Set the "seen" flag, and try to - * swap it into place as the new eseq value. Then, set that value as the new + * swap it into place as the new eseq value. If the swap fails because the + * value changed, retry with the new value. Then, set that value as the new * "since" value, and return whatever the error portion is set to. * * Note that no locking is provided here for concurrent updates to the "since" @@ -184,24 +185,30 @@ int errseq_check_and_advance(errseq_t *eseq, errseq_t *since) * to take the lock that protects the "since" value. */ old = READ_ONCE(*eseq); - if (old != *since) { + while (old != *since) { /* * Set the flag and try to swap it into place if it has * changed. * - * We don't care about the outcome of the swap here. If the - * swap doesn't occur, then it has either been updated by a - * writer who is altering the value in some way (updating - * counter or resetting the error), or another reader who is - * just setting the "seen" flag. Either outcome is OK, and we - * can advance "since" and return an error based on what we - * have. + * If the swap fails, a writer or another reader changed the + * value under us, so retry with the new value. "since" must + * only ever be set to a value that was stored with the SEEN + * flag: errseq_set() does not bump the counter while the + * flag is clear, so an unstored value could come back later + * and hide the errors that were recorded in the meantime. */ new = old | ERRSEQ_SEEN; - if (new != old) - cmpxchg(eseq, old, new); + if (new != old) { + errseq_t cur = cmpxchg(eseq, old, new); + + if (cur != old) { + old = cur; + continue; + } + } *since = new; err = -(new & ERRNO_MASK); + break; } return err; } diff --git a/lib/iov_iter.c b/lib/iov_iter.c index fa4fe2e92383..af005ef5cb82 100644 --- a/lib/iov_iter.c +++ b/lib/iov_iter.c @@ -1382,8 +1382,8 @@ static ssize_t __import_iovec_ubuf(int type, const struct iovec __user *uvec, } ssize_t __import_iovec(int type, const struct iovec __user *uvec, - unsigned nr_segs, unsigned fast_segs, struct iovec **iovp, - struct iov_iter *i, bool compat) + unsigned long nr_segs, unsigned int fast_segs, + struct iovec **iovp, struct iov_iter *i, bool compat) { ssize_t total_len = 0; unsigned long seg; @@ -1454,7 +1454,7 @@ ssize_t __import_iovec(int type, const struct iovec __user *uvec, * Return: Negative error code on error, bytes imported on success */ ssize_t import_iovec(int type, const struct iovec __user *uvec, - unsigned nr_segs, unsigned fast_segs, + unsigned long nr_segs, unsigned int fast_segs, struct iovec **iovp, struct iov_iter *i) { return __import_iovec(type, uvec, nr_segs, fast_segs, iovp, i, diff --git a/lib/tests/errseq_kunit.c b/lib/tests/errseq_kunit.c index 8f39ebc4a248..5ebc411ea749 100644 --- a/lib/tests/errseq_kunit.c +++ b/lib/tests/errseq_kunit.c @@ -2,21 +2,26 @@ /* * KUnit tests for the errseq_t error-tracking infrastructure. * - * These exercise the documented single-threaded semantics of the errseq - * API (see Documentation/core-api/errseq.rst and lib/errseq.c): error + * Most cases exercise the documented single-threaded semantics of the + * errseq API (see Documentation/core-api/errseq.rst and lib/errseq.c): error * recording and overwriting, the "seen" handoff between errseq_sample() * and errseq_check_and_advance(), and the re-reporting of an error that * is recorded again after it has been seen. * - * The lockless properties of errseq_t under concurrent updates are - * outside the scope of these deterministic tests, as is the WARN path - * for invalid error values. + * The WARN path for invalid error values is not tested. The last case + * races errseq_set() against errseq_check_and_advance() on another CPU. */ #include <kunit/test.h> +#include <linux/atomic.h> +#include <linux/cpumask.h> #include <linux/err.h> #include <linux/errno.h> #include <linux/errseq.h> +#include <linux/jiffies.h> +#include <linux/kthread.h> +#include <linux/random.h> +#include <linux/sched.h> /* * A zeroed errseq_t is the "no error has ever occurred" epoch: it @@ -209,6 +214,100 @@ static void errseq_test_two_subscribers_independent(struct kunit *test) KUNIT_EXPECT_EQ(test, errseq_check_and_advance(&eseq, &cursor_b), 0); } +/* + * errseq_check_and_advance() racing with errseq_set() on another CPU. + * + * Each round, cursor @f checks an unseen -EIO while another CPU records + * -ENOSPC. Afterwards -EIO is recorded again and cursor @g checks. The + * second -EIO is recorded after @f's check returned, so @f's next check + * must report an error, whichever way the race with -ENOSPC went. + */ +struct errseq_race { + errseq_t eseq; + atomic_t go; /* round the writer should run */ + atomic_t done; /* last round the writer completed */ + unsigned int wdelay; +}; + +static void errseq_race_spin(unsigned int n) +{ + while (n--) + cpu_relax(); +} + +static int errseq_race_writer(void *data) +{ + struct errseq_race *r = data; + int seen = 0; + + while (!kthread_should_stop()) { + int round = atomic_read_acquire(&r->go); + + if (round == seen) { + cond_resched(); + continue; + } + seen = round; + errseq_race_spin(READ_ONCE(r->wdelay)); + errseq_set(&r->eseq, -ENOSPC); + atomic_set_release(&r->done, round); + } + return 0; +} + +#define ERRSEQ_RACE_ROUNDS 2000000 +#define ERRSEQ_RACE_SECONDS 5 + +static void errseq_test_check_and_advance_race(struct kunit *test) +{ + struct errseq_race *r; + struct task_struct *writer; + unsigned long deadline; + int round, unreported = 0, missed = 0; + + if (num_online_cpus() < 2) + kunit_skip(test, "needs at least two CPUs"); + + r = kunit_kzalloc(test, sizeof(*r), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, r); + + writer = kthread_run(errseq_race_writer, r, "errseq_race"); + KUNIT_ASSERT_FALSE(test, IS_ERR(writer)); + + deadline = jiffies + ERRSEQ_RACE_SECONDS * HZ; + for (round = 1; round <= ERRSEQ_RACE_ROUNDS; round++) { + errseq_t f = 0, g = 0; + + WRITE_ONCE(r->eseq, 0); + errseq_set(&r->eseq, -EIO); + WRITE_ONCE(r->wdelay, get_random_u32_below(64)); + atomic_set_release(&r->go, round); + + errseq_race_spin(get_random_u32_below(64)); + if (!errseq_check_and_advance(&r->eseq, &f)) + unreported++; + + while (atomic_read_acquire(&r->done) != round) + cond_resched(); + + /* Recorded after f's check returned: f must hear about it. */ + errseq_set(&r->eseq, -EIO); + errseq_check_and_advance(&r->eseq, &g); + if (!errseq_check_and_advance(&r->eseq, &f)) + missed++; + + if (time_after(jiffies, deadline)) + break; + if (!(round & 1023)) + cond_resched(); + } + kthread_stop(writer); + + kunit_info(test, "%d rounds, %d missed errors\n", round - 1, missed); + KUNIT_EXPECT_EQ(test, unreported, 0); + KUNIT_EXPECT_EQ(test, missed, 0); +} + static struct kunit_case errseq_test_cases[] = { KUNIT_CASE(errseq_test_zero_epoch_reports_no_error), KUNIT_CASE(errseq_test_set_records_error), @@ -223,6 +322,7 @@ static struct kunit_case errseq_test_cases[] = { KUNIT_CASE(errseq_test_repeat_error_visible_to_all_cursors), KUNIT_CASE(errseq_test_advance_stable_when_unchanged), KUNIT_CASE(errseq_test_two_subscribers_independent), + KUNIT_CASE_SLOW(errseq_test_check_and_advance_race), {} }; diff --git a/lib/vdso/Kconfig b/lib/vdso/Kconfig index 597f5f0f9681..2436c20ee0ef 100644 --- a/lib/vdso/Kconfig +++ b/lib/vdso/Kconfig @@ -23,3 +23,13 @@ config VDSO_GETRANDOM select VDSO_DATASTORE help Selected by architectures that support vDSO getrandom(). + +config VDSO_UNALIGNED_PACKED + bool + default !HAVE_EFFICIENT_UNALIGNED_ACCESS + help + Use packed structs rather than memcpy() in include/vdso/unaligned.h + for unaligned memory accesses. Enabled by default when the + architecture does not have efficient unaligned accesses, as GCC may + emit stack spills or out-of-line memcpy() calls instead of inlining + byte shifts. diff --git a/mm/filemap.c b/mm/filemap.c index b04be64a5069..f9e34144c53c 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? */ diff --git a/mm/folio.c b/mm/folio.c index 35e242b48870..38046a40a9db 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) @@ -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 @@ next_page: 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 eb913acb03b7..7791872f14af 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 @@ out_unlock: 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 @@ -3775,6 +3793,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 +3810,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 +3836,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 +3878,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); } @@ -5215,6 +5257,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 630c96cd1e88..ce9c8e57b8e5 100644 --- a/mm/hugetlb.c +++ b/mm/hugetlb.c @@ -1297,11 +1297,11 @@ static struct folio *dequeue_hugetlb_folio_node_exact(struct hstate *h, static struct folio *dequeue_hugetlb_folio_nodemask(struct hstate *h, gfp_t gfp_mask, int nid, nodemask_t *nmask) { - unsigned int cpuset_mems_cookie; + unsigned int cpuset_mems_cookie, zonelist_cookie; struct zonelist *zonelist; struct zone *zone; struct zoneref *z; - int node = NUMA_NO_NODE; + int node; /* 'nid' should not be NUMA_NO_NODE. Try to catch any misuse of it and rectifiy. */ if (nid == NUMA_NO_NODE) @@ -1310,10 +1310,16 @@ static struct folio *dequeue_hugetlb_folio_nodemask(struct hstate *h, gfp_t gfp_ zonelist = node_zonelist(nid, gfp_mask); retry_cpuset: + node = NUMA_NO_NODE; cpuset_mems_cookie = read_mems_allowed_begin(); + zonelist_cookie = zonelist_iter_begin(); for_each_zone_zonelist_nodemask(zone, z, zonelist, gfp_zone(gfp_mask), nmask) { struct folio *folio; + /* A rebuild may have shifted a node outside @nmask into this slot. */ + if (unlikely(check_retry_zonelist(zonelist_cookie))) + goto retry_cpuset; + if (!cpuset_zone_allowed(zone, gfp_mask)) continue; /* @@ -1328,7 +1334,8 @@ retry_cpuset: if (folio) return folio; } - if (unlikely(read_mems_allowed_retry(cpuset_mems_cookie))) + if (unlikely(read_mems_allowed_retry(cpuset_mems_cookie) || + check_retry_zonelist(zonelist_cookie))) goto retry_cpuset; return NULL; diff --git a/mm/internal.h b/mm/internal.h index e3f92883bf23..85cf7becf858 100644 --- a/mm/internal.h +++ b/mm/internal.h @@ -834,6 +834,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 +1274,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/khugepaged.c b/mm/khugepaged.c index 4bbe319ef86f..964f78c3856b 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/memfd.c b/mm/memfd.c index 0e3ff3eebfa8..05088ab210ba 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.c b/mm/memory.c index ec3d9d99ccee..7f019afc35ca 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 @@ again: /* * 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 @@ again: 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); @@ -2059,8 +2076,8 @@ retry: 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) { @@ -4959,13 +4978,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; /* @@ -5752,6 +5766,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 +5823,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) @@ -5972,6 +5992,10 @@ fallback: 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/memory_hotplug.c b/mm/memory_hotplug.c index c9cc42e54f05..b9f02bc6ed0d 100644 --- a/mm/memory_hotplug.c +++ b/mm/memory_hotplug.c @@ -461,6 +461,22 @@ static unsigned long find_biggest_section_pfn(struct zone *zone, return 0; } +/* + * The page allocator checks pages against the span of their zone while the + * zone is resized, see page_outside_zone_boundaries(). It must not see the + * new value of one field together with the old value of the other one. + */ +static void zone_set_span(struct zone *zone, unsigned long start_pfn, + unsigned long spanned_pages) +{ + unsigned long flags; + + write_seqlock_irqsave(&zone->span_seqlock, flags); + zone->zone_start_pfn = start_pfn; + zone->spanned_pages = spanned_pages; + write_sequnlock_irqrestore(&zone->span_seqlock, flags); +} + static void shrink_zone_span(struct zone *zone, unsigned long start_pfn, unsigned long end_pfn) { @@ -475,13 +491,10 @@ static void shrink_zone_span(struct zone *zone, unsigned long start_pfn, */ pfn = find_smallest_section_pfn(zone, end_pfn, zone_end_pfn(zone)); - if (pfn) { - zone->spanned_pages = zone_end_pfn(zone) - pfn; - zone->zone_start_pfn = pfn; - } else { - zone->zone_start_pfn = 0; - zone->spanned_pages = 0; - } + if (pfn) + zone_set_span(zone, pfn, zone_end_pfn(zone) - pfn); + else + zone_set_span(zone, 0, 0); } else if (zone_end_pfn(zone) == end_pfn) { /* * If the section is biggest section in the zone, it need @@ -492,11 +505,10 @@ static void shrink_zone_span(struct zone *zone, unsigned long start_pfn, pfn = find_biggest_section_pfn(zone, zone->zone_start_pfn, start_pfn); if (pfn) - zone->spanned_pages = pfn - zone->zone_start_pfn + 1; - else { - zone->zone_start_pfn = 0; - zone->spanned_pages = 0; - } + zone_set_span(zone, zone->zone_start_pfn, + pfn - zone->zone_start_pfn + 1); + else + zone_set_span(zone, 0, 0); } } @@ -684,12 +696,12 @@ static void online_pages_range(unsigned long start_pfn, unsigned long nr_pages) static void __meminit resize_zone_range(struct zone *zone, unsigned long start_pfn, unsigned long nr_pages) { - unsigned long old_end_pfn = zone_end_pfn(zone); + unsigned long end_pfn = max(start_pfn + nr_pages, zone_end_pfn(zone)); - if (zone_is_empty(zone) || start_pfn < zone->zone_start_pfn) - zone->zone_start_pfn = start_pfn; + if (!zone_is_empty(zone) && start_pfn > zone->zone_start_pfn) + start_pfn = zone->zone_start_pfn; - zone->spanned_pages = max(start_pfn + nr_pages, old_end_pfn) - zone->zone_start_pfn; + zone_set_span(zone, start_pfn, end_pfn - start_pfn); } static void __meminit resize_pgdat_range(struct pglist_data *pgdat, unsigned long start_pfn, @@ -1832,6 +1844,13 @@ static int scan_movable_pages(unsigned long start, unsigned long end, if (PageOffline(page) && page_count(page)) return -EBUSY; + /* + * A page that was allocated, but was not a slab page yet, when + * its pageblock was isolated. + */ + if (PageSlab(page)) + return -EBUSY; + folio = page_folio(page); if (!folio_test_hugetlb(folio)) continue; diff --git a/mm/mempolicy.c b/mm/mempolicy.c index 0cb6da1c47a4..c7d4d149c9b8 100644 --- a/mm/mempolicy.c +++ b/mm/mempolicy.c @@ -2176,6 +2176,7 @@ unsigned int mempolicy_slab_node(void) case MPOL_PREFERRED_MANY: { struct zoneref *z; + struct zone *zone; /* * Follow bind policy behavior and start allocation at the @@ -2186,7 +2187,8 @@ unsigned int mempolicy_slab_node(void) zonelist = &NODE_DATA(node)->node_zonelists[ZONELIST_FALLBACK]; z = first_zones_zonelist(zonelist, highest_zoneidx, &policy->nodes); - return zonelist_zone(z) ? zonelist_node_idx(z) : node; + zone = zonelist_zone(z); + return zone ? zone_to_nid(zone) : node; } case MPOL_LOCAL: return node; @@ -3085,7 +3087,7 @@ int mpol_misplaced(struct folio *folio, struct vm_fault *vmf, node_zonelist(thisnid, GFP_HIGHUSER), gfp_zone(GFP_HIGHUSER), &pol->nodes); - polnid = zonelist_node_idx(z); + polnid = zone_to_nid(zonelist_zone(z)); break; default: diff --git a/mm/migrate.c b/mm/migrate.c index 875079464930..e6cd83cf32aa 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)); diff --git a/mm/mmu_gather.c b/mm/mmu_gather.c index 9f353f0e2ef4..e98397ac577c 100644 --- a/mm/mmu_gather.c +++ b/mm/mmu_gather.c @@ -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/mmzone.c b/mm/mmzone.c index 9cc9ef588580..65880396f104 100644 --- a/mm/mmzone.c +++ b/mm/mmzone.c @@ -43,13 +43,14 @@ struct zone *next_zone(struct zone *zone) return zone; } -static inline int zref_in_nodemask(struct zoneref *zref, - const nodemask_t *nodes) +/* A NULL zone terminates the zonelist, so it ends the search. */ +static inline bool zone_in_nodemask(const struct zone *zone, + const nodemask_t *nodes) { #ifdef CONFIG_NUMA - return node_isset(zonelist_node_idx(zref), *nodes); + return !zone || node_isset(zone_to_nid(zone), *nodes); #else - return 1; + return true; #endif /* CONFIG_NUMA */ } @@ -67,7 +68,7 @@ struct zoneref *__next_zones_zonelist(struct zoneref *z, z++; else while (zonelist_zone_idx(z) > highest_zoneidx || - (zonelist_zone(z) && !zref_in_nodemask(z, nodes))) + !zone_in_nodemask(zonelist_zone(z), nodes)) z++; return z; diff --git a/mm/page_alloc.c b/mm/page_alloc.c index eb4f02617f53..2fef4092c913 100644 --- a/mm/page_alloc.c +++ b/mm/page_alloc.c @@ -370,7 +370,6 @@ get_pfnblock_bitmap_bitidx(const struct page *page, unsigned long pfn, BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 4); #endif BUILD_BUG_ON(__MIGRATE_TYPE_END > PAGEBLOCK_MIGRATETYPE_MASK); - VM_BUG_ON_PAGE(!zone_spans_pfn(page_zone(page), pfn), page); bitmap = get_pageblock_bitmap(page, pfn); *bitidx = pfn_to_bitidx(page, pfn); @@ -682,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); @@ -1562,6 +1574,8 @@ static void free_one_page(struct zone *zone, struct page *page, llist_for_each_entry_safe(p, tmp, llnode, pcp_llist) { unsigned int p_order = p->private; + /* It may end up as a tail of the merged free page. */ + p->private = 0; split_large_buddy(zone, p, page_to_pfn(p), p_order, fpi_flags); __count_vm_events(PGFREE, 1 << p_order); } @@ -3799,12 +3813,21 @@ get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags, { struct zoneref *z; struct zone *zone; + struct zone *preferred_zone; struct pglist_data *last_pgdat = NULL; bool last_pgdat_dirty_ok = false; bool no_fallback; bool skip_kswapd_nodes = nr_online_nodes > 1; bool skipped_kswapd_nodes = false; + /* + * A concurrent zonelist rebuild can NULL or replace this slot. Zones + * are never freed, so reading it once keeps a usable zone. + */ + preferred_zone = zonelist_zone(ac->preferred_zoneref); + if (!preferred_zone) + return NULL; + retry: /* * Scan zonelist, looking for a zone with enough free. @@ -3851,7 +3874,7 @@ retry: } if (no_fallback && !defrag_mode && nr_online_nodes > 1 && - zone != zonelist_zone(ac->preferred_zoneref)) { + zone != preferred_zone) { int local_nid; /* @@ -3859,7 +3882,7 @@ retry: * fragmenting fallbacks. Locality is more important * than fragmentation avoidance. */ - local_nid = zonelist_node_idx(ac->preferred_zoneref); + local_nid = zone_to_nid(preferred_zone); if (zone_to_nid(zone) != local_nid) { alloc_flags &= ~ALLOC_NOFRAGMENT; goto retry; @@ -3921,7 +3944,7 @@ check_alloc_wmark: goto try_this_zone; if (!node_reclaim_enabled() || - !zone_allows_reclaim(zonelist_zone(ac->preferred_zoneref), zone)) + !zone_allows_reclaim(preferred_zone, zone)) continue; if (!node_reclaim(zone->zone_pgdat, gfp_mask, order)) @@ -3934,7 +3957,7 @@ check_alloc_wmark: } try_this_zone: - page = rmqueue(zonelist_zone(ac->preferred_zoneref), zone, order, + page = rmqueue(preferred_zone, zone, order, gfp_mask, alloc_flags, ac->migratetype); if (page) { prep_new_page(page, order, gfp_mask, alloc_flags); @@ -4405,24 +4428,21 @@ EXPORT_SYMBOL_GPL(fs_reclaim_release); * retries the allocation if zonelist changes. Writer side is protected by the * embedded spin_lock. */ -static DEFINE_SEQLOCK(zonelist_update_seq); +DEFINE_SEQLOCK(zonelist_update_seq); -static unsigned int zonelist_iter_begin(void) +/* + * Never wait for the writer, which an ALLOC_NOLOCK caller in NMI may have + * interrupted. Read the raw seqcount: on PREEMPT_RT the seqlock accessor takes + * the spinlock while a write is in progress. + */ +static unsigned int zonelist_iter_sample(void) { - if (IS_ENABLED(CONFIG_MEMORY_HOTREMOVE)) - return read_seqbegin(&zonelist_update_seq); + if (IS_ENABLED(CONFIG_MEMORY_HOTPLUG)) + return raw_seqcount_begin(&zonelist_update_seq.seqcount.seqcount); return 0; } -static unsigned int check_retry_zonelist(unsigned int seq) -{ - if (IS_ENABLED(CONFIG_MEMORY_HOTREMOVE)) - return read_seqretry(&zonelist_update_seq, seq); - - return seq; -} - /* Perform direct synchronous page reclaim */ static unsigned long __perform_reclaim(gfp_t gfp_mask, unsigned int order, @@ -4675,7 +4695,7 @@ should_reclaim_retry(gfp_t gfp_mask, unsigned order, */ wmark = __zone_watermark_ok(zone, order, min_wmark, ac->highest_zoneidx, alloc_flags, available); - trace_reclaim_retry_zone(z, order, reclaimable, + trace_reclaim_retry_zone(zone, order, reclaimable, available, min_wmark, *no_progress_loops, wmark); if (wmark) { ret = true; @@ -4788,7 +4808,7 @@ __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order, unsigned int zonelist_iter_cookie; int reserve_flags; bool compact_first = false; - bool can_retry_reserves = true; + bool can_retry_reserves; unsigned long alloc_start_time = jiffies; /* @@ -4822,6 +4842,7 @@ restart: no_progress_loops = 0; compact_result = COMPACT_SKIPPED; compact_priority = DEF_COMPACT_PRIORITY; + can_retry_reserves = true; cpuset_mems_cookie = read_mems_allowed_begin(); zonelist_iter_cookie = zonelist_iter_begin(); @@ -5110,6 +5131,12 @@ fail: warn_alloc(gfp_mask, ac->nodemask, "page allocation failure: order:%u", order); got_pg: + /* A rebuild during the walk may have handed out an ineligible zone. */ + if (page && check_retry_zonelist(zonelist_iter_cookie)) { + __free_frozen_pages(page, order, FPI_NONE); + page = NULL; + goto restart; + } return page; } @@ -5188,11 +5215,13 @@ unsigned long alloc_pages_bulk_noprof(gfp_t gfp, int preferred_nid, { struct page *page; struct zone *zone; + struct zone *preferred_zone; struct zoneref *z; struct per_cpu_pages *pcp; struct list_head *pcp_list; struct alloc_context ac; unsigned int alloc_flags = ALLOC_WMARK_LOW; + unsigned int zonelist_iter_cookie; int nr_populated = 0, nr_account = 0; /* @@ -5233,9 +5262,15 @@ unsigned long alloc_pages_bulk_noprof(gfp_t gfp, int preferred_nid, /* May set ALLOC_NOFRAGMENT, fragmentation will return 1 page. */ gfp &= gfp_allowed_mask; gfp = current_gfp_context(gfp); + zonelist_iter_cookie = zonelist_iter_sample(); if (!prepare_alloc_pages(gfp, 0, preferred_nid, nodemask, &ac, &gfp, &alloc_flags)) goto out; + /* Read once; see get_page_from_freelist(). */ + preferred_zone = zonelist_zone(ac.preferred_zoneref); + if (!preferred_zone) + goto failed; + /* Find an allowed local zone that meets the low watermark. */ z = ac.preferred_zoneref; for_next_zone_zonelist_nodemask(zone, z, ac.highest_zoneidx, ac.nodemask) { @@ -5246,8 +5281,8 @@ unsigned long alloc_pages_bulk_noprof(gfp_t gfp, int preferred_nid, continue; } - if (nr_online_nodes > 1 && zone != zonelist_zone(ac.preferred_zoneref) && - zone_to_nid(zone) != zonelist_node_idx(ac.preferred_zoneref)) { + if (nr_online_nodes > 1 && zone != preferred_zone && + zone_to_nid(zone) != zone_to_nid(preferred_zone)) { goto failed; } @@ -5255,7 +5290,7 @@ unsigned long alloc_pages_bulk_noprof(gfp_t gfp, int preferred_nid, retry_this_zone: mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK) + nr_pages - nr_populated; if (zone_watermark_fast(zone, 0, mark, - zonelist_zone_idx(ac.preferred_zoneref), + zone_idx(preferred_zone), alloc_flags, gfp)) { break; } @@ -5277,6 +5312,10 @@ retry_this_zone: if (unlikely(!zone)) goto failed; + /* The zone was chosen from a zonelist that a rebuild may have changed. */ + if (unlikely(check_retry_zonelist(zonelist_iter_cookie))) + goto failed; + /* spin_trylock may fail due to a parallel drain or IRQ reentrancy. */ pcp = pcp_spin_trylock(zone->per_cpu_pageset); if (!pcp) @@ -5314,7 +5353,7 @@ retry_this_zone: pcp_spin_unlock(pcp); __count_zid_vm_events(PGALLOC, zone_idx(zone), nr_account); - zone_statistics(zonelist_zone(ac.preferred_zoneref), zone, nr_account); + zone_statistics(preferred_zone, zone, nr_account); out: return nr_populated; @@ -5417,6 +5456,7 @@ struct page *__alloc_frozen_pages_noprof(gfp_t gfp, unsigned int order, .alloc_flags = alloc_flags, }; unsigned int fastpath_alloc_flags = alloc_flags; + unsigned int zonelist_iter_cookie; /* Other flags could be supported later if needed. */ if (WARN_ON(alloc_flags & ~(ALLOC_NOLOCK | ALLOC_NO_CODETAG))) @@ -5446,6 +5486,7 @@ struct page *__alloc_frozen_pages_noprof(gfp_t gfp, unsigned int order, */ gfp = current_gfp_context(gfp); alloc_gfp = gfp; + zonelist_iter_cookie = zonelist_iter_sample(); if (!prepare_alloc_pages(gfp, order, preferred_nid, nodemask, &ac, &alloc_gfp, &fastpath_alloc_flags)) return NULL; @@ -5462,6 +5503,11 @@ struct page *__alloc_frozen_pages_noprof(gfp_t gfp, unsigned int order, /* First allocation attempt (or, for nolock, only attempt) */ page = get_page_from_freelist(alloc_gfp, order, fastpath_alloc_flags, &ac); + if (likely(page) && unlikely(check_retry_zonelist(zonelist_iter_cookie))) { + __free_frozen_pages(page, order, + alloc_flags & ALLOC_NOLOCK ? FPI_NOLOCK : 0); + page = NULL; + } if (likely(page) || (alloc_flags & ALLOC_NOLOCK)) goto out; @@ -5961,7 +6007,7 @@ int local_memory_node(int node) z = first_zones_zonelist(node_zonelist(node, GFP_KERNEL), gfp_zone(GFP_KERNEL), NULL); - return zonelist_node_idx(z); + return zone_to_nid(zonelist_zone(z)); } #endif @@ -6327,6 +6373,10 @@ void __meminit setup_zone_pageset(struct zone *zone) { int cpu; + /* The zone has been populated before, see zone_pcp_reset(). */ + if (zone->per_cpu_pageset != &boot_pageset) + return; + /* Size may be 0 on !SMP && !NUMA */ if (sizeof(struct per_cpu_zonestat) > 0) zone->per_cpu_zonestats = alloc_percpu(struct per_cpu_zonestat); @@ -6419,6 +6469,10 @@ void __init setup_per_cpu_pageset(void) __meminit void zone_pcp_init(struct zone *zone) { + /* This initialization only needs to be done once */ + if (zone->per_cpu_pageset) + return; + /* * per cpu subsystem is not up at this point. The following code * relies on the ability of the linker to provide the @@ -7344,9 +7398,13 @@ int alloc_contig_frozen_range_noprof(unsigned long start, unsigned long end, * put back to page allocator so that buddy can use them. */ + /* + * On failure this has undone its own isolation, and any other + * isolated blocks in the range belong to someone else, e.g. offline. + */ ret = start_isolate_page_range(start, end, mode); if (ret) - goto done; + return ret; drain_all_pages(cc.zone); @@ -7550,6 +7608,7 @@ struct page *alloc_contig_frozen_pages_noprof(unsigned long nr_pages, gfp_t gfp_mask, int nid, nodemask_t *nodemask) { unsigned long ret, pfn, flags; + unsigned int zonelist_cookie; struct zonelist *zonelist; struct zone *zone; struct zoneref *z; @@ -7558,8 +7617,13 @@ struct page *alloc_contig_frozen_pages_noprof(unsigned long nr_pages, retry: zonelist = node_zonelist(nid, gfp_mask); + zonelist_cookie = zonelist_iter_begin(); for_each_zone_zonelist_nodemask(zone, z, zonelist, gfp_zone(gfp_mask), nodemask) { + /* A rebuild may have shifted an ineligible zone into this slot. */ + if (unlikely(check_retry_zonelist(zonelist_cookie))) + goto retry; + spin_lock_irqsave(&zone->lock, flags); pfn = ALIGN(zone->zone_start_pfn, nr_pages); @@ -7594,6 +7658,9 @@ retry: * second pass, we will try moving HugeTLB pages when those pages are * smaller than the requested contiguous region size. */ + /* Redo a pass that a rebuild cut short before escalating. */ + if (unlikely(check_retry_zonelist(zonelist_cookie))) + goto retry; if (skip_hugetlb && skipped_hugetlb) { skip_hugetlb = false; goto retry; @@ -7699,6 +7766,12 @@ void zone_pcp_enable(struct zone *zone) mutex_unlock(&pcp_batch_high_lock); } +/* + * The zone has become empty. Its pagesets and zonestats are not freed: nothing + * keeps somebody who found the zone populated, such as refresh_cpu_vm_stats() + * or drain_all_pages(), from still using them. They are used again when the + * zone gets memory again. + */ void zone_pcp_reset(struct zone *zone) { int cpu; @@ -7709,12 +7782,6 @@ void zone_pcp_reset(struct zone *zone) pzstats = per_cpu_ptr(zone->per_cpu_zonestats, cpu); drain_zonestat(zone, pzstats); } - free_percpu(zone->per_cpu_pageset); - zone->per_cpu_pageset = &boot_pageset; - if (zone->per_cpu_zonestats != &boot_zonestats) { - free_percpu(zone->per_cpu_zonestats); - zone->per_cpu_zonestats = &boot_zonestats; - } } } diff --git a/mm/page_alloc.h b/mm/page_alloc.h index 7097ea1805f6..917653ae14a3 100644 --- a/mm/page_alloc.h +++ b/mm/page_alloc.h @@ -9,6 +9,7 @@ #include <linux/mm.h> #include <linux/mmzone.h> #include <linux/nodemask.h> +#include <linux/seqlock.h> #include <linux/types.h> #define ALLOC_DEFAULT 0 @@ -267,6 +268,24 @@ extern void zone_pcp_disable(struct zone *zone); extern void zone_pcp_enable(struct zone *zone); extern void zone_pcp_init(struct zone *zone); +extern seqlock_t zonelist_update_seq; + +static inline unsigned int zonelist_iter_begin(void) +{ + if (IS_ENABLED(CONFIG_MEMORY_HOTPLUG)) + return read_seqbegin(&zonelist_update_seq); + + return 0; +} + +static inline unsigned int check_retry_zonelist(unsigned int seq) +{ + if (IS_ENABLED(CONFIG_MEMORY_HOTPLUG)) + return read_seqretry(&zonelist_update_seq, seq); + + return 0; +} + enum fallback_result { /* Found suitable migratetype, *mt_out is valid. */ FALLBACK_FOUND, diff --git a/mm/page_frag_cache.c b/mm/page_frag_cache.c index e63efe78b7d4..8914437ddc51 100644 --- a/mm/page_frag_cache.c +++ b/mm/page_frag_cache.c @@ -119,15 +119,20 @@ refill: size = PAGE_SIZE << encoded_page_decode_order(encoded_page); offset = __ALIGN_KERNEL_MASK(nc->offset, ~align_mask); if (unlikely(offset + fragsz > size)) { - if (unlikely(fragsz > PAGE_SIZE)) { + if (unlikely(fragsz > size)) { /* - * The caller is trying to allocate a fragment - * with fragsz > PAGE_SIZE but the cache isn't big - * enough to satisfy the request, this may - * happen in low memory conditions. - * We don't release the cache page because - * it could make memory pressure worse - * so we simply return NULL here. + * The caller is trying to allocate a fragment that's + * larger than the whole cache page. + * + * Either fragsz is larger than PAGE_FRAG_CACHE_MAX_SIZE + * so this cannot ever succeed. + * + * Or the refill has fallen back to order-0 due to a low + * memory condition. Then we don't want to release the + * cache page to attempt a new large-size refill because + * it could make memory pressure worse. + * + * So in both cases we simply return NULL here. */ return NULL; } diff --git a/mm/page_isolation.c b/mm/page_isolation.c index 5aaad037384e..f4f0571607ab 100644 --- a/mm/page_isolation.c +++ b/mm/page_isolation.c @@ -75,6 +75,13 @@ bool page_is_unmovable(struct zone *zone, struct page *page, } /* + * Slab pages are frozen: do not take their reference count of zero + * for that of a free page. + */ + if (PageSlab(page)) + return true; + + /* * We can't use page_count without pin a page * because another CPU can free compound page. * This check already skips compound tails of THP diff --git a/mm/rmap.c b/mm/rmap.c index 0faef46806e5..65646ed6fc45 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 b8399bb71997..fa12479ef51d 100644 --- a/mm/shmem.c +++ b/mm/shmem.c @@ -3335,7 +3335,7 @@ static struct inode *__shmem_get_inode(const struct mnt_idmap *idmap, inode->i_size = 2 * BOGO_DIRENT_SIZE; inode->i_op = &shmem_dir_inode_operations; inode->i_fop = &simple_offset_dir_operations; - simple_offset_init(shmem_get_offset_ctx(inode)); + simple_offset_init(shmem_get_offset_ctx(inode), inode); break; case S_IFLNK: /* @@ -3703,15 +3703,8 @@ static void zero_pipe_buf_release(struct pipe_inode_info *pipe, { } -static bool zero_pipe_buf_try_steal(struct pipe_inode_info *pipe, - struct pipe_buffer *buf) -{ - return false; -} - static const struct pipe_buf_operations zero_pipe_buf_ops = { .release = zero_pipe_buf_release, - .try_steal = zero_pipe_buf_try_steal, .get = zero_pipe_buf_get, }; @@ -3744,7 +3737,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; @@ -3830,8 +3824,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/userfaultfd.c b/mm/userfaultfd.c index 169f681f9849..14fdbf217f00 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); @@ -1266,8 +1270,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); diff --git a/net/bluetooth/hci_conn.c b/net/bluetooth/hci_conn.c index b007f623b2ec..eebd73988bf6 100644 --- a/net/bluetooth/hci_conn.c +++ b/net/bluetooth/hci_conn.c @@ -327,8 +327,10 @@ static int hci_enhanced_setup_sync(struct hci_dev *hdev, void *data) cp.out_pcm_sample_payload_msb_pos = 0; cp.in_data_path = conn->codec.data_path; cp.out_data_path = conn->codec.data_path; - cp.in_transport_unit_size = 1; - cp.out_transport_unit_size = 1; + if (conn->codec.data_path) { + cp.in_transport_unit_size = 1; + cp.out_transport_unit_size = 1; + } break; case BT_CODEC_TRANSPARENT: @@ -353,8 +355,10 @@ static int hci_enhanced_setup_sync(struct hci_dev *hdev, void *data) cp.out_pcm_sample_payload_msb_pos = 0; cp.in_data_path = conn->codec.data_path; cp.out_data_path = conn->codec.data_path; - cp.in_transport_unit_size = 1; - cp.out_transport_unit_size = 1; + if (conn->codec.data_path) { + cp.in_transport_unit_size = 1; + cp.out_transport_unit_size = 1; + } break; case BT_CODEC_CVSD: @@ -384,8 +388,10 @@ static int hci_enhanced_setup_sync(struct hci_dev *hdev, void *data) cp.out_pcm_sample_payload_msb_pos = 0; cp.in_data_path = conn->codec.data_path; cp.out_data_path = conn->codec.data_path; - cp.in_transport_unit_size = 16; - cp.out_transport_unit_size = 16; + if (conn->codec.data_path) { + cp.in_transport_unit_size = 16; + cp.out_transport_unit_size = 16; + } break; default: goto unlock; diff --git a/net/bluetooth/hci_event.c b/net/bluetooth/hci_event.c index a52574003e4f..5e6b25eb5053 100644 --- a/net/bluetooth/hci_event.c +++ b/net/bluetooth/hci_event.c @@ -816,9 +816,7 @@ static u8 hci_cc_read_local_commands(struct hci_dev *hdev, void *data, if (rp->status) return rp->status; - if (hci_dev_test_flag(hdev, HCI_SETUP) || - hci_dev_test_flag(hdev, HCI_CONFIG)) - memcpy(hdev->commands, rp->commands, sizeof(hdev->commands)); + memcpy(hdev->commands, rp->commands, sizeof(hdev->commands)); return rp->status; } diff --git a/net/bluetooth/l2cap_core.c b/net/bluetooth/l2cap_core.c index 70ad30b091e4..7dcb0586a10b 100644 --- a/net/bluetooth/l2cap_core.c +++ b/net/bluetooth/l2cap_core.c @@ -144,24 +144,12 @@ static struct l2cap_chan *l2cap_get_chan_by_dcid(struct l2cap_conn *conn, return c; } -static struct l2cap_chan *__l2cap_get_chan_by_ident(struct l2cap_conn *conn, - u8 ident) - __must_hold(&conn->lock) -{ - struct l2cap_chan *c; - - list_for_each_entry(c, &conn->chan_l, list) { - if (c->ident == ident) - return c; - } - return NULL; -} - /* Our connection request has been sent and is still outstanding */ static bool l2cap_chan_connect_pending(struct l2cap_chan *chan) { return chan->state == BT_CONNECT && - test_bit(CONF_CONNECT_PEND, &chan->conf_state); + (test_bit(CONF_CONNECT_PEND, &chan->conf_state) || + test_bit(FLAG_LE_CONN_REQ_SENT, &chan->flags)); } /* Other channels may hold the same ident for a response they still have @@ -174,7 +162,7 @@ static struct l2cap_chan *__l2cap_get_connect_chan_by_ident(struct l2cap_conn *c struct l2cap_chan *c; list_for_each_entry(c, &conn->chan_l, list) { - if (c->ident == ident && l2cap_chan_connect_pending(c)) + if (l2cap_chan_connect_pending(c) && c->ident == ident) return c; } return NULL; @@ -3984,6 +3972,7 @@ void __l2cap_le_connect_rsp_defer(struct l2cap_chan *chan) l2cap_send_cmd(conn, chan->ident, L2CAP_LE_CONN_RSP, sizeof(rsp), &rsp); + chan->ident = 0; } static void l2cap_ecred_list_defer(struct l2cap_chan *chan, void *data) @@ -5073,7 +5062,7 @@ static int l2cap_le_connect_rsp(struct l2cap_conn *conn, BT_DBG("dcid 0x%4.4x mtu %u mps %u credits %u result 0x%2.2x", dcid, mtu, mps, credits, result); - chan = __l2cap_get_chan_by_ident(conn, cmd->ident); + chan = __l2cap_get_connect_chan_by_ident(conn, cmd->ident); if (!chan) return -EBADSLT; @@ -5323,10 +5312,10 @@ static int l2cap_le_connect_req(struct l2cap_conn *conn, __set_chan_timer(chan, chan->ops->get_sndtimeo(chan)); - chan->ident = cmd->ident; chan->mode = L2CAP_MODE_LE_FLOWCTL; if (test_bit(FLAG_DEFER_SETUP, &chan->flags)) { + chan->ident = cmd->ident; l2cap_state_change(chan, BT_CONNECT2); /* The following result value is actually not defined * for LE CoC but we use it to let the function know @@ -5562,10 +5551,10 @@ static inline int l2cap_ecred_conn_req(struct l2cap_conn *conn, __set_chan_timer(chan, chan->ops->get_sndtimeo(chan)); - chan->ident = cmd->ident; chan->mode = L2CAP_MODE_EXT_FLOWCTL; if (test_bit(FLAG_DEFER_SETUP, &chan->flags)) { + chan->ident = cmd->ident; l2cap_state_change(chan, BT_CONNECT2); defer = true; chan->ops->defer(chan); @@ -5621,9 +5610,10 @@ static inline int l2cap_ecred_conn_rsp(struct l2cap_conn *conn, struct l2cap_chan *orig; u16 dcid; - if (chan->ident != cmd->ident || + if (chan->state != BT_CONNECT || chan->mode != L2CAP_MODE_EXT_FLOWCTL || - chan->state == BT_CONNECTED) + !test_bit(FLAG_ECRED_CONN_REQ_SENT, &chan->flags) || + chan->ident != cmd->ident) continue; l2cap_chan_hold(chan); @@ -5842,16 +5832,9 @@ static inline int l2cap_ecred_reconf_rsp(struct l2cap_conn *conn, BT_DBG("result 0x%4.4x", result); - if (!result) { - list_for_each_entry(chan, &conn->chan_l, list) { - if (chan->ident == cmd->ident) - chan->ident = 0; - } - return 0; - } - list_for_each_entry_safe(chan, tmp, &conn->chan_l, list) { - if (chan->ident != cmd->ident) + /* Reconfiguration updates ident with only chan->lock held. */ + if (data_race(READ_ONCE(chan->ident)) != cmd->ident) continue; if (!l2cap_chan_hold_unless_zero(chan)) @@ -5860,7 +5843,15 @@ static inline int l2cap_ecred_reconf_rsp(struct l2cap_conn *conn, lockdep_assert_held(&chan->conn->lock); - l2cap_chan_del(chan, ECONNRESET); + if (chan->ident == cmd->ident && + test_and_clear_bit(FLAG_ECRED_RECONF_REQ_SENT, &chan->flags)) { + if (result) { + l2cap_chan_del(chan, ECONNRESET); + chan->ops->close(chan); + } else { + chan->ident = 0; + } + } l2cap_chan_unlock(chan); l2cap_chan_put(chan); @@ -5875,26 +5866,35 @@ static inline int l2cap_le_command_rej(struct l2cap_conn *conn, __must_hold(&conn->lock) { struct l2cap_cmd_rej_unk *rej = (struct l2cap_cmd_rej_unk *) data; - struct l2cap_chan *chan; + struct l2cap_chan *chan, *tmp; if (cmd_len < sizeof(*rej)) return -EPROTO; - chan = __l2cap_get_chan_by_ident(conn, cmd->ident); - if (!chan) - goto done; + list_for_each_entry_safe(chan, tmp, &conn->chan_l, list) { + /* Reconfiguration updates ident with only chan->lock held. */ + if (data_race(READ_ONCE(chan->ident)) != cmd->ident) + continue; - chan = l2cap_chan_hold_unless_zero(chan); - if (!chan) - goto done; + if (!l2cap_chan_hold_unless_zero(chan)) + continue; - l2cap_chan_lock(chan); - lockdep_assert_held(&chan->conn->lock); - l2cap_chan_del(chan, ECONNREFUSED); - l2cap_chan_unlock(chan); - l2cap_chan_put(chan); + l2cap_chan_lock(chan); + lockdep_assert_held(&chan->conn->lock); + + if (chan->ident == cmd->ident && + ((chan->state == BT_CONNECT && + (test_bit(FLAG_LE_CONN_REQ_SENT, &chan->flags) || + test_bit(FLAG_ECRED_CONN_REQ_SENT, &chan->flags))) || + test_bit(FLAG_ECRED_RECONF_REQ_SENT, &chan->flags))) { + l2cap_chan_del(chan, ECONNREFUSED); + chan->ops->close(chan); + } + + l2cap_chan_unlock(chan); + l2cap_chan_put(chan); + } -done: return 0; } @@ -7765,6 +7765,7 @@ static void l2cap_ecred_reconfigure(struct l2cap_chan *chan) pdu->scid[0] = cpu_to_le16(chan->scid); chan->ident = l2cap_get_ident(conn); + set_bit(FLAG_ECRED_RECONF_REQ_SENT, &chan->flags); l2cap_send_cmd(conn, chan->ident, L2CAP_ECRED_RECONF_REQ, struct_size(pdu, scid, 1), pdu); diff --git a/net/bluetooth/l2cap_sock.c b/net/bluetooth/l2cap_sock.c index 7a2551ef7f50..e5c15c083c1a 100644 --- a/net/bluetooth/l2cap_sock.c +++ b/net/bluetooth/l2cap_sock.c @@ -1332,7 +1332,8 @@ static int l2cap_sock_recvmsg(struct socket *sock, struct msghdr *msg, * available. This avoids resending large numbers of * frames. */ - if (test_bit(CONN_LOCAL_BUSY, &pi->chan->conn_state) && + if (sk->sk_state == BT_CONNECTED && + test_bit(CONN_LOCAL_BUSY, &pi->chan->conn_state) && atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf >> 1) l2cap_chan_busy(pi->chan, 0); diff --git a/net/bridge/br_arp_nd_proxy.c b/net/bridge/br_arp_nd_proxy.c index 2123344a5677..f306cfbc1679 100644 --- a/net/bridge/br_arp_nd_proxy.c +++ b/net/bridge/br_arp_nd_proxy.c @@ -279,6 +279,7 @@ static void br_nd_send(struct net_bridge *br, struct net_bridge_port *p, struct sk_buff *reply; struct ipv6hdr *pip6; int na_olen = 8; /* opt hdr + ETH_ALEN for target */ + int headroom; int ns_olen; u8 *daddr; bool dad; @@ -288,7 +289,8 @@ static void br_nd_send(struct net_bridge *br, struct net_bridge_port *p, if (!dev) return; - len = LL_RESERVED_SPACE(dev) + sizeof(struct ipv6hdr) + + headroom = LL_RESERVED_SPACE(dev); + len = headroom + sizeof(struct ipv6hdr) + sizeof(*na) + na_olen + dev->needed_tailroom; reply = alloc_skb(len, GFP_ATOMIC); @@ -297,7 +299,7 @@ static void br_nd_send(struct net_bridge *br, struct net_bridge_port *p, reply->protocol = htons(ETH_P_IPV6); reply->dev = dev; - skb_reserve(reply, LL_RESERVED_SPACE(dev)); + skb_reserve(reply, headroom); skb_push(reply, sizeof(struct ethhdr)); skb_set_mac_header(reply, 0); diff --git a/net/bridge/netfilter/nf_conntrack_bridge.c b/net/bridge/netfilter/nf_conntrack_bridge.c index b5444335b86f..8c83dc05114b 100644 --- a/net/bridge/netfilter/nf_conntrack_bridge.c +++ b/net/bridge/netfilter/nf_conntrack_bridge.c @@ -358,7 +358,7 @@ nf_ct_bridge_refrag(struct sk_buff *skb, const struct nf_hook_state *state, nf_br_ip6_fragment(state->net, state->sk, skb, &data, output); break; default: - WARN_ON_ONCE(1); + DEBUG_NET_WARN_ON_ONCE(1); return NF_DROP; } diff --git a/net/core/dev.c b/net/core/dev.c index df1a840b0334..3c58db732761 100644 --- a/net/core/dev.c +++ b/net/core/dev.c @@ -4207,6 +4207,18 @@ static struct sk_buff *validate_xmit_skb(struct sk_buff *skb, struct net_device if (unlikely(!skb)) goto out_null; + /* Only fraglist GSO, whose segments already carry valid checksums, + * can be handed to a device as CHECKSUM_UNNECESSARY. Any other GSO + * skb has no csum_start for the device to segment from. NONE means + * the same on transmit, but makes netif_needs_gso() send it to the + * GSO code, which turns TCP into CHECKSUM_PARTIAL for TSO and + * segments anything the device cannot offload in software. + */ + if (unlikely(skb->ip_summed == CHECKSUM_UNNECESSARY && + skb_is_gso(skb) && + !(skb_shinfo(skb)->gso_type & SKB_GSO_FRAGLIST))) + skb->ip_summed = CHECKSUM_NONE; + features = netif_skb_features(skb); skb = validate_xmit_vlan(skb, features); if (unlikely(!skb)) @@ -11101,6 +11113,14 @@ atomic_t dev_unreg_count = ATOMIC_INIT(0); static void net_set_todo(struct net_device *dev) { list_add_tail(&dev->todo_list, &net_todo_list); + atomic_inc(&dev_net(dev)->dev_unreg_pending); +} + +/* Paired with net_set_todo(). @net must not be used after this call. */ +static void net_unreg_done(struct net *net) +{ + if (atomic_dec_and_test(&net->dev_unreg_pending)) + wake_up(&netdev_unregistering_wq); } static netdev_features_t netdev_sync_upper_features(struct net_device *lower, @@ -12000,6 +12020,7 @@ void netdev_run_todo(void) if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) { netdev_WARN(dev, "run_todo but not unregistering\n"); list_del(&dev->todo_list); + net_unreg_done(dev_net(dev)); continue; } @@ -12016,8 +12037,11 @@ void netdev_run_todo(void) cnt = 0; while (!list_empty(&list)) { + struct net *net; + dev = netdev_wait_allrefs_any(&list); list_del(&dev->todo_list); + net = dev_net(dev); /* paranoia */ BUG_ON(netdev_refcnt_read(dev) != 1); @@ -12038,6 +12062,8 @@ void netdev_run_todo(void) /* Free network device */ kobject_put(&dev->dev.kobj); + + net_unreg_done(net); } if (cnt && atomic_sub_and_test(cnt, &dev_unreg_count)) wake_up(&netdev_unregistering_wq); @@ -13486,6 +13512,17 @@ static void __net_exit default_device_exit_net(struct net *net) } } +static bool __net_exit netns_dev_unreg_pending(const struct list_head *net_list) +{ + struct net *net; + + list_for_each_entry(net, net_list, exit_list) { + if (atomic_read(&net->dev_unreg_pending)) + return true; + } + return false; +} + static void __net_exit default_device_exit_batch(struct list_head *net_list) { /* At exit all network devices most be removed from a network @@ -13527,6 +13564,16 @@ static void __net_exit default_device_exit_batch(struct list_head *net_list) unregister_netdevice_many(&dev_kill_list); rtnl_unlock(); + /* Devices of these netns unregistered from another context + * (e.g. a veth whose peer was deleted) can still be waiting + * in netdev_run_todo() for their last references, while + * NETDEV_UNREGISTER is rebroadcast for them. Wait for them + * before pernet exit handlers tear down the state used by + * netdevice notifiers, and before the netns is freed. + * No new unregistration can start: all devices are unlisted. + */ + wait_event(netdev_unregistering_wq, !netns_dev_unreg_pending(net_list)); + rtnl_net_flush_workqueue(); } diff --git a/net/core/filter.c b/net/core/filter.c index ca204d3e9ddc..946b07a17fce 100644 --- a/net/core/filter.c +++ b/net/core/filter.c @@ -5652,11 +5652,12 @@ static int bpf_sol_tcp_setsockopt(struct sock *sk, int optname, case TCP_BPF_IW: if (val <= 0 || tp->data_segs_out > tp->syn_data) return -EINVAL; - tcp_snd_cwnd_set(tp, val); + tcp_snd_cwnd_set(tp, min_t(u32, val, tp->snd_cwnd_clamp)); break; case TCP_BPF_SNDCWND_CLAMP: if (val <= 0) return -EINVAL; + val = min_t(u32, val, TCP_MAX_SND_CWND); tp->snd_cwnd_clamp = val; WRITE_ONCE(tp->snd_ssthresh, val); break; @@ -6187,7 +6188,7 @@ static int bpf_sock_ops_get_syn(struct bpf_sock_ops_kern *bpf_sock, * not be available. It has to resort to * saved_syn (if it is saved). */ - saved_syn = inet_reqsk(sk)->saved_syn; + saved_syn = rcu_dereference(inet_reqsk(sk)->saved_syn); else saved_syn = tcp_sk(sk)->saved_syn; diff --git a/net/core/gro.c b/net/core/gro.c index 1b033855a20d..1241b23d66ef 100644 --- a/net/core/gro.c +++ b/net/core/gro.c @@ -238,6 +238,14 @@ int skb_gro_receive_list(struct sk_buff *p, struct sk_buff *skb) NAPI_GRO_CB(skb)->flush)) return -E2BIG; + /* Fraglist members keep their own headers. Their checksum can not + * be right both for a forwarded packet and for a decapsulated one, + * if remote checksum offload adjusted it. + */ + if (unlikely(skb->remcsum_offload)) + return -EINVAL; + + skb_gro_frag0_invalidate(skb); if (!pskb_may_pull(skb, skb_gro_offset(skb))) { NAPI_GRO_CB(skb)->flush = 1; return -ENOMEM; @@ -374,6 +382,7 @@ static void gro_list_prepare(const struct list_head *head, } diffs = (unsigned long)p->dev ^ (unsigned long)skb->dev; + diffs |= p->protocol != skb->protocol; diffs |= p->vlan_all ^ skb->vlan_all; diffs |= skb_metadata_differs(p, skb); if (maclen == ETH_HLEN) @@ -413,7 +422,8 @@ static inline void skb_gro_reset_offset(struct sk_buff *skb, u32 nhoff) headlen = skb_headlen(skb); NAPI_GRO_CB(skb)->frag0 = skb->data; NAPI_GRO_CB(skb)->frag0_len = headlen; - if (headlen) + /* Shared fragments must be pulled into the linear head before parsing. */ + if (headlen || skb_has_shared_frag(skb)) return; pinfo = skb_shinfo(skb); @@ -450,12 +460,19 @@ static void gro_pull_from_frag0(struct sk_buff *skb, int grow) } } -static void gro_try_pull_from_frag0(struct sk_buff *skb) +static bool gro_try_pull_from_frag0(struct sk_buff *skb) { int grow = skb_gro_offset(skb) - skb_headlen(skb); - if (grow > 0) + if (grow <= 0) + return true; + + /* frag0 can only be used if no pull happened. */ + if (likely(NAPI_GRO_CB(skb)->frag0_len)) { gro_pull_from_frag0(skb, grow); + return true; + } + return pskb_may_pull(skb, skb_gro_offset(skb)); } static void gro_flush_oldest(struct gro_node *gro, struct list_head *head) @@ -557,13 +574,17 @@ found_ptype: if (NAPI_GRO_CB(skb)->flush) goto normal; + /* Must be called before setting NAPI_GRO_CB(skb)->{age|last}. + * A held packet must have its headers in the linear part. + */ + if (unlikely(!gro_try_pull_from_frag0(skb))) + goto normal; + if (unlikely(gro_list->count >= MAX_GRO_SKBS)) gro_flush_oldest(gro, &gro_list->list); else gro_list->count++; - /* Must be called before setting NAPI_GRO_CB(skb)->{age|last} */ - gro_try_pull_from_frag0(skb); NAPI_GRO_CB(skb)->age = jiffies; NAPI_GRO_CB(skb)->last = skb; if (!skb_is_gso(skb)) diff --git a/net/core/net_namespace.c b/net/core/net_namespace.c index 52c2bd44778a..217021eeab13 100644 --- a/net/core/net_namespace.c +++ b/net/core/net_namespace.c @@ -270,14 +270,19 @@ static void ops_undo_single(struct pernet_operations *ops, /* should be called with nsid_lock held */ static int alloc_netid(struct net *net, struct net *peer, int reqid) { - int min = 0, max = 0; + int ret; + u32 id; if (reqid >= 0) { - min = reqid; - max = reqid + 1; + id = reqid; + ret = idr_alloc_u32(&net->netns_ids, peer, &id, id, + GFP_ATOMIC); + if (ret) + return ret; + return id; } - return idr_alloc(&net->netns_ids, peer, min, max, GFP_ATOMIC); + return idr_alloc(&net->netns_ids, peer, 0, 0, GFP_ATOMIC); } /* This function is used by idr_for_each(). If net is equal to peer, the @@ -437,7 +442,7 @@ static __net_init int setup_net(struct net *net) LIST_HEAD(net_exit_list); int error = 0; - net->net_cookie = ns_tree_gen_id(net); + net->net_cookie = to_ns_common(net)->ns_id; list_for_each_entry(ops, &pernet_list, list) { error = ops_init(ops, net); @@ -449,7 +454,7 @@ static __net_init int setup_net(struct net *net) up_write(&net_rwsem); /* Without CONFIG_NET_NS init_net isn't exposed as a namespace. */ if (IS_ENABLED(CONFIG_NET_NS)) - ns_tree_add_raw(net); + ns_tree_add(net); out: return error; @@ -639,10 +644,10 @@ static void unhash_nsid(struct net *last) * use for_each_net_rcu() or net_rwsem. */ for_each_net(tmp) { - int id = 0; + unsigned long id = 0; spin_lock(&tmp->nsid_lock); - while ((peer = idr_get_next(&tmp->netns_ids, &id))) { + while ((peer = idr_get_next_ul(&tmp->netns_ids, &id))) { int curr_id = id; id++; diff --git a/net/core/skbuff.c b/net/core/skbuff.c index 8da53d5b76fc..1ac1e327ac4c 100644 --- a/net/core/skbuff.c +++ b/net/core/skbuff.c @@ -967,6 +967,7 @@ int skb_pp_cow_data(struct page_pool *pool, struct sk_buff **pskb, skb_reserve(nskb, headroom); skb_copy_header(nskb, skb); + nskb->mac_len = skb->mac_len; skb_mark_for_recycle(nskb); err = skb_copy_bits(skb, 0, nskb->data, size); @@ -1495,6 +1496,10 @@ void napi_skb_free_stolen_head(struct sk_buff *skb) skb_orphan(skb); skb->slow_gro = 0; } + if (skb->fclone != SKB_FCLONE_UNAVAILABLE) { + kfree_skbmem(skb); + return; + } napi_skb_cache_put(skb); } @@ -1908,6 +1913,7 @@ int skb_zerocopy_iter_stream(struct sock *sk, struct sk_buff *skb, struct ubuf_info *uarg, struct net_devmem_dmabuf_binding *binding) { + unsigned int orig_truesize = skb->truesize; int err, orig_len = skb->len; if (uarg->ops->link_skb) { @@ -1928,12 +1934,18 @@ int skb_zerocopy_iter_stream(struct sock *sk, struct sk_buff *skb, err = __zerocopy_sg_from_iter(msg, sk, skb, &msg->msg_iter, len, binding); if (err == -EFAULT || (err == -EMSGSIZE && skb->len == orig_len)) { + u32 delta_truesize = skb->truesize - orig_truesize; struct sock *save_sk = skb->sk; /* Streams do not free skb on error. Reset to prev state. */ iov_iter_revert(&msg->msg_iter, skb->len - orig_len); skb->sk = sk; - ___pskb_trim(skb, orig_len); + if (!___pskb_trim(skb, orig_len)) { + skb->truesize -= delta_truesize; + sk_wmem_queued_add(sk, -delta_truesize); + if (!skb_zcopy_pure(skb)) + sk_mem_uncharge(sk, delta_truesize); + } skb->sk = save_sk; return err; } @@ -3281,7 +3293,7 @@ int skb_splice_bits(struct sk_buff *skb, struct sock *sk, unsigned int offset, .pages = pages, .partial = partial, .nr_pages_max = MAX_SKB_FRAGS, - .ops = &nosteal_pipe_buf_ops, + .ops = &default_pipe_buf_ops, .spd_release = sock_spd_release, }; int ret = 0; @@ -6263,7 +6275,7 @@ void kfree_skb_partial(struct sk_buff *skb, bool head_stolen) { if (head_stolen) { skb_release_head_state(skb); - kmem_cache_free(net_hotdata.skbuff_cache, skb); + kfree_skbmem(skb); } else { __kfree_skb(skb); } @@ -6379,6 +6391,31 @@ bool skb_try_coalesce(struct sk_buff *to, struct sk_buff *from, } EXPORT_SYMBOL(skb_try_coalesce); +static void skb_ext_scrub(struct sk_buff *skb) +{ +#if IS_ENABLED(CONFIG_INET_PSP) + struct psp_skb_ext *pse = skb_ext_find(skb, SKB_EXT_PSP); + + if (pse) { + struct skb_ext *ext = skb->extensions; + struct psp_skb_ext tmp; + + /* Nothing else to scrub if PSP is the only extension in ext. */ + if (ext->chunks == SKB_EXT_CHUNKSIZEOF(*ext) + + skb_ext_type_len[SKB_EXT_PSP]) + return; + + tmp = *pse; + skb_ext_reset(skb); + pse = skb_ext_add(skb, SKB_EXT_PSP); + if (pse) + memcpy(pse, &tmp, sizeof(*pse)); + return; + } +#endif + skb_ext_reset(skb); +} + /** * skb_scrub_packet - scrub an skb * @@ -6390,7 +6427,8 @@ EXPORT_SYMBOL(skb_try_coalesce); * operations. * skb_scrub_packet can also be used to clean a skb before injecting it in * another namespace (@xnet == true). We have to clear all information in the - * skb that could impact namespace isolation. + * skb that could impact namespace isolation. Note that PSP skb extension is + * preserved across packet scrubbing by design. */ void skb_scrub_packet(struct sk_buff *skb, bool xnet) { @@ -6398,7 +6436,7 @@ void skb_scrub_packet(struct sk_buff *skb, bool xnet) skb->skb_iif = 0; skb->ignore_df = 0; skb_dst_drop(skb); - skb_ext_reset(skb); + skb_ext_scrub(skb); nf_reset_ct(skb); nf_reset_trace(skb); diff --git a/net/core/sock.c b/net/core/sock.c index e2401d735c5a..ad414878dc5b 100644 --- a/net/core/sock.c +++ b/net/core/sock.c @@ -3427,7 +3427,7 @@ int __sk_mem_raise_allocated(struct sock *sk, int size, int amt, int kind) goto suppress_allocation; } - if (!allocated) + if (sk->sk_bypass_prot_mem) return 1; /* Under limit. */ @@ -3508,7 +3508,7 @@ suppress_allocation: trace_sock_exceed_buf_limit(sk, prot, allocated, kind); - if (allocated) + if (!sk->sk_bypass_prot_mem) sk_memory_allocated_sub(sk, amt); if (charged) diff --git a/net/core/sock_reuseport.c b/net/core/sock_reuseport.c index fccbdd0430b0..b9e5648fa4c5 100644 --- a/net/core/sock_reuseport.c +++ b/net/core/sock_reuseport.c @@ -6,6 +6,7 @@ * selecting the socket index from the array of available sockets. */ +#include <net/inet_connection_sock.h> #include <net/ip.h> #include <net/sock_reuseport.h> #include <linux/bpf.h> @@ -692,6 +693,14 @@ int reuseport_attach_prog(struct sock *sk, struct bpf_prog *prog) if (!sk->sk_reuseport) return -EINVAL; + /* Do not put a shutdown()ed TCP listener back into the + * listening section of a reuseport group while it is in + * TCP_CLOSE: requests can still migrate to it. + */ + if (sk_is_tcp(sk) && + inet_csk(sk)->unhashed_state == TCP_LISTEN) + return -EINVAL; + err = reuseport_alloc(sk, false); if (err) return err; diff --git a/net/ipv4/af_inet.c b/net/ipv4/af_inet.c index 7677b0343abd..8822bae439f8 100644 --- a/net/ipv4/af_inet.c +++ b/net/ipv4/af_inet.c @@ -629,7 +629,7 @@ static long inet_wait_for_connect(struct sock *sk, long timeo, int writebias) * TCP 'magic' in here. */ int __inet_stream_connect(struct socket *sock, struct sockaddr_unsized *uaddr, - int addr_len, int flags, int is_sendmsg) + int addr_len, int flags, bool defer_connect) { struct sock *sk = sock->sk; int err; @@ -664,8 +664,10 @@ int __inet_stream_connect(struct socket *sock, struct sockaddr_unsized *uaddr, err = -EISCONN; goto out; case SS_CONNECTING: - if (inet_test_bit(DEFER_CONNECT, sk)) - err = is_sendmsg ? -EINPROGRESS : -EISCONN; + if (defer_connect) + err = -EINPROGRESS; + else if (inet_test_bit(DEFER_CONNECT, sk)) + err = -EISCONN; else err = -EALREADY; /* Fall out of switch with err, set for this state */ @@ -752,7 +754,7 @@ int inet_stream_connect(struct socket *sock, struct sockaddr_unsized *uaddr, int err; lock_sock(sock->sk); - err = __inet_stream_connect(sock, uaddr, addr_len, flags, 0); + err = __inet_stream_connect(sock, uaddr, addr_len, flags, false); release_sock(sock->sk); return err; } diff --git a/net/ipv4/cipso_ipv4.c b/net/ipv4/cipso_ipv4.c index e65a3f29d2ca..ee0c72fbc877 100644 --- a/net/ipv4/cipso_ipv4.c +++ b/net/ipv4/cipso_ipv4.c @@ -2004,11 +2004,16 @@ static int cipso_v4_delopt(struct ip_options_rcu __rcu **opt_ptr) if (!opt || opt->opt.cipso == 0) return 0; if (opt->opt.srr || opt->opt.rr || opt->opt.ts || opt->opt.router_alert) { + struct ip_options_rcu *old_opt = opt; u8 cipso_len; u8 cipso_off; unsigned char *cipso_ptr; int optlen_new; + /* ip_options_rcu must not be modified in place, use a copy */ + opt = kmemdup(opt, sizeof(*opt) + opt->opt.optlen, GFP_ATOMIC); + if (!opt) + return -ENOMEM; cipso_off = opt->opt.cipso - sizeof(struct iphdr); cipso_ptr = &opt->opt.__data[cipso_off]; cipso_len = cipso_ptr[1]; @@ -2036,6 +2041,8 @@ static int cipso_v4_delopt(struct ip_options_rcu __rcu **opt_ptr) memset(&opt->opt.__data[optlen_new], IPOPT_END, opt->opt.optlen - optlen_new); + rcu_assign_pointer(*opt_ptr, opt); + kfree_rcu(old_opt, rcu); } else { /* only the cipso option was present on the socket so we can * remove the entire option struct */ @@ -2055,7 +2062,7 @@ static int cipso_v4_delopt(struct ip_options_rcu __rcu **opt_ptr) * Removes the CIPSO option from a socket, if present. * */ -void cipso_v4_sock_delattr(struct sock *sk) +int cipso_v4_sock_delattr(struct sock *sk) { struct inet_sock *sk_inet; int hdr_delta; @@ -2068,6 +2075,7 @@ void cipso_v4_sock_delattr(struct sock *sk) sk_conn->icsk_ext_hdr_len -= hdr_delta; sk_conn->icsk_sync_mss(sk, sk_conn->icsk_pmtu_cookie); } + return (hdr_delta < 0) ? hdr_delta : 0; } /** @@ -2078,9 +2086,11 @@ void cipso_v4_sock_delattr(struct sock *sk) * Removes the CIPSO option from a request socket, if present. * */ -void cipso_v4_req_delattr(struct request_sock *req) +int cipso_v4_req_delattr(struct request_sock *req) { - cipso_v4_delopt(&inet_rsk(req)->ireq_opt); + int hdr_delta = cipso_v4_delopt(&inet_rsk(req)->ireq_opt); + + return (hdr_delta < 0) ? hdr_delta : 0; } /** diff --git a/net/ipv4/esp4_offload.c b/net/ipv4/esp4_offload.c index abd77162f5e7..2309468cfc3d 100644 --- a/net/ipv4/esp4_offload.c +++ b/net/ipv4/esp4_offload.c @@ -37,6 +37,7 @@ static struct sk_buff *esp4_gro_receive(struct list_head *head, __be32 seq; __be32 spi; + skb_gro_frag0_invalidate(skb); if (!pskb_pull(skb, offset)) return NULL; diff --git a/net/ipv4/fib_trie.c b/net/ipv4/fib_trie.c index be1e40780ad7..394df1de1281 100644 --- a/net/ipv4/fib_trie.c +++ b/net/ipv4/fib_trie.c @@ -61,6 +61,7 @@ #include <linux/export.h> #include <linux/vmalloc.h> #include <linux/notifier.h> +#include <linux/nospec.h> #include <net/net_namespace.h> #include <net/inet_dscp.h> #include <net/ip.h> @@ -961,6 +962,8 @@ static struct key_vector *fib_find_node(struct trie *t, break; } + index = array_index_nospec(index, 1ul << n->bits); + /* keep searching until we find a perfect match leaf or NULL */ } while (IS_TNODE(n)); @@ -1467,6 +1470,8 @@ int fib_table_lookup(struct fib_table *tb, const struct flowi4 *flp, if (IS_LEAF(n)) goto found; + index = array_index_nospec(index, 1ul << n->bits); + /* only record pn and cindex if we are going to be chopping * bits later. Otherwise we are just wasting cycles. */ @@ -1770,6 +1775,8 @@ static struct key_vector *leaf_walk_rcu(struct key_vector **tn, t_key key) if (cindex >> pn->bits) break; + cindex = array_index_nospec(cindex, 1ul << pn->bits); + /* descend into the next child */ n = get_child_rcu(pn, cindex++); if (!n) @@ -1791,6 +1798,8 @@ static struct key_vector *leaf_walk_rcu(struct key_vector **tn, t_key key) continue; } + cindex = array_index_nospec(cindex, 1ul << pn->bits); + /* grab the next available node */ n = get_child_rcu(pn, cindex++); if (!n) @@ -2437,7 +2446,10 @@ static struct key_vector *fib_trie_get_next(struct fib_trie_iter *iter) while (!IS_TRIE(pn)) { while (cindex < child_length(pn)) { - struct key_vector *n = get_child_rcu(pn, cindex++); + struct key_vector *n; + + cindex = array_index_nospec(cindex, child_length(pn)); + n = get_child_rcu(pn, cindex++); if (!n) continue; diff --git a/net/ipv4/fou_core.c b/net/ipv4/fou_core.c index 076fdca44f51..5c3c8f55d057 100644 --- a/net/ipv4/fou_core.c +++ b/net/ipv4/fou_core.c @@ -364,6 +364,18 @@ static struct sk_buff *gue_gro_receive(struct sock *sk, default: goto out; } + + /* Match the encapsulation format and IP version. */ + list_for_each_entry(p, head, list) { + const struct iphdr *iph2; + + if (!NAPI_GRO_CB(p)->same_flow) + continue; + + iph2 = (const struct iphdr *)(p->data + off); + if (iph2->version != ((struct iphdr *)guehdr)->version) + NAPI_GRO_CB(p)->same_flow = 0; + } goto next_proto; default: goto out; diff --git a/net/ipv4/igmp.c b/net/ipv4/igmp.c index 144fca158adc..52cde8782eeb 100644 --- a/net/ipv4/igmp.c +++ b/net/ipv4/igmp.c @@ -2463,6 +2463,8 @@ int ip_mc_leave_group(struct sock *sk, struct ip_mreqn *imr) iml->multi.imr_address.s_addr) continue; + /* The drop request may not resolve to the joined device. */ + in_dev = inetdev_by_index(net, iml->multi.imr_ifindex); (void) ip_mc_leave_src(sk, iml, in_dev); *imlp = iml->next_rcu; diff --git a/net/ipv4/inet_connection_sock.c b/net/ipv4/inet_connection_sock.c index e56beec43877..6c079929e06f 100644 --- a/net/ipv4/inet_connection_sock.c +++ b/net/ipv4/inet_connection_sock.c @@ -683,7 +683,7 @@ struct sock *inet_csk_accept(struct sock *sk, struct proto_accept_arg *arg) newsk = req->sk; if (sk->sk_protocol == IPPROTO_TCP && - tcp_rsk(req)->tfo_listener) { + tcp_sk(newsk)->syn_fastopen_child) { spin_lock_bh(&queue->fastopenq.lock); if (tcp_rsk(req)->tfo_listener) { /* We are still waiting for the final ACK from 3WHS @@ -869,7 +869,7 @@ reqsk_alloc_noprof(const struct request_sock_ops *ops, struct sock *sk_listener, req_to_sk(req)->sk_prot = sk_listener->sk_prot; sk_node_init(&req_to_sk(req)->sk_node); sk_tx_queue_clear(req_to_sk(req)); - req->saved_syn = NULL; + RCU_INIT_POINTER(req->saved_syn, NULL); req->syncookie = 0; req->num_timeout = 0; req->num_retrans = 0; @@ -908,7 +908,7 @@ void __reqsk_free(struct request_sock *req) req->rsk_ops->destructor(req); if (req->rsk_listener) sock_put(req->rsk_listener); - kfree(req->saved_syn); + kfree_rcu(unrcu_pointer(req->saved_syn), rcu); kmem_cache_free(req->rsk_ops->slab, req); } @@ -979,7 +979,7 @@ static void reqsk_queue_migrated(struct request_sock_queue *queue, static void reqsk_migrate_reset(struct request_sock *req) { - req->saved_syn = NULL; + RCU_INIT_POINTER(req->saved_syn, NULL); #if IS_ENABLED(CONFIG_IPV6) inet_rsk(req)->ipv6_opt = NULL; inet_rsk(req)->pktopts = NULL; diff --git a/net/ipv4/inet_fragment.c b/net/ipv4/inet_fragment.c index 0b8d22ffafca..f330d0a39823 100644 --- a/net/ipv4/inet_fragment.c +++ b/net/ipv4/inet_fragment.c @@ -17,6 +17,7 @@ #include <linux/rtnetlink.h> #include <linux/slab.h> #include <linux/rhashtable.h> +#include <linux/sizes.h> #include <net/sock.h> #include <net/inet_frag.h> @@ -519,6 +520,43 @@ int inet_frag_queue_insert(struct inet_frag_queue *q, struct sk_buff *skb, } EXPORT_SYMBOL(inet_frag_queue_insert); +/* When a socket owned fragment completes a queue, the truesize of all + * other fragments is charged to its sk_wmem_alloc, although they were + * orphaned when queued and possibly sent by someone else. + * Bound this like ip_append_data() bounds the memory a socket can + * allocate (2 * sk_sndbuf), plus slack for fragments inflated by a + * refragmentation using a small MTU. Otherwise, several reassembled skbs + * alive at the same time can saturate sk_wmem_alloc, and leak the socket. + * + * Several queues can complete at the same time for the same socket, + * and some sockets (tun) use sk_sndbuf = INT_MAX. The charge is reserved + * with a cmpxchg() loop, a refcount_t has no helper for this. + */ +#define INET_FRAG_WMEM_SLACK SZ_4M + +static bool inet_frag_wmem_reserve(struct sock *sk, unsigned int charge) +{ + u64 limit = 2ULL * READ_ONCE(sk->sk_sndbuf) + INET_FRAG_WMEM_SLACK; + int old = refcount_read(&sk->sk_wmem_alloc); + + limit = min_t(u64, limit, INET_FRAG_MAX_TRUESIZE); + do { + if (old <= 0 || (u64)old + charge > limit) + return false; + } while (!atomic_try_cmpxchg(&sk->sk_wmem_alloc.refs, &old, + old + charge)); + + return true; +} + +static void inet_frag_wmem_adjust(struct sock *sk, int delta) +{ + if (delta >= 0) + refcount_add(delta, &sk->sk_wmem_alloc); + else + WARN_ON_ONCE(refcount_sub_and_test(-delta, &sk->sk_wmem_alloc)); +} + void *inet_frag_reasm_prepare(struct inet_frag_queue *q, struct sk_buff *skb, struct sk_buff *parent) { @@ -530,6 +568,11 @@ void *inet_frag_reasm_prepare(struct inet_frag_queue *q, struct sk_buff *skb, int delta; if (sk && is_skb_wmem(skb)) { + /* skb->truesize is already charged to sk, and is part of + * q->truesize. inet_frag_reasm_finish() settles the charge. + */ + if (!inet_frag_wmem_reserve(sk, q->truesize - skb->truesize)) + return NULL; /* TX: skb->sk might have been passed as argument to * dst->output and must remain valid until tx completes. * @@ -605,17 +648,18 @@ void *inet_frag_reasm_prepare(struct inet_frag_queue *q, struct sk_buff *skb, out_restore_sk: if (orig_truesize) { - int ts_delta = head->truesize - orig_truesize; - /* if this reassembled skb is fragmented later, * fraglist skbs will get skb->sk assigned from head->sk, * and each frag skb will be released via sock_wfree. - * - * Update sk_wmem_alloc. */ head->sk = sk; head->destructor = destructor; - refcount_add(ts_delta, &sk->sk_wmem_alloc); + /* On failure, head stays in the queue and will be freed + * with the queue: only charge its truesize. + */ + if (!nextp) + inet_frag_wmem_adjust(sk, (int)head->truesize - + (int)q->truesize); } return nextp; @@ -626,7 +670,6 @@ void inet_frag_reasm_finish(struct inet_frag_queue *q, struct sk_buff *head, void *reasm_data, bool try_coalesce) { struct sock *sk = is_skb_wmem(head) ? head->sk : NULL; - const unsigned int head_truesize = head->truesize; struct sk_buff **nextp = reasm_data; struct rb_node *rbn; struct sk_buff *fp; @@ -691,8 +734,12 @@ void inet_frag_reasm_finish(struct inet_frag_queue *q, struct sk_buff *head, head->tstamp = q->stamp; head->tstamp_type = q->tstamp_type; + /* After inet_frag_reasm_prepare(), q->truesize is charged to sk. + * sum_truesize also includes what it added (skb_unclone() and + * frag_list clone). + */ if (sk) - refcount_add(sum_truesize - head_truesize, &sk->sk_wmem_alloc); + inet_frag_wmem_adjust(sk, sum_truesize - (int)q->truesize); } EXPORT_SYMBOL(inet_frag_reasm_finish); diff --git a/net/ipv4/ip_fragment.c b/net/ipv4/ip_fragment.c index 36105dd19282..ef7fd61284a3 100644 --- a/net/ipv4/ip_fragment.c +++ b/net/ipv4/ip_fragment.c @@ -413,16 +413,19 @@ static int ip_frag_reasm(struct ipq *qp, struct sk_buff *skb, goto out_fail; } + /* Check the size on the first fragment, which will become the head: + * inet_frag_reasm_finish() must follow inet_frag_reasm_prepare(). + */ + len = ip_hdrlen(skb_rb_first(&qp->q.rb_fragments)) + qp->q.len; + err = -E2BIG; + if (len > 65535) + goto out_oversize; + /* Make the one we just received the head. */ reasm_data = inet_frag_reasm_prepare(&qp->q, skb, prev_tail); if (!reasm_data) goto out_nomem; - len = ip_hdrlen(skb) + qp->q.len; - err = -E2BIG; - if (len > 65535) - goto out_oversize; - inet_frag_reasm_finish(&qp->q, skb, reasm_data, ip_frag_coalesce_ok(qp)); diff --git a/net/ipv4/ip_output.c b/net/ipv4/ip_output.c index 3396f177a18d..d42d776af273 100644 --- a/net/ipv4/ip_output.c +++ b/net/ipv4/ip_output.c @@ -1150,16 +1150,16 @@ alloc_new_skb: */ skb->ip_summed = csummode; skb->csum = 0; - skb_reserve(skb, hh_len); + skb_reserve(skb, hh_len + exthdrlen); /* * Find where to start putting bytes. */ - data = skb_put(skb, fraglen + exthdrlen - pagedlen); - skb_set_network_header(skb, exthdrlen); + data = skb_put(skb, fraglen - pagedlen); + skb_reset_network_header(skb); skb->transport_header = (skb->network_header + fragheaderlen); - data += fragheaderlen + exthdrlen; + data += fragheaderlen; if (fraggap) { skb->csum = skb_copy_and_csum_bits( diff --git a/net/ipv4/netfilter/arp_tables.c b/net/ipv4/netfilter/arp_tables.c index cf747e1e17a3..7ff3d1f0ffd4 100644 --- a/net/ipv4/netfilter/arp_tables.c +++ b/net/ipv4/netfilter/arp_tables.c @@ -371,11 +371,12 @@ static int mark_source_chains(const struct xt_table_info *newinfo, e->counters.pcnt = pos; pos += size; } else { - int newpos = t->verdict; + int newpos; if (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0 && - newpos >= 0) { + t->verdict >= 0) { + newpos = t->verdict; /* This a jump; chase it. */ if (!xt_find_jump_offset(offsets, newpos, newinfo->number)) diff --git a/net/ipv4/netfilter/ip_tables.c b/net/ipv4/netfilter/ip_tables.c index 809441cedced..b302bd77180a 100644 --- a/net/ipv4/netfilter/ip_tables.c +++ b/net/ipv4/netfilter/ip_tables.c @@ -422,11 +422,12 @@ mark_source_chains(const struct xt_table_info *newinfo, e->counters.pcnt = pos; pos += size; } else { - int newpos = t->verdict; + int newpos; if (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0 && - newpos >= 0) { + t->verdict >= 0) { + newpos = t->verdict; /* This a jump; chase it. */ if (!xt_find_jump_offset(offsets, newpos, newinfo->number)) diff --git a/net/ipv4/netfilter/nf_reject_ipv4.c b/net/ipv4/netfilter/nf_reject_ipv4.c index 7cb33af671e2..4082fa184af8 100644 --- a/net/ipv4/netfilter/nf_reject_ipv4.c +++ b/net/ipv4/netfilter/nf_reject_ipv4.c @@ -10,6 +10,7 @@ #include <net/dst.h> #include <net/dst_metadata.h> #include <net/netfilter/ipv4/nf_reject.h> +#include <net/netfilter/nf_recursion.h> #include <linux/netfilter_ipv4.h> #include <linux/netfilter_bridge.h> @@ -336,7 +337,18 @@ void nf_send_reset(struct net *net, struct sock *sk, struct sk_buff *oldskb, dev_queue_xmit(nskb); } else #endif + { + local_bh_disable(); + if (nf_dev_xmit_recursion()) { + local_bh_enable(); + goto free_nskb; + } + + nf_dev_xmit_recursion_inc(); ip_local_out(net, nskb->sk, nskb); + nf_dev_xmit_recursion_dec(); + local_bh_enable(); + } return; diff --git a/net/ipv4/raw.c b/net/ipv4/raw.c index 9d01006d8189..f33a9dfc5309 100644 --- a/net/ipv4/raw.c +++ b/net/ipv4/raw.c @@ -182,18 +182,19 @@ static int raw_v4_input(struct net *net, struct sk_buff *skb, iph->saddr, iph->daddr, dif, sdif)) continue; - if (atomic_read(&sk->sk_rmem_alloc) >= - READ_ONCE(sk->sk_rcvbuf)) { - sk_drops_inc(sk); - continue; - } - delivered = 1; if ((iph->protocol != IPPROTO_ICMP || !icmp_filter(sk, skb)) && ip_mc_sf_allow(sk, iph->daddr, iph->saddr, skb->dev->ifindex, sdif)) { - struct sk_buff *clone = skb_clone(skb, GFP_ATOMIC); + struct sk_buff *clone; + + if (atomic_read(&sk->sk_rmem_alloc) >= + READ_ONCE(sk->sk_rcvbuf)) { + sk_drops_inc(sk); + continue; + } + clone = skb_clone(skb, GFP_ATOMIC); /* Not releasing hash table! */ if (clone) raw_rcv(sk, clone); diff --git a/net/ipv4/route.c b/net/ipv4/route.c index 3a90c8d28b94..cd69242afab0 100644 --- a/net/ipv4/route.c +++ b/net/ipv4/route.c @@ -573,6 +573,17 @@ static void ip_rt_build_flow_key(struct flowi4 *fl4, const struct sock *sk, static DEFINE_SPINLOCK(fnhe_lock); +/* Other CPUs may still be using @rt, so don't dst_dev_put() it. + * rt_flush_dev() handles it if its device is unregistered. + * Marking it dead makes ipv4_dst_check() fail for users that cached it. + */ +static void fnhe_retire_route(struct rtable *rt) +{ + WRITE_ONCE(rt->dst.obsolete, DST_OBSOLETE_DEAD); + rt_add_uncached_list(rt); + dst_release(&rt->dst); +} + static void fnhe_flush_routes(struct fib_nh_exception *fnhe) { struct rtable *rt; @@ -580,14 +591,12 @@ static void fnhe_flush_routes(struct fib_nh_exception *fnhe) rt = rcu_dereference(fnhe->fnhe_rth_input); if (rt) { RCU_INIT_POINTER(fnhe->fnhe_rth_input, NULL); - dst_dev_put(&rt->dst); - dst_release(&rt->dst); + fnhe_retire_route(rt); } rt = rcu_dereference(fnhe->fnhe_rth_output); if (rt) { RCU_INIT_POINTER(fnhe->fnhe_rth_output, NULL); - dst_dev_put(&rt->dst); - dst_release(&rt->dst); + fnhe_retire_route(rt); } } @@ -1505,10 +1514,8 @@ static bool rt_bind_exception(struct rtable *rt, struct fib_nh_exception *fnhe, if (do_cache) { dst_hold(&rt->dst); rcu_assign_pointer(*porig, rt); - if (orig) { - dst_dev_put(&orig->dst); - dst_release(&orig->dst); - } + if (orig) + fnhe_retire_route(orig); ret = true; } diff --git a/net/ipv4/tcp.c b/net/ipv4/tcp.c index b9de7c302ba8..832b25ddd3c2 100644 --- a/net/ipv4/tcp.c +++ b/net/ipv4/tcp.c @@ -456,7 +456,7 @@ void tcp_init_sock(struct sock *sk) * initialization of these values. */ tp->snd_ssthresh = TCP_INFINITE_SSTHRESH; - tp->snd_cwnd_clamp = ~0; + tp->snd_cwnd_clamp = TCP_MAX_SND_CWND; tp->mss_cache = TCP_MSS_DEFAULT; tp->reordering = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_reordering); @@ -1057,6 +1057,7 @@ int tcp_sendmsg_fastopen(struct sock *sk, struct msghdr *msg, int *copied, struct tcp_sock *tp = tcp_sk(sk); struct inet_sock *inet = inet_sk(sk); struct sockaddr *uaddr = msg->msg_name; + bool defer_connect = false; int err, flags; if (!(READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_fastopen) & @@ -1076,6 +1077,9 @@ int tcp_sendmsg_fastopen(struct sock *sk, struct msghdr *msg, int *copied, tp->fastopen_req->uarg = uarg; if (inet_test_bit(DEFER_CONNECT, sk)) { + inet_clear_bit(DEFER_CONNECT, sk); + defer_connect = true; + err = tcp_connect(sk); /* Same failure procedure as in tcp_v4/6_connect */ if (err) { @@ -1086,14 +1090,13 @@ int tcp_sendmsg_fastopen(struct sock *sk, struct msghdr *msg, int *copied, } flags = (msg->msg_flags & MSG_DONTWAIT) ? O_NONBLOCK : 0; err = __inet_stream_connect(sk->sk_socket, (struct sockaddr_unsized *)uaddr, - msg->msg_namelen, flags, 1); + msg->msg_namelen, flags, defer_connect); /* fastopen_req could already be freed in __inet_stream_connect * if the connection times out or gets rst */ if (tp->fastopen_req) { *copied = tp->fastopen_req->copied; tcp_free_fastopen_req(tp); - inet_clear_bit(DEFER_CONNECT, sk); } return err; } @@ -3490,6 +3493,7 @@ int tcp_disconnect(struct sock *sk, int flags) tp->rx_opt.dsack = 0; tp->rx_opt.num_sacks = 0; tp->rcv_ooopack = 0; + tp->rcv_collapse_credit = 0; /* Clean up fastopen related fields */ @@ -4968,7 +4972,8 @@ tcp_inbound_md5_hash(const struct sock *sk, const struct sk_buff *skb, const void *saddr, const void *daddr, int family, int l3index, const __u8 *hash_location) { - return SKB_NOT_DROPPED_YET; + NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMD5UNEXPECTED); + return SKB_DROP_REASON_TCP_MD5UNEXPECTED; } #endif @@ -5148,6 +5153,8 @@ int tcp_abort(struct sock *sk, int err) /* Don't race with userspace socket closes such as tcp_close. */ lock_sock(sk); + inet_clear_bit(DEFER_CONNECT, sk); + /* Avoid closing the same socket twice. */ if (sk->sk_state == TCP_CLOSE) { if (!has_current_bpf_ctx()) @@ -5308,6 +5315,7 @@ static void __init tcp_struct_check(void) CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, rcv_rtt_last_tsecr); CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, delivered_ecn_bytes); CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, pkts_acked_ewma); + CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, rcv_collapse_credit); CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, rcv_rtt_est); CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, rcvq_space); } diff --git a/net/ipv4/tcp_input.c b/net/ipv4/tcp_input.c index 3fd0e215324d..a2074a1af422 100644 --- a/net/ipv4/tcp_input.c +++ b/net/ipv4/tcp_input.c @@ -5290,6 +5290,10 @@ static bool tcp_try_coalesce(struct sock *sk, if (!tcp_skb_can_collapse_rx(to, from)) return false; + /* Nothing follows a FIN. */ + if (unlikely(TCP_SKB_CB(to)->tcp_flags & TCPHDR_FIN)) + return false; + if (!skb_try_coalesce(to, from, fragstolen, &delta)) return false; @@ -5413,6 +5417,20 @@ static int tcp_try_rmem_schedule(struct sock *sk, const struct sk_buff *skb, return 0; } +/* Credit the memory added to the receive queues since @rmem was sampled + * toward the next allowed collapse. Saturate at sk_rcvbuf, not at the goal + * checked in tcp_prune_queue(): sk_rcvbuf (and the goal) can grow later, + * for instance in tcp_clamp_window(). + */ +static void tcp_collapse_credit_add(struct sock *sk, int rmem) +{ + struct tcp_sock *tp = tcp_sk(sk); + int delta = atomic_read(&sk->sk_rmem_alloc) - rmem; + + if (delta > 0 && tp->rcv_collapse_credit < (u32)sk->sk_rcvbuf) + tp->rcv_collapse_credit += delta; +} + static void tcp_data_queue_ofo(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); @@ -5420,6 +5438,7 @@ static void tcp_data_queue_ofo(struct sock *sk, struct sk_buff *skb) struct sk_buff *skb1; u32 seq, end_seq; bool fragstolen; + int rmem; tcp_save_lrcv_flowlabel(sk, skb); tcp_data_ecn_check(sk, skb); @@ -5430,6 +5449,8 @@ static void tcp_data_queue_ofo(struct sock *sk, struct sk_buff *skb) tcp_drop_reason(sk, skb, SKB_DROP_REASON_PROTO_MEM); return; } + /* Sampled after tcp_try_rmem_schedule(), which can prune. */ + rmem = atomic_read(&sk->sk_rmem_alloc); tcp_measure_rcv_mss(sk, skb); /* Disable header prediction. */ @@ -5559,6 +5580,10 @@ end: skb_condense(skb); skb_set_owner_r(skb, sk); } + /* Net growth: coalescing can charge nothing, and covered skbs + * were freed. + */ + tcp_collapse_credit_add(sk, rmem); /* do not grow rcvbuf for not-yet-accepted or orphaned sockets. */ if (sk->sk_socket) tcp_rcvbuf_grow(sk, tp->rcvq_space.space); @@ -5567,8 +5592,9 @@ end: static int __must_check tcp_queue_rcv(struct sock *sk, struct sk_buff *skb, bool *fragstolen) { - int eaten; + int rmem = atomic_read(&sk->sk_rmem_alloc); struct sk_buff *tail = skb_peek_tail(&sk->sk_receive_queue); + int eaten; bpf_tcp_ops_call_flag(enqueue_rcvq, RCVQ, sk, skb); @@ -5580,6 +5606,7 @@ static int __must_check tcp_queue_rcv(struct sock *sk, struct sk_buff *skb, tcp_add_receive_queue(sk, skb); skb_set_owner_r(skb, sk); } + tcp_collapse_credit_add(sk, rmem); return eaten; } @@ -6056,18 +6083,28 @@ static int tcp_prune_queue(struct sock *sk, const struct sk_buff *in_skb) if (tcp_can_ingest(sk, in_skb)) return 0; - tcp_collapse_ofo_queue(sk); - if (!skb_queue_empty(&sk->sk_receive_queue)) - tcp_collapse(sk, &sk->sk_receive_queue, NULL, - skb_peek(&sk->sk_receive_queue), - NULL, - tp->copied_seq, tp->rcv_nxt); + /* Collapsing walks both queues and is expensive, and can free + * almost nothing. Require at least 1/8 of sk_rcvbuf of new memory + * in the receive queues since the previous collapse, otherwise + * a stream of segments could trigger one collapse per packet. + */ + if (tp->rcv_collapse_credit >= (u32)sk->sk_rcvbuf >> 3) { + tp->rcv_collapse_credit = 0; - if (tcp_can_ingest(sk, in_skb)) - return 0; + tcp_collapse_ofo_queue(sk); + if (!skb_queue_empty(&sk->sk_receive_queue)) + tcp_collapse(sk, &sk->sk_receive_queue, NULL, + skb_peek(&sk->sk_receive_queue), + NULL, + tp->copied_seq, tp->rcv_nxt); - /* Collapsing did not help, destructive actions follow. - * This must not ever occur. */ + if (tcp_can_ingest(sk, in_skb)) + return 0; + } + + /* Collapsing did not help (or was not allowed), + * destructive actions follow. + */ tcp_prune_ofo_queue(sk, in_skb); @@ -7252,6 +7289,15 @@ tcp_rcv_state_process(struct sock *sk, struct sk_buff *skb) goto discard; case TCP_SYN_SENT: + /* We sent nothing yet, so no segment belongs to this connection. + * Send no RST: it would be built from this socket, whose TCP-AO + * keys are not set up either. + */ + if (unlikely(inet_test_bit(DEFER_CONNECT, sk))) { + SKB_DR_SET(reason, NOT_SPECIFIED); + goto discard; + } + tp->rx_opt.saw_tstamp = 0; tcp_mstamp_refresh(tp); queued = tcp_rcv_synsent_state_process(sk, skb, th); @@ -7638,7 +7684,7 @@ static void tcp_reqsk_record_syn(const struct sock *sk, saved_syn->network_hdrlen = skb_network_header_len(skb); saved_syn->tcp_hdrlen = tcp_hdrlen(skb); memcpy(saved_syn->data, base, len); - req->saved_syn = saved_syn; + RCU_INIT_POINTER(req->saved_syn, saved_syn); } } } diff --git a/net/ipv4/tcp_ipv4.c b/net/ipv4/tcp_ipv4.c index 0dc3b087665d..2fc92a7884fc 100644 --- a/net/ipv4/tcp_ipv4.c +++ b/net/ipv4/tcp_ipv4.c @@ -541,7 +541,7 @@ int tcp_v4_err(struct sk_buff *skb, u32 info) if (!(type == ICMP_DEST_UNREACH && code == ICMP_FRAG_NEEDED)) __NET_INC_STATS(net, LINUX_MIB_LOCKDROPPEDICMPS); } - if (sk->sk_state == TCP_CLOSE) + if (sk->sk_state == TCP_CLOSE || inet_test_bit(DEFER_CONNECT, sk)) goto out; if (static_branch_unlikely(&ip4_min_ttl)) { @@ -1957,6 +1957,8 @@ enum skb_drop_reason tcp_add_backlog(struct sock *sk, struct sk_buff *skb) ((TCP_SKB_CB(tail)->tcp_flags ^ TCP_SKB_CB(skb)->tcp_flags) & (TCPHDR_ECE | TCPHDR_CWR | TCPHDR_AE)) || + /* Nothing follows a FIN, see tcp_try_coalesce() */ + (TCP_SKB_CB(tail)->tcp_flags & TCPHDR_FIN) || !tcp_skb_can_collapse_rx(tail, skb) || thtail->doff != th->doff || memcmp(thtail + 1, th + 1, hdrlen - sizeof(*th)) || diff --git a/net/ipv4/tcp_metrics.c b/net/ipv4/tcp_metrics.c index d58f99c67d4d..ae551546422f 100644 --- a/net/ipv4/tcp_metrics.c +++ b/net/ipv4/tcp_metrics.c @@ -495,7 +495,8 @@ void tcp_init_metrics(struct sock *sk) } if (tcp_metric_locked(tm, TCP_METRIC_CWND)) - tp->snd_cwnd_clamp = tcp_metric_get(tm, TCP_METRIC_CWND); + tp->snd_cwnd_clamp = min(tcp_metric_get(tm, TCP_METRIC_CWND), + TCP_MAX_SND_CWND); val = READ_ONCE(net->ipv4.sysctl_tcp_no_ssthresh_metrics_save) ? 0 : tcp_metric_get(tm, TCP_METRIC_SSTHRESH); diff --git a/net/ipv4/tcp_minisocks.c b/net/ipv4/tcp_minisocks.c index 0ddfd5af6e58..a05bb02e204c 100644 --- a/net/ipv4/tcp_minisocks.c +++ b/net/ipv4/tcp_minisocks.c @@ -974,7 +974,7 @@ embryonic_reset: tcp_reset(sk, skb); } if (!fastopen) { - bool unlinked = inet_csk_reqsk_queue_drop(sk, req); + bool unlinked = inet_csk_reqsk_queue_drop(req->rsk_listener, req); if (unlinked) __NET_INC_STATS(sock_net(sk), LINUX_MIB_EMBRYONICRSTS); diff --git a/net/ipv4/udp.c b/net/ipv4/udp.c index 303d0102519a..2e5562f353f8 100644 --- a/net/ipv4/udp.c +++ b/net/ipv4/udp.c @@ -2850,8 +2850,11 @@ enum skb_drop_reason udp_v4_early_demux(struct sk_buff *skb) skb->destructor = sock_pfree; dst = rcu_dereference(sk->sk_rx_dst); - if (dst) + /* A dual-stack socket can cache an IPv6 dst. */ + if (dst && dst->ops->family == AF_INET) dst = dst_check(dst, 0); + else + dst = NULL; if (dst) { u32 itag = 0; diff --git a/net/ipv4/udp_offload.c b/net/ipv4/udp_offload.c index cf07c3c6611a..b77ae2f00c62 100644 --- a/net/ipv4/udp_offload.c +++ b/net/ipv4/udp_offload.c @@ -514,9 +514,14 @@ struct sk_buff *__udp_gso_segment(struct sk_buff *gso_skb, } if (skb_shinfo(gso_skb)->gso_type & SKB_GSO_FRAGLIST) { - /* Detect modified geometry and pass those to skb_segment. */ + /* Detect modified geometry and pass those to skb_segment. + * SKB_GSO_UDP_L4 is used by both IPv4 and IPv6: also make sure + * the frag_list skbs still have the IP family we segment for, + * as their network headers are not rebuilt. + */ if ((skb_pagelen(gso_skb) - sizeof(*uh) == skb_shinfo(gso_skb)->gso_size) && - !(skb_shinfo(gso_skb)->gso_type & SKB_GSO_DODGY)) + !(skb_shinfo(gso_skb)->gso_type & SKB_GSO_DODGY) && + ip_hdr(skb_shinfo(gso_skb)->frag_list)->version == (is_ipv6 ? 6 : 4)) return __udp_gso_segment_list(gso_skb, features, is_ipv6); ret = __skb_linearize(gso_skb); @@ -743,6 +748,7 @@ static struct sk_buff *udp_gro_receive_segment(struct list_head *head, pp = p; } else { if (NAPI_GRO_CB(skb)->is_flist) { + skb_gro_frag0_invalidate(skb); if (!pskb_may_pull(skb, skb_gro_offset(skb))) { NAPI_GRO_CB(skb)->flush = 1; return NULL; diff --git a/net/ipv4/udp_tunnel_core.c b/net/ipv4/udp_tunnel_core.c index a128fe85620d..29581c94fdcf 100644 --- a/net/ipv4/udp_tunnel_core.c +++ b/net/ipv4/udp_tunnel_core.c @@ -62,10 +62,10 @@ EXPORT_SYMBOL(udp_sock_create4); static bool sk_saddr_any(struct sock *sk) { #if IS_ENABLED(CONFIG_IPV6) - return ipv6_addr_any(&sk->sk_v6_rcv_saddr); -#else - return !sk->sk_rcv_saddr; + if (sk->sk_family == AF_INET6) + return ipv6_addr_any(&sk->sk_v6_rcv_saddr); #endif + return !sk->sk_rcv_saddr; } void setup_udp_tunnel_sock(struct net *net, struct sock *sk, diff --git a/net/ipv6/calipso.c b/net/ipv6/calipso.c index e399a42e3083..4cd0ae9313b3 100644 --- a/net/ipv6/calipso.c +++ b/net/ipv6/calipso.c @@ -1219,7 +1219,7 @@ static int calipso_req_setattr(struct request_sock *req, if (IS_ERR(new)) return PTR_ERR(new); - txopts = ipv6_renew_options(sk, req_inet->ipv6_opt, IPV6_HOPOPTS, new); + txopts = ipv6_renew_options(NULL, req_inet->ipv6_opt, IPV6_HOPOPTS, new); kfree(new); @@ -1227,10 +1227,8 @@ static int calipso_req_setattr(struct request_sock *req, return PTR_ERR(txopts); txopts = xchg(&req_inet->ipv6_opt, txopts); - if (txopts) { - atomic_sub(txopts->tot_len, &sk->sk_omem_alloc); + if (txopts) txopt_put(txopts); - } return 0; } @@ -1260,14 +1258,12 @@ static void calipso_req_delattr(struct request_sock *req) if (calipso_opt_del(req_inet->ipv6_opt->hopopt, &new)) return; /* Nothing to do */ - txopts = ipv6_renew_options(sk, req_inet->ipv6_opt, IPV6_HOPOPTS, new); + txopts = ipv6_renew_options(NULL, req_inet->ipv6_opt, IPV6_HOPOPTS, new); if (!IS_ERR(txopts)) { txopts = xchg(&req_inet->ipv6_opt, txopts); - if (txopts) { - atomic_sub(txopts->tot_len, &sk->sk_omem_alloc); + if (txopts) txopt_put(txopts); - } } kfree(new); } diff --git a/net/ipv6/esp6_offload.c b/net/ipv6/esp6_offload.c index 22895521a57d..ca947cb94fb7 100644 --- a/net/ipv6/esp6_offload.c +++ b/net/ipv6/esp6_offload.c @@ -64,6 +64,7 @@ static struct sk_buff *esp6_gro_receive(struct list_head *head, if (NAPI_GRO_CB(skb)->proto == IPPROTO_UDP) encap_type = UDP_ENCAP_ESPINUDP; + skb_gro_frag0_invalidate(skb); if (!pskb_pull(skb, offset)) return NULL; diff --git a/net/ipv6/exthdrs.c b/net/ipv6/exthdrs.c index 96c8402a27a5..ccc549de3c8a 100644 --- a/net/ipv6/exthdrs.c +++ b/net/ipv6/exthdrs.c @@ -1281,7 +1281,7 @@ static void ipv6_renew_option(int renewtype, * not copied into the new set of options. * * The new set of options is allocated from the socket option memory - * buffer of @sk. + * buffer of @sk, or with kmalloc() if @sk is NULL. */ struct ipv6_txoptions * ipv6_renew_options(struct sock *sk, struct ipv6_txoptions *opt, @@ -1309,7 +1309,8 @@ ipv6_renew_options(struct sock *sk, struct ipv6_txoptions *opt, return NULL; tot_len += sizeof(*opt2); - opt2 = sock_kmalloc(sk, tot_len, GFP_ATOMIC); + opt2 = sk ? sock_kmalloc(sk, tot_len, GFP_ATOMIC) : + kmalloc(tot_len, GFP_ATOMIC); if (!opt2) return ERR_PTR(-ENOBUFS); diff --git a/net/ipv6/exthdrs_core.c b/net/ipv6/exthdrs_core.c index 4a9748338cf4..764c694fb417 100644 --- a/net/ipv6/exthdrs_core.c +++ b/net/ipv6/exthdrs_core.c @@ -138,9 +138,6 @@ int ipv6_find_tlv(const struct sk_buff *skb, int offset, int type) int opttype = nh[offset]; int optlen; - if (opttype == type) - return offset; - switch (opttype) { case IPV6_TLV_PAD1: optlen = 1; @@ -153,6 +150,10 @@ int ipv6_find_tlv(const struct sk_buff *skb, int offset, int type) goto bad; break; } + /* Some callers read the option, so it must be in the header. */ + if (opttype == type) + return offset; + offset += optlen; len -= optlen; } diff --git a/net/ipv6/icmp.c b/net/ipv6/icmp.c index a95b0351824f..d8203ebad882 100644 --- a/net/ipv6/icmp.c +++ b/net/ipv6/icmp.c @@ -343,7 +343,12 @@ static void mip6_addr_swap(struct sk_buff *skb, const struct inet6_skb_parm *opt if (likely(off >= 0)) { hao = (struct ipv6_destopt_hao *) (skb_network_header(skb) + off); - swap(iph->saddr, hao->addr); + /* + * The header can have moved or changed after + * ipv6_dest_hao() checked the length. + */ + if (hao->length == 16) + swap(iph->saddr, hao->addr); } } } diff --git a/net/ipv6/ip6_output.c b/net/ipv6/ip6_output.c index 25fe0ba98b1a..cb648c839431 100644 --- a/net/ipv6/ip6_output.c +++ b/net/ipv6/ip6_output.c @@ -1305,7 +1305,7 @@ EXPORT_SYMBOL_GPL(ip6_dst_lookup_flow); * @sk: socket which provides the dst cache and route info * @fl6: flow to lookup * @final_dst: final destination address for ipsec lookup - * @connected: whether @sk is connected or not + * @connected: whether the flow can use and update the socket dst cache * * This function performs a route lookup on the given flow with the * possibility of using the cached route in the socket if it is valid. @@ -1322,11 +1322,14 @@ struct dst_entry *ip6_sk_dst_lookup_flow(struct sock *sk, struct flowi6 *fl6, const struct in6_addr *final_dst, bool connected) { - struct dst_entry *dst = sk_dst_check(sk, inet6_sk(sk)->dst_cookie); + struct dst_entry *dst; - dst = ip6_sk_dst_check(sk, dst, fl6); - if (dst) - return dst; + if (connected) { + dst = sk_dst_check(sk, inet6_sk(sk)->dst_cookie); + dst = ip6_sk_dst_check(sk, dst, fl6); + if (dst) + return dst; + } dst = ip6_dst_lookup_flow(sock_net(sk), sk, fl6, final_dst); if (connected && !IS_ERR(dst)) diff --git a/net/ipv6/mip6.c b/net/ipv6/mip6.c index 6a16a5bd0d91..961567972411 100644 --- a/net/ipv6/mip6.c +++ b/net/ipv6/mip6.c @@ -211,9 +211,16 @@ static int mip6_destopt_reject(struct xfrm_state *x, struct sk_buff *skb, if (likely(opt->dsthao)) { offset = ipv6_find_tlv(skb, opt->dsthao, IPV6_TLV_HAO); - if (likely(offset >= 0)) + if (likely(offset >= 0)) { hao = (struct ipv6_destopt_hao *) (skb_network_header(skb) + offset); + /* + * The header can have moved or changed after + * ipv6_dest_hao() checked the length. + */ + if (hao->length != 16) + hao = NULL; + } } stamp = skb_get_ktime(skb); diff --git a/net/ipv6/netfilter/ip6_tables.c b/net/ipv6/netfilter/ip6_tables.c index 313c4aac377a..010baaa60665 100644 --- a/net/ipv6/netfilter/ip6_tables.c +++ b/net/ipv6/netfilter/ip6_tables.c @@ -440,11 +440,12 @@ mark_source_chains(const struct xt_table_info *newinfo, e->counters.pcnt = pos; pos += size; } else { - int newpos = t->verdict; + int newpos; if (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0 && - newpos >= 0) { + t->verdict >= 0) { + newpos = t->verdict; /* This a jump; chase it. */ if (!xt_find_jump_offset(offsets, newpos, newinfo->number)) diff --git a/net/ipv6/netfilter/nf_conntrack_reasm.c b/net/ipv6/netfilter/nf_conntrack_reasm.c index be72c4346f8b..f25ff2a12a82 100644 --- a/net/ipv6/netfilter/nf_conntrack_reasm.c +++ b/net/ipv6/netfilter/nf_conntrack_reasm.c @@ -330,11 +330,10 @@ static int nf_ct_frag6_reasm(struct frag_queue *fq, struct sk_buff *skb, if (unlikely(ecn == 0xff)) goto err; - reasm_data = inet_frag_reasm_prepare(&fq->q, skb, prev_tail); - if (!reasm_data) - goto err; - - payload_len = -skb_network_offset(skb) - + /* Check the size on the first fragment, which will become the head: + * inet_frag_reasm_finish() must follow inet_frag_reasm_prepare(). + */ + payload_len = -skb_network_offset(skb_rb_first(&fq->q.rb_fragments)) - sizeof(struct ipv6hdr) + fq->q.len - sizeof(struct frag_hdr); if (payload_len > IPV6_MAXPLEN) { @@ -343,6 +342,10 @@ static int nf_ct_frag6_reasm(struct frag_queue *fq, struct sk_buff *skb, goto err; } + reasm_data = inet_frag_reasm_prepare(&fq->q, skb, prev_tail); + if (!reasm_data) + goto err; + /* We have to remove fragment header from datagram and to relocate * header in order to calculate ICV correctly. */ skb_network_header(skb)[fq->nhoffset] = skb_transport_header(skb)[0]; diff --git a/net/ipv6/netfilter/nf_reject_ipv6.c b/net/ipv6/netfilter/nf_reject_ipv6.c index 5e08d8529cc8..7c9464184517 100644 --- a/net/ipv6/netfilter/nf_reject_ipv6.c +++ b/net/ipv6/netfilter/nf_reject_ipv6.c @@ -10,6 +10,7 @@ #include <net/ip6_checksum.h> #include <net/dst_metadata.h> #include <net/netfilter/ipv6/nf_reject.h> +#include <net/netfilter/nf_recursion.h> #include <linux/netfilter_ipv6.h> #include <linux/netfilter_bridge.h> @@ -409,7 +410,19 @@ void nf_send_reset6(struct net *net, struct sock *sk, struct sk_buff *oldskb, dev_queue_xmit(nskb); } else #endif + { + local_bh_disable(); + if (nf_dev_xmit_recursion()) { + local_bh_enable(); + kfree_skb(nskb); + return; + } + + nf_dev_xmit_recursion_inc(); ip6_local_out(net, sk, nskb); + nf_dev_xmit_recursion_dec(); + local_bh_enable(); + } } EXPORT_SYMBOL_GPL(nf_send_reset6); diff --git a/net/ipv6/raw.c b/net/ipv6/raw.c index bdea825434ea..00d832c7cdae 100644 --- a/net/ipv6/raw.c +++ b/net/ipv6/raw.c @@ -160,12 +160,6 @@ static bool ipv6_raw_deliver(struct sk_buff *skb, int nexthdr) inet6_iif(skb), inet6_sdif(skb))) continue; - if (atomic_read(&sk->sk_rmem_alloc) >= - READ_ONCE(sk->sk_rcvbuf)) { - sk_drops_inc(sk); - continue; - } - delivered = true; switch (nexthdr) { case IPPROTO_ICMPV6: @@ -197,8 +191,15 @@ static bool ipv6_raw_deliver(struct sk_buff *skb, int nexthdr) if (filtered < 0) break; if (filtered == 0) { - struct sk_buff *clone = skb_clone(skb, GFP_ATOMIC); + struct sk_buff *clone; + + if (atomic_read(&sk->sk_rmem_alloc) >= + READ_ONCE(sk->sk_rcvbuf)) { + sk_drops_inc(sk); + continue; + } + clone = skb_clone(skb, GFP_ATOMIC); /* Not releasing hash table! */ if (clone) rawv6_rcv(sk, clone); diff --git a/net/ipv6/reassembly.c b/net/ipv6/reassembly.c index 8418ed9423f4..91a65fe67350 100644 --- a/net/ipv6/reassembly.c +++ b/net/ipv6/reassembly.c @@ -275,16 +275,19 @@ static int ip6_frag_reasm(struct frag_queue *fq, struct sk_buff *skb, if (unlikely(ecn == 0xff)) goto out_fail; - reasm_data = inet_frag_reasm_prepare(&fq->q, skb, prev_tail); - if (!reasm_data) - goto out_oom; - - payload_len = -skb_network_offset(skb) - + /* Check the size on the first fragment, which will become the head: + * inet_frag_reasm_finish() must follow inet_frag_reasm_prepare(). + */ + payload_len = -skb_network_offset(skb_rb_first(&fq->q.rb_fragments)) - sizeof(struct ipv6hdr) + fq->q.len - sizeof(struct frag_hdr); if (payload_len > IPV6_MAXPLEN) goto out_oversize; + reasm_data = inet_frag_reasm_prepare(&fq->q, skb, prev_tail); + if (!reasm_data) + goto out_oom; + /* We have to remove fragment header from datagram and to relocate * header in order to calculate ICV correctly. */ nhoff = fq->nhoffset; diff --git a/net/ipv6/route.c b/net/ipv6/route.c index 2eb884558c24..1b2dcc066e19 100644 --- a/net/ipv6/route.c +++ b/net/ipv6/route.c @@ -1165,6 +1165,12 @@ static void ip6_rt_init_dst(struct rt6_info *rt, const struct fib6_result *res) return; } + /* addrconf_ifdown() removed inet6_dev. The device can't do IPv6. */ + if (!rt->rt6i_idev) { + ip6_rt_init_dst_reject(rt, RTN_UNREACHABLE); + return; + } + rt->dst.error = 0; rt->dst.output = ip6_output; @@ -1200,10 +1206,10 @@ static void ip6_rt_copy_init(struct rt6_info *rt, const struct fib6_result *res) const struct net_device *dev = nh->fib_nh_dev; struct fib6_info *f6i = res->f6i; + rt->rt6i_idev = dev ? in6_dev_get(dev) : NULL; ip6_rt_init_dst(rt, res); rt->rt6i_dst = f6i->fib6_dst; - rt->rt6i_idev = dev ? in6_dev_get(dev) : NULL; rt->rt6i_flags = res->fib6_flags; if (nh->fib_nh_gw_family) { rt->rt6i_gateway = nh->fib_nh_gw6; @@ -3438,9 +3444,9 @@ static int ip6_route_check_nh(struct net *net, netdevice_tracker *dev_tracker, struct inet6_dev **idev) { + int flags = RT6_LOOKUP_F_IFACE | RT6_LOOKUP_F_IGNORE_LINKSTATE; const struct in6_addr *gw_addr = &cfg->fc_gateway; struct net_device *dev = _dev ? *_dev : NULL; - int flags = RT6_LOOKUP_F_IFACE; struct fib6_result res = {}; int err = -EHOSTUNREACH; diff --git a/net/ipv6/seg6_iptunnel.c b/net/ipv6/seg6_iptunnel.c index 0d39a38a5dd2..3bc47c5614ff 100644 --- a/net/ipv6/seg6_iptunnel.c +++ b/net/ipv6/seg6_iptunnel.c @@ -18,6 +18,7 @@ #include <net/ip6_fib.h> #include <net/route.h> #include <net/seg6.h> +#include <net/dst_metadata.h> #include <linux/seg6.h> #include <linux/seg6_iptunnel.h> #include <net/addrconf.h> @@ -60,6 +61,21 @@ static inline struct seg6_lwt *seg6_lwt_lwtunnel(struct lwtunnel_state *lwt) return (struct seg6_lwt *)lwt->data; } +static bool seg6_skb_has_lwtstate(struct sk_buff *skb) +{ + struct dst_entry *dst; + + if (unlikely(!skb_valid_dst(skb))) + return false; + + dst = skb_dst(skb); + if (unlikely(!dst->lwtstate || + dst->lwtstate->type != LWTUNNEL_ENCAP_SEG6)) + return false; + + return true; +} + static inline struct seg6_iptunnel_encap * seg6_encap_lwtunnel(struct lwtunnel_state *lwt) { @@ -622,6 +638,17 @@ drop: return err; } +static int seg6_input_core_nf(struct net *net, struct sock *sk, + struct sk_buff *skb) +{ + if (unlikely(!seg6_skb_has_lwtstate(skb))) { + kfree_skb(skb); + return -EINVAL; + } + + return seg6_input_core(net, sk, skb); +} + static int seg6_input_nf(struct sk_buff *skb) { struct net_device *dev = skb_dst_dev(skb); @@ -630,10 +657,10 @@ static int seg6_input_nf(struct sk_buff *skb) switch (skb->protocol) { case htons(ETH_P_IP): return NF_HOOK(NFPROTO_IPV4, NF_INET_POST_ROUTING, net, NULL, - skb, NULL, dev, seg6_input_core); + skb, NULL, dev, seg6_input_core_nf); case htons(ETH_P_IPV6): return NF_HOOK(NFPROTO_IPV6, NF_INET_POST_ROUTING, net, NULL, - skb, NULL, dev, seg6_input_core); + skb, NULL, dev, seg6_input_core_nf); } return -EINVAL; @@ -726,6 +753,17 @@ drop: return err; } +static int seg6_output_core_nf(struct net *net, struct sock *sk, + struct sk_buff *skb) +{ + if (unlikely(!seg6_skb_has_lwtstate(skb))) { + kfree_skb(skb); + return -EINVAL; + } + + return seg6_output_core(net, sk, skb); +} + static int seg6_output_nf(struct net *net, struct sock *sk, struct sk_buff *skb) { struct net_device *dev = skb_dst_dev(skb); @@ -733,10 +771,10 @@ static int seg6_output_nf(struct net *net, struct sock *sk, struct sk_buff *skb) switch (skb->protocol) { case htons(ETH_P_IP): return NF_HOOK(NFPROTO_IPV4, NF_INET_POST_ROUTING, net, sk, skb, - NULL, dev, seg6_output_core); + NULL, dev, seg6_output_core_nf); case htons(ETH_P_IPV6): return NF_HOOK(NFPROTO_IPV6, NF_INET_POST_ROUTING, net, sk, skb, - NULL, dev, seg6_output_core); + NULL, dev, seg6_output_core_nf); } return -EINVAL; diff --git a/net/ipv6/seg6_local.c b/net/ipv6/seg6_local.c index 0d952514d095..82207da08dfd 100644 --- a/net/ipv6/seg6_local.c +++ b/net/ipv6/seg6_local.c @@ -24,6 +24,7 @@ #include <net/addrconf.h> #include <net/ip6_route.h> #include <net/dst_cache.h> +#include <net/dst_metadata.h> #include <net/ip_tunnels.h> #ifdef CONFIG_IPV6_SEG6_HMAC #include <net/seg6_hmac.h> @@ -211,6 +212,21 @@ static struct seg6_local_lwt *seg6_local_lwtunnel(struct lwtunnel_state *lwt) return (struct seg6_local_lwt *)lwt->data; } +static bool seg6_local_skb_has_lwtstate(struct sk_buff *skb) +{ + struct dst_entry *dst; + + if (unlikely(!skb_valid_dst(skb))) + return false; + + dst = skb_dst(skb); + if (unlikely(!dst->lwtstate || + dst->lwtstate->type != LWTUNNEL_ENCAP_SEG6_LOCAL)) + return false; + + return true; +} + static struct ipv6_sr_hdr *get_and_validate_srh(struct sk_buff *skb) { struct ipv6_sr_hdr *srh; @@ -1026,6 +1042,17 @@ static int input_action_end_dx6_finish(struct net *net, struct sock *sk, return dst_input(skb); } +static int input_action_end_dx6_finish_nf(struct net *net, struct sock *sk, + struct sk_buff *skb) +{ + if (unlikely(!seg6_local_skb_has_lwtstate(skb))) { + kfree_skb(skb); + return -EINVAL; + } + + return input_action_end_dx6_finish(net, sk, skb); +} + /* decapsulate and forward to specified nexthop */ static int input_action_end_dx6(struct sk_buff *skb, struct seg6_local_lwt *slwt) @@ -1046,7 +1073,7 @@ static int input_action_end_dx6(struct sk_buff *skb, if (static_branch_unlikely(&nf_hooks_lwtunnel_enabled)) return NF_HOOK(NFPROTO_IPV6, NF_INET_PRE_ROUTING, dev_net(skb->dev), NULL, skb, skb->dev, - NULL, input_action_end_dx6_finish); + NULL, input_action_end_dx6_finish_nf); return input_action_end_dx6_finish(dev_net(skb->dev), NULL, skb); drop: @@ -1114,6 +1141,17 @@ static int input_action_end_dx4_finish(struct net *net, struct sock *sk, return dst_input(skb); } +static int input_action_end_dx4_finish_nf(struct net *net, struct sock *sk, + struct sk_buff *skb) +{ + if (unlikely(!seg6_local_skb_has_lwtstate(skb))) { + kfree_skb(skb); + return -EINVAL; + } + + return input_action_end_dx4_finish(net, sk, skb); +} + static int input_action_end_dx4(struct sk_buff *skb, struct seg6_local_lwt *slwt) { @@ -1134,7 +1172,7 @@ static int input_action_end_dx4(struct sk_buff *skb, if (static_branch_unlikely(&nf_hooks_lwtunnel_enabled)) return NF_HOOK(NFPROTO_IPV4, NF_INET_PRE_ROUTING, dev_net(skb->dev), NULL, skb, skb->dev, - NULL, input_action_end_dx4_finish); + NULL, input_action_end_dx4_finish_nf); return input_action_end_dx4_finish(dev_net(skb->dev), NULL, skb); drop: @@ -1778,6 +1816,17 @@ static int seg6_local_input_core(struct net *net, struct sock *sk, return rc; } +static int seg6_local_input_core_nf(struct net *net, struct sock *sk, + struct sk_buff *skb) +{ + if (unlikely(!seg6_local_skb_has_lwtstate(skb))) { + kfree_skb(skb); + return -EINVAL; + } + + return seg6_local_input_core(net, sk, skb); +} + static int seg6_local_input(struct sk_buff *skb) { if (skb->protocol != htons(ETH_P_IPV6)) { @@ -1788,7 +1837,7 @@ static int seg6_local_input(struct sk_buff *skb) if (static_branch_unlikely(&nf_hooks_lwtunnel_enabled)) return NF_HOOK(NFPROTO_IPV6, NF_INET_LOCAL_IN, dev_net(skb->dev), NULL, skb, skb->dev, NULL, - seg6_local_input_core); + seg6_local_input_core_nf); return seg6_local_input_core(dev_net(skb->dev), NULL, skb); } diff --git a/net/ipv6/tcp_ipv6.c b/net/ipv6/tcp_ipv6.c index b1dec5d86d63..5c7ed38f1f56 100644 --- a/net/ipv6/tcp_ipv6.c +++ b/net/ipv6/tcp_ipv6.c @@ -449,7 +449,7 @@ static int tcp_v6_err(struct sk_buff *skb, struct inet6_skb_parm *opt, if (sock_owned_by_user(sk) && type != ICMPV6_PKT_TOOBIG) __NET_INC_STATS(net, LINUX_MIB_LOCKDROPPEDICMPS); - if (sk->sk_state == TCP_CLOSE) + if (sk->sk_state == TCP_CLOSE || inet_test_bit(DEFER_CONNECT, sk)) goto out; if (static_branch_unlikely(&ip6_min_hopcount)) { diff --git a/net/ipv6/udp.c b/net/ipv6/udp.c index 59f9872c3552..9dcefa162522 100644 --- a/net/ipv6/udp.c +++ b/net/ipv6/udp.c @@ -1249,8 +1249,11 @@ void udp_v6_early_demux(struct sk_buff *skb) skb->destructor = sock_pfree; dst = rcu_dereference(sk->sk_rx_dst); - if (dst) + /* A dual-stack socket can cache an IPv4 dst. */ + if (dst && dst->ops->family == AF_INET6) dst = dst_check(dst, sk->sk_rx_dst_cookie); + else + dst = NULL; if (dst) { /* set noref for now. * any place which wants to hold dst has to call diff --git a/net/mac80211/airtime.c b/net/mac80211/airtime.c index a4e1f33c0377..c31540ff42e0 100644 --- a/net/mac80211/airtime.c +++ b/net/mac80211/airtime.c @@ -550,6 +550,8 @@ static u32 ieee80211_get_rate_duration(struct ieee80211_hw *hw, group = HE_GROUP_IDX(streams, status->he_gi, bw); break; case RX_ENC_EHT: + if (status->eht.gi > NL80211_RATE_INFO_EHT_GI_3_2) + return 0; streams = status->nss; idx = status->rate_idx; group = EHT_GROUP_IDX(streams, status->eht.gi, bw); diff --git a/net/mac80211/ap.c b/net/mac80211/ap.c index fe255891c35f..0827966980a4 100644 --- a/net/mac80211/ap.c +++ b/net/mac80211/ap.c @@ -66,7 +66,8 @@ ieee80211_rx_eml_op_mode_notif(struct ieee80211_sub_if_data *sdata, struct sta_info *sta; int opt_len = 0; - if (!ieee80211_vif_is_mld(&sdata->vif)) + if (!ieee80211_vif_is_mld(&sdata->vif) || + status->link_id == IEEE80211_LINK_UNSPECIFIED) return; /* eMLSR and eMLMR can't be enabled at the same time */ diff --git a/net/mac80211/driver-ops.c b/net/mac80211/driver-ops.c index 1f3e0765a8ab..d19ae7fbcb6a 100644 --- a/net/mac80211/driver-ops.c +++ b/net/mac80211/driver-ops.c @@ -659,12 +659,14 @@ int drv_sta_statistics(struct ieee80211_local *local, &sdata->vif, sta, sinfo); } else { - ret = -EAGAIN; + ret = 0; if (local->ops->sta_statistics_atomic) ret = local->ops->sta_statistics_atomic(&local->hw, &sdata->vif, sta, sinfo); + else if (local->ops->sta_statistics) + ret = -EAGAIN; } trace_drv_return_int(local, ret); @@ -684,6 +686,8 @@ int drv_link_sta_statistics(struct ieee80211_local *local, if (!check_sdata_in_driver(sdata)) return 0; + trace_drv_link_sta_statistics(local, sdata, link_sta); + if (locked) { might_sleep(); lockdep_assert_wiphy(local->hw.wiphy); @@ -696,16 +700,18 @@ int drv_link_sta_statistics(struct ieee80211_local *local, link_sta, link_sinfo); } else { - ret = -EAGAIN; + ret = 0; - if (local->ops->sta_statistics_atomic) + if (local->ops->link_sta_statistics_atomic) ret = local->ops->link_sta_statistics_atomic(&local->hw, &sdata->vif, link_sta, link_sinfo); + else if (local->ops->link_sta_statistics) + ret = -EAGAIN; } trace_drv_return_int(local, ret); - return 0; + return ret; } diff --git a/net/mac80211/ibss.c b/net/mac80211/ibss.c index d74b66426349..69c462c71e92 100644 --- a/net/mac80211/ibss.c +++ b/net/mac80211/ibss.c @@ -669,6 +669,10 @@ static void ieee80211_ibss_disconnect(struct ieee80211_sub_if_data *sdata) ifibss->state = IEEE80211_IBSS_MLME_SEARCH; netif_carrier_off(sdata->dev); + + sdata->vif.bss_conf.csa_active = false; + ieee80211_vif_unblock_queues_csa(sdata); + if (!sta_info_flush(sdata, -1)) synchronize_net(); @@ -680,6 +684,7 @@ static void ieee80211_ibss_disconnect(struct ieee80211_sub_if_data *sdata) spin_unlock_bh(&ifibss->incomplete_lock); sta_info_free(local, sta); + atomic_dec(&ifibss->incomplete_sta_count); spin_lock_bh(&ifibss->incomplete_lock); } spin_unlock_bh(&ifibss->incomplete_lock); @@ -1173,9 +1178,18 @@ void ieee80211_ibss_rx_no_sta(struct ieee80211_sub_if_data *sdata, band = chanctx_conf->def.chan->band; rcu_read_unlock(); + if (!atomic_add_unless(&ifibss->incomplete_sta_count, 1, + IEEE80211_IBSS_MAX_STA_ENTRIES)) { + net_info_ratelimited("%s: No room for a new IBSS STA entry %pM\n", + sdata->name, addr); + return; + } + sta = sta_info_alloc(sdata, addr, GFP_ATOMIC); - if (!sta) + if (!sta) { + atomic_dec(&ifibss->incomplete_sta_count); return; + } /* make sure mandatory rates are always added */ sband = local->hw.wiphy->bands[band]; @@ -1626,8 +1640,13 @@ void ieee80211_ibss_work(struct ieee80211_sub_if_data *sdata) list_del(&sta->list); spin_unlock_bh(&ifibss->incomplete_lock); - ieee80211_ibss_finish_sta(sta); - rcu_read_unlock(); + if (sdata->local->num_sta >= IEEE80211_IBSS_MAX_STA_ENTRIES) { + sta_info_free(sdata->local, sta); + } else { + ieee80211_ibss_finish_sta(sta); + rcu_read_unlock(); + } + atomic_dec(&ifibss->incomplete_sta_count); spin_lock_bh(&ifibss->incomplete_lock); } spin_unlock_bh(&ifibss->incomplete_lock); diff --git a/net/mac80211/ieee80211_i.h b/net/mac80211/ieee80211_i.h index 1a6cbbb5a17d..7a64aef6890d 100644 --- a/net/mac80211/ieee80211_i.h +++ b/net/mac80211/ieee80211_i.h @@ -693,6 +693,7 @@ struct ieee80211_if_ibss { spinlock_t incomplete_lock; struct list_head incomplete_stations; + atomic_t incomplete_sta_count; enum { IEEE80211_IBSS_MLME_SEARCH, @@ -707,6 +708,7 @@ struct ieee80211_if_ibss { * @wrkq_flags: OCB deferred task action * @incomplete_lock: delayed STA insertion lock * @incomplete_stations: list of STAs waiting for delayed insertion + * @incomplete_sta_count: pending entries and reserved allocations * @joined: indication if the interface is connected to an OCB network */ struct ieee80211_if_ocb { @@ -715,6 +717,7 @@ struct ieee80211_if_ocb { spinlock_t incomplete_lock; struct list_head incomplete_stations; + atomic_t incomplete_sta_count; bool joined; }; diff --git a/net/mac80211/iface.c b/net/mac80211/iface.c index d0b0a503b229..63a371c79183 100644 --- a/net/mac80211/iface.c +++ b/net/mac80211/iface.c @@ -1712,8 +1712,11 @@ static void ieee80211_iface_process_skb(struct ieee80211_local *local, break; status = IEEE80211_SKB_RXCB(skb); - link_sta = wiphy_dereference(local->hw.wiphy, - sta->link[status->link_id]); + if (status->link_id == IEEE80211_LINK_UNSPECIFIED) + link_sta = &sta->deflink; + else + link_sta = wiphy_dereference(local->hw.wiphy, + sta->link[status->link_id]); if (link_sta) ieee80211_ht_handle_chanwidth_notif(local, sdata, sta, link_sta, chanwidth, diff --git a/net/mac80211/link.c b/net/mac80211/link.c index ce1c95b40cd9..f43c0dec8cc9 100644 --- a/net/mac80211/link.c +++ b/net/mac80211/link.c @@ -192,6 +192,7 @@ struct link_container { static void ieee80211_tear_down_links(struct ieee80211_sub_if_data *sdata, struct link_container **links, u16 mask) { + struct ieee80211_link_data *stop[IEEE80211_MLD_MAX_NUM_LINKS] = {}; struct ieee80211_link_data *link; LIST_HEAD(keys); unsigned int link_id; @@ -206,11 +207,16 @@ static void ieee80211_tear_down_links(struct ieee80211_sub_if_data *sdata, continue; ieee80211_remove_link_keys(link, &keys); ieee80211_link_debugfs_remove(link); - ieee80211_link_stop(link); + stop[link_id] = link; } + /* drain RCU readers before cancelling work they may queue */ synchronize_rcu(); + for (link_id = 0; link_id < IEEE80211_MLD_MAX_NUM_LINKS; link_id++) + if (stop[link_id]) + ieee80211_link_stop(stop[link_id]); + ieee80211_free_key_list(sdata->local, &keys); } @@ -291,6 +297,7 @@ static int ieee80211_vif_update_links(struct ieee80211_sub_if_data *sdata, { u16 old_links = sdata->vif.valid_links; u16 old_active = sdata->vif.active_links; + u16 old_dormant = sdata->vif.dormant_links; unsigned long add = new_links & ~old_links; unsigned long rem = old_links & ~new_links; unsigned long sta_rem = rem; @@ -400,7 +407,9 @@ static int ieee80211_vif_update_links(struct ieee80211_sub_if_data *sdata, /* restore config */ memcpy(sdata->link, old_data, sizeof(old_data)); memcpy(sdata->vif.link_conf, old, sizeof(old)); - ieee80211_set_vif_links_bitmaps(sdata, old_links, dormant_links); + ieee80211_set_vif_links_bitmaps(sdata, old_links, old_dormant); + /* drain RCU readers before cancelling work they may queue */ + synchronize_rcu(); for_each_set_bit(link_id, &add, IEEE80211_MLD_MAX_NUM_LINKS) { ieee80211_link_debugfs_remove(&links[link_id]->data); ieee80211_link_stop(&links[link_id]->data); diff --git a/net/mac80211/mlme.c b/net/mac80211/mlme.c index 6ec45a9f7221..b5efc6ccc985 100644 --- a/net/mac80211/mlme.c +++ b/net/mac80211/mlme.c @@ -7872,15 +7872,15 @@ static void ieee80211_tid_to_link_map_work(struct wiphy *wiphy, sdata->u.mgd.ttlm_info.switch_time = 0; } -static void ieee80211_process_adv_ttlm(struct ieee80211_sub_if_data *sdata, - struct ieee802_11_elems *elems, - u64 beacon_ts) +static bool ieee80211_process_adv_ttlm(struct ieee80211_sub_if_data *sdata, + struct ieee802_11_elems *elems, + u64 beacon_ts) { u8 i; int ret; if (!ieee80211_vif_is_mld(&sdata->vif)) - return; + return true; if (!elems->ttlm_num) { if (sdata->u.mgd.ttlm_info.switch_time) { @@ -7898,14 +7898,14 @@ static void ieee80211_process_adv_ttlm(struct ieee80211_sub_if_data *sdata, 0); if (ret) { sdata_info(sdata, "Failed setting valid/dormant links\n"); - return; + return true; } ieee80211_vif_cfg_change_notify(sdata, BSS_CHANGED_MLD_VALID_LINKS); } memset(&sdata->u.mgd.ttlm_info, 0, sizeof(sdata->u.mgd.ttlm_info)); - return; + return true; } for (i = 0; i < elems->ttlm_num; i++) { @@ -7917,7 +7917,7 @@ static void ieee80211_process_adv_ttlm(struct ieee80211_sub_if_data *sdata, if (res) { __ieee80211_disconnect(sdata); - return; + return false; } if (ttlm_info.switch_time) { @@ -7942,7 +7942,7 @@ static void ieee80211_process_adv_ttlm(struct ieee80211_sub_if_data *sdata, * switch the AP will continue to announce it anyway. */ if (delay > IEEE80211_ADV_TTLM_ST_UNDERFLOW) - return; + return true; delay_usec = ieee80211_tu_to_usec(delay); @@ -7961,9 +7961,11 @@ static void ieee80211_process_adv_ttlm(struct ieee80211_sub_if_data *sdata, wiphy_hrtimer_work_queue(sdata->local->hw.wiphy, &sdata->u.mgd.ttlm_work, us_to_ktime(delay_usec)); - return; + return true; } } + + return true; } static void @@ -8486,8 +8488,9 @@ static void ieee80211_rx_mgmt_beacon(struct ieee80211_link_data *link, elems->cisco_dtpc_elem); ieee80211_ml_reconfiguration(sdata, elems); - ieee80211_process_adv_ttlm(sdata, elems, - le64_to_cpu(mgmt->u.beacon.timestamp)); + if (!ieee80211_process_adv_ttlm(sdata, elems, + le64_to_cpu(mgmt->u.beacon.timestamp))) + goto free; apply: ieee80211_link_info_change_notify(sdata, link, changed); @@ -11894,10 +11897,12 @@ void ieee80211_sta_rx_queued_frame(struct ieee80211_sub_if_data *sdata, rx_status = (struct ieee80211_rx_status *) skb->cb; fc = le16_to_cpu(mgmt->frame_control); - link = sdata_dereference(sdata->link[rx_status->link_id], - sdata); - if (!link) - return; + if (rx_status->link_id != IEEE80211_LINK_UNSPECIFIED) { + link = sdata_dereference(sdata->link[rx_status->link_id], + sdata); + if (!link) + return; + } switch (fc & IEEE80211_FCTL_STYPE) { case IEEE80211_STYPE_BEACON: diff --git a/net/mac80211/ocb.c b/net/mac80211/ocb.c index e9bf4ba3e60b..90c43eec61e3 100644 --- a/net/mac80211/ocb.c +++ b/net/mac80211/ocb.c @@ -70,9 +70,18 @@ void ieee80211_ocb_rx_no_sta(struct ieee80211_sub_if_data *sdata, band = chanctx_conf->def.chan->band; rcu_read_unlock(); + if (!atomic_add_unless(&ifocb->incomplete_sta_count, 1, + IEEE80211_OCB_MAX_STA_ENTRIES)) { + net_info_ratelimited("%s: No room for a new OCB STA entry %pM\n", + sdata->name, addr); + return; + } + sta = sta_info_alloc(sdata, addr, GFP_ATOMIC); - if (!sta) + if (!sta) { + atomic_dec(&ifocb->incomplete_sta_count); return; + } /* Add only mandatory rates for now */ sband = local->hw.wiphy->bands[band]; @@ -139,8 +148,13 @@ void ieee80211_ocb_work(struct ieee80211_sub_if_data *sdata) list_del(&sta->list); spin_unlock_bh(&ifocb->incomplete_lock); - ieee80211_ocb_finish_sta(sta); - rcu_read_unlock(); + if (sdata->local->num_sta >= IEEE80211_OCB_MAX_STA_ENTRIES) { + sta_info_free(sdata->local, sta); + } else { + ieee80211_ocb_finish_sta(sta); + rcu_read_unlock(); + } + atomic_dec(&ifocb->incomplete_sta_count); spin_lock_bh(&ifocb->incomplete_lock); } spin_unlock_bh(&ifocb->incomplete_lock); @@ -224,6 +238,7 @@ int ieee80211_ocb_leave(struct ieee80211_sub_if_data *sdata) spin_unlock_bh(&ifocb->incomplete_lock); sta_info_free(local, sta); + atomic_dec(&ifocb->incomplete_sta_count); spin_lock_bh(&ifocb->incomplete_lock); } spin_unlock_bh(&ifocb->incomplete_lock); diff --git a/net/mac80211/rx.c b/net/mac80211/rx.c index ecee9348c70d..f8cfd04c0c6c 100644 --- a/net/mac80211/rx.c +++ b/net/mac80211/rx.c @@ -2905,9 +2905,6 @@ ieee80211_rx_mesh_fast_forward(struct ieee80211_sub_if_data *sdata, if (!sta) return false; - if (skb_linearize(skb)) - return false; - tid = skb->priority & IEEE80211_QOS_CTL_TAG1D_MASK; tid_tx = rcu_dereference(sta->ampdu_mlme.tid_tx[tid]); if (tid_tx) { @@ -2918,6 +2915,10 @@ ieee80211_rx_mesh_fast_forward(struct ieee80211_sub_if_data *sdata, tid_tx->last_tx = jiffies; } + /* this function must not fail after this */ + if (skb_linearize(skb)) + return false; + ieee80211_aggr_check(sdata, sta, skb); if (ieee80211_get_8023_tunnel_proto(skb->data + hdrlen, @@ -4232,6 +4233,7 @@ static void ieee80211_rx_handlers(struct ieee80211_rx_data *rx, while ((skb = __skb_dequeue(frames))) { struct ieee80211_rx_status *status = IEEE80211_SKB_RXCB(skb); + int link_id; /* * Most fields are valid across frames. However, @@ -4240,18 +4242,27 @@ static void ieee80211_rx_handlers(struct ieee80211_rx_data *rx, * and link_sta accordingly. */ rx->skb = skb; + link_id = status->link_id == IEEE80211_LINK_UNSPECIFIED ? -1 : status->link_id; if (ieee80211_vif_is_mld(&rx->sdata->vif) && - unlikely(rx->link_id != status->link_id)) { + unlikely(rx->link_id != link_id)) { + rx->link_id = link_id; + + if (link_id >= 0) + rx->link = rcu_dereference(rx->sdata->link[link_id]); + else + rx->link = &rx->sdata->deflink; + if (rx->sta) { - rx->link_sta = - rcu_dereference(rx->sta->link[rx->link_id]); + if (WARN_ON_ONCE(link_id < 0)) + rx->link_sta = NULL; + else + rx->link_sta = + rcu_dereference(rx->sta->link[link_id]); - /* Link got disabled, just use deflink */ + /* Link disabled or invalid, just use deflink */ if (!rx->link_sta) rx->link_sta = &rx->sta->deflink; } - rx->link_id = status->link_id; - rx->link = rcu_dereference(rx->sdata->link[status->link_id]); } if (WARN_ON_ONCE(!rx->link)) { @@ -5184,7 +5195,8 @@ static bool ieee80211_invoke_fast_rx(struct ieee80211_rx_data *rx, } status = IEEE80211_SKB_RXCB(skb); - status->link_id = rx->link_id < 0 ? 0 : rx->link_id; + status->link_id = + rx->link_id < 0 ? IEEE80211_LINK_UNSPECIFIED : rx->link_id; ieee80211_rx_8023(rx, fast_rx, orig_len); @@ -5255,7 +5267,8 @@ static bool ieee80211_prepare_and_rx_handle(struct ieee80211_rx_data *rx, } status = IEEE80211_SKB_RXCB(rx->skb); - status->link_id = rx->link_id < 0 ? 0 : rx->link_id; + status->link_id = + rx->link_id < 0 ? IEEE80211_LINK_UNSPECIFIED : rx->link_id; if (ieee80211_is_s1g_beacon(hdr->frame_control)) { ieee80211_invoke_rx_handlers(rx); @@ -5348,6 +5361,29 @@ static bool ieee80211_rx_valid_freq(int freq, struct ieee80211_link_data *link) return freq == conf->def.chan->center_freq; } +static struct ieee80211_link_data * +ieee80211_link_from_freq(struct ieee80211_sub_if_data *sdata, int freq) +{ + struct ieee80211_link_data *link; + + if (ieee80211_vif_is_mld(&sdata->vif)) { + struct ieee80211_chanctx_conf *conf; + + for_each_link_data_rcu(sdata, link) { + conf = rcu_dereference(link->conf->chanctx_conf); + if (!conf || !conf->def.chan) + continue; + + if (freq == conf->def.chan->center_freq) + return link; + } + + return &sdata->deflink; + } + + return &sdata->deflink; +} + /* * This is the actual Rx frames handler. as it belongs to Rx path it must * be called with rcu_read_lock protection. @@ -5508,6 +5544,7 @@ static void __ieee80211_rx_handle_packet(struct ieee80211_hw *hw, list_for_each_entry_rcu(sdata, &local->interfaces, list) { struct ieee80211_link_data *link = NULL; + const u8 *addr = hdr->addr2; if (!ieee80211_sdata_running(sdata)) continue; @@ -5519,16 +5556,32 @@ static void __ieee80211_rx_handle_packet(struct ieee80211_hw *hw, link_sta = NULL; link = NULL; + /* + * Switch to do the STA lookup using the non-transmitted BSSID + * for beacon frames from the transmitted BSSID. This ensures + * that the keys for beacon protection are available during + * later processing. + */ + if (ieee80211_is_beacon(fc) && + sdata->vif.type == NL80211_IFTYPE_STATION) { + link = ieee80211_link_from_freq(sdata, status->freq); + + if (link->conf->nontransmitted && + ether_addr_equal(addr, + link->conf->transmitter_bssid)) + addr = link->conf->bssid; + } + /* Try to resolve the station */ if (!ieee80211_vif_is_mld(&sdata->vif)) { - sta = sta_info_get_bss(sdata, hdr->addr2); + sta = sta_info_get_bss(sdata, addr); if (sta) { link_sta = &sta->deflink; link = &sdata->deflink; } } else { - link_sta = link_sta_info_get_bss(sdata, hdr->addr2); + link_sta = link_sta_info_get_bss(sdata, addr); if (link_sta) link = rcu_dereference(sdata->link[link_sta->link_id]); @@ -5555,26 +5608,7 @@ static void __ieee80211_rx_handle_packet(struct ieee80211_hw *hw, } /* No station, try to resolve the link and RX */ - if (ieee80211_vif_is_mld(&sdata->vif)) { - struct ieee80211_chanctx_conf *conf; - bool found = false; - - for_each_link_data_rcu(sdata, link) { - conf = rcu_dereference(link->conf->chanctx_conf); - if (!conf || !conf->def.chan) - continue; - - if (status->freq == conf->def.chan->center_freq) { - found = true; - break; - } - } - - if (!found) - link = &sdata->deflink; - } else { - link = &sdata->deflink; - } + link = ieee80211_link_from_freq(sdata, status->freq); if (rx_data_pending) { ieee80211_prepare_and_rx_handle(&rx, skb, false); diff --git a/net/mac80211/scan.c b/net/mac80211/scan.c index 8a66d2e020f9..69eb991d9b5a 100644 --- a/net/mac80211/scan.c +++ b/net/mac80211/scan.c @@ -214,8 +214,9 @@ ieee80211_bss_info_update(struct ieee80211_local *local, if (ieee80211_vif_is_mld(&scan_sdata->vif)) { s8 link_id = rx_status->link_id; - link_conf = - rcu_dereference(scan_sdata->vif.link_conf[link_id]); + if (link_id != IEEE80211_LINK_UNSPECIFIED) + link_conf = + rcu_dereference(scan_sdata->vif.link_conf[link_id]); } else { link_conf = &scan_sdata->vif.bss_conf; } diff --git a/net/mac80211/tx.c b/net/mac80211/tx.c index 0f46b5ff0c4a..6e70e2046d1a 100644 --- a/net/mac80211/tx.c +++ b/net/mac80211/tx.c @@ -2591,6 +2591,12 @@ netdev_tx_t ieee80211_monitor_start_xmit(struct sk_buff *skb, /* remove the injection radiotap header */ skb_pull(skb, len_rthdr); + /* FCS removal may have shortened the 802.11 header. */ + hdrlen = max_t(int, hdrlen, + offsetofend(struct ieee80211_hdr, addr1)); + if (skb_headlen(skb) < hdrlen) + goto fail_rcu; + ieee80211_xmit(sdata, NULL, skb); rcu_read_unlock(); diff --git a/net/mctp/af_mctp.c b/net/mctp/af_mctp.c index 8af5e2b3c8d1..aa22c0860712 100644 --- a/net/mctp/af_mctp.c +++ b/net/mctp/af_mctp.c @@ -292,7 +292,7 @@ static int mctp_recvmsg(struct socket *sock, struct msghdr *msg, size_t len, u8 type; int rc; - if (flags & ~(MSG_DONTWAIT | MSG_TRUNC | MSG_PEEK)) + if (flags & ~(MSG_DONTWAIT | MSG_TRUNC | MSG_PEEK | MSG_CMSG_COMPAT)) return -EOPNOTSUPP; skb = skb_recv_datagram(sk, flags, &rc); diff --git a/net/mptcp/options.c b/net/mptcp/options.c index 64aa7a516a23..02e785a14b8a 100644 --- a/net/mptcp/options.c +++ b/net/mptcp/options.c @@ -1122,9 +1122,9 @@ static void ack_update_msk(struct mptcp_sock *msk, struct sock *ssk, struct mptcp_options_received *mp_opt) { - u64 new_wnd_end, new_snd_una, snd_nxt = READ_ONCE(msk->snd_nxt); + u64 new_wnd_end, new_snd_una, old_snd_una; struct sock *sk = (struct sock *)msk; - u64 old_snd_una; + u64 snd_nxt; mptcp_data_lock(sk); @@ -1133,10 +1133,14 @@ static void ack_update_msk(struct mptcp_sock *msk, * more dangerous than missing an ack */ old_snd_una = msk->snd_una; + snd_nxt = READ_ONCE(msk->snd_nxt); new_snd_una = mptcp_expand_seq(old_snd_una, mp_opt->data_ack, mp_opt->ack64); - /* ACK for data not even sent yet? Ignore.*/ - if (unlikely(after64(new_snd_una, snd_nxt))) + /* The active-open state sync can defer the snd_nxt update. Do not + * accept an ACK against a reversed interval, or beyond snd_nxt. + */ + if (unlikely(before64(snd_nxt, old_snd_una) || + after64(new_snd_una, snd_nxt))) new_snd_una = old_snd_una; new_wnd_end = new_snd_una + tcp_sk(ssk)->snd_wnd; diff --git a/net/mptcp/protocol.c b/net/mptcp/protocol.c index 7a22e9388e0e..8968db58083e 100644 --- a/net/mptcp/protocol.c +++ b/net/mptcp/protocol.c @@ -1920,10 +1920,12 @@ static int mptcp_sendmsg_fastopen(struct sock *sk, struct msghdr *msg, msg->msg_flags = saved_flags; release_sock(ssk); + inet_clear_bit(DEFER_CONNECT, sk); + /* do the blocking bits of inet_stream_connect outside the ssk socket lock */ if (ret == -EINPROGRESS && !(msg->msg_flags & MSG_DONTWAIT)) { ret = __inet_stream_connect(sk->sk_socket, msg->msg_name, - msg->msg_namelen, msg->msg_flags, 1); + msg->msg_namelen, msg->msg_flags, true); /* Keep the same behaviour of plain TCP: zero the copied bytes in * case of any error, except timeout or signal @@ -1941,7 +1943,6 @@ static int mptcp_sendmsg_fastopen(struct sock *sk, struct msghdr *msg, sk->sk_socket->state = SS_UNCONNECTED; } } - inet_clear_bit(DEFER_CONNECT, sk); return ret; } diff --git a/net/netfilter/ipvs/ip_vs_app.c b/net/netfilter/ipvs/ip_vs_app.c index 11cbdbaf561d..2c1b47702da2 100644 --- a/net/netfilter/ipvs/ip_vs_app.c +++ b/net/netfilter/ipvs/ip_vs_app.c @@ -242,7 +242,7 @@ void unregister_ip_vs_app(struct netns_ipvs *ipvs, struct ip_vs_app *app) } list_del(&a->a_list); - kfree(a); + kfree_rcu(a, rcu_head); /* decrease the module use count */ ip_vs_use_count_dec(); diff --git a/net/netfilter/ipvs/ip_vs_core.c b/net/netfilter/ipvs/ip_vs_core.c index fd503f0efb57..8a3c880fdb26 100644 --- a/net/netfilter/ipvs/ip_vs_core.c +++ b/net/netfilter/ipvs/ip_vs_core.c @@ -2502,12 +2502,12 @@ static int __net_init __ip_vs_init(struct net *net) if (ip_vs_estimator_net_init(ipvs) < 0) goto estimator_fail; - if (ip_vs_control_net_init(ipvs) < 0) - goto control_fail; - if (ip_vs_protocol_net_init(ipvs) < 0) goto protocol_fail; + if (ip_vs_control_net_init(ipvs) < 0) + goto control_fail; + if (ip_vs_app_net_init(ipvs) < 0) goto app_fail; @@ -2527,10 +2527,10 @@ sync_fail: conn_fail: ip_vs_app_net_cleanup(ipvs); app_fail: - ip_vs_protocol_net_cleanup(ipvs); -protocol_fail: ip_vs_control_net_cleanup(ipvs); control_fail: + ip_vs_protocol_net_cleanup(ipvs); +protocol_fail: ip_vs_estimator_net_cleanup(ipvs); estimator_fail: net->ipvs = NULL; @@ -2547,8 +2547,8 @@ static void __net_exit __ip_vs_cleanup_batch(struct list_head *net_list) ipvs = net_ipvs(net); ip_vs_conn_net_cleanup(ipvs); ip_vs_app_net_cleanup(ipvs); - ip_vs_protocol_net_cleanup(ipvs); ip_vs_control_net_cleanup(ipvs); + ip_vs_protocol_net_cleanup(ipvs); ip_vs_estimator_net_cleanup(ipvs); IP_VS_DBG(2, "ipvs netns %d released\n", ipvs->gen); net->ipvs = NULL; diff --git a/net/netfilter/nf_conntrack_sip.c b/net/netfilter/nf_conntrack_sip.c index 64bc440b1181..b05dc8858d09 100644 --- a/net/netfilter/nf_conntrack_sip.c +++ b/net/netfilter/nf_conntrack_sip.c @@ -701,9 +701,9 @@ static int ct_sip_parse_transport(struct nf_conn *ct, const char *dptr, if (ct_sip_parse_param(ct, dptr, dataoff, datalen, "transport=", &matchoff, &matchlen)) { - if (!strncasecmp(dptr + matchoff, "TCP", strlen("TCP"))) + if (matchlen >= 3 && !strncasecmp(dptr + matchoff, "TCP", 3)) *proto = IPPROTO_TCP; - else if (!strncasecmp(dptr + matchoff, "UDP", strlen("UDP"))) + else if (matchlen >= 3 && !strncasecmp(dptr + matchoff, "UDP", 3)) *proto = IPPROTO_UDP; else return 0; diff --git a/net/netfilter/nf_dup_netdev.c b/net/netfilter/nf_dup_netdev.c index c6bd5c29bed6..918716629c15 100644 --- a/net/netfilter/nf_dup_netdev.c +++ b/net/netfilter/nf_dup_netdev.c @@ -12,6 +12,7 @@ #include <net/netfilter/nf_tables.h> #include <net/netfilter/nf_tables_offload.h> #include <net/netfilter/nf_dup_netdev.h> +#include <net/netfilter/nf_recursion.h> static void nf_do_netdev_egress(struct sk_buff *skb, struct net_device *dev, enum nf_dev_hooks hook) diff --git a/net/netfilter/nf_flow_table_core.c b/net/netfilter/nf_flow_table_core.c index 0d72dc8ae47a..2aa2647ed9df 100644 --- a/net/netfilter/nf_flow_table_core.c +++ b/net/netfilter/nf_flow_table_core.c @@ -544,6 +544,7 @@ static void nf_flow_table_extend_ct_timeout(struct nf_conn *ct) switch (l4proto) { case IPPROTO_UDP: + case IPPROTO_GRE: new_timeout = NF_CT_DAY; break; case IPPROTO_TCP: diff --git a/net/netfilter/nf_nat_masquerade.c b/net/netfilter/nf_nat_masquerade.c index 4de6e0a51701..c2a85bd84af1 100644 --- a/net/netfilter/nf_nat_masquerade.c +++ b/net/netfilter/nf_nat_masquerade.c @@ -62,8 +62,7 @@ nf_nat_masquerade_ipv4(struct sk_buff *skb, unsigned int hooknum, nat->masq_index = out->ifindex; /* Transfer from original range. */ - memset(&newrange.min_addr, 0, sizeof(newrange.min_addr)); - memset(&newrange.max_addr, 0, sizeof(newrange.max_addr)); + memset(&newrange, 0, sizeof(newrange)); newrange.flags = range->flags | NF_NAT_RANGE_MAP_IPS; newrange.min_addr.ip = newsrc; newrange.max_addr.ip = newsrc; @@ -242,6 +241,7 @@ nf_nat_masquerade_ipv6(struct sk_buff *skb, const struct nf_nat_range2 *range, if (nat) nat->masq_index = out->ifindex; + memset(&newrange, 0, sizeof(newrange)); newrange.flags = range->flags | NF_NAT_RANGE_MAP_IPS; newrange.min_addr.in6 = src; newrange.max_addr.in6 = src; diff --git a/net/netfilter/nf_queue.c b/net/netfilter/nf_queue.c index 166d05e994ac..bd603e3a99a5 100644 --- a/net/netfilter/nf_queue.c +++ b/net/netfilter/nf_queue.c @@ -219,6 +219,7 @@ static int __nf_queue(struct sk_buff *skb, const struct nf_hook_state *state, *entry = (struct nf_queue_entry) { .skb = skb, .skb_dev = skb->dev, + .in_nf_duplicate = current->in_nf_duplicate, .state = *state, .hook_index = index, .size = sizeof(*entry) + route_key_size, diff --git a/net/netfilter/nf_tables_api.c b/net/netfilter/nf_tables_api.c index 59ac623e6805..8b94b5e7dbdb 100644 --- a/net/netfilter/nf_tables_api.c +++ b/net/netfilter/nf_tables_api.c @@ -760,16 +760,6 @@ static int nft_delrule(struct nft_ctx *ctx, struct nft_rule *rule) if (trans == NULL) return -ENOMEM; - if (ctx->chain->flags & NFT_CHAIN_HW_OFFLOAD) { - flow = nft_flow_rule_create(ctx->net, rule); - if (IS_ERR(flow)) { - nft_trans_destroy(trans); - return PTR_ERR(flow); - } - - nft_trans_flow_rule(trans) = flow; - } - err = nf_tables_delrule_deactivate(ctx, rule); if (err < 0) { nft_trans_destroy(trans); @@ -777,6 +767,14 @@ static int nft_delrule(struct nft_ctx *ctx, struct nft_rule *rule) } nft_rule_expr_deactivate(ctx, rule, NFT_TRANS_PREPARE); + if (ctx->chain->flags & NFT_CHAIN_HW_OFFLOAD) { + flow = nft_flow_rule_create(ctx->net, rule); + if (IS_ERR(flow)) + return PTR_ERR(flow); + + nft_trans_flow_rule(trans) = flow; + } + return 0; } @@ -4570,8 +4568,7 @@ static int nf_tables_newrule(struct sk_buff *skb, const struct nfnl_info *info, err_destroy_flow_rule: nft_use_dec_restore(&chain->use); err_destroy_flow: - if (flow) - nft_flow_rule_destroy(flow); + nft_flow_rule_destroy(flow); err_release_rule: nft_rule_expr_deactivate(&ctx, rule, NFT_TRANS_PREPARE_ERROR); nf_tables_rule_destroy(&ctx, rule); diff --git a/net/netfilter/nf_tables_offload.c b/net/netfilter/nf_tables_offload.c index 0ac3c26dfb3d..48b9e58e0c44 100644 --- a/net/netfilter/nf_tables_offload.c +++ b/net/netfilter/nf_tables_offload.c @@ -148,6 +148,9 @@ void nft_flow_rule_destroy(struct nft_flow_rule *flow) struct flow_action_entry *entry; int i; + if (!flow) + return; + flow_action_for_each(i, entry, &flow->rule->action) { switch (entry->id) { case FLOW_ACTION_REDIRECT: diff --git a/net/netfilter/nfnetlink_queue.c b/net/netfilter/nfnetlink_queue.c index 90d887546f7d..a8aa7ad832c3 100644 --- a/net/netfilter/nfnetlink_queue.c +++ b/net/netfilter/nfnetlink_queue.c @@ -44,6 +44,7 @@ #include <net/sock.h> #include <net/tcp_states.h> #include <net/netfilter/nf_queue.h> +#include <net/net_debug.h> #include <net/netns/generic.h> #include <linux/atomic.h> @@ -365,21 +366,30 @@ static void nf_reinject(struct nf_queue_entry *entry, unsigned int verdict) const struct nf_hook_entry *hook_entry; const struct nf_hook_entries *hooks; struct sk_buff *skb = entry->skb; + bool old_in_nf_duplicate; const struct net *net; unsigned int i; int err; u8 pf; + DEBUG_NET_WARN_ONCE(current->in_nf_duplicate && + !entry->in_nf_duplicate, + "%s called with unexpected duplication guard", + __func__); + local_bh_disable(); + old_in_nf_duplicate = current->in_nf_duplicate; + net = entry->state.net; pf = entry->state.pf; + current->in_nf_duplicate = entry->in_nf_duplicate; hooks = nf_hook_entries_head(net, pf, entry->state.hook); i = entry->hook_index; if (!hooks || i >= hooks->num_hook_entries) { kfree_skb_reason(skb, SKB_DROP_REASON_NETFILTER_DROP); nf_queue_entry_free(entry); - return; + goto out; } hook_entry = &hooks->hooks[i]; @@ -402,9 +412,7 @@ next_hook: switch (verdict & NF_VERDICT_MASK) { case NF_ACCEPT: case NF_STOP: - local_bh_disable(); entry->state.okfn(entry->state.net, entry->state.sk, skb); - local_bh_enable(); break; case NF_QUEUE: err = nf_queue(skb, &entry->state, i, verdict); @@ -418,6 +426,9 @@ next_hook: } nf_queue_entry_free(entry); +out: + current->in_nf_duplicate = old_in_nf_duplicate; + local_bh_enable(); } /* return true if the entry has an unconfirmed conntrack attached that isn't owned by us diff --git a/net/netfilter/nft_fwd_netdev.c b/net/netfilter/nft_fwd_netdev.c index a48c2f765bba..7447da931a95 100644 --- a/net/netfilter/nft_fwd_netdev.c +++ b/net/netfilter/nft_fwd_netdev.c @@ -14,6 +14,7 @@ #include <net/netfilter/nf_tables.h> #include <net/netfilter/nf_tables_offload.h> #include <net/netfilter/nf_dup_netdev.h> +#include <net/netfilter/nf_recursion.h> #include <net/neighbour.h> #include <net/ip.h> diff --git a/net/netfilter/nft_set_rbtree.c b/net/netfilter/nft_set_rbtree.c index fbe1750f1ca2..9d685899da70 100644 --- a/net/netfilter/nft_set_rbtree.c +++ b/net/netfilter/nft_set_rbtree.c @@ -953,7 +953,8 @@ static void nft_rbtree_gc_queue(struct nft_set *set) } gc = nft_trans_gc_catchall_sync(gc); - nft_trans_gc_queue_sync_done(gc); + if (gc) + nft_trans_gc_queue_sync_done(gc); } static u64 nft_rbtree_privsize(const struct nlattr * const nla[], diff --git a/net/netfilter/xt_NETMAP.c b/net/netfilter/xt_NETMAP.c index 7da065a472e0..8bcb3f716d68 100644 --- a/net/netfilter/xt_NETMAP.c +++ b/net/netfilter/xt_NETMAP.c @@ -44,6 +44,7 @@ netmap_tg6(struct sk_buff *skb, const struct xt_action_param *par) netmask.ip6[i]; } + memset(&newrange, 0, sizeof(newrange)); newrange.flags = range->flags | NF_NAT_RANGE_MAP_IPS; newrange.min_addr = new_addr; newrange.max_addr = new_addr; @@ -91,8 +92,7 @@ netmap_tg4(struct sk_buff *skb, const struct xt_action_param *par) new_ip = ip_hdr(skb)->saddr & ~netmask; new_ip |= mr->range[0].min_ip & netmask; - memset(&newrange.min_addr, 0, sizeof(newrange.min_addr)); - memset(&newrange.max_addr, 0, sizeof(newrange.max_addr)); + memset(&newrange, 0, sizeof(newrange)); newrange.flags = mr->range[0].flags | NF_NAT_RANGE_MAP_IPS; newrange.min_addr.ip = new_ip; newrange.max_addr.ip = new_ip; diff --git a/net/netfilter/xt_recent.c b/net/netfilter/xt_recent.c index 55f1f2d89952..00cccf003cff 100644 --- a/net/netfilter/xt_recent.c +++ b/net/netfilter/xt_recent.c @@ -650,14 +650,15 @@ static void __net_exit recent_proc_net_exit(struct net *net) /* recent_net_exit() is called before recent_mt_destroy(). Make sure * that the parent xt_recent proc entry is empty before trying to - * remove it. + * remove it. Use recent_mutex instead of recent_lock since + * remove_proc_entry() may sleep. */ - spin_lock_bh(&recent_lock); + mutex_lock(&recent_mutex); list_for_each_entry(t, &recent_net->tables, list) remove_proc_entry(t->name, recent_net->xt_recent); recent_net->xt_recent = NULL; - spin_unlock_bh(&recent_lock); + mutex_unlock(&recent_mutex); remove_proc_entry("xt_recent", net->proc_net); } diff --git a/net/netlabel/netlabel_kapi.c b/net/netlabel/netlabel_kapi.c index 3583fa63dd01..c0eddb6afef3 100644 --- a/net/netlabel/netlabel_kapi.c +++ b/net/netlabel/netlabel_kapi.c @@ -1045,18 +1045,18 @@ socket_setattr_return: * ensuring that @sk is locked. * */ -void netlbl_sock_delattr(struct sock *sk) +int netlbl_sock_delattr(struct sock *sk) { switch (sk->sk_family) { case AF_INET: - cipso_v4_sock_delattr(sk); - break; + return cipso_v4_sock_delattr(sk); #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: calipso_sock_delattr(sk); break; #endif /* IPv6 */ } + return 0; } /** @@ -1156,8 +1156,7 @@ int netlbl_conn_setattr(struct sock *sk, case NETLBL_NLTYPE_UNLABELED: /* just delete the protocols we support for right now * but we could remove other protocols if needed */ - netlbl_sock_delattr(sk); - ret_val = 0; + ret_val = netlbl_sock_delattr(sk); break; default: ret_val = -ENOENT; @@ -1185,8 +1184,7 @@ int netlbl_conn_setattr(struct sock *sk, case NETLBL_NLTYPE_UNLABELED: /* just delete the protocols we support for right now * but we could remove other protocols if needed */ - netlbl_sock_delattr(sk); - ret_val = 0; + ret_val = netlbl_sock_delattr(sk); break; default: ret_val = -ENOENT; @@ -1234,8 +1232,7 @@ int netlbl_req_setattr(struct request_sock *req, entry->cipso, secattr); break; case NETLBL_NLTYPE_UNLABELED: - netlbl_req_delattr(req); - ret_val = 0; + ret_val = netlbl_req_delattr(req); break; default: ret_val = -ENOENT; @@ -1255,8 +1252,7 @@ int netlbl_req_setattr(struct request_sock *req, entry->calipso, secattr); break; case NETLBL_NLTYPE_UNLABELED: - netlbl_req_delattr(req); - ret_val = 0; + ret_val = netlbl_req_delattr(req); break; default: ret_val = -ENOENT; @@ -1280,18 +1276,18 @@ req_setattr_return: * Remove all the NetLabel labeling from @req. * */ -void netlbl_req_delattr(struct request_sock *req) +int netlbl_req_delattr(struct request_sock *req) { switch (req->rsk_ops->family) { case AF_INET: - cipso_v4_req_delattr(req); - break; + return cipso_v4_req_delattr(req); #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: calipso_req_delattr(req); break; #endif /* IPv6 */ } + return 0; } /** diff --git a/net/netlink/af_netlink.c b/net/netlink/af_netlink.c index 1281c42a3456..69bb951b5fb8 100644 --- a/net/netlink/af_netlink.c +++ b/net/netlink/af_netlink.c @@ -1047,8 +1047,9 @@ static int netlink_bind(struct socket *sock, struct sockaddr_unsized *addr, netlink_insert(sk, nladdr->nl_pid) : netlink_autobind(sock); if (err) { + netlink_unlock_table(); netlink_undo_bind(BITS_PER_TYPE(u32), groups, sk); - goto unlock; + return err; } } diff --git a/net/nsh/nsh.c b/net/nsh/nsh.c index bfb7758063f3..dd4de50fc38c 100644 --- a/net/nsh/nsh.c +++ b/net/nsh/nsh.c @@ -9,6 +9,7 @@ #include <linux/netdevice.h> #include <linux/skbuff.h> #include <net/gso.h> +#include <net/ip_tunnels.h> #include <net/nsh.h> #include <net/tun_proto.h> @@ -84,6 +85,12 @@ static struct sk_buff *nsh_gso_segment(struct sk_buff *skb, skb_reset_network_header(skb); + /* NSH can carry NSH (directly, or in an inner Ethernet frame): + * limit the recursion, as IPv4 and IPv6 do. + */ + if (unlikely(gso_recursion_inc_test(skb, IP_TUNNEL_RECURSION_LIMIT))) + goto out; + outer_proto = skb->protocol; outer_hlen = skb_mac_header_len(skb); mac_len = skb->mac_len; diff --git a/net/openvswitch/flow.c b/net/openvswitch/flow.c index 1c4f3a079044..3734416b518d 100644 --- a/net/openvswitch/flow.c +++ b/net/openvswitch/flow.c @@ -369,11 +369,28 @@ static void get_ipv6_ext_hdrs(struct sk_buff *skb, struct ipv6hdr *nh, return; } + if (next_type == IPPROTO_FRAGMENT) { + struct frag_hdr _fh, *fh; + + fh = skb_header_pointer(skb, start, sizeof(_fh), &_fh); + if (!fh) + break; + /* Only the first fragment has the headers that follow. */ + if (fh->frag_off & htons(IP6_OFFSET)) + break; + start += sizeof(_fh); + next_type = fh->nexthdr; + continue; + } + hp = skb_header_pointer(skb, start, sizeof(_hdr), &_hdr); if (!hp) break; + if (next_type == IPPROTO_AH) + start += ipv6_authlen(hp); + else + start += ipv6_optlen(hp); next_type = hp->nexthdr; - start += ipv6_optlen(hp); } } diff --git a/net/rds/rdma.c b/net/rds/rdma.c index 078090d292fa..71b57abb96c4 100644 --- a/net/rds/rdma.c +++ b/net/rds/rdma.c @@ -957,8 +957,11 @@ int rds_cmsg_atomic(struct rds_sock *rs, struct rds_message *rm, } ret = rds_pin_pages(args->local_addr, 1, &page, 1); - if (ret != 1) + if (ret != 1) { + /* A failed pin can leave a stale page pointer. */ + page = NULL; goto err; + } ret = 0; sg_set_page(rm->atomic.op_sg, page, 8, offset_in_page(args->local_addr)); diff --git a/net/sched/act_ife.c b/net/sched/act_ife.c index 3946a9589bb8..5a527da00566 100644 --- a/net/sched/act_ife.c +++ b/net/sched/act_ife.c @@ -50,8 +50,7 @@ int ife_encode_meta_u16(u16 metaval, void *skbdata, struct tcf_meta_info *mi) edata = *(u16 *)mi->metaval; else if (metaval) edata = metaval; - - if (!edata) /* will not encode */ + else return 0; edata = htons(edata); @@ -94,8 +93,7 @@ int ife_encode_meta_u32(u32 metaval, void *skbdata, struct tcf_meta_info *mi) edata = *(u32 *)mi->metaval; else if (metaval) edata = metaval; - - if (!edata) /* will not encode */ + else return 0; edata = htonl(edata); @@ -880,13 +878,16 @@ drop: * is an Ethernet header because the skb could've been redirected with mirred * from a non-Ethernet device. */ -static bool tcf_ife_is_eth_skb(const struct sk_buff *skb) +static bool tcf_ife_is_eth_skb(struct sk_buff *skb) { if (skb->dev->type != ARPHRD_ETHER && skb->dev->type != ARPHRD_LOOPBACK) return false; - return !skb_at_tc_ingress(skb) || skb->mac_len == ETH_HLEN; + if (skb_at_tc_ingress(skb)) + return skb->mac_len == ETH_HLEN; + + return pskb_may_pull(skb, ETH_HLEN); } TC_INDIRECT_SCOPE int tcf_ife_act(struct sk_buff *skb, diff --git a/net/sched/sch_teql.c b/net/sched/sch_teql.c index 70c948a26f80..dc21cd9704a2 100644 --- a/net/sched/sch_teql.c +++ b/net/sched/sch_teql.c @@ -200,6 +200,8 @@ static int teql_qdisc_init(struct Qdisc *sch, struct nlattr *opt, struct Qdisc *first; unsigned long flags; + skb_queue_head_init(&q->q); + if (dev->hard_header_len > m->dev->hard_header_len) return -EINVAL; @@ -211,9 +213,12 @@ static int teql_qdisc_init(struct Qdisc *sch, struct nlattr *opt, return -EOPNOTSUPP; } - q->m = m; + if (dev_net(dev) != dev_net(m->dev)) { + NL_SET_ERR_MSG_MOD(extack, "teql master is in a different network namespace"); + return -EOPNOTSUPP; + } - skb_queue_head_init(&q->q); + q->m = m; raw_spin_lock_irqsave(&m->slaves_lock, flags); first = rcu_dereference_protected(m->slaves, lockdep_is_held(&m->slaves_lock)); diff --git a/net/sctp/sm_make_chunk.c b/net/sctp/sm_make_chunk.c index 90de27284251..15c2d87575a8 100644 --- a/net/sctp/sm_make_chunk.c +++ b/net/sctp/sm_make_chunk.c @@ -3160,9 +3160,12 @@ static __be16 sctp_process_asconf_param(struct sctp_association *asoc, * packet MUST be deleted. */ if (af->is_any(&addr)) { - sctp_assoc_set_primary(asoc, asconf->transport); - sctp_assoc_del_nonprimary_peers(asoc, - asconf->transport); + peer = sctp_assoc_lookup_paddr(asoc, &asconf->source); + if (!peer) + return SCTP_ERROR_REQ_REFUSED; + sctp_assoc_set_primary(asoc, peer); + sctp_assoc_del_nonprimary_peers(asoc, peer); + asconf->transport = peer; return SCTP_ERROR_NO_ERROR; } @@ -3175,13 +3178,9 @@ static __be16 sctp_process_asconf_param(struct sctp_association *asoc, if (!peer) return SCTP_ERROR_DNS_FAILED; - /* Don't free asconf->transport; a later wildcard DEL-IP - * parameter reuses it. - */ - if (peer == asconf->transport) - return SCTP_ERROR_REQ_REFUSED; - sctp_assoc_rm_peer(asoc, peer); + if (asconf->transport == peer) + asconf->transport = asoc->peer.primary_path; break; case SCTP_PARAM_SET_PRIMARY: /* ADDIP Section 4.2.4 diff --git a/net/sctp/sm_statefuns.c b/net/sctp/sm_statefuns.c index b2f609f177fb..64519fd8f943 100644 --- a/net/sctp/sm_statefuns.c +++ b/net/sctp/sm_statefuns.c @@ -1122,9 +1122,11 @@ enum sctp_disposition sctp_sf_send_reconf(struct net *net, return SCTP_DISPOSITION_DELETE_TCB; } - sctp_chunk_hold(asoc->strreset_chunk); - sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, - SCTP_CHUNK(asoc->strreset_chunk)); + if (!sctp_chunk_pending(asoc->strreset_chunk)) { + sctp_chunk_hold(asoc->strreset_chunk); + sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, + SCTP_CHUNK(asoc->strreset_chunk)); + } sctp_add_cmd_sf(commands, SCTP_CMD_STRIKE, SCTP_TRANSPORT(transport)); return SCTP_DISPOSITION_CONSUME; @@ -6197,9 +6199,11 @@ enum sctp_disposition sctp_sf_t4_timer_expire( * chunk, it MUST be the same (including its serial number) as the last * ASCONF sent. */ - sctp_chunk_hold(asoc->addip_last_asconf); - sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, - SCTP_CHUNK(asoc->addip_last_asconf)); + if (!sctp_chunk_pending(asoc->addip_last_asconf)) { + sctp_chunk_hold(asoc->addip_last_asconf); + sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, + SCTP_CHUNK(asoc->addip_last_asconf)); + } /* ADDIP 4.1 B5) Restart the T-4 RTO timer. Note that if a different * destination is selected, then the RTO used will be that of the new diff --git a/net/sctp/socket.c b/net/sctp/socket.c index b5a57f61ee6d..8e647737b256 100644 --- a/net/sctp/socket.c +++ b/net/sctp/socket.c @@ -809,7 +809,6 @@ static int sctp_send_asconf_del_ip(struct sock *sk, struct sctp_sockaddr_entry *saddr; int i; int retval = 0; - int stored = 0; chunk = NULL; sp = sctp_sk(sk); @@ -822,6 +821,7 @@ static int sctp_send_asconf_del_ip(struct sock *sk, __func__, sk, addrs, addrcnt); list_for_each_entry(asoc, &ep->asocs, asocs) { + int stored = 0; if (!asoc->peer.asconf_capable) continue; diff --git a/net/sctp/stream.c b/net/sctp/stream.c index 8fa9f431782b..30037d0ca160 100644 --- a/net/sctp/stream.c +++ b/net/sctp/stream.c @@ -749,6 +749,7 @@ struct sctp_chunk *sctp_process_strreset_tsnreq( */ max_tsn_seen = sctp_tsnmap_get_max_tsn_seen(&asoc->peer.tsn_map); asoc->stream.si->report_ftsn(&asoc->ulpq, max_tsn_seen); + asoc->stream.si->abort_pd(&asoc->ulpq, GFP_ATOMIC); /* G1: Compute an appropriate value for the Receiver's Next TSN -- the * TSN that the peer should use to send the next DATA chunk. The @@ -1028,6 +1029,7 @@ struct sctp_chunk *sctp_process_strreset_resp( LIST_HEAD(temp); asoc->stream.si->report_ftsn(&asoc->ulpq, mtsn); + asoc->stream.si->abort_pd(&asoc->ulpq, GFP_ATOMIC); sctp_tsnmap_init(&asoc->peer.tsn_map, SCTP_TSN_MAP_INITIAL, diff --git a/net/sctp/stream_interleave.c b/net/sctp/stream_interleave.c index 840f24045ae2..1113b3455369 100644 --- a/net/sctp/stream_interleave.c +++ b/net/sctp/stream_interleave.c @@ -1203,28 +1203,21 @@ static void sctp_report_fwdtsn(struct sctp_ulpq *ulpq, __u32 ftsn) sctp_ulpq_abort_pd(ulpq, GFP_ATOMIC); } -static void sctp_intl_reasm_flushtsn(struct sctp_ulpq *ulpq, __u32 ftsn) +static void sctp_intl_reasm_flush_mid(struct sk_buff_head *reasm, __u16 sid, + __u32 mid) { struct sk_buff *pos, *tmp; - skb_queue_walk_safe(&ulpq->reasm, pos, tmp) { + skb_queue_walk_safe(reasm, pos, tmp) { struct sctp_ulpevent *event = sctp_skb2event(pos); - __u32 tsn = event->tsn; - if (TSN_lte(tsn, ftsn)) { - __skb_unlink(pos, &ulpq->reasm); - sctp_ulpevent_free(event); - } - } - - skb_queue_walk_safe(&ulpq->reasm_uo, pos, tmp) { - struct sctp_ulpevent *event = sctp_skb2event(pos); - __u32 tsn = event->tsn; + if (event->stream < sid) + continue; + if (event->stream > sid || MID_lt(mid, event->mid)) + break; - if (TSN_lte(tsn, ftsn)) { - __skb_unlink(pos, &ulpq->reasm_uo); - sctp_ulpevent_free(event); - } + __skb_unlink(pos, reasm); + sctp_ulpevent_free(event); } } @@ -1232,11 +1225,6 @@ static void sctp_report_iftsn(struct sctp_ulpq *ulpq, __u32 ftsn) { /* Move the Cumulattive TSN Ack ahead. */ sctp_tsnmap_skip(&ulpq->asoc->peer.tsn_map, ftsn); - /* purge the fragmentation queue */ - sctp_intl_reasm_flushtsn(ulpq, ftsn); - /* abort only when it's for all data */ - if (ftsn == sctp_tsnmap_get_max_tsn_seen(&ulpq->asoc->peer.tsn_map)) - sctp_intl_abort_pd(ulpq, GFP_ATOMIC); } static void sctp_handle_fwdtsn(struct sctp_ulpq *ulpq, struct sctp_chunk *chunk) @@ -1255,11 +1243,12 @@ static void sctp_intl_skip(struct sctp_ulpq *ulpq, __u16 sid, __u32 mid, struct sctp_stream *stream = &ulpq->asoc->stream; if (flags & SCTP_FTSN_U_BIT) { - if (sin->pd_mode_uo && MID_lt(sin->mid_uo, mid)) { + if (sin->pd_mode_uo && !MID_lt(mid, sin->mid_uo)) { sin->pd_mode_uo = 0; - sctp_intl_stream_abort_pd(ulpq, sid, mid, 0x1, + sctp_intl_stream_abort_pd(ulpq, sid, sin->mid_uo, 0x1, GFP_ATOMIC); } + sctp_intl_reasm_flush_mid(&ulpq->reasm_uo, sid, mid); return; } @@ -1268,9 +1257,10 @@ static void sctp_intl_skip(struct sctp_ulpq *ulpq, __u16 sid, __u32 mid, if (sin->pd_mode) { sin->pd_mode = 0; - sctp_intl_stream_abort_pd(ulpq, sid, mid, 0x0, GFP_ATOMIC); + sctp_intl_stream_abort_pd(ulpq, sid, sin->mid, 0x0, GFP_ATOMIC); } + sctp_intl_reasm_flush_mid(&ulpq->reasm, sid, mid); sctp_mid_skip(stream, in, sid, mid); sctp_intl_reap_ordered(ulpq, sid); diff --git a/net/smc/af_smc.c b/net/smc/af_smc.c index d10244af5bd2..bfc0c7e71a12 100644 --- a/net/smc/af_smc.c +++ b/net/smc/af_smc.c @@ -980,7 +980,7 @@ static int smc_connect_fallback(struct smc_sock *smc, int reason_code) smc_copy_sock_settings_to_clc(smc); smc->connect_nonblock = 0; if (smc->sk.sk_state == SMC_INIT) - smc->sk.sk_state = SMC_ACTIVE; + smp_store_release(&smc->sk.sk_state, SMC_ACTIVE); return 0; } @@ -1013,14 +1013,15 @@ static void smc_conn_abort(struct smc_sock *smc, int local_first) { struct smc_connection *conn = &smc->conn; struct smc_link_group *lgr = conn->lgr; - bool lgr_valid = false; - - if (smc_conn_lgr_valid(conn)) - lgr_valid = true; + bool lgr_valid = local_first && smc_conn_lgr_valid(conn); + if (lgr_valid) + smc_lgr_hold(lgr); /* lgr_put below */ smc_conn_free(conn); - if (local_first && lgr_valid) + if (lgr_valid) { smc_lgr_cleanup_early(lgr); + smc_lgr_put(lgr); + } } /* check if there is a rdma device available for this connection. */ @@ -1385,7 +1386,7 @@ static int smc_connect_rdma(struct smc_sock *smc, smc_copy_sock_settings_to_clc(smc); smc->connect_nonblock = 0; if (smc->sk.sk_state == SMC_INIT) - smc->sk.sk_state = SMC_ACTIVE; + smp_store_release(&smc->sk.sk_state, SMC_ACTIVE); return 0; connect_abort: @@ -1488,7 +1489,7 @@ static int smc_connect_ism(struct smc_sock *smc, smc_copy_sock_settings_to_clc(smc); smc->connect_nonblock = 0; if (smc->sk.sk_state == SMC_INIT) - smc->sk.sk_state = SMC_ACTIVE; + smp_store_release(&smc->sk.sk_state, SMC_ACTIVE); return 0; connect_abort: @@ -1957,7 +1958,7 @@ static void smc_listen_out_connected(struct smc_sock *new_smc) struct sock *newsmcsk = &new_smc->sk; if (newsmcsk->sk_state == SMC_INIT) - newsmcsk->sk_state = SMC_ACTIVE; + smp_store_release(&newsmcsk->sk_state, SMC_ACTIVE); smc_listen_out(new_smc); } @@ -1971,7 +1972,7 @@ static void smc_listen_out_err(struct smc_sock *new_smc) this_cpu_inc(net->smc.smc_stats->srv_hshake_err_cnt); if (newsmcsk->sk_state == SMC_INIT) sock_put(&new_smc->sk); /* passive closing */ - newsmcsk->sk_state = SMC_CLOSED; + smp_store_release(&newsmcsk->sk_state, SMC_CLOSED); smc_listen_out(new_smc); } diff --git a/net/smc/smc.h b/net/smc/smc.h index 427b6d63b993..36b243b34a9a 100644 --- a/net/smc/smc.h +++ b/net/smc/smc.h @@ -196,6 +196,7 @@ struct smc_connection { struct rb_node alert_node; struct smc_link_group *lgr; /* link group of connection */ struct smc_link *lnk; /* assigned SMC-R link */ + bool is_smcd; /* SMC-R or SMC-D connection */ u32 alert_token_local; /* unique conn. id */ u8 peer_rmbe_idx; /* from tcp handshake */ int peer_rmbe_size; /* size of peer rx buffer */ diff --git a/net/smc/smc_close.c b/net/smc/smc_close.c index a8d4b4b65f24..736abfbd2aaf 100644 --- a/net/smc/smc_close.c +++ b/net/smc/smc_close.c @@ -155,6 +155,7 @@ void smc_close_active_abort(struct smc_sock *smc) if (sk->sk_state != SMC_PEERABORTWAIT) break; sk->sk_state = SMC_CLOSED; + sk->sk_prot->unhash(sk); smc_conn_free(&smc->conn); release_clcsock = true; sock_put(sk); /* passive closing */ @@ -166,6 +167,7 @@ void smc_close_active_abort(struct smc_sock *smc) if (sk->sk_state != SMC_PEERABORTWAIT) break; sk->sk_state = SMC_CLOSED; + sk->sk_prot->unhash(sk); smc_conn_free(&smc->conn); release_clcsock = true; break; @@ -370,6 +372,17 @@ static void smc_close_passive_work(struct work_struct *work) lock_sock(sk); old_state = sk->sk_state; + if (conn->freed) { + /* conn->freed is set under the socket lock, which is + * held here as well, so this cannot race with the free; the + * state machine and its postponed sock_put() are not owed + * anymore + */ + release_sock(sk); + sock_put(sk); /* sock_hold done by schedulers of close_work */ + return; + } + rxflags = &conn->local_rx_ctrl.conn_state_flags; if (rxflags->peer_conn_abort) { /* peer has not received all data */ @@ -437,6 +450,7 @@ wakeup: sk->sk_state_change(sk); if ((sk->sk_state == SMC_CLOSED) && (sock_flag(sk, SOCK_DEAD) || !sk->sk_socket)) { + sk->sk_prot->unhash(sk); smc_conn_free(conn); if (smc->clcsock) release_clcsock = true; diff --git a/net/smc/smc_core.c b/net/smc/smc_core.c index 6021322253e9..a3164201c142 100644 --- a/net/smc/smc_core.c +++ b/net/smc/smc_core.c @@ -80,16 +80,21 @@ static void smc_ibdev_cnt_dec(struct smc_link *lnk) static void smc_lgr_schedule_free_work(struct smc_link_group *lgr) { + spinlock_t *lgr_lock; + /* client link group creation always follows the server link group * creation. For client use a somewhat higher removal delay time, * otherwise there is a risk of out-of-sync link groups. */ + smc_lgr_list_head(lgr, &lgr_lock); + spin_lock_bh(lgr_lock); if (!lgr->freeing) { mod_delayed_work(system_percpu_wq, &lgr->free_work, (!lgr->is_smcd && lgr->role == SMC_CLNT) ? SMC_LGR_FREE_DELAY_CLNT : SMC_LGR_FREE_DELAY_SERV); } + spin_unlock_bh(lgr_lock); } /* Register connection's alert token in our lookup structure. @@ -679,19 +684,34 @@ int smcd_nl_get_lgr(struct sk_buff *skb, struct netlink_callback *cb) return skb->len; } -void smc_lgr_cleanup_early(struct smc_link_group *lgr) +/* Claim a link group for termination. Only one context can succeed: the + * lgr is removed from its list and marked freeing under lgr_lock. + * Returns false if @lgr is NULL or another context owns it. + */ +static bool smc_lgr_claim(struct smc_link_group *lgr) { spinlock_t *lgr_lock; if (!lgr) - return; - + return false; smc_lgr_list_head(lgr, &lgr_lock); spin_lock_bh(lgr_lock); + if (lgr->freeing || lgr->terminating || list_empty(&lgr->list)) { + spin_unlock_bh(lgr_lock); + return false; + } /* do not use this link group for new connections */ - if (!list_empty(&lgr->list)) - list_del_init(&lgr->list); + list_del_init(&lgr->list); + lgr->freeing = 1; spin_unlock_bh(lgr_lock); + return true; +} + +/* The caller must keep @lgr alive for the duration of the call. */ +void smc_lgr_cleanup_early(struct smc_link_group *lgr) +{ + if (!smc_lgr_claim(lgr)) + return; /* another context owns the termination */ __smc_lgr_terminate(lgr, true); } @@ -1281,10 +1301,12 @@ void smc_conn_free(struct smc_connection *conn) if (current_work() != &conn->abort_work) cancel_work_sync(&conn->abort_work); } - if (!list_empty(&lgr->list)) { + /* The handshake can retry another device or SMC version with this + * connection, so it must never stay registered in an lgr it left. + */ + if (!list_empty(&lgr->list)) smc_buf_unuse(conn, lgr); /* allow buffer reuse */ - smc_lgr_unregister_conn(conn); - } + smc_lgr_unregister_conn(conn); if (!lgr->conns_num) smc_lgr_schedule_free_work(lgr); @@ -1519,6 +1541,15 @@ static void smc_conn_kill(struct smc_connection *conn, bool soft) { struct smc_sock *smc = container_of(conn, struct smc_sock, conn); + if (conn->freed) { + /* The connection was already freed, e.g. by a close or + * a handshake that fell back to TCP. Do not abort a socket + * that is no longer part of this link group. + */ + smc_lgr_unregister_conn(conn); + return; + } + if (conn->lgr->is_smcd && conn->lgr->peer_shutdown) conn->local_tx_ctrl.conn_state_flags.peer_conn_abort = 1; else @@ -1532,8 +1563,10 @@ static void smc_conn_kill(struct smc_connection *conn, bool soft) tasklet_kill(&conn->rx_tsklet); else tasklet_unlock_wait(&conn->rx_tsklet); - if (smc_ism_support_dmb_nocopy(conn->lgr->smcd)) + if (smc_ism_support_dmb_nocopy(conn->lgr->smcd)) { + smc->sk.sk_prot->unhash(&smc->sk); smcd_buf_detach(conn); + } } else { smc_cdc_wait_pend_tx_wr(conn); } @@ -1564,12 +1597,20 @@ static void __smc_lgr_terminate(struct smc_link_group *lgr, bool soft) struct smc_connection *conn; struct smc_sock *smc; struct rb_node *node; + spinlock_t *lgr_lock; - if (lgr->terminating) + smc_lgr_list_head(lgr, &lgr_lock); + spin_lock_bh(lgr_lock); + if (lgr->terminating) { + spin_unlock_bh(lgr_lock); return; /* lgr already terminating */ - /* cancel free_work sync, will terminate when lgr->freeing is set */ - cancel_delayed_work(&lgr->free_work); + } lgr->terminating = 1; + spin_unlock_bh(lgr_lock); + /* The lgr is claimed, so no new free_work can be armed; wait for + * one that is already queued or running. + */ + cancel_delayed_work_sync(&lgr->free_work); /* kill remaining link group connections */ read_lock_bh(&lgr->conns_lock); @@ -1580,7 +1621,11 @@ static void __smc_lgr_terminate(struct smc_link_group *lgr, bool soft) sock_hold(&smc->sk); /* sock_put below */ read_unlock_bh(&lgr->conns_lock); lock_sock(&smc->sk); - smc_conn_kill(conn, soft); + /* The connection may have been re-registered in another + * link group by a retried handshake in the meantime. + */ + if (conn->lgr == lgr) + smc_conn_kill(conn, soft); release_sock(&smc->sk); sock_put(&smc->sk); /* sock_hold above */ read_lock_bh(&lgr->conns_lock); @@ -1594,17 +1639,8 @@ static void __smc_lgr_terminate(struct smc_link_group *lgr, bool soft) /* unlink link group and schedule termination */ void smc_lgr_terminate_sched(struct smc_link_group *lgr) { - spinlock_t *lgr_lock; - - smc_lgr_list_head(lgr, &lgr_lock); - spin_lock_bh(lgr_lock); - if (list_empty(&lgr->list) || lgr->terminating || lgr->freeing) { - spin_unlock_bh(lgr_lock); + if (!smc_lgr_claim(lgr)) return; /* lgr already terminating */ - } - list_del_init(&lgr->list); - lgr->freeing = 1; - spin_unlock_bh(lgr_lock); schedule_work(&lgr->terminate_work); } @@ -2053,6 +2089,10 @@ create: goto out; } } + /* cache the connection type: smc_diag reads it after + * smc_conn_free() dropped the link group reference + */ + conn->is_smcd = conn->lgr->is_smcd; smc_lgr_hold(conn->lgr); /* lgr_put in smc_conn_free() */ if (!conn->lgr->is_smcd) smcr_link_hold(conn->lnk); /* link_put in smc_conn_free() */ diff --git a/net/smc/smc_core.h b/net/smc/smc_core.h index 5c18f08a4c8a..bff4c9e17792 100644 --- a/net/smc/smc_core.h +++ b/net/smc/smc_core.h @@ -301,9 +301,9 @@ struct smc_link_group { struct delayed_work free_work; /* delayed freeing of an lgr */ struct work_struct terminate_work; /* abnormal lgr termination */ struct workqueue_struct *tx_wq; /* wq for conn. tx workers */ - u8 sync_err : 1; /* lgr no longer fits to peer */ - u8 terminating : 1;/* lgr is terminating */ - u8 freeing : 1; /* lgr is being freed */ + u8 sync_err; /* lgr no longer fits to peer */ + u8 terminating; /* lgr is terminating */ + u8 freeing; /* lgr is being freed */ refcount_t refcnt; /* lgr reference count */ bool is_smcd; /* SMC-R or SMC-D */ diff --git a/net/smc/smc_diag.c b/net/smc/smc_diag.c index bf0beaa23bdb..15485a08d9a0 100644 --- a/net/smc/smc_diag.c +++ b/net/smc/smc_diag.c @@ -87,10 +87,10 @@ static int __smc_diag_dump(struct sock *sk, struct sk_buff *skb, r = nlmsg_data(nlh); smc_diag_msg_common_fill(r, sk); - r->diag_state = sk->sk_state; + r->diag_state = smp_load_acquire(&sk->sk_state); if (smc->use_fallback) r->diag_mode = SMC_DIAG_MODE_FALLBACK_TCP; - else if (smc_conn_lgr_valid(&smc->conn) && smc->conn.lgr->is_smcd) + else if (smc->conn.is_smcd) r->diag_mode = SMC_DIAG_MODE_SMCD; else r->diag_mode = SMC_DIAG_MODE_SMCR; @@ -103,6 +103,10 @@ static int __smc_diag_dump(struct sock *sk, struct sk_buff *skb, if (nla_put(skb, SMC_DIAG_FALLBACK, sizeof(fallback), &fallback) < 0) goto errout; + if (r->diag_state == SMC_INIT || r->diag_state == SMC_CLOSED || + smc->use_fallback) + goto out; + if ((req->diag_ext & (1 << (SMC_DIAG_CONNINFO - 1))) && smc->conn.alert_token_local) { struct smc_connection *conn = &smc->conn; @@ -154,8 +158,7 @@ static int __smc_diag_dump(struct sock *sk, struct sk_buff *skb, .lnk[0].link_id = link->link_id, }; - memcpy(linfo.lnk[0].ibname, link->smcibdev->ibdev->name, - sizeof(link->smcibdev->ibdev->name)); + memcpy(linfo.lnk[0].ibname, link->ibname, sizeof(link->ibname)); smc_gid_be16_convert(linfo.lnk[0].gid, link->gid); smc_gid_be16_convert(linfo.lnk[0].peer_gid, link->peer_gid); @@ -185,6 +188,7 @@ static int __smc_diag_dump(struct sock *sk, struct sk_buff *skb, goto errout; } +out: nlmsg_end(skb, nlh); return 0; diff --git a/net/socket.c b/net/socket.c index 2e3b5737c481..08658a9b8065 100644 --- a/net/socket.c +++ b/net/socket.c @@ -2697,8 +2697,6 @@ static int ____sys_sendmsg(struct socket *sock, struct msghdr *msg_sys, flags &= ~MSG_INTERNAL_SENDMSG_FLAGS; msg_sys->msg_flags = flags; - if (sock->file->f_flags & O_NONBLOCK) - msg_sys->msg_flags |= MSG_DONTWAIT; /* * If this is sendmmsg() and current destination address is same as * previously succeeded address, omit asking LSM's decision. @@ -2762,6 +2760,9 @@ static int ___sys_sendmsg(struct socket *sock, struct user_msghdr __user *msg, msg_sys->msg_name = &address; + if (sock->file->f_flags & O_NONBLOCK) + flags |= MSG_DONTWAIT; + err = sendmsg_copy_msghdr(msg_sys, msg, flags, &iov); if (err < 0) return err; @@ -2926,9 +2927,6 @@ static int ____sys_recvmsg(struct socket *sock, struct msghdr *msg_sys, /* We assume all kernel code knows the size of sockaddr_storage */ msg_sys->msg_namelen = 0; - if (sock->file->f_flags & O_NONBLOCK) - flags |= MSG_DONTWAIT; - if (unlikely(nosec)) err = sock_recvmsg_nosec(sock, msg_sys, flags); else @@ -2970,6 +2968,9 @@ static int ___sys_recvmsg(struct socket *sock, struct user_msghdr __user *msg, struct sockaddr __user *uaddr; ssize_t err; + if (sock->file->f_flags & O_NONBLOCK) + flags |= MSG_DONTWAIT; + err = recvmsg_copy_msghdr(msg_sys, msg, flags, &uaddr, &iov); if (err < 0) return err; diff --git a/net/sunrpc/clnt.c b/net/sunrpc/clnt.c index 6cedc824cf82..2f076b4bfd54 100644 --- a/net/sunrpc/clnt.c +++ b/net/sunrpc/clnt.c @@ -653,6 +653,9 @@ static struct rpc_clnt *__rpc_clone_client(struct rpc_create_args *args, } args->servername = xprt->servername; args->nodename = clnt->cl_nodename; + args->xprtsec = clnt->cl_xprtsec; + if (!args->timeout) + args->timeout = clnt->cl_timeout; new = rpc_new_client(args, xps, xprt, clnt); if (IS_ERR(new)) @@ -901,29 +904,36 @@ void rpc_killall_tasks(struct rpc_clnt *clnt) } EXPORT_SYMBOL_GPL(rpc_killall_tasks); -/** - * rpc_cancel_tasks - try to cancel a set of RPC tasks - * @clnt: Pointer to RPC client - * @error: RPC task error value to set - * @fnmatch: Pointer to selector function - * @data: User data - * - * Uses @fnmatch to define a set of RPC tasks that are to be cancelled. - * The argument @error must be a negative error value. - */ -unsigned long rpc_cancel_tasks(struct rpc_clnt *clnt, int error, - bool (*fnmatch)(const struct rpc_task *, - const void *), - const void *data) +struct rpc_cancel_disconnect_ctx { + bool (*fnmatch)(const struct rpc_task *task, const void *data); + const void *data; +}; + +static int rpc_mark_xprt_disconnect_on_release(struct rpc_clnt *clnt, + struct rpc_xprt *xprt, + void *arg) +{ + struct rpc_cancel_disconnect_ctx *ctx = arg; + + xprt_mark_matching_reqs_disconnect_on_release(xprt, clnt, + ctx->fnmatch, + ctx->data); + return 0; +} + +static unsigned long +__rpc_cancel_tasks(struct rpc_clnt *clnt, int error, + bool (*fnmatch)(const struct rpc_task *, + const void *), + const void *data, + bool disconnect) { struct rpc_task *task; unsigned long count = 0; if (list_empty(&clnt->cl_tasks)) return 0; - /* - * Spin lock all_tasks to prevent changes... - */ + spin_lock(&clnt->cl_lock); list_for_each_entry(task, &clnt->cl_tasks, tk_task) { if (!RPC_IS_ACTIVATED(task)) @@ -934,10 +944,63 @@ unsigned long rpc_cancel_tasks(struct rpc_clnt *clnt, int error, count++; } spin_unlock(&clnt->cl_lock); + + if (disconnect && count) { + struct rpc_cancel_disconnect_ctx ctx = { + .fnmatch = fnmatch, + .data = data, + }; + rpc_clnt_iterate_for_each_xprt(clnt, + rpc_mark_xprt_disconnect_on_release, + &ctx); + } return count; } + +/** + * rpc_cancel_tasks - try to cancel a set of RPC tasks + * @clnt: Pointer to RPC client + * @error: RPC task error value to set + * @fnmatch: Pointer to selector function + * @data: User data + * + * Uses @fnmatch to define a set of RPC tasks that are to be cancelled. + * The argument @error must be a negative error value. + */ +unsigned long rpc_cancel_tasks(struct rpc_clnt *clnt, int error, + bool (*fnmatch)(const struct rpc_task *, + const void *), + const void *data) +{ + return __rpc_cancel_tasks(clnt, error, fnmatch, data, false); +} EXPORT_SYMBOL_GPL(rpc_cancel_tasks); +/** + * rpc_cancel_tasks_and_disconnect - cancel matching RPC tasks + * @clnt: Pointer to RPC client + * @error: RPC task error value to set + * @fnmatch: Pointer to selector function + * @data: User data + * + * Like rpc_cancel_tasks(), but after cancelling matching tasks, marks + * matching in-flight requests so that xprt_release() conditionally + * disconnects the connection generation on which each request was sent. + * + * @fnmatch is called while holding spinlocks and must not sleep. + * + * Returns the number of active tasks matched by @fnmatch. + */ +unsigned long +rpc_cancel_tasks_and_disconnect(struct rpc_clnt *clnt, int error, + bool (*fnmatch)(const struct rpc_task *, + const void *), + const void *data) +{ + return __rpc_cancel_tasks(clnt, error, fnmatch, data, true); +} +EXPORT_SYMBOL_GPL(rpc_cancel_tasks_and_disconnect); + static int rpc_clnt_disconnect_xprt(struct rpc_clnt *clnt, struct rpc_xprt *xprt, void *dummy) { @@ -1194,7 +1257,7 @@ void rpc_task_set_transport(struct rpc_task *task, struct rpc_clnt *clnt) (task->tk_flags & RPC_TASK_MOVEABLE))) return; xprt_release(task); - xprt_put(task->tk_xprt); + rpc_task_release_xprt(clnt, task->tk_xprt); } if (task->tk_flags & RPC_TASK_NO_ROUND_ROBIN) task->tk_xprt = rpc_task_get_first_xprt(clnt); @@ -2125,8 +2188,10 @@ call_bind_status(struct rpc_task *task) goto retry_timeout; case -ENETDOWN: case -ENETUNREACH: - if (task->tk_flags & RPC_TASK_NETUNREACH_FATAL) + if (task->tk_flags & RPC_TASK_NETUNREACH_FATAL) { + status = task->tk_status; break; + } fallthrough; case -ECONNREFUSED: /* connection problems */ case -ECONNRESET: @@ -2257,6 +2322,7 @@ call_connect_status(struct rpc_task *task) xprt_release(task); value = atomic_long_dec_return(&xprt->queuelen); + atomic_long_dec(&xps->xps_queuelen); if (value == 0) rpc_xprt_switch_remove_xprt(xps, saved, true); diff --git a/net/sunrpc/rpc_pipe.c b/net/sunrpc/rpc_pipe.c index 9d349cfbc483..f14cae295280 100644 --- a/net/sunrpc/rpc_pipe.c +++ b/net/sunrpc/rpc_pipe.c @@ -191,6 +191,7 @@ rpc_close_pipes(struct dentry *dentry) cancel_delayed_work_sync(&pipe->queue_timeout); rpc_inode_setowner(inode, NULL); RPC_I(inode)->pipe = NULL; + wake_up(&RPC_I(inode)->waitq); inode_unlock(inode); } @@ -665,8 +666,8 @@ int rpc_mkpipe_dentry(struct dentry *parent, const char *name, rpci->private = private; rpci->pipe = pipe; rpc_inode_setowner(inode, private); - pipe->dentry = dentry; // borrowed d_make_persistent(dentry, inode); + pipe->dentry = dentry; // borrowed fsnotify_create(dir, dentry); simple_done_creating(dentry); return 0; diff --git a/net/sunrpc/sunrpc.h b/net/sunrpc/sunrpc.h index e3c6e3b63f0b..11b9e5cead8e 100644 --- a/net/sunrpc/sunrpc.h +++ b/net/sunrpc/sunrpc.h @@ -38,9 +38,17 @@ static inline int sock_is_loopback(struct sock *sk) struct svc_serv; struct svc_rqst; +struct rpc_clnt; +struct rpc_task; +struct rpc_xprt; int rpc_clients_notifier_register(void); void rpc_clients_notifier_unregister(void); void auth_domain_cleanup(void); void svc_sock_update_bufs(struct svc_serv *serv); enum svc_auth_status svc_authenticate(struct svc_rqst *rqstp); +void xprt_mark_matching_reqs_disconnect_on_release(struct rpc_xprt *xprt, + const struct rpc_clnt *clnt, + bool (*fnmatch)(const struct rpc_task *, + const void *), + const void *data); #endif /* _NET_SUNRPC_SUNRPC_H */ diff --git a/net/sunrpc/xprt.c b/net/sunrpc/xprt.c index 48a3618cbb29..c110806989c5 100644 --- a/net/sunrpc/xprt.c +++ b/net/sunrpc/xprt.c @@ -812,6 +812,17 @@ xprt_request_retransmit_after_disconnect(struct rpc_task *task) !xprt_connected(xprt); } +static void xprt_conditional_disconnect_locked(struct rpc_xprt *xprt, + unsigned int cookie) + __must_hold(&xprt->transport_lock) +{ + if (cookie != xprt->connect_cookie) + return; + if (test_bit(XPRT_CLOSING, &xprt->state)) + return; + xprt_schedule_autoclose_locked(xprt); +} + /** * xprt_conditional_disconnect - force a transport to disconnect * @xprt: transport to disconnect @@ -827,12 +838,7 @@ void xprt_conditional_disconnect(struct rpc_xprt *xprt, unsigned int cookie) { /* Don't race with the test_bit() in xprt_clear_locked() */ spin_lock(&xprt->transport_lock); - if (cookie != xprt->connect_cookie) - goto out; - if (test_bit(XPRT_CLOSING, &xprt->state)) - goto out; - xprt_schedule_autoclose_locked(xprt); -out: + xprt_conditional_disconnect_locked(xprt, cookie); spin_unlock(&xprt->transport_lock); } @@ -1434,6 +1440,79 @@ xprt_request_dequeue_transmit(struct rpc_task *task) spin_unlock(&xprt->queue_lock); } +static bool +xprt_request_matches(const struct rpc_rqst *req, + const struct rpc_clnt *clnt, + bool (*fnmatch)(const struct rpc_task *, const void *), + const void *data) +{ + const struct rpc_task *task = req->rq_task; + + return task && task->tk_client == clnt && fnmatch(task, data); +} + +static void +xprt_request_mark_disconnect_on_release(struct rpc_xprt *xprt, + struct rpc_rqst *req) + __must_hold(&xprt->queue_lock) +{ + spin_lock(&xprt->transport_lock); + req->rq_disconnect_on_release = true; + spin_unlock(&xprt->transport_lock); +} + +/** + * xprt_mark_matching_reqs_disconnect_on_release - mark matching in-flight + * requests for connection-generation + * teardown at release + * @xprt: transport whose queues to walk + * @clnt: RPC client whose requests are eligible + * @fnmatch: selector called with the request's owning rpc_task + * @data: caller data forwarded to @fnmatch + * + * @fnmatch must not sleep and must be safe to call while xprt->queue_lock + * is held. + * + * Walks the transmit queue (including per-owner rq_xmit2 chains) and the + * receive tree under xprt->queue_lock and marks each matching rpc_rqst so + * that xprt_release() will conditionally disconnect the transport against + * that request's rq_connect_cookie. Requests remain eligible for marking + * while they are present on a transport queue. The marker is set under + * xprt->transport_lock, nested inside xprt->queue_lock, and xprt_release() + * consumes it with xprt->transport_lock held after removing queue membership. + * + * The @clnt qualification preserves the selection domain of + * rpc_cancel_tasks(). An rpc_xprt may be shared by multiple rpc_clnt + * instances, so requests belonging to other clients must not be marked. + */ +void +xprt_mark_matching_reqs_disconnect_on_release(struct rpc_xprt *xprt, + const struct rpc_clnt *clnt, + bool (*fnmatch)(const struct rpc_task *, + const void *), + const void *data) +{ + struct rpc_rqst *req, *pos; + struct rb_node *n; + + spin_lock(&xprt->queue_lock); + list_for_each_entry(req, &xprt->xmit_queue, rq_xmit) { + if (xprt_request_matches(req, clnt, fnmatch, data)) + xprt_request_mark_disconnect_on_release(xprt, req); + list_for_each_entry(pos, &req->rq_xmit2, rq_xmit2) { + if (xprt_request_matches(pos, clnt, fnmatch, data)) + xprt_request_mark_disconnect_on_release(xprt, + pos); + } + } + for (n = rb_first(&xprt->recv_queue); n; n = rb_next(n)) { + req = rb_entry(n, struct rpc_rqst, rq_recv); + if (xprt_request_matches(req, clnt, fnmatch, data)) + xprt_request_mark_disconnect_on_release(xprt, req); + } + spin_unlock(&xprt->queue_lock); +} + /** * xprt_request_dequeue_xprt - remove a task from the transmit+receive queue * @task: pointer to rpc_task @@ -1915,6 +1994,7 @@ xprt_request_init(struct rpc_task *task) req->rq_rcv_buf.bvec = NULL; req->rq_release_snd_buf = NULL; req->rq_seqno_count = 0; + req->rq_disconnect_on_release = false; xprt_init_majortimeo(task, req, task->tk_client->cl_timeout); trace_xprt_reserve(req); @@ -1991,6 +2071,20 @@ void xprt_release(struct rpc_task *task) xprt = req->rq_xprt; xprt_request_dequeue_xprt(task); spin_lock(&xprt->transport_lock); + if (unlikely(req->rq_disconnect_on_release)) { + req->rq_disconnect_on_release = false; + /* + * Dequeue may skip queue_lock. Pair with the fully ordered + * test_and_clear_bit(RPC_TASK_NEED_XMIT) in + * xprt_request_dequeue_transmit_locked() to order the runstate + * check before reading the sender's rq_ntrans and + * rq_connect_cookie updates. + */ + smp_rmb(); + if (req->rq_ntrans > 0) + xprt_conditional_disconnect_locked(xprt, + req->rq_connect_cookie); + } xprt->ops->release_xprt(xprt, task); if (xprt->ops->release_request) xprt->ops->release_request(task); @@ -2020,6 +2114,7 @@ xprt_init_bc_request(struct rpc_rqst *req, struct rpc_task *task, task->tk_rqstp = req; req->rq_task = task; xprt_init_connect_cookie(req, req->rq_xprt); + req->rq_disconnect_on_release = false; /* * Set up the xdr_buf length. * This also indicates that the buffer is XDR encoded already. diff --git a/net/sunrpc/xprtrdma/frwr_ops.c b/net/sunrpc/xprtrdma/frwr_ops.c index e83cef19e656..97034a3b5141 100644 --- a/net/sunrpc/xprtrdma/frwr_ops.c +++ b/net/sunrpc/xprtrdma/frwr_ops.c @@ -27,13 +27,17 @@ /* Transport recovery * - * frwr_map and frwr_unmap_* cannot run at the same time the transport - * connect worker is running. The connect worker holds the transport - * send lock, just as ->send_request does. This prevents frwr_map and - * the connect worker from running concurrently. When a connection is - * closed, the Receive completion queue is drained before the allowing - * the connect worker to get control. This prevents frwr_unmap and the - * connect worker from running concurrently. + * frwr_map() is serialized with the connect worker by the transport + * send lock. + * + * frwr_unmap_async() runs from Receive completion processing. + * rpcrdma_xprt_drain() drains the Receive Queue before the Send Queue, + * so asynchronous LOCAL_INV Work Requests are submitted before Send + * Queue drain. + * + * frwr_unmap_sync() runs after the transport send lock is released. + * rx_unmap_rwsem orders its LOCAL_INV submission before disconnect + * drains the QP. * * When the underlying transport disconnects, MRs that are in flight * are flushed and are likely unusable. Thus all MRs are destroyed. @@ -139,7 +143,6 @@ int frwr_mr_init(struct rpcrdma_xprt *r_xprt, struct rpcrdma_mr *mr) mr->mr_ibmr = frmr; mr->mr_device = NULL; INIT_LIST_HEAD(&mr->mr_list); - init_completion(&mr->mr_linv_done); frwr_cid_init(ep, mr); sg_init_table(sg, depth); @@ -539,40 +542,60 @@ static void frwr_wc_localinv(struct ib_cq *cq, struct ib_wc *wc) * @cq: completion queue * @wc: WCE for a completed LocalInv WR * - * Awaken anyone waiting for an MR to finish being fenced. + * Wake frwr_unmap_sync() after the final LOCAL_INV completion. */ static void frwr_wc_localinv_wake(struct ib_cq *cq, struct ib_wc *wc) { struct ib_cqe *cqe = wc->wr_cqe; struct rpcrdma_mr *mr = container_of(cqe, struct rpcrdma_mr, mr_cqe); + struct rpcrdma_req *req = mr->mr_req; /* WARNING: Only wr_cqe and status are reliable at this point */ trace_xprtrdma_wc_li_wake(wc, &mr->mr_cid); frwr_mr_done(wc, mr); - complete(&mr->mr_linv_done); + complete(&req->rl_linv_done); rpcrdma_flush_disconnect(cq->cq_context, wc); } /** - * frwr_unmap_sync - invalidate memory regions that were registered for @req + * frwr_unmap_sync - synchronously invalidate MRs registered for @req * @r_xprt: controlling transport instance - * @req: rpcrdma_req with a non-empty list of MRs to process + * @req: request whose registered MRs are to be invalidated * - * Sleeps until it is safe for the host CPU to access the previously mapped - * memory regions. This guarantees that registered MRs are properly fenced - * from the server before the RPC consumer accesses the data in them. It - * also ensures proper Send flow control: waking the next RPC waits until - * this RPC has relinquished all its Send Queue entries. + * If @req still owns registered MRs after synchronizing with transport + * disconnect, post a chain of LOCAL_INV Work Requests and wait for the + * final completion. On successful completion, this fences the mapped + * regions from remote access and preserves Send Queue flow control. + * + * A concurrent disconnect can reset @req while this function waits for + * the read side. In that case the MRs have already been released and no + * LOCAL_INV Work Requests are posted. + * + * Context: Process context. Takes and releases + * @r_xprt->rx_unmap_rwsem for read. May sleep. */ void frwr_unmap_sync(struct rpcrdma_xprt *r_xprt, struct rpcrdma_req *req) { struct ib_send_wr *first, **prev, *last; - struct rpcrdma_ep *ep = r_xprt->rx_ep; const struct ib_send_wr *bad_wr; + struct rpcrdma_ep *ep; struct rpcrdma_mr *mr; int rc; + /* serialize against rpcrdma_xprt_disconnect() */ + down_read(&r_xprt->rx_unmap_rwsem); + + /* + * Disconnect can reset this request while we wait for the read side. + * Recheck rl_registered in case rx_ep now refers to a new connection. + */ + ep = r_xprt->rx_ep; + if (!ep || list_empty(&req->rl_registered)) { + up_read(&r_xprt->rx_unmap_rwsem); + return; + } + /* ORDER: Invalidate all of the MRs first * * Chain the LOCAL_INV Work Requests and post them with @@ -599,37 +622,35 @@ void frwr_unmap_sync(struct rpcrdma_xprt *r_xprt, struct rpcrdma_req *req) prev = &last->next; } while ((mr = rpcrdma_mr_pop(&req->rl_registered))); - mr = container_of(last, struct rpcrdma_mr, mr_invwr); - /* Strong send queue ordering guarantees that when the * last WR in the chain completes, all WRs in the chain * are complete. */ last->wr_cqe->done = frwr_wc_localinv_wake; - reinit_completion(&mr->mr_linv_done); + reinit_completion(&req->rl_linv_done); - /* Transport disconnect drains the receive CQ before it - * replaces the QP. The RPC reply handler won't call us - * unless re_id->qp is a valid pointer. + /* + * The read side prevents disconnect from draining this QP until the + * LOCAL_INV chain has been submitted. */ bad_wr = NULL; rc = ib_post_send(ep->re_id->qp, first, &bad_wr); + if (rc) { + /* On error, the MRs get destroyed once the QP has drained. */ + trace_xprtrdma_post_linv_err(req, rc); + + /* Force a connection loss to ensure complete recovery. + */ + rpcrdma_force_disconnect(ep); + } + up_read(&r_xprt->rx_unmap_rwsem); /* The final LOCAL_INV WR in the chain is supposed to * do the wake. If it was never posted, the wake will * not happen, so don't wait in that case. */ if (bad_wr != first) - wait_for_completion(&mr->mr_linv_done); - if (!rc) - return; - - /* On error, the MRs get destroyed once the QP has drained. */ - trace_xprtrdma_post_linv_err(req, rc); - - /* Force a connection loss to ensure complete recovery. - */ - rpcrdma_force_disconnect(ep); + wait_for_completion(&req->rl_linv_done); } /** diff --git a/net/sunrpc/xprtrdma/transport.c b/net/sunrpc/xprtrdma/transport.c index d4e6746d8ecd..e38637c2ec78 100644 --- a/net/sunrpc/xprtrdma/transport.c +++ b/net/sunrpc/xprtrdma/transport.c @@ -364,6 +364,8 @@ xprt_setup_rdma(struct xprt_create *args) INIT_DELAYED_WORK(&new_xprt->rx_connect_worker, xprt_rdma_connect_worker); + init_rwsem(&new_xprt->rx_unmap_rwsem); + xprt->max_payload = RPCRDMA_MAX_DATA_SEGS << PAGE_SHIFT; return xprt; diff --git a/net/sunrpc/xprtrdma/verbs.c b/net/sunrpc/xprtrdma/verbs.c index 54957295a631..620afff79eff 100644 --- a/net/sunrpc/xprtrdma/verbs.c +++ b/net/sunrpc/xprtrdma/verbs.c @@ -572,20 +572,24 @@ out: * rpcrdma_xprt_disconnect - Disconnect underlying transport * @r_xprt: controlling transport instance * - * Caller serializes. Either the transport send lock is held, - * or we're being called to destroy the transport. + * Context: Caller serializes. Either the transport send lock is held, + * or the transport is being destroyed. Takes and releases + * @r_xprt->rx_unmap_rwsem for write. May sleep. * * On return, @r_xprt is completely divested of all hardware * resources and prepared for the next ->connect operation. */ void rpcrdma_xprt_disconnect(struct rpcrdma_xprt *r_xprt) { - struct rpcrdma_ep *ep = r_xprt->rx_ep; + struct rpcrdma_ep *ep; struct rdma_cm_id *id; int rc; + down_write(&r_xprt->rx_unmap_rwsem); + + ep = r_xprt->rx_ep; if (!ep) - return; + goto out_unlock; /* Prevent teardown-generated events from requesting another close. */ atomic_xchg(&ep->re_force_disconnect, 1); @@ -604,6 +608,9 @@ void rpcrdma_xprt_disconnect(struct rpcrdma_xprt *r_xprt) rdma_destroy_id(id); r_xprt->rx_ep = NULL; + +out_unlock: + up_write(&r_xprt->rx_unmap_rwsem); } /* Fixed-size circular FIFO queue. This implementation is wait-free and @@ -927,6 +934,7 @@ struct rpcrdma_req *rpcrdma_req_create(struct rpcrdma_xprt *r_xprt, INIT_LIST_HEAD(&req->rl_free_mrs); INIT_LIST_HEAD(&req->rl_registered); + init_completion(&req->rl_linv_done); spin_lock(&buffer->rb_lock); list_add(&req->rl_all, &buffer->rb_allreqs); spin_unlock(&buffer->rb_lock); diff --git a/net/sunrpc/xprtrdma/xprt_rdma.h b/net/sunrpc/xprtrdma/xprt_rdma.h index 4cbc941e4a3e..b3016e1eb172 100644 --- a/net/sunrpc/xprtrdma/xprt_rdma.h +++ b/net/sunrpc/xprtrdma/xprt_rdma.h @@ -46,6 +46,7 @@ #include <linux/spinlock.h> /* spinlock_t, etc */ #include <linux/atomic.h> /* atomic_t, etc */ #include <linux/kref.h> /* struct kref */ +#include <linux/rwsem.h> /* struct rw_semaphore */ #include <linux/workqueue.h> /* struct work_struct */ #include <linux/llist.h> @@ -249,7 +250,6 @@ struct rpcrdma_mr { int mr_nents; enum dma_data_direction mr_dir; struct ib_cqe mr_cqe; - struct completion mr_linv_done; union { struct ib_reg_wr mr_regwr; struct ib_send_wr mr_invwr; @@ -348,6 +348,7 @@ struct rpcrdma_req { struct list_head rl_free_mrs; struct list_head rl_registered; + struct completion rl_linv_done; }; static inline struct rpcrdma_req * @@ -449,6 +450,13 @@ struct rpcrdma_xprt { struct delayed_work rx_connect_worker; struct rpc_timeout rx_timeout; struct rpcrdma_stats rx_stats; + + /* + * Orders frwr_unmap_sync()'s LOCAL_INV submission ahead of the + * QP drain. Disconnect holds the write side across the drain + * and resource teardown. + */ + struct rw_semaphore rx_unmap_rwsem; }; #define rpcx_to_rdmax(x) container_of(x, struct rpcrdma_xprt, rx_xprt) diff --git a/net/sunrpc/xprtsock.c b/net/sunrpc/xprtsock.c index 027b37de694b..173e3b0fd7a3 100644 --- a/net/sunrpc/xprtsock.c +++ b/net/sunrpc/xprtsock.c @@ -3501,7 +3501,7 @@ static struct rpc_xprt *xs_setup_tcp_tls(struct xprt_create *args) transport = container_of(xprt, struct sock_xprt, xprt); xprt->prot = IPPROTO_TCP; - xprt->xprt_class = &xs_tcp_transport; + xprt->xprt_class = &xs_tcp_tls_transport; xprt->max_payload = RPC_MAX_FRAGMENT_SIZE; xprt->bind_timeout = XS_BIND_TO; diff --git a/net/tls/tls_sw.c b/net/tls/tls_sw.c index 771e02bff519..226e0f176fdc 100644 --- a/net/tls/tls_sw.c +++ b/net/tls/tls_sw.c @@ -436,7 +436,8 @@ int tls_tx_records(struct sock *sk, int flags) /* Tx all ready records */ list_for_each_entry_safe(rec, tmp, &ctx->tx_list, list) { - if (READ_ONCE(rec->tx_ready)) { + /* Pairs with smp_store_release() in tls_encrypt_done() */ + if (smp_load_acquire(&rec->tx_ready)) { if (flags == -1) tx_flags = rec->tx_flags; else @@ -504,8 +505,14 @@ static void tls_encrypt_done(void *data, int err) if (rec) { struct tls_rec *first_rec; - /* Mark the record as ready for transmission */ - smp_store_mb(rec->tx_ready, true); + /* Mark the record as ready for transmission. Pairs with + * smp_load_acquire() in tls_tx_records(): the sge + * offset/length update above must be visible before tx_ready. + */ + smp_store_release(&rec->tx_ready, true); + + /* Order the tx_ready store before the tx_list head check */ + smp_mb(); /* If received record is at head of tx_list, schedule tx */ first_rec = list_first_entry(&ctx->tx_list, @@ -1146,6 +1153,7 @@ tls_rx_rec_wait(struct sock *sk, bool nonblock, bool released, bool has_copied) if (!timeo) return -EAGAIN; + ctx->empty_run = 0; released = true; add_wait_queue(sk_sleep(sk), &wait); sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk); @@ -1565,6 +1573,7 @@ static int tls_rx_one_record(struct sock *sk, struct msghdr *msg, struct tls_decrypt_arg *darg) { struct tls_context *tls_ctx = tls_get_ctx(sk); + struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx); struct tls_prot_info *prot = &tls_ctx->prot_info; struct strp_msg *rxm; int err; @@ -1582,6 +1591,19 @@ static int tls_rx_one_record(struct sock *sk, struct msghdr *msg, rxm->full_len -= prot->overhead_size; tls_advance_record_sn(sk, prot, &tls_ctx->rx); + /* A peer may send empty data records, e.g. as cover traffic, but + * a burst of them traps the reader in the kernel. Treat more than + * 128 in a row, without the reader sleeping or returning to the + * caller in between, as a protocol violation. Stop the strparser + * before the next record gets parsed, so the reader finds the + * error in tls_rx_rec_wait(). + */ + if (rxm->full_len || + tls_msg(darg->skb)->control != TLS_RECORD_TYPE_DATA) + ctx->empty_run = 0; + else if (unlikely(++ctx->empty_run > 128)) + tls_strp_abort_strp(&ctx->strp, -EBADMSG); + return tls_check_pending_rekey(sk, tls_ctx, darg->skb); } @@ -1761,6 +1783,7 @@ static int tls_rx_reader_acquire(struct sock *sk, struct tls_sw_context_rx *ctx, } WRITE_ONCE(ctx->reader_present, 1); + ctx->empty_run = 0; return 0; } @@ -1874,9 +1897,11 @@ int tls_sw_recvmsg(struct sock *sk, tlm->control == TLS_RECORD_TYPE_DATA) darg.zc = true; - /* Do not use async mode if record is non-data */ + /* Do not use async mode if record is non-data or empty, + * recv_end would report an error after empty records as EOF. + */ if (tlm->control == TLS_RECORD_TYPE_DATA) - darg.async = ctx->async_capable; + darg.async = ctx->async_capable && to_decrypt; else darg.async = false; @@ -1918,7 +1943,10 @@ put_on_rx_list_err: DEBUG_NET_WARN_ON_ONCE(darg.skb == ctx->strp.anchor); - if (async) { + /* Consume empty records, even when peeking, so that + * they cannot pile up on rx_list. + */ + if (async && chunk) { /* TLS 1.2-only, to_decrypt must be text len */ chunk = min_t(int, to_decrypt, len); async_copy_bytes += chunk; @@ -1939,7 +1967,7 @@ put_on_rx_list: if (err < 0) goto put_on_rx_list_err; - if (is_peek) { + if (is_peek && chunk) { peeked += chunk; goto put_on_rx_list; } @@ -2023,32 +2051,40 @@ ssize_t tls_sw_splice_read(struct socket *sock, loff_t *ppos, if (err) goto splice_read_end; - if (!skb_queue_empty(&ctx->rx_list)) { - skb = __skb_dequeue(&ctx->rx_list); - } else { - struct tls_decrypt_arg darg; + for (;;) { + if (!skb_queue_empty(&ctx->rx_list)) { + skb = __skb_dequeue(&ctx->rx_list); + } else { + struct tls_decrypt_arg darg; - err = tls_rx_rec_wait(sk, nonblock, true, false); - if (err <= 0) - goto splice_read_end; + err = tls_rx_rec_wait(sk, nonblock, true, false); + if (err <= 0) + goto splice_read_end; - memset(&darg.inargs, 0, sizeof(darg.inargs)); + memset(&darg.inargs, 0, sizeof(darg.inargs)); - err = tls_rx_one_record(sk, NULL, &darg); - if (err < 0) - goto splice_read_end; + err = tls_rx_one_record(sk, NULL, &darg); + if (err < 0) + goto splice_read_end; - tls_rx_rec_done(ctx); - skb = darg.skb; - } + tls_rx_rec_done(ctx); + skb = darg.skb; + } - rxm = strp_msg(skb); - tlm = tls_msg(skb); + rxm = strp_msg(skb); + tlm = tls_msg(skb); - /* splice does not support reading control messages */ - if (tlm->control != TLS_RECORD_TYPE_DATA) { - err = -EINVAL; - goto splice_requeue; + /* splice does not support reading control messages */ + if (tlm->control != TLS_RECORD_TYPE_DATA) { + err = -EINVAL; + goto splice_requeue; + } + + /* Splicing zero bytes would read as EOF */ + if (rxm->full_len) + break; + + consume_skb(skb); } chunk = min_t(unsigned int, rxm->full_len, len); @@ -2594,7 +2630,8 @@ int tls_set_sw_offload(struct sock *sk, int tx, } } - ctx->push_pending_record = tls_sw_push_pending_record; + if (tx) + ctx->push_pending_record = tls_sw_push_pending_record; /* setkey is the last operation that could fail during a * rekey. if it succeeds, we can start modifying the diff --git a/net/unix/af_unix.c b/net/unix/af_unix.c index 98fcfd7301f6..f847cf1fbeaf 100644 --- a/net/unix/af_unix.c +++ b/net/unix/af_unix.c @@ -1750,6 +1750,7 @@ restart: newu = unix_sk(newsk); otheru = unix_sk(other); newu->listener = other; + newu->recvmsg_inq = READ_ONCE(otheru->recvmsg_inq); newu->scm_rights_notrunc = READ_ONCE(otheru->scm_rights_notrunc); RCU_INIT_POINTER(newsk->sk_wq, &newu->peer_wq); diff --git a/net/unix/garbage.c b/net/unix/garbage.c index da774f56ca64..fbeabfb0db34 100644 --- a/net/unix/garbage.c +++ b/net/unix/garbage.c @@ -78,9 +78,9 @@ struct unix_vertex { struct list_head edges; struct list_head entry; struct list_head scc_entry; - unsigned long out_degree; - unsigned long index; - unsigned long scc_index; + u64 out_degree; + u64 index; + u64 scc_index; }; struct unix_edge { @@ -148,8 +148,8 @@ enum unix_vertex_index { UNIX_VERTEX_INDEX_START, }; -static unsigned long unix_vertex_unvisited_index = UNIX_VERTEX_INDEX_MARK1; -static unsigned long unix_vertex_max_scc_index = UNIX_VERTEX_INDEX_START; +static u64 unix_vertex_unvisited_index = UNIX_VERTEX_INDEX_MARK1; +static u64 unix_vertex_max_scc_index = UNIX_VERTEX_INDEX_START; static void unix_add_edge(struct scm_fp_list *fpl, struct unix_edge *edge) { @@ -329,9 +329,6 @@ void unix_peek_fpl(struct scm_fp_list *fpl) if (!fpl || !fpl->count_unix) return; - if (!READ_ONCE(gc_in_progress)) - return; - /* Invalidate the final refcnt check in unix_vertex_dead(). */ spin_lock(&unix_peek_lock); raw_write_seqcount_barrier(&unix_peek_seq); @@ -372,7 +369,7 @@ static bool unix_vertex_dead(struct unix_vertex *vertex) } static LIST_HEAD(unix_visited_vertices); -static unsigned long unix_vertex_grouped_index = UNIX_VERTEX_INDEX_MARK2; +static u64 unix_vertex_grouped_index = UNIX_VERTEX_INDEX_MARK2; static bool unix_scc_dead(struct list_head *scc) { @@ -450,14 +447,14 @@ static bool unix_scc_cyclic(struct list_head *scc) return false; } -static unsigned long __unix_walk_scc(struct unix_vertex *vertex, - unsigned long *last_index, - struct sk_buff_head *hitlist) +static u64 __unix_walk_scc(struct unix_vertex *vertex, + u64 *last_index, + struct sk_buff_head *hitlist) { - unsigned long cyclic_sccs = 0; LIST_HEAD(vertex_stack); struct unix_edge *edge; LIST_HEAD(edge_stack); + u64 cyclic_sccs = 0; next_vertex: /* Push vertex to vertex_stack and mark it as on-stack @@ -553,12 +550,12 @@ prev_vertex: return cyclic_sccs; } -static unsigned long unix_graph_cyclic_sccs; +static u64 unix_graph_cyclic_sccs; static void unix_walk_scc(struct sk_buff_head *hitlist) { - unsigned long last_index = UNIX_VERTEX_INDEX_START; - unsigned long cyclic_sccs = 0; + u64 last_index = UNIX_VERTEX_INDEX_START; + u64 cyclic_sccs = 0; unix_vertex_max_scc_index = UNIX_VERTEX_INDEX_START; @@ -582,7 +579,7 @@ static void unix_walk_scc(struct sk_buff_head *hitlist) static void unix_walk_scc_fast(struct sk_buff_head *hitlist) { - unsigned long cyclic_sccs = unix_graph_cyclic_sccs; + u64 cyclic_sccs = unix_graph_cyclic_sccs; while (!list_empty(&unix_unvisited_vertices)) { struct unix_vertex *vertex; diff --git a/net/vmw_vsock/hyperv_transport.c b/net/vmw_vsock/hyperv_transport.c index 855b15971c35..551eabe69014 100644 --- a/net/vmw_vsock/hyperv_transport.c +++ b/net/vmw_vsock/hyperv_transport.c @@ -697,6 +697,9 @@ static s64 hvs_stream_has_data(struct vsock_sock *vsk) struct hvsock *hvs = vsk->trans; s64 ret; + if (!hvs->chan) + return 0; + if (hvs->recv_data_len > 0) return hvs->recv_data_len; diff --git a/net/vmw_vsock/virtio_transport.c b/net/vmw_vsock/virtio_transport.c index 4f9aa9c4c3aa..cf63bc99f3cc 100644 --- a/net/vmw_vsock/virtio_transport.c +++ b/net/vmw_vsock/virtio_transport.c @@ -714,8 +714,10 @@ static int virtio_vsock_vqs_init(struct virtio_vsock *vsock) atomic_set(&vsock->queued_replies, 0); ret = virtio_find_vqs(vdev, VSOCK_VQ_MAX, vsock->vqs, vqs_info, NULL); - if (ret < 0) + if (ret < 0) { + memset(vsock->vqs, 0, sizeof(vsock->vqs)); return ret; + } virtio_vsock_update_guest_cid(vsock); @@ -776,11 +778,19 @@ static void virtio_vsock_vqs_del(struct virtio_vsock *vsock) vsock->event_run = false; mutex_unlock(&vsock->event_lock); + virtio_vsock_skb_queue_purge(&vsock->send_pkt_queue); + /* Flush all device writes and interrupts, device will not use any * more buffers. */ virtio_reset_device(vdev); + /* After a failed restore no virtqueues are live, and a second + * del_vqs() would free virtio-mmio's IRQ again (a WARN in free_irq()). + */ + if (!vsock->vqs[VSOCK_VQ_RX]) + return; + mutex_lock(&vsock->rx_lock); while ((skb = virtqueue_detach_unused_buf(vsock->vqs[VSOCK_VQ_RX]))) kfree_skb(skb); @@ -791,10 +801,10 @@ static void virtio_vsock_vqs_del(struct virtio_vsock *vsock) kfree_skb(skb); mutex_unlock(&vsock->tx_lock); - virtio_vsock_skb_queue_purge(&vsock->send_pkt_queue); - /* Delete virtqueues and flush outstanding callbacks if any */ vdev->config->del_vqs(vdev); + + memset(vsock->vqs, 0, sizeof(vsock->vqs)); } static int virtio_vsock_probe(struct virtio_device *vdev) diff --git a/net/wireless/nl80211.c b/net/wireless/nl80211.c index f29acf851376..e7dd32880598 100644 --- a/net/wireless/nl80211.c +++ b/net/wireless/nl80211.c @@ -9028,10 +9028,8 @@ static int nl80211_dump_station(struct sk_buff *skb, /* this fails if the wdev is being removed */ wdev = __nl80211_lock_held_wdev(rdev, netns, wdev); - if (IS_ERR(wdev)) { - err = PTR_ERR(wdev); - goto out_err; - } + if (IS_ERR(wdev)) + return PTR_ERR(wdev); /* try again locked now */ locked = true; diff --git a/net/wireless/scan.c b/net/wireless/scan.c index ac56338f0f43..1c50a16c0e9b 100644 --- a/net/wireless/scan.c +++ b/net/wireless/scan.c @@ -2453,6 +2453,7 @@ cfg80211_inform_single_bss_data(struct wiphy *wiphy, if (cfg80211_add_nontrans_list(data->source_bss, &res->pub)) { if (__cfg80211_unlink_bss(rdev, res)) { rdev->bss_generation++; + bss_ref_put(rdev, res); res = NULL; } } @@ -2592,7 +2593,7 @@ cfg80211_parse_mbssid_data(struct wiphy *wiphy, if (elem->data[0] < 1 || (int)elem->data[0] > 8) continue; for_each_element(sub, elem->data + 1, elem->datalen - 1) { - u8 profile_len; + size_t profile_len; if (sub->id != 0 || sub->datalen < 4) { /* not a valid BSS profile */ diff --git a/net/wireless/util.c b/net/wireless/util.c index 59912f4a93c8..ebb1f6ec7efc 100644 --- a/net/wireless/util.c +++ b/net/wireless/util.c @@ -863,12 +863,12 @@ __ieee80211_amsdu_copy(struct sk_buff *skb, unsigned int hlen, return frame; } -static u16 +static unsigned int ieee80211_amsdu_subframe_length(void *field, u8 mesh_flags, u8 hdr_type) { __le16 *field_le = field; __be16 *field_be = field; - u16 len; + unsigned int len; if (hdr_type >= 2) len = le16_to_cpu(*field_le); @@ -890,7 +890,7 @@ bool ieee80211_is_valid_amsdu(struct sk_buff *skb, u8 mesh_hdr) __be16 len; u8 mesh_flags; } hdr; - u16 len; + unsigned int len; if (sizeof(hdr) > remaining) return false; diff --git a/net/xdp/xsk.c b/net/xdp/xsk.c index 781ba46eb152..f22f9a2cdbbe 100644 --- a/net/xdp/xsk.c +++ b/net/xdp/xsk.c @@ -241,6 +241,7 @@ static int xsk_rcv_zc(struct xdp_sock *xs, struct xdp_buff *xdp, u32 len) goto err; } + xdp_buff_clear_frags_flag(xdp); __xsk_rcv_zc_safe(xs, xskb, len, contd); xskb_list = &xskb->pool->xskb_list; list_for_each_entry_safe(pos, tmp, xskb_list, list_node) { @@ -1011,14 +1012,6 @@ static int xsk_skb_metadata(struct sk_buff *skb, void *buffer, skb->csum_start = hr + csum_start; skb->csum_offset = csum_offset; skb->ip_summed = CHECKSUM_PARTIAL; - - if (unlikely(pool->tx_sw_csum)) { - int err; - - err = skb_checksum_help(skb); - if (err) - return err; - } } if (flags & XDP_TXMD_FLAGS_LAUNCH_TIME) @@ -1030,6 +1023,15 @@ static int xsk_skb_metadata(struct sk_buff *skb, void *buffer, return 0; } +static int xsk_skb_sw_csum(struct sk_buff *skb, struct xsk_buff_pool *pool) +{ + if (unlikely(pool->tx_sw_csum && + skb->ip_summed == CHECKSUM_PARTIAL)) + return skb_checksum_help(skb); + + return 0; +} + static struct sk_buff *xsk_build_skb_zerocopy(struct xdp_sock *xs, struct xdp_desc *desc) { @@ -1277,6 +1279,12 @@ static int __xsk_generic_xmit(struct sock *sk) continue; } + err = xsk_skb_sw_csum(skb, xs->pool); + if (unlikely(err)) { + xsk_drop_skb(skb); + goto out; + } + err = __dev_direct_xmit(skb, xs->queue_id); if (err == NETDEV_TX_BUSY) { /* Tell user-space to retry the send */ diff --git a/net/xdp/xsk_buff_pool.c b/net/xdp/xsk_buff_pool.c index 7750d2ec4ee2..5ec092f7cb6f 100644 --- a/net/xdp/xsk_buff_pool.c +++ b/net/xdp/xsk_buff_pool.c @@ -629,7 +629,7 @@ struct xdp_buff *xp_alloc(struct xsk_buff_pool *pool) xskb->xdp.data = xskb->xdp.data_hard_start + XDP_PACKET_HEADROOM; xskb->xdp.data_meta = xskb->xdp.data; - xskb->xdp.flags = 0; + xskb->xdp.flags &= XDP_FLAGS_HAS_FRAGS; if (pool->dev) xp_dma_sync_for_device(pool, xskb->dma, pool->frame_len); diff --git a/samples/Kconfig b/samples/Kconfig index 00eed83c07df..744d991ea620 100644 --- a/samples/Kconfig +++ b/samples/Kconfig @@ -71,7 +71,7 @@ config SAMPLE_KOBJECT config SAMPLE_KPROBES tristate "Build kprobes examples -- loadable modules only" - depends on KPROBES && m + depends on KPROBES && EVENT_TRACING && m help This build several kprobes example modules. @@ -88,7 +88,7 @@ config SAMPLE_HW_BREAKPOINT config SAMPLE_FPROBE tristate "Build fprobe examples -- loadable modules only" - depends on FPROBE && m + depends on FPROBE && EVENT_TRACING && m help This builds a fprobe example module. This module has an option 'symbol'. You can specify a probed symbol or symbols separated with ','. diff --git a/samples/fprobe/fprobe_example.c b/samples/fprobe/fprobe_example.c index bfe98ce826f3..3b94839b3199 100644 --- a/samples/fprobe/fprobe_example.c +++ b/samples/fprobe/fprobe_example.c @@ -1,12 +1,12 @@ // SPDX-License-Identifier: GPL-2.0-only /* * Here's a sample kernel module showing the use of fprobe to dump a - * stack trace and selected registers when kernel_clone() is called. + * stack trace and function entry/exit when kernel_clone() is called. * - * For more information on theory of operation of kprobes, see - * Documentation/trace/kprobes.rst + * For more information on theory of operation of fprobe, see + * Documentation/trace/fprobe.rst * - * You will see the trace data in /var/log/messages and on the console + * You will see the trace data in /sys/kernel/tracing/trace * whenever kernel_clone() is invoked to create a new process. */ @@ -15,10 +15,9 @@ #include <linux/kernel.h> #include <linux/module.h> #include <linux/fprobe.h> -#include <linux/sched/debug.h> #include <linux/slab.h> +#include <linux/trace_printk.h> -#define BACKTRACE_DEPTH 16 #define MAX_SYMBOL_LEN 4096 static struct fprobe sample_probe; static unsigned long nhit; @@ -35,34 +34,14 @@ static bool stackdump = true; module_param(stackdump, bool, 0644); MODULE_PARM_DESC(stackdump, "Enable stackdump."); -static bool use_trace = false; -module_param(use_trace, bool, 0644); -MODULE_PARM_DESC(use_trace, "Use trace_printk instead of printk. This is only for debugging."); - -static void show_backtrace(void) -{ - unsigned long stacks[BACKTRACE_DEPTH]; - unsigned int len; - - len = stack_trace_save(stacks, BACKTRACE_DEPTH, 2); - stack_trace_print(stacks, len, 24); -} - static int sample_entry_handler(struct fprobe *fp, unsigned long ip, unsigned long ret_ip, struct ftrace_regs *fregs, void *data) { - if (use_trace) - /* - * This is just an example, no kernel code should call - * trace_printk() except when actively debugging. - */ - trace_printk("Enter <%pS> ip = 0x%p\n", (void *)ip, (void *)ip); - else - pr_info("Enter <%pS> ip = 0x%p\n", (void *)ip, (void *)ip); + trace_printk("Enter <%pS> ip = 0x%p\n", (void *)ip, (void *)ip); nhit++; if (stackdump) - show_backtrace(); + trace_dump_stack(0); return 0; } @@ -72,19 +51,11 @@ static void sample_exit_handler(struct fprobe *fp, unsigned long ip, { unsigned long rip = ret_ip; - if (use_trace) - /* - * This is just an example, no kernel code should call - * trace_printk() except when actively debugging. - */ - trace_printk("Return from <%pS> ip = 0x%p to rip = 0x%p (%pS)\n", - (void *)ip, (void *)ip, (void *)rip, (void *)rip); - else - pr_info("Return from <%pS> ip = 0x%p to rip = 0x%p (%pS)\n", - (void *)ip, (void *)ip, (void *)rip, (void *)rip); + trace_printk("Return from <%pS> ip = 0x%p to rip = 0x%p (%pS)\n", + (void *)ip, (void *)ip, (void *)rip, (void *)rip); nhit++; if (stackdump) - show_backtrace(); + trace_dump_stack(0); } static int __init fprobe_init(void) diff --git a/samples/kprobes/kprobe_example.c b/samples/kprobes/kprobe_example.c index 53ec6c8b8c40..0f516a2b04be 100644 --- a/samples/kprobes/kprobe_example.c +++ b/samples/kprobes/kprobe_example.c @@ -6,7 +6,7 @@ * For more information on theory of operation of kprobes, see * Documentation/trace/kprobes.rst * - * You will see the trace data in /var/log/messages and on the console + * You will see the trace data in /sys/kernel/tracing/trace * whenever kernel_clone() is invoked to create a new process. */ @@ -15,6 +15,7 @@ #include <linux/kernel.h> #include <linux/module.h> #include <linux/kprobes.h> +#include <linux/trace_printk.h> static char symbol[KSYM_NAME_LEN] = "kernel_clone"; module_param_string(symbol, symbol, KSYM_NAME_LEN, 0644); @@ -28,39 +29,39 @@ static struct kprobe kp = { static int __kprobes handler_pre(struct kprobe *p, struct pt_regs *regs) { #ifdef CONFIG_X86 - pr_info("<%s> p->addr = 0x%p, ip = %lx, flags = 0x%lx\n", - p->symbol_name, p->addr, regs->ip, regs->flags); + trace_printk("<%s> p->addr = 0x%p, ip = %lx, flags = 0x%lx\n", + p->symbol_name, p->addr, regs->ip, regs->flags); #endif #ifdef CONFIG_PPC - pr_info("<%s> p->addr = 0x%p, nip = 0x%lx, msr = 0x%lx\n", - p->symbol_name, p->addr, regs->nip, regs->msr); + trace_printk("<%s> p->addr = 0x%p, nip = 0x%lx, msr = 0x%lx\n", + p->symbol_name, p->addr, regs->nip, regs->msr); #endif #ifdef CONFIG_MIPS - pr_info("<%s> p->addr = 0x%p, epc = 0x%lx, status = 0x%lx\n", - p->symbol_name, p->addr, regs->cp0_epc, regs->cp0_status); + trace_printk("<%s> p->addr = 0x%p, epc = 0x%lx, status = 0x%lx\n", + p->symbol_name, p->addr, regs->cp0_epc, regs->cp0_status); #endif #ifdef CONFIG_ARM64 - pr_info("<%s> p->addr = 0x%p, pc = 0x%lx, pstate = 0x%lx\n", - p->symbol_name, p->addr, (long)regs->pc, (long)regs->pstate); + trace_printk("<%s> p->addr = 0x%p, pc = 0x%lx, pstate = 0x%lx\n", + p->symbol_name, p->addr, (long)regs->pc, (long)regs->pstate); #endif #ifdef CONFIG_ARM - pr_info("<%s> p->addr = 0x%p, pc = 0x%lx, cpsr = 0x%lx\n", - p->symbol_name, p->addr, (long)regs->ARM_pc, (long)regs->ARM_cpsr); + trace_printk("<%s> p->addr = 0x%p, pc = 0x%lx, cpsr = 0x%lx\n", + p->symbol_name, p->addr, (long)regs->ARM_pc, (long)regs->ARM_cpsr); #endif #ifdef CONFIG_RISCV - pr_info("<%s> p->addr = 0x%p, pc = 0x%lx, status = 0x%lx\n", - p->symbol_name, p->addr, regs->epc, regs->status); + trace_printk("<%s> p->addr = 0x%p, pc = 0x%lx, status = 0x%lx\n", + p->symbol_name, p->addr, regs->epc, regs->status); #endif #ifdef CONFIG_S390 - pr_info("<%s> p->addr, 0x%p, ip = 0x%lx, flags = 0x%lx\n", - p->symbol_name, p->addr, regs->psw.addr, regs->flags); + trace_printk("<%s> p->addr = 0x%p, ip = 0x%lx, flags = 0x%lx\n", + p->symbol_name, p->addr, regs->psw.addr, regs->flags); #endif #ifdef CONFIG_LOONGARCH - pr_info("<%s> p->addr = 0x%p, era = 0x%lx, estat = 0x%lx\n", - p->symbol_name, p->addr, regs->csr_era, regs->csr_estat); + trace_printk("<%s> p->addr = 0x%p, era = 0x%lx, estat = 0x%lx\n", + p->symbol_name, p->addr, regs->csr_era, regs->csr_estat); #endif - /* A dump_stack() here will give a stack backtrace */ + /* A trace_dump_stack(0) here will give a stack backtrace */ return 0; } @@ -69,36 +70,36 @@ static void __kprobes handler_post(struct kprobe *p, struct pt_regs *regs, unsigned long flags) { #ifdef CONFIG_X86 - pr_info("<%s> p->addr = 0x%p, flags = 0x%lx\n", - p->symbol_name, p->addr, regs->flags); + trace_printk("<%s> p->addr = 0x%p, flags = 0x%lx\n", + p->symbol_name, p->addr, regs->flags); #endif #ifdef CONFIG_PPC - pr_info("<%s> p->addr = 0x%p, msr = 0x%lx\n", - p->symbol_name, p->addr, regs->msr); + trace_printk("<%s> p->addr = 0x%p, msr = 0x%lx\n", + p->symbol_name, p->addr, regs->msr); #endif #ifdef CONFIG_MIPS - pr_info("<%s> p->addr = 0x%p, status = 0x%lx\n", - p->symbol_name, p->addr, regs->cp0_status); + trace_printk("<%s> p->addr = 0x%p, status = 0x%lx\n", + p->symbol_name, p->addr, regs->cp0_status); #endif #ifdef CONFIG_ARM64 - pr_info("<%s> p->addr = 0x%p, pstate = 0x%lx\n", - p->symbol_name, p->addr, (long)regs->pstate); + trace_printk("<%s> p->addr = 0x%p, pstate = 0x%lx\n", + p->symbol_name, p->addr, (long)regs->pstate); #endif #ifdef CONFIG_ARM - pr_info("<%s> p->addr = 0x%p, cpsr = 0x%lx\n", - p->symbol_name, p->addr, (long)regs->ARM_cpsr); + trace_printk("<%s> p->addr = 0x%p, cpsr = 0x%lx\n", + p->symbol_name, p->addr, (long)regs->ARM_cpsr); #endif #ifdef CONFIG_RISCV - pr_info("<%s> p->addr = 0x%p, status = 0x%lx\n", - p->symbol_name, p->addr, regs->status); + trace_printk("<%s> p->addr = 0x%p, status = 0x%lx\n", + p->symbol_name, p->addr, regs->status); #endif #ifdef CONFIG_S390 - pr_info("<%s> p->addr, 0x%p, flags = 0x%lx\n", - p->symbol_name, p->addr, regs->flags); + trace_printk("<%s> p->addr = 0x%p, flags = 0x%lx\n", + p->symbol_name, p->addr, regs->flags); #endif #ifdef CONFIG_LOONGARCH - pr_info("<%s> p->addr = 0x%p, estat = 0x%lx\n", - p->symbol_name, p->addr, regs->csr_estat); + trace_printk("<%s> p->addr = 0x%p, estat = 0x%lx\n", + p->symbol_name, p->addr, regs->csr_estat); #endif } diff --git a/samples/kprobes/kretprobe_example.c b/samples/kprobes/kretprobe_example.c index 65d6dcafd742..9dd5cf9a7432 100644 --- a/samples/kprobes/kretprobe_example.c +++ b/samples/kprobes/kretprobe_example.c @@ -14,9 +14,8 @@ * Documentation/trace/kprobes.rst * * Build and insert the kernel module as done in the kprobe example. - * You will see the trace data in /var/log/messages and on the console - * whenever the probed function returns. (Some messages may be suppressed - * if syslogd is configured to eliminate duplicate messages.) + * You will see the trace data in /sys/kernel/tracing/trace + * whenever the probed function returns. */ #include <linux/kernel.h> @@ -24,6 +23,7 @@ #include <linux/kprobes.h> #include <linux/ktime.h> #include <linux/sched.h> +#include <linux/trace_printk.h> static char func_name[KSYM_NAME_LEN] = "kernel_clone"; module_param_string(func, func_name, KSYM_NAME_LEN, 0644); @@ -63,8 +63,8 @@ static int ret_handler(struct kretprobe_instance *ri, struct pt_regs *regs) now = ktime_get(); delta = ktime_to_ns(ktime_sub(now, data->entry_stamp)); - pr_info("%s returned %lu and took %lld ns to execute\n", - func_name, retval, (long long)delta); + trace_printk("%s returned %lu and took %lld ns to execute\n", + func_name, retval, (long long)delta); return 0; } NOKPROBE_SYMBOL(ret_handler); diff --git a/scripts/Makefile.autofdo b/scripts/Makefile.autofdo index 57a3aba6ffc2..32c18df237f1 100644 --- a/scripts/Makefile.autofdo +++ b/scripts/Makefile.autofdo @@ -13,7 +13,7 @@ endif ifdef CLANG_AUTOFDO_PROFILE CFLAGS_AUTOFDO_CLANG += -fprofile-sample-use=$(CLANG_AUTOFDO_PROFILE) -ffunction-sections CFLAGS_AUTOFDO_CLANG += -fsplit-machine-functions - RUSTFLAGS_AUTOFDO_CLANG += -Zprofile-sample-use=$(CLANG_AUTOFDO_PROFILE) -Zfunction-sections=y + 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 endif diff --git a/security/keys/key.c b/security/keys/key.c index 6ebb8691551f..3f1f0fc13710 100644 --- a/security/keys/key.c +++ b/security/keys/key.c @@ -245,6 +245,8 @@ struct key *key_alloc(struct key_type *type, const char *desc, } desclen = strlen(desc); + if (desclen >= KEY_MAX_DESC_SIZE) + goto error; quotalen = desclen + 1 + type->def_datalen; /* get hold of the key tracking for this user */ @@ -829,6 +831,7 @@ static key_ref_t __key_create_or_update(key_ref_t keyring_ref, key_ref_t key_ref; int ret; struct key_restriction *restrict_link = NULL; + size_t desclen; /* look up the key type to see if it's one of the registered kernel * types */ @@ -869,7 +872,12 @@ static key_ref_t __key_create_or_update(key_ref_t keyring_ref, if (!index_key.description) goto error_free_prep; } - index_key.desc_len = strlen(index_key.description); + desclen = strlen(index_key.description); + if (desclen >= KEY_MAX_DESC_SIZE) { + key_ref = ERR_PTR(-EINVAL); + goto error_free_prep; + } + index_key.desc_len = desclen; key_set_index_key(&index_key); ret = __key_link_lock(keyring, &index_key); @@ -1093,9 +1101,12 @@ int key_update(key_ref_t key_ref, const void *payload, size_t plen) if (ret < 0) return ret; + down_write(&key->sem); + /* attempt to update it if supported */ + ret = -EOPNOTSUPP; if (!key->type->update) - return -EOPNOTSUPP; + goto out; memset(&prep, 0, sizeof(prep)); prep.data = payload; @@ -1105,11 +1116,9 @@ int key_update(key_ref_t key_ref, const void *payload, size_t plen) if (key->type->preparse) { ret = key->type->preparse(&prep); if (ret < 0) - goto error; + goto out_free_preparse; } - down_write(&key->sem); - ret = key->type->update(key, &prep); if (ret == 0) { /* Updating a negative key positively instantiates it */ @@ -1117,11 +1126,12 @@ int key_update(key_ref_t key_ref, const void *payload, size_t plen) notify_key(key, NOTIFY_KEY_UPDATED, 0); } - up_write(&key->sem); - -error: +out_free_preparse: if (key->type->preparse) key->type->free_preparse(&prep); + +out: + up_write(&key->sem); return ret; } EXPORT_SYMBOL(key_update); diff --git a/security/keys/keyctl.c b/security/keys/keyctl.c index 36ffba0ebba6..d6b10fd67627 100644 --- a/security/keys/keyctl.c +++ b/security/keys/keyctl.c @@ -24,8 +24,6 @@ #include <keys/request_key_auth-type.h> #include "internal.h" -#define KEY_MAX_DESC_SIZE 4096 - static const unsigned char keyrings_capabilities[2] = { [0] = (KEYCTL_CAPS0_CAPABILITIES | (IS_ENABLED(CONFIG_PERSISTENT_KEYRINGS) ? KEYCTL_CAPS0_PERSISTENT_KEYRINGS : 0) | diff --git a/security/keys/keyctl_pkey.c b/security/keys/keyctl_pkey.c index 15b6bf6399b5..e7121523b9c9 100644 --- a/security/keys/keyctl_pkey.c +++ b/security/keys/keyctl_pkey.c @@ -129,45 +129,77 @@ static int keyctl_pkey_params_get_2(const struct keyctl_pkey_params __user *_par if (ret < 0) return ret; + down_read(¶ms->key->sem); + + if (!params->key->type->asym_query) { + ret = -EOPNOTSUPP; + goto out_up_key_sem; + } + ret = params->key->type->asym_query(params, &info); if (ret < 0) - return ret; + goto out_up_key_sem; switch (op) { case KEYCTL_PKEY_ENCRYPT: if (uparams.in_len > info.max_dec_size || - uparams.out_len > info.max_enc_size) - return -EINVAL; + uparams.out_len > info.max_enc_size) { + ret = -EINVAL; + goto out_up_key_sem; + } params->out_len = info.max_enc_size; break; case KEYCTL_PKEY_DECRYPT: if (uparams.in_len > info.max_enc_size || - uparams.out_len > info.max_dec_size) - return -EINVAL; + uparams.out_len > info.max_dec_size) { + ret = -EINVAL; + goto out_up_key_sem; + } params->out_len = info.max_dec_size; break; case KEYCTL_PKEY_SIGN: if (uparams.in_len > info.max_data_size || - uparams.out_len > info.max_sig_size) - return -EINVAL; + uparams.out_len > info.max_sig_size) { + ret = -EINVAL; + goto out_up_key_sem; + } params->out_len = info.max_sig_size; break; case KEYCTL_PKEY_VERIFY: if (uparams.in_len > info.max_data_size || - uparams.in2_len > info.max_sig_size) - return -EINVAL; + uparams.in2_len > info.max_sig_size) { + ret = -EINVAL; + goto out_up_key_sem; + } params->out_len = info.max_sig_size; break; default: - return -EOPNOTSUPP; + ret = -EOPNOTSUPP; + goto out_up_key_sem; } params->in_len = uparams.in_len; - return 0; + + switch (op) { + case KEYCTL_PKEY_VERIFY: + if (!params->key->type->asym_verify_signature) + ret = -EOPNOTSUPP; + break; + case KEYCTL_PKEY_ENCRYPT: + case KEYCTL_PKEY_DECRYPT: + case KEYCTL_PKEY_SIGN: + if (!params->key->type->asym_eds_op) + ret = -EOPNOTSUPP; + break; + } + +out_up_key_sem: + up_read(¶ms->key->sem); + return ret; } /* @@ -185,7 +217,16 @@ long keyctl_pkey_query(key_serial_t id, if (ret < 0) goto error; + down_read(¶ms.key->sem); + if (!params.key->type->asym_query) { + ret = -EOPNOTSUPP; + goto out_up_key_sem; + } + ret = params.key->type->asym_query(¶ms, &res); + +out_up_key_sem: + up_read(¶ms.key->sem); if (ret < 0) goto error; @@ -230,10 +271,6 @@ long keyctl_pkey_e_d_s(int op, if (ret < 0) goto error_params; - ret = -EOPNOTSUPP; - if (!params.key->type->asym_eds_op) - goto error_params; - switch (op) { case KEYCTL_PKEY_ENCRYPT: params.op = kernel_pkey_encrypt; @@ -260,7 +297,16 @@ long keyctl_pkey_e_d_s(int op, if (!out) goto error_in; + down_read(¶ms.key->sem); + if (!params.key->type->asym_eds_op) { + ret = -EOPNOTSUPP; + goto out_up_key_sem; + } + ret = params.key->type->asym_eds_op(¶ms, in, out); + +out_up_key_sem: + up_read(¶ms.key->sem); if (ret < 0) goto error_out; @@ -305,31 +351,37 @@ long keyctl_pkey_verify(const struct keyctl_pkey_params __user *_params, ret = keyctl_pkey_params_get_2(_params, _info, KEYCTL_PKEY_VERIFY, ¶ms); if (ret < 0) - goto error_params; - - ret = -EOPNOTSUPP; - if (!params.key->type->asym_verify_signature) - goto error_params; + goto out_free_params; in = memdup_user(_in, params.in_len); if (IS_ERR(in)) { ret = PTR_ERR(in); - goto error_params; + goto out_free_params; } in2 = memdup_user(_in2, params.in2_len); if (IS_ERR(in2)) { ret = PTR_ERR(in2); - goto error_in; + goto out_free_in; } params.op = kernel_pkey_verify; + down_read(¶ms.key->sem); + if (!params.key->type->asym_verify_signature) { + ret = -EOPNOTSUPP; + goto out_up_key_sem; + } + ret = params.key->type->asym_verify_signature(¶ms, in, in2); +out_up_key_sem: + up_read(¶ms.key->sem); kfree(in2); -error_in: + +out_free_in: kfree(in); -error_params: + +out_free_params: keyctl_pkey_params_free(¶ms); return ret; } diff --git a/security/keys/keyring.c b/security/keys/keyring.c index 7143f3079d20..357f56360810 100644 --- a/security/keys/keyring.c +++ b/security/keys/keyring.c @@ -598,6 +598,12 @@ static int keyring_search_iterator(const void *object, void *iterator_data) return 0; } + /* A key the caller did not ask for must not decide the result. */ + if (!ctx->match_data.cmp(key, &ctx->match_data)) { + kleave(" = 0 [!match]"); + return 0; + } + /* skip invalidated, revoked and expired keys */ if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) { time64_t expiry = READ_ONCE(key->expiry); @@ -617,12 +623,6 @@ static int keyring_search_iterator(const void *object, void *iterator_data) } } - /* keys that don't match */ - if (!ctx->match_data.cmp(key, &ctx->match_data)) { - kleave(" = 0 [!match]"); - return 0; - } - /* key must have search permissions */ if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) && key_task_permission(make_key_ref(key, ctx->possessed), @@ -957,7 +957,6 @@ key_ref_t keyring_search(key_ref_t keyring, struct keyring_search_context ctx = { .index_key.type = type, .index_key.description = description, - .index_key.desc_len = strlen(description), .cred = current_cred(), .match_data.cmp = key_default_cmp, .match_data.raw_data = description, @@ -965,8 +964,14 @@ key_ref_t keyring_search(key_ref_t keyring, .flags = KEYRING_SEARCH_DO_STATE_CHECK, }; key_ref_t key; + size_t desclen; int ret; + desclen = strlen(description); + if (desclen >= KEY_MAX_DESC_SIZE) + return ERR_PTR(-EINVAL); + ctx.index_key.desc_len = desclen; + if (recurse) ctx.flags |= KEYRING_SEARCH_RECURSE; if (type->match_preparse) { @@ -1501,9 +1506,15 @@ static int __key_unlink_begin(struct key *keyring, struct key *key, struct assoc_array_edit **_edit) { struct assoc_array_edit *edit; + const void *object; BUG_ON(*_edit != NULL); + object = assoc_array_find(&keyring->keys, &keyring_assoc_array_ops, + &key->index_key); + if (!object || keyring_ptr_to_key(object) != key) + return -ENOENT; + edit = assoc_array_delete(&keyring->keys, &keyring_assoc_array_ops, &key->index_key); if (IS_ERR(edit)) diff --git a/security/keys/request_key.c b/security/keys/request_key.c index e6ba2d054399..22cd66a44da5 100644 --- a/security/keys/request_key.c +++ b/security/keys/request_key.c @@ -584,7 +584,6 @@ struct key *request_key_and_link(struct key_type *type, .index_key.type = type, .index_key.domain_tag = domain_tag, .index_key.description = description, - .index_key.desc_len = strlen(description), .cred = current_cred(), .match_data.cmp = key_default_cmp, .match_data.raw_data = description, @@ -595,8 +594,14 @@ struct key *request_key_and_link(struct key_type *type, }; struct key *key; key_ref_t key_ref; + size_t desclen; int ret; + desclen = strlen(description); + if (desclen >= KEY_MAX_DESC_SIZE) + return ERR_PTR(-EINVAL); + ctx.index_key.desc_len = desclen; + kenter("%s,%s,%p,%zu,%p,%p,%lx", ctx.index_key.type->name, ctx.index_key.description, callout_info, callout_len, aux, dest_keyring, flags); @@ -787,7 +792,6 @@ struct key *request_key_rcu(struct key_type *type, .index_key.type = type, .index_key.domain_tag = domain_tag, .index_key.description = description, - .index_key.desc_len = strlen(description), .cred = current_cred(), .match_data.cmp = key_default_cmp, .match_data.raw_data = description, @@ -797,6 +801,12 @@ struct key *request_key_rcu(struct key_type *type, }; struct key *key; key_ref_t key_ref; + size_t desclen; + + desclen = strlen(description); + if (desclen >= KEY_MAX_DESC_SIZE) + return ERR_PTR(-EINVAL); + ctx.index_key.desc_len = desclen; kenter("%s,%s", type->name, description); diff --git a/security/landlock/ns.c b/security/landlock/ns.c index cd44c927f83a..06d9784746fe 100644 --- a/security/landlock/ns.c +++ b/security/landlock/ns.c @@ -94,7 +94,8 @@ static const struct access_masks ns_permission = { * 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 * when the namespace type is not in the domain's allowed set. At allocation - * time @ns->ns_id is still zero and is logged as such. + * time @ns->ns_id is already set even though the namespace is not reachable + * from user space yet. * * Return: 0 if allowed, -EPERM if denied. */ diff --git a/security/selinux/netlabel.c b/security/selinux/netlabel.c index d51dfe892312..24b11d1891d8 100644 --- a/security/selinux/netlabel.c +++ b/security/selinux/netlabel.c @@ -557,9 +557,10 @@ static int selinux_netlbl_socket_connect_helper(struct sock *sk, * is set to AF_UNSPEC, if that is what is happening we want to reset * the socket */ if (addr->sa_family == AF_UNSPEC) { - netlbl_sock_delattr(sk); + rc = netlbl_sock_delattr(sk); + if (rc) + return rc; sksec->nlbl_state = NLBL_REQSKB; - rc = 0; return rc; } secattr = selinux_netlbl_sock_genattr(sk); diff --git a/security/smack/smack_lsm.c b/security/smack/smack_lsm.c index 28a8e12603ce..3a4a33568297 100644 --- a/security/smack/smack_lsm.c +++ b/security/smack/smack_lsm.c @@ -2656,22 +2656,26 @@ static int smack_netlbl_add(struct sock *sk) * * Remove the outbound smack value from a socket */ -static void smack_netlbl_delete(struct sock *sk) +static int smack_netlbl_delete(struct sock *sk) { struct socket_smack *ssp = smack_sock(sk); + int rc; /* * Take the label off the socket if one is set. */ if (ssp->smk_state != SMK_NETLBL_LABELED) - return; + return 0; local_bh_disable(); bh_lock_sock_nested(sk); - netlbl_sock_delattr(sk); + rc = netlbl_sock_delattr(sk); bh_unlock_sock(sk); local_bh_enable(); + if (rc) + return rc; ssp->smk_state = SMK_NETLBL_UNLABELED; + return 0; } /** @@ -2711,7 +2715,7 @@ static int smk_ipv4_check(struct sock *sk, struct sockaddr_in *sap) * Clear the socket netlabel if it's set. */ if (!rc) - smack_netlbl_delete(sk); + rc = smack_netlbl_delete(sk); } rcu_read_unlock(); @@ -4548,7 +4552,7 @@ static int smack_inet_conn_request(const struct sock *sk, struct sk_buff *skb, if (hskp == NULL) rc = netlbl_req_setattr(req, &ssp->smk_out->smk_netlabel); else - netlbl_req_delattr(req); + rc = netlbl_req_delattr(req); return rc; } diff --git a/sound/core/pcm_native.c b/sound/core/pcm_native.c index 1f5ebfd2886a..5d80b56449e2 100644 --- a/sound/core/pcm_native.c +++ b/sound/core/pcm_native.c @@ -1127,7 +1127,13 @@ int snd_pcm_status64(struct snd_pcm_substream *substream, status->trigger_tstamp_sec = runtime->trigger_tstamp.tv_sec; status->trigger_tstamp_nsec = runtime->trigger_tstamp.tv_nsec; if (snd_pcm_running(substream)) { - snd_pcm_update_hw_ptr(substream); + if (snd_pcm_update_hw_ptr(substream) < 0) { + /* update_hw_ptr may have put us in xrun state, update state */ + status->state = runtime->state; + status->suspended_state = runtime->suspended_state; + status->trigger_tstamp_sec = runtime->trigger_tstamp.tv_sec; + status->trigger_tstamp_nsec = runtime->trigger_tstamp.tv_nsec; + } if (runtime->tstamp_mode == SNDRV_PCM_TSTAMP_ENABLE) { status->tstamp_sec = runtime->status->tstamp.tv_sec; status->tstamp_nsec = diff --git a/sound/hda/codecs/cirrus/cs420x.c b/sound/hda/codecs/cirrus/cs420x.c index 6cba01228c27..85c2ecf46d38 100644 --- a/sound/hda/codecs/cirrus/cs420x.c +++ b/sound/hda/codecs/cirrus/cs420x.c @@ -571,7 +571,6 @@ static const struct hda_model_fixup cs4208_models[] = { static const struct hda_quirk cs4208_fixup_tbl[] = { SND_PCI_QUIRK_VENDOR(0x106b, "Apple", CS4208_MAC_AUTO), - SND_PCI_QUIRK(0x8086, 0x7270, "MacBookAir 7,2", CS4208_MAC_AUTO), {} /* terminator */ }; @@ -584,7 +583,6 @@ static const struct hda_quirk cs4208_mac_fixup_tbl[] = { SND_PCI_QUIRK(0x106b, 0x7800, "MacPro 6,1", CS4208_MACMINI), SND_PCI_QUIRK(0x106b, 0x7b00, "MacBookPro 12,1", CS4208_MBP11), SND_PCI_QUIRK(0x106b, 0x7f00, "iMac 16,1", CS4208_MBP11), - SND_PCI_QUIRK(0x8086, 0x7270, "MacBookAir 7,2", CS4208_MBA6), {} /* terminator */ }; diff --git a/sound/hda/codecs/conexant.c b/sound/hda/codecs/conexant.c index 88651a36dd33..5f2b0b55ab6e 100644 --- a/sound/hda/codecs/conexant.c +++ b/sound/hda/codecs/conexant.c @@ -289,6 +289,7 @@ enum { CXT_FIXUP_HEADPHONE_MIC_PIN, CXT_FIXUP_HEADPHONE_MIC, CXT_FIXUP_GPIO1, + CXT_FIXUP_GPIO2, CXT_FIXUP_ASPIRE_DMIC, CXT_FIXUP_THINKPAD_ACPI, CXT_FIXUP_LENOVO_XPAD_ACPI, @@ -1001,6 +1002,15 @@ static const struct hda_fixup cxt_fixups[] = { { } }, }, + [CXT_FIXUP_GPIO2] = { + .type = HDA_FIXUP_VERBS, + .v.verbs = (const struct hda_verb[]) { + { 0x01, AC_VERB_SET_GPIO_MASK, 0x02 }, + { 0x01, AC_VERB_SET_GPIO_DIRECTION, 0x02 }, + { 0x01, AC_VERB_SET_GPIO_DATA, 0x02 }, + { } + }, + }, [CXT_FIXUP_ASPIRE_DMIC] = { .type = HDA_FIXUP_FUNC, .v.func = cxt_fixup_stereo_dmic, @@ -1223,6 +1233,8 @@ static const struct hda_quirk cxt5066_fixups[] = { SND_PCI_QUIRK(0x14f1, 0x0252, "MBX-Z60MR100", CXT_FIXUP_HP_A_U), SND_PCI_QUIRK(0x14f1, 0x0265, "SWS JS201D", CXT_PINCFG_SWS_JS201D), SND_PCI_QUIRK(0x152d, 0x0833, "OLPC XO-1.5", CXT_FIXUP_OLPC_XO), + SND_PCI_QUIRK(0x1558, 0xa600, "Acer TravelLite TL05-41M", + CXT_FIXUP_GPIO2), SND_PCI_QUIRK(0x17aa, 0x20f2, "Lenovo T400", CXT_PINCFG_LENOVO_TP410), SND_PCI_QUIRK(0x17aa, 0x215e, "Lenovo T410", CXT_PINCFG_LENOVO_TP410), SND_PCI_QUIRK(0x17aa, 0x215f, "Lenovo T510", CXT_PINCFG_LENOVO_TP410), diff --git a/sound/hda/codecs/realtek/alc269.c b/sound/hda/codecs/realtek/alc269.c index a756e0076021..96fa8c2782bb 100644 --- a/sound/hda/codecs/realtek/alc269.c +++ b/sound/hda/codecs/realtek/alc269.c @@ -4542,7 +4542,6 @@ enum { ALC256_FIXUP_HONOR_DRA_XX_HEADSET_MODE, ALC245_FIXUP_HP_ENVY_X360_15_FH0XXX, ALC287_FIXUP_ACER_MICMUTE_LED, - ALC236_FIXUP_DELL_HP_POP_NOISE, ALC274_FIXUP_HP_89E9_GPIO, ALC274_FIXUP_HP_VERBS, ALC287_FIXUP_AW88399_I2C_2, @@ -7408,12 +7407,6 @@ static const struct hda_fixup alc269_fixups[] = { .chained = true, .chain_id = ALC2XX_FIXUP_HEADSET_MIC, }, - [ALC236_FIXUP_DELL_HP_POP_NOISE] = { - .type = HDA_FIXUP_FUNC, - .v.func = alc285_fixup_invalidate_dacs, - .chained = true, - .chain_id = ALC255_FIXUP_DELL1_MIC_NO_PRESENCE - }, [ALC274_FIXUP_HP_89E9_GPIO] = { .type = HDA_FIXUP_FUNC, .v.func = alc274_fixup_hp_89e9_amp, @@ -7553,7 +7546,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x1025, 0x170f, "Acer Predator PHN16-71", ALC2XX_FIXUP_HEADSET_MIC), 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", ALC2XX_FIXUP_HEADSET_MIC), + SND_PCI_QUIRK(0x1025, 0x1731, "Acer Predator PHN16-72", ALC245_FIXUP_ACER_MICMUTE_LED), SND_PCI_QUIRK(0x1025, 0x173a, "Acer Swift SFG14-73", ALC245_FIXUP_ACER_MICMUTE_LED), SND_PCI_QUIRK(0x1025, 0x173b, "Acer Swift SFG16-72", ALC245_FIXUP_ACER_MICMUTE_LED), SND_PCI_QUIRK(0x1025, 0x1758, "Acer Nitro ANV15-41", ALC245_FIXUP_ACER_MICMUTE_LED), @@ -7652,12 +7645,12 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x1028, 0x0cc3, "Dell Oasis 14 Low Weight MTL-U", ALC289_FIXUP_DELL_CS35L41_SPI_2), SND_PCI_QUIRK(0x1028, 0x0cc4, "Dell Oasis 16 MTL-H/U", ALC289_FIXUP_DELL_CS35L41_SPI_2), SND_PCI_QUIRK(0x1028, 0x0cc5, "Dell Oasis 14", ALC289_FIXUP_RTK_AMP_DUAL_SPK), - SND_PCI_QUIRK(0x1028, 0x0d56, "Dell Pro Tower QCT1255", ALC236_FIXUP_DELL_HP_POP_NOISE), - SND_PCI_QUIRK(0x1028, 0x0d58, "Dell Pro Micro QCM1255", ALC236_FIXUP_DELL_HP_POP_NOISE), - SND_PCI_QUIRK(0x1028, 0x0d5a, "Dell Pro Slim QCS1255", ALC236_FIXUP_DELL_HP_POP_NOISE), - SND_PCI_QUIRK(0x1028, 0x0e6b, "Dell Pro Tower QCT1255", ALC236_FIXUP_DELL_HP_POP_NOISE), - SND_PCI_QUIRK(0x1028, 0x0e6c, "Dell Pro Slim QCS1255", ALC236_FIXUP_DELL_HP_POP_NOISE), - SND_PCI_QUIRK(0x1028, 0x0e6d, "Dell Pro Micro QCM1255", ALC236_FIXUP_DELL_HP_POP_NOISE), + SND_PCI_QUIRK(0x1028, 0x0d56, "Dell Pro Tower QCT1255", ALC255_FIXUP_DELL2_MIC_NO_PRESENCE), + SND_PCI_QUIRK(0x1028, 0x0d58, "Dell Pro Micro QCM1255", ALC255_FIXUP_DELL2_MIC_NO_PRESENCE), + SND_PCI_QUIRK(0x1028, 0x0d5a, "Dell Pro Slim QCS1255", ALC255_FIXUP_DELL2_MIC_NO_PRESENCE), + SND_PCI_QUIRK(0x1028, 0x0e6b, "Dell Pro Tower QCT1255", ALC255_FIXUP_DELL2_MIC_NO_PRESENCE), + SND_PCI_QUIRK(0x1028, 0x0e6c, "Dell Pro Slim QCS1255", ALC255_FIXUP_DELL2_MIC_NO_PRESENCE), + SND_PCI_QUIRK(0x1028, 0x0e6d, "Dell Pro Micro QCM1255", ALC255_FIXUP_DELL2_MIC_NO_PRESENCE), SND_PCI_QUIRK(0x1028, 0x164a, "Dell", ALC293_FIXUP_DELL1_MIC_NO_PRESENCE), SND_PCI_QUIRK(0x1028, 0x164b, "Dell", ALC293_FIXUP_DELL1_MIC_NO_PRESENCE), SND_PCI_QUIRK(0x103c, 0x1586, "HP", ALC269_FIXUP_HP_MUTE_LED_MIC2), diff --git a/sound/hda/codecs/realtek/alc882.c b/sound/hda/codecs/realtek/alc882.c index 800c3d6f5134..cf8d3c48eb8a 100644 --- a/sound/hda/codecs/realtek/alc882.c +++ b/sound/hda/codecs/realtek/alc882.c @@ -50,6 +50,7 @@ enum { ALC889_FIXUP_MP41_VREF, ALC882_FIXUP_INV_DMIC, ALC882_FIXUP_NO_PRIMARY_HP, + ALC898_FIXUP_DELL_XPS8940_MIC, ALC887_FIXUP_ASUS_BASS, ALC887_FIXUP_BASS_CHMAP, ALC1220_FIXUP_GB_DUAL_CODECS, @@ -507,6 +508,13 @@ static const struct hda_fixup alc882_fixups[] = { .type = HDA_FIXUP_FUNC, .v.func = alc882_fixup_no_primary_hp, }, + [ALC898_FIXUP_DELL_XPS8940_MIC] = { + .type = HDA_FIXUP_PINS, + .v.pins = (const struct hda_pintbl[]) { + { 0x19, 0x02a19130 }, /* headset mic, no separate jack detect */ + {} + }, + }, [ALC887_FIXUP_ASUS_BASS] = { .type = HDA_FIXUP_PINS, .v.pins = (const struct hda_pintbl[]) { @@ -610,6 +618,8 @@ static const struct hda_quirk alc882_fixup_tbl[] = { SND_PCI_QUIRK(0x1025, 0x0259, "Acer Aspire 5935", ALC889_FIXUP_DAC_ROUTE), SND_PCI_QUIRK(0x1025, 0x026b, "Acer Aspire 8940G", ALC882_FIXUP_ACER_ASPIRE_8930G), SND_PCI_QUIRK(0x1025, 0x0296, "Acer Aspire 7736z", ALC882_FIXUP_ACER_ASPIRE_7736), + SND_PCI_QUIRK(0x1028, 0x09c5, "Dell XPS 8940", + ALC898_FIXUP_DELL_XPS8940_MIC), SND_PCI_QUIRK(0x1043, 0x13c2, "Asus A7M", ALC882_FIXUP_EAPD), SND_PCI_QUIRK(0x1043, 0x1873, "ASUS W90V", ALC882_FIXUP_ASUS_W90V), SND_PCI_QUIRK(0x1043, 0x1971, "Asus W2JC", ALC882_FIXUP_ASUS_W2JC), diff --git a/sound/hda/codecs/side-codecs/cs35l41_hda_property.c b/sound/hda/codecs/side-codecs/cs35l41_hda_property.c index c0f9611b2905..a2e6b3024820 100644 --- a/sound/hda/codecs/side-codecs/cs35l41_hda_property.c +++ b/sound/hda/codecs/side-codecs/cs35l41_hda_property.c @@ -85,9 +85,17 @@ static const struct cs35l41_config cs35l41_config_table[] = { { "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 }, - { "103C8E13", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4500, 24 }, - { "103C8E60", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4500, 24 }, - { "103C8F07", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 3900, 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 }, + { "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 }, + { "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 }, { "10431463", 2, INTERNAL, { CS35L41_LEFT, CS35L41_RIGHT, 0, 0 }, 0, 1, -1, 1000, 4500, 24 }, @@ -547,9 +555,17 @@ static const struct cs35l41_prop_model cs35l41_prop_model_table[] = { { "CSC3551", "103C8C6A", hp_i2c_int_2amp_dual_spkid }, { "CSC3551", "103C8CDD", generic_dsd_config }, { "CSC3551", "103C8CDE", generic_dsd_config }, + { "CSC3551", "103C8E11", generic_dsd_config }, + { "CSC3551", "103C8E12", generic_dsd_config }, { "CSC3551", "103C8E13", generic_dsd_config }, + { "CSC3551", "103C8E3A", generic_dsd_config }, + { "CSC3551", "103C8E3B", generic_dsd_config }, { "CSC3551", "103C8E60", generic_dsd_config }, + { "CSC3551", "103C8E61", generic_dsd_config }, + { "CSC3551", "103C8E62", generic_dsd_config }, + { "CSC3551", "103C8E75", generic_dsd_config }, { "CSC3551", "103C8F07", generic_dsd_config }, + { "CSC3551", "103C8F57", generic_dsd_config }, { "CSC3551", "104312AF", generic_dsd_config }, { "CSC3551", "10431433", generic_dsd_config }, { "CSC3551", "10431463", generic_dsd_config }, diff --git a/sound/hda/common/sysfs.c b/sound/hda/common/sysfs.c index bf65223fde10..b354cbbc3dc9 100644 --- a/sound/hda/common/sysfs.c +++ b/sound/hda/common/sysfs.c @@ -512,11 +512,12 @@ static inline int strmatch(const char *a, const char *b) static void parse_codec_mode(char *buf, struct hda_bus *bus, struct hda_codec **codecp) { - int vendorid, subid, caddr; + long long vendorid, subid; + int caddr; struct hda_codec *codec; *codecp = NULL; - if (sscanf(buf, "%i %i %i", &vendorid, &subid, &caddr) == 3) { + if (sscanf(buf, "%lli %lli %i", &vendorid, &subid, &caddr) == 3) { list_for_each_codec(codec, bus) { if ((vendorid <= 0 || codec->core.vendor_id == vendorid) && (subid <= 0 || codec->core.subsystem_id == subid) && diff --git a/sound/pci/Kconfig b/sound/pci/Kconfig index 6366f72b3667..9c192d51ff44 100644 --- a/sound/pci/Kconfig +++ b/sound/pci/Kconfig @@ -141,6 +141,7 @@ config SND_AU8830 config SND_AW2 tristate "Emagic Audiowerk 2" + select SND_PCM help Say Y here to include support for Emagic Audiowerk 2 soundcards. diff --git a/sound/soc/amd/acp-config.c b/sound/soc/amd/acp-config.c index 3d4c8526cfe2..efd664e1c34c 100644 --- a/sound/soc/amd/acp-config.c +++ b/sound/soc/amd/acp-config.c @@ -66,6 +66,13 @@ static const struct dmi_system_id acp70_acpi_flag_override_table[] = { }, }, { + /* Lenovo Legion 5 15AGP11 (ACP 7.0) */ + .matches = { + DMI_MATCH(DMI_BOARD_VENDOR, "LENOVO"), + DMI_MATCH(DMI_PRODUCT_NAME, "83Q6"), + }, + }, + { .matches = { DMI_MATCH(DMI_BOARD_VENDOR, "ASUSTeK COMPUTER INC"), DMI_MATCH(DMI_PRODUCT_NAME, "FA401EA"), @@ -140,6 +147,13 @@ static const struct dmi_system_id acp70_acpi_flag_override_table[] = { DMI_MATCH(DMI_PRODUCT_NAME, "Dell 14S DS14265"), }, }, + { + /* LG gram 16 16Z95U (ACP 7.2) */ + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "LG Electronics"), + DMI_MATCH(DMI_PRODUCT_NAME, "16Z95U"), + }, + }, {} }; @@ -244,6 +258,20 @@ static const struct config_entry config_table[] = { { .matches = { DMI_EXACT_MATCH(DMI_BOARD_VENDOR, "HUAWEI"), + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "NBM-WXX9"), + DMI_EXACT_MATCH(DMI_PRODUCT_VERSION, "M1010"), + }, + }, + {} + }, + }, + { + .flags = FLAG_AMD_LEGACY, + .device = ACP_PCI_DEV_ID, + .dmi_table = (const struct dmi_system_id []) { + { + .matches = { + DMI_EXACT_MATCH(DMI_BOARD_VENDOR, "HUAWEI"), DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "HVY-WXX9"), DMI_EXACT_MATCH(DMI_PRODUCT_VERSION, "M1010"), }, diff --git a/sound/soc/amd/acp/acp3x-es83xx/acp3x-es83xx.c b/sound/soc/amd/acp/acp3x-es83xx/acp3x-es83xx.c index 38be8fd56205..d0ba8418252b 100644 --- a/sound/soc/amd/acp/acp3x-es83xx/acp3x-es83xx.c +++ b/sound/soc/amd/acp/acp3x-es83xx/acp3x-es83xx.c @@ -18,6 +18,7 @@ #include <linux/input.h> #include <linux/io.h> #include <linux/acpi.h> +#include <linux/delay.h> #include <linux/dmi.h> #include <linux/string_choices.h> #include "../acp-mach.h" @@ -60,6 +61,8 @@ static const struct snd_pcm_hw_constraint_list constraints_channels = { #define ES83xx_12288_KHZ_MCLK_FREQ (48000 * 256) #define ES83xx_48_MHZ_MCLK_FREQ (48000 * 1000) +#define ES83XX_AMP_ON_DELAY_MS 50 + static int acp3x_es83xx_headphone_power_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event); static int acp3x_es83xx_speaker_power_event(struct snd_soc_dapm_widget *w, @@ -114,7 +117,7 @@ static struct snd_soc_jack_pin es83xx_jack_pins[] = { }; static const struct snd_soc_dapm_widget acp3x_es83xx_widgets[] = { - SND_SOC_DAPM_SPK("Speaker", NULL), + SND_SOC_DAPM_SPK("Speaker", acp3x_es83xx_speaker_power_event), SND_SOC_DAPM_HP("Headphone", NULL), SND_SOC_DAPM_MIC("Headset Mic", NULL), SND_SOC_DAPM_MIC("Internal Mic", NULL), @@ -122,9 +125,6 @@ static const struct snd_soc_dapm_widget acp3x_es83xx_widgets[] = { SND_SOC_DAPM_SUPPLY("Headphone Power", SND_SOC_NOPM, 0, 0, acp3x_es83xx_headphone_power_event, SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMU), - SND_SOC_DAPM_SUPPLY("Speaker Power", SND_SOC_NOPM, 0, 0, - acp3x_es83xx_speaker_power_event, - SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMU), }; static const struct snd_soc_dapm_route acp3x_es83xx_audio_map[] = { @@ -138,7 +138,6 @@ static const struct snd_soc_dapm_route acp3x_es83xx_audio_map[] = { */ {"Speaker", NULL, "HPOL"}, {"Speaker", NULL, "HPOR"}, - {"Speaker", NULL, "Speaker Power"}, }; @@ -186,10 +185,13 @@ static int acp3x_es83xx_speaker_power_event(struct snd_soc_dapm_widget *w, struct acp3x_es83xx_private *priv = get_mach_priv(card); dev_dbg(priv->codec_dev, "speaker power event: %d\n", event); - if (SND_SOC_DAPM_EVENT_ON(event)) + if (SND_SOC_DAPM_EVENT_ON(event)) { + /* Let the codec output settle before enabling the amplifier */ + msleep(ES83XX_AMP_ON_DELAY_MS); priv->speaker_on = true; - else + } else { priv->speaker_on = false; + } gpiod_set_value_cansleep(priv->gpio_speakers, priv->speaker_on); gpiod_set_value_cansleep(priv->gpio_headphone, priv->headphone_on); @@ -367,6 +369,14 @@ static const struct dmi_system_id acp3x_es83xx_dmi_table[] = { { .matches = { DMI_EXACT_MATCH(DMI_BOARD_VENDOR, "HUAWEI"), + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "NBM-WXX9"), + DMI_EXACT_MATCH(DMI_PRODUCT_VERSION, "M1010"), + }, + .driver_data = (void *)(ES83XX_ENABLE_DMIC|ES83XX_48_MHZ_MCLK), + }, + { + .matches = { + DMI_EXACT_MATCH(DMI_BOARD_VENDOR, "HUAWEI"), DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "HVY-WXX9"), DMI_EXACT_MATCH(DMI_PRODUCT_VERSION, "M1010"), }, diff --git a/sound/soc/amd/acp/amd-acp70-acpi-match.c b/sound/soc/amd/acp/amd-acp70-acpi-match.c index c2f0479301eb..b492cbe7b73e 100644 --- a/sound/soc/amd/acp/amd-acp70-acpi-match.c +++ b/sound/soc/amd/acp/amd-acp70-acpi-match.c @@ -583,6 +583,78 @@ static const struct snd_soc_acpi_link_adr acp70_rt722_l0_rt1320_l1[] = { {} }; +static const struct snd_soc_acpi_endpoint rt713_jack_dmic_endpoints[] = { + /* Jack Endpoint (AIF1) */ + { + .num = 0, + .aggregated = 0, + .group_position = 0, + .group_id = 0, + }, + /* DMIC Endpoint (AIF3, SmartMic function) */ + { + .num = 1, + .aggregated = 0, + .group_position = 0, + .group_id = 0, + }, +}; + +static const struct snd_soc_acpi_adr_device rt713_vb_0_single_adr[] = { + { + .adr = 0x000030025D071301ull, + .num_endpoints = ARRAY_SIZE(rt713_jack_dmic_endpoints), + .endpoints = rt713_jack_dmic_endpoints, + .name_prefix = "rt713" + } +}; + +static const struct snd_soc_acpi_adr_device rt713_0_single_adr[] = { + { + .adr = 0x000030025D071301ull, + .num_endpoints = 1, + .endpoints = &single_endpoint, + .name_prefix = "rt713" + } +}; + +static const struct snd_soc_acpi_adr_device rt1320_1_u1_single_adr[] = { + { + .adr = 0x000131025D132001ull, + .num_endpoints = 1, + .endpoints = &single_endpoint, + .name_prefix = "rt1320-1" + } +}; + +static const struct snd_soc_acpi_link_adr acp70_rt713_vb_l0_rt1320_l1u1[] = { + { + .mask = BIT(0), + .num_adr = ARRAY_SIZE(rt713_vb_0_single_adr), + .adr_d = rt713_vb_0_single_adr, + }, + { + .mask = BIT(1), + .num_adr = ARRAY_SIZE(rt1320_1_u1_single_adr), + .adr_d = rt1320_1_u1_single_adr, + }, + {} +}; + +static const struct snd_soc_acpi_link_adr acp70_rt713_l0_rt1320_l1u1[] = { + { + .mask = BIT(0), + .num_adr = ARRAY_SIZE(rt713_0_single_adr), + .adr_d = rt713_0_single_adr, + }, + { + .mask = BIT(1), + .num_adr = ARRAY_SIZE(rt1320_1_u1_single_adr), + .adr_d = rt1320_1_u1_single_adr, + }, + {} +}; + static const struct snd_soc_acpi_adr_device tas2783_2_adr[] = { { /* left */ @@ -822,6 +894,17 @@ struct snd_soc_acpi_mach snd_soc_acpi_amd_acp70_sdw_machines[] = { }, { .link_mask = BIT(0) | BIT(1), + .links = acp70_rt713_vb_l0_rt1320_l1u1, + .machine_check = snd_soc_acpi_amd_sdca_is_device_rt712_vb, + .drv_name = "amd_sdw", + }, + { + .link_mask = BIT(0) | BIT(1), + .links = acp70_rt713_l0_rt1320_l1u1, + .drv_name = "amd_sdw", + }, + { + .link_mask = BIT(0) | BIT(1), .links = acp70_4_in_1_sdca, .drv_name = "amd_sdw", }, diff --git a/sound/soc/amd/ps/pci-ps.c b/sound/soc/amd/ps/pci-ps.c index f989ad2a13d2..cf009e25307e 100644 --- a/sound/soc/amd/ps/pci-ps.c +++ b/sound/soc/amd/ps/pci-ps.c @@ -26,16 +26,20 @@ static void handle_acp70_sdw_wake_event(struct acp63_dev_data *adata) struct amd_sdw_manager *amd_manager; if (adata->acp70_sdw0_wake_event) { - amd_manager = dev_get_drvdata(&adata->sdw->pdev[0]->dev); - if (amd_manager) - pm_request_resume(amd_manager->dev); + if (adata->sdw) { + amd_manager = dev_get_drvdata(&adata->sdw->pdev[0]->dev); + if (amd_manager) + pm_request_resume(amd_manager->dev); + } adata->acp70_sdw0_wake_event = 0; } if (adata->acp70_sdw1_wake_event) { - amd_manager = dev_get_drvdata(&adata->sdw->pdev[1]->dev); - if (amd_manager) - pm_request_resume(amd_manager->dev); + if (adata->sdw) { + amd_manager = dev_get_drvdata(&adata->sdw->pdev[1]->dev); + if (amd_manager) + pm_request_resume(amd_manager->dev); + } adata->acp70_sdw1_wake_event = 0; } } @@ -209,18 +213,22 @@ static irqreturn_t acp63_irq_handler(int irq, void *dev_id) ext_intr_stat = readl(adata->acp63_base + ACP_EXTERNAL_INTR_STAT); if (ext_intr_stat & ACP_SDW0_STAT) { writel(ACP_SDW0_STAT, adata->acp63_base + ACP_EXTERNAL_INTR_STAT); - amd_manager = dev_get_drvdata(&adata->sdw->pdev[0]->dev); - if (amd_manager) - schedule_work(&amd_manager->amd_sdw_irq_thread); + if (adata->sdw) { + amd_manager = dev_get_drvdata(&adata->sdw->pdev[0]->dev); + if (amd_manager) + schedule_work(&amd_manager->amd_sdw_irq_thread); + } irq_flag = 1; } ext_intr_stat1 = readl(adata->acp63_base + ACP_EXTERNAL_INTR_STAT1); if (ext_intr_stat1 & ACP_SDW1_STAT) { writel(ACP_SDW1_STAT, adata->acp63_base + ACP_EXTERNAL_INTR_STAT1); - amd_manager = dev_get_drvdata(&adata->sdw->pdev[1]->dev); - if (amd_manager) - schedule_work(&amd_manager->amd_sdw_irq_thread); + if (adata->sdw) { + amd_manager = dev_get_drvdata(&adata->sdw->pdev[1]->dev); + if (amd_manager) + schedule_work(&amd_manager->amd_sdw_irq_thread); + } irq_flag = 1; } diff --git a/sound/soc/amd/yc/acp6x-mach.c b/sound/soc/amd/yc/acp6x-mach.c index 7ab48e3629be..e14c73e7e988 100644 --- a/sound/soc/amd/yc/acp6x-mach.c +++ b/sound/soc/amd/yc/acp6x-mach.c @@ -413,6 +413,13 @@ static const struct dmi_system_id yc_acp_quirk_table[] = { .driver_data = &acp6x_card, .matches = { DMI_MATCH(DMI_BOARD_VENDOR, "RB"), + DMI_MATCH(DMI_PRODUCT_NAME, "Nitro AN16-41"), + } + }, + { + .driver_data = &acp6x_card, + .matches = { + DMI_MATCH(DMI_BOARD_VENDOR, "RB"), DMI_MATCH(DMI_PRODUCT_NAME, "Nitro AN17-41"), } }, @@ -955,6 +962,13 @@ static const struct dmi_system_id yc_acp_quirk_table[] = { DMI_MATCH(DMI_PRODUCT_NAME, "HP 255R 15.6 inch G10 Notebook PC"), } }, + { + .driver_data = &acp6x_card, + .matches = { + DMI_MATCH(DMI_BOARD_VENDOR, "ASUSTeK COMPUTER INC."), + DMI_MATCH(DMI_PRODUCT_NAME, "TUF Gaming A16 FA607NUQ"), + } + }, {} }; @@ -986,7 +1000,7 @@ static int acp6x_probe(struct platform_device *pdev) if (!ACPI_FAILURE(ret)) { wov_en = dmic_status; if (!wov_en) - return -ENODEV; + goto check_dmi_entry; } else { /* Incase of ACPI method read failure then jump to check_dmi_entry */ goto check_dmi_entry; diff --git a/sound/soc/apple/mca.c b/sound/soc/apple/mca.c index 393274dea9b5..284b641bbf86 100644 --- a/sound/soc/apple/mca.c +++ b/sound/soc/apple/mca.c @@ -53,6 +53,8 @@ #define SYNCGEN_STATUS_EN BIT(0) #define REG_SYNCGEN_MCLK_SEL 0x104 #define SYNCGEN_MCLK_SEL GENMASK(3, 0) +#define SYNCGEN_MCLK_FE_CLK(n) ((n) + 1) +#define SYNCGEN_MCLK_BE_CLK(n) ((n) + 7) #define REG_SYNCGEN_HI_PERIOD 0x108 #define REG_SYNCGEN_LO_PERIOD 0x10c @@ -313,7 +315,8 @@ static int mca_fe_enable_clocks(struct mca_cluster *cl) return -EINVAL; } - writel_relaxed(cl->no + 1, cl->base + REG_SYNCGEN_MCLK_SEL); + writel_relaxed(SYNCGEN_MCLK_FE_CLK(cl->no), + cl->base + REG_SYNCGEN_MCLK_SEL); mca_modify(cl, REG_SYNCGEN_STATUS, SYNCGEN_STATUS_EN, SYNCGEN_STATUS_EN); mca_modify(cl, REG_STATUS, STATUS_MCLK_EN, STATUS_MCLK_EN); @@ -390,7 +393,7 @@ static int mca_fe_prepare(struct snd_pcm_substream *substream, /* Turn on the cluster power domain if not already in use */ if (!cl->syncgen_in_use) { - int port = ffs(mca_fe_get_portmask(substream)); + int port = ffs(mca_fe_get_portmask(substream)) - 1; cl->pd_link = device_link_add(mca->dev, cl->pd_dev, DL_FLAG_STATELESS | DL_FLAG_PM_RUNTIME | @@ -401,7 +404,8 @@ static int mca_fe_prepare(struct snd_pcm_substream *substream, return -EINVAL; } - mca_modify(cl, REG_SYNCGEN_MCLK_SEL, SYNCGEN_MCLK_SEL, BIT(port)); + mca_modify(cl, REG_SYNCGEN_MCLK_SEL, SYNCGEN_MCLK_SEL, + SYNCGEN_MCLK_BE_CLK(port)); mca_modify(cl, REG_SYNCGEN_STATUS, SYNCGEN_STATUS_EN, SYNCGEN_STATUS_EN); } diff --git a/sound/soc/codecs/cs43130.c b/sound/soc/codecs/cs43130.c index 9ab4a497a3cc..5ecd5571dcbc 100644 --- a/sound/soc/codecs/cs43130.c +++ b/sound/soc/codecs/cs43130.c @@ -2413,7 +2413,6 @@ static const struct snd_soc_component_driver soc_component_dev_cs43130_digital = .set_sysclk = cs43130_component_set_sysclk, .set_pll = cs43130_set_pll, .idle_bias_on = 1, - .use_pmdown_time = 1, .endianness = 1, /* Don't take into account the ending analog widgets and routes */ .dapm_widgets = hp_widgets, @@ -2429,7 +2428,6 @@ static const struct snd_soc_component_driver soc_component_dev_cs43130_analog = .set_sysclk = cs43130_component_set_sysclk, .set_pll = cs43130_set_pll, .idle_bias_on = 1, - .use_pmdown_time = 1, .endianness = 1, .dapm_widgets = hp_widgets, .num_dapm_widgets = ARRAY_SIZE(hp_widgets), diff --git a/sound/soc/codecs/es9356.c b/sound/soc/codecs/es9356.c index e0deb81afe34..f2f658d8bc53 100644 --- a/sound/soc/codecs/es9356.c +++ b/sound/soc/codecs/es9356.c @@ -73,8 +73,8 @@ static int es9356_sdw_component_probe(struct snd_soc_component *component) } static const DECLARE_TLV_DB_SCALE(out_vol_tlv, -9600, 12, 0); -static const DECLARE_TLV_DB_SCALE(amic_gain_tlv, 0, 3, 0); -static const DECLARE_TLV_DB_SCALE(dmic_gain_tlv, 0, 6, 0); +static const DECLARE_TLV_DB_SCALE(amic_gain_tlv, 0, 300, 0); +static const DECLARE_TLV_DB_SCALE(dmic_gain_tlv, 0, 600, 0); static const struct snd_kcontrol_new es9356_sdca_controls[] = { SDCA_SINGLE_Q78_TLV("FU41 Left Playback Volume", diff --git a/sound/soc/codecs/max98090.c b/sound/soc/codecs/max98090.c index a985853e48eb..3ed513f6d81c 100644 --- a/sound/soc/codecs/max98090.c +++ b/sound/soc/codecs/max98090.c @@ -743,14 +743,6 @@ static int max98090_micinput_event(struct snd_soc_dapm_widget *w, else val = (val & M98090_MIC_PA2EN_MASK) >> M98090_MIC_PA2EN_SHIFT; - if (val >= 1) { - if (w->reg == M98090_REG_MIC1_INPUT_LEVEL) { - max98090->pa1en = val - 1; /* Update for volatile */ - } else { - max98090->pa2en = val - 1; /* Update for volatile */ - } - } - switch (event) { case SND_SOC_DAPM_POST_PMU: /* If turning on, set to most recently selected volume */ @@ -759,6 +751,14 @@ static int max98090_micinput_event(struct snd_soc_dapm_widget *w, else val = max98090->pa2en + 1; break; + case SND_SOC_DAPM_PRE_PMD: + if (val >= 1) { + if (w->reg == M98090_REG_MIC1_INPUT_LEVEL) + max98090->pa1en = val - 1; + else + max98090->pa2en = val - 1; + } + return 0; case SND_SOC_DAPM_POST_PMD: /* If turning off, turn off */ val = 0; @@ -1121,11 +1121,13 @@ static const struct snd_soc_dapm_widget max98090_dapm_widgets[] = { SND_SOC_DAPM_PGA_E("MIC1 Input", M98090_REG_MIC1_INPUT_LEVEL, M98090_MIC_PA1EN_SHIFT, 0, NULL, 0, max98090_micinput_event, - SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), + SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD | + SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_PGA_E("MIC2 Input", M98090_REG_MIC2_INPUT_LEVEL, M98090_MIC_PA2EN_SHIFT, 0, NULL, 0, max98090_micinput_event, - SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), + SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD | + SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MIXER("LINEA Mixer", SND_SOC_NOPM, 0, 0, &max98090_linea_mixer_controls[0], diff --git a/sound/soc/intel/boards/sof_sdw.c b/sound/soc/intel/boards/sof_sdw.c index 64bcb3f04c95..1e5de71c0f21 100644 --- a/sound/soc/intel/boards/sof_sdw.c +++ b/sound/soc/intel/boards/sof_sdw.c @@ -140,6 +140,16 @@ static const struct dmi_system_id sof_sdw_quirk_table[] = { RT711_JD2), }, { + /* Dell Latitude 9420 */ + .callback = sof_sdw_quirk_cb, + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc"), + DMI_EXACT_MATCH(DMI_PRODUCT_SKU, "0A5B") + }, + .driver_data = (void *)(SOF_SDW_TGL_HDMI | + RT711_JD2), + }, + { /* Dell XPS 9710 */ .callback = sof_sdw_quirk_cb, .matches = { diff --git a/sound/soc/qcom/qdsp6/q6asm-dai.c b/sound/soc/qcom/qdsp6/q6asm-dai.c index dc5230f13a97..77e60b13400c 100644 --- a/sound/soc/qcom/qdsp6/q6asm-dai.c +++ b/sound/soc/qcom/qdsp6/q6asm-dai.c @@ -243,6 +243,9 @@ static int q6asm_dai_prepare(struct snd_soc_component *component, prtd->state = Q6ASM_STREAM_STOPPED; } + /* ALSA resets appl_ptr for every prepare, including xrun recovery. */ + prtd->queue_ptr = 0; + ret = q6asm_map_memory_regions(substream->stream, prtd->audio_client, prtd->phys, (prtd->pcm_size / prtd->periods), diff --git a/sound/soc/qcom/qdsp6/q6asm.c b/sound/soc/qcom/qdsp6/q6asm.c index 3f9f2448eb32..d042132caf03 100644 --- a/sound/soc/qcom/qdsp6/q6asm.c +++ b/sound/soc/qcom/qdsp6/q6asm.c @@ -514,6 +514,8 @@ int q6asm_map_memory_regions(unsigned int dir, struct audio_client *ac, ac->port[dir].buf = buf; + ac->port[dir].dsp_buf = 0; + atomic_set(&ac->port[dir].hw_ptr, 0); buf[0].phys = phys; buf[0].size = period_sz; diff --git a/sound/soc/qcom/x1e80100.c b/sound/soc/qcom/x1e80100.c index 7eeb32ada7fa..c927672eaede 100644 --- a/sound/soc/qcom/x1e80100.c +++ b/sound/soc/qcom/x1e80100.c @@ -68,6 +68,23 @@ static int x1e80100_snd_init(struct snd_soc_pcm_runtime *rtd) return qcom_snd_wcd_jack_setup(rtd, &data->jack, &data->jack_setup); } +static void x1e80100_snd_exit(struct snd_soc_pcm_runtime *rtd) +{ + struct x1e80100_snd_data *data = snd_soc_card_get_drvdata(rtd->card); + struct snd_soc_dai *cpu_dai = snd_soc_rtd_to_cpu(rtd, 0); + + switch (cpu_dai->id) { + case DISPLAY_PORT_RX_0: + case DISPLAY_PORT_RX_1 ... DISPLAY_PORT_RX_7: + return; + default: + break; + } + + qcom_snd_headset_jack_cleanup(rtd); + data->jack_setup = false; +} + static int x1e80100_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd, struct snd_pcm_hw_params *params) { @@ -172,6 +189,7 @@ static void x1e80100_add_be_ops(struct snd_soc_card *card) for_each_card_prelinks(card, i, link) { if (link->no_pcm == 1) { link->init = x1e80100_snd_init; + link->exit = x1e80100_snd_exit; link->be_hw_params_fixup = x1e80100_be_hw_params_fixup; link->ops = &x1e80100_be_ops; } diff --git a/sound/soc/soc-core.c b/sound/soc/soc-core.c index 68b54e509b65..70398e866ff2 100644 --- a/sound/soc/soc-core.c +++ b/sound/soc/soc-core.c @@ -387,6 +387,12 @@ static struct snd_soc_pcm_runtime *soc_new_pcm_runtime( device_unregister(dev); return NULL; } + /* + * devm_kzalloc_flex() presets the __counted_by() counter to the + * allocated size when the compiler has __builtin_counted_by_ref(), + * but snd_soc_rtd_add_component() expects it to start from zero. + */ + rtd->num_components = 0; rtd->dev = dev; INIT_LIST_HEAD(&rtd->list); @@ -3197,6 +3203,18 @@ void snd_soc_of_put_dai_link_codecs(struct snd_soc_dai_link *dai_link) } EXPORT_SYMBOL_GPL(snd_soc_of_put_dai_link_codecs); +/* dai_name belongs to the component, which can unbind before the card. */ +static int snd_soc_of_dup_dai_name(struct device *dev, + struct snd_soc_dai_link_component *dlc) +{ + if (!dlc->dai_name) + return 0; + + dlc->dai_name = devm_kstrdup_const(dev, dlc->dai_name, GFP_KERNEL); + + return dlc->dai_name ? 0 : -ENOMEM; +} + /* * snd_soc_of_get_dai_link_codecs - Parse a list of CODECs in the devicetree * @dev: Card device @@ -3226,6 +3244,8 @@ int snd_soc_of_get_dai_link_codecs(struct device *dev, /* Parse the list */ for_each_link_codecs(dai_link, index, component) { ret = snd_soc_of_get_dlc(of_node, NULL, component, index); + if (!ret) + ret = snd_soc_of_dup_dai_name(dev, component); if (ret) goto err; } @@ -3281,6 +3301,8 @@ int snd_soc_of_get_dai_link_cpus(struct device *dev, /* Parse the list */ for_each_link_cpus(dai_link, index, component) { ret = snd_soc_of_get_dlc(of_node, NULL, component, index); + if (!ret) + ret = snd_soc_of_dup_dai_name(dev, component); if (ret) goto err; } diff --git a/sound/soc/sof/amd/acp.c b/sound/soc/sof/amd/acp.c index 6dfed95d5512..8039b2450cf3 100644 --- a/sound/soc/sof/amd/acp.c +++ b/sound/soc/sof/amd/acp.c @@ -478,16 +478,20 @@ static void amd_sof_handle_acp70_sdw_wake_event(struct acp_dev_data *adata) struct amd_sdw_manager *amd_manager; if (adata->acp70_sdw0_wake_event) { - amd_manager = dev_get_drvdata(&adata->sdw->pdev[0]->dev); - if (amd_manager) - pm_request_resume(amd_manager->dev); + if (adata->sdw) { + amd_manager = dev_get_drvdata(&adata->sdw->pdev[0]->dev); + if (amd_manager) + pm_request_resume(amd_manager->dev); + } adata->acp70_sdw0_wake_event = 0; } if (adata->acp70_sdw1_wake_event) { - amd_manager = dev_get_drvdata(&adata->sdw->pdev[1]->dev); - if (amd_manager) - pm_request_resume(amd_manager->dev); + if (adata->sdw) { + amd_manager = dev_get_drvdata(&adata->sdw->pdev[1]->dev); + if (amd_manager) + pm_request_resume(amd_manager->dev); + } adata->acp70_sdw1_wake_event = 0; } } @@ -579,10 +583,12 @@ static irqreturn_t acp_irq_handler(int irq, void *dev_id) val = snd_sof_dsp_read(sdev, ACP_DSP_BAR, desc->ext_intr_stat); if (val & ACP_SDW0_IRQ_MASK) { - amd_manager = dev_get_drvdata(&adata->sdw->pdev[0]->dev); snd_sof_dsp_write(sdev, ACP_DSP_BAR, desc->ext_intr_stat, ACP_SDW0_IRQ_MASK); - if (amd_manager) - schedule_work(&amd_manager->amd_sdw_irq_thread); + if (adata->sdw) { + amd_manager = dev_get_drvdata(&adata->sdw->pdev[0]->dev); + if (amd_manager) + schedule_work(&amd_manager->amd_sdw_irq_thread); + } irq_flag = 1; } @@ -608,11 +614,13 @@ static irqreturn_t acp_irq_handler(int irq, void *dev_id) if (desc->ext_intr_stat1) { val = snd_sof_dsp_read(sdev, ACP_DSP_BAR, desc->ext_intr_stat1); if (val & ACP_SDW1_IRQ_MASK) { - amd_manager = dev_get_drvdata(&adata->sdw->pdev[1]->dev); snd_sof_dsp_write(sdev, ACP_DSP_BAR, desc->ext_intr_stat1, ACP_SDW1_IRQ_MASK); - if (amd_manager) - schedule_work(&amd_manager->amd_sdw_irq_thread); + if (adata->sdw) { + amd_manager = dev_get_drvdata(&adata->sdw->pdev[1]->dev); + if (amd_manager) + schedule_work(&amd_manager->amd_sdw_irq_thread); + } irq_flag = 1; } switch (adata->pci_rev) { @@ -1212,6 +1220,27 @@ static int amd_sof_sdw_exit(struct snd_sof_dev *sdev) } #endif +/* + * The PSP validates the signed DSP firmware, so it must be signed with the + * scheme the platform firmware uses: images for the alternative scheme are + * named with an "_l" suffix before the extension, the default ones have none. + */ +static int amd_sof_acp_get_fw_suffix(struct snd_sof_dev *sdev, const char **suffix) +{ + u32 val; + int ret; + + ret = amd_smn_read(0, MP0_C2PMSG_63_REG, &val); + if (ret) { + dev_err(sdev->dev, "PSP firmware signing type read failed (err %d)\n", ret); + return ret; + } + + *suffix = (val & MP0_C2PMSG_63_FW_SIGN_ALT) ? "_l" : ""; + + return 0; +} + int amd_sof_acp_probe(struct snd_sof_dev *sdev) { struct pci_dev *pci = to_pci_dev(sdev->dev); @@ -1447,8 +1476,14 @@ skip_soundwire: sdev->debug_box.size = BOX_SIZE_1024; if (adata->acp_sof_signed_firmware_image) { + const char *fw_suffix; + + ret = amd_sof_acp_get_fw_suffix(sdev, &fw_suffix); + if (ret) + goto free_ipc_irq; + adata->fw_code_bin = devm_kasprintf(sdev->dev, GFP_KERNEL, - "sof-%s-code.bin", chip->name); + "sof-%s-code%s.bin", chip->name, fw_suffix); if (!adata->fw_code_bin) { ret = -ENOMEM; goto free_ipc_irq; diff --git a/sound/soc/sof/amd/acp.h b/sound/soc/sof/amd/acp.h index b17a36b31ee0..81eeeabc5cf5 100644 --- a/sound/soc/sof/amd/acp.h +++ b/sound/soc/sof/amd/acp.h @@ -97,6 +97,8 @@ #define ACP_EXT_INTR_ERROR_STAT 0x20000000 #define MP0_C2PMSG_114_REG 0x3810AC8 #define MP0_C2PMSG_73_REG 0x3810A24 +#define MP0_C2PMSG_63_REG 0x38109FC +#define MP0_C2PMSG_63_FW_SIGN_ALT BIT(6) #define MBOX_ACP_SHA_DMA_COMMAND 0x70000 #define MBOX_ACP_IRAM_DRAM_FENCE_COMMAND 0x80000 #define MBOX_DELAY_US 1000 diff --git a/sound/soc/sof/ipc4-topology.c b/sound/soc/sof/ipc4-topology.c index c2b729186743..9a3f8896d7cd 100644 --- a/sound/soc/sof/ipc4-topology.c +++ b/sound/soc/sof/ipc4-topology.c @@ -1313,7 +1313,7 @@ static int sof_ipc4_widget_setup_comp_process(struct snd_sof_widget *swidget) ret = sof_ipc4_widget_setup_msg(swidget, &process->msg); if (ret) - goto err; + goto free_available_fmt; /* parse process init module payload config type from module info */ fw_module = swidget->module_info; diff --git a/sound/usb/caiaq/device.c b/sound/usb/caiaq/device.c index 634dc36f2ead..d28465e916df 100644 --- a/sound/usb/caiaq/device.c +++ b/sound/usb/caiaq/device.c @@ -600,14 +600,19 @@ static void snd_disconnect(struct usb_interface *intf) snd_card_disconnect(card); + /* + * Kill the EP1 URB before disconnecting the input device: its + * completion reports into cdev->input_dev, which input_disconnect() + * frees without clearing the pointer. + */ + usb_kill_urb(cdev->ep1_in_urb); + usb_kill_urb(cdev->midi_out_urb); + #ifdef CONFIG_SND_USB_CAIAQ_INPUT snd_usb_caiaq_input_disconnect(cdev); #endif snd_usb_caiaq_audio_disconnect(cdev); - usb_kill_urb(cdev->ep1_in_urb); - usb_kill_urb(cdev->midi_out_urb); - snd_card_free_when_closed(card); } diff --git a/sound/usb/pcm.c b/sound/usb/pcm.c index c2f7b08607ac..57a26492dd61 100644 --- a/sound/usb/pcm.c +++ b/sound/usb/pcm.c @@ -1337,6 +1337,12 @@ static void retire_capture_urb(struct snd_usb_substream *subs, "frame %d active: %d\n", i, urb->iso_frame_desc[i].status); bytes = urb->iso_frame_desc[i].actual_length; + if (unlikely(bytes > urb->iso_frame_desc[i].length)) { + dev_warn_ratelimited(&subs->dev->dev, + "packet %d: actual_length %u exceeds length %u, dropping\n", + i, bytes, urb->iso_frame_desc[i].length); + continue; + } if (subs->stream_offset_adj > 0) { unsigned int adj = min(subs->stream_offset_adj, bytes); cp += adj; diff --git a/sound/usb/quirks.c b/sound/usb/quirks.c index 7c581e283903..e1df5c7bf062 100644 --- a/sound/usb/quirks.c +++ b/sound/usb/quirks.c @@ -2651,6 +2651,8 @@ static const struct usb_audio_quirk_flags_table quirk_flags_table[] = { QUIRK_FLAG_CTL_MSG_DELAY_1M), DEVICE_FLG(0x0bda, 0x498a, /* Realtek Semiconductor Corp. */ QUIRK_FLAG_MIXER_PLAYBACK_MIN_MUTE | QUIRK_FLAG_MIXER_CAPTURE_MIN_MUTE), + DEVICE_FLG(0x0bda, 0x8808, /* RYDZ Technology Piva AC20 */ + QUIRK_FLAG_FORCE_IFACE_RESET | QUIRK_FLAG_IFACE_DELAY), DEVICE_FLG(0x0c45, 0x6340, /* Sonix HD USB Camera */ QUIRK_FLAG_GET_SAMPLE_RATE), DEVICE_FLG(0x0c45, 0x636b, /* Microdia JP001 USB Camera */ @@ -2833,6 +2835,8 @@ static const struct usb_audio_quirk_flags_table quirk_flags_table[] = { QUIRK_FLAG_DSD_RAW), DEVICE_FLG(0x3302, 0x17c2, /* TTGK Technology USB-C Audio */ QUIRK_FLAG_FORCE_IFACE_RESET | QUIRK_FLAG_IFACE_DELAY), + DEVICE_FLG(0x3302, 0x39c3, /* NiceHCK Octave */ + QUIRK_FLAG_DSD_RAW), DEVICE_FLG(0x339b, 0x3a07, /* Synaptics HONOR USB-C HEADSET */ QUIRK_FLAG_MIXER_PLAYBACK_MIN_MUTE), DEVICE_FLG(0x3443, 0x930d, /* NexiGo N930W 60fps Webcam */ diff --git a/tools/bootconfig/main.c b/tools/bootconfig/main.c index 6f476e3c06b8..d3f840c5adce 100644 --- a/tools/bootconfig/main.c +++ b/tools/bootconfig/main.c @@ -68,6 +68,23 @@ static int xbc_show_value(struct xbc_node *node, bool semicolon) return i; } +/* Match the conditions under which the compact formatter opens braces. */ +static bool xbc_node_needs_braces(struct xbc_node *node) +{ + struct xbc_node *child = xbc_node_get_child(node); + + if (child && xbc_node_is_value(child)) + child = xbc_node_get_next(child); + if (!child) + return false; + if (child->next) + return true; + + /* A single subkey with both a value and subkeys is not compacted. */ + child = xbc_node_get_child(child); + return child && xbc_node_is_value(child) && child->next; +} + static void xbc_show_compact_tree(void) { struct xbc_node *node, *cnode = NULL, *vnode; @@ -128,14 +145,12 @@ static void xbc_show_compact_tree(void) node = xbc_node_get_parent(node); if (!node) return; - if (!xbc_node_get_child(node)->next) + if (!depth || !xbc_node_needs_braces(node)) continue; - if (depth) { - depth--; - for (i = 0; i < depth; i++) - printf("\t"); - printf("}\n"); - } + depth--; + for (i = 0; i < depth; i++) + printf("\t"); + printf("}\n"); } node = xbc_node_get_next(node); } diff --git a/tools/bootconfig/samples/exp-good-mixed-kv1.bconf b/tools/bootconfig/samples/exp-good-mixed-kv1.bconf index 8346287d9251..0b8b2f59da31 100644 --- a/tools/bootconfig/samples/exp-good-mixed-kv1.bconf +++ b/tools/bootconfig/samples/exp-good-mixed-kv1.bconf @@ -1,2 +1,7 @@ key = "value"; key.subkey = "another-value"; +a { + b = "v"; + b.c = "w"; + z = "q"; +} diff --git a/tools/bootconfig/samples/good-mixed-kv1.bconf b/tools/bootconfig/samples/good-mixed-kv1.bconf index 1761547dd05c..35442ee62b75 100644 --- a/tools/bootconfig/samples/good-mixed-kv1.bconf +++ b/tools/bootconfig/samples/good-mixed-kv1.bconf @@ -1,3 +1,8 @@ # value -> subkey pattern key = value key.subkey = another-value + +# A valued parent with one subkey must not close its enclosing brace. +a.b = v +a.b.c = w +a.z = q diff --git a/tools/bootconfig/test-bootconfig.sh b/tools/bootconfig/test-bootconfig.sh index 530ce7e28d63..f584f7637e12 100755 --- a/tools/bootconfig/test-bootconfig.sh +++ b/tools/bootconfig/test-bootconfig.sh @@ -100,6 +100,16 @@ xpass $BOOTCONF -a $TEMPCONF $INITRD printf "badnode\n" >> $TEMPCONF xfail $BOOTCONF -a $TEMPCONF $INITRD +echo "Max key depth check" + +printf 'a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p = "value"\n' > $TEMPCONF +xpass $BOOTCONF -a $TEMPCONF $INITRD +$BOOTCONF -l $INITRD > $OUTFILE +xpass cmp $TEMPCONF $OUTFILE + +printf 'a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p.q = "value"\n' > $TEMPCONF +xfail $BOOTCONF -a $TEMPCONF $INITRD + echo "Max filesize check" # Max size is 32767 (including terminal byte) @@ -171,6 +181,24 @@ $BOOTCONF $INITRD > $OUTFILE xfail grep -q 'val[[:space:]]' $OUTFILE xpass grep -q 'val2[[:space:]]' $OUTFILE +echo "Remove unquoted trailing whitespace at end of file" +printf 'foo = val \t' > $TEMPCONF +$BOOTCONF -l $TEMPCONF > $OUTFILE +printf 'foo = "val"\n' > $TEMPCONF +xpass cmp $TEMPCONF $OUTFILE + +echo "Remove trailing whitespace from the last array value at end of file" +printf 'foo = first, last \t' > $TEMPCONF +$BOOTCONF -l $TEMPCONF > $OUTFILE +printf 'foo = "first", "last"\n' > $TEMPCONF +xpass cmp $TEMPCONF $OUTFILE + +echo "Keep quoted trailing whitespace at end of file" +printf 'foo = "val "' > $TEMPCONF +$BOOTCONF -l $TEMPCONF > $OUTFILE +printf 'foo = "val "\n' > $TEMPCONF +xpass cmp $TEMPCONF $OUTFILE + echo "Showing correct line:column of no closing brace" cat > $TEMPCONF << EOF foo { diff --git a/tools/include/vdso/unaligned.h b/tools/include/vdso/unaligned.h index 9076483c9fbb..726fd15efc82 100644 --- a/tools/include/vdso/unaligned.h +++ b/tools/include/vdso/unaligned.h @@ -4,6 +4,20 @@ #include <linux/compiler_types.h> +#ifdef CONFIG_VDSO_UNALIGNED_PACKED + +#define __get_unaligned_t(type, ptr) ({ \ + const struct { type x; } __packed * __get_pptr = (typeof(__get_pptr))(ptr); \ + __get_pptr->x; \ +}) + +#define __put_unaligned_t(type, val, ptr) do { \ + struct { type x; } __packed * __put_pptr = (typeof(__put_pptr))(ptr); \ + __put_pptr->x = (val); \ +} while (0) + +#else /* !CONFIG_VDSO_UNALIGNED_PACKED */ + /** * __get_unaligned_t - read an unaligned value from memory. * @type: the type to load from the pointer. @@ -41,4 +55,6 @@ sizeof(__put_unaligned_val)); \ } while (0) +#endif /* CONFIG_VDSO_UNALIGNED_PACKED */ + #endif /* __VDSO_UNALIGNED_H */ diff --git a/tools/testing/selftests/bpf/prog_tests/xdp_metadata.c b/tools/testing/selftests/bpf/prog_tests/xdp_metadata.c index 3ab963458903..7a72bb968779 100644 --- a/tools/testing/selftests/bpf/prog_tests/xdp_metadata.c +++ b/tools/testing/selftests/bpf/prog_tests/xdp_metadata.c @@ -18,12 +18,15 @@ #define TX_NAME "veTX" #define RX_NAME "veRX" -#define UDP_PAYLOAD_BYTES 4 +#define UDP_PAYLOAD_BYTES 32 + +#define MAX_SKB_FRAGS 17 /* minimum CONFIG_MAX_SKB_FRAGS */ +#define MAX_TX_DESCS (MAX_SKB_FRAGS + 1) #define UDP_SOURCE_PORT 1234 #define AF_XDP_CONSUMER_PORT 8080 -#define UMEM_NUM 16 +#define UMEM_NUM 64 #define UMEM_FRAME_SIZE XSK_UMEM__DEFAULT_FRAME_SIZE #define UMEM_SIZE (UMEM_FRAME_SIZE * UMEM_NUM) #define XDP_FLAGS XDP_FLAGS_DRV_MODE @@ -56,13 +59,13 @@ struct xsk { struct xsk_socket *socket; }; -static int open_xsk(int ifindex, struct xsk *xsk) +static int open_xsk(int ifindex, struct xsk *xsk, __u32 bind_flags) { int mmap_flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE; const struct xsk_socket_config socket_config = { .rx_size = XSK_RING_PROD__DEFAULT_NUM_DESCS, .tx_size = XSK_RING_PROD__DEFAULT_NUM_DESCS, - .bind_flags = XDP_COPY, + .bind_flags = bind_flags, }; const struct xsk_umem_config umem_config = { .fill_size = XSK_RING_PROD__DEFAULT_NUM_DESCS, @@ -133,31 +136,35 @@ static void close_xsk(struct xsk *xsk) munmap(xsk->umem_area, UMEM_SIZE); } -static int generate_packet(struct xsk *xsk, __u16 dst_port) +static int generate_packet(struct xsk *xsk, __u16 dst_port, u32 num) { struct xsk_tx_metadata *meta; struct xdp_desc *tx_desc; struct udphdr *udph; struct ethhdr *eth; struct iphdr *iph; + u16 first_len; + u16 pkt_len; + u8 pkt[256]; + u32 offset; void *data; __u32 idx; + u32 addr; int ret; + u32 i; - ret = xsk_ring_prod__reserve(&xsk->tx, 1, &idx); - if (!ASSERT_EQ(ret, 1, "xsk_ring_prod__reserve")) + pkt_len = sizeof(*eth) + sizeof(*iph) + sizeof(*udph) + UDP_PAYLOAD_BYTES; + first_len = sizeof(*eth) + sizeof(*iph) + sizeof(*udph); + if (!num || num > MAX_TX_DESCS || + (num > 1 && pkt_len - first_len < num - 1)) return -1; - tx_desc = xsk_ring_prod__tx_desc(&xsk->tx, idx); - tx_desc->addr = idx % (UMEM_NUM / 2) * UMEM_FRAME_SIZE + sizeof(struct xsk_tx_metadata); - printf("%p: tx_desc[%u]->addr=%llx\n", xsk, idx, tx_desc->addr); - data = xsk_umem__get_data(xsk->umem_area, tx_desc->addr); - - meta = data - sizeof(struct xsk_tx_metadata); - memset(meta, 0, sizeof(*meta)); - meta->flags = XDP_TXMD_FLAGS_TIMESTAMP; + ret = xsk_ring_prod__reserve(&xsk->tx, num, &idx); + if (!ASSERT_EQ(ret, num, "xsk_ring_prod__reserve")) + return -1; - eth = data; + memset(pkt, 0, sizeof(pkt)); + eth = (void *)pkt; iph = (void *)(eth + 1); udph = (void *)(iph + 1); @@ -180,18 +187,43 @@ static int generate_packet(struct xsk *xsk, __u16 dst_port) udph->source = htons(UDP_SOURCE_PORT); udph->dest = htons(dst_port); udph->len = htons(sizeof(*udph) + UDP_PAYLOAD_BYTES); + memset(udph + 1, 0xAA, UDP_PAYLOAD_BYTES); udph->check = ~csum_tcpudp_magic(iph->saddr, iph->daddr, ntohs(udph->len), IPPROTO_UDP, 0); - memset(udph + 1, 0xAA, UDP_PAYLOAD_BYTES); + for (i = 0, offset = 0; i < num; i++) { + u32 len; - meta->flags |= XDP_TXMD_FLAGS_CHECKSUM; - meta->request.csum_start = sizeof(*eth) + sizeof(*iph); - meta->request.csum_offset = offsetof(struct udphdr, check); + if (num == 1) + len = pkt_len; + else if (!i) + len = first_len; + else if (i == num - 1) + len = pkt_len - offset; + else + len = (pkt_len - first_len) / (num - 1); - tx_desc->len = sizeof(*eth) + sizeof(*iph) + sizeof(*udph) + UDP_PAYLOAD_BYTES; - tx_desc->options |= XDP_TX_METADATA; - xsk_ring_prod__submit(&xsk->tx, 1); + addr = (idx + i) % (UMEM_NUM / 2) * UMEM_FRAME_SIZE; + tx_desc = xsk_ring_prod__tx_desc(&xsk->tx, idx + i); + tx_desc->addr = addr + sizeof(*meta); + tx_desc->len = len; + tx_desc->options = i ? 0 : XDP_TX_METADATA; + if (i + 1 < num) + tx_desc->options |= XDP_PKT_CONTD; + printf("%p: tx_desc[%u]->addr=%llx\n", xsk, idx + i, tx_desc->addr); + data = xsk_umem__get_data(xsk->umem_area, tx_desc->addr); + if (!i) { + meta = data - sizeof(*meta); + memset(meta, 0, sizeof(*meta)); + meta->flags = XDP_TXMD_FLAGS_TIMESTAMP | XDP_TXMD_FLAGS_CHECKSUM; + meta->request.csum_start = sizeof(*eth) + sizeof(*iph); + meta->request.csum_offset = offsetof(struct udphdr, check); + } + memcpy(data, pkt + offset, len); + offset += len; + } + + xsk_ring_prod__submit(&xsk->tx, num); ret = sendto(xsk_socket__fd(xsk->socket), NULL, 0, MSG_DONTWAIT, NULL, 0); if (!ASSERT_GE(ret, 0, "sendto")) @@ -224,24 +256,27 @@ static int generate_packet_inet(void) return err; } -static void complete_tx(struct xsk *xsk) +static void complete_tx(struct xsk *xsk, u32 num) { struct xsk_tx_metadata *meta; __u64 addr; void *data; __u32 idx; + __u32 i; - if (ASSERT_EQ(xsk_ring_cons__peek(&xsk->comp, 1, &idx), 1, "xsk_ring_cons__peek")) { - addr = *xsk_ring_cons__comp_addr(&xsk->comp, idx); - - printf("%p: complete tx idx=%u addr=%llx\n", xsk, idx, addr); - - data = xsk_umem__get_data(xsk->umem_area, addr); - meta = data - sizeof(struct xsk_tx_metadata); - - ASSERT_NEQ(meta->completion.tx_timestamp, 0, "tx_timestamp"); + if (ASSERT_EQ(xsk_ring_cons__peek(&xsk->comp, num, &idx), num, + "xsk_ring_cons__peek")) { + for (i = 0; i < num; i++) { + addr = *xsk_ring_cons__comp_addr(&xsk->comp, idx + i); + printf("%p: complete tx idx=%u addr=%llx\n", xsk, idx + i, addr); - xsk_ring_cons__release(&xsk->comp, 1); + if (i == 0) { + data = xsk_umem__get_data(xsk->umem_area, addr); + meta = data - sizeof(*meta); + ASSERT_NEQ(meta->completion.tx_timestamp, 0, "tx_timestamp"); + } + } + xsk_ring_cons__release(&xsk->comp, num); } } @@ -325,7 +360,7 @@ static int verify_xsk_metadata(struct xsk *xsk, bool sent_from_af_xdp) ASSERT_EQ(meta->rx_hash_type, 0, "rx_hash_type"); /* checksum offload */ - ASSERT_EQ(udph->check, htons(0x721c), "csum"); + ASSERT_EQ(udph->check, htons(0x1c8f), "csum"); done: xsk_ring_cons__release(&xsk->rx, 1); @@ -361,6 +396,7 @@ void test_xdp_metadata(void) int retries = 10; int rx_ifindex; int tx_ifindex; + unsigned int i; int sock_fd; int ret; @@ -398,7 +434,7 @@ void test_xdp_metadata(void) /* Setup separate AF_XDP for RX interface. */ - ret = open_xsk(rx_ifindex, &rx_xsk); + ret = open_xsk(rx_ifindex, &rx_xsk, XDP_COPY); if (!ASSERT_OK(ret, "open_xsk(RX_NAME)")) goto out; @@ -462,27 +498,28 @@ void test_xdp_metadata(void) /* Setup separate AF_XDP for TX interface nad send packet to the RX socket. */ tx_ifindex = if_nametoindex(TX_NAME); - ret = open_xsk(tx_ifindex, &tx_xsk); + ret = open_xsk(tx_ifindex, &tx_xsk, XDP_COPY | XDP_USE_SG); if (!ASSERT_OK(ret, "open_xsk(TX_NAME)")) goto out; - if (!ASSERT_GE(generate_packet(&tx_xsk, AF_XDP_CONSUMER_PORT), 0, - "generate AF_XDP_CONSUMER_PORT")) - goto out; + for (i = 1; i <= MAX_TX_DESCS; i++) { + if (!ASSERT_GE(generate_packet(&tx_xsk, AF_XDP_CONSUMER_PORT, i), 0, + "generate AF_XDP packet")) + goto out; - switch_ns_to_rx(&tok); - if (!ASSERT_OK_PTR(tok, "setns rx")) - goto out; + switch_ns_to_rx(&tok); + if (!ASSERT_OK_PTR(tok, "setns rx")) + goto out; - /* Verify packet sent from AF_XDP has proper metadata. */ - if (!ASSERT_GE(verify_xsk_metadata(&rx_xsk, true), 0, - "verify_xsk_metadata")) - goto out; + if (!ASSERT_GE(verify_xsk_metadata(&rx_xsk, true), 0, + "verify xsk metadata")) + goto out; - switch_ns_to_tx(&tok); - if (!ASSERT_OK_PTR(tok, "setns tx")) - goto out; - complete_tx(&tx_xsk); + switch_ns_to_tx(&tok); + if (!ASSERT_OK_PTR(tok, "setns tx")) + goto out; + complete_tx(&tx_xsk, i); + } /* Now check metadata of packet, generated with network stack */ if (!ASSERT_GE(generate_packet_inet(), 0, "generate UDP packet")) @@ -518,7 +555,7 @@ void test_xdp_metadata(void) goto out; /* Send packet to trigger . */ - if (!ASSERT_GE(generate_packet(&tx_xsk, AF_XDP_CONSUMER_PORT), 0, + if (!ASSERT_GE(generate_packet(&tx_xsk, AF_XDP_CONSUMER_PORT, 1), 0, "generate freplace packet")) goto out; diff --git a/tools/testing/selftests/cgroup/test_cpuset_prs.sh b/tools/testing/selftests/cgroup/test_cpuset_prs.sh index 83ef6c781af3..1397ec428c46 100755 --- a/tools/testing/selftests/cgroup/test_cpuset_prs.sh +++ b/tools/testing/selftests/cgroup/test_cpuset_prs.sh @@ -137,7 +137,8 @@ LAST_PRESENT_CPU=$(cat /sys/devices/system/cpu/present | sed -e "s/.*[,-]//") # If isolated CPUs have been reserved at boot time (as shown in # /sys/devices/system/cpu/isolated), these isolated CPUs should be outside of # CPUs 0-8 that will be used by this script for testing purpose. If not, some -# of the tests may fail incorrectly. +# of the tests may fail incorrectly. The first boot isolated CPU should be +# 10 or above. # # The current set of isolated CPUs (as shown in cpuset.cpus.isolated) should # be the same as the boot value. If not, wait a bit and retry again just in @@ -156,7 +157,7 @@ TEST_ISOLCPUS= [[ -n "$BOOT_ISOLCPUS" ]] && { FIRST_ISOLCPUS=$(echo $BOOT_ISOLCPUS | sed -e "s/[,-].*//") echo "Boot isolated CPUs: $BOOT_ISOLCPUS" - [[ $FIRST_ISOLCPUS -le 8 ]] && + [[ $FIRST_ISOLCPUS -le 9 ]] && skip_test "Boot isolated CPUs overlap CPUs to be tested" } @@ -433,6 +434,12 @@ TEST_MATRIX=( # cpuset.cpus is allowed, but those extra CPUs are ignored. " C2-3:P1 C3:P1 . . . C2-4 . . 0 A1:|A2:2-3 A1:P1|A2:P1" + # Clearing cpuset.cpus.exclusive of an invalid partition releases its + # exclusive CPUs, including those of its descendants, so a sibling + # can claim them. + " CX2-3:P1 . . C3 T:O2=0:O3=0:X . . X3 0 XA1:|XB1:3 A1:P-1" + " CX2-3:P1 X3 . C3 T:O2=0:O3=0:X . . X3 0 XA1:|XA2:|XB1:3 A1:P-1" + # A child cannot recover until its exclusive CPUs are available again. " CX1-4:P1 CX3-4:P1 . . X1-2 . . . 0 A1:1-2|A2:1-2|XA2: A1:P1|A2:P-1" " CX1-4:P1 CX3-4:P1 . . X1-2:X1-4 . . . 0 A1:1-2|A2:3-4|XA2:3-4 A1:P1|A2:P1" @@ -531,6 +538,31 @@ TEST_MATRIX=( " C1-4:P1 C3-4:P2 . . T:C4-6 . . . 0 A1:5-6|A2:4 A1:P1|A2:P2 4" " C1-4:P1 C1-2:P2 . . T:C4-6 . . . 0 A1:4-6|A2:4-6 A1:P1|A2:P-2 ." + # The extra CPUs gained by a child partition when its parent expands the + # exclusive CPUs have to be taken away from the parent. + " C2-6:X2-5:P1 CX4-6:P1 \ + . . X2-6 . . . 0 A1:2-3|A2:4-6|XA2:4-6 \ + A1:P1|A2:P1 ." + " C2-6:X2-5:P1 CX4-6:P2 \ + . . X2-6 . . . 0 A1:2-3|A2:4-6|XA2:4-6 \ + A1:P1|A2:P2 4-6" + + # Both expansion and contraction of parent's effective_xcpus will be + # correctly handled in child partition and the child can be invalidated + # if a populated parent could lose all its effective_cpus. + " C2-6:X2-5:P1 CX3,5-6:P2 \ + . . X4-6 . . . 0 A1:4|A2:5-6|XA2:5-6 \ + A1:P1|A2:P2 4-6|5-6" + " C2-6:X2-5:P1 CX3-6:P2 \ + . . T:X4-6 . . . 0 A1:4-6|A2:4-6 A1:P1|A2:P-2 ." + + # Switch PRS state (root <=> isolated) will properly update cpuset.cpus.isolated + # even if child partitions are present. + " C1-6:P1 C3-6:P1 C5-6:P2 . . P2 . . 0 A1:1-2|A2:3-4|A3:5-6 \ + A1:P1|A2:P2|A3:P2 3-6" + " C1-6:P1 C3-6:P2 C5-6:P2 . . P1 . . 0 A1:1-2|A2:3-4|A3:5-6 \ + A1:P1|A2:P1|A3:P2 5-6" + # # old-A1 old-A2 old-A3 old-B1 new-A1 new-A2 new-A3 new-B1 fail ECPUs Pstate ISOLCPUS # ------ ------ ------ ------ ------ ------ ------ ------ ---- ----- ------ -------- @@ -587,6 +619,7 @@ ISOLCPUS_TEST_MATRIX=( ) # Test matrix to be run when boot time nohz_full CPUs cover all CPUs except CPUs 0-7 +# This also means that CPU 8 is available and is a nohz_full CPU. NOHZ_FULL_TEST_MATRIX=( # old-A1 old-A2 old-A3 old-B1 new-A1 new-A2 new-A3 new-B1 fail ECPUs Pstate ISOLCPUS # ------ ------ ------ ------ ------ ------ ------ ------ ---- ----- ------ -------- @@ -595,6 +628,10 @@ NOHZ_FULL_TEST_MATRIX=( " C2-7:P2 . . . C0-4 . . . 0 A1:0-4 A1:P2 0-4" " C1-7:P2 C5-7:P2 . . . . . C0:P2 0 A1:1-4|A2:5-7|B1:0 A1:P2|A2:P2|B1:P-2 1-7" + # An isolated child partition cannot grow to take over the last + # housekeeping CPU when its parent expands the exclusive CPUs. + " C0-8:X1-8:P1 CX0-8:P2 . . X0-7 . . . 0 A1:0-7|A2:0-7 A1:P1|A2:P-2 ." + " C0-8:X0-6:P1 CX0-8:P2 . . X2-8 . . . 0 A1:|A2:2-8 A1:P1|A2:P2 2-8" ) # @@ -670,6 +707,11 @@ REMOTE_TEST_MATRIX=( " C1-4:P1 C5-6 C1-2 . C5 . \ . P1 P1 . O5=0 . p1:3-4|p2:6|c11:1-2|c12:3-4|c21:6|c22:6 \ p1:P1|p2:P1|c11:P1" + # Expanding a remote partition should check top cpuset, not its member + # parent, for the no CPU left for tasks error. + " CX2-3:T . C2-3:X2:P1 . . . \ + . . X2-3 . . . p1:1,4-7|c11:2-3 \ + p1:P0|c11:P1" ) # diff --git a/tools/testing/selftests/drivers/net/hw/.gitignore b/tools/testing/selftests/drivers/net/hw/.gitignore index 46540468a775..911a9bfeaf41 100644 --- a/tools/testing/selftests/drivers/net/hw/.gitignore +++ b/tools/testing/selftests/drivers/net/hw/.gitignore @@ -1,4 +1,5 @@ # SPDX-License-Identifier: GPL-2.0-only iou-zcrx ncdevmem +tls_hw_offload toeplitz diff --git a/tools/testing/selftests/drivers/net/hw/Makefile b/tools/testing/selftests/drivers/net/hw/Makefile index 9b6b5d15f04d..429cb545a4f0 100644 --- a/tools/testing/selftests/drivers/net/hw/Makefile +++ b/tools/testing/selftests/drivers/net/hw/Makefile @@ -47,6 +47,7 @@ TEST_PROGS = \ rss_drv.py \ rss_flow_label.py \ rss_input_xfrm.py \ + tls_hw_offload.py \ toeplitz.py \ tso.py \ userns_devmem.py \ @@ -81,6 +82,7 @@ YNL_GEN_FILES := \ $(COND_GEN_FILES) \ # end of YNL_GEN_FILES TEST_GEN_FILES += $(YNL_GEN_FILES) +TEST_GEN_FILES += tls_hw_offload TEST_GEN_FILES += $(patsubst %.c,%.o,$(wildcard *.bpf.c)) include ../../../lib.mk diff --git a/tools/testing/selftests/drivers/net/hw/config b/tools/testing/selftests/drivers/net/hw/config index c6c2b64bb712..081155bf7847 100644 --- a/tools/testing/selftests/drivers/net/hw/config +++ b/tools/testing/selftests/drivers/net/hw/config @@ -22,6 +22,8 @@ CONFIG_NET_IPIP=y CONFIG_NETKIT=y CONFIG_NET_SCH_INGRESS=y CONFIG_SYNC_FILE=y +CONFIG_TLS=y +CONFIG_TLS_DEVICE=y CONFIG_UDMABUF=y CONFIG_USER_NS=y CONFIG_VLAN_8021Q=m diff --git a/tools/testing/selftests/drivers/net/hw/tls_hw_offload.c b/tools/testing/selftests/drivers/net/hw/tls_hw_offload.c new file mode 100644 index 000000000000..5b3887f32b68 --- /dev/null +++ b/tools/testing/selftests/drivers/net/hw/tls_hw_offload.c @@ -0,0 +1,908 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * TLS Hardware Offload Two-Node Test + * + * Tests kTLS hardware offload between two physical nodes using + * hardcoded keys. Supports TLS 1.2 and AES-GCM-128/256. + * + * Both ends must run this helper: there is no handshake. + */ + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> +#include <errno.h> +#include <limits.h> +#include <time.h> +#include <sys/time.h> +#include <signal.h> +#include <sys/types.h> +#include <sys/socket.h> +#include <netinet/in.h> +#include <netinet/tcp.h> +#include <netdb.h> +#include <linux/tls.h> + +#ifndef SOL_TLS +#define SOL_TLS 282 +#endif + +#define TLS_RECORD_TYPE_HANDSHAKE 22 +#define TLS_RECORD_TYPE_ALERT 21 +#define TLS_RECORD_TYPE_DATA 23 + +#define MIN_BUF_SIZE 16 + +/* Initial key material */ +static struct tls12_crypto_info_aes_gcm_128 tls_info_key0_128 = { + .info = { + .version = TLS_1_2_VERSION, + .cipher_type = TLS_CIPHER_AES_GCM_128, + }, + .iv = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }, + .key = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10 }, + .salt = { 0x01, 0x02, 0x03, 0x04 }, + .rec_seq = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, +}; + +static struct tls12_crypto_info_aes_gcm_256 tls_info_key0_256 = { + .info = { + .version = TLS_1_2_VERSION, + .cipher_type = TLS_CIPHER_AES_GCM_256, + }, + .iv = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }, + .key = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, + 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, + 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20 }, + .salt = { 0x01, 0x02, 0x03, 0x04 }, + .rec_seq = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, +}; + +static int test_record_type; +static int num_iterations = 100; +static int cipher_type = TLS_CIPHER_AES_GCM_128; +static int tls_version = TLS_1_2_VERSION; +static int server_port = 4433; +static char *server_ip; +/* Address family to force: AF_UNSPEC (any), AF_INET (-4), AF_INET6 (-6). */ +static int force_family = AF_UNSPEC; + +static int send_size = 16384; +static int random_size_max; +/* Per-iteration progress output (-V). Off by default: the + * harness runs the server in the background and captures its stdout in a + * pipe that is not drained until the server exits, so unbounded per-record + * chatter (thousands of lines for the large echo variants) would fill the + * pipe, block printf(), stall the echo loop and surface as a bogus recv + * timeout on the client. With -V off a run prints + * fixed setup/summary lines, comfortably inside a 64 KiB pipe. + */ +static int verbose; + +/* Upper bound on a helper's lifetime, enforced by SIGALRM. The harness + * waits for both helpers with the default 20s cmd()/bkg() timeout and + * cannot signal the one on the remote, so each must exit on its own first. + * A normal run takes a few seconds; the socket timeouts catch most stalls + * sooner and with a better error. + */ +#define HELPER_TIMEOUT_S 15 + +static const char *cipher_name(int cipher) +{ + switch (cipher) { + case TLS_CIPHER_AES_GCM_128: return "AES-GCM-128"; + case TLS_CIPHER_AES_GCM_256: return "AES-GCM-256"; + default: return "unknown"; + } +} + +static const char *version_name(int version) +{ + switch (version) { + case TLS_1_2_VERSION: return "TLS 1.2"; + default: return "unknown"; + } +} + +static int setup_tls_ulp(int fd) +{ + int ret; + + ret = setsockopt(fd, IPPROTO_TCP, TCP_ULP, "tls", sizeof("tls")); + if (ret < 0) { + printf("SETUP ERROR: TCP_ULP failed: %s\n", strerror(errno)); + return -1; + } + return 0; +} + +/* Echo mode drives both directions from a single thread: the + * client pushes a whole payload with one blocking send() and only reads the + * echo afterwards, while the server blocks in send() mid-echo. If a payload + * exceeds the peer's receive window the two sides deadlock - client stuck in + * send(), server stuck echoing, neither draining the other. Size the socket + * buffers so a full payload always fits in the peer's window (the forward + * send() then completes without needing the peer to read concurrently); the + * send/recv timeouts armed by set_io_timeouts() turn any residual stall into a + * loud EAGAIN instead of a hang. + */ +static void configure_echo_socket(int fd, int payload) +{ + int want = payload; + + if (want < MIN_BUF_SIZE) + want = MIN_BUF_SIZE; + + /* SO_*BUFFORCE bypasses the rmem_max/wmem_max sysctl caps (needs + * CAP_NET_ADMIN); fall back to the best-effort, cap-limited option + * when unprivileged - the timeouts below still turn any resulting + * stall into a loud failure rather than a hang. + */ + if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &want, sizeof(want)) < 0) + setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &want, sizeof(want)); + if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &want, sizeof(want)) < 0) + setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &want, sizeof(want)); +} + +/* Arm send/recv timeouts so any unexpected stall fails loudly with EAGAIN + * instead of running into HELPER_TIMEOUT_S. + */ +static void set_io_timeouts(int fd) +{ + struct timeval tv = { .tv_sec = 8, .tv_usec = 0 }; + + setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); + setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)); +} + +/* Send the whole buffer, looping over short counts. A blocking SOCK_STREAM + * send() may return fewer bytes than requested (e.g. when SO_SNDTIMEO fires + * after partial progress) without setting errno, so a short count is not an + * error - only a negative return is. + */ +static int send_all(int fd, const char *buf, ssize_t len) +{ + ssize_t sent = 0; + ssize_t ret; + + while (sent < len) { + ret = send(fd, buf + sent, len - sent, 0); + if (ret <= 0) { + /* 0 for a non-empty request would spin forever. */ + printf("FAIL: send failed: %s\n", + ret ? strerror(errno) : "no progress"); + return -1; + } + sent += ret; + } + return 0; +} + +static int recv_tls_message(int fd, char *buf, size_t buflen, int *record_type) +{ + char cmsg_buf[CMSG_SPACE(sizeof(unsigned char))]; + struct msghdr msg = {0}; + struct cmsghdr *cmsg; + struct iovec iov; + int ret; + + iov.iov_base = buf; + iov.iov_len = buflen; + + msg.msg_iov = &iov; + msg.msg_iovlen = 1; + msg.msg_control = cmsg_buf; + msg.msg_controllen = sizeof(cmsg_buf); + + ret = recvmsg(fd, &msg, 0); + if (ret <= 0) + return ret; + + cmsg = CMSG_FIRSTHDR(&msg); + if (cmsg && cmsg->cmsg_level == SOL_TLS && + cmsg->cmsg_type == TLS_GET_RECORD_TYPE) + *record_type = *((unsigned char *)CMSG_DATA(cmsg)); + + return ret; +} + +static int install_tls_key(int fd, int direction, int cipher) +{ + const char *dir = direction == TLS_TX ? "TX" : "RX"; + int ret; + + if (verbose) + printf("Installing TLS_%s %s...\n", dir, cipher_name(cipher)); + + if (cipher == TLS_CIPHER_AES_GCM_256) { + struct tls12_crypto_info_aes_gcm_256 key; + + memcpy(&key, &tls_info_key0_256, sizeof(key)); + key.info.version = tls_version; + ret = setsockopt(fd, SOL_TLS, direction, &key, sizeof(key)); + } else { + struct tls12_crypto_info_aes_gcm_128 key; + + memcpy(&key, &tls_info_key0_128, sizeof(key)); + key.info.version = tls_version; + ret = setsockopt(fd, SOL_TLS, direction, &key, sizeof(key)); + } + + if (ret < 0) { + printf("SETUP ERROR: TLS_%s %s failed: %s\n", + dir, cipher_name(cipher), strerror(errno)); + return -1; + } + printf("TLS_%s %s installed\n", dir, cipher_name(cipher)); + return 0; +} + +/* Open a TCP connection to server_ip:server_port, switch to the TLS + * ULP, and install initial TX/RX keys. Works over IPv4 or + * IPv6: getaddrinfo() resolves server_ip (honouring any -4/-6 forced + * family and %zone scope IDs in link-local addresses). Returns the fd on + * success, -1 on error (with the fd already closed). + */ +static int client_connect_tls(void) +{ + struct addrinfo hints = {0}, *res, *rp; + char port_str[16]; + int csk = -1; + int err = 0; + int ret; + + hints.ai_family = force_family; + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = IPPROTO_TCP; + snprintf(port_str, sizeof(port_str), "%d", server_port); + + ret = getaddrinfo(server_ip, port_str, &hints, &res); + if (ret) { + printf("SETUP ERROR: getaddrinfo(%s): %s\n", server_ip, + gai_strerror(ret)); + return -1; + } + + printf("Connecting to %s:%d...\n", server_ip, server_port); + for (rp = res; rp; rp = rp->ai_next) { + csk = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); + if (csk < 0) { + err = errno; + continue; + } + if (connect(csk, rp->ai_addr, rp->ai_addrlen) == 0) + break; + err = errno; + close(csk); + csk = -1; + } + freeaddrinfo(res); + + if (csk < 0) { + printf("SETUP ERROR: connect to %s:%d failed: %s\n", + server_ip, server_port, strerror(err)); + return -1; + } + printf("Connected!\n"); + + if (setup_tls_ulp(csk) < 0) + goto err; + + if (install_tls_key(csk, TLS_TX, cipher_type) < 0 || + install_tls_key(csk, TLS_RX, cipher_type) < 0) + goto err; + + set_io_timeouts(csk); + configure_echo_socket(csk, random_size_max > 0 ? + random_size_max : send_size); + + return csk; +err: + close(csk); + return -1; +} + +/* Drain `len` echoed bytes from the server and verify they match the + * payload we just sent. + */ +static int client_recv_echo(int fd, const char *sent, char *echo_buf, + ssize_t len) +{ + ssize_t total = 0; + ssize_t n; + + while (total < len) { + n = recv(fd, echo_buf + total, len - total, 0); + if (n < 0) { + printf("FAIL: Echo recv failed: %s\n", strerror(errno)); + return -1; + } + if (n == 0) { + printf("FAIL: Connection closed during echo\n"); + return -1; + } + total += n; + } + + if (memcmp(sent, echo_buf, len) != 0) { + printf("FAIL: Echo data mismatch!\n"); + return -1; + } + if (verbose) + printf("Received echo %zd bytes (ok)\n", total); + return 0; +} + +static int do_client(void) +{ + char *buf = NULL, *echo_buf = NULL; + int max_size; + int csk = -1, i = 1; + int test_result = -1; + ssize_t n, total = 0; + + max_size = random_size_max > 0 ? random_size_max : send_size; + if (max_size < MIN_BUF_SIZE) + max_size = MIN_BUF_SIZE; + buf = malloc(max_size); + echo_buf = malloc(max_size); + if (!buf || !echo_buf) { + printf("SETUP ERROR: failed to allocate buffers\n"); + goto out; + } + + csk = client_connect_tls(); + if (csk < 0) + goto out; + + printf("TLS setup complete.\n"); + + if (random_size_max > 0) + printf("Sending %d messages of random size (1..%d bytes)...\n", + num_iterations, random_size_max); + else + printf("Sending %d messages of %d bytes...\n", + num_iterations, send_size); + + for (i = 1; i <= num_iterations; i++) { + int this_size; + int j; + + if (random_size_max > 0) + this_size = (rand() % random_size_max) + 1; + else + this_size = send_size; + + for (j = 0; j < this_size; j++) + buf[j] = rand() & 0xFF; + + if (send_all(csk, buf, this_size) < 0) + goto out; + n = this_size; + total += n; + + if (verbose) + printf("Sent %zd bytes (iteration %d)\n", n, i); + if (client_recv_echo(csk, buf, echo_buf, n) < 0) + goto out; + } + + test_result = 0; +out: + printf("Sent %d/%d iterations, %zd bytes\n", i - 1, num_iterations, + total); + if (csk >= 0) + close(csk); + free(buf); + free(echo_buf); + return test_result; +} + +/* Bind/listen on server_port, accept one client, switch to the TLS ULP + * and install initial keys. + * Returns the connected fd on success and writes the listener fd to + * *lsk_out so the caller can close it. Returns -1 on error, with all + * intermediate fds already closed and *lsk_out left at -1. + */ +static int server_accept_tls(int *lsk_out) +{ + struct addrinfo hints = {0}, *res, *rp; + int lsk = -1, csk, one = 1; + char port_str[16]; + int ret; + + *lsk_out = -1; + + /* AI_PASSIVE gives a wildcard bind address for the chosen family + * (0.0.0.0 / ::). The family is forced by -4/-6; when unspecified, + * bind the first entry that works. + */ + hints.ai_family = force_family; + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = IPPROTO_TCP; + hints.ai_flags = AI_PASSIVE; + snprintf(port_str, sizeof(port_str), "%d", server_port); + + ret = getaddrinfo(NULL, port_str, &hints, &res); + if (ret) { + printf("SETUP ERROR: getaddrinfo(port %d): %s\n", server_port, + gai_strerror(ret)); + return -1; + } + + for (rp = res; rp; rp = rp->ai_next) { + lsk = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); + if (lsk < 0) + continue; + setsockopt(lsk, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)); + if (bind(lsk, rp->ai_addr, rp->ai_addrlen) == 0) + break; + close(lsk); + lsk = -1; + } + freeaddrinfo(res); + + if (lsk < 0) { + printf("SETUP ERROR: failed to bind port %d: %s\n", + server_port, strerror(errno)); + return -1; + } + + if (listen(lsk, 1) < 0) { + printf("SETUP ERROR: listen failed: %s\n", strerror(errno)); + close(lsk); + return -1; + } + + printf("Server listening on port %d\n", server_port); + printf("Waiting for client connection...\n"); + + /* Bound accept() so a client that never connects (a deploy or connect + * failure on the peer) does not block the server forever. accept() + * honours SO_RCVTIMEO on the listening socket; the client connects + * right after wait_port_listen(), so 10s is generous. + */ + { + struct timeval tv = { .tv_sec = 10, .tv_usec = 0 }; + + setsockopt(lsk, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); + } + + csk = accept(lsk, NULL, NULL); + if (csk < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK) + printf("SETUP ERROR: accept timed out, no client\n"); + else + printf("SETUP ERROR: accept failed: %s\n", + strerror(errno)); + close(lsk); + return -1; + } + printf("Client connected!\n"); + + if (setup_tls_ulp(csk) < 0) + goto err; + + if (install_tls_key(csk, TLS_TX, cipher_type) < 0 || + install_tls_key(csk, TLS_RX, cipher_type) < 0) + goto err; + + set_io_timeouts(csk); + configure_echo_socket(csk, random_size_max > 0 ? + random_size_max : send_size); + + *lsk_out = lsk; + return csk; +err: + close(csk); + close(lsk); + return -1; +} + +static int do_server(void) +{ + int lsk = -1, csk = -1; + ssize_t n, total = 0; + int test_result = -1; + int recv_count = 0; + char *buf = NULL; + int record_type = 0; + int buf_size; + + buf_size = send_size; + if (buf_size < MIN_BUF_SIZE) + buf_size = MIN_BUF_SIZE; + buf = malloc(buf_size); + if (!buf) { + printf("SETUP ERROR: failed to allocate buffer\n"); + goto out; + } + + csk = server_accept_tls(&lsk); + if (csk < 0) + goto out; + + printf("TLS %s setup complete. Receiving...\n", + cipher_name(cipher_type)); + + /* Echo everything back; the client verifies each echo. */ + while (1) { + record_type = 0; + n = recv_tls_message(csk, buf, buf_size, &record_type); + if (n == 0) { + printf("Connection closed by client\n"); + break; + } + if (n < 0) { + printf("FAIL: recv failed: %s\n", strerror(errno)); + goto out; + } + if (record_type != TLS_RECORD_TYPE_DATA) { + printf("FAIL: expected data record, got type %d\n", + record_type); + goto out; + } + + total += n; + recv_count++; + if (verbose) + printf("Received %zd bytes (total: %zd, count: %d)\n", + n, total, recv_count); + + if (send_all(csk, buf, n) < 0) + goto out; + if (verbose) + printf("Echoed %zd bytes back to client\n", n); + } + + test_result = 0; +out: + printf("Connection closed. Total received: %zd bytes in %d reads\n", + total, recv_count); + + if (csk >= 0) + close(csk); + if (lsk >= 0) + close(lsk); + free(buf); + return test_result; +} + +static int send_record_type(int fd) +{ + char control[CMSG_SPACE(sizeof(unsigned char))] = {}; + struct iovec iov = { .iov_base = "BBBB", .iov_len = 4 }; + struct msghdr msg = { + .msg_iov = &iov, + .msg_iovlen = 1, + .msg_control = control, + .msg_controllen = sizeof(control), + }; + struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg); + char ack[2]; + + if (send(fd, "AAAA", 4, MSG_MORE) != 4) { + printf("FAIL: send MSG_MORE failed: %s\n", strerror(errno)); + return -1; + } + cmsg->cmsg_level = SOL_TLS; + cmsg->cmsg_type = TLS_SET_RECORD_TYPE; + cmsg->cmsg_len = CMSG_LEN(sizeof(unsigned char)); + *CMSG_DATA(cmsg) = test_record_type; + if (sendmsg(fd, &msg, 0) != 4) { + printf("FAIL: sendmsg record type failed: %s\n", + strerror(errno)); + return -1; + } + return client_recv_echo(fd, "OK", ack, sizeof(ack)); +} + +static int expect_record(int fd, const char *data, unsigned char type) +{ + char control[CMSG_SPACE(sizeof(unsigned char))] = {}; + char buf[16]; + struct iovec iov = { .iov_base = buf, .iov_len = sizeof(buf) }; + struct msghdr msg = { + .msg_iov = &iov, + .msg_iovlen = 1, + .msg_control = control, + .msg_controllen = sizeof(control), + }; + struct cmsghdr *cmsg; + int ret; + + ret = recvmsg(fd, &msg, 0); + if (ret != 4 || memcmp(buf, data, 4) || + (msg.msg_flags & (MSG_CTRUNC | MSG_TRUNC)) || + !(msg.msg_flags & MSG_EOR)) { + printf("FAIL: expected record '%s', got %d bytes, flags %#x\n", + data, ret, msg.msg_flags); + return -1; + } + cmsg = CMSG_FIRSTHDR(&msg); + if (!cmsg || cmsg->cmsg_level != SOL_TLS || + cmsg->cmsg_type != TLS_GET_RECORD_TYPE || + cmsg->cmsg_len != CMSG_LEN(sizeof(unsigned char)) || + *CMSG_DATA(cmsg) != type) { + printf("FAIL: expected record type %u\n", type); + return -1; + } + return 0; +} + +static int recv_record_type(int fd) +{ + char buf[16]; + int ret; + + if (expect_record(fd, "AAAA", TLS_RECORD_TYPE_DATA) || + expect_record(fd, "BBBB", test_record_type) || + send_all(fd, "OK", 2)) + return -1; + ret = recv(fd, buf, sizeof(buf), 0); + if (ret) { + printf("FAIL: expected EOF after records, got %d\n", ret); + return -1; + } + return 0; +} + +static int test_pending_record(int is_server) +{ + char *buf = NULL, *echo_buf = NULL; + int lsk = -1, csk = -1; + int test_result = -1; + int i; + + buf = malloc(send_size); + echo_buf = malloc(send_size); + if (!buf || !echo_buf) { + printf("SETUP ERROR: failed to allocate buffers\n"); + goto out; + } + memset(buf, 0xa5, send_size); + + csk = is_server ? server_accept_tls(&lsk) : client_connect_tls(); + if (csk < 0) + goto out; + + /* Exercise the offload data path before the record-type transition. */ + for (i = 0; i < num_iterations; i++) { + if (!is_server && send_all(csk, buf, send_size) < 0) + goto out; + if (client_recv_echo(csk, buf, echo_buf, send_size) < 0) + goto out; + if (is_server && send_all(csk, buf, send_size) < 0) + goto out; + } + + test_result = is_server ? recv_record_type(csk) : send_record_type(csk); +out: + if (csk >= 0) + close(csk); + if (lsk >= 0) + close(lsk); + free(buf); + free(echo_buf); + return test_result; +} + +static int parse_int_arg(const char *arg, int min, int max, + const char *name, int *out) +{ + char *endp; + long val; + + errno = 0; + val = strtol(arg, &endp, 10); + if (errno || endp == arg || *endp != '\0' || val < min || val > max) { + if (max == INT_MAX) + printf("ERROR: Invalid %s '%s'. Must be >= %d.\n", + name, arg, min); + else + printf("ERROR: Invalid %s '%s'. Must be %d..%d.\n", + name, arg, min, max); + return -1; + } + *out = (int)val; + return 0; +} + +static int parse_cipher_option(const char *arg) +{ + if (strcmp(arg, "128") == 0) { + cipher_type = TLS_CIPHER_AES_GCM_128; + return 0; + } else if (strcmp(arg, "256") == 0) { + cipher_type = TLS_CIPHER_AES_GCM_256; + return 0; + } + printf("ERROR: Invalid cipher '%s'. Must be 128 or 256.\n", arg); + return -1; +} + +static int parse_version_option(const char *arg) +{ + if (strcmp(arg, "1.2") == 0) { + tls_version = TLS_1_2_VERSION; + return 0; + } + printf("ERROR: Invalid TLS version '%s'. Must be 1.2.\n", arg); + return -1; +} + +static void print_usage(const char *prog) +{ + printf("TLS Hardware Offload Two-Node Test\n\n"); + printf("Usage:\n"); + printf(" %s server [OPTIONS]\n", prog); + printf(" %s client -s <ip> [OPTIONS]\n", prog); + printf("\nOptions:\n"); + printf(" -s <ip> Server IPv4/IPv6 address (client, required)\n"); + printf(" -p <port> Server port (default: 4433)\n"); + printf(" -4 Force IPv4 (default: auto/either)\n"); + printf(" -6 Force IPv6 (default: auto/either)\n"); + printf(" -b <size> Send buffer size in bytes (default: 16384)\n"); + printf(" -r <max> Use random send buffer sizes (1..<max>)\n"); + printf(" -v <version> TLS version: 1.2 (default: 1.2)\n"); + printf(" -c <cipher> Cipher: 128 or 256 (default: 128)\n"); + printf(" -n <N> Send/echo iterations (default: 100)\n"); + printf(" -t <type> Record type test: 21=alert, 22=handshake\n"); + printf(" -V Verbose: log every iteration\n"); + printf(" -h Show this help message\n"); + printf("\nExample:\n"); + printf(" Node A: %s server\n", prog); + printf(" Node B: %s client -s 192.168.20.2\n", prog); + printf("\nIPv6 Example:\n"); + printf(" Node A: %s server -6\n", prog); + printf(" Node B: %s client -6 -s fd00::2\n", prog); +} + +int main(int argc, char *argv[]) +{ + int send_size_set = 0; + int is_server; + int opt; + + /* When the peer aborts a TLS connection (e.g. tls_err_abort() on a + * failed decrypt), a send() here would raise SIGPIPE and kill us by + * signal, so the harness sees only a bare non-zero exit with no + * "FAIL:" line. Ignore it and let send()/sendmsg() return EPIPE, which + * send_all()/send_record_type() report. + */ + signal(SIGPIPE, SIG_IGN); + + /* Line-buffer stdout so that output printed before a SIGALRM death + * is not lost in the stdio buffer. + */ + setvbuf(stdout, NULL, _IOLBF, 0); + alarm(HELPER_TIMEOUT_S); + + if (argc < 2 || + (strcmp(argv[1], "server") && strcmp(argv[1], "client"))) { + print_usage(argv[0]); + return 1; + } + is_server = !strcmp(argv[1], "server"); + + optind = 2; /* skip subcommand */ + while ((opt = getopt(argc, argv, "s:p:b:r:c:v:n:t:V46h")) != -1) { + switch (opt) { + case 's': + server_ip = optarg; + break; + case 'V': + verbose = 1; + break; + case '4': + if (force_family == AF_INET6) { + printf("ERROR: -4 and -6 are exclusive\n"); + return 1; + } + force_family = AF_INET; + break; + case '6': + if (force_family == AF_INET) { + printf("ERROR: -4 and -6 are exclusive\n"); + return 1; + } + force_family = AF_INET6; + break; + case 'p': + if (parse_int_arg(optarg, 1, 65535, "port", + &server_port) < 0) + return 1; + break; + case 'b': + if (parse_int_arg(optarg, 1, INT_MAX, "buffer size", + &send_size) < 0) + return 1; + send_size_set = 1; + break; + case 'r': + if (parse_int_arg(optarg, 1, INT_MAX, "random size", + &random_size_max) < 0) + return 1; + break; + case 'c': + if (parse_cipher_option(optarg) < 0) + return 1; + break; + case 'v': + if (parse_version_option(optarg) < 0) + return 1; + break; + case 't': + if (parse_int_arg(optarg, TLS_RECORD_TYPE_ALERT, + TLS_RECORD_TYPE_HANDSHAKE, + "record type", &test_record_type) < 0) + return 1; + break; + case 'n': + /* do_client() counts i = 1..num_iterations with an + * inclusive int bound, so INT_MAX itself would + * overflow the counter instead of terminating. + */ + if (parse_int_arg(optarg, 1, INT_MAX - 1, + "iteration count", + &num_iterations) < 0) + return 1; + break; + case 'h': + print_usage(argv[0]); + return 0; + default: + print_usage(argv[0]); + return 1; + } + } + + if (send_size_set && random_size_max > 0) { + printf("ERROR: -b and -r are mutually exclusive\n"); + return 1; + } + + if (test_record_type && random_size_max) { + printf("ERROR: -t cannot be combined with -r\n"); + return 1; + } + + if (is_server) { + if (server_ip) { + printf("warning: -s is ignored in server mode\n"); + server_ip = NULL; + } + if (random_size_max > 0) { + printf("warning: -r is ignored in server mode\n"); + random_size_max = 0; + } + } else { + if (!server_ip) { + printf("ERROR: Client requires -s <ip> option\n"); + return 1; + } + } + + printf("TLS Version: %s\n", version_name(tls_version)); + printf("Cipher: %s\n", cipher_name(cipher_type)); + printf("Address family: %s\n", + force_family == AF_INET ? "IPv4" : + force_family == AF_INET6 ? "IPv6" : "auto"); + if (random_size_max > 0) + printf("Buffer size: random (1..%d)\n", random_size_max); + else + printf("Buffer size: %d\n", send_size); + + srand(time(NULL)); + + if (test_record_type) + return test_pending_record(is_server) ? 1 : 0; + + if (is_server) + return do_server() ? 1 : 0; + + return do_client() ? 1 : 0; +} diff --git a/tools/testing/selftests/drivers/net/hw/tls_hw_offload.py b/tools/testing/selftests/drivers/net/hw/tls_hw_offload.py new file mode 100755 index 000000000000..e720ce654761 --- /dev/null +++ b/tools/testing/selftests/drivers/net/hw/tls_hw_offload.py @@ -0,0 +1,321 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0 + +"""Test kTLS hardware offload using a C helper binary.""" + +from collections import defaultdict + +from lib.py import ( + CmdExitFailure, + KsftNamedVariant, + KsftSkipEx, + NetDrvEpEnv, + bkg, + cmd, + ksft_eq, + ksft_exit, + ksft_ge, + ksft_pr, + ksft_run, + ksft_variants, + rand_port, + wait_port_listen, +) + +# `ethtool -S` counters on the DUT NIC, from the minimum set every TLS +# offload driver should report (Documentation/networking/tls-offload.rst, +# "Statistics"). Drivers expose varying subsets: mlx5 has all four, nfp +# both *_packets but no *_tls_ctx, cxgb4 and funeth only the two tx_ +# counters. Each counter is checked only when present. +# TlsTxDevice/TlsRxDevice in /proc/net/tls_stat only prove tls_dev_add() +# accepted the offload: +# - tx_tls_encrypted_packets counts TX packets passed to the device for +# encryption. Drivers bump it while building the descriptor, not on +# completion, so it shows the driver used the offload path, not that +# the NIC encrypted anything; a broken HW encrypt shows up instead as a +# peer TlsDecryptError or an echo mismatch. +# - rx_tls_decrypted_packets counts RX packets the NIC successfully +# decrypted. +# - Both *_packets count packets (mlx5 counts gso_segs), not records. +# - *_ctx increment once per tls_dev_add(). +# Missing NIC crypto counters remain optional. +HW_NIC_COUNTERS = { + 'Tx': {'crypto': 'tx_tls_encrypted_packets', 'ctx': 'tx_tls_ctx'}, + 'Rx': {'crypto': 'rx_tls_decrypted_packets', 'ctx': 'rx_tls_ctx'}, +} + + +def check_tls_support(cfg): + """Require kTLS on both hosts and at least one DUT HW direction.""" + # The tls module is autoloaded lazily on the first TCP_ULP="tls" + # setsockopt, so /proc/net/tls_stat (created from the module's pernet + # init) may not exist yet on a freshly booted host. Load the module + # explicitly before probing for it. Best effort only: with CONFIG_TLS=y + # (what the config fragment asks for) there is nothing to load, and + # modprobe may fail for reasons unrelated to kTLS (no modules.dep for a + # locally built kernel, no modprobe on a minimal rootfs). The + # /proc/net/tls_stat probe below is the authoritative check. Locally, + # cmd() runs without a shell, so a missing modprobe raises + # FileNotFoundError rather than returning a failed exit status. + try: + cmd("modprobe tls", fail=False) + except FileNotFoundError: + pass + cmd("modprobe tls", host=cfg.remote, fail=False) + try: + cmd("test -f /proc/net/tls_stat") + cmd("test -f /proc/net/tls_stat", host=cfg.remote) + except CmdExitFailure as e: + raise KsftSkipEx(f"kTLS not supported: {e}") from e + + try: + features = cmd(f"ethtool -k {cfg.ifname}").stdout + except CmdExitFailure as e: + raise KsftSkipEx(f"Cannot determine TLS HW offload support: {e}") from e + cfg.tls_hw_directions = { + direction for direction in ('Tx', 'Rx') + if f'tls-hw-{direction.lower()}-offload: on' in features + } + if not cfg.tls_hw_directions: + raise KsftSkipEx("Device has no enabled TLS HW offload direction") + + +def require_tls_setup(cfg): + """Deploy the helper and probe kTLS support once, on first use. + + This runs from within the test cases rather than main(): ksft_run() + turns KsftSkipEx into a SKIP result only for an exception raised by a + case, so a skip raised from main() would be reported as a failure. + The outcome is cached so later cases skip with the same reason. + """ + if cfg.tls_skip_reason: + raise KsftSkipEx(cfg.tls_skip_reason) + if cfg.bin_remote: + return + try: + check_tls_support(cfg) + except KsftSkipEx as e: + cfg.tls_skip_reason = str(e) + raise + cfg.bin_remote = cfg.remote.deploy(cfg.bin_local) + + +def read_tls_stats(host=None): + """Snapshot the per-netns TLS MIB from /proc/net/tls_stat as a dict.""" + # /proc/net/tls_stat exposes the per-netns TLS MIB (TLS_INC_STATS on + # sock_net(sk)). The test runs on a real NIC in the host namespace, so + # these counters are shared with anything else doing kTLS there. The + # strict before/after delta checks (zero error counters) assume no other + # kTLS activity in this namespace during a + # variant's window; concurrent kTLS users would perturb the deltas and + # cause spurious failures. Don't run other kTLS workloads alongside this + # test. + stats = defaultdict(int) + output = cmd("cat /proc/net/tls_stat", host=host) + for line in output.stdout.strip().split('\n'): + parts = line.split() + if len(parts) == 2: + stats[parts[0]] = int(parts[1]) + return stats + + +def read_nic_stats(cfg): + """Snapshot the DUT NIC's `ethtool -S` counters as a dict.""" + # Driver per-record TLS counters from `ethtool -S` on the DUT NIC. Same + # before/after-delta caveat as read_tls_stats(): these are device-wide, + # so concurrent kTLS traffic on this NIC would perturb the deltas. + stats = defaultdict(int) + output = cmd(f"ethtool -S {cfg.ifname}").stdout + for line in output.strip().split('\n'): + key, sep, val = line.partition(':') + if sep and val.strip().isdigit(): + stats[key.strip()] = int(val.strip()) + return stats + + +def stat_diff(before, after, key): + """Return the delta of counter `key` between two stat snapshots.""" + return after[key] - before[key] + + +def check_hw_crypto(cfg, nic_before, nic_after, hw_directions): + """Check DUT NIC offload-path packet counts and initial key installs.""" + for direction in hw_directions: + names = HW_NIC_COUNTERS[direction] + + key = names['crypto'] + if key in nic_after: + got = stat_diff(nic_before, nic_after, key) + ksft_ge(got, 1, + comment=f"DUT {direction}: NIC reported no TLS " + f"offload packets ({key}={got})") + else: + ksft_pr(f"NOTE: DUT {direction}: '{key}' not exposed by " + f"{cfg.ifname}, skipping NIC packet count check") + + key = names['ctx'] + if key not in nic_after: + ksft_pr(f"NOTE: DUT {direction}: '{key}' not exposed by " + f"{cfg.ifname}, skipping NIC context count check") + continue + ctx = stat_diff(nic_before, nic_after, key) + ksft_ge(ctx, 1, + comment=f"DUT {direction}: no HW context installed " + f"({key}={ctx})") + + +def check_path(before, after, direction, role, require_hw): + """Require HW for enabled DUT directions; otherwise HW or SW is fine.""" + dev = stat_diff(before, after, f'Tls{direction}Device') + sw = stat_diff(before, after, f'Tls{direction}Sw') + if require_hw: + ksft_ge(dev, 1, + comment=f"{role} {direction}: HW offload not engaged " + f"(Device={dev}, Sw={sw})") + else: + ksft_ge(dev + sw, 1, + comment=f"{role} {direction}: no TLS activity " + f"(Device={dev}, Sw={sw})") + + +def verify_tls_counters(stats_before, stats_after, is_dut, hw_directions=()): + """Verify TLS counters on one side of the connection. + + is_dut: True for the local DUT. + hw_directions: DUT directions with enabled HW offload; other directions + may use SW kTLS but still undergo activity and error checks. + """ + role = 'DUT' if is_dut else 'Peer' + + # Echo mode drives both directions on both sides. + for direction in ('Tx', 'Rx'): + check_path(stats_before, stats_after, direction, role, + require_hw=is_dut and direction in hw_directions) + + ksft_eq(stat_diff(stats_before, stats_after, 'TlsDecryptError'), 0, + comment=f"{role}: TlsDecryptError expected 0") + + +def run_tls_test(cfg, cipher="128", tls_version="1.2", + buffer_size=None, random_max=None, ipver="4", + record_type=None): + """Run the TLS offload test. + + The DUT runs the TLS client and the remote runs the echo server. + + ipver: '4' or '6' - IP version to run over. The C helper is forced to the + matching family with -4/-6 and connects to the peer's v4/v6 address. + Variants requesting '6' skip cleanly when the environment lacks IPv6 + connectivity (require_ipver()). + + The DUT (local) is the kernel under test; the remote is just a traffic + source/sink and may run any kernel without HW offload. Both sides run + kTLS because TLS is pairwise, but verify_tls_counters() requires HW + offload only in enabled DUT directions. The peer and the DUT's other + direction may use SW kTLS. + """ + require_tls_setup(cfg) + + cfg.require_ipver(ipver) + + # Echo exercises both directions, allowing SW in a direction without + # HW support. + hw_directions = tuple(d for d in ('Tx', 'Rx') if d in cfg.tls_hw_directions) + + if record_type and 'Tx' not in hw_directions: + raise KsftSkipEx("Record-type regression requires DUT TLS TX offload") + + port = rand_port() + send_size = random_max or buffer_size + + server_parts = [f"{cfg.bin_remote} server -p {port} -c {cipher}", + f"-v {tls_version}", f"-{ipver}"] + if send_size: + server_parts.append(f"-b {send_size}") + if record_type: + server_parts.append(f"-t {record_type}") + server_cmd = " ".join(server_parts) + + client_parts = [f"{cfg.bin_local} client -s {cfg.remote_addr_v[ipver]}", + f"-p {port} -c {cipher} -v {tls_version} -{ipver}"] + if random_max: + client_parts.append(f"-r {random_max}") + elif buffer_size: + client_parts.append(f"-b {buffer_size}") + if record_type: + client_parts.append(f"-t {record_type}") + client_cmd = " ".join(client_parts) + + stats_before_local = read_tls_stats() + stats_before_remote = read_tls_stats(host=cfg.remote) + nic_before = read_nic_stats(cfg) + + # The remote server runs under bkg(), whose stdout pipe is only drained + # once it exits, so the helper keeps its per-connection output small + # (see the note on verbose in tls_hw_offload.c); do not pass -V. + # + # Both helpers exit on their own within HELPER_TIMEOUT_S (see + # tls_hw_offload.c), so nothing outlives the variant even on failure. + with bkg(server_cmd, host=cfg.remote, exit_wait=True): + wait_port_listen(port, host=cfg.remote) + cmd(client_cmd) + + cfg.wait_hw_stats_settle() + stats_after_local = read_tls_stats() + stats_after_remote = read_tls_stats(host=cfg.remote) + nic_after = read_nic_stats(cfg) + + verify_tls_counters(stats_before_local, stats_after_local, is_dut=True, + hw_directions=hw_directions) + check_hw_crypto(cfg, nic_before, nic_after, hw_directions) + verify_tls_counters(stats_before_remote, stats_after_remote, is_dut=False) + + +# The cipher/version matrix runs over IPv4; the socket setup is the only +# IP-version-specific code path, so a single representative variant over +# IPv6 is enough to cover it (it skips cleanly without v6 connectivity). +# The suites below likewise stay on IPv4 to bound runtime. +@ksft_variants([ + KsftNamedVariant("tls12_aes128", "128", "1.2", "4"), + KsftNamedVariant("tls12_aes256", "256", "1.2", "4"), + KsftNamedVariant("tls12_aes128_ip6", "128", "1.2", "6"), +]) +def test_tls_offload(cfg, cipher, tls_version, ipver): + """Cipher/version matrix over the HW offload data path.""" + run_tls_test(cfg, cipher=cipher, tls_version=tls_version, ipver=ipver) + + +@ksft_variants([ + KsftNamedVariant("small_buf", 512), + KsftNamedVariant("large_buf", 2097152), + KsftNamedVariant("random_buf", None, 8192), +]) +def test_tls_offload_sizes(cfg, buffer_size=None, random_max=None): + """Echo-mode TLS 1.2 across a range of buffer sizes.""" + run_tls_test(cfg, cipher="128", tls_version="1.2", + buffer_size=buffer_size, random_max=random_max) + + +@ksft_variants([ + KsftNamedVariant("handshake", 22), + KsftNamedVariant("alert", 21), +]) +def test_tls_offload_record_type(cfg, record_type): + """RX setup must preserve the HW TX hook which flushes an open record.""" + run_tls_test(cfg, record_type=record_type) + + +def main() -> None: + """Set up the DUT/peer environment and run the offload test suites.""" + with NetDrvEpEnv(__file__, nsim_test=False) as cfg: + cfg.bin_local = cfg.test_dir / "tls_hw_offload" + cfg.bin_remote = None + cfg.tls_skip_reason = None + + ksft_run([test_tls_offload, test_tls_offload_sizes, + test_tls_offload_record_type], args=(cfg, )) + ksft_exit() + + +if __name__ == "__main__": + main() diff --git a/tools/testing/selftests/drivers/net/ping.py b/tools/testing/selftests/drivers/net/ping.py index da3623c5e8a9..a0de9a98d906 100755 --- a/tools/testing/selftests/drivers/net/ping.py +++ b/tools/testing/selftests/drivers/net/ping.py @@ -7,7 +7,7 @@ from lib.py import ksft_run, ksft_exit from lib.py import ksft_eq, KsftSkipEx, KsftFailEx from lib.py import EthtoolFamily, NetDrvEpEnv from lib.py import bkg, cmd, wait_port_listen, rand_port -from lib.py import defer, ethtool, ip +from lib.py import bpf_map_set, defer, ethtool, ip no_sleep=False @@ -75,16 +75,23 @@ def _set_xdp_generic_sb_on(cfg) -> None: if no_sleep != True: time.sleep(10) -def _set_xdp_generic_mb_on(cfg) -> None: - prog = cfg.net_lib_dir / "xdp_dummy.bpf.o" +def _set_xdp_generic_mb_on(cfg, prog="xdp_dummy.bpf.o", on_attach=None) -> None: + prog = cfg.net_lib_dir / prog cmd(f"ip link set dev {cfg.remote_ifname} mtu 9000", shell=True, host=cfg.remote) defer(ip, f"link set dev {cfg.remote_ifname} mtu 1500", host=cfg.remote) ip("link set dev %s mtu 9000 xdpgeneric obj %s sec xdp.frags" % (cfg.ifname, prog)) defer(ip, f"link set dev {cfg.ifname} mtu 1500 xdpgeneric off") + if on_attach: + on_attach() if no_sleep != True: time.sleep(10) +def _set_xdp_generic_cpumap_mb_on(cfg) -> None: + cfg.require_cmd("bpftool") + _set_xdp_generic_mb_on(cfg, "xdp_cpumap.bpf.o", + on_attach=lambda: bpf_map_set("map_cpumap", 0, 2048)) + def _set_xdp_native_sb_on(cfg) -> None: prog = cfg.net_lib_dir / "xdp_dummy.bpf.o" cmd(f"ip link set dev {cfg.remote_ifname} mtu 1500", shell=True, host=cfg.remote) @@ -192,6 +199,19 @@ def test_xdp_generic_mb(cfg, netnl) -> None: _test_v6(cfg) _test_tcp(cfg) +def test_xdp_generic_cpumap_mb(cfg, netnl) -> None: + """Redirect all packets to a cpumap from a generic xdp.frags program.""" + _schedule_checksum_reset(cfg, netnl) + _set_xdp_generic_cpumap_mb_on(cfg) + _set_offload_checksum(cfg, netnl, "off") + _test_v4(cfg) + _test_v6(cfg) + _test_tcp(cfg) + _set_offload_checksum(cfg, netnl, "on") + _test_v4(cfg) + _test_v6(cfg) + _test_tcp(cfg) + def test_xdp_native_sb(cfg, netnl) -> None: _schedule_checksum_reset(cfg, netnl) _set_xdp_native_sb_on(cfg) @@ -230,6 +250,7 @@ def main() -> None: test_default_v6, test_xdp_generic_sb, test_xdp_generic_mb, + test_xdp_generic_cpumap_mb, test_xdp_native_sb, test_xdp_native_mb, test_xdp_offload], diff --git a/tools/testing/selftests/drivers/net/psp.py b/tools/testing/selftests/drivers/net/psp.py index 473500901879..c114d2245135 100755 --- a/tools/testing/selftests/drivers/net/psp.py +++ b/tools/testing/selftests/drivers/net/psp.py @@ -120,6 +120,26 @@ def _check_data_rx(cfg, exp_len): ksft_eq(read_len, exp_len) +def _recv_careful(s, target, timeout=2): + """Read exactly target bytes, tolerating short reads""" + data = b'' + end = time.monotonic() + timeout + while time.monotonic() < end: + try: + data += s.recv(target - len(data), socket.MSG_DONTWAIT) + if len(data) == target: + return data + except BlockingIOError: + time.sleep(0.001) + raise KsftFailEx(f"short read, got {len(data)} of {target} bytes") + + +def _req_echo(cfg, s): + """Ask the peer to echo, and check the reply arrives intact""" + _send_with_ack(cfg, b'data echo\0') + ksft_eq(_recv_careful(s, 5), b'echo\0') + + def _check_data_outq(s, exp_len, force_wait=False): outq = 0 for _ in range(10): @@ -478,6 +498,7 @@ def _data_basic_send(cfg, version, ipver): data_len = _send_careful(cfg, s, 100) _check_data_rx(cfg, data_len) + _req_echo(cfg, s) _close_psp_conn(cfg, s) @@ -726,6 +747,7 @@ def _data_basic_send_netkit_psp_assoc(cfg, version, ipver): data_len = _send_careful(cfg, sock, 100) _check_data_rx(cfg, data_len) + _req_echo(cfg, sock) _close_psp_conn(cfg, sock) diff --git a/tools/testing/selftests/fchmodat2/Makefile b/tools/testing/selftests/fchmodat2/Makefile index 4373cea79b79..21f6b0b0cdc8 100644 --- a/tools/testing/selftests/fchmodat2/Makefile +++ b/tools/testing/selftests/fchmodat2/Makefile @@ -1,15 +1,23 @@ # SPDX-License-Identifier: GPL-2.0-or-later -CFLAGS += -Wall -O2 -g -fsanitize=address -fsanitize=undefined $(KHDR_INCLUDES) +CFLAGS += -Wall -O2 -g $(KHDR_INCLUDES) + +TEST_GEN_PROGS := fchmodat2_test + +include ../lib.mk # gcc requires -static-libasan in order to ensure that Address Sanitizer's # library is the first one loaded. However, clang already statically links the # Address Sanitizer if -fsanitize is specified. Therefore, simply omit # -static-libasan for clang builds. +SANITIZER_CFLAGS := -fsanitize=address -fsanitize=undefined ifeq ($(LLVM),) - CFLAGS += -static-libasan + SANITIZER_CFLAGS += -static-libasan endif -TEST_GEN_PROGS := fchmodat2_test - -include ../lib.mk +# Build without the sanitizers when the toolchain cannot link them. +ifeq ($(shell echo 'int main(void) { return 0; }' | $(CC) $(CFLAGS) \ + $(SANITIZER_CFLAGS) $(LDFLAGS) -x c - -o /dev/null >/dev/null 2>&1 && \ + echo y),y) +CFLAGS += $(SANITIZER_CFLAGS) +endif diff --git a/tools/testing/selftests/filesystems/fat/run_fat_tests.sh b/tools/testing/selftests/filesystems/fat/run_fat_tests.sh index d61264d4795d..0712c8d23fd7 100755 --- a/tools/testing/selftests/filesystems/fat/run_fat_tests.sh +++ b/tools/testing/selftests/filesystems/fat/run_fat_tests.sh @@ -15,6 +15,8 @@ BASE_DIR="$(dirname $0)" TMP_DIR="$(mktemp -d /tmp/fat_tests_tmp.XXXXXX)" IMG_PATH="${TMP_DIR}/fat.img" MNT_PATH="${TMP_DIR}/mnt" +# Kselftest framework requirement - SKIP code is 4. +ksft_skip=4 cleanup() { @@ -23,6 +25,17 @@ cleanup() } trap cleanup SIGINT SIGTERM EXIT +check_prereqs() +{ + local msg="skip all tests:" + local uid=$(id -u) + + if [ $uid -ne 0 ]; then + echo $msg must be run as root >&2 + exit $ksft_skip + fi +} + create_loopback() { touch "${IMG_PATH}" @@ -73,6 +86,7 @@ unmount_image() sudo umount "${MNT_PATH}" &> /dev/null } +check_prereqs create_loopback mount_image rename_exchange_test diff --git a/tools/testing/selftests/filesystems/mount-notify/mount-notify_test.c b/tools/testing/selftests/filesystems/mount-notify/mount-notify_test.c index 6381af6a40e3..6c95c275b162 100644 --- a/tools/testing/selftests/filesystems/mount-notify/mount-notify_test.c +++ b/tools/testing/selftests/filesystems/mount-notify/mount-notify_test.c @@ -337,18 +337,18 @@ TEST_F(fanotify, fsmount) fs = fsopen("tmpfs", 0); ASSERT_GE(fs, 0); - ret = fsconfig(fs, FSCONFIG_CMD_CREATE, 0, 0, 0); + ret = fsconfig(fs, FSCONFIG_CMD_CREATE, 0, 0, 0); ASSERT_EQ(ret, 0); - mnt = fsmount(fs, 0, 0); + mnt = fsmount(fs, 0, 0); ASSERT_GE(mnt, 0); - close(fs); + close(fs); ret = move_mount(mnt, "", AT_FDCWD, "/a", MOVE_MOUNT_F_EMPTY_PATH); ASSERT_EQ(ret, 0); - close(mnt); + close(mnt); mnts[1] = expect_notify_mask(_metadata, self, FAN_MNT_ATTACH); ASSERT_NE(mnts[0], mnts[1]); diff --git a/tools/testing/selftests/filesystems/openat2/Makefile b/tools/testing/selftests/filesystems/openat2/Makefile index d848aac96bde..2f712dfcbf75 100644 --- a/tools/testing/selftests/filesystems/openat2/Makefile +++ b/tools/testing/selftests/filesystems/openat2/Makefile @@ -1,17 +1,25 @@ # SPDX-License-Identifier: GPL-2.0-or-later CFLAGS += $(KHDR_INCLUDES) -CFLAGS += -Wall -O2 -g -fsanitize=address -fsanitize=undefined $(TOOLS_INCLUDES) +CFLAGS += -Wall -O2 -g $(TOOLS_INCLUDES) TEST_GEN_PROGS := openat2_test resolve_test rename_attack_test emptypath_test +LOCAL_HDRS += helpers.h + +include ../../lib.mk + # gcc requires -static-libasan in order to ensure that Address Sanitizer's # library is the first one loaded. However, clang already statically links the # Address Sanitizer if -fsanitize is specified. Therefore, simply omit # -static-libasan for clang builds. +SANITIZER_CFLAGS := -fsanitize=address -fsanitize=undefined ifeq ($(LLVM),) - CFLAGS += -static-libasan + SANITIZER_CFLAGS += -static-libasan endif -LOCAL_HDRS += helpers.h - -include ../../lib.mk +# Build without the sanitizers when the toolchain cannot link them. +ifeq ($(shell echo 'int main(void) { return 0; }' | $(CC) $(CFLAGS) \ + $(SANITIZER_CFLAGS) $(LDFLAGS) -x c - -o /dev/null >/dev/null 2>&1 && \ + echo y),y) +CFLAGS += $(SANITIZER_CFLAGS) +endif diff --git a/tools/testing/selftests/filesystems/overlayfs/idmapped_mounts.c b/tools/testing/selftests/filesystems/overlayfs/idmapped_mounts.c index 44a75839f4ed..5df42cf3e688 100644 --- a/tools/testing/selftests/filesystems/overlayfs/idmapped_mounts.c +++ b/tools/testing/selftests/filesystems/overlayfs/idmapped_mounts.c @@ -498,4 +498,49 @@ TEST_F(idmapped_overlay, nfs_export_handles) EXPECT_EQ(close(ovl), 0); } +/* With index=on, same-superblock lower layers must not use different idmaps. */ +TEST_F(idmapped_overlay, reject_same_sb_mixed_idmaps) +{ + char lower1[PATH_MAX], lower2[PATH_MAX]; + char upper[PATH_MAX], work[PATH_MAX]; + int fd_lower1, fd_lower2, fsfd; + + if (!ovl_supported()) + SKIP(return, "overlayfs not supported"); + + snprintf(lower1, sizeof(lower1), "%s/l", self->base); + snprintf(lower2, sizeof(lower2), "%s/l2", self->base); + snprintf(upper, sizeof(upper), "%s/u", self->base); + snprintf(work, sizeof(work), "%s/w", self->base); + ASSERT_EQ(mkdir(lower2, 0755), 0); + ASSERT_EQ(chown(lower2, ID_HOST, ID_HOST), 0); + + fd_lower1 = idmapped_layer_fd(lower1, ID_HOST, ID_NS, ID_RANGE); + ASSERT_GE(fd_lower1, 0); + fd_lower2 = sys_open_tree(AT_FDCWD, lower2, + OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC); + ASSERT_GE(fd_lower2, 0); + fsfd = sys_fsopen("overlay", 0); + ASSERT_GE(fsfd, 0); + ASSERT_EQ(sys_fsconfig(fsfd, FSCONFIG_SET_STRING, + "source", "test", 0), 0); + ASSERT_EQ(sys_fsconfig(fsfd, FSCONFIG_SET_STRING, + "upperdir", upper, 0), 0); + ASSERT_EQ(sys_fsconfig(fsfd, FSCONFIG_SET_STRING, + "workdir", work, 0), 0); + ASSERT_EQ(sys_fsconfig(fsfd, FSCONFIG_SET_STRING, + "index", "on", 0), 0); + ASSERT_EQ(sys_fsconfig(fsfd, FSCONFIG_SET_FD, + "lowerdir+", NULL, fd_lower1), 0); + ASSERT_EQ(sys_fsconfig(fsfd, FSCONFIG_SET_FD, + "lowerdir+", NULL, fd_lower2), 0); + + errno = 0; + EXPECT_EQ(sys_fsconfig(fsfd, FSCONFIG_CMD_CREATE, NULL, NULL, 0), -1); + EXPECT_EQ(errno, EINVAL); + EXPECT_EQ(close(fd_lower1), 0); + EXPECT_EQ(close(fd_lower2), 0); + EXPECT_EQ(close(fsfd), 0); +} + TEST_HARNESS_MAIN diff --git a/tools/testing/selftests/filesystems/statmount/statmount_test.c b/tools/testing/selftests/filesystems/statmount/statmount_test.c index b237a95ec9fb..8133a5841ac0 100644 --- a/tools/testing/selftests/filesystems/statmount/statmount_test.c +++ b/tools/testing/selftests/filesystems/statmount/statmount_test.c @@ -335,10 +335,10 @@ static void test_statmount_sb_basic(void) return; } - if (sm.sb_magic != sf.f_type) { + if (sm.sb_magic != (unsigned long)sf.f_type) { ksft_test_result_fail("unexpected sb magic: 0x%llx != 0x%lx\n", (unsigned long long) sm.sb_magic, - sf.f_type); + (unsigned long) sf.f_type); return; } diff --git a/tools/testing/selftests/filesystems/statmount/statmount_test_ns.c b/tools/testing/selftests/filesystems/statmount/statmount_test_ns.c index e500905e4c07..c9ef755ffaa7 100644 --- a/tools/testing/selftests/filesystems/statmount/statmount_test_ns.c +++ b/tools/testing/selftests/filesystems/statmount/statmount_test_ns.c @@ -240,8 +240,9 @@ static int validate_external_listmount(pid_t pid, uint64_t child_nr_mounts) } if (nr_mounts != child_nr_mounts) { - ksft_print_msg("listmount results is %zi != %zi\n", nr_mounts, - child_nr_mounts); + ksft_print_msg("listmount results is %llu != %llu\n", + (unsigned long long)nr_mounts, + (unsigned long long)child_nr_mounts); return NSID_FAIL; } diff --git a/tools/testing/selftests/ftrace/test.d/dynevent/fprobe_syntax_errors.tc b/tools/testing/selftests/ftrace/test.d/dynevent/fprobe_syntax_errors.tc index 384209968325..70751573e8de 100644 --- a/tools/testing/selftests/ftrace/test.d/dynevent/fprobe_syntax_errors.tc +++ b/tools/testing/selftests/ftrace/test.d/dynevent/fprobe_syntax_errors.tc @@ -33,7 +33,7 @@ check_error 'f vfs_read ^$stack10000' # BAD_STACK_NUM check_error 'f vfs_read ^$arg10000' # BAD_ARG_NUM -if !grep -q 'kernel return probes support:' README; then +if ! grep -q 'kernel return probes support:' README; then check_error 'f vfs_read $retval ^$arg1' # BAD_VAR fi check_error 'f vfs_read ^$none_var' # BAD_VAR @@ -100,7 +100,7 @@ if grep -q "<argname>" README; then check_error 'f vfs_read args=^$arg*' # BAD_VAR_ARGS check_error 'f vfs_read +0(^$arg*)' # BAD_VAR_ARGS check_error 'f vfs_read $arg* ^$arg*' # DOUBLE_ARGS -if !grep -q 'kernel return probes support:' README; then +if ! grep -q 'kernel return probes support:' README; then check_error 'f vfs_read%return ^$arg*' # NOFENTRY_ARGS fi check_error 'f vfs_read ^hoge' # NO_BTFARG diff --git a/tools/testing/selftests/ftrace/test.d/kprobe/kprobe_non_uniq_symbol.tc b/tools/testing/selftests/ftrace/test.d/kprobe/kprobe_non_uniq_symbol.tc index 03eb9e70b438..f8e18ea8c268 100644 --- a/tools/testing/selftests/ftrace/test.d/kprobe/kprobe_non_uniq_symbol.tc +++ b/tools/testing/selftests/ftrace/test.d/kprobe/kprobe_non_uniq_symbol.tc @@ -6,7 +6,7 @@ SYMBOL='init_once' # We skip this test on kernel where SYMBOL is unique or does not exist. -if [ "$(grep -c -E "[[:alnum:]]+ t ${SYMBOL}$" /proc/kallsyms)" -le '1' ]; then +if [ "$(grep -c -E "[[:alnum:]]+ t ${SYMBOL}\$" /proc/kallsyms)" -le '1' ]; then exit_unsupported fi diff --git a/tools/testing/selftests/ftrace/test.d/kprobe/kprobe_syntax_errors.tc b/tools/testing/selftests/ftrace/test.d/kprobe/kprobe_syntax_errors.tc index b0e6b80ccb01..06efa67e01ff 100644 --- a/tools/testing/selftests/ftrace/test.d/kprobe/kprobe_syntax_errors.tc +++ b/tools/testing/selftests/ftrace/test.d/kprobe/kprobe_syntax_errors.tc @@ -108,7 +108,7 @@ if grep -q "<argname>" README; then check_error 'p vfs_read args=^$arg*' # BAD_VAR_ARGS check_error 'p vfs_read +0(^$arg*)' # BAD_VAR_ARGS check_error 'p vfs_read $arg* ^$arg*' # DOUBLE_ARGS -if !grep -q 'kernel return probes support:' README; then +if ! grep -q 'kernel return probes support:' README; then check_error 'r vfs_read ^$arg*' # NOFENTRY_ARGS fi check_error 'p vfs_read+20 ^$arg*' # NOFENTRY_ARGS diff --git a/tools/testing/selftests/landlock/ns_test.c b/tools/testing/selftests/landlock/ns_test.c index f5d4b86edd30..8f387fc47e21 100644 --- a/tools/testing/selftests/landlock/ns_test.c +++ b/tools/testing/selftests/landlock/ns_test.c @@ -1899,8 +1899,9 @@ TEST(setns_inherited_fd) 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=0$"; + " blockers=namespace\\.use namespace_type=0x%x namespace_id=[1-9][0-9]*$"; char log_match[sizeof(log_template) + 10]; int log_match_len; @@ -2538,7 +2539,9 @@ static void test_ns_trace_denial(struct __test_metadata *const _metadata, ASSERT_EQ(0, tracefs_extract_field( buf, REGEX_DENY_PERMISSION_NAMESPACE(TRACE_TASK), "namespace_id", field, sizeof(field))); - EXPECT_EQ(use_setns ? expected_ns_id : 0, strtoull(field, NULL, 10)); + EXPECT_STRNE("0", field); + if (use_setns) + EXPECT_EQ(expected_ns_id, strtoull(field, NULL, 10)); free(buf); } diff --git a/tools/testing/selftests/lib.mk b/tools/testing/selftests/lib.mk index 881f13ee2c8a..506cb26510e4 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/mount_setattr/Makefile b/tools/testing/selftests/mount_setattr/Makefile index 4d4f810cdf2c..2e5b16fcdf10 100644 --- a/tools/testing/selftests/mount_setattr/Makefile +++ b/tools/testing/selftests/mount_setattr/Makefile @@ -1,6 +1,6 @@ # SPDX-License-Identifier: GPL-2.0 # Makefile for mount selftests. -CFLAGS = -g $(KHDR_INCLUDES) -Wall -O2 -pthread +CFLAGS = -g $(KHDR_INCLUDES) -Wall -O2 -pthread -D_FILE_OFFSET_BITS=64 LOCAL_HDRS += ../filesystems/wrappers.h diff --git a/tools/testing/selftests/net/.gitignore b/tools/testing/selftests/net/.gitignore index 21412510ac26..27761239d069 100644 --- a/tools/testing/selftests/net/.gitignore +++ b/tools/testing/selftests/net/.gitignore @@ -21,6 +21,7 @@ log.txt msg_zerocopy netlink-dumps nettest +nsh_gso proc_net_pktgen psock_fanout psock_snd @@ -34,6 +35,7 @@ reuseport_bpf_numa reuseport_dualstack rxtimestamp sctp_hello +sctp_ifwdtsn sk_bind_sendto_listen sk_connect_zero_addr sk_so_peek_off diff --git a/tools/testing/selftests/net/Makefile b/tools/testing/selftests/net/Makefile index 9180b9bec515..baea3e7f0f8f 100644 --- a/tools/testing/selftests/net/Makefile +++ b/tools/testing/selftests/net/Makefile @@ -76,6 +76,7 @@ TEST_PROGS := \ nk_qlease.py \ nl_netdev.py \ nl_nlctrl.py \ + nsh_gso.sh \ pmtu.sh \ protodown.sh \ psock_snd.sh \ @@ -90,6 +91,7 @@ TEST_PROGS := \ run_afpackettests \ run_netsocktests \ rxtimestamp.sh \ + sctp_ifwdtsn.sh \ sctp_vrf.sh \ skf_net_off.sh \ srv6_encap_lookup_l3vpn_test.sh \ @@ -156,6 +158,7 @@ TEST_GEN_FILES := \ ipv6_flowlabel \ msg_zerocopy \ nettest \ + nsh_gso \ psock_fanout \ psock_snd \ psock_tpacket \ @@ -163,6 +166,7 @@ TEST_GEN_FILES := \ reuseport_addr_any \ rxtimestamp \ sctp_hello \ + sctp_ifwdtsn \ skf_net_off \ so_netns_cookie \ so_rcv_listener \ diff --git a/tools/testing/selftests/net/cmsg_sender.c b/tools/testing/selftests/net/cmsg_sender.c index 67a72b1a2f3d..035ab54c1be5 100644 --- a/tools/testing/selftests/net/cmsg_sender.c +++ b/tools/testing/selftests/net/cmsg_sender.c @@ -34,6 +34,7 @@ enum { ERN_CMSG_RD, ERN_CMSG_RCV, ERN_SEND_MORE, + ERN_CONNECT, }; struct option_cmsg_u32 { @@ -48,6 +49,7 @@ struct options { unsigned int size; unsigned int num_pkt; bool msg_more; + bool connected; struct { unsigned int mark; unsigned int dontfrag; @@ -93,6 +95,7 @@ static void __attribute__((noreturn)) cs_usage(const char *bin) printf("Usage: %s [opts] <dst host> <dst port / service>\n", bin); printf("Options:\n" "\t\t-s Silent send() failures\n" + "\t\t-k Connect before sending\n" "\t\t-S send() size\n" "\t\t-4/-6 Force IPv4 / IPv6 only\n" "\t\t-p prot Socket protocol\n" @@ -121,8 +124,12 @@ static void cs_parse_args(int argc, char *argv[]) { int o; - while ((o = getopt(argc, argv, "46sS:p:P:m:M:n:d:tf:F:c:C:l:L:H:Q:")) != -1) { + while ((o = getopt(argc, argv, + "46ksS:p:P:m:M:n:d:tf:F:c:C:l:L:H:Q:")) != -1) { switch (o) { + case 'k': + opt.connected = true; + break; case 's': opt.silent_send = true; break; @@ -521,6 +528,12 @@ int main(int argc, char *argv[]) ca_set_sockopts(fd); + if (opt.connected && connect(fd, ai->ai_addr, ai->ai_addrlen)) { + fprintf(stderr, "Can't connect socket: %s\n", strerror(errno)); + err = ERN_CONNECT; + goto err_out; + } + if (clock_gettime(CLOCK_REALTIME, &time_start_real)) error(ERN_GETTIME, errno, "gettime REALTIME"); if (clock_gettime(CLOCK_MONOTONIC, &time_start_mono)) @@ -530,8 +543,10 @@ int main(int argc, char *argv[]) iov[0].iov_len = opt.size; memset(&msg, 0, sizeof(msg)); - msg.msg_name = ai->ai_addr; - msg.msg_namelen = ai->ai_addrlen; + if (!opt.connected) { + msg.msg_name = ai->ai_addr; + msg.msg_namelen = ai->ai_addrlen; + } msg.msg_iov = iov; msg.msg_iovlen = 1; diff --git a/tools/testing/selftests/net/cmsg_so_mark.sh b/tools/testing/selftests/net/cmsg_so_mark.sh index 772ad0cc2630..341abfc7ad8e 100755 --- a/tools/testing/selftests/net/cmsg_so_mark.sh +++ b/tools/testing/selftests/net/cmsg_so_mark.sh @@ -68,6 +68,28 @@ for ovr in setsock cmsg both; do done done +# Reject an explicit zero mark while leaving the socket mark allowed. +ip -netns "$NS" rule add fwmark 0/0xffffffff lookup 300 || exit 1 +ip -6 -netns "$NS" rule add fwmark 0/0xffffffff lookup 300 || exit 1 + +# Check per-message marks after connect() has populated the route cache. +for i in 4 6; do + [ "$i" = 4 ] && TGT=$TGT4 || TGT=$TGT6 + + for p in u i r; do + for mark in "$((MARK + 1))" "$MARK" 0; do + expected=0 + if [ "$mark" -eq "$MARK" ] || [ "$mark" -eq 0 ]; then + expected=1 + fi + + ip netns exec "$NS" ./cmsg_sender -"$i" -p "$p" -k \ + -M "$((MARK + 1))" -m "$mark" -s "$TGT" 1234 + check_result "$?" "$expected" "IPv$i $p connected mark $mark" + done + done +done + # Summary if [ $BAD -ne 0 ]; then echo "FAIL - $BAD/$TOTAL cases failed" diff --git a/tools/testing/selftests/net/config b/tools/testing/selftests/net/config index d4416f8bdcfd..3e7ce41bd64d 100644 --- a/tools/testing/selftests/net/config +++ b/tools/testing/selftests/net/config @@ -99,6 +99,7 @@ CONFIG_NET_IPVTI=y CONFIG_NETKIT=y CONFIG_NET_L3_MASTER_DEV=y CONFIG_NET_NS=y +CONFIG_NET_NSH=m CONFIG_NET_PKTGEN=m CONFIG_NET_SCH_ETF=m CONFIG_NET_SCH_FQ=m diff --git a/tools/testing/selftests/net/fib_tests.sh b/tools/testing/selftests/net/fib_tests.sh index 7c47d7fe250d..d7ac3c727f70 100755 --- a/tools/testing/selftests/net/fib_tests.sh +++ b/tools/testing/selftests/net/fib_tests.sh @@ -406,10 +406,50 @@ fib_carrier_unicast_test() cleanup } +fib_carrier_gw_test() +{ + echo + echo "Gateway validation with carrier down" + + setup + + set -e + $NS_EXEC sysctl -qw net.ipv4.conf.dummy0.ignore_routes_with_linkdown=1 + $NS_EXEC sysctl -qw net.ipv6.conf.dummy0.ignore_routes_with_linkdown=1 + $IP link set dev dummy0 carrier off + sleep 1 + set +e + + $IP route add 203.0.113.0/25 via 198.51.100.2 dev dummy0 &> /dev/null + log_test $? 0 "IPv4 route in main table" + $IP -6 route add 2001:db8:10::/64 via 2001:db8:1::2 dev dummy0 &> /dev/null + log_test $? 0 "IPv6 route in main table" + + $IP route add 203.0.113.0/25 table 100 via 198.51.100.2 dev dummy0 &> /dev/null + log_test $? 0 "IPv4 route in non-main table" + $IP -6 route add 2001:db8:10::/64 table 100 via 2001:db8:1::2 dev dummy0 &> /dev/null + log_test $? 0 "IPv6 route in non-main table" + + $IP route add 203.0.113.128/25 table 100 via 198.51.100.2 &> /dev/null + log_test $? 0 "IPv4 route in non-main table without device" + $IP -6 route add 2001:db8:11::/64 table 100 via 2001:db8:1::2 &> /dev/null + log_test $? 0 "IPv6 route in non-main table without device" + + $IP route show table 100 203.0.113.0/25 | \ + grep -q "linkdown" + log_test $? 0 "IPv4 linkdown flag set" + $IP -6 route show table 100 2001:db8:10::/64 | \ + grep -q "linkdown" + log_test $? 0 "IPv6 linkdown flag set" + + cleanup +} + fib_carrier_test() { fib_carrier_local_test fib_carrier_unicast_test + fib_carrier_gw_test } fib_rp_filter_test() diff --git a/tools/testing/selftests/net/lib/xdp_cpumap.bpf.c b/tools/testing/selftests/net/lib/xdp_cpumap.bpf.c new file mode 100644 index 000000000000..150352343114 --- /dev/null +++ b/tools/testing/selftests/net/lib/xdp_cpumap.bpf.c @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include <linux/bpf.h> +#include <bpf/bpf_helpers.h> + +struct { + __uint(type, BPF_MAP_TYPE_CPUMAP); + __uint(max_entries, 1); + __type(key, __u32); + __type(value, __u32); +} map_cpumap SEC(".maps"); + +SEC("xdp.frags") +int xdp_cpumap_prog_frags(struct xdp_md *ctx) +{ + return bpf_redirect_map(&map_cpumap, 0, XDP_DROP); +} + +char _license[] SEC("license") = "GPL"; diff --git a/tools/testing/selftests/net/nsh_gso.c b/tools/testing/selftests/net/nsh_gso.c new file mode 100644 index 000000000000..9acd3f755723 --- /dev/null +++ b/tools/testing/selftests/net/nsh_gso.c @@ -0,0 +1,126 @@ +// SPDX-License-Identifier: GPL-2.0 +/* Send one TCPv4 GSO packet encapsulated in a stack of NSH headers, + * through a packet socket with PACKET_VNET_HDR. + * + * Usage: nsh_gso <ifname> <number of NSH headers> + * + * The packet is made of 4 segments. The send() result is not checked: + * the caller looks at the device counters. + */ + +#include <arpa/inet.h> +#include <errno.h> +#include <error.h> +#include <linux/if_ether.h> +#include <linux/if_packet.h> +#include <linux/ip.h> +#include <linux/tcp.h> +#include <linux/virtio_net.h> +#include <net/if.h> +#include <stdint.h> +#include <stdlib.h> +#include <string.h> +#include <sys/socket.h> +#include <unistd.h> + +#ifndef ETH_P_NSH +#define ETH_P_NSH 0x894F +#endif + +#define NSH_HLEN 8 /* base header + service path header */ +#define NSH_MD_TYPE2 2 /* no mandatory context header */ +#define NSH_NP_IPV4 1 +#define NSH_NP_NSH 4 + +#define GSO_SIZE 500 +#define NR_SEGS 4 + +struct nsh_base { + __be16 ver_flags_ttl_len; + __u8 mdtype; + __u8 np; + __be32 path_hdr; +}; + +int main(int argc, char **argv) +{ + unsigned int depth, hlen, len, i; + struct sockaddr_ll addr = {}; + struct virtio_net_hdr *vnet; + struct nsh_base *nsh; + struct ethhdr *eth; + struct tcphdr *tcp; + int fd, one = 1; + struct iphdr *ip; + char *buf; + + if (argc != 3) + error(1, 0, "usage: %s <ifname> <depth>", argv[0]); + + depth = strtoul(argv[2], NULL, 0); + hlen = sizeof(*eth) + depth * NSH_HLEN + sizeof(*ip) + sizeof(*tcp); + if (!depth || hlen > UINT16_MAX) + error(1, 0, "invalid depth %u", depth); + len = sizeof(*vnet) + hlen + NR_SEGS * GSO_SIZE; + + buf = calloc(1, len); + if (!buf) + error(1, errno, "calloc"); + + vnet = (void *)buf; + vnet->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM; + vnet->gso_type = VIRTIO_NET_HDR_GSO_TCPV4; + vnet->hdr_len = hlen; + vnet->gso_size = GSO_SIZE; + vnet->csum_start = hlen - sizeof(*tcp); + vnet->csum_offset = __builtin_offsetof(struct tcphdr, check); + + eth = (void *)(vnet + 1); + memset(eth->h_dest, 0xff, ETH_ALEN); + eth->h_source[0] = 0x02; + eth->h_proto = htons(ETH_P_NSH); + + nsh = (void *)(eth + 1); + for (i = 0; i < depth; i++, nsh++) { + /* version 0, ttl 63, length in 4 byte words */ + nsh->ver_flags_ttl_len = htons(63 << 6 | NSH_HLEN / 4); + nsh->mdtype = NSH_MD_TYPE2; + nsh->np = i == depth - 1 ? NSH_NP_IPV4 : NSH_NP_NSH; + nsh->path_hdr = htonl(1 << 8 | 255); + } + + ip = (void *)nsh; + ip->version = 4; + ip->ihl = 5; + ip->ttl = 64; + ip->protocol = IPPROTO_TCP; + ip->saddr = htonl(0xc0000201); /* 192.0.2.1 */ + ip->daddr = htonl(0xc0000202); /* 192.0.2.2 */ + + tcp = (void *)(ip + 1); + tcp->source = htons(1234); + tcp->dest = htons(5678); + tcp->doff = 5; + tcp->ack = 1; + + fd = socket(AF_PACKET, SOCK_RAW, 0); + if (fd < 0) + error(1, errno, "socket"); + if (setsockopt(fd, SOL_PACKET, PACKET_VNET_HDR, &one, sizeof(one))) + error(1, errno, "setsockopt PACKET_VNET_HDR"); + + addr.sll_family = AF_PACKET; + addr.sll_protocol = htons(ETH_P_NSH); + addr.sll_ifindex = if_nametoindex(argv[1]); + if (!addr.sll_ifindex) + error(1, errno, "if_nametoindex %s", argv[1]); + + /* A packet dropped at segmentation time is reported as an error, + * this is expected for deep stacks. + */ + sendto(fd, buf, len, 0, (void *)&addr, sizeof(addr)); + + close(fd); + free(buf); + return 0; +} diff --git a/tools/testing/selftests/net/nsh_gso.sh b/tools/testing/selftests/net/nsh_gso.sh new file mode 100755 index 000000000000..d0746cf1d528 --- /dev/null +++ b/tools/testing/selftests/net/nsh_gso.sh @@ -0,0 +1,71 @@ +#!/bin/bash +# SPDX-License-Identifier: GPL-2.0 +# +# Check software GSO of NSH packets: a TCP GSO packet behind a few NSH +# headers is segmented, and a deep stack of NSH headers is dropped +# instead of recursing in nsh_gso_segment() for each of them. + +source lib.sh + +NR_SEGS=4 +ret=0 + +cleanup() +{ + cleanup_ns $ns1 +} + +tx_packets() +{ + ip netns exec $ns1 cat /sys/class/net/dummy0/statistics/tx_packets +} + +# $1: number of NSH headers, $2: expected number of transmitted packets +check_nsh_gso() +{ + local depth=$1 + local expected=$2 + local before + local sent + + before=$(tx_packets) + ip netns exec $ns1 ./nsh_gso dummy0 $depth + sent=$(($(tx_packets) - before)) + + if [ $sent -eq $expected ]; then + echo "PASS: $depth NSH headers: $sent packets sent" + else + echo "FAIL: $depth NSH headers: $sent packets sent, expected $expected" + ret=1 + fi +} + +modprobe -q nsh +nsh_loaded=$? + +trap cleanup EXIT +setup_ns ns1 || exit $ksft_skip + +ip -netns $ns1 link add dummy0 type dummy +ip -netns $ns1 link set dummy0 up +# No IPv6 autoconf traffic on the device, to get stable counters. +ip netns exec $ns1 sysctl -qw net.ipv6.conf.dummy0.disable_ipv6=1 +# Force software segmentation in validate_xmit_skb(). +ip netns exec $ns1 ethtool -K dummy0 tso off >/dev/null || exit $ksft_skip + +before=$(tx_packets) +ip netns exec $ns1 ./nsh_gso dummy0 1 +if [ $(($(tx_packets) - before)) -eq 0 ] && [ $nsh_loaded -ne 0 ]; then + echo "SKIP: NSH GSO not available" + exit $ksft_skip +fi + +check_nsh_gso 1 $NR_SEGS +# The recursion limit is shared with the inner IPv4 header. +check_nsh_gso 4 $NR_SEGS +check_nsh_gso 5 0 +check_nsh_gso 64 0 +# The largest stack that fits in a 64KB header. +check_nsh_gso 8000 0 + +exit $ret diff --git a/tools/testing/selftests/net/packetdrill/tcp_fastopen_client_defer-connect.pkt b/tools/testing/selftests/net/packetdrill/tcp_fastopen_client_defer-connect.pkt new file mode 100644 index 000000000000..e90df498d935 --- /dev/null +++ b/tools/testing/selftests/net/packetdrill/tcp_fastopen_client_defer-connect.pkt @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: GPL-2.0 +// +// Test that a TCP_FASTOPEN_CONNECT socket in DEFER_CONNECT state +// ignores inbound TCP segments and ICMP errors before SYN is sent. +// +`./defaults.sh + ./set_sysctls.py /proc/sys/net/ipv4/tcp_timestamps=0` + +// Cache warmup: send a Fast Open cookie request + 0 socket(..., SOCK_STREAM|SOCK_NONBLOCK, IPPROTO_TCP) = 3 + +0 sendto(3, ..., 0, MSG_FASTOPEN, ..., ...) = -1 EINPROGRESS (Operation is now in progress) + +0 > S 0:0(0) <mss 1460,nop,nop,sackOK,nop,wscale 8,FO,nop,nop> + +0 < S. 123:123(0) ack 1 win 14600 <mss 1460,nop,nop,sackOK,nop,wscale 6,FO abcd1234,nop,nop> + +0 > . 1:1(0) ack 1 + +0 close(3) = 0 + +0 > F. 1:1(0) ack 1 + +0 < F. 1:1(0) ack 2 win 92 + +0 > . 2:2(0) ack 2 + +// Test 1: Forged SYN during DEFER_CONNECT +// connect() + connect(AF_UNSPEC) to let packetdrill remember +// IP, ports, ISN to inject a forged SYN + +0 socket(..., SOCK_STREAM|SOCK_NONBLOCK, IPPROTO_TCP) = 4 + +0 connect(4, ..., ...) = -1 EINPROGRESS (Operation is now in progress) + +0 > S 0:0(0) <mss 1460,nop,nop,sackOK,nop,wscale 8> + +0 connect(4, AF_UNSPEC, ...) = 0 + +// set DEFER_CONNECT bit + +0 bind(4, ..., ...) = 0 + +0 setsockopt(4, SOL_TCP, TCP_FASTOPEN_CONNECT, [1], 4) = 0 + +0 connect(4, ..., ...) = 0 + +// Forged SYN should not be accepted + +0 < 8080 > 8080 S 0:0(0) win 14600 <mss 1460,nop,nop,sackOK,nop,wscale 6> + +0 %{ assert tcpi_state == TCP_SYN_SENT, tcpi_state }% + + +0 sendto(4, ..., 500, 0, ..., ...) = 500 + +0 > S 0:500(500) <mss 1460,nop,nop,sackOK,nop,wscale 8,FO abcd1234,nop,nop> + +0 < S. 5678:5678(0) ack 501 win 14600 <mss 1460,nop,nop,sackOK,nop,wscale 6> + +0 > . 501:501(0) ack 1 + +0 %{ assert tcpi_state == TCP_ESTABLISHED, tcpi_state }% + +0 close(4) = 0 + +0 > F. 501:501(0) ack 1 + +0 < R. 1:1(0) ack 502 win 0 + +// Test 2: Forged ICMP error during DEFER_CONNECT + +0 socket(..., SOCK_STREAM|SOCK_NONBLOCK, IPPROTO_TCP) = 5 + +0 setsockopt(5, SOL_SOCKET, SO_REUSEADDR, [1], 4) = 0 + +0 bind(5, ..., ...) = 0 + +0 connect(5, ..., ...) = -1 EINPROGRESS (Operation is now in progress) + +0 > S 0:0(0) <mss 1460,nop,nop,sackOK,nop,wscale 8> + +0 connect(5, AF_UNSPEC, ...) = 0 + +0 setsockopt(5, SOL_TCP, TCP_FASTOPEN_CONNECT, [1], 4) = 0 + +0 connect(5, ..., ...) = 0 + + +0 < icmp unreachable [3:3(0)] + +0 %{ assert tcpi_state == TCP_SYN_SENT, tcpi_state }% + +0 sendto(5, ..., 500, 0, ..., ...) = 500 + +0 close(5) = 0 + +`/tmp/sysctl_restore_${PPID}.sh` diff --git a/tools/testing/selftests/net/sctp_ifwdtsn.c b/tools/testing/selftests/net/sctp_ifwdtsn.c new file mode 100644 index 000000000000..23ae508d8523 --- /dev/null +++ b/tools/testing/selftests/net/sctp_ifwdtsn.c @@ -0,0 +1,699 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Helper for sctp_ifwdtsn.sh: I-FORWARD-TSN handling with SCTP user message + * interleaving (RFC 8260) and partial reliability (RFC 3758). + * + * Runs both endpoints of one association: the server socket is created in + * the current network namespace, the client socket in the namespace given + * on the command line. The caller sets up the link and any nft rule that + * drops chunks. Messages sent by the client: + * + * big: 64KB on stream 0, reliable, fragmented into ~66 I-DATA chunks + * small: on stream 1, PR-SCTP "RTX" policy allowing one retransmission; + * the nft rule drops (part of) it, so it gets abandoned + * marker: short ordered message on stream 0 + * + * The reset_pending tests instead leave a partly received PR-SCTP message + * on each stream, the one on stream 1 in partial delivery, before the + * reset; the pdapi tests abandon two messages on stream 1, the first one + * in partial delivery. + * + * Usage: sctp_ifwdtsn <client netns> <test> + * Exit status: 0 pass, 1 fail, 4 skip. + */ +#include <errno.h> +#include <fcntl.h> +#include <poll.h> +#include <sched.h> +#include <stdbool.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <time.h> +#include <unistd.h> +#include <arpa/inet.h> +#include <netinet/in.h> +#include <sys/socket.h> +#include <linux/sctp.h> + +#include "kselftest.h" + +#ifndef SOL_SCTP +#define SOL_SCTP 132 +#endif + +#define SRV_ADDR "10.0.0.1" +#define CLI_ADDR "10.0.0.2" +#define SRV_PORT 5000 +#define BIG_LEN (64 * 1024) +#define BUF_LEN (BIG_LEN + 1024) +#define MAXSEG 1000 +#define TIMEOUT_MS 5000 +#define MARKER "marker" +#define UO_MARKER "uo-marker" +#define PD_LEN 20000 /* message in partial delivery on stream 1 */ + +struct test { + const char *name; + bool big_uo; /* send big unordered */ + int small_len; /* 0: don't send the small message */ + bool small_uo; /* send small unordered */ + int pd_point; /* server SCTP_PARTIAL_DELIVERY_POINT */ + bool expect_pd_abort; /* PD on stream 1 must be aborted */ + bool uo_marker; /* then send an unordered marker on 1 */ + bool reset; /* SSN/TSN association reset after big */ + int reset_pending; /* reset with data pending, requested by + * 1: the server, 2: the client + */ + bool pdapi; /* two messages skipped on stream 1 */ +}; + +static const struct test tests[] = { + { .name = "ordered", .small_len = 3000 }, + { .name = "unordered", .big_uo = true, .small_len = 3000 }, + { .name = "leading_edge", .small_len = 1000, .pd_point = 2000 }, + { .name = "leading_edge_nopd", .small_len = 1000 }, + { .name = "uo_pd", .small_len = 20000, .small_uo = true, + .pd_point = 2000, .expect_pd_abort = true, .uo_marker = true }, + { .name = "reset", .reset = true }, + { .name = "reset_pending_srv", .reset = true, .reset_pending = 1, + .pd_point = 3000, .expect_pd_abort = true }, + { .name = "reset_pending_cli", .reset = true, .reset_pending = 2, + .pd_point = 3000, .expect_pd_abort = true }, + { .name = "pdapi", .pdapi = true, .pd_point = 2000, + .expect_pd_abort = true }, + { .name = "pdapi_uo", .pdapi = true, .small_uo = true, .pd_point = 2000, + .expect_pd_abort = true }, +}; + +static const struct test *t; + +static void die(const char *what) +{ + fprintf(stderr, "%s: %s\n", what, strerror(errno)); + exit(KSFT_FAIL); +} + +static void setopt(int fd, int opt, const void *val, socklen_t len, + const char *name) +{ + if (setsockopt(fd, SOL_SCTP, opt, val, len) < 0) { + fprintf(stderr, "setsockopt(%s): %s\n", name, strerror(errno)); + /* Interleaving disabled, or option not supported. */ + exit(errno == EPERM || errno == ENOPROTOOPT ? + KSFT_SKIP : KSFT_FAIL); + } +} + +static void set_assoc_opt(int fd, int opt, unsigned int val, const char *name) +{ + struct sctp_assoc_value av = { + .assoc_id = SCTP_FUTURE_ASSOC, + .assoc_value = val, + }; + + setopt(fd, opt, &av, sizeof(av), name); +} + +static void subscribe(int fd, int type) +{ + struct sctp_event ev = { + .se_assoc_id = SCTP_FUTURE_ASSOC, + .se_type = type, + .se_on = 1, + }; + + setopt(fd, SCTP_EVENT, &ev, sizeof(ev), "SCTP_EVENT"); +} + +static int sctp_socket(void) +{ + struct sctp_initmsg im = { + .sinit_num_ostreams = 2, + .sinit_max_instreams = 2, + }; + struct sctp_paddrparams pp = { + .spp_assoc_id = SCTP_FUTURE_ASSOC, + .spp_flags = SPP_HB_DISABLE, + }; + struct sctp_rtoinfo rto = { + .srto_assoc_id = SCTP_FUTURE_ASSOC, + .srto_initial = 300, + .srto_min = 300, + .srto_max = 1000, + }; + int fd, val; + + fd = socket(AF_INET, SOCK_STREAM, IPPROTO_SCTP); + if (fd < 0) { + perror("socket"); + exit(errno == EPROTONOSUPPORT ? KSFT_SKIP : KSFT_FAIL); + } + val = 1; + setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)); + + setopt(fd, SCTP_INITMSG, &im, sizeof(im), "SCTP_INITMSG"); + setopt(fd, SCTP_RTOINFO, &rto, sizeof(rto), "SCTP_RTOINFO"); + /* No HEARTBEATs: the nft rules only look at the first chunk of a + * packet, and a HEARTBEAT bundled in front of DATA would bypass them. + */ + setopt(fd, SCTP_PEER_ADDR_PARAMS, &pp, sizeof(pp), + "SCTP_PEER_ADDR_PARAMS"); + set_assoc_opt(fd, SCTP_PR_SUPPORTED, 1, "SCTP_PR_SUPPORTED"); + val = 2; + setopt(fd, SCTP_FRAGMENT_INTERLEAVE, &val, sizeof(val), + "SCTP_FRAGMENT_INTERLEAVE"); + set_assoc_opt(fd, SCTP_INTERLEAVING_SUPPORTED, 1, + "SCTP_INTERLEAVING_SUPPORTED"); + if (t->reset) { + set_assoc_opt(fd, SCTP_RECONFIG_SUPPORTED, 1, + "SCTP_RECONFIG_SUPPORTED"); + set_assoc_opt(fd, SCTP_ENABLE_STREAM_RESET, + SCTP_ENABLE_RESET_ASSOC_REQ, + "SCTP_ENABLE_STREAM_RESET"); + subscribe(fd, SCTP_ASSOC_RESET_EVENT); + } + val = 1; + setopt(fd, SCTP_RECVRCVINFO, &val, sizeof(val), "SCTP_RECVRCVINFO"); + + return fd; +} + +static void send_msg(int fd, int sid, bool uo, const void *buf, size_t len, + bool pr) +{ + union { + char buf[CMSG_SPACE(sizeof(struct sctp_sndinfo)) + + CMSG_SPACE(sizeof(struct sctp_prinfo))]; + struct cmsghdr align; + } cbuf = {}; + struct iovec iov = { .iov_base = (void *)buf, .iov_len = len }; + struct msghdr msg = { + .msg_iov = &iov, + .msg_iovlen = 1, + .msg_control = cbuf.buf, + .msg_controllen = CMSG_SPACE(sizeof(struct sctp_sndinfo)), + }; + struct sctp_sndinfo *si; + struct sctp_prinfo *pi; + struct cmsghdr *cm; + + cm = CMSG_FIRSTHDR(&msg); + cm->cmsg_level = IPPROTO_SCTP; + cm->cmsg_type = SCTP_SNDINFO; + cm->cmsg_len = CMSG_LEN(sizeof(*si)); + si = (struct sctp_sndinfo *)CMSG_DATA(cm); + si->snd_sid = sid; + si->snd_flags = uo ? SCTP_UNORDERED : 0; + + if (pr) { + /* Abandon once the chunk would need a second retransmission: + * only a chunk that is lost again after being retransmitted + * qualifies, so abandonment does not depend on timing. + */ + msg.msg_controllen += CMSG_SPACE(sizeof(*pi)); + cm = CMSG_NXTHDR(&msg, cm); + cm->cmsg_level = IPPROTO_SCTP; + cm->cmsg_type = SCTP_PRINFO; + cm->cmsg_len = CMSG_LEN(sizeof(*pi)); + pi = (struct sctp_prinfo *)CMSG_DATA(cm); + pi->pr_policy = SCTP_PR_SCTP_RTX; + pi->pr_value = 1; + } + + if (sendmsg(fd, &msg, 0) != (ssize_t)len) + die("sendmsg"); +} + +static unsigned char pattern(size_t i) +{ + return (i * 7 + (i >> 8)) & 0xff; +} + +static long long now_ms(void) +{ + struct timespec ts; + + clock_gettime(CLOCK_MONOTONIC, &ts); + return ts.tv_sec * 1000LL + ts.tv_nsec / 1000000; +} + +/* Wait until the client has abandoned @n sent messages. */ +static bool wait_abandoned(int fd, unsigned int n) +{ + long long end = now_ms() + TIMEOUT_MS; + struct sctp_prstatus ps; + socklen_t len; + + while (now_ms() < end) { + memset(&ps, 0, sizeof(ps)); + ps.sprstat_policy = SCTP_PR_SCTP_RTX; + len = sizeof(ps); + if (getsockopt(fd, SOL_SCTP, SCTP_PR_ASSOC_STATUS, &ps, + &len) < 0) + die("SCTP_PR_ASSOC_STATUS"); + if (ps.sprstat_abandoned_sent >= n) + return true; + usleep(10000); + } + return false; +} + +/* Wait for a notification of @type on @fd, discarding anything else. */ +static bool wait_event(int fd, int type) +{ + long long end = now_ms() + TIMEOUT_MS; + union { + char data[256]; + union sctp_notification sn; + } buf; + + for (;;) { + struct pollfd pfd = { .fd = fd, .events = POLLIN }; + struct iovec iov = { buf.data, sizeof(buf.data) }; + struct msghdr msg = { .msg_iov = &iov, .msg_iovlen = 1 }; + union sctp_notification *sn = &buf.sn; + long long left = end - now_ms(); + + if (left <= 0 || poll(&pfd, 1, left) <= 0) + break; + if (recvmsg(fd, &msg, 0) <= 0) + break; + if (!(msg.msg_flags & MSG_NOTIFICATION) || + sn->sn_header.sn_type != type) + continue; + if (type == SCTP_ASSOC_RESET_EVENT && + sn->sn_assocreset_event.assocreset_flags & + (SCTP_ASSOC_RESET_DENIED | SCTP_ASSOC_RESET_FAILED)) { + printf("association reset denied or failed\n"); + return false; + } + return true; + } + return false; +} + +/* Request an SSN/TSN association reset. The sender refuses while it still + * has data queued or in flight, so retry until that has been acked. + */ +static void reset_assoc(int fd) +{ + long long end = now_ms() + TIMEOUT_MS; + sctp_assoc_t id = 0; + + while (setsockopt(fd, SOL_SCTP, SCTP_RESET_ASSOC, &id, sizeof(id))) { + if (errno != EAGAIN || now_ms() >= end) + die("SCTP_RESET_ASSOC"); + usleep(10000); + } +} + +/* Wait until all data sent on @fd has been acked. The receiver's + * cumulative TSN only moves past an abandoned message once it has + * processed the I-FORWARD-TSN for it. + */ +static bool wait_acked(int fd) +{ + long long end = now_ms() + TIMEOUT_MS; + struct sctp_status st; + socklen_t len; + + while (now_ms() < end) { + memset(&st, 0, sizeof(st)); + len = sizeof(st); + /* Fails once the association has been aborted. */ + if (getsockopt(fd, SOL_SCTP, SCTP_STATUS, &st, &len) < 0) + return false; + if (!st.sstat_unackdata) + return true; + usleep(10000); + } + return false; +} + +/* Bytes held by the server association (/proc/net/sctp/assocs RX_QUEUE). */ +static long assoc_rx_queue(void) +{ + /* 7 columns, TX_QUEUE, RX_QUEUE, UID, INODE, LPORT */ + const char *fmt = "%*s %*s %*s %*s %*s %*s %*s %*u %lu %*s %*s %d"; + unsigned long rxq; + char line[512]; + long ret = -1; + FILE *f; + int lport; + + f = fopen("/proc/net/sctp/assocs", "r"); + if (!f) + return -1; + while (fgets(line, sizeof(line), f)) { + if (sscanf(line, fmt, &rxq, &lport) == 2 && lport == SRV_PORT) + ret = rxq; + } + fclose(f); + return ret; +} + +struct server_state { + unsigned char *buf[2]; /* message being received, per stream */ + size_t len[2]; + bool big, marker, uo_marker, reset_event; + int pd_aborts[2]; + unsigned int pd_seq[2]; /* pdapi_seq of the last abort */ + int errors; +}; + +static void check_msg(struct server_state *s, int sid) +{ + unsigned char *m = s->buf[sid]; + size_t len = s->len[sid]; + size_t i; + + s->len[sid] = 0; + if (sid == 0 && len == sizeof(MARKER) && !memcmp(m, MARKER, len)) { + s->marker = true; + return; + } + if (sid == 1 && len == sizeof(UO_MARKER) && + !memcmp(m, UO_MARKER, len)) { + s->uo_marker = true; + return; + } + if (sid == 0 && len == BIG_LEN) { + for (i = 0; i < BIG_LEN && m[i] == pattern(i); i++) + ; + if (i == BIG_LEN) { + s->big = true; + return; + } + printf("big message corrupted at offset %zu\n", i); + } else if (sid == 1 && len > sizeof(UO_MARKER) && + !memcmp(m + len - sizeof(UO_MARKER), UO_MARKER, + sizeof(UO_MARKER))) { + printf("unordered marker appended to the abandoned message\n"); + } else if (sid == 1 && t->small_len) { + printf("abandoned message delivered (%zu bytes)\n", len); + } else { + printf("unexpected %zu byte message on stream %d\n", len, sid); + } + s->errors++; +} + +/* Receive until @done(s) is true or the timeout expires. */ +static bool server_recv(int fd, struct server_state *s, + bool (*done)(const struct server_state *s)) +{ + long long end = now_ms() + TIMEOUT_MS; + static union { + char buf[CMSG_SPACE(sizeof(struct sctp_rcvinfo))]; + struct cmsghdr align; + } cbuf; + static union { + unsigned char data[BUF_LEN]; + union sctp_notification sn; + } buf; + + while (!done(s)) { + struct pollfd pfd = { .fd = fd, .events = POLLIN }; + struct iovec iov = { buf.data, sizeof(buf.data) }; + struct msghdr msg = { + .msg_iov = &iov, + .msg_iovlen = 1, + .msg_control = cbuf.buf, + .msg_controllen = sizeof(cbuf.buf), + }; + union sctp_notification *sn = &buf.sn; + struct sctp_rcvinfo *ri = NULL; + struct cmsghdr *cm; + long long left; + ssize_t n; + int sid; + + left = end - now_ms(); + if (left <= 0 || poll(&pfd, 1, left) <= 0) { + printf("timeout waiting for data\n"); + return false; + } + n = recvmsg(fd, &msg, 0); + if (n <= 0) { + printf("recvmsg: %s\n", n ? strerror(errno) : "EOF"); + return false; + } + + if (msg.msg_flags & MSG_NOTIFICATION) { + int type = sn->sn_header.sn_type; + + if (type == SCTP_PARTIAL_DELIVERY_EVENT) { + struct sctp_pdapi_event *pe = &sn->sn_pdapi_event; + + sid = pe->pdapi_stream; + if (sid > 1 || pe->pdapi_indication != + SCTP_PARTIAL_DELIVERY_ABORTED) { + printf("unexpected pdapi event %u on stream %d\n", + pe->pdapi_indication, sid); + return false; + } + s->pd_aborts[sid]++; + s->pd_seq[sid] = pe->pdapi_seq; + s->len[sid] = 0; + } else if (type == SCTP_ASSOC_RESET_EVENT) { + s->reset_event = true; + } + continue; + } + + for (cm = CMSG_FIRSTHDR(&msg); cm; cm = CMSG_NXTHDR(&msg, cm)) + if (cm->cmsg_level == IPPROTO_SCTP && + cm->cmsg_type == SCTP_RCVINFO) + ri = (struct sctp_rcvinfo *)CMSG_DATA(cm); + sid = ri ? ri->rcv_sid : 0; + if (sid > 1 || s->len[sid] + n > BUF_LEN) { + printf("unexpected data on stream %d\n", sid); + return false; + } + memcpy(s->buf[sid] + s->len[sid], buf.data, n); + s->len[sid] += n; + if (msg.msg_flags & MSG_EOR) + check_msg(s, sid); + } + return true; +} + +static bool got_reset(const struct server_state *s) +{ + return s->reset_event || s->errors; +} + +static bool got_big(const struct server_state *s) +{ + return s->big || s->errors; +} + +static bool got_all(const struct server_state *s) +{ + return ((s->big || t->pdapi) && s->marker && + (!t->uo_marker || s->uo_marker) && + (!t->expect_pd_abort || s->pd_aborts[1])) || s->errors; +} + +/* Let the nft rules that match the client address in set "hold" pass. */ +static bool release_hold(void) +{ + if (system("nft delete element ip sctp_test hold { " CLI_ADDR " }")) { + printf("failed to release the nft hold\n"); + return false; + } + return true; +} + +static int client_socket(const char *netns) +{ + int self, other, fd; + char path[256]; + + snprintf(path, sizeof(path), "/run/netns/%s", netns); + self = open("/proc/self/ns/net", O_RDONLY); + other = open(path, O_RDONLY); + if (self < 0 || other < 0) + die("open netns"); + if (setns(other, CLONE_NEWNET)) + die("setns"); + fd = sctp_socket(); + if (setns(self, CLONE_NEWNET)) + die("setns"); + close(other); + close(self); + return fd; +} + +int main(int argc, char **argv) +{ + struct sockaddr_in sa = { + .sin_family = AF_INET, + .sin_port = htons(SRV_PORT), + }; + struct server_state s = {}; + unsigned char *big, *small; + int lfd, sfd, cfd, i; + bool ok; + long rxq; + + if (argc != 3) { + fprintf(stderr, "usage: %s <client netns> <test>\n", argv[0]); + return KSFT_FAIL; + } + for (i = 0; i < (int)ARRAY_SIZE(tests); i++) + if (!strcmp(argv[2], tests[i].name)) + t = &tests[i]; + if (!t) { + fprintf(stderr, "unknown test %s\n", argv[2]); + return KSFT_FAIL; + } + inet_pton(AF_INET, SRV_ADDR, &sa.sin_addr); + + lfd = sctp_socket(); + if (t->pd_point) { + setopt(lfd, SCTP_PARTIAL_DELIVERY_POINT, &t->pd_point, + sizeof(t->pd_point), "SCTP_PARTIAL_DELIVERY_POINT"); + subscribe(lfd, SCTP_PARTIAL_DELIVERY_EVENT); + } + if (bind(lfd, (struct sockaddr *)&sa, sizeof(sa)) || listen(lfd, 1)) + die("bind/listen"); + + cfd = client_socket(argv[1]); + set_assoc_opt(cfd, SCTP_MAXSEG, MAXSEG, "SCTP_MAXSEG"); + /* Round robin, so that the small message is sent between fragments + * of the big one. + */ + set_assoc_opt(cfd, SCTP_STREAM_SCHEDULER, SCTP_SS_RR, + "SCTP_STREAM_SCHEDULER"); + if (t->pdapi) { + /* Send the marker right away. Held back by Nagle, it could + * go out bundled behind an I-FORWARD-TSN, and nft would + * drop both. + */ + i = 1; + setopt(cfd, SCTP_NODELAY, &i, sizeof(i), "SCTP_NODELAY"); + } + if (connect(cfd, (struct sockaddr *)&sa, sizeof(sa))) + die("connect"); + sfd = accept(lfd, NULL, NULL); + if (sfd < 0) + die("accept"); + + big = malloc(BIG_LEN); + small = malloc(PD_LEN); + s.buf[0] = malloc(BUF_LEN); + s.buf[1] = malloc(BUF_LEN); + if (!big || !small || !s.buf[0] || !s.buf[1]) + die("malloc"); + for (i = 0; i < BIG_LEN; i++) + big[i] = pattern(i); + memset(small, 's', PD_LEN); + + if (t->reset_pending) { + /* A message partly received on stream 0, not in partial + * delivery, and one in partial delivery on stream 1. Until + * the hold is released, nft drops a fragment of each and + * every I-FORWARD-TSN, so both are still pending on the + * server when the reset is done. + */ + send_msg(cfd, 0, false, small, 2500, true); + send_msg(cfd, 1, false, small, PD_LEN, true); + if (!wait_abandoned(cfd, 2)) { + printf("client: messages were not abandoned\n"); + return KSFT_FAIL; + } + reset_assoc(t->reset_pending == 1 ? sfd : cfd); + if (!wait_event(cfd, SCTP_ASSOC_RESET_EVENT)) { + printf("client: no association reset event\n"); + return KSFT_FAIL; + } + /* Once the server has seen the reset too, every packet the + * client sent before it has arrived. + */ + if (!server_recv(sfd, &s, got_reset) || s.errors || + !release_hold()) + return KSFT_FAIL; + /* MIDs start again from 0, so big reuses the MID of the + * message left on stream 0 and must not be mixed with it. + */ + send_msg(cfd, 0, false, big, BIG_LEN, false); + } else if (t->pdapi) { + /* Two messages on stream 1, the first one in partial + * delivery. nft drops a fragment of each and holds back + * I-FORWARD-TSNs until the marker, sent once both are + * abandoned, arrives. The client then sends one + * I-FORWARD-TSN naming both messages, below the marker's + * TSN. + */ + send_msg(cfd, 1, t->small_uo, small, PD_LEN, true); + send_msg(cfd, 1, t->small_uo, small, 3000, true); + if (!wait_abandoned(cfd, 2)) { + printf("client: messages were not abandoned\n"); + return KSFT_FAIL; + } + } else { + send_msg(cfd, 0, t->big_uo, big, BIG_LEN, false); + if (t->small_len) + send_msg(cfd, 1, t->small_uo, small, t->small_len, + true); + } + + if (t->reset && !t->reset_pending) { + ok = server_recv(sfd, &s, got_big); + if (ok) + reset_assoc(sfd); + /* Only send the marker once the reset is done. */ + if (ok && !wait_event(cfd, SCTP_ASSOC_RESET_EVENT)) { + printf("client: no association reset event\n"); + return KSFT_FAIL; + } + } + send_msg(cfd, 0, false, MARKER, sizeof(MARKER), false); + + if (t->small_len && !wait_abandoned(cfd, 1)) { + printf("client: small message was not abandoned\n"); + return KSFT_FAIL; + } + if (t->uo_marker) + send_msg(cfd, 1, true, UO_MARKER, sizeof(UO_MARKER), false); + + ok = server_recv(sfd, &s, got_all); + if (!wait_acked(cfd)) { + printf("client: data not acked\n"); + ok = false; + } + rxq = assoc_rx_queue(); + + if (!s.big && !t->pdapi) + printf("big message not delivered intact\n"); + if (!s.marker) + printf("marker not delivered\n"); + if (t->uo_marker && !s.uo_marker) + printf("unordered marker not delivered as its own message\n"); + if (s.pd_aborts[0] || (s.pd_aborts[1] && !t->expect_pd_abort)) { + printf("unexpected partial delivery abort\n"); + ok = false; + } + if (t->expect_pd_abort && !s.pd_aborts[1]) { + printf("partial delivery on stream 1 not aborted\n"); + ok = false; + } else if (t->expect_pd_abort && (s.pd_aborts[1] > 1 || s.pd_seq[1])) { + printf("%d partial delivery aborts, last for MID %u, expected one for MID 0\n", + s.pd_aborts[1], s.pd_seq[1]); + ok = false; + } + if (t->reset && !s.reset_event) { + printf("server: no association reset event\n"); + ok = false; + } + if (rxq < 0) { + printf("association is gone\n"); + ok = false; + } else if (rxq > 0) { + printf("%ld bytes left queued on the association\n", rxq); + ok = false; + } + + return ok && !s.errors ? KSFT_PASS : KSFT_FAIL; +} diff --git a/tools/testing/selftests/net/sctp_ifwdtsn.sh b/tools/testing/selftests/net/sctp_ifwdtsn.sh new file mode 100755 index 000000000000..e745d67b3b79 --- /dev/null +++ b/tools/testing/selftests/net/sctp_ifwdtsn.sh @@ -0,0 +1,233 @@ +#!/bin/bash +# SPDX-License-Identifier: GPL-2.0 +# +# SCTP I-FORWARD-TSN handling with user message interleaving (RFC 8260). +# +# TOPO: CLI_NS (veth, 10.0.0.2) <---> (veth, 10.0.0.1) SRV_NS +# +# A large reliable message on stream 0 is sent interleaved with a PR-SCTP +# message on stream 1 that an nft rule in SRV_NS drops, so the sender +# abandons it and sends an I-FORWARD-TSN. The netem delay keeps the sender +# window-limited, so the two messages' fragments interleave. Most of the +# checks are done by sctp_ifwdtsn, see there. + +source lib.sh + +ALL_TESTS=" + test_ordered + test_unordered + test_leading_edge + test_leading_edge_nopd + test_uo_pd + test_reset + test_reset_pending_srv + test_reset_pending_cli + test_pdapi + test_pdapi_uo +" + +# nft matches on the first chunk of a packet: chunk type at byte 12 of the +# SCTP header, flags at byte 13, I-DATA stream id at byte 20, MID at byte +# 24 and FSN at byte 28 (the PPID in a B fragment). SCTP_MAXSEG limits +# fragments to 1000 bytes and GSO is limited to the MTU, so no two +# full-size fragments share a packet. +NFT_SCTP="meta l4proto sctp" +NFT_CHUNK_IDATA="@th,96,8 64" +NFT_CHUNK_IFWDTSN="@th,96,8 194" +NFT_FLAG_B="@th,104,8 & 0x02 == 0x02" +NFT_FLAG_E="@th,104,8 & 0x01 == 0x01" +NFT_SID0="@th,160,16 0" +NFT_SID1="@th,160,16 1" +NFT_MID0="@th,192,32 0" +NFT_MID1="@th,192,32 1" +NFT_FSN5="@th,224,32 5" + +# Run a setup command. The config file enables everything used here, so a +# failure fails the test, with the command and its output as the reason. +setup_cmd() +{ + local out + + out=$("$@" 2>&1) && return + check_err 1 "$*: $out" + return 1 +} + +setup() +{ + if ! setup_ns CLI_NS SRV_NS; then + check_err 1 "setup_ns failed" + return 1 + fi + defer cleanup_all_ns + + setup_cmd ip -n "$SRV_NS" link add veth0 type veth peer name veth0 \ + netns "$CLI_NS" || return + setup_cmd ip -n "$SRV_NS" addr add 10.0.0.1/24 dev veth0 || return + setup_cmd ip -n "$CLI_NS" addr add 10.0.0.2/24 dev veth0 || return + for ns in "$SRV_NS" "$CLI_NS"; do + setup_cmd ip -n "$ns" link set veth0 gso_max_size 1500 up || + return + setup_cmd tc -n "$ns" qdisc add dev veth0 root netem \ + delay 50ms || return + setup_cmd ip netns exec "$ns" sysctl -wq \ + net.sctp.intl_enable=1 net.sctp.prsctp_enable=1 \ + net.sctp.reconf_enable=1 || return + done +} + +# $1: nft rules for the server's input hook (may be empty) +nft_rules() +{ + setup_cmd ip netns exec "$SRV_NS" nft -f - <<-EOF + table ip sctp_test { + set blk { + type ipv4_addr + flags dynamic + } + set hold { + type ipv4_addr + flags dynamic + elements = { 10.0.0.2 } + } + chain input { + type filter hook input priority 0; + $1 + } + } + EOF +} + +# $1: test name for sctp_ifwdtsn, $2: description, $3: nft rules (optional) +run_helper() +{ + RET=0 + retmsg= + if ! setup || { [ -n "$3" ] && ! nft_rules "$3"; }; then + log_test "$2" + return + fi + ip netns exec "$SRV_NS" ./sctp_ifwdtsn "$CLI_NS" "$1" + RET=$? + [ "$RET" -eq "$ksft_skip" ] || [ "$RET" -eq 0 ] || RET=$ksft_fail + log_test "$2" +} + +# Fragments of the abandoned message must not take fragments of a live +# message below the New Cumulative TSN with them, and the abandoned +# message's own received fragments must be freed. +test_ordered() +{ + run_helper ordered \ + "abandoned message does not purge ordered message" \ + "$NFT_SCTP $NFT_CHUNK_IDATA $NFT_SID1 $NFT_FLAG_B drop" +} + +test_unordered() +{ + run_helper unordered \ + "abandoned message does not purge unordered message" \ + "$NFT_SCTP $NFT_CHUNK_IDATA $NFT_SID1 $NFT_FLAG_B drop" +} + +# Drop the abandoned message and every packet after it until one starting +# with the I-FORWARD-TSN arrives, so that its New Cumulative TSN is the +# highest TSN received. This must not abort the partial delivery of the +# message on stream 0. +test_leading_edge() +{ + run_helper leading_edge \ + "I-FORWARD-TSN at the highest TSN is not a reset" " + $NFT_SCTP $NFT_CHUNK_IFWDTSN delete @blk { ip saddr } + $NFT_SCTP $NFT_CHUNK_IDATA $NFT_SID1 add @blk { ip saddr } drop + $NFT_SCTP ip saddr @blk drop" +} + +# The same without partial delivery: the fragments of the message on +# stream 0 must not be freed. +test_leading_edge_nopd() +{ + run_helper leading_edge_nopd \ + "I-FORWARD-TSN at the highest TSN keeps other messages" " + $NFT_SCTP $NFT_CHUNK_IFWDTSN delete @blk { ip saddr } + $NFT_SCTP $NFT_CHUNK_IDATA $NFT_SID1 add @blk { ip saddr } drop + $NFT_SCTP ip saddr @blk drop" +} + +# Abandon an unordered message during its partial delivery: the partial +# delivery must be aborted, and the next unordered message on the stream +# must not be appended to it. +test_uo_pd() +{ + run_helper uo_pd "abandoned unordered partial delivery is aborted" \ + "$NFT_SCTP $NFT_CHUNK_IDATA $NFT_SID1 $NFT_FSN5 drop" +} + +# An SSN/TSN association reset with interleaving completes and leaves a +# working association. +test_reset() +{ + run_helper reset "association reset with interleaving" +} + +# Drop a fragment of the message on each stream and every +# I-FORWARD-TSN, so that both messages are left on the server when the +# reset is done. The reset must abort the partial delivery on stream 1 +# and free both. sctp_ifwdtsn releases the hold after the reset, before +# it sends a new message on stream 0 that reuses MID 0. +NFT_PENDING=" + $NFT_SCTP ip saddr @hold $NFT_CHUNK_IFWDTSN drop + $NFT_SCTP ip saddr @hold $NFT_CHUNK_IDATA $NFT_SID0 $NFT_FLAG_E drop + $NFT_SCTP ip saddr @hold $NFT_CHUNK_IDATA $NFT_SID1 $NFT_FSN5 drop" + +test_reset_pending_srv() +{ + run_helper reset_pending_srv \ + "association reset by the server frees pending data" \ + "$NFT_PENDING" +} + +test_reset_pending_cli() +{ + run_helper reset_pending_cli \ + "association reset by the client frees pending data" \ + "$NFT_PENDING" +} + +# Abandon two messages on a stream, the first one in partial delivery, +# and let one I-FORWARD-TSN below the highest TSN received skip both. The +# partial delivery abort must name the first message. I-FORWARD-TSNs are +# dropped until the marker on stream 0, sent once both messages are +# abandoned, arrives; any later one was sent after it. +NFT_PDAPI=" + $NFT_SCTP $NFT_CHUNK_IDATA $NFT_SID0 delete @hold { ip saddr } + $NFT_SCTP ip saddr @hold $NFT_CHUNK_IFWDTSN drop + $NFT_SCTP $NFT_CHUNK_IDATA $NFT_SID1 $NFT_MID0 $NFT_FSN5 drop + $NFT_SCTP $NFT_CHUNK_IDATA $NFT_SID1 $NFT_MID1 $NFT_FLAG_E drop" + +test_pdapi() +{ + run_helper pdapi "ordered partial delivery abort names its message" \ + "$NFT_PDAPI" +} + +test_pdapi_uo() +{ + run_helper pdapi_uo \ + "unordered partial delivery abort names its message" \ + "$NFT_PDAPI" +} + +require_command nft +require_command tc +modprobe -q sctp +if [ ! -d /proc/net/sctp ]; then + echo "SKIP: SCTP not available" + exit "$ksft_skip" +fi + +trap defer_scopes_cleanup EXIT + +tests_run + +exit "$EXIT_STATUS" diff --git a/tools/testing/selftests/net/tls.c b/tools/testing/selftests/net/tls.c index c4203401c4bf..bd2797f9f619 100644 --- a/tools/testing/selftests/net/tls.c +++ b/tools/testing/selftests/net/tls.c @@ -2580,6 +2580,42 @@ static const struct raw_rec id2_data_l0 = { }, }; +static void zero_len_sock_pair(struct __test_metadata *_metadata, + int *fd, int *cfd, bool *notls) +{ + struct tls_crypto_info_keys tls12; + int ret; + + tls_crypto_info_init(TLS_1_2_VERSION, TLS_CIPHER_AES_CCM_128, + &tls12, 0); + + ulp_sock_pair(_metadata, fd, cfd, notls); + if (*notls) + return; + + /* fd gets no keys, since these fixtures send raw records over it */ + ret = setsockopt(*cfd, SOL_TLS, TLS_RX, &tls12, tls12.len); + ASSERT_EQ(ret, 0); +} + +/* Send a variant's records and return the last one carrying payload */ +static const struct raw_rec * +zero_len_send_recs(struct __test_metadata *_metadata, int fd, + const struct raw_rec *const *recs) +{ + const struct raw_rec *payload = NULL; + int i; + + for (i = 0; i < 4 && recs[i]; i++) { + EXPECT_EQ(send(fd, recs[i]->cipher_data, recs[i]->cipher_len, 0), + recs[i]->cipher_len); + if (recs[i]->plain_len) + payload = recs[i]; + } + + return payload; +} + FIXTURE(zero_len) { int fd, cfd; @@ -2642,19 +2678,7 @@ FIXTURE_VARIANT_ADD(zero_len, data_0data_0data) FIXTURE_SETUP(zero_len) { - struct tls_crypto_info_keys tls12; - int ret; - - tls_crypto_info_init(TLS_1_2_VERSION, TLS_CIPHER_AES_CCM_128, - &tls12, 0); - - ulp_sock_pair(_metadata, &self->fd, &self->cfd, &self->notls); - if (self->notls) - return; - - /* Don't install keys on fd, we'll send raw records */ - ret = setsockopt(self->cfd, SOL_TLS, TLS_RX, &tls12, tls12.len); - ASSERT_EQ(ret, 0); + zero_len_sock_pair(_metadata, &self->fd, &self->cfd, &self->notls); } FIXTURE_TEARDOWN(zero_len) @@ -2670,10 +2694,10 @@ TEST_F(zero_len, test) int rec_off; int i; - for (i = 0; i < 4 && variant->recs[i]; i++) - EXPECT_EQ(send(self->fd, variant->recs[i]->cipher_data, - variant->recs[i]->cipher_len, 0), - variant->recs[i]->cipher_len); + if (self->notls) + SKIP(return, "no TLS support"); + + zero_len_send_recs(_metadata, self->fd, variant->recs); rec = &variant->recs[0]; rec_off = 0; @@ -2699,6 +2723,301 @@ TEST_F(zero_len, test) } }; +FIXTURE(zero_len_peek) +{ + int fd, cfd; + bool notls; +}; + +FIXTURE_VARIANT(zero_len_peek) +{ + const struct raw_rec *recs[4]; + ssize_t peek_ret; +}; + +FIXTURE_VARIANT_ADD(zero_len_peek, 0data_0data_data) +{ + .recs = { &id0_data_l0, &id1_data_l0, &id2_data_l11, }, + .peek_ret = 11, +}; + +FIXTURE_VARIANT_ADD(zero_len_peek, 0data_0data_0data) +{ + .recs = { &id0_data_l0, &id1_data_l0, &id2_data_l0, }, + .peek_ret = -EAGAIN, +}; + +FIXTURE_SETUP(zero_len_peek) +{ + zero_len_sock_pair(_metadata, &self->fd, &self->cfd, &self->notls); +} + +FIXTURE_TEARDOWN(zero_len_peek) +{ + close(self->fd); + close(self->cfd); +} + +/* Peeking past a run of empty data records must reach the payload + * behind them, and a run with no payload behind it must report EAGAIN + * and leave no record queued. + */ +TEST_F(zero_len_peek, test) +{ + struct pollfd pfd = { .fd = self->cfd, .events = POLLIN }; + const struct raw_rec *payload; + unsigned char buf[128]; + ssize_t ret; + + if (self->notls) + SKIP(return, "no TLS support"); + + payload = zero_len_send_recs(_metadata, self->fd, variant->recs); + + if (variant->peek_ret < 0) { + ret = recv(self->cfd, buf, sizeof(buf), + MSG_DONTWAIT | MSG_PEEK); + EXPECT_EQ(ret, -1); + EXPECT_EQ(errno, -variant->peek_ret); + + /* A record left on rx_list keeps the socket readable */ + EXPECT_EQ(poll(&pfd, 1, 0), 0); + return; + } + + ret = recv(self->cfd, buf, sizeof(buf), MSG_DONTWAIT | MSG_PEEK); + EXPECT_EQ(ret, variant->peek_ret); + if (ret == variant->peek_ret) + EXPECT_EQ(memcmp(buf, payload->plain_data, + variant->peek_ret), 0); + + ret = recv(self->cfd, buf, sizeof(buf), MSG_DONTWAIT); + EXPECT_EQ(ret, variant->peek_ret); + if (ret == variant->peek_ret) + EXPECT_EQ(memcmp(buf, payload->plain_data, + variant->peek_ret), 0); + + ret = recv(self->cfd, buf, sizeof(buf), MSG_DONTWAIT); + EXPECT_EQ(ret, -1); + EXPECT_EQ(errno, EAGAIN); +} + +FIXTURE(zero_len_splice) +{ + int fd, cfd; + bool notls; +}; + +FIXTURE_VARIANT(zero_len_splice) +{ + const struct raw_rec *recs[4]; + ssize_t splice_ret; +}; + +FIXTURE_VARIANT_ADD(zero_len_splice, 0data_data) +{ + .recs = { &id0_data_l0, &id1_data_l11, }, + .splice_ret = 11, +}; + +FIXTURE_VARIANT_ADD(zero_len_splice, 0data_0data_data) +{ + .recs = { &id0_data_l0, &id1_data_l0, &id2_data_l11, }, + .splice_ret = 11, +}; + +FIXTURE_VARIANT_ADD(zero_len_splice, 0data_0data_0data) +{ + .recs = { &id0_data_l0, &id1_data_l0, &id2_data_l0, }, + .splice_ret = -EAGAIN, +}; + +FIXTURE_VARIANT_ADD(zero_len_splice, 0data_0ctrl) +{ + .recs = { &id0_data_l0, &id1_ctrl_l0, }, + .splice_ret = -EINVAL, +}; + +FIXTURE_SETUP(zero_len_splice) +{ + zero_len_sock_pair(_metadata, &self->fd, &self->cfd, &self->notls); +} + +FIXTURE_TEARDOWN(zero_len_splice) +{ + close(self->fd); + close(self->cfd); +} + +/* Splicing must skip a run of empty data records to reach the payload + * behind it, since a zero-byte splice reads as EOF. Splice reports + * EAGAIN for a run with no payload behind it, and EINVAL for a control + * record behind the run. + */ +TEST_F(zero_len_splice, test) +{ + struct pollfd pfd = { .fd = self->cfd, .events = POLLIN }; + const struct raw_rec *payload; + unsigned char buf[128]; + ssize_t ret; + int p[2]; + + if (self->notls) + SKIP(return, "no TLS support"); + + ASSERT_GE(pipe(p), 0); + + payload = zero_len_send_recs(_metadata, self->fd, variant->recs); + + if (variant->splice_ret < 0) { + ret = splice(self->cfd, NULL, p[1], NULL, sizeof(buf), + SPLICE_F_NONBLOCK); + EXPECT_EQ(ret, -1); + EXPECT_EQ(errno, -variant->splice_ret); + } else { + /* ASSERT so a zero return stops the test before the read + * below blocks until the harness timeout. + */ + ASSERT_EQ(splice(self->cfd, NULL, p[1], NULL, sizeof(buf), + SPLICE_F_NONBLOCK), variant->splice_ret); + ret = read(p[0], buf, sizeof(buf)); + EXPECT_EQ(ret, variant->splice_ret); + if (ret == variant->splice_ret) + EXPECT_EQ(memcmp(buf, payload->plain_data, + variant->splice_ret), 0); + + /* The empty records were consumed, not left queued */ + EXPECT_EQ(poll(&pfd, 1, 0), 0); + } + + close(p[0]); + close(p[1]); +} + +FIXTURE(zero_len_run) +{ + int fd, cfd; + bool notls; +}; + +/* Before each of two reads, send n[i] empty records followed by a data + * record if data[i] is set. ret[i] is the result of the read. + */ +FIXTURE_VARIANT(zero_len_run) +{ + unsigned int n[2]; + bool data[2]; + int ret[2]; +}; + +FIXTURE_VARIANT_ADD(zero_len_run, 128) +{ + .n = { 128, 0, }, + .data = { true, false, }, + .ret = { 4, -EAGAIN, }, +}; + +/* More than 128 consecutive empty records break the connection */ +FIXTURE_VARIANT_ADD(zero_len_run, 129) +{ + .n = { 129, 0, }, + .data = { true, false, }, + .ret = { -EBADMSG, -EAGAIN, }, +}; + +/* The count starts over on every read */ +FIXTURE_VARIANT_ADD(zero_len_run, 128_128) +{ + .n = { 128, 128, }, + .data = { false, true, }, + .ret = { -EAGAIN, 4, }, +}; + +FIXTURE_SETUP(zero_len_run) +{ + struct tls_crypto_info_keys tls13; + int ret; + + tls_crypto_info_init(TLS_1_3_VERSION, TLS_CIPHER_AES_GCM_128, + &tls13, 0); + + ulp_sock_pair(_metadata, &self->fd, &self->cfd, &self->notls); + if (self->notls) + return; + + ret = setsockopt(self->fd, SOL_TLS, TLS_TX, &tls13, tls13.len); + ASSERT_EQ(ret, 0); + ret = setsockopt(self->cfd, SOL_TLS, TLS_RX, &tls13, tls13.len); + ASSERT_EQ(ret, 0); +} + +FIXTURE_TEARDOWN(zero_len_run) +{ + close(self->fd); + close(self->cfd); +} + +static void zero_len_run_send(struct __test_metadata *_metadata, int fd, + const FIXTURE_VARIANT(zero_len_run) *variant, + int i) +{ + /* kTLS cannot send an empty record. Send the data content type as + * the only byte of a record of type 0 instead, the receiver strips + * the 0 as padding and sees an empty data record. + */ + char data_type = 0x17; + unsigned int j; + + for (j = 0; j < variant->n[i]; j++) + ASSERT_EQ(tls_send_cmsg(fd, 0, &data_type, 1, 0), 1); + if (variant->data[i]) + ASSERT_EQ(send(fd, "data", 4, 0), 4); +} + +static void zero_len_run_expect(struct __test_metadata *_metadata, + ssize_t ret, int expected) +{ + EXPECT_EQ(ret, expected >= 0 ? expected : -1); + if (expected < 0) + EXPECT_EQ(errno, -expected); +} + +TEST_F(zero_len_run, recv) +{ + char buf[16]; + int i; + + if (self->notls) + SKIP(return, "no TLS support"); + + for (i = 0; i < 2; i++) { + zero_len_run_send(_metadata, self->fd, variant, i); + zero_len_run_expect(_metadata, + recv(self->cfd, buf, sizeof(buf), + MSG_DONTWAIT), + variant->ret[i]); + } +} + +TEST_F(zero_len_run, splice) +{ + int i, p[2]; + + if (self->notls) + SKIP(return, "no TLS support"); + + ASSERT_GE(pipe(p), 0); + for (i = 0; i < 2; i++) { + zero_len_run_send(_metadata, self->fd, variant, i); + zero_len_run_expect(_metadata, + splice(self->cfd, NULL, p[1], NULL, 16, + SPLICE_F_NONBLOCK), + variant->ret[i]); + } + close(p[0]); + close(p[1]); +} + FIXTURE(tls_err) { int fd, cfd; diff --git a/tools/testing/selftests/powerpc/Makefile b/tools/testing/selftests/powerpc/Makefile index b175e94e1901..aeab9366d09b 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 7e9dbf3d0d09..3aca10223f0f 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/tc-testing/tc-tests/qdiscs/teql.json b/tools/testing/selftests/tc-testing/tc-tests/qdiscs/teql.json index 0179c57104ad..ab5d0881c007 100644 --- a/tools/testing/selftests/tc-testing/tc-tests/qdiscs/teql.json +++ b/tools/testing/selftests/tc-testing/tc-tests/qdiscs/teql.json @@ -90,12 +90,8 @@ "ets", "tbf" ], - "plugins": { - "requires": [ - "nsPlugin" - ] - }, "setup": [ + "$IP link add dev $DUMMY type dummy", "$TC qdisc add dev $DUMMY root handle 1: qfq", "$TC class add dev $DUMMY parent 1: classid 1:1 qfq weight 15 maxpkt 16384" ], @@ -104,7 +100,35 @@ "verifyCmd": "$TC -s -j qdisc ls dev $DUMMY parent 1:1", "matchJSON": [], "teardown": [ - "$TC qdisc del dev $DUMMY root handle 1:" + "$TC qdisc del dev $DUMMY root handle 1:", + "$IP link del dev $DUMMY" + ] + }, + { + "id": "6a06", + "name": "Reject TEQL attach from a different network namespace", + "category": [ + "qdisc", + "teql" + ], + "plugins": { + "requires": [ + "nsPlugin" + ] + }, + "setup": [], + "cmdUnderTest": "$TC qdisc add dev $DUMMY root handle 3: teql0", + "expExitCode": "2", + "verifyCmd": "$TC qdisc show dev $DUMMY", + "matchPattern": "qdisc teql0 3: root", + "matchCount": "0", + "teardown": [ + [ + "$TC qdisc del dev $DUMMY root handle 3:", + 0, + 1, + 2 + ] ] } ] |
