From mboxrd@z Thu Jan 1 00:00:00 1970 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=100.103.45.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1796040565; b=cy2uv5K6Dzo0t6CSi/79X/k/tDcR3ZtkuMWhG6FXyyWqln7SGDVsWGMd0fcIodiFLEVa nzeARxZGXnKp/s3g6Mig/nPwZVjMP2c8LAUUCVmv6WFNUubCwr47NXdo9JpVzlp66QgW+ mSDWyV5qyLpepI87LP4kAbd3vOqlwHn/gA40sDj8/4Rb2p1xi5/xcWOdnt9ePeQCLPces l22b+RZv3ckMl/QvLGVq5ob5LkrD9o/PikVJsJXWamo/BZHqTAD00DSkIPyCBQhEa+0Sv Yv5pM0tjWzVC/8BuVd4+SvhGRiyQC7Z3LWNaWkfqYiRsJwInqT/WQx82IPHxy2UYwgg== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796040565; h=Received:DKIM-Signature:From:To:Cc:Subject:Date:Message-ID:X-Mailer: In-Reply-To:References:MIME-Version:Content-Type: Content-Transfer-Encoding; bh=1nPEIjoD79ynNDAIIx7u064YTk0SP/nwh9nb0tIL7uw=; b=0YGxRZVgyP3Pve9z+dv52LphKfGgOk/ABVzJIUH8Gic7UEz64n4s7tXpSMcmFNslbls9 CUD7cSRtIAbTJ58vXB3Fmpf2+YINeZG8PmSonVELlLQfz/tuXYHfA/NF6TTSeAQe+kROc Di/m2/K2lH3hEdT3rx1LLdmFyp3cuLp2Ny4N4gMo0m5pDNXwwo3QkxLsHHJ/EesTKUgeG NSrYMpJkvEdqZ08ym7O63lwqE6yMTwJ7+kNXg1OFXpY5CiUAOEr7Vl8pyGFajRhEygplv vWsLeFJNIhPROEmzbEdkXRBTP6r9syurETyNe+OJixXh7AfoNolQ1PYFxYojy4l6f/Q== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass header.d=linuxfoundation.org header.i=@linuxfoundation.org header.a=rsa-sha256 header.s=korg header.b=ijg8Mqeo; arc=none smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 0D80C606A327; Mon, 30 Nov 2026 12:09:24 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=linuxfoundation.org header.i=@linuxfoundation.org header.a=rsa-sha256 header.s=korg header.b=ijg8Mqeo Received: by smtp.kernel.org (Postfix) with ESMTPSA id 81FFC1F000C1; Mon, 30 Nov 2026 12:09:22 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linuxfoundation.org; s=korg; t=1796040564; bh=1nPEIjoD79ynNDAIIx7u064YTk0SP/nwh9nb0tIL7uw=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=ijg8MqeoiAyDj+qUR4bF7f27QEonjqWt2FCa+TU9dkM5+N3XI47dUslV3dzUoEujB HIYU9PbE5//ELaj1Ye5FbEb16aYYA5FIFH/snR5y//jTMn0g23QpVDGNJ/YT2c0VN+ q3rCszedntcHFaU5pQaSXSLR7ah8XaDxFE+rPc4Y= From: Greg Kroah-Hartman To: linux-kernel@vger.kernel.org, akpm@linux-foundation.org, torvalds@linux-foundation.org, stable@vger.kernel.org Cc: lwn@lwn.net, jslaby@suse.cz, Greg Kroah-Hartman Subject: Re: Linux 7.3.7 Date: Mon, 30 Nov 2026 13:09:03 +0100 Message-ID: <2026113003-eaten-overspend-5d26@gregkh> X-Mailer: git-send-email 2.56.1 In-Reply-To: <2026113003-plenty-task-df67@gregkh> References: <2026113003-plenty-task-df67@gregkh> X-Mailing-List: stable@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit diff --git a/Documentation/ABI/testing/sysfs-driver-intel-xe-gpu b/Documentation/ABI/testing/sysfs-driver-intel-xe-gpu new file mode 100644 index 000000000000..4dc4afc3961d --- /dev/null +++ b/Documentation/ABI/testing/sysfs-driver-intel-xe-gpu @@ -0,0 +1,10 @@ +What: /sys/bus/pci/drivers/xe/.../device_uid +Date: October 2026 +KernelVersion: 7.4 +Contact: intel-xe@lists.freedesktop.org +Description: + RO. Unique 64-bit identifier of the GPU SoC device, exposed as + hexadecimal value. + + This sysfs file is present only on supported Intel Xe platforms. + Accessible only to users with administrative privileges. 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 95faec78b7f7..f8bc2f7b7888 100644 --- a/Documentation/arch/arm64/silicon-errata.rst +++ b/Documentation/arch/arm64/silicon-errata.rst @@ -168,10 +168,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 | @@ -230,6 +238,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 | @@ -254,6 +264,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/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/filesystems/9p.rst b/Documentation/filesystems/9p.rst index 3f65db648db0..dc1f5f9632d8 100644 --- a/Documentation/filesystems/9p.rst +++ b/Documentation/filesystems/9p.rst @@ -228,7 +228,7 @@ Options any v9fs does single attach and performs all operations as one user - clien + client ACL based access check on the 9p client side for access validation 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/networking/net_cachelines/tcp_sock.rst b/Documentation/networking/net_cachelines/tcp_sock.rst index 0f6088c4ab8b..fc3fa0b16393 100644 --- a/Documentation/networking/net_cachelines/tcp_sock.rst +++ b/Documentation/networking/net_cachelines/tcp_sock.rst @@ -106,6 +106,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/networking/xfrm/xfrm_migrate_state.rst b/Documentation/networking/xfrm/xfrm_migrate_state.rst index 9d53cb22b007..ca2c9e5aaf33 100644 --- a/Documentation/networking/xfrm/xfrm_migrate_state.rst +++ b/Documentation/networking/xfrm/xfrm_migrate_state.rst @@ -27,15 +27,20 @@ SA Identification ================= The struct is defined in ``include/uapi/linux/xfrm.h``. The SA is looked -up using ``xfrm_state_lookup()`` with ``id.spi``, -``id.daddr``, ``id.proto``, ``id.family``, and -``old_mark.v & old_mark.m`` as the mark key:: +up using ``xfrm_state_lookup_exact()`` with ``id.spi``, ``id.daddr``, +``id.proto``, ``id.family``, and an exact match against ``old_mark.v`` +and ``old_mark.m``. Unlike the data path, which uses a masked +comparison, this requires the SA's mark and mask to equal ``old_mark`` +exactly, so a broad-mask SA is never matched when a more specific one +was intended. If no such SA exists, ``-ESRCH`` is returned. + +The layout is:: struct xfrm_user_migrate_state { struct xfrm_usersa_id id; /* spi, daddr, proto, family */ xfrm_address_t new_daddr; xfrm_address_t new_saddr; - struct xfrm_mark old_mark; /* SA lookup: key = v & m */ + struct xfrm_mark old_mark; /* SA lookup key (exact v/m match) */ struct xfrm_selector new_sel; /* new selector (see Flags) */ __u32 new_reqid; __u32 flags; /* XFRM_MIGRATE_STATE_* */ @@ -72,8 +77,8 @@ inherits the value from the existing SA (omit-to-inherit). - Description * - ``XFRMA_MARK`` - Mark on the migrated SA (``struct xfrm_mark``). Absent inherits - ``old_mark``. To use no mark on the new SA, send ``XFRMA_MARK`` - with ``{0, 0}``. + the mark of the existing SA. To use no mark on the new SA, send + ``XFRMA_MARK`` with ``{0, 0}``. * - ``XFRMA_ENCAP`` - UDP encapsulation template; only ``UDP_ENCAP_ESPINUDP`` is supported. Set ``encap_type=0`` to remove encap. @@ -259,8 +264,12 @@ Attributes in the notification Error Handling ============== -If the target SA tuple (new daddr, SPI, proto, new family) is already -occupied, the operation returns ``-EEXIST`` before the migration begins. +If the target SA tuple (new daddr, SPI, proto, new family, mark) is +already occupied, the operation returns ``-EEXIST`` before the migration +begins. "Occupied" includes wildcard shadowing: an existing SA with a +broader mask (e.g. mark 0/0) claims every mark value, so it blocks +migrating to any more specific mark at the same tuple, not just an +exact mark/mask duplicate. The old SA remains intact and the operation is safe to retry after resolving the conflict. diff --git a/Documentation/power/runtime_pm.rst b/Documentation/power/runtime_pm.rst index a53ab09c37d5..92281f70c9d3 100644 --- a/Documentation/power/runtime_pm.rst +++ b/Documentation/power/runtime_pm.rst @@ -8,6 +8,8 @@ Runtime Power Management Framework for I/O Devices (C) 2014 Intel Corp., Rafael J. Wysocki +.. _Section 1: + 1. Introduction =============== @@ -37,6 +39,8 @@ The runtime PM callbacks present in 'struct dev_pm_ops', the device runtime PM fields of 'struct dev_pm_info' and the core helper functions provided for runtime PM are described below. +.. _Section 2: + 2. Device Runtime PM Callbacks ============================== @@ -80,8 +84,8 @@ the PM core that it is safe to run the ->runtime_suspend(), ->runtime_resume() and ->runtime_idle() callbacks for the given device in atomic context with interrupts disabled. This implies that the callback routines in question must not block or sleep, but it also means that the synchronous helper functions -listed at the end of Section 4 may be used for that device within an interrupt -handler or generally in an atomic context. +listed at the end of `Section 4`_ may be used for that device within an +interrupt handler or generally in an atomic context. The subsystem-level suspend callback, if present, is _entirely_ _responsible_ for handling the suspend of the device as appropriate, which may, but need not @@ -105,9 +109,9 @@ knows what to do to handle the device). * If the suspend callback returns an error code different from -EBUSY and -EAGAIN, 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' (the PM core provides - special helper functions for this purpose). + the helper functions described in `Section 4`_ for the device until its + status is directly set to either 'active', or 'suspended' (the PM core + provides special helper functions for this purpose). In particular, if the driver requires remote wakeup capability (i.e. hardware mechanism allowing the device to request a change of its power state, such as @@ -131,11 +135,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 @@ -154,13 +159,18 @@ suspending the device are satisfied) and to queue up a suspend request for the device in that case. If there is no idle callback, or if the callback returns 0, then the PM core will attempt to carry out a runtime suspend of the device, also respecting devices configured for autosuspend. In essence this means a -call to pm_runtime_autosuspend(). To prevent this (for example, if the callback -routine has started a delayed suspend), the routine must return a non-zero -value. Negative error return codes are ignored by the PM core. +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(), 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. -The helper functions provided by the PM core, described in Section 4, guarantee -that the following constraints are met with respect to runtime PM callbacks for -one device: +The helper functions provided by the PM core, described in `Section 4`_, +guarantee that the following constraints are met with respect to runtime PM +callbacks for one device: (1) The callbacks are mutually exclusive (e.g. it is forbidden to execute ->runtime_suspend() in parallel with ->runtime_resume() or with another @@ -200,6 +210,8 @@ rules: scheduled requests to execute the other callbacks for the same device, except for scheduled autosuspends. +.. _Section 3: + 3. Runtime PM Device Fields =========================== @@ -301,6 +313,8 @@ defined in include/linux/pm.h: All of the above fields are members of the 'power' member of 'struct device'. +.. _Section 4: + 4. Runtime PM Device Helper Functions ===================================== @@ -529,6 +543,8 @@ It is safe to execute the following helper functions from interrupt context: - pm_request_resume() - pm_runtime_get_noresume() - pm_runtime_get() +- pm_runtime_get_if_active() +- pm_runtime_get_if_in_use() - pm_runtime_put_noidle() - pm_runtime_put() - pm_runtime_put_autosuspend() @@ -538,6 +554,9 @@ It is safe to execute the following helper functions from interrupt context: - pm_runtime_set_active() - pm_runtime_set_suspended() - pm_runtime_suspended() +- pm_runtime_active() +- pm_runtime_status_suspended() +- pm_runtime_enabled() - pm_runtime_mark_last_busy() - pm_runtime_autosuspend_expiration() @@ -549,16 +568,19 @@ functions may also be used in interrupt context: - pm_runtime_autosuspend() - pm_runtime_resume() - pm_runtime_get_sync() +- pm_runtime_resume_and_get() - pm_runtime_put_sync() - pm_runtime_put_sync_suspend() - pm_runtime_put_sync_autosuspend() +.. _Section 5: + 5. Runtime PM Initialization, Device Probing and Removal ======================================================== Initially, the runtime PM is disabled for all devices, which means that the -majority of the runtime PM helper functions described in Section 4 will return --EAGAIN until pm_runtime_enable() is called for the device. +majority of the runtime PM helper functions described in `Section 4`_ will +return -EACCES until pm_runtime_enable() is called for the device. In addition to that, the initial runtime PM status of all devices is 'suspended', but it need not reflect the actual physical state of the device. @@ -581,13 +603,13 @@ pm_runtime_set_suspended(). If the default initial runtime PM status of the device (i.e. 'suspended') reflects the actual state of the device, its bus type's or its driver's ->probe() callback will likely need to wake it up using one of the PM core's -helper functions described in Section 4. In that case, pm_runtime_resume() +helper functions described in `Section 4`_. In that case, pm_runtime_resume() should be used. Of course, for this purpose the device's runtime PM has to be enabled earlier by calling pm_runtime_enable(). Note, if the device may execute pm_runtime calls during the probe (such as if it is registered with a subsystem that may call back in) then the -pm_runtime_get_sync() call paired with a pm_runtime_put() call will be +pm_runtime_resume_and_get() call paired with a pm_runtime_put() call will be appropriate to ensure that the device is not put back to sleep during the probe. This can happen with systems such as the network device layer. @@ -615,7 +637,10 @@ removal of their drivers. Drivers in ->remove() callback should undo the runtime PM changes done in ->probe(). Usually this means calling pm_runtime_disable(), -pm_runtime_dont_use_autosuspend() etc. +pm_runtime_dont_use_autosuspend() etc. Alternatively, drivers can use +devm_pm_runtime_enable() during probe, which automatically takes care of +calling pm_runtime_disable() and pm_runtime_dont_use_autosuspend() upon driver +detachment. The user space can effectively disallow the driver of the device to power manage it at run time by changing the value of its /sys/devices/.../power/control @@ -629,6 +654,8 @@ value of /sys/devices/.../power/control to "auto" to allow the driver to power manage the device at run time, the driver may confuse it by using pm_runtime_forbid() this way. +.. _Section 6: + 6. Runtime PM and System Sleep ============================== @@ -721,12 +748,14 @@ out the following operations: callback and right after executing the subsystem-level .complete() callback for it, respectively. +.. _Section 7: + 7. Generic subsystem callbacks ============================== Subsystems may wish to conserve code space by using the set of generic power management callbacks provided by the PM core, defined in -driver/base/power/generic_ops.c: +drivers/base/power/generic_ops.c: `int pm_generic_runtime_suspend(struct device *dev);` - invoke the ->runtime_suspend() callback provided by the driver of this @@ -800,8 +829,10 @@ subsystem-level dev_pm_ops structure. Device drivers that wish to use the same function as a system suspend, freeze, poweroff and runtime suspend callback, and similarly for system resume, thaw, restore, and runtime resume, can achieve similar behaviour with the help of the -DEFINE_RUNTIME_DEV_PM_OPS() defined in include/linux/pm_runtime.h (possibly setting its -last argument to NULL). +DEFINE_RUNTIME_DEV_PM_OPS() macro defined in include/linux/pm_runtime.h +(possibly setting its last argument to NULL). + +.. _Section 8: 8. "No-Callback" Devices ======================== @@ -839,6 +870,8 @@ in subsystems/drivers, the PM core allows runtime PM callbacks to be unassigned. More precisely, if a callback pointer is NULL, the PM core will act as though there was a callback and it returned 0. +.. _Section 9: + 9. Autosuspend, or automatically-delayed suspends ================================================= @@ -864,7 +897,7 @@ registration the length should be controlled by user space, using the In order to use autosuspend, subsystems or drivers must call pm_runtime_use_autosuspend() (preferably before registering the device), and -thereafter they should use the various `*_autosuspend()` helper functions +thereafter they should use the various \*_autosuspend() helper functions instead of the non-autosuspend counterparts:: Instead of: pm_runtime_suspend use: pm_runtime_autosuspend; @@ -874,7 +907,7 @@ instead of the non-autosuspend counterparts:: Drivers may also continue to use the non-autosuspend helper functions; they will behave normally, which means sometimes taking the autosuspend delay into -account (see pm_runtime_idle). The autosuspend variants of the functions also +account (see pm_runtime_idle()). The autosuspend variants of the functions also call pm_runtime_mark_last_busy(). Under some circumstances a driver or subsystem may want to prevent a device @@ -917,7 +950,7 @@ Here is a schematic pseudo-code example:: int foo_runtime_suspend(struct device *dev) { - struct foo_priv foo = container_of(dev, ...); + struct foo_priv *foo = container_of(dev, ...); int ret = 0; lock(&foo->private_lock); @@ -933,7 +966,7 @@ Here is a schematic pseudo-code example:: int foo_runtime_resume(struct device *dev) { - struct foo_priv foo = container_of(dev, ...); + struct foo_priv *foo = container_of(dev, ...); lock(&foo->private_lock); /* ... resume the device ... */ diff --git a/Documentation/trace/kprobes.rst b/Documentation/trace/kprobes.rst index 5e606730cec6..0b19d82d7d4c 100644 --- a/Documentation/trace/kprobes.rst +++ b/Documentation/trace/kprobes.rst @@ -31,7 +31,7 @@ can trap at almost any kernel code address [1]_, specifying a handler routine to be invoked when the breakpoint is hit. .. [1] some parts of the kernel code can not be trapped, see - :ref:`kprobes_blacklist`) + :ref:`kprobes_blacklist` There are currently two types of probes: kprobes, and kretprobes (also called return probes). A kprobe can be inserted on virtually diff --git a/Makefile b/Makefile index 28ae92d9d760..77f1458a2a21 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ # SPDX-License-Identifier: GPL-2.0 VERSION = 7 PATCHLEVEL = 3 -SUBLEVEL = 6 +SUBLEVEL = 7 EXTRAVERSION = NAME = Baby Opossum Posse diff --git a/arch/arm/kernel/perf_regs.c b/arch/arm/kernel/perf_regs.c index 0529f90395c9..d575a4c3ca56 100644 --- a/arch/arm/kernel/perf_regs.c +++ b/arch/arm/kernel/perf_regs.c @@ -31,9 +31,3 @@ u64 perf_reg_abi(struct task_struct *task) return PERF_SAMPLE_REGS_ABI_32; } -void perf_get_regs_user(struct perf_regs *regs_user, - struct pt_regs *regs) -{ - regs_user->regs = task_pt_regs(current); - regs_user->abi = perf_reg_abi(current); -} diff --git a/arch/arm64/Kconfig b/arch/arm64/Kconfig index 70994918fab5..d353c673826c 100644 --- a/arch/arm64/Kconfig +++ b/arch/arm64/Kconfig @@ -1048,6 +1048,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 @@ -1083,14 +1115,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 e0c09402540c..84885c864470 100644 --- a/arch/arm64/kernel/cpu_errata.c +++ b/arch/arm64/kernel/cpu_errata.c @@ -391,13 +391,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), @@ -941,6 +961,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 3ae3ad1a1cdf..318e46063cd9 100644 --- a/arch/arm64/kernel/cpufeature.c +++ b/arch/arm64/kernel/cpufeature.c @@ -2089,7 +2089,8 @@ static void cpu_amu_enable(struct arm64_cpu_capabilities const *cap) cpumask_set_cpu(smp_processor_id(), &amu_cpus); /* 0 reference values signal broken/disabled counters */ - if (!this_cpu_has_cap(ARM64_WORKAROUND_BROKEN_AMU_CONSTCNT)) + if (!this_cpu_has_cap(ARM64_WORKAROUND_BROKEN_AMU_CONSTCNT) && + !this_cpu_has_cap(ARM64_WORKAROUND_BROKEN_AMU_CORECNT)) update_freq_counters_refs(); } } diff --git a/arch/arm64/kernel/kexec_image.c b/arch/arm64/kernel/kexec_image.c index b70f4df15a1a..46a30cc0000f 100644 --- a/arch/arm64/kernel/kexec_image.c +++ b/arch/arm64/kernel/kexec_image.c @@ -82,6 +82,13 @@ static void *image_load(struct kimage *image, kbuf.mem = KEXEC_BUF_MEM_UNKNOWN; kbuf.memsz = le64_to_cpu(h->image_size); text_offset = le64_to_cpu(h->text_offset); + /* + * A CMA segment is loaded and mapped through page_address(cma), which + * is the CMA base and cannot represent the text_offset adjustment + * below. Load images with a non-zero text_offset from normal memory. + */ + if (text_offset) + image->no_cma = true; kbuf.buf_align = MIN_KIMG_ALIGN; /* Adjust kernel segment with TEXT_OFFSET */ diff --git a/arch/arm64/kernel/perf_regs.c b/arch/arm64/kernel/perf_regs.c index b4eece3eb17d..70e2f13f587f 100644 --- a/arch/arm64/kernel/perf_regs.c +++ b/arch/arm64/kernel/perf_regs.c @@ -98,9 +98,3 @@ u64 perf_reg_abi(struct task_struct *task) return PERF_SAMPLE_REGS_ABI_64; } -void perf_get_regs_user(struct perf_regs *regs_user, - struct pt_regs *regs) -{ - regs_user->regs = task_pt_regs(current); - regs_user->abi = perf_reg_abi(current); -} diff --git a/arch/arm64/kernel/ptrace.c b/arch/arm64/kernel/ptrace.c index f743cbec1c3a..81afa70e5f29 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 c41724a40b75..cde0b8c19377 100644 --- a/arch/arm64/kernel/suspend.c +++ b/arch/arm64/kernel/suspend.c @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -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 @@ -117,6 +117,16 @@ alternative_else_nop_endif alternative_if ARM64_SME mrs_s x2, SYS_TPIDR2_EL0 str x2, [x0, #112] +alternative_else_nop_endif +alternative_if ARM64_HAS_S1POE + mrs x2, REG_POR_EL0 + str x2, [x0, #120] +alternative_else_nop_endif +alternative_if ARM64_HAS_GCS + mrs x2, REG_GCSPR_EL0 + str x2, [x0, #128] + mrs x2, REG_GCSCRE0_EL1 + str x2, [x0, #136] alternative_else_nop_endif ret SYM_FUNC_END(cpu_do_suspend) @@ -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 58b6c084f9f2..b3209eaf481a 100644 --- a/arch/arm64/tools/cpucaps +++ b/arch/arm64/tools/cpucaps @@ -132,3 +132,4 @@ WORKAROUND_SPECULATIVE_AT WORKAROUND_SPECULATIVE_SSBS WORKAROUND_SPECULATIVE_UNPRIV_LOAD WORKAROUND_BROKEN_AMU_CONSTCNT +WORKAROUND_BROKEN_AMU_CORECNT diff --git a/arch/csky/kernel/perf_regs.c b/arch/csky/kernel/perf_regs.c index 09b7f88a2d6a..94601f37b596 100644 --- a/arch/csky/kernel/perf_regs.c +++ b/arch/csky/kernel/perf_regs.c @@ -31,9 +31,3 @@ u64 perf_reg_abi(struct task_struct *task) return PERF_SAMPLE_REGS_ABI_32; } -void perf_get_regs_user(struct perf_regs *regs_user, - struct pt_regs *regs) -{ - regs_user->regs = task_pt_regs(current); - regs_user->abi = perf_reg_abi(current); -} diff --git a/arch/loongarch/include/asm/inst.h b/arch/loongarch/include/asm/inst.h index 585667e361c2..d24a20ba7a73 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 #include #include +#include #include #include @@ -56,6 +57,7 @@ int machine_kexec_prepare(struct kimage *kimage) */ memcpy((void *)KEXEC_CMDLINE_ADDR, (void *)kimage->arch.cmdline_ptr, strlen((char *)kimage->arch.cmdline_ptr) + 1); + kfree((void *)kimage->arch.cmdline_ptr); kimage->arch.cmdline_ptr = (unsigned long)KEXEC_CMDLINE_ADDR; } else { /* Find the command line */ diff --git a/arch/loongarch/kernel/machine_kexec_file.c b/arch/loongarch/kernel/machine_kexec_file.c index 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/kernel/perf_regs.c b/arch/loongarch/kernel/perf_regs.c index 263ac4ab5af6..8dd604f01745 100644 --- a/arch/loongarch/kernel/perf_regs.c +++ b/arch/loongarch/kernel/perf_regs.c @@ -45,9 +45,3 @@ u64 perf_reg_value(struct pt_regs *regs, int idx) return regs->regs[idx]; } -void perf_get_regs_user(struct perf_regs *regs_user, - struct pt_regs *regs) -{ - regs_user->regs = task_pt_regs(current); - regs_user->abi = perf_reg_abi(current); -} diff --git a/arch/loongarch/kvm/intc/dmsintc.c b/arch/loongarch/kvm/intc/dmsintc.c index 89f980d867be..41c8b597b5bd 100644 --- a/arch/loongarch/kvm/intc/dmsintc.c +++ b/arch/loongarch/kvm/intc/dmsintc.c @@ -166,6 +166,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 7b333a4a0430..6ee90c10827a 100644 --- a/arch/loongarch/kvm/intc/ipi.c +++ b/arch/loongarch/kvm/intc/ipi.c @@ -444,6 +444,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 2b63b0c2c7ce..75ad58a0f363 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 119a20a7edf1..5aaf52d9e89f 100644 --- a/arch/loongarch/net/bpf_jit.c +++ b/arch/loongarch/net/bpf_jit.c @@ -1768,7 +1768,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 */ @@ -2081,9 +2081,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 */ @@ -2436,7 +2437,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/mips/Kconfig b/arch/mips/Kconfig index d7c67cebe065..5538c8ef8225 100644 --- a/arch/mips/Kconfig +++ b/arch/mips/Kconfig @@ -79,7 +79,7 @@ config MIPS select HAVE_IRQ_TIME_ACCOUNTING select HAVE_KPROBES select HAVE_KRETPROBES - select HAVE_LD_DEAD_CODE_DATA_ELIMINATION + select HAVE_LD_DEAD_CODE_DATA_ELIMINATION if !FTRACE_MCOUNT_USE_RECORDMCOUNT select HAVE_MOD_ARCH_SPECIFIC select HAVE_NMI select HAVE_PAGE_SIZE_4KB if !CPU_LOONGSON2EF && !CPU_LOONGSON64 diff --git a/arch/mips/alchemy/common/irq.c b/arch/mips/alchemy/common/irq.c index 2403afcd2fb9..d2fa8731fb3c 100644 --- a/arch/mips/alchemy/common/irq.c +++ b/arch/mips/alchemy/common/irq.c @@ -892,15 +892,21 @@ static void __init au1000_init_irq(struct alchemy_irqmap *map) mips_cpu_irq_init(); /* register all 64 possible IC0+IC1 irq sources as type "none". + * Register each chip with the IRQ core before setting its type so + * the descriptors are included in interrupt enumeration. * Use set_irq_type() to set edge/level behaviour at runtime. */ for (irq_nr = AU1000_INTC0_INT_BASE; - (irq_nr < AU1000_INTC0_INT_BASE + 32); irq_nr++) + (irq_nr < AU1000_INTC0_INT_BASE + 32); irq_nr++) { + irq_set_chip(irq_nr, &au1x_ic0_chip); au1x_ic_settype(irq_get_irq_data(irq_nr), IRQ_TYPE_NONE); + } for (irq_nr = AU1000_INTC1_INT_BASE; - (irq_nr < AU1000_INTC1_INT_BASE + 32); irq_nr++) + (irq_nr < AU1000_INTC1_INT_BASE + 32); irq_nr++) { + irq_set_chip(irq_nr, &au1x_ic1_chip); au1x_ic_settype(irq_get_irq_data(irq_nr), IRQ_TYPE_NONE); + } /* * Initialize IC0, which is fixed per processor. @@ -947,6 +953,7 @@ static void __init alchemy_gpic_init_irq(const struct alchemy_irqmap *dints) /* register an irq_chip for them, with 2nd highest priority */ for (i = ALCHEMY_GPIC_INT_BASE; i <= ALCHEMY_GPIC_INT_LAST; i++) { + irq_set_chip(i, &au1300_gpic); au1300_set_irq_priority(i, 1); au1300_gpic_settype(irq_get_irq_data(i), IRQ_TYPE_NONE); } diff --git a/arch/mips/alchemy/common/prom.c b/arch/mips/alchemy/common/prom.c index 20d30f6265cd..c4aefeb78871 100644 --- a/arch/mips/alchemy/common/prom.c +++ b/arch/mips/alchemy/common/prom.c @@ -46,6 +46,11 @@ int prom_argc; char **prom_argv; char **prom_envp; +static char prom_ethaddr[6] __initdata; +static bool prom_ethaddr_valid __initdata; + +static void __init prom_init_ethernet_addr(void); + void __init prom_init_cmdline(void) { int i; @@ -95,6 +100,9 @@ void __init prom_init(void) if (!memsize_str || kstrtoul(memsize_str, 0, &memsize)) memsize = SZ_64M; /* minimum memsize is 64MB RAM */ + /* Save the MAC before the allocator can reuse the PROM environment. */ + prom_init_ethernet_addr(); + memblock_add(0, memsize); } @@ -125,7 +133,7 @@ static inline void str2eaddr(unsigned char *ea, unsigned char *str) } } -int __init prom_get_ethernet_addr(char *ethernet_addr) +static void __init prom_init_ethernet_addr(void) { char *ethaddr_str; @@ -135,12 +143,21 @@ int __init prom_get_ethernet_addr(char *ethernet_addr) /* Check command line */ ethaddr_str = strstr(arcs_cmdline, "ethaddr="); if (!ethaddr_str) - return -1; + return; ethaddr_str += strlen("ethaddr="); } - str2eaddr(ethernet_addr, ethaddr_str); + str2eaddr(prom_ethaddr, ethaddr_str); + prom_ethaddr_valid = true; +} + +int __init prom_get_ethernet_addr(char *ethernet_addr) +{ + if (!prom_ethaddr_valid) + return -1; + + memcpy(ethernet_addr, prom_ethaddr, sizeof(prom_ethaddr)); return 0; } diff --git a/arch/mips/cobalt/pci.c b/arch/mips/cobalt/pci.c index 85ec9cc31d66..29fd052766b2 100644 --- a/arch/mips/cobalt/pci.c +++ b/arch/mips/cobalt/pci.c @@ -14,6 +14,8 @@ #include +#include + extern struct pci_ops gt64xxx_pci0_ops; static struct resource cobalt_mem_resource = { @@ -24,7 +26,7 @@ static struct resource cobalt_mem_resource = { }; static struct resource cobalt_io_resource = { - .start = 0x1000, + .start = 0, .end = 0xffffffUL, .name = "PCI I/O", .flags = IORESOURCE_IO, @@ -38,11 +40,8 @@ static struct pci_controller cobalt_pci_controller = { .io_map_base = CKSEG1ADDR(GT_DEF_PCI0_IO_BASE), }; -static int __init cobalt_pci_init(void) +void __init cobalt_pci_init(void) { + PCIBIOS_MIN_IO = 0x1000; register_pci_controller(&cobalt_pci_controller); - - return 0; } - -arch_initcall(cobalt_pci_init); diff --git a/arch/mips/cobalt/setup.c b/arch/mips/cobalt/setup.c index 9a266bf78339..502acc92969b 100644 --- a/arch/mips/cobalt/setup.c +++ b/arch/mips/cobalt/setup.c @@ -83,9 +83,11 @@ void __init plat_mem_setup(void) /* I/O port resource */ ioport_resource.end = 0x01ffffff; + cobalt_pci_init(); + /* These resources have been reserved by VIA SuperI/O chip. */ for (i = 0; i < ARRAY_SIZE(cobalt_reserved_resources); i++) - request_resource(&ioport_resource, cobalt_reserved_resources + i); + insert_resource(&ioport_resource, cobalt_reserved_resources + i); } /* diff --git a/arch/mips/configs/ip30_defconfig b/arch/mips/configs/ip30_defconfig index 93eb90efe06e..a8b1a492f20c 100644 --- a/arch/mips/configs/ip30_defconfig +++ b/arch/mips/configs/ip30_defconfig @@ -40,7 +40,6 @@ CONFIG_INET6_AH=m CONFIG_INET6_ESP=m CONFIG_INET6_IPCOMP=m CONFIG_IPV6_MIP6=m -CONFIG_IPV6_SIT=m CONFIG_IPV6_SIT_6RD=y CONFIG_IPV6_TUNNEL=m CONFIG_IPV6_MULTIPLE_TABLES=y @@ -129,11 +128,14 @@ CONFIG_SERIAL_8250_IOC3=y CONFIG_NOZOMI=m CONFIG_HW_RANDOM_TIMERIOMEM=m # CONFIG_PTP_1588_CLOCK is not set +CONFIG_W1=y +CONFIG_W1_MASTER_SGI=y +CONFIG_W1_SLAVE_DS250X=y # CONFIG_HWMON is not set CONFIG_THERMAL=y CONFIG_SGI_MFD_IOC3=y CONFIG_RTC_CLASS=y -CONFIG_RTC_DRV_M48T35=y +CONFIG_RTC_DRV_DS1685_FAMILY=y CONFIG_UIO=y CONFIG_UIO_AEC=m CONFIG_UIO_SERCOS3=m @@ -162,15 +164,12 @@ CONFIG_NFS_FS=y CONFIG_SECURITYFS=y CONFIG_CRYPTO_CRYPTD=m CONFIG_CRYPTO_BLOWFISH=m -CONFIG_CRYPTO_CAMELLIA=m CONFIG_CRYPTO_CAST5=m CONFIG_CRYPTO_CAST6=m CONFIG_CRYPTO_SERPENT=m CONFIG_CRYPTO_TWOFISH=m -CONFIG_CRYPTO_CTS=m CONFIG_CRYPTO_LRW=m CONFIG_CRYPTO_XTS=m -CONFIG_CRYPTO_HMAC=y CONFIG_CRYPTO_MD4=m CONFIG_CRYPTO_RMD160=m CONFIG_CRYPTO_WP512=m diff --git a/arch/mips/include/asm/mach-cobalt/cobalt.h b/arch/mips/include/asm/mach-cobalt/cobalt.h index 97f9d5e9446d..c7a8607cd651 100644 --- a/arch/mips/include/asm/mach-cobalt/cobalt.h +++ b/arch/mips/include/asm/mach-cobalt/cobalt.h @@ -19,6 +19,7 @@ extern int cobalt_board_id; #define COBALT_BRD_ID_QUBE2 0x5 #define COBALT_BRD_ID_RAQ2 0x6 +void cobalt_pci_init(void); void cobalt_machine_halt(void); void cobalt_machine_restart(char *command); diff --git a/arch/mips/kernel/perf_regs.c b/arch/mips/kernel/perf_regs.c index e686780d1647..7736d3c5ebd2 100644 --- a/arch/mips/kernel/perf_regs.c +++ b/arch/mips/kernel/perf_regs.c @@ -60,9 +60,3 @@ u64 perf_reg_value(struct pt_regs *regs, int idx) return (s64)v; /* Sign extend if 32-bit. */ } -void perf_get_regs_user(struct perf_regs *regs_user, - struct pt_regs *regs) -{ - regs_user->regs = task_pt_regs(current); - regs_user->abi = perf_reg_abi(current); -} diff --git a/arch/mips/sgi-ip27/ip27-nmi.c b/arch/mips/sgi-ip27/ip27-nmi.c index fc2816398d0c..c502982621e6 100644 --- a/arch/mips/sgi-ip27/ip27-nmi.c +++ b/arch/mips/sgi-ip27/ip27-nmi.c @@ -1,4 +1,5 @@ // SPDX-License-Identifier: GPL-2.0 +#include #include #include #include @@ -183,6 +184,12 @@ static void nmi_dump(void) */ arch_spin_lock(&nmi_lock); + /* + * No CPU leaves the NMI handler before the hub reset below, so an + * nbcon console's printer thread would never print the dump. + */ + nbcon_cpu_emergency_enter(); + #ifdef REAL_NMI_SIGNAL /* * Wait up to 15 seconds for the other cpus to respond to the NMI. @@ -227,5 +234,6 @@ static void nmi_dump(void) * Save the nmi cpu registers for all cpu in the eframe format. */ nmi_eframes_save(); + printk_trigger_flush(); LOCAL_HUB_S(NI_PORT_RESET, NPR_PORTRESET | NPR_LOCALRESET); } diff --git a/arch/mips/sibyte/sb1250/irq.c b/arch/mips/sibyte/sb1250/irq.c index 2f08ad267a11..d7a656cd7ec0 100644 --- a/arch/mips/sibyte/sb1250/irq.c +++ b/arch/mips/sibyte/sb1250/irq.c @@ -76,6 +76,8 @@ static int sb1250_set_affinity(struct irq_data *d, const struct cpumask *mask, unsigned long flags; i = cpumask_first_and(mask, cpu_online_mask); + if (i >= nr_cpu_ids) + return -EINVAL; /* Convert logical CPU to physical CPU */ cpu = cpu_logical_map(i); @@ -103,6 +105,7 @@ static int sb1250_set_affinity(struct irq_data *d, const struct cpumask *mask, ____raw_writeq(cur_ints, IOADDR(A_IMR_MAPPER(cpu) + R_IMR_INTERRUPT_MASK)); } + irq_data_update_effective_affinity(d, cpumask_of(i)); raw_spin_unlock_irqrestore(&sb1250_imr_lock, flags); return 0; diff --git a/arch/parisc/kernel/perf_regs.c b/arch/parisc/kernel/perf_regs.c index 10a1a5f06a18..b9fe1f2fcb9b 100644 --- a/arch/parisc/kernel/perf_regs.c +++ b/arch/parisc/kernel/perf_regs.c @@ -53,9 +53,3 @@ u64 perf_reg_abi(struct task_struct *task) return PERF_SAMPLE_REGS_ABI_64; } -void perf_get_regs_user(struct perf_regs *regs_user, - struct pt_regs *regs) -{ - regs_user->regs = task_pt_regs(current); - regs_user->abi = perf_reg_abi(current); -} diff --git a/arch/powerpc/kernel/watchdog.c b/arch/powerpc/kernel/watchdog.c index c40c69368476..922dfa42ecd3 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/riscv/kernel/perf_regs.c b/arch/riscv/kernel/perf_regs.c index fd304a248de6..3bba8deababb 100644 --- a/arch/riscv/kernel/perf_regs.c +++ b/arch/riscv/kernel/perf_regs.c @@ -35,9 +35,3 @@ u64 perf_reg_abi(struct task_struct *task) #endif } -void perf_get_regs_user(struct perf_regs *regs_user, - struct pt_regs *regs) -{ - regs_user->regs = task_pt_regs(current); - regs_user->abi = perf_reg_abi(current); -} diff --git a/arch/s390/net/bpf_jit_comp.c b/arch/s390/net/bpf_jit_comp.c index 1b2566012b63..cddea4580843 100644 --- a/arch/s390/net/bpf_jit_comp.c +++ b/arch/s390/net/bpf_jit_comp.c @@ -2452,8 +2452,6 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr fp->jited_len = jit.size - cfi_get_offset(); if (!fp->is_func || extra_pass) { - for (int i = 0; i < fp->len; i++) - jit.addrs[i] -= cfi_get_offset(); bpf_prog_fill_jited_linfo(fp, jit.addrs + 1); free_addrs: kvfree(jit.addrs); diff --git a/arch/x86/events/amd/ibs.c b/arch/x86/events/amd/ibs.c index 3531f9c23b8c..66e67e27224f 100644 --- a/arch/x86/events/amd/ibs.c +++ b/arch/x86/events/amd/ibs.c @@ -28,6 +28,7 @@ static u32 ibs_caps; #include #include +#include #include /* attr.config2 */ @@ -73,7 +74,12 @@ static u32 ibs_caps; * * XXX: we could probably be using !atomic bitops for all this. */ - +/* + * NOTE: IBS_CAPS_DIS eliminates the RMW race on the IBS_{FETCH|OP}_CTL, making + * IBS_STARTED and IBS_STOPPED states unnecessary. We use only IBS_ENABLED and + * IBS_STOPPING states when IBS_CAPS_DIS is present. Semantics of IBS_STOPPING + * changes a bit as well. + */ enum ibs_states { IBS_ENABLED = 0, IBS_STARTED = 1, @@ -557,7 +563,9 @@ static void perf_ibs_start(struct perf_event *event, int flags) struct hw_perf_event *hwc = &event->hw; struct perf_ibs *perf_ibs = container_of(event->pmu, struct perf_ibs, pmu); struct cpu_perf_ibs *pcpu = this_cpu_ptr(perf_ibs->pcpu); + unsigned int delay = 50; u64 period, config = 0; + u64 ctl; if (WARN_ON_ONCE(!(hwc->state & PERF_HES_STOPPED))) return; @@ -575,23 +583,87 @@ static void perf_ibs_start(struct perf_event *event, int flags) } config |= period >> 4; - /* - * Reset the IBS_{FETCH|OP}_CTL MSR before updating pcpu->state. - * Doing so prevents a race condition in which an NMI due to other - * source might accidentally activate the event before we enable - * it ourselves. - */ - perf_ibs_disable_event(perf_ibs, hwc, 0); + if (ibs_caps & IBS_CAPS_DIS) { + /* + * IBS HW SW + * + * o Capture sample o ->stop() + * o Set VAL bit CTL2[Dis] = 1 + * o Raise NMI --. o ... + * \ o ->start() + * \ wrmsr(IBS_{FETCH|OP}_CTL, new value); + * \ (wrmsr clears the VAL bit) + * `--> o Receives delayed NMI + * (Unknown NMI since VAL bit is cleared) + * + * Handle this with induced delay. + */ + rdmsrq(hwc->config_base, ctl); + while ((ctl & perf_ibs->valid_mask) && delay--) { + udelay(1); + rdmsrq(hwc->config_base, ctl); + } + } else { + /* + * Reset the IBS_{FETCH|OP}_CTL MSR before updating pcpu->state. + * Doing so prevents a race condition in which an NMI due to + * other source might accidentally activate the event before we + * enable it ourselves. + */ + perf_ibs_disable_event(perf_ibs, hwc, 0); + /* + * Set STARTED before enabling the hardware, such that a + * subsequent NMI must observe it. + */ + set_bit(IBS_STARTED, pcpu->state); + clear_bit(IBS_STOPPING, pcpu->state); + } + perf_ibs_enable_event(perf_ibs, hwc, config); + + perf_event_update_userpage(event); +} + +/* ->stop() for platforms with additional CTL2[Dis] bit. */ +static void perf_ibs_stop_dis(struct perf_event *event, int flags) +{ + struct hw_perf_event *hwc = &event->hw; + struct perf_ibs *perf_ibs = container_of(event->pmu, struct perf_ibs, pmu); + struct cpu_perf_ibs *pcpu = this_cpu_ptr(perf_ibs->pcpu); + u64 config; + u64 ctl2; + + WARN_ON_ONCE(test_bit(IBS_STOPPING, pcpu->state)); + + set_bit(IBS_STOPPING, pcpu->state); + + rdmsrq(hwc->extra_reg.reg, ctl2); + if (ctl2 & perf_ibs->disable_mask) + goto reset_state; + + wrmsrq(hwc->extra_reg.reg, perf_ibs->disable_mask); + + WARN_ON_ONCE(hwc->state & PERF_HES_STOPPED); + hwc->state |= PERF_HES_STOPPED; + + if (hwc->state & PERF_HES_UPTODATE) + goto reset_state; + + rdmsrq(hwc->config_base, config); + + config &= ~perf_ibs->valid_mask; /* - * Set STARTED before enabling the hardware, such that a subsequent NMI - * must observe it. + * Clear the Val bit otherwise ->start() will unnecessarily + * wait for 50us. */ - set_bit(IBS_STARTED, pcpu->state); - clear_bit(IBS_STOPPING, pcpu->state); - perf_ibs_enable_event(perf_ibs, hwc, config); + if (in_nmi()) + wrmsrq(hwc->config_base, config); - perf_event_update_userpage(event); + perf_ibs_event_update(perf_ibs, event, &config); + hwc->state |= PERF_HES_UPTODATE; + +reset_state: + clear_bit(IBS_STOPPING, pcpu->state); } static void perf_ibs_stop(struct perf_event *event, int flags) @@ -602,6 +674,9 @@ static void perf_ibs_stop(struct perf_event *event, int flags) u64 config; int stopping; + if (ibs_caps & IBS_CAPS_DIS) + return perf_ibs_stop_dis(event, flags); + if (test_and_set_bit(IBS_STOPPING, pcpu->state)) return; @@ -1416,19 +1491,43 @@ static int perf_ibs_handle_irq(struct perf_ibs *perf_ibs, struct pt_regs *iregs) unsigned int msr; u64 *buf, *config, period, new_config = 0; int br_target_idx = -1; + u64 ctl2, ctl; - if (!test_bit(IBS_STARTED, pcpu->state)) { -fail: + if (ibs_caps & IBS_CAPS_DIS) { /* - * Catch spurious interrupts after stopping IBS: After - * disabling IBS there could be still incoming NMIs - * with samples that even have the valid bit cleared. - * Mark all this NMIs as handled. + * ->stop() { + * set_bit(IBS_STOPPING); + * <-- NMI (race 1) + * CTL2[Dis]=1; + * ... <-- NMI (race 2) + * } */ - if (test_and_clear_bit(IBS_STOPPED, pcpu->state)) - return 1; + rdmsrq(perf_ibs->msr2, ctl2); + if (test_bit(IBS_STOPPING, pcpu->state) /* race 1 */ || + (ctl2 & perf_ibs->disable_mask) /* race 2 */) { + rdmsrq(perf_ibs->msr, ctl); + if (ctl & perf_ibs->valid_mask) { + ctl &= ~(perf_ibs->enable_mask | + perf_ibs->valid_mask); + wrmsrq(perf_ibs->msr, ctl); + return 1; + } + return 0; + } + } else { + if (!test_bit(IBS_STARTED, pcpu->state)) { +fail: + /* + * Catch spurious interrupts after stopping IBS: After + * disabling IBS there could be still incoming NMIs + * with samples that even have the valid bit cleared. + * Mark all this NMIs as handled. + */ + if (test_and_clear_bit(IBS_STOPPED, pcpu->state)) + return 1; - return 0; + return 0; + } } if (WARN_ON_ONCE(!event)) @@ -1533,6 +1632,56 @@ static int perf_ibs_handle_irq(struct perf_ibs *perf_ibs, struct pt_regs *iregs) throttle = perf_event_account_interrupt(event); goto out; } + + /* + * IBS captured RIP is out of sync with NMI pt_regs due to NMI + * delivery latency. Use NMI pt_regs for PERF_SAMPLE_REGS_USER. + * + * Note: Valid user regs are required for PERF_SAMPLE_STACK_USER. + */ + if (event->attr.sample_type & (PERF_SAMPLE_REGS_USER | + PERF_SAMPLE_STACK_USER)) { + perf_sample_regs_user(&data.regs_user, iregs); + + /* + * Don't update dyn_size if user has not requested for + * PERF_SAMPLE_REGS_USER. + */ + if (event->attr.sample_type & PERF_SAMPLE_REGS_USER) { + /* regs dump ABI info */ + int size = sizeof(u64); + + if (data.regs_user.regs) { + u64 mask = event->attr.sample_regs_user; + size += hweight64(mask) * sizeof(u64); + } + + data.dyn_size += size; + } + + data.sample_flags |= PERF_SAMPLE_REGS_USER; + } + + /* + * IBS captured RIP is out of sync with NMI pt_regs due to NMI + * delivery latency. Use NMI pt_regs for PERF_SAMPLE_REGS_INTR. + */ + if (event->attr.sample_type & PERF_SAMPLE_REGS_INTR) { + /* regs dump ABI info */ + int size = sizeof(u64); + + perf_sample_regs_intr(&data.regs_intr, iregs, + event->attr.exclude_kernel); + + if (data.regs_intr.regs) { + u64 mask = event->attr.sample_regs_intr; + size += hweight64(mask) * sizeof(u64); + } + + data.dyn_size += size; + data.sample_flags |= PERF_SAMPLE_REGS_INTR; + } + /* * Prevent leaking physical addresses to unprivileged users. Skip * PERF_SAMPLE_PHYS_ADDR check since generic code prevents it for @@ -1948,7 +2097,7 @@ static int perf_ibs_suspend(void *data) static void perf_ibs_resume(void *data) { ibs_eilvt_setup(); - setup_APIC_ibs(); + x86_pmu_amd_ibs_starting_cpu(smp_processor_id()); } static const struct syscore_ops perf_ibs_syscore_ops = { diff --git a/arch/x86/events/amd/uncore.c b/arch/x86/events/amd/uncore.c index 7181973b5b12..b58e0ada8546 100644 --- a/arch/x86/events/amd/uncore.c +++ b/arch/x86/events/amd/uncore.c @@ -610,7 +610,7 @@ static void amd_uncore_ctx_move(struct amd_uncore *uncore, unsigned int cpu) for (i = 0; i < uncore->num_pmus; i++) { pmu = &uncore->pmus[i]; curr = *per_cpu_ptr(pmu->ctx, cpu); - if (!curr) + if (!curr || curr->cpu != cpu) continue; /* Migrate to a shared sibling if possible */ diff --git a/arch/x86/kernel/cpu/amd.c b/arch/x86/kernel/cpu/amd.c index 9edc08b867ca..0ad06dcc0735 100644 --- a/arch/x86/kernel/cpu/amd.c +++ b/arch/x86/kernel/cpu/amd.c @@ -1362,7 +1362,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/ftrace_64.S b/arch/x86/kernel/ftrace_64.S index 62c1c93aa1c6..4b20673a3395 100644 --- a/arch/x86/kernel/ftrace_64.S +++ b/arch/x86/kernel/ftrace_64.S @@ -286,9 +286,9 @@ SYM_INNER_LABEL(ftrace_regs_caller_end, SYM_L_GLOBAL) RET 1: - testb $1, %al - jz 2f - andq $0xfffffffffffffffe, %rax + /* See ftrace_jmp_set(), jmp to the trampoline */ + btsq $63, %rax + jc 2f movq %rax, MCOUNT_REG_SIZE+8(%rsp) restore_mcount_regs /* Restore flags */ 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/kernel/perf_regs.c b/arch/x86/kernel/perf_regs.c index 624703af80a1..81204cb7f723 100644 --- a/arch/x86/kernel/perf_regs.c +++ b/arch/x86/kernel/perf_regs.c @@ -100,12 +100,6 @@ u64 perf_reg_abi(struct task_struct *task) return PERF_SAMPLE_REGS_ABI_32; } -void perf_get_regs_user(struct perf_regs *regs_user, - struct pt_regs *regs) -{ - regs_user->regs = task_pt_regs(current); - regs_user->abi = perf_reg_abi(current); -} #else /* CONFIG_X86_64 */ #define REG_NOSUPPORT ((1ULL << PERF_REG_X86_DS) | \ (1ULL << PERF_REG_X86_ES) | \ diff --git a/arch/x86/net/bpf_jit_comp.c b/arch/x86/net/bpf_jit_comp.c index 10f68ee7c9e6..1b56cb973d79 100644 --- a/arch/x86/net/bpf_jit_comp.c +++ b/arch/x86/net/bpf_jit_comp.c @@ -1838,8 +1838,13 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int * * Arg 6 goes into r9 register, not on stack. */ outgoing_rsp = out_stack_arg_cnt > 1 ? (out_stack_arg_cnt - 1) * 8 : 0; + /* + * bpf_throw() sees rsp of this frame as it is at a call. The callee-saved + * regs are above the outgoing args, or above r9, which is pushed around + * every call when the stack is private. + */ if (bpf_prog->aux->exception_boundary) - bpf_prog->aux->stack_arg_sp_adjust = outgoing_rsp; + bpf_prog->aux->stack_arg_sp_adjust = outgoing_rsp + (priv_frame_ptr ? 8 : 0); emit_sub_rsp(&prog, outgoing_rsp); if (arena_vm_start) 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/blk-mq-sched.c b/block/blk-mq-sched.c index 0a00f5a76f5a..d7b45778732b 100644 --- a/block/blk-mq-sched.c +++ b/block/blk-mq-sched.c @@ -374,7 +374,7 @@ bool blk_mq_sched_try_insert_merge(struct request_queue *q, struct request *rq, } EXPORT_SYMBOL_GPL(blk_mq_sched_try_insert_merge); -/* called in queue's release handler, tagset has gone away */ +/* Clear scheduler tags and reset queue state. */ static void blk_mq_sched_tags_teardown(struct request_queue *q, unsigned int flags) { struct blk_mq_hw_ctx *hctx; @@ -385,6 +385,10 @@ static void blk_mq_sched_tags_teardown(struct request_queue *q, unsigned int fla if (blk_mq_is_shared_tags(flags)) q->sched_shared_tags = NULL; + + blk_queue_flag_clear(QUEUE_FLAG_SQ_SCHED, q); + q->nr_requests = q->tag_set->queue_depth; + q->async_depth = q->tag_set->queue_depth; } void blk_mq_sched_reg_debugfs(struct request_queue *q) diff --git a/block/blk-mq.c b/block/blk-mq.c index a162a64648c8..b75733e1785b 100644 --- a/block/blk-mq.c +++ b/block/blk-mq.c @@ -4341,7 +4341,10 @@ static void blk_mq_del_queue_tag_set(struct request_queue *q) lockdep_assert_held(&set->tag_list_lock); + /* blk_mq_unquiesce_tagset() runs the hctxs, which are not RCU freed */ + spin_lock(&set->quiesce_lock); list_del_rcu(&q->tag_set_list); + spin_unlock(&set->quiesce_lock); if (list_is_singular(&set->tag_list)) { /* just transitioned to unshared */ set->flags &= ~BLK_MQ_F_TAG_QUEUE_SHARED; diff --git a/block/genhd.c b/block/genhd.c index 10ca8b4d6eea..69204d44adae 100644 --- a/block/genhd.c +++ b/block/genhd.c @@ -1146,7 +1146,7 @@ static ssize_t disk_discard_alignment_show(struct device *dev, { struct gendisk *disk = dev_to_disk(dev); - return sysfs_emit(buf, "%d\n", bdev_alignment_offset(disk->part0)); + return sysfs_emit(buf, "%u\n", bdev_discard_alignment(disk->part0)); } static ssize_t diskseq_show(struct device *dev, diff --git a/block/partitions/efi.c b/block/partitions/efi.c index 9865d59093fa..b31227a13db0 100644 --- a/block/partitions/efi.c +++ b/block/partitions/efi.c @@ -460,6 +460,7 @@ static inline int is_pte_valid(const gpt_entry *pte, const u64 lastlba) { if ((!efi_guidcmp(pte->partition_type_guid, NULL_GUID)) || + le64_to_cpu(pte->starting_lba) > le64_to_cpu(pte->ending_lba) || le64_to_cpu(pte->starting_lba) > lastlba || le64_to_cpu(pte->ending_lba) > lastlba) return 0; diff --git a/crypto/essiv.c b/crypto/essiv.c index a47a3eab6935..3505b2769d93 100644 --- a/crypto/essiv.c +++ b/crypto/essiv.c @@ -250,7 +250,7 @@ static int essiv_aead_crypt(struct aead_request *req, bool enc) err = enc ? crypto_aead_encrypt(subreq) : crypto_aead_decrypt(subreq); - if (rctx->assoc && err != -EINPROGRESS && err != -EBUSY) + if (err != -EINPROGRESS && err != -EBUSY) kfree(rctx->assoc); return err; } diff --git a/drivers/accel/ivpu/ivpu_pm.c b/drivers/accel/ivpu/ivpu_pm.c index de0becbfdffb..6fd99645c68d 100644 --- a/drivers/accel/ivpu/ivpu_pm.c +++ b/drivers/accel/ivpu/ivpu_pm.c @@ -151,8 +151,8 @@ static void ivpu_pm_reset_complete(struct ivpu_device *vdev) up_write(&vdev->pm->reset_lock); atomic_set(&vdev->pm->reset_pending, 0); - pm_runtime_mark_last_busy(vdev->drm.dev); pm_runtime_enable(vdev->drm.dev); + pm_request_autosuspend(vdev->drm.dev); } static void ivpu_pm_recovery_work(struct work_struct *work) @@ -416,6 +416,7 @@ void ivpu_pm_init(struct ivpu_device *vdev) atomic_set(&pm->engine_reset_counter, 0); INIT_WORK(&pm->recovery_work, ivpu_pm_recovery_work); + disable_work(&pm->recovery_work); INIT_DELAYED_WORK(&pm->job_timeout_work, ivpu_job_timeout_work); if (ivpu_disable_recovery) @@ -440,6 +441,12 @@ void ivpu_pm_enable(struct ivpu_device *vdev) { struct device *dev = vdev->drm.dev; + enable_work(&vdev->pm->recovery_work); + if (atomic_read(&vdev->pm->reset_pending)) { + queue_work(system_dfl_wq, &vdev->pm->recovery_work); + flush_work(&vdev->pm->recovery_work); + } + pm_runtime_allow(dev); pm_runtime_put_autosuspend(dev); } diff --git a/drivers/acpi/apei/ghes.c b/drivers/acpi/apei/ghes.c index 4e7df028a0b8..0d83ed1a7e33 100644 --- a/drivers/acpi/apei/ghes.c +++ b/drivers/acpi/apei/ghes.c @@ -912,7 +912,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/power.c b/drivers/acpi/power.c index 23a4e207a01e..c77342a584f0 100644 --- a/drivers/acpi/power.c +++ b/drivers/acpi/power.c @@ -1121,6 +1121,44 @@ static const struct dmi_system_id dmi_leave_unused_power_resources_on[] = { } }, + { + /* + * Acer Swift 3 SF314-56G with NVIDIA MX250 suffers from the + * same ACPI power resource regression as the Thunderobot ZERO. + * The power resource controlling the dGPU is incorrectly turned off + * during initialization, causing the GPU to fall off the bus (D3cold). + */ + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "Acer"), + DMI_MATCH(DMI_PRODUCT_NAME, "Swift SF314-56G"), + } + + }, + { + /* + * CASPER EXCALIBUR G900 laptop: Keep unused ACPI power + * resources on to prevent the NVIDIA dGPU and NVMe #2 + * from becoming inaccessible. + */ + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "CASPER BILGISAYAR SISTEMLERI"), + DMI_MATCH(DMI_PRODUCT_NAME, "EXCALIBUR G900"), + DMI_MATCH(DMI_BOARD_NAME, "NLCC 001"), + }, + }, + { + /* + * Acer Aspire A515-53G: Two SSDTs both define power resources + * for the dGPU root port RP05 ('PC01' and 'PCRP'). Only PC01 ends + * up in RP05's _PR0/_PR3, so 'PCRP' is shut down on + * initialization, cutting power to the NVIDIA dGPU behind the + * back of 'PC01' and making the dGPU unavailable. + */ + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "Acer"), + DMI_MATCH(DMI_PRODUCT_NAME, "Aspire A515-53G"), + }, + }, {} }; diff --git a/drivers/acpi/scan.c b/drivers/acpi/scan.c index e8189849eaa6..ba2f03854591 100644 --- a/drivers/acpi/scan.c +++ b/drivers/acpi/scan.c @@ -114,11 +114,7 @@ bool acpi_scan_is_offline(struct acpi_device *adev, bool uevent) bool offline = true; char *envp[] = { "EVENT=offline", NULL }; - /* - * acpi_container_offline() calls this for all of the container's - * children under the container's physical_node_lock lock. - */ - mutex_lock_nested(&adev->physical_node_lock, SINGLE_DEPTH_NESTING); + mutex_lock(&adev->physical_node_lock); list_for_each_entry(pn, &adev->physical_node_list, node) if (device_supports_offline(pn->dev) && !dev_offline(pn->dev)) { @@ -133,6 +129,59 @@ bool acpi_scan_is_offline(struct acpi_device *adev, bool uevent) return offline; } +static struct acpi_device_physical_node * +acpi_find_physical_node(struct acpi_device *adev, struct device *dev) +{ + struct acpi_device_physical_node *pn; + + lockdep_assert_held(&adev->physical_node_lock); + + list_for_each_entry(pn, &adev->physical_node_list, node) + if (pn->dev == dev) + return pn; + + return NULL; +} + +static struct device *acpi_next_offline_pending(struct acpi_device *adev) +{ + struct acpi_device_physical_node *pn; + + lockdep_assert_held(&adev->physical_node_lock); + + /* + * Find the first physical node that is still to be offlined, clear its + * offline_pending flag and return its device with a reference held. + */ + list_for_each_entry(pn, &adev->physical_node_list, node) + if (pn->offline_pending) { + pn->offline_pending = false; + return get_device(pn->dev); + } + + return NULL; +} + +static struct device *acpi_next_put_online(struct acpi_device *adev) +{ + struct acpi_device_physical_node *pn; + + lockdep_assert_held(&adev->physical_node_lock); + + /* + * Find the first physical node that has been offlined by + * acpi_bus_offline(), clear its put_online flag and return its device + * with a reference held. + */ + list_for_each_entry(pn, &adev->physical_node_list, node) + if (pn->put_online) { + pn->put_online = false; + return get_device(pn->dev); + } + + return NULL; +} + static acpi_status acpi_bus_offline(acpi_handle handle, u32 lvl, void *data, void **ret_p) { @@ -140,6 +189,7 @@ static acpi_status acpi_bus_offline(acpi_handle handle, u32 lvl, void *data, struct acpi_device_physical_node *pn; bool second_pass = (bool)data; acpi_status status = AE_OK; + struct device *dev; if (!device) return AE_OK; @@ -152,25 +202,43 @@ static acpi_status acpi_bus_offline(acpi_handle handle, u32 lvl, void *data, mutex_lock(&device->physical_node_lock); list_for_each_entry(pn, &device->physical_node_list, node) { - int ret; - if (second_pass) { /* Skip devices offlined by the first pass. */ - if (pn->put_online) - continue; + pn->offline_pending = !pn->put_online; } else { + pn->offline_pending = true; pn->put_online = false; } - ret = device_offline(pn->dev); + } + + /* + * Drop physical_node_lock around device_offline(), because the latter + * acquires locks, like the CPU hotplug ones, that must not nest under + * it. + */ + while ((dev = acpi_next_offline_pending(device))) { + int ret; + + mutex_unlock(&device->physical_node_lock); + ret = device_offline(dev); + mutex_lock(&device->physical_node_lock); + if (ret >= 0) { - pn->put_online = !ret; + /* The device may have been unbound in the meantime. */ + pn = acpi_find_physical_node(device, dev); + if (pn) + pn->put_online = !ret; } else { - *ret_p = pn->dev; + *ret_p = &device->dev; if (second_pass) { + dev_warn(dev, "Offline failed.\n"); status = AE_ERROR; - break; } } + + put_device(dev); + if (ACPI_FAILURE(status)) + break; } mutex_unlock(&device->physical_node_lock); @@ -182,18 +250,19 @@ static acpi_status acpi_bus_online(acpi_handle handle, u32 lvl, void *data, void **ret_p) { struct acpi_device *device = acpi_fetch_acpi_dev(handle); - struct acpi_device_physical_node *pn; + struct device *dev; if (!device) return AE_OK; mutex_lock(&device->physical_node_lock); - list_for_each_entry(pn, &device->physical_node_list, node) - if (pn->put_online) { - device_online(pn->dev); - pn->put_online = false; - } + while ((dev = acpi_next_put_online(device))) { + mutex_unlock(&device->physical_node_lock); + device_online(dev); + mutex_lock(&device->physical_node_lock); + put_device(dev); + } mutex_unlock(&device->physical_node_lock); @@ -235,7 +304,6 @@ static int acpi_scan_try_to_offline(struct acpi_device *device) (void **)&errdev); if (errdev) { - dev_warn(errdev, "Offline failed.\n"); acpi_bus_online(handle, 0, NULL, NULL); acpi_walk_namespace(ACPI_TYPE_ANY, handle, ACPI_UINT32_MAX, acpi_bus_online, diff --git a/drivers/ata/libata-core.c b/drivers/ata/libata-core.c index 30572ca510de..e61bc880dc4e 100644 --- a/drivers/ata/libata-core.c +++ b/drivers/ata/libata-core.c @@ -2059,6 +2059,10 @@ void ata_dev_power_set_standby(struct ata_device *dev) struct ata_taskfile tf; unsigned int err_mask; + /* Issue STANDBY IMMEDIATE command only if supported by the device */ + if (!ata_dev_power_init_tf(dev, &tf, false)) + return; + /* If the device is already sleeping or in standby, do nothing. */ if ((dev->flags & ATA_DFLAG_SLEEPING) || !ata_dev_power_is_active(dev)) @@ -2077,10 +2081,6 @@ void ata_dev_power_set_standby(struct ata_device *dev) system_entering_hibernation()) return; - /* Issue STANDBY IMMEDIATE command only if supported by the device */ - if (!ata_dev_power_init_tf(dev, &tf, false)) - return; - ata_dev_notice(dev, "Entering standby power mode\n"); err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0); diff --git a/drivers/ata/libata-eh.c b/drivers/ata/libata-eh.c index c93c24b22d9c..fd7ce2abfbcf 100644 --- a/drivers/ata/libata-eh.c +++ b/drivers/ata/libata-eh.c @@ -4077,8 +4077,20 @@ void ata_eh_finish(struct ata_port *ap) ata_eh_qc_complete(qc); } } else { - if (qc->flags & ATA_QCFLAG_SENSE_VALID || - qc->flags & ATA_QCFLAG_EH_SUCCESS_CMD) { + if (qc->flags & ATA_QCFLAG_SENSE_VALID && + qc->flags & ATA_QCFLAG_RETRY) { + /* + * The sense data asks for a retry, see + * ata_eh_analyze_tf(). ata_eh_link_autopsy() + * cleared qc->err_mask, so ata_eh_qc_retry() + * would increment scmd->allowed. Leave + * scmd->allowed alone, so that upper layer + * only retries the command if it has not + * already been retried too many times. + */ + __ata_eh_qc_complete(qc); + } else if (qc->flags & ATA_QCFLAG_SENSE_VALID || + qc->flags & ATA_QCFLAG_EH_SUCCESS_CMD) { ata_eh_qc_complete(qc); } else { /* feed zero TF to sense generation */ diff --git a/drivers/ata/libata-sata.c b/drivers/ata/libata-sata.c index ad40f516c6d4..7078f168def8 100644 --- a/drivers/ata/libata-sata.c +++ b/drivers/ata/libata-sata.c @@ -1287,7 +1287,7 @@ int ata_change_queue_depth(struct ata_port *ap, struct scsi_device *sdev, spin_lock_irqsave(ap->lock, flags); dev = ata_scsi_find_dev(ap, sdev); - if (!dev || queue_depth < 1 || queue_depth == sdev->queue_depth) { + if (!dev || queue_depth < 1) { spin_unlock_irqrestore(ap->lock, flags); return sdev->queue_depth; } diff --git a/drivers/ata/libata-scsi.c b/drivers/ata/libata-scsi.c index 5be2e2597770..c423a9153556 100644 --- a/drivers/ata/libata-scsi.c +++ b/drivers/ata/libata-scsi.c @@ -4325,14 +4325,22 @@ static unsigned int ata_scsi_zbc_out_xlat(struct ata_queued_cmd *qc) /** * ata_mselect_caching - Simulate MODE SELECT for caching info page * @qc: Storage for translated ATA taskfile - * @buf: input buffer - * @len: number of valid bytes in the input buffer - * @fp: out parameter for the failed field on error + * @buf: Mode page, starting with the mode page header + * @len: Length of the mode page, including the mode page header + * @fp: Out parameter, offset in @buf of the first invalid byte on error * * Prepare a taskfile to modify caching information for the device. * + * The caller has stripped the mode parameter header and the block + * descriptors, so @buf points at the mode page header, like the buffer + * filled by the ata_msense_*() functions, and offsets in @buf, including + * the one returned in @fp, are the byte numbers of the mode page. + * * LOCKING: * None. + * + * RETURNS: + * 0 if a taskfile was prepared, -EINVAL if the mode page is invalid. */ static int ata_mselect_caching(struct ata_queued_cmd *qc, const u8 *buf, int len, u16 *fp) @@ -4343,26 +4351,19 @@ static int ata_mselect_caching(struct ata_queued_cmd *qc, u8 wce; int i; - /* - * The first two bytes of def_cache_mpage are a header, so offsets - * in mpage are off by 2 compared to buf. Same for len. - */ - - if (len != CACHE_MPAGE_LEN - 2) { - *fp = min(len, CACHE_MPAGE_LEN - 2); + if (len != CACHE_MPAGE_LEN) { + *fp = 1; return -EINVAL; } - wce = buf[0] & (1 << 2); + wce = buf[2] & (1 << 2); /* * Check that read-only bits are not modified. */ ata_msense_caching(dev->id, mpage, false); - for (i = 0; i < CACHE_MPAGE_LEN - 2; i++) { - if (i == 0) - continue; - if (mpage[i + 2] != buf[i]) { + for (i = 3; i < CACHE_MPAGE_LEN; i++) { + if (mpage[i] != buf[i]) { *fp = i; return -EINVAL; } @@ -4376,8 +4377,26 @@ static int ata_mselect_caching(struct ata_queued_cmd *qc, return 0; } -/* - * Simulate MODE SELECT control mode page, sub-page 0. +/** + * ata_mselect_control_spg0 - Simulate MODE SELECT for control sub-page 0 + * @qc: Storage for translated ATA taskfile + * @buf: Mode page, starting with the mode page header + * @len: Length of the mode page, including the mode page header + * @fp: Out parameter, offset in @buf of the first invalid byte on error + * + * Simulate MODE SELECT control mode page, sub-page 0. + * + * The caller has stripped the mode parameter header and the block + * descriptors, so @buf points at the mode page header, like the buffer + * filled by the ata_msense_*() functions, and offsets in @buf, including + * the one returned in @fp, are the byte numbers of the mode page. + * + * LOCKING: + * None. + * + * RETURNS: + * 0, as no ATA command needs to be sent, or -EINVAL if the mode page is + * invalid. */ static int ata_mselect_control_spg0(struct ata_queued_cmd *qc, const u8 *buf, int len, u16 *fp) @@ -4387,26 +4406,19 @@ static int ata_mselect_control_spg0(struct ata_queued_cmd *qc, u8 d_sense; int i; - /* - * The first two bytes of def_control_mpage are a header, so offsets - * in mpage are off by 2 compared to buf. Same for len. - */ - - if (len != CONTROL_MPAGE_LEN - 2) { - *fp = min(len, CONTROL_MPAGE_LEN - 2); + if (len != CONTROL_MPAGE_LEN) { + *fp = 1; return -EINVAL; } - d_sense = buf[0] & (1 << 2); + d_sense = buf[2] & (1 << 2); /* * Check that read-only bits are not modified. */ ata_msense_control_spg0(dev, mpage, false); - for (i = 0; i < CONTROL_MPAGE_LEN - 2; i++) { - if (i == 0) - continue; - if (mpage[2 + i] != buf[i]) { + for (i = 3; i < CONTROL_MPAGE_LEN; i++) { + if (mpage[i] != buf[i]) { *fp = i; return -EINVAL; } @@ -4418,9 +4430,27 @@ static int ata_mselect_control_spg0(struct ata_queued_cmd *qc, return 0; } -/* - * Translate MODE SELECT control mode page, sub-page f2h (ATA feature mode - * page) into a SET FEATURES command. +/** + * ata_mselect_control_ata_feature - Translate ATA Feature Control page + * @qc: Storage for translated ATA taskfile + * @buf: Mode page, starting with the mode page header + * @len: Length of the mode page, including the mode page header + * @fp: Out parameter, offset in @buf of the first invalid byte on error + * + * Translate MODE SELECT control mode page, sub-page f2h (ATA feature mode + * page) into a SET FEATURES command. + * + * The caller has stripped the mode parameter header and the block + * descriptors, so @buf points at the mode page header, like the buffer + * filled by the ata_msense_*() functions, and offsets in @buf, including + * the one returned in @fp, are the byte numbers of the mode page. + * + * LOCKING: + * None. + * + * RETURNS: + * 1 if a taskfile was prepared, -EINVAL if the mode page is invalid or if + * CDL cannot be enabled. */ static int ata_mselect_control_ata_feature(struct ata_queued_cmd *qc, const u8 *buf, int len, u16 *fp) @@ -4429,17 +4459,13 @@ static int ata_mselect_control_ata_feature(struct ata_queued_cmd *qc, struct ata_taskfile *tf = &qc->tf; u8 cdl_action; - /* - * The first four bytes of ATA Feature Control mode page are a header, - * so offsets in mpage are off by 4 compared to buf. Same for len. - */ - if (len != ATA_FEATURE_SUB_MPAGE_LEN - 4) { - *fp = min(len, ATA_FEATURE_SUB_MPAGE_LEN - 4); + if (len != ATA_FEATURE_SUB_MPAGE_LEN) { + *fp = 2; return -EINVAL; } /* Check cdl_ctrl */ - switch (buf[0] & 0x03) { + switch (buf[4] & 0x03) { case 0: /* Disable CDL */ ata_dev_dbg(dev, "Disabling CDL\n"); @@ -4454,6 +4480,7 @@ static int ata_mselect_control_ata_feature(struct ata_queued_cmd *qc, if (dev->flags & ATA_DFLAG_NCQ_PRIO_ENABLED) { ata_dev_err(dev, "NCQ priority must be disabled to enable CDL\n"); + *fp = 4; return -EINVAL; } ata_dev_dbg(dev, "Enabling CDL\n"); @@ -4461,7 +4488,7 @@ static int ata_mselect_control_ata_feature(struct ata_queued_cmd *qc, dev->flags |= ATA_DFLAG_CDL_ENABLED; break; default: - *fp = 0; + *fp = 4; return -EINVAL; } @@ -4477,15 +4504,24 @@ static int ata_mselect_control_ata_feature(struct ata_queued_cmd *qc, /** * ata_mselect_control - Simulate MODE SELECT for control page * @qc: Storage for translated ATA taskfile - * @spg: target sub-page of the control page - * @buf: input buffer - * @len: number of valid bytes in the input buffer - * @fp: out parameter for the failed field on error + * @spg: Sub-page of the control page, 0 or ATA_FEATURE_SUB_MPAGE + * @buf: Mode page, starting with the mode page header + * @len: Length of the mode page, including the mode page header + * @fp: Out parameter, offset in @buf of the first invalid byte on error * - * Prepare a taskfile to modify caching information for the device. + * Call the handler of sub-page @spg of the control mode page. + * + * The caller has stripped the mode parameter header and the block + * descriptors, so @buf points at the mode page header, like the buffer + * filled by the ata_msense_*() functions, and offsets in @buf, including + * the one returned in @fp, are the byte numbers of the mode page. * * LOCKING: * None. + * + * RETURNS: + * 0 if no ATA command needs to be sent, 1 if a taskfile was prepared, + * -EINVAL if the mode page is invalid. */ static int ata_mselect_control(struct ata_queued_cmd *qc, u8 spg, const u8 *buf, int len, u16 *fp) @@ -4572,7 +4608,6 @@ static unsigned int ata_scsi_mode_select_xlat(struct ata_queued_cmd *qc) goto invalid_param_len; if (bd_len != 0 && bd_len != 8) { fp = (six_byte) ? 3 : 6; - fp += bd_len + hdr_len; goto invalid_param; } @@ -4587,48 +4622,56 @@ static unsigned int ata_scsi_mode_select_xlat(struct ata_queued_cmd *qc) if (len < 4) goto invalid_param_len; + /* + * Mode pages with subpage code 00h use the page_0 format: SAT + * defines the SPF bit of the Caching and Control mode pages, + * for subpage code 00h, as not changeable and set to zero. + */ spg = p[1]; - pg_len = get_unaligned_be16(&p[2]); - p += 4; - len -= 4; + if (!spg) { + fp = hdr_len + bd_len; + goto invalid_param; + } + + pg_len = get_unaligned_be16(&p[2]) + 4; } else { if (len < 2) goto invalid_param_len; spg = 0; - pg_len = p[1]; - p += 2; - len -= 2; + pg_len = p[1] + 2; } /* - * Supported subpages: all subpages and ATA feature sub-page f2h of - * the control page. + * The only supported subpage is the ATA feature sub-page f2h of the + * control page. */ if (spg) { switch (spg) { - case ALL_SUB_MPAGES: - /* All subpages is not supported for the control page */ - if (pg == CONTROL_MPAGE) { - fp = (p[0] & 0x40) ? 1 : 0; - fp += hdr_len + bd_len; - goto invalid_param; - } - break; case ATA_FEATURE_SUB_MPAGE: if (qc->dev->flags & ATA_DFLAG_CDL && pg == CONTROL_MPAGE) break; fallthrough; default: - fp = (p[0] & 0x40) ? 1 : 0; - fp += hdr_len + bd_len; + fp = hdr_len + bd_len + 1; goto invalid_param; } } if (pg_len > len) goto invalid_param_len; + /* + * A MODE SELECT command is translated into at most one ATA command, so + * only one mode page per command is supported. Reject any data after + * the mode page before calling the mode page handlers, which may + * already update the device flags. + */ + if (len > pg_len) { + fp = p - buffer + pg_len; + goto invalid_param; + } + switch (pg) { case CACHE_MPAGE: if (ata_mselect_caching(qc, p, pg_len, &fp) < 0) { @@ -4651,13 +4694,6 @@ static unsigned int ata_scsi_mode_select_xlat(struct ata_queued_cmd *qc) goto invalid_param; } - /* - * Only one page has changeable data, so we only support setting one - * page at a time. - */ - if (len > pg_len) - goto invalid_param; - return 0; invalid_fld: diff --git a/drivers/base/power/runtime.c b/drivers/base/power/runtime.c index f18d99c8d052..d36c72c5b526 100644 --- a/drivers/base/power/runtime.c +++ b/drivers/base/power/runtime.c @@ -822,6 +822,12 @@ static int rpm_resume(struct device *dev, int rpmflags) pm_runtime_deactivate_timer(dev); if (dev->power.runtime_status == RPM_ACTIVE) { + /* + * The attempt to resume the device means that it is needed for + * something, so update its last_busy timestamp as in the case + * in which it actually resumes below. + */ + pm_runtime_mark_last_busy(dev); retval = 1; goto out; } @@ -1899,7 +1905,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/block/null_blk/zoned.c b/drivers/block/null_blk/zoned.c index 7e9b5ffb9e84..015f5d304c7c 100644 --- a/drivers/block/null_blk/zoned.c +++ b/drivers/block/null_blk/zoned.c @@ -311,10 +311,8 @@ static blk_status_t null_check_open(struct nullb_device *dev) return BLK_STS_OK; if (dev->nr_zones_imp_open) { - if (null_check_active(dev) == BLK_STS_OK) { - null_close_imp_open_zone(dev); - return BLK_STS_OK; - } + null_close_imp_open_zone(dev); + return BLK_STS_OK; } return BLK_STS_ZONE_OPEN_RESOURCE; @@ -330,8 +328,11 @@ static blk_status_t null_check_open(struct nullb_device *dev) * * ZBC states that an implicit open zone shall be closed only if there is not * room within the open limit. However, with the addition of an active limit, - * it is not certain that closing an implicit open zone will allow a new zone - * to be opened, since we might already be at the active limit capacity. + * it is not certain that closing an implicit open zone will allow an empty + * zone to be opened, since we might already be at the active limit capacity. + * Therefore, the active limit is checked first for an empty zone. A closed + * zone already holds an active zone resource, so only the open limit has to + * be checked for a closed zone. */ static blk_status_t null_check_zone_resources(struct nullb_device *dev, struct nullb_zone *zone) @@ -742,6 +743,33 @@ blk_status_t null_process_zoned_cmd(struct nullb_cmd *cmd, enum req_op op, } } +/* + * Release the zone resources held by a zone, before changing the condition of + * the zone to a condition that does not hold any zone resources. + */ +static void null_release_zone_resources(struct nullb_device *dev, + struct nullb_zone *zone) +{ + if (!dev->need_zone_res_mgmt) + return; + + spin_lock(&dev->zone_res_lock); + switch (zone->cond) { + case BLK_ZONE_COND_IMP_OPEN: + dev->nr_zones_imp_open--; + break; + case BLK_ZONE_COND_EXP_OPEN: + dev->nr_zones_exp_open--; + break; + case BLK_ZONE_COND_CLOSED: + dev->nr_zones_closed--; + break; + default: + break; + } + spin_unlock(&dev->zone_res_lock); +} + /* * Set a zone in the read-only or offline condition. */ @@ -758,8 +786,8 @@ static void null_set_zone_cond(struct nullb_device *dev, * If the read-only condition is requested again to zones already in * read-only condition, restore back normal empty condition. Do the same * if the offline condition is requested for offline zones. Otherwise, - * set the specified zone condition to the zones. Finish the zones - * beforehand to free up zone resources. + * set the specified zone condition to the zones. Release the zone + * resources held by the zones beforehand. */ if (zone->cond == cond) { zone->cond = BLK_ZONE_COND_EMPTY; @@ -767,9 +795,7 @@ static void null_set_zone_cond(struct nullb_device *dev, if (dev->memory_backed) null_handle_discard(dev, zone->start, zone->len); } else { - if (zone->cond != BLK_ZONE_COND_READONLY && - zone->cond != BLK_ZONE_COND_OFFLINE) - null_finish_zone(dev, zone); + null_release_zone_resources(dev, zone); zone->cond = cond; zone->wp = NULL_ZONE_INVALID_WP; } diff --git a/drivers/block/ublk_drv.c b/drivers/block/ublk_drv.c index cc4e72fd5d4d..8d3406147b96 100644 --- a/drivers/block/ublk_drv.c +++ b/drivers/block/ublk_drv.c @@ -4403,14 +4403,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); @@ -4421,6 +4425,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); @@ -4971,6 +4988,8 @@ static int ublk_ctrl_add_dev(const struct ublksrv_ctrl_cmd *header) * ublk_add_chdev() will cleanup everything if it fails. */ ret = ublk_add_chdev(ub); + if (!ret) + ublk_publish_dev_number(ub); goto out_unlock; out_deinit_queues: diff --git a/drivers/block/virtio_blk.c b/drivers/block/virtio_blk.c index 10ba8b0b863b..2b462005cdb6 100644 --- a/drivers/block/virtio_blk.c +++ b/drivers/block/virtio_blk.c @@ -331,18 +331,25 @@ static inline u8 virtblk_vbr_status(struct virtblk_req *vbr) return *((u8 *)&vbr->in_hdr + vbr->in_hdr_len - 1); } +static inline void virtblk_update_zone_append_sector(struct request *req, + struct virtblk_req *vbr) +{ + struct virtio_blk *vblk = req->mq_hctx->queue->queuedata; + + if (req_op(req) == REQ_OP_ZONE_APPEND) + req->__sector = virtio64_to_cpu(vblk->vdev, + vbr->in_hdr.zone_append.sector); +} + static inline void virtblk_request_done(struct request *req) { struct virtblk_req *vbr = blk_mq_rq_to_pdu(req); blk_status_t status = virtblk_result(virtblk_vbr_status(vbr)); - struct virtio_blk *vblk = req->mq_hctx->queue->queuedata; virtblk_unmap_data(req, vbr); virtblk_cleanup_cmd(req); - if (req_op(req) == REQ_OP_ZONE_APPEND) - req->__sector = virtio64_to_cpu(vblk->vdev, - vbr->in_hdr.zone_append.sector); + virtblk_update_zone_append_sector(req, vbr); blk_mq_end_request(req, status); } @@ -958,16 +965,13 @@ static void virtblk_config_changed(struct virtio_device *vdev) queue_work(virtblk_wq, &vblk->config_work); } -static int init_vq(struct virtio_blk *vblk) +/* Keep the queue layout unchanged for the lifetime of the tag set. */ +static int virtblk_init_queue_layout(struct virtio_blk *vblk) { - int err; - unsigned short i; - struct virtqueue_info *vqs_info; - struct virtqueue **vqs; + struct virtio_device *vdev = vblk->vdev; unsigned short num_vqs; unsigned short num_poll_vqs; - struct virtio_device *vdev = vblk->vdev; - struct irq_affinity desc = { 0, }; + int err; err = virtio_cread_feature(vdev, VIRTIO_BLK_F_MQ, struct virtio_blk_config, num_queues, @@ -985,6 +989,7 @@ static int init_vq(struct virtio_blk *vblk) num_poll_vqs = min_t(unsigned int, poll_queues, num_vqs - 1); + vblk->num_vqs = num_vqs; vblk->io_queues[HCTX_TYPE_DEFAULT] = num_vqs - num_poll_vqs; vblk->io_queues[HCTX_TYPE_READ] = 0; vblk->io_queues[HCTX_TYPE_POLL] = num_poll_vqs; @@ -994,6 +999,20 @@ static int init_vq(struct virtio_blk *vblk) vblk->io_queues[HCTX_TYPE_READ], vblk->io_queues[HCTX_TYPE_POLL]); + return 0; +} + +static int init_vq(struct virtio_blk *vblk) +{ + int err; + unsigned short i; + struct virtqueue_info *vqs_info; + struct virtqueue **vqs; + unsigned short num_vqs = vblk->num_vqs; + unsigned short num_poll_vqs = vblk->io_queues[HCTX_TYPE_POLL]; + struct virtio_device *vdev = vblk->vdev; + struct irq_affinity desc = { 0, }; + vblk->vqs = kmalloc_objs(*vblk->vqs, num_vqs); if (!vblk->vqs) return -ENOMEM; @@ -1022,10 +1041,33 @@ static int init_vq(struct virtio_blk *vblk) goto out; for (i = 0; i < num_vqs; i++) { + unsigned int ring_size = virtqueue_get_vring_size(vqs[i]); + /* + * Each request consumes 2 extra descriptors (out_hdr and + * in_hdr) in addition to the data segments. + * + * At initial probe (!vblk->disk), each virtqueue must fit at + * least 1 data segment + 2 header descriptors (3). + * On resume/recovery (vblk->disk), each virtqueue must fit the + * existing queue_max_segments() + 2 header descriptors. + */ + unsigned int min_ring_size = 3; + + if (vblk->disk) + min_ring_size = queue_max_segments(vblk->disk->queue) + 2; + + if (ring_size < min_ring_size) { + dev_err(&vdev->dev, + "virtqueue %u ring size %u is smaller than minimum %u\n", + i, ring_size, min_ring_size); + vdev->config->del_vqs(vdev); + err = -EINVAL; + goto out; + } + spin_lock_init(&vblk->vqs[i].lock); vblk->vqs[i].vq = vqs[i]; } - vblk->num_vqs = num_vqs; out: kfree(vqs); @@ -1196,8 +1238,11 @@ static void virtblk_complete_batch(struct io_comp_batch *iob) struct request *req; rq_list_for_each(&iob->req_list, req) { - virtblk_unmap_data(req, blk_mq_rq_to_pdu(req)); + struct virtblk_req *vbr = blk_mq_rq_to_pdu(req); + + virtblk_unmap_data(req, vbr); virtblk_cleanup_cmd(req); + virtblk_update_zone_append_sector(req, vbr); } blk_mq_end_request_batch(iob); } @@ -1254,7 +1299,7 @@ static int virtblk_read_limits(struct virtio_blk *vblk, u16 min_io_size; u8 physical_block_exp, alignment_offset; size_t max_dma_size; - int err; + int err, i; /* We need to know how many segments before we allocate. */ err = virtio_cread_feature(vdev, VIRTIO_BLK_F_SEG_MAX, @@ -1268,6 +1313,23 @@ static int virtblk_read_limits(struct virtio_blk *vblk, /* Prevent integer overflows and honor max vq size */ sg_elems = min_t(u32, sg_elems, VIRTIO_BLK_MAX_SG_ELEMS - 2); + /* + * virtblk_add_req() uses separate outgoing and incoming header + * descriptors (out_hdr and in_hdr), consuming 2 extra descriptors + * per request in addition to the data segments. + * + * Per virtio specification (2.7.5.3.1), a driver MUST NOT create a + * descriptor chain longer than the Queue Size of the device. + * + * Clamp max_segments to (ring_size - 2) across all virtqueues so + * that a request never exceeds the ring size of any queue. + */ + for (i = 0; i < vblk->num_vqs; i++) { + u32 ring_size = virtqueue_get_vring_size(vblk->vqs[i].vq); + + sg_elems = min_t(u32, sg_elems, ring_size - 2); + } + /* We can handle whatever the host told us to handle. */ lim->max_segments = sg_elems; @@ -1467,9 +1529,14 @@ static int virtblk_probe(struct virtio_device *vdev) mutex_init(&vblk->vdev_mutex); vblk->vdev = vdev; + vblk->disk = NULL; INIT_WORK(&vblk->config_work, virtblk_config_changed_work); + err = virtblk_init_queue_layout(vblk); + if (err) + goto out_free_vblk; + err = init_vq(vblk); if (err) goto out_free_vblk; @@ -1548,6 +1615,7 @@ static int virtblk_probe(struct virtio_device *vdev) return 0; out_cleanup_disk: + virtio_reset_device(vdev); put_disk(vblk->disk); out_free_tags: blk_mq_free_tag_set(&vblk->tag_set); diff --git a/drivers/block/zloop.c b/drivers/block/zloop.c index e02a5249ae60..5e3eb2c7004f 100644 --- a/drivers/block/zloop.c +++ b/drivers/block/zloop.c @@ -1151,7 +1151,8 @@ static int zloop_init_zone(struct zloop_device *zlo, struct zloop_options *opts, if (restore && file_sectors != zlo->zone_size) { pr_err("Invalid conventional zone %u file size (%llu sectors != %llu)\n", - zone_no, file_sectors, zlo->zone_capacity); + zone_no, file_sectors, zlo->zone_size); + ret = -EINVAL; goto out_fput; } @@ -1329,8 +1330,8 @@ static int zloop_ctl_add(struct zloop_options *opts) zlo->disk = blk_mq_alloc_disk(&zlo->tag_set, &lim, zlo); if (IS_ERR(zlo->disk)) { - pr_err("blk_mq_alloc_disk failed (err=%d)\n", ret); ret = PTR_ERR(zlo->disk); + pr_err("blk_mq_alloc_disk failed (err=%d)\n", ret); goto out_cleanup_tags; } zlo->disk->flags = GENHD_FL_NO_PART; diff --git a/drivers/bluetooth/btintel.c b/drivers/bluetooth/btintel.c index 4871a552d3aa..85cbcfbea81a 100644 --- a/drivers/bluetooth/btintel.c +++ b/drivers/bluetooth/btintel.c @@ -1150,7 +1150,29 @@ static int btintel_download_firmware_payload(struct hci_dev *hdev, err = -EINVAL; while (fw_ptr - fw->data < fw->size) { - struct hci_command_hdr *cmd = (void *)(fw_ptr + frag_len); + struct hci_command_hdr *cmd; + size_t remain = fw->size - (fw_ptr - fw->data); + + /* Ensure the header fits before dereferencing */ + if (frag_len + sizeof(*cmd) > remain) { + bt_dev_err(hdev, + "Firmware buffer overrun at header (frag_len %u, need %zu, remain %zu)", + frag_len, frag_len + sizeof(*cmd), remain); + err = -EINVAL; + goto done; + } + + cmd = (void *)(fw_ptr + frag_len); + + /* Ensure the full command (header + payload) fits before use */ + if (frag_len + sizeof(*cmd) + cmd->plen > remain) { + bt_dev_err(hdev, + "Firmware buffer overrun at payload (frag_len %u, plen %u, need %zu, remain %zu)", + frag_len, cmd->plen, + frag_len + sizeof(*cmd) + cmd->plen, remain); + err = -EINVAL; + goto done; + } frag_len += sizeof(*cmd) + cmd->plen; diff --git a/drivers/bluetooth/btmtk.c b/drivers/bluetooth/btmtk.c index 56296d142187..ed53e1d8902c 100644 --- a/drivers/bluetooth/btmtk.c +++ b/drivers/bluetooth/btmtk.c @@ -7,6 +7,7 @@ #include #include #include +#include #include #include @@ -24,7 +25,7 @@ #define MTK_SEC_MAP_NEED_SEND_SIZE 52 /* It is for mt79xx iso data transmission setting */ -#define MTK_ISO_THRESHOLD 264 +#define MTK_ISO_THRESHOLD 342 struct btmtk_patch_header { u8 datetime[16]; @@ -1161,8 +1162,15 @@ static int btmtk_recv_isopkt(struct hci_dev *hdev, void *buffer, int count) struct btmtk_data *btmtk_data = hci_get_priv(hdev); struct sk_buff *skb; unsigned long flags; + unsigned int iso_mtu; int err = 0; + /* The controller reports the largest Data_Total_Length it will send in + * LE Read Buffer Size [v2]. Fall back to HCI_MAX_ISO_SIZE while that + * command has not completed yet. + */ + iso_mtu = hdev->iso_mtu ? hdev->iso_mtu : HCI_MAX_ISO_SIZE; + spin_lock_irqsave(&btmtk_data->isorxlock, flags); skb = btmtk_data->isopkt_skb; @@ -1170,7 +1178,16 @@ static int btmtk_recv_isopkt(struct hci_dev *hdev, void *buffer, int count) int len; if (!skb) { - skb = bt_skb_alloc(HCI_MAX_ISO_SIZE, GFP_ATOMIC); + /* Drop the endpoint's zero-filled padding before + * allocating an skb for it; a zero Data_Total_Length + * check below would miss a padding remainder + * shorter than an ISO header. + */ + if (mem_is_zero(buffer, count)) + break; + + skb = bt_skb_alloc(HCI_ISO_HDR_SIZE + iso_mtu, + GFP_ATOMIC); if (!skb) { err = -ENOMEM; break; @@ -1193,7 +1210,24 @@ static int btmtk_recv_isopkt(struct hci_dev *hdev, void *buffer, int count) /* Complete ISO header */ hci_skb_expect(skb) = __le16_to_cpu(dlen); - if (skb_tailroom(skb) < hci_skb_expect(skb)) { + if (!hci_skb_expect(skb)) { + /* Zero padding was ruled out above, so a + * zero Data_Total_Length here is invalid. + */ + kfree_skb(skb); + skb = NULL; + + err = -EILSEQ; + break; + } + + /* Reject a length the controller said it would never + * send. The skb_tailroom() test is kept because a + * fragment started before hdev->iso_mtu was populated + * sits in a smaller skb than iso_mtu now allows. + */ + if (hci_skb_expect(skb) > iso_mtu || + skb_tailroom(skb) < hci_skb_expect(skb)) { kfree_skb(skb); skb = NULL; @@ -1312,13 +1346,15 @@ static int btmtk_submit_intr_urb(struct hci_dev *hdev, gfp_t mem_flags) static int btmtk_usb_isointf_init(struct hci_dev *hdev) { struct btmtk_data *btmtk_data = hci_get_priv(hdev); - u8 iso_param[2] = { 0x08, 0x01 }; + __le16 iso_param = cpu_to_le16(MTK_ISO_THRESHOLD); struct sk_buff *skb; int err; spin_lock_init(&btmtk_data->isorxlock); - __set_mtk_intr_interface(hdev); + err = __set_mtk_intr_interface(hdev); + if (err < 0) + return err; err = btmtk_submit_intr_urb(hdev, GFP_KERNEL); if (err < 0) { @@ -1327,9 +1363,10 @@ static int btmtk_usb_isointf_init(struct hci_dev *hdev) return err; } - skb = __hci_cmd_sync(hdev, 0xfd98, sizeof(iso_param), iso_param, + skb = __hci_cmd_sync(hdev, 0xfd98, sizeof(iso_param), &iso_param, HCI_INIT_TIMEOUT); if (IS_ERR(skb)) { + usb_kill_anchored_urbs(&btmtk_data->isopkt_anchor); bt_dev_err(hdev, "Failed to apply iso setting (%ld)", PTR_ERR(skb)); return PTR_ERR(skb); } diff --git a/drivers/bluetooth/btqca.c b/drivers/bluetooth/btqca.c index 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 67b7271c9eb9..2cc28d4af2db 100644 --- a/drivers/bluetooth/btusb_main.c +++ b/drivers/bluetooth/btusb_main.c @@ -1063,6 +1063,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) @@ -4557,8 +4559,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; @@ -4599,6 +4602,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 7089e9b639b2..d96ae0fc2b2e 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 @@ ssize_t tpm_common_read(struct file *file, char __user *buf, if (!priv->response_length) { *off = 0; timer_delete_sync(&priv->user_read_timer); - flush_work(&priv->timeout_work); + flush = true; } mutex_unlock(&priv->buffer_mutex); + + /* + * tpm_timeout_work() takes buffer_mutex, so flush it after dropping + * the mutex to avoid a deadlock; the timer is deleted above, so no new + * timeout work can be queued once the mutex is released. + */ + if (flush) + flush_work(&priv->timeout_work); + return ret_size; } diff --git a/drivers/char/tpm/tpm2-sessions.c b/drivers/char/tpm/tpm2-sessions.c index 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/comedi/comedi_fops.c b/drivers/comedi/comedi_fops.c index c09bbe04be6c..2adce0cf4172 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/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 10ea6035f4ad..a797bb29385e 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 @@ void cpufreq_suspend(void) cpus_read_unlock(); } +static void cpufreq_resume_policy(struct cpufreq_policy *policy, bool start) +{ + guard(cpufreq_policy_write)(policy); + + if (!policy->suspended) + return; + + policy->suspended = false; + + if (policy_is_inactive(policy)) { + /* + * The policy was active when it was suspended, so its governor + * is still there. Let the governor go. + */ + cpufreq_exit_governor(policy); + return; + } + + if (!start) + return; + + /* + * 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 @@ void cpufreq_suspend(void) void cpufreq_resume(void) { struct cpufreq_policy *policy; - int ret; if (!cpufreq_driver) return; + guard(cpus_read_lock)(); + if (unlikely(!cpufreq_suspended)) return; @@ -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/dma-buf/dma-buf-mapping.c b/drivers/dma-buf/dma-buf-mapping.c index ef0f22854d01..5167cda7ea21 100644 --- a/drivers/dma-buf/dma-buf-mapping.c +++ b/drivers/dma-buf/dma-buf-mapping.c @@ -111,12 +111,12 @@ struct sg_table *dma_buf_phys_vec_to_sgt(struct dma_buf_attachment *attach, size_t i; int ret; - dma_resv_assert_held(attach->dmabuf->resv); - if (WARN_ON(!attach || !attach->dmabuf || !provider)) /* This function is supposed to work on MMIO memory only */ return ERR_PTR(-EINVAL); + dma_resv_assert_held(attach->dmabuf->resv); + dma = kzalloc_obj(*dma); if (!dma) return ERR_PTR(-ENOMEM); @@ -251,6 +251,8 @@ void dma_buf_free_sgt(struct dma_buf_attachment *attach, struct sg_table *sgt, sg_dma_len(sgl), dir, DMA_ATTR_MMIO); } + /* Restore the allocation count cleared for the DMA-only table. */ + sgt->orig_nents = sgt->nents; sg_free_table(sgt); kfree(dma->state); kfree(dma); diff --git a/drivers/dma-buf/dma-buf.c b/drivers/dma-buf/dma-buf.c index 4c9add51f9ef..b3d311acb883 100644 --- a/drivers/dma-buf/dma-buf.c +++ b/drivers/dma-buf/dma-buf.c @@ -904,6 +904,10 @@ static int dma_buf_wrap_sg_table(struct sg_table **sg_table) sg_assign_page(to_sg, NULL); sg_dma_address(to_sg) = sg_dma_address(from_sg); sg_dma_len(to_sg) = sg_dma_len(from_sg); +#ifdef CONFIG_NEED_SG_DMA_FLAGS + /* the flags describe the DMA side, e.g. SG_DMA_BUS_ADDRESS */ + to_sg->dma_flags = from_sg->dma_flags; +#endif to_sg = sg_next(to_sg); } 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/cirrus/cs_dsp.c b/drivers/firmware/cirrus/cs_dsp.c index 838fece8dc01..413fb997be2b 100644 --- a/drivers/firmware/cirrus/cs_dsp.c +++ b/drivers/firmware/cirrus/cs_dsp.c @@ -2793,6 +2793,7 @@ int cs_dsp_power_up(struct cs_dsp *dsp, const struct firmware *coeff_firmware, const char *coeff_filename, const char *fw_name) { + struct cs_dsp_coeff_ctl *ctl; int ret; mutex_lock(&dsp->pwr_lock); @@ -2838,6 +2839,11 @@ int cs_dsp_power_up(struct cs_dsp *dsp, return 0; err_ena: + list_for_each_entry(ctl, &dsp->ctl_list, list) + ctl->enabled = 0; + + cs_dsp_free_alg_regions(dsp); + if (dsp->ops->disable_core) dsp->ops->disable_core(dsp); err_mem: diff --git a/drivers/firmware/google/coreboot_table.c b/drivers/firmware/google/coreboot_table.c index 25ee8cf53429..6b2ea781ddf7 100644 --- a/drivers/firmware/google/coreboot_table.c +++ b/drivers/firmware/google/coreboot_table.c @@ -114,6 +114,30 @@ void coreboot_driver_unregister(struct coreboot_driver *driver) } EXPORT_SYMBOL(coreboot_driver_unregister); +/* + * Whether the memory of a CBMEM entry may be mapped: it must be exclusively + * System RAM, or exclusively Reserved memory, as CBMEM often is on x86, or + * memory that the kernel doesn't know about at all. coreboot leaves CBMEM out + * of the /memory node of the device tree that it passes to FIT payloads, e.g. + * on arm64, and only lists it in the memory reservation block. + * + * Anything else, such as no-map regions on arm64, which are IORESOURCE_MEM + * (see request_standard_resources() in arch/arm64/kernel/setup.c), must not + * be mapped. + */ +static bool cbmem_entry_is_mappable(const struct lb_cbmem_entry *entry) +{ + resource_size_t start = entry->address; + size_t size = entry->entry_size; + + return region_intersects(start, size, IORESOURCE_SYSTEM_RAM, + IORES_DESC_NONE) == REGION_INTERSECTS || + region_intersects(start, size, IORESOURCE_MEM, + IORES_DESC_RESERVED) == REGION_INTERSECTS || + region_intersects(start, size, IORESOURCE_MEM, + IORES_DESC_NONE) == REGION_DISJOINT; +} + static int coreboot_table_populate(struct device *dev, void *ptr, resource_size_t len) { int i, ret; @@ -149,23 +173,7 @@ static int coreboot_table_populate(struct device *dev, void *ptr, resource_size_ switch (device->entry.tag) { case LB_TAG_CBMEM_ENTRY: - /* - * Skip entries that are not exclusively System RAM or - * Reserved memory. - * On ARM64, no-map regions are filtered out as they are - * IORESOURCE_MEM (see request_standard_resources() in - * arch/arm64/kernel/setup.c). - * On x86, CBMEM often resides in standard reserved regions - * (IORES_DESC_RESERVED). - */ - if (region_intersects(device->cbmem_entry.address, - device->cbmem_entry.entry_size, - IORESOURCE_SYSTEM_RAM, - IORES_DESC_NONE) != REGION_INTERSECTS && - region_intersects(device->cbmem_entry.address, - device->cbmem_entry.entry_size, - IORESOURCE_MEM, - IORES_DESC_RESERVED) != REGION_INTERSECTS) { + if (!cbmem_entry_is_mappable(&device->cbmem_entry)) { kfree(device); continue; } diff --git a/drivers/gpio/gpio-aspeed.c b/drivers/gpio/gpio-aspeed.c index dc53b2decb66..6e834e83915b 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 44ca798cf832..3b1aaea63951 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 a6868f673831..605393d3c992 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 7f0751d7b1c4..0b7a48e0ac26 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-mpsse.c b/drivers/gpio/gpio-mpsse.c index 61c5ca96314b..3ad7048f009f 100644 --- a/drivers/gpio/gpio-mpsse.c +++ b/drivers/gpio/gpio-mpsse.c @@ -676,6 +676,10 @@ static int gpio_mpsse_probe(struct usb_interface *interface, if (err) return err; + /* Every read carries two status bytes ahead of the data */ + if (usb_endpoint_maxp(priv->bulk_in) < 3) + return -EINVAL; + priv->bulk_in_buf = devm_kmalloc(dev, usb_endpoint_maxp(priv->bulk_in), GFP_KERNEL); if (!priv->bulk_in_buf) diff --git a/drivers/gpio/gpio-omap.c b/drivers/gpio/gpio-omap.c index 005420baecf4..98a88dfda195 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); @@ -1468,7 +1471,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 fb21396e1d02..3b9ce1ac5556 100644 --- a/drivers/gpio/gpio-regmap.c +++ b/drivers/gpio/gpio-regmap.c @@ -504,6 +504,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 #include #include +#include #include #include #include @@ -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 bc69b8729d19..b2f2301e9e64 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 e2a784df275c..4ae38d964bfc 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 70ddccccc1c4..17bbec8495e1 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 90731a547ed6..a16a787c58cb 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; @@ -5222,21 +5236,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 ? @@ -5261,10 +5275,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; } @@ -5274,38 +5286,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_vm.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c index c07f1115f654..e9170cd475f0 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c @@ -531,12 +531,16 @@ static int amdgpu_vm_init_entities(struct amdgpu_device *adev, r = drm_sched_entity_init(&vm->immediate, DRM_SCHED_PRIORITY_NORMAL, adev->vm_manager.vm_pte_scheds, adev->vm_manager.vm_pte_num_scheds, NULL); + if (r) + return r; + + r = drm_sched_entity_init(&vm->delayed, DRM_SCHED_PRIORITY_NORMAL, + adev->vm_manager.vm_pte_scheds, + adev->vm_manager.vm_pte_num_scheds, NULL); if (r) goto error; - return drm_sched_entity_init(&vm->delayed, DRM_SCHED_PRIORITY_NORMAL, - adev->vm_manager.vm_pte_scheds, - adev->vm_manager.vm_pte_num_scheds, NULL); + return 0; error: drm_sched_entity_destroy(&vm->immediate); diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_chardev.c b/drivers/gpu/drm/amd/amdkfd/kfd_chardev.c index d65ae53c81a5..ed3294bbeb15 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_chardev.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_chardev.c @@ -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; } diff --git a/drivers/gpu/drm/amd/display/dc/dce/dce_link_encoder.c b/drivers/gpu/drm/amd/display/dc/dce/dce_link_encoder.c index c6a20378121b..0c1fcfd088ba 100644 --- a/drivers/gpu/drm/amd/display/dc/dce/dce_link_encoder.c +++ b/drivers/gpu/drm/amd/display/dc/dce/dce_link_encoder.c @@ -1841,8 +1841,11 @@ bool dce110_get_hpd_state(struct link_encoder *enc) bool dce110_program_hpd_filter(struct link_encoder *enc, int delay_on_connect_in_ms, int delay_on_disconnect_in_ms) { + if (!enc->hpd_gpio) + return false; + /* Setup HPD filtering */ - if (enc->hpd_gpio && dal_gpio_lock_pin(enc->hpd_gpio) == GPIO_RESULT_OK) { + if (dal_gpio_lock_pin(enc->hpd_gpio) == GPIO_RESULT_OK) { struct gpio_hpd_config config; config.delay_on_connect = delay_on_connect_in_ms; diff --git a/drivers/gpu/drm/amd/display/dc/dio/dcn10/dcn10_link_encoder.c b/drivers/gpu/drm/amd/display/dc/dio/dcn10/dcn10_link_encoder.c index 00e82d627d91..1295c12c3e09 100644 --- a/drivers/gpu/drm/amd/display/dc/dio/dcn10/dcn10_link_encoder.c +++ b/drivers/gpu/drm/amd/display/dc/dio/dcn10/dcn10_link_encoder.c @@ -1502,8 +1502,11 @@ bool dcn10_get_hpd_state(struct link_encoder *enc) bool dcn10_program_hpd_filter(struct link_encoder *enc, int delay_on_connect_in_ms, int delay_on_disconnect_in_ms) { + if (!enc->hpd_gpio) + return false; + /* Setup HPD filtering */ - if (enc->hpd_gpio && dal_gpio_lock_pin(enc->hpd_gpio) == GPIO_RESULT_OK) { + if (dal_gpio_lock_pin(enc->hpd_gpio) == GPIO_RESULT_OK) { struct gpio_hpd_config config; config.delay_on_connect = delay_on_connect_in_ms; diff --git a/drivers/gpu/drm/amd/pm/swsmu/smu11/smu_v11_0.c b/drivers/gpu/drm/amd/pm/swsmu/smu11/smu_v11_0.c index f0b2e7da67b1..d2dfa2bb50a5 100644 --- a/drivers/gpu/drm/amd/pm/swsmu/smu11/smu_v11_0.c +++ b/drivers/gpu/drm/amd/pm/swsmu/smu11/smu_v11_0.c @@ -1421,7 +1421,25 @@ int smu_v11_0_get_max_sustainable_clocks_by_dc(struct smu_context *smu, int smu_v11_0_baco_set_armd3_sequence(struct smu_context *smu, enum smu_baco_seq baco_seq) { - return smu_cmn_send_smc_msg_with_param(smu, SMU_MSG_ArmD3, baco_seq, NULL); + struct smu_baco_context *smu_baco = &smu->smu_baco; + int ret; + + ret = smu_cmn_send_smc_msg_with_param(smu, SMU_MSG_ArmD3, baco_seq, NULL); + if (ret) + return ret; + + /* + * PMFW owns the BACO transition once armed, so keep the driver's view + * in sync. Otherwise smu_v11_0_get_bamaco_support() falls back to the + * live BACO feature bit, which PMFW clears when armed, and the runtime + * resume wrongly concludes BACO is unsupported and skips the exit. + */ + if (baco_seq == BACO_SEQ_BAMACO || baco_seq == BACO_SEQ_BACO) + smu_baco->state = SMU_BACO_STATE_ENTER; + else + smu_baco->state = SMU_BACO_STATE_EXIT; + + return 0; } int smu_v11_0_get_bamaco_support(struct smu_context *smu) diff --git a/drivers/gpu/drm/bridge/sii902x.c b/drivers/gpu/drm/bridge/sii902x.c index 9aac44ed5b67..48058029fdfc 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/drm_panic.c b/drivers/gpu/drm/drm_panic.c index fef47625c526..1dca0b05e924 100644 --- a/drivers/gpu/drm/drm_panic.c +++ b/drivers/gpu/drm/drm_panic.c @@ -842,7 +842,7 @@ static int drm_panic_type_set(const char *val, const struct kernel_param *kp) unsigned int i; for (i = 0; i < ARRAY_SIZE(drm_panic_type_map); i++) { - if (!strcmp(val, drm_panic_type_map[i])) { + if (sysfs_streq(val, drm_panic_type_map[i])) { drm_panic_type = i; return 0; } diff --git a/drivers/gpu/drm/i915/display/intel_display.c b/drivers/gpu/drm/i915/display/intel_display.c index 9dfd095f325f..8210dbd6c438 100644 --- a/drivers/gpu/drm/i915/display/intel_display.c +++ b/drivers/gpu/drm/i915/display/intel_display.c @@ -1791,15 +1791,22 @@ static void hsw_crtc_disable(struct intel_atomic_state *state, intel_atomic_get_old_crtc_state(state, crtc); struct intel_crtc *pipe_crtc; - if (crtc->cmtg.enabled && intel_cmtg_is_allowed(old_crtc_state)) { - intel_cmtg_set_clk_select(old_crtc_state); - intel_cmtg_disable(old_crtc_state); - } /* * FIXME collapse everything to one hook. * Need care with mst->ddi interactions. */ intel_encoders_disable(state, crtc); + + /* + * Disable CMTG after the encoders are disabled, but before the + * transcoder and port PLL are torn down in + * intel_encoders_post_disable()/intel_dpll_disable(). + */ + if (crtc->cmtg.enabled && intel_cmtg_is_allowed(old_crtc_state)) { + intel_cmtg_set_clk_select(old_crtc_state); + intel_cmtg_disable(old_crtc_state); + } + intel_encoders_post_disable(state, crtc); intel_dpll_disable(old_crtc_state); @@ -2779,7 +2786,7 @@ void intel_set_transcoder_timings(const struct intel_crtc_state *crtc_state, HSYNC_END(adjusted_mode->crtc_hsync_end - 1)); if (display->platform.novalake && - IS_DISPLAY_STEP(display, STEP_A0, STEP_C0)) + IS_DISPLAY_STEP(display, STEP_A0, STEP_B0)) crtc_vtotal = 1; intel_de_write(display, TRANS_VTOTAL(display, transcoder), @@ -2876,7 +2883,7 @@ void intel_set_transcoder_timings_lrr(const struct intel_crtc_state *crtc_state, * is the transcoder's undelayed vblank. */ if (display->platform.novalake && - IS_DISPLAY_STEP(display, STEP_A0, STEP_C0)) + IS_DISPLAY_STEP(display, STEP_A0, STEP_B0)) crtc_vtotal = 1; intel_de_write(display, TRANS_VTOTAL(display, transcoder), diff --git a/drivers/gpu/drm/i915/display/intel_psr.c b/drivers/gpu/drm/i915/display/intel_psr.c index 01c36ea315fa..b68859c31d17 100644 --- a/drivers/gpu/drm/i915/display/intel_psr.c +++ b/drivers/gpu/drm/i915/display/intel_psr.c @@ -3717,12 +3717,11 @@ void intel_psr_flush(struct intel_display *display, if (intel_dp->psr.pause_counter) goto unlock; - 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); + + if (origin == ORIGIN_FLIP) goto unlock; - } if (pipe_frontbuffer_bits == 0) goto unlock; diff --git a/drivers/gpu/drm/i915/display/intel_vrr.c b/drivers/gpu/drm/i915/display/intel_vrr.c index cfc0cfbff017..d415915e09f0 100644 --- a/drivers/gpu/drm/i915/display/intel_vrr.c +++ b/drivers/gpu/drm/i915/display/intel_vrr.c @@ -1110,7 +1110,7 @@ void intel_vrr_get_config(struct intel_crtc_state *crtc_state) } if (display->platform.novalake && - IS_DISPLAY_STEP(display, STEP_A0, STEP_C0)) + IS_DISPLAY_STEP(display, STEP_A0, STEP_B0)) crtc_state->hw.adjusted_mode.crtc_vtotal = intel_vrr_vmin_vtotal(crtc_state); @@ -1170,9 +1170,13 @@ int intel_vrr_safe_window_start(const struct intel_crtc_state *crtc_state) static int intel_vrr_dcb_vmin_vblank_start(const struct intel_crtc_state *crtc_state) { - return (intel_vrr_dcb_vmin_vblank_start_next(crtc_state) < 0) ? - intel_vrr_dcb_vmin_vblank_start_final(crtc_state) : - intel_vrr_dcb_vmin_vblank_start_next(crtc_state); + int vblank_start; + + vblank_start = intel_vrr_dcb_vmin_vblank_start_next(crtc_state); + if (vblank_start < 0) + vblank_start = intel_vrr_dcb_vmin_vblank_start_final(crtc_state); + + return vblank_start; } int intel_vrr_vmin_safe_window_end(const struct intel_crtc_state *crtc_state) diff --git a/drivers/gpu/drm/imagination/pvr_rogue_fwif.h b/drivers/gpu/drm/imagination/pvr_rogue_fwif.h index 5d590c4c2566..2f8daa93c9e6 100644 --- a/drivers/gpu/drm/imagination/pvr_rogue_fwif.h +++ b/drivers/gpu/drm/imagination/pvr_rogue_fwif.h @@ -2174,7 +2174,7 @@ struct rogue_fwif_hwrtdata { bool geom_caches_need_zeroing __aligned(4); struct rogue_fwif_cleanup_ctl cleanup_state __aligned(64); -} __aligned(8); +} __aligned(64); /* ****************************************************************************** diff --git a/drivers/gpu/drm/nouveau/nouveau_drm.c b/drivers/gpu/drm/nouveau/nouveau_drm.c index 2c7077a49888..6424d0fa1f39 100644 --- a/drivers/gpu/drm/nouveau/nouveau_drm.c +++ b/drivers/gpu/drm/nouveau/nouveau_drm.c @@ -337,6 +337,7 @@ static void nouveau_accel_ce_init(struct nouveau_drm *drm) { struct nvif_device *device = &drm->client.device; + bool priv; u64 runm; int ret = 0; @@ -349,7 +350,11 @@ nouveau_accel_ce_init(struct nouveau_drm *drm) return; } - ret = nouveau_channel_new(&drm->client, true, runm, NvDmaFB, NvDmaTT, &drm->cechan); + /* priv copy engine only works on kepler and newer. */ + priv = device->info.family >= NV_DEVICE_INFO_V0_KEPLER; + + ret = nouveau_channel_new(&drm->client, priv, runm, NvDmaFB, NvDmaTT, + &drm->cechan); if (ret) NV_ERROR(drm, "failed to create ce channel, %d\n", ret); } diff --git a/drivers/gpu/drm/nouveau/nvkm/engine/fifo/gk104.c b/drivers/gpu/drm/nouveau/nvkm/engine/fifo/gk104.c index 5655eda52a7b..912eb6c3a13d 100644 --- a/drivers/gpu/drm/nouveau/nvkm/engine/fifo/gk104.c +++ b/drivers/gpu/drm/nouveau/nvkm/engine/fifo/gk104.c @@ -180,6 +180,19 @@ gk104_ectx_ctor(struct nvkm_engn *engn, struct nvkm_vctx *vctx) struct gf100_vmm_map_v0 args = { .priv = 1 }; int ret; + /* The video falcons access their context with non-privileged + * requests, and fault with PRIV_VIOLATION on a privileged mapping. + */ + switch (engn->engine->subdev.type) { + case NVKM_ENGINE_MSVLD: + case NVKM_ENGINE_MSPDEC: + case NVKM_ENGINE_MSPPP: + args.priv = 0; + break; + default: + break; + } + ret = nvkm_vmm_get(vctx->vmm, 12, vctx->inst->size, &vctx->vma); if (ret) return ret; diff --git a/drivers/gpu/drm/nouveau/nvkm/subdev/devinit/gf100.c b/drivers/gpu/drm/nouveau/nvkm/subdev/devinit/gf100.c index 186e09ea0cb1..5368e705e7fd 100644 --- a/drivers/gpu/drm/nouveau/nvkm/subdev/devinit/gf100.c +++ b/drivers/gpu/drm/nouveau/nvkm/subdev/devinit/gf100.c @@ -27,7 +27,6 @@ #include #include #include -#include int gf100_devinit_pll_set(struct nvkm_devinit *init, u32 type, u32 freq) @@ -100,25 +99,6 @@ gf100_devinit_preinit(struct nvkm_devinit *base) * can use it as a reliable way to know whether we should run devinit. */ base->post = ((nvkm_rd32(device, 0x2240c) & BIT(1)) == 0); - - /* - * However some VBIOS init sequences miss this bit. So fall back to - * the nv50 method of checking if the bit is not set. Running the - * VBIOS multiple times may have detrimental effects. - */ - if (base->post) { - u64 disable = nvkm_devinit_disable(base); - /* magic to detect whether or not x86 vbios code has - * executed the devinit scripts to initialise the - * board. only works if there's a display engine. - */ - if (!(disable & (1ULL << NVKM_ENGINE_DISP))) { - if (nvkm_rdvgac(device, 0, 0x00) || - nvkm_rdvgac(device, 0, 0x1a)) { - base->post = false; - } - } - } } static const struct nvkm_devinit_func diff --git a/drivers/gpu/drm/panel/panel-visionox-r66451.c b/drivers/gpu/drm/panel/panel-visionox-r66451.c index 690cccedd438..d2cbc60af117 100644 --- a/drivers/gpu/drm/panel/panel-visionox-r66451.c +++ b/drivers/gpu/drm/panel/panel-visionox-r66451.c @@ -36,7 +36,7 @@ static void visionox_r66451_reset(struct visionox_r66451 *ctx) gpiod_set_value_cansleep(ctx->reset_gpio, 1); usleep_range(10000, 10100); gpiod_set_value_cansleep(ctx->reset_gpio, 0); - usleep_range(10000, 10100); + usleep_range(20000, 21000); } static int visionox_r66451_on(struct visionox_r66451 *ctx) @@ -227,7 +227,7 @@ static int visionox_r66451_bl_update_status(struct backlight_device *bl) struct mipi_dsi_device *dsi = bl_get_data(bl); u16 brightness = backlight_get_brightness(bl); - return mipi_dsi_dcs_set_display_brightness(dsi, brightness); + return mipi_dsi_dcs_set_display_brightness_large(dsi, brightness); } static const struct backlight_ops visionox_r66451_bl_ops = { diff --git a/drivers/gpu/drm/panfrost/panfrost_gpu.c b/drivers/gpu/drm/panfrost/panfrost_gpu.c index 8a15ccce08e9..5ef6897fc05e 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 03a6dcd8da2f..46b5141932ee 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; } @@ -81,6 +83,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) | diff --git a/drivers/gpu/drm/xe/Kconfig b/drivers/gpu/drm/xe/Kconfig index 4d7dcaff2b91..64bbfa88b27a 100644 --- a/drivers/gpu/drm/xe/Kconfig +++ b/drivers/gpu/drm/xe/Kconfig @@ -11,6 +11,7 @@ config DRM_XE # the shmem_readpage() which depends upon tmpfs select SHMEM select TMPFS + select CONFIGFS_FS select DRM_BUDDY select DRM_CLIENT_SELECTION select DRM_KMS_HELPER diff --git a/drivers/gpu/drm/xe/display/xe_display_pcode.c b/drivers/gpu/drm/xe/display/xe_display_pcode.c index f6820ef7e666..8dc9cbdb18ec 100644 --- a/drivers/gpu/drm/xe/display/xe_display_pcode.c +++ b/drivers/gpu/drm/xe/display/xe_display_pcode.c @@ -6,12 +6,12 @@ #include "xe_device.h" #include "xe_pcode.h" -static int xe_display_pcode_read(struct drm_device *drm, u32 mbox, u32 *val, u32 *val1) +static int xe_display_pcode_read(struct drm_device *drm, u32 mbox, u32 *val0, u32 *val1) { struct xe_device *xe = to_xe_device(drm); struct xe_tile *tile = xe_device_get_root_tile(xe); - return xe_pcode_read(tile, mbox, val, val1); + return xe_pcode_read(tile, mbox, val0, val1); } static int xe_display_pcode_write_timeout(struct drm_device *drm, u32 mbox, u32 val, int timeout_ms) diff --git a/drivers/gpu/drm/xe/regs/xe_gt_regs.h b/drivers/gpu/drm/xe/regs/xe_gt_regs.h index 247a736a54aa..f8c14a7f9274 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 4ab86fc369fd..e4c7c3549735 100644 --- a/drivers/gpu/drm/xe/regs/xe_lrc_layout.h +++ b/drivers/gpu/drm/xe/regs/xe_lrc_layout.h @@ -43,4 +43,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/regs/xe_regs.h b/drivers/gpu/drm/xe/regs/xe_regs.h index ef4746b7b5d3..437485b5a0af 100644 --- a/drivers/gpu/drm/xe/regs/xe_regs.h +++ b/drivers/gpu/drm/xe/regs/xe_regs.h @@ -30,6 +30,8 @@ #define XEHP_MTCFG_ADDR XE_REG(0x101800) #define TILE_COUNT REG_GENMASK(15, 8) +#define CRI_DEVICE_UID XE_REG(0x102008) + #define GGC XE_REG(0x108040) #define GMS_MASK REG_GENMASK(15, 8) #define GGMS_MASK REG_GENMASK(7, 6) diff --git a/drivers/gpu/drm/xe/xe_configfs.h b/drivers/gpu/drm/xe/xe_configfs.h index 4fbbeafba473..f71ee4a0d1ff 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); @@ -34,32 +33,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_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 ee732e5495f7..7ec5d301f999 100644 --- a/drivers/gpu/drm/xe/xe_device.c +++ b/drivers/gpu/drm/xe/xe_device.c @@ -742,6 +742,7 @@ static void vf_update_device_info(struct xe_device *xe) xe->info.skip_guc_pc = 1; xe->info.skip_pcode = 1; xe->info.has_drm_ras = false; + xe->info.has_device_uid = false; } static int xe_device_vram_alloc(struct xe_device *xe) @@ -759,6 +760,8 @@ static int xe_device_vram_alloc(struct xe_device *xe) return 0; } +static void xe_device_wedged_fini(struct drm_device *drm, void *arg); + /** * xe_device_probe_early: Device early probe * @xe: xe device instance @@ -827,6 +830,10 @@ int xe_device_probe_early(struct xe_device *xe) if (err) return err; + err = drmm_add_action_or_reset(&xe->drm, xe_device_wedged_fini, xe); + if (err) + return err; + return 0; } ALLOW_ERROR_INJECTION(xe_device_probe_early, ERRNO); /* See xe_pci_probe() */ @@ -942,6 +949,12 @@ static int xe_debug_page_size_alloc_ctrl_init(struct xe_device *xe) } #endif +static void xe_uid_probe(struct xe_device *xe) +{ + if (xe->info.has_device_uid) + xe->device_uid = xe_mmio_read64_2x32(xe_root_tile_mmio(xe), CRI_DEVICE_UID); +} + int xe_device_probe(struct xe_device *xe) { struct xe_tile *tile; @@ -949,7 +962,11 @@ int xe_device_probe(struct xe_device *xe) int err; u8 id; - xe_pat_init_early(xe); + xe_uid_probe(xe); + + err = xe_pat_init_early(xe); + if (err) + return err; err = xe_sriov_init(xe); if (err) @@ -1137,10 +1154,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 @@ -1471,7 +1484,7 @@ void xe_device_declare_wedged(struct xe_device *xe) dev_name(xe->drm.dev)); } - for_each_gt(gt, xe, id) + for_each_initialized_gt(gt, xe, id) xe_gt_declare_wedged(gt); if (xe_device_wedged(xe)) { diff --git a/drivers/gpu/drm/xe/xe_device.h b/drivers/gpu/drm/xe/xe_device.h index 6c4cfaebc44a..1bfd641fea27 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; diff --git a/drivers/gpu/drm/xe/xe_device_sysfs.c b/drivers/gpu/drm/xe/xe_device_sysfs.c index a73e0e957cb0..18783a286a83 100644 --- a/drivers/gpu/drm/xe/xe_device_sysfs.c +++ b/drivers/gpu/drm/xe/xe_device_sysfs.c @@ -8,6 +8,7 @@ #include #include +#include "regs/xe_regs.h" #include "xe_device.h" #include "xe_device_sysfs.h" #include "xe_mmio.h" @@ -264,6 +265,35 @@ static const struct attribute_group auto_link_downgrade_attr_group = { .attrs = auto_link_downgrade_attrs, }; +/** + * DOC: Device Unique ID + * + * On supported platforms, Xe driver exposes a unique 64-bit GPU SOC + * device identifier through the 'device_uid' sysfs entry. + * + * See Documentation/ABI/testing/sysfs-driver-intel-xe-gpu for the ABI + * specification. + */ + +static ssize_t +device_uid_show(struct device *dev, struct device_attribute *attr, char *buf) +{ + struct pci_dev *pdev = to_pci_dev(dev); + struct xe_device *xe = pdev_to_xe_device(pdev); + + return sysfs_emit(buf, "0x%016llx\n", xe->device_uid); +} +static DEVICE_ATTR_ADMIN_RO(device_uid); + +static struct attribute *device_uid_attrs[] = { + &dev_attr_device_uid.attr, + NULL +}; + +static const struct attribute_group device_uid_attr_group = { + .attrs = device_uid_attrs, +}; + int xe_device_sysfs_init(struct xe_device *xe) { struct device *dev = xe->drm.dev; @@ -285,5 +315,11 @@ int xe_device_sysfs_init(struct xe_device *xe) return ret; } + if (xe->info.has_device_uid) { + ret = devm_device_add_group(dev, &device_uid_attr_group); + if (ret) + return ret; + } + return 0; } diff --git a/drivers/gpu/drm/xe/xe_device_types.h b/drivers/gpu/drm/xe/xe_device_types.h index 03a7bb08adf7..8daccb82ded7 100644 --- a/drivers/gpu/drm/xe/xe_device_types.h +++ b/drivers/gpu/drm/xe/xe_device_types.h @@ -171,6 +171,8 @@ struct xe_device { u8 has_cached_pt:1; /** @info.has_device_atomics_on_smem: Supports device atomics on SMEM */ u8 has_device_atomics_on_smem:1; + /** @info.has_device_uid: Device supports unique 64-bit GPU SOC ID */ + u8 has_device_uid:1; /** @info.has_drm_ras: Device supports drm_ras (Reliability, Availability, Serviceability) */ u8 has_drm_ras:1; /** @info.has_fan_control: Device supports fan control */ @@ -217,6 +219,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 */ @@ -255,6 +259,9 @@ struct xe_device { bool oob_initialized; } wa_active; + /** @device_uid: unique 64-bit GPU SOC identifier */ + u64 device_uid; + /** @survivability: survivability information for device */ struct xe_survivability survivability; 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_gt.c b/drivers/gpu/drm/xe/xe_gt.c index dfdacc0f6de9..2176254b10f2 100644 --- a/drivers/gpu/drm/xe/xe_gt.c +++ b/drivers/gpu/drm/xe/xe_gt.c @@ -172,6 +172,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) @@ -543,6 +544,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; } @@ -621,8 +624,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); @@ -683,11 +704,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; } @@ -697,12 +722,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]); @@ -715,8 +735,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]); @@ -745,8 +763,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); @@ -760,6 +780,8 @@ int xe_gt_init(struct xe_gt *gt) return err; } + /* Must be last */ + WRITE_ONCE(gt->initialized, true); return 0; } @@ -882,11 +904,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); @@ -1177,6 +1198,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 @@ -1186,8 +1216,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_types.h b/drivers/gpu/drm/xe/xe_gt_types.h index a8bbfbdf3849..5bb2d0281a0a 100644 --- a/drivers/gpu/drm/xe/xe_gt_types.h +++ b/drivers/gpu/drm/xe/xe_gt_types.h @@ -213,6 +213,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; @@ -390,6 +396,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 c988a2a3b7bd..944f88ee40a0 100644 --- a/drivers/gpu/drm/xe/xe_guc.c +++ b/drivers/gpu/drm/xe/xe_guc.c @@ -1837,7 +1837,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 acdc24d1a6bd..64ea57cceb6f 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 864859bd0ccc..dc4dba70612e 100644 --- a/drivers/gpu/drm/xe/xe_guc_submit.c +++ b/drivers/gpu/drm/xe/xe_guc_submit.c @@ -1505,6 +1505,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)); @@ -1520,6 +1521,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); @@ -1683,6 +1689,7 @@ guc_exec_queue_timedout_job(struct drm_sched_job *drm_job) * 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: @@ -1696,6 +1703,7 @@ guc_exec_queue_timedout_job(struct drm_sched_job *drm_job) else xe_sched_submission_start(sched); handle_vf_resume: + drm_dev_exit(idx); return DRM_GPU_SCHED_STAT_NO_HANG; } @@ -1846,16 +1854,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 @@ -1868,6 +1871,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); @@ -2088,7 +2100,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); } @@ -2270,7 +2288,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) { @@ -2340,8 +2363,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 @@ -2349,11 +2374,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); } } @@ -2376,9 +2399,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) || \ @@ -2571,10 +2594,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, @@ -3098,33 +3123,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); } } @@ -3326,7 +3368,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; } @@ -3334,9 +3376,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 de3f2aeffc3f..b47c083e52b6 100644 --- a/drivers/gpu/drm/xe/xe_hwmon.c +++ b/drivers/gpu/drm/xe/xe_hwmon.c @@ -101,14 +101,16 @@ enum sensor_attr_power { #define PWR_ATTR_TO_STR(attr) (((attr) == hwmon_power_max) ? "PL1" : "PL2") -/* - * Timeout for power limit write mailbox command. - */ -#define PL_WRITE_MBX_TIMEOUT_MS (1) - /* 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 @@ -139,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]; }; @@ -170,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 */ @@ -180,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 @@ -203,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", @@ -218,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); @@ -236,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; @@ -252,10 +262,37 @@ static int xe_hwmon_pcode_rmw_power_limit(const struct xe_hwmon *hwmon, u32 attr (channel == CHANNEL_CARD) ? WRITE_PSYSGPU_POWER_LIMIT : WRITE_PACKAGE_POWER_LIMIT, 0), - val0, val1, PL_WRITE_MBX_TIMEOUT_MS); - if (ret) + val0, val1, PCODE_DEFAULT_TIMEOUT_MS); + 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; } @@ -399,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); @@ -660,15 +699,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 */ @@ -767,16 +810,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); @@ -789,26 +833,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; } @@ -828,7 +920,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; } @@ -1492,22 +1584,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 @@ int xe_lmtt_init(struct xe_lmtt *lmtt) 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 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 e4388a960490..2e44a7000d95 100644 --- a/drivers/gpu/drm/xe/xe_lrc.c +++ b/drivers/gpu/drm/xe/xe_lrc.c @@ -1461,15 +1461,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_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 5f2a0b19839d..93438a670ae4 100644 --- a/drivers/gpu/drm/xe/xe_pci.c +++ b/drivers/gpu/drm/xe/xe_pci.c @@ -470,6 +470,7 @@ static const struct xe_device_desc cri_desc = { PLATFORM(CRESCENTISLAND), .dma_mask_size = 52, .has_display = false, + .has_device_uid = true, .has_drm_ras = true, .has_flat_ccs = false, .has_gsc_nvm = 1, @@ -482,6 +483,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, @@ -791,6 +793,7 @@ static int xe_info_init_early(struct xe_device *xe, xe->info.is_dgfx = desc->is_dgfx; xe->info.has_cached_pt = desc->has_cached_pt; + xe->info.has_device_uid = desc->has_device_uid; xe->info.has_drm_ras = desc->has_drm_ras; xe->info.has_fan_control = desc->has_fan_control; /* runtime fusing may force flat_ccs to disabled later */ @@ -812,6 +815,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; @@ -1400,6 +1404,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 e41af2ac7f23..dc9d1be7857c 100644 --- a/drivers/gpu/drm/xe/xe_pci_error.c +++ b/drivers/gpu/drm/xe/xe_pci_error.c @@ -29,8 +29,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); } diff --git a/drivers/gpu/drm/xe/xe_pci_types.h b/drivers/gpu/drm/xe/xe_pci_types.h index fed509ff601e..7cb372a83294 100644 --- a/drivers/gpu/drm/xe/xe_pci_types.h +++ b/drivers/gpu/drm/xe/xe_pci_types.h @@ -40,6 +40,7 @@ struct xe_device_desc { u8 has_cached_pt:1; u8 has_display:1; + u8 has_device_uid:1; u8 has_drm_ras:1; u8 has_fan_control:1; u8 has_flat_ccs:1; @@ -59,6 +60,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_pcode.c b/drivers/gpu/drm/xe/xe_pcode.c index ccc3bdeed6bb..6e41075ae9f6 100644 --- a/drivers/gpu/drm/xe/xe_pcode.c +++ b/drivers/gpu/drm/xe/xe_pcode.c @@ -136,12 +136,12 @@ int xe_pcode_write64_timeout(struct xe_tile *tile, u32 mbox, u32 data0, u32 data return err; } -int xe_pcode_read(struct xe_tile *tile, u32 mbox, u32 *val, u32 *val1) +int xe_pcode_read(struct xe_tile *tile, u32 mbox, u32 *val0, u32 *val1) { int err; mutex_lock(&tile->pcode.lock); - err = pcode_mailbox_rw(tile, mbox, val, val1, 1, true, false); + err = pcode_mailbox_rw(tile, mbox, val0, val1, PCODE_DEFAULT_TIMEOUT_MS, true, false); mutex_unlock(&tile->pcode.lock); return err; diff --git a/drivers/gpu/drm/xe/xe_pcode.h b/drivers/gpu/drm/xe/xe_pcode.h index 8fb3e4ba13a6..7e43792b0037 100644 --- a/drivers/gpu/drm/xe/xe_pcode.h +++ b/drivers/gpu/drm/xe/xe_pcode.h @@ -18,12 +18,14 @@ struct xe_pcode_version { u32 engg; }; +#define PCODE_DEFAULT_TIMEOUT_MS 10 + int xe_pcode_init_early(struct xe_tile *tile); int xe_pcode_probe_early(struct xe_device *xe); int xe_pcode_ready(struct xe_device *xe, bool locked); int xe_pcode_init_min_freq_table(struct xe_tile *tile, u32 min_gt_freq, u32 max_gt_freq); -int xe_pcode_read(struct xe_tile *tile, u32 mbox, u32 *val, u32 *val1); +int xe_pcode_read(struct xe_tile *tile, u32 mbox, u32 *val0, u32 *val1); int xe_pcode_write_timeout(struct xe_tile *tile, u32 mbox, u32 val, int timeout_ms); int xe_pcode_write64_timeout(struct xe_tile *tile, u32 mbox, u32 data0, @@ -31,7 +33,7 @@ int xe_pcode_write64_timeout(struct xe_tile *tile, u32 mbox, u32 data0, int xe_get_pcode_version(struct xe_device *xe, struct xe_pcode_version *version); #define xe_pcode_write(tile, mbox, val) \ - xe_pcode_write_timeout(tile, mbox, val, 1) + xe_pcode_write_timeout(tile, mbox, val, PCODE_DEFAULT_TIMEOUT_MS) int xe_pcode_request(struct xe_tile *tile, u32 mbox, u32 request, u32 reply_mask, u32 reply, int timeout_ms); diff --git a/drivers/gpu/drm/xe/xe_pm.c b/drivers/gpu/drm/xe/xe_pm.c index a5289a9df8d2..45a953c0a48f 100644 --- a/drivers/gpu/drm/xe/xe_pm.c +++ b/drivers/gpu/drm/xe/xe_pm.c @@ -239,15 +239,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); @@ -666,6 +666,7 @@ int xe_pm_runtime_suspend(struct xe_device *xe) */ int xe_pm_runtime_resume(struct xe_device *xe) { + struct xe_tile *tile; struct xe_gt *gt; u8 id; int err = 0; @@ -677,13 +678,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_svm.c b/drivers/gpu/drm/xe/xe_svm.c index b228a737cfd6..281b81c28e16 100644 --- a/drivers/gpu/drm/xe/xe_svm.c +++ b/drivers/gpu/drm/xe/xe_svm.c @@ -330,6 +330,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_tuning.c b/drivers/gpu/drm/xe/xe_tuning.c index bcec40ca2d35..315221bcccb1 100644 --- a/drivers/gpu/drm/xe/xe_tuning.c +++ b/drivers/gpu/drm/xe/xe_tuning.c @@ -116,7 +116,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 a8e6f18cc9b4..78b8f104e577 100644 --- a/drivers/gpu/drm/xe/xe_uc_fw.c +++ b/drivers/gpu/drm/xe/xe_uc_fw.c @@ -141,6 +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, 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 99e42bd29e79..90820f5fff28 100644 --- a/drivers/gpu/drm/xe/xe_vm.c +++ b/drivers/gpu/drm/xe/xe_vm.c @@ -269,8 +269,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); diff --git a/drivers/gpu/drm/xe/xe_wa.c b/drivers/gpu/drm/xe/xe_wa.c index 139434946f8f..0c847029437c 100644 --- a/drivers/gpu/drm/xe/xe_wa.c +++ b/drivers/gpu/drm/xe/xe_wa.c @@ -579,8 +579,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 6662987effd7..04eac463a261 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 6c263cb57766..c9ee50883f5d 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 08b58b49be5b..402cc000bc3f 100644 --- a/drivers/hwmon/gpio-fan.c +++ b/drivers/hwmon/gpio-fan.c @@ -531,8 +531,6 @@ static void gpio_fan_stop(void *data) mutex_lock(&fan_data->lock); set_fan_speed(data, 0); mutex_unlock(&fan_data->lock); - - pm_runtime_disable(fan_data->dev); } static int gpio_fan_probe(struct platform_device *pdev) @@ -560,6 +558,11 @@ static int gpio_fan_probe(struct platform_device *pdev) return dev_err_probe(dev, PTR_ERR(fan_data->supply), "Failed to get fan-supply"); + pm_runtime_set_suspended(dev); + err = devm_pm_runtime_enable(dev); + if (err) + return err; + /* Configure control GPIOs if available. */ if (fan_data->gpios && fan_data->num_gpios > 0) { if (!fan_data->speed || fan_data->num_speed <= 1) @@ -567,6 +570,12 @@ static int gpio_fan_probe(struct platform_device *pdev) err = fan_ctrl_init(fan_data); if (err) return err; + /* If current GPIO state is active, mark RPM as active as well */ + if (fan_data->speed_index > 0) { + err = pm_runtime_resume_and_get(dev); + if (err) + return err; + } err = devm_add_action_or_reset(dev, gpio_fan_stop, fan_data); if (err) return err; @@ -587,17 +596,6 @@ static int gpio_fan_probe(struct platform_device *pdev) return err; } - pm_runtime_set_suspended(&pdev->dev); - pm_runtime_enable(&pdev->dev); - /* If current GPIO state is active, mark RPM as active as well */ - if (fan_data->speed_index > 0) { - int ret; - - ret = pm_runtime_resume_and_get(&pdev->dev); - if (ret) - return ret; - } - /* Optional cooling device register for Device tree platforms */ fan_data->cdev = devm_thermal_of_child_cooling_device_register(dev, np, "gpio-fan", diff --git a/drivers/hwmon/max31760.c b/drivers/hwmon/max31760.c index 8d3be064b025..896bd0326b8c 100644 --- a/drivers/hwmon/max31760.c +++ b/drivers/hwmon/max31760.c @@ -27,8 +27,8 @@ #define REG_TACH(ch) (0x52 + (ch) * 2) #define REG_TEMP_INPUT(ch) (0x56 + (ch) * 2) -#define REG_TEMP_MAX(ch) (0x06 + (ch) * 2) -#define REG_TEMP_CRIT(ch) (0x0A + (ch) * 2) +#define REG_TEMP_MAX(ch) ((ch) ? 0x0C : 0x06) +#define REG_TEMP_CRIT(ch) ((ch) ? 0x08 : 0x0A) #define TEMP11_FROM_REG(reg) ((reg) / 32 * 125) #define TEMP11_TO_REG(val) (DIV_ROUND_CLOSEST(clamp_val((val), -128000, \ @@ -68,8 +68,9 @@ static const int max31760_pwm_freq[] = {33, 150, 1500, 25000}; static int tach_to_rpm(u16 tach) { + /* The count is 0 until the first measurement */ if (tach == 0) - tach = 1; + return 0; return 60 * 100000 / tach / 2; } @@ -533,8 +534,9 @@ static int max31760_probe(struct i2c_client *client) dev_set_drvdata(dev, state); - /* Set alert output to comparator mode */ - ret = regmap_set_bits(state->regmap, REG_CR2, CR2_ALERTS); + /* Leave standby mode, set alert output to comparator mode */ + ret = regmap_update_bits(state->regmap, REG_CR2, CR2_STBY | CR2_ALERTS, + CR2_ALERTS); if (ret) return dev_err_probe(dev, ret, "cannot write register\n"); diff --git a/drivers/hwmon/pmbus/mp2975.c b/drivers/hwmon/pmbus/mp2975.c index 8e5193933ceb..e2824b14160e 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, @@ -753,60 +840,6 @@ mp2975_current_sense_gain_get(struct i2c_client *client, return 0; } -static int -mp2975_vref_get(struct i2c_client *client, struct mp2975_data *data, - struct pmbus_driver_info *info) -{ - int ret; - - ret = i2c_smbus_write_byte_data(client, PMBUS_PAGE, 3); - if (ret < 0) - return ret; - - /* Get voltage reference value for rail 1. */ - ret = i2c_smbus_read_word_data(client, MP2975_MFR_READ_VREF_R1); - if (ret < 0) - return ret; - - data->vref[0] = ret * data->vid_step[0]; - - /* Get voltage reference value for rail 2, if connected. */ - if (data->info.pages == MP2975_PAGE_NUM) { - ret = i2c_smbus_read_word_data(client, MP2975_MFR_READ_VREF_R2); - if (ret < 0) - return ret; - - data->vref[1] = ret * data->vid_step[1]; - } - return 0; -} - -static int -mp2975_vref_offset_get(struct i2c_client *client, struct mp2975_data *data, - int page) -{ - int ret; - - ret = i2c_smbus_read_word_data(client, MP2975_MFR_OVP_TH_SET); - if (ret < 0) - return ret; - - switch ((ret & GENMASK(5, 3)) >> 3) { - case 1: - data->vref_off[page] = 140; - break; - case 2: - data->vref_off[page] = 220; - break; - case 4: - data->vref_off[page] = 400; - break; - default: - return -EINVAL; - } - return 0; -} - static int mp2975_vout_max_get(struct i2c_client *client, struct mp2975_data *data, struct pmbus_driver_info *info, int page) @@ -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; @@ -1043,11 +1057,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) @@ -1064,7 +1073,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 eec223d174c0..af764892e153 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; @@ -299,8 +299,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] = @@ -323,6 +327,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; } @@ -335,19 +345,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 4094299e2ed8..7b5c1ce66e95 100644 --- a/drivers/iio/accel/Kconfig +++ b/drivers/iio/accel/Kconfig @@ -32,6 +32,8 @@ config ADIS16209 config ADXL313 tristate + select IIO_BUFFER + select IIO_KFIFO_BUF config ADXL313_I2C tristate "Analog Devices ADXL313 3-Axis Digital Accelerometer I2C Driver" diff --git a/drivers/iio/accel/adxl380.c b/drivers/iio/accel/adxl380.c index 7dca5523091f..c83e82a83857 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/addac/ad74413r.c b/drivers/iio/addac/ad74413r.c index 2e5a58e48a89..20db890d958b 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/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 442b40ef27cf..659a2f888ac9 100644 --- a/drivers/iio/common/scmi_sensors/scmi_iio.c +++ b/drivers/iio/common/scmi_sensors/scmi_iio.c @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -70,8 +71,7 @@ static int scmi_iio_sensor_update_cb(struct notifier_block *nb, */ tstamp_scale = sensor->sensor_info->tstamp_scale + 9; if (tstamp_scale < 0) { - do_div(time, int_pow(10, abs(tstamp_scale))); - time_ns = time; + time_ns = div64_u64(time, int_pow(10, abs(tstamp_scale))); } else { time_ns = time * int_pow(10, tstamp_scale); } @@ -162,7 +162,7 @@ static int scmi_iio_set_odr_val(struct iio_dev *iio_dev, int val, int val2) mult = scnprintf(buf, sizeof(buf), "%llu", sf) - 1; sec = int_pow(10, mult) * MICROHZ_PER_HZ; - do_div(sec, uHz); + sec = div64_u64(sec, uHz); if (sec == 0) { dev_err(&iio_dev->dev, "Trying to set invalid sensor update value for sensor %s", @@ -237,13 +237,10 @@ static int scmi_iio_read_avail(struct iio_dev *iio_dev, static void convert_ns_to_freq(u64 interval_ns, u64 *hz, u64 *uhz) { - u64 rem, freq; + u64 rem; - freq = NSEC_PER_SEC; - rem = do_div(freq, interval_ns); - *hz = freq; - *uhz = rem * 1000000UL; - do_div(*uhz, interval_ns); + *hz = div64_u64_rem(HZ_PER_GHZ, interval_ns, &rem); + *uhz = div64_u64(rem * MICROHZ_PER_HZ, interval_ns); } static int scmi_iio_get_odr_val(struct iio_dev *iio_dev, int *val, int *val2) @@ -269,7 +266,8 @@ static int scmi_iio_get_odr_val(struct iio_dev *iio_dev, int *val, int *val2) mult = SCMI_SENS_CFG_GET_UPDATE_EXP(sensor_config); if (mult < 0) { sensor_interval_mult = int_pow(10, abs(mult)); - do_div(sensor_update_interval, sensor_interval_mult); + sensor_update_interval = div64_u64(sensor_update_interval, + sensor_interval_mult); } else { sensor_interval_mult = int_pow(10, mult); sensor_update_interval = @@ -395,9 +393,9 @@ static ssize_t scmi_iio_get_raw_available(struct iio_dev *iio_dev, */ exponent = exponent - scale; if (exponent < 0) { - rem = do_div(resolution, - int_pow(10, abs(exponent)) - ); + resolution = div64_u64_rem(resolution, + int_pow(10, abs(exponent)), + &rem); len = sysfs_emit(buf, "[%lld %llu.%llu %lld]\n", min_range, resolution, rem, max_range); @@ -491,7 +489,8 @@ static u64 scmi_iio_convert_interval_to_ns(u32 val) mult = SCMI_SENS_INTVL_GET_EXP(val); if (mult < 0) { sensor_interval_mult = int_pow(10, abs(mult)); - do_div(sensor_update_interval, sensor_interval_mult); + sensor_update_interval = div64_u64(sensor_update_interval, + sensor_interval_mult); } else { sensor_interval_mult = int_pow(10, mult); sensor_update_interval = diff --git a/drivers/iio/dac/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/gyro/bmg160_core.c b/drivers/iio/gyro/bmg160_core.c index d611341a0e2a..0b5621455216 100644 --- a/drivers/iio/gyro/bmg160_core.c +++ b/drivers/iio/gyro/bmg160_core.c @@ -761,7 +761,7 @@ static int bmg160_write_event_config(struct iio_dev *indio_dev, struct bmg160_data *data = iio_priv(indio_dev); int ret; - if (state && data->ev_enable_state) + if (state == data->ev_enable_state) return 0; mutex_lock(&data->mutex); diff --git a/drivers/iio/humidity/am2315.c b/drivers/iio/humidity/am2315.c index f29baa251f9f..31c4f52a0108 100644 --- a/drivers/iio/humidity/am2315.c +++ b/drivers/iio/humidity/am2315.c @@ -113,6 +113,7 @@ static int am2315_read_data(struct am2315_data *data, */ u8 rx_buf[8]; u16 crc; + u16 temp_raw; /* First wake up the device. */ am2315_ping(data->client); @@ -144,8 +145,15 @@ static int am2315_read_data(struct am2315_data *data, sensor_data->hum_data = (rx_buf[AM2315_HUM_OFFSET] << 8) | rx_buf[AM2315_HUM_OFFSET + 1]; - sensor_data->temp_data = (rx_buf[AM2315_TEMP_OFFSET] << 8) | - rx_buf[AM2315_TEMP_OFFSET + 1]; + + /* + * Temperature is sign-magnitude, not two's complement: + * bit 15 is the sign, bits 14-0 are the magnitude (x0.1 degC). + */ + temp_raw = (rx_buf[AM2315_TEMP_OFFSET] << 8) | + rx_buf[AM2315_TEMP_OFFSET + 1]; + sensor_data->temp_data = (temp_raw & 0x8000) ? + -(temp_raw & 0x7fff) : temp_raw; return ret; diff --git a/drivers/iio/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 c871981d2dad..6f7c6c5d2268 100644 --- a/drivers/iio/imu/inv_icm42600/inv_icm42600_buffer.c +++ b/drivers/iio/imu/inv_icm42600/inv_icm42600_buffer.c @@ -550,22 +550,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, @@ -590,20 +588,18 @@ int inv_icm42600_buffer_hwfifo_flush(struct inv_icm42600_state *st, if (st->fifo.nb.gyro > 0) { ts = &gyro_st->ts; inv_sensors_timestamp_interrupt(ts, st->fifo.nb.gyro, gyro_ts); - ret = inv_icm42600_gyro_parse_fifo(st->indio_gyro); - if (ret) - return ret; } + ret = inv_icm42600_gyro_parse_fifo(st->indio_gyro); + if (ret) + return ret; + if (st->fifo.nb.accel > 0) { ts = &accel_st->ts; inv_sensors_timestamp_interrupt(ts, st->fifo.nb.accel, accel_ts); - ret = inv_icm42600_accel_parse_fifo(st->indio_accel); - if (ret) - return ret; } - return 0; + return inv_icm42600_accel_parse_fifo(st->indio_accel); } int inv_icm42600_buffer_init(struct inv_icm42600_state *st) diff --git a/drivers/iio/imu/inv_mpu6050/inv_mpu_core.c b/drivers/iio/imu/inv_mpu6050/inv_mpu_core.c index 5796896d54cd..3bdcf92472e8 100644 --- a/drivers/iio/imu/inv_mpu6050/inv_mpu_core.c +++ b/drivers/iio/imu/inv_mpu6050/inv_mpu_core.c @@ -149,7 +149,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6050, .fifo_size = 1024, .temp = {INV_MPU6050_TEMP_OFFSET, INV_MPU6050_TEMP_SCALE}, - .startup_time = {INV_MPU6050_GYRO_STARTUP_TIME, INV_MPU6050_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6050_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6050_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_MPU6500_WHOAMI_VALUE, @@ -158,7 +161,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_MPU6500_TEMP_OFFSET, INV_MPU6500_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_MPU6515_WHOAMI_VALUE, @@ -167,7 +173,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_MPU6500_TEMP_OFFSET, INV_MPU6500_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_MPU6880_WHOAMI_VALUE, @@ -176,7 +185,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 4096, .temp = {INV_MPU6500_TEMP_OFFSET, INV_MPU6500_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_MPU6000_WHOAMI_VALUE, @@ -185,7 +197,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6050, .fifo_size = 1024, .temp = {INV_MPU6050_TEMP_OFFSET, INV_MPU6050_TEMP_SCALE}, - .startup_time = {INV_MPU6050_GYRO_STARTUP_TIME, INV_MPU6050_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6050_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6050_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_MPU9150_WHOAMI_VALUE, @@ -194,7 +209,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6050, .fifo_size = 1024, .temp = {INV_MPU6050_TEMP_OFFSET, INV_MPU6050_TEMP_SCALE}, - .startup_time = {INV_MPU6050_GYRO_STARTUP_TIME, INV_MPU6050_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6050_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6050_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_MPU9250_WHOAMI_VALUE, @@ -203,7 +221,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_MPU6500_TEMP_OFFSET, INV_MPU6500_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_MPU9255_WHOAMI_VALUE, @@ -212,7 +233,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_MPU6500_TEMP_OFFSET, INV_MPU6500_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_ICM20608_WHOAMI_VALUE, @@ -221,7 +245,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_ICM20608D_WHOAMI_VALUE, @@ -230,7 +257,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_ICM20609_WHOAMI_VALUE, @@ -239,7 +269,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 4 * 1024, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_ICM20689_WHOAMI_VALUE, @@ -248,7 +281,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 4 * 1024, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_ICM20600_WHOAMI_VALUE, @@ -257,7 +293,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 1008, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_ICM20602_GYRO_STARTUP_TIME, INV_ICM20602_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_ICM20602_ACCEL_STARTUP_TIME, + .gyro = INV_ICM20602_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_ICM20602_WHOAMI_VALUE, @@ -266,7 +305,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 1008, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_ICM20602_GYRO_STARTUP_TIME, INV_ICM20602_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_ICM20602_ACCEL_STARTUP_TIME, + .gyro = INV_ICM20602_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_ICM20690_WHOAMI_VALUE, @@ -275,7 +317,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 1024, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_ICM20690_GYRO_STARTUP_TIME, INV_ICM20690_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_ICM20690_ACCEL_STARTUP_TIME, + .gyro = INV_ICM20690_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_IAM20380_WHOAMI_VALUE, .name = "IAM20380", @@ -283,7 +328,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_IAM20680_WHOAMI_VALUE, @@ -292,7 +340,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_IAM20680HP_WHOAMI_VALUE, @@ -301,7 +352,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 4 * 1024, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_IAM20680HT_WHOAMI_VALUE, @@ -310,7 +364,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 4 * 1024, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, }; @@ -1574,6 +1631,8 @@ static const unsigned long inv_mpu_scan_masks[] = { .type = IIO_MAGN, \ .modified = 1, \ .channel2 = _chan2, \ + /* index of the axis in magn_raw_to_gauss[] */ \ + .address = (_chan2) - IIO_MOD_X, \ .info_mask_separate = BIT(IIO_CHAN_INFO_SCALE) | \ BIT(IIO_CHAN_INFO_RAW), \ .scan_index = _index, \ diff --git a/drivers/iio/imu/kmx61.c b/drivers/iio/imu/kmx61.c index c288437d53ea..a4962b88ef58 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 #include #include +#include /** * iio_read_acpi_mount_matrix() - Read accelerometer mount matrix info from ACPI @@ -63,6 +64,14 @@ bool iio_read_acpi_mount_matrix(struct device *dev, } str = elements[i].string.pointer; + /* + * Microsoft's example separates the values with spaces, "0 1 0". + * Some BIOSes use commas instead, with or without spaces around + * them: "0, 1, 0", "0, -1 , 0", "1, 0,0". The string lives in + * the buffer allocated for us above, so turn the commas into + * spaces in place before parsing. + */ + strreplace(str, ',', ' '); if (sscanf(str, "%d %d %d", &val[0], &val[1], &val[2]) != 3) { dev_err(dev, "Incorrect ACPI mount matrix string format\n"); goto out_free_buffer; diff --git a/drivers/iio/industrialio-trigger.c b/drivers/iio/industrialio-trigger.c index 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/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 #include #include +#include #include #include #include @@ -362,6 +363,10 @@ static int tsl2591_wait_adc_complete(struct tsl2591_chip *chip) * Scale values to get more representative value of lux i.e. * lux = ((C0DATA - C1DATA) * (1000 - ((C1DATA * 1000) / C0DATA))) / CPL * + * CPL is not computed on its own: at 1x gain it is below 1 for integration + * times under 500 ms, so the division by LUX DF is folded into the final + * division instead. + * * Channel 0 = IR + Visible * Channel 1 = IR only */ @@ -373,8 +378,10 @@ static int tsl2591_read_channel_data(struct iio_dev *indio_dev, struct tsl2591_als_settings *settings = &chip->als_settings; struct i2c_client *client = chip->client; u8 als_data[TSL2591_NUM_DATA_REGISTERS]; - int counts_per_lux, int_time_fval, gain_multi, lux; + int int_time_fval, gain_multi; u16 als_ch0, als_ch1; + u64 lux; + u32 rem; int ret; ret = tsl2591_wait_adc_complete(chip); @@ -410,23 +417,28 @@ static int tsl2591_read_channel_data(struct iio_dev *indio_dev, return gain_multi; } - int_time_fval = TSL2591_FVAL_TO_MSEC(settings->als_int_time); - /* Calculate counts per lux value */ - counts_per_lux = (int_time_fval * gain_multi) / TSL2591_LUX_COEFFICIENT; + /* No visible light, this also catches C0DATA == 0 */ + if (als_ch0 <= als_ch1) { + *val = 0; + *val2 = 0; + break; + } - dev_dbg(&client->dev, "Counts Per Lux: %d\n", counts_per_lux); + int_time_fval = TSL2591_FVAL_TO_MSEC(settings->als_int_time); /* Calculate lux value */ - lux = ((als_ch0 - als_ch1) * - (1000 - ((als_ch1 * 1000) / als_ch0))) / counts_per_lux; + lux = (u64)(als_ch0 - als_ch1) * + (1000 - ((als_ch1 * 1000) / als_ch0)) * + TSL2591_LUX_COEFFICIENT; + lux = div_u64(lux, int_time_fval * gain_multi); - dev_dbg(&client->dev, "Raw lux calculation: %d\n", lux); + dev_dbg(&client->dev, "Raw lux calculation: %llu\n", lux); /* Divide by 1000 to get real lux value before scaling */ - *val = lux / 1000; + *val = div_u64_rem(lux, 1000, &rem); /* Get the decimal part of lux reading */ - *val2 = (lux - (*val * 1000)) * 1000; + *val2 = rem * 1000; break; default: diff --git a/drivers/iio/light/vcnl4035.c b/drivers/iio/light/vcnl4035.c index 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 #include #include +#include #include #include #include #include +#include #include @@ -43,6 +45,7 @@ #define SX9360_REG_GNRL_CTRL1_SCANPERIOD_MASK GENMASK(2, 0) #define SX9360_REG_GNRL_CTRL2 0x12 #define SX9360_REG_GNRL_CTRL2_PERIOD_102MS 0x32 +#define SX9360_REG_GNRL_SCANPERIOD_MAX GENMASK(10, 0) #define SX9360_REG_GNRL_REG_2_PERIOD_MS(_r) \ (((_r) * 8192) / (SX9360_FOSC_HZ / 1000)) #define SX9360_REG_GNRL_FREQ_2_REG(_f) (((_f) * 8192) / SX9360_FOSC_HZ) @@ -182,9 +185,9 @@ static const struct { int val; int val2; } sx9360_samp_freq_interval[] = { - { 0, 281250 }, /* 4MHz / (8192 * 2047) */ - { 0, 281250 }, - { 448, 281250 }, /* 4MHz / 8192 */ + { 0, 238535 }, /* 4MHz / (8192 * 2047) */ + { 0, 238419 }, + { 488, 281250 }, /* 4MHz / 8192 */ }; static const struct regmap_range sx9360_writable_reg_ranges[] = { @@ -383,11 +386,25 @@ static int sx9360_read_avail(struct iio_dev *indio_dev, static int sx9360_set_samp_freq(struct sx_common_data *data, int val, int val2) { - int reg; + unsigned int period_ticks; + u64 freq_uHz; __be16 buf; - reg = val * 8192 / SX9360_FOSC_HZ + val2 * 8192 / (SX9360_FOSC_MHZ); - buf = cpu_to_be16(reg); + if (val < 0 || val2 < 0) + return -EINVAL; + + freq_uHz = (u64)val * MICROHZ_PER_HZ + val2; + if (!freq_uHz) + return -EINVAL; + + /* The register holds the scan period in ticks of 8192 FOSC cycles. */ + period_ticks = DIV64_U64_ROUND_CLOSEST((u64)SX9360_FOSC_HZ * MICROHZ_PER_HZ, + freq_uHz * 8192); + if (!period_ticks || period_ticks > SX9360_REG_GNRL_SCANPERIOD_MAX) + return -EINVAL; + + buf = cpu_to_be16(period_ticks); + guard(mutex)(&data->mutex); return regmap_bulk_write(data->regmap, SX9360_REG_GNRL_CTRL1, &buf, diff --git a/drivers/iio/proximity/sx9500.c b/drivers/iio/proximity/sx9500.c index 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/input/ff-core.c b/drivers/input/ff-core.c index 0e5d1d1ceb46..133b4622dc49 100644 --- a/drivers/input/ff-core.c +++ b/drivers/input/ff-core.c @@ -338,7 +338,7 @@ EXPORT_SYMBOL_GPL(input_ff_create); * * This function is only needed in error path as input core will * automatically free force feedback structures when device is - * destroyed. + * unregistered or destroyed. */ void input_ff_destroy(struct input_dev *dev) { diff --git a/drivers/input/ff-memless.c b/drivers/input/ff-memless.c index d1fefd1dfc0d..3069436148ec 100644 --- a/drivers/input/ff-memless.c +++ b/drivers/input/ff-memless.c @@ -483,32 +483,10 @@ static void ml_ff_destroy(struct ff_device *ff) { struct ml_device *ml = ff->private; - /* - * The timer is normally shut down in ml_ff_stop() when the device - * is unregistered. However, we still shut it down here as a safety - * net and for cases where the device was never registered (e.g. - * error paths during probe). - */ timer_shutdown_sync(&ml->timer); - kfree(ml->private); } -static void ml_ff_stop(struct ff_device *ff) -{ - struct ml_device *ml = ff->private; - - /* - * Even though we stop all playing effects when tearing down an - * input device (by the way of evdev calling input_flush_device() - * that calls into input_ff_flush() that stops and erases all - * effects), we do not actually shutdown the timer, and therefore - * we should do it here to prevent it firing after the input - * device is unregistered and its associated resources are freed. - */ - timer_shutdown_sync(&ml->timer); -} - /** * input_ff_create_memless() - create memoryless force-feedback device * @dev: input device supporting force-feedback @@ -543,7 +521,6 @@ int input_ff_create_memless(struct input_dev *dev, void *data, ff->playback = ml_ff_playback; ff->set_gain = ml_ff_set_gain; ff->destroy = ml_ff_destroy; - ff->stop = ml_ff_stop; /* we can emulate periodic effects with RUMBLE */ if (test_bit(FF_RUMBLE, ff->ffbit)) { diff --git a/drivers/input/input.c b/drivers/input/input.c index 6c45a158047f..2f0fa8ebee85 100644 --- a/drivers/input/input.c +++ b/drivers/input/input.c @@ -2265,10 +2265,9 @@ static void __input_unregister_device(struct input_dev *dev) input_wakeup_procfs_readers(); } - if (dev->ff && dev->ff->stop) - dev->ff->stop(dev->ff); - device_del(&dev->dev); + + input_ff_destroy(dev); } static void devm_input_device_unregister(struct device *dev, void *res) diff --git a/drivers/iommu/amd/init.c b/drivers/iommu/amd/init.c index cfc061a4247a..8b924d084ab7 100644 --- a/drivers/iommu/amd/init.c +++ b/drivers/iommu/amd/init.c @@ -3493,6 +3493,7 @@ static __init void iommu_snp_enable(void) return; disable_snp: + amd_iommu_snp_en = false; cc_platform_clear(CC_ATTR_HOST_SEV_SNP); #endif } diff --git a/drivers/md/dm-cache-metadata.c b/drivers/md/dm-cache-metadata.c index acd9b179fcb3..4bad5348c1bf 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 1a5072425c4a..809184371629 100644 --- a/drivers/md/dm-cache-target.c +++ b/drivers/md/dm-cache-target.c @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -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 0bd22bda3e2d..df1a4d0cda6b 100644 --- a/drivers/md/dm-crypt.c +++ b/drivers/md/dm-crypt.c @@ -1964,8 +1964,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; } @@ -2826,8 +2827,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, ','); @@ -3208,6 +3212,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; @@ -3219,10 +3231,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 @@ static int dm_integrity_ctr(struct dm_target *ti, unsigned int argc, char **argv r = create_journal(ic, &ti->error); if (r) goto bad; - } if (ic->mode == 'B') { diff --git a/drivers/md/dm-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 7cb7bb6233b6..4638df06dfab 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 7165fc0364bb..0c15bb01068e 100644 --- a/drivers/md/dm-pcache/backing_dev.c +++ b/drivers/md/dm-pcache/backing_dev.c @@ -336,9 +336,9 @@ struct pcache_backing_dev_req *backing_dev_req_create(struct pcache_backing_dev return backing_req; } -void backing_dev_flush(struct pcache_backing_dev *backing_dev) +int backing_dev_flush(struct pcache_backing_dev *backing_dev) { - blkdev_issue_flush(backing_dev->dm_dev->bdev); + return blkdev_issue_flush(backing_dev->dm_dev->bdev); } int pcache_backing_init(void) diff --git a/drivers/md/dm-pcache/backing_dev.h b/drivers/md/dm-pcache/backing_dev.h index b371cba483b9..8422e5e76e29 100644 --- a/drivers/md/dm-pcache/backing_dev.h +++ b/drivers/md/dm-pcache/backing_dev.h @@ -120,7 +120,7 @@ struct pcache_backing_dev_req *backing_dev_req_alloc(struct pcache_backing_dev * struct pcache_backing_dev_req_opts *opts); void backing_dev_req_init(struct pcache_backing_dev_req *backing_req, struct pcache_backing_dev_req_opts *opts); -void backing_dev_flush(struct pcache_backing_dev *backing_dev); +int backing_dev_flush(struct pcache_backing_dev *backing_dev); int pcache_backing_init(void); void pcache_backing_exit(void); diff --git a/drivers/md/dm-pcache/cache_writeback.c b/drivers/md/dm-pcache/cache_writeback.c index c8a4c8110a58..e09560f172dd 100644 --- a/drivers/md/dm-pcache/cache_writeback.c +++ b/drivers/md/dm-pcache/cache_writeback.c @@ -18,12 +18,18 @@ static void writeback_ctx_end(struct pcache_cache *cache, int ret) return; if (!cache->writeback_ctx.ret) { - backing_dev_flush(cache->backing_dev); - - mutex_lock(&cache->dirty_tail_lock); - cache_pos_advance(&cache->dirty_tail, cache->writeback_ctx.advance); - cache_encode_dirty_tail(cache); - mutex_unlock(&cache->dirty_tail_lock); + ret = backing_dev_flush(cache->backing_dev); + if (ret) { + pcache_dev_err(CACHE_TO_PCACHE(cache), + "failed to flush backing device: %d", ret); + cache->writeback_ctx.ret = ret; + } else { + mutex_lock(&cache->dirty_tail_lock); + cache_pos_advance(&cache->dirty_tail, + cache->writeback_ctx.advance); + cache_encode_dirty_tail(cache); + mutex_unlock(&cache->dirty_tail_lock); + } } queue_delayed_work(cache_get_wq(cache), &cache->writeback_work, 0); } @@ -76,8 +82,16 @@ static inline bool is_cache_clean(struct pcache_cache *cache, struct pcache_cach void cache_writeback_exit(struct pcache_cache *cache) { + int ret; + cancel_delayed_work_sync(&cache->writeback_work); - backing_dev_flush(cache->backing_dev); + + ret = backing_dev_flush(cache->backing_dev); + if (ret) + pcache_dev_err(CACHE_TO_PCACHE(cache), + "failed to flush backing device during exit: %d", + ret); + cache_tree_exit(&cache->writeback_key_tree); } diff --git a/drivers/md/dm-raid.c b/drivers/md/dm-raid.c index 8f5a5e1342a9..8146df7ecf33 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 a483f49dd4ce..db1ec4ae8e56 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; - - 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); + struct dm_dev_internal *dd, *dd_next; + struct dm_dev_ref *ref, *ref_next; + + 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,12 +220,27 @@ 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. */ @@ -303,31 +320,6 @@ static int device_area_is_invalid(struct dm_target *ti, struct dm_dev *dev, return 0; } -/* - * 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 59392de7a477..3fd1f63b7834 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 cb105ccc47ec..a1a963731155 100644 --- a/drivers/md/dm-verity-target.c +++ b/drivers/md/dm-verity-target.c @@ -170,6 +170,15 @@ static void verity_hash_at_level(struct dm_verity *v, sector_t block, int level, *offset = idx << (v->hash_dev_block_bits - v->hash_per_block_bits); } +/* + * Skip verity work in response to I/O error when system is shutting down. + */ +static inline bool verity_is_system_shutting_down(void) +{ + return system_state == SYSTEM_HALT || system_state == SYSTEM_POWER_OFF + || system_state == SYSTEM_RESTART; +} + /* * Handle verification errors. */ @@ -219,6 +228,15 @@ static int verity_handle_err(struct dm_verity *v, enum verity_block_type type, if (v->mode == DM_VERITY_MODE_LOGGING) return 0; + /* + * Devices may already be quiesced (e.g. UFS set offline by its + * shutdown hook), so a failure here does not imply corruption. Fail + * the I/O but do not restart or panic, which would also override the + * reboot reason of the shutdown already in progress. + */ + if (verity_is_system_shutting_down()) + return 1; + if (v->mode == DM_VERITY_MODE_RESTART) kernel_restart("dm-verity device corrupted"); @@ -593,15 +611,6 @@ static int verity_verify_io(struct dm_verity_io *io) 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 f29acf64429a..ce4f94685a78 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 aeec5b9a1dd5..19ba265181c4 100644 --- a/drivers/md/persistent-data/dm-btree-remove.c +++ b/drivers/md/persistent-data/dm-btree-remove.c @@ -253,7 +253,9 @@ static int __rebalance2(struct dm_btree_info *info, struct btree_node *parent, /* * Merge */ - node_copy(left, right, -nr_right); + ret = node_copy(left, right, -nr_right); + if (unlikely(ret)) + return ret; left->header.nr_entries = cpu_to_le32(nr_left + nr_right); delete_at(parent, r->index); @@ -315,13 +317,16 @@ static int delete_center_node(struct dm_btree_info *info, struct btree_node *par { uint32_t max_entries = le32_to_cpu(left->header.max_entries); unsigned int shift = min(max_entries - nr_left, nr_center); + int ret; if (nr_left + shift > max_entries) { DMERR("node shift out of bounds"); return -EINVAL; } - node_copy(left, center, -shift); + ret = node_copy(left, center, -shift); + if (unlikely(ret)) + return ret; left->header.nr_entries = cpu_to_le32(nr_left + shift); if (shift != nr_center) { @@ -333,7 +338,9 @@ static int delete_center_node(struct dm_btree_info *info, struct btree_node *par } node_shift(right, shift); - node_copy(center, right, shift); + ret = node_copy(center, right, shift); + if (unlikely(ret)) + return ret; right->header.nr_entries = cpu_to_le32(nr_right + shift); } *key_ptr(parent, r->index) = right->keys[0]; diff --git a/drivers/md/persistent-data/dm-btree.c b/drivers/md/persistent-data/dm-btree.c index 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 da82b1edb7c9..76d408120a8d 100644 --- a/drivers/misc/ibmvmc.c +++ b/drivers/misc/ibmvmc.c @@ -2365,14 +2365,6 @@ static int __init ibmvmc_module_init(void) ibmvmc.state = ibmvmc_state_initial; pr_info("ibmvmc: version %s\n", IBMVMC_DRIVER_VERSION); - rc = misc_register(&ibmvmc_miscdev); - if (rc) { - pr_err("ibmvmc: misc registration failed\n"); - goto misc_register_failed; - } - pr_info("ibmvmc: node %d:%d\n", MISC_MAJOR, - ibmvmc_miscdev.minor); - /* Initialize data structures */ memset(hmcs, 0, sizeof(struct ibmvmc_hmc) * MAX_HMCS); for (i = 0; i < MAX_HMCS; i++) { @@ -2382,6 +2374,14 @@ static int __init ibmvmc_module_init(void) hmcs[i].queue_outbound_msgs[j] = VMC_INVALID_BUFFER_ID; } + rc = misc_register(&ibmvmc_miscdev); + if (rc) { + pr_err("ibmvmc: misc registration failed\n"); + goto misc_register_failed; + } + pr_info("ibmvmc: node %d:%d\n", MISC_MAJOR, + ibmvmc_miscdev.minor); + /* Sanity check module parms */ ibmvmc_scrub_module_parms(); diff --git a/drivers/misc/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 694bb443d5f3..c93fef2f7d15 100644 --- a/drivers/mmc/host/meson-gx-mmc.c +++ b/drivers/mmc/host/meson-gx-mmc.c @@ -125,6 +125,7 @@ #define SD_EMMC_CFG_RESP_TIMEOUT 256 /* in clock cycles */ #define SD_EMMC_CMD_TIMEOUT 1024 /* in ms */ #define SD_EMMC_CMD_TIMEOUT_DATA 4096 /* in ms */ +#define SD_EMMC_CMD_TIMEOUT_MAX 32768 /* in ms, 2^15: limit of CMD_CFG_TIMEOUT_MASK */ #define SD_EMMC_CFG_CMD_GAP 16 /* in clock cycles */ #define SD_EMMC_DESC_BUF_LEN PAGE_SIZE @@ -211,7 +212,21 @@ static unsigned int meson_mmc_get_timeout_msecs(struct mmc_data *data) timeout = roundup_pow_of_two(timeout); - return min(timeout, 32768U); /* max. 2^15 ms */ + return min_t(unsigned int, timeout, SD_EMMC_CMD_TIMEOUT_MAX); +} + +/* For R1b the controller waits for busy to be released within this timeout. */ +static unsigned int meson_mmc_get_cmd_timeout_msecs(struct mmc_command *cmd) +{ + unsigned int timeout = cmd->busy_timeout; + + if (!timeout) + return SD_EMMC_CMD_TIMEOUT; + + timeout = clamp_t(unsigned int, timeout, SD_EMMC_CMD_TIMEOUT, + SD_EMMC_CMD_TIMEOUT_MAX); + + return roundup_pow_of_two(timeout); } static struct mmc_command *meson_mmc_get_next_command(struct mmc_command *cmd) @@ -840,7 +855,7 @@ static void meson_mmc_start_cmd(struct mmc_host *mmc, struct mmc_command *cmd) cmd_data = host->bounce_dma_addr & CMD_DATA_MASK; } else { cmd_cfg |= FIELD_PREP(CMD_CFG_TIMEOUT_MASK, - ilog2(SD_EMMC_CMD_TIMEOUT)); + ilog2(meson_mmc_get_cmd_timeout_msecs(cmd))); } /* Last descriptor */ @@ -1079,8 +1094,8 @@ static int meson_mmc_card_busy(struct mmc_host *mmc) regval = readl(host->regs + SD_EMMC_STATUS); - /* We are only interrested in lines 0 to 3, so mask the other ones */ - return !(FIELD_GET(STATUS_DATI, regval) & 0xf); + /* The card signals busy on DAT0 alone. */ + return !(FIELD_GET(STATUS_DATI, regval) & BIT(0)); } static int meson_mmc_voltage_switch(struct mmc_host *mmc, struct mmc_ios *ios) @@ -1166,6 +1181,9 @@ static int meson_mmc_probe(struct platform_device *pdev) mmc->caps |= MMC_CAP_CMD23; + /* The longest busy wait the CMD_CFG timeout field can hold. */ + mmc->max_busy_timeout = SD_EMMC_CMD_TIMEOUT_MAX; + if (mmc->caps & MMC_CAP_SDIO_IRQ) mmc->caps2 |= MMC_CAP2_SDIO_IRQ_NOTHREAD; diff --git a/drivers/mmc/host/mmci.c b/drivers/mmc/host/mmci.c index 416bdb184ed4..4db5c55b2700 100644 --- a/drivers/mmc/host/mmci.c +++ b/drivers/mmc/host/mmci.c @@ -2477,11 +2477,13 @@ static int mmci_probe(struct amba_device *dev, ret = mmc_add_host(mmc); if (ret) - goto clk_disable; + goto dma_release; pm_runtime_put(&dev->dev); return 0; +dma_release: + mmci_dma_release(host); clk_disable: clk_disable_unprepare(host->clk); return ret; diff --git a/drivers/mmc/host/omap.c b/drivers/mmc/host/omap.c index 527b89a5ed70..02d288e4e9dc 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 1de2f05fd958..7c17a3cd6a6c 100644 --- a/drivers/mmc/host/sdhci-brcmstb.c +++ b/drivers/mmc/host/sdhci-brcmstb.c @@ -491,6 +491,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; @@ -534,9 +535,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 6ab59d3e346f..931e383748a9 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 faa21015b34d..4e51269de3ca 100644 --- a/drivers/net/amt.c +++ b/drivers/net/amt.c @@ -2137,13 +2137,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) { @@ -3394,22 +3393,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) { @@ -3419,26 +3402,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 7019e5d8fdc8..e9f5e753f677 100644 --- a/drivers/net/bonding/bond_main.c +++ b/drivers/net/bonding/bond_main.c @@ -2305,7 +2305,7 @@ int bond_enslave(struct net_device *bond_dev, struct net_device *slave_dev, SLAVE_NL_ERR(bond_dev, slave_dev, extack, "Slave does not support XDP"); res = -EOPNOTSUPP; - goto err_sysfs_del; + goto err_dec_slave_cnt; } } else if (bond->xdp_prog) { struct netdev_bpf xdp = { @@ -2319,14 +2319,14 @@ int bond_enslave(struct net_device *bond_dev, struct net_device *slave_dev, SLAVE_NL_ERR(bond_dev, slave_dev, extack, "Slave has XDP program loaded, please unload before enslaving"); res = -EOPNOTSUPP; - goto err_sysfs_del; + goto err_dec_slave_cnt; } res = dev_xdp_propagate(slave_dev, &xdp); if (res < 0) { /* ndo_bpf() sets extack error message */ slave_dbg(bond_dev, slave_dev, "Error %d calling ndo_bpf\n", res); - goto err_sysfs_del; + goto err_dec_slave_cnt; } if (bond->xdp_prog) bpf_prog_inc(bond->xdp_prog); @@ -2348,6 +2348,9 @@ int bond_enslave(struct net_device *bond_dev, struct net_device *slave_dev, return 0; /* Undo stages on error */ +err_dec_slave_cnt: + WRITE_ONCE(bond->slave_cnt, bond->slave_cnt - 1); + err_sysfs_del: bond_sysfs_slave_del(new_slave); @@ -2779,6 +2782,27 @@ static void bond_miimon_link_change(struct bonding *bond, } } +static bool bond_miimon_slave_down(struct bonding *bond, + struct slave *slave) +{ + if (slave->link_failure_count < UINT_MAX) + slave->link_failure_count++; + + bond_set_slave_link_state(slave, BOND_LINK_DOWN, + BOND_SLAVE_NOTIFY_NOW); + + if (BOND_MODE(bond) == BOND_MODE_ACTIVEBACKUP || + BOND_MODE(bond) == BOND_MODE_8023AD) + bond_set_slave_inactive_flags(slave, + BOND_SLAVE_NOTIFY_NOW); + + slave_info(bond->dev, slave->dev, "link status definitely down, disabling slave\n"); + + bond_miimon_link_change(bond, slave, BOND_LINK_DOWN); + + return slave == rcu_access_pointer(bond->curr_active_slave); +} + static void bond_miimon_commit(struct bonding *bond) { struct slave *slave, *primary, *active; @@ -2807,10 +2831,22 @@ static void bond_miimon_commit(struct bonding *bond) err = bond_update_speed_duplex(slave); netdev_unlock_ops(slave->dev); if (err && bond_needs_speed_duplex(bond)) { - slave->link = BOND_LINK_DOWN; if (net_ratelimit()) slave_warn(bond->dev, slave->dev, "failed to get link speed/duplex\n"); + /* Coming from FAIL/UP, the slave may still be + * in use and may be curr_active_slave, so take + * it through the full down path. Coming from + * DOWN/BACK, it was never brought up, so just + * revert it to DOWN. + */ + if (slave->link == BOND_LINK_FAIL || + slave->link == BOND_LINK_UP) { + if (bond_miimon_slave_down(bond, slave)) + do_failover = true; + continue; + } + slave->link = BOND_LINK_DOWN; continue; } bond_set_slave_link_state(slave, BOND_LINK_UP, @@ -2839,28 +2875,13 @@ static void bond_miimon_commit(struct bonding *bond) continue; case BOND_LINK_DOWN: - if (slave->link_failure_count < UINT_MAX) - slave->link_failure_count++; - - bond_set_slave_link_state(slave, BOND_LINK_DOWN, - BOND_SLAVE_NOTIFY_NOW); - - if (BOND_MODE(bond) == BOND_MODE_ACTIVEBACKUP || - BOND_MODE(bond) == BOND_MODE_8023AD) - bond_set_slave_inactive_flags(slave, - BOND_SLAVE_NOTIFY_NOW); - - slave_info(bond->dev, slave->dev, "link status definitely down, disabling slave\n"); - - bond_miimon_link_change(bond, slave, BOND_LINK_DOWN); - - if (slave == rcu_access_pointer(bond->curr_active_slave)) + if (bond_miimon_slave_down(bond, slave)) do_failover = true; - continue; case BOND_LINK_FAIL: case BOND_LINK_BACK: + bond_commit_link_state(slave, BOND_SLAVE_NOTIFY_LATER); slave_dbg(bond->dev, slave->dev, "link_new_state %d on slave\n", slave->link_new_state); continue; @@ -2894,8 +2915,6 @@ static void bond_mii_monitor(struct work_struct *work) { struct bonding *bond = container_of(work, struct bonding, mii_work.work); - struct list_head *iter; - struct slave *slave; unsigned long delay; bool commit; @@ -2917,13 +2936,8 @@ static void bond_mii_monitor(struct work_struct *work) goto re_arm; } - if (commit) { - bond_for_each_slave(bond, slave, iter) { - bond_commit_link_state(slave, - BOND_SLAVE_NOTIFY_LATER); - } + if (commit) bond_miimon_commit(bond); - } if (bond->send_peer_notif) bond_peer_notify_may_events(bond, true); @@ -3973,18 +3987,13 @@ static int bond_slave_netdev_event(unsigned long event, case NETDEV_CHANGE: /* For 802.3ad mode only: * Getting invalid Speed/Duplex values here will put slave - * in weird state. Mark it as link-fail if the link was - * previously up or link-down if it hasn't yet come up, and - * let link-monitoring (miimon) set it right when correct - * speeds/duplex are available. + * in weird state. Mark an up slave as link-fail and let + * miimon set it right when correct speed/duplex are available. */ if (bond_update_speed_duplex(slave) && - BOND_MODE(bond) == BOND_MODE_8023AD) { - if (slave->last_link_up) - slave->link = BOND_LINK_FAIL; - else - slave->link = BOND_LINK_DOWN; - } + BOND_MODE(bond) == BOND_MODE_8023AD && + slave->link == BOND_LINK_UP) + slave->link = BOND_LINK_FAIL; if (BOND_MODE(bond) == BOND_MODE_8023AD) bond_3ad_adapter_speed_duplex_changed(slave); diff --git a/drivers/net/can/dev/netlink.c b/drivers/net/can/dev/netlink.c index b958c04d53db..081dfddda000 100644 --- a/drivers/net/can/dev/netlink.c +++ b/drivers/net/can/dev/netlink.c @@ -720,7 +720,8 @@ static int can_changelink(struct net_device *dev, struct nlattr *tb[], return 0; } -static size_t can_tdc_get_size(struct data_bittiming_params *dbt_params, +static size_t can_tdc_get_size(const struct net_device *dev, + struct data_bittiming_params *dbt_params, u32 tdc_flags) { bool tdc_manual = tdc_flags & CAN_CTRLMODE_TDC_MANUAL_MASK; @@ -742,7 +743,8 @@ static size_t can_tdc_get_size(struct data_bittiming_params *dbt_params, } if (tdc_flags) { - if (tdc_manual || dbt_params->do_get_auto_tdcv) + if (tdc_manual || + (dbt_params->do_get_auto_tdcv && netif_running(dev))) size += nla_total_size(sizeof(u32)); /* IFLA_CAN_TDCV */ size += nla_total_size(sizeof(u32)); /* IFLA_CAN_TDCO */ if (dbt_params->tdc_const->tdcf_max) @@ -752,7 +754,8 @@ static size_t can_tdc_get_size(struct data_bittiming_params *dbt_params, return size; } -static size_t can_data_bittiming_get_size(struct data_bittiming_params *dbt_params, +static size_t can_data_bittiming_get_size(const struct net_device *dev, + struct data_bittiming_params *dbt_params, u32 tdc_flags) { size_t size = 0; @@ -764,7 +767,7 @@ static size_t can_data_bittiming_get_size(struct data_bittiming_params *dbt_para if (dbt_params->data_bitrate_const) /* IFLA_CAN_{,XL}_DATA_BITRATE_CONST */ size += nla_total_size(sizeof(*dbt_params->data_bitrate_const) * dbt_params->data_bitrate_const_cnt); - size += can_tdc_get_size(dbt_params, tdc_flags);/* IFLA_CAN_{,XL}_TDC */ + size += can_tdc_get_size(dev, dbt_params, tdc_flags);/* IFLA_CAN_{,XL}_TDC */ return size; } @@ -825,10 +828,10 @@ static size_t can_get_size(const struct net_device *dev) size += sizeof(priv->bitrate_max); /* IFLA_CAN_BITRATE_MAX */ size += can_ctrlmode_ext_get_size(); /* IFLA_CAN_CTRLMODE_EXT */ - size += can_data_bittiming_get_size(&priv->fd, + size += can_data_bittiming_get_size(dev, &priv->fd, priv->ctrlmode & CAN_CTRLMODE_FD_TDC_MASK); - size += can_data_bittiming_get_size(&priv->xl, + size += can_data_bittiming_get_size(dev, &priv->xl, priv->ctrlmode & CAN_CTRLMODE_XL_TDC_MASK); size += can_pwm_get_size(priv->xl.pwm_const, /* IFLA_CAN_XL_PWM */ priv->ctrlmode & CAN_CTRLMODE_XL_TMS); @@ -910,7 +913,7 @@ static int can_tdc_fill_info(struct sk_buff *skb, const struct net_device *dev, if (tdc_manual) { tdcv = tdc->tdcv; err = 0; - } else if (dbt_params->do_get_auto_tdcv) { + } else if (dbt_params->do_get_auto_tdcv && netif_running(dev)) { err = dbt_params->do_get_auto_tdcv(dev, &tdcv); } if (!err && nla_put_u32(skb, IFLA_CAN_TDC_TDCV, tdcv)) diff --git a/drivers/net/can/dev/skb.c b/drivers/net/can/dev/skb.c index 9e274147ffe5..738d5968dfa6 100644 --- a/drivers/net/can/dev/skb.c +++ b/drivers/net/can/dev/skb.c @@ -229,7 +229,7 @@ struct sk_buff *alloc_can_skb(struct net_device *dev, struct can_frame **cf) csx = can_skb_ext_add(skb); if (!csx) { - kfree_skb(skb); + dev_kfree_skb_any(skb); goto out_error_cc; } @@ -260,7 +260,7 @@ struct sk_buff *alloc_canfd_skb(struct net_device *dev, csx = can_skb_ext_add(skb); if (!csx) { - kfree_skb(skb); + dev_kfree_skb_any(skb); goto out_error_fd; } @@ -298,7 +298,7 @@ struct sk_buff *alloc_canxl_skb(struct net_device *dev, csx = can_skb_ext_add(skb); if (!csx) { - kfree_skb(skb); + dev_kfree_skb_any(skb); goto out_error_xl; } diff --git a/drivers/net/dsa/b53/b53_common.c b/drivers/net/dsa/b53/b53_common.c index 0880310c9ce3..a2a5754c413c 100644 --- a/drivers/net/dsa/b53/b53_common.c +++ b/drivers/net/dsa/b53/b53_common.c @@ -836,6 +836,59 @@ void b53_brcm_hdr_setup(struct dsa_switch *ds, int port) } EXPORT_SYMBOL(b53_brcm_hdr_setup); +int b53_enable_mcast_snooping(struct b53_device *dev) +{ + u16 val16; + u32 val; + int ret; + + /* Older switches use different IGMP controls, not HL_PRTC_CTRL. */ + if (is5325(dev) || is5365(dev) || dev->chip_id == BCM5389_DEVICE_ID || + is5397_98(dev) || is63xx(dev)) + return 0; + + /* IGMPv2 and MLDv1 reports use the group's destination MAC. Once + * the first listener is offloaded, ordinary multicast forwarding + * can keep subsequent reports from reaching the bridge CPU. + */ + + /* BCM5395 has a narrower register and a single IGMP classifier. + * Its ICMPv6 classifier also covers MLD. + */ + if (dev->chip_id == BCM5395_DEVICE_ID) { + ret = b53_read16(dev, B53_MGMT_PAGE, B53_HL_PRTC_CTRL, &val16); + if (ret) + return ret; + + val16 |= HL_PRTC_IGMP_IP_EN_5395 | HL_PRTC_ICMPV6_EN; + /* Zero forwarding modes copy control traffic to the CPU + * independently of the ARL lookup, retaining L2 forwarding. + */ + val16 &= ~(HL_PRTC_IGMP_FWD_MODE_5395 | + HL_PRTC_ICMPV6_FWD_MODE); + + return b53_write16(dev, B53_MGMT_PAGE, B53_HL_PRTC_CTRL, + val16); + } + + ret = b53_read32(dev, B53_MGMT_PAGE, B53_HL_PRTC_CTRL, &val); + if (ret) + return ret; + + val |= HL_PRTC_IGMP_RPTLVE_EN | HL_PRTC_IGMP_QRY_EN | + HL_PRTC_IGMP_UKN_EN | HL_PRTC_MLD_RPTDONE_EN | + HL_PRTC_MLD_QRY_EN; + /* Zero forwarding modes copy control traffic to the CPU + * independently of the ARL lookup, retaining L2 forwarding. + */ + val &= ~(HL_PRTC_IGMP_RPTLVE_FWD_MODE | HL_PRTC_IGMP_QRY_FWD_MODE | + HL_PRTC_IGMP_UKN_FWD_MODE | HL_PRTC_MLD_RPTDONE_FWD_MODE | + HL_PRTC_MLD_QRY_FWD_MODE); + + return b53_write32(dev, B53_MGMT_PAGE, B53_HL_PRTC_CTRL, val); +} +EXPORT_SYMBOL(b53_enable_mcast_snooping); + static void b53_enable_cpu_port(struct b53_device *dev, int port) { u8 port_ctrl; @@ -1334,6 +1387,10 @@ static int b53_setup(struct dsa_switch *ds) b53_disable_port(ds, port); } + ret = b53_enable_mcast_snooping(dev); + if (ret) + return ret; + return b53_setup_devlink_resources(ds); } @@ -1663,9 +1720,15 @@ static void b53_phylink_mac_link_up(struct phylink_config *config, } if (mode == MLO_AN_FIXED) { - /* Force flow control on BCM5301x's CPU port */ - if (is5301x(dev) && dsa_is_cpu_port(ds, port)) - tx_pause = rx_pause = true; + /* Force flow control and 2Gbits/sec on BCM5301x and NSP CPU + * ports + */ + if ((is5301x(dev) || dev->chip_id == BCM58XX_DEVICE_ID) && + dsa_is_cpu_port(ds, port)) { + tx_pause = true; + rx_pause = true; + speed = 2000; + } b53_force_port_config(dev, port, speed, duplex, tx_pause, rx_pause); diff --git a/drivers/net/dsa/b53/b53_priv.h b/drivers/net/dsa/b53/b53_priv.h index 29cca7945df7..c4d2a41c714f 100644 --- a/drivers/net/dsa/b53/b53_priv.h +++ b/drivers/net/dsa/b53/b53_priv.h @@ -504,6 +504,7 @@ static inline struct gpio_desc *b53_switch_get_reset_gpio(struct b53_device *dev /* Exported functions towards other drivers */ void b53_imp_vlan_setup(struct dsa_switch *ds, int cpu_port); int b53_configure_vlan(struct dsa_switch *ds); +int b53_enable_mcast_snooping(struct b53_device *dev); void b53_get_strings(struct dsa_switch *ds, int port, u32 stringset, uint8_t *data); void b53_get_ethtool_stats(struct dsa_switch *ds, int port, uint64_t *data); diff --git a/drivers/net/dsa/b53/b53_regs.h b/drivers/net/dsa/b53/b53_regs.h index 54a278db67c9..cfdb5ed38326 100644 --- a/drivers/net/dsa/b53/b53_regs.h +++ b/drivers/net/dsa/b53/b53_regs.h @@ -274,6 +274,23 @@ /* Revision ID register (8 bit) */ #define B53_REV_ID 0x40 +/* High-level protocol control (16 bit on BCM5395, otherwise 32 bit) */ +#define B53_HL_PRTC_CTRL 0x50 +#define HL_PRTC_ICMPV6_EN BIT(4) +#define HL_PRTC_ICMPV6_FWD_MODE BIT(5) +#define HL_PRTC_IGMP_IP_EN_5395 BIT(6) +#define HL_PRTC_IGMP_FWD_MODE_5395 BIT(8) +#define HL_PRTC_IGMP_RPTLVE_EN BIT(9) +#define HL_PRTC_IGMP_RPTLVE_FWD_MODE BIT(10) +#define HL_PRTC_IGMP_QRY_EN BIT(11) +#define HL_PRTC_IGMP_QRY_FWD_MODE BIT(12) +#define HL_PRTC_IGMP_UKN_EN BIT(13) +#define HL_PRTC_IGMP_UKN_FWD_MODE BIT(14) +#define HL_PRTC_MLD_RPTDONE_EN BIT(15) +#define HL_PRTC_MLD_RPTDONE_FWD_MODE BIT(16) +#define HL_PRTC_MLD_QRY_EN BIT(17) +#define HL_PRTC_MLD_QRY_FWD_MODE BIT(18) + /* Broadcom header RX control (16 bit) */ #define B53_BRCM_HDR_RX_DIS 0x60 diff --git a/drivers/net/dsa/bcm_sf2.c b/drivers/net/dsa/bcm_sf2.c index de3efa3ce9a7..f3b56ea87b07 100644 --- a/drivers/net/dsa/bcm_sf2.c +++ b/drivers/net/dsa/bcm_sf2.c @@ -1059,6 +1059,7 @@ static int bcm_sf2_sw_setup(struct dsa_switch *ds) { struct bcm_sf2_priv *priv = bcm_sf2_to_priv(ds); unsigned int port; + int ret; /* Enable all valid ports and disable those unused */ for (port = 0; port < priv->hw_params.num_ports; port++) { @@ -1074,6 +1075,10 @@ static int bcm_sf2_sw_setup(struct dsa_switch *ds) b53_configure_vlan(ds); bcm_sf2_enable_acb(ds); + ret = b53_enable_mcast_snooping(priv->dev); + if (ret) + return ret; + return b53_setup_devlink_resources(ds); } diff --git a/drivers/net/dsa/microchip/ksz_common.c b/drivers/net/dsa/microchip/ksz_common.c index 1a9d6f83a023..9bae6b87a1f8 100644 --- a/drivers/net/dsa/microchip/ksz_common.c +++ b/drivers/net/dsa/microchip/ksz_common.c @@ -3928,6 +3928,7 @@ int ksz_switch_register(struct ksz_device *dev) mutex_init(&dev->regmap_mutex); mutex_init(&dev->alu_mutex); mutex_init(&dev->vlan_mutex); + mutex_init(&dev->lock_irq); ret = ksz_switch_detect(dev); if (ret) diff --git a/drivers/net/ethernet/amazon/ena/ena_netdev.c b/drivers/net/ethernet/amazon/ena/ena_netdev.c index 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/bgmac-platform.c b/drivers/net/ethernet/broadcom/bgmac-platform.c index 4e266ce41180..4880b1890481 100644 --- a/drivers/net/ethernet/broadcom/bgmac-platform.c +++ b/drivers/net/ethernet/broadcom/bgmac-platform.c @@ -243,7 +243,8 @@ static int bgmac_probe(struct platform_device *pdev) bgmac->phy_connect = platform_phy_connect; } else { bgmac->phy_connect = bgmac_phy_connect_direct; - bgmac->feature_flags |= BGMAC_FEAT_FORCE_SPEED_2500; + if (of_machine_is_compatible("brcm,nsp")) + bgmac->feature_flags |= BGMAC_FEAT_FORCE_SPEED_2500; } return bgmac_enet_probe(bgmac); diff --git a/drivers/net/ethernet/broadcom/bgmac.c b/drivers/net/ethernet/broadcom/bgmac.c index b3f0ecc583fd..409155fe8df0 100644 --- a/drivers/net/ethernet/broadcom/bgmac.c +++ b/drivers/net/ethernet/broadcom/bgmac.c @@ -1428,11 +1428,15 @@ void bgmac_adjust_link(struct net_device *net_dev) { struct bgmac *bgmac = netdev_priv(net_dev); struct phy_device *phy_dev = net_dev->phydev; + int speed = phy_dev->speed; bool update = false; + if (bgmac->feature_flags & BGMAC_FEAT_FORCE_SPEED_2500) + speed = SPEED_2500; + if (phy_dev->link) { - if (phy_dev->speed != bgmac->mac_speed) { - bgmac->mac_speed = phy_dev->speed; + if (speed != bgmac->mac_speed) { + bgmac->mac_speed = speed; update = true; } diff --git a/drivers/net/ethernet/broadcom/bnxt/bnxt.c b/drivers/net/ethernet/broadcom/bnxt/bnxt.c index 1fd6a676085b..ab932f7d0d76 100644 --- a/drivers/net/ethernet/broadcom/bnxt/bnxt.c +++ b/drivers/net/ethernet/broadcom/bnxt/bnxt.c @@ -11544,6 +11544,7 @@ static int bnxt_change_msix(struct bnxt *bp, int total) map.index = i - 1; map.virq = bp->irq_tbl[i - 1].vector; pci_msix_free_irq(bp->pdev, map); + bp->irq_tbl[i - 1].vector = 0; bp->total_irqs--; } return bp->total_irqs; @@ -11721,8 +11722,23 @@ int bnxt_reserve_rings(struct bnxt *bp, bool irq_re_init) int irqs_required; int rc; - if (!bnxt_need_reserve_rings(bp)) + if (!bnxt_need_reserve_rings(bp)) { + /* FW may already hold the reservation from an earlier + * reservation that was not followed by growing the dynamic + * MSI-X vectors, e.g. because the allocation failed. + */ + if (irq_re_init && BNXT_NEW_RM(bp) && bp->irq_tbl && + pci_msix_can_alloc_dyn(bp->pdev)) { + irqs_required = bnxt_get_num_msix(bp); + if (irqs_required > bp->total_irqs && + bnxt_change_msix(bp, irqs_required) != irqs_required) { + netdev_err(bp->dev, "Unable to allocate %d MSIX vectors, maximum available %d\n", + irqs_required, bp->total_irqs); + return -ENOSPC; + } + } return 0; + } if (BNXT_NEW_RM(bp) && !bnxt_ulp_registered(edev)) { int ulp_msix = bnxt_get_avail_msix(bp, bp->ulp_num_msix_want); @@ -11748,6 +11764,10 @@ int bnxt_reserve_rings(struct bnxt *bp, bool irq_re_init) rc = bnxt_init_int_mode(bp); bnxt_ulp_irq_restart(bp, rc); } else if (irq_change && !rc) { + /* Size the vectors from what FW actually reserved, which + * can be less than what was requested. + */ + irqs_required = bnxt_get_num_msix(bp); if (bnxt_change_msix(bp, irqs_required) != irqs_required) rc = -ENOSPC; } @@ -14806,7 +14826,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; @@ -14852,7 +14875,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) @@ -15101,6 +15127,7 @@ int bnxt_check_rings(struct bnxt *bp, int tx, int rx, bool sh, int tcs, hwr.cp = min_t(int, hwr.cp, bnxt_get_max_func_irqs(bp)); } if (hwr.cp > bp->total_irqs) { + int old_total = bp->total_irqs; int total_msix = bnxt_change_msix(bp, hwr.cp); if (total_msix < hwr.cp) { @@ -15108,6 +15135,17 @@ int bnxt_check_rings(struct bnxt *bp, int tx, int rx, bool sh, int tcs, hwr.cp, total_msix); rc = -ENOSPC; } + /* FW has not reserved the new vectors yet, and writes to + * MSI-X table entries beyond the reserved IRQs don't + * stick (seen on BCM57508). Free them again; + * bnxt_reserve_rings() allocates them after + * __bnxt_reserve_rings(). Without the new resource + * manager there is no IRQ reservation and + * bnxt_reserve_rings() does not grow the vectors, so + * keep them. + */ + if (BNXT_NEW_RM(bp)) + bnxt_change_msix(bp, old_total); } } return rc; @@ -15503,9 +15541,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) { @@ -15638,9 +15675,11 @@ static void bnxt_fw_reset_task(struct work_struct *work) netdev_err(bp->dev, "fw_health_status 0x%x\n", sts); } fw_reset_abort: + rtnl_lock(); netdev_lock(bp->dev); bnxt_fw_reset_abort(bp, rc); netdev_unlock(bp->dev); + rtnl_unlock(); ulp_start: if (!rc) bnxt_ulp_start(bp); diff --git a/drivers/net/ethernet/intel/i40e/i40e_xsk.c b/drivers/net/ethernet/intel/i40e/i40e_xsk.c index 9f47388eaba5..e48fee2a4229 100644 --- a/drivers/net/ethernet/intel/i40e/i40e_xsk.c +++ b/drivers/net/ethernet/intel/i40e/i40e_xsk.c @@ -318,22 +318,19 @@ static struct sk_buff *i40e_construct_skb_zc(struct i40e_ring *rx_ring, goto out; for (int i = 0; i < nr_frags; i++) { - struct skb_shared_info *skinfo = skb_shinfo(skb); skb_frag_t *frag = &sinfo->frags[i]; + unsigned int frag_size = skb_frag_size(frag); struct page *page; - void *addr; page = dev_alloc_page(); if (!page) { dev_kfree_skb(skb); - return NULL; + skb = NULL; + goto out; } - addr = page_to_virt(page); - memcpy(addr, skb_frag_page(frag), skb_frag_size(frag)); - - __skb_fill_page_desc_noacc(skinfo, skinfo->nr_frags++, - addr, 0, skb_frag_size(frag)); + memcpy(page_to_virt(page), skb_frag_address(frag), frag_size); + skb_add_rx_frag(skb, i, page, 0, frag_size, PAGE_SIZE); } out: @@ -459,16 +456,24 @@ int i40e_clean_rx_irq_zc(struct i40e_ring *rx_ring, int budget) xsk_buff_set_size(bi, size); xsk_buff_dma_sync_for_cpu(bi); - if (!first) + if (++next_to_process == count) + next_to_process = 0; + + if (!first) { first = bi; - else if (!xsk_buff_add_frag(first, bi)) { + } else if (!xsk_buff_add_frag(first, bi)) { + /* Drop what has been gathered so far. xp_free() skips + * @bi if it duplicates a buffer that is already on a + * pool list. Remaining buffers of this packet, if any, + * will be processed as a new packet. + */ xsk_buff_free(first); - break; + xsk_buff_free(bi); + next_to_clean = next_to_process; + first = NULL; + continue; } - if (++next_to_process == count) - next_to_process = 0; - if (i40e_is_non_eop(rx_ring, rx_desc)) continue; diff --git a/drivers/net/ethernet/intel/ice/ice_adapter.c b/drivers/net/ethernet/intel/ice/ice_adapter.c index 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 85a74cd6ea1f..bd162a0e7c30 100644 --- a/drivers/net/ethernet/intel/ice/ice_dpll.c +++ b/drivers/net/ethernet/intel/ice/ice_dpll.c @@ -2024,7 +2024,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 @@ -2032,14 +2032,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 103ba3e49068..d882846f995d 100644 --- a/drivers/net/ethernet/intel/ice/ice_dpll.h +++ b/drivers/net/ethernet/intel/ice/ice_dpll.h @@ -156,6 +156,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 @@ -167,6 +168,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 2f8563eb6fb1..07c315f3f5a1 100644 --- a/drivers/net/ethernet/intel/ice/ice_ptp.c +++ b/drivers/net/ethernet/intel/ice/ice_ptp.c @@ -1347,6 +1347,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; @@ -1365,14 +1366,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 fd4b58eb9bc0..b4773e9b64dd 100644 --- a/drivers/net/ethernet/intel/ice/ice_tspll.c +++ b/drivers/net/ethernet/intel/ice/ice_tspll.c @@ -634,6 +634,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 @@ -662,8 +663,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; @@ -680,7 +680,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 @@ -786,7 +786,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 094227404ef9..f91478f65661 100644 --- a/drivers/net/ethernet/marvell/octeontx2/af/rvu.h +++ b/drivers/net/ethernet/marvell/octeontx2/af/rvu.h @@ -75,8 +75,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; @@ -111,7 +109,6 @@ struct rvu_debugfs { int npa_qsize_id; int nix_qsize_id; }; -#endif struct rvu_work { struct work_struct work; @@ -648,9 +645,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/mediatek/mtk_ppe.c b/drivers/net/ethernet/mediatek/mtk_ppe.c index 8451dc3fd00a..d8fa1f2b4324 100644 --- a/drivers/net/ethernet/mediatek/mtk_ppe.c +++ b/drivers/net/ethernet/mediatek/mtk_ppe.c @@ -754,8 +754,7 @@ void __mtk_ppe_check_skb(struct mtk_ppe *ppe, struct sk_buff *skb, u16 hash) hlist_for_each_entry_safe(entry, n, head, list) { if (entry->type == MTK_FLOW_TYPE_L2_SUBFLOW) { - if (unlikely(FIELD_GET(MTK_FOE_IB1_STATE, hwe->ib1) == - MTK_FOE_STATE_BIND)) + if (entry->hash != hash) continue; entry->hash = 0xffff; @@ -764,7 +763,7 @@ void __mtk_ppe_check_skb(struct mtk_ppe *ppe, struct sk_buff *skb, u16 hash) } if (found || !mtk_flow_entry_match(ppe->eth, entry, hwe)) { - if (entry->hash != 0xffff) + if (entry->hash == hash) entry->hash = 0xffff; continue; } diff --git a/drivers/net/ethernet/mediatek/mtk_wed.c b/drivers/net/ethernet/mediatek/mtk_wed.c index 53d3b7e00e1c..f40ac5794341 100644 --- a/drivers/net/ethernet/mediatek/mtk_wed.c +++ b/drivers/net/ethernet/mediatek/mtk_wed.c @@ -257,7 +257,7 @@ mtk_wdma_rx_reset(struct mtk_wed_device *dev) wdma_w32(dev, MTK_WDMA_RESET_IDX, 0); for (i = 0; i < ARRAY_SIZE(dev->rx_wdma); i++) { - if (dev->rx_wdma[i].desc) + if (!dev->rx_wdma[i].desc) continue; wdma_w32(dev, @@ -949,6 +949,14 @@ mtk_wed_free_ring(struct mtk_wed_device *dev, struct mtk_wed_ring *ring) static void mtk_wed_free_rx_rings(struct mtk_wed_device *dev) { + int i; + + for (i = 0; i < ARRAY_SIZE(dev->rx_ring); i++) + mtk_wed_free_ring(dev, &dev->rx_ring[i]); + + for (i = 0; i < ARRAY_SIZE(dev->tx_wdma); i++) + mtk_wed_free_ring(dev, &dev->tx_wdma[i]); + mtk_wed_free_rx_buffer(dev); mtk_wed_free_ring(dev, &dev->rro.ring); } @@ -1938,7 +1946,7 @@ mtk_wed_wdma_tx_ring_setup(struct mtk_wed_device *dev, int idx, int size, wdma_w32(dev, MTK_WDMA_RING_TX(idx) + MTK_WED_RING_OFS_CPU_IDX, 0); wdma_w32(dev, MTK_WDMA_RING_TX(idx) + MTK_WED_RING_OFS_DMA_IDX, 0); - if (reset) + if (!mtk_wed_is_v3_or_greater(dev->hw) && reset) mtk_wed_ring_reset(wdma, MTK_WED_WDMA_RING_SIZE, true); if (!idx) { @@ -2337,7 +2345,20 @@ mtk_wed_start(struct mtk_wed_device *dev, u32 irq_mask) for (i = 0; i < ARRAY_SIZE(dev->rx_wdma); i++) if (!dev->rx_wdma[i].desc) - mtk_wed_wdma_rx_ring_setup(dev, i, 16, false); + if (mtk_wed_wdma_rx_ring_setup(dev, i, 16, false)) { + dev_err(dev->hw->dev, "wdma rx ring %d setup failed\n", i); + return; + } + + /* + * non-DBDC MT7986 allocates only rx_ring[1] and tx_wdma[1] during setup + * but tx_wdma[0] is also needed for WED to function. + */ + if (mtk_wed_is_v2(dev->hw) && !dev->rx_ring[0].desc) + if (mtk_wed_wdma_tx_ring_setup(dev, 0, MTK_WED_WDMA_RING_SIZE, !!dev->tx_wdma[0].desc)) { + dev_err(dev->hw->dev, "wdma tx ring 0 setup failed\n"); + return; + } if (dev->wlan.hw_rro) { for (i = 0; i < MTK_WED_RX_PAGE_QUEUES; i++) { diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en/fs.h b/drivers/net/ethernet/mellanox/mlx5/core/en/fs.h index 4973fb473ff0..aa370227b7bc 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en/fs.h +++ b/drivers/net/ethernet/mellanox/mlx5/core/en/fs.h @@ -158,7 +158,7 @@ void mlx5e_destroy_flow_steering(struct mlx5e_flow_steering *fs, bool ntuple, struct mlx5e_flow_steering *mlx5e_fs_init(const struct mlx5e_profile *profile, struct mlx5_core_dev *mdev, - bool state_destroy, + bool rx_mode_active, struct dentry *dfs_root); void mlx5e_fs_cleanup(struct mlx5e_flow_steering *fs); struct mlx5e_vlan_table *mlx5e_fs_get_vlan(struct mlx5e_flow_steering *fs); @@ -198,7 +198,8 @@ void mlx5e_fs_set_udp(struct mlx5e_flow_steering *fs, struct mlx5e_fs_udp *udp); struct mlx5e_accel_fs_tcp *mlx5e_fs_get_accel_tcp(struct mlx5e_flow_steering *fs); void mlx5e_fs_set_accel_tcp(struct mlx5e_flow_steering *fs, struct mlx5e_accel_fs_tcp *accel_tcp); #endif -void mlx5e_fs_set_state_destroy(struct mlx5e_flow_steering *fs, bool state_destroy); +void mlx5e_fs_set_rx_mode_active(struct mlx5e_flow_steering *fs, + bool rx_mode_active); void mlx5e_fs_set_vlan_strip_disable(struct mlx5e_flow_steering *fs, bool vlan_strip_disable); struct mlx5_core_dev *mlx5e_fs_get_mdev(struct mlx5e_flow_steering *fs); 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 e6dd911475e3..c1ff8f7a056e 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 @@ static int mlx5e_xfrm_add_state(struct net_device *dev, kfree(sa_entry->work); unblock_encap: if (allow_tunnel_mode) - mlx5_eswitch_unblock_encap(priv->mdev); -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 @@ static int rx_create(struct mlx5_core_dev *mdev, struct mlx5e_ipsec *ipsec, err_fs_ft_sa_sel: mlx5_destroy_flow_table(rx->ft.status); err_fs_ft_status: - mlx5_ipsec_fs_roce_rx_destroy(ipsec->roce, family, mdev); + ipsec_rx_status_pass_dest_put(ipsec, rx, family); return err; } @@ -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 @@ static int tx_create(struct mlx5e_ipsec *ipsec, struct mlx5e_ipsec_tx *tx, 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_fs.c b/drivers/net/ethernet/mellanox/mlx5/core/en_fs.c index 12492c4a5d41..c19238bc821f 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_fs.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_fs.c @@ -44,7 +44,7 @@ struct mlx5e_flow_steering { struct work_struct set_rx_mode_work; - bool state_destroy; + bool rx_mode_active; bool vlan_strip_disable; struct mlx5_core_dev *mdev; struct mlx5_flow_namespace *ns; @@ -560,7 +560,7 @@ static void mlx5e_del_vlan_rules(struct mlx5e_flow_steering *fs) for_each_set_bit(i, fs->vlan->active_svlans, VLAN_N_VID) mlx5e_fs_del_vlan_rule(fs, MLX5E_VLAN_RULE_TYPE_MATCH_STAG_VID, i); - WARN_ON_ONCE(fs->state_destroy); + WARN_ON_ONCE(fs->rx_mode_active); mlx5e_remove_vlan_trap(fs); @@ -743,7 +743,7 @@ static void mlx5e_handle_netdev_addr(struct mlx5e_flow_steering *fs, mlx5e_for_each_hash_node(hn, tmp, fs->l2.netdev_mc, i) hn->action = MLX5E_ACTION_DEL; - if (fs->state_destroy) + if (fs->rx_mode_active) mlx5e_sync_netdev_addr(fs, netdev, uc, mc); mlx5e_apply_netdev_addr(fs); @@ -840,7 +840,7 @@ void mlx5e_fs_set_rx_mode_work(struct mlx5e_flow_steering *fs, goto update_vport_context; } - bool rx_mode_enable = fs->state_destroy; + bool rx_mode_enable = fs->rx_mode_active; bool promisc_enabled = rx_mode_enable && (netdev->flags & IFF_PROMISC); bool allmulti_enabled = rx_mode_enable && (netdev->flags & IFF_ALLMULTI); bool broadcast_enabled = rx_mode_enable; @@ -1479,7 +1479,7 @@ static void mlx5e_fs_debugfs_init(struct mlx5e_flow_steering *fs, struct mlx5e_flow_steering *mlx5e_fs_init(const struct mlx5e_profile *profile, struct mlx5_core_dev *mdev, - bool state_destroy, + bool rx_mode_active, struct dentry *dfs_root) { struct mlx5e_flow_steering *fs; @@ -1490,7 +1490,7 @@ struct mlx5e_flow_steering *mlx5e_fs_init(const struct mlx5e_profile *profile, goto err; fs->mdev = mdev; - fs->state_destroy = state_destroy; + fs->rx_mode_active = rx_mode_active; if (mlx5e_profile_feature_cap(profile, FS_VLAN)) { err = mlx5e_fs_vlan_alloc(fs); if (err) @@ -1606,9 +1606,10 @@ void mlx5e_fs_set_accel_tcp(struct mlx5e_flow_steering *fs, struct mlx5e_accel_f } #endif -void mlx5e_fs_set_state_destroy(struct mlx5e_flow_steering *fs, bool state_destroy) +void mlx5e_fs_set_rx_mode_active(struct mlx5e_flow_steering *fs, + bool rx_mode_active) { - fs->state_destroy = state_destroy; + fs->rx_mode_active = rx_mode_active; } void mlx5e_fs_set_vlan_strip_disable(struct mlx5e_flow_steering *fs, diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_main.c b/drivers/net/ethernet/mellanox/mlx5/core/en_main.c index 38ce7d0a9001..25cc80e2a457 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_main.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_main.c @@ -5490,7 +5490,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]; @@ -5522,6 +5522,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; @@ -6039,9 +6042,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); @@ -6383,7 +6384,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; @@ -6468,6 +6469,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); @@ -6556,9 +6559,6 @@ int mlx5e_attach_netdev(struct mlx5e_priv *priv) int err; clear_bit(MLX5E_STATE_DESTROYING, &priv->state); - if (priv->fs) - mlx5e_fs_set_state_destroy(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 +6619,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 +6633,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,9 +6644,6 @@ int mlx5e_attach_netdev(struct mlx5e_priv *priv) out: mlx5e_reset_channels(priv->netdev); set_bit(MLX5E_STATE_DESTROYING, &priv->state); - if (priv->fs) - mlx5e_fs_set_state_destroy(priv->fs, - !test_bit(MLX5E_STATE_DESTROYING, &priv->state)); cancel_work_sync(&priv->update_stats_work); return err; } @@ -6650,8 +6654,7 @@ void mlx5e_detach_netdev(struct mlx5e_priv *priv) set_bit(MLX5E_STATE_DESTROYING, &priv->state); if (priv->fs) - mlx5e_fs_set_state_destroy(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 88a170e40bd9..a50a42581528 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 b290beb4369a..38dbda82c749 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; } @@ -4833,16 +4834,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) @@ -4850,7 +4854,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 fc197d1dc9df..07bea6b0e3d6 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/eswitch.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/eswitch.c @@ -1509,13 +1509,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. @@ -1524,7 +1520,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; } @@ -1535,18 +1535,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; } @@ -3039,12 +3039,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 8b1f93b13ea9..176940a20b75 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 eb74b6260168..023d87f17e90 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); } @@ -4343,7 +4342,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; @@ -4351,8 +4350,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; @@ -4419,7 +4421,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); @@ -4431,34 +4433,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, @@ -4485,10 +4483,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; @@ -4551,7 +4550,8 @@ int mlx5_devlink_eswitch_mode_set(struct devlink *devlink, u16 mode, 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) @@ -4632,7 +4632,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: @@ -4670,7 +4670,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: @@ -4689,25 +4689,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) @@ -4734,7 +4740,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) || @@ -4790,7 +4796,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 +#include #include "ipoib.h" #define MLX5I_MAX_LOG_PKEY_SUP 7 @@ -39,11 +40,12 @@ struct qpn_to_netdev { struct net_device *netdev; struct hlist_node hlist; u32 underlay_qpn; + struct rcu_head rcu; }; struct mlx5i_pkey_qpn_ht { struct hlist_head buckets[1 << MLX5I_MAX_LOG_PKEY_SUP]; - spinlock_t ht_lock; /* Synchronise with NAPI */ + spinlock_t ht_lock; /* Serialize hash table updates */ }; int mlx5i_pkey_qpn_ht_init(struct net_device *netdev) @@ -68,13 +70,14 @@ void mlx5i_pkey_qpn_ht_cleanup(struct net_device *netdev) kfree(ipriv->qpn_htbl); } -static struct qpn_to_netdev *mlx5i_find_qpn_to_netdev_node(struct hlist_head *buckets, - u32 qpn) +static struct qpn_to_netdev * +mlx5i_find_qpn_to_netdev_node(struct mlx5i_pkey_qpn_ht *ht, u32 qpn) { - struct hlist_head *h = &buckets[hash_32(qpn, MLX5I_MAX_LOG_PKEY_SUP)]; + struct hlist_head *h = &ht->buckets[hash_32(qpn, MLX5I_MAX_LOG_PKEY_SUP)]; struct qpn_to_netdev *node; - hlist_for_each_entry(node, h, hlist) { + hlist_for_each_entry_rcu(node, h, hlist, + lockdep_is_held(&ht->ht_lock)) { if (node->underlay_qpn == qpn) return node; } @@ -96,7 +99,7 @@ int mlx5i_pkey_add_qpn(struct net_device *netdev, u32 qpn) new_node->netdev = netdev; new_node->underlay_qpn = qpn; spin_lock_bh(&ht->ht_lock); - hlist_add_head(&new_node->hlist, &ht->buckets[key]); + hlist_add_head_rcu(&new_node->hlist, &ht->buckets[key]); spin_unlock_bh(&ht->ht_lock); return 0; @@ -109,16 +112,17 @@ int mlx5i_pkey_del_qpn(struct net_device *netdev, u32 qpn) struct mlx5i_pkey_qpn_ht *ht = ipriv->qpn_htbl; struct qpn_to_netdev *node; - node = mlx5i_find_qpn_to_netdev_node(ht->buckets, qpn); + spin_lock_bh(&ht->ht_lock); + node = mlx5i_find_qpn_to_netdev_node(ht, qpn); if (!node) { + spin_unlock_bh(&ht->ht_lock); mlx5_core_warn(epriv->mdev, "QPN to netdev delete from HT failed\n"); return -EINVAL; } - spin_lock_bh(&ht->ht_lock); - hlist_del_init(&node->hlist); + hlist_del_rcu(&node->hlist); spin_unlock_bh(&ht->ht_lock); - kfree(node); + kfree_rcu(node, rcu); return 0; } @@ -128,7 +132,7 @@ struct net_device *mlx5i_pkey_get_netdev(struct net_device *netdev, u32 qpn) struct mlx5i_priv *ipriv = netdev_priv(netdev); struct qpn_to_netdev *node; - node = mlx5i_find_qpn_to_netdev_node(ipriv->qpn_htbl->buckets, qpn); + node = mlx5i_find_qpn_to_netdev_node(ipriv->qpn_htbl, qpn); if (!node) return NULL; diff --git a/drivers/net/ethernet/mellanox/mlx5/core/lag/lag.c b/drivers/net/ethernet/mellanox/mlx5/core/lag/lag.c index 4e173b08cb37..a8ba1c208606 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/lag/lag.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/lag/lag.c @@ -1096,7 +1096,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)) { @@ -1106,7 +1105,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 efc5167493c1..4892175ca577 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/lib/macsec_fs.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/lib/macsec_fs.c @@ -94,6 +94,7 @@ struct mlx5_fs_id { refcount_t refcnt; sci_t sci; struct rhash_head hash; + struct rcu_head rcu; }; struct mlx5_macsec_device { @@ -684,7 +685,7 @@ static void macsec_fs_id_del(struct list_head *macsec_devices_list, u32 fs_id, xa_erase(fs_id_xa, fs_id); - kfree(fs_id_found); + kfree_rcu(fs_id_found, rcu); if (macsec_fs_is_macsec_device_empty(macsec_device)) { list_del(&macsec_device->macsec_devices_list_entry); @@ -763,13 +764,9 @@ static int macsec_fs_id_add(struct list_head *macsec_devices_list, u32 fs_id, return err; } -static void macsec_fs_tx_del_rule(struct mlx5_macsec_fs *macsec_fs, - struct mlx5_macsec_tx_rule *tx_rule, - void *macdev) +static void macsec_fs_tx_free_rule(struct mlx5_macsec_fs *macsec_fs, + struct mlx5_macsec_tx_rule *tx_rule) { - macsec_fs_id_del(&macsec_fs->macsec_devices_list, tx_rule->fs_id, macdev, - &macsec_fs->sci_hash, true); - if (tx_rule->rule) { mlx5_del_flow_rules(tx_rule->rule); tx_rule->rule = NULL; @@ -790,6 +787,15 @@ static void macsec_fs_tx_del_rule(struct mlx5_macsec_fs *macsec_fs, macsec_fs_tx_ft_put(macsec_fs); } +static void macsec_fs_tx_del_rule(struct mlx5_macsec_fs *macsec_fs, + struct mlx5_macsec_tx_rule *tx_rule, + void *macdev) +{ + macsec_fs_id_del(&macsec_fs->macsec_devices_list, tx_rule->fs_id, macdev, + &macsec_fs->sci_hash, true); + macsec_fs_tx_free_rule(macsec_fs, tx_rule); +} + #define MLX5_REFORMAT_PARAM_ADD_MACSEC_OFFSET_4_BYTES 1 static union mlx5_macsec_rule * @@ -882,7 +888,7 @@ macsec_fs_tx_add_rule(struct mlx5_macsec_fs *macsec_fs, goto out_spec; err: - macsec_fs_tx_del_rule(macsec_fs, tx_rule, macsec_ctx->secy->netdev); + macsec_fs_tx_free_rule(macsec_fs, tx_rule); macsec_rule = NULL; out_spec: kvfree(spec); @@ -1647,15 +1653,11 @@ static void macsec_fs_rx_ft_put(struct mlx5_macsec_fs *macsec_fs) macsec_fs_rx_destroy(macsec_fs); } -static void macsec_fs_rx_del_rule(struct mlx5_macsec_fs *macsec_fs, - struct mlx5_macsec_rx_rule *rx_rule, - void *macdev, u32 fs_id) +static void macsec_fs_rx_free_rule(struct mlx5_macsec_fs *macsec_fs, + struct mlx5_macsec_rx_rule *rx_rule) { int i; - macsec_fs_id_del(&macsec_fs->macsec_devices_list, fs_id, macdev, - &macsec_fs->fs_id_hash, false); - for (i = 0; i < RX_NUM_OF_RULES_PER_SA; ++i) { if (rx_rule->rule[i]) { mlx5_del_flow_rules(rx_rule->rule[i]); @@ -1673,6 +1675,15 @@ static void macsec_fs_rx_del_rule(struct mlx5_macsec_fs *macsec_fs, macsec_fs_rx_ft_put(macsec_fs); } +static void macsec_fs_rx_del_rule(struct mlx5_macsec_fs *macsec_fs, + struct mlx5_macsec_rx_rule *rx_rule, + void *macdev, u32 fs_id) +{ + macsec_fs_id_del(&macsec_fs->macsec_devices_list, fs_id, macdev, + &macsec_fs->fs_id_hash, false); + macsec_fs_rx_free_rule(macsec_fs, rx_rule); +} + static void macsec_fs_rx_setup_fte(struct mlx5_flow_spec *spec, struct mlx5_flow_act *flow_act, struct mlx5_macsec_rule_attrs *attrs, @@ -1832,7 +1843,7 @@ macsec_fs_rx_add_rule(struct mlx5_macsec_fs *macsec_fs, return macsec_rule; err: - macsec_fs_rx_del_rule(macsec_fs, rx_rule, macsec_ctx->secy->netdev, fs_id); + macsec_fs_rx_free_rule(macsec_fs, rx_rule); macsec_rule = NULL; out_spec: kvfree(spec); diff --git a/drivers/net/ethernet/mellanox/mlx5/core/main.c b/drivers/net/ethernet/mellanox/mlx5/core/main.c index 5f28d906c35b..fe98e35d15d2 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/main.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/main.c @@ -1810,6 +1810,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 d6958ba5dcc2..4b29d7183c4a 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); @@ -936,7 +936,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 baba3471bf5a..85ad53829bef 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_csr.h +++ b/drivers/net/ethernet/meta/fbnic/fbnic_csr.h @@ -459,6 +459,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 */ @@ -973,6 +974,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 ce2a66aeb8d2..2369fcf9b350 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_fw.c +++ b/drivers/net/ethernet/meta/fbnic/fbnic_fw.c @@ -7,6 +7,7 @@ #include #include #include +#include #include #include "fbnic.h" @@ -176,10 +177,25 @@ static void fbnic_mbx_unmap_and_free_msg(struct fbnic_dev *fbd, int mbx_idx, static void fbnic_mbx_clean_desc_ring(struct fbnic_dev *fbd, int mbx_idx) { + u32 flush_done, val; int i; fbnic_mbx_reset_desc_ring(fbd, mbx_idx); + /* Arming the flush only starts it. Wait for the outbound path to + * retire the requests it still holds before the buffers they may + * target are unmapped and freed. A lost link reads back as all ones, + * which ends the poll on the first pass. + */ + flush_done = mbx_idx == FBNIC_IPC_MBX_RX_IDX ? + FBNIC_PUL_USER_IP_LINK_RST_STATUS_AW_FLUSH_DONE : + FBNIC_PUL_USER_IP_LINK_RST_STATUS_AR_FLUSH_DONE; + if (read_poll_timeout_atomic(fbnic_rd32, val, val & flush_done, 2, + 1000, false, fbd, + FBNIC_PUL_USER_IP_LINK_RST_STATUS)) + dev_warn(fbd->dev, "Outbound flush did not complete: %08x\n", + val); + for (i = FBNIC_IPC_MBX_DESC_LEN; i--;) fbnic_mbx_unmap_and_free_msg(fbd, mbx_idx, i); } diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_netdev.c b/drivers/net/ethernet/meta/fbnic/fbnic_netdev.c index 10bf99be3f24..9c205999b29a 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 c6698e3002a1..1335310a1cc1 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_pci.c +++ b/drivers/net/ethernet/meta/fbnic/fbnic_pci.c @@ -229,18 +229,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(); } @@ -455,6 +462,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); @@ -555,19 +568,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 69cd96a4508f..c869b88db81a 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +++ b/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c @@ -2309,15 +2309,19 @@ void fbnic_disable(struct fbnic_net *fbn) static void fbnic_tx_flush(struct fbnic_dev *fbd) { + u32 drop_ctrl = FBNIC_TMI_DROP_CTRL_EN | FBNIC_TMI_DROP_CTRL_CMPL_DIS; + netdev_warn(fbd->netdev, "triggering Tx flush\n"); - fbnic_rmw32(fbd, FBNIC_TMI_DROP_CTRL, FBNIC_TMI_DROP_CTRL_EN, - FBNIC_TMI_DROP_CTRL_EN); + /* Drop packets and retire their PTP completions */ + fbnic_rmw32(fbd, FBNIC_TMI_DROP_CTRL, drop_ctrl, drop_ctrl); } static void fbnic_tx_flush_off(struct fbnic_dev *fbd) { - fbnic_rmw32(fbd, FBNIC_TMI_DROP_CTRL, FBNIC_TMI_DROP_CTRL_EN, 0); + u32 drop_ctrl = FBNIC_TMI_DROP_CTRL_EN | FBNIC_TMI_DROP_CTRL_CMPL_DIS; + + fbnic_rmw32(fbd, FBNIC_TMI_DROP_CTRL, drop_ctrl, 0); } struct fbnic_idle_regs { diff --git a/drivers/net/ethernet/microchip/lan966x/lan966x_fdma.c b/drivers/net/ethernet/microchip/lan966x/lan966x_fdma.c index 5cc9b2321dad..7bd133847723 100644 --- a/drivers/net/ethernet/microchip/lan966x/lan966x_fdma.c +++ b/drivers/net/ethernet/microchip/lan966x/lan966x_fdma.c @@ -354,6 +354,12 @@ static void lan966x_fdma_tx_clear_buf(struct lan966x *lan966x, int weight) if (!fdma_db_is_done(db)) continue; + /* XDP and page pool APIs can't be used with a budget of 0. + * Leave these buffers for the next NAPI poll. + */ + if (!weight && !dcb_buf->use_skb) + continue; + dcb_buf->dev->stats.tx_packets++; dcb_buf->dev->stats.tx_bytes += dcb_buf->len; diff --git a/drivers/net/ethernet/microchip/sparx5/sparx5_ptp.c b/drivers/net/ethernet/microchip/sparx5/sparx5_ptp.c index 2826e48af103..9f61692b243b 100644 --- a/drivers/net/ethernet/microchip/sparx5/sparx5_ptp.c +++ b/drivers/net/ethernet/microchip/sparx5/sparx5_ptp.c @@ -204,9 +204,10 @@ static void sparx5_ptp_classify(struct sparx5_port *port, struct sk_buff *skb, *rew_op = IFH_REW_OP_TWO_STEP_PTP; } -static void sparx5_ptp_txtstamp_old_release(struct sparx5_port *port) +static unsigned int sparx5_ptp_txtstamp_old_release(struct sparx5_port *port) { struct sk_buff *skb, *skb_tmp; + unsigned int purged = 0; unsigned long flags; spin_lock_irqsave(&port->tx_skbs.lock, flags); @@ -217,8 +218,11 @@ static void sparx5_ptp_txtstamp_old_release(struct sparx5_port *port) __skb_unlink(skb, &port->tx_skbs); dev_kfree_skb_any(skb); + purged++; } spin_unlock_irqrestore(&port->tx_skbs.lock, flags); + + return purged; } int sparx5_ptp_txtstamp_request(struct sparx5_port *port, @@ -226,6 +230,7 @@ int sparx5_ptp_txtstamp_request(struct sparx5_port *port, { struct sparx5 *sparx5 = port->sparx5; u8 rew_op, pdu_type, pdu_w16_offset; + unsigned int purged; unsigned long flags; sparx5_ptp_classify(port, skb, &rew_op, &pdu_type, &pdu_w16_offset); @@ -236,9 +241,10 @@ int sparx5_ptp_txtstamp_request(struct sparx5_port *port, if (rew_op != IFH_REW_OP_TWO_STEP_PTP) return 0; - sparx5_ptp_txtstamp_old_release(port); + purged = sparx5_ptp_txtstamp_old_release(port); spin_lock_irqsave(&sparx5->ptp_ts_id_lock, flags); + sparx5->ptp_skbs -= purged; if (sparx5->ptp_skbs == SPARX5_MAX_PTP_ID) { spin_unlock_irqrestore(&sparx5->ptp_ts_id_lock, flags); return -EBUSY; diff --git a/drivers/net/ethernet/microsoft/mana/mana_bpf.c b/drivers/net/ethernet/microsoft/mana/mana_bpf.c index b27fd9b8c4f6..3b6f75611944 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 89af8bf6758b..63c55ef06a69 100644 --- a/drivers/net/ethernet/microsoft/mana/mana_en.c +++ b/drivers/net/ethernet/microsoft/mana/mana_en.c @@ -2126,7 +2126,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; @@ -2148,10 +2148,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) @@ -2919,6 +2918,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); @@ -3203,6 +3205,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/realtek/8139cp.c b/drivers/net/ethernet/realtek/8139cp.c index 9016527e229a..8f81dc7deef1 100644 --- a/drivers/net/ethernet/realtek/8139cp.c +++ b/drivers/net/ethernet/realtek/8139cp.c @@ -600,11 +600,11 @@ static irqreturn_t cp_interrupt (int irq, void *dev_instance) goto out_unlock; } - if (status & (RxOK | RxErr | RxEmpty | RxFIFOOvr)) - if (napi_schedule_prep(&cp->napi)) { - cpw16_f(IntrMask, cp_norx_intr_mask); + if (status & (RxOK | RxErr | RxEmpty | RxFIFOOvr)) { + cpw16_f(IntrMask, cp_norx_intr_mask); + if (napi_schedule_prep(&cp->napi)) __napi_schedule(&cp->napi); - } + } if (status & (TxOK | TxErr | TxEmpty | SWInt)) cp_tx(cp); diff --git a/drivers/net/ethernet/sfc/ptp.c b/drivers/net/ethernet/sfc/ptp.c index 6ca9a75af01d..3c6a85b979ce 100644 --- a/drivers/net/ethernet/sfc/ptp.c +++ b/drivers/net/ethernet/sfc/ptp.c @@ -36,6 +36,7 @@ #include #include #include +#include #include #include #include "net_driver.h" @@ -267,11 +268,12 @@ struct efx_ptp_rxfilter { * @evt_frag_idx: Current fragment number * @evt_code: Last event code * @start: Address at which MC indicates ready for synchronisation - * @host_time_pps: Host time at last PPS * @adjfreq_ppb_shift: Shift required to convert scaled parts-per-billion * frequency adjustment into a fixed point fractional nanosecond format. * @current_adjfreq: Current ppb adjustment. * @phc_clock: Pointer to registered phc device (if primary function) + * @phc_lock: Serializes PHC commands and synchronization, and protects + * @current_adjfreq * @phc_clock_info: Registration structure for phc device * @pps_work: pps work task for handling pps events * @pps_workwq: pps work queue @@ -327,10 +329,10 @@ struct efx_ptp_data { int evt_frag_idx; int evt_code; struct efx_buffer start; - struct pps_event_time host_time_pps; unsigned int adjfreq_ppb_shift; s64 current_adjfreq; struct ptp_clock *phc_clock; + struct mutex phc_lock; struct ptp_clock_info phc_clock_info; struct work_struct pps_work; struct workqueue_struct *pps_workwq; @@ -908,7 +910,8 @@ static void efx_ptp_read_timeset(MCDI_DECLARE_STRUCT_PTR(data), static int efx_ptp_process_times(struct efx_nic *efx, MCDI_DECLARE_STRUCT_PTR(synch_buf), size_t response_length, - const struct pps_event_time *last_time) + const struct pps_event_time *last_time, + struct pps_event_time *host_time_pps) { unsigned number_readings = MCDI_VAR_ARRAY_LEN(response_length, @@ -986,6 +989,10 @@ efx_ptp_process_times(struct efx_nic *efx, MCDI_DECLARE_STRUCT_PTR(synch_buf), "PTP bad synchronisation seconds\n"); return -EAGAIN; } + + if (!host_time_pps) + return 0; + delta.tv_sec = (last_sec - start_sec) & 1; delta.tv_nsec = last_time->ts_real.tv_nsec - @@ -1002,14 +1009,22 @@ efx_ptp_process_times(struct efx_nic *efx, MCDI_DECLARE_STRUCT_PTR(synch_buf), delta.tv_nsec += ktime_to_timespec64(mc_time).tv_nsec; /* Set PPS timestamp to match NIC top of second */ - ptp->host_time_pps = *last_time; - pps_sub_ts(&ptp->host_time_pps, delta); + *host_time_pps = *last_time; + pps_sub_ts(host_time_pps, delta); return 0; } -/* Synchronize times between the host and the MC */ -static int efx_ptp_synchronize(struct efx_nic *efx, unsigned int num_readings) +/* Synchronize times between the host and the MC. + * + * The MC serializes PTP requests, so MC_CMD_PTP_OP_ADJUST cannot be applied + * while MC_CMD_PTP_OP_SYNCHRONIZE is collecting timesets. This holds across + * functions of a controller, which share the clock but adjust it only through + * the function that registered it, so a secondary function can capture here + * without serializing against the primary. + */ +static int efx_ptp_synchronize(struct efx_nic *efx, unsigned int num_readings, + struct pps_event_time *host_time_pps) { struct efx_ptp_data *ptp = efx->ptp_data; MCDI_DECLARE_BUF(synch_buf, MC_CMD_PTP_OUT_SYNCHRONIZE_LENMAX); @@ -1027,11 +1042,14 @@ static int efx_ptp_synchronize(struct efx_nic *efx, unsigned int num_readings) MCDI_SET_QWORD(synch_buf, PTP_IN_SYNCHRONIZE_START_ADDR, ptp->start.dma_addr); + mutex_lock(&ptp->phc_lock); + /* Clear flag that signals MC ready */ WRITE_ONCE(*start, 0); rc = efx_mcdi_rpc_start(efx, MC_CMD_PTP, synch_buf, MC_CMD_PTP_IN_SYNCHRONIZE_LEN); - EFX_WARN_ON_ONCE_PARANOID(rc); + if (rc) + goto out; /* Wait for start from MCDI (or timeout) */ timeout = jiffies + msecs_to_jiffies(MAX_SYNCHRONISE_WAIT_MS); @@ -1055,18 +1073,20 @@ static int efx_ptp_synchronize(struct efx_nic *efx, unsigned int num_readings) &response_length); if (rc == 0) { rc = efx_ptp_process_times(efx, synch_buf, response_length, - &last_time); + &last_time, host_time_pps); if (rc == 0) ++ptp->good_syncs; else ++ptp->no_time_syncs; } +out: /* Increment the bad syncs counter if the synchronize fails, whatever * the reason. */ if (rc != 0) ++ptp->bad_syncs; + mutex_unlock(&ptp->phc_lock); return rc; } @@ -1446,7 +1466,6 @@ static int efx_ptp_start(struct efx_nic *efx) goto fail; ptp->evt_frag_idx = 0; - ptp->current_adjfreq = 0; return 0; @@ -1486,14 +1505,15 @@ static void efx_ptp_pps_worker(struct work_struct *work) { struct efx_ptp_data *ptp = container_of(work, struct efx_ptp_data, pps_work); + struct pps_event_time host_time_pps = {}; struct efx_nic *efx = ptp->efx; struct ptp_clock_event ptp_evt; - if (efx_ptp_synchronize(efx, PTP_SYNC_ATTEMPTS)) + if (efx_ptp_synchronize(efx, PTP_SYNC_ATTEMPTS, &host_time_pps)) return; ptp_evt.type = PTP_CLOCK_PPSUSR; - ptp_evt.pps_times = ptp->host_time_pps; + ptp_evt.pps_times = host_time_pps; ptp_clock_event(ptp->phc_clock, &ptp_evt); } @@ -1570,6 +1590,7 @@ int efx_ptp_probe(struct efx_nic *efx, struct efx_channel *channel) if (!efx->ptp_data) return -ENOMEM; + mutex_init(&ptp->phc_lock); ptp->efx = efx; ptp->channel = channel; @@ -1641,6 +1662,7 @@ int efx_ptp_probe(struct efx_nic *efx, struct efx_channel *channel) efx_nic_free_buffer(efx, &ptp->start); fail1: + mutex_destroy(&ptp->phc_lock); kfree(efx->ptp_data); efx->ptp_data = NULL; @@ -1695,6 +1717,7 @@ void efx_ptp_remove(struct efx_nic *efx) destroy_workqueue(efx->ptp_data->workwq); efx_nic_free_buffer(efx, &efx->ptp_data->start); + mutex_destroy(&efx->ptp_data->phc_lock); kfree(efx->ptp_data); efx->ptp_data = NULL; } @@ -1826,7 +1849,8 @@ int efx_ptp_change_mode(struct efx_nic *efx, bool enable_wanted, rc = efx_ptp_start(efx); if (rc == 0) { rc = efx_ptp_synchronize(efx, - PTP_SYNC_ATTEMPTS * 2); + PTP_SYNC_ATTEMPTS * 2, + NULL); if (rc != 0) efx_ptp_stop(efx); } @@ -2106,23 +2130,23 @@ static int efx_phc_adjfine(struct ptp_clock_info *ptp, long scaled_ppm) MCDI_SET_QWORD(inadj, PTP_IN_ADJUST_FREQ, adjustment_ns); MCDI_SET_DWORD(inadj, PTP_IN_ADJUST_SECONDS, 0); MCDI_SET_DWORD(inadj, PTP_IN_ADJUST_NANOSECONDS, 0); + mutex_lock(&ptp_data->phc_lock); rc = efx_mcdi_rpc(efx, MC_CMD_PTP, inadj, sizeof(inadj), NULL, 0, NULL); - if (rc != 0) - return rc; - - ptp_data->current_adjfreq = adjustment_ns; - return 0; + if (!rc) + ptp_data->current_adjfreq = adjustment_ns; + mutex_unlock(&ptp_data->phc_lock); + return rc; } -static int efx_phc_adjtime(struct ptp_clock_info *ptp, s64 delta) +static int _efx_phc_adjtime(struct efx_ptp_data *ptp_data, s64 delta) + __must_hold(&ptp_data->phc_lock) { - u32 nic_major, nic_minor; - struct efx_ptp_data *ptp_data = container_of(ptp, - struct efx_ptp_data, - phc_clock_info); - struct efx_nic *efx = ptp_data->efx; MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_ADJUST_LEN); + struct efx_nic *efx = ptp_data->efx; + u32 nic_major, nic_minor; + + lockdep_assert_held(&ptp_data->phc_lock); efx->ptp_data->ns_to_nic_time(delta, &nic_major, &nic_minor); @@ -2135,6 +2159,18 @@ static int efx_phc_adjtime(struct ptp_clock_info *ptp, s64 delta) NULL, 0, NULL); } +static int efx_phc_adjtime(struct ptp_clock_info *ptp, s64 delta) +{ + struct efx_ptp_data *ptp_data = container_of(ptp, struct efx_ptp_data, + phc_clock_info); + int rc; + + mutex_lock(&ptp_data->phc_lock); + rc = _efx_phc_adjtime(ptp_data, delta); + mutex_unlock(&ptp_data->phc_lock); + return rc; +} + static int efx_phc_gettime(struct ptp_clock_info *ptp, struct timespec64 *ts) { struct efx_ptp_data *ptp_data = container_of(ptp, @@ -2166,23 +2202,21 @@ static int efx_phc_settime(struct ptp_clock_info *ptp, { /* Get the current NIC time, efx_phc_gettime. * Subtract from the desired time to get the offset - * call efx_phc_adjtime with the offset + * call _efx_phc_adjtime with the offset */ + struct efx_ptp_data *ptp_data = container_of(ptp, struct efx_ptp_data, + phc_clock_info); + struct timespec64 time_now, delta; int rc; - struct timespec64 time_now; - struct timespec64 delta; + mutex_lock(&ptp_data->phc_lock); rc = efx_phc_gettime(ptp, &time_now); - if (rc != 0) - return rc; - - delta = timespec64_sub(*e_ts, time_now); - - rc = efx_phc_adjtime(ptp, timespec64_to_ns(&delta)); - if (rc != 0) - return rc; - - return 0; + if (!rc) { + delta = timespec64_sub(*e_ts, time_now); + rc = _efx_phc_adjtime(ptp_data, timespec64_to_ns(&delta)); + } + mutex_unlock(&ptp_data->phc_lock); + return rc; } static int efx_phc_enable(struct ptp_clock_info *ptp, diff --git a/drivers/net/ethernet/stmicro/stmmac/enh_desc.c b/drivers/net/ethernet/stmicro/stmmac/enh_desc.c index 023b54b72478..7ece8d4157a8 100644 --- a/drivers/net/ethernet/stmicro/stmmac/enh_desc.c +++ b/drivers/net/ethernet/stmicro/stmmac/enh_desc.c @@ -205,7 +205,7 @@ static int enh_desc_get_rx_status(struct stmmac_extra_stats *x, if (unlikely(!(rdes0 & RDES0_LAST_DESCRIPTOR))) { x->rx_length++; - return discard_frame; + return discard_frame | rx_not_ls; } if (unlikely(rdes0 & RDES0_ERROR_SUMMARY)) { diff --git a/drivers/net/ethernet/stmicro/stmmac/hwif.h b/drivers/net/ethernet/stmicro/stmmac/hwif.h index 9925b789bcc9..4c2d7b156ac0 100644 --- a/drivers/net/ethernet/stmicro/stmmac/hwif.h +++ b/drivers/net/ethernet/stmicro/stmmac/hwif.h @@ -496,6 +496,8 @@ struct stmmac_ops { #define stmmac_fpe_map_preemption_class(__priv, __args...) \ stmmac_do_callback(__priv, mac, fpe_map_preemption_class, __args) +struct ptp_system_timestamp; + /* PTP and HW Timer helpers */ struct stmmac_hwtimestamp { void (*config_hw_tstamping) (void __iomem *ioaddr, u32 data); @@ -505,7 +507,8 @@ struct stmmac_hwtimestamp { int (*config_addend) (void __iomem *ioaddr, u32 addend); int (*adjust_systime) (void __iomem *ioaddr, u32 sec, u32 nsec, int add_sub, int gmac4); - void (*get_systime) (void __iomem *ioaddr, u64 *systime); + void (*get_systime)(void __iomem *ioaddr, u64 *systime, + struct ptp_system_timestamp *sts); void (*get_ptptime)(void __iomem *ioaddr, u64 *ptp_time); void (*timestamp_interrupt)(struct stmmac_priv *priv); void (*hwtstamp_correct_latency)(struct stmmac_priv *priv); @@ -620,7 +623,7 @@ struct stmmac_mmc_ops { struct stmmac_est_ops { int (*configure)(struct stmmac_priv *priv, struct stmmac_est *cfg, - unsigned int ptp_rate); + unsigned int ptp_rate, bool enable); void (*irq_status)(struct stmmac_priv *priv, struct net_device *dev, struct stmmac_extra_stats *x, u32 txqcnt); }; diff --git a/drivers/net/ethernet/stmicro/stmmac/norm_desc.c b/drivers/net/ethernet/stmicro/stmmac/norm_desc.c index c4b613564f87..d19bf7ca4db3 100644 --- a/drivers/net/ethernet/stmicro/stmmac/norm_desc.c +++ b/drivers/net/ethernet/stmicro/stmmac/norm_desc.c @@ -70,7 +70,7 @@ static int ndesc_get_rx_status(struct stmmac_extra_stats *x, if (unlikely(!(rdes0 & RDES0_LAST_DESCRIPTOR))) { x->rx_length++; - return discard_frame; + return discard_frame | rx_not_ls; } if (unlikely(rdes0 & RDES0_ERROR_SUMMARY)) { diff --git a/drivers/net/ethernet/stmicro/stmmac/stmmac.h b/drivers/net/ethernet/stmicro/stmmac/stmmac.h index 9cdad8430856..6f34cae04f19 100644 --- a/drivers/net/ethernet/stmicro/stmmac/stmmac.h +++ b/drivers/net/ethernet/stmicro/stmmac/stmmac.h @@ -239,6 +239,7 @@ struct stmmac_est { u32 gcl[EST_GCL]; u32 gcl_size; u32 max_sdu[MTL_MAX_TX_QUEUES]; + u32 pclass; }; struct stmmac_msi { @@ -336,6 +337,8 @@ struct stmmac_priv { struct kernel_hwtstamp_config tstamp_config; struct ptp_clock *ptp_clock; struct ptp_clock_info ptp_clock_ops; + bool ptp_enabled; + unsigned int default_addend; u32 sub_second_inc; u32 systime_flags; @@ -426,6 +429,11 @@ int stmmac_set_clk_tx_rate(void *bsp_priv, struct clk *clk_tx_i, struct plat_stmmacenet_data *stmmac_plat_dat_alloc(struct device *dev); +static inline bool stmmac_check_timestamp_cap(struct stmmac_priv *priv) +{ + return priv->dma_cap.time_stamp || priv->dma_cap.atime_stamp; +} + static inline bool stmmac_xdp_is_enabled(struct stmmac_priv *priv) { return !!priv->xdp_prog; diff --git a/drivers/net/ethernet/stmicro/stmmac/stmmac_est.c b/drivers/net/ethernet/stmicro/stmmac/stmmac_est.c index afc516059b89..59e9a54e864d 100644 --- a/drivers/net/ethernet/stmicro/stmmac/stmmac_est.c +++ b/drivers/net/ethernet/stmicro/stmmac/stmmac_est.c @@ -26,7 +26,7 @@ static int est_write(void __iomem *est_addr, u32 reg, u32 val, bool gcl) } static int est_configure(struct stmmac_priv *priv, struct stmmac_est *cfg, - unsigned int ptp_rate) + unsigned int ptp_rate, bool enable) { void __iomem *est_addr = priv->estaddr; int i, ret = 0; @@ -62,7 +62,7 @@ static int est_configure(struct stmmac_priv *priv, struct stmmac_est *cfg, ctrl |= ((NSEC_PER_SEC / ptp_rate) * EST_GMAC5_PTOV_MUL) << EST_GMAC5_PTOV_SHIFT; } - if (cfg->enable) + if (enable) ctrl |= EST_EEST | EST_SSWL | EST_DFBS; else ctrl &= ~EST_EEST; @@ -70,7 +70,7 @@ static int est_configure(struct stmmac_priv *priv, struct stmmac_est *cfg, writel(ctrl, est_addr + EST_CONTROL); /* Configure EST interrupt */ - if (cfg->enable) + if (enable) ctrl = EST_IECGCE | EST_IEHS | EST_IEHF | EST_IEBE | EST_IECC; else ctrl = 0; @@ -80,6 +80,61 @@ static int est_configure(struct stmmac_priv *priv, struct stmmac_est *cfg, return 0; } +int __stmmac_setup_est(struct stmmac_priv *priv) +{ + struct timespec64 current_time, time; + ktime_t current_time_ns, basetime; + u64 cycle_time; + int err; + + lockdep_assert_held(&priv->est_lock); + + priv->ptp_clock_ops.gettimex64(&priv->ptp_clock_ops, ¤t_time, + NULL); + current_time_ns = timespec64_to_ktime(current_time); + + time.tv_nsec = priv->est->btr_reserve[0]; + time.tv_sec = priv->est->btr_reserve[1]; + basetime = timespec64_to_ktime(time); + + cycle_time = (u64)priv->est->ctr[1] * NSEC_PER_SEC + priv->est->ctr[0]; + + time = stmmac_calc_tas_basetime(basetime, current_time_ns, cycle_time); + priv->est->btr[0] = (u32)time.tv_nsec; + priv->est->btr[1] = (u32)time.tv_sec; + + err = stmmac_est_configure(priv, priv, priv->est, + priv->plat->clk_ptp_rate, true); + if (err) { + netdev_err(priv->dev, "failed to re-configure EST\n"); + return err; + } + + return 0; +} + +int stmmac_setup_est(struct stmmac_priv *priv) +{ + int ret = 0; + + if (!priv->ptp_enabled) + return 0; + + mutex_lock(&priv->est_lock); + if (priv->est && priv->est->enable) { + ret = __stmmac_setup_est(priv); + if (ret) + goto unlock; + + ret = stmmac_fpe_map_preemption_class(priv, priv->dev, NULL, + priv->est->pclass); + } +unlock: + mutex_unlock(&priv->est_lock); + + return ret; +} + static void est_irq_status(struct stmmac_priv *priv, struct net_device *dev, struct stmmac_extra_stats *x, u32 txqcnt) { diff --git a/drivers/net/ethernet/stmicro/stmmac/stmmac_est.h b/drivers/net/ethernet/stmicro/stmmac/stmmac_est.h index f70221c9c84a..5e07b84957f3 100644 --- a/drivers/net/ethernet/stmicro/stmmac/stmmac_est.h +++ b/drivers/net/ethernet/stmicro/stmmac/stmmac_est.h @@ -4,6 +4,9 @@ * stmmac EST(802.3 Qbv) handling */ +#ifndef __STMMAC_EST_H__ +#define __STMMAC_EST_H__ + #define EST_GMAC4_OFFSET 0x00000c50 #define EST_XGMAC_OFFSET 0x00001050 @@ -65,3 +68,8 @@ #define EST_GCL_DATA 0x00000034 extern const struct stmmac_est_ops dwmac510_est_ops; + +int __stmmac_setup_est(struct stmmac_priv *priv); +int stmmac_setup_est(struct stmmac_priv *priv); + +#endif /* __STMMAC_EST_H__ */ diff --git a/drivers/net/ethernet/stmicro/stmmac/stmmac_ethtool.c b/drivers/net/ethernet/stmicro/stmmac/stmmac_ethtool.c index e2c5b6950510..30e0d499326d 100644 --- a/drivers/net/ethernet/stmicro/stmmac/stmmac_ethtool.c +++ b/drivers/net/ethernet/stmicro/stmmac/stmmac_ethtool.c @@ -1008,8 +1008,7 @@ static int stmmac_get_ts_info(struct net_device *dev, { struct stmmac_priv *priv = netdev_priv(dev); - if ((priv->dma_cap.time_stamp || priv->dma_cap.atime_stamp)) { - + if (stmmac_check_timestamp_cap(priv)) { info->so_timestamping = SOF_TIMESTAMPING_TX_SOFTWARE | SOF_TIMESTAMPING_TX_HARDWARE | SOF_TIMESTAMPING_RX_HARDWARE | diff --git a/drivers/net/ethernet/stmicro/stmmac/stmmac_hwtstamp.c b/drivers/net/ethernet/stmicro/stmmac/stmmac_hwtstamp.c index b9a985fa772c..870c740b4a50 100644 --- a/drivers/net/ethernet/stmicro/stmmac/stmmac_hwtstamp.c +++ b/drivers/net/ethernet/stmicro/stmmac/stmmac_hwtstamp.c @@ -183,7 +183,8 @@ static int adjust_systime(void __iomem *ioaddr, u32 sec, u32 nsec, 10, 100000); } -static void get_systime(void __iomem *ioaddr, u64 *systime) +static void get_systime(void __iomem *ioaddr, u64 *systime, + struct ptp_system_timestamp *sts) { u64 ns, sec0, sec1; @@ -191,8 +192,10 @@ static void get_systime(void __iomem *ioaddr, u64 *systime) sec1 = readl_relaxed(ioaddr + PTP_STSR); do { sec0 = sec1; + ptp_read_system_prets(sts); /* Get the TSSS value */ - ns = readl_relaxed(ioaddr + PTP_STNSR); + ns = readl(ioaddr + PTP_STNSR); + ptp_read_system_postts(sts); /* Get the TSS value */ sec1 = readl_relaxed(ioaddr + PTP_STSR); } while (sec0 != sec1); diff --git a/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c b/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c index 8a8e9f71e6f9..fa4bd6a3a1bf 100644 --- a/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +++ b/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c @@ -48,6 +48,7 @@ #include "stmmac_ptp.h" #include "stmmac_fpe.h" #include "stmmac.h" +#include "stmmac_est.h" #include "stmmac_pcs.h" #include "stmmac_xdp.h" #include @@ -653,7 +654,8 @@ static int stmmac_hwtstamp_set(struct net_device *dev, u32 ts_master_en = 0; u32 ts_event_en = 0; - if (!(priv->dma_cap.time_stamp || priv->adv_ts)) { + if (!priv->plat->clk_ptp_rate || + !(priv->dma_cap.time_stamp || priv->adv_ts)) { NL_SET_ERR_MSG_MOD(extack, "No support for HW time stamping"); priv->hwts_tx_en = 0; priv->hwts_rx_en = 0; @@ -843,7 +845,7 @@ static int stmmac_hwtstamp_get(struct net_device *dev, { struct stmmac_priv *priv = netdev_priv(dev); - if (!(priv->dma_cap.time_stamp || priv->dma_cap.atime_stamp)) + if (!stmmac_check_timestamp_cap(priv)) return -EOPNOTSUPP; *config = priv->tstamp_config; @@ -866,11 +868,6 @@ static int stmmac_init_tstamp_counter(struct stmmac_priv *priv, { struct timespec64 now; - if (!priv->plat->clk_ptp_rate) { - netdev_err(priv->dev, "Invalid PTP clock rate"); - return -EINVAL; - } - stmmac_config_hw_tstamping(priv, priv->ptpaddr, systime_flags); priv->systime_flags = systime_flags; @@ -885,26 +882,37 @@ static int stmmac_init_tstamp_counter(struct stmmac_priv *priv, return 0; } +static int stmmac_init_ptp_clk_freq(struct stmmac_priv *priv) +{ + if (priv->plat->ptp_clk_freq_config) + priv->plat->ptp_clk_freq_config(priv); + + if (!priv->plat->clk_ptp_rate) { + netdev_info(priv->dev, "PTP clock rate not configured\n"); + return -EINVAL; + } + + return 0; +} + /** * stmmac_init_timestamping - initialise timestamping * @priv: driver private structure - * Description: this is to verify if the HW supports the PTPv1 or PTPv2. - * This is done by looking at the HW cap. register. - * This function also registers the ptp driver. + * + * Description: initialise the hardware timestamping counter, reset the + * timestamping configuration and derive the advanced timestamping flags from + * the HW capabilities. The caller must have ensured a valid PTP reference + * clock rate (see stmmac_init_ptp_clk_freq()); the configured state is valid + * as long as the interface is open and not suspended, and this function is + * re-run on resume. + * + * Return: 0 on success, a negative errno otherwise. */ static int stmmac_init_timestamping(struct stmmac_priv *priv) { bool xmac = dwmac_is_xmac(priv->plat->core_type); int ret; - if (priv->plat->ptp_clk_freq_config) - priv->plat->ptp_clk_freq_config(priv); - - if (!(priv->dma_cap.time_stamp || priv->dma_cap.atime_stamp)) { - netdev_info(priv->dev, "PTP not supported by HW\n"); - return -EOPNOTSUPP; - } - ret = stmmac_init_tstamp_counter(priv, STMMAC_HWTS_ACTIVE | PTP_TCR_TSCFUPDT); if (ret) { @@ -937,24 +945,48 @@ static int stmmac_init_timestamping(struct stmmac_priv *priv) return 0; } -static void stmmac_setup_ptp(struct stmmac_priv *priv) +static int stmmac_setup_ptp(struct stmmac_priv *priv) { int ret; + if (!stmmac_check_timestamp_cap(priv)) { + netdev_info(priv->dev, "PTP not supported\n"); + return 0; + } + ret = clk_prepare_enable(priv->plat->clk_ptp_ref); - if (ret < 0) + if (ret < 0) { netdev_warn(priv->dev, "failed to enable PTP reference clock: %pe\n", ERR_PTR(ret)); + return ret; + } + + if (stmmac_init_ptp_clk_freq(priv)) { + clk_disable_unprepare(priv->plat->clk_ptp_ref); + return 0; + } + + ret = stmmac_init_timestamping(priv); + if (ret) { + clk_disable_unprepare(priv->plat->clk_ptp_ref); + return ret; + } - if (stmmac_init_timestamping(priv) == 0) - stmmac_ptp_register(priv); + stmmac_ptp_register(priv); + priv->ptp_enabled = true; + + return 0; } static void stmmac_release_ptp(struct stmmac_priv *priv) { + if (!priv->ptp_enabled) + return; + stmmac_ptp_unregister(priv); clk_disable_unprepare(priv->plat->clk_ptp_ref); + priv->ptp_enabled = false; } static void stmmac_legacy_serdes_power_down(struct stmmac_priv *priv) @@ -2151,6 +2183,9 @@ static void __free_dma_rx_desc_resources(struct stmmac_priv *priv, else dma_free_rx_skbufs(priv, dma_conf, queue); + dev_kfree_skb_any(rx_q->state.skb); + rx_q->state.skb = NULL; + rx_q->state_saved = false; rx_q->buf_alloc_num = 0; rx_q->xsk_pool = NULL; @@ -4172,10 +4207,16 @@ static int __stmmac_open(struct net_device *dev, ret = stmmac_hw_setup(dev); if (ret < 0) { netdev_err(priv->dev, "%s: Hw setup failed\n", __func__); - goto init_error; + return ret; } - stmmac_setup_ptp(priv); + ret = stmmac_setup_ptp(priv); + if (ret) + goto ptp_error; + + ret = stmmac_setup_est(priv); + if (ret) + goto est_error; stmmac_init_coalesce(priv); @@ -4198,9 +4239,12 @@ static int __stmmac_open(struct net_device *dev, for (chan = 0; chan < priv->plat->tx_queues_to_use; chan++) hrtimer_cancel(&priv->dma_conf.tx_queue[chan].txtimer); - +est_error: stmmac_release_ptp(priv); -init_error: +ptp_error: + stmmac_stop_all_dma(priv); + stmmac_mac_set(priv, priv->ioaddr, false); + return ret; } @@ -5060,22 +5104,35 @@ static netdev_features_t stmmac_features_check(struct sk_buff *skb, return vlan_features_check(skb, features); } -static void stmmac_rx_vlan(struct net_device *dev, struct sk_buff *skb) +static int stmmac_rx_vlan(struct net_device *dev, struct sk_buff *skb) { - struct vlan_ethhdr *veth = skb_vlan_eth_hdr(skb); - __be16 vlan_proto = veth->h_vlan_proto; - u16 vlanid; + struct vlan_ethhdr *veth; - if ((vlan_proto == htons(ETH_P_8021Q) && + if (!pskb_may_pull(skb, ETH_HLEN)) + return -EINVAL; + + veth = skb_vlan_eth_hdr(skb); + if ((veth->h_vlan_proto == htons(ETH_P_8021Q) && dev->features & NETIF_F_HW_VLAN_CTAG_RX) || - (vlan_proto == htons(ETH_P_8021AD) && + (veth->h_vlan_proto == htons(ETH_P_8021AD) && dev->features & NETIF_F_HW_VLAN_STAG_RX)) { + __be16 vlan_proto = veth->h_vlan_proto; + u8 meta_len = skb_metadata_len(skb); + u16 vlanid; + /* pop the vlan tag */ + if (!pskb_may_pull(skb, VLAN_ETH_HLEN)) + return -EINVAL; + + veth = skb_vlan_eth_hdr(skb); vlanid = ntohs(veth->h_vlan_TCI); - memmove(skb->data + VLAN_HLEN, veth, ETH_ALEN * 2); + memmove(skb->data - meta_len + VLAN_HLEN, + skb->data - meta_len, meta_len + ETH_ALEN * 2); skb_pull(skb, VLAN_HLEN); __vlan_hwaccel_put_tag(skb, vlan_proto, vlanid); } + + return 0; } /** @@ -5415,7 +5472,8 @@ static struct sk_buff *stmmac_construct_skb_zc(struct stmmac_channel *ch, return NULL; skb_reserve(skb, xdp->data - xdp->data_hard_start); - memcpy(__skb_put(skb, datasize), xdp->data, datasize); + __skb_put(skb, datasize); + memcpy(skb->data - metasize, xdp->data_meta, datasize + metasize); if (metasize) skb_metadata_set(skb, metasize); @@ -5441,12 +5499,15 @@ static void stmmac_dispatch_skb_zc(struct stmmac_priv *priv, u32 queue, } stmmac_get_rx_hwtstamp(priv, p, np, skb); - if (priv->hw->hw_vlan_en) + if (priv->hw->hw_vlan_en) { /* MAC level stripping. */ stmmac_rx_hw_vlan(priv, priv->hw, p, skb); - else - /* Driver level stripping. */ - stmmac_rx_vlan(priv->dev, skb); + } else if (stmmac_rx_vlan(priv->dev, skb)) { + dev_kfree_skb_any(skb); + priv->xstats.rx_dropped++; + return; + } + skb->protocol = eth_type_trans(skb, priv->dev); if (unlikely(!coe) || !stmmac_has_ip_ethertype(skb)) @@ -5461,7 +5522,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); } @@ -5536,12 +5597,12 @@ static int stmmac_rx_zc(struct stmmac_priv *priv, int limit, u32 queue) unsigned int count = 0, error = 0, len = 0; int dirty = stmmac_rx_dirty(priv, queue); unsigned int next_entry = rx_q->cur_rx; + bool in_progress = rx_q->state_saved; u32 rx_errors = 0, rx_dropped = 0; unsigned int desc_size; struct bpf_prog *prog; bool failure = false; int xdp_status = 0; - int status = 0; if (netif_msg_rx_status(priv)) { void *rx_head = stmmac_get_rx_desc(priv, rx_q, 0); @@ -5552,23 +5613,25 @@ static int stmmac_rx_zc(struct stmmac_priv *priv, int limit, u32 queue) stmmac_display_ring(priv, rx_head, priv->dma_conf.dma_rx_size, true, rx_q->dma_rx_phy, desc_size); } + + if (rx_q->state_saved) { + error = rx_q->state.error; + len = rx_q->state.len; + rx_q->state_saved = false; + } + while (count < limit) { struct stmmac_rx_buffer *buf; struct stmmac_xdp_buff *ctx; unsigned int buf1_len = 0; struct dma_desc *np, *p; - int entry; + int entry, status; int res; - if (!count && rx_q->state_saved) { - error = rx_q->state.error; - len = rx_q->state.len; - } else { - rx_q->state_saved = false; + if (!in_progress) { error = 0; len = 0; } - read_again: if (count >= limit) break; @@ -5607,6 +5670,8 @@ static int stmmac_rx_zc(struct stmmac_priv *priv, int limit, u32 queue) if (!buf->xdp) break; + in_progress = status & rx_not_ls; + if (priv->extend_desc) { /* Read the extended status after the own bit */ dma_rmb(); @@ -5614,18 +5679,21 @@ static int stmmac_rx_zc(struct stmmac_priv *priv, int limit, u32 queue) &rx_q->dma_erx[entry], status); } - if (unlikely(status == discard_frame)) { - xsk_buff_free(buf->xdp); - buf->xdp = NULL; - dirty++; + + if (unlikely(!error && (status & discard_frame))) { error = 1; if (!priv->hwts_rx_en) rx_errors++; } - if (unlikely(error && (status & rx_not_ls))) - goto read_again; if (unlikely(error)) { + xsk_buff_free(buf->xdp); + buf->xdp = NULL; + dirty++; + + if (status & rx_not_ls) + goto read_again; + count++; continue; } @@ -5634,8 +5702,9 @@ static int stmmac_rx_zc(struct stmmac_priv *priv, int limit, u32 queue) if (likely(status & rx_not_ls)) { xsk_buff_free(buf->xdp); buf->xdp = NULL; + rx_dropped++; + error = 1; dirty++; - count++; goto read_again; } @@ -5683,7 +5752,7 @@ static int stmmac_rx_zc(struct stmmac_priv *priv, int limit, u32 queue) count++; } - if (status & rx_not_ls) { + if (in_progress) { rx_q->state_saved = true; rx_q->state.error = error; rx_q->state.len = len; @@ -5725,9 +5794,10 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue) struct stmmac_rx_queue *rx_q = &priv->dma_conf.rx_queue[queue]; struct stmmac_channel *ch = &priv->channel[queue]; unsigned int count = 0, error = 0, len = 0; - int status = 0, coe = priv->hw->rx_csum; unsigned int next_entry = rx_q->cur_rx; + bool in_progress = rx_q->state_saved; enum dma_data_direction dma_dir; + int coe = priv->hw->rx_csum; unsigned int desc_size; struct sk_buff *skb = NULL; struct stmmac_xdp_buff ctx; @@ -5747,25 +5817,28 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue) stmmac_display_ring(priv, rx_head, priv->dma_conf.dma_rx_size, true, rx_q->dma_rx_phy, desc_size); } + + if (rx_q->state_saved) { + skb = rx_q->state.skb; + error = rx_q->state.error; + len = rx_q->state.len; + rx_q->state.skb = NULL; + rx_q->state_saved = false; + } + while (count < limit) { unsigned int buf1_len = 0, buf2_len = 0; enum pkt_hash_types hash_type; struct stmmac_rx_buffer *buf; struct dma_desc *np, *p; - int entry; + int entry, status; u32 hash; - if (!count && rx_q->state_saved) { - skb = rx_q->state.skb; - error = rx_q->state.error; - len = rx_q->state.len; - } else { - rx_q->state_saved = false; + if (!in_progress) { skb = NULL; error = 0; len = 0; } - read_again: if (count >= limit) break; @@ -5794,6 +5867,8 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue) prefetch(np); + in_progress = status & rx_not_ls; + if (priv->extend_desc) { /* Read the extended status after the own bit */ dma_rmb(); @@ -5801,21 +5876,26 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue) &rx_q->dma_erx[entry], status); } - if (unlikely(status == discard_frame)) { - page_pool_put_page(rx_q->page_pool, buf->page, 0, true); - buf->page = NULL; + + if (unlikely(!error && (status & discard_frame))) { error = 1; if (!priv->hwts_rx_en) rx_errors++; } - if (unlikely(error && (status & rx_not_ls))) - goto read_again; + /* We do not support SG in XDP mode */ + if (unlikely(!error && (status & rx_not_ls) && + stmmac_xdp_is_enabled(priv))) { + rx_dropped++; + error = 1; + } + if (unlikely(error)) { + if (status & rx_not_ls) + goto read_again; + dev_kfree_skb(skb); - skb = NULL; - count++; - continue; + goto next; } /* Buffer is good. Go on. */ @@ -5825,13 +5905,19 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue) buf2_len = stmmac_rx_buf2_len(priv, p, status, len); len += buf2_len; + /* Drop the packet if it is split over buf1 and buf2 on a + * single descriptor if the interface is running in XDP mode. + */ + if (unlikely(stmmac_xdp_is_enabled(priv) && buf2_len)) { + rx_dropped++; + goto next; + } + /* ACS is disabled; strip manually. */ if (likely(!(status & rx_not_ls))) len -= ETH_FCS_LEN; if (!skb) { - unsigned int pre_len, sync_len; - /* Each frame starts here: reset the FCS handling */ fcs_stripped = false; @@ -5849,55 +5935,32 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue) xdp_prepare_buff(&ctx.xdp, page_address(buf->page), buf->page_offset, buf1_len, true); - pre_len = ctx.xdp.data_end - ctx.xdp.data_hard_start - - buf->page_offset; - ctx.priv = priv; ctx.desc = p; ctx.ndesc = np; skb = stmmac_xdp_run_prog(priv, &ctx.xdp); - /* Due xdp_adjust_tail: DMA sync for_device - * cover max len CPU touch - */ - sync_len = ctx.xdp.data_end - ctx.xdp.data_hard_start - - buf->page_offset; - sync_len = max(sync_len, pre_len); - /* For Not XDP_PASS verdict */ if (IS_ERR(skb)) { unsigned int xdp_res = -PTR_ERR(skb); if (xdp_res & STMMAC_XDP_CONSUMED) { - page_pool_put_page(rx_q->page_pool, - virt_to_head_page(ctx.xdp.data), - sync_len, true); + page_pool_recycle_direct(rx_q->page_pool, + virt_to_head_page(ctx.xdp.data)); buf->page = NULL; rx_dropped++; - - /* Clear skb as it was set as - * status by XDP program. - */ - skb = NULL; - - if (unlikely((status & rx_not_ls))) - goto read_again; - - count++; - continue; + goto next; } else if (xdp_res & (STMMAC_XDP_TX | STMMAC_XDP_REDIRECT)) { xdp_status |= xdp_res; buf->page = NULL; - skb = NULL; - count++; - continue; + goto next; } } } if (!skb) { - unsigned int head_pad_len; + unsigned int metasize; /* XDP program may expand or reduce tail */ buf1_len = ctx.xdp.data_end - ctx.xdp.data; @@ -5914,10 +5977,14 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue) } /* XDP program may adjust header */ - head_pad_len = ctx.xdp.data - ctx.xdp.data_hard_start; - skb_reserve(skb, head_pad_len); + skb_reserve(skb, + ctx.xdp.data - ctx.xdp.data_hard_start); skb_put(skb, buf1_len); skb_mark_for_recycle(skb); + + metasize = ctx.xdp.data - ctx.xdp.data_meta; + if (metasize) + skb_metadata_set(skb, metasize); buf->page = NULL; } else if (buf1_len) { dma_sync_single_for_cpu(priv->device, buf->addr, @@ -5948,20 +6015,20 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue) /* Remove FCS if needed */ if (!fcs_stripped && pskb_trim(skb, len)) { dev_kfree_skb_any(skb); - skb = NULL; rx_dropped++; - count++; - continue; + goto next; } stmmac_get_rx_hwtstamp(priv, p, np, skb); - if (priv->hw->hw_vlan_en) + if (priv->hw->hw_vlan_en) { /* MAC level stripping. */ stmmac_rx_hw_vlan(priv, priv->hw, p, skb); - else - /* Driver level stripping. */ - stmmac_rx_vlan(priv->dev, skb); + } else if (stmmac_rx_vlan(priv->dev, skb)) { + dev_kfree_skb_any(skb); + rx_dropped++; + goto next; + } skb->protocol = eth_type_trans(skb, priv->dev); @@ -5976,14 +6043,15 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue) skb_record_rx_queue(skb, queue); napi_gro_receive(&ch->rx_napi, skb); - skb = NULL; - rx_packets++; rx_bytes += len; +next: + in_progress = false; + skb = NULL; count++; } - if (status & rx_not_ls || skb) { + if (in_progress || skb) { rx_q->state_saved = true; rx_q->state.skb = skb; rx_q->state.error = error; @@ -7773,8 +7841,7 @@ static int stmmac_register_devlink(struct stmmac_priv *priv) /* For now, what is exposed over devlink is only relevant when * timestamping is available and we have a valid ptp clock rate */ - if (!(priv->dma_cap.time_stamp || priv->dma_cap.atime_stamp) || - !priv->plat->clk_ptp_rate) + if (!stmmac_check_timestamp_cap(priv) || !priv->plat->clk_ptp_rate) return 0; priv->devlink = devlink_alloc(&stmmac_devlink_ops, sizeof(*dl_priv), @@ -8087,6 +8154,7 @@ static int __stmmac_dvr_probe(struct device *device, stmmac_napi_add(ndev); mutex_init(&priv->lock); + mutex_init(&priv->est_lock); rwlock_init(&priv->ptp_lock); stmmac_fpe_init(priv); @@ -8220,6 +8288,7 @@ void stmmac_dvr_remove(struct device *dev) destroy_workqueue(priv->wq); mutex_destroy(&priv->lock); + mutex_destroy(&priv->est_lock); bitmap_free(priv->af_xdp_zc_qps); pm_runtime_disable(dev); @@ -8295,6 +8364,9 @@ static void stmmac_reset_rx_queue(struct stmmac_priv *priv, u32 queue) { struct stmmac_rx_queue *rx_q = &priv->dma_conf.rx_queue[queue]; + dev_kfree_skb_any(rx_q->state.skb); + rx_q->state.skb = NULL; + rx_q->state_saved = false; rx_q->cur_rx = 0; rx_q->dirty_rx = 0; } @@ -8389,14 +8461,23 @@ int stmmac_resume(struct device *dev) ret = stmmac_hw_setup(ndev); if (ret < 0) { netdev_err(priv->dev, "%s: Hw setup failed\n", __func__); - stmmac_legacy_serdes_power_down(priv); - mutex_unlock(&priv->lock); - rtnl_unlock(); - return ret; + goto error_unlock; } - stmmac_init_timestamping(priv); + if (priv->ptp_enabled) { + if (stmmac_init_ptp_clk_freq(priv)) + goto init_coalesce; + + ret = stmmac_init_timestamping(priv); + if (ret) + goto error_stop_dma; + + ret = stmmac_setup_est(priv); + if (ret) + goto error_stop_dma; + } +init_coalesce: stmmac_init_coalesce(priv); phylink_rx_clk_stop_block(priv->phylink); stmmac_set_rx_mode(ndev); @@ -8419,6 +8500,16 @@ int stmmac_resume(struct device *dev) netif_device_attach(ndev); return 0; + +error_stop_dma: + stmmac_stop_all_dma(priv); + stmmac_mac_set(priv, priv->ioaddr, false); +error_unlock: + stmmac_legacy_serdes_power_down(priv); + mutex_unlock(&priv->lock); + rtnl_unlock(); + + return ret; } EXPORT_SYMBOL_GPL(stmmac_resume); diff --git a/drivers/net/ethernet/stmicro/stmmac/stmmac_platform.c b/drivers/net/ethernet/stmicro/stmmac/stmmac_platform.c index 6128ed1bd521..19d481554499 100644 --- a/drivers/net/ethernet/stmicro/stmmac/stmmac_platform.c +++ b/drivers/net/ethernet/stmicro/stmmac/stmmac_platform.c @@ -959,7 +959,8 @@ static int __maybe_unused stmmac_pltfr_noirq_suspend(struct device *dev) if (!priv->wolopts) { /* Disable clock in case of PWM is off */ - clk_disable_unprepare(priv->plat->clk_ptp_ref); + if (priv->ptp_enabled) + clk_disable_unprepare(priv->plat->clk_ptp_ref); ret = pm_runtime_force_suspend(dev); if (ret) @@ -984,6 +985,9 @@ static int __maybe_unused stmmac_pltfr_noirq_resume(struct device *dev) if (ret) return ret; + if (!priv->ptp_enabled) + return 0; + ret = clk_prepare_enable(priv->plat->clk_ptp_ref); if (ret < 0) { netdev_warn(priv->dev, diff --git a/drivers/net/ethernet/stmicro/stmmac/stmmac_ptp.c b/drivers/net/ethernet/stmicro/stmmac/stmmac_ptp.c index 3bfcc9760dce..31a66e855d6b 100644 --- a/drivers/net/ethernet/stmicro/stmmac/stmmac_ptp.c +++ b/drivers/net/ethernet/stmicro/stmmac/stmmac_ptp.c @@ -8,6 +8,7 @@ Author: Rayagond Kokatanur *******************************************************************************/ #include "stmmac.h" +#include "stmmac_est.h" #include "stmmac_ptp.h" #define PTP_SAFE_TIME_OFFSET_NS 500000 @@ -54,8 +55,7 @@ static int stmmac_adjust_time(struct ptp_clock_info *ptp, s64 delta) u32 sec, nsec; u32 quotient, reminder; int neg_adj = 0; - bool xmac, est_rst = false; - int ret; + bool xmac; xmac = dwmac_is_xmac(priv->plat->core_type); @@ -69,60 +69,35 @@ static int stmmac_adjust_time(struct ptp_clock_info *ptp, s64 delta) nsec = reminder; /* If EST is enabled, disabled it before adjust ptp time. */ - if (priv->est && priv->est->enable) { - est_rst = true; - mutex_lock(&priv->est_lock); - priv->est->enable = false; + mutex_lock(&priv->est_lock); + if (priv->est && priv->est->enable) stmmac_est_configure(priv, priv, priv->est, - priv->plat->clk_ptp_rate); - mutex_unlock(&priv->est_lock); - } + priv->plat->clk_ptp_rate, false); + mutex_unlock(&priv->est_lock); write_lock_irqsave(&priv->ptp_lock, flags); stmmac_adjust_systime(priv, priv->ptpaddr, sec, nsec, neg_adj, xmac); write_unlock_irqrestore(&priv->ptp_lock, flags); /* Calculate new basetime and re-configured EST after PTP time adjust. */ - if (est_rst) { - struct timespec64 current_time, time; - ktime_t current_time_ns, basetime; - u64 cycle_time; - - mutex_lock(&priv->est_lock); - priv->ptp_clock_ops.gettime64(&priv->ptp_clock_ops, ¤t_time); - current_time_ns = timespec64_to_ktime(current_time); - time.tv_nsec = priv->est->btr_reserve[0]; - time.tv_sec = priv->est->btr_reserve[1]; - basetime = timespec64_to_ktime(time); - cycle_time = (u64)priv->est->ctr[1] * NSEC_PER_SEC + - priv->est->ctr[0]; - time = stmmac_calc_tas_basetime(basetime, - current_time_ns, - cycle_time); - - priv->est->btr[0] = (u32)time.tv_nsec; - priv->est->btr[1] = (u32)time.tv_sec; - priv->est->enable = true; - ret = stmmac_est_configure(priv, priv, priv->est, - priv->plat->clk_ptp_rate); - mutex_unlock(&priv->est_lock); - if (ret) - netdev_err(priv->dev, "failed to configure EST\n"); - } + mutex_lock(&priv->est_lock); + if (priv->est && priv->est->enable) + __stmmac_setup_est(priv); + mutex_unlock(&priv->est_lock); return 0; } /** - * stmmac_get_time - * + * stmmac_get_timex - read the PTP clock, with system timestamps if requested * @ptp: pointer to ptp_clock_info structure * @ts: pointer to hold time/result + * @sts: pointer to hold system timestamps around the read, or NULL * - * Description: this function will read the current time from the - * hardware clock and store it in @ts. + * Return: 0 */ -static int stmmac_get_time(struct ptp_clock_info *ptp, struct timespec64 *ts) +static int stmmac_get_timex(struct ptp_clock_info *ptp, struct timespec64 *ts, + struct ptp_system_timestamp *sts) { struct stmmac_priv *priv = container_of(ptp, struct stmmac_priv, ptp_clock_ops); @@ -130,7 +105,7 @@ static int stmmac_get_time(struct ptp_clock_info *ptp, struct timespec64 *ts) u64 ns = 0; read_lock_irqsave(&priv->ptp_lock, flags); - stmmac_get_systime(priv, priv->ptpaddr, &ns); + stmmac_get_systime(priv, priv->ptpaddr, &ns, sts); read_unlock_irqrestore(&priv->ptp_lock, flags); *ts = ns_to_timespec64(ns); @@ -200,7 +175,7 @@ static int stmmac_enable(struct ptp_clock_info *ptp, target_ns = cfg->start.tv_nsec + ((u64)cfg->start.tv_sec * NSEC_PER_SEC); - stmmac_get_systime(priv, priv->ptpaddr, &ns); + stmmac_get_systime(priv, priv->ptpaddr, &ns, NULL); if (ns > TIME64_MAX - PTP_SAFE_TIME_OFFSET_NS) return -EINVAL; @@ -302,9 +277,10 @@ const struct ptp_clock_info stmmac_ptp_clock_ops = { .n_per_out = 0, /* will be overwritten in stmmac_ptp_register */ .n_pins = 0, .pps = 0, + .supported_extts_flags = PTP_RISING_EDGE | PTP_STRICT_FLAGS, .adjfine = stmmac_adjust_freq, .adjtime = stmmac_adjust_time, - .gettime64 = stmmac_get_time, + .gettimex64 = stmmac_get_timex, .settime64 = stmmac_set_time, .enable = stmmac_enable, }; @@ -319,9 +295,10 @@ const struct ptp_clock_info dwmac1000_ptp_clock_ops = { .n_per_out = 0, .n_pins = 0, .pps = 0, + .supported_extts_flags = PTP_RISING_EDGE | PTP_STRICT_FLAGS, .adjfine = stmmac_adjust_freq, .adjtime = stmmac_adjust_time, - .gettime64 = stmmac_get_time, + .gettimex64 = stmmac_get_timex, .settime64 = stmmac_set_time, .enable = dwmac1000_ptp_enable, }; diff --git a/drivers/net/ethernet/stmicro/stmmac/stmmac_selftests.c b/drivers/net/ethernet/stmicro/stmmac/stmmac_selftests.c index 6c01fdb6667e..57aedf522808 100644 --- a/drivers/net/ethernet/stmicro/stmmac/stmmac_selftests.c +++ b/drivers/net/ethernet/stmicro/stmmac/stmmac_selftests.c @@ -1887,7 +1887,7 @@ static int stmmac_test_tbs(struct stmmac_priv *priv) return ret; read_lock_irqsave(&priv->ptp_lock, flags); - stmmac_get_systime(priv, priv->ptpaddr, &curr_time); + stmmac_get_systime(priv, priv->ptpaddr, &curr_time, NULL); read_unlock_irqrestore(&priv->ptp_lock, flags); if (!curr_time) { @@ -1909,7 +1909,7 @@ static int stmmac_test_tbs(struct stmmac_priv *priv) /* Check if expected time has elapsed */ read_lock_irqsave(&priv->ptp_lock, flags); - stmmac_get_systime(priv, priv->ptpaddr, &curr_time); + stmmac_get_systime(priv, priv->ptpaddr, &curr_time, NULL); read_unlock_irqrestore(&priv->ptp_lock, flags); if ((curr_time - start_time) < STMMAC_TBS_LT_OFFSET) diff --git a/drivers/net/ethernet/stmicro/stmmac/stmmac_tc.c b/drivers/net/ethernet/stmicro/stmmac/stmmac_tc.c index a7721b2eee96..dab79d8a3bc2 100644 --- a/drivers/net/ethernet/stmicro/stmmac/stmmac_tc.c +++ b/drivers/net/ethernet/stmicro/stmmac/stmmac_tc.c @@ -966,11 +966,12 @@ static void tc_taprio_map_maxsdu_txq(struct stmmac_priv *priv, static int tc_taprio_configure(struct stmmac_priv *priv, struct tc_taprio_qopt_offload *qopt) { - u32 size, wid = priv->dma_cap.estwid, dep = priv->dma_cap.estdep; + u32 wid = priv->dma_cap.estwid, dep = priv->dma_cap.estdep; struct netlink_ext_ack *extack = qopt->mqprio.extack; struct timespec64 time, current_time, qopt_time; ktime_t current_time_ns; int err, i, ret = 0; + u32 *gcl = NULL; u64 ctr; if (qopt->base_time < 0) @@ -1013,44 +1014,46 @@ static int tc_taprio_configure(struct stmmac_priv *priv, return -EOPNOTSUPP; } + mutex_lock(&priv->est_lock); + if (qopt->cmd == TAPRIO_CMD_DESTROY) goto disable; - if (qopt->num_entries > dep) - return -EINVAL; - if (!qopt->cycle_time) - return -ERANGE; - if (qopt->cycle_time_extension >= BIT(wid + 7)) - return -ERANGE; - - if (!priv->est) { - priv->est = devm_kzalloc(priv->device, sizeof(*priv->est), - GFP_KERNEL); - if (!priv->est) - return -ENOMEM; + if (qopt->num_entries > dep) { + ret = -EINVAL; + goto error_unlock; + } - mutex_init(&priv->est_lock); - } else { - mutex_lock(&priv->est_lock); - memset(priv->est, 0, sizeof(*priv->est)); - mutex_unlock(&priv->est_lock); + if (!qopt->cycle_time || + qopt->cycle_time > (u64)U32_MAX * NSEC_PER_SEC) { + ret = -ERANGE; + goto error_unlock; } - size = qopt->num_entries; + if (qopt->cycle_time_extension >= BIT(wid + 7)) { + ret = -ERANGE; + goto error_unlock; + } - mutex_lock(&priv->est_lock); - priv->est->gcl_size = size; - priv->est->enable = qopt->cmd == TAPRIO_CMD_REPLACE; - mutex_unlock(&priv->est_lock); + gcl = kcalloc(qopt->num_entries, sizeof(*gcl), GFP_KERNEL); + if (!gcl) { + ret = -ENOMEM; + goto error_unlock; + } - for (i = 0; i < size; i++) { + for (i = 0; i < qopt->num_entries; i++) { s64 delta_ns = qopt->entries[i].interval; u32 gates = qopt->entries[i].gate_mask; - if (delta_ns > GENMASK(wid - 1, 0)) - return -ERANGE; - if (gates > GENMASK(31 - wid, 0)) - return -ERANGE; + if (delta_ns > GENMASK(wid - 1, 0)) { + ret = -ERANGE; + goto error_unlock; + } + + if (gates > GENMASK(31 - wid, 0)) { + ret = -ERANGE; + goto error_unlock; + } switch (qopt->entries[i].command) { case TC_TAPRIO_CMD_SET_GATES: @@ -1062,15 +1065,29 @@ static int tc_taprio_configure(struct stmmac_priv *priv, gates &= ~BIT(0); break; default: - return -EOPNOTSUPP; + ret = -EOPNOTSUPP; + goto error_unlock; } - priv->est->gcl[i] = delta_ns | (gates << wid); + gcl[i] = delta_ns | (gates << wid); } - mutex_lock(&priv->est_lock); + if (!priv->est) { + priv->est = devm_kzalloc(priv->device, sizeof(*priv->est), + GFP_KERNEL); + if (!priv->est) { + ret = -ENOMEM; + goto error_unlock; + } + } else { + memset(priv->est, 0, sizeof(*priv->est)); + } + memcpy(priv->est->gcl, gcl, sizeof(*gcl) * qopt->num_entries); + priv->est->gcl_size = qopt->num_entries; + /* Adjust for real system time */ - priv->ptp_clock_ops.gettime64(&priv->ptp_clock_ops, ¤t_time); + priv->ptp_clock_ops.gettimex64(&priv->ptp_clock_ops, ¤t_time, + NULL); current_time_ns = timespec64_to_ktime(current_time); time = stmmac_calc_tas_basetime(qopt->base_time, current_time_ns, qopt->cycle_time); @@ -1091,8 +1108,7 @@ static int tc_taprio_configure(struct stmmac_priv *priv, tc_taprio_map_maxsdu_txq(priv, qopt); ret = stmmac_est_configure(priv, priv, priv->est, - priv->plat->clk_ptp_rate); - mutex_unlock(&priv->est_lock); + priv->plat->clk_ptp_rate, true); if (ret) { netdev_err(priv->dev, "failed to configure EST\n"); goto disable; @@ -1103,24 +1119,31 @@ static int tc_taprio_configure(struct stmmac_priv *priv, if (ret) goto disable; + priv->est->pclass = qopt->mqprio.preemptible_tcs; + priv->est->enable = true; + + mutex_unlock(&priv->est_lock); + kfree(gcl); + return 0; disable: if (priv->est) { - mutex_lock(&priv->est_lock); priv->est->enable = false; stmmac_est_configure(priv, priv, priv->est, - priv->plat->clk_ptp_rate); + priv->plat->clk_ptp_rate, false); /* Reset taprio status */ for (i = 0; i < priv->plat->tx_queues_to_use; i++) { priv->xstats.max_sdu_txq_drop[i] = 0; priv->xstats.mtl_est_txq_hlbf[i] = 0; priv->xstats.mtl_est_txq_hlbs[i] = 0; } - mutex_unlock(&priv->est_lock); } err = stmmac_fpe_map_preemption_class(priv, priv->dev, extack, 0); +error_unlock: + mutex_unlock(&priv->est_lock); + kfree(gcl); return qopt->cmd == TAPRIO_CMD_DESTROY ? err : ret; } diff --git a/drivers/net/ethernet/ti/am65-cpts.c b/drivers/net/ethernet/ti/am65-cpts.c index df5659ead72f..ca885405fea0 100644 --- a/drivers/net/ethernet/ti/am65-cpts.c +++ b/drivers/net/ethernet/ti/am65-cpts.c @@ -176,6 +176,9 @@ struct am65_cpts { struct mutex ptp_clk_lock; /* PHC access sync */ u64 timestamp; u32 genf_enable; + bool genf_neg_adj; + u32 genf_ppm_hi; + u32 genf_ppm_low; u32 hw_ts_enable; u32 estf_enable; struct sk_buff_head txq; @@ -436,9 +439,11 @@ static int am65_cpts_ptp_adjfine(struct ptp_clock_info *ptp, long scaled_ppm) { struct am65_cpts *cpts = container_of(ptp, struct am65_cpts, ptp_info); u32 estf_ctrl_val = 0, estf_ppm_hi = 0, estf_ppm_low = 0; + u32 genf_ctrl_val[AM65_CPTS_GENF_MAX_NUM]; + u32 genf_ppm_hi, genf_ppm_low; s32 ppb = scaled_ppm_to_ppb(scaled_ppm); int pps_index = cpts->pps_genf_idx; - u64 adj_period, pps_adj_period; + u64 adj_period, genf_adj_period; u32 ctrl_val, ppm_hi, ppm_low; unsigned long flags; int neg_adj = 0, i; @@ -470,20 +475,33 @@ static int am65_cpts_ptp_adjfine(struct ptp_clock_info *ptp, long scaled_ppm) ppm_hi = upper_32_bits(adj_period) & 0x3FF; ppm_low = lower_32_bits(adj_period); + /* GenF PPM will do correction using cpts refclk tick which is + * (cpts->ts_add_val + 1) ns, so GenF length PPM adj period + * need to be corrected. + */ + genf_adj_period = adj_period * (cpts->ts_add_val + 1); + genf_ppm_hi = upper_32_bits(genf_adj_period) & 0x3FF; + genf_ppm_low = lower_32_bits(genf_adj_period); + cpts->genf_neg_adj = neg_adj; + cpts->genf_ppm_hi = genf_ppm_hi; + cpts->genf_ppm_low = genf_ppm_low; + + for (i = 0; i < AM65_CPTS_GENF_MAX_NUM; i++) { + if (cpts->genf_enable & BIT(i)) { + genf_ctrl_val[i] = am65_cpts_read32(cpts, + genf[i].control); + if (neg_adj) + genf_ctrl_val[i] &= ~BIT(1); + else + genf_ctrl_val[i] |= BIT(1); + } + } + if (cpts->pps_enabled) { - estf_ctrl_val = am65_cpts_read32(cpts, genf[pps_index].control); - if (neg_adj) - estf_ctrl_val &= ~BIT(1); - else - estf_ctrl_val |= BIT(1); - - /* GenF PPM will do correction using cpts refclk tick which is - * (cpts->ts_add_val + 1) ns, so GenF length PPM adj period - * need to be corrected. - */ - pps_adj_period = adj_period * (cpts->ts_add_val + 1); - estf_ppm_hi = upper_32_bits(pps_adj_period) & 0x3FF; - estf_ppm_low = lower_32_bits(pps_adj_period); + /* am65_cpts_perout_enable_hw() sets pps_index in genf_enable */ + estf_ctrl_val = genf_ctrl_val[pps_index]; + estf_ppm_hi = genf_ppm_hi; + estf_ppm_low = genf_ppm_low; } spin_lock_irqsave(&cpts->lock, flags); @@ -500,10 +518,13 @@ static int am65_cpts_ptp_adjfine(struct ptp_clock_info *ptp, long scaled_ppm) am65_cpts_write32(cpts, ppm_hi, ts_ppm_hi); am65_cpts_write32(cpts, ppm_low, ts_ppm_low); - if (cpts->pps_enabled) { - am65_cpts_write32(cpts, estf_ctrl_val, genf[pps_index].control); - am65_cpts_write32(cpts, estf_ppm_hi, genf[pps_index].ppm_hi); - am65_cpts_write32(cpts, estf_ppm_low, genf[pps_index].ppm_low); + for (i = 0; i < AM65_CPTS_GENF_MAX_NUM; i++) { + if (cpts->genf_enable & BIT(i)) { + am65_cpts_write32(cpts, genf_ctrl_val[i], + genf[i].control); + am65_cpts_write32(cpts, genf_ppm_hi, genf[i].ppm_hi); + am65_cpts_write32(cpts, genf_ppm_low, genf[i].ppm_low); + } } for (i = 0; i < AM65_CPTS_ESTF_MAX_NUM; i++) { @@ -513,7 +534,6 @@ static int am65_cpts_ptp_adjfine(struct ptp_clock_info *ptp, long scaled_ppm) am65_cpts_write32(cpts, estf_ppm_low, estf[i].ppm_low); } } - /* All GenF/EstF can be updated here the same way */ spin_unlock_irqrestore(&cpts->lock, flags); mutex_unlock(&cpts->ptp_clk_lock); @@ -679,9 +699,12 @@ static void am65_cpts_perout_enable_hw(struct am65_cpts *cpts, val = lower_32_bits(cycles); am65_cpts_write32(cpts, val, genf[req->index].length); - am65_cpts_write32(cpts, 0, genf[req->index].control); - am65_cpts_write32(cpts, 0, genf[req->index].ppm_hi); - am65_cpts_write32(cpts, 0, genf[req->index].ppm_low); + am65_cpts_write32(cpts, cpts->genf_neg_adj ? 0 : BIT(1), + genf[req->index].control); + am65_cpts_write32(cpts, cpts->genf_ppm_hi, + genf[req->index].ppm_hi); + am65_cpts_write32(cpts, cpts->genf_ppm_low, + genf[req->index].ppm_low); cpts->genf_enable |= BIT(req->index); } else { @@ -788,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) { @@ -797,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); @@ -810,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 efb045001c43..88c8d9831aaa 100644 --- a/drivers/net/gtp.c +++ b/drivers/net/gtp.c @@ -560,16 +560,19 @@ static int gtp0_handle_echo_resp(struct gtp_dev *gtp, struct sk_buff *skb) msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC); if (!msg) - return -ENOMEM; + return -1; ret = gtp_genl_fill_echo(msg, 0, 0, 0, GTP_CMD_ECHOREQ, echo); if (ret < 0) { nlmsg_free(msg); - return ret; + return -1; } - return genlmsg_multicast_netns(>p_genl_family, dev_net(gtp->dev), - msg, 0, GTP_GENL_MCGRP, GFP_ATOMIC); + genlmsg_multicast_netns(>p_genl_family, dev_net(gtp->dev), + msg, 0, GTP_GENL_MCGRP, GFP_ATOMIC); + consume_skb(skb); + + return 0; } static int gtp_proto_to_family(__u16 proto) @@ -747,16 +750,19 @@ static int gtp1u_handle_echo_resp(struct gtp_dev *gtp, struct sk_buff *skb) msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC); if (!msg) - return -ENOMEM; + return -1; ret = gtp_genl_fill_echo(msg, 0, 0, 0, GTP_CMD_ECHOREQ, echo); if (ret < 0) { nlmsg_free(msg); - return ret; + return -1; } - return genlmsg_multicast_netns(>p_genl_family, dev_net(gtp->dev), - msg, 0, GTP_GENL_MCGRP, GFP_ATOMIC); + genlmsg_multicast_netns(>p_genl_family, dev_net(gtp->dev), + msg, 0, GTP_GENL_MCGRP, GFP_ATOMIC); + consume_skb(skb); + + return 0; } static int gtp_parse_exthdrs(struct sk_buff *skb, unsigned int *hdrlen) diff --git a/drivers/net/hyperv/rndis_filter.c b/drivers/net/hyperv/rndis_filter.c index 9b6c44979b4e..2c30abf9faf8 100644 --- a/drivers/net/hyperv/rndis_filter.c +++ b/drivers/net/hyperv/rndis_filter.c @@ -401,12 +401,12 @@ static inline void *rndis_get_ppi(struct net_device *ndev, /* Validate ppi_offset and ppi_size */ if (ppi->size > len) { netdev_err(ndev, "Invalid ppi size: %u\n", ppi->size); - continue; + return NULL; } if (ppi->ppi_offset >= ppi->size) { netdev_err(ndev, "Invalid ppi_offset: %u\n", ppi->ppi_offset); - continue; + return NULL; } if (ppi->type == type && ppi->internal == internal) { @@ -414,7 +414,7 @@ static inline void *rndis_get_ppi(struct net_device *ndev, if (ppi->size - ppi->ppi_offset < ppi_size) { netdev_err(ndev, "Invalid ppi: size %u ppi_offset %u\n", ppi->size, ppi->ppi_offset); - continue; + return NULL; } return (void *)((ulong)ppi + ppi->ppi_offset); } diff --git a/drivers/net/ipa/ipa_interrupt.c b/drivers/net/ipa/ipa_interrupt.c index 131b9cc94201..766b094eb069 100644 --- a/drivers/net/ipa/ipa_interrupt.c +++ b/drivers/net/ipa/ipa_interrupt.c @@ -260,10 +260,8 @@ int ipa_interrupt_config(struct ipa *ipa) interrupt->enabled = 0; interrupt->suspend_enabled = bitmap_zalloc(ipa->endpoint_count, GFP_KERNEL); - if (!interrupt->suspend_enabled) { - ret = -ENOMEM; - goto err_kfree; - } + if (!interrupt->suspend_enabled) + return -ENOMEM; /* Disable IPA interrupt types */ reg = ipa_reg(ipa, IPA_IRQ_EN); @@ -289,8 +287,6 @@ int ipa_interrupt_config(struct ipa *ipa) goto err_disable_wakeup; } - ipa->interrupt = interrupt; - return 0; err_disable_wakeup: @@ -299,8 +295,6 @@ int ipa_interrupt_config(struct ipa *ipa) free_irq(interrupt->irq, interrupt); err_free_bitmap: bitmap_free(interrupt->suspend_enabled); -err_kfree: - kfree(interrupt); return ret; } @@ -311,8 +305,6 @@ void ipa_interrupt_deconfig(struct ipa *ipa) struct ipa_interrupt *interrupt = ipa->interrupt; struct device *dev = ipa->dev; - ipa->interrupt = NULL; - dev_pm_clear_wake_irq(dev); (void)device_init_wakeup(dev, false); free_irq(interrupt->irq, interrupt); diff --git a/drivers/net/ipvlan/ipvlan_core.c b/drivers/net/ipvlan/ipvlan_core.c index 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 233391acebb0..34eaea102d35 100644 --- a/drivers/net/macsec.c +++ b/drivers/net/macsec.c @@ -407,8 +407,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 */ @@ -1330,9 +1332,12 @@ static rx_handler_result_t macsec_handle_frame(struct sk_buff **pskb) nosci: /* 10.6.1 if the SC is not found */ cbit = !!(hdr->tci_an & MACSEC_TCI_C); - if (!cbit) - macsec_finalize_skb(skb, MACSEC_DEFAULT_ICV_LEN, - macsec_extra_len(macsec_skb_cb(skb)->has_sci)); + if (!cbit) { + len = macsec_extra_len(macsec_skb_cb(skb)->has_sci); + if (skb->len < ETH_HLEN + len + MACSEC_DEFAULT_ICV_LEN) + goto drop_nosc; + macsec_finalize_skb(skb, MACSEC_DEFAULT_ICV_LEN, len); + } list_for_each_entry_rcu(macsec, &rxd->secys, secys) { struct sk_buff *nskb; diff --git a/drivers/net/mctp/mctp-i3c.c b/drivers/net/mctp/mctp-i3c.c index 4e857dd5df64..5f225999d715 100644 --- a/drivers/net/mctp/mctp-i3c.c +++ b/drivers/net/mctp/mctp-i3c.c @@ -111,8 +111,7 @@ static int mctp_i3c_read(struct mctp_i3c_device *mi) mi->mrl + sizeof(struct mctp_i3c_internal_hdr)); if (!skb) { stats->rx_dropped++; - rc = -ENOMEM; - goto err; + return -ENOMEM; } skb->protocol = htons(ETH_P_MCTP); diff --git a/drivers/net/phy/phy-c45.c b/drivers/net/phy/phy-c45.c index 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/phy/phy_device.c b/drivers/net/phy/phy_device.c index 94b2e85e00a3..5ec2bfdb2337 100644 --- a/drivers/net/phy/phy_device.c +++ b/drivers/net/phy/phy_device.c @@ -1734,6 +1734,102 @@ static bool phy_drv_supports_irq(const struct phy_driver *phydrv) return phydrv->config_intr && phydrv->handle_interrupt; } +/** + * phy_detach_internal - detach a PHY device from its network device + * @phydev: target phy_device struct + * + * This detaches the phy device from its network device and the phy + * driver, and drops the reference count taken in phy_attach_direct(). + */ +static void phy_detach_internal(struct phy_device *phydev) +{ + struct net_device *dev = phydev->attached_dev; + struct module *ndev_owner = NULL; + struct mii_bus *bus; + + if (phydev->devlink) { + device_link_del(phydev->devlink); + phydev->devlink = NULL; + } + + if (phydev->sysfs_links) { + if (dev) + sysfs_remove_link(&dev->dev.kobj, "phydev"); + sysfs_remove_link(&phydev->mdio.dev.kobj, "attached_dev"); + } + + if (!phydev->attached_dev) + sysfs_remove_file(&phydev->mdio.dev.kobj, + &dev_attr_phy_standalone.attr); + + phy_suspend(phydev); + if (dev) { + struct hwtstamp_provider *hwprov; + + /* hwprov may technically be protected by ops lock but + * not for devices with a phydev, see phy_link_topo_add_phy(). + * Drivers may detach without RTNL while dev is unregistered, + * but then nothing else can reach hwprov. + */ + hwprov = rcu_dereference_protected(dev->hwprov, + lockdep_rtnl_is_held() || + dev->reg_state != NETREG_REGISTERED); + /* Disable timestamp if it is the one selected */ + if (hwprov && hwprov->phydev == phydev) { + rcu_assign_pointer(dev->hwprov, NULL); + kfree_rcu(hwprov, rcu_head); + } + + phydev->attached_dev->phydev = NULL; + phydev->attached_dev = NULL; + phy_link_topo_del_phy(dev, phydev); + } + + phydev->phy_link_change = NULL; + phydev->phylink = NULL; + + if (phydev->mdio.dev.driver) + module_put(phydev->mdio.dev.driver->owner); + + /* If the device had no specific driver before (i.e. - it + * was using the generic driver), we unbind the device + * from the generic driver so that there's a chance a + * real driver could be loaded + */ + if (phydev->is_genphy_driven) { + device_release_driver(&phydev->mdio.dev); + phydev->is_genphy_driven = 0; + } + + /* Assert the reset signal */ + phy_device_reset(phydev, 1); + + /* + * The phydev might go away on the put_device() below, so avoid + * a use-after-free bug by reading the underlying bus first. + */ + bus = phydev->mdio.bus; + + put_device(&phydev->mdio.dev); + if (dev) + ndev_owner = dev->dev.parent->driver->owner; + if (ndev_owner != bus->owner) + module_put(bus->owner); +} + +/** + * phy_detach - detach a PHY device from its network device + * @phydev: target phy_device struct + * + * This detaches the phy device from its network device and the phy + * driver, and drops the reference count taken in phy_attach_direct(). + */ +void phy_detach(struct phy_device *phydev) +{ + phy_detach_internal(phydev); +} +EXPORT_SYMBOL(phy_detach); + /** * phy_attach_direct - attach a network device to a given PHY device pointer * @dev: network device to attach @@ -1906,86 +2002,6 @@ int phy_attach_direct(struct net_device *dev, struct phy_device *phydev, } EXPORT_SYMBOL(phy_attach_direct); -/** - * phy_detach - detach a PHY device from its network device - * @phydev: target phy_device struct - * - * This detaches the phy device from its network device and the phy - * driver, and drops the reference count taken in phy_attach_direct(). - */ -void phy_detach(struct phy_device *phydev) -{ - struct net_device *dev = phydev->attached_dev; - struct module *ndev_owner = NULL; - struct mii_bus *bus; - - if (phydev->devlink) { - device_link_del(phydev->devlink); - phydev->devlink = NULL; - } - - if (phydev->sysfs_links) { - if (dev) - sysfs_remove_link(&dev->dev.kobj, "phydev"); - sysfs_remove_link(&phydev->mdio.dev.kobj, "attached_dev"); - } - - if (!phydev->attached_dev) - sysfs_remove_file(&phydev->mdio.dev.kobj, - &dev_attr_phy_standalone.attr); - - phy_suspend(phydev); - if (dev) { - struct hwtstamp_provider *hwprov; - - /* hwprov may technically be protected by ops lock but - * not for devices with a phydev, see phy_link_topo_add_phy() - */ - hwprov = rtnl_dereference(dev->hwprov); - /* Disable timestamp if it is the one selected */ - if (hwprov && hwprov->phydev == phydev) { - rcu_assign_pointer(dev->hwprov, NULL); - kfree_rcu(hwprov, rcu_head); - } - - phydev->attached_dev->phydev = NULL; - phydev->attached_dev = NULL; - phy_link_topo_del_phy(dev, phydev); - } - - phydev->phy_link_change = NULL; - phydev->phylink = NULL; - - if (phydev->mdio.dev.driver) - module_put(phydev->mdio.dev.driver->owner); - - /* If the device had no specific driver before (i.e. - it - * was using the generic driver), we unbind the device - * from the generic driver so that there's a chance a - * real driver could be loaded - */ - if (phydev->is_genphy_driven) { - device_release_driver(&phydev->mdio.dev); - phydev->is_genphy_driven = 0; - } - - /* Assert the reset signal */ - phy_device_reset(phydev, 1); - - /* - * The phydev might go away on the put_device() below, so avoid - * a use-after-free bug by reading the underlying bus first. - */ - bus = phydev->mdio.bus; - - put_device(&phydev->mdio.dev); - if (dev) - ndev_owner = dev->dev.parent->driver->owner; - if (ndev_owner != bus->owner) - module_put(bus->owner); -} -EXPORT_SYMBOL(phy_detach); - int phy_suspend(struct phy_device *phydev) { struct net_device *netdev = phydev->attached_dev; 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 2ed348b95315..092adb497dc7 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) @@ -1943,7 +1949,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; @@ -2619,7 +2626,11 @@ static int tun_xdp_one(struct tun_struct *tun, 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; @@ -3360,6 +3371,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 3bd7cb66f3fc..3c6ac561fe86 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 af845623bf60..c434a1e84dfb 100644 --- a/drivers/net/usb/lan78xx.c +++ b/drivers/net/usb/lan78xx.c @@ -4592,13 +4592,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); @@ -5370,6 +5369,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; } @@ -5384,15 +5389,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 584bc05c577c..3a34a1376752 100644 --- a/drivers/net/virtio_net.c +++ b/drivers/net/virtio_net.c @@ -790,19 +790,32 @@ static unsigned int mergeable_ctx_to_truesize(void *mrg_ctx) return (unsigned long)mrg_ctx & ((1 << MRG_CTX_HEADER_SHIFT) - 1); } -static int check_mergeable_len(struct net_device *dev, void *mrg_ctx, - unsigned int len) +/* Length of the mergeable buffer that add_recvbuf_mergeable() posted. */ +static unsigned int mergeable_ctx_to_buflen(void *mrg_ctx) { - unsigned int headroom, tailroom, room, truesize; + unsigned int headroom, tailroom, room; - truesize = mergeable_ctx_to_truesize(mrg_ctx); headroom = mergeable_ctx_to_headroom(mrg_ctx); tailroom = headroom ? sizeof(struct skb_shared_info) : 0; room = SKB_DATA_ALIGN(headroom + tailroom); - if (len > truesize - room) { - pr_debug("%s: rx error: len %u exceeds truesize %lu\n", - dev->name, len, (unsigned long)(truesize - room)); + return mergeable_ctx_to_truesize(mrg_ctx) - room; +} + +/* Length of the small buffer that add_recvbuf_small() posts. */ +static unsigned int small_buflen(const struct virtnet_info *vi) +{ + return vi->hdr_len + GOOD_PACKET_LEN; +} + +static int check_mergeable_len(struct net_device *dev, void *mrg_ctx, + unsigned int len) +{ + unsigned int buflen = mergeable_ctx_to_buflen(mrg_ctx); + + if (len > buflen) { + pr_debug("%s: rx error: len %u exceeds buffer length %u\n", + dev->name, len, buflen); DEV_STATS_INC(dev, rx_length_errors); return -1; } @@ -1795,15 +1808,15 @@ static struct page *xdp_linearize_page(struct net_device *dev, p = virt_to_head_page(buf); off = buf - page_address(p); - if (rq->use_page_pool_dma) - page_pool_dma_sync_for_cpu(rq->page_pool, p, - off, buflen); - if (check_mergeable_len(dev, ctx, buflen)) { page_pool_put_page(rq->page_pool, p, -1, true); goto err_buf; } + if (rq->use_page_pool_dma) + page_pool_dma_sync_for_cpu(rq->page_pool, p, + off, buflen); + /* guard against a misconfigured or uncooperative backend that * is sending packet larger than the MTU. */ @@ -2158,15 +2171,15 @@ static int virtnet_build_xdp_buff_mrg(struct net_device *dev, page = virt_to_head_page(buf); offset = buf - page_address(page); - if (rq->use_page_pool_dma) - page_pool_dma_sync_for_cpu(rq->page_pool, page, - offset, len); - if (check_mergeable_len(dev, ctx, len)) { page_pool_put_page(rq->page_pool, page, -1, true); goto err; } + if (rq->use_page_pool_dma) + page_pool_dma_sync_for_cpu(rq->page_pool, page, + offset, len); + truesize = mergeable_ctx_to_truesize(ctx); xdp_frags_truesz += truesize; @@ -2435,15 +2448,15 @@ static struct sk_buff *receive_mergeable(struct net_device *dev, u64_stats_add(&stats->bytes, len); page = virt_to_head_page(buf); + if (check_mergeable_len(dev, ctx, len)) + goto err_skb; + if (rq->use_page_pool_dma) { offset = buf - page_address(page); page_pool_dma_sync_for_cpu(rq->page_pool, page, offset, len); } - if (check_mergeable_len(dev, ctx, len)) - goto err_skb; - truesize = mergeable_ctx_to_truesize(ctx); curr_skb = virtnet_skb_append_frag(rq, head_skb, curr_skb, page, buf, len, truesize); @@ -2520,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", @@ -2561,12 +2574,22 @@ static void receive_buf(struct virtnet_info *vi, struct receive_queue *rq, /* Sync the memory before touching anything through buf, * unless virtio core did it already. + * + * len comes from the device and is checked against the buffer + * only later, so never sync past the buffer posted to the device. + * The sync still covers the header, which receive_buf() and the + * mergeable drop path read. Big buffers never come from the page + * pool, so a buffer here is either mergeable or small. */ if (rq->use_page_pool_dma) { struct page *page = virt_to_head_page(buf); int offset = buf - page_address(page); + unsigned int buflen = vi->mergeable_rx_bufs ? + mergeable_ctx_to_buflen(ctx) : + small_buflen(vi); - page_pool_dma_sync_for_cpu(rq->page_pool, page, offset, len); + page_pool_dma_sync_for_cpu(rq->page_pool, page, offset, + min(len, buflen)); } /* About the flags below: @@ -2642,7 +2665,7 @@ static int add_recvbuf_small(struct virtnet_info *vi, struct receive_queue *rq, buf += VIRTNET_RX_PAD + xdp_headroom; ctx = mergeable_len_to_ctx(alloc_len, xdp_headroom); - err = virtnet_rq_submit(rq, buf, vi->hdr_len + GOOD_PACKET_LEN, ctx, gfp); + err = virtnet_rq_submit(rq, buf, small_buflen(vi), ctx, gfp); if (err < 0) page_pool_put_page(rq->page_pool, virt_to_head_page(buf), -1, false); 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 df79f15c1cca..31009313e07b 100644 --- a/drivers/net/wireless/ath/ath12k/ahb.c +++ b/drivers/net/wireless/ath/ath12k/ahb.c @@ -574,8 +574,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) @@ -591,9 +591,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 c6af10e54c3f..e83a194b334f 100644 --- a/drivers/net/wireless/ath/ath12k/core.c +++ b/drivers/net/wireless/ath/ath12k/core.c @@ -2007,7 +2007,8 @@ static struct ath12k_hw_group *ath12k_core_hw_group_assign(struct ath12k_base *a goto invalid_group; } - ab->device_id = ag->num_probed++; + ag->num_probed++; + ab->device_id = wsi->index; ag->ab[ab->device_id] = ab; ab->ag = ag; diff --git a/drivers/net/wireless/ath/ath12k/dp_mon.c b/drivers/net/wireless/ath/ath12k/dp_mon.c index db20d27b6333..fdbdad72a3c9 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 56578321e88c..beccf11eb8aa 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/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..a5eb7ff349da 100644 --- a/drivers/net/wireless/nxp/nxpwifi/scan.c +++ b/drivers/net/wireless/nxp/nxpwifi/scan.c @@ -2017,12 +2017,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/realtek/rtw89/rtw8851bu.c b/drivers/net/wireless/realtek/rtw89/rtw8851bu.c index 1e827205f254..6672ebe68f17 100644 --- a/drivers/net/wireless/realtek/rtw89/rtw8851bu.c +++ b/drivers/net/wireless/realtek/rtw89/rtw8851bu.c @@ -59,10 +59,16 @@ static const struct usb_device_id rtw_8851bu_id_table[] = { }; MODULE_DEVICE_TABLE(usb, rtw_8851bu_id_table); +static int rtw8851bu_probe(struct usb_interface *intf, + const struct usb_device_id *id) +{ + return rtw89_usb_probe(intf, id, &rtw89_8851bu_info); +} + static struct usb_driver rtw_8851bu_driver = { .name = KBUILD_MODNAME, .id_table = rtw_8851bu_id_table, - .probe = rtw89_usb_probe, + .probe = rtw8851bu_probe, .disconnect = rtw89_usb_disconnect, }; module_usb_driver(rtw_8851bu_driver); diff --git a/drivers/net/wireless/realtek/rtw89/rtw8852au.c b/drivers/net/wireless/realtek/rtw89/rtw8852au.c index 065f4e5b17af..1a2e5dfbaab3 100644 --- a/drivers/net/wireless/realtek/rtw89/rtw8852au.c +++ b/drivers/net/wireless/realtek/rtw89/rtw8852au.c @@ -73,10 +73,16 @@ static const struct usb_device_id rtw_8852au_id_table[] = { }; MODULE_DEVICE_TABLE(usb, rtw_8852au_id_table); +static int rtw8852au_probe(struct usb_interface *intf, + const struct usb_device_id *id) +{ + return rtw89_usb_probe(intf, id, &rtw89_8852au_info); +} + static struct usb_driver rtw_8852au_driver = { .name = KBUILD_MODNAME, .id_table = rtw_8852au_id_table, - .probe = rtw89_usb_probe, + .probe = rtw8852au_probe, .disconnect = rtw89_usb_disconnect, }; module_usb_driver(rtw_8852au_driver); diff --git a/drivers/net/wireless/realtek/rtw89/rtw8852bu.c b/drivers/net/wireless/realtek/rtw89/rtw8852bu.c index de79a19a2824..550fc4ac7a21 100644 --- a/drivers/net/wireless/realtek/rtw89/rtw8852bu.c +++ b/drivers/net/wireless/realtek/rtw89/rtw8852bu.c @@ -73,10 +73,16 @@ static const struct usb_device_id rtw_8852bu_id_table[] = { }; MODULE_DEVICE_TABLE(usb, rtw_8852bu_id_table); +static int rtw8852bu_probe(struct usb_interface *intf, + const struct usb_device_id *id) +{ + return rtw89_usb_probe(intf, id, &rtw89_8852bu_info); +} + static struct usb_driver rtw_8852bu_driver = { .name = KBUILD_MODNAME, .id_table = rtw_8852bu_id_table, - .probe = rtw89_usb_probe, + .probe = rtw8852bu_probe, .disconnect = rtw89_usb_disconnect, }; module_usb_driver(rtw_8852bu_driver); diff --git a/drivers/net/wireless/realtek/rtw89/rtw8852cu.c b/drivers/net/wireless/realtek/rtw89/rtw8852cu.c index 2dec9b845481..6f852f4a713e 100644 --- a/drivers/net/wireless/realtek/rtw89/rtw8852cu.c +++ b/drivers/net/wireless/realtek/rtw89/rtw8852cu.c @@ -133,10 +133,16 @@ static const struct usb_device_id rtw_8852cu_id_table[] = { }; MODULE_DEVICE_TABLE(usb, rtw_8852cu_id_table); +static int rtw8852cu_probe(struct usb_interface *intf, + const struct usb_device_id *id) +{ + return rtw89_usb_probe(intf, id, &rtw89_8852cu_info); +} + static struct usb_driver rtw_8852cu_driver = { .name = KBUILD_MODNAME, .id_table = rtw_8852cu_id_table, - .probe = rtw89_usb_probe, + .probe = rtw8852cu_probe, .disconnect = rtw89_usb_disconnect, }; module_usb_driver(rtw_8852cu_driver); diff --git a/drivers/net/wireless/realtek/rtw89/rtw8922au.c b/drivers/net/wireless/realtek/rtw89/rtw8922au.c index 56c79b1ec865..b146bd79c675 100644 --- a/drivers/net/wireless/realtek/rtw89/rtw8922au.c +++ b/drivers/net/wireless/realtek/rtw89/rtw8922au.c @@ -52,6 +52,8 @@ static const struct usb_device_id rtw_8922au_id_table[] = { .driver_info = (kernel_ulong_t)&rtw89_8922au_info }, { USB_DEVICE_AND_INTERFACE_INFO(0x0b05, 0x1bd2, 0xff, 0xff, 0xff), .driver_info = (kernel_ulong_t)&rtw89_8922au_info }, + { USB_DEVICE_AND_INTERFACE_INFO(0x0b05, 0x1d84, 0xff, 0xff, 0xff), + .driver_info = (kernel_ulong_t)&rtw89_8922au_info }, { USB_DEVICE_AND_INTERFACE_INFO(0x0bda, 0x8912, 0xff, 0xff, 0xff), .driver_info = (kernel_ulong_t)&rtw89_8922au_info }, { USB_DEVICE_AND_INTERFACE_INFO(0x0db0, 0xda0e, 0xff, 0xff, 0xff), @@ -64,6 +66,10 @@ static const struct usb_device_id rtw_8922au_id_table[] = { .driver_info = (kernel_ulong_t)&rtw89_8922au_info }, { USB_DEVICE_AND_INTERFACE_INFO(0x37ad, 0x0101, 0xff, 0xff, 0xff), .driver_info = (kernel_ulong_t)&rtw89_8922au_info }, + { USB_DEVICE_AND_INTERFACE_INFO(0x37ad, 0x0104, 0xff, 0xff, 0xff), + .driver_info = (kernel_ulong_t)&rtw89_8922au_info }, + { USB_DEVICE_AND_INTERFACE_INFO(0x37ad, 0x0106, 0xff, 0xff, 0xff), + .driver_info = (kernel_ulong_t)&rtw89_8922au_info }, { USB_DEVICE_AND_INTERFACE_INFO(0x7392, 0x3822, 0xff, 0xff, 0xff), .driver_info = (kernel_ulong_t)&rtw89_8922au_info }, { USB_DEVICE_AND_INTERFACE_INFO(0x7392, 0x4822, 0xff, 0xff, 0xff), @@ -74,10 +80,16 @@ static const struct usb_device_id rtw_8922au_id_table[] = { }; MODULE_DEVICE_TABLE(usb, rtw_8922au_id_table); +static int rtw8922au_probe(struct usb_interface *intf, + const struct usb_device_id *id) +{ + return rtw89_usb_probe(intf, id, &rtw89_8922au_info); +} + static struct usb_driver rtw_8922au_driver = { .name = KBUILD_MODNAME, .id_table = rtw_8922au_id_table, - .probe = rtw89_usb_probe, + .probe = rtw8922au_probe, .disconnect = rtw89_usb_disconnect, }; module_usb_driver(rtw_8922au_driver); diff --git a/drivers/net/wireless/realtek/rtw89/usb.c b/drivers/net/wireless/realtek/rtw89/usb.c index 22a1a988f307..8dc2c93e502e 100644 --- a/drivers/net/wireless/realtek/rtw89/usb.c +++ b/drivers/net/wireless/realtek/rtw89/usb.c @@ -1206,7 +1206,8 @@ static const struct attribute_group rtw89_usb_group = { __ATTRIBUTE_GROUPS(rtw89_usb); int rtw89_usb_probe(struct usb_interface *intf, - const struct usb_device_id *id) + const struct usb_device_id *id, + const struct rtw89_driver_info *default_info) { const struct rtw89_driver_info *info; struct rtw89_dev *rtwdev; @@ -1214,6 +1215,8 @@ int rtw89_usb_probe(struct usb_interface *intf, int ret; info = (const struct rtw89_driver_info *)id->driver_info; + if (!info) + info = default_info; rtwdev = rtw89_alloc_ieee80211_hw(&intf->dev, sizeof(struct rtw89_usb), info); diff --git a/drivers/net/wireless/realtek/rtw89/usb.h b/drivers/net/wireless/realtek/rtw89/usb.h index bdf312559743..d2af29d068f1 100644 --- a/drivers/net/wireless/realtek/rtw89/usb.h +++ b/drivers/net/wireless/realtek/rtw89/usb.h @@ -95,7 +95,8 @@ static inline struct rtw89_usb *rtw89_usb_priv(struct rtw89_dev *rtwdev) } int rtw89_usb_probe(struct usb_interface *intf, - const struct usb_device_id *id); + const struct usb_device_id *id, + const struct rtw89_driver_info *default_info); void rtw89_usb_disconnect(struct usb_interface *intf); #endif diff --git a/drivers/net/wireless/virtual/mac80211_hwsim_main.c b/drivers/net/wireless/virtual/mac80211_hwsim_main.c index b9446577ff49..ea56b87cf0ea 100644 --- a/drivers/net/wireless/virtual/mac80211_hwsim_main.c +++ b/drivers/net/wireless/virtual/mac80211_hwsim_main.c @@ -6136,7 +6136,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; } @@ -7197,7 +7197,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/nvme/host/core.c b/drivers/nvme/host/core.c index a0811b49710c..9a53914c65fc 100644 --- a/drivers/nvme/host/core.c +++ b/drivers/nvme/host/core.c @@ -3399,7 +3399,11 @@ static int nvme_init_subsystem(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id) return 0; out_put_subsystem: + if (!found) + list_del_init(&subsys->entry); + mutex_unlock(&nvme_subsystems_lock); nvme_put_subsystem(subsys); + return ret; out_unlock: mutex_unlock(&nvme_subsystems_lock); return ret; diff --git a/drivers/nvme/target/admin-cmd.c b/drivers/nvme/target/admin-cmd.c index 3704493dbec9..266a3618d81a 100644 --- a/drivers/nvme/target/admin-cmd.c +++ b/drivers/nvme/target/admin-cmd.c @@ -1338,7 +1338,7 @@ static u16 nvmet_set_feat_arbitration(struct nvmet_req *req) .hpw = (cdw11 >> 24) & 0xff, .mpw = (cdw11 >> 16) & 0xff, .lpw = (cdw11 >> 8) & 0xff, - .ab = cdw11 & 0x3, + .ab = cdw11 & 0x7, }; if (!ctrl->ops->set_feature) { @@ -1493,7 +1493,7 @@ static u16 nvmet_get_feat_arbitration(struct nvmet_req *req) ((u32)arb.hpw << 24) | ((u32)arb.mpw << 16) | ((u32)arb.lpw << 8) | - (arb.ab & 0x3)); + (arb.ab & 0x7)); return NVME_SC_SUCCESS; } diff --git a/drivers/nvme/target/auth.c b/drivers/nvme/target/auth.c index 574025730834..ccba84b1344e 100644 --- a/drivers/nvme/target/auth.c +++ b/drivers/nvme/target/auth.c @@ -135,6 +135,7 @@ u8 nvmet_setup_auth(struct nvmet_ctrl *ctrl, struct nvmet_sq *sq, bool reset) int ret = 0; struct nvmet_host_link *p; struct nvmet_host *host = NULL; + struct nvme_dhchap_key *host_key, *ctrl_key = NULL; down_read(&nvmet_config_sem); if (nvmet_is_disc_subsys(ctrl->subsys)) @@ -172,55 +173,41 @@ u8 nvmet_setup_auth(struct nvmet_ctrl *ctrl, struct nvmet_sq *sq, bool reset) goto out_unlock; } - if (host->dhchap_hash_id == ctrl->shash_id) { - pr_debug("Re-use existing hash ID %d\n", - ctrl->shash_id); - } else { - ctrl->shash_id = host->dhchap_hash_id; - } - - /* Skip the 'DHHC-1:XX:' prefix */ - nvme_auth_free_key(ctrl->host_key); - ctrl->host_key = nvme_auth_extract_key(host->dhchap_secret + 10, - host->dhchap_key_hash); - if (IS_ERR(ctrl->host_key)) { + /* + * Skip the 'DHHC-1:XX:' prefix. Keep the old keys until the new ones + * are there: a controller without a host key needs no authentication. + */ + host_key = nvme_auth_extract_key(host->dhchap_secret + 10, + host->dhchap_key_hash); + if (IS_ERR(host_key)) { ret = NVME_AUTH_DHCHAP_FAILURE_NOT_USABLE; - ctrl->host_key = NULL; - goto out_free_hash; + goto out_unlock; } + if (host->dhchap_ctrl_secret) { + ctrl_key = nvme_auth_extract_key(host->dhchap_ctrl_secret + 10, + host->dhchap_ctrl_key_hash); + if (IS_ERR(ctrl_key)) { + nvme_auth_free_key(host_key); + ret = NVME_AUTH_DHCHAP_FAILURE_NOT_USABLE; + goto out_unlock; + } + } + nvme_auth_free_key(ctrl->host_key); + ctrl->host_key = host_key; + nvme_auth_free_key(ctrl->ctrl_key); + ctrl->ctrl_key = ctrl_key; + ctrl->shash_id = host->dhchap_hash_id; #ifdef CONFIG_NVME_TARGET_AUTH_DEBUG pr_debug("%s: using hash %s key %*ph\n", __func__, ctrl->host_key->hash > 0 ? nvme_auth_hmac_name(ctrl->host_key->hash) : "none", (int)ctrl->host_key->len, ctrl->host_key->key); + if (ctrl->ctrl_key) + pr_debug("%s: using ctrl hash %s key %*ph\n", __func__, + ctrl->ctrl_key->hash > 0 ? + nvme_auth_hmac_name(ctrl->ctrl_key->hash) : "none", + (int)ctrl->ctrl_key->len, ctrl->ctrl_key->key); #endif - nvme_auth_free_key(ctrl->ctrl_key); - if (!host->dhchap_ctrl_secret) { - ctrl->ctrl_key = NULL; - goto out_unlock; - } - - ctrl->ctrl_key = nvme_auth_extract_key(host->dhchap_ctrl_secret + 10, - host->dhchap_ctrl_key_hash); - if (IS_ERR(ctrl->ctrl_key)) { - ret = NVME_AUTH_DHCHAP_FAILURE_NOT_USABLE; - ctrl->ctrl_key = NULL; - goto out_free_hash; - } -#ifdef CONFIG_NVME_TARGET_AUTH_DEBUG - pr_debug("%s: using ctrl hash %s key %*ph\n", __func__, - ctrl->ctrl_key->hash > 0 ? - nvme_auth_hmac_name(ctrl->ctrl_key->hash) : "none", - (int)ctrl->ctrl_key->len, ctrl->ctrl_key->key); -#endif -out_free_hash: - if (ret) { - if (ctrl->host_key) { - nvme_auth_free_key(ctrl->host_key); - ctrl->host_key = NULL; - } - ctrl->shash_id = 0; - } out_unlock: up_read(&nvmet_config_sem); diff --git a/drivers/nvme/target/loop.c b/drivers/nvme/target/loop.c index e579a307798b..80b67608eb15 100644 --- a/drivers/nvme/target/loop.c +++ b/drivers/nvme/target/loop.c @@ -420,6 +420,8 @@ static void nvme_loop_shutdown_ctrl(struct nvme_loop_ctrl *ctrl) static void nvme_loop_delete_ctrl_host(struct nvme_ctrl *ctrl) { nvme_loop_shutdown_ctrl(to_loop_ctrl(ctrl)); + /* Left quiesced if a failed reset has left no admin queue behind */ + nvme_unquiesce_admin_queue(ctrl); nvme_remove_admin_tag_set(ctrl); } @@ -483,9 +485,8 @@ static void nvme_loop_reset_ctrl_work(struct work_struct *work) nvme_cancel_admin_tagset(&ctrl->ctrl); nvme_loop_destroy_admin_queue(ctrl); out_disable: - nvme_remove_admin_tag_set(&ctrl->ctrl); dev_warn(ctrl->ctrl.device, "Removing after reset failure\n"); - nvme_uninit_ctrl(&ctrl->ctrl); + nvme_delete_ctrl(&ctrl->ctrl); } static const struct nvme_ctrl_ops nvme_loop_ctrl_ops = { diff --git a/drivers/nvme/target/rdma.c b/drivers/nvme/target/rdma.c index b9e39d1657d2..ff387fc47885 100644 --- a/drivers/nvme/target/rdma.c +++ b/drivers/nvme/target/rdma.c @@ -1197,13 +1197,18 @@ static void nvmet_rdma_free_dev(struct kref *ref) struct nvmet_rdma_device *ndev = container_of(ref, struct nvmet_rdma_device, ref); + nvmet_rdma_destroy_srqs(ndev); + ib_dealloc_pd(ndev->pd); + + /* + * Only delete from the device list once all RDMA resources are torn + * down because nvmet_rdma_remove_one waits for the release work only + * if the device still is on the list. + */ mutex_lock(&device_list_mutex); list_del(&ndev->entry); mutex_unlock(&device_list_mutex); - nvmet_rdma_destroy_srqs(ndev); - ib_dealloc_pd(ndev->pd); - kfree(ndev); } @@ -1694,7 +1699,7 @@ static void nvmet_rdma_queue_established(struct nvmet_rdma_queue *queue) static void __nvmet_rdma_queue_disconnect(struct nvmet_rdma_queue *queue) { - bool disconnect = false; + bool disconnect = false, live = false; unsigned long flags; pr_debug("cm_id= %p queue->state= %d\n", queue->cm_id, queue->state); @@ -1713,6 +1718,7 @@ static void __nvmet_rdma_queue_disconnect(struct nvmet_rdma_queue *queue) } fallthrough; case NVMET_RDMA_Q_LIVE: + live = queue->state == NVMET_RDMA_Q_LIVE; queue->state = NVMET_RDMA_Q_DISCONNECTING; disconnect = true; break; @@ -1722,24 +1728,34 @@ static void __nvmet_rdma_queue_disconnect(struct nvmet_rdma_queue *queue) spin_unlock_irqrestore(&queue->state_lock, flags); if (disconnect) { - rdma_disconnect(queue->cm_id); + /* + * Over iWARP rdma_disconnect() sleeps until the CM has handled + * the ESTABLISHED event of this connection. The CM handles the + * events of all connections one at a time, and our handler + * takes nvmet_rdma_queue_mutex, which callers of this function + * hold. So a queue that has not seen the event is left to the + * release work: ib_drain_qp() moves the queue pair to the error + * state, which ends the connection. + */ + if (live) + rdma_disconnect(queue->cm_id); queue_work(nvmet_wq, &queue->release_work); } } static void nvmet_rdma_queue_disconnect(struct nvmet_rdma_queue *queue) { - bool disconnect = false; - + /* + * Queue the release work with &nvmet_rdma_queue_mutex held, so that + * nvmet_rdma_remove_one() either finds the queue on the list or the + * work has already been queued. + */ mutex_lock(&nvmet_rdma_queue_mutex); if (!list_empty(&queue->queue_list)) { list_del_init(&queue->queue_list); - disconnect = true; + __nvmet_rdma_queue_disconnect(queue); } mutex_unlock(&nvmet_rdma_queue_mutex); - - if (disconnect) - __nvmet_rdma_queue_disconnect(queue); } static void nvmet_rdma_queue_connect_fail(struct rdma_cm_id *cm_id, @@ -1766,10 +1782,13 @@ static void nvmet_rdma_queue_connect_fail(struct rdma_cm_id *cm_id, * queue cm_id and/or a device bound listener cm_id (where in this * case queue will be null). * - * We registered an ib_client to handle device removal for queues, - * so we only need to handle the listening port cm_ids. In this case - * we nullify the priv to prevent double cm_id destruction and destroying - * the cm_id implicitly by returning a non-zero rc to the callout. + * The RDMA CM waits until each cm_id of the device is destroyed, so a queue + * has to go now. Our ib_client also removes the queues, but it cannot be + * relied on here: built in, it is called after the RDMA CM's client. + * + * For a listening port cm_id we nullify the priv to prevent double cm_id + * destruction and destroying the cm_id implicitly by returning a non-zero + * rc to the callout. */ static int nvmet_rdma_device_removal(struct rdma_cm_id *cm_id, struct nvmet_rdma_queue *queue) @@ -1777,11 +1796,7 @@ static int nvmet_rdma_device_removal(struct rdma_cm_id *cm_id, struct nvmet_rdma_port *port; if (queue) { - /* - * This is a queue cm_id. we have registered - * an ib_client to handle queues removal - * so don't interfere and just return. - */ + nvmet_rdma_queue_disconnect(queue); return 0; } diff --git a/drivers/nvme/target/tcp.c b/drivers/nvme/target/tcp.c index 85a10679d0a9..8788cfd813b8 100644 --- a/drivers/nvme/target/tcp.c +++ b/drivers/nvme/target/tcp.c @@ -102,6 +102,7 @@ MODULE_PARM_DESC(tls_handshake_timeout, #define NVMET_TCP_RECV_BUDGET 8 #define NVMET_TCP_SEND_BUDGET 8 #define NVMET_TCP_IO_WORK_BUDGET 64 +#define NVMET_TCP_ACCEPT_BUDGET 16 enum nvmet_tcp_send_state { NVMET_TCP_SEND_DATA_PDU, @@ -1302,6 +1303,11 @@ static int nvmet_tcp_try_recv_data(struct nvmet_tcp_queue *queue) int len, ret; while (msg_data_left(&cmd->recv_msg)) { + if (queue->tls_pskid) { + /* The last receive has used it up */ + cmd->recv_msg.msg_control = cmd->recv_cbuf; + cmd->recv_msg.msg_controllen = sizeof(cmd->recv_cbuf); + } len = sock_recvmsg(cmd->queue->sock, &cmd->recv_msg, cmd->recv_msg.msg_flags); if (len <= 0) @@ -2068,9 +2074,9 @@ static void nvmet_tcp_accept_work(struct work_struct *w) struct nvmet_tcp_port *port = container_of(w, struct nvmet_tcp_port, accept_work); struct socket *newsock; - int ret; + int ret, i; - while (true) { + for (i = 0; i < NVMET_TCP_ACCEPT_BUDGET; i++) { ret = kernel_accept(port->sock, &newsock, O_NONBLOCK); if (ret < 0) { if (ret != -EAGAIN) @@ -2079,6 +2085,9 @@ static void nvmet_tcp_accept_work(struct work_struct *w) } nvmet_tcp_alloc_queue(port, newsock); } + + /* There may be more. Come to an end for those who flush nvmet_wq. */ + queue_work(nvmet_wq, &port->accept_work); } static void nvmet_tcp_listen_data_ready(struct sock *sk) diff --git a/drivers/power/sequencing/pwrseq-pcie-m2.c b/drivers/power/sequencing/pwrseq-pcie-m2.c index a745dc81003f..5fe11e9540d1 100644 --- a/drivers/power/sequencing/pwrseq-pcie-m2.c +++ b/drivers/power/sequencing/pwrseq-pcie-m2.c @@ -270,7 +270,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); @@ -282,16 +282,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; } } @@ -492,6 +490,14 @@ static int pwrseq_pcie_m2_create_serdev(struct pwrseq_pcie_m2_ctx *ctx) 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; @@ -522,19 +528,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; @@ -543,11 +549,9 @@ 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); INIT_LIST_HEAD(&ctx->pci_devices); @@ -572,9 +576,6 @@ static int pwrseq_pcie_m2_probe(struct platform_device *pdev) 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); return ret; } @@ -586,9 +587,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 34146d6372f3..1e893565bf59 100644 --- a/drivers/power/sequencing/pwrseq-qcom-wcn.c +++ b/drivers/power/sequencing/pwrseq-qcom-wcn.c @@ -397,7 +397,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_clock.c b/drivers/ptp/ptp_clock.c index 4111342d64f0..47ffc773065a 100644 --- a/drivers/ptp/ptp_clock.c +++ b/drivers/ptp/ptp_clock.c @@ -508,6 +508,11 @@ static int unregister_vclock(struct device *dev, void *data) int ptp_clock_unregister(struct ptp_clock *ptp) { + /* + * Stop and drain virtual-clock creation and deletion before walking the + * children. Do not hold n_vclocks_mux while waiting for sysfs callbacks. + */ + ptp_vclock_remove_sysfs(ptp); if (ptp_vclock_in_use(ptp)) { device_for_each_child(&ptp->dev, NULL, unregister_vclock); } diff --git a/drivers/ptp/ptp_kvm_x86.c b/drivers/ptp/ptp_kvm_x86.c index 6cea4fe39bcf..811758bd8b0d 100644 --- a/drivers/ptp/ptp_kvm_x86.c +++ b/drivers/ptp/ptp_kvm_x86.c @@ -36,7 +36,7 @@ int kvm_arch_ptp_init(void) clock_pair = page_address(p); ret = set_memory_decrypted((unsigned long)clock_pair, 1); if (ret) { - __free_page(p); + /* The page may be left shared, so leak it. */ clock_pair = NULL; goto nofree; } @@ -68,8 +68,9 @@ int kvm_arch_ptp_init(void) void kvm_arch_ptp_exit(void) { if (cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT)) { - WARN_ON(set_memory_encrypted((unsigned long)clock_pair, 1)); - free_page((unsigned long)clock_pair); + /* Leak the page if it cannot be made private again. */ + if (!WARN_ON(set_memory_encrypted((unsigned long)clock_pair, 1))) + free_page((unsigned long)clock_pair); clock_pair = NULL; } } diff --git a/drivers/ptp/ptp_private.h b/drivers/ptp/ptp_private.h index db4039d642b4..99e7eb241336 100644 --- a/drivers/ptp/ptp_private.h +++ b/drivers/ptp/ptp_private.h @@ -81,7 +81,11 @@ struct ptp_vclock { struct hlist_node vclock_hash_node; struct cyclecounter cc; struct timecounter tc; - struct mutex lock; /* protects tc/cc */ + u64 cycles; + struct mutex lock; /* protects tc/cc and the cached sample */ + /* Owned by the auxiliary worker. */ + unsigned long retry_delay; + unsigned long refresh_deadline; }; /* @@ -169,6 +173,7 @@ extern const struct attribute_group *ptp_groups[]; int ptp_populate_pin_groups(struct ptp_clock *ptp); void ptp_cleanup_pin_groups(struct ptp_clock *ptp); +void ptp_vclock_remove_sysfs(struct ptp_clock *ptp); struct ptp_vclock *ptp_vclock_register(struct ptp_clock *pclock); void ptp_vclock_unregister(struct ptp_vclock *vclock); diff --git a/drivers/ptp/ptp_sysfs.c b/drivers/ptp/ptp_sysfs.c index 7d09256aca72..8e0e0aa09981 100644 --- a/drivers/ptp/ptp_sysfs.c +++ b/drivers/ptp/ptp_sysfs.c @@ -228,8 +228,10 @@ static ssize_t n_vclocks_store(struct device *dev, if (num > ptp->n_vclocks) { for (i = 0; i < num - ptp->n_vclocks; i++) { vclock = ptp_vclock_register(ptp); - if (!vclock) - goto out; + if (IS_ERR(vclock)) { + err = PTR_ERR(vclock); + goto err_register; + } *(ptp->vclock_index + ptp->n_vclocks + i) = vclock->clock->index; @@ -261,12 +263,24 @@ static ssize_t n_vclocks_store(struct device *dev, mutex_unlock(&ptp->n_vclocks_mux); return count; +err_register: + num = i; + if (num) + device_for_each_child_reverse(dev, &num, unregister_vclock); + for (num = 0; num < i; num++) + ptp->vclock_index[ptp->n_vclocks + num] = -1; out: mutex_unlock(&ptp->n_vclocks_mux); return err; } static DEVICE_ATTR_RW(n_vclocks); +void ptp_vclock_remove_sysfs(struct ptp_clock *ptp) +{ + if (!ptp->is_virtual_clock) + device_remove_file(&ptp->dev, &dev_attr_n_vclocks); +} + static ssize_t max_vclocks_show(struct device *dev, struct device_attribute *attr, char *page) { diff --git a/drivers/ptp/ptp_vclock.c b/drivers/ptp/ptp_vclock.c index 84cb527f59cc..e9cf4da3ed8a 100644 --- a/drivers/ptp/ptp_vclock.c +++ b/drivers/ptp/ptp_vclock.c @@ -4,6 +4,7 @@ * * Copyright 2021 NXP */ +#include #include #include #include "ptp_private.h" @@ -13,6 +14,7 @@ #define PTP_VCLOCK_FADJ_SHIFT 9 #define PTP_VCLOCK_FADJ_DENOMINATOR 15625ULL #define PTP_VCLOCK_REFRESH_INTERVAL (HZ * 2) +#define PTP_VCLOCK_RETRY_INTERVAL msecs_to_jiffies(10) /* protects vclock_hash addition/deletion */ static DEFINE_SPINLOCK(vclock_hash_lock); @@ -42,21 +44,39 @@ static void ptp_vclock_hash_del(struct ptp_vclock *vclock) synchronize_srcu(&vclock_srcu); } +/* The caller holds vclock->lock, or has not published the clock yet. */ +static int ptp_vclock_sample(struct ptp_vclock *vclock) +{ + struct ptp_clock *ptp = vclock->pclock; + struct timespec64 ts; + int err; + + err = ptp->info->getcycles64(ptp->info, &ts); + if (!err) + vclock->cycles = timespec64_to_ns(&ts); + + return err; +} + static int ptp_vclock_adjfine(struct ptp_clock_info *ptp, long scaled_ppm) { struct ptp_vclock *vclock = info_to_vclock(ptp); s64 adj; + int err; adj = (s64)scaled_ppm << PTP_VCLOCK_FADJ_SHIFT; adj = div_s64(adj, PTP_VCLOCK_FADJ_DENOMINATOR); if (mutex_lock_interruptible(&vclock->lock)) return -EINTR; - timecounter_read(&vclock->tc); - vclock->cc.mult = PTP_VCLOCK_CC_MULT + adj; + err = ptp_vclock_sample(vclock); + if (!err) { + timecounter_read(&vclock->tc); + vclock->cc.mult = PTP_VCLOCK_CC_MULT + adj; + } mutex_unlock(&vclock->lock); - return 0; + return err; } static int ptp_vclock_adjtime(struct ptp_clock_info *ptp, s64 delta) @@ -75,15 +95,16 @@ static int ptp_vclock_gettime(struct ptp_clock_info *ptp, struct timespec64 *ts) { struct ptp_vclock *vclock = info_to_vclock(ptp); - u64 ns; + int err; if (mutex_lock_interruptible(&vclock->lock)) return -EINTR; - ns = timecounter_read(&vclock->tc); + err = ptp_vclock_sample(vclock); + if (!err) + *ts = ns_to_timespec64(timecounter_read(&vclock->tc)); mutex_unlock(&vclock->lock); - *ts = ns_to_timespec64(ns); - return 0; + return err; } static int ptp_vclock_gettimex(struct ptp_clock_info *ptp, @@ -94,20 +115,18 @@ static int ptp_vclock_gettimex(struct ptp_clock_info *ptp, struct ptp_clock *pptp = vclock->pclock; struct timespec64 pts; int err; - u64 ns; - - err = pptp->info->getcyclesx64(pptp->info, &pts, sts); - if (err) - return err; if (mutex_lock_interruptible(&vclock->lock)) return -EINTR; - ns = timecounter_cyc2time(&vclock->tc, timespec64_to_ns(&pts)); - mutex_unlock(&vclock->lock); + err = pptp->info->getcyclesx64(pptp->info, &pts, sts); + if (!err) { + u64 ns = timecounter_cyc2time(&vclock->tc, timespec64_to_ns(&pts)); - *ts = ns_to_timespec64(ns); + *ts = ns_to_timespec64(ns); + } + mutex_unlock(&vclock->lock); - return 0; + return err; } static int ptp_vclock_settime(struct ptp_clock_info *ptp, @@ -115,13 +134,16 @@ static int ptp_vclock_settime(struct ptp_clock_info *ptp, { struct ptp_vclock *vclock = info_to_vclock(ptp); u64 ns = timespec64_to_ns(ts); + int err; if (mutex_lock_interruptible(&vclock->lock)) return -EINTR; - timecounter_init(&vclock->tc, &vclock->cc, ns); + err = ptp_vclock_sample(vclock); + if (!err) + timecounter_init(&vclock->tc, &vclock->cc, ns); mutex_unlock(&vclock->lock); - return 0; + return err; } static int ptp_vclock_getcrosststamp(struct ptp_clock_info *ptp, @@ -130,20 +152,18 @@ static int ptp_vclock_getcrosststamp(struct ptp_clock_info *ptp, struct ptp_vclock *vclock = info_to_vclock(ptp); struct ptp_clock *pptp = vclock->pclock; int err; - u64 ns; - - err = pptp->info->getcrosscycles(pptp->info, xtstamp); - if (err) - return err; if (mutex_lock_interruptible(&vclock->lock)) return -EINTR; - ns = timecounter_cyc2time(&vclock->tc, ktime_to_ns(xtstamp->device)); - mutex_unlock(&vclock->lock); + err = pptp->info->getcrosscycles(pptp->info, xtstamp); + if (!err) { + u64 ns = timecounter_cyc2time(&vclock->tc, ktime_to_ns(xtstamp->device)); - xtstamp->device = ns_to_ktime(ns); + xtstamp->device = ns_to_ktime(ns); + } + mutex_unlock(&vclock->lock); - return 0; + return err; } static long ptp_vclock_refresh(struct ptp_clock_info *ptp) @@ -151,8 +171,24 @@ static long ptp_vclock_refresh(struct ptp_clock_info *ptp) struct ptp_vclock *vclock = info_to_vclock(ptp); struct timespec64 ts; - ptp_vclock_gettime(&vclock->info, &ts); + /* Retry transient failures promptly, but back off during long outages. */ + if (ptp_vclock_gettime(&vclock->info, &ts)) { + unsigned long now = jiffies; + + /* Retries must not postpone the next regular refresh attempt. */ + if (!vclock->retry_delay || time_after_eq(now, vclock->refresh_deadline)) + vclock->refresh_deadline = now + PTP_VCLOCK_REFRESH_INTERVAL; + + if (!vclock->retry_delay) + vclock->retry_delay = PTP_VCLOCK_RETRY_INTERVAL; + else + vclock->retry_delay = min_t(unsigned long, + vclock->retry_delay * 2, + PTP_VCLOCK_REFRESH_INTERVAL); + return min(vclock->retry_delay, vclock->refresh_deadline - now); + } + vclock->retry_delay = 0; return PTP_VCLOCK_REFRESH_INTERVAL; } @@ -174,12 +210,9 @@ static const struct ptp_clock_info ptp_vclock_info = { static u64 ptp_vclock_read(struct cyclecounter *cc) { struct ptp_vclock *vclock = cc_to_vclock(cc); - struct ptp_clock *ptp = vclock->pclock; - struct timespec64 ts = {}; - ptp->info->getcycles64(ptp->info, &ts); - - return timespec64_to_ns(&ts); + /* The cyclecounter callback cannot report a failed PHC read. */ + return vclock->cycles; } static const struct cyclecounter ptp_vclock_cc = { @@ -192,10 +225,11 @@ static const struct cyclecounter ptp_vclock_cc = { struct ptp_vclock *ptp_vclock_register(struct ptp_clock *pclock) { struct ptp_vclock *vclock; + int err; vclock = kzalloc_obj(*vclock); if (!vclock) - return NULL; + return ERR_PTR(-ENOMEM); vclock->pclock = pclock; vclock->info = ptp_vclock_info; @@ -214,20 +248,29 @@ struct ptp_vclock *ptp_vclock_register(struct ptp_clock *pclock) mutex_init(&vclock->lock); + err = ptp_vclock_sample(vclock); + if (err) + goto free_vclock; + timecounter_init(&vclock->tc, &vclock->cc, 0); + vclock->clock = ptp_clock_register(&vclock->info, &pclock->dev); - if (IS_ERR_OR_NULL(vclock->clock)) { - kfree(vclock); - return NULL; + if (IS_ERR(vclock->clock)) { + err = PTR_ERR(vclock->clock); + goto free_vclock; } ptp_vclock_set_subclass(vclock->clock); - timecounter_init(&vclock->tc, &vclock->cc, 0); - ptp_schedule_worker(vclock->clock, PTP_VCLOCK_REFRESH_INTERVAL); + /* The initial sample predates registration; refresh without more delay. */ + ptp_schedule_worker(vclock->clock, 0); ptp_vclock_hash_add(vclock); return vclock; + +free_vclock: + kfree(vclock); + return ERR_PTR(err); } void ptp_vclock_unregister(struct ptp_vclock *vclock) @@ -283,6 +326,8 @@ ktime_t ptp_convert_timestamp(const ktime_t *hwtstamp, int vclock_index) u64 ns; ns = ktime_to_ns(*hwtstamp); + if (!ns) + return 0; srcu_idx = srcu_read_lock(&vclock_srcu); diff --git a/drivers/regulator/Kconfig b/drivers/regulator/Kconfig index 89789ac7a786..9e4d3b859ed1 100644 --- a/drivers/regulator/Kconfig +++ b/drivers/regulator/Kconfig @@ -1191,6 +1191,7 @@ config REGULATOR_QCOM_SMD_RPM config REGULATOR_QCOM_SPMI tristate "Qualcomm SPMI regulator driver" depends on SPMI || COMPILE_TEST + select REGMAP_MMIO help If you say yes to this option, support will be included for the regulators found in Qualcomm SPMI PMICs. diff --git a/drivers/regulator/mt6363-regulator.c b/drivers/regulator/mt6363-regulator.c index aa6a8eb7ac4b..e6c4bd851fef 100644 --- a/drivers/regulator/mt6363-regulator.c +++ b/drivers/regulator/mt6363-regulator.c @@ -4,7 +4,6 @@ // Copyright (c) 2025 Collabora Ltd // AngeloGioacchino Del Regno -#include #include #include #include @@ -147,7 +146,7 @@ struct mt6363_regulator_info { } #define MT6363_LDO_LINEAR_OPS(match, vreg, in_sup, vops, min, max, \ - step, buck_reg, ocp_intn) \ + step, en_reg, lp_reg, ocp_intn) \ [MT6363_ID_##vreg] = { \ .desc = { \ .name = match, \ @@ -160,13 +159,13 @@ struct mt6363_regulator_info { .n_voltages = (max - min) / step + 1, \ .min_uV = min, \ .uV_step = step, \ - .enable_reg = MT6363_RG_##buck_reg##_EN_ADDR, \ + .enable_reg = en_reg, \ .enable_mask = BIT(MT6363_RG_LDO_##vreg##_EN_BIT), \ .vsel_reg = MT6363_RG_LDO_##vreg##_VOSEL_ADDR, \ .vsel_mask = MT6363_RG_LDO_##vreg##_VOSEL_MASK, \ .of_map_mode = mt6363_map_mode, \ }, \ - .lp_mode_reg = MT6363_RG_##buck_reg##_LP_ADDR, \ + .lp_mode_reg = lp_reg, \ .lp_mode_mask = BIT(MT6363_RG_LDO_##vreg##_LP_BIT), \ .hw_lp_mode_reg = MT6363_LDO_##vreg##_HW_LP_MODE, \ .hw_lp_mode_mask = 0x4, \ @@ -176,12 +175,15 @@ struct mt6363_regulator_info { #define MT6363_LDO_L_SC(match, vreg, inp, min, max, step, buck_reg, \ ocp_intn) \ MT6363_LDO_LINEAR_OPS(match, vreg, inp, mt6363_vreg_setclr_ops, \ - min, max, step, buck_reg, ocp_intn) + min, max, step, \ + MT6363_RG_##buck_reg##_EN_ADDR, \ + MT6363_RG_##buck_reg##_LP_ADDR, ocp_intn) -#define MT6363_LDO_L(match, vreg, inp, min, max, step, buck_reg, \ - ocp_intn) \ +#define MT6363_LDO_L(match, vreg, inp, min, max, step, ocp_intn) \ MT6363_LDO_LINEAR_OPS(match, vreg, inp, mt6363_ldo_linear_ops, \ - min, max, step, buck_reg, ocp_intn) + min, max, step, \ + MT6363_RG_LDO_##vreg##_ADDR, \ + MT6363_RG_LDO_##vreg##_ADDR, ocp_intn) #define MT6363_LDO_LINEAR_CAL_OPS(match, vreg, in_sup, vops, vrnum, \ ocp_intn) \ @@ -381,7 +383,7 @@ static unsigned int mt6363_regulator_get_mode(struct regulator_dev *rdev) static int mt6363_buck_unlock(struct regmap *map, bool unlock) { - u16 buf = unlock ? MT6363_BUCK_TOP_UNLOCK_VALUE : 0; + __le16 buf = cpu_to_le16(unlock ? MT6363_BUCK_TOP_UNLOCK_VALUE : 0); return regmap_bulk_write(map, MT6363_BUCK_TOP_KEY_PROT_LO, &buf, sizeof(buf)); } @@ -482,31 +484,9 @@ static int mt6363_regulator_set_load(struct regulator_dev *rdev, int load_uA) static int mt6363_vemc_set_voltage_sel(struct regulator_dev *rdev, unsigned int sel) { - const u16 tma_unlock_key = MT6363_TMA_UNLOCK_VALUE; - const struct regulator_desc *rdesc = rdev->desc; - struct regmap *regmap = rdev->regmap; - unsigned int range, val; - int i, ret; - u16 mask; - - for (i = 0; i < rdesc->n_linear_ranges; i++) { - const struct linear_range *r = &rdesc->linear_ranges[i]; - unsigned int voltages_in_range = linear_range_values_in_range(r); - - if (sel < voltages_in_range) - break; - sel -= voltages_in_range; - } - - if (i == rdesc->n_linear_ranges) - return -EINVAL; - - ret = regmap_read(rdev->regmap, MT6363_TOP_TRAP, &val); - if (ret) - return ret; - - if (val > 1) - return -EINVAL; + const __le16 tma_unlock_key = cpu_to_le16(MT6363_TMA_UNLOCK_VALUE); + const __le16 tma_lock_key = cpu_to_le16(0); + int ret; /* Unlock TMA for writing */ ret = regmap_bulk_write(rdev->regmap, MT6363_TOP_TMA_KEY_L, @@ -514,76 +494,15 @@ static int mt6363_vemc_set_voltage_sel(struct regulator_dev *rdev, unsigned int if (ret) return ret; - /* If HW trapping value is 1, use VEMC_VOSEL_1 instead of VEMC_VOSEL_0 */ - if (val == 1) { - mask = MT6363_RG_VEMC_VOSEL_1_MASK; - sel = FIELD_PREP(MT6363_RG_VEMC_VOSEL_1_MASK, sel); - } else { - mask = rdesc->vsel_mask; - } - - sel <<= ffs(rdesc->vsel_mask) - 1; - sel += rdesc->linear_ranges[i].min_sel; - - range = rdesc->linear_range_selectors_bitfield[i]; - range <<= ffs(rdesc->vsel_range_mask) - 1; - - /* Write to the vreg calibration register for voltage finetuning */ - ret = regmap_update_bits(regmap, rdesc->vsel_range_reg, - rdesc->vsel_range_mask, range); - if (ret) - goto lock_tma; - - /* Function must return the result of this write operation */ - ret = regmap_update_bits(regmap, rdesc->vsel_reg, mask, sel); + ret = regulator_set_voltage_sel_pickable_regmap(rdev, sel); -lock_tma: /* Unconditionally re-lock TMA */ - val = 0; - regmap_bulk_write(rdev->regmap, MT6363_TOP_TMA_KEY_L, &val, 2); + regmap_bulk_write(rdev->regmap, MT6363_TOP_TMA_KEY_L, + &tma_lock_key, sizeof(tma_lock_key)); return ret; } -static int mt6363_vemc_get_voltage_sel(struct regulator_dev *rdev) -{ - const struct regulator_desc *rdesc = rdev->desc; - unsigned int vosel, trap, calsel; - int vcal, vsel, range, ret; - - ret = regmap_read(rdev->regmap, rdesc->vsel_reg, &vosel); - if (ret) - return ret; - - ret = regmap_read(rdev->regmap, rdesc->vsel_range_reg, &calsel); - if (ret) - return ret; - - calsel &= rdesc->vsel_range_mask; - for (range = 0; range < rdesc->n_linear_ranges; range++) - if (rdesc->linear_range_selectors_bitfield[range] != calsel) - break; - - if (range == rdesc->n_linear_ranges) - return -EINVAL; - - ret = regmap_read(rdev->regmap, MT6363_TOP_TRAP, &trap); - if (ret) - return ret; - - /* If HW trapping value is 1, use VEMC_VOSEL_1 instead of VEMC_VOSEL_0 */ - if (trap > 1) - return -EINVAL; - else if (trap == 1) - vsel = FIELD_GET(MT6363_RG_VEMC_VOSEL_1_MASK, vosel); - else - vsel = vosel & rdesc->vsel_mask; - - vcal = linear_range_values_in_range_array(rdesc->linear_ranges, range); - - return vsel + vcal; -} - static int mt6363_va15_set_voltage_sel(struct regulator_dev *rdev, unsigned int sel) { struct regmap *regmap = rdev->regmap; @@ -696,7 +615,7 @@ static const struct regulator_ops mt6363_ldo_vemc_ops = { .list_voltage = regulator_list_voltage_pickable_linear_range, .map_voltage = regulator_map_voltage_pickable_linear_range, .set_voltage_sel = mt6363_vemc_set_voltage_sel, - .get_voltage_sel = mt6363_vemc_get_voltage_sel, + .get_voltage_sel = regulator_get_voltage_sel_pickable_regmap, .set_voltage_time_sel = regulator_set_voltage_time_sel, .enable = regulator_enable_regmap, .disable = regulator_disable_regmap, @@ -754,10 +673,10 @@ static struct mt6363_regulator_info mt6363_regulators[] = { MT6363_LDO_VT("vio0p75", VIO075, "vs1-ldo1", 5, 36), MT6363_LDO_VT("vio18", VIO18, "vs1-ldo2", 3, 35), MT6363_LDO_VT("vm18", VM18, "vs1-ldo1", 4, 40), - MT6363_LDO_L("vsram-apu", VSRAM_APU, "vs3-ldo1", 400000, 1193750, 6250, BUCK1, 30), - MT6363_LDO_L("vsram-cpub", VSRAM_CPUB, "vs2-ldo1", 400000, 1193750, 6250, BUCK1, 27), - MT6363_LDO_L("vsram-cpum", VSRAM_CPUM, "vs2-ldo1", 400000, 1193750, 6250, BUCK1, 28), - MT6363_LDO_L("vsram-cpul", VSRAM_CPUL, "vs2-ldo2", 400000, 1193750, 6250, BUCK1, 29), + MT6363_LDO_L("vsram-apu", VSRAM_APU, "vs3-ldo1", 400000, 1193750, 6250, 30), + MT6363_LDO_L("vsram-cpub", VSRAM_CPUB, "vs2-ldo1", 400000, 1193750, 6250, 27), + MT6363_LDO_L("vsram-cpum", VSRAM_CPUM, "vs2-ldo1", 400000, 1193750, 6250, 28), + MT6363_LDO_L("vsram-cpul", VSRAM_CPUL, "vs2-ldo2", 400000, 1193750, 6250, 29), MT6363_LDO_L_SC("vsram-digrf", VSRAM_DIGRF, "vs3-ldo1", 400000, 1193750, 6250, BUCK1, 23), MT6363_LDO_L_SC("vsram-mdfe", VSRAM_MDFE, "vs3-ldo1", 400000, 1193750, 6250, BUCK1, 24), MT6363_LDO_L_SC("vsram-modem", VSRAM_MODEM, "vs3-ldo2", 400000, 1193750, 6250, BUCK1, 25), @@ -793,6 +712,30 @@ static int mt6363_backup_op_setting(struct regmap *map, struct mt6363_regulator_ return 0; } +static int mt6363_vemc_select_bank(struct regmap *map, struct regulator_desc *desc) +{ + unsigned int trap; + int ret; + + ret = regmap_read(map, MT6363_TOP_TRAP, &trap); + if (ret) + return ret; + + /* The hardware trap value selects which VEMC voltage controls are used */ + switch (trap) { + case 0: + desc->vsel_reg = MT6363_RG_VEMC_VOCAL_ADDR; + desc->vsel_range_mask = MT6363_RG_VEMC_VOSEL_MASK; + return 0; + case 1: + desc->vsel_reg = MT6363_RG_VEMC_VOCAL_1_ADDR; + desc->vsel_range_mask = MT6363_RG_VEMC_VOSEL_1_MASK; + return 0; + default: + return -EINVAL; + } +} + static void mt6363_irq_remove(void *data) { int *virq = data; @@ -811,7 +754,7 @@ static struct regmap *mt6363_spmi_register_regmap(struct device *dev) { struct regmap_config mt6363_regmap_config = { .reg_bits = 16, - .val_bits = 16, + .val_bits = 8, .max_register = 0x1f90, .fast_io = true, }; @@ -877,6 +820,11 @@ static int mt6363_regulator_probe(struct platform_device *pdev) */ regmap_read(config.regmap, MT6363_TOP_TRAP, &val); + ret = mt6363_vemc_select_bank(config.regmap, + &mt6363_regulators[MT6363_ID_VEMC].desc); + if (ret) + return dev_err_probe(dev, ret, "Failed to select VEMC bank\n"); + interrupt_parent = of_irq_find_parent(dev->of_node); if (!interrupt_parent) return dev_err_probe(dev, -EINVAL, "Cannot find IRQ parent\n"); diff --git a/drivers/regulator/qcom_spmi-regulator.c b/drivers/regulator/qcom_spmi-regulator.c index c1a41ce70b36..a04ddb1eac94 100644 --- a/drivers/regulator/qcom_spmi-regulator.c +++ b/drivers/regulator/qcom_spmi-regulator.c @@ -12,13 +12,13 @@ #include #include #include +#include #include #include #include #include #include #include -#include #include /* Pin control enable input pins. */ @@ -1335,6 +1335,14 @@ static irqreturn_t spmi_regulator_vs_ocp_isr(int irq, void *data) static struct regmap *saw_regmap; +static const struct regmap_config saw_regmap_config = { + .name = "saw", + .reg_bits = 32, + .val_bits = 32, + .reg_stride = 4, + .use_raw_spinlock = true, +}; + static void spmi_saw_set_vdd(void *data) { u32 vctl, data3, avs_ctl, pmic_sts; @@ -2504,7 +2512,8 @@ static int qcom_spmi_regulator_probe(struct platform_device *pdev) const char *name; struct device *dev = &pdev->dev; struct device_node *node = pdev->dev.of_node; - struct device_node *syscon, *reg_node; + struct device_node *saw, *reg_node; + void __iomem *saw_base; struct property *reg_prop; int ret, lenp; struct list_head *vreg_list; @@ -2523,12 +2532,22 @@ static int qcom_spmi_regulator_probe(struct platform_device *pdev) if (!reg) return -ENODEV; - syscon = of_parse_phandle(node, "qcom,saw-reg", 0); - if (syscon) { - saw_regmap = syscon_node_to_regmap(syscon); - of_node_put(syscon); - if (IS_ERR(saw_regmap)) - dev_err(dev, "ERROR reading SAW regmap\n"); + saw = of_parse_phandle(node, "qcom,saw-reg", 0); + if (saw) { + saw_base = devm_of_iomap(dev, saw, 0, NULL); + of_node_put(saw); + if (IS_ERR(saw_base)) + return dev_err_probe(dev, PTR_ERR(saw_base), + "failed to map the SAW\n"); + + saw_regmap = devm_regmap_init_mmio(dev, saw_base, + &saw_regmap_config); + if (IS_ERR(saw_regmap)) { + ret = PTR_ERR(saw_regmap); + saw_regmap = NULL; + return dev_err_probe(dev, ret, + "failed to set the SAW regmap up\n"); + } } for (; reg->name; reg++) { diff --git a/drivers/s390/block/dasd_eckd.c b/drivers/s390/block/dasd_eckd.c index 9d1b11020b4e..d3de0d97cca2 100644 --- a/drivers/s390/block/dasd_eckd.c +++ b/drivers/s390/block/dasd_eckd.c @@ -2780,7 +2780,8 @@ dasd_eckd_build_check_tcw(struct dasd_device *base, struct format_data_t *fdata, return cqr; out_err: - dasd_sfree_request(cqr, startdev); + start_priv->count--; + dasd_ffree_request(cqr, startdev); return ERR_PTR(rc); } diff --git a/drivers/s390/block/dasd_ioctl.c b/drivers/s390/block/dasd_ioctl.c index 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/scsi/aha1542.c b/drivers/scsi/aha1542.c index 93dab19c1cb9..1cd85da47cc9 100644 --- a/drivers/scsi/aha1542.c +++ b/drivers/scsi/aha1542.c @@ -271,8 +271,6 @@ static void aha1542_free_cmd(struct scsi_cmnd *cmd) buf += bv.bv_len; } } - - scsi_dma_unmap(cmd); } static irqreturn_t aha1542_interrupt(int irq, void *dev_id) diff --git a/drivers/scsi/aic7xxx/aic7xxx_core.c b/drivers/scsi/aic7xxx/aic7xxx_core.c index 8ad82171e925..af6115bfb280 100644 --- a/drivers/scsi/aic7xxx/aic7xxx_core.c +++ b/drivers/scsi/aic7xxx/aic7xxx_core.c @@ -1097,7 +1097,7 @@ ahc_handle_seqint(struct ahc_softc *ahc, u_int intstat) sc->byte2 = SCB_GET_LUN(scb) << 5; sc->unused[0] = 0; sc->unused[1] = 0; - sc->length = sg->len; + sc->length = ahc_get_sense_bufsize(ahc, scb); sc->control = 0; /* diff --git a/drivers/scsi/mpt3sas/mpt3sas_scsih.c b/drivers/scsi/mpt3sas/mpt3sas_scsih.c index 0e12009a87f6..a77bbc3d2b66 100644 --- a/drivers/scsi/mpt3sas/mpt3sas_scsih.c +++ b/drivers/scsi/mpt3sas/mpt3sas_scsih.c @@ -5401,23 +5401,23 @@ _scsih_setup_eedp(struct MPT3SAS_ADAPTER *ioc, struct scsi_cmnd *scmd, static void _scsih_eedp_error_handling(struct scsi_cmnd *scmd, u16 ioc_status) { - u8 ascq; + u16 sense_code; switch (ioc_status) { case MPI2_IOCSTATUS_EEDP_GUARD_ERROR: - ascq = 0x01; + sense_code = LOGICAL_BLOCK_GUARD_CHECK_FAILED; break; case MPI2_IOCSTATUS_EEDP_APP_TAG_ERROR: - ascq = 0x02; + sense_code = LOGICAL_BLOCK_APPLICATION_TAG_CHECK_FAILED; break; case MPI2_IOCSTATUS_EEDP_REF_TAG_ERROR: - ascq = 0x03; + sense_code = LOGICAL_BLOCK_REFERENCE_TAG_CHECK_FAILED; break; default: - ascq = 0x00; + sense_code = ID_CRC_OR_ECC_ERROR; break; } - scsi_build_sense(scmd, 0, ILLEGAL_REQUEST, 0x10, ascq); + scsi_set_sense(scmd, 0, ILLEGAL_REQUEST, sense_code); set_host_byte(scmd, DID_ABORT); } @@ -5474,7 +5474,8 @@ static enum scsi_qc_status scsih_qcmd(struct Scsi_Host *shost, if (handle == MPT3SAS_INVALID_DEVICE_HANDLE || sas_device_priv_data->block) { if (scsi_get_host_state(scmd->device->host) == SHOST_RECOVERY && scmd->cmnd[0] == TEST_UNIT_READY) { - scsi_build_sense(scmd, 0, UNIT_ATTENTION, 0x29, 0x07); + scsi_set_sense(scmd, 0, UNIT_ATTENTION, + I_T_NEXUS_LOSS_OCCURRED); scsi_done(scmd); return 0; } @@ -5986,7 +5987,7 @@ _scsih_smart_predicted_fault(struct MPT3SAS_ADAPTER *ioc, u16 handle) event_data = (Mpi2EventDataSasDeviceStatusChange_t *) event_reply->EventData; event_data->ReasonCode = MPI2_EVENT_SAS_DEV_STAT_RC_SMART_DATA; - event_data->ASC = 0x5D; + event_data->ASC = ASC_FAILURE_PREDICTION_THRESHOLD_EXCEEDED; event_data->DevHandle = cpu_to_le16(handle); event_data->SASAddress = cpu_to_le64(sas_target_priv_data->sas_address); mpt3sas_ctl_add_to_event_log(ioc, event_reply); @@ -6109,8 +6110,7 @@ _scsih_io_done(struct MPT3SAS_ADAPTER *ioc, u16 smid, u8 msix_index, u32 reply) le32_to_cpu(mpi_reply->SenseCount)); memcpy(scmd->sense_buffer, sense_data, sz); _scsih_normalize_sense(scmd->sense_buffer, &data); - /* failure prediction threshold exceeded */ - if (data.asc == 0x5D) + if (data.asc == ASC_FAILURE_PREDICTION_THRESHOLD_EXCEEDED) _scsih_smart_predicted_fault(ioc, le16_to_cpu(mpi_reply->DevHandle)); mpt3sas_trigger_scsi(ioc, data.skey, data.asc, data.ascq); @@ -6199,8 +6199,8 @@ _scsih_io_done(struct MPT3SAS_ADAPTER *ioc, u16 smid, u8 msix_index, u32 reply) else if (!xfer_cnt && scmd->cmnd[0] == REPORT_LUNS) { mpi_reply->SCSIState = MPI2_SCSI_STATE_AUTOSENSE_VALID; mpi_reply->SCSIStatus = SAM_STAT_CHECK_CONDITION; - scsi_build_sense(scmd, 0, ILLEGAL_REQUEST, - 0x20, 0); + scsi_set_sense(scmd, 0, ILLEGAL_REQUEST, + INVALID_COMMAND_OP_CODE); } break; @@ -7691,38 +7691,43 @@ _scsih_determine_disposition(struct MPT3SAS_ADAPTER *ioc, if (check_sense) { _scsih_normalize_sense(transfer_packet->sense, &sense_info); - if (sense_info.skey == UNIT_ATTENTION) + if (sense_info.skey == UNIT_ATTENTION) { rc = DEVICE_RETRY_UA; - else if (sense_info.skey == NOT_READY) { - /* medium isn't present */ - if (sense_info.asc == 0x3a) + } else if (sense_info.skey == NOT_READY) { + if (sense_info.asc == ASC_MEDIUM_NOT_PRESENT) { rc = DEVICE_READY; - /* LOGICAL UNIT NOT READY */ - else if (sense_info.asc == 0x04) { - if (sense_info.ascq == 0x03 || - sense_info.ascq == 0x0b || - sense_info.ascq == 0x0c) { + } else if (sense_info.asc == ASC_LU_NOT_READY) { + u16 scode = scsi_sense_code(sense_info.asc, + sense_info.ascq); + + if (scode == LU_NOT_READY_SANITIZE_IN_PROGRESS) + rc = DEVICE_READY; + else if (scode == + LU_NOT_READY_MANUAL_INTERVENTION_REQUIRED || + scode == + LU_NOT_ACCESSIBLE_TARGET_PORT_IN_STANDBY_STATE || + scode == + LU_NOT_ACCESSIBLE_TARGET_PORT_IN_UNAVAILABLE_STATE) rc = DEVICE_ERROR; - } else + else rc = DEVICE_START_UNIT; - } - /* LOGICAL UNIT HAS NOT SELF-CONFIGURED YET */ - else if (sense_info.asc == 0x3e && !sense_info.ascq) + } else if (sense_info.asc == + ASC_LU_HAS_NOT_SELF_CONFIGURED_YET && + !sense_info.ascq) { rc = DEVICE_START_UNIT; + } } else if (sense_info.skey == ILLEGAL_REQUEST && - transfer_packet->cdb[0] == REPORT_LUNS) { + transfer_packet->cdb[0] == REPORT_LUNS) { rc = DEVICE_READY; } else if (sense_info.skey == MEDIUM_ERROR) { - - /* medium is corrupt, lets add the device so - * users can collect some info as needed + /* + * medium is corrupt, lets add the device so users can + * collect some info as needed */ - - if (sense_info.asc == 0x31) + if (sense_info.asc == ASC_MEDIUM_FORMAT_CORRUPTED) rc = DEVICE_READY; } else if (sense_info.skey == HARDWARE_ERROR) { - /* Defect List Error, still add the device */ - if (sense_info.asc == 0x19) + if (sense_info.asc == ASC_DEFECT_LIST_ERROR) rc = DEVICE_READY; } } diff --git a/drivers/scsi/scsi_debug.c b/drivers/scsi/scsi_debug.c index 8290feadc212..2b8d83e598cc 100644 --- a/drivers/scsi/scsi_debug.c +++ b/drivers/scsi/scsi_debug.c @@ -4183,6 +4183,8 @@ static int do_device_access(struct sdeb_store_info *sip, struct scsi_cmnd *scp, u64 block; enum dma_data_direction dir; struct scsi_data_buffer *sdb = &scp->sdb; + struct scsi_device *sdp = scp->device; + struct sdebug_dev_info *devip = (struct sdebug_dev_info *)sdp->hostdata; u8 *fsp; int i, total = 0; @@ -4210,6 +4212,25 @@ static int do_device_access(struct sdeb_store_info *sip, struct scsi_cmnd *scp, fsp = sip->storep; + /* + * A write to a sequential write required zone has to end on a physical + * block boundary, so if the data-out buffer does not hold all of the + * data that the command asks for, write up to the last whole physical + * block that it does hold. What is left over is reported as part of + * the residual. + */ + if (do_write && sdebug_dev_is_zoned(devip)) { + struct sdeb_zone_state *zsp = zbc_zone(devip, lba); + + if (zsp->z_type == ZBC_ZTYPE_SWR) { + u32 avail = (sdb->length - sg_skip) + >> ilog2(sdebug_sector_size); + + if (avail < num) + num = round_down(avail, 1U << sdebug_physblk_exp); + } + } + block = do_div(lba, sdebug_store_sectors); /* Only allow 1x atomic write or multiple non-atomic writes at any given time */ @@ -5013,6 +5034,9 @@ static int resp_write_dt0(struct scsi_cmnd *scp, struct sdebug_dev_info *devip) "%s: write: cdb indicated=%u, IO sent=%d bytes\n", my_name, num * sdebug_sector_size, ret); + if (ret < scsi_bufflen(scp)) + scsi_set_resid(scp, scsi_bufflen(scp) - ret); + if (unlikely((sdebug_opts & SDEBUG_OPT_RECOV_DIF_DIX) && atomic_read(&sdeb_inject_pending))) { if (sdebug_opts & SDEBUG_OPT_RECOVERED_ERR) { @@ -5085,8 +5109,10 @@ static int resp_write_scat(struct scsi_cmnd *scp, "Unprotected WR to DIF device\n"); } } - if ((num_lrd == 0) || (bt_len == 0)) + if (num_lrd == 0 || bt_len == 0) { + scsi_set_resid(scp, scsi_bufflen(scp)); return 0; /* T10 says these do-nothings are not errors */ + } if (lbdof == 0) { if (sdebug_verbose) sdev_printk(KERN_INFO, scp->device, @@ -5182,6 +5208,8 @@ static int resp_write_scat(struct scsi_cmnd *scp, if (unlikely((sdebug_opts & SDEBUG_OPT_RECOV_DIF_DIX) && atomic_read(&sdeb_inject_pending))) { + /* This range has been written */ + sg_off += num_by; if (sdebug_opts & SDEBUG_OPT_RECOVERED_ERR) { mk_sense_buffer(scp, RECOVERED_ERROR, FAILURE_PREDICTION_THRESHOLD_EXCEEDED); @@ -5207,6 +5235,13 @@ static int resp_write_scat(struct scsi_cmnd *scp, } ret = 0; err_out_unlock: + /* + * sg_off counts what the command asked for, which can exceed the + * buffer: lbdof is not validated against it, and a range is counted + * in full even if do_device_access() copied less. + */ + if (scsi_bufflen(scp) > sg_off) + scsi_set_resid(scp, scsi_bufflen(scp) - sg_off); sdeb_meta_write_unlock(sip); err_out: kfree(lrdp); @@ -6082,6 +6117,9 @@ static int resp_atomic_write(struct scsi_cmnd *scp, return DID_ERROR << 16; if (unlikely(ret != len * sdebug_sector_size)) return DID_ERROR << 16; + + if (ret < scsi_bufflen(scp)) + scsi_set_resid(scp, scsi_bufflen(scp) - ret); return 0; } @@ -8723,6 +8761,7 @@ static void __exit scsi_debug_exit(void) sdebug_erase_all_stores(false); xa_destroy(per_store_ap); + async_synchronize_full_domain(&sdebug_async_domain); debugfs_remove(sdebug_debugfs_root); } diff --git a/drivers/scsi/scsi_scan.c b/drivers/scsi/scsi_scan.c index 6cd77b0592e4..53a0af2104ef 100644 --- a/drivers/scsi/scsi_scan.c +++ b/drivers/scsi/scsi_scan.c @@ -2156,14 +2156,13 @@ struct scsi_device *scsi_get_pseudo_sdev(struct Scsi_Host *shost) goto out; sdev = scsi_alloc_sdev(starget, U64_MAX, NULL); - if (!sdev) { - scsi_target_reap(starget); + if (!sdev) goto put_target; - } sdev->borken = 0; put_target: + scsi_target_reap(starget); /* See also the get_device(dev) call in scsi_alloc_target(). */ put_device(&starget->dev); diff --git a/drivers/soundwire/dmi-quirks.c b/drivers/soundwire/dmi-quirks.c index 62fa64b22412..0daa877cd905 100644 --- a/drivers/soundwire/dmi-quirks.c +++ b/drivers/soundwire/dmi-quirks.c @@ -111,6 +111,25 @@ static const struct adr_remap ghost_realtek[] = { {} }; +/* + * The Microsoft Surface Pro 11 (Intel) describes its single physical RT1320 + * amplifier twice on link 0, as two _ADR entries differing only in SDCA class + * id and sharing the same unique id. Only the class 1 entry enumerates; the + * class 0 entry is a ghost. + * + * Matched on the product SKU rather than the product name: a later batch of the + * same model could carry a different RT1320 version, which would change the + * _ADR. Keying on the SKU keeps this remap to the hardware it was verified on. + */ +static const struct adr_remap microsoft_sp11_intel[] = { + /* ghost rt1320 on link0 */ + { + 0x000030025d132000ull, + 0x0000000000000000ull + }, + {} +}; + static const struct dmi_system_id adr_remap_quirk_table[] = { /* TGL devices */ { @@ -221,6 +240,13 @@ static const struct dmi_system_id adr_remap_quirk_table[] = { }, .driver_data = (void *)ghost_realtek, }, + { + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"), + DMI_MATCH(DMI_PRODUCT_NAME, "83QM"), + }, + .driver_data = (void *)ghost_realtek, + }, { .matches = { DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"), @@ -235,6 +261,22 @@ static const struct dmi_system_id adr_remap_quirk_table[] = { }, .driver_data = (void *)ghost_realtek, }, + { + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"), + DMI_MATCH(DMI_PRODUCT_NAME, "83U9"), + }, + .driver_data = (void *)ghost_realtek, + }, + /* LNL devices */ + { + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), + DMI_EXACT_MATCH(DMI_PRODUCT_SKU, + "Surface_Pro_11th_Edition_With_Intel_For_Business_2103") + }, + .driver_data = (void *)microsoft_sp11_intel, + }, {} }; diff --git a/drivers/spi/spi-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-cadence-quadspi.c b/drivers/spi/spi-cadence-quadspi.c index 5a5f1a852cbe..c31e225f240a 100644 --- a/drivers/spi/spi-cadence-quadspi.c +++ b/drivers/spi/spi-cadence-quadspi.c @@ -955,11 +955,11 @@ static int cqspi_versal_indirect_read_dma(struct cqspi_flash_pdata *f_pdata, writel(CQSPI_REG_VERSAL_DMA_DST_CTRL_VAL, reg_base + CQSPI_REG_VERSAL_DMA_DST_CTRL); + reinit_completion(&cqspi->transfer_complete); + writel(CQSPI_REG_INDIRECTRD_START_MASK, reg_base + CQSPI_REG_INDIRECTRD); - reinit_completion(&cqspi->transfer_complete); - if (!wait_for_completion_timeout(&cqspi->transfer_complete, msecs_to_jiffies(max_t(size_t, bytes_to_dma, 500)))) { ret = -ETIMEDOUT; diff --git a/drivers/spi/spi-pic32-sqi.c b/drivers/spi/spi-pic32-sqi.c index 5d3921e29461..35f0c60a31d6 100644 --- a/drivers/spi/spi-pic32-sqi.c +++ b/drivers/spi/spi-pic32-sqi.c @@ -297,7 +297,7 @@ static int pic32_sqi_one_transfer(struct pic32_sqi *sqi, /* get ring descriptor */ rdesc = ring_desc_get(sqi); if (!rdesc) - break; + return -ENOMEM; bd = rdesc->bd; @@ -387,6 +387,7 @@ static int pic32_sqi_one_message(struct spi_controller *host, ret = pic32_sqi_one_transfer(sqi, msg, xfer); if (ret) { dev_err(&spi->dev, "xfer %p err\n", xfer); + msg->status = ret; goto xfer_out; } } diff --git a/drivers/spi/spi-tegra210-quad.c b/drivers/spi/spi-tegra210-quad.c index 8ede864c3d3c..405c89e4e8f2 100644 --- a/drivers/spi/spi-tegra210-quad.c +++ b/drivers/spi/spi-tegra210-quad.c @@ -215,6 +215,17 @@ struct tegra_qspi { bool is_packed; bool use_dma; + /* + * Set while a streaming mapping created by + * tegra_qspi_dma_map_xfer() is outstanding, together with the + * length that was handed to dma_map_single(). is_curr_dma_xfer + * only records that the last armed chunk took the DMA path, + * which is not the same thing: a chunk whose mapping failed + * leaves the DMA path flagged with nothing mapped. + */ + bool is_dma_mapped; + unsigned int dma_map_len; + u32 command1_reg; u32 dma_control_reg; u32 def_command1_reg; @@ -584,24 +595,32 @@ static int tegra_qspi_dma_map_xfer(struct tegra_qspi *tqspi, struct spi_transfer if (t->rx_buf) { t->rx_dma = dma_map_single(tqspi->rx_dma_dev, (void *)rx_buf, len, DMA_FROM_DEVICE); if (dma_mapping_error(tqspi->rx_dma_dev, t->rx_dma)) { - dma_unmap_single(tqspi->tx_dma_dev, t->tx_dma, len, DMA_TO_DEVICE); + if (t->tx_buf) + dma_unmap_single(tqspi->tx_dma_dev, t->tx_dma, + len, DMA_TO_DEVICE); return -ENOMEM; } } + tqspi->dma_map_len = len; + tqspi->is_dma_mapped = true; + return 0; } static void tegra_qspi_dma_unmap_xfer(struct tegra_qspi *tqspi, struct spi_transfer *t) { - unsigned int len; - - len = DIV_ROUND_UP(tqspi->curr_dma_words * tqspi->bytes_per_word, 4) * 4; + if (!tqspi->is_dma_mapped) + return; if (t->tx_buf) - dma_unmap_single(tqspi->tx_dma_dev, t->tx_dma, len, DMA_TO_DEVICE); + dma_unmap_single(tqspi->tx_dma_dev, t->tx_dma, + tqspi->dma_map_len, DMA_TO_DEVICE); if (t->rx_buf) - dma_unmap_single(tqspi->rx_dma_dev, t->rx_dma, len, DMA_FROM_DEVICE); + dma_unmap_single(tqspi->rx_dma_dev, t->rx_dma, + tqspi->dma_map_len, DMA_FROM_DEVICE); + + tqspi->is_dma_mapped = false; } static int tegra_qspi_start_dma_based_transfer(struct tegra_qspi *tqspi, struct spi_transfer *t) @@ -1243,10 +1262,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); @@ -1360,8 +1381,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 96cdaf1b3697..bbc1edbd3b00 100644 --- a/drivers/spi/spi-virtio.c +++ b/drivers/spi/spi-virtio.c @@ -319,10 +319,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); } @@ -351,21 +349,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); @@ -419,6 +422,7 @@ static struct virtio_driver virtio_spi_driver = { }, .id_table = virtio_spi_id_table, .probe = virtio_spi_probe, + .remove = virtio_spi_remove, }; module_virtio_driver(virtio_spi_driver); diff --git a/drivers/spi/spi.c b/drivers/spi/spi.c index 172141650b64..b20116527923 100644 --- a/drivers/spi/spi.c +++ b/drivers/spi/spi.c @@ -2983,9 +2983,9 @@ EXPORT_SYMBOL_GPL(devm_spi_new_ancillary_device); #ifdef CONFIG_ACPI struct acpi_spi_lookup { struct spi_controller *ctlr; + acpi_handle device_handle; u32 max_speed_hz; u32 mode; - int irq; u8 bits_per_word; u8 chip_select; int n; @@ -3077,7 +3077,7 @@ static int acpi_spi_add_resource(struct acpi_resource *ares, void *data) if (lookup->index != -1 && lookup->n++ != lookup->index) return 1; - status = acpi_get_handle(NULL, + status = acpi_get_handle(lookup->device_handle, sb->resource_source.string_ptr, &parent_handle); @@ -3128,17 +3128,25 @@ static int acpi_spi_add_resource(struct acpi_resource *ares, void *data) if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH) lookup->mode |= SPI_CS_HIGH; } - } else if (lookup->irq < 0) { - struct resource r; - - if (acpi_dev_resource_interrupt(ares, 0, &r)) - lookup->irq = r.start; } /* Always tell the ACPI core to skip this resource */ return 1; } +static int acpi_spi_add_irq_resource(struct acpi_resource *ares, void *data) +{ + int *irq = data; + struct resource r; + + if (*irq < 0 && ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS && + acpi_dev_resource_interrupt(ares, 0, &r)) + *irq = r.start; + + /* Always tell the ACPI core to skip this resource */ + return 1; +} + /** * acpi_spi_device_alloc - Allocate a spi device, and fill it in with ACPI information * @ctlr: controller to which the spi device belongs @@ -3163,13 +3171,14 @@ struct spi_device *acpi_spi_device_alloc(struct spi_controller *ctlr, struct list_head resource_list; struct acpi_spi_lookup lookup = {}; struct spi_device *spi; + int irq = -1; int ret; if (!ctlr && index == -1) return ERR_PTR(-EINVAL); lookup.ctlr = ctlr; - lookup.irq = -1; + lookup.device_handle = acpi_device_handle(adev); lookup.index = index; lookup.n = 0; @@ -3192,6 +3201,19 @@ struct spi_device *acpi_spi_device_alloc(struct spi_controller *ctlr, if (!lookup.max_speed_hz) return ERR_PTR(-ENODEV); + /* + * Only look up the IRQ once we know this is an SPI device for us. + * Parsing an interrupt resource maps its GSI, which must not be done + * for every unrelated ACPI device walked during enumeration. + */ + INIT_LIST_HEAD(&resource_list); + ret = acpi_dev_get_resources(adev, &resource_list, + acpi_spi_add_irq_resource, &irq); + if (ret < 0) + return ERR_PTR(ret); + + acpi_dev_free_resource_list(&resource_list); + spi = spi_alloc_device(lookup.ctlr); if (!spi) { dev_err(&lookup.ctlr->dev, "failed to allocate SPI device for %s\n", @@ -3204,7 +3226,7 @@ struct spi_device *acpi_spi_device_alloc(struct spi_controller *ctlr, ACPI_COMPANION_SET(&spi->dev, adev); spi->max_speed_hz = lookup.max_speed_hz; spi->mode |= lookup.mode; - spi->irq = lookup.irq; + spi->irq = irq; spi->bits_per_word = lookup.bits_per_word; /* * By default spi->chip_select[0] will hold the physical CS number, diff --git a/drivers/target/target_core_pr.c b/drivers/target/target_core_pr.c index 25b1bcacc0c8..ca1a2802aa22 100644 --- a/drivers/target/target_core_pr.c +++ b/drivers/target/target_core_pr.c @@ -3226,10 +3226,11 @@ core_scsi3_emulate_pro_register_and_move(struct se_cmd *cmd, u64 res_key, transport_kunmap_data_sg(cmd); buf = NULL; - if ((tid_len + 24) != cmd->data_length) { - pr_err("SPC-3 PR: Illegal tid_len: %u + 24 byte header" - " does not equal CDB data_length: %u\n", tid_len, - cmd->data_length); + /* TransportID is at least 24 bytes. buf[24] is its first byte. */ + if (tid_len < 24 || + tid_len != cmd->data_length - 24) { + pr_err("SPC-3 PR: Illegal tid_len: %u for data_length: %u\n", + tid_len, cmd->data_length); ret = TCM_INVALID_PARAMETER_LIST; goto out_put_pr_reg; } diff --git a/drivers/thunderbolt/stream.c b/drivers/thunderbolt/stream.c index 988765c98c8c..ef0960cf303a 100644 --- a/drivers/thunderbolt/stream.c +++ b/drivers/thunderbolt/stream.c @@ -630,6 +630,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 2e7adf6a410c..5e3e7d0a4e63 100644 --- a/drivers/tty/serial/8250/8250_exar.c +++ b/drivers/tty/serial/8250/8250_exar.c @@ -1180,7 +1180,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_lpss.c b/drivers/tty/serial/8250/8250_lpss.c index 325e587ae2c4..aaf50ac1aee5 100644 --- a/drivers/tty/serial/8250/8250_lpss.c +++ b/drivers/tty/serial/8250/8250_lpss.c @@ -82,6 +82,9 @@ static void byt_set_termios(struct uart_port *p, struct ktermios *termios, /* Gracefully handle the B0 case: fall back to B9600 */ fuart = fuart ? fuart : 9600 * 16; + /* Fuart <= Fref: leave it to the core to refuse a higher baud rate */ + fuart = min(fuart, fref); + /* Get Fuart closer to Fref */ fuart *= rounddown_pow_of_two(fref / fuart); diff --git a/drivers/tty/serial/8250/8250_mxpcie.c b/drivers/tty/serial/8250/8250_mxpcie.c index 19f1f51eec47..bccb69f2616e 100644 --- a/drivers/tty/serial/8250/8250_mxpcie.c +++ b/drivers/tty/serial/8250/8250_mxpcie.c @@ -411,7 +411,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; @@ -438,9 +438,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 b7919c05f0fb..4852a68d535f 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 986fefb45c63..18892fc4a35b 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 87fa30d68687..9c1785771cbb 100644 --- a/drivers/tty/serial/rda-uart.c +++ b/drivers/tty/serial/rda-uart.c @@ -471,6 +471,8 @@ static void rda_uart_shutdown(struct uart_port *port) rda_uart_write(port, val, RDA_UART_CTRL); uart_port_unlock_irqrestore(port, flags); + + free_irq(port->irq, port); } static const char *rda_uart_type(struct uart_port *port) diff --git a/drivers/tty/serial/samsung_tty.c b/drivers/tty/serial/samsung_tty.c index 63d0232dffc2..34dcec0d90a4 100644 --- a/drivers/tty/serial/samsung_tty.c +++ b/drivers/tty/serial/samsung_tty.c @@ -736,14 +736,13 @@ static irqreturn_t s3c24xx_serial_rx_chars_dma(struct s3c24xx_uart_port *ourport s3c24xx_serial_rx_drain_fifo(ourport); - if (tty) { + if (tty) tty_flip_buffer_push(t); - tty_kref_put(tty); - } wr_regl(port, S3C2410_UTRSTAT, S3C2410_UTRSTAT_TIMEOUT); finish: + tty_kref_put(tty); uart_port_unlock(port); return IRQ_HANDLED; @@ -1499,11 +1498,14 @@ static void s3c24xx_serial_set_termios(struct uart_port *port, if (!IS_ERR(ourport->baudclk)) { clk_disable_unprepare(ourport->baudclk); + clk_put(ourport->baudclk); ourport->baudclk = ERR_PTR(-EINVAL); } ourport->baudclk = clk; ourport->baudclk_rate = clk ? clk_get_rate(clk) : 0; + } else { + clk_put(clk); } if (ourport->info->has_divslot) { diff --git a/drivers/tty/serial/serial_core.c b/drivers/tty/serial/serial_core.c index d873df2f1529..c379686186d8 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 c41d850b29c6..d3d47c727631 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 49a140b49eff..f8b7710fb693 100644 --- a/drivers/tty/vt/vt.c +++ b/drivers/tty/vt/vt.c @@ -1857,6 +1857,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 b832505e1b04..475bc19a1746 100644 --- a/drivers/usb/dwc3/dwc3-xilinx.c +++ b/drivers/usb/dwc3/dwc3-xilinx.c @@ -48,6 +48,9 @@ struct dwc3_xlnx { void __iomem *regs; int (*pltfm_init)(struct dwc3_xlnx *data); struct phy *usb3_phy; + struct reset_control *usb_crst; + struct reset_control *usb_hibrst; + struct reset_control *usb_apbrst; }; static void dwc3_xlnx_mask_phy_rst(struct dwc3_xlnx *priv_data, bool mask) @@ -109,10 +112,42 @@ static int dwc3_xlnx_init_versal(struct dwc3_xlnx *priv_data) return 0; } +static void dwc3_xlnx_zynqmp_teardown(void *data) +{ + struct dwc3_xlnx *priv_data = data; + + phy_power_off(priv_data->usb3_phy); + + /* + * Undo only the reset cycle init performed. As on the init error + * path, the unconditional deasserts are not paired with an assert + * here: with no usb3-phy, resetting the core could break a USB3 + * configuration that is live but missing from the device tree. + */ + if (priv_data->usb3_phy) { + reset_control_assert(priv_data->usb_hibrst); + reset_control_assert(priv_data->usb_crst); + reset_control_assert(priv_data->usb_apbrst); + } + + phy_exit(priv_data->usb3_phy); +} + +/* + * Run the platform teardown explicitly, so the resets are asserted while the + * clocks are still running. devm_release_action() unlinks the action before + * calling it, so devres will not run it a second time. + */ +static void dwc3_xlnx_release_teardown(struct device *dev, + struct dwc3_xlnx *priv_data) +{ + if (devm_is_action_added(dev, dwc3_xlnx_zynqmp_teardown, priv_data)) + devm_release_action(dev, dwc3_xlnx_zynqmp_teardown, priv_data); +} + static int dwc3_xlnx_init_zynqmp(struct dwc3_xlnx *priv_data) { struct device *dev = priv_data->dev; - struct reset_control *crst, *hibrst, *apbrst; struct gpio_desc *reset_gpio; int ret = 0; @@ -124,25 +159,25 @@ static int dwc3_xlnx_init_zynqmp(struct dwc3_xlnx *priv_data) goto err; } - crst = devm_reset_control_get_exclusive(dev, "usb_crst"); - if (IS_ERR(crst)) { - ret = PTR_ERR(crst); + priv_data->usb_crst = devm_reset_control_get_exclusive(dev, "usb_crst"); + if (IS_ERR(priv_data->usb_crst)) { + ret = PTR_ERR(priv_data->usb_crst); dev_err_probe(dev, ret, "failed to get core reset signal\n"); goto err; } - hibrst = devm_reset_control_get_exclusive(dev, "usb_hibrst"); - if (IS_ERR(hibrst)) { - ret = PTR_ERR(hibrst); + priv_data->usb_hibrst = devm_reset_control_get_exclusive(dev, "usb_hibrst"); + if (IS_ERR(priv_data->usb_hibrst)) { + ret = PTR_ERR(priv_data->usb_hibrst); dev_err_probe(dev, ret, "failed to get hibernation reset signal\n"); goto err; } - apbrst = devm_reset_control_get_exclusive(dev, "usb_apbrst"); - if (IS_ERR(apbrst)) { - ret = PTR_ERR(apbrst); + priv_data->usb_apbrst = devm_reset_control_get_exclusive(dev, "usb_apbrst"); + if (IS_ERR(priv_data->usb_apbrst)) { + ret = PTR_ERR(priv_data->usb_apbrst); dev_err_probe(dev, ret, "failed to get APB reset signal\n"); goto err; @@ -156,19 +191,19 @@ static int dwc3_xlnx_init_zynqmp(struct dwc3_xlnx *priv_data) * absent. */ if (priv_data->usb3_phy) { - ret = reset_control_assert(crst); + ret = reset_control_assert(priv_data->usb_crst); if (ret < 0) { dev_err(dev, "Failed to assert core reset\n"); goto err; } - ret = reset_control_assert(hibrst); + ret = reset_control_assert(priv_data->usb_hibrst); if (ret < 0) { dev_err(dev, "Failed to assert hibernation reset\n"); goto err; } - ret = reset_control_assert(apbrst); + ret = reset_control_assert(priv_data->usb_apbrst); if (ret < 0) { dev_err(dev, "Failed to assert APB reset\n"); goto err; @@ -179,7 +214,7 @@ static int dwc3_xlnx_init_zynqmp(struct dwc3_xlnx *priv_data) if (ret < 0) goto err; - ret = reset_control_deassert(apbrst); + ret = reset_control_deassert(priv_data->usb_apbrst); if (ret < 0) { dev_err(dev, "Failed to release APB reset\n"); goto err_phy_exit; @@ -195,21 +230,21 @@ static int dwc3_xlnx_init_zynqmp(struct dwc3_xlnx *priv_data) writel(PIPE_CLK_DESELECT, priv_data->regs + XLNX_USB_FPD_PIPE_CLK); } - ret = reset_control_deassert(crst); + ret = reset_control_deassert(priv_data->usb_crst); if (ret < 0) { dev_err(dev, "Failed to release core reset\n"); - goto err_phy_exit; + goto err_reset_assert; } - ret = reset_control_deassert(hibrst); + ret = reset_control_deassert(priv_data->usb_hibrst); if (ret < 0) { dev_err(dev, "Failed to release hibernation reset\n"); - goto err_phy_exit; + goto err_reset_assert; } ret = phy_power_on(priv_data->usb3_phy); if (ret < 0) - goto err_phy_exit; + goto err_reset_assert; /* ulpi reset via gpio-modepin or gpio-framework driver */ reset_gpio = devm_gpiod_get_optional(dev, "reset", GPIOD_OUT_HIGH); @@ -226,10 +261,26 @@ static int dwc3_xlnx_init_zynqmp(struct dwc3_xlnx *priv_data) dwc3_xlnx_set_coherency(priv_data, XLNX_USB_TRAFFIC_ROUTE_CONFIG); - return 0; + return devm_add_action_or_reset(dev, dwc3_xlnx_zynqmp_teardown, + priv_data); err_phy_power_off: phy_power_off(priv_data->usb3_phy); +err_reset_assert: + /* + * Undo only the reset cycle performed above. That cycle is skipped + * when there is no usb3-phy. The deasserts stay unconditional so a + * core the bootloader left in reset still comes up, but they are + * deliberately not paired with an assert here: resetting a USB3 + * configuration that is live but missing from the device tree could + * break it. Asserting an already asserted reset is harmless, so one + * block covers however far the cycle's deasserts got. + */ + if (priv_data->usb3_phy) { + reset_control_assert(priv_data->usb_hibrst); + reset_control_assert(priv_data->usb_crst); + reset_control_assert(priv_data->usb_apbrst); + } err_phy_exit: phy_exit(priv_data->usb3_phy); err: @@ -338,6 +389,7 @@ static int dwc3_xlnx_probe(struct platform_device *pdev) pm_runtime_set_suspended(dev); err_clk_put: + dwc3_xlnx_release_teardown(dev, priv_data); clk_bulk_disable_unprepare(priv_data->num_clocks, priv_data->clks); return ret; @@ -350,6 +402,13 @@ static void dwc3_xlnx_remove(struct platform_device *pdev) of_platform_depopulate(dev); + /* + * This is also what makes .shutdown behave the same as .remove: + * device_shutdown() does not call devres_release_all(), so a teardown + * left to devres would never run on the shutdown path. + */ + dwc3_xlnx_release_teardown(dev, priv_data); + clk_bulk_disable_unprepare(priv_data->num_clocks, priv_data->clks); priv_data->num_clocks = 0; @@ -383,13 +442,26 @@ static int __maybe_unused dwc3_xlnx_runtime_idle(struct device *dev) static int __maybe_unused dwc3_xlnx_suspend(struct device *dev) { struct dwc3_xlnx *priv_data = dev_get_drvdata(dev); + int ret; - phy_exit(priv_data->usb3_phy); + ret = phy_power_off(priv_data->usb3_phy); + if (ret < 0) + return ret; + + ret = phy_exit(priv_data->usb3_phy); + if (ret < 0) + goto err_phy_power_on; /* Disable the clocks */ clk_bulk_disable(priv_data->num_clocks, priv_data->clks); return 0; + +err_phy_power_on: + if (phy_power_on(priv_data->usb3_phy)) + dev_err(dev, "failed to restore PHY power after suspend error\n"); + + return ret; } static int __maybe_unused dwc3_xlnx_resume(struct device *dev) @@ -403,15 +475,20 @@ static int __maybe_unused dwc3_xlnx_resume(struct device *dev) ret = phy_init(priv_data->usb3_phy); if (ret < 0) - return ret; + goto err_clk_disable; ret = phy_power_on(priv_data->usb3_phy); if (ret < 0) { phy_exit(priv_data->usb3_phy); - return ret; + goto err_clk_disable; } return 0; + +err_clk_disable: + clk_bulk_disable(priv_data->num_clocks, priv_data->clks); + + return ret; } static const struct dev_pm_ops dwc3_xlnx_dev_pm_ops = { diff --git a/drivers/usb/dwc3/ep0.c b/drivers/usb/dwc3/ep0.c index 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 @@ static int __dwc3_gadget_ep_enable(struct dwc3_ep *dep, unsigned int action) return 0; } -void dwc3_remove_requests(struct dwc3 *dwc, struct dwc3_ep *dep, int status) +void dwc3_remove_requests(struct dwc3 *dwc, struct dwc3_ep *dep, int status, + bool interrupt) { struct dwc3_request *req; - dwc3_stop_active_transfer(dep, false, false); + dwc3_stop_active_transfer(dep, false, interrupt); /* If endxfer is delayed, avoid unmapping requests */ if (dep->flags & DWC3_EP_DELAY_STOP) return; + /* Give the controller time to stop accessing the request buffers */ + if (dep->flags & DWC3_EP_END_TRANSFER_PENDING) + mdelay(1); + /* - giveback all requests to gadget driver */ while (!list_empty(&dep->started_list)) { req = next_request(&dep->started_list); @@ -1084,7 +1097,9 @@ static int __dwc3_gadget_ep_disable(struct dwc3_ep *dep) reg &= ~DWC3_DALEPENA_EP(dep->number); dwc3_writel(dwc, DWC3_DALEPENA, reg); - dwc3_remove_requests(dwc, dep, -ESHUTDOWN); + dep->flags &= ~DWC3_EP_ENABLED; + + dwc3_remove_requests(dwc, dep, -ESHUTDOWN, true); dep->stream_capable = false; dep->type = 0; @@ -1096,6 +1111,15 @@ static int __dwc3_gadget_ep_disable(struct dwc3_ep *dep) */ if (dep->flags & DWC3_EP_DELAY_STOP) mask |= (DWC3_EP_DELAY_STOP | DWC3_EP_TRANSFER_STARTED); + + /* + * The End Transfer command is still in progress. Do not clear the + * flags, so that the ep is only rearmed once the command completes. + */ + if (dep->flags & DWC3_EP_END_TRANSFER_PENDING) + mask |= (DWC3_EP_END_TRANSFER_PENDING | + DWC3_EP_TRANSFER_STARTED); + dep->flags &= mask; /* Clear out the ep descriptors for non-ep0 */ @@ -1751,6 +1775,8 @@ static int __dwc3_gadget_get_frame(struct dwc3 *dwc) return DWC3_DSTS_SOFFN(reg); } +static void dwc3_schedule_err_recovery(struct dwc3 *dwc); + /** * __dwc3_stop_active_transfer - stop the current active transfer * @dep: isoc endpoint @@ -1794,11 +1820,14 @@ static int __dwc3_stop_active_transfer(struct dwc3_ep *dep, bool force, bool int dev_err_ratelimited(dep->dwc->dev, "end transfer failed: %d\n", ret); + if (ret == -ETIMEDOUT && dep->dwc->err_state == DWC3_ERR_NONE) + dwc3_schedule_err_recovery(dep->dwc); + dep->resource_index = 0; - if (!interrupt) + if (!interrupt || (ret && ret != -ETIMEDOUT)) dep->flags &= ~DWC3_EP_TRANSFER_STARTED; - else if (!ret) + else dep->flags |= DWC3_EP_END_TRANSFER_PENDING; dep->flags &= ~DWC3_EP_DELAY_STOP; @@ -1990,7 +2019,8 @@ static int __dwc3_gadget_ep_queue(struct dwc3_ep *dep, struct dwc3_request *req) { struct dwc3 *dwc = dep->dwc; - if (!dep->endpoint.desc || !dwc->pullups_connected || !dwc->connected) { + if (!(dep->flags & DWC3_EP_ENABLED) || !dep->endpoint.desc || + !dwc->pullups_connected || !dwc->connected) { dev_dbg(dwc->dev, "%s: can't queue to disabled endpoint\n", dep->name); return -ESHUTDOWN; @@ -2547,7 +2577,7 @@ static void dwc3_stop_active_transfers(struct dwc3 *dwc) if (!dep) continue; - dwc3_remove_requests(dwc, dep, -ESHUTDOWN); + dwc3_remove_requests(dwc, dep, -ESHUTDOWN, false); } } @@ -2947,6 +2977,7 @@ static int __dwc3_gadget_start(struct dwc3 *dwc) { struct dwc3_ep *dep; int ret = 0; + u32 epnum; u32 reg; /* @@ -3004,6 +3035,15 @@ static int __dwc3_gadget_start(struct dwc3 *dwc) return ret; } + for (epnum = 2; epnum < dwc->num_eps; epnum++) { + dep = dwc->eps[epnum]; + if (!dep) + continue; + + dep->flags &= (DWC3_EP_TXFIFO_RESIZED | + DWC3_EP_RESOURCE_ALLOCATED); + } + dep = dwc->eps[0]; dep->flags = 0; ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT); @@ -3872,6 +3912,7 @@ static void dwc3_gadget_endpoint_command_complete(struct dwc3_ep *dep, if (dep->stream_capable) dep->flags |= DWC3_EP_IGNORE_NEXT_NOSTREAM; + dep->flags &= ~DWC3_EP_DELAY_STOP; dep->flags &= ~DWC3_EP_END_TRANSFER_PENDING; dep->flags &= ~DWC3_EP_TRANSFER_STARTED; dwc3_gadget_ep_cleanup_cancelled_requests(dep); @@ -3894,7 +3935,16 @@ static void dwc3_gadget_endpoint_command_complete(struct dwc3_ep *dep, dwc3_ep0_send_delayed_status(dwc); } + if (dep->flags & DWC3_EP_PENDING_NOOP_START) { + dep->flags &= ~DWC3_EP_PENDING_NOOP_START; + + if (!(dep->flags & DWC3_EP_DELAY_START) && + (dep->flags & DWC3_EP_ENABLED)) + dwc3_gadget_ep_start_noop_transfer(dep); + } + if ((dep->flags & DWC3_EP_DELAY_START) && + (dep->flags & DWC3_EP_ENABLED) && !usb_endpoint_xfer_isoc(dep->endpoint.desc)) __dwc3_gadget_kick_transfer(dep); 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 42fd2d6ffd88..f13da3a080ae 100644 --- a/drivers/usb/gadget/function/f_mass_storage.c +++ b/drivers/usb/gadget/function/f_mass_storage.c @@ -2667,8 +2667,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, @@ -3246,7 +3247,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 500c9c19c78b..ab6da3ef8783 100644 --- a/drivers/usb/gadget/function/f_ncm.c +++ b/drivers/usb/gadget/function/f_ncm.c @@ -1148,6 +1148,7 @@ static enum hrtimer_restart ncm_tx_timeout(struct hrtimer *data) { struct f_ncm *ncm = container_of(data, struct f_ncm, task_timer); struct net_device *netdev = READ_ONCE(ncm->netdev); + netdev_tx_t ret; if (netdev) { /* XXX This allowance of a NULL skb argument to ndo_start_xmit @@ -1158,7 +1159,11 @@ static enum hrtimer_restart ncm_tx_timeout(struct hrtimer *data) * * This will call directly into u_ether's eth_start_xmit() */ - netdev->netdev_ops->ndo_start_xmit(NULL, netdev); + ret = netdev->netdev_ops->ndo_start_xmit(NULL, netdev); + if (ret == NETDEV_TX_BUSY) { + hrtimer_forward_now(data, TX_TIMEOUT_NSECS); + return HRTIMER_RESTART; + } } return HRTIMER_NORESTART; } diff --git a/drivers/usb/gadget/function/storage_common.c b/drivers/usb/gadget/function/storage_common.c index 75831f2c7abe..51a70f2abe57 100644 --- a/drivers/usb/gadget/function/storage_common.c +++ b/drivers/usb/gadget/function/storage_common.c @@ -415,7 +415,8 @@ ssize_t fsg_store_ro(struct fsg_lun *curlun, struct rw_semaphore *filesem, } EXPORT_SYMBOL_GPL(fsg_store_ro); -ssize_t fsg_store_nofua(struct fsg_lun *curlun, const char *buf, size_t count) +ssize_t fsg_store_nofua(struct fsg_lun *curlun, struct rw_semaphore *filesem, + const char *buf, size_t count) { bool nofua; int ret; @@ -425,8 +426,10 @@ ssize_t fsg_store_nofua(struct fsg_lun *curlun, const char *buf, size_t count) return ret; /* Sync data when switching from async mode to sync */ - if (!nofua && curlun->nofua) + if (!nofua && curlun->nofua) { + guard(rwsem_read)(filesem); fsg_lun_fsync_sub(curlun); + } curlun->nofua = nofua; diff --git a/drivers/usb/gadget/function/storage_common.h b/drivers/usb/gadget/function/storage_common.h index 11ac785d5eee..347a86b8d6e4 100644 --- a/drivers/usb/gadget/function/storage_common.h +++ b/drivers/usb/gadget/function/storage_common.h @@ -210,7 +210,8 @@ ssize_t fsg_show_cdrom(struct fsg_lun *curlun, char *buf); ssize_t fsg_show_removable(struct fsg_lun *curlun, char *buf); ssize_t fsg_store_ro(struct fsg_lun *curlun, struct rw_semaphore *filesem, const char *buf, size_t count); -ssize_t fsg_store_nofua(struct fsg_lun *curlun, const char *buf, size_t count); +ssize_t fsg_store_nofua(struct fsg_lun *curlun, struct rw_semaphore *filesem, + const char *buf, size_t count); ssize_t fsg_store_file(struct fsg_lun *curlun, struct rw_semaphore *filesem, const char *buf, size_t count); ssize_t fsg_store_cdrom(struct fsg_lun *curlun, struct rw_semaphore *filesem, diff --git a/drivers/usb/gadget/function/u_serial.c b/drivers/usb/gadget/function/u_serial.c index 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/pci-quirks.c b/drivers/usb/host/pci-quirks.c index ba158d63bb8b..1363c3502f98 100644 --- a/drivers/usb/host/pci-quirks.c +++ b/drivers/usb/host/pci-quirks.c @@ -1194,10 +1194,11 @@ static void quirk_usb_handoff_xhci(struct pci_dev *pdev) && pdev->device == 0x0014)) { val = (val | XHCI_HC_OS_OWNED) & ~XHCI_HC_BIOS_OWNED; writel(val, base + ext_cap_offset); - } - - /* If the BIOS owns the HC, signal that the OS wants it, and wait */ - if (val & XHCI_HC_BIOS_OWNED) { + } else { + /* + * Perform the standard handoff and leave OS ownership set to + * keep the BIOS at bay during subsequent suspends. + */ writel(val | XHCI_HC_OS_OWNED, base + ext_cap_offset); /* Wait for 1 second with 10 microsecond polling interval */ @@ -1209,7 +1210,9 @@ static void quirk_usb_handoff_xhci(struct pci_dev *pdev) dev_warn(&pdev->dev, "xHCI BIOS handoff failed (BIOS bug ?) %08x\n", val); - writel(val & ~XHCI_HC_BIOS_OWNED, base + ext_cap_offset); + writel((val | XHCI_HC_OS_OWNED) & + ~XHCI_HC_BIOS_OWNED, + base + ext_cap_offset); } } diff --git a/drivers/usb/host/xhci-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.c b/drivers/usb/host/xhci.c index 28bfe5fd0b6f..ec9ae4e15b5b 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; @@ -4300,7 +4301,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,37 +1441,15 @@ static void edge_unthrottle(struct tty_struct *tty) } /* if we are implementing RTS/CTS, toggle that line */ if (C_CRTSCTS(tty)) { + mutex_lock(&edge_port->mutex); edge_port->shadowMCR |= MCR_RTS; send_cmd_write_uart_register(edge_port, MCR, edge_port->shadowMCR); + mutex_unlock(&edge_port->mutex); } } -/***************************************************************************** - * SerialSetTermios - * this function is called by the tty driver when it wants to change - * the termios structure - *****************************************************************************/ -static void edge_set_termios(struct tty_struct *tty, - struct usb_serial_port *port, - const struct ktermios *old_termios) -{ - struct edgeport_port *edge_port = usb_get_serial_port_data(port); - - if (edge_port == NULL) - return; - - if (!edge_port->open) { - dev_dbg(&port->dev, "%s - port not opened\n", __func__); - return; - } - - /* change the port settings to the new ones specified */ - change_port_settings(tty, edge_port, old_termios); -} - - /***************************************************************************** * get_lsr_info - get line status register info * @@ -1499,6 +1486,7 @@ static int edge_tiocmset(struct tty_struct *tty, struct edgeport_port *edge_port = usb_get_serial_port_data(port); unsigned int mcr; + mutex_lock(&edge_port->mutex); mcr = edge_port->shadowMCR; if (set & TIOCM_RTS) mcr |= MCR_RTS; @@ -1517,6 +1505,7 @@ static int edge_tiocmset(struct tty_struct *tty, edge_port->shadowMCR = mcr; send_cmd_write_uart_register(edge_port, MCR, edge_port->shadowMCR); + mutex_unlock(&edge_port->mutex); return 0; } @@ -1530,6 +1519,7 @@ static int edge_tiocmget(struct tty_struct *tty) unsigned int mcr; msr = edge_port->shadowMSR; + mutex_lock(&edge_port->mutex); mcr = edge_port->shadowMCR; result = ((mcr & MCR_DTR) ? TIOCM_DTR: 0) /* 0x002 */ | ((mcr & MCR_RTS) ? TIOCM_RTS: 0) /* 0x004 */ @@ -1537,6 +1527,7 @@ static int edge_tiocmget(struct tty_struct *tty) | ((msr & EDGEPORT_MSR_CD) ? TIOCM_CAR: 0) /* 0x040 */ | ((msr & EDGEPORT_MSR_RI) ? TIOCM_RI: 0) /* 0x080 */ | ((msr & EDGEPORT_MSR_DSR) ? TIOCM_DSR: 0); /* 0x100 */ + mutex_unlock(&edge_port->mutex); return result; } @@ -1752,9 +1743,9 @@ static void process_rcvd_status(struct edgeport_serial *edge_serial, { struct usb_serial_port *port; struct edgeport_port *edge_port; - struct tty_struct *tty; struct device *dev; __u8 code = edge_serial->rxStatusCode; + unsigned long flags; /* switch the port pointer to the one being currently talked about */ if (edge_serial->rxPort >= edge_serial->serial->num_ports) @@ -1798,24 +1789,22 @@ static void process_rcvd_status(struct edgeport_serial *edge_serial, } if (code == IOSP_STATUS_OPEN_RSP) { + spin_lock_irqsave(&edge_port->ep_lock, flags); + /* reject stray open responses to avoid FIFO corruption */ + if (!edge_port->openPending) { + spin_unlock_irqrestore(&edge_port->ep_lock, flags); + return; + } edge_port->txCredits = GET_TX_BUFFER_SIZE(byte3); edge_port->maxTxCredits = edge_port->txCredits; dev_dbg(dev, "%s - Port %u Open Response Initial MSR = %02x TxBufferSize = %d\n", __func__, edge_serial->rxPort, byte2, edge_port->txCredits); handle_new_msr(edge_port, byte2); - /* send the current line settings to the port so we are - in sync with any further termios calls */ - tty = tty_port_tty_get(&edge_port->port->port); - if (tty) { - change_port_settings(tty, - edge_port, &tty->termios); - tty_kref_put(tty); - } - /* we have completed the open */ edge_port->openPending = false; - edge_port->open = true; + spin_unlock_irqrestore(&edge_port->ep_lock, flags); + wake_up(&edge_port->wait_open); return; } @@ -2143,24 +2132,21 @@ static int write_cmd_usb(struct edgeport_port *edge_port, if (!urb) return -ENOMEM; - atomic_inc(&CmdUrbs); - dev_dbg(dev, "%s - ALLOCATE URB %p (outstanding %d)\n", - __func__, urb, atomic_read(&CmdUrbs)); - usb_fill_bulk_urb(urb, edge_serial->serial->dev, usb_sndbulkpipe(edge_serial->serial->dev, edge_serial->bulk_out_endpoint), buffer, length, edge_bulk_out_cmd_callback, edge_port); edge_port->commandPending = true; + usb_anchor_urb(urb, &edge_serial->cmd_anchor); status = usb_submit_urb(urb, GFP_ATOMIC); if (status) { /* something went wrong */ dev_err(dev, "%s - usb_submit_urb(write command) failed, status = %d\n", __func__, status); + usb_unanchor_urb(urb); usb_free_urb(urb); - atomic_dec(&CmdUrbs); return status; } @@ -2325,18 +2311,12 @@ static int send_cmd_write_uart_register(struct edgeport_port *edge_port, } -/***************************************************************************** - * change_port_settings - * This routine is called to set the UART on the device to match the - * specified new settings. - *****************************************************************************/ - -static void change_port_settings(struct tty_struct *tty, - struct edgeport_port *edge_port, const struct ktermios *old_termios) +static void edge_set_termios(struct tty_struct *tty, struct usb_serial_port *port, + const struct ktermios *old_termios) { - struct device *dev = &edge_port->port->dev; - struct edgeport_serial *edge_serial = - usb_get_serial_data(edge_port->port->serial); + struct edgeport_serial *edge_serial = usb_get_serial_data(port->serial); + struct edgeport_port *edge_port = usb_get_serial_port_data(port); + struct device *dev = &port->dev; int baud; unsigned cflag; __u8 mask = 0xff; @@ -2347,12 +2327,6 @@ static void change_port_settings(struct tty_struct *tty, __u8 txFlow; int status; - if (!edge_port->open && - !edge_port->openPending) { - dev_dbg(dev, "%s - port not opened\n", __func__); - return; - } - cflag = tty->termios.c_cflag; switch (cflag & CSIZE) { @@ -2468,12 +2442,14 @@ static void change_port_settings(struct tty_struct *tty, return; /* set up the MCR register and send it to the EdgePort */ + mutex_lock(&edge_port->mutex); edge_port->shadowMCR = MCR_MASTER_IE; if (cflag & CBAUD) edge_port->shadowMCR |= (MCR_DTR | MCR_RTS); status = send_cmd_write_uart_register(edge_port, MCR, edge_port->shadowMCR); + mutex_unlock(&edge_port->mutex); if (status != 0) return; @@ -2486,7 +2462,7 @@ static void change_port_settings(struct tty_struct *tty, dev_dbg(dev, "%s - baud rate = %d\n", __func__, baud); status = send_cmd_write_baud_rate(edge_port, baud); - if (status == -1) { + if (status == -1 && old_termios) { /* Speed change was not possible - put back the old speed */ baud = tty_termios_baud_rate(old_termios); tty_encode_baud_rate(tty, baud, baud); @@ -2724,6 +2700,7 @@ static int edge_startup(struct usb_serial *serial) spin_lock_init(&edge_serial->es_lock); edge_serial->serial = serial; + init_usb_anchor(&edge_serial->cmd_anchor); usb_set_serial_data(serial, edge_serial); /* get the name for the device from the device */ @@ -2928,6 +2905,8 @@ static void edge_disconnect(struct usb_serial *serial) { struct edgeport_serial *edge_serial = usb_get_serial_data(serial); + usb_kill_anchored_urbs(&edge_serial->cmd_anchor); + if (edge_serial->is_epic) { usb_kill_urb(edge_serial->interrupt_read_urb); usb_kill_urb(edge_serial->read_urb); @@ -2965,6 +2944,12 @@ static int edge_port_probe(struct usb_serial_port *port) return -ENOMEM; spin_lock_init(&edge_port->ep_lock); + mutex_init(&edge_port->mutex); + + init_waitqueue_head(&edge_port->wait_open); + init_waitqueue_head(&edge_port->wait_chase); + init_waitqueue_head(&edge_port->wait_command); + edge_port->port = port; usb_set_serial_port_data(port, edge_port); diff --git a/drivers/usb/serial/oti6858.c b/drivers/usb/serial/oti6858.c index 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 bea0c1deec94..e05ab3c10c81 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 d1fa26ff442c..52e3c9db35a7 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 264338fd594a..4debac1cafaa 100644 --- a/drivers/usb/typec/ucsi/ucsi.c +++ b/drivers/usb/typec/ucsi/ucsi.c @@ -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++) diff --git a/drivers/usb/typec/ucsi/ucsi_acpi.c b/drivers/usb/typec/ucsi/ucsi_acpi.c index 5697ccc24ec3..2421a92ecb0e 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) @@ -196,6 +224,13 @@ static const struct dmi_system_id ucsi_acpi_quirks[] = { }, .driver_data = (void *)&ucsi_acer_ops, }, + { + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "HP"), + DMI_MATCH(DMI_BOARD_NAME, "8ED9"), + }, + .driver_data = (void *)&ucsi_hp_ops, + }, { .matches = { DMI_MATCH(DMI_SYS_VENDOR, "LG Electronics"), diff --git a/drivers/vdpa/mlx5/net/mlx5_vnet.c b/drivers/vdpa/mlx5/net/mlx5_vnet.c index 8563fec2855d..0fcb18b5f30a 100644 --- a/drivers/vdpa/mlx5/net/mlx5_vnet.c +++ b/drivers/vdpa/mlx5/net/mlx5_vnet.c @@ -3059,7 +3059,15 @@ static int mlx5_vdpa_change_map(struct mlx5_vdpa_dev *mvdev, bool teardown = !is_resumable(ndev); int err; - suspend_vqs(ndev, 0, ndev->cur_num_vqs); + if ((mvdev->status & VIRTIO_CONFIG_S_DRIVER_OK) && !mvdev->suspended) { + err = suspend_vqs(ndev, 0, ndev->cur_num_vqs); + if (err && !teardown) { + for (int i = 0; i < ndev->cur_num_vqs; i++) + resume_vqs(ndev, i, 1); + mlx5_vdpa_put_mr(mvdev, new_mr); + return err; + } + } if (teardown) { err = save_channels_info(ndev); if (err) { diff --git a/drivers/vdpa/vdpa.c b/drivers/vdpa/vdpa.c index 47c6c3d23f5c..6455f837dd26 100644 --- a/drivers/vdpa/vdpa.c +++ b/drivers/vdpa/vdpa.c @@ -1313,15 +1313,16 @@ static int vdpa_nl_cmd_dev_config_get_doit(struct sk_buff *skb, struct genl_info } err = vdpa_dev_config_fill(vdev, msg, info->snd_portid, info->snd_seq, 0, info->extack); - if (!err) + if (!err) { err = genlmsg_reply(msg, info); + msg = NULL; + } mdev_err: put_device(dev); dev_err: up_read(&vdpa_dev_lock); - if (err) - nlmsg_free(msg); + nlmsg_free(msg); return err; } diff --git a/drivers/vdpa/vdpa_sim/vdpa_sim.c b/drivers/vdpa/vdpa_sim/vdpa_sim.c index cfa88a60a38f..97d437d89524 100644 --- a/drivers/vdpa/vdpa_sim/vdpa_sim.c +++ b/drivers/vdpa/vdpa_sim/vdpa_sim.c @@ -638,6 +638,7 @@ static int vdpasim_set_map(struct vdpa_device *vdpa, unsigned int asid, if (asid >= vdpasim->dev_attr.nas) return -EINVAL; + mutex_lock(&vdpasim->mutex); spin_lock(&vdpasim->iommu_lock); iommu = &vdpasim->iommu[asid]; @@ -652,11 +653,13 @@ static int vdpasim_set_map(struct vdpa_device *vdpa, unsigned int asid, goto err; } spin_unlock(&vdpasim->iommu_lock); + mutex_unlock(&vdpasim->mutex); return 0; err: vhost_iotlb_reset(iommu); spin_unlock(&vdpasim->iommu_lock); + mutex_unlock(&vdpasim->mutex); return ret; } @@ -713,6 +716,7 @@ static int vdpasim_dma_map(struct vdpa_device *vdpa, unsigned int asid, if (asid >= vdpasim->dev_attr.nas) return -EINVAL; + mutex_lock(&vdpasim->mutex); spin_lock(&vdpasim->iommu_lock); if (vdpasim->iommu_pt[asid]) { vhost_iotlb_reset(&vdpasim->iommu[asid]); @@ -721,6 +725,7 @@ static int vdpasim_dma_map(struct vdpa_device *vdpa, unsigned int asid, ret = vhost_iotlb_add_range_ctx(&vdpasim->iommu[asid], iova, iova + size - 1, pa, perm, opaque); spin_unlock(&vdpasim->iommu_lock); + mutex_unlock(&vdpasim->mutex); return ret; } @@ -733,6 +738,7 @@ static int vdpasim_dma_unmap(struct vdpa_device *vdpa, unsigned int asid, if (asid >= vdpasim->dev_attr.nas) return -EINVAL; + mutex_lock(&vdpasim->mutex); spin_lock(&vdpasim->iommu_lock); if (vdpasim->iommu_pt[asid]) { vhost_iotlb_reset(&vdpasim->iommu[asid]); @@ -740,6 +746,7 @@ static int vdpasim_dma_unmap(struct vdpa_device *vdpa, unsigned int asid, } vhost_iotlb_del_range(&vdpasim->iommu[asid], iova, iova + size - 1); spin_unlock(&vdpasim->iommu_lock); + mutex_unlock(&vdpasim->mutex); return 0; } diff --git a/drivers/vdpa/vdpa_user/vduse_dev.c b/drivers/vdpa/vdpa_user/vduse_dev.c index 49a231bdf948..f953353b50b4 100644 --- a/drivers/vdpa/vdpa_user/vduse_dev.c +++ b/drivers/vdpa/vdpa_user/vduse_dev.c @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -1430,14 +1431,10 @@ static void vduse_vq_update_effective_cpu(struct vduse_virtqueue *vq) { int curr_cpu = vq->irq_effective_cpu; - while (true) { - curr_cpu = cpumask_next(curr_cpu, &vq->irq_affinity); - if (cpu_online(curr_cpu)) - break; - - if (curr_cpu >= nr_cpu_ids) - curr_cpu = IRQ_UNBOUND; - } + curr_cpu = cpumask_next_and_wrap(curr_cpu, &vq->irq_affinity, + cpu_online_mask); + if (curr_cpu >= nr_cpu_ids) + curr_cpu = IRQ_UNBOUND; vq->irq_effective_cpu = curr_cpu; } @@ -1672,10 +1669,12 @@ static long vduse_dev_ioctl(struct file *file, unsigned int cmd, ret = 0; index = array_index_nospec(index, dev->vq_num); if (!vduse_vq_signal_irqfd(dev->vqs[index])) { + cpus_read_lock(); vduse_vq_update_effective_cpu(dev->vqs[index]); ret = vduse_dev_queue_irq_work(dev, &dev->vqs[index]->inject, dev->vqs[index]->irq_effective_cpu); + cpus_read_unlock(); } break; } diff --git a/drivers/vhost/scsi.c b/drivers/vhost/scsi.c index ddc9bea190de..6bf1ab773d54 100644 --- a/drivers/vhost/scsi.c +++ b/drivers/vhost/scsi.c @@ -638,6 +638,16 @@ vhost_scsi_do_evt_work(struct vhost_scsi *vs, struct vhost_scsi_evt *evt) return; } + /* + * Eventq buffers are device-writable only. A nonzero in count + * guarantees that out is within the bounds of vq->iov. + */ + if (unlikely(out || !in)) { + vq_err(vq, "Invalid event buffer: out %u, in %u\n", out, in); + vs->vs_events_missed = true; + return; + } + if ((vq->iov[out].iov_len != sizeof(struct virtio_scsi_event))) { vq_err(vq, "Expecting virtio_scsi_event, got %zu bytes\n", vq->iov[out].iov_len); @@ -660,19 +670,26 @@ vhost_scsi_do_evt_work(struct vhost_scsi *vs, struct vhost_scsi_evt *evt) vhost_scsi_log_write(vq, vq_log, log_num); } -static void vhost_scsi_complete_events(struct vhost_scsi *vs, bool drop) +/* Caller must hold the event virtqueue mutex. */ +static void __vhost_scsi_complete_events(struct vhost_scsi *vs, bool drop) { - struct vhost_virtqueue *vq = &vs->vqs[VHOST_SCSI_VQ_EVT].vq; struct vhost_scsi_evt *evt, *t; struct llist_node *llnode; - mutex_lock(&vq->mutex); - llnode = llist_del_all(&vs->vs_event_list); + llnode = llist_reverse_order(llist_del_all(&vs->vs_event_list)); llist_for_each_entry_safe(evt, t, llnode, list) { if (!drop) vhost_scsi_do_evt_work(vs, evt); vhost_scsi_free_evt(vs, evt); } +} + +static void vhost_scsi_complete_events(struct vhost_scsi *vs, bool drop) +{ + struct vhost_virtqueue *vq = &vs->vqs[VHOST_SCSI_VQ_EVT].vq; + + mutex_lock(&vq->mutex); + __vhost_scsi_complete_events(vs, drop); mutex_unlock(&vq->mutex); } @@ -883,11 +900,16 @@ vhost_scsi_map_to_sgl(struct vhost_scsi_cmd *cmd, vhost_scsi_revert_map_iov_to_sgl(iter, *sgl, sg); iov_iter_revert(iter, bytes); + /* + * pages[npages] is the first page not added to the SG list. + * The remaining data starts at offset in that page. + */ while (bytes) { - n = min_t(unsigned int, PAGE_SIZE, bytes); + n = min_t(unsigned int, PAGE_SIZE - offset, bytes); put_page(pages[npages++]); bytes -= n; + offset = 0; } return -EINVAL; @@ -1539,9 +1561,17 @@ vhost_scsi_handle_vq(struct vhost_scsi *vs, struct vhost_virtqueue *vq) * vhost_scsi_queue_data_in() and vhost_scsi_queue_status() */ cmd->tvc_vq_desc = vc.head; + /* + * vhost_scsi_mapal() maps the PI bytes into cmd->prot_table. + * It maps the remaining exp_data_len bytes into cmd->table, + * which is the data SGL passed to the target core. Its + * expected length must therefore exclude prot_bytes. + * + * sbc_check_prot() derives the data length for protected READ + * and WRITE commands from the CDB. + */ vhost_scsi_target_queue_cmd(nexus, cmd, cdb, lun, task_attr, - data_direction, - exp_data_len + prot_bytes); + data_direction, exp_data_len); ret = 0; err: /* @@ -1864,7 +1894,7 @@ vhost_scsi_send_evt(struct vhost_scsi *vs, struct vhost_virtqueue *vq, llist_add(&evt->list, &vs->vs_event_list); if (!vhost_vq_work_queue(vq, &vs->vs_event_work)) - vhost_scsi_complete_events(vs, true); + __vhost_scsi_complete_events(vs, true); } static void vhost_scsi_evt_handle_kick(struct vhost_work *work) @@ -2110,6 +2140,9 @@ vhost_scsi_set_endpoint(struct vhost_scsi *vs, for (i = 0; i < vs->dev.nvqs; i++) { vq = &vs->vqs[i].vq; + if (i >= VHOST_SCSI_VQ_IO && !vs->vqs[i].scsi_cmds) + continue; + mutex_lock(&vq->mutex); vhost_vq_set_backend(vq, vs_tpg); vhost_vq_init_access(vq); @@ -2471,10 +2504,16 @@ vhost_scsi_ioctl(struct file *f, default: mutex_lock(&vs->dev.mutex); r = vhost_dev_ioctl(&vs->dev, ioctl, argp); - if (r == -ENOIOCTLCMD) - r = vhost_vring_ioctl(&vs->dev, ioctl, argp); - else + if (r == -ENOIOCTLCMD) { + if (vs->vs_tpg && + (ioctl == VHOST_SET_VRING_NUM || + ioctl == VHOST_SET_VRING_ADDR)) + r = -EBUSY; + else + r = vhost_vring_ioctl(&vs->dev, ioctl, argp); + } else { vhost_scsi_flush(vs); + } mutex_unlock(&vs->dev.mutex); return r; } diff --git a/drivers/vhost/test.c b/drivers/vhost/test.c index 24514c8fdee4..15b19e07f811 100644 --- a/drivers/vhost/test.c +++ b/drivers/vhost/test.c @@ -287,6 +287,10 @@ static long vhost_test_set_backend(struct vhost_test *n, unsigned index, int fd) r = -EFAULT; goto err_vq; } + if (enable && !vq->kick) { + r = -EINVAL; + goto err_vq; + } if (!enable) { vhost_poll_stop(&vq->poll); backend = vhost_vq_get_backend(vq); diff --git a/drivers/vhost/vdpa.c b/drivers/vhost/vdpa.c index c7a9702c2447..ad5d1dfd104d 100644 --- a/drivers/vhost/vdpa.c +++ b/drivers/vhost/vdpa.c @@ -767,13 +767,46 @@ static long vhost_vdpa_vring_ioctl(struct vhost_vdpa *v, unsigned int cmd, if (ops->get_status(vdpa) & VIRTIO_CONFIG_S_DRIVER_OK) vhost_vdpa_unsetup_vq_irq(v, idx); + /* + * The parent caches call_ctx.ctx in cb.trigger without + * holding a reference, so it has to stop using it + * before vhost_vring_ioctl() drops the last one. + */ + cb.callback = NULL; + cb.private = NULL; + cb.trigger = NULL; + ops->set_vq_cb(vdpa, idx, &cb); + + /* + * A parent interrupt handler that loaded the callback + * before that store can still be running, so wait for + * it to finish with the context too. + */ + if (ops->get_vq_irq) { + int irq = ops->get_vq_irq(vdpa, idx); + + if (irq >= 0) + synchronize_irq(irq); + } } break; } r = vhost_vring_ioctl(&v->vdev, cmd, argp); - if (r) + if (r) { + /* + * A failure here means the swap never happened and the old + * context is still installed, so give the parent back the + * callback that was torn down above. + */ + if (cmd == VHOST_SET_VRING_CALL && vq->call_ctx.ctx) { + cb.callback = vhost_vdpa_virtqueue_cb; + cb.private = vq; + cb.trigger = vq->call_ctx.ctx; + ops->set_vq_cb(vdpa, idx, &cb); + } return r; + } switch (cmd) { case VHOST_SET_VRING_ADDR: @@ -976,6 +1009,8 @@ static void vhost_vdpa_pa_unmap(struct vhost_vdpa *v, struct vhost_iotlb *iotlb, unsigned long pfn, pinned; while ((map = vhost_iotlb_itree_first(iotlb, start, last)) != NULL) { + /* Stop device access before releasing the pinned pages. */ + vhost_vdpa_general_unmap(v, map, asid); pinned = PFN_DOWN(map->size); for (pfn = PFN_DOWN(map->addr); pinned > 0; pfn++, pinned--) { @@ -985,7 +1020,6 @@ static void vhost_vdpa_pa_unmap(struct vhost_vdpa *v, struct vhost_iotlb *iotlb, unpin_user_page(page); } atomic64_sub(PFN_DOWN(map->size), &dev->mm->pinned_vm); - vhost_vdpa_general_unmap(v, map, asid); vhost_iotlb_map_free(iotlb, map); } } @@ -997,10 +1031,10 @@ static void vhost_vdpa_va_unmap(struct vhost_vdpa *v, struct vhost_iotlb *iotlb, struct vdpa_map_file *map_file; while ((map = vhost_iotlb_itree_first(iotlb, start, last)) != NULL) { + vhost_vdpa_general_unmap(v, map, asid); map_file = (struct vdpa_map_file *)map->opaque; fput(map_file->file); kfree(map_file); - vhost_vdpa_general_unmap(v, map, asid); vhost_iotlb_map_free(iotlb, map); } } @@ -1074,21 +1108,39 @@ static int vhost_vdpa_map(struct vhost_vdpa *v, struct vhost_iotlb *iotlb, return 0; } -static void vhost_vdpa_unmap(struct vhost_vdpa *v, - struct vhost_iotlb *iotlb, - u64 iova, u64 size) +static int vhost_vdpa_unmap(struct vhost_vdpa *v, + struct vhost_iotlb *iotlb, + u64 iova, u64 size) { struct vdpa_device *vdpa = v->vdpa; const struct vdpa_config_ops *ops = vdpa->config; + struct vhost_iotlb_map *map; + struct vhost_iotlb new_iotlb; u32 asid = iotlb_to_asid(iotlb); + u64 last = iova + size - 1; + int ret; - vhost_vdpa_iotlb_unmap(v, iotlb, iova, iova + size - 1, asid); + if (ops->set_map && !ops->dma_map) { + vhost_iotlb_init(&new_iotlb, iotlb->limit, iotlb->flags); + list_for_each_entry(map, &iotlb->list, link) { + if (map->start <= last && map->last >= iova) + continue; + ret = vhost_iotlb_add_range_ctx(&new_iotlb, map->start, + map->last, map->addr, + map->perm, map->opaque); + if (ret) + goto reset; + } - if (ops->set_map) { - if (!v->in_batch) - ops->set_map(vdpa, asid, iotlb); + ret = ops->set_map(vdpa, asid, &new_iotlb); +reset: + vhost_iotlb_reset(&new_iotlb); + if (ret) + return ret; } + vhost_vdpa_iotlb_unmap(v, iotlb, iova, last, asid); + return 0; } static int vhost_vdpa_va_map(struct vhost_vdpa *v, @@ -1338,7 +1390,11 @@ static int vhost_vdpa_process_iotlb_msg(struct vhost_dev *dev, u32 asid, r = vhost_vdpa_process_iotlb_update(v, iotlb, msg); break; case VHOST_IOTLB_INVALIDATE: - vhost_vdpa_unmap(v, iotlb, msg->iova, msg->size); + if (!msg->size || msg->iova > U64_MAX - msg->size + 1) { + r = -EINVAL; + break; + } + r = vhost_vdpa_unmap(v, iotlb, msg->iova, msg->size); break; case VHOST_IOTLB_BATCH_BEGIN: v->batch_asid = asid; @@ -1651,7 +1707,7 @@ static int vhost_vdpa_probe(struct vdpa_device *vdpa) return minor; } - atomic_set(&v->opened, 0); + atomic_set(&v->opened, 1); spin_lock_init(&v->config_lock); v->minor = minor; v->vdpa = vdpa; @@ -1674,16 +1730,17 @@ static int vhost_vdpa_probe(struct vdpa_device *vdpa) cdev_init(&v->cdev, &vhost_vdpa_fops); v->cdev.owner = THIS_MODULE; + init_completion(&v->completion); + for (i = 0; i < VHOST_VDPA_IOTLB_BUCKETS; i++) + INIT_HLIST_HEAD(&v->as[i]); r = cdev_device_add(&v->cdev, &v->dev); if (r) goto err; - init_completion(&v->completion); vdpa_set_drvdata(vdpa, v); - for (i = 0; i < VHOST_VDPA_IOTLB_BUCKETS; i++) - INIT_HLIST_HEAD(&v->as[i]); + atomic_set_release(&v->opened, 0); return 0; diff --git a/drivers/vhost/vhost.c b/drivers/vhost/vhost.c index 0226c4c59709..8afdd43d313c 100644 --- a/drivers/vhost/vhost.c +++ b/drivers/vhost/vhost.c @@ -1750,7 +1750,8 @@ ssize_t vhost_chr_write_iter(struct vhost_dev *dev, goto done; } - if (msg.type == VHOST_IOTLB_UPDATE && msg.size == 0) { + if (msg.type == VHOST_IOTLB_UPDATE && + (!msg.size || !msg.perm || (msg.perm & ~VHOST_ACCESS_RW))) { ret = -EINVAL; goto done; } @@ -3163,7 +3164,6 @@ static int vhost_add_used_n_in_order(struct vhost_virtqueue *vq, return -EINVAL; start = vq->last_used_idx & (vq->num - 1); - used = vq->used->ring + start; for (i = 0; i < count; i++) { if (vhost_put_used(vq, &heads[i], start, 1)) { @@ -3176,14 +3176,31 @@ static int vhost_add_used_n_in_order(struct vhost_virtqueue *vq, } if (unlikely(vq->log_used)) { + unsigned int log_count = 0; + int log_start = 0, next; + /* Make sure data is seen before log. */ smp_wmb(); - /* Log used ring entry write. */ - log_used(vq, ((void __user *)used - (void __user *)vq->used), - (vq->num - start) * sizeof *used); - if (start + count > vq->num) - log_used(vq, 0, - (start + count - vq->num) * sizeof *used); + /* Log contiguous runs of used ring entries that were written. */ + start = vq->last_used_idx & (vq->num - 1); + for (i = 0; i < count; i++) { + if (!log_count) + log_start = start; + log_count++; + + next = start + nheads[i]; + if (next >= vq->num) + next -= vq->num; + if (i + 1 == count || next != start + 1) { + used = vq->used->ring + log_start; + log_used(vq, + ((void __user *)used - + (void __user *)vq->used), + log_count * sizeof(*used)); + log_count = 0; + } + start = next; + } } old = vq->last_used_idx; diff --git a/drivers/virtio/virtio_balloon.c b/drivers/virtio/virtio_balloon.c index ab3e3d887e00..8c1b47ec17a2 100644 --- a/drivers/virtio/virtio_balloon.c +++ b/drivers/virtio/virtio_balloon.c @@ -942,6 +942,7 @@ static int virtballoon_probe(struct virtio_device *vdev) INIT_WORK(&vb->update_balloon_stats_work, update_balloon_stats_func); INIT_WORK(&vb->update_balloon_size_work, update_balloon_size_func); spin_lock_init(&vb->stop_update_lock); + spin_lock_init(&vb->wakeup_lock); mutex_init(&vb->balloon_lock); init_waitqueue_head(&vb->acked); vb->vdev = vdev; @@ -1049,8 +1050,6 @@ static int virtballoon_probe(struct virtio_device *vdev) goto out_unregister_oom; } - spin_lock_init(&vb->wakeup_lock); - /* * The virtio balloon itself can't wake up the device, but it is * responsible for processing wakeup events passed up from the transport diff --git a/drivers/virtio/virtio_pci_common.c b/drivers/virtio/virtio_pci_common.c index b90c174450b2..24af84b0c6ad 100644 --- a/drivers/virtio/virtio_pci_common.c +++ b/drivers/virtio/virtio_pci_common.c @@ -633,7 +633,7 @@ static bool vp_supports_pm_no_reset(struct device *dev) pci_read_config_word(pci_dev, pci_dev->pm_cap + PCI_PM_CTRL, &pmcsr); if (PCI_POSSIBLE_ERROR(pmcsr)) { - dev_err(dev, "Unable to query pmcsr"); + dev_err(dev, "Unable to query pmcsr\n"); return false; } diff --git a/drivers/virtio/virtio_ring.c b/drivers/virtio/virtio_ring.c index db678f5a80e0..bec008123ce8 100644 --- a/drivers/virtio/virtio_ring.c +++ b/drivers/virtio/virtio_ring.c @@ -559,6 +559,11 @@ static void virtqueue_init(struct vring_virtqueue *vq, u32 num) vq->in_use = false; vq->last_add_time_valid = false; #endif + + if (virtqueue_is_in_order(vq)) { + vq->free_head = 0; + vq->batch_last.id = UINT_MAX; + } } @@ -905,7 +910,6 @@ static unsigned detach_buf_split_in_order(struct vring_virtqueue *vq, { struct vring_desc_extra *extra; unsigned int i; - __virtio16 nextflag = cpu_to_virtio16(vq->vq.vdev, VRING_DESC_F_NEXT); /* Clear data ptr. */ vq->split.desc_state[head].data = NULL; @@ -915,7 +919,7 @@ static unsigned detach_buf_split_in_order(struct vring_virtqueue *vq, /* Put back on free list: unmap first-level descriptors and find end */ i = head; - while (vq->split.vring.desc[i].flags & nextflag) { + while (extra[i].flags & VRING_DESC_F_NEXT) { i = vring_unmap_one_split(vq, &extra[i]); vq->vq.num_free++; } diff --git a/drivers/w1/masters/ds2482.c b/drivers/w1/masters/ds2482.c index cbd11bc61274..5498bb04f7ce 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..fed45ad4e4e7 100644 --- a/drivers/w1/slaves/w1_therm.c +++ b/drivers/w1/slaves/w1_therm.c @@ -906,6 +906,19 @@ static inline bool bulk_read_support(struct w1_slave *sl) return false; /* No device family */ } +/** + * bulk_read_slave() - check if a slave of the bus takes part in a bulk read + * @sl: any slave on the list of the master + * + * The family data of the slaves of other families is none of our business. + * + * Return: true if it is one of our devices and supports bulk read + */ +static bool bulk_read_slave(struct w1_slave *sl) +{ + return device_family(sl) && sl->family_data && bulk_read_support(sl); +} + /** * conversion_time() - get the Tconv for the slave * @sl: device to get the conversion time @@ -1496,9 +1509,7 @@ static int trigger_bulk_read(struct w1_master *dev_master) * so we can apply a strong pullup if required */ list_for_each_entry(sl, &dev_master->slist, w1_slave_entry) { - if (!sl->family_data) - goto error; - if (bulk_read_support(sl)) { + if (bulk_read_slave(sl)) { int t_cur = conversion_time(sl); t_conv = max(t_cur, t_conv); @@ -1536,7 +1547,7 @@ static int trigger_bulk_read(struct w1_master *dev_master) /* set a flag to instruct that converT pending */ list_for_each_entry(sl, &dev_master->slist, w1_slave_entry) { - if (bulk_read_support(sl)) + if (bulk_read_slave(sl)) SLAVE_CONVERT_TRIGGERED(sl) = -1; } @@ -1565,7 +1576,7 @@ static int trigger_bulk_read(struct w1_master *dev_master) set_flag: /* set a flag to register convsersion is done */ list_for_each_entry(sl, &dev_master->slist, w1_slave_entry) { - if (bulk_read_support(sl)) + if (bulk_read_slave(sl)) SLAVE_CONVERT_TRIGGERED(sl) = 1; } error: @@ -1933,16 +1944,14 @@ static ssize_t therm_bulk_read_show(struct device *device, int ret = 0; list_for_each_entry(sl, &dev_master->slist, w1_slave_entry) { - if (sl->family_data) { - if (bulk_read_support(sl)) { - if (SLAVE_CONVERT_TRIGGERED(sl) == -1) { - ret = -1; - goto show_result; - } - if (SLAVE_CONVERT_TRIGGERED(sl) == 1) - /* continue to check other slaves */ - ret = 1; + if (bulk_read_slave(sl)) { + if (SLAVE_CONVERT_TRIGGERED(sl) == -1) { + ret = -1; + goto show_result; } + if (SLAVE_CONVERT_TRIGGERED(sl) == 1) + /* continue to check other slaves */ + ret = 1; } } show_result: diff --git a/drivers/w1/w1.c b/drivers/w1/w1.c index 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 557a78306d18..348c7ccddde0 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/npcm_wdt.c b/drivers/watchdog/npcm_wdt.c index 51348969bf49..31253fd7bad5 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/rzv2h_wdt.c b/drivers/watchdog/rzv2h_wdt.c index 83540dd9a37b..537c62c18a93 100644 --- a/drivers/watchdog/rzv2h_wdt.c +++ b/drivers/watchdog/rzv2h_wdt.c @@ -174,7 +174,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; } @@ -256,20 +256,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/xen/gntdev.c b/drivers/xen/gntdev.c index b71f5bae25b6..1ad022015f1a 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 076c1b0ab87f..2a28884a84b7 100644 --- a/drivers/xen/grant-table.c +++ b/drivers/xen/grant-table.c @@ -38,6 +38,7 @@ #include #include #include +#include #include #include #include @@ -1096,6 +1097,24 @@ int gnttab_dma_alloc_pages(struct gnttab_dma_alloc_args *args) ret = xenmem_reservation_decrease(args->nr_pages, args->frames); if (ret != args->nr_pages) { pr_debug("Failed to decrease reservation for DMA buffer\n"); + if (ret >= 0) { + /* Free the part where decrease didn't work. */ + size_t done = ret << PAGE_SHIFT; + + if (args->coherent) + dma_free_coherent(args->dev, size - done, + args->vaddr + done, + args->dev_bus_addr + done); + else + dma_free_wc(args->dev, size - done, + args->vaddr + done, + args->dev_bus_addr + done); + + if (!ret) /* Nothing else to do? */ + return -EFAULT; + + args->nr_pages = ret; + } ret = -EFAULT; goto fail; } @@ -1129,7 +1148,12 @@ int gnttab_dma_free_pages(struct gnttab_dma_alloc_args *args) ret = xenmem_reservation_increase(args->nr_pages, args->frames); if (ret != args->nr_pages) { pr_debug("Failed to increase reservation for DMA buffer\n"); - ret = -EFAULT; + /* Can only free what has been re-filled. */ + if (!ret) + return -ENOMEM; + if (ret > 0) + args->nr_pages = ret; + ret = -ENOMEM; } else { ret = 0; } @@ -1361,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/privcmd.c b/drivers/xen/privcmd.c index c67ec6d282cf..2a710cff2dd2 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/9p/v9fs.h b/fs/9p/v9fs.h index 2ac863dc8446..9a730d2d9d87 100644 --- a/fs/9p/v9fs.h +++ b/fs/9p/v9fs.h @@ -21,20 +21,16 @@ * @V9FS_ACCESS_SINGLE: only the mounting user can access the hierarchy * @V9FS_ACCESS_USER: a new attach will be issued for every user (default) * @V9FS_ACCESS_CLIENT: Just like user, but access check is performed on client. - * @V9FS_ACCESS_ANY: use a single attach for all users - * @V9FS_ACCESS_MASK: bit mask of different ACCESS options * @V9FS_POSIX_ACL: POSIX ACLs are enforced + * @V9FS_NO_XATTR: do not offer xattr functions on this mount + * @V9FS_IGNORE_QV: ignore qid.version==0 as a marker to disable data cache + * @V9FS_DIRECT_IO: disable data read/write cache + * @V9FS_SYNC: disable data write cache * @V9FS_NDENTRY_TIMEOUT_SET: Has negative dentry timeout retention time been * overridden by negtimeout mount option * * Session flags reflect options selected by users at mount time */ -#define V9FS_ACCESS_ANY (V9FS_ACCESS_SINGLE | \ - V9FS_ACCESS_USER | \ - V9FS_ACCESS_CLIENT) -#define V9FS_ACCESS_MASK V9FS_ACCESS_ANY -#define V9FS_ACL_MASK V9FS_POSIX_ACL - enum p9_session_flags { V9FS_PROTO_2000U = 0x01, V9FS_PROTO_2000L = 0x02, @@ -49,6 +45,20 @@ enum p9_session_flags { V9FS_NDENTRY_TIMEOUT_SET = 0x400, }; +/** + * V9FS_ACCESS_ANY - use a single attach for all users + */ +#define V9FS_ACCESS_ANY (V9FS_ACCESS_SINGLE | \ + V9FS_ACCESS_USER | \ + V9FS_ACCESS_CLIENT) + +/** + * V9FS_ACCESS_MASK - bit mask of different ACCESS options + */ +#define V9FS_ACCESS_MASK V9FS_ACCESS_ANY + +#define V9FS_ACL_MASK V9FS_POSIX_ACL + /** * enum p9_cache_shortcuts - human readable cache preferences * @CACHE_SC_NONE: disable all caches diff --git a/fs/9p/vfs_addr.c b/fs/9p/vfs_addr.c index 13cf87a5f90c..a48cc34b9a23 100644 --- a/fs/9p/vfs_addr.c +++ b/fs/9p/vfs_addr.c @@ -99,6 +99,7 @@ static void v9fs_issue_read(struct netfs_io_subrequest *subreq) char *target; unsigned long long pos = subreq->start + subreq->transferred; int total = 0, err, len, n; + size_t to_read = iov_iter_count(&subreq->io_iter); if (S_ISLNK(rreq->inode->i_mode)) { /* p9_client_readlink() must not be called for legacy protocols @@ -131,6 +132,8 @@ static void v9fs_issue_read(struct netfs_io_subrequest *subreq) __set_bit(NETFS_SREQ_CLEAR_TAIL, &subreq->flags); if (pos + total >= i_size_read(rreq->inode)) __set_bit(NETFS_SREQ_HIT_EOF, &subreq->flags); + if (!err && !total && to_read) + __set_bit(NETFS_SREQ_HIT_EOF, &subreq->flags); if (!err && total) { subreq->transferred += total; __set_bit(NETFS_SREQ_MADE_PROGRESS, &subreq->flags); diff --git a/fs/9p/vfs_dir.c b/fs/9p/vfs_dir.c index 323f85352f6a..733ec42258bc 100644 --- a/fs/9p/vfs_dir.c +++ b/fs/9p/vfs_dir.c @@ -196,8 +196,12 @@ static int v9fs_dir_readdir_dotl(struct file *file, struct dir_context *ctx) if (!dir_emit(ctx, curdirent.d_name, strlen(curdirent.d_name), QID2INO(&curdirent.qid), - curdirent.d_type)) + curdirent.d_type)) { + kfree(curdirent.d_name); return 0; + } + + kfree(curdirent.d_name); ctx->pos = curdirent.d_off; rdir->head += err; diff --git a/fs/9p/vfs_inode.c b/fs/9p/vfs_inode.c index 2d7e0c1a5353..347739b81513 100644 --- a/fs/9p/vfs_inode.c +++ b/fs/9p/vfs_inode.c @@ -810,6 +810,16 @@ v9fs_vfs_atomic_open(struct inode *dir, struct dentry *dentry, v9fs_invalidate_inode_attr(dir); inode = d_inode(dentry); v9inode = V9FS_I(inode); + if (!S_ISREG(inode->i_mode)) { + /* + * Not a regular file. v9fs_create() already stored the + * unopened fid on the dentry. Clunk the opened fid from + * the create and let the VFS call ->open. + */ + p9_fid_put(fid); + file->f_mode |= FMODE_CREATED; + return finish_no_open(file, NULL); + } err = finish_open(file, dentry, generic_file_open); if (unlikely(err)) { p9_fid_put(fid); diff --git a/fs/9p/vfs_inode_dotl.c b/fs/9p/vfs_inode_dotl.c index 116b29e95f21..d9156b2509ac 100644 --- a/fs/9p/vfs_inode_dotl.c +++ b/fs/9p/vfs_inode_dotl.c @@ -312,20 +312,40 @@ v9fs_vfs_atomic_open_dotl(struct inode *dir, struct dentry *dentry, v9fs_fid_add(dentry, &fid); d_instantiate(dentry, inode); + if (!S_ISREG(inode->i_mode)) { + /* + * Not a regular file. The unopened fid is already on the + * dentry. Clunk the opened create fid and let the VFS call + * ->open. + */ + p9_fid_put(ofid); + ofid = NULL; + file->f_mode |= FMODE_CREATED; + err = finish_no_open(file, NULL); + goto out; + } /* Since we are opening a file, assign the open fid to the file */ err = finish_open(file, dentry, generic_file_open); if (err) goto out; - file->private_data = ofid; + /* + * Special files have type-specific fops that own + * file->private_data. The create fid is unused + * there: leave it for p9_fid_put() on the out + * path so it is clunked before we return. + */ + if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode)) { + file->private_data = ofid; #ifdef CONFIG_9P_FSCACHE - if (v9ses->cache & CACHE_FSCACHE) { - struct v9fs_inode *v9inode = V9FS_I(inode); - fscache_use_cookie(v9fs_inode_cookie(v9inode), - file->f_mode & FMODE_WRITE); - } + if (v9ses->cache & CACHE_FSCACHE) { + struct v9fs_inode *v9inode = V9FS_I(inode); + fscache_use_cookie(v9fs_inode_cookie(v9inode), + file->f_mode & FMODE_WRITE); + } #endif - v9fs_fid_add_modes(ofid, v9ses->flags, v9ses->cache, flags); - v9fs_open_fid_add(inode, &ofid); + v9fs_fid_add_modes(ofid, v9ses->flags, v9ses->cache, flags); + v9fs_open_fid_add(inode, &ofid); + } file->f_mode |= FMODE_CREATED; out: p9_fid_put(dfid); diff --git a/fs/adfs/dir_fplus.c b/fs/adfs/dir_fplus.c index 4a15924014da..c68c301d8903 100644 --- a/fs/adfs/dir_fplus.c +++ b/fs/adfs/dir_fplus.c @@ -192,6 +192,8 @@ adfs_fplus_getnext(struct adfs_dir *dir, struct object_info *obj) obj->indaddr = le32_to_cpu(bde.bigdirindaddr); obj->attr = le32_to_cpu(bde.bigdirattr); obj->name_len = le32_to_cpu(bde.bigdirobnamelen); + if (obj->name_len > ADFS_MAX_NAME_LEN - 4) /* leave room for ,xyz suffix */ + return -EIO; offset = adfs_fplus_offset(h, le32_to_cpu(h->bigdirentries)); offset += le32_to_cpu(bde.bigdirobnameptr); diff --git a/fs/aio.c b/fs/aio.c index f77cbc046e91..f15cfa7d8af0 100644 --- a/fs/aio.c +++ b/fs/aio.c @@ -962,7 +962,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; @@ -986,7 +986,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 4f6b3b588f74..ee1d7e820ee0 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 19b4855969f5..068df4931797 100644 --- a/fs/btrfs/bio.c +++ b/fs/btrfs/bio.c @@ -634,6 +634,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; } @@ -772,6 +774,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; } @@ -832,6 +835,7 @@ static bool btrfs_submit_chunk(struct btrfs_bio *bbio, int mirror_num) return map_length == length; fail: + btrfs_put_bioc(bioc); btrfs_bio_counter_dec(fs_info); /* * We have split the original bbio, now we have to end both the current diff --git a/fs/btrfs/fiemap.c b/fs/btrfs/fiemap.c index 7a2a97180099..817171028413 100644 --- a/fs/btrfs/fiemap.c +++ b/fs/btrfs/fiemap.c @@ -228,7 +228,8 @@ static int emit_fiemap_extent(struct fiemap_extent_info *fieinfo, * * 3) Share same flags */ - if (cache->offset + cache->len == offset && + if (!(flags & FIEMAP_EXTENT_ENCODED) && + cache->offset + cache->len == offset && cache->phys + cache->len == phys && cache->flags == flags) { cache->len += len; diff --git a/fs/btrfs/ioctl.c b/fs/btrfs/ioctl.c index beae9dcb5a3e..2ea0146730d8 100644 --- a/fs/btrfs/ioctl.c +++ b/fs/btrfs/ioctl.c @@ -5173,8 +5173,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/scrub.c b/fs/btrfs/scrub.c index 479c0e037015..91e441d0ff3c 100644 --- a/fs/btrfs/scrub.c +++ b/fs/btrfs/scrub.c @@ -2250,7 +2250,7 @@ static int scrub_raid56_parity_stripe(struct scrub_ctx *sctx, "scrub: unrepaired sectors detected, full stripe %llu data stripe %u errors %*pbl", full_stripe_start, i, stripe->nr_sectors, &error); - return ret; + return -EIO; } bitmap_or(&extent_bitmap, &extent_bitmap, &has_extent, stripe->nr_sectors); @@ -3171,7 +3171,6 @@ int btrfs_scrub_dev(struct btrfs_fs_info *fs_info, u64 devid, u64 start, memalloc_nofs_restore(nofs_flag); atomic_dec(&fs_info->scrubs_running); - wake_up(&fs_info->scrub_pause_wait); if (progress) memcpy(progress, &sctx->stat, sizeof(*progress)); @@ -3184,6 +3183,13 @@ int btrfs_scrub_dev(struct btrfs_fs_info *fs_info, u64 devid, u64 start, dev->scrub_ctx = NULL; mutex_unlock(&fs_info->scrub_lock); + /* + * We have set dev->scrub_ctx to NULL, now do the wakeup as a concurrent + * scrub cancel (btrfs_scrub_cancel_dev()) waits for dev->scrub_ctx to + * be set to NULL. + */ + wake_up(&fs_info->scrub_pause_wait); + scrub_workers_put(fs_info); scrub_put_ctx(sctx); diff --git a/fs/btrfs/verity.c b/fs/btrfs/verity.c index c29d92c3bbc3..87722e5d4186 100644 --- a/fs/btrfs/verity.c +++ b/fs/btrfs/verity.c @@ -610,7 +610,7 @@ static int btrfs_begin_enable_verity(struct file *filp) set_bit(BTRFS_INODE_VERITY_IN_PROGRESS, &inode->runtime_flags); btrfs_end_transaction(trans); - return 0; + return ret; } /* diff --git a/fs/btrfs/volumes.h b/fs/btrfs/volumes.h index 0415d74cad9b..e516c874f349 100644 --- a/fs/btrfs/volumes.h +++ b/fs/btrfs/volumes.h @@ -711,9 +711,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 3b41e964d209..40eb56499346 100644 --- a/fs/btrfs/zoned.c +++ b/fs/btrfs/zoned.c @@ -645,6 +645,11 @@ struct btrfs_zoned_device_info *btrfs_clone_dev_zone_info(struct btrfs_device *o if (!zone_info) return NULL; + /* Don't let the error path free the bitmaps still owned by @orig_dev. */ + zone_info->seq_zones = NULL; + zone_info->empty_zones = NULL; + zone_info->active_zones = NULL; + zone_info->seq_zones = bitmap_zalloc(zone_info->nr_zones, GFP_KERNEL); if (!zone_info->seq_zones) goto out; @@ -1126,11 +1131,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; @@ -1142,23 +1149,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, @@ -1380,11 +1393,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; @@ -1396,7 +1411,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; } @@ -1424,8 +1438,6 @@ static int btrfs_load_zone_info(struct btrfs_fs_info *fs_info, int zone_idx, break; } - up_read(&dev_replace->rwsem); - return 0; } @@ -2411,6 +2423,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)) @@ -2464,12 +2477,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--; } @@ -2503,8 +2516,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(); @@ -2516,6 +2537,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) @@ -2537,9 +2559,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; } @@ -2587,9 +2609,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); @@ -3118,6 +3141,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; @@ -3159,11 +3184,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); /* @@ -3177,7 +3201,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, @@ -3187,7 +3210,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); @@ -3198,7 +3221,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; @@ -3227,12 +3250,28 @@ int btrfs_reset_unused_block_groups(struct btrfs_space_info *space_info, u64 num btrfs_return_free_space(space_info, reclaimed); spin_unlock(&space_info->lock); + btrfs_put_block_group(bg); + if (num_bytes <= reclaimed) break; num_bytes -= reclaimed; + continue; + +requeue: + list_add_tail(&bg->bg_list, &retry_list); + + if (ret) + goto out; } - return 0; +out: + if (!list_empty(&retry_list)) { + spin_lock(&fs_info->unused_bgs_lock); + list_splice_tail(&retry_list, &fs_info->unused_bgs); + spin_unlock(&fs_info->unused_bgs_lock); + } + + return ret; } 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 58d9ff76fe07..082f653464c8 100644 --- a/fs/btrfs/zstd.c +++ b/fs/btrfs/zstd.c @@ -347,7 +347,8 @@ void zstd_put_workspace(struct btrfs_fs_info *fs_info, struct list_head *ws) /* A node is only taken off the lru if we are the corresponding level */ if (clip_level(workspace->req_level) == workspace->level) { /* Hide a max level workspace from reclaim */ - if (list_empty(&zwsm->idle_ws[ZSTD_BTRFS_MAX_LEVEL - 1])) { + if (workspace->level == ZSTD_BTRFS_MAX_LEVEL - 1 && + list_empty(&zwsm->idle_ws[ZSTD_BTRFS_MAX_LEVEL - 1])) { INIT_LIST_HEAD(&workspace->lru_list); } else { workspace->last_used = jiffies; diff --git a/fs/coda/file.c b/fs/coda/file.c index 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)); diff --git a/fs/dcache.c b/fs/dcache.c index 7d7d96a098d7..456abd41a104 100644 --- a/fs/dcache.c +++ b/fs/dcache.c @@ -45,7 +45,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: @@ -1101,7 +1102,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); } @@ -1589,21 +1601,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); @@ -1621,8 +1637,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; } @@ -1811,8 +1828,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); @@ -1875,6 +1897,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); @@ -1887,6 +1910,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 a726be5e27ca..67052e98ef44 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; 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/eventpoll.c b/fs/eventpoll.c index 872396a0ad64..c6e1d683e247 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/ext2/dir.c b/fs/ext2/dir.c index e17bbc7598c1..5de32c221a83 100644 --- a/fs/ext2/dir.c +++ b/fs/ext2/dir.c @@ -442,6 +442,9 @@ static int ext2_handle_dirsync(struct inode *dir) { int err; + if (!IS_DIRSYNC(dir)) + return 0; + err = filemap_write_and_wait(dir->i_mapping); if (!err) err = sync_inode_metadata(dir, 1); diff --git a/fs/ext2/inode.c b/fs/ext2/inode.c index 53edda7217f3..c13c3a63fb3c 100644 --- a/fs/ext2/inode.c +++ b/fs/ext2/inode.c @@ -1264,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); } @@ -1565,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__, @@ -1585,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/inode.c b/fs/ext4/inode.c index bd1c14b98376..eb8544c42c75 100644 --- a/fs/ext4/inode.c +++ b/fs/ext4/inode.c @@ -5060,7 +5060,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) { @@ -5096,7 +5097,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)) { @@ -5921,22 +5922,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; } diff --git a/fs/file.c b/fs/file.c index 628ca07dc4b1..4364cfe38efc 100644 --- a/fs/file.c +++ b/fs/file.c @@ -1237,14 +1237,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/inode.c b/fs/inode.c index bc93c1757a38..bf7b38c858e2 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/isofs/util.c b/fs/isofs/util.c index 42f479da0b28..6f9a90e58a89 100644 --- a/fs/isofs/util.c +++ b/fs/isofs/util.c @@ -25,7 +25,7 @@ struct timespec64 iso_date(u8 *p, int flags) year = (p[0] - '0') * 1000 + (p[1] - '0') * 100 + (p[2] - '0') * 10 + - (p[3] - '0') - 1900; + (p[3] - '0'); month = ((p[4] - '0') * 10 + (p[5] - '0')); day = ((p[6] - '0') * 10 + (p[7] - '0')); hour = ((p[8] - '0') * 10 + (p[9] - '0')); @@ -34,7 +34,7 @@ struct timespec64 iso_date(u8 *p, int flags) ts.tv_nsec = ((p[14] - '0') * 10 + (p[15] - '0')) * 10000000; tz = p[16]; } else { - year = p[0]; + year = p[0] + 1900; month = p[1]; day = p[2]; hour = p[3]; @@ -45,10 +45,10 @@ struct timespec64 iso_date(u8 *p, int flags) tz = flags & ISO_DATE_HIGH_SIERRA ? 0 : p[6]; } - if (year < 0) { + if (year < 1) { ts.tv_sec = 0; } else { - ts.tv_sec = mktime64(year+1900, month, day, hour, minute, second); + ts.tv_sec = mktime64(year, month, day, hour, minute, second); /* sign extend */ if (tz & 0x80) diff --git a/fs/libfs.c b/fs/libfs.c index 27d7dc16fcb0..53b3d1256640 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 abec438330a7..deac05472bef 100644 --- a/fs/minix/bitmap.c +++ b/fs/minix/bitmap.c @@ -103,21 +103,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"); @@ -131,19 +145,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 daf83e4ff25c..095eb8ef0fbb 100644 --- a/fs/minix/inode.c +++ b/fs/minix/inode.c @@ -702,24 +702,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 78722ce22e1e..d585bb97de0e 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/netfs/read_retry.c b/fs/netfs/read_retry.c index 4f6a36c6e214..00aab4c69743 100644 --- a/fs/netfs/read_retry.c +++ b/fs/netfs/read_retry.c @@ -28,6 +28,7 @@ static void netfs_retry_read_subrequests(struct netfs_io_request *rreq) struct netfs_io_subrequest *subreq; struct netfs_io_stream *stream = &rreq->io_streams[0]; struct list_head *next; + int ret; _enter("R=%x", rreq->debug_id); @@ -140,8 +141,11 @@ static void netfs_retry_read_subrequests(struct netfs_io_request *rreq) /* Renegotiate max_len (rsize) */ stream->sreq_max_len = subreq->len; - if (rreq->netfs_ops->prepare_read && - rreq->netfs_ops->prepare_read(subreq) < 0) { + ret = 0; + if (rreq->netfs_ops->prepare_read) + ret = rreq->netfs_ops->prepare_read(subreq); + if (ret < 0) { + subreq->error = ret; trace_netfs_sreq(subreq, netfs_sreq_trace_reprep_failed); __set_bit(NETFS_SREQ_FAILED, &subreq->flags); goto abandon; @@ -222,7 +226,9 @@ static void netfs_retry_read_subrequests(struct netfs_io_request *rreq) part = netfs_limit_iter(&source, 0, part, stream->sreq_max_segs); netfs_stat(&netfs_n_rh_download); - if (rreq->netfs_ops->prepare_read(subreq) < 0) { + ret = rreq->netfs_ops->prepare_read(subreq); + if (ret < 0) { + subreq->error = ret; trace_netfs_sreq(subreq, netfs_sreq_trace_reprep_failed); __set_bit(NETFS_SREQ_FAILED, &subreq->flags); goto abandon; @@ -258,10 +264,13 @@ static void netfs_retry_read_subrequests(struct netfs_io_request *rreq) if (!test_bit(NETFS_SREQ_FAILED, &subreq->flags) && !test_bit(NETFS_SREQ_NEED_RETRY, &subreq->flags)) continue; - subreq->error = -ENOMEM; + if (!subreq->error || + !test_bit(NETFS_SREQ_FAILED, &subreq->flags)) + subreq->error = -ENOMEM; __set_bit(NETFS_SREQ_FAILED, &subreq->flags); __clear_bit(NETFS_SREQ_NEED_RETRY, &subreq->flags); } + netfs_wake_collector(rreq); } /* diff --git a/fs/netfs/write_issue.c b/fs/netfs/write_issue.c index 851f6f93ad45..d3d61bd309cd 100644 --- a/fs/netfs/write_issue.c +++ b/fs/netfs/write_issue.c @@ -252,7 +252,9 @@ void netfs_reissue_write(struct netfs_io_stream *stream, iov_iter_truncate(&subreq->io_iter, size); subreq->retry_count++; - subreq->error = 0; + /* Keep prepare_write() errno; do_issue_write() terminates FAILED. */ + if (!test_bit(NETFS_SREQ_FAILED, &subreq->flags)) + subreq->error = 0; __clear_bit(NETFS_SREQ_MADE_PROGRESS, &subreq->flags); __set_bit(NETFS_SREQ_IN_PROGRESS, &subreq->flags); netfs_stat(&netfs_n_wh_retry_write_subreq); diff --git a/fs/nfs/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 71a342e9589f..ea95522f9c64 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 989f30e7d950..a4ccd53c79e7 100644 --- a/fs/nfs/flexfilelayout/flexfilelayout.c +++ b/fs/nfs/flexfilelayout/flexfilelayout.c @@ -44,10 +44,11 @@ static void ff_layout_read_record_layoutstats_done(struct rpc_task *task, static int ff_layout_mirror_prepare_stats(struct pnfs_layout_hdr *lo, struct nfs42_layoutstat_devinfo *devinfo, + struct nfs4_ff_layoutstat_priv *priv, int dev_limit, enum nfs4_ff_op_type type); static void ff_layout_encode_ff_layoutupdate(struct xdr_stream *xdr, const struct nfs42_layoutstat_devinfo *devinfo, - struct nfs4_ff_layout_ds_stripe *dss_info); + struct nfs4_ff_layoutstat_priv *priv); static struct pnfs_layout_hdr * ff_layout_alloc_layout_hdr(struct inode *inode, gfp_t gfp_flags) @@ -312,7 +313,9 @@ static void ff_layout_free_mirror(struct nfs4_ff_layout_mirror *mirror) cred = rcu_access_pointer(mirror->dss[dss_id].rw_cred); put_cred(cred); nfs_close_local_fh(&mirror->dss[dss_id].nfl); - nfs4_ff_layout_put_deviceid(mirror->dss[dss_id].mirror_ds); + /* the last reference to the mirror is gone; no concurrency */ + nfs4_ff_layout_put_deviceid(rcu_dereference_protected( + mirror->dss[dss_id].mirror_ds, 1)); } kfree(mirror->dss); @@ -878,7 +881,7 @@ ff_layout_mark_ds_reachable(struct pnfs_layout_segment *lseg, u32 idx, u32 dss_i nfs4_mark_deviceid_available(devid); } -static struct nfs4_pnfs_ds * +static struct nfs4_ff_layout_ds * ff_layout_choose_ds_for_read(struct pnfs_layout_segment *lseg, u32 start_idx, u32 *best_idx, u64 offset, u32 *dss_id, @@ -886,7 +889,9 @@ ff_layout_choose_ds_for_read(struct pnfs_layout_segment *lseg, { struct nfs4_ff_layout_segment *fls = FF_LAYOUT_LSEG(lseg); struct nfs4_ff_layout_mirror *mirror; - struct nfs4_pnfs_ds *ds = ERR_PTR(-EAGAIN); + struct nfs4_ff_layout_ds *mirror_ds; + struct nfs4_ff_layout_ds *ret = ERR_PTR(-EAGAIN); + struct nfs4_pnfs_ds *ds; u32 idx; /* mirrors are initially sorted by efficiency */ @@ -896,25 +901,32 @@ ff_layout_choose_ds_for_read(struct pnfs_layout_segment *lseg, fls->stripe_unit, fls->mirror_array[idx]->dss_count, offset); - ds = nfs4_ff_layout_prepare_ds(lseg, mirror, *dss_id, false); - if (IS_ERR(ds)) + mirror_ds = ff_layout_get_mirror_ds(lseg->pls_layout, mirror, + *dss_id); + ds = nfs4_ff_layout_prepare_ds(lseg, mirror, mirror_ds, + *dss_id, false); + if (IS_ERR(ds)) { + nfs4_ff_layout_put_deviceid(mirror_ds); + ret = ERR_CAST(ds); continue; + } if (check_device && - nfs4_test_deviceid_unavailable(&mirror->dss[*dss_id].mirror_ds->id_node)) { + nfs4_test_deviceid_unavailable(&mirror_ds->id_node)) { + nfs4_ff_layout_put_deviceid(mirror_ds); // reinitialize the error state in case if this is the last iteration - ds = ERR_PTR(-EINVAL); + ret = ERR_PTR(-EINVAL); continue; } *best_idx = idx; - break; + return mirror_ds; } - return ds; + return ret; } -static struct nfs4_pnfs_ds * +static struct nfs4_ff_layout_ds * ff_layout_choose_any_ds_for_read(struct pnfs_layout_segment *lseg, u32 start_idx, u32 *best_idx, u64 offset, u32 *dss_id) @@ -923,7 +935,7 @@ ff_layout_choose_any_ds_for_read(struct pnfs_layout_segment *lseg, offset, dss_id, false); } -static struct nfs4_pnfs_ds * +static struct nfs4_ff_layout_ds * ff_layout_choose_valid_ds_for_read(struct pnfs_layout_segment *lseg, u32 start_idx, u32 *best_idx, u64 offset, u32 *dss_id) @@ -932,34 +944,36 @@ ff_layout_choose_valid_ds_for_read(struct pnfs_layout_segment *lseg, offset, dss_id, true); } -static struct nfs4_pnfs_ds * +static struct nfs4_ff_layout_ds * ff_layout_choose_best_ds_for_read(struct pnfs_layout_segment *lseg, u32 start_idx, u32 *best_idx, u64 offset, u32 *dss_id) { - struct nfs4_pnfs_ds *ds; + struct nfs4_ff_layout_ds *mirror_ds; - ds = ff_layout_choose_valid_ds_for_read(lseg, start_idx, best_idx, - offset, dss_id); - if (!IS_ERR(ds)) - return ds; + mirror_ds = ff_layout_choose_valid_ds_for_read(lseg, start_idx, + best_idx, offset, + dss_id); + if (!IS_ERR(mirror_ds)) + return mirror_ds; return ff_layout_choose_any_ds_for_read(lseg, start_idx, best_idx, offset, dss_id); } -static struct nfs4_pnfs_ds * +static struct nfs4_ff_layout_ds * ff_layout_get_ds_for_read(struct nfs_pageio_descriptor *pgio, u32 *best_idx, u64 offset, u32 *dss_id) { struct pnfs_layout_segment *lseg = pgio->pg_lseg; - struct nfs4_pnfs_ds *ds; + struct nfs4_ff_layout_ds *mirror_ds; - ds = ff_layout_choose_best_ds_for_read(lseg, pgio->pg_mirror_idx, - best_idx, offset, dss_id); - if (!IS_ERR(ds) || !pgio->pg_mirror_idx) - return ds; + mirror_ds = ff_layout_choose_best_ds_for_read(lseg, + pgio->pg_mirror_idx, + best_idx, offset, dss_id); + if (!IS_ERR(mirror_ds) || !pgio->pg_mirror_idx) + return mirror_ds; return ff_layout_choose_best_ds_for_read(lseg, 0, best_idx, offset, dss_id); } @@ -1048,8 +1062,7 @@ ff_layout_pg_init_read(struct nfs_pageio_descriptor *pgio, struct nfs_page *req) { struct nfs_pgio_mirror *pgm; - struct nfs4_ff_layout_mirror *mirror; - struct nfs4_pnfs_ds *ds; + struct nfs4_ff_layout_ds *mirror_ds; u32 ds_idx, dss_id; if (NFS_SERVER(pgio->pg_inode)->flags & @@ -1071,9 +1084,9 @@ ff_layout_pg_init_read(struct nfs_pageio_descriptor *pgio, /* Reset wb_nio, since getting layout segment was successful */ req->wb_nio = 0; - ds = ff_layout_get_ds_for_read(pgio, &ds_idx, - req_offset(req), &dss_id); - if (IS_ERR(ds)) { + mirror_ds = ff_layout_get_ds_for_read(pgio, &ds_idx, + req_offset(req), &dss_id); + if (IS_ERR(mirror_ds)) { if (!ff_layout_no_fallback_to_mds(pgio->pg_lseg)) goto out_mds; pnfs_generic_pg_cleanup(pgio); @@ -1083,9 +1096,9 @@ ff_layout_pg_init_read(struct nfs_pageio_descriptor *pgio, goto retry; } - mirror = FF_LAYOUT_COMP(pgio->pg_lseg, ds_idx); pgm = &pgio->pg_mirrors[0]; - pgm->pg_bsize = mirror->dss[dss_id].mirror_ds->ds_versions[0].rsize; + pgm->pg_bsize = mirror_ds->ds_versions[0].rsize; + nfs4_ff_layout_put_deviceid(mirror_ds); pgio->pg_mirror_idx = ds_idx; return; @@ -1135,6 +1148,7 @@ ff_layout_pg_init_write(struct nfs_pageio_descriptor *pgio, struct nfs_page *req) { struct nfs4_ff_layout_mirror *mirror; + struct nfs4_ff_layout_ds *mirror_ds; struct nfs_pgio_mirror *pgm; struct nfs4_pnfs_ds *ds; u32 i, dss_id; @@ -1166,9 +1180,12 @@ ff_layout_pg_init_write(struct nfs_pageio_descriptor *pgio, FF_LAYOUT_LSEG(pgio->pg_lseg)->stripe_unit, mirror->dss_count, req_offset(req)); + mirror_ds = ff_layout_get_mirror_ds(pgio->pg_lseg->pls_layout, + mirror, dss_id); ds = nfs4_ff_layout_prepare_ds(pgio->pg_lseg, mirror, - dss_id, true); + mirror_ds, dss_id, true); if (IS_ERR(ds)) { + nfs4_ff_layout_put_deviceid(mirror_ds); if (!ff_layout_no_fallback_to_mds(pgio->pg_lseg)) goto out_mds; pnfs_generic_pg_cleanup(pgio); @@ -1178,7 +1195,8 @@ ff_layout_pg_init_write(struct nfs_pageio_descriptor *pgio, goto retry; } pgm = &pgio->pg_mirrors[i]; - pgm->pg_bsize = mirror->dss[dss_id].mirror_ds->ds_versions[0].wsize; + pgm->pg_bsize = mirror_ds->ds_versions[0].wsize; + nfs4_ff_layout_put_deviceid(mirror_ds); } if (NFS_SERVER(pgio->pg_inode)->flags & @@ -1310,14 +1328,16 @@ static void ff_layout_resend_pnfs_read(struct nfs_pgio_header *hdr) u32 idx = hdr->pgio_mirror_idx + 1; u32 new_idx = 0; u32 dss_id = 0; - struct nfs4_pnfs_ds *ds; + struct nfs4_ff_layout_ds *mirror_ds; - ds = ff_layout_choose_any_ds_for_read(hdr->lseg, idx, &new_idx, - hdr->args.offset, &dss_id); - if (IS_ERR(ds)) + mirror_ds = ff_layout_choose_any_ds_for_read(hdr->lseg, idx, &new_idx, + hdr->args.offset, &dss_id); + if (IS_ERR(mirror_ds)) { pnfs_error_mark_layout_for_return(hdr->inode, hdr->lseg); - else + } else { + nfs4_ff_layout_put_deviceid(mirror_ds); ff_layout_send_layouterror(hdr->lseg); + } pnfs_read_resend_pnfs(hdr, new_idx); } @@ -2238,6 +2258,7 @@ ff_layout_read_pagelist(struct nfs_pgio_header *hdr) struct rpc_clnt *ds_clnt; struct nfsd_file *localio; struct nfs4_ff_layout_mirror *mirror; + struct nfs4_ff_layout_ds *mirror_ds; const struct cred *ds_cred; loff_t offset = hdr->args.offset; u32 idx = hdr->pgio_mirror_idx; @@ -2255,22 +2276,24 @@ ff_layout_read_pagelist(struct nfs_pgio_header *hdr) FF_LAYOUT_LSEG(lseg)->stripe_unit, mirror->dss_count, offset); - ds = nfs4_ff_layout_prepare_ds(lseg, mirror, dss_id, false); + mirror_ds = ff_layout_get_mirror_ds(lseg->pls_layout, mirror, dss_id); + ds = nfs4_ff_layout_prepare_ds(lseg, mirror, mirror_ds, dss_id, false); if (IS_ERR(ds)) { ds_fatal_error = nfs_error_is_fatal(PTR_ERR(ds)); goto out_failed; } - ds_clnt = nfs4_ff_find_or_create_ds_client(mirror, ds->ds_clp, - hdr->inode, dss_id); + ds_clnt = nfs4_ff_find_or_create_ds_client(mirror_ds, ds->ds_clp, + hdr->inode); if (IS_ERR(ds_clnt)) goto out_failed; - ds_cred = ff_layout_get_ds_cred(mirror, &lseg->pls_range, hdr->cred, dss_id); + ds_cred = ff_layout_get_ds_cred(mirror, &lseg->pls_range, hdr->cred, + mirror_ds, dss_id); if (!ds_cred) goto out_failed; - vers = nfs4_ff_layout_ds_version(mirror, dss_id); + vers = nfs4_ff_layout_ds_version(mirror_ds); dprintk("%s USE DS: %s cl_count %d vers %d\n", __func__, ds->ds_remotestr, refcount_read(&ds->ds_clp->cl_count), vers); @@ -2282,7 +2305,8 @@ ff_layout_read_pagelist(struct nfs_pgio_header *hdr) if (fh) hdr->args.fh = fh; - nfs4_ff_layout_select_ds_stateid(mirror, dss_id, &hdr->args.stateid); + nfs4_ff_layout_select_ds_stateid(mirror, mirror_ds, dss_id, + &hdr->args.stateid); /* * Note that if we ever decide to split across DSes, @@ -2305,9 +2329,11 @@ ff_layout_read_pagelist(struct nfs_pgio_header *hdr) &ff_layout_read_call_ops_v4, 0, RPC_TASK_SOFTCONN, localio); put_cred(ds_cred); + nfs4_ff_layout_put_deviceid(mirror_ds); return PNFS_ATTEMPTED; out_failed: + nfs4_ff_layout_put_deviceid(mirror_ds); if (ff_layout_avoid_mds_available_ds(lseg) && !ds_fatal_error) return PNFS_TRY_AGAIN; if (ff_layout_no_fallback_to_mds(lseg)) { @@ -2333,6 +2359,7 @@ ff_layout_write_pagelist(struct nfs_pgio_header *hdr, int sync) struct rpc_clnt *ds_clnt; struct nfsd_file *localio; struct nfs4_ff_layout_mirror *mirror; + struct nfs4_ff_layout_ds *mirror_ds; const struct cred *ds_cred; loff_t offset = hdr->args.offset; int vers; @@ -2346,22 +2373,24 @@ ff_layout_write_pagelist(struct nfs_pgio_header *hdr, int sync) FF_LAYOUT_LSEG(lseg)->stripe_unit, mirror->dss_count, offset); - ds = nfs4_ff_layout_prepare_ds(lseg, mirror, dss_id, true); + mirror_ds = ff_layout_get_mirror_ds(lseg->pls_layout, mirror, dss_id); + ds = nfs4_ff_layout_prepare_ds(lseg, mirror, mirror_ds, dss_id, true); if (IS_ERR(ds)) { ds_fatal_error = nfs_error_is_fatal(PTR_ERR(ds)); goto out_failed; } - ds_clnt = nfs4_ff_find_or_create_ds_client(mirror, ds->ds_clp, - hdr->inode, dss_id); + ds_clnt = nfs4_ff_find_or_create_ds_client(mirror_ds, ds->ds_clp, + hdr->inode); if (IS_ERR(ds_clnt)) goto out_failed; - ds_cred = ff_layout_get_ds_cred(mirror, &lseg->pls_range, hdr->cred, dss_id); + ds_cred = ff_layout_get_ds_cred(mirror, &lseg->pls_range, hdr->cred, + mirror_ds, dss_id); if (!ds_cred) goto out_failed; - vers = nfs4_ff_layout_ds_version(mirror, dss_id); + vers = nfs4_ff_layout_ds_version(mirror_ds); dprintk("%s ino %llu sync %d req %zu@%llu DS: %s cl_count %d vers %d\n", __func__, hdr->inode->i_ino, sync, (size_t) hdr->args.count, @@ -2376,7 +2405,8 @@ ff_layout_write_pagelist(struct nfs_pgio_header *hdr, int sync) if (fh) hdr->args.fh = fh; - nfs4_ff_layout_select_ds_stateid(mirror, dss_id, &hdr->args.stateid); + nfs4_ff_layout_select_ds_stateid(mirror, mirror_ds, dss_id, + &hdr->args.stateid); /* * Note that if we ever decide to split across DSes, @@ -2398,9 +2428,11 @@ ff_layout_write_pagelist(struct nfs_pgio_header *hdr, int sync) &ff_layout_write_call_ops_v4, sync, RPC_TASK_SOFTCONN, localio); put_cred(ds_cred); + nfs4_ff_layout_put_deviceid(mirror_ds); return PNFS_ATTEMPTED; out_failed: + nfs4_ff_layout_put_deviceid(mirror_ds); if (ff_layout_avoid_mds_available_ds(lseg) && !ds_fatal_error) return PNFS_TRY_AGAIN; if (ff_layout_no_fallback_to_mds(lseg)) { @@ -2435,6 +2467,7 @@ static int ff_layout_initiate_commit(struct nfs_commit_data *data, int how) struct rpc_clnt *ds_clnt; struct nfsd_file *localio; struct nfs4_ff_layout_mirror *mirror; + struct nfs4_ff_layout_ds *mirror_ds = NULL; const struct cred *ds_cred; u32 idx, dss_id; int vers, ret; @@ -2447,20 +2480,22 @@ static int ff_layout_initiate_commit(struct nfs_commit_data *data, int how) idx = calc_mirror_idx_from_commit(lseg, data->ds_commit_index); mirror = FF_LAYOUT_COMP(lseg, idx); dss_id = calc_dss_id_from_commit(lseg, data->ds_commit_index); - ds = nfs4_ff_layout_prepare_ds(lseg, mirror, dss_id, true); + mirror_ds = ff_layout_get_mirror_ds(lseg->pls_layout, mirror, dss_id); + ds = nfs4_ff_layout_prepare_ds(lseg, mirror, mirror_ds, dss_id, true); if (IS_ERR(ds)) goto out_err; - ds_clnt = nfs4_ff_find_or_create_ds_client(mirror, ds->ds_clp, - data->inode, dss_id); + ds_clnt = nfs4_ff_find_or_create_ds_client(mirror_ds, ds->ds_clp, + data->inode); if (IS_ERR(ds_clnt)) goto out_err; - ds_cred = ff_layout_get_ds_cred(mirror, &lseg->pls_range, data->cred, dss_id); + ds_cred = ff_layout_get_ds_cred(mirror, &lseg->pls_range, data->cred, + mirror_ds, dss_id); if (!ds_cred) goto out_err; - vers = nfs4_ff_layout_ds_version(mirror, dss_id); + vers = nfs4_ff_layout_ds_version(mirror_ds); dprintk("%s ino %llu, how %d cl_count %d vers %d\n", __func__, data->inode->i_ino, how, refcount_read(&ds->ds_clp->cl_count), @@ -2486,8 +2521,10 @@ static int ff_layout_initiate_commit(struct nfs_commit_data *data, int how) &ff_layout_commit_call_ops_v4, how, RPC_TASK_SOFTCONN, localio); put_cred(ds_cred); + nfs4_ff_layout_put_deviceid(mirror_ds); return ret; out_err: + nfs4_ff_layout_put_deviceid(mirror_ds); pnfs_generic_prepare_to_resend_writes(data); pnfs_generic_commit_release(data); return -EAGAIN; @@ -2543,22 +2580,28 @@ static void ff_layout_cancel_io(struct pnfs_layout_segment *lseg) for (idx = 0; idx < flseg->mirror_array_cnt; idx++) { mirror = flseg->mirror_array[idx]; for (dss_id = 0; dss_id < mirror->dss_count; dss_id++) { - mirror_ds = mirror->dss[dss_id].mirror_ds; - if (IS_ERR_OR_NULL(mirror_ds)) + rcu_read_lock(); + mirror_ds = rcu_dereference(mirror->dss[dss_id].mirror_ds); + if (IS_ERR_OR_NULL(mirror_ds) || + !atomic_inc_not_zero(&mirror_ds->id_node.ref)) { + rcu_read_unlock(); continue; - ds = mirror->dss[dss_id].mirror_ds->ds; + } + rcu_read_unlock(); + ds = mirror_ds->ds; if (!ds) - continue; + goto next; ds_clp = ds->ds_clp; if (!ds_clp) - continue; + goto next; clnt = ds_clp->cl_rpcclient; if (!clnt) - continue; - if (!rpc_cancel_tasks(clnt, -ECANCELED, - ff_layout_match_io, lseg)) - continue; - rpc_clnt_disconnect(clnt); + goto next; + rpc_cancel_tasks_and_disconnect(clnt, -ECANCELED, + ff_layout_match_io, + lseg); +next: + nfs4_ff_layout_put_deviceid(mirror_ds); } } } @@ -2771,7 +2814,7 @@ ff_layout_prepare_layoutreturn(struct nfs4_layoutreturn_args *args) spin_lock(&args->inode->i_lock); ff_args->num_dev = ff_layout_mirror_prepare_stats( - &ff_layout->generic_hdr, &ff_args->devinfo[0], + &ff_layout->generic_hdr, &ff_args->devinfo[0], &ff_args->priv[0], ARRAY_SIZE(ff_args->devinfo), NFS4_FF_OP_LAYOUTRETURN); spin_unlock(&args->inode->i_lock); @@ -2946,10 +2989,11 @@ ff_layout_encode_io_latency(struct xdr_stream *xdr, static void ff_layout_encode_ff_layoutupdate(struct xdr_stream *xdr, const struct nfs42_layoutstat_devinfo *devinfo, - struct nfs4_ff_layout_ds_stripe *dss_info) + struct nfs4_ff_layoutstat_priv *priv) { + struct nfs4_ff_layout_ds_stripe *dss_info = priv->dss_info; struct nfs4_pnfs_ds_addr *da; - struct nfs4_pnfs_ds *ds = dss_info->mirror_ds->ds; + struct nfs4_pnfs_ds *ds = priv->mirror_ds->ds; struct nfs_fh *fh = &dss_info->fh_versions[0]; __be32 *p; @@ -2996,10 +3040,10 @@ ff_layout_encode_layoutstats(struct xdr_stream *xdr, const void *args, static void ff_layout_free_layoutstats(struct nfs4_xdr_opaque_data *opaque) { - struct nfs4_ff_layout_ds_stripe *dss_info = opaque->data; - struct nfs4_ff_layout_mirror *mirror = dss_info->mirror; + struct nfs4_ff_layoutstat_priv *priv = opaque->data; - ff_layout_put_mirror(mirror); + nfs4_ff_layout_put_deviceid(priv->mirror_ds); + ff_layout_put_mirror(priv->dss_info->mirror); } static const struct nfs4_xdr_opaque_ops layoutstat_ops = { @@ -3010,20 +3054,23 @@ static const struct nfs4_xdr_opaque_ops layoutstat_ops = { static int ff_layout_mirror_prepare_stats(struct pnfs_layout_hdr *lo, struct nfs42_layoutstat_devinfo *devinfo, + struct nfs4_ff_layoutstat_priv *priv, int dev_limit, enum nfs4_ff_op_type type) { struct nfs4_flexfile_layout *ff_layout = FF_LAYOUT_FROM_HDR(lo); struct nfs4_ff_layout_mirror *mirror; struct nfs4_ff_layout_ds_stripe *dss_info; - struct nfs4_deviceid_node *dev; + struct nfs4_ff_layout_ds *mirror_ds; int i = 0, dss_id; + rcu_read_lock(); list_for_each_entry(mirror, &ff_layout->mirrors, mirrors) { for (dss_id = 0; dss_id < mirror->dss_count; ++dss_id) { dss_info = &mirror->dss[dss_id]; if (i >= dev_limit) break; - if (IS_ERR_OR_NULL(dss_info->mirror_ds)) + mirror_ds = rcu_dereference(dss_info->mirror_ds); + if (IS_ERR_OR_NULL(mirror_ds)) continue; if (!test_and_clear_bit(NFS4_FF_MIRROR_STAT_AVAIL, &mirror->flags) && @@ -3032,9 +3079,12 @@ ff_layout_mirror_prepare_stats(struct pnfs_layout_hdr *lo, /* mirror refcount put in cleanup_layoutstats */ if (!refcount_inc_not_zero(&mirror->ref)) continue; - dev = &dss_info->mirror_ds->id_node; + /* The pin holds a reference; it is exchanged out only + * under i_lock. Put in ff_layout_free_layoutstats(). + */ + atomic_inc(&mirror_ds->id_node.ref); memcpy(&devinfo->dev_id, - &dev->deviceid, + &mirror_ds->id_node.deviceid, NFS4_DEVICEID4_SIZE); devinfo->offset = 0; devinfo->length = NFS4_MAX_UINT64; @@ -3050,12 +3100,16 @@ ff_layout_mirror_prepare_stats(struct pnfs_layout_hdr *lo, spin_unlock(&mirror->lock); devinfo->layout_type = LAYOUT_FLEX_FILES; devinfo->ld_private.ops = &layoutstat_ops; - devinfo->ld_private.data = &mirror->dss[dss_id]; + priv->dss_info = dss_info; + priv->mirror_ds = mirror_ds; + devinfo->ld_private.data = priv; devinfo++; + priv++; i++; } } + rcu_read_unlock(); return i; } @@ -3063,21 +3117,28 @@ static int ff_layout_prepare_layoutstats(struct nfs42_layoutstat_args *args) { struct pnfs_layout_hdr *lo; struct nfs4_flexfile_layout *ff_layout; + struct nfs4_ff_layoutstat_priv *priv; const int dev_count = PNFS_LAYOUTSTATS_MAXDEV; - /* For now, send at most PNFS_LAYOUTSTATS_MAXDEV statistics */ - args->devinfo = kmalloc_objs(*args->devinfo, dev_count, - nfs_io_gfp_mask()); + /* + * For now, send at most PNFS_LAYOUTSTATS_MAXDEV statistics. + * The per-devinfo private entries are co-allocated after the + * devinfo array and freed along with it. + */ + args->devinfo = kmalloc(dev_count * (sizeof(*args->devinfo) + + sizeof(*priv)), + nfs_io_gfp_mask()); if (!args->devinfo) return -ENOMEM; + priv = (struct nfs4_ff_layoutstat_priv *)&args->devinfo[dev_count]; spin_lock(&args->inode->i_lock); lo = NFS_I(args->inode)->layout; if (lo && pnfs_layout_is_valid(lo)) { ff_layout = FF_LAYOUT_FROM_HDR(lo); args->num_dev = ff_layout_mirror_prepare_stats( - &ff_layout->generic_hdr, &args->devinfo[0], dev_count, - NFS4_FF_OP_LAYOUTSTATS); + &ff_layout->generic_hdr, &args->devinfo[0], priv, + dev_count, NFS4_FF_OP_LAYOUTSTATS); } else args->num_dev = 0; spin_unlock(&args->inode->i_lock); diff --git a/fs/nfs/flexfilelayout/flexfilelayout.h b/fs/nfs/flexfilelayout/flexfilelayout.h index ec69cd1c3ae9..24de108af2cf 100644 --- a/fs/nfs/flexfilelayout/flexfilelayout.h +++ b/fs/nfs/flexfilelayout/flexfilelayout.h @@ -79,7 +79,7 @@ struct nfs4_ff_layout_ds_stripe { struct nfs4_ff_layout_mirror *mirror; struct nfs4_deviceid devid; u32 efficiency; - struct nfs4_ff_layout_ds *mirror_ds; + struct nfs4_ff_layout_ds __rcu *mirror_ds; u32 fh_versions_cnt; struct nfs_fh *fh_versions; nfs4_stateid stateid; @@ -124,9 +124,20 @@ struct nfs4_flexfile_layout { unsigned long flags; }; +/* + * Per-devinfo private data for a layoutstats/layoutreturn encode: the + * stripe the stats describe plus a reference on its device node so the + * node (and its DS addresses) stay valid until the XDR encode runs. + */ +struct nfs4_ff_layoutstat_priv { + struct nfs4_ff_layout_ds_stripe *dss_info; + struct nfs4_ff_layout_ds *mirror_ds; +}; + struct nfs4_flexfile_layoutreturn_args { struct list_head errors; struct nfs42_layoutstat_devinfo devinfo[FF_LAYOUTSTATS_MAXDEV]; + struct nfs4_ff_layoutstat_priv priv[FF_LAYOUTSTATS_MAXDEV]; unsigned int num_errors; unsigned int num_dev; struct page *pages[1]; @@ -207,9 +218,9 @@ ff_layout_no_read_on_rw(struct pnfs_layout_segment *lseg) } static inline int -nfs4_ff_layout_ds_version(const struct nfs4_ff_layout_mirror *mirror, u32 dss_id) +nfs4_ff_layout_ds_version(const struct nfs4_ff_layout_ds *mirror_ds) { - return mirror->dss[dss_id].mirror_ds->ds_versions[0].version; + return mirror_ds->ds_versions[0].version; } static inline u32 @@ -245,23 +256,29 @@ struct nfs_fh * nfs4_ff_layout_select_ds_fh(struct nfs4_ff_layout_mirror *mirror, u32 dss_id); void nfs4_ff_layout_select_ds_stateid(const struct nfs4_ff_layout_mirror *mirror, + const struct nfs4_ff_layout_ds *mirror_ds, u32 dss_id, nfs4_stateid *stateid); +struct nfs4_ff_layout_ds * +ff_layout_get_mirror_ds(struct pnfs_layout_hdr *lo, + struct nfs4_ff_layout_mirror *mirror, + u32 dss_id); struct nfs4_pnfs_ds * nfs4_ff_layout_prepare_ds(struct pnfs_layout_segment *lseg, struct nfs4_ff_layout_mirror *mirror, + struct nfs4_ff_layout_ds *mirror_ds, u32 dss_id, bool fail_return); struct rpc_clnt * -nfs4_ff_find_or_create_ds_client(struct nfs4_ff_layout_mirror *mirror, +nfs4_ff_find_or_create_ds_client(const struct nfs4_ff_layout_ds *mirror_ds, struct nfs_client *ds_clp, - struct inode *inode, - u32 dss_id); + struct inode *inode); const struct cred *ff_layout_get_ds_cred(struct nfs4_ff_layout_mirror *mirror, const struct pnfs_layout_range *range, const struct cred *mdscred, + const struct nfs4_ff_layout_ds *mirror_ds, u32 dss_id); bool ff_layout_avoid_mds_available_ds(struct pnfs_layout_segment *lseg); bool ff_layout_avoid_read_on_rw(struct pnfs_layout_segment *lseg); diff --git a/fs/nfs/flexfilelayout/flexfilelayoutdev.c b/fs/nfs/flexfilelayout/flexfilelayoutdev.c index 6cd3859d4a24..3cef6a4a51a7 100644 --- a/fs/nfs/flexfilelayout/flexfilelayoutdev.c +++ b/fs/nfs/flexfilelayout/flexfilelayoutdev.c @@ -304,48 +304,79 @@ nfs4_ff_layout_select_ds_fh(struct nfs4_ff_layout_mirror *mirror, u32 dss_id) void nfs4_ff_layout_select_ds_stateid(const struct nfs4_ff_layout_mirror *mirror, + const struct nfs4_ff_layout_ds *mirror_ds, u32 dss_id, nfs4_stateid *stateid) { - if (nfs4_ff_layout_ds_version(mirror, dss_id) == 4) + if (nfs4_ff_layout_ds_version(mirror_ds) == 4) nfs4_stateid_copy(stateid, &mirror->dss[dss_id].stateid); } -static bool -ff_layout_init_mirror_ds(struct pnfs_layout_hdr *lo, - struct nfs4_ff_layout_mirror *mirror, - u32 dss_id) +/* + * Resolve the stripe's deviceid on first use and pin the node on the + * mirror. Returns a node the caller must put, or an ERR_PTR. + */ +struct nfs4_ff_layout_ds * +ff_layout_get_mirror_ds(struct pnfs_layout_hdr *lo, + struct nfs4_ff_layout_mirror *mirror, + u32 dss_id) { + struct nfs4_ff_layout_ds *mirror_ds, *old; + struct nfs4_deviceid_node *node; + if (mirror == NULL) - goto outerr; - if (mirror->dss[dss_id].mirror_ds == NULL) { - struct nfs4_deviceid_node *node; - struct nfs4_ff_layout_ds *mirror_ds = ERR_PTR(-ENODEV); - - node = nfs4_find_get_deviceid(NFS_SERVER(lo->plh_inode), - &mirror->dss[dss_id].devid, lo->plh_lc_cred, - GFP_KERNEL); - if (node) - mirror_ds = FF_LAYOUT_MIRROR_DS(node); - - /* check for race with another call to this function */ - if (cmpxchg(&mirror->dss[dss_id].mirror_ds, NULL, mirror_ds) && - mirror_ds != ERR_PTR(-ENODEV)) - nfs4_put_deviceid_node(node); + return ERR_PTR(-ENODEV); + +retry: + rcu_read_lock(); + mirror_ds = rcu_dereference(mirror->dss[dss_id].mirror_ds); + if (mirror_ds && !IS_ERR(mirror_ds) && + atomic_inc_not_zero(&mirror_ds->id_node.ref)) { + rcu_read_unlock(); + return mirror_ds; + } + rcu_read_unlock(); + if (IS_ERR(mirror_ds)) + return mirror_ds; + if (mirror_ds != NULL) + /* raced with a reset; the field is being re-pointed */ + goto retry; + + node = nfs4_find_get_deviceid(NFS_SERVER(lo->plh_inode), + &mirror->dss[dss_id].devid, lo->plh_lc_cred, + GFP_KERNEL); + if (node) { + mirror_ds = FF_LAYOUT_MIRROR_DS(node); + /* + * Take the caller's reference before the pointer becomes + * visible below, so a concurrent reset of the installed + * pointer cannot drop the last reference under us. + */ + atomic_inc(&node->ref); + } else { + mirror_ds = ERR_PTR(-ENODEV); } - if (IS_ERR(mirror->dss[dss_id].mirror_ds)) - goto outerr; + /* check for race with another call to this function */ + old = unrcu_pointer(cmpxchg(&mirror->dss[dss_id].mirror_ds, + NULL, RCU_INITIALIZER(mirror_ds))); + if (old == NULL) + return mirror_ds; - return true; -outerr: - return false; + /* lost the race; use the winner's node instead */ + if (node) { + nfs4_put_deviceid_node(node); + nfs4_put_deviceid_node(node); + } + goto retry; } /** * nfs4_ff_layout_prepare_ds - prepare a DS connection for an RPC call * @lseg: the layout segment we're operating on * @mirror: layout mirror describing the DS to use + * @mirror_ds: referenced device node for the stripe, from + * ff_layout_get_mirror_ds() (may be an ERR_PTR) * @dss_id: DS stripe id to select stripe to use * @fail_return: return layout on connect failure? * @@ -363,6 +394,7 @@ ff_layout_init_mirror_ds(struct pnfs_layout_hdr *lo, struct nfs4_pnfs_ds * nfs4_ff_layout_prepare_ds(struct pnfs_layout_segment *lseg, struct nfs4_ff_layout_mirror *mirror, + struct nfs4_ff_layout_ds *mirror_ds, u32 dss_id, bool fail_return) { @@ -372,10 +404,10 @@ nfs4_ff_layout_prepare_ds(struct pnfs_layout_segment *lseg, unsigned int max_payload; int status = -EAGAIN; - if (!ff_layout_init_mirror_ds(lseg->pls_layout, mirror, dss_id)) + if (IS_ERR_OR_NULL(mirror_ds)) goto noconnect; - ds = mirror->dss[dss_id].mirror_ds->ds; + ds = mirror_ds->ds; if (READ_ONCE(ds->ds_clp)) goto out; /* matching smp_wmb() in _nfs4_pnfs_v3/4_ds_connect */ @@ -384,11 +416,11 @@ nfs4_ff_layout_prepare_ds(struct pnfs_layout_segment *lseg, /* FIXME: For now we assume the server sent only one version of NFS * to use for the DS. */ - status = nfs4_pnfs_ds_connect(s, ds, &mirror->dss[dss_id].mirror_ds->id_node, + status = nfs4_pnfs_ds_connect(s, ds, &mirror_ds->id_node, dataserver_timeo, dataserver_retrans, - mirror->dss[dss_id].mirror_ds->ds_versions[0].version, - mirror->dss[dss_id].mirror_ds->ds_versions[0].minor_version, - mirror->dss[dss_id].mirror_ds->ds_versions[0].tightly_coupled); + mirror_ds->ds_versions[0].version, + mirror_ds->ds_versions[0].minor_version, + mirror_ds->ds_versions[0].tightly_coupled); /* connect success, check rsize/wsize limit */ if (!status) { @@ -401,10 +433,10 @@ nfs4_ff_layout_prepare_ds(struct pnfs_layout_segment *lseg, max_payload = nfs_block_size(rpc_max_payload(ds->ds_clp->cl_rpcclient), NULL); - if (mirror->dss[dss_id].mirror_ds->ds_versions[0].rsize > max_payload) - mirror->dss[dss_id].mirror_ds->ds_versions[0].rsize = max_payload; - if (mirror->dss[dss_id].mirror_ds->ds_versions[0].wsize > max_payload) - mirror->dss[dss_id].mirror_ds->ds_versions[0].wsize = max_payload; + if (mirror_ds->ds_versions[0].rsize > max_payload) + mirror_ds->ds_versions[0].rsize = max_payload; + if (mirror_ds->ds_versions[0].wsize > max_payload) + mirror_ds->ds_versions[0].wsize = max_payload; goto out; } noconnect: @@ -424,11 +456,12 @@ const struct cred * ff_layout_get_ds_cred(struct nfs4_ff_layout_mirror *mirror, const struct pnfs_layout_range *range, const struct cred *mdscred, + const struct nfs4_ff_layout_ds *mirror_ds, u32 dss_id) { const struct cred *cred; - if (mirror && !mirror->dss[dss_id].mirror_ds->ds_versions[0].tightly_coupled) { + if (mirror && !mirror_ds->ds_versions[0].tightly_coupled) { cred = ff_layout_get_mirror_cred(mirror, range->iomode, dss_id); if (!cred) cred = get_cred(mdscred); @@ -440,20 +473,18 @@ ff_layout_get_ds_cred(struct nfs4_ff_layout_mirror *mirror, /** * nfs4_ff_find_or_create_ds_client - Find or create a DS rpc client - * @mirror: pointer to the mirror + * @mirror_ds: device node for the stripe * @ds_clp: nfs_client for the DS * @inode: pointer to inode - * @dss_id: DS stripe id * * Find or create a DS rpc client with th MDS server rpc client auth flavor * in the nfs_client cl_ds_clients list. */ struct rpc_clnt * -nfs4_ff_find_or_create_ds_client(struct nfs4_ff_layout_mirror *mirror, - struct nfs_client *ds_clp, struct inode *inode, - u32 dss_id) +nfs4_ff_find_or_create_ds_client(const struct nfs4_ff_layout_ds *mirror_ds, + struct nfs_client *ds_clp, struct inode *inode) { - switch (mirror->dss[dss_id].mirror_ds->ds_versions[0].version) { + switch (mirror_ds->ds_versions[0].version) { case 3: /* For NFSv3 DS, flavor is set when creating DS connections */ return ds_clp->cl_rpcclient; @@ -558,49 +589,60 @@ unsigned int ff_layout_fetch_ds_ioerr(struct pnfs_layout_hdr *lo, static bool ff_read_layout_has_available_ds(struct pnfs_layout_segment *lseg) { struct nfs4_ff_layout_mirror *mirror; - struct nfs4_deviceid_node *devid; + struct nfs4_ff_layout_ds *mirror_ds; + bool ret = false; u32 idx, dss_id; + rcu_read_lock(); for (idx = 0; idx < FF_LAYOUT_MIRROR_COUNT(lseg); idx++) { mirror = FF_LAYOUT_COMP(lseg, idx); if (!mirror) continue; for (dss_id = 0; dss_id < mirror->dss_count; dss_id++) { - if (!mirror->dss[dss_id].mirror_ds) - return true; - if (IS_ERR(mirror->dss[dss_id].mirror_ds)) + mirror_ds = rcu_dereference(mirror->dss[dss_id].mirror_ds); + if (!mirror_ds) { + ret = true; + goto out; + } + if (IS_ERR(mirror_ds)) continue; - devid = &mirror->dss[dss_id].mirror_ds->id_node; - if (!nfs4_test_deviceid_unavailable(devid)) - return true; + if (!nfs4_test_deviceid_unavailable(&mirror_ds->id_node)) { + ret = true; + goto out; + } } } - - return false; +out: + rcu_read_unlock(); + return ret; } static bool ff_rw_layout_has_available_ds(struct pnfs_layout_segment *lseg) { struct nfs4_ff_layout_mirror *mirror; - struct nfs4_deviceid_node *devid; + struct nfs4_ff_layout_ds *mirror_ds; + bool ret = false; u32 idx, dss_id; + rcu_read_lock(); for (idx = 0; idx < FF_LAYOUT_MIRROR_COUNT(lseg); idx++) { mirror = FF_LAYOUT_COMP(lseg, idx); if (!mirror) - return false; + goto out; for (dss_id = 0; dss_id < mirror->dss_count; dss_id++) { - if (IS_ERR(mirror->dss[dss_id].mirror_ds)) - return false; - if (!mirror->dss[dss_id].mirror_ds) + mirror_ds = rcu_dereference(mirror->dss[dss_id].mirror_ds); + if (IS_ERR(mirror_ds)) + goto out; + if (!mirror_ds) continue; - devid = &mirror->dss[dss_id].mirror_ds->id_node; - if (nfs4_test_deviceid_unavailable(devid)) - return false; + if (nfs4_test_deviceid_unavailable(&mirror_ds->id_node)) + goto out; } } - - return FF_LAYOUT_MIRROR_COUNT(lseg) != 0; + ret = FF_LAYOUT_MIRROR_COUNT(lseg) != 0; +out: + rcu_read_unlock(); + return ret; } static bool ff_layout_has_available_ds(struct pnfs_layout_segment *lseg) diff --git a/fs/nfs/inode.c b/fs/nfs/inode.c index 3022454f7698..beffa3a2968c 100644 --- a/fs/nfs/inode.c +++ b/fs/nfs/inode.c @@ -623,28 +623,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; } @@ -659,7 +683,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); } @@ -678,6 +706,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) { @@ -740,7 +769,7 @@ nfs_setattr(struct mnt_idmap *idmap, struct dentry *dentry, } else if (nfs_have_delegated_atime(inode) && attr->ia_valid & ATTR_ATIME && !(attr->ia_valid & ATTR_MTIME)) { - if (!(attr->ia_valid & ATTR_ATIME_SET)) { + if (!(attr->ia_valid & (ATTR_ATIME_SET | ATTR_TIMES_SET))) { nfs_update_delegated_atime(inode); attr->ia_valid &= ~ATTR_ATIME; } @@ -802,10 +831,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; @@ -831,6 +864,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..d5859e8c2a2a 100644 --- a/fs/nfs/localio.c +++ b/fs/nfs/localio.c @@ -203,15 +203,22 @@ void nfs_local_probe_async_work(struct work_struct *work) struct nfs_client *clp = container_of(work, struct nfs_client, cl_local_probe_work); - if (!refcount_inc_not_zero(&clp->cl_count)) - return; nfs_local_probe(clp); + /* The reference nfs_local_probe_async() took for this work */ nfs_put_client(clp); } +/* + * The work is part of the client, so it holds a reference on the client + * from when it is queued until it has run: the last nfs_put_client() + * cannot free the client under a queued probe. + */ void nfs_local_probe_async(struct nfs_client *clp) { - queue_work(nfsiod_workqueue, &clp->cl_local_probe_work); + if (!refcount_inc_not_zero(&clp->cl_count)) + return; + if (!queue_work(nfsiod_workqueue, &clp->cl_local_probe_work)) + nfs_put_client(clp); /* already queued, with its reference */ } EXPORT_SYMBOL_GPL(nfs_local_probe_async); diff --git a/fs/nfs/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 @@ static int process_copy_commit(struct file *dst, loff_t pos_dst, * @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 @@ static int process_copy_commit(struct file *dst, loff_t pos_dst, * 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 028459fb6edb..2a27d17a86b1 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); diff --git a/fs/nfs/pnfs.c b/fs/nfs/pnfs.c index 0d51be32b638..ff85b82a1e22 100644 --- a/fs/nfs/pnfs.c +++ b/fs/nfs/pnfs.c @@ -2071,7 +2071,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/notify/fanotify/fanotify.h b/fs/notify/fanotify/fanotify.h index 87ba788574bf..c25cf5c1fc70 100644 --- a/fs/notify/fanotify/fanotify.h +++ b/fs/notify/fanotify/fanotify.h @@ -444,7 +444,7 @@ struct fanotify_perm_event { struct fanotify_event fae; struct path path; loff_t pos; /* FANOTIFY_NO_RANGE if unavailable */ - size_t count; + u64 count; u32 response; /* userspace answer to the event */ unsigned short state; /* state of the event */ unsigned short watchdog_cnt; /* already scanned by watchdog? */ diff --git a/fs/notify/fsnotify.c b/fs/notify/fsnotify.c index 7e2f330fd283..8657bb94dfa8 100644 --- a/fs/notify/fsnotify.c +++ b/fs/notify/fsnotify.c @@ -157,7 +157,7 @@ static inline __u32 fsnotify_object_watched(struct inode *inode, __u32 mnt_mask, /* Report pre-content event with optional range info */ int fsnotify_pre_content(const struct path *path, const loff_t *ppos, - size_t count) + u64 count) { struct file_range range; diff --git a/fs/ntfs/attrib.c b/fs/ntfs/attrib.c index ee54ebdeb7c7..0bd4b20132df 100644 --- a/fs/ntfs/attrib.c +++ b/fs/ntfs/attrib.c @@ -704,17 +704,20 @@ static bool ntfs_resident_attr_value_get(const struct attr_record *a, struct ntfs_resident_attr_value *value) { u32 attr_len; + u32 min_len; u16 value_offset; attr_len = le32_to_cpu(a->length); - if (attr_len < offsetof(struct attr_record, data.resident.reserved) + - sizeof(a->data.resident.reserved)) + min_len = offsetof(struct attr_record, data.resident.reserved) + + sizeof(a->data.resident.reserved); + if (attr_len < min_len) return false; value->len = le32_to_cpu(a->data.resident.value_length); value_offset = le16_to_cpu(a->data.resident.value_offset); - if (value->len > attr_len || value_offset > attr_len - value->len) + if (value_offset < min_len || value->len > attr_len || + value_offset > attr_len - value->len) return false; value->data = (const u8 *)a + value_offset; diff --git a/fs/ntfs/dir.c b/fs/ntfs/dir.c index b72990c2dd58..72edf9f2df8a 100644 --- a/fs/ntfs/dir.c +++ b/fs/ntfs/dir.c @@ -307,6 +307,20 @@ u64 ntfs_lookup_inode_by_name(struct ntfs_inode *dir_ni, const __le16 *uname, 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 diff --git a/fs/ntfs/index.c b/fs/ntfs/index.c index 9a23d0786959..676ae2267814 100644 --- a/fs/ntfs/index.c +++ b/fs/ntfs/index.c @@ -41,9 +41,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); @@ -97,12 +99,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; @@ -768,6 +788,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); @@ -1547,9 +1571,9 @@ static int ntfs_ih_insert(struct index_header *ih, struct index_entry *orig_ie, ie_node = ntfs_ie_get_by_pos(ih, pos); old_vcn = ntfs_ie_get_vcn(ie_node); ntfs_ie_set_vcn(ie_node, new_vcn); + ntfs_ie_set_vcn(ie, old_vcn); ntfs_ie_insert(ih, ie, ie_node); - ntfs_ie_set_vcn(ie_node, old_vcn); out: kfree(ie); return ret; diff --git a/fs/ntfs/inode.c b/fs/ntfs/inode.c index 64c415edc398..907fe8ecb2a3 100644 --- a/fs/ntfs/inode.c +++ b/fs/ntfs/inode.c @@ -3630,7 +3630,7 @@ s64 ntfs_inode_attr_pread(struct inode *vi, s64 pos, s64 count, u8 *buf) mutex_unlock(&ni->mrec_lock); return -EINVAL; } - if (pos + count > isize) + if (count > isize - pos) count = isize - pos; if (!NInoNonResident(ni)) { diff --git a/fs/ntfs/namei.c b/fs/ntfs/namei.c index 3e0adb9a0ea4..850555bc22b2 100644 --- a/fs/ntfs/namei.c +++ b/fs/ntfs/namei.c @@ -449,8 +449,10 @@ static struct ntfs_inode *__ntfs_create(struct mnt_idmap *idmap, struct inode *d #ifdef CONFIG_NTFS_FS_POSIX_ACL if (!S_ISLNK(mode) && (sb->s_flags & SB_POSIXACL)) { err = ntfs_init_acl(idmap, vi, dir); - if (err) - goto err_out; + if (err) { + iput(vi); + return ERR_PTR(err); + } } else #endif { diff --git a/fs/overlayfs/dir.c b/fs/overlayfs/dir.c index c77af9a79d88..facc3f942640 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 @@ static int ovl_maybe_lookup_lowerdata(struct dentry *dentry) out_err: pr_warn_ratelimited("lazy lowerdata lookup failed (%pd2, err=%i)\n", dentry, err); + /* + * The data of a metacopy file is missing or is not a regular file in + * the data-only layers: the layers are corrupted. Do not return the + * error of the lookup (e.g. ENOENT) to the caller, it would make the + * file look like it does not exist. + */ + if (err != -ENOMEM) + err = -EIO; goto out; } @@ -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 a5aa22cc79a8..21b4cf97bb0a 100644 --- a/fs/overlayfs/overlayfs.h +++ b/fs/overlayfs/overlayfs.h @@ -74,9 +74,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, }; @@ -580,6 +586,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); @@ -630,11 +637,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 80cad4ea96a3..04c9ddf6f357 100644 --- a/fs/overlayfs/ovl_entry.h +++ b/fs/overlayfs/ovl_entry.h @@ -24,6 +24,8 @@ struct ovl_config { struct ovl_sb { struct super_block *sb; dev_t pseudo_dev; + /* Idmap of the first lower layer on this fs */ + const struct mnt_idmap *lower_idmap; /* Unusable (conflicting) uuid */ bool bad_uuid; /* Used as a lower layer (but maybe also as upper) */ diff --git a/fs/overlayfs/params.c b/fs/overlayfs/params.c index 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) { @@ -906,6 +928,13 @@ int ovl_fs_params_verify(const struct ovl_fs_context *ctx, config->uuid = OVL_UUID_NULL; } + /* + * Resolve redirect_dir=off to the default redirect follow mode. + * 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 c06bfe9765e2..5cbf11bfedb0 100644 --- a/fs/overlayfs/super.c +++ b/fs/overlayfs/super.c @@ -680,7 +680,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; @@ -744,9 +744,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; @@ -823,7 +825,7 @@ static int ovl_make_workdir(struct super_block *sb, struct ovl_fs *ofs, 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; @@ -852,7 +854,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, @@ -1120,6 +1122,29 @@ static int ovl_get_layers(struct super_block *sb, struct ovl_fs *ofs, return err; } + /* + * Lower file handles identify the lower fs, but not the layer, + * so with different idmaps on the same lower fs, index and + * nfs_export may decode a file handle through a layer with the + * wrong idmap. Following copy up origin without index is only + * used for st_ino, which does not depend on the idmap. + */ + if (i < nr_merged_lower && + (ofs->config.index || ofs->config.nfs_export)) { + const struct mnt_idmap *idmap = mnt_idmap(mnt); + struct ovl_sb *fs = &ofs->fs[fsid]; + + if (!fs->lower_idmap) { + fs->lower_idmap = idmap; + } else if (fs->lower_idmap != idmap) { + pr_err("lower layer '%pd2' conflicts with idmap of another lower layer on the same fs, mount with '-o index=off,nfs_export=off' to override.\n", + l->path.dentry); + iput(trap); + kern_unmount(mnt); + return -EINVAL; + } + } + /* * Make lower layers R/O. That way fchmod/fchown on lower file * will fail instead of modifying lower fs. @@ -1464,7 +1489,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; @@ -1598,13 +1624,23 @@ int ovl_fill_super(struct super_block *sb, struct fs_context *fc) return err; } +static void ovl_kill_sb(struct super_block *sb) +{ + struct ovl_fs *ofs = OVL_FS(sb); + + /* Nothing can modify them now, do not hold them across the sync */ + if (ofs) + ovl_inuse_unlock_all(ofs); + kill_anon_super(sb); +} + struct file_system_type ovl_fs_type = { .owner = THIS_MODULE, .name = "overlay", .init_fs_context = ovl_init_fs_context, .parameters = ovl_parameter_spec, .fs_flags = FS_USERNS_MOUNT | 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 04103a6741ba..b31b8f7d7ce0 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 03422f49be65..c3e12616cb6b 100644 --- a/fs/pidfs.c +++ b/fs/pidfs.c @@ -590,6 +590,14 @@ static long pidfd_ioctl(struct file *file, unsigned int cmd, unsigned long arg) if (arg) return -EINVAL; + /* + * Require the target to be visible in the caller's pid namespace + * for operations that grant access to its resources, mirroring + * procfs and PIDFD_GET_INFO. + */ + if (!pid_in_current_pidns(pidfd_pid(file))) + return -EREMOTE; + /* * We're trying to open a file descriptor to the namespace so perform a * filesystem cred ptrace check. Hold @task's exec_update_lock for the diff --git a/fs/proc/proc_sysctl.c b/fs/proc/proc_sysctl.c index 04a382178c65..eb10dbec16c5 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 ccaaa454dce0..a7043e234e2f 100644 --- a/fs/read_write.c +++ b/fs/read_write.c @@ -333,13 +333,15 @@ loff_t default_llseek(struct file *file, loff_t offset, int whence) { struct inode *inode = file_inode(file); loff_t retval; + loff_t eof; retval = inode_lock_killable(inode); if (retval) return retval; + eof = i_size_read(inode); switch (whence) { case SEEK_END: - offset += i_size_read(inode); + offset += eof; break; case SEEK_CUR: if (offset == 0) { @@ -354,7 +356,7 @@ loff_t default_llseek(struct file *file, loff_t offset, int whence) * long as offset isn't at the end of the file then the * offset is data. */ - if (offset >= inode->i_size) { + if ((unsigned long long)offset >= eof) { retval = -ENXIO; goto out; } @@ -365,11 +367,11 @@ loff_t default_llseek(struct file *file, loff_t offset, int whence) * as long as offset isn't i_size or larger, return * i_size. */ - if (offset >= inode->i_size) { + if ((unsigned long long)offset >= eof) { retval = -ENXIO; goto out; } - offset = inode->i_size; + offset = eof; break; } retval = -EINVAL; diff --git a/fs/smb/client/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 e37cf5043f8f..388140680a95 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 @@ sid_to_id(struct cifs_sb_info *cifs_sb, struct smb_sid *psid, */ 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 c1f99d7007b1..5a22796f2e95 100644 --- a/fs/smb/client/cifsfs.c +++ b/fs/smb/client/cifsfs.c @@ -165,6 +165,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; /* @@ -298,6 +299,15 @@ static void cifs_kill_sb(struct super_block *sb) { struct cifs_sb_info *cifs_sb = CIFS_SB(sb); + /* + * 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 (atomic_read(&cifs_sb->umount_aborts)) + WRITE_ONCE(cifs_sb->exiting, true); + /* * We need to release all dentries for the cached directories * and close all deferred file handles before we kill the sb. @@ -837,6 +847,7 @@ static void cifs_umount_begin(struct super_block *sb) if (cifs_sb == NULL) return; + atomic_inc(&cifs_sb->umount_aborts); tcon = cifs_sb_master_tcon(cifs_sb); spin_lock(&cifs_tcp_ses_lock); @@ -2125,9 +2136,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) @@ -2198,6 +2216,8 @@ init_cifs(void) cifs_destroy_netfs(); out_destroy_inodecache: cifs_destroy_inodecache(); +out_destroy_writeback_wq: + destroy_workqueue(cifs_writeback_wq); out_destroy_cfid_put_wq: destroy_workqueue(cfid_put_wq); out_destroy_serverclose_wq: @@ -2243,6 +2263,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 92174c4483a2..68f56547ef72 100644 --- a/fs/smb/client/cifsglob.h +++ b/fs/smb/client/cifsglob.h @@ -1486,6 +1486,7 @@ struct cifs_io_request { struct netfs_io_request rreq; struct cifsFileInfo *cfile; pid_t pid; + int umount_aborts; }; /* asynchronous read support */ @@ -1502,6 +1503,7 @@ struct cifs_io_subrequest { bool replay; 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 @@ -1895,6 +1897,7 @@ 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), }; #define MID_FREE 0 @@ -2145,6 +2148,7 @@ extern struct workqueue_struct *cifsoplockd_wq; extern struct workqueue_struct *deferredclose_wq; extern struct workqueue_struct *serverclose_wq; extern struct workqueue_struct *cfid_put_wq; +extern struct workqueue_struct *cifs_writeback_wq; extern __u32 cifs_lock_secret; extern mempool_t *cifs_sm_req_poolp; diff --git a/fs/smb/client/cifsproto.h b/fs/smb/client/cifsproto.h index 2a8f830dff08..5b41af529955 100644 --- a/fs/smb/client/cifsproto.h +++ b/fs/smb/client/cifsproto.h @@ -137,6 +137,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, diff --git a/fs/smb/client/connect.c b/fs/smb/client/connect.c index 230b7a4a500e..1878a880e166 100644 --- a/fs/smb/client/connect.c +++ b/fs/smb/client/connect.c @@ -2179,7 +2179,8 @@ void __cifs_put_smb_ses(struct cifs_ses *ses) kref_put(&ses->chans[i].iface->refcount, release_iface); ses->chans[i].iface = NULL; } - cifs_put_tcp_session(ses->chans[i].server, 0); + if (ses->chans[i].server) + cifs_put_tcp_session(ses->chans[i].server, 0); ses->chans[i].server = NULL; } diff --git a/fs/smb/client/dfs.c b/fs/smb/client/dfs.c index f65a8a90ba27..87486e67c9a1 100644 --- a/fs/smb/client/dfs.c +++ b/fs/smb/client/dfs.c @@ -33,7 +33,7 @@ int dfs_parse_target_referral(const char *full_path, const struct dfs_info3_para if (WARN_ON_ONCE(!ref->node_name || ref->path_consumed < 0)) return -EINVAL; - if (strlen(full_path) - ref->path_consumed) { + if ((size_t)ref->path_consumed < strlen(full_path)) { prepath = full_path + ref->path_consumed; /* skip initial delimiter */ if (*prepath == '/' || *prepath == '\\') @@ -103,6 +103,7 @@ static int setup_dfs_ref(struct dfs_info3_param *tgt, struct dfs_ref_walk *rw) struct cifs_sb_info *cifs_sb = rw->mnt_ctx->cifs_sb; struct smb3_fs_context *ctx = rw->mnt_ctx->fs_ctx; char *ref_path, *full_path; + const char *raw_path; int rc; set_root_smb_session(rw->mnt_ctx); @@ -114,9 +115,10 @@ static int setup_dfs_ref(struct dfs_info3_param *tgt, struct dfs_ref_walk *rw) if (!tgt || (tgt->server_type == DFS_TYPE_LINK && DFS_INTERLINK(tgt->flags))) - ref_path = dfs_get_path(cifs_sb, ctx->UNC); + raw_path = ctx->UNC; else - ref_path = dfs_get_path(cifs_sb, full_path); + raw_path = full_path; + ref_path = dfs_get_path(cifs_sb, raw_path); if (IS_ERR(ref_path)) { rc = PTR_ERR(ref_path); kfree(full_path); @@ -125,9 +127,7 @@ static int setup_dfs_ref(struct dfs_info3_param *tgt, struct dfs_ref_walk *rw) ref_walk_path(rw) = ref_path; ref_walk_fpath(rw) = full_path; - return dfs_get_referral(rw->mnt_ctx, - ref_walk_path(rw) + 1, - ref_walk_tl(rw)); + return dfs_get_referral(rw->mnt_ctx, raw_path + 1, ref_walk_tl(rw)); } static int __dfs_referral_walk(struct dfs_ref_walk *rw) diff --git a/fs/smb/client/file.c b/fs/smb/client/file.c index 11355d6bf89d..4da53f84196f 100644 --- a/fs/smb/client/file.c +++ b/fs/smb/client/file.c @@ -39,6 +39,61 @@ static int cifs_reopen_file(struct cifsFileInfo *cfile, bool can_flush); +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; +} + /* * Prepare a subrequest to upload to the server. We need to allocate credits * so that we know the maximum amount of data that we can include in it. @@ -52,6 +107,7 @@ 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 reprepared = wdata->have_xid; size_t wsize = req->rreq.wsize; int rc; @@ -63,6 +119,12 @@ static void cifs_prepare_write(struct netfs_io_subrequest *subreq) server = cifs_pick_channel(tlink_tcon(open_file->tlink)->ses); wdata->server = server; + 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)); @@ -105,10 +167,16 @@ static void cifs_prepare_write(struct netfs_io_subrequest *subreq) #endif } +static bool cifs_writeback_dying(struct netfs_io_subrequest *subreq) +{ + return subreq->rreq->origin == NETFS_WRITEBACK && + fatal_signal_pending(current); +} + /* * Issue a subrequest to upload to the server. */ -static void cifs_issue_write(struct netfs_io_subrequest *subreq) +static void __cifs_issue_write(struct netfs_io_subrequest *subreq) { struct cifs_io_subrequest *wdata = container_of(subreq, struct cifs_io_subrequest, subreq); @@ -120,6 +188,10 @@ 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; @@ -128,20 +200,43 @@ static void cifs_issue_write(struct netfs_io_subrequest *subreq) if (wdata->req->cfile->invalidHandle) goto fail; + if (wdata->replay && wdata->cur_sleep) + msleep(wdata->cur_sleep); + 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 netfs_io_subrequest *subreq; + + subreq = container_of(work, struct netfs_io_subrequest, work); + __cifs_issue_write(subreq); +} + +static void cifs_issue_write(struct netfs_io_subrequest *subreq) +{ + if (unlikely(cifs_writeback_dying(subreq))) { + subreq->work.func = cifs_issue_write_worker; + WARN_ON_ONCE(!queue_work(cifs_writeback_wq, &subreq->work)); + return; + } + __cifs_issue_write(subreq); +} + static void cifs_netfs_invalidate_cache(struct netfs_io_request *wreq) { cifs_invalidate_cache(wreq->inode, 0); @@ -157,6 +252,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,6 +264,10 @@ 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)); @@ -218,6 +318,10 @@ 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; @@ -234,6 +338,9 @@ static void cifs_issue_read(struct netfs_io_subrequest *subreq) subreq->rreq->origin != NETFS_DIO_READ) __set_bit(NETFS_SREQ_CLEAR_TAIL, &subreq->flags); + if (rdata->replay && rdata->cur_sleep) + msleep(rdata->cur_sleep); + trace_netfs_sreq(subreq, netfs_sreq_trace_submit); rc = rdata->server->ops->async_readv(rdata); if (rc) @@ -255,9 +362,15 @@ 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_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_ANY, + &req->cfile); + } + if (ret) { + cifs_dbg(VFS, "%s: couldn't find writable handle: %d\n", + __func__, ret); return; } @@ -276,6 +389,7 @@ 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); if (file) { open_file = file->private_data; @@ -2232,7 +2346,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; } @@ -2626,6 +2740,14 @@ void cifs_write_subrequest_terminated(struct cifs_io_subrequest *wdata, ssize_t spin_unlock(&inode->i_lock); } + if ((is_interrupt_error(result) || result == -ENOMEM) && + wreq->origin == NETFS_WRITEBACK && 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); + } + netfs_write_subrequest_terminated(&wdata->subreq, result); } @@ -2719,7 +2841,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_DIRECT; cifs_sb = CIFS_SB(cifs_inode); @@ -2749,6 +2871,9 @@ int __cifs_get_writable_file(struct cifsInodeInfo *cifs_inode, !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 */ @@ -2877,6 +3002,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. */ @@ -2888,7 +3052,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; @@ -2920,7 +3084,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; @@ -2961,11 +3125,19 @@ int cifs_fsync(struct file *file, loff_t start, loff_t end, int datasync) */ int cifs_flush(struct file *file, fl_owner_t id) { + struct address_space *mapping = file->f_mapping; struct inode *inode = file_inode(file); - int rc = 0; + int rc = 0, rc2; - if (file->f_mode & FMODE_WRITE) - rc = filemap_write_and_wait(inode->i_mapping); + if (file->f_mode & FMODE_WRITE) { + rc = filemap_fdatawrite(mapping); + if (fatal_signal_pending(current) || + cifs_wait_writeback_killable(mapping, 0, LLONG_MAX)) + return 0; + rc2 = filemap_check_errors(mapping); + if (!rc) + rc = rc2; + } cifs_dbg(FYI, "Flush inode %p file %p rc %d\n", inode, file, rc); if (rc) { @@ -3354,6 +3526,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); @@ -3441,6 +3621,7 @@ void cifs_oplock_break(struct work_struct *work) cifs_put_tlink(tlink); out: cifs_done_oplock_break(cinode); + iput(inode); } #ifdef CONFIG_SWAP diff --git a/fs/smb/client/sess.c b/fs/smb/client/sess.c index 0ab3f37d4809..31ae93696dec 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/smb2ops.c b/fs/smb/client/smb2ops.c index a6da016ce7b9..dbf8e170f737 100644 --- a/fs/smb/client/smb2ops.c +++ b/fs/smb/client/smb2ops.c @@ -2935,14 +2935,7 @@ bool smb2_should_replay(struct cifs_tcon *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 78ced1f51044..3c7e42a47a5a 100644 --- a/fs/smb/client/smb2pdu.c +++ b/fs/smb/client/smb2pdu.c @@ -250,9 +250,10 @@ static int smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon, struct TCP_Server_Info *server, bool from_reconnect) { + bool hold_server_ref = false; struct cifs_ses *ses; - int xid; int rc = 0; + int xid; /* * SMB2s NegProt, SessSetup, Logoff do not have tcon yet so @@ -470,6 +471,20 @@ smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon, * 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 +513,8 @@ smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon, 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: @@ -3453,11 +3470,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); @@ -3465,15 +3483,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); @@ -3497,7 +3518,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; @@ -4037,6 +4058,14 @@ query_info(const unsigned int xid, struct cifs_tcon *tcon, ses->Suid, info_class, (__u32)info_type); if (dlen) { + rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset), + le32_to_cpu(rsp->OutputBufferLength), + &rsp_iov, min_len); + if (rc) { + *dlen = 0; + goto qinf_exit; + } + *dlen = le32_to_cpu(rsp->OutputBufferLength); if (!*data) { *data = kmalloc(*dlen, GFP_KERNEL); @@ -4091,7 +4120,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 @@ -4709,6 +4739,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; @@ -4757,6 +4788,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 */ @@ -4829,9 +4861,7 @@ smb2_readv_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid) /* 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, @@ -4894,12 +4924,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, @@ -4940,9 +4966,7 @@ smb2_async_readv(struct cifs_io_subrequest *rdata) 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); @@ -5074,6 +5098,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; @@ -5087,10 +5112,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); } @@ -5119,12 +5141,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: @@ -5178,11 +5197,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); @@ -5300,12 +5325,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)); @@ -5353,9 +5374,7 @@ smb2_async_writev(struct cifs_io_subrequest *wdata) 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 2e9f70096825..cc5d2aad4ab9 100644 --- a/fs/smb/client/smb2proto.h +++ b/fs/smb/client/smb2proto.h @@ -119,6 +119,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/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 828e2cf1dda5..8f9773e0cf01 100644 --- a/fs/smb/server/smb2pdu.c +++ b/fs/smb/server/smb2pdu.c @@ -2358,6 +2358,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; } @@ -3439,6 +3450,11 @@ static int smb2_set_ea(struct smb2_ea_info *eabuf, unsigned int buf_len, if (!eabuf->EaNameLength) goto next; + if (eabuf->name[eabuf->EaNameLength]) { + rc = -EBADMSG; + break; + } + ksmbd_debug(SMB, "name : <%s>, name_len : %u, value_len : %u, next : %u\n", eabuf->name, eabuf->EaNameLength, @@ -4343,7 +4359,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); @@ -4852,14 +4869,17 @@ int smb2_open(struct ksmbd_work *work) 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; @@ -5622,6 +5642,8 @@ int smb2_open(struct ksmbd_work *work) if (rc) { if (rc == -EINVAL) rsp->hdr.Status = STATUS_INVALID_PARAMETER; + else if (rc == -EBADMSG) + rsp->hdr.Status = STATUS_EA_LIST_INCONSISTENT; else if (rc == -EOPNOTSUPP) rsp->hdr.Status = STATUS_NOT_SUPPORTED; else if ((rc == -EACCES || rc == -ESTALE || rc == -EXDEV) && @@ -6140,6 +6162,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); @@ -8974,6 +8997,8 @@ int smb2_set_info(struct ksmbd_work *work) } else if (rc == -EINVAL) rsp->hdr.Status = STATUS_INVALID_PARAMETER; + else if (rc == -EBADMSG) + rsp->hdr.Status = STATUS_EA_LIST_INCONSISTENT; else if (rc == -EMSGSIZE) rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH; else if (rc == -ENOSPC || rc == -EFBIG) diff --git a/fs/smb/server/smbacl.c b/fs/smb/server/smbacl.c index cc3a450e4cb2..c3be25f2db87 100644 --- a/fs/smb/server/smbacl.c +++ b/fs/smb/server/smbacl.c @@ -1452,9 +1452,44 @@ 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- 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); +} + 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) { struct mnt_idmap *idmap = mnt_idmap(path->mnt); struct smb_ntsd *pntsd = NULL; @@ -1468,13 +1503,20 @@ 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; 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 match every session against + * Authenticated Users. + */ + bool authusers = authenticated || maximal; vfsuid_t vfsuid; ksmbd_debug(SMB, "check permission using windows acl\n"); @@ -1515,7 +1557,7 @@ int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path, */ if (is_owner) allowed = READ_CONTROL | WRITE_DAC; - if (*pdaccess & FILE_MAXIMAL_ACCESS_LE) + if (maximal) requested |= allowed; if (!allowed || requested & ~allowed) rc = -EACCES; @@ -1524,53 +1566,92 @@ 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 MAXIMUM_ALLOWED. 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; + /* An explicit request counts only SIDs that match exactly */ + if (!maximal && !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: + if (counted) + grp_allowed |= bits; + /* MAXIMUM_ALLOWED takes no group grants */ + if (maximal && 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: + if (counted) + grp_denied |= ~grp_allowed & bits; + /* MAXIMUM_ALLOWED takes no group denials either */ + if (!(maximal && 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; @@ -1580,6 +1661,15 @@ int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path, (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)); @@ -1609,15 +1699,23 @@ int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path, !(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. + */ + if (!IS_ERR_OR_NULL(posix_acls) && !found && !others_ace && + !au_ace) { unsigned int id = -1; pa_entry = posix_acls->a_entries; @@ -1639,6 +1737,15 @@ int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path, 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; } @@ -1661,7 +1768,15 @@ int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path, */ 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 (maximal) requested |= allowed; if (!allowed || requested & ~allowed) { ksmbd_debug(SMB, "Can't find corresponding sid\n"); @@ -1673,7 +1788,7 @@ int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path, } } - 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); diff --git a/fs/smb/server/smbacl.h b/fs/smb/server/smbacl.h index 01810c16cc04..667835de95db 100644 --- a/fs/smb/server/smbacl.h +++ b/fs/smb/server/smbacl.h @@ -96,7 +96,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); diff --git a/fs/splice.c b/fs/splice.c index a815f8c70e65..facf72ca9c5e 100644 --- a/fs/splice.c +++ b/fs/splice.c @@ -737,9 +737,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 +866,9 @@ ssize_t splice_to_socket(struct pipe_inode_info *pipe, struct file *out, bvec_set_page(&bvec[bc++], buf->page, seg, buf->offset); remain -= seg; + tail++; if (remain == 0 || bc >= ARRAY_SIZE(bvec)) break; - tail++; } if (!bc) diff --git a/fs/stat.c b/fs/stat.c index e03954c36b33..689c610f3676 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 49673b555c62..f852e9994613 100644 --- a/fs/udf/inode.c +++ b/fs/udf/inode.c @@ -1735,25 +1735,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/udf/super.c b/fs/udf/super.c index 7570506ff2dd..a81a8509524a 100644 --- a/fs/udf/super.c +++ b/fs/udf/super.c @@ -1329,6 +1329,12 @@ static int udf_load_vat(struct super_block *sb, int p_index, int type1_index) (sbi->s_vat_inode->i_size - 36) >> 2; } else if (map->s_partition_type == UDF_VIRTUAL_MAP20) { vati = UDF_I(sbi->s_vat_inode); + if (sbi->s_vat_inode->i_size < + sizeof(struct virtualAllocationTable20)) { + udf_err(sb, "Too short VAT inode size %lld\n", + sbi->s_vat_inode->i_size); + return -EFSCORRUPTED; + } if (vati->i_alloc_type != ICBTAG_FLAG_AD_IN_ICB) { int err = 0; @@ -1346,8 +1352,12 @@ static int udf_load_vat(struct super_block *sb, int p_index, int type1_index) map->s_type_specific.s_virtual.s_start_offset = le16_to_cpu(vat20->lengthHeader); - if (map->s_type_specific.s_virtual.s_start_offset - > sbi->s_vat_inode->i_size) { + if (map->s_type_specific.s_virtual.s_start_offset < + sizeof(struct virtualAllocationTable20) || + map->s_type_specific.s_virtual.s_start_offset > + sb->s_blocksize || + map->s_type_specific.s_virtual.s_start_offset > + sbi->s_vat_inode->i_size) { udf_err(sb, "Corrupted VAT header length %u (VAT inode size %lld)\n", map->s_type_specific.s_virtual.s_start_offset, sbi->s_vat_inode->i_size); diff --git a/include/acpi/acpi_bus.h b/include/acpi/acpi_bus.h index 40df037804a5..57145e2aec21 100644 --- a/include/acpi/acpi_bus.h +++ b/include/acpi/acpi_bus.h @@ -329,6 +329,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/linux/blk-mq.h b/include/linux/blk-mq.h index aa3b35405edc..9268b79de247 100644 --- a/include/linux/blk-mq.h +++ b/include/linux/blk-mq.h @@ -524,7 +524,8 @@ enum hctx_type { * @tag_list: List of the request queues that use this tag set. See also * request_queue.tag_set_list. * @quiesce_lock: Serializes blk_mq_[un]quiesce_tagset() against each other - * and against a request queue being added to @tag_list. + * and against a request queue being added to or removed from + * @tag_list. * @quiesce_depth: How often blk_mq_quiesce_tagset() has been called without * blk_mq_unquiesce_tagset(). * @srcu: Use as lock when type of the request queue is blocking diff --git a/include/linux/bpf.h b/include/linux/bpf.h index a628f182bb64..c4d1053bfe2b 100644 --- a/include/linux/bpf.h +++ b/include/linux/bpf.h @@ -2916,6 +2916,8 @@ static inline void bpf_map_dec_elem_count(struct bpf_map *map) this_cpu_dec(*map->elem_count); } +s64 bpf_map_sum_elem_count(const struct bpf_map *map); + extern int sysctl_unprivileged_bpf_disabled; bool bpf_token_capable(const struct bpf_token *token, int cap); diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h index 0eda96e1162f..a253ca2c6e5d 100644 --- a/include/linux/bpf_verifier.h +++ b/include/linux/bpf_verifier.h @@ -1053,7 +1053,7 @@ static inline struct bpf_subprog_info *subprog_info(struct bpf_verifier_env *env } struct bpf_call_summary { - u8 num_params; + u8 arg_slot_cnt; bool is_void; bool fastcall; }; @@ -1076,6 +1076,12 @@ static inline bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn) insn->src_reg == BPF_PSEUDO_KFUNC_CALL; } +/* callx: indirect call of a bpf subprog whose address is in insn->dst_reg */ +static inline bool bpf_is_callx(const struct bpf_insn *insn) +{ + return insn->code == (BPF_JMP | BPF_CALL | BPF_X); +} + __printf(2, 0) void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt, va_list args); __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env, diff --git a/include/linux/compiler.h b/include/linux/compiler.h index cb2f6050bdf7..a7e57ffb6126 100644 --- a/include/linux/compiler.h +++ b/include/linux/compiler.h @@ -241,10 +241,13 @@ void ftrace_likely_update(struct ftrace_likely_data *f, int val, #endif /* __KERNEL__ */ -#if defined(CONFIG_CFI) && !defined(__DISABLE_EXPORTS) && !defined(BUILD_VDSO) +#if defined(CONFIG_CFI) && !defined(__DISABLE_EXPORTS) && !defined(BUILD_VDSO) && \ + !defined(MODULE) /* * Force a reference to the external symbol so the compiler generates - * __kcfi_typid. + * __kcfi_typid. Only vmlinux needs it, as that is where the assembly + * using the typeid lives; in a module it would only add a reference to + * the symbol, which fails modpost if the symbol is GPL-only. */ #define KCFI_REFERENCE(sym) __ADDRESSABLE(sym) #else diff --git a/include/linux/cpufreq.h b/include/linux/cpufreq.h index 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/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 f155984f5bd0..0296f1f98986 100644 --- a/include/linux/fs.h +++ b/include/linux/fs.h @@ -3328,7 +3328,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/fsnotify.h b/include/linux/fsnotify.h index bda798bc67bc..a4a29b365008 100644 --- a/include/linux/fsnotify.h +++ b/include/linux/fsnotify.h @@ -135,7 +135,7 @@ int fsnotify_open_perm_and_set_mode(struct file *file); * fsnotify_file_area_perm - permission hook before access to file range */ static inline int fsnotify_file_area_perm(struct file *file, int perm_mask, - const loff_t *ppos, size_t count) + const loff_t *ppos, u64 count) { /* * filesystem may be modified in the context of permission events @@ -213,7 +213,7 @@ static inline int fsnotify_open_perm_and_set_mode(struct file *file) } static inline int fsnotify_file_area_perm(struct file *file, int perm_mask, - const loff_t *ppos, size_t count) + const loff_t *ppos, u64 count) { return 0; } diff --git a/include/linux/fsnotify_backend.h b/include/linux/fsnotify_backend.h index a6d5c1a89cff..faf21564380d 100644 --- a/include/linux/fsnotify_backend.h +++ b/include/linux/fsnotify_backend.h @@ -323,7 +323,7 @@ struct fs_error_report { struct file_range { const struct path *path; loff_t pos; - size_t count; + u64 count; }; static inline const struct path *file_range_path(const struct file_range *range) @@ -946,12 +946,12 @@ static inline void fsnotify_init_event(struct fsnotify_event *event) INIT_LIST_HEAD(&event->list); } int fsnotify_pre_content(const struct path *path, const loff_t *ppos, - size_t count); + u64 count); #else static inline int fsnotify_pre_content(const struct path *path, - const loff_t *ppos, size_t count) + const loff_t *ppos, u64 count) { return 0; } diff --git a/include/linux/ftrace.h b/include/linux/ftrace.h index b041d9142d2b..1c2056a1a68b 100644 --- a/include/linux/ftrace.h +++ b/include/linux/ftrace.h @@ -618,19 +618,21 @@ static inline void arch_ftrace_set_direct_caller(struct ftrace_regs *fregs, #endif /* CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS */ #ifdef CONFIG_DYNAMIC_FTRACE_WITH_JMP +#define FTRACE_JMP_BIT BIT(BITS_PER_LONG - 1) + static inline bool ftrace_is_jmp(unsigned long addr) { - return addr & 1; + return !(addr & FTRACE_JMP_BIT); } static inline unsigned long ftrace_jmp_set(unsigned long addr) { - return addr | 1UL; + return addr & ~FTRACE_JMP_BIT; } static inline unsigned long ftrace_jmp_get(unsigned long addr) { - return addr & ~1UL; + return addr | FTRACE_JMP_BIT; } #else static inline bool ftrace_is_jmp(unsigned long addr) 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/input.h b/include/linux/input.h index 3381608127f7..02047cc45d04 100644 --- a/include/linux/input.h +++ b/include/linux/input.h @@ -549,8 +549,6 @@ extern const struct class input_class; * @set_autocenter: Called to auto-center device * @destroy: called by input core when parent input device is being * destroyed - * @stop: called by input core when parent input device is being - * unregistered * @private: driver-specific data, will be freed automatically * @ffbit: bitmap of force feedback capabilities truly supported by * device (not emulated like ones in input_dev->ffbit) @@ -579,7 +577,6 @@ struct ff_device { void (*set_autocenter)(struct input_dev *dev, u16 magnitude); void (*destroy)(struct ff_device *); - void (*stop)(struct ff_device *); void *private; diff --git a/include/linux/key.h b/include/linux/key.h index e40b5267658f..3b8af14fb323 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 83d0a83bbfbc..a778733fdb66 100644 --- a/include/linux/mlx5/driver.h +++ b/include/linux/mlx5/driver.h @@ -788,8 +788,12 @@ struct mlx5_core_dev { u32 vsc_addr; struct mlx5_hv_vhca *hv_vhca; struct mlx5_hwmon *hwmon; - u64 num_block_tc; - u64 num_block_ipsec; + struct { + /* Protects the fields below. */ + spinlock_t lock; + u64 num_block_tc; + u64 num_block_ipsec; + } offload_block; #ifdef CONFIG_MLX5_MACSEC struct mlx5_macsec_fs *macsec_fs; /* MACsec notifier chain to sync MACsec core and IB database */ diff --git a/include/linux/mmzone.h b/include/linux/mmzone.h index da8dd04fb462..c28aaba3cdd2 100644 --- a/include/linux/mmzone.h +++ b/include/linux/mmzone.h @@ -1815,7 +1815,8 @@ extern struct zone *next_zone(struct zone *zone); static inline struct zone *zonelist_zone(struct zoneref *zoneref) { - return zoneref->zone; + /* Memory hotplug rewrites zonelists in place. */ + return READ_ONCE(zoneref->zone); } static inline int zonelist_zone_idx(const struct zoneref *zoneref) diff --git a/include/linux/mroute_base.h b/include/linux/mroute_base.h index 4d55827e9705..2d506966357b 100644 --- a/include/linux/mroute_base.h +++ b/include/linux/mroute_base.h @@ -119,6 +119,7 @@ enum { * @mfc_flags: entry flags * @expires: unresolved entry expire time * @unresolved: unresolved cached skbs + * @nl_queries: queued RTM_GETROUTE requests waiting for resolution * @last_assert: time of last assert * @minvif: minimum VIF id * @maxvif: maximum VIF id @@ -141,6 +142,7 @@ struct mr_mfc { struct { unsigned long expires; struct sk_buff_head unresolved; + struct sk_buff_head nl_queries; } unres; struct { unsigned long last_assert; 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 34d294774f8c..5f9415d7059e 100644 --- a/include/linux/nfs_fs_sb.h +++ b/include/linux/nfs_fs_sb.h @@ -116,6 +116,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/perf_event.h b/include/linux/perf_event.h index 2d5e7687875b..8a985486ab12 100644 --- a/include/linux/perf_event.h +++ b/include/linux/perf_event.h @@ -306,6 +306,7 @@ struct perf_event_pmu_context; #define PERF_PMU_CAP_AUX_PAUSE 0x0200 #define PERF_PMU_CAP_AUX_PREFER_LARGE 0x0400 #define PERF_PMU_CAP_MEDIATED_VPMU 0x0800 +#define PERF_PMU_CAP_SIMD_REGS 0x1000 /** * pmu::scope @@ -1518,6 +1519,27 @@ perf_event__output_id_sample(struct perf_event *event, extern void perf_log_lost_samples(struct perf_event *event, u64 lost); +static inline bool event_has_simd_regs(struct perf_event *event) +{ + struct perf_event_attr *attr = &event->attr; + + if (!(event->attr.sample_type & + (PERF_SAMPLE_REGS_INTR | PERF_SAMPLE_REGS_USER))) + return false; + + return attr->sample_simd_regs_enabled != 0; +} + +static inline bool event_has_extended_regs(struct perf_event *event) +{ + struct perf_event_attr *attr = &event->attr; + + return ((attr->sample_type & PERF_SAMPLE_REGS_USER) && + (attr->sample_regs_user & PERF_REG_EXTENDED_MASK)) || + ((attr->sample_type & PERF_SAMPLE_REGS_INTR) && + (attr->sample_regs_intr & PERF_REG_EXTENDED_MASK)); +} + static inline bool event_has_any_exclude_flag(struct perf_event *event) { struct perf_event_attr *attr = &event->attr; @@ -1791,6 +1813,12 @@ extern unsigned long perf_misc_flags(struct perf_event *event, struct pt_regs *r extern unsigned long perf_instruction_pointer(struct perf_event *event, struct pt_regs *regs); +extern void perf_sample_regs_user(struct perf_regs *regs_user, + struct pt_regs *regs); +extern void perf_sample_regs_intr(struct perf_regs *regs_intr, + struct pt_regs *regs, + bool exclude_kernel); + #ifndef perf_arch_misc_flags # define perf_arch_misc_flags(regs) \ (user_mode(regs) ? PERF_RECORD_MISC_USER : PERF_RECORD_MISC_KERNEL) diff --git a/include/linux/perf_regs.h b/include/linux/perf_regs.h index f632c5725f16..518f28c6a7d4 100644 --- a/include/linux/perf_regs.h +++ b/include/linux/perf_regs.h @@ -9,6 +9,16 @@ struct perf_regs { struct pt_regs *regs; }; +u64 perf_reg_value(struct pt_regs *regs, int idx); +int perf_reg_validate(u64 mask); +u64 perf_reg_abi(struct task_struct *task); +void perf_get_regs_user(struct perf_regs *regs_user, + struct pt_regs *regs); +int perf_simd_reg_validate(u16 vec_qwords, u64 vec_mask, + u16 pred_qwords, u32 pred_mask); +u64 perf_simd_reg_value(struct pt_regs *regs, int idx, + u16 qwords_idx, bool pred); + #ifdef CONFIG_HAVE_PERF_REGS #include @@ -16,35 +26,9 @@ struct perf_regs { #define PERF_REG_EXTENDED_MASK 0 #endif -u64 perf_reg_value(struct pt_regs *regs, int idx); -int perf_reg_validate(u64 mask); -u64 perf_reg_abi(struct task_struct *task); -void perf_get_regs_user(struct perf_regs *regs_user, - struct pt_regs *regs); #else #define PERF_REG_EXTENDED_MASK 0 -static inline u64 perf_reg_value(struct pt_regs *regs, int idx) -{ - return 0; -} - -static inline int perf_reg_validate(u64 mask) -{ - return mask ? -ENOSYS : 0; -} - -static inline u64 perf_reg_abi(struct task_struct *task) -{ - return PERF_SAMPLE_REGS_ABI_NONE; -} - -static inline void perf_get_regs_user(struct perf_regs *regs_user, - struct pt_regs *regs) -{ - regs_user->regs = task_pt_regs(current); - regs_user->abi = perf_reg_abi(current); -} #endif /* CONFIG_HAVE_PERF_REGS */ #endif /* _LINUX_PERF_REGS_H */ diff --git a/include/linux/ptp_clock_kernel.h b/include/linux/ptp_clock_kernel.h index 36a27a910595..56f6ab1855d3 100644 --- a/include/linux/ptp_clock_kernel.h +++ b/include/linux/ptp_clock_kernel.h @@ -496,7 +496,7 @@ int ptp_get_vclocks_index(int pclock_index, int **vclock_index); * @hwtstamp: timestamp * @vclock_index: phc index of ptp vclock. * - * Returns: converted timestamp, or 0 on error. + * Returns: converted timestamp, or 0 if @hwtstamp is zero or on error. */ ktime_t ptp_convert_timestamp(const ktime_t *hwtstamp, int vclock_index); #else diff --git a/include/linux/regulator/mt6363-regulator.h b/include/linux/regulator/mt6363-regulator.h index 60761f01d3ad..e0d2c01827a7 100644 --- a/include/linux/regulator/mt6363-regulator.h +++ b/include/linux/regulator/mt6363-regulator.h @@ -138,6 +138,7 @@ #define MT6363_RG_LDO_VSRAM_APU_VOSEL_ADDR 0x1b17 #define MT6363_RG_LDO_VSRAM_APU_VOSEL_MASK GENMASK(6, 0) #define MT6363_RG_VEMC_VOCAL_ADDR 0x1b1b +#define MT6363_RG_VEMC_VOCAL_1_ADDR 0x1b1c #define MT6363_RG_VEMC_VOCAL_MASK GENMASK(3, 0) #define MT6363_RG_LDO_VCN15_ADDR 0x1b57 #define MT6363_RG_LDO_VCN15_EN_BIT 0 diff --git a/include/linux/sched.h b/include/linux/sched.h index 09d90f5edd2b..bdfd662e2c37 100644 --- a/include/linux/sched.h +++ b/include/linux/sched.h @@ -880,6 +880,8 @@ struct task_struct { */ int recent_used_cpu; int wake_cpu; + /* CPU charged while is_blocked && in_iowait. */ + int iowait_cpu; int prio; int static_prio; 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 a82045804d34..ef120fc50422 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 6a8c77719322..ed9c668f9b4b 100644 --- a/include/linux/tcp.h +++ b/include/linux/tcp.h @@ -179,6 +179,9 @@ struct tcp_request_sock { u8 ao_rcv_next; bool used_tcp_ao; #endif +#if IS_ENABLED(CONFIG_IPV6) + __be32 syn_flowlabel; +#endif }; #define tcp_rsk(ptr) container_of_const(ptr, struct tcp_request_sock, req.req) @@ -353,6 +356,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; @@ -608,13 +612,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 fe2e985d74d2..529c6cd53df7 100644 --- a/include/linux/uio.h +++ b/include/linux/uio.h @@ -362,11 +362,11 @@ struct iovec *iovec_from_user(const struct iovec __user *uvector, unsigned long nr_segs, unsigned long fast_segs, struct iovec *fast_iov, bool compat); ssize_t import_iovec(int type, const struct iovec __user *uvec, - unsigned nr_segs, unsigned fast_segs, struct iovec **iovp, - struct iov_iter *i); + unsigned long nr_segs, unsigned int fast_segs, + struct iovec **iovp, struct iov_iter *i); ssize_t __import_iovec(int type, const struct iovec __user *uvec, - unsigned nr_segs, unsigned fast_segs, struct iovec **iovp, - struct iov_iter *i, bool compat); + unsigned long nr_segs, unsigned int fast_segs, + struct iovec **iovp, struct iov_iter *i, bool compat); int import_ubuf(int type, void __user *buf, size_t len, struct iov_iter *i); static inline void iov_iter_ubuf(struct iov_iter *i, unsigned int direction, diff --git a/include/linux/virtio_net.h b/include/linux/virtio_net.h index d6466f96cdd0..fc9667176f23 100644 --- a/include/linux/virtio_net.h +++ b/include/linux/virtio_net.h @@ -5,7 +5,10 @@ #include #include #include +#include #include +#include +#include #include #include #include @@ -48,6 +51,145 @@ static inline int virtio_net_hdr_set_proto(struct sk_buff *skb, return 0; } +/* TODO: nothing virtio specific here, move to ip.h */ + +/* + * Pull and minimally validate the IPv4 header at @nhoff. + * Returns the header and stores the transport header offset in + * @thoff, or NULL if truncated or malformed. The whole header, + * options included, is guaranteed linear on return. + */ +static inline struct iphdr *virtio_net_ip4_parse(struct sk_buff *skb, + unsigned int nhoff, + unsigned int *thoff) +{ + unsigned int ihl; + struct iphdr *iph; + + if (!pskb_may_pull(skb, nhoff + sizeof(struct iphdr))) + return NULL; + + iph = (struct iphdr *)(skb->data + nhoff); + if (iph->version != 4 || + iph->ihl < sizeof(struct iphdr) / sizeof(u32)) + return NULL; + + ihl = iph->ihl * sizeof(u32); + *thoff = nhoff + ihl; + /* Pull the options as well: the transport header offset + * returned above must be within the linear data. iph goes + * stale across the pull. + */ + if (!pskb_may_pull(skb, nhoff + ihl)) + return NULL; + + return (struct iphdr *)(skb->data + nhoff); +} + +/* Where does the L3 header start, and what protocol is it? + * With @has_eth, the frame starts with an Ethernet header, possibly + * followed by VLAN tags. Otherwise the L3 header starts at the network + * header offset the caller set up. + * + * The caller knows how the frame will be parsed later: the device + * type does not tell, as tun can change it with TUNSETLINK. + */ +static inline bool +virtio_net_l3_start(struct sk_buff *skb, bool has_eth, int *nhoff, + __be16 *proto) +{ + if (has_eth) { + __be16 h_proto; + + if (!pskb_may_pull(skb, ETH_HLEN)) + return false; + h_proto = eth_hdr(skb)->h_proto; + /* skb->protocol is a sender claim, and parts of the + * stack parse the packet per it: when it disagrees with + * the frame we do not know which view the packet will + * be parsed as, so do not validate. + */ + if (skb->protocol && skb->protocol != h_proto) + return false; + *nhoff = ETH_HLEN; + *proto = h_proto; + if (eth_type_vlan(*proto)) { + *proto = __vlan_get_protocol(skb, *proto, nhoff); + if (!*proto) + return false; + } + } else { + const struct iphdr *iph; + + *nhoff = skb_network_offset(skb); + /* An unset network header shows up as an offset + * outside of the packet. + */ + if (*nhoff < 0 || (unsigned int)*nhoff >= skb->len) + return false; + /* No L2 header to cross-check with: take the protocol + * from the IP version at the network header. + */ + if (!pskb_may_pull(skb, *nhoff + 1)) + return false; + iph = (const struct iphdr *)(skb->data + *nhoff); + if (iph->version == 4) + *proto = htons(ETH_P_IP); + else if (iph->version == 6) + *proto = htons(ETH_P_IPV6); + else + return false; + if (skb->protocol && skb->protocol != *proto) + return false; + } + return true; +} + +/* Walk the L3 header at @nhoff: where does its transport header + * start, and which protocol is it? Returns false if the header + * is truncated, malformed or fragmented. + */ +static inline bool +virtio_net_l4_start(struct sk_buff *skb, unsigned int nhoff, __be16 proto, + unsigned int *thoff, int *ip_proto) +{ + if (proto == htons(ETH_P_IP)) { + const struct iphdr *iph = virtio_net_ip4_parse(skb, nhoff, thoff); + + if (!iph || ip_is_fragment(iph)) + return false; + *ip_proto = iph->protocol; + return true; + } + + if (proto == htons(ETH_P_IPV6)) { + const struct ipv6hdr *iph; + int flags = IP6_FH_F_AUTH; + + if (!pskb_may_pull(skb, nhoff + sizeof(*iph))) + return false; + iph = (const void *)(skb->data + nhoff); + if (iph->version != 6) + return false; + *thoff = nhoff + sizeof(*iph); + *ip_proto = iph->nexthdr; + if (*ip_proto != IPPROTO_TCP && *ip_proto != IPPROTO_UDP) { + *thoff = nhoff; + /* Find the transport header behind any + * extension headers. IP6_FH_F_AUTH stops + * the walk at AH, so frames with AH are rejected. + */ + *ip_proto = ipv6_find_hdr(skb, thoff, -1, NULL, + &flags); + if (*ip_proto < 0 || flags & IP6_FH_F_FRAG) + return false; + } + return true; + } + + return false; +} + static inline int __virtio_net_hdr_to_skb(struct sk_buff *skb, const struct virtio_net_hdr *hdr, bool little_endian, u8 hdr_gso_type) @@ -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/9p/client.h b/include/net/9p/client.h index 55c6cb54bd25..0a1de81c8cd8 100644 --- a/include/net/9p/client.h +++ b/include/net/9p/client.h @@ -270,7 +270,7 @@ struct p9_dirent { struct p9_qid qid; u64 d_off; unsigned char d_type; - char d_name[256]; + char *d_name; }; struct iov_iter; diff --git a/include/net/bluetooth/hci_core.h b/include/net/bluetooth/hci_core.h index fa2a367731b5..3a1169e19eb8 100644 --- a/include/net/bluetooth/hci_core.h +++ b/include/net/bluetooth/hci_core.h @@ -677,6 +677,45 @@ enum conn_reasons { CONN_REASON_ISO_CONNECT, }; +enum { + HCI_CONN_AUTH_PEND, + HCI_CONN_ENCRYPT_PEND, + HCI_CONN_RSWITCH_PEND, + HCI_CONN_MODE_CHANGE_PEND, + HCI_CONN_SCO_SETUP_PEND, + HCI_CONN_MGMT_CONNECTED, + HCI_CONN_SSP_ENABLED, + HCI_CONN_SC_ENABLED, + HCI_CONN_AES_CCM, + HCI_CONN_POWER_SAVE, + HCI_CONN_FLUSH_KEY, + HCI_CONN_ENCRYPT, + HCI_CONN_AUTH, + HCI_CONN_SECURE, + HCI_CONN_FIPS, + HCI_CONN_STK_ENCRYPT, + HCI_CONN_AUTH_INITIATOR, + HCI_CONN_DROP, + HCI_CONN_CANCEL, + HCI_CONN_PARAM_REMOVAL_PEND, + HCI_CONN_NEW_LINK_KEY, + HCI_CONN_SCANNING, + HCI_CONN_AUTH_FAILURE, + HCI_CONN_PER_ADV, + HCI_CONN_BIG_CREATED, + HCI_CONN_CREATE, + HCI_CONN_CREATE_CIS, + HCI_CONN_CREATE_BIG_SYNC, + HCI_CONN_BIG_SYNC, + HCI_CONN_BIG_SYNC_FAILED, + HCI_CONN_CREATE_PA_SYNC, + HCI_CONN_PA_SYNC, + HCI_CONN_PA_SYNC_FAILED, + HCI_CONN_ENC_KEY_SIZE_PEND, + + __HCI_CONN_NUM_FLAGS, +}; + struct hci_conn { struct list_head list; @@ -747,7 +786,7 @@ struct hci_conn { __u8 num_bis; __u8 bis[HCI_MAX_ISO_BIS]; - unsigned long flags; + DECLARE_BITMAP(flags, __HCI_CONN_NUM_FLAGS); enum conn_reasons conn_reason; __u8 abort_reason; @@ -977,55 +1016,18 @@ u32 hci_inquiry_cache_update(struct hci_dev *hdev, struct inquiry_data *data, bool name_known); void hci_inquiry_cache_flush(struct hci_dev *hdev); -/* ----- HCI Connections ----- */ -enum { - HCI_CONN_AUTH_PEND, - HCI_CONN_ENCRYPT_PEND, - HCI_CONN_RSWITCH_PEND, - HCI_CONN_MODE_CHANGE_PEND, - HCI_CONN_SCO_SETUP_PEND, - HCI_CONN_MGMT_CONNECTED, - HCI_CONN_SSP_ENABLED, - HCI_CONN_SC_ENABLED, - HCI_CONN_AES_CCM, - HCI_CONN_POWER_SAVE, - HCI_CONN_FLUSH_KEY, - HCI_CONN_ENCRYPT, - HCI_CONN_AUTH, - HCI_CONN_SECURE, - HCI_CONN_FIPS, - HCI_CONN_STK_ENCRYPT, - HCI_CONN_AUTH_INITIATOR, - HCI_CONN_DROP, - HCI_CONN_CANCEL, - HCI_CONN_PARAM_REMOVAL_PEND, - HCI_CONN_NEW_LINK_KEY, - HCI_CONN_SCANNING, - HCI_CONN_AUTH_FAILURE, - HCI_CONN_PER_ADV, - HCI_CONN_BIG_CREATED, - HCI_CONN_CREATE, - HCI_CONN_CREATE_CIS, - HCI_CONN_CREATE_BIG_SYNC, - HCI_CONN_BIG_SYNC, - HCI_CONN_BIG_SYNC_FAILED, - HCI_CONN_CREATE_PA_SYNC, - HCI_CONN_PA_SYNC, - HCI_CONN_PA_SYNC_FAILED, -}; - static inline bool hci_conn_ssp_enabled(struct hci_conn *conn) { struct hci_dev *hdev = conn->hdev; return hci_dev_test_flag(hdev, HCI_SSP_ENABLED) && - test_bit(HCI_CONN_SSP_ENABLED, &conn->flags); + test_bit(HCI_CONN_SSP_ENABLED, conn->flags); } static inline bool hci_conn_sc_enabled(struct hci_conn *conn) { struct hci_dev *hdev = conn->hdev; return hci_dev_test_flag(hdev, HCI_SC_ENABLED) && - test_bit(HCI_CONN_SC_ENABLED, &conn->flags); + test_bit(HCI_CONN_SC_ENABLED, conn->flags); } static inline void hci_conn_hash_add(struct hci_dev *hdev, struct hci_conn *c) @@ -1198,7 +1200,7 @@ hci_conn_hash_lookup_create_pa_sync(struct hci_dev *hdev) if (c->type != PA_LINK) continue; - if (!test_bit(HCI_CONN_CREATE_PA_SYNC, &c->flags)) + if (!test_bit(HCI_CONN_CREATE_PA_SYNC, c->flags)) continue; rcu_read_unlock(); @@ -1222,7 +1224,7 @@ hci_conn_hash_lookup_per_adv_bis(struct hci_dev *hdev, list_for_each_entry_rcu(c, &h->list, list) { if (bacmp(&c->dst, ba) || c->type != BIS_LINK || - !test_bit(HCI_CONN_PER_ADV, &c->flags)) + !test_bit(HCI_CONN_PER_ADV, c->flags)) continue; if (c->iso_qos.bcast.big == big && @@ -1459,7 +1461,7 @@ hci_conn_hash_lookup_pa_sync_big_handle(struct hci_dev *hdev, __u8 big) list_for_each_entry_rcu(c, &h->list, list) { if (c->type != BIS_LINK || - !test_bit(HCI_CONN_PA_SYNC, &c->flags)) + !test_bit(HCI_CONN_PA_SYNC, c->flags)) continue; if (c->iso_qos.bcast.big == big) { @@ -1535,7 +1537,7 @@ static inline void hci_conn_hash_list_flag(struct hci_dev *hdev, rcu_read_lock(); list_for_each_entry_rcu(c, &h->list, list) { - if (c->type == type && test_bit(flag, &c->flags)) + if (c->type == type && test_bit(flag, c->flags)) func(c, data); } @@ -1551,7 +1553,7 @@ static inline struct hci_conn *hci_lookup_le_connect(struct hci_dev *hdev) list_for_each_entry_rcu(c, &h->list, list) { if (c->type == LE_LINK && c->state == BT_CONNECT && - !test_bit(HCI_CONN_SCANNING, &c->flags)) { + !test_bit(HCI_CONN_SCANNING, c->flags)) { rcu_read_unlock(); return c; } @@ -1572,7 +1574,7 @@ static inline bool hci_is_le_conn_scanning(struct hci_dev *hdev) list_for_each_entry_rcu(c, &h->list, list) { if (c->type == LE_LINK && c->state == BT_CONNECT && - test_bit(HCI_CONN_SCANNING, &c->flags)) { + test_bit(HCI_CONN_SCANNING, c->flags)) { rcu_read_unlock(); return true; } @@ -2192,10 +2194,10 @@ static inline void hci_auth_cfm(struct hci_conn *conn, __u8 status) struct hci_cb *cb; __u8 encrypt; - if (test_bit(HCI_CONN_ENCRYPT_PEND, &conn->flags)) + if (test_bit(HCI_CONN_ENCRYPT_PEND, conn->flags)) return; - encrypt = test_bit(HCI_CONN_ENCRYPT, &conn->flags) ? 0x01 : 0x00; + encrypt = test_bit(HCI_CONN_ENCRYPT, conn->flags) ? 0x01 : 0x00; mutex_lock(&hci_cb_list_lock); list_for_each_entry(cb, &hci_cb_list, list) { @@ -2208,6 +2210,8 @@ static inline void hci_auth_cfm(struct hci_conn *conn, __u8 status) conn->security_cfm_cb(conn, status); } +void mgmt_security_level_changed(struct hci_conn *conn); + static inline void hci_encrypt_cfm(struct hci_conn *conn, __u8 status) { struct hci_cb *cb; @@ -2222,19 +2226,27 @@ static inline void hci_encrypt_cfm(struct hci_conn *conn, __u8 status) return; } - if (!test_bit(HCI_CONN_ENCRYPT, &conn->flags)) + if (!test_bit(HCI_CONN_ENCRYPT, conn->flags)) encrypt = 0x00; - else if (test_bit(HCI_CONN_AES_CCM, &conn->flags)) + else if (test_bit(HCI_CONN_AES_CCM, conn->flags)) encrypt = 0x02; else encrypt = 0x01; if (!status) { - if (conn->sec_level == BT_SECURITY_SDP) + /* Callers either set conn->sec_level = conn->pending_sec_level + * unconditionally before calling this function, or never + * reach here with status == 0 (e.g. conn->state == BT_CONFIG + * returns early above, or status is actually an error). So + * conn->pending_sec_level is never greater than + * conn->sec_level at this point; only the initial + * BT_SECURITY_SDP -> BT_SECURITY_LOW bump can still happen + * here. + */ + if (conn->sec_level == BT_SECURITY_SDP) { conn->sec_level = BT_SECURITY_LOW; - - if (conn->pending_sec_level > conn->sec_level) - conn->sec_level = conn->pending_sec_level; + mgmt_security_level_changed(conn); + } } mutex_lock(&hci_cb_list_lock); @@ -2308,8 +2320,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; @@ -2335,19 +2345,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; } @@ -2367,6 +2372,8 @@ void hci_send_sco(struct hci_conn *conn, struct sk_buff *skb); void hci_send_iso(struct hci_conn *conn, struct sk_buff *skb); void *hci_sent_cmd_data(struct hci_dev *hdev, __u16 opcode); +void *hci_sent_cmd_data_len(struct hci_dev *hdev, __u16 opcode, + size_t *len); void *hci_recv_event_data(struct hci_dev *hdev, __u8 event); u32 hci_conn_get_phy(struct hci_conn *conn); diff --git a/include/net/bluetooth/mgmt.h b/include/net/bluetooth/mgmt.h index 1e22eab1081c..b02e915bb44c 100644 --- a/include/net/bluetooth/mgmt.h +++ b/include/net/bluetooth/mgmt.h @@ -1221,3 +1221,17 @@ struct mgmt_ev_conn_subrate { __le16 cont_num; __le16 supv_timeout; } __packed; + +#define MGMT_CONN_SEC_ENCRYPT_NONE 0x00 +#define MGMT_CONN_SEC_ENCRYPT_E0 0x01 +#define MGMT_CONN_SEC_ENCRYPT_AES_CCM 0x02 + +#define MGMT_SEC_LEVEL_CHANGED_PARAM_LEVEL 0x0000 +#define MGMT_SEC_LEVEL_CHANGED_PARAM_ENC_TYPE 0x0001 + +#define MGMT_EV_SECURITY_LEVEL_CHANGED 0x0034 +struct mgmt_ev_security_level_changed { + struct mgmt_addr_info addr; + __u8 tlv_length; + __u8 tlv_data[] __counted_by(tlv_length); +} __packed; 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 0749230d414e..e311a8f5b5a7 100644 --- a/include/net/gso.h +++ b/include/net/gso.h @@ -19,7 +19,7 @@ struct skb_gso_cb { int encap_level; __wsum csum; __u16 csum_start; - /* Number of IPv4/IPv6 GSO handler entries for this packet. */ + /* Number of IPv4/IPv6/NSH GSO handler entries for this packet. */ u8 recursion_counter; }; #define SKB_GSO_CB_OFFSET 32 diff --git a/include/net/inet_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/inet_connection_sock.h b/include/net/inet_connection_sock.h index 433c2df23076..903499581db7 100644 --- a/include/net/inet_connection_sock.h +++ b/include/net/inet_connection_sock.h @@ -94,6 +94,7 @@ struct inet_connection_sock { u32 icsk_rto_max; __u32 icsk_delack_max; __u32 icsk_pmtu_cookie; + unsigned char unhashed_state; const struct tcp_congestion_ops *icsk_ca_ops; const struct inet_connection_sock_af_ops *icsk_af_ops; const struct tcp_ulp_ops *icsk_ulp_ops; diff --git a/include/net/ip6_route.h b/include/net/ip6_route.h index 5fd0c0e4beac..cf75208bfaa9 100644 --- a/include/net/ip6_route.h +++ b/include/net/ip6_route.h @@ -231,6 +231,13 @@ void rt6_multipath_rebalance(struct fib6_info *f6i); void rt6_uncached_list_add(struct rt6_info *rt); void rt6_uncached_list_del(struct rt6_info *rt); +#ifdef CONFIG_IPV6 +void rt6_uncached_list_flush_dev(struct net_device *dev); +#else +static inline void rt6_uncached_list_flush_dev(struct net_device *dev) +{ +} +#endif static inline const struct rt6_info *skb_rt6_info(const struct sk_buff *skb) { diff --git a/include/net/iw_handler.h b/include/net/iw_handler.h index b80e474cb0aa..632618d9ff93 100644 --- a/include/net/iw_handler.h +++ b/include/net/iw_handler.h @@ -201,6 +201,8 @@ #include /* IOCTL user space API */ #include +struct net; + /***************************** VERSION *****************************/ /* * This constant is used to know which version of the driver API is @@ -411,10 +413,10 @@ struct iw_spy_data { void wireless_send_event(struct net_device *dev, unsigned int cmd, union iwreq_data *wrqu, const char *extra); #ifdef CONFIG_WEXT_CORE -/* flush all previous wext events - if work is done from netdev notifiers */ -void wireless_nlevent_flush(void); +/* Flush previous wext events in this netns from netdev notifiers. */ +void wireless_nlevent_flush(struct net *net); #else -static inline void wireless_nlevent_flush(void) {} +static inline void wireless_nlevent_flush(struct net *net) {} #endif /* We may need a function to send a stream of events to user space. diff --git a/include/net/libeth/xsk.h b/include/net/libeth/xsk.h index 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/mana/mana.h b/include/net/mana/mana.h index e46ba02529c2..6a761672bd5b 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 */ @@ -694,7 +696,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 e5ee673b9fcf..119df9dac750 100644 --- a/include/net/net_namespace.h +++ b/include/net/net_namespace.h @@ -69,6 +69,7 @@ struct net { spinlock_t rules_mod_lock; unsigned int dev_base_seq; /* protected by rtnl_mutex */ + 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 fc3e81c07364..039622d48905 100644 --- a/include/net/netfilter/nf_queue.h +++ b/include/net/netfilter/nf_queue.h @@ -23,6 +23,7 @@ struct nf_queue_entry { struct net_device *physout; #endif struct nf_hook_state state; + bool in_nf_duplicate; bool nf_ct_is_unconfirmed; u16 size; /* sizeof(entry) + saved route keys */ diff --git a/include/net/netfilter/nf_recursion.h b/include/net/netfilter/nf_recursion.h new file mode 100644 index 000000000000..1ac65f7793f1 --- /dev/null +++ b/include/net/netfilter/nf_recursion.h @@ -0,0 +1,42 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _NF_RECURSION_H_ +#define _NF_RECURSION_H_ + +#include + +#define NF_RECURSION_LIMIT 2 + +#ifndef CONFIG_PREEMPT_RT +static inline bool nf_dev_xmit_recursion(void) +{ + return unlikely(__this_cpu_read(softnet_data.xmit.nf_xmit_skb_recursion) > + NF_RECURSION_LIMIT); +} + +static inline void nf_dev_xmit_recursion_inc(void) +{ + __this_cpu_inc(softnet_data.xmit.nf_xmit_skb_recursion); +} + +static inline void nf_dev_xmit_recursion_dec(void) +{ + __this_cpu_dec(softnet_data.xmit.nf_xmit_skb_recursion); +} +#else +static inline bool nf_dev_xmit_recursion(void) +{ + return unlikely(current->net_xmit.nf_xmit_skb_recursion > NF_RECURSION_LIMIT); +} + +static inline void nf_dev_xmit_recursion_inc(void) +{ + current->net_xmit.nf_xmit_skb_recursion++; +} + +static inline void nf_dev_xmit_recursion_dec(void) +{ + current->net_xmit.nf_xmit_skb_recursion--; +} +#endif + +#endif /* _NF_RECURSION_H_ */ diff --git a/include/net/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/route.h b/include/net/route.h index 45290177a33c..b4dfa2dcfd6c 100644 --- a/include/net/route.h +++ b/include/net/route.h @@ -129,7 +129,13 @@ struct in_device; int ip_rt_init(void); void rt_cache_flush(struct net *net); +#ifdef CONFIG_INET void rt_flush_dev(struct net_device *dev); +#else +static inline void rt_flush_dev(struct net_device *dev) +{ +} +#endif static inline void inet_sk_init_flowi4(const struct inet_sock *inet, struct flowi4 *fl4) diff --git a/include/net/sock.h b/include/net/sock.h index 60ea55dc1885..145770c9394d 100644 --- a/include/net/sock.h +++ b/include/net/sock.h @@ -2214,10 +2214,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) @@ -2280,6 +2283,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)) @@ -2291,7 +2302,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); } @@ -3024,14 +3036,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 4416cdf9bf30..00c2bcd5cac2 100644 --- a/include/net/tcp.h +++ b/include/net/tcp.h @@ -1514,6 +1514,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..29965e369598 100644 --- a/include/net/xdp_sock_drv.h +++ b/include/net/xdp_sock_drv.h @@ -160,15 +160,18 @@ static inline void xsk_buff_free(struct xdp_buff *xdp) static inline bool xsk_buff_add_frag(struct xdp_buff *head, struct xdp_buff *xdp) { + struct xdp_buff_xsk *frag = container_of(xdp, struct xdp_buff_xsk, xdp); const void *data = xdp->data; - struct xdp_buff_xsk *frag; + + /* Duplicate fill ring entries map to the same xskb in aligned mode */ + if (unlikely(xdp == head || !list_empty(&frag->list_node))) + return false; if (!__xdp_buff_add_frag(head, virt_to_netmem(data), offset_in_page(data), xdp->data_end - data, xdp->frame_sz, false)) return false; - frag = container_of(xdp, struct xdp_buff_xsk, xdp); list_add_tail(&frag->list_node, &frag->pool->xskb_list); return true; diff --git a/include/net/xfrm.h b/include/net/xfrm.h index 298ca9bb0083..445223a8dc6f 100644 --- a/include/net/xfrm.h +++ b/include/net/xfrm.h @@ -1765,6 +1765,13 @@ struct xfrm_state *xfrm_state_lookup_byaddr(struct net *net, u32 mark, const xfrm_address_t *saddr, u8 proto, unsigned short family); +struct xfrm_state *xfrm_state_lookup_exact(struct net *net, const struct xfrm_mark *mark, + const xfrm_address_t *daddr, __be32 spi, + u8 proto, unsigned short family); +bool xfrm_state_mark_collides(struct net *net, u32 mark, + const xfrm_address_t *daddr, __be32 spi, + u8 proto, unsigned short family, + const struct xfrm_state *self); #ifdef CONFIG_XFRM_SUB_POLICY void xfrm_tmpl_sort(struct xfrm_tmpl **dst, struct xfrm_tmpl **src, int n, unsigned short family); 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/perf_event.h b/include/uapi/linux/perf_event.h index fd10aa8d697f..c49fc76292f7 100644 --- a/include/uapi/linux/perf_event.h +++ b/include/uapi/linux/perf_event.h @@ -314,8 +314,9 @@ enum { */ enum perf_sample_regs_abi { PERF_SAMPLE_REGS_ABI_NONE = 0, - PERF_SAMPLE_REGS_ABI_32 = 1, - PERF_SAMPLE_REGS_ABI_64 = 2, + PERF_SAMPLE_REGS_ABI_32 = (1 << 0), + PERF_SAMPLE_REGS_ABI_64 = (1 << 1), + PERF_SAMPLE_REGS_ABI_SIMD = (1 << 2), }; /* @@ -383,6 +384,7 @@ enum perf_event_read_format { #define PERF_ATTR_SIZE_VER7 128 /* Add: sig_data */ #define PERF_ATTR_SIZE_VER8 136 /* Add: config3 */ #define PERF_ATTR_SIZE_VER9 144 /* add: config4 */ +#define PERF_ATTR_SIZE_VER10 176 /* Add: sample_simd_{vec|pred}_reg_* */ /* * 'struct perf_event_attr' contains various attributes that define @@ -547,6 +549,29 @@ struct perf_event_attr { __u64 config3; /* extension of config2 */ __u64 config4; /* extension of config3 */ + + /* + * Defines the sampling SIMD/PRED(predicate) registers bitmap and + * qwords (8 bytes) length. + * + * sample_simd_regs_enabled != 0 indicates there are SIMD/PRED + * registers to be sampled, the SIMD/PRED registers bitmap and + * qwords length are represented in + * sample_simd_{vec|pred}_reg_{intr|user} and + * sample_simd_{vec|pred}_reg_qwords fields separately. + * + * sample_simd_regs_enabled == 0 indicates no SIMD/PRED registers + * are sampled. + */ + __u16 sample_simd_regs_enabled; + __u16 sample_simd_pred_reg_qwords; + __u16 sample_simd_vec_reg_qwords; + __u16 __reserved_4; + + __u32 sample_simd_pred_reg_intr; + __u32 sample_simd_pred_reg_user; + __u64 sample_simd_vec_reg_intr; + __u64 sample_simd_vec_reg_user; }; /* @@ -1020,7 +1045,15 @@ enum perf_event_type { * } && PERF_SAMPLE_BRANCH_STACK * * { u64 abi; # enum perf_sample_regs_abi - * u64 regs[weight(mask)]; } && PERF_SAMPLE_REGS_USER + * u64 regs[weight(mask)]; + * struct { + * u64 nr_vectors; # 0 ... weight(sample_simd_vec_reg_user) + * u64 vector_qwords; # 0 ... sample_simd_vec_reg_qwords + * u64 nr_pred; # 0 ... weight(sample_simd_pred_reg_user) + * u64 pred_qwords; # 0 ... sample_simd_pred_reg_qwords + * u64 data[nr_vectors * vector_qwords + nr_pred * pred_qwords]; + * } && (abi & PERF_SAMPLE_REGS_ABI_SIMD) + * } && PERF_SAMPLE_REGS_USER * * { u64 size; * char data[size]; @@ -1047,7 +1080,15 @@ enum perf_event_type { * { u64 data_src; } && PERF_SAMPLE_DATA_SRC * { u64 transaction; } && PERF_SAMPLE_TRANSACTION * { u64 abi; # enum perf_sample_regs_abi - * u64 regs[weight(mask)]; } && PERF_SAMPLE_REGS_INTR + * u64 regs[weight(mask)]; + * struct { + * u64 nr_vectors; # 0 ... weight(sample_simd_vec_reg_intr) + * u64 vector_qwords; # 0 ... sample_simd_vec_reg_qwords + * u64 nr_pred; # 0 ... weight(sample_simd_pred_reg_intr) + * u64 pred_qwords; # 0 ... sample_simd_pred_reg_qwords + * u64 data[nr_vectors * vector_qwords + nr_pred * pred_qwords]; + * } && (abi & PERF_SAMPLE_REGS_ABI_SIMD) + * } && PERF_SAMPLE_REGS_INTR * { u64 phys_addr;} && PERF_SAMPLE_PHYS_ADDR * { u64 cgroup;} && PERF_SAMPLE_CGROUP * { u64 data_page_size;} && PERF_SAMPLE_DATA_PAGE_SIZE diff --git a/include/uapi/linux/virtio_spi.h b/include/uapi/linux/virtio_spi.h index 8ab3c970cdd3..459c2276c938 100644 --- a/include/uapi/linux/virtio_spi.h +++ b/include/uapi/linux/virtio_spi.h @@ -73,7 +73,7 @@ * @max_cs_hold_ns: the maximum delay supported before chipselect is deasserted, * in ns unit, 0 means delay is not supported to introduce before chipselect * is deasserted. - * @max_cs_incative_ns: maximum delay supported after chipselect is deasserted, + * @max_cs_inactive_ns: maximum delay supported after chipselect is deasserted, * in ns unit, 0 means delay is not supported to introduce after chipselect is * deasserted. */ diff --git a/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 +#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/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 @@ int __init rd_load_image(void) fput(in_file); noclose_input: fput(out_file); + /* + * The image only reaches the ramdisk when the deferred __fput() + * syncs the block device. Flush it before mount_root() reads it. + */ + init_flush_fput(); out: kfree(buf); init_unlink("/dev/ram"); diff --git a/io_uring/futex.c b/io_uring/futex.c index 9203998654ff..8a85ae20964b 100644 --- a/io_uring/futex.c +++ b/io_uring/futex.c @@ -107,6 +107,7 @@ static bool __io_futex_cancel(struct io_kiocb *req) } hlist_del_init(&req->hash_node); + req_set_fail(req); io_req_set_res(req, -ECANCELED, 0); io_req_task_work_add(req); return true; diff --git a/io_uring/io-wq.c b/io_uring/io-wq.c index 6b9395060262..d2ef08d65ec8 100644 --- a/io_uring/io-wq.c +++ b/io_uring/io-wq.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -737,6 +738,34 @@ static bool io_worker_retire(struct io_wq_acct *acct, struct io_worker *worker) return false; } +/* + * The CPUs a worker of @wq runs on: those of the io-wq affinity that the + * worker's cpuset allows, or the cpuset if they have none in common, as the + * scheduler does with a task's requested affinity when its cpuset changes. + * Read the cpuset each time: it can change while the io-wq exists. + */ +static void io_wq_worker_cpus(struct io_wq *wq, struct task_struct *tsk, + struct cpumask *cpus) +{ + cpuset_cpus_allowed(tsk, cpus); + if (cpumask_intersects(cpus, wq->cpu_mask)) + cpumask_and(cpus, cpus, wq->cpu_mask); +} + +/* Is the current worker on a CPU that a new worker would not get? */ +static bool io_wq_worker_off_cpus(struct io_wq *wq) +{ + cpumask_var_t cpus; + bool off; + + if (!alloc_cpumask_var(&cpus, GFP_KERNEL)) + return false; + io_wq_worker_cpus(wq, current, cpus); + off = !cpumask_test_cpu(raw_smp_processor_id(), cpus); + free_cpumask_var(cpus); + return off; +} + static int io_wq_worker(void *data) { struct io_worker *worker = data; @@ -815,8 +844,7 @@ static int io_wq_worker(void *data) } if (!ret) { last_timeout = true; - exit_mask = !cpumask_test_cpu(raw_smp_processor_id(), - wq->cpu_mask); + exit_mask = io_wq_worker_off_cpus(wq); } } @@ -866,9 +894,16 @@ void io_wq_worker_sleeping(struct task_struct *tsk) static void io_init_new_worker(struct io_wq *wq, struct io_wq_acct *acct, struct io_worker *worker, struct task_struct *tsk) { + cpumask_var_t cpus; + tsk->worker_private = worker; worker->task = tsk; - set_cpus_allowed_ptr(tsk, wq->cpu_mask); + /* Without a mask, the worker keeps its creator's CPUs. */ + if (alloc_cpumask_var(&cpus, GFP_KERNEL)) { + io_wq_worker_cpus(wq, tsk, cpus); + set_cpus_allowed_ptr(tsk, cpus); + free_cpumask_var(cpus); + } raw_spin_lock(&acct->workers_lock); hlist_nulls_add_head_rcu(&worker->nulls_node, &acct->free_list); @@ -1365,7 +1400,7 @@ struct io_wq *io_wq_create(unsigned bounded, struct io_wq_data *data) if (!alloc_cpumask_var(&wq->cpu_mask, GFP_KERNEL)) goto err; - cpuset_cpus_allowed(data->task, wq->cpu_mask); + cpumask_copy(wq->cpu_mask, cpu_possible_mask); wq->acct[IO_WQ_ACCT_BOUND].max_workers = bounded; wq->acct[IO_WQ_ACCT_UNBOUND].max_workers = task_rlimit(current, RLIMIT_NPROC); @@ -1444,6 +1479,22 @@ static void io_wq_cancel_tw_create(struct io_wq *wq) } } +static bool io_wq_worker_show(struct io_worker *worker, void *data) +{ + sched_show_task(worker->task); + return false; +} + +/* The exit path is always the same, show what the workers are stuck on */ +static void io_wq_show_stuck_workers(struct io_wq *wq) +{ + pr_warn("io-wq: %s/%d stuck waiting for workers to exit\n", + current->comm, task_pid_nr(current)); + rcu_read_lock(); + io_wq_for_each_worker(wq, io_wq_worker_show, NULL); + rcu_read_unlock(); +} + static void io_wq_exit_workers(struct io_wq *wq) { unsigned long timeout, warn_timeout; @@ -1465,8 +1516,8 @@ static void io_wq_exit_workers(struct io_wq *wq) * * where completely overloading the system with tons of long running * io-wq items can easily trigger the hung task timeout. Only sleep - * uninterruptibly for half that time, and warn if we exceeded end - * up waiting more than IO_URING_EXIT_WAIT_MAX. + * uninterruptibly for half that time, and show the stuck workers if + * we end up waiting more than IO_URING_EXIT_WAIT_MAX. */ timeout = sysctl_hung_task_timeout_secs * HZ / 2; if (!timeout) @@ -1475,7 +1526,8 @@ static void io_wq_exit_workers(struct io_wq *wq) do { if (wait_for_completion_timeout(&wq->worker_done, timeout)) break; - WARN_ON_ONCE(time_after(jiffies, warn_timeout)); + if (time_after(jiffies, warn_timeout)) + DO_ONCE_LITE(io_wq_show_stuck_workers, wq); } while (1); spin_lock_irq(&wq->hash->wait.lock); @@ -1570,7 +1622,7 @@ int io_wq_cpu_affinity(struct io_uring_task *tctx, cpumask_var_t mask) else ret = -EINVAL; } else { - cpumask_copy(tctx->io_wq->cpu_mask, allowed_mask); + cpumask_copy(tctx->io_wq->cpu_mask, cpu_possible_mask); } rcu_read_unlock(); diff --git a/io_uring/io_uring.c b/io_uring/io_uring.c index 41a03979cb8b..c6bd17cca45f 100644 --- a/io_uring/io_uring.c +++ b/io_uring/io_uring.c @@ -1498,9 +1498,11 @@ static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags) ret = __io_issue_sqe(req, issue_flags, def); if (ret == IOU_COMPLETE) { - /* not all handlers take care of the internal restart codes */ - if (unlikely(req->cqe.res <= -ERESTARTSYS)) - req->cqe.res = io_fixup_restart_res(req->cqe.res); + if (unlikely(req->cqe.res < 0)) { + if (req->cqe.res <= -ERESTARTSYS) + req->cqe.res = io_fixup_restart_res(req->cqe.res); + req_set_fail(req); + } if (issue_flags & IO_URING_F_COMPLETE_DEFER) io_req_complete_defer(req); else diff --git a/io_uring/io_uring.h b/io_uring/io_uring.h index 2d6b2158605a..0cb053aabe4b 100644 --- a/io_uring/io_uring.h +++ b/io_uring/io_uring.h @@ -139,6 +139,7 @@ struct io_wait_queue { #ifdef CONFIG_NET_RX_BUSY_POLL ktime_t napi_busy_poll_dt; + ktime_t napi_busy_poll_end; bool napi_prefer_busy_poll; #endif }; diff --git a/io_uring/kbuf.c b/io_uring/kbuf.c index abf44f5dba26..873d66a06b36 100644 --- a/io_uring/kbuf.c +++ b/io_uring/kbuf.c @@ -370,6 +370,7 @@ int io_buffers_select(struct io_kiocb *req, struct buf_sel_arg *arg, req->flags |= REQ_F_BUF_MORE; } } else { + arg->out_len = arg->max_len; ret = io_provided_buffers_select(req, &arg->out_len, sel->buf_list, arg->iovs); } out_unlock: diff --git a/io_uring/napi.c b/io_uring/napi.c index 7e698720cd51..54c1b328a89d 100644 --- a/io_uring/napi.c +++ b/io_uring/napi.c @@ -134,19 +134,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) { @@ -156,8 +152,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; @@ -215,13 +210,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; @@ -232,8 +230,7 @@ static void io_napi_blocking_busy_loop(struct io_ring_ctx *ctx, do { is_stale = __io_napi_do_busy_loop(ctx, loop_end, loop_end_arg); - } while (!io_napi_busy_loop_should_end(iowq, start_time) && - !loop_end_arg); + } while (!io_napi_busy_loop_should_end(iowq, 0)); } io_napi_remove_stale(ctx, is_stale); diff --git a/io_uring/rsrc.c b/io_uring/rsrc.c index c1ab760c4591..d1ba00390c58 100644 --- a/io_uring/rsrc.c +++ b/io_uring/rsrc.c @@ -330,8 +330,6 @@ static int __io_sqe_files_update(struct io_ring_ctx *ctx, if (i >= ctx->file_table.data.nr) break; i = array_index_nospec(i, ctx->file_table.data.nr); - if (io_reset_rsrc_node(ctx, &ctx->file_table.data, i)) - io_file_bitmap_clear(&ctx->file_table, i); if (fd != -1) { struct file *file = fget(fd); @@ -355,11 +353,15 @@ static int __io_sqe_files_update(struct io_ring_ctx *ctx, fput(file); break; } + if (io_reset_rsrc_node(ctx, &ctx->file_table.data, i)) + io_file_bitmap_clear(&ctx->file_table, i); ctx->file_table.data.nodes[i] = node; if (tag) node->tag = tag; io_fixed_file_set(node, file); io_file_bitmap_set(&ctx->file_table, i); + } else if (io_reset_rsrc_node(ctx, &ctx->file_table.data, i)) { + io_file_bitmap_clear(&ctx->file_table, i); } } return done ? done : err; diff --git a/io_uring/rw.c b/io_uring/rw.c index b21daa3cfa5c..0426c27f3c4c 100644 --- a/io_uring/rw.c +++ b/io_uring/rw.c @@ -603,8 +603,10 @@ static void io_complete_rw_iopoll(struct kiocb *kiocb, long res) if (res == -EAGAIN && io_rw_should_reissue(req)) req->flags |= REQ_F_REISSUE | REQ_F_BL_NO_RECYCLE; - else if (unlikely(final_res != req->cqe.res)) + else if (unlikely(final_res != req->cqe.res)) { + req_set_fail(req); req->cqe.res = final_res; + } /* order with io_iopoll_complete() checking ->iopoll_completed */ smp_store_release(&req->iopoll_completed, 1); diff --git a/io_uring/timeout.c b/io_uring/timeout.c index 8e7a4bd7e514..b46a50b39517 100644 --- a/io_uring/timeout.c +++ b/io_uring/timeout.c @@ -115,7 +115,8 @@ static void io_timeout_complete(struct io_tw_req tw_req, io_tw_token_t tw) struct io_ring_ctx *ctx = req->ctx; if (!io_timeout_finish(timeout, data)) { - if (io_req_post_cqe(req, -ETIME, IORING_CQE_F_MORE)) { + if (!tw.cancel && + io_req_post_cqe(req, -ETIME, IORING_CQE_F_MORE)) { /* re-arm timer */ raw_spin_lock_irq(&ctx->timeout_lock); list_add(&timeout->list, ctx->timeout_list.prev); diff --git a/kernel/bpf/arena.c b/kernel/bpf/arena.c index 868589f07330..5b65ffefbebd 100644 --- a/kernel/bpf/arena.c +++ b/kernel/bpf/arena.c @@ -7,6 +7,7 @@ #include #include "linux/filter.h" #include +#include #include #include #include @@ -630,11 +631,11 @@ static unsigned long arena_get_unmapped_area(struct file *filp, unsigned long ad { struct bpf_map *map = filp->private_data; struct bpf_arena *arena = container_of(map, struct bpf_arena, map); - long ret; + unsigned long ret; if (pgoff) return -EINVAL; - if (len > SZ_4G) + if (len > (u64)map->max_entries * PAGE_SIZE) return -E2BIG; /* if user_vm_start was specified at arena creation time */ @@ -647,14 +648,22 @@ static unsigned long arena_get_unmapped_area(struct file *filp, unsigned long ad return -EINVAL; } - ret = mm_get_unmapped_area(filp, addr, len * 2, 0, flags); + /* + * Without MAP_FIXED the mm finds a free range. Ask for twice the + * length, so that there is room for round_up(). With MAP_FIXED the mm + * does no search, and the caller wants this address. Thus the range + * cannot move. + */ + ret = mm_get_unmapped_area(filp, addr, flags & MAP_FIXED ? len : len * 2, 0, flags); if (IS_ERR_VALUE(ret)) return ret; + if (!ret) + /* user_vm_start == 0 means that the user range is not set yet */ + return -EINVAL; if ((ret >> 32) == ((ret + len - 1) >> 32)) return ret; - if (WARN_ON_ONCE(arena->user_vm_start)) - /* checks at map creation time should prevent this */ - return -EFAULT; + if (flags & MAP_FIXED) + return -EINVAL; return round_up(ret, SZ_4G); } @@ -679,7 +688,7 @@ static int arena_map_mmap(struct bpf_map *map, struct vm_area_struct *vma) return -EBUSY; /* Earlier checks should prevent this */ - if (WARN_ON_ONCE(vma->vm_end - vma->vm_start > SZ_4G || vma->vm_pgoff)) + if (WARN_ON_ONCE(vma_pages(vma) > map->max_entries || vma->vm_pgoff)) return -EFAULT; if (remember_vma(arena, vma)) @@ -987,6 +996,8 @@ static int arena_free_range(struct bpf_arena *arena, long uaddr, long page_cnt) static void arena_free_pages(struct bpf_arena *arena, long uaddr, long page_cnt, bool sleepable) { + /* The first mmap() may be setting the user range right now */ + u64 user_vm_start = READ_ONCE(arena->user_vm_start); struct mem_cgroup *new_memcg, *old_memcg; u64 full_uaddr, uaddr_end; struct arena_free_span *s; @@ -994,8 +1005,8 @@ static void arena_free_pages(struct bpf_arena *arena, long uaddr, long page_cnt, /* only aligned lower 32-bit are relevant */ uaddr = (u32)uaddr; uaddr &= PAGE_MASK; - full_uaddr = clear_lo32(arena->user_vm_start) + uaddr; - if (full_uaddr < arena->user_vm_start) + full_uaddr = clear_lo32(user_vm_start) + uaddr; + if (!user_vm_start || full_uaddr < user_vm_start) return; uaddr_end = min(arena->user_vm_end, full_uaddr + (page_cnt << PAGE_SHIFT)); if (full_uaddr >= uaddr_end) diff --git a/kernel/bpf/backtrack.c b/kernel/bpf/backtrack.c index 44d107fd96c4..cdf96ef68f7e 100644 --- a/kernel/bpf/backtrack.c +++ b/kernel/bpf/backtrack.c @@ -406,15 +406,18 @@ static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx, if (class == BPF_STX) bt_set_reg(bt, sreg); } else if (class == BPF_JMP || class == BPF_JMP32) { - if (bpf_pseudo_call(insn)) { - int subprog_insn_idx, subprog; + if (bpf_pseudo_call(insn) || bpf_is_callx(insn)) { + int subprog_insn_idx, subprog = -1; - subprog_insn_idx = idx + insn->imm + 1; - subprog = bpf_find_subprog(env, subprog_insn_idx); - if (subprog < 0) - return -EFAULT; + if (bpf_pseudo_call(insn)) { + subprog_insn_idx = idx + insn->imm + 1; + subprog = bpf_find_subprog(env, subprog_insn_idx); + if (subprog < 0) + return -EFAULT; + } - if (bpf_subprog_is_global(env, subprog)) { + /* callx calls static subprogs only */ + if (subprog >= 0 && bpf_subprog_is_global(env, subprog)) { /* check that jump history doesn't have any * extra instructions from subprog; the next * instruction after call to global subprog @@ -531,7 +534,8 @@ static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx, * necessary. In the former we never do that. */ from_subprog_call = subseq_idx - 1 >= 0 && - bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]); + (bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) || + bpf_is_callx(&env->prog->insnsi[subseq_idx - 1])); r0_precise = from_subprog_call && bt_is_reg_set(bt, BPF_REG_0); @@ -707,6 +711,17 @@ void bpf_mark_all_scalars_precise(struct bpf_verifier_env *env, i, -(j + 1) * 8); } } + for (j = 0; j < func->out_stack_arg_cnt; j++) { + reg = &func->stack_arg_regs[j]; + if (reg->type != SCALAR_VALUE || reg->precise) + continue; + reg->precise = true; + if (env->log.level & BPF_LOG_LEVEL2) { + verbose(env, + "force_precise: frame%d: forcing r11%d to be precise\n", + i, -(j + 1) * BPF_REG_SIZE); + } + } } } } diff --git a/kernel/bpf/cgroup.c b/kernel/bpf/cgroup.c index 149672c76c49..59326938a01e 100644 --- a/kernel/bpf/cgroup.c +++ b/kernel/bpf/cgroup.c @@ -1125,9 +1125,14 @@ static struct bpf_prog_list *find_detach_entry(struct hlist_head *progs, return ERR_PTR(-ENOENT); /* to maintain backward compatibility NONE and OVERRIDE cgroups - * allow detaching with invalid FD (prog==NULL) in legacy mode + * allow detaching with invalid FD (prog==NULL) in legacy mode. + * Without the FD of the attached program the caller needs + * CAP_NET_ADMIN or CAP_SYS_ADMIN in the initial user namespace. */ - return hlist_entry(progs->first, typeof(*pl), node); + pl = hlist_entry(progs->first, typeof(*pl), node); + if (pl->prog != prog && !bpf_net_capable()) + return ERR_PTR(-EPERM); + return pl; } if (!prog && !link) @@ -1625,7 +1630,7 @@ int __cgroup_bpf_run_filter_skb(struct sock *sk, struct sk_buff *skb, enum cgroup_bpf_attach_type atype) { - unsigned int offset = -skb_network_offset(skb); + int offset = skb_network_offset(skb); struct sock *save_sk; void *saved_data_end; struct cgroup *cgrp; @@ -1637,7 +1642,15 @@ int __cgroup_bpf_run_filter_skb(struct sock *sk, cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data); save_sk = skb->sk; skb->sk = sk; - __skb_push(skb, offset); + + /* + * The program sees the packet from its network header on, on + * whichever side of skb->data that header lies. + */ + if (offset > 0) + __skb_pull(skb, offset); + else + __skb_push(skb, -offset); /* compute pointers for the bpf prog */ bpf_compute_and_save_data_end(skb, &saved_data_end); @@ -1679,7 +1692,10 @@ int __cgroup_bpf_run_filter_skb(struct sock *sk, ret = -EFAULT; } bpf_restore_data_end(skb, saved_data_end); - __skb_pull(skb, offset); + if (offset > 0) + __skb_push(skb, offset); + else + __skb_pull(skb, -offset); skb->sk = save_sk; return ret; diff --git a/kernel/bpf/const_fold.c b/kernel/bpf/const_fold.c index d8d2d00380ae..e090f368e925 100644 --- a/kernel/bpf/const_fold.c +++ b/kernel/bpf/const_fold.c @@ -191,7 +191,8 @@ static void const_reg_xfer(struct bpf_verifier_env *env, struct const_arg_info * dst->val = val; break; case BPF_JMP: - if (opcode != BPF_CALL) + /* both 'call imm' and 'callx reg' clobber caller saved registers */ + if (BPF_OP(insn->code) != BPF_CALL) break; process_call: for (r = BPF_REG_0; r <= BPF_REG_5; r++) diff --git a/kernel/bpf/core.c b/kernel/bpf/core.c index f4682bcaea9d..37f6cbfac511 100644 --- a/kernel/bpf/core.c +++ b/kernel/bpf/core.c @@ -210,7 +210,9 @@ void bpf_prog_jit_attempt_done(struct bpf_prog *prog) * here is relative to the prog itself instead of the main prog. * This array has one entry for each xlated bpf insn. * - * jited_off is the byte off to the end of the jited insn. + * jited_off is the byte off to the end of the jited insn, counted from + * the start of the jited image, which is cfi_get_offset() bytes before + * prog->bpf_func. * * Hence, with * insn_start: @@ -224,7 +226,7 @@ void bpf_prog_jit_attempt_done(struct bpf_prog *prog) * * For i > linfo_idx, * - * jited_linfo[i] = prog->bpf_func + + * jited_linfo[i] = prog->bpf_func - cfi_get_offset() + * insn_to_jit_off[linfo[i].insn_off - insn_start - 1] */ void bpf_prog_fill_jited_linfo(struct bpf_prog *prog, @@ -252,7 +254,7 @@ void bpf_prog_fill_jited_linfo(struct bpf_prog *prog, /* The verifier ensures that linfo[i].insn_off is * strictly increasing */ - jited_linfo[i] = prog->bpf_func + + jited_linfo[i] = prog->bpf_func - cfi_get_offset() + insn_to_jit_off[linfo[i].insn_off - insn_start - 1]; } diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c index 5a5f7ec21f2d..524e6d3de077 100644 --- a/kernel/bpf/fixups.c +++ b/kernel/bpf/fixups.c @@ -1621,6 +1621,8 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env) struct bpf_subprog_info *subprogs = env->subprog_info; u16 stack_depth = subprogs[cur_subprog].stack_depth; u16 stack_depth_extra = 0; + /* arch_bpf_timed_may_goto() takes and returns AX in a cpu register: for JITs only */ + bool timed_may_goto = prog->jit_requested && bpf_jit_supports_timed_may_goto(); if (env->seen_exception && !env->exception_callback_subprog) { struct bpf_insn *patch = insn_buf; @@ -1876,7 +1878,7 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env) goto next_insn; } - if (bpf_is_may_goto_insn(insn) && bpf_jit_supports_timed_may_goto()) { + if (bpf_is_may_goto_insn(insn) && timed_may_goto) { int stack_off_cnt = -stack_depth - 16; /* * AX is used as an argument to pass in stack_off_cnt @@ -1906,6 +1908,7 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env) * after subtraction, rinse and repeat. */ stack_depth_extra = 16; + prog->jit_required = 1; cnt = may_goto_expand(insn_buf, insn->off, stack_off_cnt, tail, ARRAY_SIZE(tail)); @@ -2527,7 +2530,7 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env) env->prog->aux->stack_depth = subprogs[0].stack_depth; for (i = 0; i < env->subprog_cnt; i++) { - int delta = bpf_jit_supports_timed_may_goto() ? 2 : 1; + int delta = timed_may_goto ? 2 : 1; int subprog_start = subprogs[i].start; int stack_slots = subprogs[i].stack_extra / 8; int slots = delta, cnt = 0; @@ -2541,7 +2544,7 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env) } stack_depth = subprogs[i].stack_depth; - if (bpf_jit_supports_timed_may_goto()) { + if (timed_may_goto) { insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth, BPF_MAX_TIMED_LOOPS); insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth + 8, 0); diff --git a/kernel/bpf/hashtab.c b/kernel/bpf/hashtab.c index b2b27f87d8f5..d41fe658ae84 100644 --- a/kernel/bpf/hashtab.c +++ b/kernel/bpf/hashtab.c @@ -94,10 +94,10 @@ struct bpf_htab { struct bpf_lru lru; }; struct htab_elem *__percpu *extra_elems; - /* number of elements in non-preallocated hashtable are kept - * in either pcount or count + /* number of elements in non-preallocated hashtable. With + * use_percpu_counter it only follows map.elem_count in steps of + * PERCPU_COUNTER_BATCH, see is_map_full() */ - struct percpu_counter pcount; atomic_t count; bool use_percpu_counter; u32 n_buckets; /* number of hash buckets */ @@ -630,29 +630,20 @@ static struct bpf_map *htab_map_alloc(union bpf_attr *attr) htab_init_buckets(htab); -/* compute_batch_value() computes batch value as num_online_cpus() * 2 - * and __percpu_counter_compare() needs - * htab->max_entries - cur_number_of_elems to be more than batch * num_online_cpus() - * for percpu_counter to be faster than atomic_t. In practice the average bpf - * hash map size is 10k, which means that a system with 64 cpus will fill - * hashmap to 20% of 10k before percpu_counter becomes ineffective. Therefore - * define our own batch count as 32 then 10k hash map can be filled up to 80%: +/* is_map_full() needs htab->max_entries - cur_number_of_elems to be more than + * batch * nr_cpu_ids for the percpu counter to be faster than atomic_t. In + * practice the average bpf hash map size is 10k. With batch count of 32 a 10k + * hash map on a system with 64 cpus can be filled up to 80%: * 10k - 8k > 32 _batch_ * 64 _cpus_ - * and __percpu_counter_compare() will still be fast. At that point hash map + * and is_map_full() will still be fast. At that point hash map * collisions will dominate its performance anyway. Assume that hash map filled * to 50+% isn't going to be O(1) and use the following formula to choose - * between percpu_counter and atomic_t. + * between the percpu counter and atomic_t. The batch has to be a power of 2. */ #define PERCPU_COUNTER_BATCH 32 - if (attr->max_entries / 2 > num_online_cpus() * PERCPU_COUNTER_BATCH) + if (attr->max_entries / 2 > nr_cpu_ids * PERCPU_COUNTER_BATCH) htab->use_percpu_counter = true; - if (htab->use_percpu_counter) { - err = percpu_counter_init(&htab->pcount, 0, GFP_KERNEL); - if (err) - goto free_map_locked; - } - if (prealloc) { err = prealloc_init(htab); if (err) @@ -680,8 +671,6 @@ static struct bpf_map *htab_map_alloc(union bpf_attr *attr) free_prealloc: prealloc_destroy(htab); free_map_locked: - if (htab->use_percpu_counter) - percpu_counter_destroy(&htab->pcount); bpf_map_area_free(htab->buckets); bpf_mem_alloc_destroy(&htab->pcpu_ma); bpf_mem_alloc_destroy(&htab->ma); @@ -990,30 +979,33 @@ static void htab_put_fd_value(struct bpf_htab *htab, struct htab_elem *l) static bool is_map_full(struct bpf_htab *htab) { - if (htab->use_percpu_counter) - return __percpu_counter_compare(&htab->pcount, htab->map.max_entries, - PERCPU_COUNTER_BATCH) >= 0; - return atomic_read(&htab->count) >= htab->map.max_entries; + s64 count = atomic_read(&htab->count); + + /* each cpu's elem_count is ahead of count by less than the batch */ + if (htab->use_percpu_counter && + count + nr_cpu_ids * PERCPU_COUNTER_BATCH >= htab->map.max_entries) + count = bpf_map_sum_elem_count(&htab->map); + return count >= htab->map.max_entries; } static void inc_elem_count(struct bpf_htab *htab) { - bpf_map_inc_elem_count(&htab->map); + s64 cnt = this_cpu_inc_return(*htab->map.elem_count); - if (htab->use_percpu_counter) - percpu_counter_add_batch(&htab->pcount, 1, PERCPU_COUNTER_BATCH); - else + if (!htab->use_percpu_counter) atomic_inc(&htab->count); + else if (!(cnt & (PERCPU_COUNTER_BATCH - 1))) + atomic_add(PERCPU_COUNTER_BATCH, &htab->count); } static void dec_elem_count(struct bpf_htab *htab) { - bpf_map_dec_elem_count(&htab->map); + s64 cnt = this_cpu_dec_return(*htab->map.elem_count); - if (htab->use_percpu_counter) - percpu_counter_add_batch(&htab->pcount, -1, PERCPU_COUNTER_BATCH); - else + if (!htab->use_percpu_counter) atomic_dec(&htab->count); + else if (!((cnt + 1) & (PERCPU_COUNTER_BATCH - 1))) + atomic_sub(PERCPU_COUNTER_BATCH, &htab->count); } static void free_htab_elem(struct bpf_htab *htab, struct htab_elem *l) @@ -1682,8 +1674,6 @@ static void htab_map_free(struct bpf_map *map) bpf_map_area_free(htab->buckets); bpf_mem_alloc_destroy(&htab->pcpu_ma); bpf_mem_alloc_destroy(&htab->ma); - if (htab->use_percpu_counter) - percpu_counter_destroy(&htab->pcount); bpf_map_area_free(htab); } @@ -2393,9 +2383,7 @@ static u64 htab_map_mem_usage(const struct bpf_map *map) } else { #define LLIST_NODE_SZ sizeof(struct llist_node) - num_entries = htab->use_percpu_counter ? - percpu_counter_sum(&htab->pcount) : - atomic_read(&htab->count); + num_entries = bpf_map_sum_elem_count(map); usage += (htab->elem_size + LLIST_NODE_SZ) * num_entries; if (percpu) { usage += (LLIST_NODE_SZ + sizeof(void *)) * num_entries; diff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c index 7c2e6f0e7409..9100283e2935 100644 --- a/kernel/bpf/helpers.c +++ b/kernel/bpf/helpers.c @@ -3255,8 +3255,10 @@ __bpf_kfunc int bpf_dynptr_copy(const struct bpf_dynptr *dst_ptr, u64 dst_off, { const struct bpf_dynptr_kern *dst = (struct bpf_dynptr_kern *)dst_ptr; const struct bpf_dynptr_kern *src = (struct bpf_dynptr_kern *)src_ptr; + bool same = src->data == dst->data; void *src_slice, *dst_slice; char buf[256]; + bool rev; u64 off; src_slice = bpf_dynptr_slice(src_ptr, src_off, NULL, size); @@ -3267,25 +3269,31 @@ __bpf_kfunc int bpf_dynptr_copy(const struct bpf_dynptr *dst_ptr, u64 dst_off, return 0; } - if (src_slice) + /* The other range is copied piece by piece. A slice of the same packet + * may overlap with it, so it cannot be the buffer for that. + */ + if (src_slice && !same) return __bpf_dynptr_write(dst, dst_off, src_slice, size, 0); - if (dst_slice) + if (dst_slice && !same) return __bpf_dynptr_read(dst_slice, size, src, src_off, 0); if (bpf_dynptr_check_off_len(dst, dst_off, size) || bpf_dynptr_check_off_len(src, src_off, size)) return -E2BIG; + /* like memmove(): from the end if the destination is above the source */ + rev = same && dst->offset + dst_off > src->offset + src_off; off = 0; while (off < size) { u64 chunk_sz = min_t(u64, sizeof(buf), size - off); + u64 pos = rev ? size - off - chunk_sz : off; int err; - err = __bpf_dynptr_read(buf, chunk_sz, src, src_off + off, 0); + err = __bpf_dynptr_read(buf, chunk_sz, src, src_off + pos, 0); if (err) return err; - err = __bpf_dynptr_write(dst, dst_off + off, buf, chunk_sz, 0); + err = __bpf_dynptr_write(dst, dst_off + pos, buf, chunk_sz, 0); if (err) return err; diff --git a/kernel/bpf/liveness.c b/kernel/bpf/liveness.c index acee6f86f847..8980e2aa2573 100644 --- a/kernel/bpf/liveness.c +++ b/kernel/bpf/liveness.c @@ -464,12 +464,29 @@ int bpf_live_stack_query_init(struct bpf_verifier_env *env, struct bpf_verifier_ return 0; } +/* + * Stack slots of outer frames that the callee may read are accounted as read + * by the @callsite insn itself, i.e. they are live before @callsite and may be + * dead after it, when: + * - @callsite calls a callback, which may be called several times; + * - @callsite is callx. Its callee is not known when stack liveness is + * computed, so there is no func instance for it at @callsite. While + * the verifier is in the callee lookup_instance() finds its standalone + * instance that knows nothing about outer frames. What the callee may read + * there is recorded by record_call_access(). + */ +static bool callee_stack_access_at_callsite(struct bpf_verifier_env *env, u32 callsite) +{ + return bpf_calls_callback(env, callsite) || + bpf_is_callx(&env->prog->insnsi[callsite]); +} + bool bpf_stack_slot_alive(struct bpf_verifier_env *env, u32 frameno, u32 half_spi) { /* * Slot is alive if it is read before q->insn_idx in current func instance, * or if for some outer func instance: - * - alive before callsite if callsite calls callback, otherwise + * - alive before callsite if callsite calls callback or is callx, otherwise * - alive after callsite */ struct live_stack_query *q = &env->liveness->live_stack_query; @@ -502,7 +519,7 @@ bool bpf_stack_slot_alive(struct bpf_verifier_env *env, u32 frameno, u32 half_sp /* Get callsite from verifier state, not from instance callchain */ callsite = q->callsites[i]; - alive = bpf_calls_callback(env, callsite) + alive = callee_stack_access_at_callsite(env, callsite) ? is_live_before(instance, callsite, rel, half_spi) : is_live_before(instance, callsite + 1, rel, half_spi); if (alive) @@ -872,6 +889,19 @@ static struct arg_track arg_join_imprecise(struct arg_track a, struct arg_track return (struct arg_track){ .mask = m, .frame = ARG_IMPRECISE }; } +/* + * 'a' or a value that is not a pointer to stack. A single fp-N gets a fake fp+0, + * to keep stack_use and prevent stack_def. fp+0 itself would stay a single offset. + */ +static struct arg_track arg_or_none(struct arg_track a) +{ + if (a.off_cnt != 1) + return a; + if (!a.off[0]) + return (struct arg_track){ .frame = a.frame }; + return arg_merge_offsets(a, arg_single(a.frame, 0)); +} + /* Join two arg_track values at merge points */ static struct arg_track __arg_track_join(struct arg_track a, struct arg_track b) { @@ -896,20 +926,10 @@ static struct arg_track __arg_track_join(struct arg_track a, struct arg_track b) */ if (a.frame == ARG_NONE && b.frame == ARG_NONE) return a; - if (a.frame >= 0 && b.frame == ARG_NONE) { - /* - * When joining single fp-N add fake fp+0 to - * keep stack_use and prevent stack_def - */ - if (a.off_cnt == 1) - return arg_merge_offsets(a, arg_single(a.frame, 0)); - return a; - } - if (b.frame >= 0 && a.frame == ARG_NONE) { - if (b.off_cnt == 1) - return arg_merge_offsets(b, arg_single(b.frame, 0)); - return b; - } + if (a.frame >= 0 && b.frame == ARG_NONE) + return arg_or_none(a); + if (b.frame >= 0 && a.frame == ARG_NONE) + return arg_or_none(b); return arg_join_imprecise(a, b); } @@ -1262,6 +1282,31 @@ static struct arg_track arg_track_deref(struct bpf_verifier_env *env, struct bpf return (struct arg_track){ .frame = ARG_NONE }; } +/* + * True if the call at @insn_idx can pass a pointer to the frame at @depth to a static subprog + * or to a callback. They use it as a pointer to stack, a global subprog gets plain memory. + * It errs on the safe side: it looks at all argument registers and stack args, also at those + * that this callee doesn't take. + */ +static bool subprog_gets_local_fp(struct bpf_verifier_env *env, struct bpf_insn *insn, int insn_idx, + struct arg_track *at, int depth) +{ + int r; + + if (bpf_pseudo_call(insn)) { + r = bpf_find_subprog(env, insn_idx + insn->imm + 1); + if (r >= 0 && bpf_subprog_is_global(env, r)) + return false; + } else if (!bpf_is_callx(insn) && !bpf_calls_callback(env, insn_idx)) { + return false; + } + /* R1-R5 and stack args */ + for (r = BPF_REG_1; r < MAX_AT_TRACK_REGS; r++) + if ((r <= BPF_REG_5 || r >= MAX_BPF_REG) && can_be_local_fp(depth, r, &at[r])) + return true; + return false; +} + /* * Pure dataflow transfer function for arg_track state. * Updates at_out[] based on how the instruction modifies registers. @@ -1325,21 +1370,22 @@ static void arg_track_xfer(struct bpf_verifier_env *env, struct bpf_insn *insn, *dst = none; } else if (class == BPF_JMP && code == BPF_CALL) { /* - * at_stack_out[slot] is not cleared by the helper and subprog calls. - * The fill_from_stack() may return the stale spill — which is an FP-derived arg_track - * (the value that was originally spilled there). The loaded register then carries - * a phantom FP-derived identity that doesn't correspond to what's actually in the slot. - * This phantom FP pointer propagates forward, and wherever it's subsequently used - * (as a helper argument, another store, etc.), it sets stack liveness bits. - * Those bits correspond to stack accesses that don't actually happen. - * So the effect is over-reporting stack liveness — marking slots as live that aren't - * actually accessed. The verifier preserves more state than necessary across calls, - * which is conservative. + * Helpers, kfuncs and global subprogs can scratch stack slots. The verifier reads + * a scalar from a scratched slot, but at_stack_out[slot] is not cleared, and + * fill_from_stack() returns the stale spill: an FP-derived arg_track for a scalar. + * A scalar can't be dereferenced, so the stale value can only set liveness bits + * for stack accesses that don't happen. That is conservative. * - * helpers can scratch stack slots, but they won't make a valid pointer out of it. - * subprogs are allowed to write into parent slots, but they cannot write - * _any_ FP-derived pointer into it (either their own or parent's FP). + * Static subprogs and callbacks can't store an FP-derived pointer into the frame of + * the caller, but they can store any other pointer there. The caller can fill it + * and store through it. With the stale spill that store would be a definite write + * to a stack slot, and it doesn't touch the stack. Callees are analyzed after the + * caller, and they reach the whole frame from one pointer to it. So after the call + * every slot holds what it held before or a value that is not FP-derived. */ + if (subprog_gets_local_fp(env, insn, insn_idx, at_out, depth)) + for (slot = 0; slot < nslots; slot++) + at_stack_out[slot] = __arg_track_join(at_stack_out[slot], none); for (r = BPF_REG_0; r <= BPF_REG_5; r++) at_out[r] = none; } else if (class == BPF_LDX) { @@ -1593,21 +1639,29 @@ static int record_call_access(struct bpf_verifier_env *env, { struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; struct bpf_call_summary cs; - int r, err, num_params = 5; + int r, err, arg_slot_cnt = 5; if (bpf_pseudo_call(insn)) return 0; - if (bpf_get_call_summary(env, insn, &cs)) - num_params = cs.num_params; + if (bpf_is_callx(insn)) + /* + * The callee is not known statically. Assume that all arg + * slots are passed and let record_arg_access() conservatively + * mark the stack of all frames as read if any of them is + * derived from a frame pointer. + */ + arg_slot_cnt = MAX_BPF_FUNC_REG_ARGS + MAX_STACK_ARG_SLOTS; + else if (bpf_get_call_summary(env, insn, &cs)) + arg_slot_cnt = cs.arg_slot_cnt; - for (r = BPF_REG_1; r < BPF_REG_1 + min(num_params, MAX_BPF_FUNC_REG_ARGS); r++) { + for (r = BPF_REG_1; r < BPF_REG_1 + min(arg_slot_cnt, MAX_BPF_FUNC_REG_ARGS); r++) { err = record_arg_access(env, instance, insn, &at[r], r - 1, insn_idx); if (err) return err; } - for (r = 0; r < MAX_STACK_ARG_SLOTS && r < num_params - MAX_BPF_FUNC_REG_ARGS; r++) { + for (r = 0; r < MAX_STACK_ARG_SLOTS && r < arg_slot_cnt - MAX_BPF_FUNC_REG_ARGS; r++) { err = record_arg_access(env, instance, insn, &at[MAX_BPF_REG + r], r + MAX_BPF_FUNC_REG_ARGS, insn_idx); if (err) @@ -1692,7 +1746,7 @@ static void print_subprog_arg_access(struct bpf_verifier_env *env, bool has_extra = false; u8 cls = BPF_CLASS(insns[idx].code); bool is_ldx_stx_call = cls == BPF_LDX || cls == BPF_STX || - insns[idx].code == (BPF_JMP | BPF_CALL); + (cls == BPF_JMP && BPF_OP(insns[idx].code) == BPF_CALL); verbose(env, "%3d: ", idx); bpf_verbose_insn(env, &insns[idx]); @@ -1884,7 +1938,7 @@ static int compute_subprog_args(struct bpf_verifier_env *env, if (err) goto err_free; - if (insn->code == (BPF_JMP | BPF_CALL)) { + if (BPF_CLASS(insn->code) == BPF_JMP && BPF_OP(insn->code) == BPF_CALL) { err = record_call_access(env, instance, at_in[i], idx); if (err) goto err_free; @@ -2383,9 +2437,12 @@ static void compute_insn_live_regs(struct bpf_verifier_env *env, def = ALL_CALLER_SAVED_REGS; use = def & ~BIT(BPF_REG_0); if (bpf_get_call_summary(env, insn, &cs)) - use = GENMASK(min_t(u8, cs.num_params, MAX_BPF_FUNC_REG_ARGS), 1); + use = GENMASK(min_t(u8, cs.arg_slot_cnt, MAX_BPF_FUNC_REG_ARGS), 1); def = mask_widen(def); use = mask_widen(use); + /* callx reads the address of the callee from dst_reg */ + if (bpf_is_callx(insn)) + use |= dst; break; default: def = 0; diff --git a/kernel/bpf/stackmap.c b/kernel/bpf/stackmap.c index d09d4c3fe547..118fec76b9c2 100644 --- a/kernel/bpf/stackmap.c +++ b/kernel/bpf/stackmap.c @@ -527,12 +527,14 @@ static int stackid_init(struct stackid *stackid, struct bpf_map *map, u32 skip = flags & BPF_F_SKIP_FIELD_MASK; u32 max_depth; + max_depth = stack_map_calculate_max_depth(map->value_size, stack_map_data_size(map), flags); + /* trace_nr can be above max_depth and max_depth below skip: clamp first */ + trace_nr = min_t(u32, trace_nr, max_depth); if (trace_nr <= skip) /* skipping more than usable stack trace */ return -EFAULT; - max_depth = stack_map_calculate_max_depth(map->value_size, stack_map_data_size(map), flags); - stackid->nr = min_t(u32, trace_nr - skip, max_depth - skip); + stackid->nr = trace_nr - skip; stackid->len = stackid->nr * sizeof(u64); stackid->ips = trace->ip + skip; stackid->hash = jhash2((const u32 *)stackid->ips, stackid->len / sizeof(u32), 0); @@ -647,7 +649,8 @@ BPF_CALL_3(bpf_get_stackid, struct pt_regs *, regs, struct bpf_map *, map, /* couldn't fetch the stack trace */ return -EFAULT; - err = stackid_fastpath(&stackid, map, trace, trace->nr, flags); + /* the entry is released already, an NMI can change trace->nr */ + err = stackid_fastpath(&stackid, map, trace, READ_ONCE(trace->nr), flags); if (err != -ENOENT) return err; @@ -827,14 +830,20 @@ static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task, crosstask, false, 0); } - if (unlikely(!trace) || trace->nr < skip) { - if (may_fault) - rcu_read_unlock(); - preempt_enable(); - goto err_fault; - } + if (unlikely(!trace)) + goto err_unlock; - trace_nr = callchain_store(trace, trace->nr, buf, elem_size, flags); + /* + * trace->nr can be above max_depth. The per-CPU entry is released + * already: a tracing program or an NMI which takes a callchain in the + * same context before the copy below reuses it. And the unwinders of + * PowerPC store context markers on top of max_depth. + */ + trace_nr = min_t(u32, READ_ONCE(trace->nr), max_depth); + if (trace_nr < skip) + goto err_unlock; + + trace_nr = callchain_store(trace, trace_nr, buf, elem_size, flags); /* trace should not be dereferenced after this point */ if (may_fault) @@ -843,6 +852,10 @@ static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task, return callchain_finalize(buf, size, trace_nr, elem_size, flags, may_fault); +err_unlock: + if (may_fault) + rcu_read_unlock(); + preempt_enable(); err_fault: err = -EFAULT; clear: diff --git a/kernel/bpf/states.c b/kernel/bpf/states.c index f28b11c18908..4b407b629c99 100644 --- a/kernel/bpf/states.c +++ b/kernel/bpf/states.c @@ -1066,6 +1066,20 @@ static int propagate_precision(struct bpf_verifier_env *env, bpf_bt_set_frame_slot(&env->bt, fr, i); first = false; } + for (i = 0; i < state->out_stack_arg_cnt; i++) { + state_reg = &state->stack_arg_regs[i]; + if (state_reg->type != SCALAR_VALUE || !state_reg->precise) + continue; + if (env->log.level & BPF_LOG_LEVEL2) { + if (first) + verbose(env, "frame %d: propagating r11%d", + fr, -(i + 1) * BPF_REG_SIZE); + else + verbose(env, ",r11%d", -(i + 1) * BPF_REG_SIZE); + } + bt_set_frame_stack_arg_slot(&env->bt, fr, i); + first = false; + } if (!first && (env->log.level & BPF_LOG_LEVEL2)) verbose(env, "\n"); } diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c index 2ed356a03a57..4bb0f362f44a 100644 --- a/kernel/bpf/verifier.c +++ b/kernel/bpf/verifier.c @@ -17985,11 +17985,11 @@ bool bpf_get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call, (bpf_verifier_inlines_helper_call(env, call->imm) || bpf_jit_inlines_helper_call(call->imm)); cs->is_void = fn->ret_type == RET_VOID; - cs->num_params = 0; + cs->arg_slot_cnt = 0; for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) { if (fn->arg_type[i] == ARG_DONTCARE) break; - cs->num_params++; + cs->arg_slot_cnt++; } return true; } @@ -18001,7 +18001,7 @@ bool bpf_get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call, if (err < 0) /* error would be reported later */ return false; - cs->num_params = btf_type_vlen(meta.func_proto); + cs->arg_slot_cnt = btf_type_vlen(meta.func_proto); cs->fastcall = meta.kfunc_flags & KF_FASTCALL; cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type)); return true; @@ -18110,7 +18110,7 @@ static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env, * - includes R1-R5 if corresponding parameter has is described * in the function prototype. */ - clobbered_regs_mask = GENMASK(cs.num_params, cs.is_void ? 1 : 0); + clobbered_regs_mask = GENMASK(cs.arg_slot_cnt, cs.is_void ? 1 : 0); /* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */ expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS; diff --git a/kernel/cgroup/cgroup.c b/kernel/cgroup/cgroup.c index 37be027ce140..35c57390cf2b 100644 --- a/kernel/cgroup/cgroup.c +++ b/kernel/cgroup/cgroup.c @@ -4810,19 +4810,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 6f336ace3033..1d3dedcca871 100644 --- a/kernel/cgroup/cpuset.c +++ b/kernel/cgroup/cpuset.c @@ -1511,6 +1511,48 @@ static bool prstate_housekeeping_conflict(int new_prs, int parent_prs, 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 * @@ -1921,18 +1963,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 @@ -2510,32 +2544,6 @@ static int parse_cpuset_cpulist(const char *buf, struct cpumask *out_mask) return 0; } -/** - * 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 @@ -2549,33 +2557,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; @@ -2640,8 +2639,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 */ @@ -2705,8 +2707,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); /* @@ -3146,12 +3151,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 @@ -3188,7 +3213,7 @@ static int update_prstate(struct cpuset *cs, int new_prs) 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(old_prs, new_prs, tmpmask.new_cpus); spin_unlock_irq(&callback_lock); /* Force update if partition is disabled & update effective_xcpus */ @@ -3974,11 +3999,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; } @@ -4145,10 +4179,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 e8293a0e7945..a62a1273fc69 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) @@ -5347,7 +5357,7 @@ static bool is_sb_event(struct perf_event *event) attr->comm || attr->comm_exec || attr->task || attr->ksymbol || attr->context_switch || attr->text_poke || - attr->bpf_event) + attr->bpf_event || attr->defer_output) return true; return false; @@ -7843,24 +7853,84 @@ unsigned long perf_instruction_pointer(struct perf_event *event, 0 : perf_arch_instruction_pointer(regs); } +u64 __weak perf_reg_value(struct pt_regs *regs, int idx) +{ + return 0; +} + +int __weak perf_reg_validate(u64 mask) +{ + return mask ? -ENOSYS : 0; +} + +u64 __weak perf_reg_abi(struct task_struct *task) +{ + return PERF_SAMPLE_REGS_ABI_NONE; +} + +void __weak perf_get_regs_user(struct perf_regs *regs_user, + struct pt_regs *regs) +{ + regs_user->regs = task_pt_regs(current); + regs_user->abi = perf_reg_abi(current); +} + +#define word_for_each_set_bit(bit, val) \ + for (unsigned long long __v = (val); \ + __v && ((bit = __builtin_ctzll(__v)), 1); \ + __v &= __v - 1) + static void perf_output_sample_regs(struct perf_output_handle *handle, struct pt_regs *regs, u64 mask) { int bit; - DECLARE_BITMAP(_mask, 64); - - bitmap_from_u64(_mask, mask); - for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) { - u64 val; - val = perf_reg_value(regs, bit); + word_for_each_set_bit(bit, mask) { + u64 val = perf_reg_value(regs, bit); perf_output_put(handle, val); } } -static void perf_sample_regs_user(struct perf_regs *regs_user, - struct pt_regs *regs) +static void +perf_output_sample_simd_regs(struct perf_output_handle *handle, + struct perf_event *event, + struct pt_regs *regs, + u64 mask, u32 pred_mask) +{ + u64 pred_qwords = event->attr.sample_simd_pred_reg_qwords; + u64 vec_qwords = event->attr.sample_simd_vec_reg_qwords; + u64 nr_vectors = hweight64(mask); + u64 nr_pred = hweight32(pred_mask); + int bit; + + perf_output_put(handle, nr_vectors); + perf_output_put(handle, vec_qwords); + perf_output_put(handle, nr_pred); + perf_output_put(handle, pred_qwords); + + if (nr_vectors) { + word_for_each_set_bit(bit, mask) { + for (int i = 0; i < vec_qwords; i++) { + u64 val = perf_simd_reg_value(regs, bit, + i, false); + perf_output_put(handle, val); + } + } + } + if (nr_pred) { + word_for_each_set_bit(bit, pred_mask) { + for (int i = 0; i < pred_qwords; i++) { + u64 val = perf_simd_reg_value(regs, bit, + i, true); + perf_output_put(handle, val); + } + } + } +} + +void perf_sample_regs_user(struct perf_regs *regs_user, + struct pt_regs *regs) { if (user_mode(regs)) { regs_user->abi = perf_reg_abi(current); @@ -7873,9 +7943,9 @@ static void perf_sample_regs_user(struct perf_regs *regs_user, } } -static void perf_sample_regs_intr(struct perf_regs *regs_intr, - struct pt_regs *regs, - bool exclude_kernel) +void perf_sample_regs_intr(struct perf_regs *regs_intr, + struct pt_regs *regs, + bool exclude_kernel) { /* * Hardware skid can lead to a scenario where a PMI is @@ -7892,6 +7962,17 @@ static void perf_sample_regs_intr(struct perf_regs *regs_intr, } } +int __weak perf_simd_reg_validate(u16 vec_qwords, u64 vec_mask, + u16 pred_qwords, u32 pred_mask) +{ + return -EINVAL; +} + +u64 __weak perf_simd_reg_value(struct pt_regs *regs, int idx, + u16 qwords_idx, bool pred) +{ + return 0; +} /* * Get remaining task size from user stack pointer. @@ -8427,10 +8508,17 @@ void perf_output_sample(struct perf_output_handle *handle, perf_output_put(handle, abi); if (abi) { - u64 mask = event->attr.sample_regs_user; + struct perf_event_attr *attr = &event->attr; + u64 mask = attr->sample_regs_user; perf_output_sample_regs(handle, data->regs_user.regs, mask); + if (abi & PERF_SAMPLE_REGS_ABI_SIMD) { + perf_output_sample_simd_regs(handle, event, + data->regs_user.regs, + attr->sample_simd_vec_reg_user, + attr->sample_simd_pred_reg_user); + } } } @@ -8458,11 +8546,18 @@ void perf_output_sample(struct perf_output_handle *handle, perf_output_put(handle, abi); if (abi) { - u64 mask = event->attr.sample_regs_intr; + struct perf_event_attr *attr = &event->attr; + u64 mask = attr->sample_regs_intr; perf_output_sample_regs(handle, data->regs_intr.regs, mask); + if (abi & PERF_SAMPLE_REGS_ABI_SIMD) { + perf_output_sample_simd_regs(handle, event, + data->regs_intr.regs, + attr->sample_simd_vec_reg_intr, + attr->sample_simd_pred_reg_intr); + } } } @@ -8665,6 +8760,29 @@ static __always_inline u64 __cond_set(u64 flags, u64 s, u64 d) return d * !!(flags & s); } +static u64 perf_update_xregs_size(struct perf_event *event, bool intr) +{ + u16 pred_qwords = event->attr.sample_simd_pred_reg_qwords; + u16 vec_qwords = event->attr.sample_simd_vec_reg_qwords; + u64 pred_mask; + u64 mask; + int size; + + if (intr) { + mask = event->attr.sample_simd_vec_reg_intr; + pred_mask = event->attr.sample_simd_pred_reg_intr; + } else { + mask = event->attr.sample_simd_vec_reg_user; + pred_mask = event->attr.sample_simd_pred_reg_user; + } + + size = sizeof(u64) * 4; + size += (hweight64(mask) * vec_qwords + + hweight64(pred_mask) * pred_qwords) * sizeof(u64); + + return size; +} + void perf_prepare_sample(struct perf_sample_data *data, struct perf_event *event, struct pt_regs *regs) @@ -8727,7 +8845,12 @@ void perf_prepare_sample(struct perf_sample_data *data, if (data->regs_user.regs) { u64 mask = event->attr.sample_regs_user; + size += hweight64(mask) * sizeof(u64); + if (event_has_simd_regs(event)) { + size += perf_update_xregs_size(event, false); + data->regs_user.abi |= PERF_SAMPLE_REGS_ABI_SIMD; + } } data->dyn_size += size; @@ -8792,6 +8915,10 @@ void perf_prepare_sample(struct perf_sample_data *data, u64 mask = event->attr.sample_regs_intr; size += hweight64(mask) * sizeof(u64); + if (event_has_simd_regs(event)) { + size += perf_update_xregs_size(event, true); + data->regs_intr.abi |= PERF_SAMPLE_REGS_ABI_SIMD; + } } data->dyn_size += size; @@ -10397,8 +10524,6 @@ struct perf_callchain_deferred_event { struct { struct perf_event_header header; u64 cookie; - u64 nr; - u64 ips[]; } event; }; @@ -10407,12 +10532,19 @@ static void perf_callchain_deferred_output(struct perf_event *event, void *data) struct perf_callchain_deferred_event *deferred_event = data; struct perf_output_handle handle; struct perf_sample_data sample; + u64 nr = deferred_event->trace->nr; + u16 size, id_size, max_payload; int ret; - u16 size = sizeof(deferred_event->event) + (deferred_event->trace->nr * sizeof(u64)); if (!event->attr.defer_output) return; + id_size = event->attr.sample_id_all ? event->id_header_size : 0; + max_payload = round_down(U16_MAX - sizeof(deferred_event->event) - + sizeof(u64) - id_size, sizeof(u64)); + nr = min_t(u64, nr, max_payload / sizeof(u64)); + size = sizeof(deferred_event->event) + sizeof(u64) + nr * sizeof(u64); + /* XXX do we really need sample_id_all for this ??? */ perf_event_header__init(&deferred_event->event.header, &sample, PERF_RECORD_CALLCHAIN_DEFERRED, @@ -10426,8 +10558,10 @@ static void perf_callchain_deferred_output(struct perf_event *event, void *data) return; perf_output_put(&handle, deferred_event->event); - for (int i = 0; i < deferred_event->trace->nr; i++) { + perf_output_put(&handle, nr); + for (u64 i = 0; i < nr; i++) { u64 entry = deferred_event->trace->entries[i]; + perf_output_put(&handle, entry); } perf_event__output_id_sample(event, &handle, &sample); @@ -10442,7 +10576,6 @@ static void perf_unwind_deferred_callback(struct unwind_work *work, .trace = trace, .event = { .cookie = cookie, - .nr = trace->nr, }, }; @@ -12647,13 +12780,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); @@ -13082,12 +13210,6 @@ int perf_pmu_unregister(struct pmu *pmu) } EXPORT_SYMBOL_GPL(perf_pmu_unregister); -static inline bool has_extended_regs(struct perf_event *event) -{ - return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) || - (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK); -} - static int perf_try_init_event(struct pmu *pmu, struct perf_event *event) { struct perf_event_context *ctx = NULL; @@ -13121,8 +13243,14 @@ static int perf_try_init_event(struct pmu *pmu, struct perf_event *event) if (ret) goto err_pmu; + if (!(pmu->capabilities & PERF_PMU_CAP_SIMD_REGS) && + event_has_simd_regs(event)) { + ret = -EOPNOTSUPP; + goto err_destroy; + } + if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) && - has_extended_regs(event)) { + event_has_extended_regs(event)) { ret = -EOPNOTSUPP; goto err_destroy; } @@ -13616,7 +13744,8 @@ static int perf_copy_attr(struct perf_event_attr __user *uattr, attr->size = size; - if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3) + if (attr->__reserved_1 || attr->__reserved_2 || + attr->__reserved_3 || attr->__reserved_4) return -EINVAL; if (attr->sample_type & ~(PERF_SAMPLE_MAX-1)) @@ -13665,6 +13794,14 @@ static int perf_copy_attr(struct perf_event_attr __user *uattr, ret = perf_reg_validate(attr->sample_regs_user); if (ret) return ret; + if (attr->sample_simd_regs_enabled) { + ret = perf_simd_reg_validate(attr->sample_simd_vec_reg_qwords, + attr->sample_simd_vec_reg_user, + attr->sample_simd_pred_reg_qwords, + attr->sample_simd_pred_reg_user); + if (ret) + return ret; + } } if (attr->sample_type & PERF_SAMPLE_STACK_USER) { @@ -13685,8 +13822,19 @@ static int perf_copy_attr(struct perf_event_attr __user *uattr, if (!attr->sample_max_stack) attr->sample_max_stack = sysctl_perf_event_max_stack; - if (attr->sample_type & PERF_SAMPLE_REGS_INTR) + if (attr->sample_type & PERF_SAMPLE_REGS_INTR) { ret = perf_reg_validate(attr->sample_regs_intr); + if (ret) + return ret; + if (attr->sample_simd_regs_enabled) { + ret = perf_simd_reg_validate(attr->sample_simd_vec_reg_qwords, + attr->sample_simd_vec_reg_intr, + attr->sample_simd_pred_reg_qwords, + attr->sample_simd_pred_reg_intr); + if (ret) + return ret; + } + } #ifndef CONFIG_CGROUP_PERF if (attr->sample_type & PERF_SAMPLE_CGROUP) diff --git a/kernel/events/hw_breakpoint.c b/kernel/events/hw_breakpoint.c index 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 e787e4948c8b..246111601580 100644 --- a/kernel/kprobes.c +++ b/kernel/kprobes.c @@ -1558,52 +1558,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; @@ -1711,6 +1720,8 @@ static int __register_kprobe(struct kprobe *p) if (ret) { hlist_del_rcu(&p->hlist); synchronize_rcu(); + arch_remove_kprobe(p); + return ret; } } @@ -1732,7 +1743,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; @@ -2268,20 +2279,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; @@ -2368,8 +2378,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 @@ -2381,7 +2393,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 3c87c2a3d6f0..ab55b77119d6 100644 --- a/kernel/liveupdate/kexec_handover.c +++ b/kernel/liveupdate/kexec_handover.c @@ -1631,7 +1631,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 @@ -176,16 +176,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 @@ -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/locking/lockdep.c b/kernel/locking/lockdep.c index c3dc84a7cef2..fdae495bf918 100644 --- a/kernel/locking/lockdep.c +++ b/kernel/locking/lockdep.c @@ -811,7 +811,7 @@ static void lockdep_print_held_locks(struct task_struct *p) */ printk("locks held by %s/%d: %d, %s CPU#%d%s\n", p->comm, task_pid_nr(p), depth, - task_is_running(p) ? "last" : "on", task_cpu(p), + task_is_running(p) ? "on" : "last", task_cpu(p), depth > 0 ? ":" : ""); for (i = 0; i < depth; i++) { diff --git a/kernel/locking/osq_lock.c b/kernel/locking/osq_lock.c index b4233dc2c2b0..2bcc148eb2dd 100644 --- a/kernel/locking/osq_lock.c +++ b/kernel/locking/osq_lock.c @@ -59,7 +59,7 @@ osq_wait_next(struct optimistic_spin_queue *lock, for (;;) { if (atomic_read(&lock->tail) == curr && - atomic_cmpxchg_acquire(&lock->tail, curr, old_cpu) == curr) { + atomic_cmpxchg_release(&lock->tail, curr, old_cpu) == curr) { /* * We were the last queued, we moved @lock back. @prev * will now observe @lock and will complete its @@ -90,6 +90,49 @@ osq_wait_next(struct optimistic_spin_queue *lock, } } +/* + * Set prev->next; this is the counterpart of osq_wait_next() in that + * by setting ->next the wait is terminated and progress is resumed. + */ +static inline void osq_link_next(struct optimistic_spin_node *prev, + struct optimistic_spin_node *next) +{ + /* + * Suppose: + * + * tail + * | + * V + * CPU1 -> CPU2 -> CPU3: + * n: 2 n: 3 n: nil + * p: nil p: 1 p: 2 + * + * And this is CPU2 doing the self-unqueue concurrent against CPU1s + * unlock()/unqueue(). Since 'prev->next == NULL' and CPU1 will be + * stuck in osq_wait_next() until the below store of 'prev->next'. + * + * CPU2 CPU1 + * + * next->prev = prev; osq_wait_next() + * WMB MB + * prev->next = next; next->prev = prev + * + * Without the WMB it would be possible to have conflicting stores + * like: + * + * CPU2 CPU1 + * + * prev->next = next // CPU1.n = 3 + * next = osq_wait_next() // = 3 + * next->prev = prev // CPU3.p = nil + * next->prev = prev // CPU3.p = 1 + * + * Which would result in list corruption. + */ + smp_wmb(); + WRITE_ONCE(prev->next, next); +} + bool osq_lock(struct optimistic_spin_queue *lock) { struct optimistic_spin_node *node = this_cpu_ptr(&osq_node); @@ -113,20 +156,7 @@ bool osq_lock(struct optimistic_spin_queue *lock) prev = decode_cpu(old); node->prev = prev; - - /* - * osq_lock() unqueue - * - * node->prev = prev osq_wait_next() - * WMB MB - * prev->next = node next->prev = prev // unqueue-C - * - * Here 'node->prev' and 'next->prev' are the same variable and we need - * to ensure these stores happen in-order to avoid corrupting the list. - */ - smp_wmb(); - - WRITE_ONCE(prev->next, node); + osq_link_next(prev, node); /* * Normally @prev is untouchable after the above store; because at that @@ -202,7 +232,7 @@ bool osq_lock(struct optimistic_spin_queue *lock) */ WRITE_ONCE(next->prev, prev); - WRITE_ONCE(prev->next, next); + osq_link_next(prev, next); return false; } diff --git a/kernel/printk/printk.c b/kernel/printk/printk.c index bc3b9f6e404b..a14ab648ee9b 100644 --- a/kernel/printk/printk.c +++ b/kernel/printk/printk.c @@ -3790,6 +3790,13 @@ static struct syscore printk_syscore = { * If appropriate, start nbcon kthreads and set @printk_kthreads_running. * If any kthreads fail to start, those consoles are unregistered. * + * Called after consoles are registered or unregistered. + * + * This MUST NOT be called within an hlist_for_each_entry_safe(console_list) + * loop because it can unregister multiple consoles if any kthreads fail to + * start. That would lead to use-after-free scenarios within the + * hlist_for_each_entry_safe(console_list) loop of the caller. + * * Must be called under console_list_lock(). */ static void printk_kthreads_check_locked(void) @@ -4228,7 +4235,20 @@ void register_console(struct console *newcon) } EXPORT_SYMBOL(register_console); -/* Must be called under console_list_lock(). */ +/* + * Unregister the specified console. + * + * This can be called safely from within an + * hlist_for_each_entry_safe(console_list) loop because it unregisters + * _only_ the specified console. + * + * Afterwards the caller should call printk_kthreads_check_locked() since + * unregistering a console may require printer threads to start/stop. Note + * that printk_kthreads_check_locked() cannot be called safely from within + * an hlist_for_each_entry_safe(console_list) loop. + * + * Must be called under console_list_lock(). + */ static int unregister_console_locked(struct console *console) { bool use_device_lock = (console->flags & CON_NBCON) && console->write_atomic; @@ -4320,9 +4340,6 @@ static int unregister_console_locked(struct console *console) if (console->exit) res = console->exit(console); - /* Changed console list, may require printer threads to start/stop. */ - printk_kthreads_check_locked(); - return res; } @@ -4331,7 +4348,12 @@ int unregister_console(struct console *console) int res; console_list_lock(); + res = unregister_console_locked(console); + + /* Changed console list, may require printer threads to start/stop. */ + printk_kthreads_check_locked(); + console_list_unlock(); return res; } @@ -4455,6 +4477,10 @@ static int __init printk_late_init(void) unregister_console_locked(con); } } + + /* Changed console list, may require printer threads to start/stop. */ + printk_kthreads_check_locked(); + console_list_unlock(); ret = cpuhp_setup_state_nocalls(CPUHP_PRINTK_DEAD, "printk:dead", NULL, diff --git a/kernel/printk/printk_ringbuffer.c b/kernel/printk/printk_ringbuffer.c index 85c0c854b3ce..1b0198317a2f 100644 --- a/kernel/printk/printk_ringbuffer.c +++ b/kernel/printk/printk_ringbuffer.c @@ -1238,11 +1238,9 @@ static unsigned int space_used(struct prb_data_ring *data_ring, if (BLK_DATALESS(blk_lpos)) return 0; - if (!is_blk_wrapped(data_ring, blk_lpos->begin, blk_lpos->next)) { - /* Data block does not wrap. */ - return (DATA_INDEX(data_ring, blk_lpos->next) - - DATA_INDEX(data_ring, blk_lpos->begin)); - } + /* Data block does not wrap. */ + if (!is_blk_wrapped(data_ring, blk_lpos->begin, blk_lpos->next)) + return blk_lpos->next - blk_lpos->begin; /* * For wrapping data blocks, the trailing (wasted) space is diff --git a/kernel/sched/core.c b/kernel/sched/core.c index 4a051764e711..645111c09d7e 100644 --- a/kernel/sched/core.c +++ b/kernel/sched/core.c @@ -636,7 +636,7 @@ int task_llc(const struct task_struct *p) * * p->is_blocked <- { 0, 1 }: * - * is set by try_to_block_task() and cleared by ttwu_do_wakeup() and tracks + * is set by try_to_block_task() and cleared by unblock_task() and tracks * if the task is blocked. Traditionally this would mirror p->on_rq, however * due things like DELAY_DEQUEUE and PROXY_EXEC, this can diverge. * @@ -3740,12 +3740,22 @@ ttwu_stat(struct task_struct *p, int cpu, int wake_flags) __schedstat_inc(p->stats.nr_wakeups_sync); } +static inline void unblock_task(struct task_struct *p) +{ + if (p->is_blocked && p->in_iowait) { + delayacct_blkio_end(p); + atomic_dec(&cpu_rq(p->iowait_cpu)->nr_iowait); + } + + p->is_blocked = 0; +} + /* * Mark the task runnable. */ static inline void ttwu_do_wakeup(struct task_struct *p) { - p->is_blocked = 0; + unblock_task(p); WRITE_ONCE(p->__state, TASK_RUNNING); trace_sched_wakeup(p); } @@ -3843,10 +3853,6 @@ ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags, en_flags |= ENQUEUE_RQ_SELECTED; if (wake_flags & WF_MIGRATED) en_flags |= ENQUEUE_MIGRATED; - else if (p->in_iowait) { - delayacct_blkio_end(p); - atomic_dec(&task_rq(p)->nr_iowait); - } activate_task(rq, p, en_flags); wakeup_preempt(rq, p, wake_flags); @@ -4419,11 +4425,6 @@ int try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags) cpu = select_task_rq(p, p->wake_cpu, &wake_flags); if (task_cpu(p) != cpu) { - if (p->in_iowait) { - delayacct_blkio_end(p); - atomic_dec(&task_rq(p)->nr_iowait); - } - wake_flags |= WF_MIGRATED; psi_ttwu_dequeue(p); set_task_cpu(p, cpu); @@ -6250,7 +6251,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; @@ -6300,8 +6300,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; @@ -6367,7 +6365,7 @@ pick_next_task(struct rq *rq, struct rq_flags *rf) * 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); /* @@ -6400,7 +6398,7 @@ pick_next_task(struct rq *rq, struct rq_flags *rf) * 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; @@ -6446,7 +6444,7 @@ pick_next_task(struct rq *rq, struct rq_flags *rf) * 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); /* @@ -6766,6 +6764,12 @@ static bool try_to_block_task(struct rq *rq, struct task_struct *p, p->is_blocked = 1; + if (p->in_iowait) { + p->iowait_cpu = cpu_of(rq); + atomic_inc(&rq->nr_iowait); + delayacct_blkio_start(); + } + /* * We check should_block after signal_pending because we * will want to wake the task in that case. But if @@ -6938,7 +6942,7 @@ find_proxy_task(struct rq *rq, struct task_struct *donor, struct rq_flags *rf) if (!mutex) { clear_task_blocked_on(p, mutex); if (task_current(rq, p)) { - p->is_blocked = 0; + unblock_task(p); return p; } goto deactivate; @@ -6974,7 +6978,7 @@ find_proxy_task(struct rq *rq, struct task_struct *donor, struct rq_flags *rf) */ __clear_task_blocked_on(p, NULL); if (task_current(rq, p)) { - p->is_blocked = 0; + unblock_task(p); return p; } goto deactivate; 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 @@ int sched_core_share_pid(unsigned int cmd, pid_t pid, enum pid_type type, /* 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/deadline.c b/kernel/sched/deadline.c index 1502a45d76aa..4d502ca88448 100644 --- a/kernel/sched/deadline.c +++ b/kernel/sched/deadline.c @@ -444,7 +444,7 @@ static void task_non_contending(struct sched_dl_entity *dl_se, bool dl_task) if (!dl_task || READ_ONCE(p->__state) == TASK_DEAD) { struct dl_bw *dl_b = dl_bw_of(task_cpu(p)); - if (READ_ONCE(p->__state) == TASK_DEAD) + if (dl_task && READ_ONCE(p->__state) == TASK_DEAD) sub_rq_bw(dl_se, &rq->dl); raw_spin_lock(&dl_b->lock); __dl_sub(dl_b, dl_se->dl_bw, dl_bw_cpus(task_cpu(p))); diff --git a/kernel/sched/ext/cid.c b/kernel/sched/ext/cid.c index 3d0687184b44..17c86f25a59c 100644 --- a/kernel/sched/ext/cid.c +++ b/kernel/sched/ext/cid.c @@ -63,7 +63,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 4b04ed0441fc..cc8d09924fa1 100644 --- a/kernel/sched/ext/ext.c +++ b/kernel/sched/ext/ext.c @@ -2150,7 +2150,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); @@ -3000,6 +3000,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); @@ -3027,6 +3033,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; @@ -3789,6 +3799,24 @@ 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(); @@ -3869,26 +3897,13 @@ static void rq_online_scx(struct rq *rq) 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); - } + drain_offline_rq(rq); } static bool check_rq_for_timeouts(struct rq *rq) @@ -7106,10 +7121,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); } @@ -11226,6 +11248,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 @@ -11240,6 +11267,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..5dce394e0813 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; @@ -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 68703b10d899..2f35b98adb72 100644 --- a/kernel/sched/ext/internal.h +++ b/kernel/sched/ext/internal.h @@ -839,6 +839,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 cb75d1912a7b..4dc3bb12aca3 100644 --- a/kernel/sched/ext/sub.c +++ b/kernel/sched/ext/sub.c @@ -2064,8 +2064,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 327d5f8f4596..d1ea0e53f165 100644 --- a/kernel/sched/fair.c +++ b/kernel/sched/fair.c @@ -11035,7 +11035,14 @@ alb_break_llc(struct lb_env *env) return true; cur = rcu_dereference_all(env->src_rq->curr); - if (cur && cur->sched_class == &fair_sched_class) + /* + * Active balance only detaches CFS tasks, so a non-fair + * curr is never migrated. Ignore it and avoid using its + * state util in the misfit and LLC checks. + */ + if (cur && cur->sched_class != &fair_sched_class) + cur = NULL; + if (cur) util = task_util(cur); if (task_misfits_asym_cpu(env, cur) || diff --git a/kernel/sched/pelt.c b/kernel/sched/pelt.c index 779eb58a4261..d10d57b6b8ec 100644 --- a/kernel/sched/pelt.c +++ b/kernel/sched/pelt.c @@ -99,7 +99,7 @@ static u32 __accumulate_pelt_segments(u64 periods, u32 d1, u32 d3) * d1 y^p + 1024 \Sum y^n + d3 y^0 (Step 2) * n=1 */ -static __always_inline u32 +static __always_inline u64 accumulate_sum(u64 delta, struct sched_avg *sa, unsigned long load, unsigned long runnable, int running) { diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h index 8d805aa7c85d..b345f62263b3 100644 --- a/kernel/sched/sched.h +++ b/kernel/sched/sched.h @@ -1514,6 +1514,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); @@ -3082,11 +3101,6 @@ static inline void __block_task(struct rq *rq, struct task_struct *p) if (p->sched_contributes_to_load) rq->nr_uninterruptible++; - if (p->in_iowait) { - atomic_inc(&rq->nr_iowait); - delayacct_blkio_start(); - } - ASSERT_EXCLUSIVE_WRITER(p->on_rq); /* @@ -4233,7 +4247,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 b215b0ead9a6..51c35a9158e5 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 @@ int __sched_setscheduler(struct task_struct *p, * the entire root_domain to become SCHED_DEADLINE. We * will also fail if there's no bandwidth available. */ - if (!cpumask_subset(span, p->cpus_ptr) || + if (!cpumask_subset(span, &p->cpus_mask) || rq->rd->dl_bw.bw == 0) { retval = -EPERM; goto unlock; @@ -640,8 +640,10 @@ int __sched_setscheduler(struct task_struct *p, if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) { policy = oldpolicy = -1; task_rq_unlock(rq, p, &rf); - if (cpuset_locked) + if (cpuset_locked) { cpuset_unlock(); + cpuset_locked = false; + } goto recheck; } diff --git a/kernel/sched/topology.c b/kernel/sched/topology.c index 3dab0253976f..21e3ab1af4c8 100644 --- a/kernel/sched/topology.c +++ b/kernel/sched/topology.c @@ -3314,13 +3314,25 @@ int __init sched_init_domains(const struct cpumask *cpu_map) static void detach_destroy_domains(const struct cpumask *cpu_map) { unsigned int cpu = cpumask_any(cpu_map); + bool has_cluster = false; int i; if (rcu_access_pointer(per_cpu(sd_asym_cpucapacity, cpu))) static_branch_dec_cpuslocked(&sched_asym_cpucapacity); - if (static_branch_unlikely(&sched_cluster_active)) - static_branch_dec_cpuslocked(&sched_cluster_active); + if (static_branch_unlikely(&sched_cluster_active)) { + rcu_read_lock(); + for_each_cpu(i, cpu_map) { + if (lowest_flag_domain(i, SD_CLUSTER)) { + has_cluster = true; + break; + } + } + rcu_read_unlock(); + + if (has_cluster) + static_branch_dec_cpuslocked(&sched_cluster_active); + } rcu_read_lock(); for_each_cpu(i, cpu_map) diff --git a/kernel/time/timekeeping.c b/kernel/time/timekeeping.c index cae3e51eaf55..bd0602103241 100644 --- a/kernel/time/timekeeping.c +++ b/kernel/time/timekeeping.c @@ -1598,6 +1598,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 @@ -1773,6 +1776,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 */ @@ -2698,7 +2702,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 88518c5322a5..b79bd04a3bbb 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(mtype)) { 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; - } - - type = btf_type_skip_modifiers(btf, field->type, NULL); - if (!type) { - trace_probe_log_err(ctx->offset, BAD_BTF_TID); - return -EINVAL; + if (BTF_INFO_KIND(type->info) == BTF_KIND_INT) { + u32 intdata = btf_type_int(type); + + 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/lib/bootconfig.c b/lib/bootconfig.c index 89c88e359179..e4c9dc9f6e56 100644 --- a/lib/bootconfig.c +++ b/lib/bootconfig.c @@ -431,9 +431,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) @@ -790,16 +790,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 56c59a2b589d..55c0dc7e1074 100644 --- a/lib/iov_iter.c +++ b/lib/iov_iter.c @@ -1366,8 +1366,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; @@ -1438,7 +1438,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/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/memory_hotplug.c b/mm/memory_hotplug.c index 0a4df6ba2d53..c48d4de96c86 100644 --- a/mm/memory_hotplug.c +++ b/mm/memory_hotplug.c @@ -475,6 +475,22 @@ static unsigned long find_biggest_section_pfn(int nid, struct zone *zone, return 0; } +/* + * The page allocator checks pages against the span of their zone while the + * zone is resized, see page_outside_zone_boundaries(). It must not see the + * new value of one field together with the old value of the other one. + */ +static void zone_set_span(struct zone *zone, unsigned long start_pfn, + unsigned long spanned_pages) +{ + unsigned long flags; + + write_seqlock_irqsave(&zone->span_seqlock, flags); + zone->zone_start_pfn = start_pfn; + zone->spanned_pages = spanned_pages; + write_sequnlock_irqrestore(&zone->span_seqlock, flags); +} + static void shrink_zone_span(struct zone *zone, unsigned long start_pfn, unsigned long end_pfn) { @@ -490,13 +506,10 @@ static void shrink_zone_span(struct zone *zone, unsigned long start_pfn, */ pfn = find_smallest_section_pfn(nid, zone, end_pfn, zone_end_pfn(zone)); - if (pfn) { - zone->spanned_pages = zone_end_pfn(zone) - pfn; - zone->zone_start_pfn = pfn; - } else { - zone->zone_start_pfn = 0; - zone->spanned_pages = 0; - } + if (pfn) + zone_set_span(zone, pfn, zone_end_pfn(zone) - pfn); + else + zone_set_span(zone, 0, 0); } else if (zone_end_pfn(zone) == end_pfn) { /* * If the section is biggest section in the zone, it need @@ -507,11 +520,10 @@ static void shrink_zone_span(struct zone *zone, unsigned long start_pfn, pfn = find_biggest_section_pfn(nid, zone, zone->zone_start_pfn, start_pfn); if (pfn) - zone->spanned_pages = pfn - zone->zone_start_pfn + 1; - else { - zone->zone_start_pfn = 0; - zone->spanned_pages = 0; - } + zone_set_span(zone, zone->zone_start_pfn, + pfn - zone->zone_start_pfn + 1); + else + zone_set_span(zone, 0, 0); } } @@ -703,12 +715,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, @@ -1823,6 +1835,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 d9de3b5d5ebe..e6b34488ddcc 100644 --- a/mm/mempolicy.c +++ b/mm/mempolicy.c @@ -2159,6 +2159,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 @@ -2169,7 +2170,8 @@ unsigned int mempolicy_slab_node(void) zonelist = &NODE_DATA(node)->node_zonelists[ZONELIST_FALLBACK]; z = first_zones_zonelist(zonelist, highest_zoneidx, &policy->nodes); - return zonelist_zone(z) ? zonelist_node_idx(z) : node; + zone = zonelist_zone(z); + return zone ? zone_to_nid(zone) : node; } case MPOL_LOCAL: return node; diff --git a/mm/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 8714425ffe84..55232081a32b 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); @@ -1580,6 +1579,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); } @@ -3817,12 +3818,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. @@ -3869,7 +3879,7 @@ get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags, } if (no_fallback && !defrag_mode && nr_online_nodes > 1 && - zone != zonelist_zone(ac->preferred_zoneref)) { + zone != preferred_zone) { int local_nid; /* @@ -3877,7 +3887,7 @@ get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags, * fragmenting fallbacks. Locality is more important * than fragmentation avoidance. */ - local_nid = zonelist_node_idx(ac->preferred_zoneref); + local_nid = zone_to_nid(preferred_zone); if (zone_to_nid(zone) != local_nid) { alloc_flags &= ~ALLOC_NOFRAGMENT; goto retry; @@ -3939,7 +3949,7 @@ get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags, goto try_this_zone; if (!node_reclaim_enabled() || - !zone_allows_reclaim(zonelist_zone(ac->preferred_zoneref), zone)) + !zone_allows_reclaim(preferred_zone, zone)) continue; if (!node_reclaim(zone->zone_pgdat, gfp_mask, order)) @@ -3952,7 +3962,7 @@ get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags, } try_this_zone: - page = rmqueue(zonelist_zone(ac->preferred_zoneref), zone, order, + page = rmqueue(preferred_zone, zone, order, gfp_mask, alloc_flags, ac->migratetype); if (page) { prep_new_page(page, order, gfp_mask, alloc_flags); @@ -4427,7 +4437,7 @@ static DEFINE_SEQLOCK(zonelist_update_seq); static unsigned int zonelist_iter_begin(void) { - if (IS_ENABLED(CONFIG_MEMORY_HOTREMOVE)) + if (IS_ENABLED(CONFIG_MEMORY_HOTPLUG)) return read_seqbegin(&zonelist_update_seq); return 0; @@ -4435,7 +4445,7 @@ static unsigned int zonelist_iter_begin(void) static unsigned int check_retry_zonelist(unsigned int seq) { - if (IS_ENABLED(CONFIG_MEMORY_HOTREMOVE)) + if (IS_ENABLED(CONFIG_MEMORY_HOTPLUG)) return read_seqretry(&zonelist_update_seq, seq); return seq; @@ -4693,7 +4703,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; @@ -4806,7 +4816,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; /* @@ -4840,6 +4850,7 @@ __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order, 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(); @@ -5206,6 +5217,7 @@ 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; @@ -5253,6 +5265,11 @@ unsigned long alloc_pages_bulk_noprof(gfp_t gfp, int preferred_nid, 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) { @@ -5263,8 +5280,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; } @@ -5272,7 +5289,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; } @@ -5329,7 +5346,7 @@ unsigned long alloc_pages_bulk_noprof(gfp_t gfp, int preferred_nid, 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; @@ -6356,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); @@ -6448,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 @@ -7377,9 +7402,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); @@ -7583,6 +7612,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; @@ -7591,8 +7621,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); @@ -7627,6 +7662,9 @@ struct page *alloc_contig_frozen_pages_noprof(unsigned long nr_pages, * 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; @@ -7732,6 +7770,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; @@ -7742,12 +7786,6 @@ void zone_pcp_reset(struct zone *zone) pzstats = per_cpu_ptr(zone->per_cpu_zonestats, cpu); drain_zonestat(zone, pzstats); } - free_percpu(zone->per_cpu_pageset); - zone->per_cpu_pageset = &boot_pageset; - if (zone->per_cpu_zonestats != &boot_zonestats) { - free_percpu(zone->per_cpu_zonestats); - zone->per_cpu_zonestats = &boot_zonestats; - } } } diff --git a/mm/page_frag_cache.c b/mm/page_frag_cache.c index e63efe78b7d4..8914437ddc51 100644 --- a/mm/page_frag_cache.c +++ b/mm/page_frag_cache.c @@ -119,15 +119,20 @@ void *__page_frag_alloc_align(struct page_frag_cache *nc, size = PAGE_SIZE << encoded_page_decode_order(encoded_page); offset = __ALIGN_KERNEL_MASK(nc->offset, ~align_mask); if (unlikely(offset + fragsz > size)) { - if (unlikely(fragsz > PAGE_SIZE)) { + if (unlikely(fragsz > size)) { /* - * The caller is trying to allocate a fragment - * with fragsz > PAGE_SIZE but the cache isn't big - * enough to satisfy the request, this may - * happen in low memory conditions. - * We don't release the cache page because - * it could make memory pressure worse - * so we simply return NULL here. + * The caller is trying to allocate a fragment that's + * larger than the whole cache page. + * + * Either fragsz is larger than PAGE_FRAG_CACHE_MAX_SIZE + * so this cannot ever succeed. + * + * Or the refill has fallen back to order-0 due to a low + * memory condition. Then we don't want to release the + * cache page to attempt a new large-size refill because + * it could make memory pressure worse. + * + * So in both cases we simply return NULL here. */ return NULL; } diff --git a/mm/page_isolation.c b/mm/page_isolation.c index 5aaad037384e..f4f0571607ab 100644 --- a/mm/page_isolation.c +++ b/mm/page_isolation.c @@ -74,6 +74,13 @@ bool page_is_unmovable(struct zone *zone, struct page *page, return false; } + /* + * 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. diff --git a/mm/shmem.c b/mm/shmem.c index eac9017cfb8d..9742258e871f 100644 --- a/mm/shmem.c +++ b/mm/shmem.c @@ -3131,7 +3131,7 @@ static struct inode *__shmem_get_inode(struct mnt_idmap *idmap, inode->i_size = 2 * BOGO_DIRENT_SIZE; inode->i_op = &shmem_dir_inode_operations; inode->i_fop = &simple_offset_dir_operations; - simple_offset_init(shmem_get_offset_ctx(inode)); + simple_offset_init(shmem_get_offset_ctx(inode), inode); break; case S_IFLNK: /* diff --git a/mm/slub.c b/mm/slub.c index 6bb75db087a2..41a66fc15edf 100644 --- a/mm/slub.c +++ b/mm/slub.c @@ -422,6 +422,7 @@ struct node_barn { spinlock_t lock; struct list_head sheaves_full; struct list_head sheaves_empty; + struct slab_sheaf *sheaf_partial; unsigned int nr_full; unsigned int nr_empty; }; @@ -3298,6 +3299,7 @@ static void barn_init(struct node_barn *barn) spin_lock_init(&barn->lock); INIT_LIST_HEAD(&barn->sheaves_full); INIT_LIST_HEAD(&barn->sheaves_empty); + barn->sheaf_partial = NULL; barn->nr_full = 0; barn->nr_empty = 0; } @@ -3315,6 +3317,10 @@ static void barn_shrink(struct kmem_cache *s, struct node_barn *barn) barn->nr_full = 0; list_splice_init(&barn->sheaves_empty, &empty_list); barn->nr_empty = 0; + if (barn->sheaf_partial) { + list_add(&barn->sheaf_partial->barn_list, &full_list); + barn->sheaf_partial = NULL; + } spin_unlock_irqrestore(&barn->lock, flags); @@ -5073,12 +5079,87 @@ void *kmem_cache_alloc_node_noprof(struct kmem_cache *s, gfp_t gfpflags, int nod } EXPORT_SYMBOL(kmem_cache_alloc_node_noprof); +/* + * Refill @sheaf from the barn: from its partial sheaf first, then from its full + * sheaves. A sheaf that objects were copied from stays in the barn as the + * partial sheaf if it still holds objects, or goes on the empty list if it is + * empty. + * + * Returns true if the sheaf is now full, at s->sheaf_capacity. + * Returns false if the sheaf is still not full. + */ +static bool refill_sheaf_from_barn(struct kmem_cache *s, + struct slab_sheaf *sheaf) +{ + struct node_barn *barn = get_barn(s); + struct slab_sheaf *src; + unsigned int to_move; + unsigned long flags; + + if (!barn) + return false; + + if (!data_race(barn->nr_full) && !data_race(barn->sheaf_partial)) + return false; + + spin_lock_irqsave(&barn->lock, flags); + + /* + * The partial sheaf can hold fewer objects than @sheaf needs to + * reach capacity, and a sheaf on the full list is not necessarily + * full (see the comment in rcu_free_sheaf()), so keep taking from + * the barn until @sheaf is full or nothing is left. + */ + while (sheaf->size < s->sheaf_capacity) { + src = barn->sheaf_partial; + barn->sheaf_partial = NULL; + if (!src) { + if (!barn->nr_full) + break; + src = list_first_entry(&barn->sheaves_full, + struct slab_sheaf, barn_list); + list_del(&src->barn_list); + barn->nr_full--; + } + + to_move = min(s->sheaf_capacity - sheaf->size, src->size); + src->size -= to_move; + memcpy(&sheaf->objects[sheaf->size], &src->objects[src->size], + to_move * sizeof(void *)); + sheaf->size += to_move; + + if (src->size) { + barn->sheaf_partial = src; + } else { + /* + * No empty-limit check: the sheaf put on the empty list + * was already in the barn, so the barn holds no more + * sheaves than before. barn_replace_empty_sheaf() skips + * the check for the same reason. + */ + list_add(&src->barn_list, &barn->sheaves_empty); + barn->nr_empty++; + } + } + + spin_unlock_irqrestore(&barn->lock, flags); + + if (sheaf->size < s->sheaf_capacity) + return false; + + stat(s, BARN_GET); + return true; +} + static int __prefill_sheaf_pfmemalloc(struct kmem_cache *s, struct slab_sheaf *sheaf, gfp_t gfp) { gfp_t gfp_nomemalloc; int ret; + if (refill_sheaf_from_barn(s, sheaf)) + return 0; + gfp_nomemalloc = gfp | __GFP_NOMEMALLOC; if (gfp_pfmemalloc_allowed(gfp)) gfp_nomemalloc |= __GFP_NOWARN; diff --git a/net/9p/protocol.c b/net/9p/protocol.c index 67b0586d807f..d4335884e0c0 100644 --- a/net/9p/protocol.c +++ b/net/9p/protocol.c @@ -770,7 +770,7 @@ int p9dirent_read(struct p9_client *clnt, char *buf, int len, { struct p9_fcall fake_pdu; int ret; - char *nameptr; + char *nameptr = NULL; fake_pdu.size = len; fake_pdu.capacity = len; @@ -785,15 +785,7 @@ int p9dirent_read(struct p9_client *clnt, char *buf, int len, return ret; } - ret = strscpy(dirent->d_name, nameptr, sizeof(dirent->d_name)); - if (ret < 0) { - p9_debug(P9_DEBUG_ERROR, - "On the wire dirent name too long: %s\n", - nameptr); - kfree(nameptr); - return ret; - } - kfree(nameptr); + dirent->d_name = nameptr; return fake_pdu.offset; } diff --git a/net/9p/trans_fd.c b/net/9p/trans_fd.c index eb685b52aeb2..dce963332a04 100644 --- a/net/9p/trans_fd.c +++ b/net/9p/trans_fd.c @@ -887,8 +887,8 @@ p9_fd_create_tcp(struct p9_client *client, struct fs_context *fc) return -EINVAL; sprintf(port_str, "%u", opts.port); - err = inet_pton_with_scope(current->nsproxy->net_ns, AF_UNSPEC, addr, - port_str, &stor); + err = inet_pton_with_scope(fc->net_ns, AF_UNSPEC, addr, port_str, + &stor); if (err < 0) return err; @@ -896,8 +896,8 @@ p9_fd_create_tcp(struct p9_client *client, struct fs_context *fc) client->trans_opts.tcp.port = opts.port; client->trans_opts.tcp.privport = opts.privport; - err = __sock_create(current->nsproxy->net_ns, stor.ss_family, - SOCK_STREAM, IPPROTO_TCP, &csocket, 1); + err = __sock_create(fc->net_ns, stor.ss_family, SOCK_STREAM, + IPPROTO_TCP, &csocket, 1); if (err) { pr_err("%s (%d): problem creating socket\n", __func__, task_pid_nr(current)); @@ -946,8 +946,7 @@ p9_fd_create_unix(struct p9_client *client, struct fs_context *fc) __func__, task_pid_nr(current), addr); return -ENAMETOOLONG; } - err = __sock_create(current->nsproxy->net_ns, PF_UNIX, - SOCK_STREAM, 0, &csocket, 1); + err = __sock_create(fc->net_ns, PF_UNIX, SOCK_STREAM, 0, &csocket, 1); if (err < 0) { pr_err("%s (%d): problem creating socket\n", __func__, task_pid_nr(current)); diff --git a/net/9p/trans_rdma.c b/net/9p/trans_rdma.c index b4274f10fa44..f4450e779a79 100644 --- a/net/9p/trans_rdma.c +++ b/net/9p/trans_rdma.c @@ -556,7 +556,7 @@ rdma_create_trans(struct p9_client *client, struct fs_context *fc) return -ENOMEM; /* Create the RDMA CM ID */ - rdma->cm_id = rdma_create_id(&init_net, p9_cm_event_handler, client, + rdma->cm_id = rdma_create_id(fc->net_ns, p9_cm_event_handler, client, RDMA_PS_TCP, IB_QPT_RC); if (IS_ERR(rdma->cm_id)) goto error; diff --git a/net/9p/trans_usbg.c b/net/9p/trans_usbg.c index 7d600e1288a3..45b0ea594211 100644 --- a/net/9p/trans_usbg.c +++ b/net/9p/trans_usbg.c @@ -460,6 +460,11 @@ static void usb9pfs_clear_tx(struct f_usb9pfs *usb9pfs) if (!req || !client) return; + usb9pfs->in_req->context = NULL; + + if (!usb9pfs->client) + return; + if (!req->t_err) req->t_err = -ECONNRESET; @@ -483,6 +488,7 @@ static void p9_usbg_close(struct p9_client *client) client->status = Disconnected; usb9pfs_clear_tx(usb9pfs); + usb9pfs->client = NULL; opts = container_of(usb9pfs->function.fi, struct f_usb9pfs_opts, func_inst); @@ -754,8 +760,6 @@ static void usb9pfs_free_func(struct usb_function *f) struct f_usb9pfs *usb9pfs = func_to_usb9pfs(f); struct f_usb9pfs_opts *opts; - kfree(usb9pfs); - opts = container_of(f->fi, struct f_usb9pfs_opts, func_inst); mutex_lock(&opts->lock); @@ -763,6 +767,8 @@ static void usb9pfs_free_func(struct usb_function *f) mutex_unlock(&opts->lock); usb_free_all_descriptors(f); + + kfree(usb9pfs); } static int usb9pfs_set_alt(struct usb_function *f, diff --git a/net/batman-adv/bat_iv_ogm.c b/net/batman-adv/bat_iv_ogm.c index 1c2ab79adabc..084970404d3e 100644 --- a/net/batman-adv/bat_iv_ogm.c +++ b/net/batman-adv/bat_iv_ogm.c @@ -1410,7 +1410,7 @@ batadv_iv_ogm_update_seqnos(const struct ethhdr *ethhdr, return BATADV_NO_DUP; orig_ifinfo = batadv_orig_ifinfo_new(orig_node, if_outgoing); - if (WARN_ON(!orig_ifinfo)) { + if (!orig_ifinfo) { batadv_orig_node_put(orig_node); return 0; } diff --git a/net/bluetooth/hci_conn.c b/net/bluetooth/hci_conn.c index cf44452e0766..eebd73988bf6 100644 --- a/net/bluetooth/hci_conn.c +++ b/net/bluetooth/hci_conn.c @@ -138,10 +138,10 @@ static void hci_conn_cleanup(struct hci_conn *conn) { struct hci_dev *hdev = conn->hdev; - if (test_bit(HCI_CONN_PARAM_REMOVAL_PEND, &conn->flags)) + if (test_bit(HCI_CONN_PARAM_REMOVAL_PEND, conn->flags)) hci_conn_params_del(conn->hdev, &conn->dst, conn->dst_type); - if (test_and_clear_bit(HCI_CONN_FLUSH_KEY, &conn->flags)) + if (test_and_clear_bit(HCI_CONN_FLUSH_KEY, conn->flags)) hci_remove_link_key(hdev, &conn->dst); hci_chan_list_flush(conn); @@ -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; @@ -685,7 +691,7 @@ static void hci_conn_idle(struct work_struct *work) hci_send_cmd(hdev, HCI_OP_SNIFF_SUBRATE, sizeof(cp), &cp); } - if (!test_and_set_bit(HCI_CONN_MODE_CHANGE_PEND, &conn->flags)) { + if (!test_and_set_bit(HCI_CONN_MODE_CHANGE_PEND, conn->flags)) { struct hci_cp_sniff_mode cp; cp.handle = cpu_to_le16(conn->handle); cp.max_interval = cpu_to_le16(hdev->sniff_max_interval); @@ -814,7 +820,7 @@ static int hci_le_terminate_big(struct hci_dev *hdev, struct hci_conn *conn) d->big = conn->iso_qos.bcast.big; d->bis = conn->iso_qos.bcast.bis; - d->big_term = test_and_clear_bit(HCI_CONN_BIG_CREATED, &conn->flags); + d->big_term = test_and_clear_bit(HCI_CONN_BIG_CREATED, conn->flags); ret = hci_cmd_sync_queue(hdev, terminate_big_sync, d, terminate_big_destroy); @@ -867,7 +873,7 @@ static int hci_le_big_terminate(struct hci_dev *hdev, struct hci_conn *conn) d->sync_handle = conn->sync_handle; if (conn->type == PA_LINK && - test_and_clear_bit(HCI_CONN_PA_SYNC, &conn->flags)) { + test_and_clear_bit(HCI_CONN_PA_SYNC, conn->flags)) { hci_conn_hash_list_flag(hdev, find_bis, PA_LINK, HCI_CONN_PA_SYNC, d); @@ -877,7 +883,7 @@ static int hci_le_big_terminate(struct hci_dev *hdev, struct hci_conn *conn) d->count = 0; } - if (test_and_clear_bit(HCI_CONN_BIG_SYNC, &conn->flags)) { + if (test_and_clear_bit(HCI_CONN_BIG_SYNC, conn->flags)) { hci_conn_hash_list_flag(hdev, find_bis, BIS_LINK, HCI_CONN_BIG_SYNC, d); @@ -912,7 +918,7 @@ static void bis_cleanup(struct hci_conn *conn) bt_dev_dbg(hdev, "conn %p", conn); if (conn->role == HCI_ROLE_MASTER) { - if (!test_and_clear_bit(HCI_CONN_PER_ADV, &conn->flags)) + if (!test_and_clear_bit(HCI_CONN_PER_ADV, conn->flags)) return; /* Check if ISO connection is a BIS and terminate advertising @@ -1087,7 +1093,7 @@ static struct hci_conn *__hci_conn_add(struct hci_dev *hdev, int type, conn->sync_handle = HCI_SYNC_HANDLE_INVALID; conn->sid = HCI_SID_INVALID; - set_bit(HCI_CONN_POWER_SAVE, &conn->flags); + set_bit(HCI_CONN_POWER_SAVE, conn->flags); conn->disc_timeout = HCI_DISCONN_TIMEOUT; /* Set Default Authenticated payload timeout to 30s */ @@ -1217,8 +1223,8 @@ static void hci_conn_cleanup_child(struct hci_conn *conn, u8 reason) case BIS_LINK: case PA_LINK: if ((conn->state != BT_CONNECTED && - !test_bit(HCI_CONN_CREATE_CIS, &conn->flags)) || - test_bit(HCI_CONN_BIG_CREATED, &conn->flags)) + !test_bit(HCI_CONN_CREATE_CIS, conn->flags)) || + test_bit(HCI_CONN_BIG_CREATED, conn->flags)) hci_conn_failed(conn, reason); break; } @@ -1233,6 +1239,29 @@ static void hci_conn_unlink(struct hci_conn *conn) if (!conn->parent) { struct hci_link *link, *t; + conn->sec_level = BT_SECURITY_SDP; + clear_bit(HCI_CONN_ENCRYPT, conn->flags); + clear_bit(HCI_CONN_AES_CCM, conn->flags); + /* mgmt_security_level_changed() reports the reset only if + * this connection was actually reported to userspace as + * connected (it checks HCI_CONN_MGMT_CONNECTED itself), so it + * must be called before the flag is cleared below. + * Callers that already know whether the connection was + * mgmt-connected (e.g. disconnect event handlers) only peek + * at the flag, so it is still set here; this is the place + * actually clearing it. + * + * Skip the report if hdev is down: this means + * hci_dev_close_sync()/hci_conn_hash_flush() is in progress + * and no MGMT_EV_DEVICE_DISCONNECTED was ever sent for this + * connection, so sending a security level reset here would + * be a spurious, order-less event; the adapter-wide powered + * off notification is enough for userspace to reset state. + */ + if (test_bit(HCI_UP, &hdev->flags)) + mgmt_security_level_changed(conn); + clear_bit(HCI_CONN_MGMT_CONNECTED, conn->flags); + list_for_each_entry_safe(link, t, &conn->link_list, list) { struct hci_conn *child = link->conn; @@ -1435,8 +1464,8 @@ void hci_conn_failed(struct hci_conn *conn, u8 status) /* In case of BIG/PA sync failed, clear conn flags so that * the conns will be correctly cleaned up by ISO layer */ - test_and_clear_bit(HCI_CONN_BIG_SYNC_FAILED, &conn->flags); - test_and_clear_bit(HCI_CONN_PA_SYNC_FAILED, &conn->flags); + test_and_clear_bit(HCI_CONN_BIG_SYNC_FAILED, conn->flags); + test_and_clear_bit(HCI_CONN_PA_SYNC_FAILED, conn->flags); conn->state = BT_CLOSED; hci_connect_cfm(conn, status); @@ -1501,9 +1530,8 @@ struct hci_conn *hci_connect_le(struct hci_dev *hdev, bdaddr_t *dst, * to connect. */ conn = hci_conn_hash_lookup_le(hdev, dst, dst_type); - if (conn && !test_bit(HCI_CONN_SCANNING, &conn->flags)) { + if (conn && !test_bit(HCI_CONN_SCANNING, conn->flags)) return ERR_PTR(-EBUSY); - } /* Check if the destination address has been resolved by the controller * since if it did then the identity address shall be used. @@ -1543,6 +1571,11 @@ struct hci_conn *hci_connect_le(struct hci_dev *hdev, bdaddr_t *dst, conn->pending_sec_level = sec_level; } + /* Do not report the security level here: conn->dst may still hold + * the peer's RPA instead of its identity address, and the connection + * is not established yet. le_conn_complete_evt() reports it once the + * connection completes and the identity address has been resolved. + */ conn->sec_level = BT_SECURITY_LOW; conn->conn_timeout = conn_timeout; conn->le_adv_phy = phy; @@ -1586,8 +1619,9 @@ static int hci_explicit_conn_params_set(struct hci_dev *hdev, if (!params) return -ENOMEM; - /* If we created new params, mark them to be deleted in - * hci_connect_le_scan_cleanup. It's different case than + /* If we created new params, mark them to be deleted once the + * explicit connect is done, see le_conn_complete_evt() and + * hci_connect_le_scan_cleanup(). It's different case than * existing disabled params, those will stay after cleanup. */ params->auto_connect = HCI_AUTO_CONN_EXPLICIT; @@ -1769,7 +1803,7 @@ struct hci_conn *hci_connect_le_scan(struct hci_dev *hdev, bdaddr_t *dst, } conn->state = BT_CONNECT; - set_bit(HCI_CONN_SCANNING, &conn->flags); + set_bit(HCI_CONN_SCANNING, conn->flags); conn->sec_level = BT_SECURITY_LOW; conn->pending_sec_level = sec_level; conn->conn_timeout = conn_timeout; @@ -1895,12 +1929,12 @@ struct hci_conn *hci_connect_sco(struct hci_dev *hdev, int type, bdaddr_t *dst, if (acl->state == BT_CONNECTED && (sco->state == BT_OPEN || sco->state == BT_CLOSED)) { - set_bit(HCI_CONN_POWER_SAVE, &acl->flags); + set_bit(HCI_CONN_POWER_SAVE, acl->flags); hci_conn_enter_active_mode(acl, BT_POWER_FORCE_ACTIVE_ON); - if (test_bit(HCI_CONN_MODE_CHANGE_PEND, &acl->flags)) { + if (test_bit(HCI_CONN_MODE_CHANGE_PEND, acl->flags)) { /* defer SCO setup until mode change completed */ - set_bit(HCI_CONN_SCO_SETUP_PEND, &acl->flags); + set_bit(HCI_CONN_SCO_SETUP_PEND, acl->flags); return sco; } @@ -2192,7 +2226,7 @@ int hci_le_create_cis_pending(struct hci_dev *hdev) rcu_read_lock(); list_for_each_entry_rcu(conn, &hdev->conn_hash.list, list) { - if (test_bit(HCI_CONN_CREATE_CIS, &conn->flags)) { + if (test_bit(HCI_CONN_CREATE_CIS, conn->flags)) { rcu_read_unlock(); return -EBUSY; } @@ -2420,7 +2454,7 @@ static void bis_mark_per_adv(struct hci_conn *conn, void *data) d->bis != conn->iso_qos.bcast.bis) return; - set_bit(HCI_CONN_PER_ADV, &conn->flags); + set_bit(HCI_CONN_PER_ADV, conn->flags); } struct hci_conn *hci_connect_bis(struct hci_dev *hdev, bdaddr_t *dst, @@ -2540,7 +2574,7 @@ int hci_conn_check_link_mode(struct hci_conn *conn) */ if (hci_dev_test_flag(conn->hdev, HCI_SC_ONLY)) { if (!hci_conn_sc_enabled(conn) || - !test_bit(HCI_CONN_AES_CCM, &conn->flags) || + !test_bit(HCI_CONN_AES_CCM, conn->flags) || conn->key_type != HCI_LK_AUTH_COMBINATION_P256) return 0; } @@ -2556,14 +2590,14 @@ int hci_conn_check_link_mode(struct hci_conn *conn) * not shortened) */ if (conn->sec_level == BT_SECURITY_FIPS && - !test_bit(HCI_CONN_AES_CCM, &conn->flags)) { + !test_bit(HCI_CONN_AES_CCM, conn->flags)) { bt_dev_err(conn->hdev, "Invalid security: Missing AES-CCM usage"); return 0; } if (hci_conn_ssp_enabled(conn) && - !test_bit(HCI_CONN_ENCRYPT, &conn->flags)) + !test_bit(HCI_CONN_ENCRYPT, conn->flags)) return 0; return 1; @@ -2579,7 +2613,7 @@ static int hci_conn_auth(struct hci_conn *conn, __u8 sec_level, __u8 auth_type) if (sec_level > conn->sec_level) conn->pending_sec_level = sec_level; - else if (test_bit(HCI_CONN_AUTH, &conn->flags)) + else if (test_bit(HCI_CONN_AUTH, conn->flags)) return 1; /* Make sure we preserve an existing MITM requirement*/ @@ -2587,7 +2621,7 @@ static int hci_conn_auth(struct hci_conn *conn, __u8 sec_level, __u8 auth_type) conn->auth_type = auth_type; - if (!test_and_set_bit(HCI_CONN_AUTH_PEND, &conn->flags)) { + if (!test_and_set_bit(HCI_CONN_AUTH_PEND, conn->flags)) { struct hci_cp_auth_requested cp; cp.handle = cpu_to_le16(conn->handle); @@ -2597,8 +2631,8 @@ static int hci_conn_auth(struct hci_conn *conn, __u8 sec_level, __u8 auth_type) /* Set the ENCRYPT_PEND to trigger encryption after * authentication. */ - if (!test_bit(HCI_CONN_ENCRYPT, &conn->flags)) - set_bit(HCI_CONN_ENCRYPT_PEND, &conn->flags); + if (!test_bit(HCI_CONN_ENCRYPT, conn->flags)) + set_bit(HCI_CONN_ENCRYPT_PEND, conn->flags); } return 0; @@ -2609,7 +2643,7 @@ static void hci_conn_encrypt(struct hci_conn *conn) { BT_DBG("hcon %p", conn); - if (!test_and_set_bit(HCI_CONN_ENCRYPT_PEND, &conn->flags)) { + if (!test_and_set_bit(HCI_CONN_ENCRYPT_PEND, conn->flags)) { struct hci_cp_set_conn_encrypt cp; cp.handle = cpu_to_le16(conn->handle); cp.encrypt = 0x01; @@ -2637,7 +2671,7 @@ int hci_conn_security(struct hci_conn *conn, __u8 sec_level, __u8 auth_type, return 1; /* For other security levels we need the link key. */ - if (!test_bit(HCI_CONN_AUTH, &conn->flags)) + if (!test_bit(HCI_CONN_AUTH, conn->flags)) goto auth; switch (conn->key_type) { @@ -2677,17 +2711,17 @@ int hci_conn_security(struct hci_conn *conn, __u8 sec_level, __u8 auth_type, } auth: - if (test_bit(HCI_CONN_ENCRYPT_PEND, &conn->flags)) + if (test_bit(HCI_CONN_ENCRYPT_PEND, conn->flags)) return 0; if (initiator) - set_bit(HCI_CONN_AUTH_INITIATOR, &conn->flags); + set_bit(HCI_CONN_AUTH_INITIATOR, conn->flags); if (!hci_conn_auth(conn, sec_level, auth_type)) return 0; encrypt: - if (test_bit(HCI_CONN_ENCRYPT, &conn->flags)) { + if (test_bit(HCI_CONN_ENCRYPT, conn->flags)) { /* Ensure that the encryption key size has been read, * otherwise stall the upper layer responses. */ @@ -2730,7 +2764,7 @@ int hci_conn_switch_role(struct hci_conn *conn, __u8 role) if (role == conn->role) return 1; - if (!test_and_set_bit(HCI_CONN_RSWITCH_PEND, &conn->flags)) { + if (!test_and_set_bit(HCI_CONN_RSWITCH_PEND, conn->flags)) { struct hci_cp_switch_role cp; bacpy(&cp.bdaddr, &conn->dst); cp.role = role; @@ -2751,10 +2785,10 @@ void hci_conn_enter_active_mode(struct hci_conn *conn, __u8 force_active) if (conn->mode != HCI_CM_SNIFF) goto timer; - if (!test_bit(HCI_CONN_POWER_SAVE, &conn->flags) && !force_active) + if (!test_bit(HCI_CONN_POWER_SAVE, conn->flags) && !force_active) goto timer; - if (!test_and_set_bit(HCI_CONN_MODE_CHANGE_PEND, &conn->flags)) { + if (!test_and_set_bit(HCI_CONN_MODE_CHANGE_PEND, conn->flags)) { struct hci_cp_exit_sniff_mode cp; cp.handle = cpu_to_le16(conn->handle); hci_send_cmd(hdev, HCI_OP_EXIT_SNIFF_MODE, sizeof(cp), &cp); @@ -2794,16 +2828,16 @@ static u32 get_link_mode(struct hci_conn *conn) if (conn->role == HCI_ROLE_MASTER) link_mode |= HCI_LM_MASTER; - if (test_bit(HCI_CONN_ENCRYPT, &conn->flags)) + if (test_bit(HCI_CONN_ENCRYPT, conn->flags)) link_mode |= HCI_LM_ENCRYPT; - if (test_bit(HCI_CONN_AUTH, &conn->flags)) + if (test_bit(HCI_CONN_AUTH, conn->flags)) link_mode |= HCI_LM_AUTH; - if (test_bit(HCI_CONN_SECURE, &conn->flags)) + if (test_bit(HCI_CONN_SECURE, conn->flags)) link_mode |= HCI_LM_SECURE; - if (test_bit(HCI_CONN_FIPS, &conn->flags)) + if (test_bit(HCI_CONN_FIPS, conn->flags)) link_mode |= HCI_LM_FIPS; return link_mode; @@ -2917,7 +2951,7 @@ struct hci_chan *hci_chan_create(struct hci_conn *conn) BT_DBG("%s hcon %p", hdev->name, conn); - if (test_bit(HCI_CONN_DROP, &conn->flags)) { + if (test_bit(HCI_CONN_DROP, conn->flags)) { BT_DBG("Refusing to create new hci_chan"); return NULL; } @@ -2947,7 +2981,7 @@ void hci_chan_del(struct hci_chan *chan) synchronize_rcu(); /* Prevent new hci_chan's to be created for this hci_conn */ - set_bit(HCI_CONN_DROP, &conn->flags); + set_bit(HCI_CONN_DROP, conn->flags); hci_conn_put(conn); diff --git a/net/bluetooth/hci_core.c b/net/bluetooth/hci_core.c index becac4a223df..8784c28297ac 100644 --- a/net/bluetooth/hci_core.c +++ b/net/bluetooth/hci_core.c @@ -1075,17 +1075,16 @@ struct link_key *hci_find_link_key(struct hci_dev *hdev, bdaddr_t *bdaddr) rcu_read_lock(); list_for_each_entry_rcu(k, &hdev->link_keys, list) { if (bacmp(bdaddr, &k->bdaddr) == 0) { - rcu_read_unlock(); - if (hci_is_blocked_key(hdev, HCI_BLOCKED_KEY_TYPE_LINKKEY, k->val)) { bt_dev_warn_ratelimited(hdev, "Link key blocked for %pMR", &k->bdaddr); - return NULL; + k = NULL; } + rcu_read_unlock(); return k; } } @@ -1252,7 +1251,6 @@ struct link_key *hci_add_link_key(struct hci_dev *hdev, struct hci_conn *conn, key = kzalloc_obj(*key); if (!key) return NULL; - list_add_rcu(&key->list, &hdev->link_keys); } BT_DBG("%s key for %pMR type %u", hdev->name, bdaddr, type); @@ -1276,6 +1274,9 @@ struct link_key *hci_add_link_key(struct hci_dev *hdev, struct hci_conn *conn, else key->type = type; + if (!old_key) + list_add_rcu(&key->list, &hdev->link_keys); + if (persistent) *persistent = hci_persistent_key(hdev, conn, type, old_key_type); @@ -1297,7 +1298,6 @@ struct smp_ltk *hci_add_ltk(struct hci_dev *hdev, bdaddr_t *bdaddr, key = kzalloc_obj(*key); if (!key) return NULL; - list_add_rcu(&key->list, &hdev->long_term_keys); } bacpy(&key->bdaddr, bdaddr); @@ -1309,15 +1309,19 @@ struct smp_ltk *hci_add_ltk(struct hci_dev *hdev, bdaddr_t *bdaddr, key->enc_size = enc_size; key->type = type; + if (!old_key) + list_add_rcu(&key->list, &hdev->long_term_keys); + return key; } struct smp_irk *hci_add_irk(struct hci_dev *hdev, bdaddr_t *bdaddr, u8 addr_type, u8 val[16], bdaddr_t *rpa) { - struct smp_irk *irk; + struct smp_irk *irk, *old_irk; - irk = hci_find_irk_by_addr(hdev, bdaddr, addr_type); + old_irk = hci_find_irk_by_addr(hdev, bdaddr, addr_type); + irk = old_irk; if (!irk) { irk = kzalloc_obj(*irk); if (!irk) @@ -1326,12 +1330,14 @@ struct smp_irk *hci_add_irk(struct hci_dev *hdev, bdaddr_t *bdaddr, bacpy(&irk->bdaddr, bdaddr); irk->addr_type = addr_type; - list_add_rcu(&irk->list, &hdev->identity_resolving_keys); } memcpy(irk->val, val, 16); bacpy(&irk->rpa, rpa); + if (!old_irk) + list_add_rcu(&irk->list, &hdev->identity_resolving_keys); + return irk; } @@ -1694,6 +1700,9 @@ struct adv_info *hci_add_adv_instance(struct hci_dev *hdev, u8 instance, if (!adv) return ERR_PTR(-ENOMEM); + INIT_DELAYED_WORK(&adv->rpa_expired_cb, + adv_instance_rpa_expired); + adv->pending = true; adv->instance = instance; @@ -1730,8 +1739,6 @@ struct adv_info *hci_add_adv_instance(struct hci_dev *hdev, u8 instance, else adv->duration = duration; - INIT_DELAYED_WORK(&adv->rpa_expired_cb, adv_instance_rpa_expired); - BT_DBG("%s for %dMR", hdev->name, instance); return adv; @@ -2897,8 +2904,14 @@ int hci_recv_frame(struct hci_dev *hdev, struct sk_buff *skb) { u8 dev_pkt_type; + /* Pairs with synchronize_rcu() in hci_dev_close_sync(), so rx_work is + * not queued once the workqueue is being drained. + */ + rcu_read_lock(); + if (!hdev || (!test_bit(HCI_UP, &hdev->flags) && !test_bit(HCI_INIT, &hdev->flags))) { + rcu_read_unlock(); kfree_skb(skb); return -ENXIO; } @@ -2932,6 +2945,7 @@ int hci_recv_frame(struct hci_dev *hdev, struct sk_buff *skb) case HCI_DRV_PKT: break; default: + rcu_read_unlock(); kfree_skb(skb); return -EINVAL; } @@ -2945,6 +2959,8 @@ int hci_recv_frame(struct hci_dev *hdev, struct sk_buff *skb) skb_queue_tail(&hdev->rx_q, skb); queue_work(hdev->workqueue, &hdev->rx_work); + rcu_read_unlock(); + return 0; } EXPORT_SYMBOL(hci_recv_frame); @@ -3122,7 +3138,8 @@ int __hci_cmd_send(struct hci_dev *hdev, u16 opcode, u32 plen, EXPORT_SYMBOL(__hci_cmd_send); /* Get data from the previously sent command */ -static void *hci_cmd_data(struct sk_buff *skb, __u16 opcode) +static void *hci_cmd_data(struct sk_buff *skb, __u16 opcode, + size_t *len) { struct hci_command_hdr *hdr; @@ -3134,23 +3151,32 @@ static void *hci_cmd_data(struct sk_buff *skb, __u16 opcode) if (hdr->opcode != cpu_to_le16(opcode)) return NULL; + if (len) + *len = skb->len - HCI_COMMAND_HDR_SIZE; + return skb->data + HCI_COMMAND_HDR_SIZE; } /* Get data from the previously sent command */ -void *hci_sent_cmd_data(struct hci_dev *hdev, __u16 opcode) +void *hci_sent_cmd_data_len(struct hci_dev *hdev, __u16 opcode, size_t *len) { void *data; /* Check if opcode matches last sent command */ - data = hci_cmd_data(hdev->sent_cmd, opcode); + data = hci_cmd_data(hdev->sent_cmd, opcode, len); if (!data) /* Check if opcode matches last request */ - data = hci_cmd_data(hdev->req_skb, opcode); + data = hci_cmd_data(hdev->req_skb, opcode, len); return data; } +/* Get data from the previously sent command */ +void *hci_sent_cmd_data(struct hci_dev *hdev, __u16 opcode) +{ + return hci_sent_cmd_data_len(hdev, opcode, NULL); +} + /* Get data from last received event */ void *hci_recv_event_data(struct hci_dev *hdev, __u8 event) { diff --git a/net/bluetooth/hci_event.c b/net/bluetooth/hci_event.c index 3288f92fe41b..fd5c185bb10b 100644 --- a/net/bluetooth/hci_event.c +++ b/net/bluetooth/hci_event.c @@ -404,10 +404,7 @@ static u8 hci_cc_write_auth_enable(struct hci_dev *hdev, void *data, if (!rp->status) { __u8 param = *((__u8 *) sent); - if (param == AUTH_ENABLED) - set_bit(HCI_AUTH, &hdev->flags); - else - clear_bit(HCI_AUTH, &hdev->flags); + assign_bit(HCI_AUTH, &hdev->flags, param == AUTH_ENABLED); } if (hci_dev_test_flag(hdev, HCI_MGMT)) @@ -436,10 +433,7 @@ static u8 hci_cc_write_encrypt_mode(struct hci_dev *hdev, void *data, param = *((__u8 *) sent); - if (param) - set_bit(HCI_ENCRYPT, &hdev->flags); - else - clear_bit(HCI_ENCRYPT, &hdev->flags); + assign_bit(HCI_ENCRYPT, &hdev->flags, param); return rp->status; } @@ -466,15 +460,9 @@ static u8 hci_cc_write_scan_enable(struct hci_dev *hdev, void *data, goto done; } - if (param & SCAN_INQUIRY) - set_bit(HCI_ISCAN, &hdev->flags); - else - clear_bit(HCI_ISCAN, &hdev->flags); + assign_bit(HCI_ISCAN, &hdev->flags, param & SCAN_INQUIRY); - if (param & SCAN_PAGE) - set_bit(HCI_PSCAN, &hdev->flags); - else - clear_bit(HCI_PSCAN, &hdev->flags); + assign_bit(HCI_PSCAN, &hdev->flags, param & SCAN_PAGE); done: hci_dev_unlock(hdev); @@ -736,6 +724,8 @@ static u8 hci_cc_read_enc_key_size(struct hci_dev *hdev, void *data, goto done; } + clear_bit(HCI_CONN_ENC_KEY_SIZE_PEND, conn->flags); + /* While unexpected, the read_enc_key_size command may fail. The most * secure approach is to then assume the key size is 0 to force a * disconnection. @@ -744,6 +734,14 @@ static u8 hci_cc_read_enc_key_size(struct hci_dev *hdev, void *data, bt_dev_err(hdev, "failed to read key size for handle %u", handle); conn->enc_key_size = 0; + clear_bit(HCI_CONN_ENCRYPT, conn->flags); + clear_bit(HCI_CONN_AES_CCM, conn->flags); + /* Downgrade to reflect the connection no longer being + * encrypted, instead of advertising a stale elevated + * security level alongside MGMT_CONN_SEC_ENCRYPT_NONE. + */ + if (conn->sec_level > BT_SECURITY_LOW) + conn->sec_level = BT_SECURITY_LOW; } else { u8 *key_enc_size = hci_conn_key_enc_size(conn); @@ -765,8 +763,27 @@ static u8 hci_cc_read_enc_key_size(struct hci_dev *hdev, void *data, * state at a later time. */ status = HCI_ERROR_AUTH_FAILURE; - clear_bit(HCI_CONN_ENCRYPT, &conn->flags); - clear_bit(HCI_CONN_AES_CCM, &conn->flags); + clear_bit(HCI_CONN_ENCRYPT, conn->flags); + clear_bit(HCI_CONN_AES_CCM, conn->flags); + /* Downgrade to reflect the connection no longer being + * encrypted, instead of advertising a stale elevated + * security level alongside MGMT_CONN_SEC_ENCRYPT_NONE. + */ + if (conn->sec_level > BT_SECURITY_LOW) + conn->sec_level = BT_SECURITY_LOW; + } else { + /* Pre-apply hci_encrypt_cfm()'s own upgrade rules + * here unconditionally on success, so its internal + * change check below always finds nothing new: this + * function remains the sole place deciding whether + * and when to report the change, regardless of + * whether the caller already touched conn->sec_level + * (e.g. hci_encrypt_change_evt()) or not. + */ + if (conn->sec_level == BT_SECURITY_SDP) + conn->sec_level = BT_SECURITY_LOW; + if (conn->pending_sec_level > conn->sec_level) + conn->sec_level = conn->pending_sec_level; } /* Update the key encryption size with the connection one */ @@ -776,6 +793,13 @@ static u8 hci_cc_read_enc_key_size(struct hci_dev *hdev, void *data, hci_encrypt_cfm(conn, status); + /* mgmt_security_level_changed() only reports the change for + * connections already announced to userspace (it checks + * HCI_CONN_MGMT_CONNECTED itself); otherwise it is a no-op here and + * reporting is deferred to mgmt_device_connected(). + */ + mgmt_security_level_changed(conn); + done: hci_dev_unlock(hdev); @@ -792,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; } @@ -1795,6 +1817,8 @@ static void store_pending_adv_report(struct hci_dev *hdev, bdaddr_t *bdaddr, static void le_set_scan_enable_complete(struct hci_dev *hdev, u8 enable) { + bool timeout_pending; + hci_dev_lock(hdev); switch (enable) { @@ -1824,10 +1848,18 @@ static void le_set_scan_enable_complete(struct hci_dev *hdev, u8 enable) /* Cancel this timer so that we don't try to disable scanning * when it's already disabled. */ - cancel_delayed_work(&hdev->le_scan_disable); + timeout_pending = cancel_delayed_work(&hdev->le_scan_disable); hci_dev_clear_flag(hdev, HCI_LE_SCAN); + /* The scan of a discovery was disabled before its timeout, + * for example by a Stop Discovery that timed out and still + * completed, so nothing else would end the discovery. + */ + if (timeout_pending && + hdev->discovery.state == DISCOVERY_FINDING) + hci_discovery_set_state(hdev, DISCOVERY_STOPPED); + if (hdev->discovery.type == DISCOV_TYPE_INTERLEAVED && hci_test_quirk(hdev, HCI_QUIRK_SIMULTANEOUS_DISCOVERY) && !test_bit(HCI_INQUIRY, &hdev->flags) && @@ -2573,10 +2605,10 @@ static void hci_cs_remote_name_req(struct hci_dev *hdev, __u8 status) if (!hci_outgoing_auth_needed(hdev, conn)) goto unlock; - if (!test_and_set_bit(HCI_CONN_AUTH_PEND, &conn->flags)) { + if (!test_and_set_bit(HCI_CONN_AUTH_PEND, conn->flags)) { struct hci_cp_auth_requested auth_cp; - set_bit(HCI_CONN_AUTH_INITIATOR, &conn->flags); + set_bit(HCI_CONN_AUTH_INITIATOR, conn->flags); auth_cp.handle = __cpu_to_le16(conn->handle); hci_send_cmd(hdev, HCI_OP_AUTH_REQUESTED, @@ -2716,9 +2748,9 @@ static void hci_cs_sniff_mode(struct hci_dev *hdev, __u8 status) conn = hci_conn_hash_lookup_handle(hdev, __le16_to_cpu(cp->handle)); if (conn) { - clear_bit(HCI_CONN_MODE_CHANGE_PEND, &conn->flags); + clear_bit(HCI_CONN_MODE_CHANGE_PEND, conn->flags); - if (test_and_clear_bit(HCI_CONN_SCO_SETUP_PEND, &conn->flags)) + if (test_and_clear_bit(HCI_CONN_SCO_SETUP_PEND, conn->flags)) hci_sco_setup(conn, status); } @@ -2743,9 +2775,9 @@ static void hci_cs_exit_sniff_mode(struct hci_dev *hdev, __u8 status) conn = hci_conn_hash_lookup_handle(hdev, __le16_to_cpu(cp->handle)); if (conn) { - clear_bit(HCI_CONN_MODE_CHANGE_PEND, &conn->flags); + clear_bit(HCI_CONN_MODE_CHANGE_PEND, conn->flags); - if (test_and_clear_bit(HCI_CONN_SCO_SETUP_PEND, &conn->flags)) + if (test_and_clear_bit(HCI_CONN_SCO_SETUP_PEND, conn->flags)) hci_sco_setup(conn, status); } @@ -2798,10 +2830,14 @@ static void hci_cs_disconnect(struct hci_dev *hdev, u8 status) if (hdev->suspended) conn->state = BT_CLOSED; - mgmt_conn = test_and_clear_bit(HCI_CONN_MGMT_CONNECTED, &conn->flags); + /* Only peek at the flag here: hci_conn_del() (via hci_conn_unlink()) + * still needs it set to know whether to report the security level + * reset, so it is consumed there instead of here. + */ + mgmt_conn = test_bit(HCI_CONN_MGMT_CONNECTED, conn->flags); if (conn->type == ACL_LINK) { - if (test_and_clear_bit(HCI_CONN_FLUSH_KEY, &conn->flags)) + if (test_and_clear_bit(HCI_CONN_FLUSH_KEY, conn->flags)) hci_remove_link_key(hdev, &conn->dst); } @@ -3052,7 +3088,7 @@ static void hci_cs_switch_role(struct hci_dev *hdev, u8 status) conn = hci_conn_hash_lookup_ba(hdev, ACL_LINK, &cp->bdaddr); if (conn) - clear_bit(HCI_CONN_RSWITCH_PEND, &conn->flags); + clear_bit(HCI_CONN_RSWITCH_PEND, conn->flags); hci_dev_unlock(hdev); } @@ -3164,6 +3200,7 @@ static int hci_read_enc_key_size(struct hci_dev *hdev, struct hci_conn *conn) { struct hci_cp_read_enc_key_size cp; u8 *key_enc_size = hci_conn_key_enc_size(conn); + int err; if (!read_key_size_capable(hdev)) { conn->enc_key_size = HCI_LINK_KEY_SIZE; @@ -3185,7 +3222,14 @@ static int hci_read_enc_key_size(struct hci_dev *hdev, struct hci_conn *conn) else conn->enc_key_size = hdev->min_enc_key_size; - return hci_send_cmd(hdev, HCI_OP_READ_ENC_KEY_SIZE, sizeof(cp), &cp); + /* L2CAP holds incoming data back until the key size is known */ + set_bit(HCI_CONN_ENC_KEY_SIZE_PEND, conn->flags); + + err = hci_send_cmd(hdev, HCI_OP_READ_ENC_KEY_SIZE, sizeof(cp), &cp); + if (err) + clear_bit(HCI_CONN_ENC_KEY_SIZE_PEND, conn->flags); + + return err; } static void hci_conn_complete_evt(struct hci_dev *hdev, void *data, @@ -3283,19 +3327,19 @@ static void hci_conn_complete_evt(struct hci_dev *hdev, void *data, hci_conn_add_sysfs(conn); if (test_bit(HCI_AUTH, &hdev->flags)) - set_bit(HCI_CONN_AUTH, &conn->flags); + set_bit(HCI_CONN_AUTH, conn->flags); if (test_bit(HCI_ENCRYPT, &hdev->flags)) - set_bit(HCI_CONN_ENCRYPT, &conn->flags); + set_bit(HCI_CONN_ENCRYPT, conn->flags); /* "Link key request" completed ahead of "connect request" completes */ - if (ev->encr_mode == 1 && !test_bit(HCI_CONN_ENCRYPT, &conn->flags) && + if (ev->encr_mode == 1 && !test_bit(HCI_CONN_ENCRYPT, conn->flags) && ev->link_type == ACL_LINK) { struct link_key *key; key = hci_find_link_key(hdev, &ev->bdaddr); if (key) { - set_bit(HCI_CONN_ENCRYPT, &conn->flags); + set_bit(HCI_CONN_ENCRYPT, conn->flags); hci_read_enc_key_size(hdev, conn); hci_encrypt_cfm(conn, ev->status); } @@ -3419,6 +3463,16 @@ static void hci_conn_request_evt(struct hci_dev *hdev, void *data, bt_dev_err(hdev, "connection err: %ld", PTR_ERR(conn)); goto unlock; } + + /* Unlike outgoing BR/EDR connections, conn->sec_level is not + * set at connection request time for incoming connections, + * so it is still at its zero-initialized value + * (BT_SECURITY_SDP) here. Set it to BT_SECURITY_LOW so + * mgmt_device_connected() later reports the correct initial + * security level instead of a transient, never-really-in-use + * SDP value. + */ + conn->sec_level = BT_SECURITY_LOW; } memcpy(conn->dev_class, ev->dev_class, 3); @@ -3485,9 +3539,13 @@ static void hci_disconn_complete_evt(struct hci_dev *hdev, void *data, conn->state = BT_CLOSED; - mgmt_connected = test_and_clear_bit(HCI_CONN_MGMT_CONNECTED, &conn->flags); + /* Only peek at the flag here: hci_conn_del() (via hci_conn_unlink()) + * still needs it set to know whether to report the security level + * reset, so it is consumed there instead of here. + */ + mgmt_connected = test_bit(HCI_CONN_MGMT_CONNECTED, conn->flags); - if (test_bit(HCI_CONN_AUTH_FAILURE, &conn->flags)) + if (test_bit(HCI_CONN_AUTH_FAILURE, conn->flags)) reason = MGMT_DEV_DISCONN_AUTH_FAILURE; else reason = hci_to_mgmt_reason(ev->reason); @@ -3496,7 +3554,7 @@ static void hci_disconn_complete_evt(struct hci_dev *hdev, void *data, reason, mgmt_connected); if (conn->type == ACL_LINK) { - if (test_and_clear_bit(HCI_CONN_FLUSH_KEY, &conn->flags)) + if (test_and_clear_bit(HCI_CONN_FLUSH_KEY, conn->flags)) hci_remove_link_key(hdev, &conn->dst); hci_update_scan(hdev); @@ -3567,17 +3625,26 @@ static void hci_auth_complete_evt(struct hci_dev *hdev, void *data, goto unlock; if (!ev->status) { - clear_bit(HCI_CONN_AUTH_FAILURE, &conn->flags); - set_bit(HCI_CONN_AUTH, &conn->flags); + clear_bit(HCI_CONN_AUTH_FAILURE, conn->flags); + set_bit(HCI_CONN_AUTH, conn->flags); + /* Authentication alone does not imply encryption: for SSP + * capable devices, encryption is only requested below, and + * for legacy devices it is requested by a separate + * HCI_OP_SET_CONN_ENCRYPT command. Do not report the new + * security level yet, to avoid userspace seeing an elevated + * level alongside no encryption; hci_encrypt_change_evt() + * (possibly via hci_cc_read_enc_key_size() for ACL links) + * reports it once encryption is actually confirmed. + */ conn->sec_level = conn->pending_sec_level; } else { if (ev->status == HCI_ERROR_PIN_OR_KEY_MISSING) - set_bit(HCI_CONN_AUTH_FAILURE, &conn->flags); + set_bit(HCI_CONN_AUTH_FAILURE, conn->flags); mgmt_auth_failed(conn, ev->status); } - clear_bit(HCI_CONN_AUTH_PEND, &conn->flags); + clear_bit(HCI_CONN_AUTH_PEND, conn->flags); if (conn->state == BT_CONFIG) { if (!ev->status && hci_conn_ssp_enabled(conn)) { @@ -3599,7 +3666,7 @@ static void hci_auth_complete_evt(struct hci_dev *hdev, void *data, hci_conn_drop(conn); } - if (test_bit(HCI_CONN_ENCRYPT_PEND, &conn->flags)) { + if (test_bit(HCI_CONN_ENCRYPT_PEND, conn->flags)) { if (!ev->status) { struct hci_cp_set_conn_encrypt cp; cp.handle = ev->handle; @@ -3607,7 +3674,7 @@ static void hci_auth_complete_evt(struct hci_dev *hdev, void *data, hci_send_cmd(hdev, HCI_OP_SET_CONN_ENCRYPT, sizeof(cp), &cp); } else { - clear_bit(HCI_CONN_ENCRYPT_PEND, &conn->flags); + clear_bit(HCI_CONN_ENCRYPT_PEND, conn->flags); hci_encrypt_cfm(conn, ev->status); } } @@ -3644,10 +3711,10 @@ static void hci_remote_name_evt(struct hci_dev *hdev, void *data, if (!hci_outgoing_auth_needed(hdev, conn)) goto unlock; - if (!test_and_set_bit(HCI_CONN_AUTH_PEND, &conn->flags)) { + if (!test_and_set_bit(HCI_CONN_AUTH_PEND, conn->flags)) { struct hci_cp_auth_requested cp; - set_bit(HCI_CONN_AUTH_INITIATOR, &conn->flags); + set_bit(HCI_CONN_AUTH_INITIATOR, conn->flags); cp.handle = __cpu_to_le16(conn->handle); hci_send_cmd(hdev, HCI_OP_AUTH_REQUESTED, sizeof(cp), &cp); @@ -3674,20 +3741,39 @@ static void hci_encrypt_change_evt(struct hci_dev *hdev, void *data, if (!ev->status) { if (ev->encrypt) { /* Encryption implies authentication */ - set_bit(HCI_CONN_AUTH, &conn->flags); - set_bit(HCI_CONN_ENCRYPT, &conn->flags); + set_bit(HCI_CONN_AUTH, conn->flags); + set_bit(HCI_CONN_ENCRYPT, conn->flags); conn->sec_level = conn->pending_sec_level; /* P-256 authentication key implies FIPS */ if (conn->key_type == HCI_LK_AUTH_COMBINATION_P256) - set_bit(HCI_CONN_FIPS, &conn->flags); + set_bit(HCI_CONN_FIPS, conn->flags); if ((conn->type == ACL_LINK && ev->encrypt == 0x02) || conn->type == LE_LINK) - set_bit(HCI_CONN_AES_CCM, &conn->flags); + set_bit(HCI_CONN_AES_CCM, conn->flags); + + /* For ACL links the encryption key size is still + * validated below via hci_read_enc_key_size(). Its + * completion handler, hci_cc_read_enc_key_size(), + * reports the final security level so userspace does + * not see a transient "encrypted" state that a + * key-size downgrade would immediately invalidate. + */ + if (conn->type != ACL_LINK) + mgmt_security_level_changed(conn); } else { - clear_bit(HCI_CONN_ENCRYPT, &conn->flags); - clear_bit(HCI_CONN_AES_CCM, &conn->flags); + clear_bit(HCI_CONN_ENCRYPT, conn->flags); + clear_bit(HCI_CONN_AES_CCM, conn->flags); + /* Elevated security levels (MEDIUM and above) require + * encryption, so downgrade to reflect the connection + * no longer being encrypted before reporting, instead + * of advertising a stale elevated level alongside + * MGMT_CONN_SEC_ENCRYPT_NONE. + */ + if (conn->sec_level > BT_SECURITY_LOW) + conn->sec_level = BT_SECURITY_LOW; + mgmt_security_level_changed(conn); } } @@ -3699,7 +3785,7 @@ static void hci_encrypt_change_evt(struct hci_dev *hdev, void *data, hci_adv_instances_set_rpa_expired(hdev, true); } - clear_bit(HCI_CONN_ENCRYPT_PEND, &conn->flags); + clear_bit(HCI_CONN_ENCRYPT_PEND, conn->flags); /* Check link security requirements are met */ if (!hci_conn_check_link_mode(conn)) @@ -3707,7 +3793,7 @@ static void hci_encrypt_change_evt(struct hci_dev *hdev, void *data, if (ev->status && conn->state == BT_CONNECTED) { if (ev->status == HCI_ERROR_PIN_OR_KEY_MISSING) - set_bit(HCI_CONN_AUTH_FAILURE, &conn->flags); + set_bit(HCI_CONN_AUTH_FAILURE, conn->flags); /* Notify upper layers so they can cleanup before * disconnecting. @@ -3720,8 +3806,14 @@ static void hci_encrypt_change_evt(struct hci_dev *hdev, void *data, /* Try reading the encryption key size for encrypted ACL links */ if (!ev->status && ev->encrypt && conn->type == ACL_LINK) { - if (hci_read_enc_key_size(hdev, conn)) + if (hci_read_enc_key_size(hdev, conn)) { + /* Could not even issue the key-size read: report the + * security level now since hci_cc_read_enc_key_size() + * will not run to do it. + */ + mgmt_security_level_changed(conn); goto notify; + } goto unlock; } @@ -3739,8 +3831,8 @@ static void hci_encrypt_change_evt(struct hci_dev *hdev, void *data, * type can be either LE or ACL and controller must support LMP Ping. * Ensure for AES-CCM encryption as well. */ - if (test_bit(HCI_CONN_ENCRYPT, &conn->flags) && - test_bit(HCI_CONN_AES_CCM, &conn->flags) && + if (test_bit(HCI_CONN_ENCRYPT, conn->flags) && + test_bit(HCI_CONN_AES_CCM, conn->flags) && ((conn->type == ACL_LINK && lmp_ping_capable(hdev)) || (conn->type == LE_LINK && (hdev->le_features[0] & HCI_LE_PING)))) { struct hci_cp_write_auth_payload_to cp; @@ -3772,9 +3864,9 @@ static void hci_change_link_key_complete_evt(struct hci_dev *hdev, void *data, conn = hci_conn_hash_lookup_handle(hdev, __le16_to_cpu(ev->handle)); if (conn) { if (!ev->status) - set_bit(HCI_CONN_SECURE, &conn->flags); + set_bit(HCI_CONN_SECURE, conn->flags); - clear_bit(HCI_CONN_AUTH_PEND, &conn->flags); + clear_bit(HCI_CONN_AUTH_PEND, conn->flags); hci_key_change_cfm(conn, ev->status); } @@ -3901,13 +3993,16 @@ static u8 hci_cc_le_set_cig_params(struct hci_dev *hdev, void *data, struct hci_conn *conn; u8 status = rp->status; bool pending = false; + size_t len; int i; bt_dev_dbg(hdev, "status 0x%2.2x", rp->status); - cp = hci_sent_cmd_data(hdev, HCI_OP_LE_SET_CIG_PARAMS); + cp = hci_sent_cmd_data_len(hdev, HCI_OP_LE_SET_CIG_PARAMS, &len); if (!rp->status && - (!cp || rp->num_handles != cp->num_cis || + (!cp || len < sizeof(*cp) || + len < struct_size(cp, cis, cp->num_cis) || + rp->num_handles != cp->num_cis || rp->cig_id != cp->cig_id || skb->len < array_size(rp->num_handles, sizeof(*rp->handle)))) { bt_dev_err(hdev, "unexpected Set CIG Parameters response data"); @@ -4000,7 +4095,7 @@ static u8 hci_cc_le_setup_iso_path(struct hci_dev *hdev, void *data, hci_connect_cfm(conn, rp->status); /* Notify device connected in case it is a BIG Sync */ - if (!rp->status && test_bit(HCI_CONN_BIG_SYNC, &conn->flags)) + if (!rp->status && test_bit(HCI_CONN_BIG_SYNC, conn->flags)) mgmt_device_connected(hdev, conn, NULL, 0); break; @@ -4404,6 +4499,7 @@ static void hci_cs_le_create_cis(struct hci_dev *hdev, u8 status) { struct hci_cp_le_create_cis *cp; bool pending = false; + size_t len; int i; bt_dev_dbg(hdev, "status 0x%2.2x", status); @@ -4411,10 +4507,14 @@ static void hci_cs_le_create_cis(struct hci_dev *hdev, u8 status) if (!status) return; - cp = hci_sent_cmd_data(hdev, HCI_OP_LE_CREATE_CIS); + cp = hci_sent_cmd_data_len(hdev, HCI_OP_LE_CREATE_CIS, &len); if (!cp) return; + if (len < sizeof(*cp) || + len < struct_size(cp, cis, cp->num_cis)) + return; + hci_dev_lock(hdev); /* Remove connection if command failed */ @@ -4427,7 +4527,7 @@ static void hci_cs_le_create_cis(struct hci_dev *hdev, u8 status) conn = hci_conn_hash_lookup_handle(hdev, handle); if (conn) { if (test_and_clear_bit(HCI_CONN_CREATE_CIS, - &conn->flags)) + conn->flags)) pending = true; conn->state = BT_CLOSED; hci_connect_cfm(conn, status); @@ -4548,7 +4648,7 @@ static void hci_role_change_evt(struct hci_dev *hdev, void *data, if (!ev->status) conn->role = ev->role; - clear_bit(HCI_CONN_RSWITCH_PEND, &conn->flags); + clear_bit(HCI_CONN_RSWITCH_PEND, conn->flags); hci_role_switch_cfm(conn, ev->status, ev->role); } @@ -4660,14 +4760,12 @@ static void hci_mode_change_evt(struct hci_dev *hdev, void *data, conn->mode = ev->mode; if (!test_and_clear_bit(HCI_CONN_MODE_CHANGE_PEND, - &conn->flags)) { - if (conn->mode == HCI_CM_ACTIVE) - set_bit(HCI_CONN_POWER_SAVE, &conn->flags); - else - clear_bit(HCI_CONN_POWER_SAVE, &conn->flags); + conn->flags)) { + assign_bit(HCI_CONN_POWER_SAVE, conn->flags, + conn->mode == HCI_CM_ACTIVE); } - if (test_and_clear_bit(HCI_CONN_SCO_SETUP_PEND, &conn->flags)) + if (test_and_clear_bit(HCI_CONN_SCO_SETUP_PEND, conn->flags)) hci_sco_setup(conn, ev->status); } @@ -4695,7 +4793,7 @@ static void hci_pin_code_request_evt(struct hci_dev *hdev, void *data, } if (!hci_dev_test_flag(hdev, HCI_BONDABLE) && - !test_bit(HCI_CONN_AUTH_INITIATOR, &conn->flags)) { + !test_bit(HCI_CONN_AUTH_INITIATOR, conn->flags)) { hci_send_cmd(hdev, HCI_OP_PIN_CODE_NEG_REPLY, sizeof(ev->bdaddr), &ev->bdaddr); } else if (hci_dev_test_flag(hdev, HCI_MGMT)) { @@ -4770,7 +4868,7 @@ static void hci_link_key_request_evt(struct hci_dev *hdev, void *data, conn = hci_conn_hash_lookup_ba(hdev, ACL_LINK, &ev->bdaddr); if (conn) { - clear_bit(HCI_CONN_NEW_LINK_KEY, &conn->flags); + clear_bit(HCI_CONN_NEW_LINK_KEY, conn->flags); if ((key->type == HCI_LK_UNAUTH_COMBINATION_P192 || key->type == HCI_LK_UNAUTH_COMBINATION_P256) && @@ -4833,7 +4931,7 @@ static void hci_link_key_notify_evt(struct hci_dev *hdev, void *data, conn->disc_timeout = HCI_DISCONN_TIMEOUT; hci_conn_drop(conn); - set_bit(HCI_CONN_NEW_LINK_KEY, &conn->flags); + set_bit(HCI_CONN_NEW_LINK_KEY, conn->flags); conn_set_key(conn, ev->key_type, conn->pin_length); if (!hci_dev_test_flag(hdev, HCI_MGMT)) @@ -4864,10 +4962,7 @@ static void hci_link_key_notify_evt(struct hci_dev *hdev, void *data, goto unlock; } - if (persistent) - clear_bit(HCI_CONN_FLUSH_KEY, &conn->flags); - else - set_bit(HCI_CONN_FLUSH_KEY, &conn->flags); + assign_bit(HCI_CONN_FLUSH_KEY, conn->flags, !persistent); unlock: hci_dev_unlock(hdev); @@ -5045,7 +5140,7 @@ static void hci_remote_ext_features_evt(struct hci_dev *hdev, void *data, ie->data.ssp_mode = (ev->features[0] & LMP_HOST_SSP); if (ev->features[0] & LMP_HOST_SSP) { - set_bit(HCI_CONN_SSP_ENABLED, &conn->flags); + set_bit(HCI_CONN_SSP_ENABLED, conn->flags); } else { /* It is mandatory by the Bluetooth specification that * Extended Inquiry Results are only used when Secure @@ -5055,17 +5150,17 @@ static void hci_remote_ext_features_evt(struct hci_dev *hdev, void *data, * To make these devices work, the internal SSP * enabled flag needs to be cleared if the remote host * features do not indicate SSP support */ - clear_bit(HCI_CONN_SSP_ENABLED, &conn->flags); + clear_bit(HCI_CONN_SSP_ENABLED, conn->flags); } if (ev->features[0] & LMP_HOST_SC) - set_bit(HCI_CONN_SC_ENABLED, &conn->flags); + set_bit(HCI_CONN_SC_ENABLED, conn->flags); } if (conn->state != BT_CONFIG) goto unlock; - if (!ev->status && !test_bit(HCI_CONN_MGMT_CONNECTED, &conn->flags)) { + if (!ev->status && !test_bit(HCI_CONN_MGMT_CONNECTED, conn->flags)) { struct hci_cp_remote_name_req cp; memset(&cp, 0, sizeof(cp)); bacpy(&cp.bdaddr, &conn->dst); @@ -5292,10 +5387,16 @@ static void hci_key_refresh_complete_evt(struct hci_dev *hdev, void *data, if (conn->type != LE_LINK) goto unlock; - if (!ev->status) + if (!ev->status) { + bool sec_level_changed = + conn->sec_level != conn->pending_sec_level; + conn->sec_level = conn->pending_sec_level; + if (sec_level_changed) + mgmt_security_level_changed(conn); + } - clear_bit(HCI_CONN_ENCRYPT_PEND, &conn->flags); + clear_bit(HCI_CONN_ENCRYPT_PEND, conn->flags); if (ev->status && conn->state == BT_CONNECTED) { hci_disconnect(conn, HCI_ERROR_AUTH_FAILURE); @@ -5396,7 +5497,7 @@ static void hci_io_capa_request_evt(struct hci_dev *hdev, void *data, goto unlock; /* Assume remote supports SSP since it has triggered this event */ - set_bit(HCI_CONN_SSP_ENABLED, &conn->flags); + set_bit(HCI_CONN_SSP_ENABLED, conn->flags); hci_conn_hold(conn); @@ -5407,7 +5508,7 @@ static void hci_io_capa_request_evt(struct hci_dev *hdev, void *data, * pairing or if the remote is not requesting bonding. */ if (hci_dev_test_flag(hdev, HCI_BONDABLE) || - test_bit(HCI_CONN_AUTH_INITIATOR, &conn->flags) || + test_bit(HCI_CONN_AUTH_INITIATOR, conn->flags) || (conn->remote_auth & ~0x01) == HCI_AT_NO_BONDING) { struct hci_cp_io_capability_reply cp; @@ -5517,7 +5618,7 @@ static void hci_user_confirm_request_evt(struct hci_dev *hdev, void *data, * local IO capability is not NoInputNoOutput, use JUST_WORKS * method (mgmt_user_confirm with confirm_hint set to 1). */ - if (!test_bit(HCI_CONN_AUTH_PEND, &conn->flags) && + if (!test_bit(HCI_CONN_AUTH_PEND, conn->flags) && conn->io_capability != HCI_IO_NO_INPUT_OUTPUT) { bt_dev_dbg(hdev, "Confirming auto-accept as acceptor"); confirm_hint = 1; @@ -5660,7 +5761,7 @@ static void hci_simple_pair_complete_evt(struct hci_dev *hdev, void *data, * initiated the authentication. A traditional auth_complete * event gets always produced as initiator and is also mapped to * the mgmt_auth_failed event */ - if (!test_bit(HCI_CONN_AUTH_PEND, &conn->flags) && ev->status) + if (!test_bit(HCI_CONN_AUTH_PEND, conn->flags) && ev->status) mgmt_auth_failed(conn, ev->status); hci_conn_drop(conn); @@ -5906,7 +6007,7 @@ static void le_conn_complete_evt(struct hci_dev *hdev, u8 status, goto unlock; /* Drop the connection if it has been aborted */ - if (test_bit(HCI_CONN_CANCEL, &conn->flags)) { + if (test_bit(HCI_CONN_CANCEL, conn->flags)) { hci_conn_drop(conn); goto unlock; } @@ -5922,9 +6023,16 @@ static void le_conn_complete_evt(struct hci_dev *hdev, u8 status, goto unlock; } + /* Unlike outgoing BR/EDR connections, conn->sec_level is not set at + * connection request time for LE, so it is still at its + * zero-initialized value (BT_SECURITY_SDP) here. Set it to + * BT_SECURITY_LOW before reporting the connection so + * mgmt_device_connected() reports the correct initial security level + * instead of a transient, never-really-in-use SDP value. + */ + conn->sec_level = BT_SECURITY_LOW; mgmt_device_connected(hdev, conn, NULL, 0); - conn->sec_level = BT_SECURITY_LOW; conn->state = BT_CONFIG; /* Store current advertising instance as connection advertising instance @@ -5956,6 +6064,28 @@ static void le_conn_complete_evt(struct hci_dev *hdev, u8 status, hci_conn_put(params->conn); params->conn = NULL; } + + /* An explicit connect request is complete once connected, so + * clean it up here: hci_connect_le_scan_cleanup() no longer + * finds the params since they have just been removed from + * pend_le_conns. + */ + if (params->explicit_connect) { + params->explicit_connect = false; + + switch (params->auto_connect) { + case HCI_AUTO_CONN_EXPLICIT: + hci_conn_params_del(hdev, &conn->dst, + conn->dst_type); + break; + case HCI_AUTO_CONN_REPORT: + hci_pend_le_list_add(params, + &hdev->pend_le_reports); + break; + default: + break; + } + } } /* If we are central and have subrate parameters stored, queue a @@ -6016,8 +6146,8 @@ static void hci_le_pa_sync_lost_evt(struct hci_dev *hdev, void *data, /* Delete the pa sync connection */ conn = hci_conn_hash_lookup_pa_sync_handle(hdev, handle); if (conn) { - clear_bit(HCI_CONN_BIG_SYNC, &conn->flags); - clear_bit(HCI_CONN_PA_SYNC, &conn->flags); + clear_bit(HCI_CONN_BIG_SYNC, conn->flags); + clear_bit(HCI_CONN_PA_SYNC, conn->flags); hci_disconn_cfm(conn, HCI_ERROR_REMOTE_USER_TERM); hci_conn_del(conn); } @@ -6151,7 +6281,7 @@ static void hci_le_past_received_evt(struct hci_dev *hdev, void *data, pa_sync->sync_handle = le16_to_cpu(ev->sync_handle); if (ev->status) { - set_bit(HCI_CONN_PA_SYNC_FAILED, &pa_sync->flags); + set_bit(HCI_CONN_PA_SYNC_FAILED, pa_sync->flags); /* Notify iso layer */ hci_connect_cfm(pa_sync, ev->status); @@ -6673,7 +6803,7 @@ static void hci_le_pa_sync_established_evt(struct hci_dev *hdev, void *data, goto unlock; } - clear_bit(HCI_CONN_CREATE_PA_SYNC, &conn->flags); + clear_bit(HCI_CONN_CREATE_PA_SYNC, conn->flags); conn->sync_handle = le16_to_cpu(ev->handle); conn->sid = HCI_SID_INVALID; @@ -6698,7 +6828,7 @@ static void hci_le_pa_sync_established_evt(struct hci_dev *hdev, void *data, pa_sync->sync_handle = le16_to_cpu(ev->handle); if (ev->status) { - set_bit(HCI_CONN_PA_SYNC_FAILED, &pa_sync->flags); + set_bit(HCI_CONN_PA_SYNC_FAILED, pa_sync->flags); /* Notify iso layer */ hci_connect_cfm(pa_sync, ev->status); @@ -6742,7 +6872,7 @@ static void hci_le_per_adv_report_evt(struct hci_dev *hdev, void *data, goto unlock; if (ev->data_status == LE_PA_DATA_COMPLETE && - !test_and_set_bit(HCI_CONN_PA_SYNC, &pa_sync->flags)) { + !test_and_set_bit(HCI_CONN_PA_SYNC, pa_sync->flags)) { /* Notify iso layer */ hci_connect_cfm(pa_sync, 0); @@ -6855,11 +6985,11 @@ static void hci_le_ltk_request_evt(struct hci_dev *hdev, void *data, * using a distributed LTK. */ if (ltk->type == SMP_STK) { - set_bit(HCI_CONN_STK_ENCRYPT, &conn->flags); + set_bit(HCI_CONN_STK_ENCRYPT, conn->flags); list_del_rcu(<k->list); kfree_rcu(ltk, rcu); } else { - clear_bit(HCI_CONN_STK_ENCRYPT, &conn->flags); + clear_bit(HCI_CONN_STK_ENCRYPT, conn->flags); } hci_dev_unlock(hdev); @@ -7055,7 +7185,7 @@ static void hci_le_cis_established_evt(struct hci_dev *hdev, void *data, qos = &conn->iso_qos; - pending = test_and_clear_bit(HCI_CONN_CREATE_CIS, &conn->flags); + pending = test_and_clear_bit(HCI_CONN_CREATE_CIS, conn->flags); /* BLUETOOTH CORE SPECIFICATION Version 5.4 | Vol 6, Part G * page 3075: @@ -7252,7 +7382,7 @@ static void hci_le_create_big_complete_evt(struct hci_dev *hdev, void *data, } conn->state = BT_CONNECTED; - set_bit(HCI_CONN_BIG_CREATED, &conn->flags); + set_bit(HCI_CONN_BIG_CREATED, conn->flags); hci_debugfs_create_conn(conn); hci_conn_add_sysfs(conn); hci_iso_setup_path(conn); @@ -7297,7 +7427,7 @@ static void hci_le_big_sync_established_evt(struct hci_dev *hdev, void *data, goto unlock; } - clear_bit(HCI_CONN_CREATE_BIG_SYNC, &conn->flags); + clear_bit(HCI_CONN_CREATE_BIG_SYNC, conn->flags); conn->num_bis = 0; memset(conn->bis, 0, sizeof(conn->bis)); @@ -7320,7 +7450,7 @@ static void hci_le_big_sync_established_evt(struct hci_dev *hdev, void *data, if (ev->status != 0x42) /* Mark PA sync as established */ - set_bit(HCI_CONN_PA_SYNC, &bis->flags); + set_bit(HCI_CONN_PA_SYNC, bis->flags); bis->sync_handle = conn->sync_handle; bis->iso_qos.bcast.big = ev->handle; @@ -7333,7 +7463,7 @@ static void hci_le_big_sync_established_evt(struct hci_dev *hdev, void *data, if (!ev->status) { bis->state = BT_CONNECTED; - set_bit(HCI_CONN_BIG_SYNC, &bis->flags); + set_bit(HCI_CONN_BIG_SYNC, bis->flags); hci_debugfs_create_conn(bis); hci_conn_add_sysfs(bis); hci_iso_setup_path(bis); @@ -7351,7 +7481,7 @@ static void hci_le_big_sync_established_evt(struct hci_dev *hdev, void *data, if (!bis) continue; - set_bit(HCI_CONN_BIG_SYNC_FAILED, &bis->flags); + set_bit(HCI_CONN_BIG_SYNC_FAILED, bis->flags); hci_connect_cfm(bis, ev->status); } @@ -7375,14 +7505,19 @@ static void hci_le_big_sync_lost_evt(struct hci_dev *hdev, void *data, BT_CONNECTED, HCI_ROLE_SLAVE))) { if (!mgmt_conn) { - mgmt_conn = test_and_clear_bit(HCI_CONN_MGMT_CONNECTED, - &bis->flags); + /* Only peek at the flag here: hci_conn_del() (via + * hci_conn_unlink()) still needs it set to know + * whether to report the security level reset, so + * it is consumed there instead of here. + */ + mgmt_conn = test_bit(HCI_CONN_MGMT_CONNECTED, + bis->flags); mgmt_device_disconnected(hdev, &bis->dst, bis->type, bis->dst_type, ev->reason, mgmt_conn); } - clear_bit(HCI_CONN_BIG_SYNC, &bis->flags); + clear_bit(HCI_CONN_BIG_SYNC, bis->flags); hci_disconn_cfm(bis, ev->reason); hci_conn_del(bis); } diff --git a/net/bluetooth/hci_sync.c b/net/bluetooth/hci_sync.c index 4e5c47872c30..8f90e5ffebd4 100644 --- a/net/bluetooth/hci_sync.c +++ b/net/bluetooth/hci_sync.c @@ -376,8 +376,18 @@ static void le_scan_disable(struct work_struct *work) bt_dev_dbg(hdev, ""); hci_dev_lock(hdev); - if (!hci_dev_test_flag(hdev, HCI_LE_SCAN)) + if (!hci_dev_test_flag(hdev, HCI_LE_SCAN)) { + /* The scan of a discovery can be disabled while this work + * waits for the lock, for example by a Stop Discovery that + * timed out and still completed, so end the discovery as + * le_set_scan_enable_complete() does when it cancels this + * work. + */ + if (hdev->discovery.state == DISCOVERY_FINDING) + goto discov_stopped; + goto _return; + } status = hci_cmd_sync_queue(hdev, scan_disable_sync, NULL, NULL); if (status) { @@ -2448,15 +2458,17 @@ static int hci_le_del_resolve_list_sync(struct hci_dev *hdev, bdaddr_t *bdaddr, u8 bdaddr_type) { struct hci_cp_le_del_from_resolv_list cp; - struct bdaddr_list_with_irk *entry; + bool exists; if (!ll_privacy_capable(hdev)) return 0; /* Check if the IRK has been programmed */ - entry = hci_bdaddr_list_lookup_with_irk(&hdev->le_resolv_list, bdaddr, - bdaddr_type); - if (!entry) + hci_dev_lock(hdev); + exists = hci_bdaddr_list_lookup_with_irk(&hdev->le_resolv_list, + bdaddr, bdaddr_type); + hci_dev_unlock(hdev); + if (!exists) return 0; cp.bdaddr_type = bdaddr_type; @@ -2512,8 +2524,8 @@ static int hci_le_add_resolve_list_sync(struct hci_dev *hdev, { struct hci_cp_le_add_to_resolv_list cp; struct smp_irk *irk; - struct bdaddr_list_with_irk *entry; struct hci_conn_params *p; + bool exists; if (!ll_privacy_capable(hdev)) return 0; @@ -2531,20 +2543,28 @@ static int hci_le_add_resolve_list_sync(struct hci_dev *hdev, } else if (!(params->flags & HCI_CONN_FLAG_ADDRESS_RESOLUTION)) return 0; + rcu_read_lock(); + irk = hci_find_irk_by_addr(hdev, ¶ms->addr, params->addr_type); - if (!irk) + if (!irk) { + rcu_read_unlock(); return 0; + } + + memcpy(cp.peer_irk, irk->val, 16); + + rcu_read_unlock(); /* Check if the IK has _not_ been programmed yet. */ - entry = hci_bdaddr_list_lookup_with_irk(&hdev->le_resolv_list, - ¶ms->addr, - params->addr_type); - if (entry) + hci_dev_lock(hdev); + exists = hci_bdaddr_list_lookup_with_irk( + &hdev->le_resolv_list, ¶ms->addr, params->addr_type); + hci_dev_unlock(hdev); + if (exists) return 0; cp.bdaddr_type = params->addr_type; bacpy(&cp.bdaddr, ¶ms->addr); - memcpy(cp.peer_irk, irk->val, 16); /* Default privacy mode is always Network */ params->privacy_mode = HCI_NETWORK_PRIVACY; @@ -2885,6 +2905,31 @@ static struct conn_params *conn_params_copy(struct list_head *list, size_t *n) return p; } +static struct conn_params *le_accept_list_copy(struct hci_dev *hdev, + size_t *n) +{ + struct bdaddr_list *entry; + struct conn_params *params; + size_t i = 0; + + hci_dev_lock(hdev); + + *n = list_count_nodes(&hdev->le_accept_list); + params = kvzalloc_objs(struct conn_params, *n); + if (!params) + goto unlock; + + list_for_each_entry(entry, &hdev->le_accept_list, list) { + bacpy(¶ms[i].addr, &entry->bdaddr); + params[i].addr_type = entry->bdaddr_type; + i++; + } + +unlock: + hci_dev_unlock(hdev); + return params; +} + /* Clear LE Accept List */ static int hci_le_clear_accept_list_sync(struct hci_dev *hdev) { @@ -2915,7 +2960,6 @@ static int hci_le_clear_accept_list_sync(struct hci_dev *hdev) static u8 hci_update_accept_list_sync(struct hci_dev *hdev) { struct conn_params *params; - struct bdaddr_list *b, *t; u8 num_entries = 0; bool pend_conn, pend_report; u8 filter_policy; @@ -2980,20 +3024,27 @@ static u8 hci_update_accept_list_sync(struct hci_dev *hdev) * report. If not present in either list, then remove it from * the controller. */ - list_for_each_entry_safe(b, t, &hdev->le_accept_list, list) { + params = le_accept_list_copy(hdev, &n); + if (!params) { + err = -ENOMEM; + goto done; + } + + for (i = 0; i < n; i++) { rcu_read_lock(); - if (hci_conn_hash_lookup_le(hdev, &b->bdaddr, b->bdaddr_type)) { + if (hci_conn_hash_lookup_le(hdev, ¶ms[i].addr, + params[i].addr_type)) { rcu_read_unlock(); continue; } pend_conn = hci_pend_le_action_lookup(&hdev->pend_le_conns, - &b->bdaddr, - b->bdaddr_type); - pend_report = hci_pend_le_action_lookup(&hdev->pend_le_reports, - &b->bdaddr, - b->bdaddr_type); + ¶ms[i].addr, + params[i].addr_type); + pend_report = hci_pend_le_action_lookup( + &hdev->pend_le_reports, ¶ms[i].addr, + params[i].addr_type); rcu_read_unlock(); @@ -3001,14 +3052,16 @@ static u8 hci_update_accept_list_sync(struct hci_dev *hdev) * remove it from the acceptlist. */ if (!pend_conn && !pend_report) { - hci_le_del_accept_list_sync(hdev, &b->bdaddr, - b->bdaddr_type); + hci_le_del_accept_list_sync(hdev, ¶ms[i].addr, + params[i].addr_type); continue; } num_entries++; } + kvfree(params); + /* Since all no longer valid accept list entries have been * removed, walk through the list of pending connections * and ensure that any new device gets programmed into @@ -3511,9 +3564,13 @@ int hci_write_ssp_mode_sync(struct hci_dev *hdev, u8 mode) return hci_write_sc_support_sync(hdev, 0x01); } +static int hci_le_set_host_feature_sync(struct hci_dev *hdev, u16 bit, + u8 value); + int hci_write_le_host_supported_sync(struct hci_dev *hdev, u8 le, u8 simul) { struct hci_cp_write_le_host_supported cp; + int err; if (!hci_dev_test_flag(hdev, HCI_LE_ENABLED) || !lmp_bredr_capable(hdev)) @@ -3531,8 +3588,16 @@ int hci_write_le_host_supported_sync(struct hci_dev *hdev, u8 le, u8 simul) cp.le = le; cp.simul = simul; - return __hci_cmd_sync_status(hdev, HCI_OP_WRITE_LE_HOST_SUPPORTED, - sizeof(cp), &cp, HCI_CMD_TIMEOUT); + err = __hci_cmd_sync_status(hdev, HCI_OP_WRITE_LE_HOST_SUPPORTED, + sizeof(cp), &cp, HCI_CMD_TIMEOUT); + if (err || !cis_capable(hdev)) + return err; + + /* The CIS host feature is set during init based on LE being enabled, + * which is not repeated when LE is enabled afterwards, e.g. while the + * controller is still auto powered on, so update it here. + */ + return hci_le_set_host_feature_sync(hdev, 32, iso_enabled(hdev)); } static int hci_powered_update_adv_sync(struct hci_dev *hdev) @@ -4834,6 +4899,9 @@ static int hci_le_set_def_rate_sync(struct hci_dev *hdev) struct hci_cp_le_set_def_rate cp; u16 interval_min = 0x000a; /* 1.25 ms */ u16 interval_max = 0x0078; /* 15 ms */ + u16 subrate_max = 0x0004; + u16 max_latency = 0x0000; + u32 supv_timeout; if (!le_sci_capable(hdev)) return 0; @@ -4858,10 +4926,31 @@ static int hci_le_set_def_rate_sync(struct hci_dev *hdev) cp.interval_min = cpu_to_le16(interval_min); cp.interval_max = cpu_to_le16(interval_max); cp.subrate_min = cpu_to_le16(0x0001); - cp.subrate_max = cpu_to_le16(0x0004); - cp.max_latency = cpu_to_le16(0x0000); + cp.subrate_max = cpu_to_le16(subrate_max); + cp.max_latency = cpu_to_le16(max_latency); cp.cont_num = cpu_to_le16(0x0001); - cp.supv_timeout = cpu_to_le16(0x000c); /* 120 ms */ + + /* HOGP v1.2 recommends a Supervision_Timeout greater than or equal to + * (1 + Max_Latency) x Subrate_Max x Connection_Interval_Max x 2, but + * the Core spec treats the equality as invalid: + * + * BLUETOOTH CORE SPECIFICATION Version 6.3 | Vol 4, Part E + * 7.8.158. LE Set Default Rate Parameters command + * + * If Connection_Interval_Max x Subrate_Max x (Max_Latency + 1) is + * greater than or equal to Supervision_Timeout x 40, the Controller + * shall return the error code Invalid HCI Command Parameters (0x12). + * + * So default to 2 s, 10x lower than the 20 s used for non-SCI + * connections while still well above the minimum required, but make + * sure it stays strictly above the minimum in case interval_max has + * been raised. + */ + supv_timeout = (u32)interval_max * subrate_max * (max_latency + 1); + supv_timeout = supv_timeout / 40 + 1; + supv_timeout = clamp_t(u32, max_t(u32, supv_timeout, 0x00c8), + 0x000a, 0x0c80); + cp.supv_timeout = cpu_to_le16(supv_timeout); /* The connection event length recommended in requests by a Peripheral * uses units of 125 us with a valid range of 0x0001 to 0x7CFF @@ -5635,6 +5724,11 @@ int hci_dev_close_sync(struct hci_dev *hdev) return err; } + /* Wait for hci_recv_frame() callers that still saw HCI_UP, so that + * none of them queues rx_work while the workqueue is drained below. + */ + synchronize_rcu(); + hci_leds_update_powered(hdev, false); /* Flush RX and TX works */ @@ -5846,11 +5940,15 @@ int hci_stop_discovery_sync(struct hci_dev *hdev) } if (hci_dev_test_flag(hdev, HCI_LE_SCAN)) { - cancel_delayed_work(&hdev->le_scan_disable); - err = hci_scan_disable_sync(hdev); if (err) return err; + + /* Only cancel the LE scan timeout once the scan is + * disabled, so that the discovery still ends if + * stopping it failed. + */ + cancel_delayed_work(&hdev->le_scan_disable); } } else { @@ -5929,11 +6027,11 @@ static int hci_le_connect_cancel_sync(struct hci_dev *hdev, /* Return reason if scanning since the connection shall probably be * cleanup directly. */ - if (test_bit(HCI_CONN_SCANNING, &conn->flags)) + if (test_bit(HCI_CONN_SCANNING, conn->flags)) return reason; if (conn->role == HCI_ROLE_SLAVE || - test_and_set_bit(HCI_CONN_CANCEL, &conn->flags)) + test_and_set_bit(HCI_CONN_CANCEL, conn->flags)) return 0; return __hci_cmd_sync_status(hdev, HCI_OP_LE_CREATE_CONN_CANCEL, @@ -5955,7 +6053,7 @@ static int hci_connect_cancel_sync(struct hci_dev *hdev, struct hci_conn *conn, * then an HCI_LE_CIS_Established event shall also be sent for * this CIS with the Status Operation Cancelled by Host (0x44). */ - if (test_bit(HCI_CONN_CREATE_CIS, &conn->flags)) + if (test_bit(HCI_CONN_CREATE_CIS, conn->flags)) return hci_disconnect_sync(hdev, conn, reason); /* CIS with no Create CIS sent have nothing to cancel */ @@ -6485,6 +6583,12 @@ static int hci_pause_discovery_sync(struct hci_dev *hdev) return 0; hci_discovery_set_state(hdev, DISCOVERY_STOPPING); + + /* Cancel the LE scan timeout first, so that it does not run while + * suspended if the scan cannot be disabled. + */ + cancel_delayed_work(&hdev->le_scan_disable); + err = hci_stop_discovery_sync(hdev); if (err) return err; @@ -6953,7 +7057,7 @@ static int hci_le_create_conn_sync(struct hci_dev *hdev, void *data) bt_dev_dbg(hdev, "conn %p", conn); - clear_bit(HCI_CONN_SCANNING, &conn->flags); + clear_bit(HCI_CONN_SCANNING, conn->flags); conn->state = BT_CONNECT; /* If requested to connect as peripheral use directed advertising */ @@ -7020,7 +7124,7 @@ static int hci_le_create_conn_sync(struct hci_dev *hdev, void *data) /* Mark create connection in flight so hci_cancel_connect_sync() can * cancel it while blocking on the connection complete event. */ - set_bit(HCI_CONN_CREATE, &conn->flags); + set_bit(HCI_CONN_CREATE, conn->flags); /* Send command LE Extended Create Connection if supported */ if (use_ext_conn(hdev)) { @@ -7057,7 +7161,7 @@ static int hci_le_create_conn_sync(struct hci_dev *hdev, void *data) conn->conn_timeout, NULL); done: - clear_bit(HCI_CONN_CREATE, &conn->flags); + clear_bit(HCI_CONN_CREATE, conn->flags); if (err == -ETIMEDOUT) hci_le_connect_cancel_sync(hdev, conn, 0x00); @@ -7104,7 +7208,7 @@ int hci_le_create_cis_sync(struct hci_dev *hdev) /* Wait until previous Create CIS has completed */ list_for_each_entry_rcu(conn, &hdev->conn_hash.list, list) { - if (test_bit(HCI_CONN_CREATE_CIS, &conn->flags)) + if (test_bit(HCI_CONN_CREATE_CIS, conn->flags)) goto done; } @@ -7140,7 +7244,7 @@ int hci_le_create_cis_sync(struct hci_dev *hdev) conn->iso_qos.ucast.cig != cig) continue; - set_bit(HCI_CONN_CREATE_CIS, &conn->flags); + set_bit(HCI_CONN_CREATE_CIS, conn->flags); cis->acl_handle = cpu_to_le16(conn->parent->handle); cis->cis_handle = cpu_to_le16(conn->handle); timeout = conn->conn_timeout; @@ -7343,14 +7447,14 @@ static int hci_acl_create_conn_sync(struct hci_dev *hdev, void *data) /* Mark create connection in flight so hci_cancel_connect_sync() can * cancel it while blocking on the connection complete event. */ - set_bit(HCI_CONN_CREATE, &conn->flags); + set_bit(HCI_CONN_CREATE, conn->flags); err = __hci_cmd_sync_status_sk(hdev, HCI_OP_CREATE_CONN, sizeof(cp), &cp, HCI_EV_CONN_COMPLETE, conn->conn_timeout, NULL); - clear_bit(HCI_CONN_CREATE, &conn->flags); + clear_bit(HCI_CONN_CREATE, conn->flags); return err; } @@ -7439,7 +7543,7 @@ static int hci_acl_cancel_create_conn_sync(struct hci_dev *hdev, mutex_lock(&hdev->cmd_sync_work_lock); /* In flight: this connection owns the pending request, cancel it. */ - if (test_bit(HCI_CONN_CREATE, &conn->flags)) { + if (test_bit(HCI_CONN_CREATE, conn->flags)) { hci_cmd_sync_cancel(hdev, ECANCELED); goto unlock; } @@ -7470,7 +7574,7 @@ static int hci_le_cancel_create_conn_sync(struct hci_dev *hdev, */ mutex_lock(&hdev->cmd_sync_work_lock); - if (test_bit(HCI_CONN_CREATE, &conn->flags)) { + if (test_bit(HCI_CONN_CREATE, conn->flags)) { hci_cmd_sync_cancel(hdev, ECANCELED); goto unlock; } @@ -7497,7 +7601,7 @@ static int hci_cis_cancel_create_conn_sync(struct hci_dev *hdev, */ mutex_lock(&hdev->cmd_sync_work_lock); - if (test_bit(HCI_CONN_CREATE_CIS, &conn->flags)) + if (test_bit(HCI_CONN_CREATE_CIS, conn->flags)) hci_cmd_sync_cancel(hdev, ECANCELED); mutex_unlock(&hdev->cmd_sync_work_lock); @@ -7634,7 +7738,7 @@ static void create_pa_complete(struct hci_dev *hdev, void *data, int err) hci_dev_lock(hdev); if (hci_conn_valid(hdev, conn)) - clear_bit(HCI_CONN_CREATE_PA_SYNC, &conn->flags); + clear_bit(HCI_CONN_CREATE_PA_SYNC, conn->flags); if (!err) goto unlock; @@ -7646,7 +7750,7 @@ static void create_pa_complete(struct hci_dev *hdev, void *data, int err) if (IS_ERR(pa_sync)) goto unlock; - set_bit(HCI_CONN_PA_SYNC_FAILED, &pa_sync->flags); + set_bit(HCI_CONN_PA_SYNC_FAILED, pa_sync->flags); /* Notify iso layer */ hci_connect_cfm(pa_sync, bt_status(err)); @@ -7719,7 +7823,7 @@ static int hci_le_pa_create_sync(struct hci_dev *hdev, void *data) * program the address in the allow list so PA advertisements can be * received. */ - set_bit(HCI_CONN_CREATE_PA_SYNC, &conn->flags); + set_bit(HCI_CONN_CREATE_PA_SYNC, conn->flags); hci_update_passive_scan_sync(hdev); @@ -7822,7 +7926,7 @@ static void create_big_complete(struct hci_dev *hdev, void *data, int err) if (err == -ECANCELED) goto done; - clear_bit(HCI_CONN_CREATE_BIG_SYNC, &conn->flags); + clear_bit(HCI_CONN_CREATE_BIG_SYNC, conn->flags); done: hci_conn_put(conn); @@ -7839,7 +7943,7 @@ static int hci_le_big_create_sync(struct hci_dev *hdev, void *data) if (!hci_conn_valid(hdev, conn)) return -ECANCELED; - set_bit(HCI_CONN_CREATE_BIG_SYNC, &conn->flags); + set_bit(HCI_CONN_CREATE_BIG_SYNC, conn->flags); memset(cp, 0, sizeof(*cp)); cp->handle = qos->bcast.big; diff --git a/net/bluetooth/iso.c b/net/bluetooth/iso.c index 8768d9c0cf51..06f1e7ba2cb1 100644 --- a/net/bluetooth/iso.c +++ b/net/bluetooth/iso.c @@ -912,7 +912,7 @@ static void iso_sock_disconn(struct sock *sk) struct sock *bis_sk; struct hci_conn *hcon = iso_pi(sk)->conn->hcon; - if (test_bit(HCI_CONN_BIG_CREATED, &hcon->flags)) { + if (test_bit(HCI_CONN_BIG_CREATED, hcon->flags)) { bis_sk = iso_get_sock_big(sk, &iso_pi(sk)->src, &iso_pi(sk)->dst, iso_pi(sk)->qos.bcast.big); @@ -957,8 +957,8 @@ static void __iso_sock_close(struct sock *sk) case BT_CONNECT2: if (iso_pi(sk)->conn->hcon && - (test_bit(HCI_CONN_PA_SYNC, &iso_pi(sk)->conn->hcon->flags) || - test_bit(HCI_CONN_PA_SYNC_FAILED, &iso_pi(sk)->conn->hcon->flags))) + (test_bit(HCI_CONN_PA_SYNC, iso_pi(sk)->conn->hcon->flags) || + test_bit(HCI_CONN_PA_SYNC_FAILED, iso_pi(sk)->conn->hcon->flags))) iso_sock_disconn(sk); else iso_chan_del(sk, ECONNRESET); @@ -1977,10 +1977,7 @@ static int iso_sock_setsockopt(struct socket *sock, int level, int optname, if (err) break; - if (opt) - set_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags); - else - clear_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags); + assign_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags, opt); break; case BT_PKT_STATUS: @@ -1988,10 +1985,7 @@ static int iso_sock_setsockopt(struct socket *sock, int level, int optname, if (err) break; - if (opt) - set_bit(BT_SK_PKT_STATUS, &bt_sk(sk)->flags); - else - clear_bit(BT_SK_PKT_STATUS, &bt_sk(sk)->flags); + assign_bit(BT_SK_PKT_STATUS, &bt_sk(sk)->flags, opt); break; case BT_PKT_SEQNUM: @@ -1999,10 +1993,7 @@ static int iso_sock_setsockopt(struct socket *sock, int level, int optname, if (err) break; - if (opt) - set_bit(BT_SK_PKT_SEQNUM, &bt_sk(sk)->flags); - else - clear_bit(BT_SK_PKT_SEQNUM, &bt_sk(sk)->flags); + assign_bit(BT_SK_PKT_SEQNUM, &bt_sk(sk)->flags, opt); break; case BT_ISO_QOS: @@ -2298,7 +2289,7 @@ static void iso_conn_ready(struct iso_conn *conn) hdev = hcon->hdev; - if (test_bit(HCI_CONN_BIG_SYNC, &hcon->flags)) { + if (test_bit(HCI_CONN_BIG_SYNC, hcon->flags)) { /* A BIS slave hcon is notified to the ISO layer * after the Command Complete for the LE Setup * ISO Data Path command is received. Get the @@ -2307,7 +2298,7 @@ static void iso_conn_ready(struct iso_conn *conn) parent = iso_get_sock(hdev, &hcon->src, &hcon->dst, BT_LISTEN, iso_match_big_hcon, hcon); - } else if (test_bit(HCI_CONN_BIG_SYNC_FAILED, &hcon->flags)) { + } else if (test_bit(HCI_CONN_BIG_SYNC_FAILED, hcon->flags)) { ev = hci_recv_event_data(hcon->hdev, HCI_EVT_LE_BIG_SYNC_ESTABLISHED); @@ -2321,7 +2312,7 @@ static void iso_conn_ready(struct iso_conn *conn) &hcon->dst, BT_LISTEN, iso_match_big, ev); - } else if (test_bit(HCI_CONN_PA_SYNC_FAILED, &hcon->flags)) { + } else if (test_bit(HCI_CONN_PA_SYNC_FAILED, hcon->flags)) { ev2 = hci_recv_event_data(hcon->hdev, HCI_EV_LE_PA_SYNC_ESTABLISHED); if (ev2) @@ -2329,7 +2320,7 @@ static void iso_conn_ready(struct iso_conn *conn) &hcon->dst, BT_LISTEN, iso_match_sid, ev2); - } else if (test_bit(HCI_CONN_PA_SYNC, &hcon->flags)) { + } else if (test_bit(HCI_CONN_PA_SYNC, hcon->flags)) { ev3 = hci_recv_event_data(hcon->hdev, HCI_EV_LE_PER_ADV_REPORT); if (ev3) @@ -2385,7 +2376,7 @@ static void iso_conn_ready(struct iso_conn *conn) hcon->dst_type = le_addr_type(iso_pi(parent)->dst_type); } - if (test_bit(HCI_CONN_PA_SYNC, &hcon->flags)) { + if (test_bit(HCI_CONN_PA_SYNC, hcon->flags)) { iso_pi(sk)->qos = iso_pi(parent)->qos; hcon->iso_qos = iso_pi(sk)->qos; iso_pi(sk)->bc_sid = iso_pi(parent)->bc_sid; @@ -2685,8 +2676,8 @@ static void iso_connect_cfm(struct hci_conn *hcon, __u8 status) * into the accept queue of the listening socket and wake up * userspace, to inform the user about the event. */ - if (!status || test_bit(HCI_CONN_BIG_SYNC_FAILED, &hcon->flags) || - test_bit(HCI_CONN_PA_SYNC_FAILED, &hcon->flags)) { + if (!status || test_bit(HCI_CONN_BIG_SYNC_FAILED, hcon->flags) || + test_bit(HCI_CONN_PA_SYNC_FAILED, hcon->flags)) { struct iso_conn *conn; conn = iso_conn_add(hcon); diff --git a/net/bluetooth/l2cap_core.c b/net/bluetooth/l2cap_core.c index 443392cb1748..fdf92a3d5745 100644 --- a/net/bluetooth/l2cap_core.c +++ b/net/bluetooth/l2cap_core.c @@ -1556,7 +1556,7 @@ static bool l2cap_check_enc_key_size(struct hci_conn *hcon, if (chan->sec_level == BT_SECURITY_FIPS) min_key_size = 16; - return (!test_bit(HCI_CONN_ENCRYPT, &hcon->flags) || + return (!test_bit(HCI_CONN_ENCRYPT, hcon->flags) || hcon->enc_key_size >= min_key_size); } @@ -3958,6 +3958,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) @@ -5207,10 +5208,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 @@ -5442,10 +5443,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); @@ -7253,7 +7254,11 @@ static void l2cap_recv_frame(struct l2cap_conn *conn, struct sk_buff *skb) u16 cid, len; __le16 psm; - if (hcon->state != BT_CONNECTED) { + /* Also hold data back while the encryption key size is read, as + * the security of the link, e.g. for SMP over BR/EDR, depends on it. + */ + if (hcon->state != BT_CONNECTED || + test_bit(HCI_CONN_ENC_KEY_SIZE_PEND, hcon->flags)) { BT_DBG("queueing pending rx skb"); skb_queue_tail(&conn->pending_rx, skb); return; @@ -7316,7 +7321,11 @@ static void process_pending_rx(struct work_struct *work) mutex_lock(&conn->lock); - while ((skb = skb_dequeue(&conn->pending_rx))) + /* l2cap_recv_frame() would queue it all again while the encryption + * key size is read, l2cap_security_cfm() schedules this once known. + */ + while (!test_bit(HCI_CONN_ENC_KEY_SIZE_PEND, conn->hcon->flags) && + (skb = skb_dequeue(&conn->pending_rx))) l2cap_recv_frame(conn, skb); mutex_unlock(&conn->lock); @@ -7899,6 +7908,10 @@ static void l2cap_security_cfm(struct hci_conn *hcon, u8 status, u8 encrypt) } mutex_unlock(&conn->lock); + + /* Process data held back while the encryption key size was read */ + if (!skb_queue_empty(&conn->pending_rx)) + queue_work(hcon->hdev->workqueue, &conn->pending_rx_work); } /* Append fragment into frame respecting the maximum len of rx_skb */ diff --git a/net/bluetooth/l2cap_sock.c b/net/bluetooth/l2cap_sock.c index 1796929f61b8..f413e5beab9e 100644 --- a/net/bluetooth/l2cap_sock.c +++ b/net/bluetooth/l2cap_sock.c @@ -871,15 +871,11 @@ static int l2cap_sock_setsockopt_old(struct socket *sock, int optname, if (opt & L2CAP_LM_SECURE) chan->sec_level = BT_SECURITY_HIGH; - if (opt & L2CAP_LM_MASTER) - set_bit(FLAG_ROLE_SWITCH, &chan->flags); - else - clear_bit(FLAG_ROLE_SWITCH, &chan->flags); + assign_bit(FLAG_ROLE_SWITCH, &chan->flags, + opt & L2CAP_LM_MASTER); - if (opt & L2CAP_LM_RELIABLE) - set_bit(FLAG_FORCE_RELIABLE, &chan->flags); - else - clear_bit(FLAG_FORCE_RELIABLE, &chan->flags); + assign_bit(FLAG_FORCE_RELIABLE, &chan->flags, + opt & L2CAP_LM_RELIABLE); break; default: @@ -1046,10 +1042,7 @@ static int l2cap_sock_setsockopt(struct socket *sock, int level, int optname, } } - if (opt) - set_bit(FLAG_FLUSHABLE, &chan->flags); - else - clear_bit(FLAG_FLUSHABLE, &chan->flags); + assign_bit(FLAG_FLUSHABLE, &chan->flags, opt); break; case BT_POWER: @@ -1065,10 +1058,7 @@ static int l2cap_sock_setsockopt(struct socket *sock, int level, int optname, if (err) break; - if (pwr.force_active) - set_bit(FLAG_FORCE_ACTIVE, &chan->flags); - else - clear_bit(FLAG_FORCE_ACTIVE, &chan->flags); + assign_bit(FLAG_FORCE_ACTIVE, &chan->flags, pwr.force_active); break; case BT_CHANNEL_POLICY: @@ -1342,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/bluetooth/mgmt.c b/net/bluetooth/mgmt.c index 11f01b8d53f8..a287dd4bb26e 100644 --- a/net/bluetooth/mgmt.c +++ b/net/bluetooth/mgmt.c @@ -177,6 +177,7 @@ static const u16 mgmt_events[] = { MGMT_EV_CONTROLLER_RESUME, MGMT_EV_ADV_MONITOR_DEVICE_FOUND, MGMT_EV_ADV_MONITOR_DEVICE_LOST, + MGMT_EV_SECURITY_LEVEL_CHANGED, }; static const u16 mgmt_untrusted_commands[] = { @@ -301,6 +302,10 @@ static u8 mgmt_errno_status(int err) return MGMT_STATUS_ALREADY_CONNECTED; case -ENOTCONN: return MGMT_STATUS_DISCONNECTED; + case -ECANCELED: + return MGMT_STATUS_CANCELLED; + case -ERFKILL: + return MGMT_STATUS_RFKILLED; } return MGMT_STATUS_FAILED; @@ -3238,7 +3243,7 @@ static int unpair_device(struct sock *sk, struct hci_dev *hdev, void *data, /* Defer clearing up the connection parameters until closing to * give a chance of keeping them if a repairing happens. */ - set_bit(HCI_CONN_PARAM_REMOVAL_PEND, &conn->flags); + set_bit(HCI_CONN_PARAM_REMOVAL_PEND, conn->flags); /* Disable auto-connection parameters if present */ params = hci_conn_params_lookup(hdev, &cp->addr.bdaddr, addr_type); @@ -3413,7 +3418,7 @@ static int get_connections(struct sock *sk, struct hci_dev *hdev, void *data, i = 0; list_for_each_entry(c, &hdev->conn_hash.list, list) { - if (test_bit(HCI_CONN_MGMT_CONNECTED, &c->flags)) + if (test_bit(HCI_CONN_MGMT_CONNECTED, c->flags)) i++; } @@ -3425,7 +3430,7 @@ static int get_connections(struct sock *sk, struct hci_dev *hdev, void *data, i = 0; list_for_each_entry(c, &hdev->conn_hash.list, list) { - if (!test_bit(HCI_CONN_MGMT_CONNECTED, &c->flags)) + if (!test_bit(HCI_CONN_MGMT_CONNECTED, c->flags)) continue; bacpy(&rp->addr[i].bdaddr, &c->dst); rp->addr[i].type = link_to_bdaddr(c->type, c->dst_type); @@ -3625,7 +3630,7 @@ static int pairing_complete(struct mgmt_pending_cmd *cmd, u8 status) /* The device is paired so there is no need to remove * its connection parameters anymore. */ - clear_bit(HCI_CONN_PARAM_REMOVAL_PEND, &conn->flags); + clear_bit(HCI_CONN_PARAM_REMOVAL_PEND, conn->flags); hci_conn_put(conn); @@ -5689,8 +5694,18 @@ static void mgmt_remove_adv_monitor_complete(struct hci_dev *hdev, struct mgmt_pending_cmd *cmd = data; struct mgmt_cp_remove_adv_monitor *cp; - if (status == -ECANCELED) + /* Reply to a cancelled command so bluetoothd's serialised mgmt queue + * is not blocked. + */ + if (status == -ECANCELED) { + cp = cmd->param; + rp.monitor_handle = cp->monitor_handle; + + mgmt_cmd_complete(cmd->sk, cmd->hdev->id, cmd->opcode, + mgmt_status(status), &rp, sizeof(rp)); + mgmt_pending_free(cmd); return; + } hci_dev_lock(hdev); @@ -6303,12 +6318,29 @@ static void stop_discovery_complete(struct hci_dev *hdev, void *data, int err) bt_dev_dbg(hdev, "err %d", err); + hci_dev_lock(hdev); + + /* Change the state before replying, so that a client acting on the + * reply sees it, and only while the discovery is still stopping, as + * Inquiry Cancel may already have stopped it and a new Start Discovery + * may have followed. Go back to DISCOVERY_FINDING when stopping failed + * while the inquiry or the active LE scan of the discovery is still + * running, so that it can be stopped again. + */ + if (hdev->discovery.state == DISCOVERY_STOPPING) { + if (err && (test_bit(HCI_INQUIRY, &hdev->flags) || + (hci_dev_test_flag(hdev, HCI_LE_SCAN) && + hdev->le_scan_type == LE_SCAN_ACTIVE))) + hci_discovery_set_state(hdev, DISCOVERY_FINDING); + else + hci_discovery_set_state(hdev, DISCOVERY_STOPPED); + } + + hci_dev_unlock(hdev); + mgmt_cmd_complete(cmd->sk, cmd->hdev->id, cmd->opcode, mgmt_status(err), cmd->param, 1); mgmt_pending_free(cmd); - - if (!err) - hci_discovery_set_state(hdev, DISCOVERY_STOPPED); } static int stop_discovery_sync(struct hci_dev *hdev, void *data) @@ -8160,7 +8192,11 @@ static int load_conn_param(struct sock *sk, struct hci_dev *hdev, void *data, hci_dev_lock(hdev); - if (param_count > 1) + /* A single entry may be an update for one device, so keep the other + * disabled parameters then, but clear them otherwise, including when + * no entries are loaded. + */ + if (param_count != 1) hci_conn_params_clear_disabled(hdev); for (i = 0; i < param_count; i++) { @@ -10115,7 +10151,7 @@ void mgmt_device_connected(struct hci_dev *hdev, struct hci_conn *conn, u16 eir_len = 0; u32 flags = 0; - if (test_and_set_bit(HCI_CONN_MGMT_CONNECTED, &conn->flags)) + if (test_and_set_bit(HCI_CONN_MGMT_CONNECTED, conn->flags)) return; /* allocate buff for LE or BR/EDR adv */ @@ -10158,6 +10194,14 @@ void mgmt_device_connected(struct hci_dev *hdev, struct hci_conn *conn, ev->eir_len = cpu_to_le16(eir_len); mgmt_event_skb(skb, NULL); + + /* Connections that negotiated encryption as part of setup (e.g. via + * an existing link key) had their security level change suppressed + * since userspace did not know about them yet, so report it now. + * Unencrypted connections have no change to report. + */ + if (test_bit(HCI_CONN_ENCRYPT, conn->flags)) + mgmt_security_level_changed(conn); } static void unpair_device_rsp(struct mgmt_pending_cmd *cmd, void *data) @@ -10264,7 +10308,11 @@ void mgmt_connect_failed(struct hci_dev *hdev, struct hci_conn *conn, u8 status) { struct mgmt_ev_connect_failed ev; - if (test_and_clear_bit(HCI_CONN_MGMT_CONNECTED, &conn->flags)) { + /* Only peek at the flag here: hci_conn_del() (via hci_conn_unlink()) + * still needs it set to know whether to report the security level + * reset, so it is consumed there instead of here. + */ + if (test_bit(HCI_CONN_MGMT_CONNECTED, conn->flags)) { mgmt_device_disconnected(hdev, &conn->dst, conn->type, conn->dst_type, hci_to_mgmt_reason(status), true); @@ -10898,6 +10946,57 @@ void mgmt_device_found(struct hci_dev *hdev, bdaddr_t *bdaddr, u8 link_type, mgmt_adv_monitor_device_found(hdev, bdaddr, report_device, skb, NULL); } +void mgmt_security_level_changed(struct hci_conn *conn) +{ + struct mgmt_ev_security_level_changed *ev; + struct mgmt_tlv *tlv; + u8 *tlv_data; + u8 tlv_len; + + if (!test_bit(HCI_CONN_MGMT_CONNECTED, conn->flags)) + return; + + /* Only ACL, LE and BIS links are tracked as mgmt connections, so + * restrict the event to those link types. Other transports (SCO, + * CIS, PA sync, ...) share the parent's address and would otherwise + * report a spurious security level change for it. + */ + if (conn->type != ACL_LINK && conn->type != LE_LINK && + conn->type != BIS_LINK) + return; + + tlv_len = 2 * (sizeof(*tlv) + sizeof(__u8)); + ev = kzalloc_flex(*ev, tlv_data, tlv_len, GFP_KERNEL); + if (!ev) + return; + + bacpy(&ev->addr.bdaddr, &conn->dst); + ev->addr.type = link_to_bdaddr(conn->type, conn->dst_type); + ev->tlv_length = tlv_len; + + tlv_data = ev->tlv_data; + tlv = (void *)tlv_data; + tlv->type = cpu_to_le16(MGMT_SEC_LEVEL_CHANGED_PARAM_LEVEL); + tlv->length = sizeof(__u8); + tlv->value[0] = conn->sec_level; + + tlv_data += sizeof(*tlv) + sizeof(__u8); + tlv = (void *)tlv_data; + tlv->type = cpu_to_le16(MGMT_SEC_LEVEL_CHANGED_PARAM_ENC_TYPE); + tlv->length = sizeof(__u8); + if (!test_bit(HCI_CONN_ENCRYPT, conn->flags)) + tlv->value[0] = MGMT_CONN_SEC_ENCRYPT_NONE; + else if (test_bit(HCI_CONN_AES_CCM, conn->flags)) + tlv->value[0] = MGMT_CONN_SEC_ENCRYPT_AES_CCM; + else + tlv->value[0] = MGMT_CONN_SEC_ENCRYPT_E0; + + mgmt_event(MGMT_EV_SECURITY_LEVEL_CHANGED, conn->hdev, ev, + struct_size(ev, tlv_data, tlv_len), NULL); + + kfree(ev); +} + void mgmt_remote_name(struct hci_dev *hdev, bdaddr_t *bdaddr, u8 link_type, u8 addr_type, s8 rssi, u8 *name, u8 name_len) { diff --git a/net/bluetooth/rfcomm/core.c b/net/bluetooth/rfcomm/core.c index 54ec1136f87e..8a4205347c4a 100644 --- a/net/bluetooth/rfcomm/core.c +++ b/net/bluetooth/rfcomm/core.c @@ -1740,10 +1740,8 @@ static int rfcomm_recv_msc(struct rfcomm_session *s, int cr, struct sk_buff *skb return 0; if (cr) { - if (msc->v24_sig & RFCOMM_V24_FC && !d->cfc) - set_bit(RFCOMM_TX_THROTTLED, &d->flags); - else - clear_bit(RFCOMM_TX_THROTTLED, &d->flags); + assign_bit(RFCOMM_TX_THROTTLED, &d->flags, + msc->v24_sig & RFCOMM_V24_FC && !d->cfc); rfcomm_dlc_lock(d); diff --git a/net/bluetooth/rfcomm/sock.c b/net/bluetooth/rfcomm/sock.c index b26918dc9e9e..3fb8b5474948 100644 --- a/net/bluetooth/rfcomm/sock.c +++ b/net/bluetooth/rfcomm/sock.c @@ -724,10 +724,7 @@ static int rfcomm_sock_setsockopt(struct socket *sock, int level, int optname, if (err) break; - if (opt) - set_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags); - else - clear_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags); + assign_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags, opt); break; diff --git a/net/bluetooth/sco.c b/net/bluetooth/sco.c index f4a20d7b5f9c..8be48ca9f4c5 100644 --- a/net/bluetooth/sco.c +++ b/net/bluetooth/sco.c @@ -1037,10 +1037,7 @@ static int sco_sock_setsockopt(struct socket *sock, int level, int optname, if (err) break; - if (opt) - set_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags); - else - clear_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags); + assign_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags, opt); break; case BT_VOICE: @@ -1080,10 +1077,7 @@ static int sco_sock_setsockopt(struct socket *sock, int level, int optname, if (err) break; - if (opt) - set_bit(BT_SK_PKT_STATUS, &bt_sk(sk)->flags); - else - clear_bit(BT_SK_PKT_STATUS, &bt_sk(sk)->flags); + assign_bit(BT_SK_PKT_STATUS, &bt_sk(sk)->flags, opt); break; case BT_CODEC: diff --git a/net/bluetooth/smp.c b/net/bluetooth/smp.c index 81d255525fe0..4af7fa7f4a8e 100644 --- a/net/bluetooth/smp.c +++ b/net/bluetooth/smp.c @@ -982,12 +982,12 @@ static u8 smp_random(struct smp_chan *smp) smp_s1(smp->tk, smp->rrnd, smp->prnd, stk); - if (test_and_set_bit(HCI_CONN_ENCRYPT_PEND, &hcon->flags)) + if (test_and_set_bit(HCI_CONN_ENCRYPT_PEND, hcon->flags)) return SMP_UNSPECIFIED; hci_le_start_enc(hcon, ediv, rand, stk, smp->enc_key_size); hcon->enc_key_size = smp->enc_key_size; - set_bit(HCI_CONN_STK_ENCRYPT, &hcon->flags); + set_bit(HCI_CONN_STK_ENCRYPT, hcon->flags); } else { u8 stk[16], auth; __le64 rand = 0; @@ -1026,7 +1026,7 @@ static void smp_notify_keys(struct l2cap_conn *conn) persistent = false; else persistent = !test_bit(HCI_CONN_FLUSH_KEY, - &hcon->flags); + hcon->flags); } else { /* The LTKs, IRKs and CSRKs should be persistent only if * both sides had the bonding bit set in their @@ -1184,9 +1184,13 @@ static void sc_generate_ltk(struct smp_chan *smp) struct hci_conn *hcon = smp->conn->hcon; struct hci_dev *hdev = hcon->hdev; struct link_key *key; + int err; + + rcu_read_lock(); key = hci_find_link_key(hdev, &hcon->dst); if (!key) { + rcu_read_unlock(); bt_dev_err(hdev, "no Link Key found to generate LTK"); return; } @@ -1198,16 +1202,19 @@ static void sc_generate_ltk(struct smp_chan *smp) /* SALT = 0x000000000000000000000000746D7032 */ const u8 salt[16] = { 0x32, 0x70, 0x6d, 0x74 }; - if (smp_h7(key->val, salt, smp->tk)) - return; + err = smp_h7(key->val, salt, smp->tk); } else { /* From core spec. Spells out in ASCII as 'tmp2'. */ const u8 tmp2[4] = { 0x32, 0x70, 0x6d, 0x74 }; - if (smp_h6(key->val, tmp2, smp->tk)) - return; + err = smp_h6(key->val, tmp2, smp->tk); } + rcu_read_unlock(); + + if (err) + return; + if (smp_h6(smp->tk, brle, smp->tk)) return; @@ -1751,7 +1758,7 @@ static u8 smp_cmd_pairing_req(struct l2cap_conn *conn, struct sk_buff *skb) /* SMP over BR/EDR requires special treatment */ if (conn->hcon->type == ACL_LINK) { /* We must have a BR/EDR SC link */ - if (!test_bit(HCI_CONN_AES_CCM, &conn->hcon->flags) && + if (!test_bit(HCI_CONN_AES_CCM, conn->hcon->flags) && !hci_dev_test_flag(hdev, HCI_FORCE_BREDR_SMP)) return SMP_CROSS_TRANSP_NOT_ALLOWED; @@ -2200,24 +2207,30 @@ static bool smp_ltk_encrypt(struct l2cap_conn *conn, u8 sec_level) { struct smp_ltk *key; struct hci_conn *hcon = conn->hcon; + bool ret = false; + + rcu_read_lock(); key = hci_find_ltk(hcon->hdev, &hcon->dst, hcon->dst_type, hcon->role); if (!key) - return false; + goto unlock; if (smp_ltk_sec_level(key) < sec_level) - return false; + goto unlock; - if (test_and_set_bit(HCI_CONN_ENCRYPT_PEND, &hcon->flags)) - return true; + ret = true; + if (test_and_set_bit(HCI_CONN_ENCRYPT_PEND, hcon->flags)) + goto unlock; hci_le_start_enc(hcon, key->ediv, key->rand, key->val, key->enc_size); hcon->enc_key_size = key->enc_size; /* We never store STKs for initiator role, so clear this flag */ - clear_bit(HCI_CONN_STK_ENCRYPT, &hcon->flags); + clear_bit(HCI_CONN_STK_ENCRYPT, hcon->flags); - return true; +unlock: + rcu_read_unlock(); + return ret; } bool smp_sufficient_security(struct hci_conn *hcon, u8 sec_level, @@ -2233,7 +2246,7 @@ bool smp_sufficient_security(struct hci_conn *hcon, u8 sec_level, * don't have an LTK (e.g. because of key distribution bits). */ if (key_pref == SMP_USE_LTK && - test_bit(HCI_CONN_STK_ENCRYPT, &hcon->flags) && + test_bit(HCI_CONN_STK_ENCRYPT, hcon->flags) && hci_find_ltk(hcon->hdev, &hcon->dst, hcon->dst_type, hcon->role)) return false; @@ -3082,11 +3095,11 @@ static void bredr_pairing(struct l2cap_chan *chan) bt_dev_dbg(hdev, "chan %p", chan); /* Only new pairings are interesting */ - if (!test_bit(HCI_CONN_NEW_LINK_KEY, &hcon->flags)) + if (!test_bit(HCI_CONN_NEW_LINK_KEY, hcon->flags)) return; /* Don't bother if we're not encrypted */ - if (!test_bit(HCI_CONN_ENCRYPT, &hcon->flags)) + if (!test_bit(HCI_CONN_ENCRYPT, hcon->flags)) return; /* Only initiator may initiate SMP over BR/EDR */ @@ -3098,7 +3111,7 @@ static void bredr_pairing(struct l2cap_chan *chan) return; /* BR/EDR must use Secure Connections for SMP */ - if (!test_bit(HCI_CONN_AES_CCM, &hcon->flags) && + if (!test_bit(HCI_CONN_AES_CCM, hcon->flags) && !hci_dev_test_flag(hdev, HCI_FORCE_BREDR_SMP)) return; @@ -3147,7 +3160,7 @@ static void smp_resume_cb(struct l2cap_chan *chan) if (!smp) return; - if (!test_bit(HCI_CONN_ENCRYPT, &hcon->flags)) + if (!test_bit(HCI_CONN_ENCRYPT, hcon->flags)) return; cancel_delayed_work(&smp->security_timer); @@ -3170,7 +3183,7 @@ static void smp_ready_cb(struct l2cap_chan *chan) */ conn->smp = chan; - if (hcon->type == ACL_LINK && test_bit(HCI_CONN_ENCRYPT, &hcon->flags)) + if (hcon->type == ACL_LINK && test_bit(HCI_CONN_ENCRYPT, hcon->flags)) bredr_pairing(chan); } diff --git a/net/bpf/test_run.c b/net/bpf/test_run.c index 3043a7393c29..d6c9dc62182e 100644 --- a/net/bpf/test_run.c +++ b/net/bpf/test_run.c @@ -1210,7 +1210,8 @@ int bpf_prog_test_run_skb(struct bpf_prog *prog, const union bpf_attr *kattr, skb->ip_summed = CHECKSUM_COMPLETE; } - if (prog->type == BPF_PROG_TYPE_LWT_XMIT) { + if (prog->type == BPF_PROG_TYPE_LWT_IN || + prog->type == BPF_PROG_TYPE_LWT_XMIT) { if (!ipv6_mod_enabled()) { pr_warn_once("Please test this program with IPv6 enabled kernel\n"); ret = -EOPNOTSUPP; diff --git a/net/bridge/br_arp_nd_proxy.c b/net/bridge/br_arp_nd_proxy.c index 87a40e2f1c50..985ed43f7e30 100644 --- a/net/bridge/br_arp_nd_proxy.c +++ b/net/bridge/br_arp_nd_proxy.c @@ -262,6 +262,7 @@ static void br_nd_send(struct net_bridge *br, struct net_bridge_port *p, struct sk_buff *reply; struct ipv6hdr *pip6; int na_olen = 8; /* opt hdr + ETH_ALEN for target */ + int headroom; int ns_olen; u8 *daddr; bool dad; @@ -271,7 +272,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); @@ -280,7 +282,7 @@ static void br_nd_send(struct net_bridge *br, struct net_bridge_port *p, reply->protocol = htons(ETH_P_IPV6); reply->dev = dev; - skb_reserve(reply, LL_RESERVED_SPACE(dev)); + skb_reserve(reply, headroom); skb_push(reply, sizeof(struct ethhdr)); skb_set_mac_header(reply, 0); diff --git a/net/bridge/br_if.c b/net/bridge/br_if.c index c52613431f88..45642b6a5866 100644 --- a/net/bridge/br_if.c +++ b/net/bridge/br_if.c @@ -340,13 +340,13 @@ static void del_nbp(struct net_bridge_port *p) nbp_delete_promisc(p); + br_mrp_port_del(br, p); + br_cfm_port_del(br, p); + spin_lock_bh(&br->lock); br_stp_disable_port(p); spin_unlock_bh(&br->lock); - br_mrp_port_del(br, p); - br_cfm_port_del(br, p); - br_ifinfo_notify(RTM_DELLINK, NULL, p); list_del_rcu(&p->list); diff --git a/net/bridge/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 6ebba16aff1c..f5c7ca0f58b9 100644 --- a/net/core/dev.c +++ b/net/core/dev.c @@ -129,7 +129,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -4103,6 +4105,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)) @@ -6967,16 +6981,22 @@ static void __skb_defer_free_flush(struct skb_defer_node *sdn, int budget) { struct llist_node *free_list; struct sk_buff *skb, *next; + long n = 0; if (llist_empty(&sdn->defer_list)) return; - atomic_long_set(&sdn->defer_count, 0); free_list = llist_del_all(&sdn->defer_list); llist_for_each_entry_safe(skb, next, free_list, ll_node) { prefetch(next); napi_consume_skb(skb, budget); + n++; } + /* Subtract exactly what was drained. Never store an absolute value: + * mixing one with the relative updates in skb_attempt_defer_free() + * lets the counter go negative, and it is read as unsigned there. + */ + atomic_long_sub(n, &sdn->defer_count); } void skb_defer_node_flush(struct skb_defer_node *sdn) @@ -10987,6 +11007,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, @@ -11870,6 +11898,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; } @@ -11879,10 +11908,18 @@ void netdev_run_todo(void) linkwatch_sync_dev(dev); } + if (!list_empty(&list)) { + rt_flush_dev(NULL); + rt6_uncached_list_flush_dev(NULL); + } + 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); @@ -11903,6 +11940,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); @@ -13347,6 +13386,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 @@ -13388,6 +13438,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 0ad1507759de..30bbd0c20a04 100644 --- a/net/core/filter.c +++ b/net/core/filter.c @@ -3369,6 +3369,10 @@ static const struct bpf_func_proto bpf_skb_vlan_pop_proto = { static int bpf_skb_generic_push(struct sk_buff *skb, u32 off, u32 len) { + /* The bytes in front of @off are moved with skb->data. */ + if (unlikely(off > skb->len || !pskb_may_pull(skb, off))) + return -ENOMEM; + /* Caller already did skb_cow() with meta_len+len as headroom, * so no need to do it here. */ @@ -3389,9 +3393,10 @@ static int bpf_skb_generic_pop(struct sk_buff *skb, u32 off, u32 len) void *old_data; /* skb_ensure_writable() is not needed here, as we're - * already working on an uncloned skb. + * already working on an uncloned skb. The first test + * keeps off + len from wrapping. */ - if (unlikely(!pskb_may_pull(skb, off + len))) + if (unlikely(off > skb->len || !pskb_may_pull(skb, off + len))) return -ENOMEM; old_data = skb->data; @@ -3402,9 +3407,25 @@ static int bpf_skb_generic_pop(struct sk_buff *skb, u32 off, u32 len) return 0; } +/* + * bpf_skb_net_hdr_push() inserts bytes at @off, bpf_skb_net_hdr_pop() removes + * bytes at @off. Both move the bytes in front of @off together with skb->data, + * and leave the rest of the packet where it is. Return true if the transport + * header is in the part that moves. A transport header that is equal to the + * network header stays equal to it. + */ +static bool bpf_skb_trans_hdr_moves(const struct sk_buff *skb, u32 off) +{ + if (skb->transport_header == skb->network_header) + return true; + + return skb_transport_header_was_set(skb) && + (u32)skb_transport_offset(skb) < off; +} + static int bpf_skb_net_hdr_push(struct sk_buff *skb, u32 off, u32 len) { - bool trans_same = skb->transport_header == skb->network_header; + bool trans_moves = bpf_skb_trans_hdr_moves(skb, off); int ret; /* There's no need for __skb_push()/__skb_pull() pair to @@ -3415,8 +3436,8 @@ static int bpf_skb_net_hdr_push(struct sk_buff *skb, u32 off, u32 len) if (likely(!ret)) { skb->mac_header -= len; skb->network_header -= len; - if (trans_same) - skb->transport_header = skb->network_header; + if (trans_moves) + skb->transport_header -= len; } return ret; @@ -3424,7 +3445,7 @@ static int bpf_skb_net_hdr_push(struct sk_buff *skb, u32 off, u32 len) static int bpf_skb_net_hdr_pop(struct sk_buff *skb, u32 off, u32 len) { - bool trans_same = skb->transport_header == skb->network_header; + bool trans_moves = bpf_skb_trans_hdr_moves(skb, off); int ret; /* Same here, __skb_push()/__skb_pull() pair not needed. */ @@ -3432,8 +3453,17 @@ static int bpf_skb_net_hdr_pop(struct sk_buff *skb, u32 off, u32 len) if (likely(!ret)) { skb->mac_header += len; skb->network_header += len; - if (trans_same) - skb->transport_header = skb->network_header; + if (trans_moves) { + skb->transport_header += len; + } else if (skb_transport_header_was_set(skb) && + skb_transport_offset(skb) < (int)off) { + /* It was in the removed bytes or before skb->data. */ + skb_set_transport_header(skb, off); + } + /* Do not leave the inner transport header in front of @off. */ + if (skb->encapsulation && + skb_inner_transport_offset(skb) < (int)off) + skb_set_inner_transport_header(skb, off); } return ret; @@ -3744,6 +3774,25 @@ static int bpf_skb_net_grow(struct sk_buff *skb, u32 off, u32 len_diff, return 0; } +/* + * Code that went by the inner transport header while skb->encapsulation was set + * goes by the transport header from now on. So take the inner one over, unless + * it is the smaller one, as it is if nobody has set it. Do not leave the result + * in front of @off, where the bytes were removed. + */ +static void bpf_skb_clear_encap(struct sk_buff *skb, u32 off) +{ + int thoff; + + if (!skb->encapsulation) + return; + + thoff = max(skb->inner_transport_header, skb->transport_header) - + skb_headroom(skb); + skb_set_transport_header(skb, max_t(int, thoff, off)); + skb->encapsulation = 0; +} + static int bpf_skb_net_shrink(struct sk_buff *skb, u32 off, u32 len_diff, u64 flags) { @@ -3762,6 +3811,14 @@ static int bpf_skb_net_shrink(struct sk_buff *skb, u32 off, u32 len_diff, return -ENOTSUPP; } + /* + * The MSS is raised by len_diff. It has 16 bits, and GSO_BY_FRAGS is + * not a size. + */ + if (skb_is_gso(skb) && !(flags & BPF_F_ADJ_ROOM_FIXED_GSO) && + skb_shinfo(skb)->gso_size + len_diff >= GSO_BY_FRAGS) + return -ENOTSUPP; + ret = skb_unclone(skb, GFP_ATOMIC); if (unlikely(ret < 0)) return ret; @@ -3817,8 +3874,7 @@ static int bpf_skb_net_shrink(struct sk_buff *skb, u32 off, u32 len_diff, SKB_GSO_IPXIP4 | SKB_GSO_IPXIP6 | SKB_GSO_ESP))) - if (skb->encapsulation) - skb->encapsulation = 0; + bpf_skb_clear_encap(skb, off); } /* Header must be checked, and gso_segs recomputed. */ @@ -3826,10 +3882,9 @@ static int bpf_skb_net_shrink(struct sk_buff *skb, u32 off, u32 len_diff, shinfo->gso_segs = 0; } else { /* For non-GSO packets, clear encapsulation if decap flags are set */ - if ((flags & (BPF_F_ADJ_ROOM_DECAP_L4_MASK | - BPF_F_ADJ_ROOM_DECAP_IPXIP_MASK)) && - skb->encapsulation) - skb->encapsulation = 0; + if (flags & (BPF_F_ADJ_ROOM_DECAP_L4_MASK | + BPF_F_ADJ_ROOM_DECAP_IPXIP_MASK)) + bpf_skb_clear_encap(skb, off); } return 0; @@ -5597,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; @@ -6132,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; @@ -6916,14 +6972,22 @@ static int bpf_push_seg6_encap(struct sk_buff *skb, u32 type, void *hdr, u32 len int err; struct ipv6_sr_hdr *srh = (struct ipv6_sr_hdr *)hdr; + /* With ipv6.disable=1 the netns has no seg6 data and no IPv6 tables. */ + if (!ipv6_mod_enabled()) + return -EAFNOSUPPORT; + if (!seg6_validate_srh(srh, len, false)) return -EINVAL; + /* + * The encap mode names IPv6 as the inner protocol, and neither mode + * updates skb->protocol. + */ + if (skb->protocol != htons(ETH_P_IPV6)) + return -EBADMSG; + switch (type) { case BPF_LWT_ENCAP_SEG6_INLINE: - if (skb->protocol != htons(ETH_P_IPV6)) - return -EBADMSG; - err = seg6_do_srh_inline(skb, srh); break; case BPF_LWT_ENCAP_SEG6: @@ -7012,12 +7076,13 @@ BPF_CALL_4(bpf_lwt_seg6_store_bytes, struct sk_buff *, skb, u32, offset, this_cpu_ptr(&seg6_bpf_srh_states); struct ipv6_sr_hdr *srh = srh_state->srh; void *srh_tlvs, *srh_end, *ptr; - int srhoff = 0; + int srhoff; lockdep_assert_held(&srh_state->bh_lock); if (srh == NULL) return -EINVAL; + srhoff = (unsigned char *)srh - skb->data; srh_tlvs = (void *)((char *)srh + ((srh->first_segment + 1) << 4)); srh_end = (void *)((char *)srh + sizeof(*srh) + srh_state->hdrlen); @@ -7030,8 +7095,7 @@ BPF_CALL_4(bpf_lwt_seg6_store_bytes, struct sk_buff *, skb, u32, offset, if (unlikely(bpf_try_make_writable(skb, offset + len))) return -EFAULT; - if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0) - return -EINVAL; + /* The head may have moved. */ srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff); memcpy(skb->data + offset, from, len); @@ -7147,16 +7211,18 @@ BPF_CALL_3(bpf_lwt_seg6_adjust_srh, struct sk_buff *, skb, u32, offset, { struct seg6_bpf_srh_state *srh_state = this_cpu_ptr(&seg6_bpf_srh_states); + bool mac_set = skb_mac_header_was_set(skb); struct ipv6_sr_hdr *srh = srh_state->srh; void *srh_end, *srh_tlvs, *ptr; struct ipv6hdr *hdr; - int srhoff = 0; + int srhoff; int ret; lockdep_assert_held(&srh_state->bh_lock); if (unlikely(srh == NULL)) return -EINVAL; + srhoff = (unsigned char *)srh - skb->data; srh_tlvs = (void *)((unsigned char *)srh + sizeof(*srh) + ((srh->first_segment + 1) << 4)); srh_end = (void *)((unsigned char *)srh + sizeof(*srh) + @@ -7167,26 +7233,46 @@ BPF_CALL_3(bpf_lwt_seg6_adjust_srh, struct sk_buff *, skb, u32, offset, return -EFAULT; if (unlikely(len < 0 && (void *)((char *)ptr - len) > srh_end)) return -EFAULT; + /* The length field of the SRH has 8 bits, in units of 8 bytes. */ + if (unlikely(len > (U8_MAX << 3) - srh_state->hdrlen)) + return -EFAULT; + /* + * skb->data is the network header here. The MAC header is in front of + * it, so bpf_skb_net_hdr_push() and bpf_skb_net_hdr_pop() do not move + * it with the other headers. + */ if (len > 0) { - ret = skb_cow_head(skb, len); + ret = skb_cow_head(skb, len + skb->mac_len); if (unlikely(ret < 0)) return ret; + /* The push can write over the MAC header, so move it first. */ + if (mac_set) + memmove(skb->data - len - skb->mac_len, + skb_mac_header(skb), skb->mac_len); ret = bpf_skb_net_hdr_push(skb, offset, len); } else { ret = bpf_skb_net_hdr_pop(skb, offset, -1 * len); + /* The pop has added -len to skb->mac_header. */ + if (likely(!ret) && mac_set) + memmove(skb->data - skb->mac_len, + skb_mac_header(skb) + len, skb->mac_len); } bpf_compute_data_pointers(skb); if (unlikely(ret < 0)) return ret; + if (mac_set) + skb_set_mac_header(skb, -skb->mac_len); + else + skb_unset_mac_header(skb); + hdr = (struct ipv6hdr *)skb->data; hdr->payload_len = htons(skb->len - sizeof(struct ipv6hdr)); - if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0) - return -EINVAL; + /* The bytes in front of offset have moved together with skb->data. */ srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff); srh_state->hdrlen += len; srh_state->valid = false; diff --git a/net/core/gro.c b/net/core/gro.c index 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 @@ static enum gro_result dev_gro_receive(struct gro_node *gro, if (NAPI_GRO_CB(skb)->flush) goto normal; + /* Must be called before setting NAPI_GRO_CB(skb)->{age|last}. + * A held packet must have its headers in the linear part. + */ + if (unlikely(!gro_try_pull_from_frag0(skb))) + goto normal; + if (unlikely(gro_list->count >= MAX_GRO_SKBS)) gro_flush_oldest(gro, &gro_list->list); else gro_list->count++; - /* Must be called before setting NAPI_GRO_CB(skb)->{age|last} */ - gro_try_pull_from_frag0(skb); NAPI_GRO_CB(skb)->age = jiffies; NAPI_GRO_CB(skb)->last = skb; if (!skb_is_gso(skb)) diff --git a/net/core/lwt_bpf.c b/net/core/lwt_bpf.c index da49364ec63d..72c86ff2a847 100644 --- a/net/core/lwt_bpf.c +++ b/net/core/lwt_bpf.c @@ -85,6 +85,32 @@ static int run_lwt_bpf(struct sk_buff *skb, struct bpf_lwt_prog *lwt, return ret; } +/* + * skb->cb still describes the IP header that was the first one before the + * prog ran. The option offsets in IPCB(skb)->opt are wrong for a pushed + * header, and a header of the other family needs the other layout. iif + * stays: behind a VRF skb->skb_iif is the L3 master and not the port. + * bpf_lwt_push_encap() cannot do this, because bpf_prog_run_save_cb() can + * restore skb->cb after the prog. + */ +static void bpf_lwt_reset_cb(struct sk_buff *skb, __be16 proto) +{ + int iif; + + if (skb->protocol == proto) { + if (proto == htons(ETH_P_IP)) + memset(&IPCB(skb)->opt, 0, sizeof(IPCB(skb)->opt)); + } else if (skb->protocol == htons(ETH_P_IP)) { + iif = IP6CB(skb)->iif; + memset(IPCB(skb), 0, sizeof(*IPCB(skb))); + IPCB(skb)->iif = iif; + } else { + iif = IPCB(skb)->iif; + memset(IP6CB(skb), 0, sizeof(*IP6CB(skb))); + IP6CB(skb)->iif = iif; + } +} + static int bpf_lwt_input_reroute(struct sk_buff *skb) { enum skb_drop_reason reason; @@ -102,7 +128,7 @@ static int bpf_lwt_input_reroute(struct sk_buff *skb) dev_put(dev); } else if (skb->protocol == htons(ETH_P_IPV6)) { skb_dst_drop(skb); - if (IS_ENABLED(CONFIG_IPV6)) { + if (ipv6_mod_enabled()) { ip6_route_input(skb); err = skb_dst(skb)->error; } else { @@ -124,6 +150,8 @@ static int bpf_lwt_input_reroute(struct sk_buff *skb) static int bpf_input(struct sk_buff *skb) { struct dst_entry *dst = skb_dst(skb); + __be16 proto = skb->protocol; + unsigned int len = skb->len; struct bpf_lwt *bpf; int ret; @@ -132,8 +160,21 @@ static int bpf_input(struct sk_buff *skb) ret = run_lwt_bpf(skb, &bpf->in, dst, NO_REDIRECT); if (ret < 0) return ret; + /* An lwt_in prog can change the length only with a push. */ + if (skb->len != len) + bpf_lwt_reset_cb(skb, proto); if (ret == BPF_LWT_REROUTE) return bpf_lwt_input_reroute(skb); + /* + * orig_input() is for the old protocol only, see bpf_xmit(). + * It also needs a dst of the old family. BPF_LWT_ENCAP_SEG6 + * puts an IPv6 dst into the skb. + */ + if (skb->protocol != proto || + skb_dst(skb)->ops->family != dst->ops->family) { + kfree_skb(skb); + return -EINVAL; + } } if (unlikely(!dst->lwtstate->orig_input)) { @@ -304,13 +345,17 @@ static int bpf_xmit(struct sk_buff *skb) * made before LWT xmit. */ ret = xmit_check_headroom(skb, hroom); - if (unlikely(ret)) + if (unlikely(ret)) { + kfree_skb(skb); return ret; + } return LWTUNNEL_XMIT_CONTINUE; case BPF_REDIRECT: return LWTUNNEL_XMIT_DONE; case BPF_LWT_REROUTE: + /* An lwt_xmit prog can also write to the options. */ + bpf_lwt_reset_cb(skb, proto); return bpf_lwt_xmit_reroute(skb); default: return ret; @@ -649,6 +694,14 @@ int bpf_lwt_push_ip_encap(struct sk_buff *skb, void *hdr, u32 len, bool ingress) if (ingress) skb_postpush_rcsum(skb, iph, len); skb_reset_network_header(skb); + /* + * The new header goes over the MAC header. On ingress move it first. + * On egress the packet gets a new one, so forget the old one. + */ + if (ingress) + skb_mac_header_rebuild(skb); + else + skb_unset_mac_header(skb); if (is_udp_tunnel) { size_t iph_sz = ipv4 ? iph->ihl * 4 : sizeof(struct ipv6hdr); diff --git a/net/core/net_namespace.c b/net/core/net_namespace.c index 52c2bd44778a..c94718429771 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 @@ -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 512eddc0fc3d..e685964654df 100644 --- a/net/core/skbuff.c +++ b/net/core/skbuff.c @@ -966,6 +966,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); @@ -1504,6 +1505,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); } @@ -1917,6 +1922,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) { @@ -1937,12 +1943,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; } @@ -6192,7 +6204,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); } @@ -6299,6 +6311,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 * @@ -6310,7 +6347,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) { @@ -6318,7 +6356,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); @@ -6779,7 +6817,7 @@ int skb_mpls_dec_ttl(struct sk_buff *skb) lse = be32_to_cpu(mpls_hdr(skb)->label_stack_entry); ttl = (lse & MPLS_LS_TTL_MASK) >> MPLS_LS_TTL_SHIFT; - if (!--ttl) + if (!ttl || !--ttl) return -EINVAL; lse &= ~MPLS_LS_TTL_MASK; @@ -7408,8 +7446,14 @@ nodefer: kfree_skb_napi_cache(skb); defer_max = READ_ONCE(net_hotdata.sysctl_skb_defer_max); defer_count = atomic_long_inc_return(&sdn->defer_count); - if (defer_count >= defer_max) + if (defer_count > defer_max) { + /* Undo the reservation. An llist_add() does not release one -- + * the skb stays charged until a flush subtracts the batch that + * contains it -- so a rejected free must undo its own. + */ + atomic_long_dec(&sdn->defer_count); goto nodefer; + } llist_add(&skb->ll_node, &sdn->defer_list); @@ -7418,8 +7462,13 @@ nodefer: kfree_skb_napi_cache(skb); return; } - /* Send an IPI every time queue reaches half capacity. */ - kick = (defer_count - 1) == (defer_max >> 1); + /* Half capacity, plus the skb that fills the queue. Equality alone can + * be consumed early -- if the producer holding the kick value publishes + * first, its purge drains only that skb and the reservations published + * after it match nothing -- which would leave a full queue with nothing + * pending. + */ + kick = (defer_count - 1) == (defer_max >> 1) || defer_count == defer_max; /* Make sure to trigger NET_RX_SOFTIRQ on the remote CPU * if we are unlucky enough (this seems very unlikely). diff --git a/net/core/sock.c b/net/core/sock.c index a74be1cc9302..f93ae40ef6bd 100644 --- a/net/core/sock.c +++ b/net/core/sock.c @@ -3357,7 +3357,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. */ @@ -3438,7 +3438,7 @@ int __sk_mem_raise_allocated(struct sock *sk, int size, int amt, int kind) 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 29948cb44b7d..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 #include #include #include @@ -124,10 +125,10 @@ static int reuseport_sock_index(struct sock *sk, static void __reuseport_add_sock(struct sock *sk, struct sock_reuseport *reuse) { - reuse->socks[reuse->num_socks] = sk; + WRITE_ONCE(reuse->socks[reuse->num_socks], sk); /* paired with smp_rmb() in reuseport_(select|migrate)_sock() */ smp_wmb(); - reuse->num_socks++; + WRITE_ONCE(reuse->num_socks, reuse->num_socks + 1); reuseport_get_incoming_cpu(sk, reuse); } @@ -139,8 +140,8 @@ static bool __reuseport_detach_sock(struct sock *sk, if (i == -1) return false; - reuse->socks[i] = reuse->socks[reuse->num_socks - 1]; - reuse->num_socks--; + WRITE_ONCE(reuse->socks[i], reuse->socks[reuse->num_socks - 1]); + WRITE_ONCE(reuse->num_socks, reuse->num_socks - 1); reuseport_put_incoming_cpu(sk, reuse); return true; @@ -149,7 +150,7 @@ static bool __reuseport_detach_sock(struct sock *sk, static void __reuseport_add_closed_sock(struct sock *sk, struct sock_reuseport *reuse) { - reuse->socks[reuse->max_socks - reuse->num_closed_socks - 1] = sk; + WRITE_ONCE(reuse->socks[reuse->max_socks - reuse->num_closed_socks - 1], sk); /* paired with READ_ONCE() in inet_csk_bind_conflict() */ WRITE_ONCE(reuse->num_closed_socks, reuse->num_closed_socks + 1); reuseport_get_incoming_cpu(sk, reuse); @@ -163,7 +164,8 @@ static bool __reuseport_detach_closed_sock(struct sock *sk, if (i == -1) return false; - reuse->socks[i] = reuse->socks[reuse->max_socks - reuse->num_closed_socks]; + WRITE_ONCE(reuse->socks[i], + reuse->socks[reuse->max_socks - reuse->num_closed_socks]); /* paired with READ_ONCE() in inet_csk_bind_conflict() */ WRITE_ONCE(reuse->num_closed_socks, reuse->num_closed_socks - 1); reuseport_put_incoming_cpu(sk, reuse); @@ -521,7 +523,7 @@ static struct sock *run_bpf_filter(struct sock_reuseport *reuse, u16 socks, if (index >= socks) return NULL; - return reuse->socks[index]; + return READ_ONCE(reuse->socks[index]); } static struct sock *reuseport_select_sock_by_hash(struct sock_reuseport *reuse, @@ -532,7 +534,7 @@ static struct sock *reuseport_select_sock_by_hash(struct sock_reuseport *reuse, i = j = reciprocal_scale(hash, num_socks); do { - struct sock *sk = reuse->socks[i]; + struct sock *sk = READ_ONCE(reuse->socks[i]); if (sk->sk_state != TCP_ESTABLISHED) { /* Paired with WRITE_ONCE() in __reuseport_(get|put)_incoming_cpu(). */ @@ -691,6 +693,14 @@ int reuseport_attach_prog(struct sock *sk, struct bpf_prog *prog) if (!sk->sk_reuseport) return -EINVAL; + /* Do not put a shutdown()ed TCP listener back into the + * listening section of a reuseport group while it is in + * TCP_CLOSE: requests can still migrate to it. + */ + if (sk_is_tcp(sk) && + inet_csk(sk)->unhashed_state == TCP_LISTEN) + return -EINVAL; + err = reuseport_alloc(sk, false); if (err) return err; diff --git a/net/ipv4/af_inet.c b/net/ipv4/af_inet.c index 14ce01092fda..bc3bbb2366d8 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/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 248514dce0cd..e2d9b25950cf 100644 --- a/net/ipv4/fib_trie.c +++ b/net/ipv4/fib_trie.c @@ -61,6 +61,7 @@ #include #include #include +#include #include #include #include @@ -961,6 +962,8 @@ static struct key_vector *fib_find_node(struct trie *t, break; } + index = array_index_nospec(index, 1ul << n->bits); + /* keep searching until we find a perfect match leaf or NULL */ } while (IS_TNODE(n)); @@ -1466,6 +1469,8 @@ int fib_table_lookup(struct fib_table *tb, const struct flowi4 *flp, if (IS_LEAF(n)) goto found; + index = array_index_nospec(index, 1ul << n->bits); + /* only record pn and cindex if we are going to be chopping * bits later. Otherwise we are just wasting cycles. */ @@ -1766,6 +1771,8 @@ static struct key_vector *leaf_walk_rcu(struct key_vector **tn, t_key key) if (cindex >> pn->bits) break; + cindex = array_index_nospec(cindex, 1ul << pn->bits); + /* descend into the next child */ n = get_child_rcu(pn, cindex++); if (!n) @@ -1787,6 +1794,8 @@ static struct key_vector *leaf_walk_rcu(struct key_vector **tn, t_key key) continue; } + cindex = array_index_nospec(cindex, 1ul << pn->bits); + /* grab the next available node */ n = get_child_rcu(pn, cindex++); if (!n) @@ -2431,7 +2440,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..bff4dc488def 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; @@ -1059,6 +1071,9 @@ static int fou_build_header(struct sk_buff *skb, struct ip_tunnel_encap *e, __be16 sport; int err; + if (skb_cow_head(skb, fou_encap_hlen(e))) + return -ENOMEM; + err = __fou_build_header(skb, e, protocol, &sport, type); if (err) return err; @@ -1071,16 +1086,24 @@ static int fou_build_header(struct sk_buff *skb, struct ip_tunnel_encap *e, static int gue_build_header(struct sk_buff *skb, struct ip_tunnel_encap *e, u8 *protocol, struct flowi4 *fl4) { - int type = e->flags & TUNNEL_ENCAP_FLAG_CSUM ? SKB_GSO_UDP_TUNNEL_CSUM : - SKB_GSO_UDP_TUNNEL; + struct ip_tunnel_encap encap = { + .flags = READ_ONCE(e->flags), + .sport = READ_ONCE(e->sport), + .dport = READ_ONCE(e->dport), + }; + int type = encap.flags & TUNNEL_ENCAP_FLAG_CSUM ? + SKB_GSO_UDP_TUNNEL_CSUM : SKB_GSO_UDP_TUNNEL; __be16 sport; int err; - err = __gue_build_header(skb, e, protocol, &sport, type); + if (skb_cow_head(skb, gue_encap_hlen(&encap))) + return -ENOMEM; + + err = __gue_build_header(skb, &encap, protocol, &sport, type); if (err) return err; - fou_build_udp(skb, e, fl4, protocol, sport); + fou_build_udp(skb, &encap, fl4, protocol, sport); return 0; } diff --git a/net/ipv4/igmp.c b/net/ipv4/igmp.c index d56355aca797..4221f2b9c658 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 71b0c344579f..ca3057192e6d 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; @@ -1262,6 +1262,7 @@ struct sock *inet_csk_clone_lock(const struct sock *sk, memset(&newicsk->icsk_accept_queue, 0, sizeof(newicsk->icsk_accept_queue)); + newicsk->unhashed_state = 0; inet_sk_set_state(newsk, TCP_SYN_RECV); inet_clone_ulp(req, newsk, priority); @@ -1532,17 +1533,15 @@ void inet_csk_listen_stop(struct sock *sk) if (!has_current_bpf_ctx()) cond_resched(); } - if (queue->fastopenq.rskq_rst_head) { - /* Free all the reqs queued in rskq_rst_head. */ - spin_lock_bh(&queue->fastopenq.lock); - req = queue->fastopenq.rskq_rst_head; - queue->fastopenq.rskq_rst_head = NULL; - spin_unlock_bh(&queue->fastopenq.lock); - while (req != NULL) { - next = req->dl_next; - reqsk_put(req); - req = next; - } + /* Free all the reqs queued in rskq_rst_head. */ + spin_lock_bh(&queue->fastopenq.lock); + req = queue->fastopenq.rskq_rst_head; + queue->fastopenq.rskq_rst_head = NULL; + spin_unlock_bh(&queue->fastopenq.lock); + while (req != NULL) { + next = req->dl_next; + reqsk_put(req); + req = next; } WARN_ON_ONCE(sk->sk_ack_backlog); } diff --git a/net/ipv4/inet_hashtables.c b/net/ipv4/inet_hashtables.c index 7ffa9171d6de..860145d810ed 100644 --- a/net/ipv4/inet_hashtables.c +++ b/net/ipv4/inet_hashtables.c @@ -804,6 +804,11 @@ int inet_hash(struct sock *sk) inet_init_ehash_secret(); WARN_ON(!sk_unhashed(sk)); + + if (unlikely(inet_csk(sk)->unhashed_state && + inet_csk(sk)->unhashed_state != TCP_LISTEN)) + return -EINVAL; + ilb2 = inet_lhash2_bucket_sk(hashinfo, sk); spin_lock(&ilb2->lock); @@ -833,6 +838,9 @@ void inet_unhash(struct sock *sk) return; sock_rps_delete_flow(sk); + + inet_csk(sk)->unhashed_state = sk->sk_state; + if (sk->sk_state == TCP_LISTEN) { struct inet_listen_hashbucket *ilb2; @@ -1059,6 +1067,9 @@ int __inet_hash_connect(struct inet_timewait_death_row *death_row, int ret, i, low, high; bool local_ports; + if (unlikely(inet_csk(sk)->unhashed_state == TCP_LISTEN)) + return -EINVAL; + if (port) { local_bh_disable(); ret = check_established(death_row, sk, port, NULL, false, diff --git a/net/ipv4/inet_timewait_sock.c b/net/ipv4/inet_timewait_sock.c index 74ff40d42e56..e256c55ce9f2 100644 --- a/net/ipv4/inet_timewait_sock.c +++ b/net/ipv4/inet_timewait_sock.c @@ -105,10 +105,12 @@ void inet_twsk_hashdance_schedule(struct inet_timewait_sock *tw, struct inet_hashinfo *hashinfo, int timeo) { - const struct inet_sock *inet = inet_sk(sk); - const struct inet_connection_sock *icsk = inet_csk(sk); spinlock_t *lock = inet_ehash_lockp(hashinfo, sk->sk_hash); + struct inet_connection_sock *icsk = inet_csk(sk); struct inet_bind_hashbucket *bhead, *bhead2; + const struct inet_sock *inet = inet_sk(sk); + + icsk->unhashed_state = sk->sk_state; /* Put TW into bind hash. Original socket stays there too. * Note, that any socket with inet->num != 0 MUST be bound in diff --git a/net/ipv4/ip_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 @@ static int __ip_append_data(struct sock *sk, */ skb->ip_summed = csummode; skb->csum = 0; - skb_reserve(skb, hh_len); + skb_reserve(skb, hh_len + exthdrlen); /* * Find where to start putting bytes. */ - data = skb_put(skb, fraglen + exthdrlen - pagedlen); - skb_set_network_header(skb, exthdrlen); + data = skb_put(skb, fraglen - pagedlen); + skb_reset_network_header(skb); skb->transport_header = (skb->network_header + fragheaderlen); - data += fragheaderlen + exthdrlen; + data += fragheaderlen; if (fraggap) { skb->csum = skb_copy_and_csum_bits( diff --git a/net/ipv4/ip_tunnel.c b/net/ipv4/ip_tunnel.c index 13b5e35e8790..d30edab7bba7 100644 --- a/net/ipv4/ip_tunnel.c +++ b/net/ipv4/ip_tunnel.c @@ -604,6 +604,7 @@ void ip_md_tunnel_xmit(struct sk_buff *skb, struct net_device *dev, if (ip_tunnel_encap(skb, &tun_info->encap, &proto, &fl4) < 0) goto tx_error; + inner_iph = (const struct iphdr *)skb_inner_network_header(skb); use_cache = ip_tunnel_dst_cache_usable(skb, tun_info); if (use_cache) @@ -747,6 +748,8 @@ void ip_tunnel_xmit(struct sk_buff *skb, struct net_device *dev, } tos = tnl_params->tos; + df = tnl_params->frag_off; + ttl = tnl_params->ttl; if (tos & 0x1) { tos &= ~0x1; if (payload_protocol == htons(ETH_P_IP)) { @@ -765,6 +768,7 @@ void ip_tunnel_xmit(struct sk_buff *skb, struct net_device *dev, if (ip_tunnel_encap(skb, &tunnel->encap, &protocol, &fl4) < 0) goto tx_error; + inner_iph = (const struct iphdr *)skb_inner_network_header(skb); if (connected && md) { use_cache = ip_tunnel_dst_cache_usable(skb, tun_info); @@ -797,7 +801,6 @@ void ip_tunnel_xmit(struct sk_buff *skb, struct net_device *dev, goto tx_error; } - df = tnl_params->frag_off; if (payload_protocol == htons(ETH_P_IP) && !tunnel->ignore_df) df |= (inner_iph->frag_off & htons(IP_DF)); @@ -819,7 +822,6 @@ void ip_tunnel_xmit(struct sk_buff *skb, struct net_device *dev, } tos = ip_tunnel_ecn_encap(tos, inner_iph, skb); - ttl = tnl_params->ttl; if (ttl == 0) { if (payload_protocol == htons(ETH_P_IP)) ttl = inner_iph->ttl; diff --git a/net/ipv4/ipmr.c b/net/ipv4/ipmr.c index 5bfbb8d88bf4..365cf1cf39f3 100644 --- a/net/ipv4/ipmr.c +++ b/net/ipv4/ipmr.c @@ -109,7 +109,8 @@ static void ip_mr_forward(struct net *net, struct mr_table *mrt, struct net_device *dev, struct sk_buff *skb, struct mfc_cache *cache, int local); static int ipmr_cache_report(const struct mr_table *mrt, - struct sk_buff *pkt, vifi_t vifi, int assert); + struct sk_buff *pkt, vifi_t vifi, int assert, + bool nl_query); static void mroute_netlink_event(struct mr_table *mrt, struct mfc_cache *mfc, int cmd); static void igmpmsg_netlink_event(const struct mr_table *mrt, struct sk_buff *pkt); @@ -561,7 +562,7 @@ static netdev_tx_t reg_vif_xmit(struct sk_buff *skb, struct net_device *dev) /* Pairs with WRITE_ONCE() in vif_add() and vif_delete() */ ipmr_cache_report(mrt, skb, READ_ONCE(mrt->mroute_reg_vif_num), - IGMPMSG_WHOLEPKT); + IGMPMSG_WHOLEPKT, false); rcu_read_unlock(); kfree_skb(skb); @@ -775,23 +776,21 @@ static void ipmr_destroy_unres(struct mr_table *mrt, struct mfc_cache *c) WRITE_ONCE(mrt->cache_resolve_queue_len, mrt->cache_resolve_queue_len - 1); - while ((skb = skb_dequeue(&c->_c.mfc_un.unres.unresolved))) { - if (ip_hdr(skb)->version == 0) { - struct nlmsghdr *nlh = skb_pull(skb, - sizeof(struct iphdr)); - nlh->nlmsg_type = NLMSG_ERROR; - nlh->nlmsg_len = nlmsg_msg_size(sizeof(struct nlmsgerr)); - skb_trim(skb, nlh->nlmsg_len); - e = nlmsg_data(nlh); - e->error = -ETIMEDOUT; - memset(&e->msg, 0, sizeof(e->msg)); + while ((skb = skb_dequeue(&c->_c.mfc_un.unres.nl_queries))) { + struct nlmsghdr *nlh = skb_pull(skb, sizeof(struct iphdr)); - rtnl_unicast(skb, net, NETLINK_CB(skb).portid); - } else { - kfree_skb(skb); - } + nlh->nlmsg_type = NLMSG_ERROR; + nlh->nlmsg_len = nlmsg_msg_size(sizeof(struct nlmsgerr)); + skb_trim(skb, nlh->nlmsg_len); + e = nlmsg_data(nlh); + e->error = -ETIMEDOUT; + memset(&e->msg, 0, sizeof(e->msg)); + + rtnl_unicast(skb, net, NETLINK_CB(skb).portid); } + skb_queue_purge(&c->_c.mfc_un.unres.unresolved); + ipmr_cache_free(c); } @@ -1021,6 +1020,7 @@ static struct mfc_cache *ipmr_cache_alloc_unres(void) if (c) { skb_queue_head_init(&c->_c.mfc_un.unres.unresolved); + skb_queue_head_init(&c->_c.mfc_un.unres.nl_queries); c->_c.mfc_un.unres.expires = jiffies + 10 * HZ; } return c; @@ -1033,31 +1033,29 @@ static void ipmr_cache_resolve(struct net *net, struct mr_table *mrt, struct sk_buff *skb; struct nlmsgerr *e; - /* Play the pending entries through our router */ - while ((skb = __skb_dequeue(&uc->_c.mfc_un.unres.unresolved))) { - if (ip_hdr(skb)->version == 0) { - struct nlmsghdr *nlh = skb_pull(skb, - sizeof(struct iphdr)); - - if (mr_fill_mroute(mrt, skb, &c->_c, - nlmsg_data(nlh)) > 0) { - nlh->nlmsg_len = skb_tail_pointer(skb) - - (u8 *)nlh; - } else { - nlh->nlmsg_type = NLMSG_ERROR; - nlh->nlmsg_len = nlmsg_msg_size(sizeof(struct nlmsgerr)); - skb_trim(skb, nlh->nlmsg_len); - e = nlmsg_data(nlh); - e->error = -EMSGSIZE; - memset(&e->msg, 0, sizeof(e->msg)); - } + /* Answer the pending netlink route queries */ + while ((skb = __skb_dequeue(&uc->_c.mfc_un.unres.nl_queries))) { + struct nlmsghdr *nlh = skb_pull(skb, sizeof(struct iphdr)); - rtnl_unicast(skb, net, NETLINK_CB(skb).portid); + if (mr_fill_mroute(mrt, skb, &c->_c, nlmsg_data(nlh)) > 0) { + nlh->nlmsg_len = skb_tail_pointer(skb) - (u8 *)nlh; } else { - rcu_read_lock(); - ip_mr_forward(net, mrt, skb->dev, skb, c, 0); - rcu_read_unlock(); + nlh->nlmsg_type = NLMSG_ERROR; + nlh->nlmsg_len = nlmsg_msg_size(sizeof(struct nlmsgerr)); + skb_trim(skb, nlh->nlmsg_len); + e = nlmsg_data(nlh); + e->error = -EMSGSIZE; + memset(&e->msg, 0, sizeof(e->msg)); } + + rtnl_unicast(skb, net, NETLINK_CB(skb).portid); + } + + /* Play the pending packets through our router */ + while ((skb = __skb_dequeue(&uc->_c.mfc_un.unres.unresolved))) { + rcu_read_lock(); + ip_mr_forward(net, mrt, skb->dev, skb, c, 0); + rcu_read_unlock(); } } @@ -1066,7 +1064,8 @@ static void ipmr_cache_resolve(struct net *net, struct mr_table *mrt, * Called under rcu_read_lock(). */ static int ipmr_cache_report(const struct mr_table *mrt, - struct sk_buff *pkt, vifi_t vifi, int assert) + struct sk_buff *pkt, vifi_t vifi, int assert, + bool nl_query) { unsigned char pkt_cb[sizeof(pkt->cb)]; const int ihl = ip_hdrlen(pkt); @@ -1136,7 +1135,7 @@ static int ipmr_cache_report(const struct mr_table *mrt, memset(skb->cb, 0, sizeof(skb->cb)); /* Route queries from ipmr_get_route() carry NETLINK_CB, not IPCB. */ - if (ip_hdr(pkt)->version) { + if (!nl_query) { memcpy(pkt_cb, pkt->cb, sizeof(pkt_cb)); ipv4_pktinfo_prepare(mroute_sk, pkt, false); *PKTINFO_SKB_CB(skb) = *PKTINFO_SKB_CB(pkt); @@ -1159,7 +1158,8 @@ static int ipmr_cache_report(const struct mr_table *mrt, /* Queue a packet for resolution. It gets locked cache entry! */ /* Called under rcu_read_lock() */ static int ipmr_cache_unresolved(struct mr_table *mrt, vifi_t vifi, - struct sk_buff *skb, struct net_device *dev) + struct sk_buff *skb, struct net_device *dev, + bool nl_query) { struct net *net = read_pnet(&mrt->net); const struct iphdr *iph = ip_hdr(skb); @@ -1196,7 +1196,8 @@ static int ipmr_cache_unresolved(struct mr_table *mrt, vifi_t vifi, c->mfc_mcastgrp = iph->daddr; /* Reflect first query at mrouted. */ - err = ipmr_cache_report(mrt, skb, vifi, IGMPMSG_NOCACHE); + err = ipmr_cache_report(mrt, skb, vifi, IGMPMSG_NOCACHE, + nl_query); if (err < 0) goto err; @@ -1211,7 +1212,8 @@ static int ipmr_cache_unresolved(struct mr_table *mrt, vifi_t vifi, } /* See if we can append the packet */ - if (c->_c.mfc_un.unres.unresolved.qlen > 3) { + if (skb_queue_len(&c->_c.mfc_un.unres.unresolved) + + skb_queue_len(&c->_c.mfc_un.unres.nl_queries) > 3) { c = NULL; err = -ENOBUFS; goto err; @@ -1222,7 +1224,8 @@ static int ipmr_cache_unresolved(struct mr_table *mrt, vifi_t vifi, skb->skb_iif = dev->ifindex; } - skb_queue_tail(&c->_c.mfc_un.unres.unresolved, skb); + skb_queue_tail(nl_query ? &c->_c.mfc_un.unres.nl_queries : + &c->_c.mfc_un.unres.unresolved, skb); spin_unlock_bh(&mfc_unres_lock); return 0; @@ -1937,7 +1940,7 @@ static int ipmr_prepare_xmit(struct net *net, struct mr_table *mrt, WRITE_ONCE(vif->bytes_out, vif->bytes_out + skb->len); DEV_STATS_ADD(vif_dev, tx_bytes, skb->len); DEV_STATS_INC(vif_dev, tx_packets); - ipmr_cache_report(mrt, skb, vifi, IGMPMSG_WHOLEPKT); + ipmr_cache_report(mrt, skb, vifi, IGMPMSG_WHOLEPKT, false); return -1; } @@ -2114,10 +2117,11 @@ static void ip_mr_forward(struct net *net, struct mr_table *mrt, c->_c.mfc_un.res.last_assert + MFC_ASSERT_THRESH)) { c->_c.mfc_un.res.last_assert = jiffies; - ipmr_cache_report(mrt, skb, true_vifi, IGMPMSG_WRONGVIF); + ipmr_cache_report(mrt, skb, true_vifi, IGMPMSG_WRONGVIF, + false); if (READ_ONCE(mrt->mroute_do_wrvifwhole)) ipmr_cache_report(mrt, skb, true_vifi, - IGMPMSG_WRVIFWHOLE); + IGMPMSG_WRVIFWHOLE, false); } goto dont_forward; } @@ -2287,7 +2291,7 @@ int ip_mr_input(struct sk_buff *skb) vif = ipmr_find_vif(mrt, dev); if (vif >= 0) - return ipmr_cache_unresolved(mrt, vif, skb, dev); + return ipmr_cache_unresolved(mrt, vif, skb, dev, false); kfree_skb(skb); return -ENODEV; } @@ -2395,7 +2399,7 @@ int ip_mr_output(struct net *net, struct sock *sk, struct sk_buff *skb) if (!cache) { vif = ipmr_find_vif(mrt, dev); if (vif >= 0) - return ipmr_cache_unresolved(mrt, vif, skb, dev); + return ipmr_cache_unresolved(mrt, vif, skb, dev, false); goto mc_output; } @@ -2517,7 +2521,7 @@ int ipmr_get_route(struct net *net, struct sk_buff *skb, iph->saddr = saddr; iph->daddr = daddr; iph->version = 0; - err = ipmr_cache_unresolved(mrt, vif, skb2, dev); + err = ipmr_cache_unresolved(mrt, vif, skb2, dev, true); rcu_read_unlock(); return err; } diff --git a/net/ipv4/netfilter/arp_tables.c b/net/ipv4/netfilter/arp_tables.c index db307fa49f3f..8c5f7cf15045 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 #include #include +#include #include #include @@ -336,7 +337,18 @@ void nf_send_reset(struct net *net, struct sock *sk, struct sk_buff *oldskb, dev_queue_xmit(nskb); } else #endif + { + local_bh_disable(); + if (nf_dev_xmit_recursion()) { + local_bh_enable(); + goto free_nskb; + } + + nf_dev_xmit_recursion_inc(); ip_local_out(net, nskb->sk, nskb); + nf_dev_xmit_recursion_dec(); + local_bh_enable(); + } return; diff --git a/net/ipv4/raw.c b/net/ipv4/raw.c index d756e5e31b90..f0035f8da3cf 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 1d8fcd19eaf6..e8bd10b28eb8 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; } @@ -1589,6 +1596,9 @@ void rt_flush_dev(struct net_device *dev) struct rtable *rt, *safe; int cpu; + if (dev && dev->dismantle) + return; + for_each_possible_cpu(cpu) { struct uncached_list *ul = &per_cpu(rt_uncached_list, cpu); @@ -1597,10 +1607,14 @@ void rt_flush_dev(struct net_device *dev) spin_lock_bh(&ul->lock); list_for_each_entry_safe(rt, safe, &ul->head, dst.rt_uncached) { - if (rt->dst.dev != dev) + struct net_device *rt_dev = rt->dst.dev; + + if (dev ? rt_dev != dev : + READ_ONCE(rt_dev->reg_state) != NETREG_UNREGISTERED) continue; + rcu_assign_pointer(rt->dst.dev_rcu, blackhole_netdev); - netdev_ref_replace(dev, blackhole_netdev, + netdev_ref_replace(rt_dev, blackhole_netdev, &rt->dst.dev_tracker, GFP_ATOMIC); list_del_init(&rt->dst.rt_uncached); } @@ -2487,6 +2501,8 @@ ip_route_input_slow(struct sk_buff *skb, __be32 daddr, __be32 saddr, if (unlikely(!rt_cache_route(nhc, rth))) rt_add_uncached_list(rth); + } else { + rt_add_uncached_list(rth); } skb_dst_set(skb, &rth->dst); reason = SKB_NOT_DROPPED_YET; diff --git a/net/ipv4/tcp.c b/net/ipv4/tcp.c index 73d5b7c8e3c7..338c30c65dad 100644 --- a/net/ipv4/tcp.c +++ b/net/ipv4/tcp.c @@ -455,7 +455,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); @@ -1054,6 +1054,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) & @@ -1073,6 +1074,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) { @@ -1083,14 +1087,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; } @@ -3492,6 +3495,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 */ @@ -4970,7 +4974,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 @@ -5150,6 +5155,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()) @@ -5306,6 +5313,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_fastopen.c b/net/ipv4/tcp_fastopen.c index e40477b6b554..b621c48a5231 100644 --- a/net/ipv4/tcp_fastopen.c +++ b/net/ipv4/tcp_fastopen.c @@ -543,6 +543,8 @@ bool tcp_fastopen_defer_connect(struct sock *sk, int *err) if (tp->fastopen_connect && !tp->fastopen_req) { if (tcp_fastopen_cookie_check(sk, &mss, &cookie)) { + WRITE_ONCE(tp->snd_una, tp->write_seq); + WRITE_ONCE(tp->snd_nxt, tp->write_seq); inet_set_bit(DEFER_CONNECT, sk); return true; } diff --git a/net/ipv4/tcp_input.c b/net/ipv4/tcp_input.c index 3583867487d7..84d0277bdda5 100644 --- a/net/ipv4/tcp_input.c +++ b/net/ipv4/tcp_input.c @@ -107,7 +107,8 @@ int sysctl_tcp_max_orphans __read_mostly = NR_FILE; #define FLAG_TS_PROGRESS 0x40000 /* Positive timestamp delta */ #define FLAG_ACKED (FLAG_DATA_ACKED|FLAG_SYN_ACKED) -#define FLAG_NOT_DUP (FLAG_DATA|FLAG_WIN_UPDATE|FLAG_ACKED) +#define FLAG_NOT_DUP (FLAG_DATA|FLAG_WIN_UPDATE|FLAG_ACKED| \ + FLAG_SND_UNA_ADVANCED) #define FLAG_CA_ALERT (FLAG_DATA_SACKED|FLAG_ECE|FLAG_DSACKING_ACK) #define FLAG_FORWARD_PROGRESS (FLAG_ACKED|FLAG_DATA_SACKED) @@ -3959,11 +3960,11 @@ static int tcp_ack_update_window(struct sock *sk, const struct sk_buff *skb, u32 nwin <<= tp->rx_opt.snd_wscale; if (tcp_may_update_window(tp, ack, ack_seq, nwin)) { - flag |= FLAG_WIN_UPDATE; tcp_update_wl(tp, ack_seq); if (tp->snd_wnd != nwin) { tp->snd_wnd = nwin; + flag |= FLAG_WIN_UPDATE; /* Note, it is the only place, where * fast path is recovered for sending TCP. @@ -4354,7 +4355,6 @@ static int tcp_ack(struct sock *sk, const struct sk_buff *skb, int flag) */ tcp_update_wl(tp, ack_seq); tcp_snd_una_update(tp, ack); - flag |= FLAG_WIN_UPDATE; NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPHPACKS); } else { @@ -5263,6 +5263,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; @@ -5384,6 +5388,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); @@ -5391,6 +5409,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); @@ -5401,6 +5420,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. */ @@ -5530,6 +5551,10 @@ static void tcp_data_queue_ofo(struct sock *sk, struct sk_buff *skb) skb_condense(skb); skb_set_owner_r(skb, sk); } + /* Net growth: coalescing can charge nothing, and covered skbs + * were freed. + */ + tcp_collapse_credit_add(sk, rmem); /* do not grow rcvbuf for not-yet-accepted or orphaned sockets. */ if (sk->sk_socket) tcp_rcvbuf_grow(sk, tp->rcvq_space.space); @@ -5538,8 +5563,9 @@ static void tcp_data_queue_ofo(struct sock *sk, struct sk_buff *skb) static int __must_check tcp_queue_rcv(struct sock *sk, struct sk_buff *skb, bool *fragstolen) { - int eaten; + int rmem = atomic_read(&sk->sk_rmem_alloc); struct sk_buff *tail = skb_peek_tail(&sk->sk_receive_queue); + int eaten; eaten = (tail && tcp_try_coalesce(sk, tail, @@ -5549,6 +5575,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; } @@ -5846,6 +5873,10 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root, __skb_queue_before(list, skb, nskb); else __skb_queue_tail(&tmp, nskb); /* defer rbtree insertion */ + /* nskb is charged before the skbs it replaces are freed. + * Make sure sk->sk_forward_alloc can not become negative. + */ + sk_forced_mem_schedule(sk, nskb->truesize); skb_set_owner_r(nskb, sk); mptcp_skb_ext_move(nskb, skb); @@ -6014,18 +6045,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); @@ -7199,6 +7240,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); @@ -7590,7 +7640,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 b41431338102..a58cc080fc9c 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)) || @@ -3550,6 +3552,7 @@ static int __net_init tcp_sk_init(struct net *net) static void __net_exit tcp_sk_exit_batch(struct list_head *net_exit_list) { + bool synced = false; struct net *net; /* make sure concurrent calls to tcp_sk_exit_batch from net_cleanup_work @@ -3564,9 +3567,27 @@ static void __net_exit tcp_sk_exit_batch(struct list_head *net_exit_list) tcp_twsk_purge(net_exit_list); + /* inet_twsk_kill() unhashes a twsk before it is done with ehash + * and bhash, and before it drops its tw_refcount reference, + * so tcp_twsk_purge() can miss it. Such callers run with BH + * disabled: wait for them before freeing a private ehash. + */ + list_for_each_entry(net, net_exit_list, exit_list) { + if (net->ipv4.tcp_death_row.hashinfo->pernet) { + synchronize_net(); + synced = true; + break; + } + } + list_for_each_entry(net, net_exit_list, exit_list) { inet_pernet_hashinfo_free(net->ipv4.tcp_death_row.hashinfo); - WARN_ON_ONCE(!refcount_dec_and_test(&net->ipv4.tcp_death_row.tw_refcount)); + /* Without a grace period, a concurrent inet_twsk_kill() might + * still hold a tw_refcount reference. Let it drop it: struct net + * is freed by a later cleanup_net(), after an RCU grace period. + */ + if (!refcount_dec_if_one(&net->ipv4.tcp_death_row.tw_refcount)) + WARN_ON_ONCE(synced); tcp_fastopen_ctx_destroy(net); } diff --git a/net/ipv4/tcp_metrics.c b/net/ipv4/tcp_metrics.c index 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 @@ struct sock *tcp_check_req(struct sock *sk, struct sk_buff *skb, tcp_reset(sk, skb); } if (!fastopen) { - bool unlinked = inet_csk_reqsk_queue_drop(sk, req); + bool unlinked = inet_csk_reqsk_queue_drop(req->rsk_listener, req); if (unlinked) __NET_INC_STATS(sock_net(sk), LINUX_MIB_EMBRYONICRSTS); diff --git a/net/ipv4/udp.c b/net/ipv4/udp.c index b090bd1f59e8..9a91e3533c15 100644 --- a/net/ipv4/udp.c +++ b/net/ipv4/udp.c @@ -2849,8 +2849,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 3ef3c2635581..b523de2e5b7a 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_fib.c b/net/ipv6/ip6_fib.c index ef65dd9870ea..2e1d8ab25f77 100644 --- a/net/ipv6/ip6_fib.c +++ b/net/ipv6/ip6_fib.c @@ -89,6 +89,40 @@ static void fib6_walker_unlink(struct net *net, struct fib6_walker *w) write_unlock_bh(&net->ipv6.fib6_walker_lock); } +/* @old is leaving the tree. Walkers resting on it continue from @new, or + * climb to the parent node when there is no @new. Called with tb6_lock + * held. + */ +static void fib6_walkers_replace_leaf(struct net *net, struct fib6_info *old, + struct fib6_info *new) +{ + struct fib6_walker *w; + + read_lock(&net->ipv6.fib6_walker_lock); + FOR_WALKERS(net, w) { + if (w->state == FWS_C && w->leaf == old) { + pr_debug("walker %p adjusted by unlink of %p\n", w, old); + w->leaf = new; + w->skip_in_node = 0; + if (!new) + w->state = FWS_U; + } + } + read_unlock(&net->ipv6.fib6_walker_lock); +} + +/* @rt is removed from its node: walkers resting on it continue from the + * next route of the node. + */ +static void fib6_walkers_skip_rt(struct net *net, struct fib6_info *rt) +{ + struct fib6_info *next; + + next = rcu_dereference_protected(rt->fib6_next, + lockdep_is_held(&rt->fib6_table->tb6_lock)); + fib6_walkers_replace_leaf(net, rt, next); +} + static int fib6_new_sernum(struct net *net) { int new, old = atomic_read(&net->ipv6.fib6_sernum); @@ -1312,6 +1346,7 @@ static int fib6_add_rt2node(struct fib6_node *fn, struct fib6_info *rt, rcu_assign_pointer(rt->fib6_node, fn); rt->fib6_next = iter->fib6_next; rcu_assign_pointer(*ins, rt); + fib6_walkers_replace_leaf(info->nl_net, iter, rt); if (!info->skip_notify) inet6_rt_notify(RTM_NEWROUTE, rt, info, NLM_F_REPLACE); if (!(fn->fn_flags & RTN_RTINFO)) { @@ -1333,6 +1368,7 @@ static int fib6_add_rt2node(struct fib6_node *fn, struct fib6_info *rt, if (iter->fib6_metric > rt->fib6_metric) break; if (rt6_qualify_for_ecmp(iter)) { + fib6_walkers_skip_rt(info->nl_net, iter); *ins = iter->fib6_next; iter->fib6_node = NULL; list_add(&iter->purge_link, purge_list); @@ -1967,7 +2003,6 @@ static void fib6_del_route(struct fib6_table *table, struct fib6_node *fn, enum rt_del_reason del_reason) { struct fib6_info *leaf, *replace_rt = NULL; - struct fib6_walker *w; struct fib6_info *rt = rcu_dereference_protected(*rtp, lockdep_is_held(&table->tb6_lock)); struct net *net = info->nl_net; @@ -2018,18 +2053,7 @@ static void fib6_del_route(struct fib6_table *table, struct fib6_node *fn, rt6_multipath_rebalance(next_sibling); } - /* Adjust walkers */ - read_lock(&net->ipv6.fib6_walker_lock); - FOR_WALKERS(net, w) { - if (w->state == FWS_C && w->leaf == rt) { - pr_debug("walker %p adjusted by delroute\n", w); - w->leaf = rcu_dereference_protected(rt->fib6_next, - lockdep_is_held(&table->tb6_lock)); - if (!w->leaf) - w->state = FWS_U; - } - } - read_unlock(&net->ipv6.fib6_walker_lock); + fib6_walkers_skip_rt(net, rt); /* If it was last route, call fib6_repair_tree() to: * 1. For root node, put back null_entry as how the table was created. diff --git a/net/ipv6/ip6_output.c b/net/ipv6/ip6_output.c index 550965058991..606f1f8a1ff8 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/ip6mr.c b/net/ipv6/ip6mr.c index 8e647213ade1..fff0a16ad11f 100644 --- a/net/ipv6/ip6mr.c +++ b/net/ipv6/ip6mr.c @@ -826,19 +826,18 @@ static void ip6mr_destroy_unres(struct mr_table *mrt, struct mfc6_cache *c) WRITE_ONCE(mrt->cache_resolve_queue_len, mrt->cache_resolve_queue_len - 1); - while ((skb = skb_dequeue(&c->_c.mfc_un.unres.unresolved)) != NULL) { - if (ipv6_hdr(skb)->version == 0) { - struct nlmsghdr *nlh = skb_pull(skb, - sizeof(struct ipv6hdr)); - nlh->nlmsg_type = NLMSG_ERROR; - nlh->nlmsg_len = nlmsg_msg_size(sizeof(struct nlmsgerr)); - skb_trim(skb, nlh->nlmsg_len); - ((struct nlmsgerr *)nlmsg_data(nlh))->error = -ETIMEDOUT; - rtnl_unicast(skb, net, NETLINK_CB(skb).portid); - } else - kfree_skb(skb); + while ((skb = skb_dequeue(&c->_c.mfc_un.unres.nl_queries))) { + struct nlmsghdr *nlh = skb_pull(skb, sizeof(struct ipv6hdr)); + + nlh->nlmsg_type = NLMSG_ERROR; + nlh->nlmsg_len = nlmsg_msg_size(sizeof(struct nlmsgerr)); + skb_trim(skb, nlh->nlmsg_len); + ((struct nlmsgerr *)nlmsg_data(nlh))->error = -ETIMEDOUT; + rtnl_unicast(skb, net, NETLINK_CB(skb).portid); } + skb_queue_purge(&c->_c.mfc_un.unres.unresolved); + ip6mr_cache_free(c); } @@ -1046,6 +1045,7 @@ static struct mfc6_cache *ip6mr_cache_alloc_unres(void) if (!c) return NULL; skb_queue_head_init(&c->_c.mfc_un.unres.unresolved); + skb_queue_head_init(&c->_c.mfc_un.unres.nl_queries); c->_c.mfc_un.unres.expires = jiffies + 10 * HZ; return c; } @@ -1059,30 +1059,26 @@ static void ip6mr_cache_resolve(struct net *net, struct mr_table *mrt, { struct sk_buff *skb; - /* - * Play the pending entries through our router - */ + /* Answer the pending netlink route queries */ + while ((skb = __skb_dequeue(&uc->_c.mfc_un.unres.nl_queries))) { + struct nlmsghdr *nlh = skb_pull(skb, sizeof(struct ipv6hdr)); - while ((skb = __skb_dequeue(&uc->_c.mfc_un.unres.unresolved))) { - if (ipv6_hdr(skb)->version == 0) { - struct nlmsghdr *nlh = skb_pull(skb, - sizeof(struct ipv6hdr)); - - if (mr_fill_mroute(mrt, skb, &c->_c, - nlmsg_data(nlh)) > 0) { - nlh->nlmsg_len = skb_tail_pointer(skb) - (u8 *)nlh; - } else { - nlh->nlmsg_type = NLMSG_ERROR; - nlh->nlmsg_len = nlmsg_msg_size(sizeof(struct nlmsgerr)); - skb_trim(skb, nlh->nlmsg_len); - ((struct nlmsgerr *)nlmsg_data(nlh))->error = -EMSGSIZE; - } - rtnl_unicast(skb, net, NETLINK_CB(skb).portid); + if (mr_fill_mroute(mrt, skb, &c->_c, nlmsg_data(nlh)) > 0) { + nlh->nlmsg_len = skb_tail_pointer(skb) - (u8 *)nlh; } else { - rcu_read_lock(); - ip6_mr_forward(net, mrt, skb->dev, skb, c); - rcu_read_unlock(); + nlh->nlmsg_type = NLMSG_ERROR; + nlh->nlmsg_len = nlmsg_msg_size(sizeof(struct nlmsgerr)); + skb_trim(skb, nlh->nlmsg_len); + ((struct nlmsgerr *)nlmsg_data(nlh))->error = -EMSGSIZE; } + rtnl_unicast(skb, net, NETLINK_CB(skb).portid); + } + + /* Play the pending packets through our router */ + while ((skb = __skb_dequeue(&uc->_c.mfc_un.unres.unresolved))) { + rcu_read_lock(); + ip6_mr_forward(net, mrt, skb->dev, skb, c); + rcu_read_unlock(); } } @@ -1187,7 +1183,8 @@ static int ip6mr_cache_report(const struct mr_table *mrt, struct sk_buff *pkt, /* Queue a packet for resolution. It gets locked cache entry! */ static int ip6mr_cache_unresolved(struct mr_table *mrt, mifi_t mifi, - struct sk_buff *skb, struct net_device *dev) + struct sk_buff *skb, struct net_device *dev, + bool nl_query) { struct net *net = read_pnet(&mrt->net); struct mfc6_cache *c = NULL; @@ -1241,7 +1238,8 @@ static int ip6mr_cache_unresolved(struct mr_table *mrt, mifi_t mifi, } /* See if we can append the packet */ - if (c->_c.mfc_un.unres.unresolved.qlen > 3) { + if (skb_queue_len(&c->_c.mfc_un.unres.unresolved) + + skb_queue_len(&c->_c.mfc_un.unres.nl_queries) > 3) { c = NULL; err = -ENOBUFS; goto err; @@ -1253,7 +1251,8 @@ static int ip6mr_cache_unresolved(struct mr_table *mrt, mifi_t mifi, } skb_dst_drop(skb); - skb_queue_tail(&c->_c.mfc_un.unres.unresolved, skb); + skb_queue_tail(nl_query ? &c->_c.mfc_un.unres.nl_queries : + &c->_c.mfc_un.unres.unresolved, skb); spin_unlock_bh(&mfc_unres_lock); return 0; @@ -1622,12 +1621,20 @@ static void mroute_clean_tables(struct mr_table *mrt, int flags, } } -static int ip6mr_sk_init(struct mr_table *mrt, struct sock *sk) +static int ip6mr_sk_init(struct sock *sk) { - int err = 0; struct net *net = sock_net(sk); + struct mr_table *mrt; + int err = 0; rtnl_lock(); + mrt = __ip6mr_get_table(net, + raw6_sk(sk)->ip6mr_table ? : RT6_TABLE_DFLT); + if (!mrt) { + err = -ENOENT; + goto out_unlock; + } + spin_lock(&mrt_lock); if (rtnl_dereference(mrt->mroute_sk)) { err = -EADDRINUSE; @@ -1643,6 +1650,7 @@ static int ip6mr_sk_init(struct mr_table *mrt, struct sock *sk) NETCONFA_MC_FORWARDING, NETCONFA_IFINDEX_ALL, net->ipv6.devconf_all); +out_unlock: rtnl_unlock(); return err; @@ -1744,7 +1752,7 @@ int ip6_mroute_setsockopt(struct sock *sk, int optname, sockptr_t optval, if (optlen < sizeof(int)) return -EINVAL; - return ip6mr_sk_init(mrt, sk); + return ip6mr_sk_init(sk); case MRT6_DONE: return ip6mr_sk_done(sk); @@ -1871,16 +1879,21 @@ int ip6_mroute_setsockopt(struct sock *sk, int optname, sockptr_t optval, /* "pim6reg%u" should not exceed 16 bytes (IFNAMSIZ) */ if (v != RT_TABLE_DEFAULT && v >= 100000000) return -EINVAL; - if (sk == rcu_access_pointer(mrt->mroute_sk)) - return -EBUSY; - rtnl_lock(); ret = 0; - mrt = ip6mr_new_table(net, v); - if (IS_ERR(mrt)) - ret = PTR_ERR(mrt); - else - raw6_sk(sk)->ip6mr_table = v; + mrt = __ip6mr_get_table(net, + raw6_sk(sk)->ip6mr_table ? : RT6_TABLE_DFLT); + if (!mrt) { + ret = -ENOENT; + } else if (sk == rtnl_dereference(mrt->mroute_sk)) { + ret = -EBUSY; + } else { + mrt = ip6mr_new_table(net, v); + if (IS_ERR(mrt)) + ret = PTR_ERR(mrt); + else + raw6_sk(sk)->ip6mr_table = v; + } rtnl_unlock(); return ret; } @@ -2398,7 +2411,8 @@ int ip6_mr_input(struct sk_buff *skb) vif = ip6mr_find_vif(mrt, dev); if (vif >= 0) { - int err = ip6mr_cache_unresolved(mrt, vif, skb, dev); + int err = ip6mr_cache_unresolved(mrt, vif, skb, dev, + false); return err; } @@ -2450,7 +2464,7 @@ int ip6_mr_output(struct net *net, struct sock *sk, struct sk_buff *skb) if (!cache) { vif = ip6mr_find_vif(mrt, dev); if (vif >= 0) - return ip6mr_cache_unresolved(mrt, vif, skb, dev); + return ip6mr_cache_unresolved(mrt, vif, skb, dev, false); goto ip6_output; } @@ -2527,7 +2541,7 @@ int ip6mr_get_route(struct net *net, struct sk_buff *skb, struct rtmsg *rtm, iph->saddr = rt->rt6i_src.addr; iph->daddr = rt->rt6i_dst.addr; - err = ip6mr_cache_unresolved(mrt, vif, skb2, dev); + err = ip6mr_cache_unresolved(mrt, vif, skb2, dev, true); rcu_read_unlock(); return err; 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_reject_ipv6.c b/net/ipv6/netfilter/nf_reject_ipv6.c index 5e08d8529cc8..7c9464184517 100644 --- a/net/ipv6/netfilter/nf_reject_ipv6.c +++ b/net/ipv6/netfilter/nf_reject_ipv6.c @@ -10,6 +10,7 @@ #include #include #include +#include #include #include @@ -409,7 +410,19 @@ void nf_send_reset6(struct net *net, struct sock *sk, struct sk_buff *oldskb, dev_queue_xmit(nskb); } else #endif + { + local_bh_disable(); + if (nf_dev_xmit_recursion()) { + local_bh_enable(); + kfree_skb(nskb); + return; + } + + nf_dev_xmit_recursion_inc(); ip6_local_out(net, sk, nskb); + nf_dev_xmit_recursion_dec(); + local_bh_enable(); + } } EXPORT_SYMBOL_GPL(nf_send_reset6); diff --git a/net/ipv6/raw.c b/net/ipv6/raw.c index 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/route.c b/net/ipv6/route.c index b8f51cabca3c..745782f80af4 100644 --- a/net/ipv6/route.c +++ b/net/ipv6/route.c @@ -158,10 +158,16 @@ void rt6_uncached_list_del(struct rt6_info *rt) } } -static void rt6_uncached_list_flush_dev(struct net_device *dev) +void rt6_uncached_list_flush_dev(struct net_device *dev) { int cpu; + if (!ipv6_mod_enabled()) + return; + + if (dev && dev->dismantle) + return; + for_each_possible_cpu(cpu) { struct uncached_list *ul = per_cpu_ptr(&rt6_uncached_list, cpu); struct rt6_info *rt, *safe; @@ -173,22 +179,38 @@ static void rt6_uncached_list_flush_dev(struct net_device *dev) list_for_each_entry_safe(rt, safe, &ul->head, dst.rt_uncached) { struct inet6_dev *rt_idev = rt->rt6i_idev; struct net_device *rt_dev = rt->dst.dev; - bool handled = false; + struct fib6_info *from; + bool release_fib; + + rcu_read_lock(); + from = rcu_dereference(rt->from); + release_fib = from && from->fib6_destroying; + rcu_read_unlock(); - if (rt_idev && rt_idev->dev == dev) { + if (rt_idev && + (dev ? rt_idev->dev == dev : + READ_ONCE(rt_idev->dev->reg_state) == NETREG_UNREGISTERED)) { rt->rt6i_idev = in6_dev_get(blackhole_netdev); in6_dev_put(rt_idev); - handled = true; + release_fib = true; } - if (rt_dev == dev) { - rt->dst.dev = blackhole_netdev; + if (dev ? rt_dev == dev : + READ_ONCE(rt_dev->reg_state) == NETREG_UNREGISTERED) { + rcu_assign_pointer(rt->dst.dev_rcu, blackhole_netdev); netdev_ref_replace(rt_dev, blackhole_netdev, &rt->dst.dev_tracker, GFP_ATOMIC); - handled = true; + release_fib = true; } - if (handled) + + if (release_fib) { + from = unrcu_pointer(xchg(&rt->from, NULL)); + fib6_info_release(from); + } + + if (rt->dst.dev == blackhole_netdev && + (!rt->rt6i_idev || rt->rt6i_idev->dev == blackhole_netdev)) list_del_init(&rt->dst.rt_uncached); } spin_unlock_bh(&ul->lock); @@ -1143,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; @@ -1178,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; @@ -3461,9 +3489,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 7cbe0685f8bb..1769fb8ab40c 100644 --- a/net/ipv6/seg6_iptunnel.c +++ b/net/ipv6/seg6_iptunnel.c @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -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) { @@ -616,6 +632,17 @@ static int seg6_input_core(struct net *net, struct sock *sk, return err; } +static int seg6_input_core_nf(struct net *net, struct sock *sk, + struct sk_buff *skb) +{ + if (unlikely(!seg6_skb_has_lwtstate(skb))) { + kfree_skb(skb); + return -EINVAL; + } + + return seg6_input_core(net, sk, skb); +} + static int seg6_input_nf(struct sk_buff *skb) { struct net_device *dev = skb_dst_dev(skb); @@ -624,10 +651,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; @@ -720,6 +747,17 @@ static int seg6_output_core(struct net *net, struct sock *sk, return err; } +static int seg6_output_core_nf(struct net *net, struct sock *sk, + struct sk_buff *skb) +{ + if (unlikely(!seg6_skb_has_lwtstate(skb))) { + kfree_skb(skb); + return -EINVAL; + } + + return seg6_output_core(net, sk, skb); +} + static int seg6_output_nf(struct net *net, struct sock *sk, struct sk_buff *skb) { struct net_device *dev = skb_dst_dev(skb); @@ -727,10 +765,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 0c3d1be7f129..82207da08dfd 100644 --- a/net/ipv6/seg6_local.c +++ b/net/ipv6/seg6_local.c @@ -24,6 +24,7 @@ #include #include #include +#include #include #ifdef CONFIG_IPV6_SEG6_HMAC #include @@ -149,9 +150,7 @@ struct seg6_end_dt_info { int vrf_ifindex; int vrf_table; - /* tunneled packet family (IPv4 or IPv6). - * Protocol and header length are inferred from family. - */ + /* tunneled packet family (IPv4 or IPv6) */ u16 family; }; @@ -213,6 +212,21 @@ static struct seg6_local_lwt *seg6_local_lwtunnel(struct lwtunnel_state *lwt) return (struct seg6_local_lwt *)lwt->data; } +static bool seg6_local_skb_has_lwtstate(struct sk_buff *skb) +{ + struct dst_entry *dst; + + if (unlikely(!skb_valid_dst(skb))) + return false; + + dst = skb_dst(skb); + if (unlikely(!dst->lwtstate || + dst->lwtstate->type != LWTUNNEL_ENCAP_SEG6_LOCAL)) + return false; + + return true; +} + static struct ipv6_sr_hdr *get_and_validate_srh(struct sk_buff *skb) { struct ipv6_sr_hdr *srh; @@ -1028,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) @@ -1048,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: @@ -1056,6 +1081,40 @@ static int input_action_end_dx6(struct sk_buff *skb, return -EINVAL; } +/* Validate the length of the IPv4 header at skb->data (which must point to + * the network header) and report that length, options included. + * Only the version, the header length and the presence of the whole header + * are checked. + * The length is written only when SKB_NOT_DROPPED_YET is returned. + * + * skb pointers may change: after this call, the caller must evaluate again + * any pointer into the packet data. + */ +static enum skb_drop_reason +seg6_validate_iphdr_len(struct sk_buff *skb, int *hdrlen) +{ + enum skb_drop_reason reason; + const struct iphdr *iph; + int len; + + reason = pskb_may_pull_reason(skb, sizeof(struct iphdr)); + if (reason) + return reason; + + iph = ip_hdr(skb); + if (iph->version != 4 || iph->ihl < 5) + return SKB_DROP_REASON_IP_INHDR; + + len = ip_hdrlen(skb); + + reason = pskb_may_pull_reason(skb, len); + if (reason) + return reason; + + *hdrlen = len; + return SKB_NOT_DROPPED_YET; +} + static int input_action_end_dx4_finish(struct net *net, struct sock *sk, struct sk_buff *skb) { @@ -1082,27 +1141,42 @@ static int input_action_end_dx4_finish(struct net *net, struct sock *sk, return dst_input(skb); } +static int input_action_end_dx4_finish_nf(struct net *net, struct sock *sk, + struct sk_buff *skb) +{ + if (unlikely(!seg6_local_skb_has_lwtstate(skb))) { + kfree_skb(skb); + return -EINVAL; + } + + return input_action_end_dx4_finish(net, sk, skb); +} + static int input_action_end_dx4(struct sk_buff *skb, struct seg6_local_lwt *slwt) { + SKB_DR(reason); + int hdrlen; + if (!decap_and_validate(skb, IPPROTO_IPIP)) goto drop; - if (!pskb_may_pull(skb, sizeof(struct iphdr))) + reason = seg6_validate_iphdr_len(skb, &hdrlen); + if (reason) goto drop; skb->protocol = htons(ETH_P_IP); - skb_set_transport_header(skb, sizeof(struct iphdr)); + skb_set_transport_header(skb, hdrlen); nf_reset_ct(skb); if (static_branch_unlikely(&nf_hooks_lwtunnel_enabled)) return NF_HOOK(NFPROTO_IPV4, NF_INET_PRE_ROUTING, dev_net(skb->dev), NULL, skb, skb->dev, - NULL, input_action_end_dx4_finish); + NULL, input_action_end_dx4_finish_nf); return input_action_end_dx4_finish(dev_net(skb->dev), NULL, skb); drop: - kfree_skb(skb); + kfree_skb_reason(skb, reason); return -EINVAL; } @@ -1237,16 +1311,24 @@ static struct sk_buff *end_dt_vrf_core(struct sk_buff *skb, struct seg6_end_dt_info *info = &slwt->dt_info; struct net_device *vrf; __be16 protocol; + SKB_DR(reason); int hdrlen; vrf = end_dt_get_vrf_rcu(skb, info); if (unlikely(!vrf)) goto drop; + if (unlikely(info->family != AF_UNSPEC && info->family != family)) { + pr_warn_once("seg6local: SRv6 End.DT* family mismatch"); + goto drop; + } + switch (family) { case AF_INET: protocol = htons(ETH_P_IP); - hdrlen = sizeof(struct iphdr); + reason = seg6_validate_iphdr_len(skb, &hdrlen); + if (unlikely(reason)) + goto drop; break; case AF_INET6: protocol = htons(ETH_P_IPV6); @@ -1258,11 +1340,6 @@ static struct sk_buff *end_dt_vrf_core(struct sk_buff *skb, goto drop; } - if (unlikely(info->family != AF_UNSPEC && info->family != family)) { - pr_warn_once("seg6local: SRv6 End.DT* family mismatch"); - goto drop; - } - skb->protocol = protocol; skb_dst_drop(skb); @@ -1273,7 +1350,7 @@ static struct sk_buff *end_dt_vrf_core(struct sk_buff *skb, return end_dt_vrf_rcv(skb, family, vrf); drop: - kfree_skb(skb); + kfree_skb_reason(skb, reason); return ERR_PTR(-EINVAL); } @@ -1286,9 +1363,7 @@ static int input_action_end_dt4(struct sk_buff *skb, if (!decap_and_validate(skb, IPPROTO_IPIP)) goto drop; - if (!pskb_may_pull(skb, sizeof(struct iphdr))) - goto drop; - + /* end_dt_vrf_core() validates the inner IPv4 header length */ skb = end_dt_vrf_core(skb, slwt, AF_INET); if (!skb) /* packet has been processed and consumed by the VRF */ @@ -1741,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)) { @@ -1751,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 be50b2fe1274..ef5928885cc6 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)) { @@ -578,8 +578,8 @@ static int tcp_v6_send_synack(const struct sock *sk, struct dst_entry *dst, &ireq->ir_v6_rmt_addr); fl6->daddr = ireq->ir_v6_rmt_addr; - if (inet6_test_bit(REPFLOW, sk) && ireq->pktopts) - fl6->flowlabel = ip6_flowlabel(ipv6_hdr(ireq->pktopts)); + if (inet6_test_bit(REPFLOW, sk)) + fl6->flowlabel = tcp_rsk(req)->syn_flowlabel; tclass = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_reflect_tos) ? (tcp_rsk(req)->syn_tos & ~INET_ECN_MASK) | @@ -607,7 +607,7 @@ static int tcp_v6_send_synack(const struct sock *sk, struct dst_entry *dst, static void tcp_v6_reqsk_destructor(struct request_sock *req) { - kfree(inet_rsk(req)->ipv6_opt); + kfree_rcu(inet_rsk(req)->ipv6_opt, rcu); consume_skb(inet_rsk(req)->pktopts); } @@ -789,6 +789,7 @@ static void tcp_v6_init_req(struct request_sock *req, ireq->ir_v6_loc_addr = ipv6_hdr(skb)->daddr; ireq->ir_rmt_addr = LOOPBACK4_IPV6; ireq->ir_loc_addr = LOOPBACK4_IPV6; + tcp_rsk(req)->syn_flowlabel = ip6_flowlabel(ipv6_hdr(skb)); /* So that link locals have meaning */ if ((!sk_listener->sk_bound_dev_if || l3_slave) && diff --git a/net/ipv6/udp.c b/net/ipv6/udp.c index 93478d1ad576..471cf3fba80e 100644 --- a/net/ipv6/udp.c +++ b/net/ipv6/udp.c @@ -1255,8 +1255,11 @@ void udp_v6_early_demux(struct sk_buff *skb) skb->destructor = sock_pfree; dst = rcu_dereference(sk->sk_rx_dst); - if (dst) + /* A dual-stack socket can cache an IPv4 dst. */ + if (dst && dst->ops->family == AF_INET6) dst = dst_check(dst, sk->sk_rx_dst_cookie); + else + dst = NULL; if (dst) { /* set noref for now. * any place which wants to hold dst has to call diff --git a/net/iucv/af_iucv.c b/net/iucv/af_iucv.c index db261ecd19af..b02c865c71fa 100644 --- a/net/iucv/af_iucv.c +++ b/net/iucv/af_iucv.c @@ -2072,11 +2072,20 @@ static int afiucv_hs_rcv(struct sk_buff *skb, struct net_device *dev, int err = NET_RX_SUCCESS; char nullstring[8]; + skb = skb_share_check(skb, GFP_ATOMIC); + if (!skb) + return NET_RX_SUCCESS; + if (!pskb_may_pull(skb, sizeof(*trans_hdr))) { kfree_skb(skb); return NET_RX_SUCCESS; } + if (skb_cow(skb, ETH_HLEN)) { + kfree_skb(skb); + return NET_RX_SUCCESS; + } + trans_hdr = iucv_trans_hdr(skb); EBCASC(trans_hdr->destAppName, sizeof(trans_hdr->destAppName)); EBCASC(trans_hdr->destUserID, sizeof(trans_hdr->destUserID)); diff --git a/net/mac80211/airtime.c b/net/mac80211/airtime.c index 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/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 cdd2581d7f59..711239edbe4b 100644 --- a/net/mac80211/ieee80211_i.h +++ b/net/mac80211/ieee80211_i.h @@ -682,6 +682,7 @@ struct ieee80211_if_ibss { spinlock_t incomplete_lock; struct list_head incomplete_stations; + atomic_t incomplete_sta_count; enum { IEEE80211_IBSS_MLME_SEARCH, @@ -696,6 +697,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 { @@ -704,6 +706,7 @@ struct ieee80211_if_ocb { spinlock_t incomplete_lock; struct list_head incomplete_stations; + atomic_t incomplete_sta_count; bool joined; }; diff --git a/net/mac80211/link.c b/net/mac80211/link.c index 931950a10508..918c1f8d3dc8 100644 --- a/net/mac80211/link.c +++ b/net/mac80211/link.c @@ -191,6 +191,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; @@ -205,11 +206,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); } @@ -290,6 +296,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; @@ -399,7 +406,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 d1c847dcce2f..1657346e01dd 100644 --- a/net/mac80211/mlme.c +++ b/net/mac80211/mlme.c @@ -7849,15 +7849,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) { @@ -7875,14 +7875,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++) { @@ -7894,7 +7894,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) { @@ -7919,7 +7919,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); @@ -7938,9 +7938,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 @@ -8463,8 +8465,9 @@ static void ieee80211_rx_mgmt_beacon(struct ieee80211_link_data *link, elems->cisco_dtpc_elem); ieee80211_ml_reconfiguration(sdata, elems); - ieee80211_process_adv_ttlm(sdata, elems, - le64_to_cpu(mgmt->u.beacon.timestamp)); + if (!ieee80211_process_adv_ttlm(sdata, elems, + le64_to_cpu(mgmt->u.beacon.timestamp))) + goto free; apply: ieee80211_link_info_change_notify(sdata, link, changed); diff --git a/net/mac80211/ocb.c b/net/mac80211/ocb.c index 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 aa8e3e375e07..e66a8b66d6a4 100644 --- a/net/mac80211/rx.c +++ b/net/mac80211/rx.c @@ -2930,9 +2930,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) { @@ -2943,6 +2940,10 @@ ieee80211_rx_mesh_fast_forward(struct ieee80211_sub_if_data *sdata, tid_tx->last_tx = jiffies; } + /* this function must not fail after this */ + if (skb_linearize(skb)) + return false; + ieee80211_aggr_check(sdata, sta, skb); if (ieee80211_get_8023_tunnel_proto(skb->data + hdrlen, diff --git a/net/mac80211/tx.c b/net/mac80211/tx.c index 0492205459f0..3b4e6e1bed17 100644 --- a/net/mac80211/tx.c +++ b/net/mac80211/tx.c @@ -2586,6 +2586,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 966e785a4f0f..3b9fc1f0187e 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 05c38564e8fd..8e08feb676f7 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 @@ static int __net_init __ip_vs_init(struct net *net) conn_fail: ip_vs_app_net_cleanup(ipvs); app_fail: - ip_vs_protocol_net_cleanup(ipvs); -protocol_fail: ip_vs_control_net_cleanup(ipvs); control_fail: + ip_vs_protocol_net_cleanup(ipvs); +protocol_fail: ip_vs_estimator_net_cleanup(ipvs); estimator_fail: net->ipvs = NULL; @@ -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 #include #include +#include static void nf_do_netdev_egress(struct sk_buff *skb, struct net_device *dev, enum nf_dev_hooks hook) diff --git a/net/netfilter/nf_flow_table_core.c b/net/netfilter/nf_flow_table_core.c index 36bbc7be2f74..94502c97ba23 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 73363ceedebe..44f182eba953 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 b59628e6240c..1322f37b9635 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; } @@ -4536,8 +4534,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 477fc632657f..90eab03572b6 100644 --- a/net/netfilter/nfnetlink_queue.c +++ b/net/netfilter/nfnetlink_queue.c @@ -44,6 +44,7 @@ #include #include #include +#include #include #include @@ -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 @@ static void nf_reinject(struct nf_queue_entry *entry, unsigned int verdict) switch (verdict & NF_VERDICT_MASK) { case NF_ACCEPT: case NF_STOP: - local_bh_disable(); entry->state.okfn(entry->state.net, entry->state.sk, skb); - local_bh_enable(); break; case NF_QUEUE: err = nf_queue(skb, &entry->state, i, verdict); @@ -418,6 +426,9 @@ static void nf_reinject(struct nf_queue_entry *entry, unsigned int verdict) } nf_queue_entry_free(entry); +out: + current->in_nf_duplicate = old_in_nf_duplicate; + local_bh_enable(); } /* return true if the entry has an unconfirmed conntrack attached that isn't owned by us diff --git a/net/netfilter/nft_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 #include #include +#include #include #include 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 d34831ce3adf..d89021f704ba 100644 --- a/net/netfilter/xt_recent.c +++ b/net/netfilter/xt_recent.c @@ -649,14 +649,15 @@ static void __net_exit recent_proc_net_exit(struct net *net) /* recent_net_exit() is called before recent_mt_destroy(). Make sure * that the parent xt_recent proc entry is empty before trying to - * remove it. + * remove it. Use recent_mutex instead of recent_lock since + * remove_proc_entry() may sleep. */ - spin_lock_bh(&recent_lock); + mutex_lock(&recent_mutex); list_for_each_entry(t, &recent_net->tables, list) remove_proc_entry(t->name, recent_net->xt_recent); recent_net->xt_recent = NULL; - spin_unlock_bh(&recent_lock); + mutex_unlock(&recent_mutex); remove_proc_entry("xt_recent", net->proc_net); } diff --git a/net/netlink/af_netlink.c b/net/netlink/af_netlink.c index 510fb5ebf9ff..4850bac3a3f8 100644 --- a/net/netlink/af_netlink.c +++ b/net/netlink/af_netlink.c @@ -1050,8 +1050,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 #include #include +#include #include #include @@ -84,6 +85,12 @@ static struct sk_buff *nsh_gso_segment(struct sk_buff *skb, skb_reset_network_header(skb); + /* NSH can carry NSH (directly, or in an inner Ethernet frame): + * limit the recursion, as IPv4 and IPv6 do. + */ + if (unlikely(gso_recursion_inc_test(skb, IP_TUNNEL_RECURSION_LIMIT))) + goto out; + outer_proto = skb->protocol; outer_hlen = skb_mac_header_len(skb); mac_len = skb->mac_len; diff --git a/net/openvswitch/flow.c b/net/openvswitch/flow.c index 868d9fdf3afd..03a41594fcec 100644 --- a/net/openvswitch/flow.c +++ b/net/openvswitch/flow.c @@ -370,11 +370,28 @@ static void get_ipv6_ext_hdrs(struct sk_buff *skb, struct ipv6hdr *nh, return; } + if (next_type == IPPROTO_FRAGMENT) { + struct frag_hdr _fh, *fh; + + fh = skb_header_pointer(skb, start, sizeof(_fh), &_fh); + if (!fh) + break; + /* Only the first fragment has the headers that follow. */ + if (fh->frag_off & htons(IP6_OFFSET)) + break; + start += sizeof(_fh); + next_type = fh->nexthdr; + continue; + } + hp = skb_header_pointer(skb, start, sizeof(_hdr), &_hdr); if (!hp) break; + if (next_type == IPPROTO_AH) + start += ipv6_authlen(hp); + else + start += ipv6_optlen(hp); next_type = hp->nexthdr; - start += ipv6_optlen(hp); } } diff --git a/net/rds/rdma.c b/net/rds/rdma.c index 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 @@ static int tcf_ife_encode(struct sk_buff *skb, const struct tc_action *a, * is an Ethernet header because the skb could've been redirected with mirred * from a non-Ethernet device. */ -static bool tcf_ife_is_eth_skb(const struct sk_buff *skb) +static bool tcf_ife_is_eth_skb(struct sk_buff *skb) { if (skb->dev->type != ARPHRD_ETHER && skb->dev->type != ARPHRD_LOOPBACK) return false; - return !skb_at_tc_ingress(skb) || skb->mac_len == ETH_HLEN; + if (skb_at_tc_ingress(skb)) + return skb->mac_len == ETH_HLEN; + + return pskb_may_pull(skb, ETH_HLEN); } TC_INDIRECT_SCOPE int tcf_ife_act(struct sk_buff *skb, diff --git a/net/sched/sch_teql.c b/net/sched/sch_teql.c index b60ab79a6572..726f34e840f8 100644 --- a/net/sched/sch_teql.c +++ b/net/sched/sch_teql.c @@ -198,6 +198,8 @@ static int teql_qdisc_init(struct Qdisc *sch, struct nlattr *opt, struct Qdisc *first; unsigned long flags; + skb_queue_head_init(&q->q); + if (dev->hard_header_len > m->dev->hard_header_len) return -EINVAL; @@ -209,9 +211,12 @@ static int teql_qdisc_init(struct Qdisc *sch, struct nlattr *opt, return -EOPNOTSUPP; } - q->m = m; + if (dev_net(dev) != dev_net(m->dev)) { + NL_SET_ERR_MSG_MOD(extack, "teql master is in a different network namespace"); + return -EOPNOTSUPP; + } - skb_queue_head_init(&q->q); + q->m = m; raw_spin_lock_irqsave(&m->slaves_lock, flags); first = rcu_dereference_protected(m->slaves, lockdep_is_held(&m->slaves_lock)); diff --git a/net/sctp/sm_make_chunk.c b/net/sctp/sm_make_chunk.c index 90de27284251..ba0474c2a0bc 100644 --- a/net/sctp/sm_make_chunk.c +++ b/net/sctp/sm_make_chunk.c @@ -2870,7 +2870,6 @@ struct sctp_chunk *sctp_make_asconf_update_ip(struct sctp_association *asoc, int addr_param_len = 0; union sctp_addr *addr; int totallen = 0, i; - int del_pickup = 0; struct sctp_af *af; void *addr_buf; @@ -2885,16 +2884,21 @@ struct sctp_chunk *sctp_make_asconf_update_ip(struct sctp_association *asoc, totallen += addr_param_len; addr_buf += af->sockaddr_len; - if (asoc->asconf_addr_del_pending && !del_pickup) { - /* reuse the parameter length from the same scope one */ - totallen += paramlen; - totallen += addr_param_len; - del_pickup = 1; - - pr_debug("%s: picked same-scope del_pending addr, " - "totallen for all addresses is %d\n", - __func__, totallen); - } + } + + if (asoc->asconf_addr_del_pending) { + /* The DEL_IP parameter is serialized from the pending address + * itself below; account for its own address family, which may + * differ from the added ones. + */ + addr = asoc->asconf_addr_del_pending; + af = sctp_get_af_specific(addr->v4.sin_family); + totallen += paramlen; + totallen += af->to_addr_param(addr, &addr_param); + + pr_debug("%s: picked del_pending addr, " + "totallen for all addresses is %d\n", + __func__, totallen); } /* Create an asconf chunk with the required length. */ @@ -2917,7 +2921,7 @@ struct sctp_chunk *sctp_make_asconf_update_ip(struct sctp_association *asoc, addr_buf += af->sockaddr_len; } - if (flags == SCTP_PARAM_ADD_IP && del_pickup) { + if (flags == SCTP_PARAM_ADD_IP && asoc->asconf_addr_del_pending) { addr = asoc->asconf_addr_del_pending; af = sctp_get_af_specific(addr->v4.sin_family); addr_param_len = af->to_addr_param(addr, &addr_param); @@ -3160,9 +3164,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 +3182,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 e4354d58f20b..d5e71a2027f5 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 8b3ee70f8433..2f64c555625f 100644 --- a/net/smc/af_smc.c +++ b/net/smc/af_smc.c @@ -976,7 +976,7 @@ static int smc_connect_fallback(struct smc_sock *smc, int reason_code) smc_copy_sock_settings_to_clc(smc); smc->connect_nonblock = 0; if (smc->sk.sk_state == SMC_INIT) - smc->sk.sk_state = SMC_ACTIVE; + smp_store_release(&smc->sk.sk_state, SMC_ACTIVE); return 0; } @@ -1009,14 +1009,15 @@ static void smc_conn_abort(struct smc_sock *smc, int local_first) { struct smc_connection *conn = &smc->conn; struct smc_link_group *lgr = conn->lgr; - bool lgr_valid = false; - - if (smc_conn_lgr_valid(conn)) - lgr_valid = true; + bool lgr_valid = local_first && smc_conn_lgr_valid(conn); + if (lgr_valid) + smc_lgr_hold(lgr); /* lgr_put below */ smc_conn_free(conn); - if (local_first && lgr_valid) + if (lgr_valid) { smc_lgr_cleanup_early(lgr); + smc_lgr_put(lgr); + } } /* check if there is a rdma device available for this connection. */ @@ -1381,7 +1382,7 @@ static int smc_connect_rdma(struct smc_sock *smc, smc_copy_sock_settings_to_clc(smc); smc->connect_nonblock = 0; if (smc->sk.sk_state == SMC_INIT) - smc->sk.sk_state = SMC_ACTIVE; + smp_store_release(&smc->sk.sk_state, SMC_ACTIVE); return 0; connect_abort: @@ -1484,7 +1485,7 @@ static int smc_connect_ism(struct smc_sock *smc, smc_copy_sock_settings_to_clc(smc); smc->connect_nonblock = 0; if (smc->sk.sk_state == SMC_INIT) - smc->sk.sk_state = SMC_ACTIVE; + smp_store_release(&smc->sk.sk_state, SMC_ACTIVE); return 0; connect_abort: @@ -1951,7 +1952,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); } @@ -1965,7 +1966,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 bb0313ef5f7c..cbe1cdf01aed 100644 --- a/net/smc/smc_close.c +++ b/net/smc/smc_close.c @@ -154,6 +154,7 @@ void smc_close_active_abort(struct smc_sock *smc) if (sk->sk_state != SMC_PEERABORTWAIT) break; sk->sk_state = SMC_CLOSED; + sk->sk_prot->unhash(sk); smc_conn_free(&smc->conn); release_clcsock = true; sock_put(sk); /* passive closing */ @@ -165,6 +166,7 @@ void smc_close_active_abort(struct smc_sock *smc) if (sk->sk_state != SMC_PEERABORTWAIT) break; sk->sk_state = SMC_CLOSED; + sk->sk_prot->unhash(sk); smc_conn_free(&smc->conn); release_clcsock = true; break; @@ -367,6 +369,17 @@ static void smc_close_passive_work(struct work_struct *work) lock_sock(sk); old_state = sk->sk_state; + if (conn->freed) { + /* conn->freed is set under the socket lock, which is + * held here as well, so this cannot race with the free; the + * state machine and its postponed sock_put() are not owed + * anymore + */ + release_sock(sk); + sock_put(sk); /* sock_hold done by schedulers of close_work */ + return; + } + rxflags = &conn->local_rx_ctrl.conn_state_flags; if (rxflags->peer_conn_abort) { /* peer has not received all data */ @@ -433,6 +446,7 @@ static void smc_close_passive_work(struct work_struct *work) sk->sk_state_change(sk); if ((sk->sk_state == SMC_CLOSED) && (sock_flag(sk, SOCK_DEAD) || !sk->sk_socket)) { + sk->sk_prot->unhash(sk); smc_conn_free(conn); if (smc->clcsock) release_clcsock = true; diff --git a/net/smc/smc_core.c b/net/smc/smc_core.c index 9974149659c2..af324d06f2be 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); } @@ -1279,10 +1299,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); @@ -1517,6 +1539,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 @@ -1530,8 +1561,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); } @@ -1562,12 +1595,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); @@ -1578,7 +1619,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); @@ -1592,17 +1637,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); } @@ -2051,6 +2087,10 @@ int smc_conn_create(struct smc_sock *smc, struct smc_init_info *ini) goto out; } } + /* cache the connection type: smc_diag reads it after + * smc_conn_free() dropped the link group reference + */ + conn->is_smcd = conn->lgr->is_smcd; smc_lgr_hold(conn->lgr); /* lgr_put in smc_conn_free() */ if (!conn->lgr->is_smcd) smcr_link_hold(conn->lnk); /* link_put in smc_conn_free() */ diff --git a/net/smc/smc_core.h b/net/smc/smc_core.h index 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/smc/smc_sysctl.c b/net/smc/smc_sysctl.c index 09dad48337f6..f58cf256f61a 100644 --- a/net/smc/smc_sysctl.c +++ b/net/smc/smc_sysctl.c @@ -160,11 +160,9 @@ static const struct ctl_table smc_table[] = { { .procname = "limit_smc_hs", .data = &init_net.smc.limit_smc_hs, - .maxlen = sizeof(int), + .maxlen = sizeof(bool), .mode = 0644, - .proc_handler = proc_dointvec_minmax, - .extra1 = SYSCTL_ZERO, - .extra2 = SYSCTL_ONE, + .proc_handler = proc_dobool, }, { .procname = "smcr_max_send_wr", diff --git a/net/socket.c b/net/socket.c index c05d86e63abf..13b4755d6551 100644 --- a/net/socket.c +++ b/net/socket.c @@ -2695,8 +2695,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. @@ -2760,6 +2758,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; @@ -2924,9 +2925,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 @@ -2968,6 +2966,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 @@ int rpcrdma_xprt_connect(struct rpcrdma_xprt *r_xprt) * 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 /* spinlock_t, etc */ #include /* atomic_t, etc */ #include /* struct kref */ +#include /* struct rw_semaphore */ #include /* struct work_struct */ #include @@ -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 963e46a51421..a4a9b62bf666 100644 --- a/net/sunrpc/xprtsock.c +++ b/net/sunrpc/xprtsock.c @@ -3525,7 +3525,7 @@ static struct rpc_xprt *xs_setup_tcp_tls(struct xprt_create *args) transport = container_of(xprt, struct sock_xprt, xprt); xprt->prot = IPPROTO_TCP; - xprt->xprt_class = &xs_tcp_transport; + xprt->xprt_class = &xs_tcp_tls_transport; xprt->max_payload = RPC_MAX_FRAGMENT_SIZE; xprt->bind_timeout = XS_BIND_TO; diff --git a/net/tipc/bearer.c b/net/tipc/bearer.c index 5e7e220fa7f5..d041a1a7c6dc 100644 --- a/net/tipc/bearer.c +++ b/net/tipc/bearer.c @@ -285,17 +285,50 @@ static int tipc_enable_bearer(struct net *net, const char *name, bearer_id = MAX_BEARERS; i = MAX_BEARERS; while (i-- != 0) { + struct net_device *dev; + b = rtnl_dereference(tn->bearer_list[i]); if (!b) { bearer_id = i; continue; } if (!strcmp(name, b->name)) { +duplicate: errstr = "already enabled"; NL_SET_ERR_MSG(extack, "Already enabled"); goto rejected; } + /* udp media can be used together with any media */ + if (b->media->type_id == TIPC_MEDIA_TYPE_UDP || + m->type_id == TIPC_MEDIA_TYPE_UDP) + goto priority; + + dev = __dev_get_by_name(net, b_names.if_name); + + if (!dev) { + res = -ENODEV; + errstr = "no device for the media"; + NL_SET_ERR_MSG(extack, "No device for the media"); + goto rejected; + } + + if (rtnl_dereference(b->media_ptr) == dev) { + char *dev_name = strchr((const char *)b->name, ':') + 1; + + /* Not allow altname of occupied device */ + if (strcmp(dev_name, b_names.if_name) && + b->media->type_id == m->type_id) + goto duplicate; + + /* Not allow eth and ib to attach to the same device */ + errstr = "same dev for different media"; + NL_SET_ERR_MSG(extack, + "Same dev for different media"); + goto rejected; + } + +priority: if (b->priority == prio && (++with_this_prio > 2)) { pr_warn("Bearer <%s>: already 2 bearers with priority %u\n", diff --git a/net/tls/tls_sw.c b/net/tls/tls_sw.c index 79639ed79821..9a60d52b36fd 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 @@ int tls_sw_recvmsg(struct sock *sk, 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 @@ int tls_sw_recvmsg(struct sock *sk, 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 42cffeafc8c1..6be50ef557d6 100644 --- a/net/unix/af_unix.c +++ b/net/unix/af_unix.c @@ -1752,6 +1752,7 @@ static int unix_stream_connect(struct socket *sock, struct sockaddr_unsized *uad 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 @@ static unsigned long __unix_walk_scc(struct unix_vertex *vertex, return cyclic_sccs; } -static unsigned long unix_graph_cyclic_sccs; +static u64 unix_graph_cyclic_sccs; static void unix_walk_scc(struct sk_buff_head *hitlist) { - unsigned long last_index = UNIX_VERTEX_INDEX_START; - unsigned long cyclic_sccs = 0; + u64 last_index = UNIX_VERTEX_INDEX_START; + u64 cyclic_sccs = 0; unix_vertex_max_scc_index = UNIX_VERTEX_INDEX_START; @@ -582,7 +579,7 @@ static void unix_walk_scc(struct sk_buff_head *hitlist) static void unix_walk_scc_fast(struct sk_buff_head *hitlist) { - unsigned long cyclic_sccs = unix_graph_cyclic_sccs; + u64 cyclic_sccs = unix_graph_cyclic_sccs; while (!list_empty(&unix_unvisited_vertices)) { struct unix_vertex *vertex; diff --git a/net/vmw_vsock/af_vsock.c b/net/vmw_vsock/af_vsock.c index 6ba8c85dc161..9f9b02d1e050 100644 --- a/net/vmw_vsock/af_vsock.c +++ b/net/vmw_vsock/af_vsock.c @@ -2101,7 +2101,8 @@ static int vsock_connectible_setsockopt(struct socket *sock, optname == SO_VM_SOCKETS_CONNECT_TIMEOUT_OLD); if (err) break; - if (tv.tv_sec >= 0 && tv.tv_usec < USEC_PER_SEC && + if (tv.tv_sec >= 0 && tv.tv_usec >= 0 && + tv.tv_usec < USEC_PER_SEC && tv.tv_sec < (MAX_SCHEDULE_TIMEOUT / HZ - 1)) { vsk->connect_timeout = tv.tv_sec * HZ + DIV_ROUND_UP((unsigned long)tv.tv_usec, (USEC_PER_SEC / HZ)); diff --git a/net/vmw_vsock/hyperv_transport.c b/net/vmw_vsock/hyperv_transport.c index 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/core.c b/net/wireless/core.c index 3ac3b2a67a9c..625cb2c2a05a 100644 --- a/net/wireless/core.c +++ b/net/wireless/core.c @@ -1913,7 +1913,7 @@ static int cfg80211_netdev_notifier_call(struct notifier_block *nb, return NOTIFY_DONE; } - wireless_nlevent_flush(); + wireless_nlevent_flush(dev_net(dev)); return NOTIFY_OK; } diff --git a/net/wireless/scan.c b/net/wireless/scan.c index d35c826c4b1a..5f3dbf191fd1 100644 --- a/net/wireless/scan.c +++ b/net/wireless/scan.c @@ -2452,6 +2452,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; } } @@ -2591,7 +2592,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 f2464d2ce0d5..c510fc62d819 100644 --- a/net/wireless/util.c +++ b/net/wireless/util.c @@ -822,12 +822,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); @@ -849,7 +849,7 @@ bool ieee80211_is_valid_amsdu(struct sk_buff *skb, u8 mesh_hdr) __be16 len; u8 mesh_flags; } hdr; - u16 len; + unsigned int len; if (sizeof(hdr) > remaining) return false; diff --git a/net/wireless/wext-core.c b/net/wireless/wext-core.c index db77912b3994..f09c589ff94c 100644 --- a/net/wireless/wext-core.c +++ b/net/wireless/wext-core.c @@ -342,32 +342,28 @@ static const int compat_event_type_size[] = { /* IW event code */ -void wireless_nlevent_flush(void) +void wireless_nlevent_flush(struct net *net) { struct sk_buff *skb; - struct net *net; - down_read(&net_rwsem); - for_each_net(net) { - while ((skb = skb_dequeue(&net->wext_nlevents))) - rtnl_notify(skb, net, 0, RTNLGRP_LINK, NULL, - GFP_KERNEL); - } - up_read(&net_rwsem); + while ((skb = skb_dequeue(&net->wext_nlevents))) + rtnl_notify(skb, net, 0, RTNLGRP_LINK, NULL, GFP_KERNEL); } EXPORT_SYMBOL_GPL(wireless_nlevent_flush); static int wext_netdev_notifier_call(struct notifier_block *nb, unsigned long state, void *ptr) { + struct net_device *dev = netdev_notifier_info_to_dev(ptr); + /* - * When a netdev changes state in any way, flush all pending messages - * to avoid them going out in a strange order, e.g. RTM_NEWLINK after - * RTM_DELLINK, or with IFF_UP after without IFF_UP during dev_close() - * or similar - all of which could otherwise happen due to delays from - * schedule_work(). + * When a netdev changes state in any way, flush all pending messages in + * its network namespace to avoid them going out in a strange order, + * e.g. RTM_NEWLINK after RTM_DELLINK, or with IFF_UP after without + * IFF_UP during dev_close() or similar - all of which could otherwise + * happen due to delays from schedule_work(). */ - wireless_nlevent_flush(); + wireless_nlevent_flush(dev_net(dev)); return NOTIFY_OK; } @@ -410,7 +406,12 @@ subsys_initcall(wireless_nlevent_init); /* Process events generated by the wireless layer or the driver. */ static void wireless_nlevent_process(struct work_struct *work) { - wireless_nlevent_flush(); + struct net *net; + + down_read(&net_rwsem); + for_each_net(net) + wireless_nlevent_flush(net); + up_read(&net_rwsem); } static DECLARE_WORK(wireless_nlevent_work, wireless_nlevent_process); diff --git a/net/xdp/xsk.c b/net/xdp/xsk.c index 781ba46eb152..7d31e06cc0d1 100644 --- a/net/xdp/xsk.c +++ b/net/xdp/xsk.c @@ -1011,14 +1011,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 +1022,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 +1278,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/xfrm/xfrm_iptfs.c b/net/xfrm/xfrm_iptfs.c index 6920940a35b4..71bdc8d61015 100644 --- a/net/xfrm/xfrm_iptfs.c +++ b/net/xfrm/xfrm_iptfs.c @@ -1183,6 +1183,7 @@ static bool __input_process_payload(struct xfrm_state *x, u32 data, /* this should not happen from the above code */ XFRM_INC_STATS(net, LINUX_MIB_XFRMINIPTFSERROR); +done: if (first_skb && first_iplen && !defer && !first_skb_partial) { /* first_skb is queued b/c !defer and not partial */ if (pskb_trim(first_skb, first_iplen)) { @@ -1199,7 +1200,7 @@ static bool __input_process_payload(struct xfrm_state *x, u32 data, if (xfrm_input(skb, 0, 0, -2)) kfree_skb(skb); } -done: + skb = skbseq->root_skb; skb_abort_seq_read(skbseq); diff --git a/net/xfrm/xfrm_replay.c b/net/xfrm/xfrm_replay.c index dbdf8a39dffe..9394953247ab 100644 --- a/net/xfrm/xfrm_replay.c +++ b/net/xfrm/xfrm_replay.c @@ -40,7 +40,7 @@ static void xfrm_replay_notify_esn(struct xfrm_state *x, int event); void xfrm_replay_notify(struct xfrm_state *x, int event) { - struct km_event c; + struct km_event c = {}; /* we send notify messages in case * 1. we updated on of the sequence numbers, and the seqno difference * is at least x->replay_maxdiff, in this case we also update the @@ -304,7 +304,7 @@ static void xfrm_replay_advance_bmp(struct xfrm_state *x, __be32 net_seq) static void xfrm_replay_notify_bmp(struct xfrm_state *x, int event) { - struct km_event c; + struct km_event c = {}; struct xfrm_replay_state_esn *replay_esn = x->replay_esn; struct xfrm_replay_state_esn *preplay_esn = x->preplay_esn; @@ -356,7 +356,7 @@ static void xfrm_replay_notify_bmp(struct xfrm_state *x, int event) static void xfrm_replay_notify_esn(struct xfrm_state *x, int event) { u32 seq_diff, oseq_diff; - struct km_event c; + struct km_event c = {}; struct xfrm_replay_state_esn *replay_esn = x->replay_esn; struct xfrm_replay_state_esn *preplay_esn = x->preplay_esn; diff --git a/net/xfrm/xfrm_state.c b/net/xfrm/xfrm_state.c index e45aa1ed5b96..5b241dfcae62 100644 --- a/net/xfrm/xfrm_state.c +++ b/net/xfrm/xfrm_state.c @@ -1177,11 +1177,19 @@ static struct xfrm_state *__xfrm_state_lookup_all(const struct xfrm_hash_state_p return NULL; } -static struct xfrm_state *__xfrm_state_lookup(const struct xfrm_hash_state_ptrs *state_ptrs, - u32 mark, - const xfrm_address_t *daddr, - __be32 spi, u8 proto, - unsigned short family) +static bool xfrm_state_mark_matches(const struct xfrm_state *x, u32 mark, u32 mask, bool exact) +{ + if (exact) + return x->mark.v == mark && x->mark.m == mask; + return (mark & x->mark.m) == x->mark.v; +} + +static struct xfrm_state * +__xfrm_state_lookup(const struct xfrm_hash_state_ptrs *state_ptrs, + u32 mark, u32 mask, bool exact, + const xfrm_address_t *daddr, + __be32 spi, u8 proto, + unsigned short family) { unsigned int h = __xfrm_spi_hash(daddr, spi, proto, family, state_ptrs->hmask); struct xfrm_state *x; @@ -1193,7 +1201,7 @@ static struct xfrm_state *__xfrm_state_lookup(const struct xfrm_hash_state_ptrs !xfrm_addr_equal(&x->id.daddr, daddr, family)) continue; - if ((mark & x->mark.m) != x->mark.v) + if (!xfrm_state_mark_matches(x, mark, mask, exact)) continue; if (!xfrm_state_hold_rcu(x)) continue; @@ -1203,6 +1211,17 @@ static struct xfrm_state *__xfrm_state_lookup(const struct xfrm_hash_state_ptrs return NULL; } +static struct xfrm_state * +__xfrm_state_lookup_exact(const struct xfrm_hash_state_ptrs *state_ptrs, + const struct xfrm_mark *mark, + const xfrm_address_t *daddr, + __be32 spi, u8 proto, + unsigned short family) +{ + return __xfrm_state_lookup(state_ptrs, mark->v, mark->m, true, + daddr, spi, proto, family); +} + struct xfrm_state *xfrm_input_state_lookup(struct net *net, u32 mark, const xfrm_address_t *daddr, __be32 spi, u8 proto, @@ -1233,7 +1252,7 @@ struct xfrm_state *xfrm_input_state_lookup(struct net *net, u32 mark, xfrm_hash_ptrs_get(net, &state_ptrs); - x = __xfrm_state_lookup(&state_ptrs, mark, daddr, spi, proto, family); + x = __xfrm_state_lookup(&state_ptrs, mark, 0, false, daddr, spi, proto, family); if (x) { spin_lock(&net->xfrm.xfrm_state_lock); if (x->km.state != XFRM_STATE_VALID) { @@ -1283,7 +1302,7 @@ static struct xfrm_state *__xfrm_state_lookup_byaddr(const struct xfrm_hash_stat return NULL; } -static inline struct xfrm_state * +static struct xfrm_state * __xfrm_state_locate(struct xfrm_state *x, int use_spi, int family) { struct xfrm_hash_state_ptrs state_ptrs; @@ -1293,7 +1312,7 @@ __xfrm_state_locate(struct xfrm_state *x, int use_spi, int family) xfrm_hash_ptrs_get(net, &state_ptrs); if (use_spi) - return __xfrm_state_lookup(&state_ptrs, mark, &x->id.daddr, + return __xfrm_state_lookup(&state_ptrs, mark, 0, false, &x->id.daddr, x->id.spi, x->id.proto, family); else return __xfrm_state_lookup_byaddr(&state_ptrs, mark, @@ -2186,10 +2205,12 @@ int xfrm_state_migrate_install(const struct xfrm_state *x, struct netlink_ext_ack *extack) { if (m->new_family == m->old_family && - xfrm_addr_equal(&x->id.daddr, &m->new_daddr, m->new_family)) { + xfrm_addr_equal(&x->id.daddr, &m->new_daddr, m->new_family) && + xc->mark.v == x->mark.v && xc->mark.m == x->mark.m) { /* - * Care is needed when the destination address of the state is - * to be updated as it is a part of triplet. + * Care is needed when the destination address or mark of the + * state is to be updated, as they are part of the lookup + * triplet. */ xfrm_state_insert(xc); } else { @@ -2383,7 +2404,7 @@ xfrm_state_lookup(struct net *net, u32 mark, const xfrm_address_t *daddr, __be32 rcu_read_lock(); xfrm_hash_ptrs_get(net, &state_ptrs); - x = __xfrm_state_lookup(&state_ptrs, mark, daddr, spi, proto, family); + x = __xfrm_state_lookup(&state_ptrs, mark, 0, false, daddr, spi, proto, family); rcu_read_unlock(); return x; } @@ -2407,6 +2428,55 @@ xfrm_state_lookup_byaddr(struct net *net, u32 mark, } EXPORT_SYMBOL(xfrm_state_lookup_byaddr); +struct xfrm_state * +xfrm_state_lookup_exact(struct net *net, const struct xfrm_mark *mark, + const xfrm_address_t *daddr, __be32 spi, + u8 proto, unsigned short family) +{ + struct xfrm_hash_state_ptrs state_ptrs; + struct xfrm_state *x; + + rcu_read_lock(); + xfrm_hash_ptrs_get(net, &state_ptrs); + + x = __xfrm_state_lookup_exact(&state_ptrs, mark, daddr, spi, proto, family); + rcu_read_unlock(); + return x; +} +EXPORT_SYMBOL(xfrm_state_lookup_exact); + +/* True if some OTHER state at this tuple would wildcard-match "mark". + * Used by MIGRATE_STATE, which must exclude the state being migrated. + */ +bool xfrm_state_mark_collides(struct net *net, u32 mark, + const xfrm_address_t *daddr, __be32 spi, + u8 proto, unsigned short family, + const struct xfrm_state *self) +{ + struct xfrm_hash_state_ptrs state_ptrs; + unsigned int h; + struct xfrm_state *x; + bool collides = false; + + rcu_read_lock(); + xfrm_hash_ptrs_get(net, &state_ptrs); + h = __xfrm_spi_hash(daddr, spi, proto, family, state_ptrs.hmask); + + hlist_for_each_entry_rcu(x, state_ptrs.byspi + h, byspi) { + if (x != self && x->props.family == family && + x->id.spi == spi && x->id.proto == proto && + xfrm_addr_equal(&x->id.daddr, daddr, family) && + (mark & x->mark.m) == x->mark.v) { + collides = true; + break; + } + } + rcu_read_unlock(); + + return collides; +} +EXPORT_SYMBOL(xfrm_state_mark_collides); + struct xfrm_state * xfrm_find_acq(struct net *net, const struct xfrm_mark *mark, u8 mode, u32 reqid, u32 if_id, u32 pcpu_num, u8 proto, const xfrm_address_t *daddr, @@ -3317,7 +3387,7 @@ int xfrm_init_state(struct xfrm_state *x, struct netlink_ext_ack *extack) if (err) return err; - err = xfrm_init_replay(x, NULL); + err = xfrm_init_replay(x, extack); if (err) return err; diff --git a/net/xfrm/xfrm_user.c b/net/xfrm/xfrm_user.c index a2587c7e796b..f8c2b17c6f2b 100644 --- a/net/xfrm/xfrm_user.c +++ b/net/xfrm/xfrm_user.c @@ -1089,11 +1089,12 @@ static struct xfrm_state *xfrm_user_state_lookup(struct net *net, struct xfrm_state *x = NULL; struct xfrm_mark m; int err; - u32 mark = xfrm_mark_get(attrs, &m); + + xfrm_mark_get(attrs, &m); if (xfrm_id_proto_match(p->proto, IPSEC_PROTO_ANY)) { err = -ESRCH; - x = xfrm_state_lookup(net, mark, &p->daddr, p->spi, p->proto, p->family); + x = xfrm_state_lookup_exact(net, &m, &p->daddr, p->spi, p->proto, p->family); } else { xfrm_address_t *saddr = NULL; @@ -1104,7 +1105,7 @@ static struct xfrm_state *xfrm_user_state_lookup(struct net *net, } err = -ESRCH; - x = xfrm_state_lookup_byaddr(net, mark, + x = xfrm_state_lookup_byaddr(net, m.v & m.m, &p->daddr, saddr, p->proto, p->family); } @@ -2795,14 +2796,13 @@ static int xfrm_get_ae(struct sk_buff *skb, struct nlmsghdr *nlh, struct sk_buff *r_skb; int err; struct km_event c; - u32 mark; struct xfrm_mark m; struct xfrm_aevent_id *p = nlmsg_data(nlh); struct xfrm_usersa_id *id = &p->sa_id; - mark = xfrm_mark_get(attrs, &m); + xfrm_mark_get(attrs, &m); - x = xfrm_state_lookup(net, mark, &id->daddr, id->spi, id->proto, id->family); + x = xfrm_state_lookup_exact(net, &m, &id->daddr, id->spi, id->proto, id->family); if (x == NULL) return -ESRCH; @@ -2843,7 +2843,6 @@ static int xfrm_new_ae(struct sk_buff *skb, struct nlmsghdr *nlh, struct xfrm_state *x; struct km_event c; int err = -EINVAL; - u32 mark = 0; struct xfrm_mark m; struct xfrm_aevent_id *p = nlmsg_data(nlh); struct nlattr *rp = attrs[XFRMA_REPLAY_VAL]; @@ -2863,9 +2862,10 @@ static int xfrm_new_ae(struct sk_buff *skb, struct nlmsghdr *nlh, return err; } - mark = xfrm_mark_get(attrs, &m); + xfrm_mark_get(attrs, &m); - x = xfrm_state_lookup(net, mark, &p->sa_id.daddr, p->sa_id.spi, p->sa_id.proto, p->sa_id.family); + x = xfrm_state_lookup_exact(net, &m, &p->sa_id.daddr, p->sa_id.spi, + p->sa_id.proto, p->sa_id.family); if (x == NULL) return -ESRCH; @@ -2999,9 +2999,10 @@ static int xfrm_add_sa_expire(struct sk_buff *skb, struct nlmsghdr *nlh, struct xfrm_user_expire *ue = nlmsg_data(nlh); struct xfrm_usersa_info *p = &ue->state; struct xfrm_mark m; - u32 mark = xfrm_mark_get(attrs, &m); - x = xfrm_state_lookup(net, mark, &p->id.daddr, p->id.spi, p->id.proto, p->family); + xfrm_mark_get(attrs, &m); + + x = xfrm_state_lookup_exact(net, &m, &p->id.daddr, p->id.spi, p->id.proto, p->family); err = -ENOENT; if (x == NULL) @@ -3372,9 +3373,9 @@ static int xfrm_do_migrate_state(struct sk_buff *skb, struct nlmsghdr *nlh, copy_from_user_migrate_state(&m, um); - x = xfrm_state_lookup(net, m.old_mark.v & m.old_mark.m, - &um->id.daddr, um->id.spi, - um->id.proto, um->id.family); + x = xfrm_state_lookup_exact(net, &m.old_mark, + &um->id.daddr, um->id.spi, + um->id.proto, um->id.family); if (!x) { NL_SET_ERR_MSG(extack, "Can not find state"); return -ESRCH; @@ -3445,15 +3446,14 @@ static int xfrm_do_migrate_state(struct sk_buff *skb, struct nlmsghdr *nlh, x->nat_keepalive_interval); if (m.new_family != um->id.family || - !xfrm_addr_equal(&m.new_daddr, &um->id.daddr, um->id.family)) { - u32 new_mark_key = m.new_mark ? m.new_mark->v & m.new_mark->m : - m.old_mark.v & m.old_mark.m; - struct xfrm_state *x_new; - - x_new = xfrm_state_lookup(net, new_mark_key, &m.new_daddr, - um->id.spi, um->id.proto, m.new_family); - if (x_new) { - xfrm_state_put(x_new); + !xfrm_addr_equal(&m.new_daddr, &um->id.daddr, um->id.family) || + (m.new_mark && (m.new_mark->v != x->mark.v || + m.new_mark->m != x->mark.m))) { + const struct xfrm_mark *new_mark = m.new_mark ? m.new_mark : &x->mark; + + if (xfrm_state_mark_collides(net, new_mark->v & new_mark->m, + &m.new_daddr, um->id.spi, + um->id.proto, m.new_family, x)) { NL_SET_ERR_MSG(extack, "New SA tuple already occupied"); err = -EEXIST; goto out; @@ -3478,6 +3478,7 @@ static int xfrm_do_migrate_state(struct sk_buff *skb, struct nlmsghdr *nlh, __xfrm_state_delete(x); spin_unlock_bh(&x->lock); + xfrm_state_hold(xc); err = xfrm_state_migrate_install(x, xc, &m, extack); if (err < 0) { /* @@ -3485,6 +3486,7 @@ static int xfrm_do_migrate_state(struct sk_buff *skb, struct nlmsghdr *nlh, * free under xfrm_cfg_mutex. Both SAs are gone if it does; * restoring x would risk SN/IV reuse. */ + xfrm_state_put(xc); goto out; } @@ -3503,10 +3505,13 @@ static int xfrm_do_migrate_state(struct sk_buff *skb, struct nlmsghdr *nlh, err = 0; } + xfrm_state_put(xc); out: xfrm_state_put(x); return err; out_xc: + if (m.xuo) + xfrm_dev_state_delete(xc); xc->km.state = XFRM_STATE_DEAD; xfrm_state_put(xc); xfrm_state_put(x); 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..e88548f1a704 100644 --- a/security/keys/key.c +++ b/security/keys/key.c @@ -245,6 +245,8 @@ struct key *key_alloc(struct key_type *type, const char *desc, } desclen = strlen(desc); + if (desclen >= KEY_MAX_DESC_SIZE) + goto error; quotalen = desclen + 1 + type->def_datalen; /* get hold of the key tracking for this user */ @@ -829,6 +831,7 @@ static key_ref_t __key_create_or_update(key_ref_t keyring_ref, key_ref_t key_ref; int ret; struct key_restriction *restrict_link = NULL; + size_t desclen; /* look up the key type to see if it's one of the registered kernel * types */ @@ -869,7 +872,12 @@ static key_ref_t __key_create_or_update(key_ref_t keyring_ref, if (!index_key.description) goto error_free_prep; } - index_key.desc_len = strlen(index_key.description); + desclen = strlen(index_key.description); + if (desclen >= KEY_MAX_DESC_SIZE) { + key_ref = ERR_PTR(-EINVAL); + goto error_free_prep; + } + index_key.desc_len = desclen; key_set_index_key(&index_key); ret = __key_link_lock(keyring, &index_key); diff --git a/security/keys/keyctl.c b/security/keys/keyctl.c index 36ffba0ebba6..d6b10fd67627 100644 --- a/security/keys/keyctl.c +++ b/security/keys/keyctl.c @@ -24,8 +24,6 @@ #include #include "internal.h" -#define KEY_MAX_DESC_SIZE 4096 - static const unsigned char keyrings_capabilities[2] = { [0] = (KEYCTL_CAPS0_CAPABILITIES | (IS_ENABLED(CONFIG_PERSISTENT_KEYRINGS) ? KEYCTL_CAPS0_PERSISTENT_KEYRINGS : 0) | diff --git a/security/keys/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 fa2bb9f2f538..ef00c2b08fe0 100644 --- a/security/keys/request_key.c +++ b/security/keys/request_key.c @@ -584,7 +584,6 @@ struct key *request_key_and_link(struct key_type *type, .index_key.type = type, .index_key.domain_tag = domain_tag, .index_key.description = description, - .index_key.desc_len = strlen(description), .cred = current_cred(), .match_data.cmp = key_default_cmp, .match_data.raw_data = description, @@ -595,8 +594,14 @@ struct key *request_key_and_link(struct key_type *type, }; struct key *key; key_ref_t key_ref; + size_t desclen; int ret; + desclen = strlen(description); + if (desclen >= KEY_MAX_DESC_SIZE) + return ERR_PTR(-EINVAL); + ctx.index_key.desc_len = desclen; + kenter("%s,%s,%p,%zu,%p,%p,%lx", ctx.index_key.type->name, ctx.index_key.description, callout_info, callout_len, aux, dest_keyring, flags); @@ -787,7 +792,6 @@ struct key *request_key_rcu(struct key_type *type, .index_key.type = type, .index_key.domain_tag = domain_tag, .index_key.description = description, - .index_key.desc_len = strlen(description), .cred = current_cred(), .match_data.cmp = key_default_cmp, .match_data.raw_data = description, @@ -797,6 +801,12 @@ struct key *request_key_rcu(struct key_type *type, }; struct key *key; key_ref_t key_ref; + size_t desclen; + + desclen = strlen(description); + if (desclen >= KEY_MAX_DESC_SIZE) + return ERR_PTR(-EINVAL); + ctx.index_key.desc_len = desclen; kenter("%s,%s", type->name, description); diff --git a/sound/core/memalloc.c b/sound/core/memalloc.c index 5bc7e586b430..3118bb14231c 100644 --- a/sound/core/memalloc.c +++ b/sound/core/memalloc.c @@ -506,7 +506,7 @@ static void *snd_dma_wc_alloc(struct snd_dma_buffer *dmab, size_t size) return NULL; dmab->addr = dma_map_single(dmab->dev.dev, p, size, DMA_BIDIRECTIONAL); if (dma_mapping_error(dmab->dev.dev, dmab->addr)) { - do_free_pages(dmab->area, size, true); + do_free_pages(p, size, true); return NULL; } return p; diff --git a/sound/firewire/tascam/tascam-stream.c b/sound/firewire/tascam/tascam-stream.c index 4ecd151a46c1..462766946e94 100644 --- a/sound/firewire/tascam/tascam-stream.c +++ b/sound/firewire/tascam/tascam-stream.c @@ -287,10 +287,10 @@ static int keep_resources(struct snd_tscm *tscm, unsigned int rate, if (stream == &tscm->tx_stream) { resources = &tscm->tx_resources; - speed = fw_parent_device(tscm->unit)->max_speed; + speed = SCODE_400; } else { resources = &tscm->rx_resources; - speed = SCODE_400; + speed = fw_parent_device(tscm->unit)->max_speed; } err = amdtp_tscm_set_parameters(stream, rate); 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/realtek/alc269.c b/sound/hda/codecs/realtek/alc269.c index 350003d406e7..c9b75def6732 100644 --- a/sound/hda/codecs/realtek/alc269.c +++ b/sound/hda/codecs/realtek/alc269.c @@ -4436,7 +4436,6 @@ enum { ALC256_FIXUP_HONOR_MRB_XXX_M1020_AUDIO, 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, @@ -7226,12 +7225,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, @@ -7370,7 +7363,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x1025, 0x169a, "Acer Swift SFG16", ALC256_FIXUP_ACER_SFG16_MICMUTE_LED), 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), @@ -7469,12 +7462,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), @@ -7896,7 +7889,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x103c, 0x8e36, "HP 14 Enstrom OmniBook X", ALC287_FIXUP_CS35L41_I2C_2), SND_PCI_QUIRK(0x103c, 0x8e37, "HP 16 Piston OmniBook X", ALC287_FIXUP_CS35L41_I2C_2), SND_PCI_QUIRK(0x103c, 0x8e3a, "HP Agusta", ALC287_FIXUP_CS35L41_I2C_2), - SND_PCI_QUIRK(0x103c, 0x8e3b, "HP Agusta", ALC287_FIXUP_CS35L41_I2C_2), + SND_PCI_QUIRK(0x103c, 0x8e3b, "HP OmniBook 7", ALC245_FIXUP_CS35L41_I2C_2_MUTE_MICMUTE_LED), SND_PCI_QUIRK(0x103c, 0x8e43, "HP Laptop 15-fd2xxx", ALC236_FIXUP_HP_MUTE_LED_MICMUTE_GPIO), SND_PCI_QUIRK(0x103c, 0x8e60, "HP OmniBook 7 Laptop 16-bh0xxx", ALC245_FIXUP_CS35L41_I2C_2_MUTE_LED), SND_PCI_QUIRK(0x103c, 0x8e61, "HP Trekker ", ALC287_FIXUP_CS35L41_I2C_2), @@ -7934,11 +7927,11 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x103c, 0x8f3a, "HP EliteBook 6 G2i", ALC236_FIXUP_HP_GPIO_LED), SND_PCI_QUIRK(0x103c, 0x8f3c, "HP EliteBook 6 G2a", ALC236_FIXUP_HP_MUTE_LED_MICMUTE_VREF), SND_PCI_QUIRK(0x103c, 0x8f3d, "HP EliteBook 6 G2a", ALC236_FIXUP_HP_MUTE_LED_MICMUTE_VREF), - SND_PCI_QUIRK(0x103c, 0x8f40, "HP ZBook 8 G2a 14", ALC245_FIXUP_HP_TAS2781_I2C_MUTE_LED), - SND_PCI_QUIRK(0x103c, 0x8f41, "HP ZBook 8 G2a 16", ALC245_FIXUP_HP_TAS2781_I2C_MUTE_LED), - SND_PCI_QUIRK(0x103c, 0x8f42, "HP ZBook 8 G2a 14W", ALC245_FIXUP_HP_TAS2781_I2C_MUTE_LED), + SND_PCI_QUIRK(0x103c, 0x8f40, "HP ZBook 8 G2a 14", ALC245_FIXUP_HP_TAS2781_I2C_MUTE_LED_INVERTED), + SND_PCI_QUIRK(0x103c, 0x8f41, "HP ZBook 8 G2a 16", ALC245_FIXUP_HP_TAS2781_I2C_MUTE_LED_INVERTED), + SND_PCI_QUIRK(0x103c, 0x8f42, "HP ZBook 8 G2a 14W", ALC245_FIXUP_HP_TAS2781_I2C_MUTE_LED_INVERTED), SND_PCI_QUIRK(0x103c, 0x8f57, "HP Trekker G7JC", ALC287_FIXUP_CS35L41_I2C_2), - SND_PCI_QUIRK(0x103c, 0x8f62, "HP ZBook 8 G2a 16W", ALC245_FIXUP_HP_TAS2781_I2C_MUTE_LED), + SND_PCI_QUIRK(0x103c, 0x8f62, "HP ZBook 8 G2a 16W", ALC245_FIXUP_HP_TAS2781_I2C_MUTE_LED_INVERTED), SND_PCI_QUIRK(0x103c, 0x8f7e, "HP Messi", ALC245_FIXUP_HP_TAS2781_I2C_MUTE_LED), SND_PCI_QUIRK(0x103c, 0x8f94, "HP ZBook 8 G2a 14", ALC245_FIXUP_HP_TAS2781_I2C_MUTE_LED_INVERTED), SND_PCI_QUIRK(0x103c, 0x8f95, "HP ZBook 8 G2a 16", ALC245_FIXUP_HP_TAS2781_I2C_MUTE_LED_INVERTED), diff --git a/sound/hda/codecs/realtek/alc882.c b/sound/hda/codecs/realtek/alc882.c index fd466b6985f0..9577b8af9e21 100644 --- a/sound/hda/codecs/realtek/alc882.c +++ b/sound/hda/codecs/realtek/alc882.c @@ -50,6 +50,7 @@ enum { ALC889_FIXUP_MP41_VREF, ALC882_FIXUP_INV_DMIC, ALC882_FIXUP_NO_PRIMARY_HP, + ALC898_FIXUP_DELL_XPS8940_MIC, ALC887_FIXUP_ASUS_BASS, ALC887_FIXUP_BASS_CHMAP, ALC1220_FIXUP_GB_DUAL_CODECS, @@ -507,6 +508,13 @@ static const struct hda_fixup alc882_fixups[] = { .type = HDA_FIXUP_FUNC, .v.func = alc882_fixup_no_primary_hp, }, + [ALC898_FIXUP_DELL_XPS8940_MIC] = { + .type = HDA_FIXUP_PINS, + .v.pins = (const struct hda_pintbl[]) { + { 0x19, 0x02a19130 }, /* headset mic, no separate jack detect */ + {} + }, + }, [ALC887_FIXUP_ASUS_BASS] = { .type = HDA_FIXUP_PINS, .v.pins = (const struct hda_pintbl[]) { @@ -610,6 +618,8 @@ static const struct hda_quirk alc882_fixup_tbl[] = { SND_PCI_QUIRK(0x1025, 0x0259, "Acer Aspire 5935", ALC889_FIXUP_DAC_ROUTE), SND_PCI_QUIRK(0x1025, 0x026b, "Acer Aspire 8940G", ALC882_FIXUP_ACER_ASPIRE_8930G), SND_PCI_QUIRK(0x1025, 0x0296, "Acer Aspire 7736z", ALC882_FIXUP_ACER_ASPIRE_7736), + SND_PCI_QUIRK(0x1028, 0x09c5, "Dell XPS 8940", + ALC898_FIXUP_DELL_XPS8940_MIC), SND_PCI_QUIRK(0x1043, 0x13c2, "Asus A7M", ALC882_FIXUP_EAPD), SND_PCI_QUIRK(0x1043, 0x1873, "ASUS W90V", ALC882_FIXUP_ASUS_W90V), SND_PCI_QUIRK(0x1043, 0x1971, "Asus W2JC", ALC882_FIXUP_ASUS_W2JC), diff --git a/sound/hda/codecs/side-codecs/cs35l56_hda.c b/sound/hda/codecs/side-codecs/cs35l56_hda.c index bc207ab5b020..5982eebae152 100644 --- a/sound/hda/codecs/side-codecs/cs35l56_hda.c +++ b/sound/hda/codecs/side-codecs/cs35l56_hda.c @@ -562,7 +562,7 @@ static void cs35l56_hda_fw_load(struct cs35l56_hda *cs35l56) * downloaded previously then it needs to be powered down so that it * can be updated. */ - if (cs35l56->base.fw_patched) + if (cs35l56->cs_dsp.booted) cs_dsp_power_down(&cs35l56->cs_dsp); cs35l56->base.fw_patched = false; @@ -634,7 +634,7 @@ static void cs35l56_hda_fw_load(struct cs35l56_hda *cs35l56) regcache_mark_dirty(cs35l56->base.regmap); ret = cs35l56_wait_for_firmware_boot(&cs35l56->base); if (ret) - goto err_powered_up; + return; regcache_cache_only(cs35l56->base.regmap, false); } @@ -642,7 +642,7 @@ static void cs35l56_hda_fw_load(struct cs35l56_hda *cs35l56) /* Disable auto-hibernate so that runtime_pm has control */ ret = cs35l56_mbox_send(&cs35l56->base, CS35L56_MBOX_CMD_PREVENT_AUTO_HIBERNATE); if (ret) - goto err_powered_up; + return; regcache_sync(cs35l56->base.regmap); @@ -663,10 +663,6 @@ static void cs35l56_hda_fw_load(struct cs35l56_hda *cs35l56) cs_dsp_stop(&cs35l56->cs_dsp); cs35l56_log_tuning(&cs35l56->base, &cs35l56->cs_dsp); - -err_powered_up: - if (!cs35l56->base.fw_patched) - cs_dsp_power_down(&cs35l56->cs_dsp); } static void cs35l56_hda_dsp_work(struct work_struct *work) @@ -813,8 +809,10 @@ static void cs35l56_hda_unbind(struct device *dev, struct device *master, void * cs_dsp_cleanup_debugfs(&cs35l56->cs_dsp); debugfs_remove_recursive(cs35l56->debugfs_root); #endif + if (cs35l56->cs_dsp.running) + cs_dsp_stop(&cs35l56->cs_dsp); - if (cs35l56->base.fw_patched) + if (cs35l56->cs_dsp.booted) cs_dsp_power_down(&cs35l56->cs_dsp); comp = hda_component_from_index(parent, cs35l56->index); diff --git a/sound/hda/codecs/side-codecs/tas2781_hda.c b/sound/hda/codecs/side-codecs/tas2781_hda.c index 9162173ccb10..b9b6e44f8791 100644 --- a/sound/hda/codecs/side-codecs/tas2781_hda.c +++ b/sound/hda/codecs/side-codecs/tas2781_hda.c @@ -89,6 +89,7 @@ static void tas2781_apply_calib(struct tasdevice_priv *p) TASDEVICE_REG(0, 0x18, 0x7c), }; unsigned int crc, oft, node_num; + bool custom_addr = false; unsigned char *buf; int i, j, k, l; @@ -129,6 +130,7 @@ static void tas2781_apply_calib(struct tasdevice_priv *p) for (j = 0, k = 0; j < node_num; j++) { oft = j * 6 + 3; if (tmp_val[oft] == TASDEV_UEFI_CALI_REG_ADDR_FLG) { + custom_addr = true; for (i = 0; i < TASDEV_CALIB_N; i++) { buf = &data[(oft + i + 1) * 4]; cali_reg[i] = TASDEVICE_REG(buf[1], @@ -188,7 +190,7 @@ static void tas2781_apply_calib(struct tasdevice_priv *p) } } - if (p->dspbin_typ == TASDEV_BASIC) { + if (custom_addr || p->dspbin_typ == TASDEV_BASIC) { r->r0_reg = cali_reg[0]; r->invr0_reg = cali_reg[1]; r->r0_low_reg = cali_reg[2]; diff --git a/sound/hda/common/sysfs.c b/sound/hda/common/sysfs.c index 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/hda/core/controller.c b/sound/hda/core/controller.c index 78855ac357c6..b37ae6062158 100644 --- a/sound/hda/core/controller.c +++ b/sound/hda/core/controller.c @@ -426,6 +426,13 @@ int snd_hdac_bus_parse_capabilities(struct hdac_bus *bus) break; } + /* An all-zero header means no capability is present here */ + if (!cur_cap) { + dev_dbg(bus->dev, "Empty capability header at offset 0x%x\n", + offset); + break; + } + switch ((cur_cap & AZX_CAP_HDR_ID_MASK) >> AZX_CAP_HDR_ID_OFF) { case AZX_ML_CAP_ID: dev_dbg(bus->dev, "Found ML capability\n"); @@ -456,7 +463,8 @@ int snd_hdac_bus_parse_capabilities(struct hdac_bus *bus) break; default: - dev_err(bus->dev, "Unknown capability %d\n", cur_cap); + dev_err(bus->dev, "Unknown capability ID 0x%x\n", + (cur_cap & AZX_CAP_HDR_ID_MASK) >> AZX_CAP_HDR_ID_OFF); cur_cap = 0; break; } @@ -745,10 +753,13 @@ int snd_hdac_bus_alloc_stream_pages(struct hdac_bus *bus) error_posbuf: snd_dma_free_pages(&bus->posbuf); + bus->posbuf.area = NULL; error_bdl: list_for_each_entry(s, &bus->stream_list, list) { - if (s->bdl.area) + if (s->bdl.area) { snd_dma_free_pages(&s->bdl); + s->bdl.area = NULL; + } } return -ENOMEM; } 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/acp3x-es83xx/acp3x-es83xx.c b/sound/soc/amd/acp/acp3x-es83xx/acp3x-es83xx.c index eb0e9a6af6ef..80985d044896 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 #include #include +#include #include #include #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); diff --git a/sound/soc/amd/ps/pci-ps.c b/sound/soc/amd/ps/pci-ps.c index b604db4942dd..d0b66df10157 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/apple/mca.c b/sound/soc/apple/mca.c index be702b2942a5..ec3636f9dc86 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/es9356.c b/sound/soc/codecs/es9356.c index 80db0f2f4aef..02c0c34c0454 100644 --- a/sound/soc/codecs/es9356.c +++ b/sound/soc/codecs/es9356.c @@ -59,8 +59,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/lpass-rx-macro.c b/sound/soc/codecs/lpass-rx-macro.c index 282a6aaa9986..1737d525ca86 100644 --- a/sound/soc/codecs/lpass-rx-macro.c +++ b/sound/soc/codecs/lpass-rx-macro.c @@ -3681,7 +3681,7 @@ static int swclk_gate_enable(struct clk_hw *hw) ret = rx_macro_mclk_enable(rx, true); if (ret) { - clk_disable_unprepare(rx->mclk); + pm_runtime_put_autosuspend(rx->dev); return ret; } diff --git a/sound/soc/codecs/max98090.c b/sound/soc/codecs/max98090.c index 64dc442e9066..696ea68e38f8 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/codecs/tas2770.c b/sound/soc/codecs/tas2770.c index 355fcbfd01c7..a77ca55d5cf0 100644 --- a/sound/soc/codecs/tas2770.c +++ b/sound/soc/codecs/tas2770.c @@ -353,6 +353,7 @@ static int tas2770_set_fmt(struct snd_soc_dai *dai, unsigned int fmt) struct tas2770_priv *tas2770 = snd_soc_component_get_drvdata(component); u8 tdm_rx_start_slot = 0, invert_fpol = 0, fpol_preinv = 0, asi_cfg_1 = 0; + u8 tx_edge; int ret; switch (fmt & SND_SOC_DAIFMT_CLOCK_PROVIDER_MASK) { @@ -369,12 +370,14 @@ static int tas2770_set_fmt(struct snd_soc_dai *dai, unsigned int fmt) fallthrough; case SND_SOC_DAIFMT_NB_NF: asi_cfg_1 |= TAS2770_TDM_CFG_REG1_RX_RSING; + tx_edge = TAS2770_TDM_CFG_REG4_TX_FALING; break; case SND_SOC_DAIFMT_IB_IF: invert_fpol = 1; fallthrough; case SND_SOC_DAIFMT_IB_NF: asi_cfg_1 |= TAS2770_TDM_CFG_REG1_RX_FALING; + tx_edge = TAS2770_TDM_CFG_REG4_TX_RISING; break; default: dev_err(tas2770->dev, "ASI format Inverse is not found\n"); @@ -387,6 +390,12 @@ static int tas2770_set_fmt(struct snd_soc_dai *dai, unsigned int fmt) if (ret < 0) return ret; + ret = snd_soc_component_update_bits(component, TAS2770_TDM_CFG_REG4, + TAS2770_TDM_CFG_REG4_TX_EDGE, + tx_edge); + if (ret < 0) + return ret; + switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) { case SND_SOC_DAIFMT_I2S: tdm_rx_start_slot = 1; diff --git a/sound/soc/codecs/tas2770.h b/sound/soc/codecs/tas2770.h index 102040b6bdf8..666a9631c65d 100644 --- a/sound/soc/codecs/tas2770.h +++ b/sound/soc/codecs/tas2770.h @@ -74,7 +74,9 @@ #define TAS2770_TDM_CFG_REG4_TX_KEEPER BIT(5) #define TAS2770_TDM_CFG_REG4_TX_FILL BIT(4) #define TAS2770_TDM_CFG_REG4_TX_OFFSET_MASK GENMASK(3, 1) -#define TAS2770_TDM_CFG_REG4_TX_EDGE_FALLING BIT(0) +#define TAS2770_TDM_CFG_REG4_TX_EDGE BIT(0) +#define TAS2770_TDM_CFG_REG4_TX_RISING 0x0 +#define TAS2770_TDM_CFG_REG4_TX_FALING 0x1 /* TDM Configuration Reg5 */ #define TAS2770_TDM_CFG_REG5 TAS2770_REG(0X0, 0x0F) #define TAS2770_TDM_CFG_REG5_VSNS_MASK BIT(6) diff --git a/sound/soc/codecs/wm_adsp.c b/sound/soc/codecs/wm_adsp.c index b8f3035af3ba..7740a9c8ced3 100644 --- a/sound/soc/codecs/wm_adsp.c +++ b/sound/soc/codecs/wm_adsp.c @@ -46,6 +46,9 @@ #define adsp_dbg(_dsp, fmt, ...) \ dev_dbg(_dsp->cs_dsp.dev, "%s: " fmt, _dsp->cs_dsp.name, ##__VA_ARGS__) +#define adsp_warn_once(_dsp, fmt, ...) \ + dev_warn_once(_dsp->cs_dsp.dev, "%s: " fmt, _dsp->cs_dsp.name, ##__VA_ARGS__) + #define compr_err(_obj, fmt, ...) \ adsp_err(_obj->dsp, "%s: " fmt, _obj->name ? _obj->name : "legacy", \ ##__VA_ARGS__) @@ -625,6 +628,13 @@ int wm_adsp_control_add(struct cs_dsp_coeff_ctl *cs_ctl) if (dsp->component->name_prefix) avail -= strlen(dsp->component->name_prefix) + 1; + if (avail < 1) { + adsp_warn_once(dsp, + "%.*s: ALSA prefix too long: control not created\n", + cs_ctl->subname_len, cs_ctl->subname); + return -EINVAL; + } + /* Truncate the subname from the start if it is too long */ if (cs_ctl->subname_len > avail) skip = cs_ctl->subname_len - avail; diff --git a/sound/soc/meson/axg-fifo.c b/sound/soc/meson/axg-fifo.c index 75909196b769..edf43b7fb5cf 100644 --- a/sound/soc/meson/axg-fifo.c +++ b/sound/soc/meson/axg-fifo.c @@ -244,17 +244,10 @@ int axg_fifo_pcm_open(struct snd_soc_component *component, if (ret) return ret; - /* Use the threaded irq handler only with non-atomic links */ - ret = request_threaded_irq(fifo->irq, NULL, - axg_fifo_pcm_irq_block, - IRQF_ONESHOT, dev_name(dev), ss); - if (ret) - return ret; - /* Enable pclk to access registers and clock the fifo ip */ ret = clk_prepare_enable(fifo->pclk); if (ret) - goto free_irq; + return ret; /* Setup status2 so it reports the memory pointer */ regmap_update_bits(fifo->map, FIFO_CTRL1, @@ -271,17 +264,24 @@ int axg_fifo_pcm_open(struct snd_soc_component *component, /* Clear any pending interrupt */ axg_fifo_ack_irq(fifo, FIFO_INT_MASK); + /* Use the threaded irq handler only with non-atomic links */ + ret = request_threaded_irq(fifo->irq, NULL, + axg_fifo_pcm_irq_block, + IRQF_ONESHOT, dev_name(dev), ss); + if (ret) + goto free_clk; + /* Take memory arbitror out of reset */ ret = reset_control_deassert(fifo->arb); if (ret) - goto free_clk; + goto free_irq; return 0; -free_clk: - clk_disable_unprepare(fifo->pclk); free_irq: free_irq(fifo->irq, ss); +free_clk: + clk_disable_unprepare(fifo->pclk); return ret; } EXPORT_SYMBOL_GPL(axg_fifo_pcm_open); @@ -295,12 +295,12 @@ int axg_fifo_pcm_close(struct snd_soc_component *component, /* Put the memory arbitror back in reset */ ret = reset_control_assert(fifo->arb); - /* Disable fifo ip and register access */ - clk_disable_unprepare(fifo->pclk); - /* remove IRQ */ free_irq(fifo->irq, ss); + /* Disable fifo ip and register access */ + clk_disable_unprepare(fifo->pclk); + return ret; } EXPORT_SYMBOL_GPL(axg_fifo_pcm_close); diff --git a/sound/soc/qcom/common.c b/sound/soc/qcom/common.c index d9f256d51973..83b745f617a8 100644 --- a/sound/soc/qcom/common.c +++ b/sound/soc/qcom/common.c @@ -339,13 +339,11 @@ static struct snd_soc_jack_pin qcom_headset_jack_pins[] = { }, }; -int qcom_snd_wcd_jack_setup(struct snd_soc_pcm_runtime *rtd, - struct snd_soc_jack *jack, bool *jack_setup) +static int qcom_snd_headset_jack_init(struct snd_soc_card *card, + struct snd_soc_jack *jack, + bool *jack_setup) { - struct snd_soc_dai *cpu_dai = snd_soc_rtd_to_cpu(rtd, 0); - struct snd_soc_dai *codec_dai = snd_soc_rtd_to_codec(rtd, 0); - struct snd_soc_card *card = rtd->card; - int rval, i; + int rval; if (!*jack_setup) { rval = snd_soc_card_jack_new_pins(card, "Headset Jack", @@ -369,6 +367,55 @@ int qcom_snd_wcd_jack_setup(struct snd_soc_pcm_runtime *rtd, *jack_setup = true; } + return 0; +} + +int qcom_snd_headset_jack_setup(struct snd_soc_pcm_runtime *rtd, + struct snd_soc_jack *jack, bool *jack_setup) +{ + struct snd_soc_dai *codec_dai; + struct snd_soc_card *card = rtd->card; + int rval, i; + + rval = qcom_snd_headset_jack_init(card, jack, jack_setup); + if (rval) + return rval; + + for_each_rtd_codec_dais(rtd, i, codec_dai) { + rval = snd_soc_component_set_jack(codec_dai->component, jack, NULL); + if (rval != 0 && rval != -ENOTSUPP) { + dev_warn(card->dev, "Failed to set jack: %d\n", rval); + qcom_snd_headset_jack_cleanup(rtd); + return rval; + } + } + + return 0; +} +EXPORT_SYMBOL_GPL(qcom_snd_headset_jack_setup); + +void qcom_snd_headset_jack_cleanup(struct snd_soc_pcm_runtime *rtd) +{ + struct snd_soc_dai *codec_dai; + int i; + + for_each_rtd_codec_dais(rtd, i, codec_dai) + snd_soc_component_set_jack(codec_dai->component, NULL, NULL); +} +EXPORT_SYMBOL_GPL(qcom_snd_headset_jack_cleanup); + +int qcom_snd_wcd_jack_setup(struct snd_soc_pcm_runtime *rtd, + struct snd_soc_jack *jack, bool *jack_setup) +{ + struct snd_soc_dai *cpu_dai = snd_soc_rtd_to_cpu(rtd, 0); + struct snd_soc_dai *codec_dai = snd_soc_rtd_to_codec(rtd, 0); + struct snd_soc_card *card = rtd->card; + int rval, i; + + rval = qcom_snd_headset_jack_init(card, jack, jack_setup); + if (rval) + return rval; + switch (cpu_dai->id) { case LPI_MI2S_RX_0: case TX_CODEC_DMA_TX_0: @@ -388,8 +435,6 @@ int qcom_snd_wcd_jack_setup(struct snd_soc_pcm_runtime *rtd, default: break; } - - return 0; } EXPORT_SYMBOL_GPL(qcom_snd_wcd_jack_setup); diff --git a/sound/soc/qcom/common.h b/sound/soc/qcom/common.h index c1deac109f24..b6204a32bd64 100644 --- a/sound/soc/qcom/common.h +++ b/sound/soc/qcom/common.h @@ -24,6 +24,9 @@ int qcom_snd_apply_dai_tdm_slots_cfg(struct snd_soc_pcm_runtime *rtd, const struct qcom_snd_tdm_slot_cfg *cpu_cfg, const struct qcom_snd_tdm_slot_cfg *codec_cfg); int qcom_snd_apply_dai_tdm_slots(struct snd_soc_pcm_runtime *rtd); +int qcom_snd_headset_jack_setup(struct snd_soc_pcm_runtime *rtd, + struct snd_soc_jack *jack, bool *jack_setup); +void qcom_snd_headset_jack_cleanup(struct snd_soc_pcm_runtime *rtd); int qcom_snd_wcd_jack_setup(struct snd_soc_pcm_runtime *rtd, struct snd_soc_jack *jack, bool *jack_setup); int qcom_snd_dp_jack_setup(struct snd_soc_pcm_runtime *rtd, diff --git a/sound/soc/qcom/qdsp6/q6asm-dai.c b/sound/soc/qcom/qdsp6/q6asm-dai.c index e3742663c13e..3231e2cf306b 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 de0bd8fd08ee..8dde9a3b9c76 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 c81df41ace88..213d7f45198c 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/rockchip/Kconfig b/sound/soc/rockchip/Kconfig index 391ce2225fde..0e5110125c14 100644 --- a/sound/soc/rockchip/Kconfig +++ b/sound/soc/rockchip/Kconfig @@ -5,6 +5,7 @@ menu "Rockchip" config SND_SOC_ROCKCHIP_I2S tristate "Rockchip I2S Device Driver" + select REGMAP_MMIO select SND_SOC_GENERIC_DMAENGINE_PCM help Say Y or M if you want to add support for I2S driver for @@ -13,6 +14,7 @@ config SND_SOC_ROCKCHIP_I2S config SND_SOC_ROCKCHIP_I2S_TDM tristate "Rockchip I2S/TDM Device Driver" + select REGMAP_MMIO select SND_SOC_GENERIC_DMAENGINE_PCM help Say Y or M if you want to add support for the I2S/TDM driver for @@ -23,6 +25,7 @@ config SND_SOC_ROCKCHIP_I2S_TDM config SND_SOC_ROCKCHIP_PDM tristate "Rockchip PDM Controller Driver" + select REGMAP_MMIO select SND_SOC_GENERIC_DMAENGINE_PCM select RATIONAL help @@ -32,6 +35,7 @@ config SND_SOC_ROCKCHIP_PDM config SND_SOC_ROCKCHIP_SAI tristate "Rockchip SAI Controller Driver" + select REGMAP_MMIO select SND_SOC_GENERIC_DMAENGINE_PCM help Say Y or M if you want to add support for the Rockchip Serial Audio @@ -41,6 +45,7 @@ config SND_SOC_ROCKCHIP_SAI config SND_SOC_ROCKCHIP_SPDIF tristate "Rockchip SPDIF Device Driver" + select REGMAP_MMIO select SND_PCM_IEC958 select SND_SOC_GENERIC_DMAENGINE_PCM help diff --git a/sound/soc/soc-core.c b/sound/soc/soc-core.c index b9c70268d49f..2ba53102a630 100644 --- a/sound/soc/soc-core.c +++ b/sound/soc/soc-core.c @@ -3610,6 +3610,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 @@ -3639,6 +3651,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; } @@ -3694,6 +3708,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 5570f3d1348d..7656f9bb6f16 100644 --- a/sound/soc/sof/amd/acp.c +++ b/sound/soc/sof/amd/acp.c @@ -430,16 +430,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; } } @@ -531,10 +535,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; } @@ -560,11 +566,13 @@ static irqreturn_t acp_irq_handler(int irq, void *dev_id) if (desc->ext_intr_stat1) { val = snd_sof_dsp_read(sdev, ACP_DSP_BAR, desc->ext_intr_stat1); if (val & ACP_SDW1_IRQ_MASK) { - amd_manager = dev_get_drvdata(&adata->sdw->pdev[1]->dev); snd_sof_dsp_write(sdev, ACP_DSP_BAR, desc->ext_intr_stat1, ACP_SDW1_IRQ_MASK); - if (amd_manager) - schedule_work(&amd_manager->amd_sdw_irq_thread); + if (adata->sdw) { + amd_manager = dev_get_drvdata(&adata->sdw->pdev[1]->dev); + if (amd_manager) + schedule_work(&amd_manager->amd_sdw_irq_thread); + } irq_flag = 1; } switch (adata->pci_rev) { diff --git a/sound/soc/sof/ipc4-topology.c b/sound/soc/sof/ipc4-topology.c index 22c15fbb93f2..e9f5706867f0 100644 --- a/sound/soc/sof/ipc4-topology.c +++ b/sound/soc/sof/ipc4-topology.c @@ -1310,7 +1310,7 @@ static int sof_ipc4_widget_setup_comp_process(struct snd_sof_widget *swidget) ret = sof_ipc4_widget_setup_msg(swidget, &process->msg); if (ret) - goto err; + goto free_available_fmt; /* parse process init module payload config type from module info */ fw_module = swidget->module_info; diff --git a/sound/usb/caiaq/device.c b/sound/usb/caiaq/device.c index 5e89047c9d9c..aec96ad0c040 100644 --- a/sound/usb/caiaq/device.c +++ b/sound/usb/caiaq/device.c @@ -593,14 +593,19 @@ static void snd_disconnect(struct usb_interface *intf) snd_card_disconnect(card); + /* + * Kill the EP1 URB before disconnecting the input device: its + * completion reports into cdev->input_dev, which input_disconnect() + * frees without clearing the pointer. + */ + usb_kill_urb(cdev->ep1_in_urb); + usb_kill_urb(cdev->midi_out_urb); + #ifdef CONFIG_SND_USB_CAIAQ_INPUT snd_usb_caiaq_input_disconnect(cdev); #endif snd_usb_caiaq_audio_disconnect(cdev); - usb_kill_urb(cdev->ep1_in_urb); - usb_kill_urb(cdev->midi_out_urb); - snd_card_free_when_closed(card); } diff --git a/sound/usb/pcm.c b/sound/usb/pcm.c index c2f7b08607ac..57a26492dd61 100644 --- a/sound/usb/pcm.c +++ b/sound/usb/pcm.c @@ -1337,6 +1337,12 @@ static void retire_capture_urb(struct snd_usb_substream *subs, "frame %d active: %d\n", i, urb->iso_frame_desc[i].status); bytes = urb->iso_frame_desc[i].actual_length; + if (unlikely(bytes > urb->iso_frame_desc[i].length)) { + dev_warn_ratelimited(&subs->dev->dev, + "packet %d: actual_length %u exceeds length %u, dropping\n", + i, bytes, urb->iso_frame_desc[i].length); + continue; + } if (subs->stream_offset_adj > 0) { unsigned int adj = min(subs->stream_offset_adj, bytes); cp += adj; diff --git a/tools/bootconfig/main.c b/tools/bootconfig/main.c index df0534035857..caff4338bba6 100644 --- a/tools/bootconfig/main.c +++ b/tools/bootconfig/main.c @@ -39,6 +39,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; @@ -99,14 +116,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 fc69f815ce4a..26cfef5d2b31 100755 --- a/tools/bootconfig/test-bootconfig.sh +++ b/tools/bootconfig/test-bootconfig.sh @@ -171,6 +171,24 @@ $BOOTCONF $INITRD > $OUTFILE xfail grep -q 'val[[:space:]]' $OUTFILE xpass grep -q 'val2[[:space:]]' $OUTFILE +echo "Remove unquoted trailing whitespace at end of file" +printf 'foo = val \t' > $TEMPCONF +$BOOTCONF -l $TEMPCONF > $OUTFILE +printf 'foo = "val"\n' > $TEMPCONF +xpass cmp $TEMPCONF $OUTFILE + +echo "Remove trailing whitespace from the last array value at end of file" +printf 'foo = first, last \t' > $TEMPCONF +$BOOTCONF -l $TEMPCONF > $OUTFILE +printf 'foo = "first", "last"\n' > $TEMPCONF +xpass cmp $TEMPCONF $OUTFILE + +echo "Keep quoted trailing whitespace at end of file" +printf 'foo = "val "' > $TEMPCONF +$BOOTCONF -l $TEMPCONF > $OUTFILE +printf 'foo = "val "\n' > $TEMPCONF +xpass cmp $TEMPCONF $OUTFILE + echo "Showing correct line:column of no closing brace" cat > $TEMPCONF << EOF foo { diff --git a/tools/testing/selftests/bpf/progs/verifier_live_stack.c b/tools/testing/selftests/bpf/progs/verifier_live_stack.c index 401152b2b64f..ec2f25df3d4d 100644 --- a/tools/testing/selftests/bpf/progs/verifier_live_stack.c +++ b/tools/testing/selftests/bpf/progs/verifier_live_stack.c @@ -1763,11 +1763,15 @@ static __used __naked void grandchild_deref(void) ::: __clobber_all); } +/* + * The callee gets a pointer to the frame that holds the spills. It can store a pointer + * that is not FP-derived over them: after the call each of them is "fp-N or not FP-derived". + */ SEC("socket") __log_level(2) __success -__msg("14: (79) r1 = *(u64 *)(r10 -8) // r6=fp0-8 r7=fp1-16 fp-8=fp1-16 fp-16=fp0-8") -__msg("15: (79) r0 = *(u64 *)(r1 +0) // r1=fp1-16 r6=fp0-8 r7=fp1-16 fp-8=fp1-16 fp-16=fp0-8") +__msg("14: (79) r1 = *(u64 *)(r10 -8) // r6=fp0-8 r7=fp1-16 fp-8=fp1-16|fp1+0 fp-16=fp0-8|fp0+0") +__msg("15: (79) r0 = *(u64 *)(r1 +0) // r1=fp1-16|fp1+0 r6=fp0-8 r7=fp1-16 fp-8=fp1-16|fp1+0") __msg("stack use/def subprog#1 mid_two_fp_threshold (d1,cs2):") __msg("14: (79) r1 = *(u64 *)(r10 -8) ; use: fp1-8") __msg("15: (79) r0 = *(u64 *)(r1 +0) ; use: fp1-16") @@ -1812,8 +1816,8 @@ static __used __naked void inner_nop_fptest(void) SEC("socket") __log_level(2) __success -__msg("13: (79) r1 = *(u64 *)(r10 -8) // r6=fp0-8 r7=fp1-16 fp-8=fp1-16 fp-16=fp0-8") -__msg("14: (79) r0 = *(u64 *)(r1 +0) // r1=fp1-16 r6=fp0-8 r7=fp1-16 fp-8=fp1-16 fp-16=fp0-8") +__msg("13: (79) r1 = *(u64 *)(r10 -8) // r6=fp0-8 r7=fp1-16 fp-8=fp1-16|fp1+0 fp-16=fp0-8|fp0+0") +__msg("14: (79) r0 = *(u64 *)(r1 +0) // r1=fp1-16|fp1+0 r6=fp0-8 r7=fp1-16 fp-8=fp1-16|fp1+0") __msg("stack use/def subprog#1 mid_one_fp_threshold (d1,cs2):") __msg("13: (79) r1 = *(u64 *)(r10 -8) ; use: fp1-8") __msg("14: (79) r0 = *(u64 *)(r1 +0) ; use: fp1-16") diff --git a/tools/testing/selftests/bpf/progs/verifier_may_goto_1.c b/tools/testing/selftests/bpf/progs/verifier_may_goto_1.c index db7e30da234f..a95735d98c7c 100644 --- a/tools/testing/selftests/bpf/progs/verifier_may_goto_1.c +++ b/tools/testing/selftests/bpf/progs/verifier_may_goto_1.c @@ -82,6 +82,7 @@ __naked void may_goto_batch_1(void) SEC("raw_tp") __description("may_goto batch with offsets 2/0") +__load_if_JITed() __arch_x86_64 __arch_s390x __arch_arm64 diff --git a/tools/testing/selftests/cgroup/test_cpuset_prs.sh b/tools/testing/selftests/cgroup/test_cpuset_prs.sh index 78ed0500e11d..cd29cf740e40 100755 --- a/tools/testing/selftests/cgroup/test_cpuset_prs.sh +++ b/tools/testing/selftests/cgroup/test_cpuset_prs.sh @@ -364,6 +364,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" @@ -462,6 +468,13 @@ 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 ." + # 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 # ------ ------ ------ ------ ------ ------ ------ ------ ---- ----- ------ -------- @@ -550,6 +563,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/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 "" README; then check_error 'f vfs_read args=^$arg*' # BAD_VAR_ARGS check_error 'f vfs_read +0(^$arg*)' # BAD_VAR_ARGS check_error 'f vfs_read $arg* ^$arg*' # DOUBLE_ARGS -if !grep -q 'kernel return probes support:' README; then +if ! grep -q 'kernel return probes support:' README; then check_error 'f vfs_read%return ^$arg*' # NOFENTRY_ARGS fi check_error 'f vfs_read ^hoge' # NO_BTFARG diff --git a/tools/testing/selftests/ftrace/test.d/kprobe/kprobe_non_uniq_symbol.tc b/tools/testing/selftests/ftrace/test.d/kprobe/kprobe_non_uniq_symbol.tc index 07b1177c1634..5b95c7f312f4 100644 --- a/tools/testing/selftests/ftrace/test.d/kprobe/kprobe_non_uniq_symbol.tc +++ b/tools/testing/selftests/ftrace/test.d/kprobe/kprobe_non_uniq_symbol.tc @@ -6,7 +6,7 @@ SYMBOL='name_show' # We skip this test on kernel where SYMBOL is unique or does not exist. -if [ "$(grep -c -E "[[:alnum:]]+ t ${SYMBOL}$" /proc/kallsyms)" -le '1' ]; then +if [ "$(grep -c -E "[[:alnum:]]+ t ${SYMBOL}\$" /proc/kallsyms)" -le '1' ]; then exit_unsupported fi diff --git a/tools/testing/selftests/ftrace/test.d/kprobe/kprobe_syntax_errors.tc b/tools/testing/selftests/ftrace/test.d/kprobe/kprobe_syntax_errors.tc index 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 "" README; then check_error 'p vfs_read args=^$arg*' # BAD_VAR_ARGS check_error 'p vfs_read +0(^$arg*)' # BAD_VAR_ARGS check_error 'p vfs_read $arg* ^$arg*' # DOUBLE_ARGS -if !grep -q 'kernel return probes support:' README; then +if ! grep -q 'kernel return probes support:' README; then check_error 'r vfs_read ^$arg*' # NOFENTRY_ARGS fi check_error 'p vfs_read+20 ^$arg*' # NOFENTRY_ARGS diff --git a/tools/testing/selftests/mm/merge.c b/tools/testing/selftests/mm/merge.c index 52b8727b6628..395502aa2794 100644 --- a/tools/testing/selftests/mm/merge.c +++ b/tools/testing/selftests/mm/merge.c @@ -22,9 +22,12 @@ FIXTURE(merge) struct procmap_fd procmap; }; +#define FAR_PAGES 30 +#define CARVEOUT_PAGES (3 * FAR_PAGES) + static char *map_carveout(unsigned int page_size) { - return mmap(NULL, 30 * page_size, PROT_NONE, + return mmap(NULL, CARVEOUT_PAGES * page_size, PROT_NONE, MAP_ANON | MAP_PRIVATE, -1, 0); } @@ -73,7 +76,7 @@ FIXTURE_SETUP(merge) FIXTURE_TEARDOWN(merge) { - ASSERT_EQ(munmap(self->carveout, 30 * self->page_size), 0); + ASSERT_EQ(munmap(self->carveout, CARVEOUT_PAGES * self->page_size), 0); /* May fail for parent of forked process. */ close_procmap(&self->procmap); /* @@ -115,7 +118,7 @@ FIXTURE_SETUP(merge_with_fork) FIXTURE_TEARDOWN(merge_with_fork) { - ASSERT_EQ(munmap(self->carveout, 30 * self->page_size), 0); + ASSERT_EQ(munmap(self->carveout, CARVEOUT_PAGES * self->page_size), 0); ASSERT_EQ(close_procmap(&self->procmap), 0); /* See above. */ prctl(PR_SET_MEMORY_MERGE, 0, 0, 0, 0); @@ -660,7 +663,7 @@ TEST_F(merge, mremap_unfaulted_to_faulted) /* Offset ptr2 further away. */ ptr2 = sys_mremap(ptr2, 5 * page_size, 5 * page_size, - MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + page_size * 1000); + MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + FAR_PAGES * page_size); ASSERT_NE(ptr2, MAP_FAILED); /* @@ -721,7 +724,7 @@ TEST_F(merge, mremap_unfaulted_behind_faulted) /* Offset ptr2 further away. */ ptr2 = sys_mremap(ptr2, 5 * page_size, 5 * page_size, - MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + page_size * 1000); + MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + FAR_PAGES * page_size); ASSERT_NE(ptr2, MAP_FAILED); /* @@ -785,12 +788,12 @@ TEST_F(merge, mremap_unfaulted_between_faulted) /* Offset ptr3 further away. */ ptr3 = sys_mremap(ptr3, 5 * page_size, 5 * page_size, - MREMAP_MAYMOVE | MREMAP_FIXED, ptr3 + page_size * 2000); + MREMAP_MAYMOVE | MREMAP_FIXED, ptr3 + 2 * FAR_PAGES * page_size); ASSERT_NE(ptr3, MAP_FAILED); /* Offset ptr2 further away. */ ptr2 = sys_mremap(ptr2, 5 * page_size, 5 * page_size, - MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + page_size * 1000); + MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + FAR_PAGES * page_size); ASSERT_NE(ptr2, MAP_FAILED); /* @@ -870,13 +873,13 @@ TEST_F(merge, mremap_unfaulted_between_faulted_unfaulted) /* Offset ptr3 further away. */ ptr3 = sys_mremap(ptr3, 5 * page_size, 5 * page_size, - MREMAP_MAYMOVE | MREMAP_FIXED, ptr3 + page_size * 2000); + MREMAP_MAYMOVE | MREMAP_FIXED, ptr3 + 2 * FAR_PAGES * page_size); ASSERT_NE(ptr3, MAP_FAILED); /* Offset ptr2 further away. */ ptr2 = sys_mremap(ptr2, 5 * page_size, 5 * page_size, - MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + page_size * 1000); + MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + FAR_PAGES * page_size); ASSERT_NE(ptr2, MAP_FAILED); /* @@ -1035,11 +1038,11 @@ TEST_F(merge, mremap_correct_placed_faulted) */ ptr3 = &ptr[10 * page_size]; ptr3 = sys_mremap(ptr3, 5 * page_size, 5 * page_size, - MREMAP_MAYMOVE | MREMAP_FIXED, ptr3 + page_size * 2000); + MREMAP_MAYMOVE | MREMAP_FIXED, ptr3 + 2 * FAR_PAGES * page_size); ASSERT_NE(ptr3, MAP_FAILED); ptr2 = &ptr[5 * page_size]; ptr2 = sys_mremap(ptr2, 5 * page_size, 5 * page_size, - MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + page_size * 1000); + MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + FAR_PAGES * page_size); ASSERT_NE(ptr2, MAP_FAILED); /* @@ -1075,7 +1078,7 @@ TEST_F(merge, mremap_correct_placed_faulted) * ptr2 \ ptr \ ptr3 */ ptr = sys_mremap(ptr, 5 * page_size, 5 * page_size, - MREMAP_MAYMOVE | MREMAP_FIXED, ptr + page_size * 1000); + MREMAP_MAYMOVE | MREMAP_FIXED, ptr + FAR_PAGES * page_size); ASSERT_NE(ptr, MAP_FAILED); /* @@ -1110,7 +1113,7 @@ TEST_F(merge, mremap_correct_placed_faulted) * ptr2 \ ptr \ ptr3 */ ptr = sys_mremap(ptr, 5 * page_size, 5 * page_size, - MREMAP_MAYMOVE | MREMAP_FIXED, ptr + page_size * 1000); + MREMAP_MAYMOVE | MREMAP_FIXED, ptr + FAR_PAGES * page_size); ASSERT_NE(ptr, MAP_FAILED); /* @@ -1168,7 +1171,7 @@ TEST_F(merge, mremap_correct_placed_faulted) * ptr ptr3 \ ptr2 */ ptr2 = sys_mremap(ptr2, 5 * page_size, 5 * page_size, - MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + page_size * 1000); + MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + FAR_PAGES * page_size); ASSERT_NE(ptr2, MAP_FAILED); /* @@ -1203,7 +1206,7 @@ TEST_F(merge, mremap_correct_placed_faulted) * ptr \ ptr3 */ ptr3 = sys_mremap(ptr3, 5 * page_size, 5 * page_size, - MREMAP_MAYMOVE | MREMAP_FIXED, ptr3 + page_size * 1000); + MREMAP_MAYMOVE | MREMAP_FIXED, ptr3 + FAR_PAGES * page_size); ASSERT_NE(ptr3, MAP_FAILED); /* diff --git a/tools/testing/selftests/net/packetdrill/tcp_bidir_fast_retransmit_nosack.pkt b/tools/testing/selftests/net/packetdrill/tcp_bidir_fast_retransmit_nosack.pkt new file mode 100644 index 000000000000..5c66b7171d22 --- /dev/null +++ b/tools/testing/selftests/net/packetdrill/tcp_bidir_fast_retransmit_nosack.pkt @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: GPL-2.0 +// +// Verify that non-SACK connections properly detect duplicate acks when mixed +// with other data segments from peer. + +`./defaults.sh` + + 0 socket(..., SOCK_STREAM, IPPROTO_TCP) = 4 + +0...0 connect(4, ..., ...) = 0 + + // Three-way handshake, SACK not supported by peer + +0 > S 0:0(0) + +0 < S. 0:0(0) ack 1 win 65535 + +0 > . 1:1(0) ack 1 + + // Send 1000 bytes, peer acks everything + +0 send(4, ..., 1000, 0) = 1000 + +0 > P. 1:1001(1000) ack 1 + +0 < . 1:1(0) ack 1001 win 65535 + + // Send 4000 more bytes + +0 send(4, ..., 4000, 0) = 4000 + +0 > P. 1001:5001(4000) ack 1 + + // Receive first dup-ack (considering segment 1001-2001 was lost) + +0 < . 1:1(0) ack 1001 win 65535 + + // Receive unrelated data segment from peer and ack it + +0 < P. 1:11(10) ack 1001 win 65535 + +0 > . 5001:5001(0) ack 11 + + // Receive second dup-ack + +0 < . 11:11(0) ack 1001 win 65535 + + // Receive another data segment from peer and ack it + +0 < P. 11:21(10) ack 1001 win 65535 + +0 > . 5001:5001(0) ack 21 + + // Receive third dup-ack, which should trigger fast retransmit (without + // waiting for RTO) + +0 < . 21:21(0) ack 1001 win 65535 + +0 > . 1001:2001(1000) ack 21 diff --git a/tools/testing/selftests/net/tls.c b/tools/testing/selftests/net/tls.c index 9d3cd4fff062..0bc43728262e 100644 --- a/tools/testing/selftests/net/tls.c +++ b/tools/testing/selftests/net/tls.c @@ -2639,6 +2639,9 @@ TEST_F(zero_len, test) int rec_off; int i; + if (self->notls) + SKIP(return, "no TLS support"); + for (i = 0; i < 4 && variant->recs[i]; i++) EXPECT_EQ(send(self->fd, variant->recs[i]->cipher_data, variant->recs[i]->cipher_len, 0),